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.

capture.rb 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  1. # -*- coding: binary -*-
  2. module Msf
  3. ###
  4. #
  5. # This module provides methods for sending and receiving
  6. # raw packets. It should be preferred over the soon-to-be
  7. # deprecated Rex::Socket::Ip and Msf::Exploit::Remote::Ip
  8. # mixins.
  9. #
  10. # Please see the pcaprub documentation for more information
  11. # on how to use capture objects.
  12. #
  13. ###
  14. class Exploit
  15. module Capture
  16. #
  17. # Initializes an instance of an exploit module that captures traffic
  18. #
  19. def initialize(info = {})
  20. super
  21. register_options(
  22. [
  23. OptPath.new('PCAPFILE', [false, 'The name of the PCAP capture file to process']),
  24. OptString.new('INTERFACE', [false, 'The name of the interface']),
  25. OptString.new('FILTER', [false, 'The filter string for capturing traffic']),
  26. OptInt.new('SNAPLEN', [true, 'The number of bytes to capture', 65535]),
  27. OptInt.new('TIMEOUT', [true, 'The number of seconds to wait for new data', 500]),
  28. Opt::RHOST
  29. ], Msf::Exploit::Capture
  30. )
  31. register_advanced_options(
  32. [
  33. OptInt.new('SECRET', [true, 'A 32-bit cookie for probe requests.', 'MSF!'.unpack('N').first]),
  34. OptAddress.new('GATEWAY_PROBE_HOST',
  35. [
  36. true,
  37. 'Send a TTL=1 random UDP datagram to this host to discover the default gateway\'s MAC',
  38. '8.8.8.8']),
  39. OptPort.new('GATEWAY_PROBE_PORT',
  40. [
  41. false,
  42. 'The port on GATEWAY_PROBE_HOST to send a random UDP probe to (random if 0 or unset)'])
  43. ], Msf::Exploit::Capture
  44. )
  45. require 'packetfu'
  46. begin
  47. require 'pcaprub'
  48. @pcaprub_loaded = true
  49. rescue ::LoadError => e
  50. @pcaprub_loaded = false
  51. @pcaprub_error = e
  52. end
  53. begin
  54. require 'network_interface'
  55. @network_interface_loaded = true
  56. rescue ::LoadError => e
  57. @network_interface_loaded = false
  58. @network_interface_error = e
  59. end
  60. end
  61. def stats_recv(pcap=self.capture)
  62. return(0) unless pcap
  63. pcap.stats['recv']
  64. end
  65. def stats_drop(pcap=self.capture)
  66. return(0) unless pcap
  67. pcap.stats['drop']
  68. end
  69. def stats_ifdrop(pcap=self.capture)
  70. return(0) unless pcap
  71. pcap.stats['ifdrop']
  72. end
  73. #
  74. # Opens a handle to the specified device
  75. #
  76. def open_pcap(opts={})
  77. check_pcaprub_loaded
  78. if RUBY_PLATFORM == "i386-mingw32"
  79. if opts['INTERFACE'] or datastore['INTERFACE']
  80. dev = opts['INTERFACE'] || datastore['INTERFACE']
  81. if is_interface?(dev)
  82. dev = get_interface_guid(dev)
  83. end
  84. end
  85. else
  86. dev = opts['INTERFACE'] || datastore['INTERFACE'] || nil
  87. end
  88. len = (opts['SNAPLEN'] || datastore['SNAPLEN'] || 65535).to_i
  89. tim = (opts['TIMEOUT'] || datastore['TIMEOUT'] || 0).to_i
  90. fil = opts['FILTER'] || datastore['FILTER']
  91. do_arp = (opts['ARPCAP'] == false) ? false : true
  92. # Look for a PCAP file
  93. cap = datastore['PCAPFILE'] || ''
  94. if (not cap.empty?)
  95. if (not File.exist?(cap))
  96. raise RuntimeError, "The PCAP file #{cap} could not be found"
  97. end
  98. self.capture = ::Pcap.open_offline(cap)
  99. else
  100. dev ||= ::Pcap.lookupdev
  101. unless RUBY_PLATFORM == "i386-mingw32"
  102. system("ifconfig", dev, "up")
  103. end
  104. self.capture = ::Pcap.open_live(dev, len, true, tim)
  105. if do_arp
  106. self.arp_capture = ::Pcap.open_live(dev, 512, true, tim)
  107. preamble = datastore['SECRET'].to_i
  108. arp_filter = "arp[6:2] = 2 or (udp[8:4] = #{preamble})"
  109. self.arp_capture.setfilter(arp_filter)
  110. end
  111. end
  112. if (not self.capture)
  113. raise RuntimeError, "Could not start the capture process"
  114. elsif (do_arp and !self.arp_capture and cap.empty?)
  115. raise RuntimeError, "Could not start the ARP capture process"
  116. end
  117. self.capture.setfilter(fil) if fil
  118. end
  119. def close_pcap
  120. return unless self.capture
  121. self.capture = nil
  122. self.arp_capture = nil
  123. end
  124. def capture_extract_ies(raw)
  125. set = {}
  126. idx = 0
  127. len = 0
  128. while (idx < raw.length)
  129. len = raw[idx+1]
  130. return set unless len
  131. set[raw[idx]] ||= []
  132. set[raw[idx]].push(raw[idx + 2, len])
  133. idx += len + 2
  134. end
  135. return set
  136. end
  137. #
  138. # Loop through each packet
  139. #
  140. def each_packet
  141. return unless capture
  142. @capture_count ||= 0
  143. capture.each do |pkt|
  144. yield(pkt)
  145. @capture_count += 1
  146. end
  147. @capture_count
  148. end
  149. # Injects a packet on the wire. For all injection-related functions, it's
  150. # on the module to open up a capture device first (this way, we don't
  151. # needlessly spawn new capture devices).
  152. def inject(pkt="", pcap=self.capture)
  153. check_pcaprub_loaded
  154. if not pcap
  155. raise RuntimeError, "Could not access the capture process (remember to open_pcap first!)"
  156. else
  157. pcap.inject(pkt.to_s) # Can be a PacketFu Packet object or a pre-packed string
  158. end
  159. end
  160. # Injects an Ethernet packet with an optional payload. The payload
  161. # may be a regular PacketFu packet, an EthHeader, or a string.
  162. def inject_eth(args={})
  163. eth_daddr = args[:eth_daddr] || "ff:ff:ff:ff:ff:ff"
  164. eth_saddr = args[:eth_saddr] || "00:00:00:00:00:00"
  165. eth_type = args[:eth_type] || 0x0800 # IP default
  166. payload = args[:payload]
  167. pcap = args[:pcap] || self.capture
  168. p = PacketFu::EthPacket.new
  169. p.eth_daddr = eth_daddr
  170. p.eth_saddr = eth_saddr
  171. p.eth_proto = eth_type
  172. if payload
  173. if payload.kind_of? PacketFu::EthPacket
  174. p.payload = payload.eth_header.body
  175. elsif payload.kind_of? PacketFu::EthHeader
  176. p.payload = payload.body
  177. else
  178. p.payload = payload.to_s
  179. end
  180. end
  181. inject p.to_s, pcap
  182. end
  183. def inject_pcap(pcap_file, filter=nil, delay = 0, pcap=self.capture)
  184. check_pcaprub_loaded
  185. unless pcap
  186. raise RuntimeError, "Could not access the capture process (remember to open_pcap first!)"
  187. end
  188. if (not File.exist?(pcap_file))
  189. raise RuntimeError, "The PCAP file #{pcap_file} could not be found"
  190. end
  191. if (pcap_file.empty?)
  192. raise RuntimeError, "The PCAP file #{pcap_file} is empty"
  193. end
  194. capture_file = ::Pcap.open_offline(pcap_file)
  195. capture_file.setfilter(filter) if filter
  196. while (pkt = capture_file.next) do
  197. pcap.inject(pkt)
  198. Rex.sleep((delay * 1.0)/1000)
  199. end
  200. end
  201. # Sends a payload to a given target using the pcap capture interface
  202. #
  203. # == Parameters:
  204. # payload:: The payload String to send
  205. # dhost:: the destination host to send to
  206. # bcast:: set to `true` to send to the broadcast address if necessary
  207. # dev:: the name of the network interface to send the payload on
  208. #
  209. # == Returns:
  210. # The number of bytes sent iff the payload was successfully sent/injected. `false` otherwise
  211. def capture_sendto(payload="", dhost=nil, bcast=false, dev=nil)
  212. raise RuntimeError, "Could not access the capture process (remember to open_pcap first!)" unless self.capture
  213. raise RuntimeError, "Must specify a host to sendto" unless dhost
  214. dev ||= datastore['INTERFACE']
  215. dst_mac, src_mac = lookup_eth(dhost, dev)
  216. if dst_mac == nil and not bcast
  217. vprint_error("Unable to determine the destination MAC for #{dhost} on #{dev} and bcast is false")
  218. return false
  219. end
  220. inject_eth(:payload => payload, :eth_daddr => dst_mac, :eth_saddr => src_mac)
  221. end
  222. # The return value either be a PacketFu::Packet object, or nil
  223. def inject_reply(proto=:udp, pcap=self.capture)
  224. # Defaults to ~2 seconds
  225. to = ((datastore['TIMEOUT'] || 500).to_f * 4) / 1000.0
  226. raise RuntimeError, "Could not access the capture process (remember to open_pcap first!)" if not pcap
  227. begin
  228. ::Timeout.timeout(to) do
  229. pcap.each do |r|
  230. packet = PacketFu::Packet.parse(r)
  231. next unless packet.proto.map { |x| x.downcase.to_sym }.include? proto
  232. return packet
  233. end
  234. end
  235. rescue ::Timeout::Error
  236. end
  237. nil
  238. end
  239. # This ascertains the correct Ethernet addresses one should use to
  240. # ensure injected IP packets actually get where they are going, and
  241. # manages the self.arp_cache hash. It always uses self.arp_capture
  242. # to inject and capture packets, and will always first fire off a
  243. # UDP packet using the regular socket to learn the source host's
  244. # and gateway's mac addresses.
  245. def lookup_eth(addr=nil, iface=nil)
  246. raise RuntimeError, "Could not access the capture process." unless self.arp_capture
  247. self.arp_cache ||= {}
  248. self.dst_cache ||= {}
  249. return self.dst_cache[addr] if self.dst_cache[addr]
  250. if !self.arp_cache[Rex::Socket.source_address(addr)]
  251. probe_gateway(addr)
  252. end
  253. src_mac = self.arp_cache[Rex::Socket.source_address(addr)]
  254. if should_arp?(addr)
  255. dst_mac = self.arp_cache[addr] || arp(addr)
  256. else
  257. dst_mac = self.arp_cache[:gateway]
  258. end
  259. self.dst_cache[addr] = [dst_mac, src_mac]
  260. end
  261. def probe_gateway(addr)
  262. dst_host = datastore['GATEWAY_PROBE_HOST']
  263. dst_port = datastore['GATEWAY_PROBE_PORT'].to_i == 0 ? rand(30000) + 1024 : datastore['GATEWAY_PROBE_PORT']
  264. preamble = [datastore['SECRET']].pack("N")
  265. secret = "#{preamble}#{Rex::Text.rand_text(rand(0xff)+1)}"
  266. begin
  267. UDPSocket.open do |sock|
  268. sock.setsockopt(::Socket::IPPROTO_IP, ::Socket::IP_TTL, 1)
  269. sock.send(secret, 0, dst_host, dst_port)
  270. end
  271. rescue Errno::ENETUNREACH
  272. # This happens on networks with no gateway. We'll need to use a
  273. # fake source hardware address.
  274. self.arp_cache[Rex::Socket.source_address(addr)] = "00:00:00:00:00:00"
  275. end
  276. begin
  277. to = ((datastore['TIMEOUT'] || 500).to_f * 8) / 1000.0
  278. ::Timeout.timeout(to) do
  279. loop do
  280. my_packet = inject_reply(:udp, self.arp_capture)
  281. next unless my_packet
  282. next unless my_packet.payload == secret
  283. dst_mac = self.arp_cache[:gateway] = my_packet.eth_daddr
  284. src_mac = self.arp_cache[Rex::Socket.source_address(addr)] = my_packet.eth_saddr
  285. return [dst_mac, src_mac]
  286. end
  287. end
  288. rescue ::Timeout::Error
  289. # Well, that didn't work (this is common on networks where there's no gateway, like
  290. # VMWare network interfaces. We'll need to use a fake source hardware address.
  291. self.arp_cache[Rex::Socket.source_address(addr)] = "00:00:00:00:00:00"
  292. end
  293. end
  294. # A pure-Ruby ARP exchange. It uses self.arp_capture to send and recv
  295. # packets, rather than self.capture.
  296. def arp(target_ip=nil)
  297. return self.arp_cache[target_ip] if self.arp_cache[target_ip]
  298. return self.arp_cache[:gateway] unless should_arp? target_ip
  299. source_ip = Rex::Socket.source_address(target_ip)
  300. raise RuntimeError, "Could not access the capture process." unless self.arp_capture
  301. p = arp_packet(target_ip, source_ip)
  302. # Try up to 3 times to get an ARP response
  303. 1.upto(3) do
  304. inject_eth(:eth_type => 0x0806,
  305. :payload => p,
  306. :pcap => self.arp_capture,
  307. :eth_saddr => self.arp_cache[Rex::Socket.source_address(target_ip)]
  308. )
  309. begin
  310. to = ((datastore['TIMEOUT'] || 500).to_f * 8) / 1000.0
  311. ::Timeout.timeout(to) do
  312. loop do
  313. my_packet = inject_reply(:arp, self.arp_capture)
  314. next unless my_packet
  315. next unless my_packet.arp_saddr_ip == target_ip
  316. self.arp_cache[target_ip] = my_packet.eth_saddr
  317. return self.arp_cache[target_ip]
  318. end
  319. end
  320. rescue ::Timeout::Error
  321. end
  322. end
  323. nil
  324. end
  325. # Creates a full ARP packet, mainly for use with inject_eth()
  326. def arp_packet(target_ip=nil, source_ip=nil)
  327. p = PacketFu::ARPPacket.new
  328. p.arp_opcode = 1
  329. p.arp_daddr_ip = target_ip || datastore['RHOST']
  330. p.arp_saddr_ip = source_ip || datastore['LHOST']
  331. my_eth = self.arp_cache[Rex::Socket.source_address(target_ip)]
  332. p.arp_saddr_mac = my_eth || "00:00:00:00:00:00"
  333. return p
  334. end
  335. # Allow modules to reset their arp caches arbitrarily.
  336. def expire_arpcache
  337. self.arp_cache = {}
  338. end
  339. # For compatibilty with Msf::Exploit::Remote::Ip
  340. def rhost
  341. datastore['RHOST']
  342. end
  343. def check_pcaprub_loaded
  344. if not @pcaprub_loaded
  345. print_status("The Pcaprub module is not available: #{@pcaprub_error}")
  346. raise RuntimeError, "Pcaprub not available"
  347. elsif not @network_interface_loaded
  348. print_status("The NetworkInterface module is not available: #{@network_interface_error}")
  349. raise RuntimeError, "NetworkInterface not available"
  350. else
  351. true
  352. end
  353. end
  354. def lookupnet
  355. check_pcaprub_loaded
  356. dev = datastore['INTERFACE'] || ::Pcap.lookupdev
  357. begin
  358. my_ip, my_mask = Pcap.lookupnet(dev)
  359. # convert the netmask obtained from the relevant interface to CIDR
  360. cidr_mask = my_mask.to_s(2).count('1')
  361. my_net = IPAddr.new("#{my_ip}/#{cidr_mask}")
  362. rescue RuntimeError => e
  363. @pcaprub_error = e
  364. print_status("Cannot stat device: #{@pcaprub_error}")
  365. raise RuntimeError, "Pcaprub error: #{@pcaprub_error}"
  366. end
  367. return my_net
  368. end
  369. def should_arp?(ip)
  370. lookupnet.include?(IPAddr.new(ip))
  371. end
  372. attr_accessor :capture, :arp_cache, :arp_capture, :dst_cache
  373. # Netifaces code
  374. def netifaces_implemented?
  375. @network_interface_loaded and
  376. NetworkInterface.respond_to?(:interfaces) and
  377. NetworkInterface.respond_to?(:addresses)
  378. end
  379. def list_interfaces
  380. check_pcaprub_loaded
  381. NetworkInterface.interfaces
  382. end
  383. def is_interface?(dev)
  384. check_pcaprub_loaded
  385. if RUBY_PLATFORM == "i386-mingw32"
  386. if dev =~ /\\Device\\NPF_\{[A-F0-9]{8}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{12}\}/
  387. return NetworkInterface.interfaces.include?(dev)
  388. elsif dev.to_s =~ /^[0-9]{1,2}$/
  389. if (dev.to_i <= NetworkInterface.interfaces.length) and (dev.to_i >= 0)
  390. return true
  391. else
  392. return false
  393. end
  394. else
  395. return false
  396. end
  397. else
  398. return NetworkInterface.interfaces.include?(dev)
  399. end
  400. end
  401. # This function is useful only on windows where pcaprub use the GUID
  402. def get_interface_guid(dev)
  403. check_pcaprub_loaded
  404. if RUBY_PLATFORM == "i386-mingw32"
  405. if dev.to_s =~ /^[0-9]{1,2}$/
  406. if is_interface?(dev)
  407. NetworkInterface.interfaces[(dev.to_i) - 1]
  408. else
  409. return dev
  410. end
  411. else
  412. return dev
  413. end
  414. else #Non windows
  415. return dev
  416. end
  417. end
  418. def get_mac(dev)
  419. check_pcaprub_loaded
  420. dev = get_interface_guid(dev)
  421. addrs = NetworkInterface.addresses(dev)
  422. raise RuntimeError, "Interface #{dev} does not exist" if !addrs
  423. raise RuntimeError, "Cannot get mac address for interface #{dev}" if !addrs[NetworkInterface::AF_LINK][0]['addr']
  424. addrs[NetworkInterface::AF_LINK][0]['addr']
  425. end
  426. def get_ipv4_addr_count(dev)
  427. check_pcaprub_loaded
  428. dev = get_interface_guid(dev)
  429. addrs = NetworkInterface.addresses(dev)
  430. raise RuntimeError, "Interface #{dev} does not exist" if !addrs
  431. addrs[NetworkInterface::AF_INET].length
  432. end
  433. def get_ipv4_addr(dev, num=0)
  434. check_pcaprub_loaded
  435. dev = get_interface_guid(dev)
  436. addrs = NetworkInterface.addresses(dev)
  437. raise RuntimeError, "Interface #{dev} does not exist" if !addrs
  438. raise RuntimeError, "Interface #{dev} does not have an ipv4 address at position #{num}" if addrs[NetworkInterface::AF_INET].length < num + 1
  439. raise RuntimeError, "Cannot get the IPv4 address for interface #{dev}" if !addrs[NetworkInterface::AF_INET][num]['addr']
  440. addrs[NetworkInterface::AF_INET][num]['addr']
  441. end
  442. def get_ipv4_netmask(dev, num=0)
  443. check_pcaprub_loaded
  444. dev = get_interface_guid(dev)
  445. addrs = NetworkInterface.addresses(dev)
  446. raise RuntimeError, "Interface #{dev} does not exist" if !addrs
  447. raise RuntimeError, "Interface #{dev} does not have an ipv4 address at position #{num}" if addrs[NetworkInterface::AF_INET].length < num + 1
  448. raise RuntimeError, "Cannot get IPv4 netmask for interface #{dev}" if !addrs[NetworkInterface::AF_INET][num]['netmask']
  449. addrs[NetworkInterface::AF_INET][num]['netmask']
  450. end
  451. def get_ipv4_broadcast(dev, num=0)
  452. check_pcaprub_loaded
  453. dev = get_interface_guid(dev)
  454. addrs = NetworkInterface.addresses(dev)
  455. raise RuntimeError, "Interface #{dev} do not exists" if !addrs
  456. raise RuntimeError, "Interface #{dev} do not have an ipv4 address at position #{num}" if addrs[NetworkInterface::AF_INET].length < num + 1
  457. raise RuntimeError, "Cannot get IPv4 broadcast address for interface #{dev}" if !addrs[NetworkInterface::AF_INET][num]['broadcast']
  458. addrs[NetworkInterface::AF_INET][num]['broadcast']
  459. end
  460. def get_ipv6_addr_count(dev)
  461. check_pcaprub_loaded
  462. dev = get_interface_guid(dev)
  463. raise RuntimeError, "IPv6 information is not available on this platform" unless ::NetworkInterface.const_defined?(:AF_INET6)
  464. addrs = NetworkInterface.addresses(dev)
  465. raise RuntimeError, "Interface #{dev} do not exists" if !addrs
  466. addrs[NetworkInterface::AF_INET6].length
  467. end
  468. # NOTE: IPv6 is not implemented on Windows
  469. def get_ipv6_addr(dev, num=0)
  470. check_pcaprub_loaded
  471. dev = get_interface_guid(dev)
  472. raise RuntimeError, "IPv6 information is not available on this platform" unless ::NetworkInterface.const_defined?(:AF_INET6)
  473. addrs = NetworkInterface.addresses(dev)
  474. raise RuntimeError, "Interface #{dev} do not exists" if !addrs
  475. raise RuntimeError, "Interface #{dev} do not have an ipv6 address at position #{num}" if addrs[NetworkInterface::AF_INET6].length < num + 1
  476. raise RuntimeError, "Cannot get ipv6 address for interface #{dev}" if !addrs[NetworkInterface::AF_INET6][num]['addr']
  477. addrs[NetworkInterface::AF_INET6][num]['addr'].gsub(/%(.)*$/, '')
  478. end
  479. def get_ipv6_netmask(dev, num=0)
  480. check_pcaprub_loaded
  481. dev = get_interface_guid(dev)
  482. raise RuntimeError, "IPv6 information is not available on this platform" unless ::NetworkInterface.const_defined?(:AF_INET6)
  483. addrs = NetworkInterface.addresses(dev)
  484. raise RuntimeError, "Interface #{dev} do not exists" if !addrs
  485. raise RuntimeError, "Interface #{dev} do not have an ipv6 address at position #{num}" if addrs[NetworkInterface::AF_INET6].length < num + 1
  486. raise RuntimeError, "Cannot get ipv6 netmask address for interface #{dev}" if !addrs[NetworkInterface::AF_INET6][num]['netmask']
  487. addrs[NetworkInterface::AF_INET6][num]['netmask']
  488. end
  489. # Protocol-specific encoding/decoding methods until more
  490. # application protos get into PacketFu proper
  491. # Intended to be used as the payload to an ICMP echo request's payload
  492. def capture_icmp_echo_pack(id=nil, seq=nil, payload=nil)
  493. id ||= rand(0x10000)
  494. seq ||= rand(0x10000)
  495. [id, seq, payload.to_s].pack("nna*")
  496. end
  497. # Decodes and ICMP echo request or response.
  498. def capture_icmp_echo_unpack(data)
  499. data.unpack("nna*")
  500. end
  501. end
  502. end
  503. end