Mirror of metasploit
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

payload.rb 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678
  1. # -*- coding: binary -*-
  2. require 'msf/core'
  3. require 'metasm'
  4. module Msf
  5. ###
  6. #
  7. # This class represents the base class for a logical payload. The framework
  8. # automatically generates payload combinations at runtime which are all
  9. # extended for this Payload as a base class.
  10. #
  11. ###
  12. class Payload < Msf::Module
  13. require 'rex/payloads'
  14. require 'msf/core/payload/single'
  15. require 'msf/core/payload/generic'
  16. require 'msf/core/payload/stager'
  17. # Platform specific includes
  18. require 'msf/core/payload/aix'
  19. require 'msf/core/payload/bsd'
  20. require 'msf/core/payload/linux'
  21. require 'msf/core/payload/osx'
  22. require 'msf/core/payload/solaris'
  23. require 'msf/core/payload/windows'
  24. require 'msf/core/payload/netware'
  25. require 'msf/core/payload/java'
  26. require 'msf/core/payload/dalvik'
  27. require 'msf/core/payload/firefox'
  28. require 'msf/core/payload/mainframe'
  29. ##
  30. #
  31. # Payload types
  32. #
  33. ##
  34. module Type
  35. #
  36. # Single payload type. These types of payloads are self contained and
  37. # do not go through any staging.
  38. #
  39. Single = (1 << 0)
  40. #
  41. # The stager half of a staged payload. Its responsibility in life is to
  42. # read in the stage and execute it.
  43. #
  44. Stager = (1 << 1)
  45. #
  46. # The stage half of a staged payload. This payload performs whatever
  47. # arbitrary task it's designed to do, possibly making use of the same
  48. # connection that the stager used to read the stage in on, if
  49. # applicable.
  50. #
  51. Stage = (1 << 2)
  52. end
  53. #
  54. # Creates an instance of a payload module using the supplied information.
  55. #
  56. def initialize(info = {})
  57. super
  58. # If this is a staged payload but there is no stage information,
  59. # then this is actually a stager + single combination. Set up the
  60. # information hash accordingly.
  61. if self.class.include?(Msf::Payload::Single) and
  62. self.class.include?(Msf::Payload::Stager)
  63. self.module_info['Stage'] = {}
  64. if self.module_info['Payload']
  65. self.module_info['Stage']['Payload'] = self.module_info['Payload']['Payload'] || ""
  66. self.module_info['Stage']['Assembly'] = self.module_info['Payload']['Assembly'] || ""
  67. self.module_info['Stage']['Offsets'] = self.module_info['Payload']['Offsets'] || {}
  68. else
  69. self.module_info['Stage']['Payload'] = ""
  70. self.module_info['Stage']['Assembly'] = ""
  71. self.module_info['Stage']['Offsets'] = {}
  72. end
  73. @staged = true
  74. else
  75. @staged = false
  76. end
  77. # Update the module info hash with the connection type
  78. # that is derived from the handler for this payload. This is
  79. # used for compatibility filtering purposes.
  80. self.module_info['ConnectionType'] = connection_type
  81. end
  82. ##
  83. #
  84. # Accessors
  85. #
  86. ##
  87. #
  88. # Returns MODULE_PAYLOAD to indicate that this is a payload module.
  89. #
  90. def self.type
  91. return Msf::MODULE_PAYLOAD
  92. end
  93. #
  94. # Returns MODULE_PAYLOAD to indicate that this is a payload module.
  95. #
  96. def type
  97. return Msf::MODULE_PAYLOAD
  98. end
  99. #
  100. # Returns the string of bad characters for this payload, if any.
  101. #
  102. def badchars
  103. return self.module_info['BadChars']
  104. end
  105. #
  106. # The list of registers that should be saved by any NOP generators or
  107. # encoders, if possible.
  108. #
  109. def save_registers
  110. return self.module_info['SaveRegisters']
  111. end
  112. #
  113. # Returns the type of payload, either single or staged. Stage is
  114. # the default because singles and stagers are encouraged to include
  115. # the Single and Stager mixin which override the payload_type.
  116. #
  117. def payload_type
  118. return Type::Stage
  119. end
  120. #
  121. # Returns the string version of the payload type
  122. #
  123. def payload_type_s
  124. case payload_type
  125. when Type::Stage
  126. return "stage"
  127. when Type::Stager
  128. return "stager"
  129. when Type::Single
  130. return "single"
  131. else
  132. return "unknown"
  133. end
  134. end
  135. #
  136. # This method returns whether or not this payload uses staging.
  137. #
  138. def staged?
  139. (@staged or payload_type == Type::Stager or payload_type == Type::Stage)
  140. end
  141. #
  142. # This method returns an optional cached size value
  143. #
  144. def self.cached_size
  145. csize = (const_defined?('CachedSize')) ? const_get('CachedSize') : nil
  146. csize == :dynamic ? nil : csize
  147. end
  148. #
  149. # This method returns whether the payload generates variable-sized output
  150. #
  151. def self.dynamic_size?
  152. csize = (const_defined?('CachedSize')) ? const_get('CachedSize') : nil
  153. csize == :dynamic
  154. end
  155. #
  156. # This method returns an optional cached size value
  157. #
  158. def cached_size
  159. self.class.cached_size
  160. end
  161. #
  162. # This method returns whether the payload generates variable-sized output
  163. #
  164. def dynamic_size?
  165. self.class.dynamic_size?
  166. end
  167. #
  168. # Returns the payload's size. If the payload is staged, the size of the
  169. # first stage is returned.
  170. #
  171. def size
  172. pl = nil
  173. begin
  174. pl = generate()
  175. rescue NoCompatiblePayloadError
  176. end
  177. pl ||= ''
  178. pl.length
  179. end
  180. #
  181. # Returns the raw payload that has not had variable substitution occur.
  182. #
  183. def payload
  184. return module_info['Payload'] ? module_info['Payload']['Payload'] : nil
  185. end
  186. #
  187. # Returns the assembly string that describes the payload if one exists.
  188. #
  189. def assembly
  190. return module_info['Payload'] ? module_info['Payload']['Assembly'] : nil
  191. end
  192. #
  193. # Sets the assembly string that describes the payload
  194. # If this method is used to define the payload, a payload with no offsets will be created
  195. #
  196. def assembly=(asm)
  197. module_info['Payload'] ||= {'Offsets' => {} }
  198. module_info['Payload']['Assembly'] = asm
  199. end
  200. #
  201. # Returns the offsets to variables that must be substitute, if any.
  202. #
  203. def offsets
  204. return module_info['Payload'] ? module_info['Payload']['Offsets'] : nil
  205. end
  206. #
  207. # Returns the staging convention that the payload uses, if any. This is
  208. # used to make sure that only compatible stagers and stages are built
  209. # (where assumptions are made about register/environment initialization
  210. # state and hand-off).
  211. #
  212. def convention
  213. module_info['Convention']
  214. end
  215. #
  216. # Returns the module's connection type, such as reverse, bind, noconn,
  217. # or whatever else the case may be.
  218. #
  219. def connection_type
  220. handler_klass.general_handler_type
  221. end
  222. #
  223. # Returns the method used by the payload to resolve symbols for the purpose
  224. # of calling functions, such as ws2ord.
  225. #
  226. def symbol_lookup
  227. module_info['SymbolLookup']
  228. end
  229. #
  230. # Checks to see if the supplied convention is compatible with this
  231. # payload's convention.
  232. #
  233. def compatible_convention?(conv)
  234. # If we don't have a convention or our convention is equal to
  235. # the one supplied, then we know we are compatible.
  236. if ((self.convention == nil) or
  237. (self.convention == conv))
  238. true
  239. # On the flip side, if we are a stager and the supplied convention is
  240. # nil, then we know it's compatible.
  241. elsif ((payload_type == Type::Stager) and
  242. (conv == nil))
  243. true
  244. # Otherwise, the conventions don't match in some way or another, and as
  245. # such we deem ourself as not being compatible with the supplied
  246. # convention.
  247. else
  248. false
  249. end
  250. end
  251. #
  252. # Return the connection associated with this payload, or none if there
  253. # isn't one.
  254. #
  255. def handler_klass
  256. return module_info['Handler'] || Msf::Handler::None
  257. end
  258. #
  259. # Returns the session class that is associated with this payload and will
  260. # be used to create a session as necessary.
  261. #
  262. def session
  263. return module_info['Session']
  264. end
  265. ##
  266. #
  267. # Generation & variable substitution
  268. #
  269. ##
  270. #
  271. # Generates the payload and returns the raw buffer to the caller.
  272. #
  273. def generate
  274. internal_generate
  275. end
  276. #
  277. # Generates the payload and returns the raw buffer to the caller,
  278. # handling any post-processing tasks, such as prepended code stubs.
  279. def generate_complete
  280. apply_prepends(generate)
  281. end
  282. #
  283. # Convert raw bytes to metasm-ready 'db' encoding format
  284. # eg. "\x90\xCC" => "db 0x90,0xCC"
  285. #
  286. # @param raw [Array] Byte array to encode.
  287. #
  288. def raw_to_db(raw)
  289. raw.unpack("C*").map {|c| "0x%.2x" % c}.join(",")
  290. end
  291. #
  292. # Substitutes variables with values from the module's datastore in the
  293. # supplied raw buffer for a given set of named offsets. For instance,
  294. # RHOST is substituted with the RHOST value from the datastore which will
  295. # have been populated by the framework.
  296. #
  297. # Supported packing types:
  298. #
  299. # - ADDR (foo.com, 1.2.3.4)
  300. # - ADDR6 (foo.com, fe80::1234:5678:8910:1234)
  301. # - ADDR16MSB, ADD16LSB, ADDR22MSB, ADD22LSB (foo.com, 1.2.3.4)
  302. # Advanced packing types for 16/16 and 22/10 bits substitution. The 16
  303. # bits types uses two offsets indicating where the 16 bits pair will be
  304. # substituted, while the 22 bits types uses two offsets indicating the
  305. # instructions where the 22/10 bits pair will be substituted. Normally
  306. # these are offsets to "sethi" and "or" instructions on SPARC architecture.
  307. # - HEX (0x12345678, "\x41\x42\x43\x44")
  308. # - RAW (raw bytes)
  309. #
  310. def substitute_vars(raw, offsets)
  311. offsets.each_pair { |name, info|
  312. offset, pack = info
  313. # Give the derived class a chance to substitute this variable
  314. next if (replace_var(raw, name, offset, pack) == true)
  315. # Now it's our turn...
  316. if ((val = datastore[name]))
  317. if (pack == 'ADDR')
  318. val = Rex::Socket.resolv_nbo(val)
  319. # Someone gave us a funky address (ipv6?)
  320. if(val.length == 16)
  321. raise RuntimeError, "IPv6 address specified for IPv4 payload."
  322. end
  323. elsif (pack == 'ADDR6')
  324. val = Rex::Socket.resolv_nbo(val)
  325. # Convert v4 to the v6ish address
  326. if(val.length == 4)
  327. nip = "fe80::5efe:" + val.unpack("C*").join(".")
  328. val = Rex::Socket.resolv_nbo(nip)
  329. end
  330. elsif (['ADDR16MSB', 'ADDR16LSB', 'ADDR22MSB', 'ADDR22LSB'].include?(pack))
  331. val = Rex::Socket.resolv_nbo(val)
  332. # Someone gave us a funky address (ipv6?)
  333. if(val.length == 16)
  334. raise RuntimeError, "IPv6 address specified for IPv4 payload."
  335. end
  336. elsif (pack == 'RAW')
  337. # Just use the raw value...
  338. else
  339. # Check to see if the value is a hex string. If so, convert
  340. # it.
  341. if val.kind_of?(String)
  342. if val =~ /^\\x/n
  343. val = [ val.gsub(/\\x/n, '') ].pack("H*").unpack(pack)[0]
  344. elsif val =~ /^0x/n
  345. val = val.hex
  346. end
  347. end
  348. # NOTE:
  349. # Packing assumes integer format at this point, should fix...
  350. val = [ val.to_i ].pack(pack)
  351. end
  352. # Substitute it
  353. if (['ADDR16MSB', 'ADDR16LSB'].include?(pack))
  354. if (offset.length != 2)
  355. raise RuntimeError, "Missing value for payload offset, there must be two offsets."
  356. end
  357. if (pack == 'ADDR16LSB')
  358. val = val.unpack('N').pack('V')
  359. end
  360. raw[offset[0], 2] = val[0, 2]
  361. raw[offset[1], 2] = val[2, 2]
  362. elsif (['ADDR22MSB', 'ADDR22LSB'].include?(pack))
  363. if (offset.length != 2)
  364. raise RuntimeError, "Missing value for payload offset, there must be two offsets."
  365. end
  366. if (pack == 'ADDR22LSB')
  367. val = val.unpack('N').pack('V')
  368. end
  369. hi = (0xfffffc00 & val) >> 10
  370. lo = 0x3ff & val
  371. ins = raw[offset[0], 4]
  372. raw[offset[0], 4] = ins | hi
  373. ins = raw[offset[1], 4]
  374. raw[offset[1], 4] = ins | lo
  375. else
  376. raw[offset, val.length] = val
  377. end
  378. else
  379. wlog("Missing value for payload offset #{name}, skipping.",
  380. 'core', LEV_3)
  381. end
  382. }
  383. end
  384. #
  385. # Replaces an individual variable in the supplied buffer at an offset
  386. # using the given pack type. This is here to allow derived payloads
  387. # the opportunity to replace advanced variables.
  388. #
  389. def replace_var(raw, name, offset, pack)
  390. return false
  391. end
  392. ##
  393. #
  394. # Shortcut methods for filtering compatible encoders
  395. # and NOP sleds
  396. #
  397. ##
  398. #
  399. # Returns the array of compatible encoders for this payload instance.
  400. #
  401. def compatible_encoders
  402. encoders = []
  403. framework.encoders.each_module_ranked(
  404. 'Arch' => self.arch, 'Platform' => self.platform) { |name, mod|
  405. encoders << [ name, mod ]
  406. }
  407. return encoders
  408. end
  409. #
  410. # Returns the array of compatible nops for this payload instance.
  411. #
  412. def compatible_nops
  413. nops = []
  414. framework.nops.each_module_ranked(
  415. 'Arch' => self.arch) { |name, mod|
  416. nops << [ name, mod ]
  417. }
  418. return nops
  419. end
  420. #
  421. # A placeholder stub, to be overriden by mixins
  422. #
  423. def apply_prepends(raw)
  424. raw
  425. end
  426. ##
  427. #
  428. # Event notifications.
  429. #
  430. ##
  431. #
  432. # Once an exploit completes and a session has been created on behalf of the
  433. # payload, the framework will call the payload's on_session notification
  434. # routine to allow it to manipulate the session prior to handing off
  435. # control to the user.
  436. #
  437. def on_session(session)
  438. # If this payload is associated with an exploit, inform the exploit
  439. # that a session has been created and potentially shut down any
  440. # open sockets. This allows active exploits to continue hammering
  441. # on a service until a session is created.
  442. if (assoc_exploit)
  443. # Signal that a new session is created by calling the exploit's
  444. # on_new_session handler. The default behavior is to set an
  445. # instance variable, which the exploit will have to check.
  446. begin
  447. assoc_exploit.on_new_session(session)
  448. rescue ::Exception => e
  449. dlog("#{assoc_exploit.refname}: on_new_session handler triggered exception: #{e.class} #{e} #{e.backtrace}", 'core', LEV_1) rescue nil
  450. end
  451. # Set the abort sockets flag only if the exploit is not passive
  452. # and the connection type is not 'find'
  453. if (
  454. (assoc_exploit.exploit_type == Exploit::Type::Remote) and
  455. (assoc_exploit.passive? == false) and
  456. (connection_type != 'find')
  457. )
  458. assoc_exploit.abort_sockets
  459. end
  460. end
  461. end
  462. #
  463. # This attribute holds the string that should be prepended to the buffer
  464. # when it's generated.
  465. #
  466. attr_accessor :prepend
  467. #
  468. # This attribute holds the string that should be appended to the buffer
  469. # when it's generated.
  470. #
  471. attr_accessor :append
  472. #
  473. # This attribute holds the string that should be prepended to the encoded
  474. # version of the payload (in front of the encoder as well).
  475. #
  476. attr_accessor :prepend_encoder
  477. #
  478. # If this payload is associated with an exploit, the assoc_exploit
  479. # attribute will point to that exploit instance.
  480. #
  481. attr_accessor :assoc_exploit
  482. #
  483. # The amount of space available to the payload, which may be nil,
  484. # indicating that the smallest possible payload should be used.
  485. #
  486. attr_accessor :available_space
  487. protected
  488. #
  489. # If the payload has assembly that needs to be compiled, do so now.
  490. #
  491. # Blobs will be cached in the framework's PayloadSet
  492. #
  493. # @see PayloadSet#check_blob_cache
  494. # @param asm [String] Assembly code to be assembled into a raw payload
  495. # @return [String] The final, assembled payload
  496. # @raise ArgumentError if +asm+ is blank
  497. def build(asm, off={})
  498. if(asm.nil? or asm.empty?)
  499. raise ArgumentError, "Assembly must not be empty"
  500. end
  501. # Use the refname so blobs can be flushed when the module gets
  502. # reloaded and use the hash value to ensure that we're actually
  503. # getting the right blob for the given assembly.
  504. cache_key = refname + asm.hash.to_s
  505. cache_entry = framework.payloads.check_blob_cache(cache_key)
  506. off.each_pair { |option, val|
  507. if (val[1] == 'RAW')
  508. asm = asm.gsub(/#{option}/){ datastore[option] }
  509. off.delete(option)
  510. end
  511. }
  512. # If there is a valid cache entry, then we don't need to worry about
  513. # rebuilding the assembly
  514. if cache_entry
  515. # Update the local offsets from the cache
  516. off.each_key { |option|
  517. off[option] = cache_entry[1][option]
  518. }
  519. # Return the cached payload blob
  520. return cache_entry[0].dup
  521. end
  522. # Assemble the payload from the assembly
  523. a = self.arch
  524. if a.kind_of? Array
  525. a = self.arch.first
  526. end
  527. cpu = case a
  528. when ARCH_X86 then Metasm::Ia32.new
  529. when ARCH_X86_64 then Metasm::X86_64.new
  530. when ARCH_X64 then Metasm::X86_64.new
  531. when ARCH_PPC then Metasm::PowerPC.new
  532. when ARCH_ARMLE then Metasm::ARM.new
  533. when ARCH_MIPSLE then Metasm::MIPS.new(:little)
  534. when ARCH_MIPSBE then Metasm::MIPS.new(:big)
  535. else
  536. elog("Broken payload #{refname} has arch unsupported with assembly: #{module_info["Arch"].inspect}")
  537. elog("Call stack:\n#{caller.join("\n")}")
  538. return ""
  539. end
  540. sc = Metasm::Shellcode.assemble(cpu, asm).encoded
  541. # Calculate the actual offsets now that it's been built
  542. off.each_pair { |option, val|
  543. off[option] = [ sc.offset_of_reloc(option) || val[0], val[1] ]
  544. }
  545. # Cache the payload blob
  546. framework.payloads.add_blob_cache(cache_key, sc.data, off)
  547. # Return a duplicated copy of the assembled payload
  548. sc.data.dup
  549. end
  550. #
  551. # Generate the payload using our local payload blob and offsets
  552. #
  553. def internal_generate
  554. # Build the payload, either by using the raw payload blob defined in the
  555. # module or by actually assembling it
  556. if assembly and !assembly.empty?
  557. raw = build(assembly, offsets)
  558. else
  559. raw = payload.dup
  560. end
  561. # If the payload is generated and there are offsets to substitute,
  562. # do that now.
  563. if (raw and offsets)
  564. substitute_vars(raw, offsets)
  565. end
  566. return raw
  567. end
  568. ##
  569. #
  570. # Custom merge operations for payloads
  571. #
  572. ##
  573. #
  574. # Merge the name to prefix the existing one and separate them
  575. # with a comma
  576. #
  577. def merge_name(info, val)
  578. if (info['Name'])
  579. info['Name'] = val + ',' + info['Name']
  580. else
  581. info['Name'] = val
  582. end
  583. end
  584. end
  585. end