Module: PWN::Plugins::Recon
- Defined in:
- lib/pwn/plugins/recon.rb
Overview
subfinder/httpx/masscan wrappers + cert-transparency (crt.sh, certspotter).
Constant Summary collapse
- UA =
'pwn-recon/1.0'
Class Method Summary collapse
- .amass(opts = {}) ⇒ Object
- .authors ⇒ Object
- .crt_sh(opts = {}) ⇒ Object
- .help ⇒ Object
- .httpx(opts = {}) ⇒ Object
- .masscan(opts = {}) ⇒ Object
- .passive_dns(opts = {}) ⇒ Object
- .required_bins ⇒ Object
-
.run(opts = {}) ⇒ Object
Persisted asset IDs are the join key for Context ingestion and Findings.
- .subdomains(opts = {}) ⇒ Object
Class Method Details
.amass(opts = {}) ⇒ Object
242 243 244 245 246 247 248 249 |
# File 'lib/pwn/plugins/recon.rb', line 242 public_class_method def self.amass(opts = {}) PWN::Plugins::PreflightChecker.require_bin!(name: 'amass') domain = opts[:domain].to_s raise 'ERROR: domain is required' if domain.empty? stdout, = Open3.capture3('amass', 'enum', '-passive', '-d', domain, '-nocolor') stdout.lines.map(&:strip).reject(&:empty?) end |
.authors ⇒ Object
262 263 264 |
# File 'lib/pwn/plugins/recon.rb', line 262 public_class_method def self. "AUTHOR(S):\n 0day Inc. <[email protected]>\n" end |
.crt_sh(opts = {}) ⇒ Object
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 |
# File 'lib/pwn/plugins/recon.rb', line 217 public_class_method def self.crt_sh(opts = {}) domain = opts[:domain].to_s.downcase.strip raise 'ERROR: domain is required' if domain.empty? errors = [] names = [] sources = [ "https://api.certspotter.com/v1/issuances?domain=#{URI.encode_www_form_component(domain)}&include_subdomains=true&expand=dns_names", "https://crt.sh/?q=#{URI.encode_www_form_component(domain)}&output=json", "https://crt.sh/?q=#{URI.encode_www_form_component("%.#{domain}")}&output=json" ] sources.each do |url| next if !names.empty? && url.include?('crt.sh') rows = http_json(url: url, timeout: url.include?('crt.sh') ? 8 : (opts[:timeout] || 15)) names.concat(extract_dns_names(rows: rows)) rescue StandardError => e errors << "#{URI(url).host}: #{e.class}: #{e.message}" end out = normalize_names(names: names, domain: domain) return out unless out.empty? raise "ERROR: cert-transparency lookup failed for #{domain} (#{errors.join('; ')})" end |
.help ⇒ Object
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 |
# File 'lib/pwn/plugins/recon.rb', line 266 public_class_method def self.help puts "USAGE: # List host binaries this module expects to be installed. #{self}.required_bins # Normalize explicit scan modules and persist stable evidence-backed asset IDs. #{self}.run( target: 'required - single hostname or IP', modules: 'optional - Array nmap/banner/tls/subfinder/nuclei; defaults nmap/banner', ports: 'optional - Array of integer ports; defaults 80 and 443', engagement_id: 'optional - simple identifier; defaults default', root: 'optional - engagements directory; defaults ~/.pwn/engagements', timeout: 'optional - per-operation timeout seconds; defaults 15, maximum 300', ingest: 'optional - invoke Context.ingest after persistence; defaults false', ingestor: 'optional - callable(path, **options) replacing Context.ingest', ingest_options: 'optional - Hash passed to the ingestor' ) # Run subdomains and return its result #{self}.subdomains( domain: 'required - FQDN to query (e.g. example.com)' ) # Run httpx and return its result #{self}.httpx( hosts: 'optional - Array of hostnames or URLs to probe', urls: 'optional - Array of HTTP(S) URLs' ) # Run masscan and return its result #{self}.masscan( target: 'optional - hostname, IP, or CIDR to scan', ports: 'optional - port, list, or range (e.g. 22,80,443 or 1-1024)' ) # Run crt sh and return its result #{self}.crt_sh( domain: 'required - FQDN to query (e.g. example.com)', timeout: 'optional - seconds to wait before giving up' ) # Passive amass enum (requires amass). #{self}.amass( domain: 'required - FQDN to query (e.g. example.com)' ) # Passive DNS hostsearch for a domain (hackertarget). #{self}.passive_dns( domain: 'required - FQDN to query (e.g. example.com)', timeout: 'optional - seconds to wait before giving up' ) # Print the AUTHOR(S) string for this module. #{self}.authors " constants.sort end |
.httpx(opts = {}) ⇒ Object
196 197 198 199 200 201 202 203 204 205 |
# File 'lib/pwn/plugins/recon.rb', line 196 public_class_method def self.httpx(opts = {}) PWN::Plugins::PreflightChecker.require_bin!(name: 'httpx') hosts = Array(opts[:hosts] || opts[:urls]) stdout, = Open3.capture3('httpx', '-silent', '-json', stdin_data: "#{hosts.join("\n")}\n") stdout.each_line.filter_map do |ln| JSON.parse(ln) rescue JSON::ParserError nil end end |
.masscan(opts = {}) ⇒ Object
207 208 209 210 211 212 213 214 215 |
# File 'lib/pwn/plugins/recon.rb', line 207 public_class_method def self.masscan(opts = {}) bin = %w[masscan naabu].find { |b| PWN::Plugins::PreflightChecker.bin?(name: b) } raise PWN::Plugins::PreflightChecker::MissingBinary, 'ERROR: masscan/naabu missing' unless bin target = opts[:target].to_s ports = (opts[:ports] || '1-1024').to_s stdout, = Open3.capture3(bin, '-p', ports, target) stdout end |
.passive_dns(opts = {}) ⇒ Object
251 252 253 254 255 256 257 258 259 260 |
# File 'lib/pwn/plugins/recon.rb', line 251 public_class_method def self.passive_dns(opts = {}) domain = opts[:domain].to_s.downcase.strip raise 'ERROR: domain is required' if domain.empty? uri = URI("https://api.hackertarget.com/hostsearch/?q=#{URI.encode_www_form_component(domain)}") rows = http_json(url: uri.to_s, timeout: opts[:timeout] || 8) Array(rows) rescue StandardError => e { error: "#{e.class}: #{e.message}", domain: domain } end |
.required_bins ⇒ Object
22 23 24 |
# File 'lib/pwn/plugins/recon.rb', line 22 public_class_method def self.required_bins %w[subfinder httpx masscan amass] end |
.run(opts = {}) ⇒ Object
Persisted asset IDs are the join key for Context ingestion and Findings.
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 |
# File 'lib/pwn/plugins/recon.rb', line 27 public_class_method def self.run(opts = {}) target = opts[:target].to_s raise ArgumentError, 'target must be a single hostname or IP' unless target.match?(/\A[a-zA-Z0-9][a-zA-Z0-9.:-]*\z/) engagement = opts.fetch(:engagement_id, 'default').to_s raise ArgumentError, 'engagement_id must be a simple identifier' unless engagement.match?(/\A[a-zA-Z0-9_-]+\z/) modules = opts.fetch(:modules, %w[nmap banner]).map(&:to_s) raise ArgumentError, 'modules must contain nmap, banner, tls, subfinder or nuclei' if modules.empty? || (modules - %w[nmap banner tls subfinder nuclei]).any? ports = Array(opts.fetch(:ports, [80, 443])) raise ArgumentError, 'ports must be integers in 1..65535' unless !ports.empty? && ports.all? { |port| port.is_a?(Integer) && port.between?(1, 65_535) } timeout = Float(opts.fetch(:timeout, 15)) raise ArgumentError, 'timeout must be in 0..300 seconds' unless timeout.positive? && timeout <= 300 dir = File.join(File.(opts[:root] || '~/.pwn/engagements'), engagement, 'recon') FileUtils.mkdir_p(dir) assets = [] results = modules.uniq.map do |name| probe_errors = [] evidence = File.join(dir, "#{SecureRandom.hex(8)}-#{name}.#{name == 'nmap' ? 'xml' : 'json'}") observations = if name == 'nmap' xml = pipeline_command(argv: ['nmap', '-n', '-Pn', '-sT', '-p', ports.uniq.join(','), '-oX', '-', target], timeout: timeout) File.write(evidence, xml) doc = REXML::Document.new(xml) REXML::XPath.match(doc, '//host').flat_map do |host| address = host.elements['address']&.attributes&.[]('addr') || target REXML::XPath.match(host, 'ports/port').filter_map do |port| next unless port.elements['state']&.attributes&.[]('state') == 'open' { address: address, port: port.attributes['portid'].to_i, protocol: port.attributes['protocol'], source: name, state: 'open', service: port.elements['service']&.attributes&.[]('name') } end end elsif %w[subfinder nuclei].include?(name) argv = name == 'subfinder' ? ['subfinder', '-silent', '-d', target] : ['nuclei', '-silent', '-jsonl', '-duc', '-u', target] output = pipeline_command(argv: argv, timeout: timeout) rows = output.lines.reject { |line| line.strip.empty? }.map do |line| if name == 'subfinder' { address: line.strip.downcase, protocol: 'host', port: nil, source: name } else row = JSON.parse(line) host = URI(row['host'].to_s) { address: host.host || target, protocol: 'tcp', port: host.port, source: name, template_id: row['template-id'], matched_at: row['matched-at'], scanner_severity: row.dig('info', 'severity'), classification: 'scanner_observation' } end end.uniq File.write(evidence, JSON.pretty_generate(rows)) rows else rows = ports.filter_map do |port| Socket.tcp(target, port, connect_timeout: timeout) do |socket| data = if name == 'tls' context = OpenSSL::SSL::SSLContext.new context.verify_mode = OpenSSL::SSL::VERIFY_NONE ssl = OpenSSL::SSL::SSLSocket.new(socket, context) ssl.hostname = target begin Timeout.timeout(timeout) { ssl.connect } cert = ssl.peer_cert { subject: cert.subject.to_s, issuer: cert.issuer.to_s, not_before: cert.not_before.utc.iso8601, not_after: cert.not_after.utc.iso8601, certificate_sha256: Digest::SHA256.hexdigest(cert.to_der), san: cert.extensions.find { |ext| ext.oid == 'subjectAltName' }&.value, tls_version: ssl.ssl_version, trust_verified: false } ensure ssl.close end else = Timeout.timeout(timeout) { socket.readpartial(4096) } { banner: .encode('UTF-8', invalid: :replace, undef: :replace) } end { address: socket.remote_address.ip_address, port: port, protocol: 'tcp', source: name }.merge(data) end rescue StandardError => e probe_errors << { port: port, error: "#{e.class}: #{e.message}" } nil end File.write(evidence, JSON.pretty_generate(rows)) rows end observations.each do |row| id = "asset-#{Digest::SHA256.hexdigest([row[:address].downcase, row[:protocol], row[:port]].join('|'))[0, 24]}" assets << { id: id, address: row[:address], protocol: row[:protocol], port: row[:port], observations: [row], evidence_paths: [evidence] } end status = if probe_errors.empty? 'ok' else (observations.empty? ? 'error' : 'partial') end { name: name, status: status, evidence_path: evidence, errors: probe_errors } rescue Errno::ENOENT => e { name: name, status: 'unavailable', error: e. } rescue StandardError => e { name: name, status: 'error', error: "#{e.class}: #{e.message}" } end path = File.join(dir, 'assets.json') File.open("#{path}.lock", 'a') do |lock| lock.flock(File::LOCK_EX) previous = File.file?(path) ? JSON.parse(File.read(path), symbolize_names: true).fetch(:assets) : [] merged = (previous + assets).group_by { |row| row[:id] }.map do |_id, rows| rows.last.merge(observations: rows.flat_map { |row| row[:observations] }.uniq, evidence_paths: rows.flat_map { |row| row[:evidence_paths] }.uniq) end merged.sort_by! { |row| row[:id] } payload = { schema_version: 1, engagement_id: engagement, assets: merged, modules: results } temp = "#{path}.#{SecureRandom.hex(8)}.tmp" File.write(temp, JSON.pretty_generate(payload)) File.rename(temp, path) end result = JSON.parse(File.read(path), symbolize_names: true).merge(path: path) if opts[:ingest] begin ingestor = opts[:ingestor] || PWN::AI::Context.method(:ingest) result[:ingestion] = ingestor.call(path, session_id: engagement, **opts[:ingest_options] || {}) rescue StandardError => e result[:ingestion] = { status: 'error', error: "#{e.class}: #{e.message}" } end end result end |
.subdomains(opts = {}) ⇒ Object
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 |
# File 'lib/pwn/plugins/recon.rb', line 179 public_class_method def self.subdomains(opts = {}) domain = opts[:domain].to_s.downcase.strip raise 'ERROR: domain is required' if domain.empty? names = [] if PWN::Plugins::PreflightChecker.bin?(name: 'subfinder') stdout, = Open3.capture3('subfinder', '-silent', '-d', domain) names.concat(stdout.lines.map(&:strip).reject(&:empty?)) end if PWN::Plugins::PreflightChecker.bin?(name: 'amass') stdout, = Open3.capture3('amass', 'enum', '-passive', '-d', domain, '-nocolor') names.concat(stdout.lines.map(&:strip).reject(&:empty?)) end names.concat(Array(crt_sh(domain: domain))) normalize_names(names: names, domain: domain) end |