1
0
mirror of https://github.com/nmap/nmap.git synced 2025-12-07 13:11:28 +00:00

Remove trailing whitespace from C/C++ files

https://secwiki.org/w/Nmap/Code_Standards
This commit is contained in:
dmiller
2014-02-12 20:25:51 +00:00
parent 2896c21989
commit c9714990c7
41 changed files with 374 additions and 374 deletions

View File

@@ -149,13 +149,13 @@ class FingerPrintResults {
FingerPrintResults(); FingerPrintResults();
virtual ~FingerPrintResults(); virtual ~FingerPrintResults();
double accuracy[MAX_FP_RESULTS]; /* Percentage of match (1.0 == perfect double accuracy[MAX_FP_RESULTS]; /* Percentage of match (1.0 == perfect
match) in same order as matches[] below */ match) in same order as matches[] below */
FingerMatch *matches[MAX_FP_RESULTS]; /* ptrs to matching references -- FingerMatch *matches[MAX_FP_RESULTS]; /* ptrs to matching references --
highest accuracy matches first */ highest accuracy matches first */
int num_perfect_matches; /* Number of 1.0 accuracy matches in matches[] */ int num_perfect_matches; /* Number of 1.0 accuracy matches in matches[] */
int num_matches; /* Total number of matches in matches[] */ int num_matches; /* Total number of matches in matches[] */
int overall_results; /* OSSCAN_TOOMANYMATCHES, OSSCAN_NOMATCHES, int overall_results; /* OSSCAN_TOOMANYMATCHES, OSSCAN_NOMATCHES,
OSSCAN_SUCCESS, etc */ OSSCAN_SUCCESS, etc */
/* Ensures that the results are available and then returns them. /* Ensures that the results are available and then returns them.
@@ -166,11 +166,11 @@ class FingerPrintResults {
returned */ returned */
const struct OS_Classification_Results *getOSClassification(); const struct OS_Classification_Results *getOSClassification();
int osscan_opentcpport; /* Open TCP port used for scannig (if one found -- int osscan_opentcpport; /* Open TCP port used for scannig (if one found --
otherwise -1) */ otherwise -1) */
int osscan_closedtcpport; /* Closed TCP port used for scannig (if one found -- int osscan_closedtcpport; /* Closed TCP port used for scannig (if one found --
otherwise -1) */ otherwise -1) */
int osscan_closedudpport; /* Closed UDP port used for scannig (if one found -- int osscan_closedudpport; /* Closed UDP port used for scannig (if one found --
otherwise -1) */ otherwise -1) */
int distance; /* How "far" is this FP gotten from? */ int distance; /* How "far" is this FP gotten from? */
int distance_guess; /* How "far" is this FP gotten from? by guessing based on ttl. */ int distance_guess; /* How "far" is this FP gotten from? by guessing based on ttl. */

View File

@@ -363,7 +363,7 @@ void NmapOps::Initialize() {
ipoptions = NULL; ipoptions = NULL;
ipoptionslen = 0; ipoptionslen = 0;
ipopt_firsthop = 0; ipopt_firsthop = 0;
ipopt_lasthop = 0; ipopt_lasthop = 0;
release_memory = false; release_memory = false;
topportlevel = -1; topportlevel = -1;
#ifndef NOLUA #ifndef NOLUA
@@ -407,7 +407,7 @@ bool NmapOps::RawScan() {
if ((pingtype & PINGTYPE_TCP_USE_SYN) && isr00t) if ((pingtype & PINGTYPE_TCP_USE_SYN) && isr00t)
return true; return true;
return false; return false;
} }
@@ -485,50 +485,50 @@ dialog where you can start NPF if you have administrator privileges.";
} }
/* We start with stuff users should not do if they are not root */ /* We start with stuff users should not do if they are not root */
if (!isr00t) { if (!isr00t) {
if (ackscan|finscan|idlescan|ipprotscan|maimonscan|nullscan|synscan|udpscan|windowscan|xmasscan|sctpinitscan|sctpcookieechoscan) { if (ackscan|finscan|idlescan|ipprotscan|maimonscan|nullscan|synscan|udpscan|windowscan|xmasscan|sctpinitscan|sctpcookieechoscan) {
fatal("You requested a scan type which requires %s", privreq); fatal("You requested a scan type which requires %s", privreq);
} }
if (numdecoys > 0) { if (numdecoys > 0) {
fatal("Sorry, but decoys (-D) require %s", privreq); fatal("Sorry, but decoys (-D) require %s", privreq);
} }
if (fragscan) { if (fragscan) {
fatal("Sorry, but fragscan requires %s", privreq); fatal("Sorry, but fragscan requires %s", privreq);
} }
if (osscan) { if (osscan) {
fatal("TCP/IP fingerprinting (for OS scan) requires %s", privreq); fatal("TCP/IP fingerprinting (for OS scan) requires %s", privreq);
} }
} }
if (bouncescan && pingtype != PINGTYPE_NONE) if (bouncescan && pingtype != PINGTYPE_NONE)
log_write(LOG_STDOUT, "Hint: if your bounce scan target hosts aren't reachable from here, remember to use -Pn so we don't try and ping them prior to the scan\n"); log_write(LOG_STDOUT, "Hint: if your bounce scan target hosts aren't reachable from here, remember to use -Pn so we don't try and ping them prior to the scan\n");
if (ackscan+bouncescan+connectscan+finscan+idlescan+maimonscan+nullscan+synscan+windowscan+xmasscan > 1) if (ackscan+bouncescan+connectscan+finscan+idlescan+maimonscan+nullscan+synscan+windowscan+xmasscan > 1)
fatal("You specified more than one type of TCP scan. Please choose only one of -sA, -b, -sT, -sF, -sI, -sM, -sN, -sS, -sW, and -sX"); fatal("You specified more than one type of TCP scan. Please choose only one of -sA, -b, -sT, -sF, -sI, -sM, -sN, -sS, -sW, and -sX");
if (numdecoys > 0 && (bouncescan || connectscan)) { if (numdecoys > 0 && (bouncescan || connectscan)) {
error("WARNING: Decoys are irrelevant to the bounce or connect scans"); error("WARNING: Decoys are irrelevant to the bounce or connect scans");
} }
if (fragscan && !(ackscan|finscan|maimonscan|nullscan|synscan|windowscan|xmasscan) && \ if (fragscan && !(ackscan|finscan|maimonscan|nullscan|synscan|windowscan|xmasscan) && \
!(pingtype&(PINGTYPE_ICMP_TS|PINGTYPE_TCP)) && !(fragscan == 8 && pingtype&PINGTYPE_ICMP_MASK) && \ !(pingtype&(PINGTYPE_ICMP_TS|PINGTYPE_TCP)) && !(fragscan == 8 && pingtype&PINGTYPE_ICMP_MASK) && \
!(extra_payload_length + 8 > fragscan)) { !(extra_payload_length + 8 > fragscan)) {
fatal("Fragscan only works with TCP, ICMP Timestamp or ICMP Mask (mtu=8) ping types or ACK, FIN, Maimon, NULL, SYN, Window, and XMAS scan types"); fatal("Fragscan only works with TCP, ICMP Timestamp or ICMP Mask (mtu=8) ping types or ACK, FIN, Maimon, NULL, SYN, Window, and XMAS scan types");
} }
if (osscan && bouncescan) if (osscan && bouncescan)
error("Combining bounce scan with OS scan seems silly, but I will let you do whatever you want!"); error("Combining bounce scan with OS scan seems silly, but I will let you do whatever you want!");
#if !defined(LINUX) && !defined(OPENBSD) && !defined(FREEBSD) && !defined(NETBSD) #if !defined(LINUX) && !defined(OPENBSD) && !defined(FREEBSD) && !defined(NETBSD)
if (fragscan) { if (fragscan) {
error("Warning: Packet fragmentation selected on a host other than Linux, OpenBSD, FreeBSD, or NetBSD. This may or may not work."); error("Warning: Packet fragmentation selected on a host other than Linux, OpenBSD, FreeBSD, or NetBSD. This may or may not work.");
} }
#endif #endif
if (osscan && noportscan) { if (osscan && noportscan) {
fatal("WARNING: OS Scan is unreliable without a port scan. You need to use a scan type along with it, such as -sS, -sT, -sF, etc instead of -sn"); fatal("WARNING: OS Scan is unreliable without a port scan. You need to use a scan type along with it, such as -sS, -sT, -sF, etc instead of -sn");
} }
@@ -549,10 +549,10 @@ dialog where you can start NPF if you have administrator privileges.";
if (defeat_rst_ratelimit && !synscan) { if (defeat_rst_ratelimit && !synscan) {
fatal("Option --defeat-rst-ratelimit works only with a SYN scan (-sS)"); fatal("Option --defeat-rst-ratelimit works only with a SYN scan (-sS)");
} }
if (resume_ip.s_addr && generate_random_ips) if (resume_ip.s_addr && generate_random_ips)
resume_ip.s_addr = 0; resume_ip.s_addr = 0;
if (magic_port_set && connectscan) { if (magic_port_set && connectscan) {
error("WARNING: -g is incompatible with the default connect() scan (-sT). Use a raw scan such as -sS if you want to set the source port."); error("WARNING: -g is incompatible with the default connect() scan (-sT). Use a raw scan such as -sS if you want to set the source port.");
} }
@@ -564,7 +564,7 @@ dialog where you can start NPF if you have administrator privileges.";
if (min_packet_send_rate != 0.0 && max_packet_send_rate != 0.0 && min_packet_send_rate > max_packet_send_rate) { if (min_packet_send_rate != 0.0 && max_packet_send_rate != 0.0 && min_packet_send_rate > max_packet_send_rate) {
fatal("--min-rate=%g must be less than or equal to --max-rate=%g", min_packet_send_rate, max_packet_send_rate); fatal("--min-rate=%g must be less than or equal to --max-rate=%g", min_packet_send_rate, max_packet_send_rate);
} }
if (af() == AF_INET6 && (generate_random_ips|numdecoys|bouncescan|fragscan)) { if (af() == AF_INET6 && (generate_random_ips|numdecoys|bouncescan|fragscan)) {
fatal("Sorry -- IPv6 support is currently only available for TCP, UDP, and SCTP port scans and list scan (-sL). OS detection, random targets and decoys are also not supported with IPv6. Further support is under consideration."); fatal("Sorry -- IPv6 support is currently only available for TCP, UDP, and SCTP port scans and list scan (-sL). OS detection, random targets and decoys are also not supported with IPv6. Further support is under consideration.");
} }
@@ -580,32 +580,32 @@ dialog where you can start NPF if you have administrator privileges.";
} }
void NmapOps::setMaxOSTries(int mot) { void NmapOps::setMaxOSTries(int mot) {
if (mot <= 0) if (mot <= 0)
fatal("%s: value must be at least 1", __func__); fatal("%s: value must be at least 1", __func__);
max_os_tries = mot; max_os_tries = mot;
} }
void NmapOps::setMaxRttTimeout(int rtt) void NmapOps::setMaxRttTimeout(int rtt)
{ {
if (rtt <= 0) fatal("%s: maximum round trip time must be greater than 0", __func__); if (rtt <= 0) fatal("%s: maximum round trip time must be greater than 0", __func__);
max_rtt_timeout = rtt; max_rtt_timeout = rtt;
if (rtt < min_rtt_timeout) min_rtt_timeout = rtt; if (rtt < min_rtt_timeout) min_rtt_timeout = rtt;
if (rtt < initial_rtt_timeout) initial_rtt_timeout = rtt; if (rtt < initial_rtt_timeout) initial_rtt_timeout = rtt;
} }
void NmapOps::setMinRttTimeout(int rtt) void NmapOps::setMinRttTimeout(int rtt)
{ {
if (rtt < 0) fatal("%s: minimum round trip time must be at least 0", __func__); if (rtt < 0) fatal("%s: minimum round trip time must be at least 0", __func__);
min_rtt_timeout = rtt; min_rtt_timeout = rtt;
if (rtt > max_rtt_timeout) max_rtt_timeout = rtt; if (rtt > max_rtt_timeout) max_rtt_timeout = rtt;
if (rtt > initial_rtt_timeout) initial_rtt_timeout = rtt; if (rtt > initial_rtt_timeout) initial_rtt_timeout = rtt;
} }
void NmapOps::setInitialRttTimeout(int rtt) void NmapOps::setInitialRttTimeout(int rtt)
{ {
if (rtt <= 0) fatal("%s: initial round trip time must be greater than 0", __func__); if (rtt <= 0) fatal("%s: initial round trip time must be greater than 0", __func__);
initial_rtt_timeout = rtt; initial_rtt_timeout = rtt;
if (rtt > max_rtt_timeout) max_rtt_timeout = rtt; if (rtt > max_rtt_timeout) max_rtt_timeout = rtt;
if (rtt < min_rtt_timeout) min_rtt_timeout = rtt; if (rtt < min_rtt_timeout) min_rtt_timeout = rtt;
} }

View File

