Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Path: blob/master/lib/rex/proto/natpmp/packet.rb
Views: 11704
# -*- coding: binary -*-1##2#3# NAT-PMP protocol support4#5##67module Rex8module Proto9module NATPMP::Packet1011# Return a NAT-PMP request to get the external address.12def external_address_request13[ 0, 0 ].pack('nn')14end1516def get_external_address(udp_sock, host, port, timeout=1)17vprint_status("#{host}:#{port} - Probing NAT-PMP for external address")18udp_sock.sendto(external_address_request, host, port, 0)19external_address = nil20while (r = udp_sock.recvfrom(12, timeout) and r[1])21(ver, op, result, epoch, external_address) = parse_external_address_response(r[0])22if external_address23vprint_good("#{host}:#{port} - NAT-PMP external address is #{external_address}")24break25end26end27external_address28end2930# Parse a NAT-PMP external address response +resp+.31# Returns the decoded parts of the response as an array.32def parse_external_address_response(resp)33(ver, op, result, epoch, addr) = resp.unpack("CCnNN")34[ ver, op, result, epoch, Rex::Socket::addr_itoa(addr) ]35end3637def map_port(udp_sock, host, port, int_port, ext_port, protocol, lifetime, timeout=1)38vprint_status("#{host}:#{port} - Sending NAT-PMP mapping request")39# build the mapping request40req = map_port_request(int_port, ext_port,41Rex::Proto::NATPMP.const_get(datastore['PROTOCOL']), datastore['LIFETIME'])42# send it43udp_sock.sendto(req, host, datastore['RPORT'], 0)44# handle the reply45while (r = udp_sock.recvfrom(16, timeout) and r[1])46(_, _, result, _, _, actual_ext_port, _) = parse_map_port_response(r[0])47return (result == 0 ? actual_ext_port : nil)48end49nil50end5152# Return a NAT-PMP request to map remote port +rport+/+protocol+ to local port +lport+ for +lifetime+ ms53def map_port_request(lport, rport, protocol, lifetime)54[ Rex::Proto::NATPMP::Version, # version55protocol, # opcode, which is now the protocol we are asking to forward560, # reserved57lport,58rport,59lifetime60].pack("CCnnnN")61end6263# Parse a NAT-PMP mapping response +resp+.64# Returns the decoded parts as an array.65def parse_map_port_response(resp)66resp.unpack("CCnNnnN")67end6869end7071end72end737475