scan_engine.cc

来自「Ubuntu packages of security software。 相」· CC 代码 · 共 1,755 行 · 第 1/5 页

CC
1,755
字号
  int num_probes_active;   UltraScanInfo *USI; /* The USI which contains this GSS.  Use for at least			 getting the current time w/o gettimeofday() */  struct ultra_timing_vals timing;  struct timeout_info to; /* Group-wide packet rtt/timeout info */  int numtargets; /* Total # of targets scanned -- includes finished and incomplete hosts */  int numprobes; /* Number of probes/ports scanned on each host */  /* The last time waitForResponses finished (initialized to GSS creation time */  int probes_sent; /* Number of probes sent in total.  This DOES include pings and retransmissions */  int probes_replied_to; /* The number of probes for which we've received     responses. Used for scaling congestion control increments. */  /* Returns the scaling factor to use when incrementing the congestion window.     This is the minimum of probes_sent / probes_replied_to and cc_scale_max. */  double cc_scale();  /* The most recently received probe response time -- initialized to scan     start time. */  struct timeval lastrcvd;  /* The time the most recent ping was sent (initialized to scan begin time) */  struct timeval lastping_sent;  /* Value of numprobes_sent at lastping_sent time -- to ensure that we don't     send too many pings when probes are going slowly. */  int lastping_sent_numprobes;   /* The host to which global pings are sent. This is kept updated to be the     most recent host that was found up. */  HostScanStats *pinghost;  struct timeval last_wait;   int probes_sent_at_last_wait;  // number of hosts that timed out during scan, or were already timedout  int num_hosts_timedout;  ConnectScanInfo *CSI;};struct send_delay_nfo {  unsigned int delayms; /* Milliseconds to delay between probes */  /* The number of successful and dropped probes since the last time delayms     was changed */  unsigned int goodRespSinceDelayChanged;  unsigned int droppedRespSinceDelayChanged;  struct timeval last_boost; /* Most recent time of increase to delayms.  Init to creation time. */};/* To test for rate limiting, there is a delay in sending the first packet   of a certain retransmission number.  These values help track that. */struct rate_limit_detection_nfo {  unsigned int max_tryno_sent; /* What is the max tryno we have sent so far (starts at 0) */  bool rld_waiting; /* Are we currently waiting due to RLD? */  struct timeval rld_waittime; /* if RLD waiting, when can we send? */};/* The ultra_scan() statistics that apply to individual target hosts in a    group */class HostScanStats {public:  Target *target; /* A copy of the Target that these stats refer to. */  HostScanStats(Target *t, UltraScanInfo *UltraSI);  ~HostScanStats();  int freshPortsLeft(); /* Returns the number of ports remaining to probe */  int next_portidx; /* Index of the next port to probe in the relevent		       ports array in USI.ports */  bool sent_arp; /* Has an ARP probe been sent for the target yet? */  /* massping state. */  /* The index of the next ACK port in o.ping_ackprobes to probe during ping     scan. */  int next_ackportpingidx;  /* The index of the next SYN port in o.ping_synprobes to probe during ping     scan. */  int next_synportpingidx;  /* The index of the next UDP port in o.ping_udpprobes to probe during ping     scan. */  int next_udpportpingidx;  /* The index of the next IP protocol in o.ping_protoprobes to probe during ping     scan. */  int next_protoportpingidx;  /* Whether we have sent an ICMP echo request. */  bool sent_icmp_ping;  /* Whether we have sent an ICMP address mask request. */  bool sent_icmp_mask;  /* Whether we have sent an ICMP timestamp request. */  bool sent_icmp_ts;  /* How long I am currently willing to wait for a probe response     before considering it timed out.  Uses the host values from     target if they are available, otherwise from gstats.  Results     returned in MICROseconds.  */  unsigned long probeTimeout();  /* How long I'll wait until completely giving up on a probe.     Timedout probes are often marked as such (and sometimes     considered a drop), but kept in the list juts in case they come     really late.  But after probeExpireTime(), I don't waste time     keeping them around. Give in MICROseconds */  unsigned long probeExpireTime(const UltraProbe *probe);/* Returns OK if sending a new probe to this host is OK (to avoid   flooding). If when is non-NULL, fills it with the time that sending   will be OK assuming no pending probes are resolved by responses   (call it again if they do).  when will become now if it returns   true. */  bool sendOK(struct timeval *when); /* If there are pending probe timeouts, fills in when with the time of   the earliest one and returns true.  Otherwise returns false and   puts now in when. */  bool nextTimeout(struct timeval *when);  UltraScanInfo *USI; /* The USI which contains this HSS */  /* Removes a probe from probes_outstanding, adjusts HSS and USS     active probe stats accordingly, then deletes the probe. */  void destroyOutstandingProbe(list<UltraProbe *>::iterator probeI);  /* Removes all probes from probes_outstanding using     destroyOutstandingProbe. This is used in ping scan to quit waiting     for responses once a host is known to be up. Invalidates iterators     pointing into probes_outstanding. */  void destroyAllOutstandingProbes();  /* Mark an outstanding probe as timedout.  Adjusts stats     accordingly.  For connect scans, this closes the socket. */  void markProbeTimedout(list<UltraProbe *>::iterator probeI);  /* New (active) probes are appended to the end of this list.  When a     host times out, it will be marked as such, but may hang around on     the list for a while just in case a response comes in.  So use     num_probes_active to learn how many active (not timed out) probes     are outstanding.  Probes on the bench (reached the current     maximum tryno and expired) are not counted in     probes_outstanding.  */  list<UltraProbe *> probes_outstanding;  /* The number of probes in probes_outstanding, minus the inactive (timed out) ones */  unsigned int num_probes_active;  /* Probes timed out but not yet retransmitted because of congestion     control limits or because more retransmits may not be     neccessary.  Note that probes on probe_bench are not included     in this value. */  unsigned int num_probes_waiting_retransmit;  unsigned int num_probes_outstanding() { return probes_outstanding.size(); }  /* The bench is a stock of probes (compacted into just the     probespec) that have met the current maximum tryno, and are on     ice until that tryno increases (so we can retransmit again), or     solidifies (so we can mark the port firewalled or whatever).  The     tryno of benh members is bench_tryno.  If the maximum tryno     increases, everyone on the bench is moved to the retry_stack.   */  vector<probespec> probe_bench;  unsigned int bench_tryno; /* # tryno of probes on the bench */  /* The retry_stack are probespecs that were on the bench but are now     slated to be retried.  It is kept sorted such that probes with highest     retry counts are on top, ready to be taken first. */  vector<probespec> retry_stack;  /* retry_stack_tries MUST BE KEPT IN SYNC WITH retry_stack.     retry_stack_tries[i] is the number of completed retries for the     probe in retry_stack[i] */  vector<u8> retry_stack_tries;   /* tryno of probes on the retry queue */  /* Moves the given probe from the probes_outstanding list, to     probe_bench, and decrements num_probes_waiting_retransmit accordingly */  void moveProbeToBench(list<UltraProbe *>::iterator probeI);  /* Dismiss all probe attempts on bench -- the ports are marked     'filtered' or whatever is appropriate for having no response */  void dismissBench();  /* Move all members of bench to retry_stack for probe retransmission */  void retransmitBench();    bool completed(); /* Whether or not the scan of this Target has completed */  /* This function provides the proper cwnd and ccthresh to use.  It     may differ from versions in timing member var because when no     responses have been received for this host, may look at others in     the group.  For CHANGING this host's timing, use the timing     memberval instead. */  void getTiming(struct ultra_timing_vals *tmng);  struct ultra_timing_vals timing;  /* The most recently received probe response time -- initialized to scan start time. */  struct timeval lastrcvd;  struct timeval lastping_sent; /* The time the most recent ping was sent (initialized to scan begin time) *//* Value of numprobes_sent at lastping_sent time -- to ensure that we   don't send too many pings when probes are going slowly. */  int lastping_sent_numprobes;   struct timeval lastprobe_sent; /* Most recent probe send (including pings) by host.  Init to scan begin time. */  /* A valid probe for sending scanpings. */  probespec pingprobe;  int pingprobestate; /* PORT_UNKNOWN if no pingprobe yet found */  /* gives the maximum try number (try numbers start at zero and     increments for each retransmission) that may be used, based on     the scan type, observed network reliability, timing mode, etc.     This may change during the scan based on network traffic.  If     capped is not null, it will be filled with true if the tryno is     at its upper limit.  That often calls for a warning to be issued,     and marking of remaining timedout ports firewalled or whatever is     appropriate.  If mayincrease is non-NULL, it is set to whether     the allowedTryno may increase again.  If it is false, any probes     which have reached the given limit may be dealth with. */  unsigned int allowedTryno(bool *capped, bool *mayincrease);  /* Provides the next ping sequence number.  This starts at one, goes   up to 255, then wraps around back to 1.  If inc is true, it is   incremented.  Otherwise you just get a peek at what the next one   will be. */  u8 nextPingSeq(bool inc=true) {    u8 ret = nxtpseq;    if (inc) {      nxtpseq++;      if (nxtpseq == 0) nxtpseq++;    }    return ret;  }  /* This is the highest try number that has produced useful results     (such as port status change). */  unsigned int max_successful_tryno;  /* This starts as true because tryno may increase based on results, but     it becomes false if it becomes clear that tryno will not increase      further during the scan */  bool tryno_mayincrease;  int ports_finished; /* The number of ports of this host that have been determined */  int numprobes_sent; /* Number of port probes (not counting pings, but counting retransmits) sent to this host */  int numpings_sent;  /* Boost the scan delay for this host, usually because too many packet     drops were detected. */  int numprobes_replied_to; /* The number of probes for which we've received     responses. Used for scaling congestion control increments. */  /* Returns the scaling factor to use when incrementing the congestion window.     This is the minimum of     (numprobes_sent + numpings_sent) / numprobes_replied_to and     cc_scale_max. */  double cc_scale();  void boostScanDelay();  struct send_delay_nfo sdn;  struct rate_limit_detection_nfo rld;private:  u8 nxtpseq; /* the next scanping sequence number to use */};class UltraScanInfo {public:  UltraScanInfo();  UltraScanInfo(vector<Target *> &Targets, struct scan_lists *pts, stype scantype) { Init(Targets, pts, scantype); }  ~UltraScanInfo();  /* Must call Init if you create object with default constructor */  void Init(vector<Target *> &Targets, struct scan_lists *pts, stype scantp);  unsigned int numProbesPerHost();  /* Consults with the group stats, and the hstats for every     incomplete hosts to determine whether any probes may be sent.     Returns true if they can be sent immediately.  If when is non-NULL,     it is filled with the next possible time that probes can be sent     (which will be now, if the function returns true */  bool sendOK(struct timeval *tv);  stype scantype;  bool tcp_scan; /* scantype is a type of TCP scan */  bool udp_scan;  bool prot_scan;  bool ping_scan; /* Includes trad. ping scan & arp scan */  bool ping_scan_arp; /* ONLY includes arp ping scan */  bool noresp_open_scan; /* Whether no response means a port is open */  /* massping state. */  /* If ping_scan is true (unless ping_scan_arp is also true), this is the set     of ping techniques to use (ICMP, raw ICMP, TCP connect, raw TCP, or raw     UDP). */  struct pingtech ptech;  bool isRawScan();  struct timeval now; /* Updated after potentially meaningful delays.  This can			 be used to save a call to gettimeofday() */  GroupScanStats *gstats;  struct ultra_scan_performance_vars perf;  /* A circular buffer of the incompleteHosts.  nextIncompleteHost() gives     the next one.  The first time it is called, it will give the     first host in the list.  If incompleteHosts is empty, returns     NULL. */  HostScanStats *nextIncompleteHost();  /* Removes any hosts that have completed their scans from the incompleteHosts     list.  Returns the number of hosts removed. */  int removeCompletedHosts();  /* Find a HostScanStats by its IP address in the incomplete and completed     lists.  Returns NULL if none are found. */  HostScanStats *findHost(struct sockaddr_storage *ss);  unsigned int numIncompleteHosts() { return incompleteHosts.size(); }  /* Call this instead of checking for numIncompleteHosts() == 0 because it     avoids a potential traversal of the list to find the size. */  bool incompleteHostsEmpty() { return incompleteHosts.empty(); }  bool numIncompleteHostsLessThan(unsigned int n);  unsigned int numInitialHosts() { return numInitialTargets; }  /* Any function which messes with (removes elements from)     incompleteHosts may have to manipulate nextI */  list<HostScanStats *> incompleteHosts;  /* Hosts are moved from incompleteHosts to completedHosts as they are     completed. We keep them around because sometimes responses come back very     late, after we consider a host completed. */  list<HostScanStats *> completedHosts;  ScanProgressMeter *SPM;  struct scan_lists *ports;  int rawsd; /* raw socket descriptor */  pcap_t *pd;  eth_t *ethsd;  u32 seqmask; /* This mask value is used to encode values in sequence 		  numbers.  It is set randomly in UltraScanInfo::Init() */private:  unsigned int numInitialTargets;  list<HostScanStats *>::iterator nextI;};/* Whether this is storing timing stats for a whole group or an   individual host */enum ultra_timing_type { TIMING_HOST, TIMING_GROUP };/* Initialize the ultra_timing_vals structure timing.  The utt must be   TIMING_HOST or TIMING_GROUP.  If you happen to have the current   time handy, pass it as now, otherwise pass NULL */static void init_ultra_timing_vals(ultra_timing_vals *timing, 				   enum ultra_timing_type utt, 				   int num_hosts_in_group, 				   struct ultra_scan_performance_vars *perf,				   struct timeval *now);/* Take a buffer, buf, of size bufsz (32 bytes is sufficient) and    writes a short description of the probe (arg1) into buf.  It also returns    buf. */static char *probespec2ascii(probespec *pspec, char *buf, unsigned int bufsz) {  char flagbuf[32];  char *f;  switch(pspec->type) {  case PS_TCP:    if (!pspec->pd.tcp.flags) Strncpy(flagbuf, "(none)", sizeof(flagbuf));    else {      f = flagbuf;      if (pspec->pd.tcp.flags & TH_SYN) *f++ = 'S';      if (pspec->pd.tcp.flags & TH_FIN) *f++ = 'F';      if (pspec->pd.tcp.flags & TH_RST) *f++ = 'R';      if (pspec->pd.tcp.flags & TH_PUSH) *f++ = 'P';      if (pspec->pd.tcp.flags & TH_ACK) *f++ = 'A';      if (pspec->pd.tcp.flags & TH_URG) *f++ = 'U';      if (pspec->pd.tcp.flags & TH_ECE) *f++ = 'E'; /* rfc 2481/3168 */      if (pspec->pd.tcp.flags & TH_CWR) *f++ = 'C'; /* rfc 2481/3168 */      *f++ = '\0';    }    Snprintf(buf, bufsz, "tcp to port %hu; flags: %s", pspec->pd.tcp.dport, 

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?