@@ -279,7 +279,7 @@ class NmapOps {
/* Gets the spoofed MAC address, but returns NULL if it hasn't been set */ /* Gets the spoofed MAC address, but returns NULL if it hasn't been set */
const u8 *spoofMACAddress() { return spoof_mac_set? spoof_mac : NULL; } const u8 *spoofMACAddress() { return spoof_mac_set? spoof_mac : NULL; }
int max_ips_to_scan; // Used for Random input (-iR) to specify how int max_ips_to_scan; // Used for Random input (-iR) to specify how
// many IPs to try before stopping. 0 means unlimited. // many IPs to try before stopping. 0 means unlimited.
int extra_payload_length; /* These two are for --data-length op */ int extra_payload_length; /* These two are for --data-length op */
char *extra_payload; char *extra_payload;
@@ -297,10 +297,10 @@ class NmapOps {
slow against it. If we don't distinguish between closed and filtered ports, slow against it. If we don't distinguish between closed and filtered ports,
we can get the list of open ports very fast */ we can get the list of open ports very fast */
struct in_addr resume_ip; /* The last IP in the log file if user struct in_addr resume_ip; /* The last IP in the log file if user
requested --restore . Otherwise requested --restore . Otherwise
restore_ip.s_addr == 0. Also restore_ip.s_addr == 0. Also
target_struct_get will eventually set it target_struct_get will eventually set it
to 0. */ to 0. */
// Version Detection Options // Version Detection Options
@@ -413,7 +413,7 @@ class NmapOps {
unsigned int min_host_group_sz; unsigned int min_host_group_sz;
unsigned int max_host_group_sz; unsigned int max_host_group_sz;
void Initialize(); void Initialize();
int addressfamily; /* Address family: AF_INET or AF_INET6 */ int addressfamily; /* Address family: AF_INET or AF_INET6 */
struct sockaddr_storage sourcesock; struct sockaddr_storage sourcesock;
size_t sourcesocklen; size_t sourcesocklen;
struct timeval start_time; struct timeval start_time;
@@ -424,4 +424,4 @@ class NmapOps {
u8 spoof_mac[6]; u8 spoof_mac[6];
bool spoof_mac_set; bool spoof_mac_set;
}; };

View File

@@ -169,7 +169,7 @@ void NmapOutputTable::addItem(unsigned int row, unsigned int column, bool fullro
bool copy, const char *item, int itemlen) { bool copy, const char *item, int itemlen) {
struct NmapOutputTableCell *cell; struct NmapOutputTableCell *cell;
int mc = maxColLen[column]; int mc = maxColLen[column];
addItem(row, column, copy, item, itemlen); addItem(row, column, copy, item, itemlen);
if(fullrow) { if(fullrow) {
@@ -180,7 +180,7 @@ void NmapOutputTable::addItem(unsigned int row, unsigned int column, bool fullro
return; return;
} }
void NmapOutputTable::addItem(unsigned int row, unsigned int column, bool copy, const char *item, void NmapOutputTable::addItem(unsigned int row, unsigned int column, bool copy, const char *item,
int itemlen) { int itemlen) {
struct NmapOutputTableCell *cell; struct NmapOutputTableCell *cell;
@@ -214,14 +214,14 @@ void NmapOutputTable::addItem(unsigned int row, unsigned int column, bool copy,
return; return;
} }
void NmapOutputTable::addItemFormatted(unsigned int row, void NmapOutputTable::addItemFormatted(unsigned int row,
unsigned int column, unsigned int column,
bool fullrow, bool fullrow,
const char *fmt, ...) { const char *fmt, ...) {
struct NmapOutputTableCell *cell; struct NmapOutputTableCell *cell;
int mc = maxColLen[column]; int mc = maxColLen[column];
unsigned int res; unsigned int res;
va_list ap; va_list ap;
va_start(ap,fmt); va_start(ap,fmt);
char buf[4096]; char buf[4096];
res = Vsnprintf(buf, sizeof(buf), fmt, ap); res = Vsnprintf(buf, sizeof(buf), fmt, ap);
@@ -244,7 +244,7 @@ bool NmapOutputTable::emptyRow(unsigned int nrow) {
NmapOutputTableCell *cell; NmapOutputTableCell *cell;
unsigned int col; unsigned int col;
bool isEmpty = true; bool isEmpty = true;
assert(nrow < numRows); assert(nrow < numRows);
for(col = 0 ; col < numColumns; col++) { for(col = 0 ; col < numColumns; col++) {
@@ -254,14 +254,14 @@ bool NmapOutputTable::emptyRow(unsigned int nrow) {
break; break;
} }
} }
return isEmpty; return isEmpty;
} }
// This function sticks the entire table into a character buffer. // This function sticks the entire table into a character buffer.
// Note that the buffer is likely to be reused if you call the // Note that the buffer is likely to be reused if you call the
// function again, and it will also be invalidated if you free the // function again, and it will also be invalidated if you free the
// table. If size is not NULL, it will be filled with the size of // table. If size is not NULL, it will be filled with the size of
// the ASCII table in bytes (not including the terminating NUL) // the ASCII table in bytes (not including the terminating NUL)
// All blank rows are removed from the returned string // All blank rows are removed from the returned string
char *NmapOutputTable::printableTable(int *size) { char *NmapOutputTable::printableTable(int *size) {
unsigned int col, row; unsigned int col, row;
@@ -279,7 +279,7 @@ char *NmapOutputTable::printableTable(int *size) {
for(row = 0; row < numRows; row++) { for(row = 0; row < numRows; row++) {
validthisrow = 0; validthisrow = 0;
if(emptyRow(row)) if(emptyRow(row))
continue; continue;
cell = getCellAddy(row, 0); cell = getCellAddy(row, 0);

View File

@@ -180,11 +180,11 @@ class NmapOutputTable {
assert(row < numRows); assert(col < numColumns); assert(row < numRows); assert(col < numColumns);
return table + row * numColumns + col; return table + row * numColumns + col;
} }
int *maxColLen; // An array that gives the maximum length of any member of each column int *maxColLen; // An array that gives the maximum length of any member of each column
// (excluding terminator) // (excluding terminator)
// Array that tells the number of valid (> 0 length) items in each row // Array that tells the number of valid (> 0 length) items in each row
int *itemsInRow; int *itemsInRow;
unsigned int numRows; unsigned int numRows;
unsigned int numColumns; unsigned int numColumns;
char *tableout; // If printableTable() is called, we return this char *tableout; // If printableTable() is called, we return this
int tableoutsz; // Amount of space ALLOCATED for tableout. Includes space allocated for NUL. int tableoutsz; // Amount of space ALLOCATED for tableout. Includes space allocated for NUL.

View File

@@ -183,7 +183,7 @@ const char * Target::deviceName() const {
} }
const char * Target::deviceFullName() const { const char * Target::deviceFullName() const {
return (devfullname[0] != '\0')? devfullname : NULL; return (devfullname[0] != '\0')? devfullname : NULL;
} }
void Target::Recycle() { void Target::Recycle() {
@@ -225,10 +225,10 @@ void Target::GenerateTargetIPString() {
struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) &targetsock; struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) &targetsock;
#endif #endif
if (inet_ntop(sin->sin_family, (sin->sin_family == AF_INET)? if (inet_ntop(sin->sin_family, (sin->sin_family == AF_INET)?
(char *) &sin->sin_addr : (char *) &sin->sin_addr :
#if HAVE_IPV6 #if HAVE_IPV6
(char *) &sin6->sin6_addr, (char *) &sin6->sin6_addr,
#else #else
(char *) NULL, (char *) NULL,
#endif #endif
@@ -269,7 +269,7 @@ int Target::af() const {
to the size of the sockaddr copied in. */ to the size of the sockaddr copied in. */
int Target::TargetSockAddr(struct sockaddr_storage *ss, size_t *ss_len) const { int Target::TargetSockAddr(struct sockaddr_storage *ss, size_t *ss_len) const {
assert(ss); assert(ss);
assert(ss_len); assert(ss_len);
if (targetsocklen <= 0) if (targetsocklen <= 0)
return 1; return 1;
assert(targetsocklen <= sizeof(*ss)); assert(targetsocklen <= sizeof(*ss));
@@ -378,7 +378,7 @@ const struct in6_addr *Target::v6sourceip() const {
return NULL; return NULL;
} }
/* You can set to NULL to erase a name or if it failed to resolve -- or /* You can set to NULL to erase a name or if it failed to resolve -- or
just don't call this if it fails to resolve */ just don't call this if it fails to resolve */
void Target::setHostName(const char *name) { void Target::setHostName(const char *name) {
char *p; char *p;

View File

@@ -226,7 +226,7 @@ class Target {
or v6). If the name has not been set, or was set to NULL, an empty or v6). If the name has not been set, or was set to NULL, an empty
string ("") is returned to make printing easier. */ string ("") is returned to make printing easier. */
const char *HostName() const { return hostname? hostname : ""; } const char *HostName() const { return hostname? hostname : ""; }
/* You can set to NULL to erase a name or if it failed to resolve -- or /* You can set to NULL to erase a name or if it failed to resolve -- or
just don't call this if it fails to resolve. The hostname is blown just don't call this if it fails to resolve. The hostname is blown
away when you setTargetSockAddr(), so make sure you do these in proper away when you setTargetSockAddr(), so make sure you do these in proper
order order
@@ -241,7 +241,7 @@ class Target {
/* This next version returns a STATIC buffer -- so no concurrency */ /* This next version returns a STATIC buffer -- so no concurrency */
const char *NameIP() const; const char *NameIP() const;
/* Give the name from the last setTargetName() call, which is the /* Give the name from the last setTargetName() call, which is the
name of the target given on the command line if it's a named name of the target given on the command line if it's a named
host. */ host. */
const char *TargetName() { return targetname; } const char *TargetName() { return targetname; }
@@ -270,7 +270,7 @@ class Target {
void setMTU(int devmtu); void setMTU(int devmtu);
int MTU(void); int MTU(void);
/* Sets the interface type to one of: /* Sets the interface type to one of:
devt_ethernet, devt_loopback, devt_p2p, devt_other devt_ethernet, devt_loopback, devt_p2p, devt_other
*/ */
void setIfType(devtype iftype) { interface_type = iftype; } void setIfType(devtype iftype) { interface_type = iftype; }
@@ -361,7 +361,7 @@ class Target {
char targetipstring[INET6_ADDRSTRLEN]; char targetipstring[INET6_ADDRSTRLEN];
char sourceipstring[INET6_ADDRSTRLEN]; char sourceipstring[INET6_ADDRSTRLEN];
mutable char *nameIPBuf; /* for the NameIP(void) function to return */ mutable char *nameIPBuf; /* for the NameIP(void) function to return */
u8 MACaddress[6], SrcMACaddress[6], NextHopMACaddress[6]; u8 MACaddress[6], SrcMACaddress[6], NextHopMACaddress[6];
bool MACaddress_set, SrcMACaddress_set, NextHopMACaddress_set; bool MACaddress_set, SrcMACaddress_set, NextHopMACaddress_set;
struct host_timeout_nfo htn; struct host_timeout_nfo htn;
devtype interface_type; devtype interface_type;
@@ -369,9 +369,9 @@ class Target {
char devfullname[32]; char devfullname[32];
int mtu; int mtu;
/* 0 (OS_NOTPERF) if os detection not performed /* 0 (OS_NOTPERF) if os detection not performed
* 1 (OS_PERF) if os detection performed * 1 (OS_PERF) if os detection performed
* 2 (OS_PERF_UNREL) if an unreliable os detection has been performed */ * 2 (OS_PERF_UNREL) if an unreliable os detection has been performed */
int osscan_flag; int osscan_flag;
}; };
#endif /* TARGET_H */ #endif /* TARGET_H */

View File

@@ -138,7 +138,7 @@ struct portinfo {
unsigned long portno; /* TCP/UDP/SCTP port or RPC program id or IP protocool */ unsigned long portno; /* TCP/UDP/SCTP port or RPC program id or IP protocool */
short trynum; short trynum;
int sd[3]; /* Socket descriptors for connect_scan */ int sd[3]; /* Socket descriptors for connect_scan */
struct timeval sent[3]; struct timeval sent[3];
int state; int state;
int next; /* not struct portinfo * for historical reasons */ int next; /* not struct portinfo * for historical reasons */
int prev; int prev;
@@ -166,15 +166,15 @@ struct udpprobeinfo {
many ports we can try at once */ many ports we can try at once */
struct scanstats { struct scanstats {
int packet_incr; int packet_incr;
int initial_packet_width; /* Number of queries in parallel we should int initial_packet_width; /* Number of queries in parallel we should
start with */ start with */
double fallback_percent; double fallback_percent;
int numqueries_outstanding; /* How many unexpired queries are on the 'net int numqueries_outstanding; /* How many unexpired queries are on the 'net
right now? */ right now? */
double numqueries_ideal; /* How many do we WANT to be on the 'net right now? */ double numqueries_ideal; /* How many do we WANT to be on the 'net right now? */
int max_width; /* What is the MOST we will tolerate at once. Can be int max_width; /* What is the MOST we will tolerate at once. Can be
modified via --max_parallelism */ modified via --max_parallelism */
int min_width; /* We must always allow at least this many at once. Can int min_width; /* We must always allow at least this many at once. Can
be modified via --min_parallelism*/ be modified via --min_parallelism*/
int ports_left; int ports_left;
int changed; /* Has anything changed since last round? */ int changed; /* Has anything changed since last round? */
@@ -272,7 +272,7 @@ struct scan_performance_vars {
outstanding */ outstanding */
int slow_incr; /* How many probes are incremented for each response int slow_incr; /* How many probes are incremented for each response
in slow start mode */ in slow start mode */
int ca_incr; /* How many probes are incremented per (roughly) rtt in int ca_incr; /* How many probes are incremented per (roughly) rtt in
congestion avoidance mode */ congestion avoidance mode */
int cc_scale_max; /* The maximum scaling factor for congestion window int cc_scale_max; /* The maximum scaling factor for congestion window
increments. */ increments. */

View File

@@ -194,7 +194,7 @@ struct idle_proxy_info {
}; };
/* Finds the IPv6 extension header for fragmentation in an IPv6 packet, and returns /* Finds the IPv6 extension header for fragmentation in an IPv6 packet, and returns
* the identification value of the fragmentation header * the identification value of the fragmentation header
*/ */
int ipv6_get_fragment_id(const struct ip6_hdr *ip6, unsigned int len) { int ipv6_get_fragment_id(const struct ip6_hdr *ip6, unsigned int len) {
const unsigned char *p, *end; const unsigned char *p, *end;
@@ -209,15 +209,15 @@ int ipv6_get_fragment_id(const struct ip6_hdr *ip6, unsigned int len) {
hdr = ip6->ip6_nxt; hdr = ip6->ip6_nxt;
p += sizeof(*ip6); p += sizeof(*ip6);
/* If the first extension header is not the fragmentation, we search our way /* If the first extension header is not the fragmentation, we search our way
* through the extension headers until we find the fragmentation header */ * through the extension headers until we find the fragmentation header */
while (p < end && hdr != IP_PROTO_FRAGMENT) { while (p < end && hdr != IP_PROTO_FRAGMENT) {
if (p + 2 > end) if (p + 2 > end)
return -1; return -1;
hdr = *p; hdr = *p;
p += (*(p + 1) + 1) * 8; p += (*(p + 1) + 1) * 8;
} }
if ( hdr != IP_PROTO_FRAGMENT || (p + 2 + sizeof(ip6_ext_data_fragment)) > end) if ( hdr != IP_PROTO_FRAGMENT || (p + 2 + sizeof(ip6_ext_data_fragment)) > end)
return -1; return -1;
@@ -274,7 +274,7 @@ static int ipid_proxy_probe(struct idle_proxy_info *proxy, int *probes_sent,
gettimeofday(&tv_sent[tries], NULL); gettimeofday(&tv_sent[tries], NULL);
/* Time to send the pr0be!*/ /* Time to send the pr0be!*/
if (o.af() == AF_INET) if (o.af() == AF_INET)
send_tcp_raw(proxy->rawsd, proxy->ethptr, send_tcp_raw(proxy->rawsd, proxy->ethptr,
proxy->host.v4sourceip(), proxy->host.v4hostip(), proxy->host.v4sourceip(), proxy->host.v4hostip(),
o.ttl, false, o.ttl, false,
@@ -285,12 +285,12 @@ static int ipid_proxy_probe(struct idle_proxy_info *proxy, int *probes_sent,
NULL, 0); NULL, 0);
else { else {
ipv6_packet = build_tcp_raw_ipv6(proxy->host.v6sourceip(), proxy->host.v6hostip(), ipv6_packet = build_tcp_raw_ipv6(proxy->host.v6sourceip(), proxy->host.v6hostip(),
0x00, 0x0000, 0x00, 0x0000,
o.ttl, o.ttl,
base_port + tries, proxy->probe_port, base_port + tries, proxy->probe_port,
seq_base + (packet_send_count++ * 500) + 1, ack, 0, TH_SYN | TH_ACK, 0, 0, seq_base + (packet_send_count++ * 500) + 1, ack, 0, TH_SYN | TH_ACK, 0, 0,
(u8 *) "\x02\x04\x05\xb4", 4, (u8 *) "\x02\x04\x05\xb4", 4,
NULL, 0, NULL, 0,
&packetlen); &packetlen);
proxy->host.TargetSockAddr(&ss, &sslen); proxy->host.TargetSockAddr(&ss, &sslen);
res = send_ip_packet(proxy->rawsd, proxy->ethptr, &ss, ipv6_packet, packetlen); res = send_ip_packet(proxy->rawsd, proxy->ethptr, &ss, ipv6_packet, packetlen);
@@ -322,12 +322,12 @@ static int ipid_proxy_probe(struct idle_proxy_info *proxy, int *probes_sent,
error("IPv6 packet with a version field != 6 received"); error("IPv6 packet with a version field != 6 received");
} else { } else {
ip6 = (struct ip6_hdr *) ip; ip6 = (struct ip6_hdr *) ip;
ipv6_data = ipv6_get_data(ip6, &packetlen, &hdr); ipv6_data = ipv6_get_data(ip6, &packetlen, &hdr);
if (hdr == IPPROTO_TCP && ipv6_data != NULL) { if (hdr == IPPROTO_TCP && ipv6_data != NULL) {
tcp = (struct tcp_hdr *) ipv6_data; tcp = (struct tcp_hdr *) ipv6_data;
} }
} }
} }
if (tcp) { if (tcp) {
if (ntohs(tcp->th_dport) < base_port || ntohs(tcp->th_dport) - base_port >= tries || ntohs(tcp->th_sport) != proxy->probe_port || ((tcp->th_flags & TH_RST) == 0)) { if (ntohs(tcp->th_dport) < base_port || ntohs(tcp->th_dport) - base_port >= tries || ntohs(tcp->th_sport) != proxy->probe_port || ((tcp->th_flags & TH_RST) == 0)) {
if (ntohs(tcp->th_dport) > o.magic_port && ntohs(tcp->th_dport) < (o.magic_port + 260)) { if (ntohs(tcp->th_dport) > o.magic_port && ntohs(tcp->th_dport) < (o.magic_port + 260)) {
@@ -354,7 +354,7 @@ static int ipid_proxy_probe(struct idle_proxy_info *proxy, int *probes_sent,
if (o.af() == AF_INET) if (o.af() == AF_INET)
ipid = ntohs(ip->ip_id); ipid = ntohs(ip->ip_id);
else if (o.af() == AF_INET6) else if (o.af() == AF_INET6)
ipid = ipv6_get_fragment_id(ip6, bytes); ipid = ipv6_get_fragment_id(ip6, bytes);
adjust_timeouts2(&(tv_sent[trynum]), &rcvdtime, &(proxy->host.to)); adjust_timeouts2(&(tv_sent[trynum]), &rcvdtime, &(proxy->host.to));
} }
@@ -409,14 +409,14 @@ static void initialize_proxy_struct(struct idle_proxy_info *proxy) {
} }
/* Forces the permanent use of the IPv6 extension header for fragmentation in each IPv6 packet sent from /* Forces the permanent use of the IPv6 extension header for fragmentation in each IPv6 packet sent from
* the idle host to the target or the attacker * the idle host to the target or the attacker
* This is achieved by first sending a ping, and afterwards an ICMPv6 Packet Too Big message * This is achieved by first sending a ping, and afterwards an ICMPv6 Packet Too Big message
* which states that the response from the ping was too big, our MTU is smaller than the IPv6 minimum MTU */ * which states that the response from the ping was too big, our MTU is smaller than the IPv6 minimum MTU */
static void ipv6_force_fragmentation(struct idle_proxy_info *proxy, Target *target) { static void ipv6_force_fragmentation(struct idle_proxy_info *proxy, Target *target) {
int hardtimeout = 9000000; /* Generally don't wait more than 9 secs total */ int hardtimeout = 9000000; /* Generally don't wait more than 9 secs total */
char filter[512]; /* Libpcap filter string */ char filter[512]; /* Libpcap filter string */
struct ip *ip; struct ip *ip;
/* The maximum data size we can create without fragmenting, considering that the headers also need place */ /* The maximum data size we can create without fragmenting, considering that the headers also need place */
char data[IP6_MTU_MIN - IPv6_HEADER_LEN - ETH_HDR_LEN - ICMPv6_MIN_HEADER_LEN]; char data[IP6_MTU_MIN - IPv6_HEADER_LEN - ETH_HDR_LEN - ICMPv6_MIN_HEADER_LEN];
unsigned int datalen, bytes; unsigned int datalen, bytes;
const unsigned int proxy_reply_timeout = 2000; const unsigned int proxy_reply_timeout = 2000;
@@ -439,7 +439,7 @@ static void ipv6_force_fragmentation(struct idle_proxy_info *proxy, Target *targ
memset(data,'A', sizeof(data)); memset(data,'A', sizeof(data));
pingid = get_random_u16(); pingid = get_random_u16();
seq = get_random_u16(); seq = get_random_u16();
/* pcap, to get the answer. Max size here is the IPv6 minimum MTU */ /* pcap, to get the answer. Max size here is the IPv6 minimum MTU */
if ((proxy->pd = my_pcap_open_live(proxy->host.deviceName(), IP6_MTU_MIN, (o.spoofsource) ? 1 : 0, 50)) == NULL) if ((proxy->pd = my_pcap_open_live(proxy->host.deviceName(), IP6_MTU_MIN, (o.spoofsource) ? 1 : 0, 50)) == NULL)
fatal("%s", PCAP_OPEN_ERRMSG); fatal("%s", PCAP_OPEN_ERRMSG);
@@ -456,7 +456,7 @@ static void ipv6_force_fragmentation(struct idle_proxy_info *proxy, Target *targ
fatal("Error occured while trying to send ICMPv6 Echo Request to the idle host"); fatal("Error occured while trying to send ICMPv6 Echo Request to the idle host");
free(ipv6_packet); free(ipv6_packet);
gettimeofday(&ipv6_packet_send_time, NULL); gettimeofday(&ipv6_packet_send_time, NULL);
/* Now let's wait for the answer */ /* Now let's wait for the answer */
while (!response_received) { while (!response_received) {
gettimeofday(&tmptv, NULL); gettimeofday(&tmptv, NULL);
@@ -484,7 +484,7 @@ static void ipv6_force_fragmentation(struct idle_proxy_info *proxy, Target *targ
if (proxy->pd) if (proxy->pd)
pcap_close(proxy->pd); pcap_close(proxy->pd);
/* Now we can tell the idle host that its reply was too big, we want it smaller than the IPV6 minimum MTU */ /* Now we can tell the idle host that its reply was too big, we want it smaller than the IPV6 minimum MTU */
/* the data contains first the MTU we want, and then the received IPv6 package */ /* the data contains first the MTU we want, and then the received IPv6 package */
*(uint32_t *)&data = ntohl(IP6_MTU_MIN - 2); *(uint32_t *)&data = ntohl(IP6_MTU_MIN - 2);
@@ -496,7 +496,7 @@ static void ipv6_force_fragmentation(struct idle_proxy_info *proxy, Target *targ
fatal("Error occured while trying to send spoofed ICMPv6 Echo Request to the idle host"); fatal("Error occured while trying to send spoofed ICMPv6 Echo Request to the idle host");
free(ipv6_packet); free(ipv6_packet);
/* Now we do the same in the name of the target */ /* Now we do the same in the name of the target */
/* No pcap this time, we won't receive the answer */ /* No pcap this time, we won't receive the answer */
memset(data,'A', sizeof(data)); memset(data,'A', sizeof(data));
@@ -509,20 +509,20 @@ static void ipv6_force_fragmentation(struct idle_proxy_info *proxy, Target *targ
fatal("Error occured while trying to send ICMPv6 Echo Request to the idle host"); fatal("Error occured while trying to send ICMPv6 Echo Request to the idle host");
free(ipv6_packet); free(ipv6_packet);
/* Now we guess what answer the decoy host sent to the target, so that we can piggyback this on the ICMPV6 Packet too Big message */ /* Now we guess what answer the decoy host sent to the target, so that we can piggyback this on the ICMPV6 Packet too Big message */
ipv6_packet = build_icmpv6_raw(proxy->host.v6hostip(), target->v6hostip(), 0x00, 0x0000, o.ttl, seq , pingid, ICMPV6_ECHOREPLY, 0x00, data, sizeof(data) , &packetlen); ipv6_packet = build_icmpv6_raw(proxy->host.v6hostip(), target->v6hostip(), 0x00, 0x0000, o.ttl, seq , pingid, ICMPV6_ECHOREPLY, 0x00, data, sizeof(data) , &packetlen);
*(uint32_t *)&data = ntohl(IP6_MTU_MIN - 2); *(uint32_t *)&data = ntohl(IP6_MTU_MIN - 2);
memcpy(&data[4], ipv6_packet, sizeof(data)-4); memcpy(&data[4], ipv6_packet, sizeof(data)-4);
free(ipv6_packet); free(ipv6_packet);
ipv6_packet = build_icmpv6_raw(target->v6hostip(), proxy->host.v6hostip(), 0x00, 0x0000, o.ttl, 0x00 , 0x00, 0x02, 0x00, data, sizeof(data) , &packetlen); ipv6_packet = build_icmpv6_raw(target->v6hostip(), proxy->host.v6hostip(), 0x00, 0x0000, o.ttl, 0x00 , 0x00, 0x02, 0x00, data, sizeof(data) , &packetlen);
/* give the decoy host time to reply to the target */ /* give the decoy host time to reply to the target */
usleep(10000); usleep(10000);
res = send_ip_packet(proxy->rawsd, proxy->ethptr, &ss, ipv6_packet, packetlen); res = send_ip_packet(proxy->rawsd, proxy->ethptr, &ss, ipv6_packet, packetlen);
if (res == -1) if (res == -1)
fatal("Error occured while trying to send ICMPv6 PTB to the idle host"); fatal("Error occured while trying to send ICMPv6 PTB to the idle host");
free(ipv6_packet); free(ipv6_packet);
} }
/* takes a proxy name/IP, resolves it if necessary, tests it for IP ID /* takes a proxy name/IP, resolves it if necessary, tests it for IP ID
@@ -561,7 +561,7 @@ static void initialize_idleproxy(struct idle_proxy_info *proxy, char *proxyName,
const struct ip6_hdr *ip6; const struct ip6_hdr *ip6;
u8 ip6hdr; u8 ip6hdr;
const void *ip6data; const void *ip6data;
bool retried_forcing_fragmentation = false; bool retried_forcing_fragmentation = false;
assert(proxy); assert(proxy);
assert(proxyName); assert(proxyName);
int res; int res;
@@ -578,8 +578,8 @@ static void initialize_idleproxy(struct idle_proxy_info *proxy, char *proxyName,
proxy->max_groupsz = MAX(proxy->min_groupsz, o.max_parallelism ? o.max_parallelism : 100); proxy->max_groupsz = MAX(proxy->min_groupsz, o.max_parallelism ? o.max_parallelism : 100);
proxy->max_senddelay = 100000; proxy->max_senddelay = 100000;
/* If we have an IPv6 address, we specify the port with [address]:port */ /* If we have an IPv6 address, we specify the port with [address]:port */
if (o.af() == AF_INET) if (o.af() == AF_INET)
q = strchr(proxyName, ':'); q = strchr(proxyName, ':');
else if (o.af() == AF_INET6) { else if (o.af() == AF_INET6) {
@@ -595,7 +595,7 @@ static void initialize_idleproxy(struct idle_proxy_info *proxy, char *proxyName,
strncpy(name, proxyName , MIN(strcspn(proxyName,":") , sizeof(name))); strncpy(name, proxyName , MIN(strcspn(proxyName,":") , sizeof(name)));
else if (o.af() == AF_INET6 && strchr(proxyName, '[') != NULL && strchr(proxyName, ']') != NULL) else if (o.af() == AF_INET6 && strchr(proxyName, '[') != NULL && strchr(proxyName, ']') != NULL)
strncpy(name, strchr(proxyName, '[') + 1, MIN(strcspn(proxyName,"]") - strcspn(proxyName, "[") - 1, sizeof(name))); strncpy(name, strchr(proxyName, '[') + 1, MIN(strcspn(proxyName,"]") - strcspn(proxyName, "[") - 1, sizeof(name)));
else else
strncpy(name, proxyName, sizeof(name)); strncpy(name, proxyName, sizeof(name));
if (q) { if (q) {
@@ -676,10 +676,10 @@ static void initialize_idleproxy(struct idle_proxy_info *proxy, char *proxyName,
} }
if (proxy->host.af() == AF_INET6) if (proxy->host.af() == AF_INET6)
ipv6_force_fragmentation(proxy, target); ipv6_force_fragmentation(proxy, target);
/* Now for the pcap opening nonsense ... /* Now for the pcap opening nonsense ...
Snaplen will be the IPv6 minimum MTU of 1280, because an IPv6 packet Snaplen will be the IPv6 minimum MTU of 1280, because an IPv6 packet
may have any number of extension header up to the minimal IPv6 MTU */ may have any number of extension header up to the minimal IPv6 MTU */
if ((proxy->pd = my_pcap_open_live(proxy->host.deviceName(), IP6_MTU_MIN, (o.spoofsource) ? 1 : 0, 50)) == NULL) if ((proxy->pd = my_pcap_open_live(proxy->host.deviceName(), IP6_MTU_MIN, (o.spoofsource) ? 1 : 0, 50)) == NULL)
fatal("%s", PCAP_OPEN_ERRMSG); fatal("%s", PCAP_OPEN_ERRMSG);
@@ -712,7 +712,7 @@ static void initialize_idleproxy(struct idle_proxy_info *proxy, char *proxyName,
a response with the exact request for timing purposes. So I a response with the exact request for timing purposes. So I
think I'll use TH_SYN, although it is a tough call. */ think I'll use TH_SYN, although it is a tough call. */
/* We can't use decoys 'cause that would screw up the IP IDs */ /* We can't use decoys 'cause that would screw up the IP IDs */
if (o.af() == AF_INET) if (o.af() == AF_INET)
send_tcp_raw(proxy->rawsd, proxy->ethptr, send_tcp_raw(proxy->rawsd, proxy->ethptr,
proxy->host.v4sourceip(), proxy->host.v4hostip(), proxy->host.v4sourceip(), proxy->host.v4hostip(),
o.ttl, false, o.ttl, false,
@@ -722,13 +722,13 @@ static void initialize_idleproxy(struct idle_proxy_info *proxy, char *proxyName,
(u8 *) "\x02\x04\x05\xb4", 4, (u8 *) "\x02\x04\x05\xb4", 4,
NULL, 0); NULL, 0);
else if (o.af() == AF_INET6) { else if (o.af() == AF_INET6) {
ipv6_packet = build_tcp_raw_ipv6(proxy->host.v6sourceip(), proxy->host.v6hostip(), ipv6_packet = build_tcp_raw_ipv6(proxy->host.v6sourceip(), proxy->host.v6hostip(),
0x00, 0x0000, 0x00, 0x0000,
o.ttl, o.ttl,
o.magic_port + probes_sent + 1, proxy->probe_port, o.magic_port + probes_sent + 1, proxy->probe_port,
sequence_base + probes_sent + 1, ack, 0, TH_SYN | TH_ACK, 0, 0, sequence_base + probes_sent + 1, ack, 0, TH_SYN | TH_ACK, 0, 0,
(u8 *) "\x02\x04\x05\xb4", 4, (u8 *) "\x02\x04\x05\xb4", 4,
NULL, 0, NULL, 0,
&packetlen); &packetlen);
res = send_ip_packet(proxy->rawsd, proxy->ethptr, &ss, ipv6_packet, packetlen); res = send_ip_packet(proxy->rawsd, proxy->ethptr, &ss, ipv6_packet, packetlen);
if (res == -1) if (res == -1)
@@ -802,7 +802,7 @@ static void initialize_idleproxy(struct idle_proxy_info *proxy, char *proxyName,
ip6 = (struct ip6_hdr *) ip; ip6 = (struct ip6_hdr *) ip;
newipid = ipv6_get_fragment_id(ip6, bytes); newipid = ipv6_get_fragment_id(ip6, bytes);
if (newipid < 0 ) { if (newipid < 0 ) {
/* ok, the idle host does not seem to append the extension header for fragmentation. Let's try this once more, /* ok, the idle host does not seem to append the extension header for fragmentation. Let's try this once more,
* maybe the idle host just adjusted its Path MTU. If we keep on having the problem, we quit */ * maybe the idle host just adjusted its Path MTU. If we keep on having the problem, we quit */
if (!retried_forcing_fragmentation) { if (!retried_forcing_fragmentation) {
ipv6_force_fragmentation(proxy, target); ipv6_force_fragmentation(proxy, target);
@@ -824,7 +824,7 @@ static void initialize_idleproxy(struct idle_proxy_info *proxy, char *proxyName,
continue; continue;
} }
}else }else
{ {
error("Malformed packet received"); error("Malformed packet received");
continue; continue;
} }
@@ -866,7 +866,7 @@ static void initialize_idleproxy(struct idle_proxy_info *proxy, char *proxyName,
if (o.af() == AF_INET) if (o.af() == AF_INET)
proxy->seqclass = get_ipid_sequence_16(probes_returned, ipids, 0); proxy->seqclass = get_ipid_sequence_16(probes_returned, ipids, 0);
else else
proxy->seqclass = get_ipid_sequence_32(probes_returned, ipids, 0); proxy->seqclass = get_ipid_sequence_32(probes_returned, ipids, 0);
switch (proxy->seqclass) { switch (proxy->seqclass) {
case IPID_SEQ_INCR: case IPID_SEQ_INCR:
@@ -917,18 +917,18 @@ static void initialize_idleproxy(struct idle_proxy_info *proxy, char *proxyName,
4, NULL, 0); 4, NULL, 0);
} else { } else {
ipv6_packet = build_tcp_raw_ipv6(target->v6hostip(), proxy->host.v6hostip(), ipv6_packet = build_tcp_raw_ipv6(target->v6hostip(), proxy->host.v6hostip(),
0x00, 0x0000, 0x00, 0x0000,
o.ttl, o.ttl,
o.magic_port, proxy->probe_port, o.magic_port, proxy->probe_port,
sequence_base + probes_sent + 1, ack, 0, TH_SYN | TH_ACK, 0, 0, sequence_base + probes_sent + 1, ack, 0, TH_SYN | TH_ACK, 0, 0,
(u8 *) "\x02\x04\x05\xb4", (u8 *) "\x02\x04\x05\xb4",
4, NULL, 0, 4, NULL, 0,
&packetlen); &packetlen);
res = send_ip_packet(proxy->rawsd, proxy->ethptr, &ss, ipv6_packet, packetlen); res = send_ip_packet(proxy->rawsd, proxy->ethptr, &ss, ipv6_packet, packetlen);
if (res == -1) if (res == -1)
fatal("Error occured while trying to send IPv6 packet "); fatal("Error occured while trying to send IPv6 packet ");
free(ipv6_packet); free(ipv6_packet);
} }
} }
/* Sleep a little while to give packets time to reach their destination */ /* Sleep a little while to give packets time to reach their destination */
@@ -1091,11 +1091,11 @@ static int idlescan_countopen2(struct idle_proxy_info *proxy,
o.extra_payload, o.extra_payload_length); o.extra_payload, o.extra_payload_length);
} else { } else {
packet = build_tcp_raw_ipv6(proxy->host.v6hostip(), target->v6hostip(), packet = build_tcp_raw_ipv6(proxy->host.v6hostip(), target->v6hostip(),
0x00, 0x0000, 0x00, 0x0000,
o.ttl, o.ttl,
proxy->probe_port, ports[pr0be], seq, 0, 0, TH_SYN, 0, 0, proxy->probe_port, ports[pr0be], seq, 0, 0, TH_SYN, 0, 0,
(u8 *) "\x02\x04\x05\xb4", 4, (u8 *) "\x02\x04\x05\xb4", 4,
o.extra_payload, o.extra_payload_length, o.extra_payload, o.extra_payload_length,
&packetlen); &packetlen);
res = send_ip_packet(proxy->rawsd, eth.ethsd ? &eth : NULL, &ss, packet, packetlen); res = send_ip_packet(proxy->rawsd, eth.ethsd ? &eth : NULL, &ss, packet, packetlen);
if (res == -1) if (res == -1)

View File

@@ -190,7 +190,7 @@ int main(int argc, char *argv[]) {
#ifdef MTRACE #ifdef MTRACE
// This glibc extension enables memory tracing to detect memory // This glibc extension enables memory tracing to detect memory
// leaks, frees of unallocated memory, etc. // leaks, frees of unallocated memory, etc.
// See http://www.gnu.org/manual/glibc-2.2.5/html_node/Allocation-Debugging.html#Allocation%20Debugging . // See http://www.gnu.org/manual/glibc-2.2.5/html_node/Allocation-Debugging.html#Allocation%20Debugging .
// It only works if the environment variable MALLOC_TRACE is set to a file // It only works if the environment variable MALLOC_TRACE is set to a file
// which a memory usage log will be written to. After the program quits // which a memory usage log will be written to. After the program quits

View File

@@ -9,10 +9,10 @@
* modify, merge, publish, distribute, sublicense, and/or sell copies * modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is * of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions: * furnished to do so, subject to the following conditions:
* *
* The above copyright notice and this permission notice shall be * The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software. * included in all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
@@ -209,7 +209,7 @@ int _getopt_internal(int argc, char * argv[], const char *shortopts,
if(((optopt = argv[optind][1]) != '-') && ! argv[optind][2]) { if(((optopt = argv[optind][1]) != '-') && ! argv[optind][2]) {
int c; int c;
ind = shortoff; ind = shortoff;
while((c = shortopts[ind++])) { while((c = shortopts[ind++])) {
if(((shortopts[ind] == ':') || if(((shortopts[ind] == ':') ||
@@ -280,7 +280,7 @@ int _getopt_internal(int argc, char * argv[], const char *shortopts,
} }
/* This function is kinda problematic because most getopt() nowadays /* This function is kinda problematic because most getopt() nowadays
seem to use char * const argv[] (they DON'T permute the options list), seem to use char * const argv[] (they DON'T permute the options list),
but this one does. So we remove it as long as HAVE_GETOPT is define, so but this one does. So we remove it as long as HAVE_GETOPT is define, so
people can use the version from their platform instead */ people can use the version from their platform instead */

View File

@@ -9,10 +9,10 @@
* modify, merge, publish, distribute, sublicense, and/or sell copies * modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is * of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions: * furnished to do so, subject to the following conditions:
* *
* The above copyright notice and this permission notice shall be * The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software. * included in all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND

View File

@@ -170,7 +170,7 @@ void addrset_free(struct addrset *set)
void addrset_elem_print(FILE *fp, const struct addrset_elem *elem) void addrset_elem_print(FILE *fp, const struct addrset_elem *elem)
{ {
const size_t num_bitvector = sizeof(octet_bitvector) / sizeof(bitvector_t); const size_t num_bitvector = sizeof(octet_bitvector) / sizeof(bitvector_t);
int i; int i;
size_t j; size_t j;
if (elem->type == ADDRSET_TYPE_IPV4_BITVECTOR) { if (elem->type == ADDRSET_TYPE_IPV4_BITVECTOR) {
@@ -361,7 +361,7 @@ int addrset_add_spec(struct addrset *set, const char *spec, int af, int dns)
} }
apply_ipv4_netmask_bits(elem, netmask_bits); apply_ipv4_netmask_bits(elem, netmask_bits);
log_debug("Add IPv4 %s/%ld to addrset.\n", addr_string, netmask_bits > 0 ? netmask_bits : 32); log_debug("Add IPv4 %s/%ld to addrset.\n", addr_string, netmask_bits > 0 ? netmask_bits : 32);
#ifdef HAVE_IPV6 #ifdef HAVE_IPV6
} else if (addr->ai_family == AF_INET6) { } else if (addr->ai_family == AF_INET6) {
const struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) addr->ai_addr; const struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) addr->ai_addr;

22
nmap.h
View File

@@ -180,7 +180,7 @@ void *realloc();
#include <sys/wait.h> #include <sys/wait.h>
#endif /* !WIN32 */ #endif /* !WIN32 */
#ifdef HAVE_SYS_PARAM_H #ifdef HAVE_SYS_PARAM_H
#include <sys/param.h> /* Defines MAXHOSTNAMELEN on BSD*/ #include <sys/param.h> /* Defines MAXHOSTNAMELEN on BSD*/
#endif #endif
@@ -193,7 +193,7 @@ void *realloc();
#if HAVE_SYS_SOCKET_H #if HAVE_SYS_SOCKET_H
#include <sys/socket.h> #include <sys/socket.h>
#endif #endif
#include <sys/stat.h> #include <sys/stat.h>
#if HAVE_NETINET_IN_H #if HAVE_NETINET_IN_H
@@ -250,7 +250,7 @@ void *realloc();
// #define NET_IF_H // #define NET_IF_H
// #endif // #endif
// #endif // #endif
// #if HAVE_NETINET_IF_ETHER_H // #if HAVE_NETINET_IF_ETHER_H
// #ifndef NETINET_IF_ETHER_H // #ifndef NETINET_IF_ETHER_H
// #include <netinet/if_ether.h> // #include <netinet/if_ether.h>
// #define NETINET_IF_ETHER_H // #define NETINET_IF_ETHER_H
@@ -274,12 +274,12 @@ void *realloc();
/* User configurable #defines: */ /* User configurable #defines: */
#define MAX_PROBE_PORTS 10 /* How many TCP probe ports are allowed ? */ #define MAX_PROBE_PORTS 10 /* How many TCP probe ports are allowed ? */
/* Default number of ports in parallel. Doesn't always involve actual /* Default number of ports in parallel. Doesn't always involve actual
sockets. Can also adjust with the -M command line option. */ sockets. Can also adjust with the -M command line option. */
#define MAX_SOCKETS 36 #define MAX_SOCKETS 36
#define MAX_TIMEOUTS MAX_SOCKETS /* How many timed out connection attempts #define MAX_TIMEOUTS MAX_SOCKETS /* How many timed out connection attempts
in a row before we decide the host is in a row before we decide the host is
dead? */ dead? */
#define _STR(X) #X #define _STR(X) #X
#define STR(X) _STR(X) #define STR(X) _STR(X)
@@ -323,7 +323,7 @@ void *realloc();
drops until many probes later on extremely low-latency drops until many probes later on extremely low-latency
networks (such as localhost scans). */ networks (such as localhost scans). */
#ifndef MIN_RTT_TIMEOUT #ifndef MIN_RTT_TIMEOUT
#define MIN_RTT_TIMEOUT 100 #define MIN_RTT_TIMEOUT 100
#endif #endif
#ifndef MAX_RTT_TIMEOUT #ifndef MAX_RTT_TIMEOUT
@@ -349,7 +349,7 @@ void *realloc();
#define HOST_UNKNOWN 0 #define HOST_UNKNOWN 0
#define HOST_UP 1 #define HOST_UP 1
#define HOST_DOWN 2 #define HOST_DOWN 2
#define PINGTYPE_UNKNOWN 0 #define PINGTYPE_UNKNOWN 0
#define PINGTYPE_NONE 1 #define PINGTYPE_NONE 1
@@ -398,9 +398,9 @@ void *realloc();
#define IPID_SEQ_UNKNOWN 0 #define IPID_SEQ_UNKNOWN 0
#define IPID_SEQ_INCR 1 /* simple increment by one each time */ #define IPID_SEQ_INCR 1 /* simple increment by one each time */
#define IPID_SEQ_BROKEN_INCR 2 /* Stupid MS -- forgot htons() so it #define IPID_SEQ_BROKEN_INCR 2 /* Stupid MS -- forgot htons() so it
counts by 256 on little-endian platforms */ counts by 256 on little-endian platforms */
#define IPID_SEQ_RPI 3 /* Goes up each time but by a "random" positive #define IPID_SEQ_RPI 3 /* Goes up each time but by a "random" positive
increment */ increment */
#define IPID_SEQ_RD 4 /* Appears to select IPID using a "random" distributions (meaning it can go up or down) */ #define IPID_SEQ_RD 4 /* Appears to select IPID using a "random" distributions (meaning it can go up or down) */
#define IPID_SEQ_CONSTANT 5 /* Contains 1 or more sequential duplicates */ #define IPID_SEQ_CONSTANT 5 /* Contains 1 or more sequential duplicates */

View File

@@ -202,7 +202,7 @@ void pfatal(const char *fmt, ...) {
#ifdef WIN32 #ifdef WIN32
error_number = GetLastError(); error_number = GetLastError();
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM, FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
NULL, error_number, MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT), NULL, error_number, MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &strerror_s, 0, NULL); (LPTSTR) &strerror_s, 0, NULL);
#else #else
@@ -264,14 +264,14 @@ void gh_perror(const char *fmt, ...) {
#ifdef WIN32 #ifdef WIN32
error_number = GetLastError(); error_number = GetLastError();
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM, FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
NULL, error_number, MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT), NULL, error_number, MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &strerror_s, 0, NULL); (LPTSTR) &strerror_s, 0, NULL);
#else #else
error_number = errno; error_number = errno;
strerror_s = strerror(error_number); strerror_s = strerror(error_number);
#endif #endif
va_start(ap, fmt); va_start(ap, fmt);
log_vwrite(LOG_NORMAL|LOG_STDERR, fmt, ap); log_vwrite(LOG_NORMAL|LOG_STDERR, fmt, ap);
va_end(ap); va_end(ap);

View File

@@ -157,7 +157,7 @@ extern "C" {
#ifdef WIN32 #ifdef WIN32
__declspec(noreturn) __declspec(noreturn)
#endif #endif
void fatal(const char *fmt, ...) void fatal(const char *fmt, ...)
__attribute__ ((noreturn)) __attribute__ ((noreturn))
__attribute__ ((format (printf, 1, 2))); __attribute__ ((format (printf, 1, 2)));

View File

@@ -128,7 +128,7 @@
#include "nmap.h" /* u16 */ #include "nmap.h" /* u16 */
/* How do we want to log into ftp sites for */ /* How do we want to log into ftp sites for */
#define FTPUSER "anonymous" #define FTPUSER "anonymous"
#define FTPPASS "-wwwuser@" #define FTPPASS "-wwwuser@"
#define FTP_RETRIES 2 /* How many times should we relogin if we lose control #define FTP_RETRIES 2 /* How many times should we relogin if we lose control

View File

@@ -133,7 +133,7 @@ static int l_unpack(lua_State *L) /** unpack(f,s, [init]) */
{ {
int c=*f++; int c=*f++;
int N=1; int N=1;
if (isdigit((int) (unsigned char) *f)) if (isdigit((int) (unsigned char) *f))
{ {
N=0; N=0;
while (isdigit((int) (unsigned char) *f)) N=10*N+(*f++)-'0'; while (isdigit((int) (unsigned char) *f)) N=10*N+(*f++)-'0';
@@ -283,7 +283,7 @@ static int l_pack(lua_State *L) /** pack(f,...) */
{ {
int c=*f++; int c=*f++;
int N=1; int N=1;
if (isdigit((int) (unsigned char) *f)) if (isdigit((int) (unsigned char) *f))
{ {
N=0; N=0;
while (isdigit((int) (unsigned char) *f)) N=10*N+(*f++)-'0'; while (isdigit((int) (unsigned char) *f)) N=10*N+(*f++)-'0';
@@ -341,15 +341,15 @@ static int l_pack(lua_State *L) /** pack(f,...) */
} }
break; break;
} }
case OP_NULL: case OP_NULL:
{ {
char nullbyte = 0; char nullbyte = 0;
luaL_addlstring(&b, &nullbyte, 1); luaL_addlstring(&b, &nullbyte, 1);
break; break;
} }
case OP_HEX: case OP_HEX:
{ // doing digit parsing the lpack way { // doing digit parsing the lpack way
unsigned char sbyte = 0; unsigned char sbyte = 0;
size_t l; size_t l;
@@ -367,7 +367,7 @@ static int l_pack(lua_State *L) /** pack(f,...) */
} else if (a[ii] >= 'a' && a[ii] <= 'f') { } else if (a[ii] >= 'a' && a[ii] <= 'f') {
sbyte += a[ii] - 'a' + 10; sbyte += a[ii] - 'a' + 10;
odd++; odd++;
} }
if (odd == 1) { if (odd == 1) {
sbyte = sbyte << 4; sbyte = sbyte << 4;
} else if (odd == 2) { } else if (odd == 2) {

View File

@@ -1,4 +1,4 @@
/* Bitwise operations library /* Bitwise operations library
* by Reuben Thomas (rrt@sc3d.org) * by Reuben Thomas (rrt@sc3d.org)
* bitlib is a C library for Lua 5.x that provides bitwise operations * bitlib is a C library for Lua 5.x that provides bitwise operations
* It is copyright Reuben Thomas 2000-2006, and is released under the * It is copyright Reuben Thomas 2000-2006, and is released under the

View File

@@ -321,7 +321,7 @@ static int aux_mutex (lua_State *L)
return 0; return 0;
} }
/* This is the mutex destructor called when a thread ends but failed to /* This is the mutex destructor called when a thread ends but failed to
* unlock the mutex. * unlock the mutex.
* It has 1 upvalue: The nmap.mutex function closure. * It has 1 upvalue: The nmap.mutex function closure.
*/ */
@@ -492,7 +492,7 @@ static int l_port_is_excluded (lua_State *L)
unsigned short portno = (unsigned short) luaL_checkint(L, 1); unsigned short portno = (unsigned short) luaL_checkint(L, 1);
int protocol = NSE_PROTOCOL[luaL_checkoption(L, 2, NULL, NSE_PROTOCOL_OP)]; int protocol = NSE_PROTOCOL[luaL_checkoption(L, 2, NULL, NSE_PROTOCOL_OP)];
lua_pushboolean(L, AllProbes::check_excluded_port(portno, protocol)); lua_pushboolean(L, AllProbes::check_excluded_port(portno, protocol));
return 1; return 1;
} }
@@ -690,7 +690,7 @@ static int l_get_timing_level (lua_State *L)
* If this function was called without an argument then it * If this function was called without an argument then it
* will simply return the number of pending targets that are * will simply return the number of pending targets that are
* in the queue (waiting to be passed to Nmap). * in the queue (waiting to be passed to Nmap).
* *
* If the function was only able to add a one target, then we * If the function was only able to add a one target, then we
* consider this success. */ * consider this success. */
static int l_add_targets (lua_State *L) static int l_add_targets (lua_State *L)
@@ -715,7 +715,7 @@ static int l_add_targets (lua_State *L)
return 2; return 2;
} }
} else { } else {
/* function called without arguments */ /* function called without arguments */
/* push the number of pending targets that are in the queue */ /* push the number of pending targets that are in the queue */
lua_pushnumber(L, NewTargets::insert("")); lua_pushnumber(L, NewTargets::insert(""));
return 1; return 1;
@@ -804,7 +804,7 @@ static int l_get_interface (lua_State *L)
return 1; return 1;
} }
/* returns a list of tables where each table contains information about each /* returns a list of tables where each table contains information about each
* interface. * interface.
*/ */
static int l_list_interfaces (lua_State *L) static int l_list_interfaces (lua_State *L)
@@ -817,9 +817,9 @@ static int l_list_interfaces (lua_State *L)
struct addr src, bcast; struct addr src, bcast;
iflist = getinterfaces(&numifs, errstr, sizeof(errstr)); iflist = getinterfaces(&numifs, errstr, sizeof(errstr));
int i; int i;
if (iflist==NULL || numifs<=0) { if (iflist==NULL || numifs<=0) {
return nseU_safeerror(L, "%s", errstr); return nseU_safeerror(L, "%s", errstr);
} else { } else {
@@ -827,21 +827,21 @@ static int l_list_interfaces (lua_State *L)
memset(&src, 0, sizeof(src)); memset(&src, 0, sizeof(src));
memset(&bcast, 0, sizeof(bcast)); memset(&bcast, 0, sizeof(bcast));
lua_newtable(L); //base table lua_newtable(L); //base table
for(i=0; i< numifs; i++) { for(i=0; i< numifs; i++) {
lua_newtable(L); //interface table lua_newtable(L); //interface table
nseU_setsfield(L, -1, "device", iflist[i].devfullname); nseU_setsfield(L, -1, "device", iflist[i].devfullname);
nseU_setsfield(L, -1, "shortname", iflist[i].devname); nseU_setsfield(L, -1, "shortname", iflist[i].devname);
nseU_setnfield(L, -1, "netmask", iflist[i].netmask_bits); nseU_setnfield(L, -1, "netmask", iflist[i].netmask_bits);
nseU_setsfield(L, -1, "address", inet_ntop_ez(&(iflist[i].addr), nseU_setsfield(L, -1, "address", inet_ntop_ez(&(iflist[i].addr),
sizeof(iflist[i].addr) )); sizeof(iflist[i].addr) ));
switch (iflist[i].device_type){ switch (iflist[i].device_type){
case devt_ethernet: case devt_ethernet:
nseU_setsfield(L, -1, "link", "ethernet"); nseU_setsfield(L, -1, "link", "ethernet");
lua_pushlstring(L, (const char *) iflist[i].mac, 6); lua_pushlstring(L, (const char *) iflist[i].mac, 6);
lua_setfield(L, -2, "mac"); lua_setfield(L, -2, "mac");
/* calculate the broadcast address */ /* calculate the broadcast address */
if (iflist[i].addr.ss_family == AF_INET) { if (iflist[i].addr.ss_family == AF_INET) {
src.addr_type = ADDR_TYPE_IP; src.addr_type = ADDR_TYPE_IP;
@@ -863,10 +863,10 @@ static int l_list_interfaces (lua_State *L)
default: default:
nseU_setsfield(L, -1, "link", "other"); nseU_setsfield(L, -1, "link", "other");
} }
nseU_setsfield(L, -1, "up", (iflist[i].device_up ? "up" : "down")); nseU_setsfield(L, -1, "up", (iflist[i].device_up ? "up" : "down"));
nseU_setnfield(L, -1, "mtu", iflist[i].mtu); nseU_setnfield(L, -1, "mtu", iflist[i].mtu);
/* After setting the fields, add the interface table to the base table */ /* After setting the fields, add the interface table to the base table */
lua_rawseti(L, -2, i + 1); lua_rawseti(L, -2, i + 1);
} }
@@ -874,8 +874,8 @@ static int l_list_interfaces (lua_State *L)
return 1; return 1;
} }
/* return the ttl (time to live) specified with the /* return the ttl (time to live) specified with the
* --ttl command line option. If a wrong value is * --ttl command line option. If a wrong value is
* specified it defaults to 64. * specified it defaults to 64.
*/ */
static int l_get_ttl (lua_State *L) static int l_get_ttl (lua_State *L)
@@ -887,8 +887,8 @@ static int l_get_ttl (lua_State *L)
return 1; return 1;
} }
/* return the payload length specified by the --data-length /* return the payload length specified by the --data-length
* command line option. If it * isn't specified or the value * command line option. If it * isn't specified or the value
* is out of range then the default value (0) is returned. * is out of range then the default value (0) is returned.
*/ */
static int l_get_payload_length(lua_State *L) static int l_get_payload_length(lua_State *L)

View File

@@ -155,7 +155,7 @@ static std::string hexify (const unsigned char *str, size_t len)
* *
* THREAD_SOCKETS is a weak keyed table of <Thread, Socket Table> pairs. * THREAD_SOCKETS is a weak keyed table of <Thread, Socket Table> pairs.
* A socket table is a weak keyed table (socket keys with garbage values) of * A socket table is a weak keyed table (socket keys with garbage values) of
* sockets the Thread has allocated but not necessarily open). You may * sockets the Thread has allocated but not necessarily open). You may
* test for an open socket by checking whether its nsiod field in the * test for an open socket by checking whether its nsiod field in the
* socket userdata structure is not NULL. * socket userdata structure is not NULL.
* *
@@ -566,7 +566,7 @@ static int l_sendto (lua_State *L)
trace(nu->nsiod, hexify((unsigned char *) string, size).c_str(), TO); trace(nu->nsiod, hexify((unsigned char *) string, size).c_str(), TO);
freeaddrinfo(dest); freeaddrinfo(dest);
return yield(L, nu, "SEND", TO, 0, NULL); return yield(L, nu, "SEND", TO, 0, NULL);
} }
static void receive_callback (nsock_pool nsp, nsock_event nse, void *udata) static void receive_callback (nsock_pool nsp, nsock_event nse, void *udata)

View File

@@ -224,7 +224,7 @@ static int l_md4(lua_State *L) /** md4(string s) */
size_t len; size_t len;
const unsigned char *s = (unsigned char *) luaL_checklstring( L, 1, &len ); const unsigned char *s = (unsigned char *) luaL_checklstring( L, 1, &len );
unsigned char digest[16]; unsigned char digest[16];
lua_pushlstring( L, (char *) MD4( s, len, digest ), 16 ); lua_pushlstring( L, (char *) MD4( s, len, digest ), 16 );
return 1; return 1;
} }
@@ -234,7 +234,7 @@ static int l_md5(lua_State *L) /** md5(string s) */
size_t len; size_t len;
const unsigned char *s = (unsigned char *) luaL_checklstring( L, 1, &len ); const unsigned char *s = (unsigned char *) luaL_checklstring( L, 1, &len );
unsigned char digest[16]; unsigned char digest[16];
lua_pushlstring( L, (char *) MD5( s, len, digest ), 16 ); lua_pushlstring( L, (char *) MD5( s, len, digest ), 16 );
return 1; return 1;
} }
@@ -244,7 +244,7 @@ static int l_sha1(lua_State *L) /** sha1(string s) */
size_t len; size_t len;
const unsigned char *s = (unsigned char *) luaL_checklstring( L, 1, &len ); const unsigned char *s = (unsigned char *) luaL_checklstring( L, 1, &len );
unsigned char digest[20]; unsigned char digest[20];
lua_pushlstring( L, (char *) SHA1( s, len, digest ), 20 ); lua_pushlstring( L, (char *) SHA1( s, len, digest ), 20 );
return 1; return 1;
} }
@@ -254,7 +254,7 @@ static int l_ripemd160(lua_State *L) /** ripemd160(string s) */
size_t len; size_t len;
const unsigned char *s = (unsigned char *) luaL_checklstring( L, 1, &len ); const unsigned char *s = (unsigned char *) luaL_checklstring( L, 1, &len );
unsigned char digest[20]; unsigned char digest[20];
lua_pushlstring( L, (char *) RIPEMD160( s, len, digest ), 20 ); lua_pushlstring( L, (char *) RIPEMD160( s, len, digest ), 20 );
return 1; return 1;
} }
@@ -270,7 +270,7 @@ static int l_digest(lua_State *L) /** digest(string algorithm, string messag
EVP_MD_CTX mdctx; EVP_MD_CTX mdctx;
evp_md = EVP_get_digestbyname( algorithm ); evp_md = EVP_get_digestbyname( algorithm );
if (!evp_md) return luaL_error( L, "Unknown digest algorithm: %s", algorithm ); if (!evp_md) return luaL_error( L, "Unknown digest algorithm: %s", algorithm );
EVP_MD_CTX_init(&mdctx); EVP_MD_CTX_init(&mdctx);
@@ -280,7 +280,7 @@ static int l_digest(lua_State *L) /** digest(string algorithm, string messag
EVP_DigestFinal_ex( &mdctx, digest, &digest_len ))) { EVP_DigestFinal_ex( &mdctx, digest, &digest_len ))) {
EVP_MD_CTX_cleanup( &mdctx ); EVP_MD_CTX_cleanup( &mdctx );
unsigned long e = ERR_get_error(); unsigned long e = ERR_get_error();
return luaL_error( L, "OpenSSL error %d in %s: function %s: %s", e, ERR_lib_error_string(e), return luaL_error( L, "OpenSSL error %d in %s: function %s: %s", e, ERR_lib_error_string(e),
ERR_func_error_string(e), ERR_reason_error_string(e)); ERR_func_error_string(e), ERR_reason_error_string(e));
} }
EVP_MD_CTX_cleanup( &mdctx ); EVP_MD_CTX_cleanup( &mdctx );
@@ -299,11 +299,11 @@ static int l_hmac(lua_State *L) /** hmac(string algorithm, string key, strin
unsigned char digest[EVP_MAX_MD_SIZE]; unsigned char digest[EVP_MAX_MD_SIZE];
const EVP_MD * evp_md; const EVP_MD * evp_md;
evp_md = EVP_get_digestbyname( algorithm ); evp_md = EVP_get_digestbyname( algorithm );
if (!evp_md) return luaL_error( L, "Unknown digest algorithm: %s", algorithm ); if (!evp_md) return luaL_error( L, "Unknown digest algorithm: %s", algorithm );
HMAC( evp_md, key, key_len, msg, msg_len, digest, &digest_len ); HMAC( evp_md, key, key_len, msg, msg_len, digest, &digest_len );
lua_pushlstring( L, (char *) digest, digest_len ); lua_pushlstring( L, (char *) digest, digest_len );
return 1; return 1;
} }
@@ -326,7 +326,7 @@ static int l_supported_digests(lua_State *L) /** supported_digests() */
enumerator_data data; enumerator_data data;
data.L = L; data.L = L;
data.index = 1; data.index = 1;
lua_newtable( L ); lua_newtable( L );
OBJ_NAME_do_all_sorted( OBJ_NAME_TYPE_MD_METH,enumerate_algorithms, &data ); OBJ_NAME_do_all_sorted( OBJ_NAME_TYPE_MD_METH,enumerate_algorithms, &data );
@@ -338,7 +338,7 @@ static int l_supported_ciphers(lua_State *L) /** supported_ciphers() */
enumerator_data data; enumerator_data data;
data.L = L; data.L = L;
data.index = 1; data.index = 1;
lua_newtable( L ); lua_newtable( L );
OBJ_NAME_do_all_sorted( OBJ_NAME_TYPE_CIPHER_METH,enumerate_algorithms, &data ); OBJ_NAME_do_all_sorted( OBJ_NAME_TYPE_CIPHER_METH,enumerate_algorithms, &data );
@@ -360,7 +360,7 @@ static int l_encrypt(lua_State *L) /** encrypt( string algorithm, string key, st
iv = NULL; iv = NULL;
EVP_CIPHER_CTX cipher_ctx; EVP_CIPHER_CTX cipher_ctx;
EVP_CIPHER_CTX_init( &cipher_ctx ); EVP_CIPHER_CTX_init( &cipher_ctx );
/* First create the cipher context, then set the key length and padding, and /* First create the cipher context, then set the key length and padding, and
check the iv length. Below we set the key and iv. */ check the iv length. Below we set the key and iv. */
@@ -369,7 +369,7 @@ static int l_encrypt(lua_State *L) /** encrypt( string algorithm, string key, st
EVP_CIPHER_CTX_set_key_length( &cipher_ctx, key_len ) && EVP_CIPHER_CTX_set_key_length( &cipher_ctx, key_len ) &&
EVP_CIPHER_CTX_set_padding( &cipher_ctx, padding ))) { EVP_CIPHER_CTX_set_padding( &cipher_ctx, padding ))) {
unsigned long e = ERR_get_error(); unsigned long e = ERR_get_error();
return luaL_error( L, "OpenSSL error %d in %s: function %s: %s", e, ERR_lib_error_string(e), return luaL_error( L, "OpenSSL error %d in %s: function %s: %s", e, ERR_lib_error_string(e),
ERR_func_error_string(e), ERR_reason_error_string(e)); ERR_func_error_string(e), ERR_reason_error_string(e));
} }
@@ -389,7 +389,7 @@ static int l_encrypt(lua_State *L) /** encrypt( string algorithm, string key, st
EVP_CIPHER_CTX_cleanup( &cipher_ctx ); EVP_CIPHER_CTX_cleanup( &cipher_ctx );
free( out ); free( out );
unsigned long e = ERR_get_error(); unsigned long e = ERR_get_error();
return luaL_error( L, "OpenSSL error %d in %s: function %s: %s", e, ERR_lib_error_string(e), return luaL_error( L, "OpenSSL error %d in %s: function %s: %s", e, ERR_lib_error_string(e),
ERR_func_error_string(e), ERR_reason_error_string(e)); ERR_func_error_string(e), ERR_reason_error_string(e));
} }
@@ -416,14 +416,14 @@ static int l_decrypt(lua_State *L) /** decrypt( string algorithm, string key, st
iv = NULL; iv = NULL;
EVP_CIPHER_CTX cipher_ctx; EVP_CIPHER_CTX cipher_ctx;
EVP_CIPHER_CTX_init( &cipher_ctx ); EVP_CIPHER_CTX_init( &cipher_ctx );
if (!( if (!(
EVP_DecryptInit_ex( &cipher_ctx, evp_cipher, NULL, NULL, NULL ) && EVP_DecryptInit_ex( &cipher_ctx, evp_cipher, NULL, NULL, NULL ) &&
EVP_CIPHER_CTX_set_key_length( &cipher_ctx, key_len ) && EVP_CIPHER_CTX_set_key_length( &cipher_ctx, key_len ) &&
EVP_CIPHER_CTX_set_padding( &cipher_ctx, padding ))) { EVP_CIPHER_CTX_set_padding( &cipher_ctx, padding ))) {
unsigned long e = ERR_get_error(); unsigned long e = ERR_get_error();
return luaL_error( L, "OpenSSL error %d in %s: function %s: %s", e, ERR_lib_error_string(e), return luaL_error( L, "OpenSSL error %d in %s: function %s: %s", e, ERR_lib_error_string(e),
ERR_func_error_string(e), ERR_reason_error_string(e)); ERR_func_error_string(e), ERR_reason_error_string(e));
} }
@@ -443,7 +443,7 @@ static int l_decrypt(lua_State *L) /** decrypt( string algorithm, string key, st
EVP_CIPHER_CTX_cleanup( &cipher_ctx ); EVP_CIPHER_CTX_cleanup( &cipher_ctx );
free( out ); free( out );
unsigned long e = ERR_get_error(); unsigned long e = ERR_get_error();
return luaL_error( L, "OpenSSL error %d in %s: function %s: %s", e, ERR_lib_error_string(e), return luaL_error( L, "OpenSSL error %d in %s: function %s: %s", e, ERR_lib_error_string(e),
ERR_func_error_string(e), ERR_reason_error_string(e)); ERR_func_error_string(e), ERR_reason_error_string(e));
} }
@@ -466,7 +466,7 @@ static int l_DES_string_to_key(lua_State *L) /** DES_string_to_key( string data
key[0] = data[0]; key[0] = data[0];
for( int i = 1; i < 8; i++ ) for( int i = 1; i < 8; i++ )
key[i] = data[i-1] << (8-i) | data[i] >> i; key[i] = data[i-1] << (8-i) | data[i] >> i;
DES_set_odd_parity( &key ); DES_set_odd_parity( &key );
lua_pushlstring( L, (char *) key, 8 ); lua_pushlstring( L, (char *) key, 8 );

View File

@@ -74,7 +74,7 @@
struct sslinfo { struct sslinfo {
/* SSL_ERROR_NONE, SSL_ERROR_WANT_CONNECT, SSL_ERROR_WAINT_READ, or /* SSL_ERROR_NONE, SSL_ERROR_WANT_CONNECT, SSL_ERROR_WAINT_READ, or
* SSL_ERROR_WANT_WRITE */ * SSL_ERROR_WANT_WRITE */
int ssl_desire; int ssl_desire;
}; };
int nsi_ssl_post_connect_verify(const nsock_iod nsockiod); int nsi_ssl_post_connect_verify(const nsock_iod nsockiod);

View File

@@ -171,7 +171,7 @@ void free_fingerprint_file(FingerPrintDB *DB);
/* Compares 2 fingerprints -- a referenceFP (can have expression /* Compares 2 fingerprints -- a referenceFP (can have expression
attributes) with an observed fingerprint (no expressions). If attributes) with an observed fingerprint (no expressions). If
verbose is nonzero, differences will be printed. The comparison verbose is nonzero, differences will be printed. The comparison
accuracy (between 0 and 1) is returned). If MatchPoints is not NULL, it is accuracy (between 0 and 1) is returned). If MatchPoints is not NULL, it is
a special "fingerprints" which tells how many points each test is worth. */ a special "fingerprints" which tells how many points each test is worth. */
double compare_fingerprints(const FingerPrint *referenceFP, const FingerPrint *observedFP, double compare_fingerprints(const FingerPrint *referenceFP, const FingerPrint *observedFP,
const FingerPrint *MatchPoints, int verbose); const FingerPrint *MatchPoints, int verbose);

View File

@@ -371,9 +371,9 @@ int get_ipid_sequence_16(int numSamples, u32 *ipids, int islocalhost) {
assert(numSamples < (int) (sizeof(ipid_diffs) / 2)); assert(numSamples < (int) (sizeof(ipid_diffs) / 2));
allipideqz = get_diffs(ipid_diffs, numSamples, ipids, islocalhost); allipideqz = get_diffs(ipid_diffs, numSamples, ipids, islocalhost);
/* AND with 0xffff so that in case the 16 bit counter was /* AND with 0xffff so that in case the 16 bit counter was
* flipped over we still have a continuous sequence */ * flipped over we still have a continuous sequence */
for (i = 0; i < numSamples; i++) { for (i = 0; i < numSamples; i++) {
ipid_diffs[i] = ipid_diffs[i] & 0xffff; ipid_diffs[i] = ipid_diffs[i] & 0xffff;
} }
return identify_sequence(numSamples, ipid_diffs, islocalhost, allipideqz); return identify_sequence(numSamples, ipid_diffs, islocalhost, allipideqz);
} }

View File

@@ -365,9 +365,9 @@ int print_iflist(void) {
NmapOutputTable *Tbl = NULL; NmapOutputTable *Tbl = NULL;
char errstr[256]; char errstr[256];
errstr[0]='\0'; errstr[0]='\0';
iflist = getinterfaces(&numifs, errstr, sizeof(errstr)); iflist = getinterfaces(&numifs, errstr, sizeof(errstr));
int i; int i;
/* First let's handle interfaces ... */ /* First let's handle interfaces ... */
if (iflist==NULL || numifs<=0) { if (iflist==NULL || numifs<=0) {
@@ -998,7 +998,7 @@ void log_vwrite(int logt, const char *fmt, va_list ap) {
} }
free(writebuf); free(writebuf);
break; break;
default: default:
/* Unknown log type. /* Unknown log type.
* --- * ---
@@ -1398,7 +1398,7 @@ static char *num_to_string_sigdigits(double d, int digits) {
return buf; return buf;
} }
/* Writes a heading for a full scan report ("Nmap scan report for..."), /* Writes a heading for a full scan report ("Nmap scan report for..."),
including host status and DNS records. */ including host status and DNS records. */
void write_host_header(Target *currenths) { void write_host_header(Target *currenths) {
@@ -2216,7 +2216,7 @@ void printscriptresults(ScriptResults *scriptResults, stype scantype) {
} else { } else {
xml_start_tag("postscript"); xml_start_tag("postscript");
log_write(LOG_PLAIN, "Post-scan script results:\n"); log_write(LOG_PLAIN, "Post-scan script results:\n");
} }
for (iter = scriptResults->begin(); iter != scriptResults->end(); iter++) { for (iter = scriptResults->begin(); iter != scriptResults->end(); iter++) {
iter->write_xml(); iter->write_xml();
script_output = formatScriptOutput((*iter)); script_output = formatScriptOutput((*iter));

View File

@@ -215,7 +215,7 @@ void log_flush(int logt);
corresponding logs immediately */ corresponding logs immediately */
void log_flush_all(); void log_flush_all();
/* Open a log descriptor of the type given to the filename given. If /* Open a log descriptor of the type given to the filename given. If
append is nonzero, the file will be appended instead of clobbered if append is nonzero, the file will be appended instead of clobbered if
it already exists. If the file does not exist, it will be created */ it already exists. If the file does not exist, it will be created */
int log_open(int logt, int append, char *filename); int log_open(int logt, int append, char *filename);
@@ -239,7 +239,7 @@ void output_xml_scaninfo_records(struct scan_lists *ports);
void write_host_header(Target *currenths); void write_host_header(Target *currenths);
/* Writes host status info to the log streams (including STDOUT). An /* Writes host status info to the log streams (including STDOUT). An
example is "Host: 10.11.12.13 (foo.bar.example.com)\tStatus: Up\n" to example is "Host: 10.11.12.13 (foo.bar.example.com)\tStatus: Up\n" to
machine log. */ machine log. */
void write_host_status(Target *currenths); void write_host_status(Target *currenths);

View File

@@ -129,7 +129,7 @@
#include "nbase.h" #include "nbase.h"
#ifndef NOLUA #ifndef NOLUA
#include "nse_main.h" #include "nse_main.h"
#endif #endif
#include "portreasons.h" #include "portreasons.h"
@@ -143,9 +143,9 @@
#define PORT_UNFILTERED 6 #define PORT_UNFILTERED 6
#define PORT_OPENFILTERED 7 /* Like udp/fin/xmas/null/ipproto scan with no response */ #define PORT_OPENFILTERED 7 /* Like udp/fin/xmas/null/ipproto scan with no response */
#define PORT_CLOSEDFILTERED 8 /* Idle scan */ #define PORT_CLOSEDFILTERED 8 /* Idle scan */
#define PORT_HIGHEST_STATE 9 /* ***IMPORTANT -- BUMP THIS UP WHEN STATES ARE #define PORT_HIGHEST_STATE 9 /* ***IMPORTANT -- BUMP THIS UP WHEN STATES ARE
ADDED *** */ ADDED *** */
#define TCPANDUDPANDSCTP IPPROTO_MAX #define TCPANDUDPANDSCTP IPPROTO_MAX
#define UDPANDSCTP (IPPROTO_MAX + 1) #define UDPANDSCTP (IPPROTO_MAX + 1)
@@ -190,9 +190,9 @@ struct serviceDeductions {
char *devicetype; char *devicetype;
std::vector<char *> cpe; std::vector<char *> cpe;
// SERVICE_TUNNEL_NONE or SERVICE_TUNNEL_SSL // SERVICE_TUNNEL_NONE or SERVICE_TUNNEL_SSL
enum service_tunnel_type service_tunnel; enum service_tunnel_type service_tunnel;
// if we should give the user a service fingerprint to submit, here it is. Otherwise NULL. // if we should give the user a service fingerprint to submit, here it is. Otherwise NULL.
char *service_fp; char *service_fp;
enum service_detection_type dtype; // definition above enum service_detection_type dtype; // definition above
}; };
@@ -207,7 +207,7 @@ class Port {
u16 portno; u16 portno;
u8 proto; u8 proto;
u8 state; u8 state;
state_reason_t reason; state_reason_t reason;
#ifndef NOLUA #ifndef NOLUA
@@ -240,7 +240,7 @@ class PortList {
static void initializePortMap(int protocol, u16 *ports, int portcount); static void initializePortMap(int protocol, u16 *ports, int portcount);
/* Free memory used by port_map. It should be done somewhere before quitting*/ /* Free memory used by port_map. It should be done somewhere before quitting*/
static void freePortMap(); static void freePortMap();
void setDefaultPortState(u8 protocol, int state); void setDefaultPortState(u8 protocol, int state);
void setPortState(u16 portno, u8 protocol, int state); void setPortState(u16 portno, u8 protocol, int state);
int getPortState(u16 portno, u8 protocol); int getPortState(u16 portno, u8 protocol);
@@ -286,7 +286,7 @@ class PortList {
// detected and we tried to tunnel through it ). // detected and we tried to tunnel through it ).
void setServiceProbeResults(u16 portno, int protocol, void setServiceProbeResults(u16 portno, int protocol,
enum serviceprobestate sres, const char *sname, enum serviceprobestate sres, const char *sname,
enum service_tunnel_type tunnel, const char *product, enum service_tunnel_type tunnel, const char *product,
const char *version, const char *hostname, const char *version, const char *hostname,
const char *ostype, const char *devicetype, const char *ostype, const char *devicetype,
const char *extrainfo, const char *extrainfo,
@@ -328,7 +328,7 @@ class PortList {
/* Set Port structure to PortList structure.*/ /* Set Port structure to PortList structure.*/
void setPortEntry(u16 portno, u8 protocol, Port *port); void setPortEntry(u16 portno, u8 protocol, Port *port);
/* A string identifying the system these ports are on. Just used for /* A string identifying the system these ports are on. Just used for
printing open ports, if it is set with setIdStr() */ printing open ports, if it is set with setIdStr() */
char *idstr; char *idstr;
/* Number of ports in each state per each protocol. */ /* Number of ports in each state per each protocol. */
@@ -336,7 +336,7 @@ class PortList {
Port **port_list[PORTLIST_PROTO_MAX]; Port **port_list[PORTLIST_PROTO_MAX];
protected: protected:
/* Maps port_number to index in port_list array. /* Maps port_number to index in port_list array.
* Only functions: getPortEntry, setPortEntry, initializePortMap and * Only functions: getPortEntry, setPortEntry, initializePortMap and
* nextPort should access this structure directly. */ * nextPort should access this structure directly. */
static u16 *port_map[PORTLIST_PROTO_MAX]; static u16 *port_map[PORTLIST_PROTO_MAX];
static u16 *port_map_rev[PORTLIST_PROTO_MAX]; static u16 *port_map_rev[PORTLIST_PROTO_MAX];

View File

@@ -179,11 +179,11 @@ typedef struct port_reason_summary {
enum reason_codes { enum reason_codes {
ER_RESETPEER, ER_CONREFUSED, ER_CONACCEPT, ER_RESETPEER, ER_CONREFUSED, ER_CONACCEPT,
ER_SYNACK, ER_SYN, ER_UDPRESPONSE, ER_PROTORESPONSE, ER_ACCES, ER_SYNACK, ER_SYN, ER_UDPRESPONSE, ER_PROTORESPONSE, ER_ACCES,
ER_NETUNREACH, ER_HOSTUNREACH, ER_PROTOUNREACH, ER_NETUNREACH, ER_HOSTUNREACH, ER_PROTOUNREACH,
ER_PORTUNREACH, ER_ECHOREPLY, ER_PORTUNREACH, ER_ECHOREPLY,
ER_DESTUNREACH, ER_SOURCEQUENCH, ER_NETPROHIBITED, ER_DESTUNREACH, ER_SOURCEQUENCH, ER_NETPROHIBITED,
ER_HOSTPROHIBITED, ER_ADMINPROHIBITED, ER_HOSTPROHIBITED, ER_ADMINPROHIBITED,

View File

@@ -3751,7 +3751,7 @@ static UltraProbe *sendIPScanProbe(UltraScanInfo *USI, HostScanStats *hss,
hss->probeSent(packetlen); hss->probeSent(packetlen);
send_ip_packet(USI->rawsd, ethptr, hss->target->TargetSockAddr(), packet, packetlen); send_ip_packet(USI->rawsd, ethptr, hss->target->TargetSockAddr(), packet, packetlen);
free(packet); free(packet);
} else assert(0); } else assert(0);
/* Now that the probe has been sent, add it to the Queue for this host */ /* Now that the probe has been sent, add it to the Queue for this host */
hss->probes_outstanding.push_back(probe); hss->probes_outstanding.push_back(probe);
@@ -5503,7 +5503,7 @@ static void waitForResponses(UltraScanInfo *USI) {
gotone = get_pcap_result(USI, &stime); gotone = get_pcap_result(USI, &stime);
} else if (USI->scantype == CONNECT_SCAN) { } else if (USI->scantype == CONNECT_SCAN) {
gotone = do_one_select_round(USI, &stime); gotone = do_one_select_round(USI, &stime);
} else assert(0); } else assert(0);
} while (gotone && USI->gstats->num_probes_active > 0); } while (gotone && USI->gstats->num_probes_active > 0);
gettimeofday(&USI->now, NULL); gettimeofday(&USI->now, NULL);

View File

@@ -186,7 +186,7 @@ typedef struct probespec {
} probespec; } probespec;
/* 3rd generation Nmap scanning function. Handles most Nmap port scan types */ /* 3rd generation Nmap scanning function. Handles most Nmap port scan types */
void ultra_scan(std::vector<Target *> &Targets, struct scan_lists *ports, void ultra_scan(std::vector<Target *> &Targets, struct scan_lists *ports,
stype scantype, struct timeout_info *to = NULL); stype scantype, struct timeout_info *to = NULL);
/* Determines an ideal number of hosts to be scanned (port scan, os /* Determines an ideal number of hosts to be scanned (port scan, os
@@ -197,7 +197,7 @@ void ultra_scan(std::vector<Target *> &Targets, struct scan_lists *ports,
results). Memory consumption usually also increases with the results). Memory consumption usually also increases with the
number of hosts scanned in parallel, though rarely to significant number of hosts scanned in parallel, though rarely to significant
levels. */ levels. */
int determineScanGroupSize(int hosts_scanned_so_far, int determineScanGroupSize(int hosts_scanned_so_far,
struct scan_lists *ports); struct scan_lists *ports);
#endif /* SCAN_ENGINE_H */ #endif /* SCAN_ENGINE_H */

View File

@@ -173,7 +173,7 @@ public:
// the response the the fingerprint for that service. The // the response the the fingerprint for that service. The
// fingerprint can be printed when nothing matches the service. You // fingerprint can be printed when nothing matches the service. You
// can obtain the fingerprint (if any) via getServiceFingerprint(); // can obtain the fingerprint (if any) via getServiceFingerprint();
void addToServiceFingerprint(const char *probeName, const u8 *resp, void addToServiceFingerprint(const char *probeName, const u8 *resp,
int resplen); int resplen);
// Get the service fingerprint. It is NULL if there is none, such // Get the service fingerprint. It is NULL if there is none, such
@@ -207,7 +207,7 @@ public:
// if a match was found (see above), this tells whether it was a "soft" // if a match was found (see above), this tells whether it was a "soft"
// or hard match. It is always false if no match has been found. // or hard match. It is always false if no match has been found.
bool softMatchFound; bool softMatchFound;
// most recent probe executed (or in progress). If there has been a match // most recent probe executed (or in progress). If there has been a match
// (probe_matched != NULL), this will be the corresponding ServiceProbe. // (probe_matched != NULL), this will be the corresponding ServiceProbe.
ServiceProbe *currentProbe(); ServiceProbe *currentProbe();
// computes the next probe to test, and ALSO CHANGES currentProbe() to // computes the next probe to test, and ALSO CHANGES currentProbe() to
@@ -220,7 +220,7 @@ public:
// service fingerprint is freed too. // service fingerprint is freed too.
void resetProbes(bool freefp); void resetProbes(bool freefp);
// Number of milliseconds left to complete the present probe, or 0 if // Number of milliseconds left to complete the present probe, or 0 if
// the probe is already expired. Timeval can omitted, it is just there // the probe is already expired. Timeval can omitted, it is just there
// as an optimization in case you have it handy. // as an optimization in case you have it handy.
int probe_timemsleft(const ServiceProbe *probe, const struct timeval *now = NULL); int probe_timemsleft(const ServiceProbe *probe, const struct timeval *now = NULL);
enum serviceprobestate probe_state; // defined in portlist.h enum serviceprobestate probe_state; // defined in portlist.h
@@ -232,11 +232,11 @@ public:
struct timeval currentprobe_exec_time; struct timeval currentprobe_exec_time;
// Append newly-received data to the current response string (if any) // Append newly-received data to the current response string (if any)
void appendtocurrentproberesponse(const u8 *respstr, int respstrlen); void appendtocurrentproberesponse(const u8 *respstr, int respstrlen);
// Get the full current response string. Note that this pointer is // Get the full current response string. Note that this pointer is
// INVALIDATED if you call appendtocurrentproberesponse() or nextProbe() // INVALIDATED if you call appendtocurrentproberesponse() or nextProbe()
u8 *getcurrentproberesponse(int *respstrlen); u8 *getcurrentproberesponse(int *respstrlen);
AllProbes *AP; AllProbes *AP;
private: private:
// Adds a character to servicefp. Takes care of word wrapping if // Adds a character to servicefp. Takes care of word wrapping if
// necessary at the given (wrapat) column. Chars will only be // necessary at the given (wrapat) column. Chars will only be
@@ -276,7 +276,7 @@ struct substargs {
// This is the length of each string arg, since they can contain zeros. // This is the length of each string arg, since they can contain zeros.
// The str_args[] are zero-terminated for convenience in the cases where // The str_args[] are zero-terminated for convenience in the cases where
// you know they won't contain zero. // you know they won't contain zero.
int str_args_len[SUBSTARGS_MAX_ARGS]; int str_args_len[SUBSTARGS_MAX_ARGS];
int int_args[SUBSTARGS_MAX_ARGS]; int int_args[SUBSTARGS_MAX_ARGS];
// The type of each argument -- see #define's above. // The type of each argument -- see #define's above.
int arg_types[SUBSTARGS_MAX_ARGS]; int arg_types[SUBSTARGS_MAX_ARGS];
@@ -401,7 +401,7 @@ void ServiceProbeMatch::InitMatch(const char *matchtext, int lineno) {
char **curr_tmp = NULL; char **curr_tmp = NULL;
if (isInitialized) fatal("Sorry ... %s does not yet support reinitializion", __func__); if (isInitialized) fatal("Sorry ... %s does not yet support reinitializion", __func__);
if (!matchtext || !*matchtext) if (!matchtext || !*matchtext)
fatal("%s: no matchtext passed in (line %d of nmap-service-probes)", __func__, lineno); fatal("%s: no matchtext passed in (line %d of nmap-service-probes)", __func__, lineno);
isInitialized = true; isInitialized = true;
@@ -415,7 +415,7 @@ void ServiceProbeMatch::InitMatch(const char *matchtext, int lineno) {
} else if (strncmp(matchtext, "match ", 6) == 0) { } else if (strncmp(matchtext, "match ", 6) == 0) {
isSoft = false; isSoft = false;
matchtext += 6; matchtext += 6;
} else } else
fatal("%s: parse error on line %d of nmap-service-probes - must begin with \"match\" or \"softmatch\"", __func__, lineno); fatal("%s: parse error on line %d of nmap-service-probes - must begin with \"match\" or \"softmatch\"", __func__, lineno);
// next comes the service name // next comes the service name
@@ -458,7 +458,7 @@ void ServiceProbeMatch::InitMatch(const char *matchtext, int lineno) {
if (matchops_dotall) if (matchops_dotall)
pcre_compile_ops |= PCRE_DOTALL; pcre_compile_ops |= PCRE_DOTALL;
regex_compiled = pcre_compile(matchstr, pcre_compile_ops, &pcre_errptr, regex_compiled = pcre_compile(matchstr, pcre_compile_ops, &pcre_errptr,
&pcre_erroffset, NULL); &pcre_erroffset, NULL);
if (regex_compiled == NULL) if (regex_compiled == NULL)
@@ -545,7 +545,7 @@ const struct MatchDetails *ServiceProbeMatch::testMatch(const u8 *buf, int bufle
if (rc < 0) { if (rc < 0) {
#ifdef PCRE_ERROR_MATCHLIMIT // earlier PCRE versions lack this #ifdef PCRE_ERROR_MATCHLIMIT // earlier PCRE versions lack this
if (rc == PCRE_ERROR_MATCHLIMIT) { if (rc == PCRE_ERROR_MATCHLIMIT) {
if (o.debugging || o.verbose > 1) if (o.debugging || o.verbose > 1)
error("Warning: Hit PCRE_ERROR_MATCHLIMIT when probing for service %s with the regex '%s'", servicename, matchstr); error("Warning: Hit PCRE_ERROR_MATCHLIMIT when probing for service %s with the regex '%s'", servicename, matchstr);
} else } else
#endif // PCRE_ERROR_MATCHLIMIT #endif // PCRE_ERROR_MATCHLIMIT
@@ -567,7 +567,7 @@ const struct MatchDetails *ServiceProbeMatch::testMatch(const u8 *buf, int bufle
if (*cpe_a) MD_return.cpe_a = cpe_a; if (*cpe_a) MD_return.cpe_a = cpe_a;
if (*cpe_h) MD_return.cpe_h = cpe_h; if (*cpe_h) MD_return.cpe_h = cpe_h;
if (*cpe_o) MD_return.cpe_o = cpe_o; if (*cpe_o) MD_return.cpe_o = cpe_o;
MD_return.serviceName = servicename; MD_return.serviceName = servicename;
MD_return.lineno = getLineNo(); MD_return.lineno = getLineNo();
} }
@@ -583,7 +583,7 @@ const struct MatchDetails *ServiceProbeMatch::testMatch(const u8 *buf, int bufle
// args_end (if non-null) is set to the character after the closing // args_end (if non-null) is set to the character after the closing
// ')'. Otherwise we return -1 and the values of args and args_end // ')'. Otherwise we return -1 and the values of args and args_end
// are undefined. // are undefined.
static int getsubstcommandargs(struct substargs *args, char *args_start, static int getsubstcommandargs(struct substargs *args, char *args_start,
char **args_end) { char **args_end) {
char *p; char *p;
unsigned int len; unsigned int len;
@@ -772,7 +772,7 @@ static char *substvar(char *tmplvar, char **tmplvarend,
assert(offstart >= 0 && offstart < subjectlen); assert(offstart >= 0 && offstart < subjectlen);
assert(offend >= 0 && offend <= subjectlen); assert(offend >= 0 && offend <= subjectlen);
// This filter only includes printable characters. It is particularly // This filter only includes printable characters. It is particularly
// useful for collapsing unicode text that looks like // useful for collapsing unicode text that looks like
// "W\0O\0R\0K\0G\0R\0O\0U\0P\0" // "W\0O\0R\0K\0G\0R\0O\0U\0P\0"
for(i=offstart; i < offend; i++) { for(i=offstart; i < offend; i++) {
if (isprint((int) subject[i])) if (isprint((int) subject[i]))
@@ -826,7 +826,7 @@ static char *substvar(char *tmplvar, char **tmplvarend,
// The transform argument is a function pointer. If not NULL, the given // The transform argument is a function pointer. If not NULL, the given
// function is applied to all substitutions before they are inserted // function is applied to all substitutions before they are inserted
// into the result string. // into the result string.
static int dotmplsubst(const u8 *subject, int subjectlen, static int dotmplsubst(const u8 *subject, int subjectlen,
int *ovector, int nummatches, char *tmpl, char *newstr, int *ovector, int nummatches, char *tmpl, char *newstr,
int newstrlen, int newstrlen,
char *(*transform)(const char *) = NULL) { char *(*transform)(const char *) = NULL) {
@@ -838,7 +838,7 @@ static int dotmplsubst(const u8 *subject, int subjectlen,
if (!newstr || !tmpl) return -1; if (!newstr || !tmpl) return -1;
if (newstrlen < 3) return -1; // fuck this! if (newstrlen < 3) return -1; // fuck this!
while(*srcstart) { while(*srcstart) {
// First do any literal text before '$' // First do any literal text before '$'
srcend = strchr(srcstart, '$'); srcend = strchr(srcstart, '$');
@@ -851,7 +851,7 @@ static int dotmplsubst(const u8 *subject, int subjectlen,
} }
*dst = '\0'; *dst = '\0';
while (--dst >= newstr) { while (--dst >= newstr) {
if (isspace((int) (unsigned char) *dst) || *dst == ',') if (isspace((int) (unsigned char) *dst) || *dst == ',')
*dst = '\0'; *dst = '\0';
else break; else break;
} }
@@ -893,7 +893,7 @@ static int dotmplsubst(const u8 *subject, int subjectlen,
return -1; return -1;
*dst = '\0'; *dst = '\0';
while (--dst >= newstr) { while (--dst >= newstr) {
if (isspace((int) (unsigned char) *dst) || *dst == ',') if (isspace((int) (unsigned char) *dst) || *dst == ',')
*dst = '\0'; *dst = '\0';
else break; else break;
} }
@@ -908,7 +908,7 @@ static int dotmplsubst(const u8 *subject, int subjectlen,
// for a string, that string will have zero length after the function // for a string, that string will have zero length after the function
// call (assuming the corresponding length passed in is at least 1) // call (assuming the corresponding length passed in is at least 1)
int ServiceProbeMatch::getVersionStr(const u8 *subject, int subjectlen, int ServiceProbeMatch::getVersionStr(const u8 *subject, int subjectlen,
int *ovector, int nummatches, char *product, int productlen, int *ovector, int nummatches, char *product, int productlen,
char *version, int versionlen, char *info, int infolen, char *version, int versionlen, char *info, int infolen,
char *hostname, int hostnamelen, char *ostype, int ostypelen, char *hostname, int hostnamelen, char *ostype, int ostypelen,
@@ -920,7 +920,7 @@ int ServiceProbeMatch::getVersionStr(const u8 *subject, int subjectlen,
int rc; int rc;
assert(productlen >= 0 && versionlen >= 0 && infolen >= 0 && assert(productlen >= 0 && versionlen >= 0 && infolen >= 0 &&
hostnamelen >= 0 && ostypelen >= 0 && devicetypelen >= 0); hostnamelen >= 0 && ostypelen >= 0 && devicetypelen >= 0);
if (productlen > 0) *product = '\0'; if (productlen > 0) *product = '\0';
if (versionlen > 0) *version = '\0'; if (versionlen > 0) *version = '\0';
if (infolen > 0) *info = '\0'; if (infolen > 0) *info = '\0';
@@ -968,7 +968,7 @@ int ServiceProbeMatch::getVersionStr(const u8 *subject, int subjectlen,
retval = -1; retval = -1;
} }
} }
if (hostname_template) { if (hostname_template) {
rc = dotmplsubst(subject, subjectlen, ovector, nummatches, hostname_template, hostname, hostnamelen); rc = dotmplsubst(subject, subjectlen, ovector, nummatches, hostname_template, hostname, hostnamelen);
if (rc != 0) { if (rc != 0) {
@@ -1034,7 +1034,7 @@ int ServiceProbeMatch::getVersionStr(const u8 *subject, int subjectlen,
retval = -1; retval = -1;
} }
} }
return retval; return retval;
} }
@@ -1120,7 +1120,7 @@ void ServiceProbe::setProbeString(const u8 *ps, int stringlen) {
} else probestring = NULL; } else probestring = NULL;
} }
void ServiceProbe::setPortVector(std::vector<u16> *portv, const char *portstr, void ServiceProbe::setPortVector(std::vector<u16> *portv, const char *portstr,
int lineno) { int lineno) {
const char *current_range; const char *current_range;
char *endptr; char *endptr;
@@ -1165,7 +1165,7 @@ void ServiceProbe::setPortVector(std::vector<u16> *portv, const char *portstr,
portv->push_back(rangestart); portv->push_back(rangestart);
rangestart++; rangestart++;
} }
/* Find the next range */ /* Find the next range */
while(isspace((int) (unsigned char) *current_range)) current_range++; while(isspace((int) (unsigned char) *current_range)) current_range++;
if (*current_range && *current_range != ',') { if (*current_range && *current_range != ',') {
@@ -1201,7 +1201,7 @@ bool ServiceProbe::portIsProbable(enum service_tunnel_type tunnel, u16 portno) {
std::vector<u16> *portv; std::vector<u16> *portv;
portv = (tunnel == SERVICE_TUNNEL_SSL)? &probablesslports : &probableports; portv = (tunnel == SERVICE_TUNNEL_SSL)? &probablesslports : &probableports;
if (find(portv->begin(), portv->end(), portno) == portv->end()) if (find(portv->begin(), portv->end(), portno) == portv->end())
return false; return false;
return true; return true;
@@ -1262,15 +1262,15 @@ void parse_nmap_service_probe_file(AllProbes *AP, char *filename) {
// We better start by opening the file // We better start by opening the file
fp = fopen(filename, "r"); fp = fopen(filename, "r");
if (!fp) if (!fp)
fatal("Failed to open nmap-service-probes file %s for reading", filename); fatal("Failed to open nmap-service-probes file %s for reading", filename);
while(fgets(line, sizeof(line), fp)) { while(fgets(line, sizeof(line), fp)) {
lineno++; lineno++;
if (*line == '\n' || *line == '#') if (*line == '\n' || *line == '#')
continue; continue;
if (strncmp(line, "Exclude ", 8) == 0) { if (strncmp(line, "Exclude ", 8) == 0) {
if (AP->excluded_seen) if (AP->excluded_seen)
fatal("Only 1 Exclude directive is allowed in the nmap-service-probes file"); fatal("Only 1 Exclude directive is allowed in the nmap-service-probes file");
@@ -1278,21 +1278,21 @@ void parse_nmap_service_probe_file(AllProbes *AP, char *filename) {
AP->excluded_seen = true; AP->excluded_seen = true;
continue; continue;
} }
anotherprobe: anotherprobe:
if (strncmp(line, "Probe ", 6) != 0) if (strncmp(line, "Probe ", 6) != 0)
fatal("Parse error on line %d of nmap-service-probes file: %s -- line was expected to begin with \"Probe \" or \"Exclude \"", lineno, filename); fatal("Parse error on line %d of nmap-service-probes file: %s -- line was expected to begin with \"Probe \" or \"Exclude \"", lineno, filename);
newProbe = new ServiceProbe(); newProbe = new ServiceProbe();
newProbe->setProbeDetails(line + 6, lineno); newProbe->setProbeDetails(line + 6, lineno);
// Now we read the rest of the probe info // Now we read the rest of the probe info
while(fgets(line, sizeof(line), fp)) { while(fgets(line, sizeof(line), fp)) {
lineno++; lineno++;
if (*line == '\n' || *line == '#') if (*line == '\n' || *line == '#')
continue; continue;
if (strncmp(line, "Probe ", 6) == 0) { if (strncmp(line, "Probe ", 6) == 0) {
if (newProbe->isNullProbe()) { if (newProbe->isNullProbe()) {
assert(!AP->nullProbe); assert(!AP->nullProbe);
@@ -1554,7 +1554,7 @@ ServiceNFO::ServiceNFO(AllProbes *newAP) {
probe_state = PROBESTATE_INITIAL; probe_state = PROBESTATE_INITIAL;
portno = proto = 0; portno = proto = 0;
AP = newAP; AP = newAP;
currentresp = NULL; currentresp = NULL;
currentresplen = 0; currentresplen = 0;
product_matched[0] = version_matched[0] = extrainfo_matched[0] = '\0'; product_matched[0] = version_matched[0] = extrainfo_matched[0] = '\0';
hostname_matched[0] = ostype_matched[0] = devicetype_matched[0] = '\0'; hostname_matched[0] = ostype_matched[0] = devicetype_matched[0] = '\0';
@@ -1598,7 +1598,7 @@ void ServiceNFO::addServiceChar(const char c, int wrapat) {
// Like addServiceChar, but for a whole zero-terminated string // Like addServiceChar, but for a whole zero-terminated string
void ServiceNFO::addServiceString(const char *s, int wrapat) { void ServiceNFO::addServiceString(const char *s, int wrapat) {
while(*s) while(*s)
addServiceChar(*s++, wrapat); addServiceChar(*s++, wrapat);
} }
@@ -1606,15 +1606,15 @@ void ServiceNFO::addServiceString(const char *s, int wrapat) {
// response to the fingerprint for that service. The fingerprint can // response to the fingerprint for that service. The fingerprint can
// be printed when nothing matches the service. You can obtain the // be printed when nothing matches the service. You can obtain the
// fingerprint (if any) via getServiceFingerprint(); // fingerprint (if any) via getServiceFingerprint();
void ServiceNFO::addToServiceFingerprint(const char *probeName, const u8 *resp, void ServiceNFO::addToServiceFingerprint(const char *probeName, const u8 *resp,
int resplen) { int resplen) {
int spaceleft = servicefpalloc - servicefplen; int spaceleft = servicefpalloc - servicefplen;
int servicewrap=74; // Wrap after 74 chars / line int servicewrap=74; // Wrap after 74 chars / line
int respused = MIN(resplen, (o.debugging)? 1300 : 900); // truncate to reasonable size int respused = MIN(resplen, (o.debugging)? 1300 : 900); // truncate to reasonable size
// every char could require \xHH escape, plus there is the matter of // every char could require \xHH escape, plus there is the matter of
// "\nSF:" for each line, plus "%r(probename,probelen,"") Oh, and // "\nSF:" for each line, plus "%r(probename,probelen,"") Oh, and
// the SF-PortXXXX-TCP stuff, etc // the SF-PortXXXX-TCP stuff, etc
int spaceneeded = respused * 5 + strlen(probeName) + 128; int spaceneeded = respused * 5 + strlen(probeName) + 128;
int srcidx; int srcidx;
struct tm *ltime; struct tm *ltime;
time_t timep; time_t timep;
@@ -1642,7 +1642,7 @@ void ServiceNFO::addToServiceFingerprint(const char *probeName, const u8 *resp,
addServiceString(buf, servicewrap); addServiceString(buf, servicewrap);
} }
// Note that we give the total length of the response, even though we // Note that we give the total length of the response, even though we
// may truncate // may truncate
Snprintf(buf, sizeof(buf), "%%r(%s,%X,\"", probeName, resplen); Snprintf(buf, sizeof(buf), "%%r(%s,%X,\"", probeName, resplen);
addServiceString(buf, servicewrap); addServiceString(buf, servicewrap);
@@ -1651,7 +1651,7 @@ void ServiceNFO::addToServiceFingerprint(const char *probeName, const u8 *resp,
for(srcidx=0; srcidx < respused; srcidx++) { for(srcidx=0; srcidx < respused; srcidx++) {
// A run of this can take up to 8 chars: "\n \x20" // A run of this can take up to 8 chars: "\n \x20"
assert( servicefpalloc - servicefplen > 8); assert( servicefpalloc - servicefplen > 8);
if (isalnum((int)resp[srcidx])) if (isalnum((int)resp[srcidx]))
addServiceChar((char) resp[srcidx], servicewrap); addServiceChar((char) resp[srcidx], servicewrap);
else if (resp[srcidx] == '\0') { else if (resp[srcidx] == '\0') {
@@ -1718,7 +1718,7 @@ ServiceProbe *ServiceNFO::currentProbe() {
} else if (probe_state == PROBESTATE_NULLPROBE) { } else if (probe_state == PROBESTATE_NULLPROBE) {
assert(AP->nullProbe); assert(AP->nullProbe);
return AP->nullProbe; return AP->nullProbe;
} else if (probe_state == PROBESTATE_MATCHINGPROBES || } else if (probe_state == PROBESTATE_MATCHINGPROBES ||
probe_state == PROBESTATE_NONMATCHINGPROBES) { probe_state == PROBESTATE_NONMATCHINGPROBES) {
return *current_probe; return *current_probe;
} }
@@ -1733,7 +1733,7 @@ ServiceProbe *ServiceNFO::nextProbe(bool newresp) {
bool dropdown = false; bool dropdown = false;
// This invalidates the probe response string if any // This invalidates the probe response string if any
if (newresp) { if (newresp) {
if (currentresp) free(currentresp); if (currentresp) free(currentresp);
currentresp = NULL; currentresplen = 0; currentresp = NULL; currentresplen = 0;
} }
@@ -1744,10 +1744,10 @@ bool dropdown = false;
// but obviously NULL probe only works with TCP // but obviously NULL probe only works with TCP
if (proto == IPPROTO_TCP && AP->nullProbe) if (proto == IPPROTO_TCP && AP->nullProbe)
return AP->nullProbe; return AP->nullProbe;
// No valid NULL probe -- we'll drop to the next state // No valid NULL probe -- we'll drop to the next state
} }
if (probe_state == PROBESTATE_NULLPROBE) { if (probe_state == PROBESTATE_NULLPROBE) {
// There can only be one (or zero) NULL probe. So now we go through the // There can only be one (or zero) NULL probe. So now we go through the
// list looking for matching probes // list looking for matching probes
@@ -1760,7 +1760,7 @@ bool dropdown = false;
if (!dropdown && current_probe != AP->probes.end()) current_probe++; if (!dropdown && current_probe != AP->probes.end()) current_probe++;
while (current_probe != AP->probes.end()) { while (current_probe != AP->probes.end()) {
// For the first run, we only do probes that match this port number // For the first run, we only do probes that match this port number
if ((proto == (*current_probe)->getProbeProtocol()) && if ((proto == (*current_probe)->getProbeProtocol()) &&
(*current_probe)->portIsProbable(tunnel, portno)) { (*current_probe)->portIsProbable(tunnel, portno)) {
// This appears to be a valid probe. Let's do it! // This appears to be a valid probe. Let's do it!
return *current_probe; return *current_probe;
@@ -1780,7 +1780,7 @@ bool dropdown = false;
// and we better either have no soft match yet, or the soft service match must // and we better either have no soft match yet, or the soft service match must
// be available via this probe. Also, the Probe's rarity must be <= to our // be available via this probe. Also, the Probe's rarity must be <= to our
// version detection intensity level. // version detection intensity level.
if ((proto == (*current_probe)->getProbeProtocol()) && if ((proto == (*current_probe)->getProbeProtocol()) &&
!(*current_probe)->portIsProbable(tunnel, portno) && !(*current_probe)->portIsProbable(tunnel, portno) &&
(*current_probe)->getRarity() <= o.version_intensity && (*current_probe)->getRarity() <= o.version_intensity &&
(!softMatchFound || (*current_probe)->serviceIsPossible(probe_matched))) { (!softMatchFound || (*current_probe)->serviceIsPossible(probe_matched))) {
@@ -1792,7 +1792,7 @@ bool dropdown = false;
// Tried all NONMATCHINGPROBES -- we're finished // Tried all NONMATCHINGPROBES -- we're finished
probe_state = (softMatchFound)? PROBESTATE_FINISHED_SOFTMATCHED : PROBESTATE_FINISHED_NOMATCH; probe_state = (softMatchFound)? PROBESTATE_FINISHED_SOFTMATCHED : PROBESTATE_FINISHED_NOMATCH;
return NULL; return NULL;
} }
fatal("%s called for probe in state (%d)", __func__, (int) probe_state); fatal("%s called for probe in state (%d)", __func__, (int) probe_state);
@@ -1842,7 +1842,7 @@ void ServiceNFO::appendtocurrentproberesponse(const u8 *respstr, int respstrlen)
currentresplen += respstrlen; currentresplen += respstrlen;
} }
// Get the full current response string. Note that this pointer is // Get the full current response string. Note that this pointer is
// INVALIDATED if you call appendtocurrentproberesponse() or nextProbe() // INVALIDATED if you call appendtocurrentproberesponse() or nextProbe()
u8 *ServiceNFO::getcurrentproberesponse(int *respstrlen) { u8 *ServiceNFO::getcurrentproberesponse(int *respstrlen) {
*respstrlen = currentresplen; *respstrlen = currentresplen;
@@ -1928,7 +1928,7 @@ static void adjustPortStateIfNecessary(ServiceNFO *svc) {
oldstate = svc->target->ports.getPortState(svc->portno, svc->proto); oldstate = svc->target->ports.getPortState(svc->portno, svc->proto);
if (oldstate != PORT_OPEN) { if (oldstate != PORT_OPEN) {
svc->target->ports.setPortState(svc->portno, svc->proto, PORT_OPEN); svc->target->ports.setPortState(svc->portno, svc->proto, PORT_OPEN);
if (svc->proto == IPPROTO_TCP) if (svc->proto == IPPROTO_TCP)
svc->target->ports.setStateReason(svc->portno, svc->proto, ER_TCPRESPONSE, 0, NULL); svc->target->ports.setStateReason(svc->portno, svc->proto, ER_TCPRESPONSE, 0, NULL);
if (svc->proto == IPPROTO_UDP) if (svc->proto == IPPROTO_UDP)
svc->target->ports.setStateReason(svc->portno, svc->proto, ER_UDPRESPONSE, 0, NULL); svc->target->ports.setStateReason(svc->portno, svc->proto, ER_UDPRESPONSE, 0, NULL);
@@ -1952,10 +1952,10 @@ static void adjustPortStateIfNecessary(ServiceNFO *svc) {
const u8 *probestring; const u8 *probestring;
int probestringlen; int probestringlen;
// Report data as probes are sent if --version-trace has been requested // Report data as probes are sent if --version-trace has been requested
if (o.debugging > 1 || o.versionTrace()) { if (o.debugging > 1 || o.versionTrace()) {
log_write(LOG_PLAIN, "Service scan sending probe %s to %s:%hu (%s)\n", probe->getName(), svc->target->targetipstr(), svc->portno, proto2ascii_lowercase(svc->proto)); log_write(LOG_PLAIN, "Service scan sending probe %s to %s:%hu (%s)\n", probe->getName(), svc->target->targetipstr(), svc->portno, proto2ascii_lowercase(svc->proto));
} }
assert(probe); assert(probe);
if (probe->isNullProbe()) if (probe->isNullProbe())
@@ -1974,7 +1974,7 @@ static void adjustPortStateIfNecessary(ServiceNFO *svc) {
// and moved to the finished list. If you pass 'true' for alwaysrestart, a // and moved to the finished list. If you pass 'true' for alwaysrestart, a
// new connection will be made even if the previous probe was the NULL probe. // new connection will be made even if the previous probe was the NULL probe.
// You would do this, for example, if the other side has closed the connection. // You would do this, for example, if the other side has closed the connection.
static void startNextProbe(nsock_pool nsp, nsock_iod nsi, ServiceGroup *SG, static void startNextProbe(nsock_pool nsp, nsock_iod nsi, ServiceGroup *SG,
ServiceNFO *svc, bool alwaysrestart) { ServiceNFO *svc, bool alwaysrestart) {
bool isInitial = svc->probe_state == PROBESTATE_INITIAL; bool isInitial = svc->probe_state == PROBESTATE_INITIAL;
ServiceProbe *probe = svc->currentProbe(); ServiceProbe *probe = svc->currentProbe();
@@ -1988,7 +1988,7 @@ static void startNextProbe(nsock_pool nsp, nsock_iod nsi, ServiceGroup *SG,
if (probe) { if (probe) {
svc->currentprobe_exec_time = *nsock_gettimeofday(); svc->currentprobe_exec_time = *nsock_gettimeofday();
send_probe_text(nsp, nsi, svc, probe); send_probe_text(nsp, nsi, svc, probe);
nsock_read(nsp, nsi, servicescan_read_handler, nsock_read(nsp, nsi, servicescan_read_handler,
svc->probe_timemsleft(probe, nsock_gettimeofday()), svc); svc->probe_timemsleft(probe, nsock_gettimeofday()), svc);
} else { } else {
// Should only happen if someone has a highly perverse nmap-service-probes // Should only happen if someone has a highly perverse nmap-service-probes
@@ -2020,14 +2020,14 @@ static void startNextProbe(nsock_pool nsp, nsock_iod nsi, ServiceGroup *SG,
} }
svc->target->TargetSockAddr(&ss, &ss_len); svc->target->TargetSockAddr(&ss, &ss_len);
if (svc->tunnel == SERVICE_TUNNEL_NONE) { if (svc->tunnel == SERVICE_TUNNEL_NONE) {
nsock_connect_tcp(nsp, svc->niod, servicescan_connect_handler, nsock_connect_tcp(nsp, svc->niod, servicescan_connect_handler,
DEFAULT_CONNECT_TIMEOUT, svc, DEFAULT_CONNECT_TIMEOUT, svc,
(struct sockaddr *) &ss, ss_len, (struct sockaddr *) &ss, ss_len,
svc->portno); svc->portno);
} else { } else {
assert(svc->tunnel == SERVICE_TUNNEL_SSL); assert(svc->tunnel == SERVICE_TUNNEL_SSL);
nsock_connect_ssl(nsp, svc->niod, servicescan_connect_handler, nsock_connect_ssl(nsp, svc->niod, servicescan_connect_handler,
DEFAULT_CONNECT_SSL_TIMEOUT, svc, DEFAULT_CONNECT_SSL_TIMEOUT, svc,
(struct sockaddr *) &ss, (struct sockaddr *) &ss,
ss_len, svc->proto, svc->portno, svc->ssl_session); ss_len, svc->proto, svc->portno, svc->ssl_session);
} }
@@ -2037,7 +2037,7 @@ static void startNextProbe(nsock_pool nsp, nsock_iod nsi, ServiceGroup *SG,
svc->currentprobe_exec_time = *nsock_gettimeofday(); svc->currentprobe_exec_time = *nsock_gettimeofday();
send_probe_text(nsp, nsi, svc, probe); send_probe_text(nsp, nsi, svc, probe);
// Now let us read any results // Now let us read any results
nsock_read(nsp, nsi, servicescan_read_handler, nsock_read(nsp, nsi, servicescan_read_handler,
svc->probe_timemsleft(probe, nsock_gettimeofday()), svc); svc->probe_timemsleft(probe, nsock_gettimeofday()), svc);
} }
} else { } else {
@@ -2063,7 +2063,7 @@ static void startNextProbe(nsock_pool nsp, nsock_iod nsi, ServiceGroup *SG,
That is a special case. That is a special case.
*/ */
static int scanThroughTunnel(nsock_pool nsp, nsock_iod nsi, ServiceGroup *SG, static int scanThroughTunnel(nsock_pool nsp, nsock_iod nsi, ServiceGroup *SG,
ServiceNFO *svc) { ServiceNFO *svc) {
if (svc->probe_matched && strncmp(svc->probe_matched, "ssl/", 4) == 0) { if (svc->probe_matched && strncmp(svc->probe_matched, "ssl/", 4) == 0) {
@@ -2079,7 +2079,7 @@ static int scanThroughTunnel(nsock_pool nsp, nsock_iod nsi, ServiceGroup *SG,
return 0; return 0;
} }
if (svc->proto != IPPROTO_TCP || if (svc->proto != IPPROTO_TCP ||
!svc->probe_matched || strcmp(svc->probe_matched, "ssl") != 0) !svc->probe_matched || strcmp(svc->probe_matched, "ssl") != 0)
return 0; // Not SSL return 0; // Not SSL
@@ -2105,7 +2105,7 @@ static void considerPrintingStats(nsock_pool nsp, ServiceGroup *SG) {
if (keyWasPressed()) { if (keyWasPressed()) {
nmap_adjust_loglevel(nsp, o.versionTrace()); nmap_adjust_loglevel(nsp, o.versionTrace());
SG->SPM->printStats(SG->services_finished.size() / SG->SPM->printStats(SG->services_finished.size() /
((double)SG->services_remaining.size() + SG->services_in_progress.size() + ((double)SG->services_remaining.size() + SG->services_in_progress.size() +
SG->services_finished.size()), nsock_gettimeofday()); SG->services_finished.size()), nsock_gettimeofday());
} }
@@ -2123,7 +2123,7 @@ static void handleHostIfDone(ServiceGroup *SG, Target *target) {
std::list<ServiceNFO *>::iterator svcI; std::list<ServiceNFO *>::iterator svcI;
bool found = false; bool found = false;
for(svcI = SG->services_in_progress.begin(); for(svcI = SG->services_in_progress.begin();
svcI != SG->services_in_progress.end(); svcI++) { svcI != SG->services_in_progress.end(); svcI++) {
if ((*svcI)->target == target) { if ((*svcI)->target == target) {
found = true; found = true;
@@ -2131,7 +2131,7 @@ static void handleHostIfDone(ServiceGroup *SG, Target *target) {
} }
} }
for(svcI = SG->services_remaining.begin(); for(svcI = SG->services_remaining.begin();
!found && svcI != SG->services_remaining.end(); svcI++) { !found && svcI != SG->services_remaining.end(); svcI++) {
if ((*svcI)->target == target) { if ((*svcI)->target == target) {
found = true; found = true;
@@ -2226,13 +2226,13 @@ static int launchSomeServiceProbes(nsock_pool nsp, ServiceGroup *SG) {
nsi_set_ipoptions(svc->niod, o.ipoptions, o.ipoptionslen); nsi_set_ipoptions(svc->niod, o.ipoptions, o.ipoptionslen);
svc->target->TargetSockAddr(&ss, &ss_len); svc->target->TargetSockAddr(&ss, &ss_len);
if (svc->proto == IPPROTO_TCP) if (svc->proto == IPPROTO_TCP)
nsock_connect_tcp(nsp, svc->niod, servicescan_connect_handler, nsock_connect_tcp(nsp, svc->niod, servicescan_connect_handler,
DEFAULT_CONNECT_TIMEOUT, svc, DEFAULT_CONNECT_TIMEOUT, svc,
(struct sockaddr *)&ss, ss_len, (struct sockaddr *)&ss, ss_len,
svc->portno); svc->portno);
else { else {
assert(svc->proto == IPPROTO_UDP); assert(svc->proto == IPPROTO_UDP);
nsock_connect_udp(nsp, svc->niod, servicescan_connect_handler, nsock_connect_udp(nsp, svc->niod, servicescan_connect_handler,
svc, (struct sockaddr *) &ss, ss_len, svc, (struct sockaddr *) &ss, ss_len,
svc->portno); svc->portno);
} }
@@ -2297,7 +2297,7 @@ static void servicescan_connect_handler(nsock_pool nsp, nsock_event nse, void *m
error("Got nsock CONNECT response with status %s - aborting this service", nse_status2str(status)); error("Got nsock CONNECT response with status %s - aborting this service", nse_status2str(status));
end_svcprobe(nsp, PROBESTATE_INCOMPLETE, SG, svc, nsi); end_svcprobe(nsp, PROBESTATE_INCOMPLETE, SG, svc, nsi);
break; break;
case NSE_STATUS_KILL: case NSE_STATUS_KILL:
/* User probablby specified host_timeout and so the service scan is /* User probablby specified host_timeout and so the service scan is
* shutting down */ * shutting down */
@@ -2326,10 +2326,10 @@ static void servicescan_write_handler(nsock_pool nsp, nsock_event nse, void *myd
// Check if a status message was requested // Check if a status message was requested
if (keyWasPressed()) { if (keyWasPressed()) {
SG->SPM->printStats(SG->services_finished.size() / SG->SPM->printStats(SG->services_finished.size() /
((double)SG->services_remaining.size() + SG->services_in_progress.size() + ((double)SG->services_remaining.size() + SG->services_in_progress.size() +
SG->services_finished.size()), nsock_gettimeofday()); SG->services_finished.size()), nsock_gettimeofday());
} }
if (svc->target->timedOut(nsock_gettimeofday())) { if (svc->target->timedOut(nsock_gettimeofday())) {
end_svcprobe(nsp, PROBESTATE_INCOMPLETE, SG, svc, nsi); end_svcprobe(nsp, PROBESTATE_INCOMPLETE, SG, svc, nsi);
@@ -2353,13 +2353,13 @@ static void servicescan_write_handler(nsock_pool nsp, nsock_event nse, void *myd
// Uh-oh. Some sort of write failure ... maybe the connection closed // Uh-oh. Some sort of write failure ... maybe the connection closed
// on us unexpectedly? // on us unexpectedly?
if (o.debugging) if (o.debugging)
error("Got nsock WRITE response with status %s - aborting this service", nse_status2str(status)); error("Got nsock WRITE response with status %s - aborting this service", nse_status2str(status));
end_svcprobe(nsp, PROBESTATE_INCOMPLETE, SG, svc, nsi); end_svcprobe(nsp, PROBESTATE_INCOMPLETE, SG, svc, nsi);
// We may have room for more pr0bes! // We may have room for more pr0bes!
launchSomeServiceProbes(nsp, SG); launchSomeServiceProbes(nsp, SG);
return; return;
} }
@@ -2406,8 +2406,8 @@ static void servicescan_read_handler(nsock_pool nsp, nsock_event nse, void *myda
log_write(LOG_PLAIN, "Service scan match (Probe %s matched with %s line %d): %s:%hu is %s%s. Version: |%s|%s|%s|\n", log_write(LOG_PLAIN, "Service scan match (Probe %s matched with %s line %d): %s:%hu is %s%s. Version: |%s|%s|%s|\n",
probe->getName(), (*probe->fallbacks[fallbackDepth]).getName(), probe->getName(), (*probe->fallbacks[fallbackDepth]).getName(),
MD->lineno, MD->lineno,
svc->target->targetipstr(), svc->portno, (svc->tunnel == SERVICE_TUNNEL_SSL)? "SSL/" : "", svc->target->targetipstr(), svc->portno, (svc->tunnel == SERVICE_TUNNEL_SSL)? "SSL/" : "",
MD->serviceName, (MD->product)? MD->product : "", (MD->version)? MD->version : "", MD->serviceName, (MD->product)? MD->product : "", (MD->version)? MD->version : "",
(MD->info)? MD->info : ""); (MD->info)? MD->info : "");
else else
log_write(LOG_PLAIN, "Service scan %s match (Probe %s matched with %s line %d): %s:%hu is %s%s\n", log_write(LOG_PLAIN, "Service scan %s match (Probe %s matched with %s line %d): %s:%hu is %s%s\n",
@@ -2419,15 +2419,15 @@ static void servicescan_read_handler(nsock_pool nsp, nsock_event nse, void *myda
svc->probe_matched = MD->serviceName; svc->probe_matched = MD->serviceName;
if (MD->product) if (MD->product)
Strncpy(svc->product_matched, MD->product, sizeof(svc->product_matched)); Strncpy(svc->product_matched, MD->product, sizeof(svc->product_matched));
if (MD->version) if (MD->version)
Strncpy(svc->version_matched, MD->version, sizeof(svc->version_matched)); Strncpy(svc->version_matched, MD->version, sizeof(svc->version_matched));
if (MD->info) if (MD->info)
Strncpy(svc->extrainfo_matched, MD->info, sizeof(svc->extrainfo_matched)); Strncpy(svc->extrainfo_matched, MD->info, sizeof(svc->extrainfo_matched));
if (MD->hostname) if (MD->hostname)
Strncpy(svc->hostname_matched, MD->hostname, sizeof(svc->hostname_matched)); Strncpy(svc->hostname_matched, MD->hostname, sizeof(svc->hostname_matched));
if (MD->ostype) if (MD->ostype)
Strncpy(svc->ostype_matched, MD->ostype, sizeof(svc->ostype_matched)); Strncpy(svc->ostype_matched, MD->ostype, sizeof(svc->ostype_matched));
if (MD->devicetype) if (MD->devicetype)
Strncpy(svc->devicetype_matched, MD->devicetype, sizeof(svc->devicetype_matched)); Strncpy(svc->devicetype_matched, MD->devicetype, sizeof(svc->devicetype_matched));
if (MD->cpe_a) if (MD->cpe_a)
Strncpy(svc->cpe_a_matched, MD->cpe_a, sizeof(svc->cpe_a_matched)); Strncpy(svc->cpe_a_matched, MD->cpe_a, sizeof(svc->cpe_a_matched));
@@ -2437,9 +2437,9 @@ static void servicescan_read_handler(nsock_pool nsp, nsock_event nse, void *myda
Strncpy(svc->cpe_o_matched, MD->cpe_o, sizeof(svc->cpe_o_matched)); Strncpy(svc->cpe_o_matched, MD->cpe_o, sizeof(svc->cpe_o_matched));
svc->softMatchFound = MD->isSoft; svc->softMatchFound = MD->isSoft;
if (!svc->softMatchFound) { if (!svc->softMatchFound) {
// We might be able to continue scan through a tunnel protocol // We might be able to continue scan through a tunnel protocol
// like SSL // like SSL
if (scanThroughTunnel(nsp, nsi, SG, svc) == 0) if (scanThroughTunnel(nsp, nsi, SG, svc) == 0)
end_svcprobe(nsp, PROBESTATE_FINISHED_HARDMATCHED, SG, svc, nsi); end_svcprobe(nsp, PROBESTATE_FINISHED_HARDMATCHED, SG, svc, nsi);
} }
} }
@@ -2452,7 +2452,7 @@ static void servicescan_read_handler(nsock_pool nsp, nsock_event nse, void *myda
// to timeout. For now I'll limit it to 4096 bytes just to // to timeout. For now I'll limit it to 4096 bytes just to
// avoid reading megs from services like chargen. But better // avoid reading megs from services like chargen. But better
// approach is needed. // approach is needed.
if (svc->probe_timemsleft(probe) > 0 && readstrlen < 4096) { if (svc->probe_timemsleft(probe) > 0 && readstrlen < 4096) {
nsock_read(nsp, nsi, servicescan_read_handler, svc->probe_timemsleft(probe), svc); nsock_read(nsp, nsi, servicescan_read_handler, svc->probe_timemsleft(probe), svc);
} else { } else {
// Failed -- lets go to the next probe. // Failed -- lets go to the next probe.
@@ -2468,17 +2468,17 @@ static void servicescan_read_handler(nsock_pool nsp, nsock_event nse, void *myda
readstr = svc->getcurrentproberesponse(&readstrlen); readstr = svc->getcurrentproberesponse(&readstrlen);
if (readstrlen > 0) if (readstrlen > 0)
svc->addToServiceFingerprint(svc->currentProbe()->getName(), readstr, svc->addToServiceFingerprint(svc->currentProbe()->getName(), readstr,
readstrlen); readstrlen);
startNextProbe(nsp, nsi, SG, svc, false); startNextProbe(nsp, nsi, SG, svc, false);
} else if (status == NSE_STATUS_EOF) { } else if (status == NSE_STATUS_EOF) {
// The jerk closed on us during read request! // The jerk closed on us during read request!
// If this was during the NULL probe, let's (for now) assume // If this was during the NULL probe, let's (for now) assume
// the port is TCP wrapped. Otherwise, we'll treat it as a nomatch // the port is TCP wrapped. Otherwise, we'll treat it as a nomatch
readstr = svc->getcurrentproberesponse(&readstrlen); readstr = svc->getcurrentproberesponse(&readstrlen);
if (readstrlen > 0) if (readstrlen > 0)
svc->addToServiceFingerprint(svc->currentProbe()->getName(), readstr, svc->addToServiceFingerprint(svc->currentProbe()->getName(), readstr,
readstrlen); readstrlen);
if (probe->isNullProbe() && readstrlen == 0) { if (probe->isNullProbe() && readstrlen == 0) {
// TODO: Perhaps should do further verification before making this assumption // TODO: Perhaps should do further verification before making this assumption
@@ -2494,7 +2494,7 @@ static void servicescan_read_handler(nsock_pool nsp, nsock_event nse, void *myda
int err = nse_errorcode(nse); int err = nse_errorcode(nse);
switch(err) { switch(err) {
case ECONNRESET: case ECONNRESET:
case ECONNREFUSED: // weird to get this on a connected socket (shrug) but case ECONNREFUSED: // weird to get this on a connected socket (shrug) but
// BSD sometimes gives it // BSD sometimes gives it
case ECONNABORTED: case ECONNABORTED:
// Jerk hung up on us. Probably didn't like our probe. We treat it as with EOF above. // Jerk hung up on us. Probably didn't like our probe. We treat it as with EOF above.
@@ -2502,7 +2502,7 @@ static void servicescan_read_handler(nsock_pool nsp, nsock_event nse, void *myda
// TODO: Perhaps should do further verification before making this assumption // TODO: Perhaps should do further verification before making this assumption
end_svcprobe(nsp, PROBESTATE_FINISHED_TCPWRAPPED, SG, svc, nsi); end_svcprobe(nsp, PROBESTATE_FINISHED_TCPWRAPPED, SG, svc, nsi);
} else { } else {
// Perhaps this service didn't like the particular probe text. We'll try the // Perhaps this service didn't like the particular probe text. We'll try the
// next one // next one
startNextProbe(nsp, nsi, SG, svc, true); startNextProbe(nsp, nsi, SG, svc, true);
} }
@@ -2537,14 +2537,14 @@ static void servicescan_read_handler(nsock_pool nsp, nsock_event nse, void *myda
socket_strerror(err)); socket_strerror(err));
} }
} else if (status == NSE_STATUS_KILL) { } else if (status == NSE_STATUS_KILL) {
/* User probablby specified host_timeout and so the service scan is /* User probablby specified host_timeout and so the service scan is
shutting down */ shutting down */
end_svcprobe(nsp, PROBESTATE_INCOMPLETE, SG, svc, nsi); end_svcprobe(nsp, PROBESTATE_INCOMPLETE, SG, svc, nsi);
return; return;
} else { } else {
fatal("Unexpected status (%d) in NSE_TYPE_READ callback.", (int) status); fatal("Unexpected status (%d) in NSE_TYPE_READ callback.", (int) status);
} }
// We may have room for more pr0bes! // We may have room for more pr0bes!
launchSomeServiceProbes(nsp, SG); launchSomeServiceProbes(nsp, SG);
return; return;
@@ -2584,15 +2584,15 @@ std::list<ServiceNFO *>::iterator svc;
cpe.push_back((*svc)->cpe_o_matched); cpe.push_back((*svc)->cpe_o_matched);
(*svc)->target->ports.setServiceProbeResults((*svc)->portno, (*svc)->proto, (*svc)->target->ports.setServiceProbeResults((*svc)->portno, (*svc)->proto,
(*svc)->probe_state, (*svc)->probe_state,
(*svc)->probe_matched, (*svc)->probe_matched,
(*svc)->tunnel, (*svc)->tunnel,
*(*svc)->product_matched? (*svc)->product_matched : NULL, *(*svc)->product_matched? (*svc)->product_matched : NULL,
*(*svc)->version_matched? (*svc)->version_matched : NULL, *(*svc)->version_matched? (*svc)->version_matched : NULL,
*(*svc)->extrainfo_matched? (*svc)->extrainfo_matched : NULL, *(*svc)->extrainfo_matched? (*svc)->extrainfo_matched : NULL,
*(*svc)->hostname_matched? (*svc)->hostname_matched : NULL, *(*svc)->hostname_matched? (*svc)->hostname_matched : NULL,
*(*svc)->ostype_matched? (*svc)->ostype_matched : NULL, *(*svc)->ostype_matched? (*svc)->ostype_matched : NULL,
*(*svc)->devicetype_matched? (*svc)->devicetype_matched : NULL, *(*svc)->devicetype_matched? (*svc)->devicetype_matched : NULL,
(cpe.size() > 0) ? &cpe : NULL, (cpe.size() > 0) ? &cpe : NULL,
shouldWePrintFingerprint(*svc) ? (*svc)->getServiceFingerprint(NULL) : NULL); shouldWePrintFingerprint(*svc) ? (*svc)->getServiceFingerprint(NULL) : NULL);
} else { } else {
@@ -2614,7 +2614,7 @@ static void startTimeOutClocks(ServiceGroup *SG) {
struct timeval tv; struct timeval tv;
gettimeofday(&tv, NULL); gettimeofday(&tv, NULL);
for(svcI = SG->services_remaining.begin(); for(svcI = SG->services_remaining.begin();
svcI != SG->services_remaining.end(); svcI++) { svcI != SG->services_remaining.end(); svcI++) {
target = (*svcI)->target; target = (*svcI)->target;
if (!target->timeOutClockRunning()) if (!target->timeOutClockRunning())
@@ -2642,7 +2642,7 @@ static void remove_excluded_ports(AllProbes *AP, ServiceGroup *SG) {
IPPROTO2STR(svc->proto)); IPPROTO2STR(svc->proto));
svc->target->ports.setServiceProbeResults(svc->portno, svc->proto, svc->target->ports.setServiceProbeResults(svc->portno, svc->proto,
PROBESTATE_EXCLUDED, NULL, PROBESTATE_EXCLUDED, NULL,
SERVICE_TUNNEL_NONE, SERVICE_TUNNEL_NONE,
"Excluded from version scan", NULL, "Excluded from version scan", NULL,
NULL, NULL, NULL, NULL, NULL, NULL); NULL, NULL, NULL, NULL, NULL, NULL);
@@ -2688,7 +2688,7 @@ int service_scan(std::vector<Target *> &Targets) {
delete SG; delete SG;
return 1; return 1;
} }
gettimeofday(&starttv, NULL); gettimeofday(&starttv, NULL);
if (o.verbose) { if (o.verbose) {
char targetstr[128]; char targetstr[128];
@@ -2697,9 +2697,9 @@ int service_scan(std::vector<Target *> &Targets) {
(*(Targets.begin()))->NameIP(targetstr, sizeof(targetstr)); (*(Targets.begin()))->NameIP(targetstr, sizeof(targetstr));
} else Snprintf(targetstr, sizeof(targetstr), "%u hosts", (unsigned) Targets.size()); } else Snprintf(targetstr, sizeof(targetstr), "%u hosts", (unsigned) Targets.size());
log_write(LOG_STDOUT, "Scanning %u %s on %s\n", log_write(LOG_STDOUT, "Scanning %u %s on %s\n",
(unsigned) SG->services_remaining.size(), (unsigned) SG->services_remaining.size(),
(SG->services_remaining.size() == 1)? "service" : "services", (SG->services_remaining.size() == 1)? "service" : "services",
targetstr); targetstr);
} }
@@ -2741,11 +2741,11 @@ int service_scan(std::vector<Target *> &Targets) {
char additional_info[128]; char additional_info[128];
if (SG->num_hosts_timedout == 0) if (SG->num_hosts_timedout == 0)
Snprintf(additional_info, sizeof(additional_info), "%u %s on %u %s", Snprintf(additional_info, sizeof(additional_info), "%u %s on %u %s",
(unsigned) SG->services_finished.size(), (unsigned) SG->services_finished.size(),
(SG->services_finished.size() == 1)? "service" : "services", (SG->services_finished.size() == 1)? "service" : "services",
(unsigned) Targets.size(), (Targets.size() == 1)? "host" : "hosts"); (unsigned) Targets.size(), (Targets.size() == 1)? "host" : "hosts");
else Snprintf(additional_info, sizeof(additional_info), "%u %s timed out", else Snprintf(additional_info, sizeof(additional_info), "%u %s timed out",
SG->num_hosts_timedout, SG->num_hosts_timedout,
(SG->num_hosts_timedout == 1)? "host" : "hosts"); (SG->num_hosts_timedout == 1)? "host" : "hosts");
SG->SPM->endTask(NULL, additional_info); SG->SPM->endTask(NULL, additional_info);
} }

View File

@@ -241,7 +241,7 @@ class ServiceProbeMatch {
// are sufficient). Returns zero for success. If no template is available // are sufficient). Returns zero for success. If no template is available
// for a string, that string will have zero length after the function // for a string, that string will have zero length after the function
// call (assuming the corresponding length passed in is at least 1) // call (assuming the corresponding length passed in is at least 1)
int getVersionStr(const u8 *subject, int subjectlen, int *ovector, int getVersionStr(const u8 *subject, int subjectlen, int *ovector,
int nummatches, char *product, int productlen, int nummatches, char *product, int productlen,
char *version, int versionlen, char *info, int infolen, char *version, int versionlen, char *info, int infolen,
char *hostname, int hostnamelen, char *ostype, int ostypelen, char *hostname, int hostnamelen, char *ostype, int ostypelen,
@@ -273,16 +273,16 @@ class ServiceProbe {
// (giving the line number) if it fails to parse the string. // (giving the line number) if it fails to parse the string.
void setProbeDetails(char *pd, int lineno); void setProbeDetails(char *pd, int lineno);
// obtains the probe string (in raw binary form) and the length. The string will be // obtains the probe string (in raw binary form) and the length. The string will be
// NUL-terminated, but there may be other \0 in the string, so the termination is only // NUL-terminated, but there may be other \0 in the string, so the termination is only
// done for ease of printing ASCII probes in debugging cases. // done for ease of printing ASCII probes in debugging cases.
const u8 *getProbeString(int *stringlen) { *stringlen = probestringlen; return probestring; } const u8 *getProbeString(int *stringlen) { *stringlen = probestringlen; return probestring; }
void setProbeString(const u8 *ps, int stringlen); void setProbeString(const u8 *ps, int stringlen);
/* Protocols are IPPROTO_TCP and IPPROTO_UDP */ /* Protocols are IPPROTO_TCP and IPPROTO_UDP */
u8 getProbeProtocol() { u8 getProbeProtocol() {
assert(probeprotocol == IPPROTO_TCP || probeprotocol == IPPROTO_UDP); assert(probeprotocol == IPPROTO_TCP || probeprotocol == IPPROTO_UDP);
return probeprotocol; return probeprotocol;
} }
void setProbeProtocol(u8 protocol) { probeprotocol = protocol; } void setProbeProtocol(u8 protocol) { probeprotocol = protocol; }
@@ -336,7 +336,7 @@ class ServiceProbe {
ServiceProbe *fallbacks[MAXFALLBACKS+1]; ServiceProbe *fallbacks[MAXFALLBACKS+1];
private: private:
void setPortVector(std::vector<u16> *portv, const char *portstr, void setPortVector(std::vector<u16> *portv, const char *portstr,
int lineno); int lineno);
char *probename; char *probename;
@@ -372,7 +372,7 @@ public:
int isExcluded(unsigned short port, int proto); int isExcluded(unsigned short port, int proto);
bool excluded_seen; bool excluded_seen;
struct scan_lists excludedports; struct scan_lists excludedports;
static AllProbes *service_scan_init(void); static AllProbes *service_scan_init(void);
static void service_scan_free(void); static void service_scan_free(void);
static int check_excluded_port(unsigned short port, int proto); static int check_excluded_port(unsigned short port, int proto);

View File

@@ -140,7 +140,7 @@
#define SERVICE_TABLE_SIZE 1024 #define SERVICE_TABLE_SIZE 1024
/* just flags to indicate whether a particular port number should get tcp /* just flags to indicate whether a particular port number should get tcp
* scanned, udp scanned, or both * scanned, udp scanned, or both
*/ */
#define SCAN_TCP_PORT (1 << 0) #define SCAN_TCP_PORT (1 << 0)

View File

@@ -66,7 +66,7 @@ struct ip
u_int8_t ip_hl:4; /* header length */ u_int8_t ip_hl:4; /* header length */
#else #else
u_int8_t ip_hl:4; /* header length */ u_int8_t ip_hl:4; /* header length */
u_int8_t ip_v:4; /* version */ u_int8_t ip_v:4; /* version */
#endif #endif
u_int8_t ip_tos; /* type of service */ u_int8_t ip_tos; /* type of service */
u_short ip_len; /* total length */ u_short ip_len; /* total length */

View File

@@ -156,14 +156,14 @@ static void arpping(Target *hostbatch[], int num_hosts) {
if (!hostbatch[targetno]->SrcMACAddress()) { if (!hostbatch[targetno]->SrcMACAddress()) {
bool islocal = islocalhost(hostbatch[targetno]->TargetSockAddr()); bool islocal = islocalhost(hostbatch[targetno]->TargetSockAddr());
if (islocal) { if (islocal) {
log_write(LOG_STDOUT|LOG_NORMAL, log_write(LOG_STDOUT|LOG_NORMAL,
"ARP ping: Considering %s UP because it is a local IP, despite no MAC address for device %s\n", "ARP ping: Considering %s UP because it is a local IP, despite no MAC address for device %s\n",
hostbatch[targetno]->NameIP(), hostbatch[targetno]->deviceName()); hostbatch[targetno]->NameIP(), hostbatch[targetno]->deviceName());
hostbatch[targetno]->flags = HOST_UP; hostbatch[targetno]->flags = HOST_UP;
} else { } else {
log_write(LOG_STDOUT|LOG_NORMAL, log_write(LOG_STDOUT|LOG_NORMAL,
"ARP ping: Considering %s DOWN because no MAC address found for device %s.\n", "ARP ping: Considering %s DOWN because no MAC address found for device %s.\n",
hostbatch[targetno]->NameIP(), hostbatch[targetno]->NameIP(),
hostbatch[targetno]->deviceName()); hostbatch[targetno]->deviceName());
hostbatch[targetno]->flags = HOST_DOWN; hostbatch[targetno]->flags = HOST_DOWN;
} }
@@ -194,7 +194,7 @@ void returnhost(HostGroupState *hs) {
/* Is the host passed as Target to be excluded? Much of this logic had /* Is the host passed as Target to be excluded? Much of this logic had
to be rewritten from wam's original code to allow for the objects */ to be rewritten from wam's original code to allow for the objects */
static int hostInExclude(struct sockaddr *checksock, size_t checksocklen, static int hostInExclude(struct sockaddr *checksock, size_t checksocklen,
const addrset *exclude_group) { const addrset *exclude_group) {
if (exclude_group == NULL) if (exclude_group == NULL)
return 0; return 0;
@@ -256,7 +256,7 @@ int dumpExclude(addrset *exclude_group) {
return 1; return 1;
} }
static void massping(Target *hostbatch[], int num_hosts, struct scan_lists *ports) { static void massping(Target *hostbatch[], int num_hosts, struct scan_lists *ports) {
static struct timeout_info group_to = { 0, 0, 0 }; static struct timeout_info group_to = { 0, 0, 0 };
static char prev_device_name[16] = ""; static char prev_device_name[16] = "";
@@ -658,9 +658,9 @@ static void refresh_hostbatch(HostGroupState *hs, const addrset *exclude_group,
/* First I'll do the ARP ping if all of the machines in the group are /* First I'll do the ARP ping if all of the machines in the group are
directly connected over ethernet. I may need the MAC addresses directly connected over ethernet. I may need the MAC addresses
later anyway. */ later anyway. */
if (hs->hostbatch[0]->ifType() == devt_ethernet && if (hs->hostbatch[0]->ifType() == devt_ethernet &&
hs->hostbatch[0]->af() == AF_INET && hs->hostbatch[0]->af() == AF_INET &&
hs->hostbatch[0]->directlyConnected() && hs->hostbatch[0]->directlyConnected() &&
o.sendpref != PACKET_SEND_IP_STRONG && o.sendpref != PACKET_SEND_IP_STRONG &&
(pingtype == PINGTYPE_ARP || o.implicitARPPing)) { (pingtype == PINGTYPE_ARP || o.implicitARPPing)) {
arpping(hs->hostbatch, hs->current_batch_sz); arpping(hs->hostbatch, hs->current_batch_sz);
@@ -679,13 +679,13 @@ static void refresh_hostbatch(HostGroupState *hs, const addrset *exclude_group,
} }
gettimeofday(&now, NULL); gettimeofday(&now, NULL);
if ((o.sendpref & PACKET_SEND_ETH) && if ((o.sendpref & PACKET_SEND_ETH) &&
hs->hostbatch[0]->ifType() == devt_ethernet) { hs->hostbatch[0]->ifType() == devt_ethernet) {
for (i=0; i < hs->current_batch_sz; i++) { for (i=0; i < hs->current_batch_sz; i++) {
if (!(hs->hostbatch[i]->flags & HOST_DOWN) && if (!(hs->hostbatch[i]->flags & HOST_DOWN) &&
!hs->hostbatch[i]->timedOut(&now)) { !hs->hostbatch[i]->timedOut(&now)) {
if (!setTargetNextHopMAC(hs->hostbatch[i])) { if (!setTargetNextHopMAC(hs->hostbatch[i])) {
fatal("%s: Failed to determine dst MAC address for target %s", fatal("%s: Failed to determine dst MAC address for target %s",
__func__, hs->hostbatch[i]->NameIP()); __func__, hs->hostbatch[i]->NameIP());
} }
} }

View File

@@ -1,7 +1,7 @@
/*************************************************************************** /***************************************************************************
* targets.h -- Functions relating to "ping scanning" as well as * * targets.h -- Functions relating to "ping scanning" as well as *
* determining the exact IPs to hit based on CIDR and other input formats. * * determining the exact IPs to hit based on CIDR and other input formats. *
* * * *
***********************IMPORTANT NMAP LICENSE TERMS************************ ***********************IMPORTANT NMAP LICENSE TERMS************************
* * * *
@@ -144,7 +144,7 @@
#include <unistd.h> #include <unistd.h>
#endif #endif
#ifdef HAVE_SYS_PARAM_H #ifdef HAVE_SYS_PARAM_H
#include <sys/param.h> /* Defines MAXHOSTNAMELEN on BSD*/ #include <sys/param.h> /* Defines MAXHOSTNAMELEN on BSD*/
#endif #endif
@@ -224,7 +224,7 @@ public:
/* Ports is the list of ports the user asked to be scanned (0 terminated), /* Ports is the list of ports the user asked to be scanned (0 terminated),
you can just pass NULL (it is only a stupid optimization that needs it) */ you can just pass NULL (it is only a stupid optimization that needs it) */
Target *nexthost(HostGroupState *hs,const addrset *exclude_group, Target *nexthost(HostGroupState *hs,const addrset *exclude_group,
struct scan_lists *ports, int pingtype); struct scan_lists *ports, int pingtype);
int load_exclude_file(addrset *exclude_group, FILE *fp); int load_exclude_file(addrset *exclude_group, FILE *fp);
int load_exclude_string(addrset *exclude_group, const char *s); int load_exclude_string(addrset *exclude_group, const char *s);

30
tcpip.h
View File

@@ -253,7 +253,7 @@ class PacketTrace {
sock may be a sockaddr_in or sockaddr_in6. The return code of sock may be a sockaddr_in or sockaddr_in6. The return code of
connect is passed in connectrc. If the return code is -1, get the connect is passed in connectrc. If the return code is -1, get the
errno and pass that as connect_errno. */ errno and pass that as connect_errno. */
static void traceConnect(u8 proto, const struct sockaddr *sock, static void traceConnect(u8 proto, const struct sockaddr *sock,
int socklen, int connectrc, int connect_errno, int socklen, int connectrc, int connect_errno,
const struct timeval *now); const struct timeval *now);
/* Takes an ARP PACKET (including ethernet header) and prints it if /* Takes an ARP PACKET (including ethernet header) and prints it if
@@ -288,7 +288,7 @@ class PacketCounter {
/* Prototypes */ /* Prototypes */
/* Converts an IP address given in a sockaddr_storage to an IPv4 or /* Converts an IP address given in a sockaddr_storage to an IPv4 or
IPv6 IP address string. Since a static buffer is returned, this is IPv6 IP address string. Since a static buffer is returned, this is
not thread-safe and can only be used once in calls like printf() not thread-safe and can only be used once in calls like printf()
*/ */
const char *inet_socktop(struct sockaddr_storage *ss); const char *inet_socktop(struct sockaddr_storage *ss);
@@ -320,7 +320,7 @@ int send_ip_packet(int sd, const struct eth_nfo *eth,
actually sent by this function. Caller must delete the buffer when actually sent by this function. Caller must delete the buffer when
finished with the packet. The packet length is returned in finished with the packet. The packet length is returned in
packetlen, which must be a valid int pointer. */ packetlen, which must be a valid int pointer. */
u8 *build_ip_raw(const struct in_addr *source, const struct in_addr *victim, u8 *build_ip_raw(const struct in_addr *source, const struct in_addr *victim,
u8 proto, u8 proto,
int ttl, u16 ipid, u8 tos, bool df, int ttl, u16 ipid, u8 tos, bool df,
const u8* ipopt, int ipoptlen, const u8* ipopt, int ipoptlen,
@@ -357,7 +357,7 @@ u8 *build_tcp_raw_ipv6(const struct in6_addr *source,
/* Build and send a raw tcp packet. If TTL is -1, a partially random /* Build and send a raw tcp packet. If TTL is -1, a partially random
(but likely large enough) one is chosen */ (but likely large enough) one is chosen */
int send_tcp_raw( int sd, const struct eth_nfo *eth, int send_tcp_raw( int sd, const struct eth_nfo *eth,
const struct in_addr *source, const struct in_addr *victim, const struct in_addr *source, const struct in_addr *victim,
int ttl, bool df, int ttl, bool df,
u8* ipopt, int ipoptlen, u8* ipopt, int ipoptlen,
u16 sport, u16 dport, u16 sport, u16 dport,
@@ -365,9 +365,9 @@ int send_tcp_raw( int sd, const struct eth_nfo *eth,
u8 *options, int optlen, u8 *options, int optlen,
const char *data, u16 datalen); const char *data, u16 datalen);
int send_tcp_raw_decoys( int sd, const struct eth_nfo *eth, int send_tcp_raw_decoys( int sd, const struct eth_nfo *eth,
const struct in_addr *victim, const struct in_addr *victim,
int ttl, bool df, int ttl, bool df,
u8* ipopt, int ipoptlen, u8* ipopt, int ipoptlen,
u16 sport, u16 dport, u16 sport, u16 dport,
u32 seq, u32 ack, u8 reserved, u8 flags, u16 window, u16 urp, u32 seq, u32 ack, u8 reserved, u8 flags, u16 window, u16 urp,
@@ -381,11 +381,11 @@ int send_tcp_raw_decoys( int sd, const struct eth_nfo *eth,
finished with the packet. The packet length is returned in finished with the packet. The packet length is returned in
packetlen, which must be a valid int pointer. */ packetlen, which must be a valid int pointer. */
u8 *build_udp_raw(const struct in_addr *source, const struct in_addr *victim, u8 *build_udp_raw(const struct in_addr *source, const struct in_addr *victim,
int ttl, u16 ipid, u8 tos, bool df, int ttl, u16 ipid, u8 tos, bool df,
u8* ipopt, int ipoptlen, u8* ipopt, int ipoptlen,
u16 sport, u16 dport, u16 sport, u16 dport,
const char *data, u16 datalen, const char *data, u16 datalen,
u32 *packetlen); u32 *packetlen);
u8 *build_udp_raw_ipv6(const struct in6_addr *source, u8 *build_udp_raw_ipv6(const struct in6_addr *source,
const struct in6_addr *victim, u8 tc, u32 flowlabel, const struct in6_addr *victim, u8 tc, u32 flowlabel,
@@ -399,7 +399,7 @@ int send_udp_raw( int sd, const struct eth_nfo *eth,
u16 sport, u16 dport, u16 sport, u16 dport,
const char *data, u16 datalen); const char *data, u16 datalen);
int send_udp_raw_decoys( int sd, const struct eth_nfo *eth, int send_udp_raw_decoys( int sd, const struct eth_nfo *eth,
const struct in_addr *victim, const struct in_addr *victim,
int ttl, u16 ipid, int ttl, u16 ipid,
u8* ipops, int ip, u8* ipops, int ip,
@@ -434,7 +434,7 @@ u8 *build_sctp_raw_ipv6(const struct in6_addr *source,
returned in packetlen, which must be a valid int pointer. The returned in packetlen, which must be a valid int pointer. The
id/seq will be converted to network byte order (if it differs from id/seq will be converted to network byte order (if it differs from
HBO) */ HBO) */
u8 *build_icmp_raw(const struct in_addr *source, const struct in_addr *victim, u8 *build_icmp_raw(const struct in_addr *source, const struct in_addr *victim,
int ttl, u16 ipid, u8 tos, bool df, int ttl, u16 ipid, u8 tos, bool df,
u8* ipopt, int ipoptlen, u8* ipopt, int ipoptlen,
u16 seq, unsigned short id, u8 ptype, u8 pcode, u16 seq, unsigned short id, u8 ptype, u8 pcode,
@@ -452,7 +452,7 @@ u8 *build_icmpv6_raw(const struct in6_addr *source,
finished with the packet. The packet length is returned in packetlen, finished with the packet. The packet length is returned in packetlen,
which must be a valid int pointer. which must be a valid int pointer.
*/ */
u8 *build_igmp_raw(const struct in_addr *source, const struct in_addr *victim, u8 *build_igmp_raw(const struct in_addr *source, const struct in_addr *victim,
int ttl, u16 ipid, u8 tos, bool df, int ttl, u16 ipid, u8 tos, bool df,
u8* ipopt, int ipoptlen, u8* ipopt, int ipoptlen,
u8 ptype, u8 pcode, u8 ptype, u8 pcode,
@@ -497,7 +497,7 @@ char *getFinalPacketStats(char *buf, int buflen);
directly connected to the src host running Nmap. If it is, set the MAC. directly connected to the src host running Nmap. If it is, set the MAC.
This function returns 0 if it ends up setting the MAC, nonzero otherwise This function returns 0 if it ends up setting the MAC, nonzero otherwise
*/ */
int setTargetMACIfAvailable(Target *target, struct link_header *linkhdr, int setTargetMACIfAvailable(Target *target, struct link_header *linkhdr,
const struct sockaddr_storage *src, int overwrite); const struct sockaddr_storage *src, int overwrite);
@@ -522,7 +522,7 @@ int get_link_offset(char *device);
filled with the time that packet was captured from the wire by filled with the time that packet was captured from the wire by
pcap. If linknfo is not NULL, lnknfo->headerlen and pcap. If linknfo is not NULL, lnknfo->headerlen and
lnkinfo->header will be filled with the appropriate values. */ lnkinfo->header will be filled with the appropriate values. */
char *readipv4_pcap(pcap_t *pd, unsigned int *len, long to_usec, char *readipv4_pcap(pcap_t *pd, unsigned int *len, long to_usec,
struct timeval *rcvdtime, struct link_header *linknfo, bool validate); struct timeval *rcvdtime, struct link_header *linknfo, bool validate);
char *readip_pcap(pcap_t *pd, unsigned int *len, long to_usec, char *readip_pcap(pcap_t *pd, unsigned int *len, long to_usec,

View File

@@ -141,7 +141,7 @@ void initialize_timeout_info(struct timeout_info *to) {
to->timeout = o.initialRttTimeout() * 1000; to->timeout = o.initialRttTimeout() * 1000;
} }
/* Adjust our timeout values based on the time the latest probe took for a /* Adjust our timeout values based on the time the latest probe took for a
response. We update our RTT averages, etc. */ response. We update our RTT averages, etc. */
void adjust_timeouts(struct timeval sent, struct timeout_info *to) { void adjust_timeouts(struct timeval sent, struct timeout_info *to) {
struct timeval received; struct timeval received;
@@ -155,8 +155,8 @@ void adjust_timeouts(struct timeval sent, struct timeout_info *to) {
the receive time too (which could be because it was received a while the receive time too (which could be because it was received a while
back or it could be for efficiency because the caller already knows back or it could be for efficiency because the caller already knows
the current time */ the current time */
void adjust_timeouts2(const struct timeval *sent, void adjust_timeouts2(const struct timeval *sent,
const struct timeval *received, const struct timeval *received,
struct timeout_info *to) { struct timeout_info *to) {
long delta = 0; long delta = 0;
@@ -200,16 +200,16 @@ void adjust_timeouts2(const struct timeval *sent,
} }
to->srtt += rttdelta >> 3; to->srtt += rttdelta >> 3;
to->rttvar += (ABS(rttdelta) - to->rttvar) >> 2; to->rttvar += (ABS(rttdelta) - to->rttvar) >> 2;
to->timeout = to->srtt + (to->rttvar << 2); to->timeout = to->srtt + (to->rttvar << 2);
} }
if (to->rttvar > 2300000) { if (to->rttvar > 2300000) {
error("RTTVAR has grown to over 2.3 seconds, decreasing to 2.0"); error("RTTVAR has grown to over 2.3 seconds, decreasing to 2.0");
to->rttvar = 2000000; to->rttvar = 2000000;
} }
/* It hurts to do this ... it really does ... but otherwise we are being /* It hurts to do this ... it really does ... but otherwise we are being
too risky */ too risky */
to->timeout = box(o.minRttTimeout() * 1000, o.maxRttTimeout() * 1000, to->timeout = box(o.minRttTimeout() * 1000, o.maxRttTimeout() * 1000,
to->timeout); to->timeout);
if (o.scan_delay) if (o.scan_delay)
@@ -219,7 +219,7 @@ void adjust_timeouts2(const struct timeval *sent,
log_write(LOG_STDOUT, "delta %ld ==> srtt: %d rttvar: %d to: %d\n", delta, to->srtt, to->rttvar, to->timeout); log_write(LOG_STDOUT, "delta %ld ==> srtt: %d rttvar: %d to: %d\n", delta, to->srtt, to->rttvar, to->timeout);
} }
/* if (to->srtt < 0 || to->rttvar < 0 || to->timeout < 0 || delta < -50000000 || /* if (to->srtt < 0 || to->rttvar < 0 || to->timeout < 0 || delta < -50000000 ||
sent->tv_sec == 0 || received->tv_sec == 0 ) { sent->tv_sec == 0 || received->tv_sec == 0 ) {
fatal("Serious time computation problem in adjust_timeout ... received = (%ld, %ld) sent=(%ld,%ld) delta = %ld srtt = %d rttvar = %d to = %d", (long) received->tv_sec, (long)received->tv_usec, (long) sent->tv_sec, (long) sent->tv_usec, delta, to->srtt, to->rttvar, to->timeout); fatal("Serious time computation problem in adjust_timeout ... received = (%ld, %ld) sent=(%ld,%ld) delta = %ld srtt = %d rttvar = %d to = %d", (long) received->tv_sec, (long)received->tv_usec, (long) sent->tv_sec, (long) sent->tv_usec, delta, to->srtt, to->rttvar, to->timeout);
} */ } */
@@ -249,7 +249,7 @@ void enforce_scan_delay(struct timeval *tv) {
gettimeofday(&now, NULL); gettimeofday(&now, NULL);
time_diff = TIMEVAL_MSEC_SUBTRACT(now, lastcall); time_diff = TIMEVAL_MSEC_SUBTRACT(now, lastcall);
if (time_diff < (int) o.scan_delay) { if (time_diff < (int) o.scan_delay) {
if (o.debugging > 1) { if (o.debugging > 1) {
log_write(LOG_PLAIN, "Sleeping for %d milliseconds in %s()\n", o.scan_delay - time_diff, __func__); log_write(LOG_PLAIN, "Sleeping for %d milliseconds in %s()\n", o.scan_delay - time_diff, __func__);
} }
@@ -261,7 +261,7 @@ void enforce_scan_delay(struct timeval *tv) {
memcpy(tv, &lastcall, sizeof(struct timeval)); memcpy(tv, &lastcall, sizeof(struct timeval));
} }
return; return;
} }
@@ -593,7 +593,7 @@ bool ScanProgressMeter::mayBePrinted(const struct timeval *now) {
return true; return true;
else else
return false; return false;
} }
if (difftime(now->tv_sec, last_print_test.tv_sec) < 3) if (difftime(now->tv_sec, last_print_test.tv_sec) < 3)
return false; /* No point even checking too often */ return false; /* No point even checking too often */
@@ -623,7 +623,7 @@ static double estimate_time_left(double perc_done,
so if mayBePrinted() is true, and it seems reasonable to do so so if mayBePrinted() is true, and it seems reasonable to do so
because the estimate has changed significantly. Returns whether because the estimate has changed significantly. Returns whether
or not a line was printed.*/ or not a line was printed.*/
bool ScanProgressMeter::printStatsIfNecessary(double perc_done, bool ScanProgressMeter::printStatsIfNecessary(double perc_done,
const struct timeval *now) { const struct timeval *now) {
struct timeval tvtmp; struct timeval tvtmp;
double time_left_s; double time_left_s;
@@ -667,13 +667,13 @@ bool ScanProgressMeter::printStatsIfNecessary(double perc_done,
if (printit) { if (printit) {
return printStats(perc_done, now); return printStats(perc_done, now);
} }
return false; return false;
} }
/* Prints an estimate of when this scan will complete. */ /* Prints an estimate of when this scan will complete. */
bool ScanProgressMeter::printStats(double perc_done, bool ScanProgressMeter::printStats(double perc_done,
const struct timeval *now) { const struct timeval *now) {
struct timeval tvtmp; struct timeval tvtmp;
double time_left_s; double time_left_s;
@@ -722,7 +722,7 @@ bool ScanProgressMeter::printStats(double perc_done,
xml_close_empty_tag(); xml_close_empty_tag();
xml_newline(); xml_newline();
log_flush(LOG_STDOUT|LOG_XML); log_flush(LOG_STDOUT|LOG_XML);
return true; return true;
} }

View File

@@ -140,11 +140,11 @@ void initialize_timeout_info(struct timeout_info *to);
the receive time too (which could be because it was received a while the receive time too (which could be because it was received a while
back or it could be for efficiency because the caller already knows back or it could be for efficiency because the caller already knows
the current time */ the current time */
void adjust_timeouts2(const struct timeval *sent, void adjust_timeouts2(const struct timeval *sent,
const struct timeval *received, const struct timeval *received,
struct timeout_info *to); struct timeout_info *to);
/* Adjust our timeout values based on the time the latest probe took for a /* Adjust our timeout values based on the time the latest probe took for a
response. We update our RTT averages, etc. */ response. We update our RTT averages, etc. */
void adjust_timeouts(struct timeval sent, struct timeout_info *to); void adjust_timeouts(struct timeval sent, struct timeout_info *to);

View File

@@ -502,7 +502,7 @@ Hop *HostState::insert_hop(u8 ttl, const struct sockaddr_storage *addr,
} else { } else {
if (o.debugging) { if (o.debugging) {
log_write(LOG_STDOUT, "Found existing %s", ss_to_string(&hop->addr)); log_write(LOG_STDOUT, "Found existing %s", ss_to_string(&hop->addr));
log_write(LOG_STDOUT, " while inserting %s at TTL %d for %s\n", log_write(LOG_STDOUT, " while inserting %s at TTL %d for %s\n",
ss_to_string(addr), ttl, target->targetipstr()); ss_to_string(addr), ttl, target->targetipstr());
} }
} }