1
0
mirror of https://github.com/nmap/nmap.git synced 2025-12-06 04:31:29 +00:00

Merge from /nmap-exp/luis/nmap-os6.

svn merge --ignore-ancestry svn://svn.insecure.org/nmap@26621 svn://svn.insecure.org/nmap-exp/luis/nmap-os6

This is the IPv6 OS detection branch. "nmap -6 -O" works now, though at
this point it only prints fingerprints and not OS guesses, because we
need to collect more submissions.
This commit is contained in:
david
2011-09-19 18:31:46 +00:00
parent f41753c4e9
commit 9bf2ec3884
93 changed files with 24665 additions and 222 deletions

2582
FPEngine.cc Normal file

File diff suppressed because it is too large Load Diff

437
FPEngine.h Normal file
View File

@@ -0,0 +1,437 @@
/***************************************************************************
* FPEngine.h -- Header info for IPv6 OS detection via TCP/IP *
* fingerprinting. For more information on how this works in Nmap, see *
* http://insecure.org/osdetect/ *
* *
***********************IMPORTANT NMAP LICENSE TERMS************************
* *
* The Nmap Security Scanner is (C) 1996-2011 Insecure.Com LLC. Nmap is *
* also a registered trademark of Insecure.Com LLC. This program is free *
* software; you may redistribute and/or modify it under the terms of the *
* GNU General Public License as published by the Free Software *
* Foundation; Version 2 with the clarifications and exceptions described *
* below. This guarantees your right to use, modify, and redistribute *
* this software under certain conditions. If you wish to embed Nmap *
* technology into proprietary software, we sell alternative licenses *
* (contact sales@insecure.com). Dozens of software vendors already *
* license Nmap technology such as host discovery, port scanning, OS *
* detection, and version detection. *
* *
* Note that the GPL places important restrictions on "derived works", yet *
* it does not provide a detailed definition of that term. To avoid *
* misunderstandings, we consider an application to constitute a *
* "derivative work" for the purpose of this license if it does any of the *
* following: *
* o Integrates source code from Nmap *
* o Reads or includes Nmap copyrighted data files, such as *
* nmap-os-db or nmap-service-probes. *
* o Executes Nmap and parses the results (as opposed to typical shell or *
* execution-menu apps, which simply display raw Nmap output and so are *
* not derivative works.) *
* o Integrates/includes/aggregates Nmap into a proprietary executable *
* installer, such as those produced by InstallShield. *
* o Links to a library or executes a program that does any of the above *
* *
* The term "Nmap" should be taken to also include any portions or derived *
* works of Nmap. This list is not exclusive, but is meant to clarify our *
* interpretation of derived works with some common examples. Our *
* interpretation applies only to Nmap--we don't speak for other people's *
* GPL works. *
* *
* If you have any questions about the GPL licensing restrictions on using *
* Nmap in non-GPL works, we would be happy to help. As mentioned above, *
* we also offer alternative license to integrate Nmap into proprietary *
* applications and appliances. These contracts have been sold to dozens *
* of software vendors, and generally include a perpetual license as well *
* as providing for priority support and updates as well as helping to *
* fund the continued development of Nmap technology. Please email *
* sales@insecure.com for further information. *
* *
* As a special exception to the GPL terms, Insecure.Com LLC grants *
* permission to link the code of this program with any version of the *
* OpenSSL library which is distributed under a license identical to that *
* listed in the included docs/licenses/OpenSSL.txt file, and distribute *
* linked combinations including the two. You must obey the GNU GPL in all *
* respects for all of the code used other than OpenSSL. If you modify *
* this file, you may extend this exception to your version of the file, *
* but you are not obligated to do so. *
* *
* If you received these files with a written license agreement or *
* contract stating terms other than the terms above, then that *
* alternative license agreement takes precedence over these comments. *
* *
* Source is provided to this software because we believe users have a *
* right to know exactly what a program is going to do before they run it. *
* This also allows you to audit the software for security holes (none *
* have been found so far). *
* *
* Source code also allows you to port Nmap to new platforms, fix bugs, *
* and add new features. You are highly encouraged to send your changes *
* to nmap-dev@insecure.org for possible incorporation into the main *
* distribution. By sending these changes to Fyodor or one of the *
* Insecure.Org development mailing lists, it is assumed that you are *
* offering the Nmap Project (Insecure.Com LLC) the unlimited, *
* non-exclusive right to reuse, modify, and relicense the code. Nmap *
* will always be available Open Source, but this is important because the *
* inability to relicense code has caused devastating problems for other *
* Free Software projects (such as KDE and NASM). We also occasionally *
* relicense the code to third parties as discussed above. If you wish to *
* specify special license conditions of your contributions, just say so *
* when you send them. *
* *
* This program is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* General Public License v2.0 for more details at *
* http://www.gnu.org/licenses/gpl-2.0.html , or in the COPYING file *
* included with Nmap. *
* *
***************************************************************************/
/* $Id$ */
#ifndef __FPENGINE_H__
#define __FPENGINE_H__ 1
#include "nsock.h"
#include <list>
#include <vector>
#include "nmap.h"
#include "libnetutil/npacket.h"
using namespace std;
/* Mention some classes here so we don't have to place the declarations in
* the right order (otherwise the compiler complains). */
class FPHost;
class FPHost6;
class FPProbe;
class Target;
class FingerPrintResultsIPv6;
/******************************************************************************
* CONSTANT DEFINITIONS *
******************************************************************************/
#define NELEMS(a) (sizeof(a) / sizeof((a)[0]))
#define NUM_FP_PROBES_IPv6_TCP 13
#define NUM_FP_PROBES_IPv6_ICMPv6 4
#define NUM_FP_PROBES_IPv6_UDP 1
/* Total number of IPv6 OS detection probes. */
#define NUM_FP_PROBES_IPv6 (NUM_FP_PROBES_IPv6_TCP+NUM_FP_PROBES_IPv6_ICMPv6+NUM_FP_PROBES_IPv6_UDP)
const unsigned int OSDETECT_FLOW_LABEL = 0x12345;
/* Number of timed probes for IPv6 OS scan. This is, the number of probes that
* have specific timing requirements and need to be processed together. This
* are the probes that are sent 100ms apart. */
#define NUM_FP_TIMEDPROBES_IPv6 6
/* Initial congestion window. It is set to the number of timed probes because
* hosts need to be able to schedule all of them at once. */
#define OSSCAN_INITIAL_CWND (NUM_FP_TIMEDPROBES_IPv6)
/* Initial Slow Start threshold. It is set to four times the initial CWND. */
#define OSSCAN_INITIAL_SSTHRESH (4 * OSSCAN_INITIAL_CWND)
/* Host group size is the number of osscan hosts that are processed in parallel.
* Note that this osscan engine always keeps a working group of this many hosts.
* in other words, if one host in the group finishes, another is added to it
* dynamically. */
#define OSSCAN_GROUP_SIZE 10
/* Initial retransmission timeout. This is the time we initially wait for a
* probe response before retransmitting the original probe. Note that this is
* only the initial RTO, used only when no RTT measures have been taken yet.
* The actual RTO varies each time we get a response to a probe.
* It is set to 3 seconds (3*10^6 usecs) as per RFC 2988. */
#define OSSCAN_INITIAL_RTO (3*1000000)
/******************************************************************************
* CLASS DEFINITIONS *
******************************************************************************/
/* This class handles the access to the network. It handles packet transmission
* scheduling, packet capture and congestion control. Every FPHost should be
* linked to the same instance of this class, so the access to the network can
* be managed globally (for the whole OS detection process). */
class FPNetworkControl {
private:
nsock_pool nsp; /* Nsock pool. */
nsock_iod pcap_nsi; /* Nsock Pcap descriptor. */
nsock_event_id pcap_ev_id; /* Last pcap read event that was scheduled. */
bool first_pcap_scheduled; /* True if we scheduled the first pcap read event. */
bool nsock_init; /* True if the nsock pool has been initialized. */
int rawsd; /* Raw socket. */
vector<FPHost *> callers; /* List of users of this instance (used for callbacks).*/
int probes_sent; /* Number of unique probes sent (not retransmissions). */
int responses_recv; /* Number of probe responses received. */
int probes_timedout; /* Number of probes that timeout after all retransms. */
float cc_cwnd; /* Current congestion window. */
float cc_ssthresh; /* Current Slow Start threshold. */
int cc_init();
int cc_update_sent(int pkts);
int cc_report_drop();
int cc_update_received();
public:
FPNetworkControl();
~FPNetworkControl();
void init(const char *ifname, devtype iftype);
int register_caller(FPHost *newcaller);
int unregister_caller(FPHost *oldcaller);
int setup_sniffer(const char *iface, const char *bfp_filter);
void handle_events();
int scheduleProbe(FPProbe *pkt, int in_msecs_time);
void probe_transmission_handler(nsock_pool nsp, nsock_event nse, void *arg);
void response_reception_handler(nsock_pool nsp, nsock_event nse, void *arg);
bool request_slots(size_t num_packets);
int cc_report_final_timeout();
};
/* +-----------+
| FPEngine |
+-----------+
| |
+-----+-----+
|
+-------+-------+
| |
| |
+-----------+ +-----------+
| FPEngine4 | | FPEngine6 |
+-----------+ +-----------+
| | | |
+-----------+ +-----------+ */
/* This class is the generic fingerprinting engine. */
class FPEngine {
protected:
size_t osgroup_size;
public:
FPEngine();
~FPEngine();
void reset();
virtual int os_scan(vector<Target *> &Targets) = 0;
const char *bpf_filter(vector<Target *> &Targets);
};
/* This class handles IPv6 OS fingerprinting. Using it is very simple, just
* instance it and then call os_scan() with the list of IPv6 targets to
* fingerprint. If everything goes well, the internal state of the supplied
* target objects will be modified to reflect the results of the fingerprinting
* process. */
class FPEngine6 : public FPEngine {
private:
vector<FPHost6 *> fphosts; /* Information about each target to fingerprint */
public:
FPEngine6();
~FPEngine6();
void reset();
int os_scan(vector<Target *> &Targets);
};
/* +----------+
| FPPacket |
+----------+
| |
+-----+----+
|
|
+-----------+
| FPProbe |
+-----------+
| |
+-----+-----+ */
/* This class represents a generic packet for the OS fingerprinting process */
class FPPacket {
protected:
PacketElement *pkt; /* Actual packet associated with this FPPacket */
bool link_eth; /* Ethernet layer required? */
struct eth_nfo eth_hdr; /* Eth info, valid when this->link_eth==true */
struct timeval pkt_time; /* Time at which the packet was sent or received */
int resetTime();
void __reset();
public:
FPPacket();
~FPPacket();
int setTime(const struct timeval *tv = NULL);
struct timeval getTime() const;
int setPacket(PacketElement *pkt);
int setEthernet(const u8 *src_mac, const u8 *dst_mac, const char *devname);
const struct eth_nfo *getEthernet() const;
const PacketElement *getPacket() const;
size_t getLength() const;
u8 *getPacketBuffer(size_t *pkt_len) const;
bool is_set() const;
};
/* This class represents a generic OS fingerprinting probe. In other words, it
* represents a network packet that Nmap sends to a target in order to
* obtain information about the target's TCP/IP stack. */
class FPProbe : public FPPacket {
private:
char *probe_id;
int probe_no;
int retransmissions;
int times_replied;
bool failed;
bool timed;
public:
FPHost *host;
FPProbe();
~FPProbe();
void reset();
bool isResponse(PacketElement *rcvd);
int setProbeID(const char *id);
const char *getProbeID() const;
int getRetransmissions() const;
int incrementRetransmissions();
int getReplies() const;
int incrementReplies();
int setTimeSent();
int resetTimeSent();
struct timeval getTimeSent() const;
bool probeFailed() const;
int setFailed();
bool isTimed() const;
int setTimed();
};
/* This class represents a generic received packet. */
struct FPResponse {
const char *probe_id;
u8 *buf;
size_t len;
struct timeval senttime, rcvdtime;
FPResponse(const char *probe_id, const u8 *buf, size_t len,
struct timeval senttime, struct timeval rcvdtime);
~FPResponse();
};
/* +-----------+
| FPHost |
+-----------+
| |
+-----+-----+
|
+-------+-------+
| |
| |
+-----------+ +-----------+
| FPHost4 | | FPHost6 |
+-----------+ +-----------+
| | | |
+-----------+ +-----------+ */
/* This class represents a generic host to be fingerprinted. */
class FPHost {
protected:
unsigned int total_probes; /* Number of different OS scan probes to be sent to targets */
unsigned int timed_probes; /* Number of probes that have specific timing requirements */
unsigned int probes_sent; /* Number of FPProbes sent (not counting retransmissions) */
unsigned int probes_answered; /* Number of FPResponses received */
unsigned int probes_unanswered; /* Number of FPProbes that timedout (after all retransmissions) */
bool detection_done; /* True if the OS detection process has been completed. */
bool timedprobes_sent; /* True if the probes that have timing requirements were sent */
Target *target_host; /* Info about the host to fingerprint */
FPNetworkControl *netctl; /* Link to the network manager (for scheduling and CC) */
bool netctl_registered; /* True if we are already registered in the network controller */
u32 tcpSeqBase; /* Base for sequence numbers set in outgoing probes */
int open_port_tcp; /* Open TCP port to be used in the OS detection probes */
int closed_port_tcp; /* Closed TCP port for the OS detection probes. */
int closed_port_udp; /* Closed UDP port. */
int tcp_port_base; /* Send TCP probes starting with this port number. */
int udp_port_base; /* Send UDP probes with this port number. */
u16 icmp_seq_counter; /* ICMPv6 sequence number counter. */
int rto; /* Retransmission timeout for the host */
int rttvar; /* Round-Trip Time variation (RFC 2988) */
int srtt; /* Smoothed Round-Trip Time (RFC 2988) */
void __reset();
int update_RTO(int measured_rtt_usecs, bool retransmission);
int choose_osscan_ports();
private:
virtual int build_probe_list() = 0;
public:
struct timeval begin_time;
FPHost();
~FPHost();
virtual bool done() = 0;
virtual int schedule() = 0;
virtual int callback(const u8 *pkt, size_t pkt_len, const struct timeval *tv) = 0;
const struct sockaddr_storage *getTargetAddress();
};
/* This class represents IPv6 hosts to be fingerprinted. The class performs
* OS detection asynchronously. To use it, shedule() must be called at regular
* intervals until done() returns true. After that, status() will indicate
* whether the host was successfully matched with a particular OS or not. */
class FPHost6 : public FPHost {
private:
FPProbe fp_probes[NUM_FP_PROBES_IPv6]; /* OS detection probes to be sent.*/
FPResponse *fp_responses[NUM_FP_PROBES_IPv6]; /* Received responses. */
FPResponse *aux_resp[NUM_FP_TIMEDPROBES_IPv6]; /* Aux vector for timed responses */
int build_probe_list();
int set_done_and_wrap_up();
public:
FPHost6(Target *tgt, FPNetworkControl *fpnc);
~FPHost6();
void reset();
void init(Target *tgt, FPNetworkControl *fpnc);
void finish();
bool done();
int schedule();
int callback(const u8 *pkt, size_t pkt_len, const struct timeval *tv);
const FPProbe *getProbe(const char *id);
const FPResponse *getResponse(const char *id);
void fill_FPR(FingerPrintResultsIPv6 *FPR);
};
/******************************************************************************
* Nsock handler wrappers. *
******************************************************************************/
void probe_transmission_handler_wrapper(nsock_pool nsp, nsock_event nse, void *arg);
void response_reception_handler_wrapper(nsock_pool nsp, nsock_event nse, void *arg);
std::vector<FingerMatch> load_fp_matches();
#endif /* __FPENGINE_H__ */

1590
FPmodel.cc Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -104,12 +104,18 @@ FingerPrintResults::FingerPrintResults() {
osscan_opentcpport = osscan_closedtcpport = osscan_closedudpport = -1; osscan_opentcpport = osscan_closedtcpport = osscan_closedudpport = -1;
distance = -1; distance = -1;
distance_guess = -1; distance_guess = -1;
FPs = (FingerPrint **) safe_zalloc(o.maxOSTries() * sizeof(FingerPrint *));
maxTimingRatio = 0; maxTimingRatio = 0;
numFPs = 0;
} }
FingerPrintResults::~FingerPrintResults() { FingerPrintResults::~FingerPrintResults() {
}
FingerPrintResultsIPv4::FingerPrintResultsIPv4() {
FPs = (FingerPrint **) safe_zalloc(o.maxOSTries() * sizeof(FingerPrint *));
numFPs = 0;
}
FingerPrintResultsIPv4::~FingerPrintResultsIPv4() {
int i; int i;
/* Free OS fingerprints of OS scanning was done */ /* Free OS fingerprints of OS scanning was done */
@@ -121,6 +127,25 @@ FingerPrintResults::~FingerPrintResults() {
free(FPs); free(FPs);
} }
FingerPrintResultsIPv6::FingerPrintResultsIPv6() {
unsigned int i;
begin_time.tv_sec = 0;
begin_time.tv_usec = 0;
for (i = 0; i < sizeof(fp_responses) / sizeof(*fp_responses); i++)
fp_responses[i] = NULL;
flow_label = 0;
}
FingerPrintResultsIPv6::~FingerPrintResultsIPv6() {
unsigned int i;
for (i = 0; i < sizeof(fp_responses) / sizeof(*fp_responses); i++) {
if (fp_responses[i])
delete fp_responses[i];
}
}
const struct OS_Classification_Results *FingerPrintResults::getOSClassification() { const struct OS_Classification_Results *FingerPrintResults::getOSClassification() {
if (!isClassified) { populateClassification(); isClassified = true; } if (!isClassified) { populateClassification(); isClassified = true; }
return &OSR; return &OSR;
@@ -178,6 +203,19 @@ const char *FingerPrintResults::OmitSubmissionFP() {
return NULL; return NULL;
} }
/* IPv6 classification is more robust to errors than IPv4, so apply less
stringent conditions than the general OmitSubmissionFP. */
const char *FingerPrintResultsIPv6::OmitSubmissionFP() {
static char reason[128];
if (o.scan_delay > 500) { // This can screw up the sequence timing
Snprintf(reason, sizeof(reason), "Scan delay (%d) is greater than 500", o.scan_delay);
return reason;
}
return NULL;
}
/* Goes through fingerprinting results to populate OSR */ /* Goes through fingerprinting results to populate OSR */
void FingerPrintResults::populateClassification() { void FingerPrintResults::populateClassification() {
@@ -196,8 +234,8 @@ void FingerPrintResults::populateClassification() {
for(printno = 0; printno < num_matches; printno++) { for(printno = 0; printno < num_matches; printno++) {
// a single print may have multiple classifications // a single print may have multiple classifications
for (osclass = prints[printno]->OS_class.begin(); for (osclass = matches[printno]->OS_class.begin();
osclass != prints[printno]->OS_class.end(); osclass != matches[printno]->OS_class.end();
osclass++) { osclass++) {
if (!classAlreadyExistsInResults(&*osclass)) { if (!classAlreadyExistsInResults(&*osclass)) {
// Then we have to add it ... first ensure we have room // Then we have to add it ... first ensure we have room
@@ -217,7 +255,7 @@ void FingerPrintResults::populateClassification() {
// OK, we will add the new class // OK, we will add the new class
OSR.OSC[OSR.OSC_num_matches] = &*osclass; OSR.OSC[OSR.OSC_num_matches] = &*osclass;
OSR.OSC_Accuracy[OSR.OSC_num_matches] = accuracy[printno]; OSR.OSC_Accuracy[OSR.OSC_num_matches] = accuracy[printno];
if (accuracy[printno] == 1.0) OSR.OSC_num_perfect_matches++; if (printno < num_perfect_matches) OSR.OSC_num_perfect_matches++;
OSR.OSC_num_matches++; OSR.OSC_num_matches++;
} }
} }

View File

@@ -97,6 +97,7 @@ class FingerPrintResults;
#include "nmap.h" #include "nmap.h"
#include "global_structures.h" #include "global_structures.h"
#include "FPEngine.h"
/* Maximum number of results allowed in one of these things ... */ /* Maximum number of results allowed in one of these things ... */
#define MAX_FP_RESULTS 36 #define MAX_FP_RESULTS 36
@@ -112,11 +113,11 @@ struct OS_Classification_Results {
class FingerPrintResults { class FingerPrintResults {
public: /* For now ... a lot of the data members should be made private */ public: /* For now ... a lot of the data members should be made private */
FingerPrintResults(); FingerPrintResults();
~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 pritns[] below */ match) in same order as pritns[] below */
FingerPrint *prints[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 prints[] */ int num_perfect_matches; /* Number of 1.0 accuracy matches in prints[] */
int num_matches; /* Total number of matches in prints[] */ int num_matches; /* Total number of matches in prints[] */
@@ -147,14 +148,13 @@ class FingerPrintResults {
consistancy standpoint. */ consistancy standpoint. */
double maxTimingRatio; double maxTimingRatio;
FingerPrint **FPs; /* Fingerprint data obtained from host */
int numFPs;
/* If the fingerprint is of potentially poor quality, we don't want to /* If the fingerprint is of potentially poor quality, we don't want to
print it and ask the user to submit it. In that case, the reason print it and ask the user to submit it. In that case, the reason
for skipping the FP is returned as a static string. If the FP is for skipping the FP is returned as a static string. If the FP is
great and should be printed, NULL is returned. */ great and should be printed, NULL is returned. */
const char *OmitSubmissionFP(); virtual const char *OmitSubmissionFP();
virtual const char *merge_fpr(const Target *currenths, bool isGoodFP, bool wrapit) const = 0;
private: private:
bool isClassified; // Whether populateClassification() has been called bool isClassified; // Whether populateClassification() has been called
@@ -165,4 +165,27 @@ class FingerPrintResults {
struct OS_Classification_Results OSR; struct OS_Classification_Results OSR;
}; };
class FingerPrintResultsIPv4 : public FingerPrintResults {
public:
FingerPrint **FPs; /* Fingerprint data obtained from host */
int numFPs;
FingerPrintResultsIPv4();
virtual ~FingerPrintResultsIPv4();
const char *merge_fpr(const Target *currenths, bool isGoodFP, bool wrapit) const;
};
class FingerPrintResultsIPv6 : public FingerPrintResults {
public:
FPResponse *fp_responses[NUM_FP_PROBES_IPv6];
struct timeval begin_time;
/* The flow label we set in our sent packets, for calculating offsets later. */
unsigned int flow_label;
FingerPrintResultsIPv6();
virtual ~FingerPrintResultsIPv6();
const char *OmitSubmissionFP();
const char *merge_fpr(const Target *currenths, bool isGoodFP, bool wrapit) const;
};
#endif /* FINGERPRINTRESULTS_H */ #endif /* FINGERPRINTRESULTS_H */

View File

@@ -17,8 +17,10 @@ NMAPDEVDIR=~/nmap-private-dev
export NBASEDIR=@NBASEDIR@ export NBASEDIR=@NBASEDIR@
export NSOCKDIR=@NSOCKDIR@ export NSOCKDIR=@NSOCKDIR@
export LIBLUADIR = @LIBLUADIR@ export LIBLUADIR = @LIBLUADIR@
export LIBLINEARDIR = @LIBLINEARDIR@
export NDIR=$(shell pwd) export NDIR=$(shell pwd)
export LIBLUA_LIBS = @LIBLUA_LIBS@ export LIBLUA_LIBS = @LIBLUA_LIBS@
export LIBLINEAR_LIBS = @LIBLINEAR_LIBS@
export NCATDIR=@NCATDIR@ export NCATDIR=@NCATDIR@
CC = @CC@ CC = @CC@
CXX = @CXX@ CXX = @CXX@
@@ -47,7 +49,7 @@ export CFLAGS = $(CXXFLAGS)
# CFLAGS = $(DEFS) $(INCLS) # CFLAGS = $(DEFS) $(INCLS)
STATIC = STATIC =
LDFLAGS = @LDFLAGS@ $(DBGFLAGS) $(STATIC) LDFLAGS = @LDFLAGS@ $(DBGFLAGS) $(STATIC)
LIBS = @LIBNBASE_LIBS@ @LIBNSOCK_LIBS@ @LIBPCRE_LIBS@ @LIBPCAP_LIBS@ $(OPENSSL_LIBS) libnetutil/libnetutil.a @LIBDNET_LIBS@ @LIBLUA_LIBS@ @LIBS@ LIBS = @LIBNBASE_LIBS@ @LIBNSOCK_LIBS@ @LIBPCRE_LIBS@ @LIBPCAP_LIBS@ $(OPENSSL_LIBS) libnetutil/libnetutil.a @LIBDNET_LIBS@ @LIBLUA_LIBS@ @LIBLINEAR_LIBS@ @LIBS@
OPENSSL_LIBS = @OPENSSL_LIBS@ OPENSSL_LIBS = @OPENSSL_LIBS@
# LIBS = -lefence @LIBS@ # LIBS = -lefence @LIBS@
# LIBS = -lrmalloc @LIBS@ # LIBS = -lrmalloc @LIBS@
@@ -93,20 +95,20 @@ NSE_OBJS+=nse_openssl.o nse_ssl_cert.o
endif endif
endif endif
export SRCS = main.cc nmap.cc targets.cc tcpip.cc nmap_error.cc utils.cc idle_scan.cc osscan.cc osscan2.cc output.cc payload.cc scan_engine.cc timing.cc charpool.cc services.cc protocols.cc nmap_rpc.cc portlist.cc NmapOps.cc TargetGroup.cc Target.cc FingerPrintResults.cc service_scan.cc NmapOutputTable.cc MACLookup.cc nmap_tty.cc nmap_dns.cc traceroute.cc portreasons.cc xml.cc $(NSE_SRC) @COMPAT_SRCS@ export SRCS = main.cc nmap.cc targets.cc tcpip.cc nmap_error.cc utils.cc idle_scan.cc osscan.cc osscan2.cc FPEngine.cc FPmodel.cc output.cc payload.cc scan_engine.cc timing.cc charpool.cc services.cc protocols.cc nmap_rpc.cc portlist.cc NmapOps.cc TargetGroup.cc Target.cc FingerPrintResults.cc service_scan.cc NmapOutputTable.cc MACLookup.cc nmap_tty.cc nmap_dns.cc traceroute.cc portreasons.cc xml.cc $(NSE_SRC) @COMPAT_SRCS@
export HDRS = charpool.h FingerPrintResults.h global_structures.h idle_scan.h MACLookup.h nmap_amigaos.h nmap_dns.h nmap_error.h nmap.h NmapOps.h NmapOutputTable.h nmap_rpc.h nmap_tty.h nmap_winconfig.h osscan.h osscan2.h output.h payload.h portlist.h protocols.h scan_engine.h service_scan.h services.h TargetGroup.h Target.h targets.h tcpip.h timing.h utils.h traceroute.h portreasons.h xml.h $(NSE_HDRS) export HDRS = charpool.h FingerPrintResults.h global_structures.h idle_scan.h MACLookup.h nmap_amigaos.h nmap_dns.h nmap_error.h nmap.h NmapOps.h NmapOutputTable.h nmap_rpc.h nmap_tty.h nmap_winconfig.h osscan.h osscan2.h FPEngine.h output.h payload.h portlist.h protocols.h scan_engine.h service_scan.h services.h TargetGroup.h Target.h targets.h tcpip.h timing.h utils.h traceroute.h portreasons.h xml.h $(NSE_HDRS)
OBJS = main.o nmap.o targets.o tcpip.o nmap_error.o utils.o idle_scan.o osscan.o osscan2.o output.o payload.o scan_engine.o timing.o charpool.o services.o protocols.o nmap_rpc.o portlist.o NmapOps.o TargetGroup.o Target.o FingerPrintResults.o service_scan.o NmapOutputTable.o MACLookup.o nmap_tty.o nmap_dns.o traceroute.o portreasons.o xml.o $(NSE_OBJS) @COMPAT_OBJS@ OBJS = main.o nmap.o targets.o tcpip.o nmap_error.o utils.o idle_scan.o osscan.o osscan2.o FPEngine.o FPmodel.o output.o payload.o scan_engine.o timing.o charpool.o services.o protocols.o nmap_rpc.o portlist.o NmapOps.o TargetGroup.o Target.o FingerPrintResults.o service_scan.o NmapOutputTable.o MACLookup.o nmap_tty.o nmap_dns.o traceroute.o portreasons.o xml.o $(NSE_OBJS) @COMPAT_OBJS@
# %.o : %.cc -- nope this is a GNU extension # %.o : %.cc -- nope this is a GNU extension
.cc.o: .cc.o:
$(CXX) -c $(CPPFLAGS) $(CXXFLAGS) $< -o $@ $(CXX) -c $(CPPFLAGS) $(CXXFLAGS) $< -o $@
all: @LUA_BUILD@ @PCAP_BUILD@ @PCRE_BUILD@ @DNET_BUILD@ @NBASE_BUILD@ @NSOCK_BUILD@ @NCAT_BUILD@ netutil_build all: @LUA_BUILD@ @LIBLINEAR_BUILD@ @PCAP_BUILD@ @PCRE_BUILD@ @DNET_BUILD@ @NBASE_BUILD@ @NSOCK_BUILD@ @NCAT_BUILD@ netutil_build
$(MAKE) $(TARGET) $(BUILDZENMAP) $(BUILDNDIFF) $(BUILDNPING) $(MAKE) $(TARGET) $(BUILDZENMAP) $(BUILDNDIFF) $(BUILDNPING)
$(TARGET): @LUA_DEPENDS@ @PCAP_DEPENDS@ @PCRE_DEPENDS@ @DNET_DEPENDS@ $(NBASEDIR)/libnbase.a $(NSOCKDIR)/src/libnsock.a libnetutil/libnetutil.a $(OBJS) $(TARGET): @LUA_DEPENDS@ @LIBLINEAR_DEPENDS@ @PCAP_DEPENDS@ @PCRE_DEPENDS@ @DNET_DEPENDS@ $(NBASEDIR)/libnbase.a $(NSOCKDIR)/src/libnsock.a libnetutil/libnetutil.a $(OBJS)
@echo Compiling nmap @echo Compiling nmap
rm -f $@ rm -f $@
$(CXX) $(LDFLAGS) -o $@ $(OBJS) $(LIBS) $(CXX) $(LDFLAGS) -o $@ $(OBJS) $(LIBS)
@@ -138,6 +140,9 @@ ncat_build: $(NCATDIR)/Makefile nbase_build nsock_build $(NCATDIR)/ncat.h
lua_build: $(LIBLUADIR)/Makefile lua_build: $(LIBLUADIR)/Makefile
@echo Compiling liblua; cd $(LIBLUADIR) && $(MAKE) liblua.a CC="$(CC)" MYCFLAGS="$(CFLAGS) @LUA_CFLAGS@" @echo Compiling liblua; cd $(LIBLUADIR) && $(MAKE) liblua.a CC="$(CC)" MYCFLAGS="$(CFLAGS) @LUA_CFLAGS@"
liblinear_build: $(LIBLINEARDIR)/Makefile
@echo Compiling liblinear; cd $(LIBLINEARDIR) && $(MAKE) liblinear.a CC="$(CC)" CFLAGS="$(CFLAGS)"
#$(LIBPCAPDIR)/Makefile: #$(LIBPCAPDIR)/Makefile:
# @echo Configuring libpcap; cd $(LIBPCAPDIR); ./configure # @echo Configuring libpcap; cd $(LIBPCAPDIR); ./configure
@@ -166,7 +171,7 @@ release-rpms:
web: web:
cd $(NMAPDEVDIR) && $(MAKE) web cd $(NMAPDEVDIR) && $(MAKE) web
clean: @LUA_CLEAN@ @PCAP_CLEAN@ @PCRE_CLEAN@ @DNET_CLEAN@ nsock_clean nbase_clean netutil_clean my_clean @NPING_CLEAN@ @ZENMAP_CLEAN@ @NCAT_CLEAN@ clean: @LUA_CLEAN@ @LIBLINEAR_CLEAN@ @PCAP_CLEAN@ @PCRE_CLEAN@ @DNET_CLEAN@ nsock_clean nbase_clean netutil_clean my_clean @NPING_CLEAN@ @ZENMAP_CLEAN@ @NCAT_CLEAN@
my_clean: my_clean:
rm -f dependencies.mk makefile.dep rm -f dependencies.mk makefile.dep
@@ -187,6 +192,8 @@ ncat_clean:
-cd $(NCATDIR) && $(MAKE) clean -cd $(NCATDIR) && $(MAKE) clean
lua_clean: lua_clean:
-cd $(LIBLUADIR) && $(MAKE) clean -cd $(LIBLUADIR) && $(MAKE) clean
liblinear_clean:
-cd $(LIBLINEARDIR) && $(MAKE) clean
zenmap_clean: zenmap_clean:
-cd $(ZENMAPDIR) && $(PYTHON) setup.py clean --all -cd $(ZENMAPDIR) && $(PYTHON) setup.py clean --all
ndiff_clean: ndiff_clean:
@@ -201,6 +208,7 @@ dnet_dist_clean:
-cd $(LIBDNETDIR) && $(MAKE) distclean -cd $(LIBDNETDIR) && $(MAKE) distclean
lua_dist_clean: lua_dist_clean:
-cd $(LIBLUADIR) && $(MAKE) clean -cd $(LIBLUADIR) && $(MAKE) clean
liblinear_dist_clean: liblinear_clean
nbase_dist_clean: nbase_dist_clean:
-cd $(NBASEDIR) && $(MAKE) distclean -cd $(NBASEDIR) && $(MAKE) distclean
nsock_dist_clean: nsock_dist_clean:
@@ -218,7 +226,7 @@ nping_dist_clean:
debugclean: debugclean:
rm -f *.gcov *.gcda *.gcno gmon.out rm -f *.gcov *.gcda *.gcno gmon.out
distclean: my_clean my_distclean @LUA_DIST_CLEAN@ @PCAP_DIST_CLEAN@ @PCRE_DIST_CLEAN@ @DNET_DIST_CLEAN@ @NPING_DIST_CLEAN@ @ZENMAP_DIST_CLEAN@ @NCAT_DIST_CLEAN@ nsock_dist_clean nbase_dist_clean netutil_dist_clean distclean: my_clean my_distclean @LUA_DIST_CLEAN@ @LIBLINEAR_DIST_CLEAN@ @PCAP_DIST_CLEAN@ @PCRE_DIST_CLEAN@ @DNET_DIST_CLEAN@ @NPING_DIST_CLEAN@ @ZENMAP_DIST_CLEAN@ @NCAT_DIST_CLEAN@ nsock_dist_clean nbase_dist_clean netutil_dist_clean
my_distclean: my_distclean:
rm -f Makefile Makefile.bak makefile.dep nmap_config.h stamp-h stamp-h.in \ rm -f Makefile Makefile.bak makefile.dep nmap_config.h stamp-h stamp-h.in \

View File

@@ -326,6 +326,7 @@ void NmapOps::Initialize() {
ipopt_firsthop = 0; ipopt_firsthop = 0;
ipopt_lasthop = 0; ipopt_lasthop = 0;
release_memory = false; release_memory = false;
disable_ipv6_os_results = true;
topportlevel = -1; topportlevel = -1;
#ifndef NOLUA #ifndef NOLUA
script = 0; script = 0;
@@ -526,7 +527,7 @@ dialog where you can start NPF if you have administrator privileges.";
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|osscan|bouncescan|fragscan|idlescan)) { if (af() == AF_INET6 && (generate_random_ips|numdecoys|bouncescan|fragscan|idlescan)) {
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.");
} }

View File

@@ -187,6 +187,7 @@ class NmapOps {
int nogcc; /* Turn off group congestion control with --nogcc */ int nogcc; /* Turn off group congestion control with --nogcc */
int generate_random_ips; /* -iR option */ int generate_random_ips; /* -iR option */
FingerPrintDB *reference_FPs; /* Used in the new OS scan system. */ FingerPrintDB *reference_FPs; /* Used in the new OS scan system. */
std::vector<FingerMatch> os_labels_ipv6;
u16 magic_port; u16 magic_port;
unsigned short magic_port_set; /* Was this set by user? */ unsigned short magic_port_set; /* Was this set by user? */
@@ -351,6 +352,11 @@ class NmapOps {
bool noninteractive; bool noninteractive;
bool release_memory; /* suggest to release memory before quitting. used to find memory leaks. */ bool release_memory; /* suggest to release memory before quitting. used to find memory leaks. */
/* This is a temporary option that disables the printing of IPv6 OS results,
to allow collection of more fingerprints. */
bool disable_ipv6_os_results;
private: private:
int max_os_tries; int max_os_tries;
int max_rtt_timeout; int max_rtt_timeout;

View File

@@ -113,6 +113,7 @@ void Target::Initialize() {
targetname = NULL; targetname = NULL;
memset(&seq, 0, sizeof(seq)); memset(&seq, 0, sizeof(seq));
distance = -1; distance = -1;
distance_calculation_method = DIST_METHOD_NONE;
FPR = NULL; FPR = NULL;
osscan_flag = OS_NOTPERF; osscan_flag = OS_NOTPERF;
weird_responses = flags = 0; weird_responses = flags = 0;
@@ -124,6 +125,7 @@ void Target::Initialize() {
targetsocklen = sourcesocklen = nexthopsocklen = 0; targetsocklen = sourcesocklen = nexthopsocklen = 0;
directly_connected = -1; directly_connected = -1;
targetipstring[0] = '\0'; targetipstring[0] = '\0';
sourceipstring[0] = '\0';
nameIPBuf = NULL; nameIPBuf = NULL;
memset(&MACaddress, 0, sizeof(MACaddress)); memset(&MACaddress, 0, sizeof(MACaddress));
memset(&SrcMACaddress, 0, sizeof(SrcMACaddress)); memset(&SrcMACaddress, 0, sizeof(SrcMACaddress));
@@ -177,7 +179,7 @@ void Target::FreeInternal() {
/* Creates a "presentation" formatted string out of the IPv4/IPv6 address. /* Creates a "presentation" formatted string out of the IPv4/IPv6 address.
Called when the IP changes */ Called when the IP changes */
void Target::GenerateIPString() { void Target::GenerateTargetIPString() {
struct sockaddr_in *sin = (struct sockaddr_in *) &targetsock; struct sockaddr_in *sin = (struct sockaddr_in *) &targetsock;
#if HAVE_IPV6 #if HAVE_IPV6
struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) &targetsock; struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) &targetsock;
@@ -195,6 +197,26 @@ void Target::GenerateIPString() {
} }
} }
/* Creates a "presentation" formatted string out of the IPv4/IPv6 address.
Called when the IP changes */
void Target::GenerateSourceIPString() {
struct sockaddr_in *sin = (struct sockaddr_in *) &sourcesock;
#if HAVE_IPV6
struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) &sourcesock;
#endif
if (inet_ntop(sin->sin_family, (sin->sin_family == AF_INET)?
(char *) &sin->sin_addr :
#if HAVE_IPV6
(char *) &sin6->sin6_addr,
#else
(char *) NULL,
#endif
sourceipstring, sizeof(sourceipstring)) == NULL) {
fatal("Failed to convert source address to presentation format!?! Error: %s", strerror(socket_errno()));
}
}
/* Returns the address family of the destination address. */ /* Returns the address family of the destination address. */
int Target::af() const { int Target::af() const {
return targetsock.ss_family; return targetsock.ss_family;
@@ -233,7 +255,7 @@ void Target::setTargetSockAddr(const struct sockaddr_storage *ss, size_t ss_len)
} }
memcpy(&targetsock, ss, ss_len); memcpy(&targetsock, ss, ss_len);
targetsocklen = ss_len; targetsocklen = ss_len;
GenerateIPString(); GenerateTargetIPString();
/* The ports array needs to know a name too */ /* The ports array needs to know a name too */
ports.setIdStr(targetipstr()); ports.setIdStr(targetipstr());
} }
@@ -286,6 +308,7 @@ void Target::setSourceSockAddr(const struct sockaddr_storage *ss, size_t ss_len)
assert(ss_len > 0 && ss_len <= sizeof(*ss)); assert(ss_len > 0 && ss_len <= sizeof(*ss));
memcpy(&sourcesock, ss, ss_len); memcpy(&sourcesock, ss, ss_len);
sourcesocklen = ss_len; sourcesocklen = ss_len;
GenerateSourceIPString();
} }
// Returns IPv4 host address or {0} if unavailable. // Returns IPv4 host address or {0} if unavailable.

View File

@@ -185,6 +185,8 @@ class Target {
const struct in6_addr *v6sourceip() const; const struct in6_addr *v6sourceip() const;
/* The IPv4 or IPv6 literal string for the target host */ /* The IPv4 or IPv6 literal string for the target host */
const char *targetipstr() const { return targetipstring; } const char *targetipstr() const { return targetipstring; }
/* The IPv4 or IPv6 literal string for the source address */
const char *sourceipstr() const { return sourceipstring; }
/* Give the name from the last setHostName() call, which should be /* Give the name from the last setHostName() call, which should be
the name obtained from reverse-resolution (PTR query) of the IP (v4 the name obtained from reverse-resolution (PTR query) of the IP (v4
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
@@ -315,12 +317,15 @@ class Target {
private: private:
void Initialize(); void Initialize();
void FreeInternal(); // Free memory allocated inside this object void FreeInternal(); // Free memory allocated inside this object
// Creates a "presentation" formatted string out of the IPv4/IPv6 address // Creates a "presentation" formatted string out of the target's IPv4/IPv6 address
void GenerateIPString(); void GenerateTargetIPString();
// Creates a "presentation" formatted string out of the source IPv4/IPv6 address.
void GenerateSourceIPString();
struct sockaddr_storage targetsock, sourcesock, nexthopsock; struct sockaddr_storage targetsock, sourcesock, nexthopsock;
size_t targetsocklen, sourcesocklen, nexthopsocklen; size_t targetsocklen, sourcesocklen, nexthopsocklen;
int directly_connected; // -1 = unset; 0 = no; 1 = yes int directly_connected; // -1 = unset; 0 = no; 1 = yes
char targetipstring[INET6_ADDRSTRLEN]; char targetipstring[INET6_ADDRSTRLEN];
char sourceipstring[INET6_ADDRSTRLEN];
char *nameIPBuf; /* for the NameIP(void) function to return */ 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;

127
configure vendored
View File

@@ -606,6 +606,12 @@ NSOCKDIR
LIBNBASE_LIBS LIBNBASE_LIBS
NBASE_BUILD NBASE_BUILD
NBASEDIR NBASEDIR
LIBLINEAR_DIST_CLEAN
LIBLINEAR_CLEAN
LIBLINEAR_BUILD
LIBLINEAR_DEPENDS
LIBLINEARDIR
LIBLINEAR_LIBS
INSTALLNSE INSTALLNSE
LUA_DIST_CLEAN LUA_DIST_CLEAN
LUA_CLEAN LUA_CLEAN
@@ -741,6 +747,7 @@ with_libpcap
with_libpcre with_libpcre
with_libdnet with_libdnet
with_liblua with_liblua
with_liblinear
with_libnbase with_libnbase
with_libnsock with_libnsock
with_ncat with_ncat
@@ -1403,6 +1410,28 @@ Optional Packages:
--with-liblua=included Use the liblua version included with Nmap --with-liblua=included Use the liblua version included with Nmap
--without-liblua Compile without lua (this will exclude all of NSE --without-liblua Compile without lua (this will exclude all of NSE
from compilation) from compilation)
--with-liblinear=DIR Use an existing (compiled) liblinear from
DIR/include and DIR/lib.
--with-liblinear=included
Use the liblinear version included with Nmap
case "$with_liblinear" in
yes)
;;
included)
CPPFLAGS="-I\$(top_srcdir)/$LIBLINEARDIR $CPPFLAGS"
LIBLINEAR_LIBS="\$(top_srcdir)/$LIBLINEARDIR/liblinear.a"
LIBLINEAR_DEPENDS="\$(top_srcdir)/$LIBLINEARDIR/liblinear.a"
LIBLINEAR_BUILD="liblinear_build"
LIBLINEAR_CLEAN="liblinear_clean"
LIBLINEAR_DIST_CLEAN="liblinear_dist_clean"
have_liblinear=yes
;;
*)
CPPFLAGS="-I$with_liblinear/include $CPPFLAGS"
LDFLAGS="-L$with_liblinear/lib $LDFLAGS"
;;
esac
--with-libnbase=DIR Look for nbase include/libs in DIR --with-libnbase=DIR Look for nbase include/libs in DIR
--with-libnsock=DIR Compile and link to libnsock in DIR --with-libnsock=DIR Compile and link to libnsock in DIR
--without-ncat Skip build and installation of Ncat --without-ncat Skip build and installation of Ncat
@@ -6797,6 +6826,104 @@ fi
LIBLINEARDIR=liblinear
have_liblinear=no
# First we test whether they specified liblinear explicitly
# Check whether --with-liblinear was given.
if test "${with_liblinear+set}" = set; then :
withval=$with_liblinear;
fi
# If they didn't specify it, we try to find it
if test $have_liblinear != yes; then
for ac_header in linear.h
do :
ac_fn_c_check_header_mongrel "$LINENO" "linear.h" "ac_cv_header_linear_h" "$ac_includes_default"
if test "x$ac_cv_header_linear_h" = x""yes; then :
cat >>confdefs.h <<_ACEOF
#define HAVE_LINEAR_H 1
_ACEOF
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for predict in -llinear" >&5
$as_echo_n "checking for predict in -llinear... " >&6; }
if test "${ac_cv_lib_linear_predict+set}" = set; then :
$as_echo_n "(cached) " >&6
else
ac_check_lib_save_LIBS=$LIBS
LIBS="-llinear -lm $LIBS"
cat confdefs.h - <<_ACEOF >conftest.$ac_ext
/* end confdefs.h. */
/* Override any GCC internal prototype to avoid an error.
Use char because int might match the return type of a GCC
builtin and then its argument prototype would still apply. */
#ifdef __cplusplus
extern "C"
#endif
char predict ();
int
main ()
{
return predict ();
;
return 0;
}
_ACEOF
if ac_fn_c_try_link "$LINENO"; then :
ac_cv_lib_linear_predict=yes
else
ac_cv_lib_linear_predict=no
fi
rm -f core conftest.err conftest.$ac_objext \
conftest$ac_exeext conftest.$ac_ext
LIBS=$ac_check_lib_save_LIBS
fi
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_linear_predict" >&5
$as_echo "$ac_cv_lib_linear_predict" >&6; }
if test "x$ac_cv_lib_linear_predict" = x""yes; then :
have_liblinear=yes; LIBLINEAR_LIBS="-llinear"; break
fi
fi
done
LIBLINEAR_DEPENDS=""
LIBLINEAR_BUILD=""
LIBLINEAR_CLEAN=""
LIBLINEAR_DIST_CLEAN=""
fi
# if we didn't find we use our own
if test $have_liblinear != yes; then
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
$as_echo "no" >&6; }
CPPFLAGS="-I\$(top_srcdir)/$LIBLINEARDIR $CPPFLAGS"
LIBLINEAR_LIBS="\$(top_srcdir)/$LIBLINEARDIR/liblinear.a"
LIBLINEAR_DEPENDS="\$(top_srcdir)/$LIBLINEARDIR/liblinear.a"
LIBLINEAR_BUILD="liblinear_build"
LIBLINEAR_CLEAN="liblinear_clean"
LIBLINEAR_DIST_CLEAN="liblinear_dist_clean"
$as_echo "#define LIBLINEAR_INCLUDED 1" >>confdefs.h
else
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
$as_echo "yes" >&6; }
fi
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if sockaddr{} has sa_len member" >&5 { $as_echo "$as_me:${as_lineno-$LINENO}: checking if sockaddr{} has sa_len member" >&5
$as_echo_n "checking if sockaddr{} has sa_len member... " >&6; } $as_echo_n "checking if sockaddr{} has sa_len member... " >&6; }
if test "${ac_cv_sockaddr_has_sa_len+set}" = set; then : if test "${ac_cv_sockaddr_has_sa_len+set}" = set; then :

View File

@@ -645,6 +645,67 @@ AC_SUBST(LUA_DIST_CLEAN)
AC_SUBST(INSTALLNSE) AC_SUBST(INSTALLNSE)
AC_SUBST(CXXFLAGS) AC_SUBST(CXXFLAGS)
LIBLINEARDIR=liblinear
have_liblinear=no
# First we test whether they specified liblinear explicitly
AC_ARG_WITH(liblinear,
AC_HELP_STRING([--with-liblinear=DIR], [Use an existing (compiled) liblinear from DIR/include and DIR/lib.])
AC_HELP_STRING([--with-liblinear=included], [Use the liblinear version included with Nmap])
[ case "$with_liblinear" in
yes)
;;
included)
CPPFLAGS="-I\$(top_srcdir)/$LIBLINEARDIR $CPPFLAGS"
LIBLINEAR_LIBS="\$(top_srcdir)/$LIBLINEARDIR/liblinear.a"
LIBLINEAR_DEPENDS="\$(top_srcdir)/$LIBLINEARDIR/liblinear.a"
LIBLINEAR_BUILD="liblinear_build"
LIBLINEAR_CLEAN="liblinear_clean"
LIBLINEAR_DIST_CLEAN="liblinear_dist_clean"
have_liblinear=yes
;;
*)
CPPFLAGS="-I$with_liblinear/include $CPPFLAGS"
LDFLAGS="-L$with_liblinear/lib $LDFLAGS"
;;
esac]
)
# If they didn't specify it, we try to find it
if test $have_liblinear != yes; then
AC_CHECK_HEADERS([linear.h],
AC_CHECK_LIB(linear, predict, [have_liblinear=yes; LIBLINEAR_LIBS="-llinear"; break],, [-lm])
)
LIBLINEAR_DEPENDS=""
LIBLINEAR_BUILD=""
LIBLINEAR_CLEAN=""
LIBLINEAR_DIST_CLEAN=""
fi
# if we didn't find we use our own
if test $have_liblinear != yes; then
AC_MSG_RESULT(no)
CPPFLAGS="-I\$(top_srcdir)/$LIBLINEARDIR $CPPFLAGS"
LIBLINEAR_LIBS="\$(top_srcdir)/$LIBLINEARDIR/liblinear.a"
LIBLINEAR_DEPENDS="\$(top_srcdir)/$LIBLINEARDIR/liblinear.a"
LIBLINEAR_BUILD="liblinear_build"
LIBLINEAR_CLEAN="liblinear_clean"
LIBLINEAR_DIST_CLEAN="liblinear_dist_clean"
AC_DEFINE(LIBLINEAR_INCLUDED)
else
AC_MSG_RESULT(yes)
fi
AC_SUBST(LIBLINEAR_LIBS)
AC_SUBST(LIBLINEARDIR)
AC_SUBST(LIBLINEAR_DEPENDS)
AC_SUBST(LIBLINEAR_BUILD)
AC_SUBST(LIBLINEAR_CLEAN)
AC_SUBST(LIBLINEAR_DIST_CLEAN)
dnl This test is from the configure.in of Unix Network Programming second dnl This test is from the configure.in of Unix Network Programming second
dnl edition example code by W. Richard Stevens dnl edition example code by W. Richard Stevens
dnl ################################################################## dnl ##################################################################

View File

@@ -31,6 +31,8 @@ On all platforms, Nmap is normally linked with:
the subdirectory mswin32/OpenSSL. OpenSSL can be disabled by the subdirectory mswin32/OpenSSL. OpenSSL can be disabled by
configuring with the --without-openssl configuration directive. configuring with the --without-openssl configuration directive.
http://www.openssl.org/ http://www.openssl.org/
o LIBLINEAR. Used for IPv6 OS classifiction.
http://www.csie.ntu.edu.tw/~cjlin/liblinear/
On Windows only, Nmap uses: On Windows only, Nmap uses:
o WinPcap: libpcap for Windows. The libpcap license applies to WinPcap, o WinPcap: libpcap for Windows. The libpcap license applies to WinPcap,
@@ -390,6 +392,41 @@ http://www.winpcap.org/misc/copyright.htm.
======== ========
License of LIBLINEAR
Copyright (c) 2007-2011 The LIBLINEAR Project.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither name of copyright holders nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
========
License of Python License of Python
PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2 PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2

View File

@@ -169,6 +169,14 @@ struct OS_Classification {
std::vector<const char *> cpe; std::vector<const char *> cpe;
}; };
/* A description of an operating system: a human-readable name and a list of
classifications. */
struct FingerMatch {
int line; /* For reference prints, the line # in nmap-os-db */
char *OS_name;
std::vector<OS_Classification> OS_class;
};
struct FingerTest { struct FingerTest {
const char *name; const char *name;
std::vector<struct AVal> results; std::vector<struct AVal> results;
@@ -176,9 +184,7 @@ struct FingerTest {
}; };
struct FingerPrint { struct FingerPrint {
int line; /* For reference prints, the line # in nmap-os-db */ FingerMatch match;
char *OS_name;
std::vector<OS_Classification> OS_class;
std::vector<FingerTest> tests; std::vector<FingerTest> tests;
const FingerTest *gettestbyname(const char *name) const; const FingerTest *gettestbyname(const char *name) const;
FingerPrint(); FingerPrint();

31
liblinear/COPYRIGHT Normal file
View File

@@ -0,0 +1,31 @@
Copyright (c) 2007-2011 The LIBLINEAR Project.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither name of copyright holders nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

36
liblinear/Makefile Normal file
View File

@@ -0,0 +1,36 @@
CXX ?= g++
CC ?= gcc
CFLAGS = -Wall -Wconversion -O3 -fPIC
LIBS = blas/blas.a
SHVER = 1
AR = ar
RANLIB = ranlib
#LIBS = -lblas
all: train predict
lib: linear.o tron.o blas/blas.a
$(CXX) -shared -dynamiclib linear.o tron.o blas/blas.a -o liblinear.so.$(SHVER)
liblinear.a: linear.o tron.o blas/blas.a
$(AR) rcv liblinear.a linear.o tron.o blas/*.o
$(RANLIB) liblinear.a
train: tron.o linear.o train.c blas/blas.a
$(CXX) $(CFLAGS) -o train train.c tron.o linear.o $(LIBS)
predict: tron.o linear.o predict.c blas/blas.a
$(CXX) $(CFLAGS) -o predict predict.c tron.o linear.o $(LIBS)
tron.o: tron.cpp tron.h
$(CXX) $(CFLAGS) -c -o tron.o tron.cpp
linear.o: linear.cpp linear.h
$(CXX) $(CFLAGS) -c -o linear.o linear.cpp
blas/blas.a:
cd blas; make OPTFLAGS='$(CFLAGS)' CC='$(CC)';
clean:
cd blas; make clean
rm -f *~ tron.o linear.o train predict liblinear.so.$(SHVER) liblinear.a

30
liblinear/Makefile.win Normal file
View File

@@ -0,0 +1,30 @@
#You must ensure nmake.exe, cl.exe, link.exe are in system path.
#VCVARS32.bat
#Under dosbox prompt
#nmake -f Makefile.win
##########################################
CXXC = cl.exe
CFLAGS = -nologo -O2 -EHsc -I. -D __WIN32__ -D _CRT_SECURE_NO_DEPRECATE
TARGET = windows
all: $(TARGET)\train.exe $(TARGET)\predict.exe
$(TARGET)\train.exe: tron.obj linear.obj train.c blas\*.c
$(CXX) $(CFLAGS) -Fe$(TARGET)\train.exe tron.obj linear.obj train.c blas\*.c
$(TARGET)\predict.exe: tron.obj linear.obj predict.c blas\*.c
$(CXX) $(CFLAGS) -Fe$(TARGET)\predict.exe tron.obj linear.obj predict.c blas\*.c
linear.obj: linear.cpp linear.h
$(CXX) $(CFLAGS) -c linear.cpp
tron.obj: tron.cpp tron.h
$(CXX) $(CFLAGS) -c tron.cpp
lib: linear.cpp linear.h linear.def tron.obj
$(CXX) $(CFLAGS) -LD linear.cpp tron.obj blas\*.c -Fe$(TARGET)\liblinear -link -DEF:linear.def
clean:
-erase /Q *.obj $(TARGET)\.

485
liblinear/README Normal file
View File

@@ -0,0 +1,485 @@
LIBLINEAR is a simple package for solving large-scale regularized
linear classification. It currently supports L2-regularized logistic
regression/L2-loss support vector classification/L1-loss support vector
classification, and L1-regularized L2-loss support vector classification/
logistic regression. This document explains the usage of LIBLINEAR.
To get started, please read the ``Quick Start'' section first.
For developers, please check the ``Library Usage'' section to learn
how to integrate LIBLINEAR in your software.
Table of Contents
=================
- When to use LIBLINEAR but not LIBSVM
- Quick Start
- Installation
- `train' Usage
- `predict' Usage
- Examples
- Library Usage
- Building Windows Binaries
- Additional Information
- MATLAB/OCTAVE interface
- PYTHON interface
When to use LIBLINEAR but not LIBSVM
====================================
There are some large data for which with/without nonlinear mappings
gives similar performances. Without using kernels, one can
efficiently train a much larger set via a linear classifier. These
data usually have a large number of features. Document classification
is an example.
Warning: While generally liblinear is very fast, its default solver
may be slow under certain situations (e.g., data not scaled or C is
large). See Appendix B of our SVM guide about how to handle such
cases.
http://www.csie.ntu.edu.tw/~cjlin/papers/guide/guide.pdf
Warning: If you are a beginner and your data sets are not large, you
should consider LIBSVM first.
LIBSVM page:
http://www.csie.ntu.edu.tw/~cjlin/libsvm
Quick Start
===========
See the section ``Installation'' for installing LIBLINEAR.
After installation, there are programs `train' and `predict' for
training and testing, respectively.
About the data format, please check the README file of LIBSVM. Note
that feature index must start from 1 (but not 0).
A sample classification data included in this package is `heart_scale'.
Type `train heart_scale', and the program will read the training
data and output the model file `heart_scale.model'. If you have a test
set called heart_scale.t, then type `predict heart_scale.t
heart_scale.model output' to see the prediction accuracy. The `output'
file contains the predicted class labels.
For more information about `train' and `predict', see the sections
`train' Usage and `predict' Usage.
To obtain good performances, sometimes one needs to scale the
data. Please check the program `svm-scale' of LIBSVM. For large and
sparse data, use `-l 0' to keep the sparsity.
Installation
============
On Unix systems, type `make' to build the `train' and `predict'
programs. Run them without arguments to show the usages.
On other systems, consult `Makefile' to build them (e.g., see
'Building Windows binaries' in this file) or use the pre-built
binaries (Windows binaries are in the directory `windows').
This software uses some level-1 BLAS subroutines. The needed functions are
included in this package. If a BLAS library is available on your
machine, you may use it by modifying the Makefile: Unmark the following line
#LIBS ?= -lblas
and mark
LIBS ?= blas/blas.a
`train' Usage
=============
Usage: train [options] training_set_file [model_file]
options:
-s type : set type of solver (default 1)
0 -- L2-regularized logistic regression (primal)
1 -- L2-regularized L2-loss support vector classification (dual)
2 -- L2-regularized L2-loss support vector classification (primal)
3 -- L2-regularized L1-loss support vector classification (dual)
4 -- multi-class support vector classification by Crammer and Singer
5 -- L1-regularized L2-loss support vector classification
6 -- L1-regularized logistic regression
7 -- L2-regularized logistic regression (dual)
-c cost : set the parameter C (default 1)
-e epsilon : set tolerance of termination criterion
-s 0 and 2
|f'(w)|_2 <= eps*min(pos,neg)/l*|f'(w0)|_2,
where f is the primal function and pos/neg are # of
positive/negative data (default 0.01)
-s 1, 3, 4 and 7
Dual maximal violation <= eps; similar to libsvm (default 0.1)
-s 5 and 6
|f'(w)|_inf <= eps*min(pos,neg)/l*|f'(w0)|_inf,
where f is the primal function (default 0.01)
-B bias : if bias >= 0, instance x becomes [x; bias]; if < 0, no bias term added (default -1)
-wi weight: weights adjust the parameter C of different classes (see README for details)
-v n: n-fold cross validation mode
-q : quiet mode (no outputs)
Option -v randomly splits the data into n parts and calculates cross
validation accuracy on them.
Formulations:
For L2-regularized logistic regression (-s 0), we solve
min_w w^Tw/2 + C \sum log(1 + exp(-y_i w^Tx_i))
For L2-regularized L2-loss SVC dual (-s 1), we solve
min_alpha 0.5(alpha^T (Q + I/2/C) alpha) - e^T alpha
s.t. 0 <= alpha_i,
For L2-regularized L2-loss SVC (-s 2), we solve
min_w w^Tw/2 + C \sum max(0, 1- y_i w^Tx_i)^2
For L2-regularized L1-loss SVC dual (-s 3), we solve
min_alpha 0.5(alpha^T Q alpha) - e^T alpha
s.t. 0 <= alpha_i <= C,
For L1-regularized L2-loss SVC (-s 5), we solve
min_w \sum |w_j| + C \sum max(0, 1- y_i w^Tx_i)^2
For L1-regularized logistic regression (-s 6), we solve
min_w \sum |w_j| + C \sum log(1 + exp(-y_i w^Tx_i))
where
Q is a matrix with Q_ij = y_i y_j x_i^T x_j.
For L2-regularized logistic regression (-s 7), we solve
min_alpha 0.5(alpha^T Q alpha) + \sum alpha_i*log(alpha_i) + \sum (C-alpha_i)*log(C-alpha_i) - a constant
s.t. 0 <= alpha_i <= C,
If bias >= 0, w becomes [w; w_{n+1}] and x becomes [x; bias].
The primal-dual relationship implies that -s 1 and -s 2 give the same
model, and -s 0 and -s 7 give the same.
We implement 1-vs-the rest multi-class strategy. In training i
vs. non_i, their C parameters are (weight from -wi)*C and C,
respectively. If there are only two classes, we train only one
model. Thus weight1*C vs. weight2*C is used. See examples below.
We also implement multi-class SVM by Crammer and Singer (-s 4):
min_{w_m, \xi_i} 0.5 \sum_m ||w_m||^2 + C \sum_i \xi_i
s.t. w^T_{y_i} x_i - w^T_m x_i >= \e^m_i - \xi_i \forall m,i
where e^m_i = 0 if y_i = m,
e^m_i = 1 if y_i != m,
Here we solve the dual problem:
min_{\alpha} 0.5 \sum_m ||w_m(\alpha)||^2 + \sum_i \sum_m e^m_i alpha^m_i
s.t. \alpha^m_i <= C^m_i \forall m,i , \sum_m \alpha^m_i=0 \forall i
where w_m(\alpha) = \sum_i \alpha^m_i x_i,
and C^m_i = C if m = y_i,
C^m_i = 0 if m != y_i.
`predict' Usage
===============
Usage: predict [options] test_file model_file output_file
options:
-b probability_estimates: whether to predict probability estimates, 0 or 1 (default 0)
Examples
========
> train data_file
Train linear SVM with L2-loss function.
> train -s 0 data_file
Train a logistic regression model.
> train -v 5 -e 0.001 data_file
Do five-fold cross-validation using L2-loss svm.
Use a smaller stopping tolerance 0.001 than the default
0.1 if you want more accurate solutions.
> train -c 10 -w1 2 -w2 5 -w3 2 four_class_data_file
Train four classifiers:
positive negative Cp Cn
class 1 class 2,3,4. 20 10
class 2 class 1,3,4. 50 10
class 3 class 1,2,4. 20 10
class 4 class 1,2,3. 10 10
> train -c 10 -w3 1 -w2 5 two_class_data_file
If there are only two classes, we train ONE model.
The C values for the two classes are 10 and 50.
> predict -b 1 test_file data_file.model output_file
Output probability estimates (for logistic regression only).
Library Usage
=============
- Function: model* train(const struct problem *prob,
const struct parameter *param);
This function constructs and returns a linear classification model
according to the given training data and parameters.
struct problem describes the problem:
struct problem
{
int l, n;
int *y;
struct feature_node **x;
double bias;
};
where `l' is the number of training data. If bias >= 0, we assume
that one additional feature is added to the end of each data
instance. `n' is the number of feature (including the bias feature
if bias >= 0). `y' is an array containing the target values. And
`x' is an array of pointers,
each of which points to a sparse representation (array of feature_node) of one
training vector.
For example, if we have the following training data:
LABEL ATTR1 ATTR2 ATTR3 ATTR4 ATTR5
----- ----- ----- ----- ----- -----
1 0 0.1 0.2 0 0
2 0 0.1 0.3 -1.2 0
1 0.4 0 0 0 0
2 0 0.1 0 1.4 0.5
3 -0.1 -0.2 0.1 1.1 0.1
and bias = 1, then the components of problem are:
l = 5
n = 6
y -> 1 2 1 2 3
x -> [ ] -> (2,0.1) (3,0.2) (6,1) (-1,?)
[ ] -> (2,0.1) (3,0.3) (4,-1.2) (6,1) (-1,?)
[ ] -> (1,0.4) (6,1) (-1,?)
[ ] -> (2,0.1) (4,1.4) (5,0.5) (6,1) (-1,?)
[ ] -> (1,-0.1) (2,-0.2) (3,0.1) (4,1.1) (5,0.1) (6,1) (-1,?)
struct parameter describes the parameters of a linear classification model:
struct parameter
{
int solver_type;
/* these are for training only */
double eps; /* stopping criteria */
double C;
int nr_weight;
int *weight_label;
double* weight;
};
solver_type can be one of L2R_LR, L2R_L2LOSS_SVC_DUAL, L2R_L2LOSS_SVC, L2R_L1LOSS_SVC_DUAL, MCSVM_CS, L1R_L2LOSS_SVC, L1R_LR, L2R_LR_DUAL.
L2R_LR L2-regularized logistic regression (primal)
L2R_L2LOSS_SVC_DUAL L2-regularized L2-loss support vector classification (dual)
L2R_L2LOSS_SVC L2-regularized L2-loss support vector classification (primal)
L2R_L1LOSS_SVC_DUAL L2-regularized L1-loss support vector classification (dual)
MCSVM_CS multi-class support vector classification by Crammer and Singer
L1R_L2LOSS_SVC L1-regularized L2-loss support vector classification
L1R_LR L1-regularized logistic regression
L2R_LR_DUAL L2-regularized logistic regression (dual)
C is the cost of constraints violation.
eps is the stopping criterion.
nr_weight, weight_label, and weight are used to change the penalty
for some classes (If the weight for a class is not changed, it is
set to 1). This is useful for training classifier using unbalanced
input data or with asymmetric misclassification cost.
nr_weight is the number of elements in the array weight_label and
weight. Each weight[i] corresponds to weight_label[i], meaning that
the penalty of class weight_label[i] is scaled by a factor of weight[i].
If you do not want to change penalty for any of the classes,
just set nr_weight to 0.
*NOTE* To avoid wrong parameters, check_parameter() should be
called before train().
struct model stores the model obtained from the training procedure:
struct model
{
struct parameter param;
int nr_class; /* number of classes */
int nr_feature;
double *w;
int *label; /* label of each class */
double bias;
};
param describes the parameters used to obtain the model.
nr_class and nr_feature are the number of classes and features, respectively.
The nr_feature*nr_class array w gives feature weights. We use one
against the rest for multi-class classification, so each feature
index corresponds to nr_class weight values. Weights are
organized in the following way
+------------------+------------------+------------+
| nr_class weights | nr_class weights | ...
| for 1st feature | for 2nd feature |
+------------------+------------------+------------+
If bias >= 0, x becomes [x; bias]. The number of features is
increased by one, so w is a (nr_feature+1)*nr_class array. The
value of bias is stored in the variable bias.
The array label stores class labels.
- Function: void cross_validation(const problem *prob, const parameter *param, int nr_fold, int *target);
This function conducts cross validation. Data are separated to
nr_fold folds. Under given parameters, sequentially each fold is
validated using the model from training the remaining. Predicted
labels in the validation process are stored in the array called
target.
The format of prob is same as that for train().
- Function: int predict(const model *model_, const feature_node *x);
This functions classifies a test vector using the given
model. The predicted label is returned.
- Function: int predict_values(const struct model *model_,
const struct feature_node *x, double* dec_values);
This function gives nr_w decision values in the array
dec_values. nr_w is 1 if there are two classes except multi-class
svm by Crammer and Singer (-s 4), and is the number of classes otherwise.
We implement one-vs-the rest multi-class strategy (-s 0,1,2,3) and
multi-class svm by Crammer and Singer (-s 4) for multi-class SVM.
The class with the highest decision value is returned.
- Function: int predict_probability(const struct model *model_,
const struct feature_node *x, double* prob_estimates);
This function gives nr_class probability estimates in the array
prob_estimates. nr_class can be obtained from the function
get_nr_class. The class with the highest probability is
returned. Currently, we support only the probability outputs of
logistic regression.
- Function: int get_nr_feature(const model *model_);
The function gives the number of attributes of the model.
- Function: int get_nr_class(const model *model_);
The function gives the number of classes of the model.
- Function: void get_labels(const model *model_, int* label);
This function outputs the name of labels into an array called label.
- Function: const char *check_parameter(const struct problem *prob,
const struct parameter *param);
This function checks whether the parameters are within the feasible
range of the problem. This function should be called before calling
train() and cross_validation(). It returns NULL if the
parameters are feasible, otherwise an error message is returned.
- Function: int save_model(const char *model_file_name,
const struct model *model_);
This function saves a model to a file; returns 0 on success, or -1
if an error occurs.
- Function: struct model *load_model(const char *model_file_name);
This function returns a pointer to the model read from the file,
or a null pointer if the model could not be loaded.
- Function: void free_model_content(struct model *model_ptr);
This function frees the memory used by the entries in a model structure.
- Function: void free_and_destroy_model(struct model **model_ptr_ptr);
This function frees the memory used by a model and destroys the model
structure.
- Function: void destroy_param(struct parameter *param);
This function frees the memory used by a parameter set.
- Function: void set_print_string_function(void (*print_func)(const char *));
Users can specify their output format by a function. Use
set_print_string_function(NULL);
for default printing to stdout.
Building Windows Binaries
=========================
Windows binaries are in the directory `windows'. To build them via
Visual C++, use the following steps:
1. Open a dos command box and change to liblinear directory. If
environment variables of VC++ have not been set, type
"C:\Program Files\Microsoft Visual Studio 10.0\VC\bin\vcvars32.bat"
You may have to modify the above command according which version of
VC++ or where it is installed.
2. Type
nmake -f Makefile.win clean all
MATLAB/OCTAVE Interface
=======================
Please check the file README in the directory `matlab'.
PYTHON Interface
================
Please check the file README in the directory `python'.
Additional Information
======================
If you find LIBLINEAR helpful, please cite it as
R.-E. Fan, K.-W. Chang, C.-J. Hsieh, X.-R. Wang, and C.-J. Lin.
LIBLINEAR: A Library for Large Linear Classification, Journal of
Machine Learning Research 9(2008), 1871-1874. Software available at
http://www.csie.ntu.edu.tw/~cjlin/liblinear
For any questions and comments, please send your email to
cjlin@csie.ntu.edu.tw

22
liblinear/blas/Makefile Normal file
View File

@@ -0,0 +1,22 @@
AR = ar rcv
RANLIB = ranlib
HEADERS = blas.h blas.h blasp.h
FILES = dnrm2.o daxpy.o ddot.o dscal.o
CFLAGS = $(OPTFLAGS)
FFLAGS = $(OPTFLAGS)
blas: $(FILES) $(HEADERS)
$(AR) blas.a $(FILES)
$(RANLIB) blas.a
clean:
- rm -f *.o
- rm -f *.a
- rm -f *~
.c.o:
$(CC) $(CFLAGS) -c $*.c

25
liblinear/blas/blas.h Normal file
View File

@@ -0,0 +1,25 @@
/* blas.h -- C header file for BLAS Ver 1.0 */
/* Jesse Bennett March 23, 2000 */
/** barf [ba:rf] 2. "He suggested using FORTRAN, and everybody barfed."
- From The Shogakukan DICTIONARY OF NEW ENGLISH (Second edition) */
#ifndef BLAS_INCLUDE
#define BLAS_INCLUDE
/* Data types specific to BLAS implementation */
typedef struct { float r, i; } fcomplex;
typedef struct { double r, i; } dcomplex;
typedef int blasbool;
#include "blasp.h" /* Prototypes for all BLAS functions */
#define FALSE 0
#define TRUE 1
/* Macro functions */
#define MIN(a,b) ((a) <= (b) ? (a) : (b))
#define MAX(a,b) ((a) >= (b) ? (a) : (b))
#endif

430
liblinear/blas/blasp.h Normal file
View File

@@ -0,0 +1,430 @@
/* blasp.h -- C prototypes for BLAS Ver 1.0 */
/* Jesse Bennett March 23, 2000 */
/* Functions listed in alphabetical order */
#ifdef F2C_COMPAT
void cdotc_(fcomplex *dotval, int *n, fcomplex *cx, int *incx,
fcomplex *cy, int *incy);
void cdotu_(fcomplex *dotval, int *n, fcomplex *cx, int *incx,
fcomplex *cy, int *incy);
double sasum_(int *n, float *sx, int *incx);
double scasum_(int *n, fcomplex *cx, int *incx);
double scnrm2_(int *n, fcomplex *x, int *incx);
double sdot_(int *n, float *sx, int *incx, float *sy, int *incy);
double snrm2_(int *n, float *x, int *incx);
void zdotc_(dcomplex *dotval, int *n, dcomplex *cx, int *incx,
dcomplex *cy, int *incy);
void zdotu_(dcomplex *dotval, int *n, dcomplex *cx, int *incx,
dcomplex *cy, int *incy);
#else
fcomplex cdotc_(int *n, fcomplex *cx, int *incx, fcomplex *cy, int *incy);
fcomplex cdotu_(int *n, fcomplex *cx, int *incx, fcomplex *cy, int *incy);
float sasum_(int *n, float *sx, int *incx);
float scasum_(int *n, fcomplex *cx, int *incx);
float scnrm2_(int *n, fcomplex *x, int *incx);
float sdot_(int *n, float *sx, int *incx, float *sy, int *incy);
float snrm2_(int *n, float *x, int *incx);
dcomplex zdotc_(int *n, dcomplex *cx, int *incx, dcomplex *cy, int *incy);
dcomplex zdotu_(int *n, dcomplex *cx, int *incx, dcomplex *cy, int *incy);
#endif
/* Remaining functions listed in alphabetical order */
int caxpy_(int *n, fcomplex *ca, fcomplex *cx, int *incx, fcomplex *cy,
int *incy);
int ccopy_(int *n, fcomplex *cx, int *incx, fcomplex *cy, int *incy);
int cgbmv_(char *trans, int *m, int *n, int *kl, int *ku,
fcomplex *alpha, fcomplex *a, int *lda, fcomplex *x, int *incx,
fcomplex *beta, fcomplex *y, int *incy);
int cgemm_(char *transa, char *transb, int *m, int *n, int *k,
fcomplex *alpha, fcomplex *a, int *lda, fcomplex *b, int *ldb,
fcomplex *beta, fcomplex *c, int *ldc);
int cgemv_(char *trans, int *m, int *n, fcomplex *alpha, fcomplex *a,
int *lda, fcomplex *x, int *incx, fcomplex *beta, fcomplex *y,
int *incy);
int cgerc_(int *m, int *n, fcomplex *alpha, fcomplex *x, int *incx,
fcomplex *y, int *incy, fcomplex *a, int *lda);
int cgeru_(int *m, int *n, fcomplex *alpha, fcomplex *x, int *incx,
fcomplex *y, int *incy, fcomplex *a, int *lda);
int chbmv_(char *uplo, int *n, int *k, fcomplex *alpha, fcomplex *a,
int *lda, fcomplex *x, int *incx, fcomplex *beta, fcomplex *y,
int *incy);
int chemm_(char *side, char *uplo, int *m, int *n, fcomplex *alpha,
fcomplex *a, int *lda, fcomplex *b, int *ldb, fcomplex *beta,
fcomplex *c, int *ldc);
int chemv_(char *uplo, int *n, fcomplex *alpha, fcomplex *a, int *lda,
fcomplex *x, int *incx, fcomplex *beta, fcomplex *y, int *incy);
int cher_(char *uplo, int *n, float *alpha, fcomplex *x, int *incx,
fcomplex *a, int *lda);
int cher2_(char *uplo, int *n, fcomplex *alpha, fcomplex *x, int *incx,
fcomplex *y, int *incy, fcomplex *a, int *lda);
int cher2k_(char *uplo, char *trans, int *n, int *k, fcomplex *alpha,
fcomplex *a, int *lda, fcomplex *b, int *ldb, float *beta,
fcomplex *c, int *ldc);
int cherk_(char *uplo, char *trans, int *n, int *k, float *alpha,
fcomplex *a, int *lda, float *beta, fcomplex *c, int *ldc);
int chpmv_(char *uplo, int *n, fcomplex *alpha, fcomplex *ap, fcomplex *x,
int *incx, fcomplex *beta, fcomplex *y, int *incy);
int chpr_(char *uplo, int *n, float *alpha, fcomplex *x, int *incx,
fcomplex *ap);
int chpr2_(char *uplo, int *n, fcomplex *alpha, fcomplex *x, int *incx,
fcomplex *y, int *incy, fcomplex *ap);
int crotg_(fcomplex *ca, fcomplex *cb, float *c, fcomplex *s);
int cscal_(int *n, fcomplex *ca, fcomplex *cx, int *incx);
int csscal_(int *n, float *sa, fcomplex *cx, int *incx);
int cswap_(int *n, fcomplex *cx, int *incx, fcomplex *cy, int *incy);
int csymm_(char *side, char *uplo, int *m, int *n, fcomplex *alpha,
fcomplex *a, int *lda, fcomplex *b, int *ldb, fcomplex *beta,
fcomplex *c, int *ldc);
int csyr2k_(char *uplo, char *trans, int *n, int *k, fcomplex *alpha,
fcomplex *a, int *lda, fcomplex *b, int *ldb, fcomplex *beta,
fcomplex *c, int *ldc);
int csyrk_(char *uplo, char *trans, int *n, int *k, fcomplex *alpha,
fcomplex *a, int *lda, fcomplex *beta, fcomplex *c, int *ldc);
int ctbmv_(char *uplo, char *trans, char *diag, int *n, int *k,
fcomplex *a, int *lda, fcomplex *x, int *incx);
int ctbsv_(char *uplo, char *trans, char *diag, int *n, int *k,
fcomplex *a, int *lda, fcomplex *x, int *incx);
int ctpmv_(char *uplo, char *trans, char *diag, int *n, fcomplex *ap,
fcomplex *x, int *incx);
int ctpsv_(char *uplo, char *trans, char *diag, int *n, fcomplex *ap,
fcomplex *x, int *incx);
int ctrmm_(char *side, char *uplo, char *transa, char *diag, int *m,
int *n, fcomplex *alpha, fcomplex *a, int *lda, fcomplex *b,
int *ldb);
int ctrmv_(char *uplo, char *trans, char *diag, int *n, fcomplex *a,
int *lda, fcomplex *x, int *incx);
int ctrsm_(char *side, char *uplo, char *transa, char *diag, int *m,
int *n, fcomplex *alpha, fcomplex *a, int *lda, fcomplex *b,
int *ldb);
int ctrsv_(char *uplo, char *trans, char *diag, int *n, fcomplex *a,
int *lda, fcomplex *x, int *incx);
int daxpy_(int *n, double *sa, double *sx, int *incx, double *sy,
int *incy);
int dcopy_(int *n, double *sx, int *incx, double *sy, int *incy);
int dgbmv_(char *trans, int *m, int *n, int *kl, int *ku,
double *alpha, double *a, int *lda, double *x, int *incx,
double *beta, double *y, int *incy);
int dgemm_(char *transa, char *transb, int *m, int *n, int *k,
double *alpha, double *a, int *lda, double *b, int *ldb,
double *beta, double *c, int *ldc);
int dgemv_(char *trans, int *m, int *n, double *alpha, double *a,
int *lda, double *x, int *incx, double *beta, double *y,
int *incy);
int dger_(int *m, int *n, double *alpha, double *x, int *incx,
double *y, int *incy, double *a, int *lda);
int drot_(int *n, double *sx, int *incx, double *sy, int *incy,
double *c, double *s);
int drotg_(double *sa, double *sb, double *c, double *s);
int dsbmv_(char *uplo, int *n, int *k, double *alpha, double *a,
int *lda, double *x, int *incx, double *beta, double *y,
int *incy);
int dscal_(int *n, double *sa, double *sx, int *incx);
int dspmv_(char *uplo, int *n, double *alpha, double *ap, double *x,
int *incx, double *beta, double *y, int *incy);
int dspr_(char *uplo, int *n, double *alpha, double *x, int *incx,
double *ap);
int dspr2_(char *uplo, int *n, double *alpha, double *x, int *incx,
double *y, int *incy, double *ap);
int dswap_(int *n, double *sx, int *incx, double *sy, int *incy);
int dsymm_(char *side, char *uplo, int *m, int *n, double *alpha,
double *a, int *lda, double *b, int *ldb, double *beta,
double *c, int *ldc);
int dsymv_(char *uplo, int *n, double *alpha, double *a, int *lda,
double *x, int *incx, double *beta, double *y, int *incy);
int dsyr_(char *uplo, int *n, double *alpha, double *x, int *incx,
double *a, int *lda);
int dsyr2_(char *uplo, int *n, double *alpha, double *x, int *incx,
double *y, int *incy, double *a, int *lda);
int dsyr2k_(char *uplo, char *trans, int *n, int *k, double *alpha,
double *a, int *lda, double *b, int *ldb, double *beta,
double *c, int *ldc);
int dsyrk_(char *uplo, char *trans, int *n, int *k, double *alpha,
double *a, int *lda, double *beta, double *c, int *ldc);
int dtbmv_(char *uplo, char *trans, char *diag, int *n, int *k,
double *a, int *lda, double *x, int *incx);
int dtbsv_(char *uplo, char *trans, char *diag, int *n, int *k,
double *a, int *lda, double *x, int *incx);
int dtpmv_(char *uplo, char *trans, char *diag, int *n, double *ap,
double *x, int *incx);
int dtpsv_(char *uplo, char *trans, char *diag, int *n, double *ap,
double *x, int *incx);
int dtrmm_(char *side, char *uplo, char *transa, char *diag, int *m,
int *n, double *alpha, double *a, int *lda, double *b,
int *ldb);
int dtrmv_(char *uplo, char *trans, char *diag, int *n, double *a,
int *lda, double *x, int *incx);
int dtrsm_(char *side, char *uplo, char *transa, char *diag, int *m,
int *n, double *alpha, double *a, int *lda, double *b,
int *ldb);
int dtrsv_(char *uplo, char *trans, char *diag, int *n, double *a,
int *lda, double *x, int *incx);
int saxpy_(int *n, float *sa, float *sx, int *incx, float *sy, int *incy);
int scopy_(int *n, float *sx, int *incx, float *sy, int *incy);
int sgbmv_(char *trans, int *m, int *n, int *kl, int *ku,
float *alpha, float *a, int *lda, float *x, int *incx,
float *beta, float *y, int *incy);
int sgemm_(char *transa, char *transb, int *m, int *n, int *k,
float *alpha, float *a, int *lda, float *b, int *ldb,
float *beta, float *c, int *ldc);
int sgemv_(char *trans, int *m, int *n, float *alpha, float *a,
int *lda, float *x, int *incx, float *beta, float *y,
int *incy);
int sger_(int *m, int *n, float *alpha, float *x, int *incx,
float *y, int *incy, float *a, int *lda);
int srot_(int *n, float *sx, int *incx, float *sy, int *incy,
float *c, float *s);
int srotg_(float *sa, float *sb, float *c, float *s);
int ssbmv_(char *uplo, int *n, int *k, float *alpha, float *a,
int *lda, float *x, int *incx, float *beta, float *y,
int *incy);
int sscal_(int *n, float *sa, float *sx, int *incx);
int sspmv_(char *uplo, int *n, float *alpha, float *ap, float *x,
int *incx, float *beta, float *y, int *incy);
int sspr_(char *uplo, int *n, float *alpha, float *x, int *incx,
float *ap);
int sspr2_(char *uplo, int *n, float *alpha, float *x, int *incx,
float *y, int *incy, float *ap);
int sswap_(int *n, float *sx, int *incx, float *sy, int *incy);
int ssymm_(char *side, char *uplo, int *m, int *n, float *alpha,
float *a, int *lda, float *b, int *ldb, float *beta,
float *c, int *ldc);
int ssymv_(char *uplo, int *n, float *alpha, float *a, int *lda,
float *x, int *incx, float *beta, float *y, int *incy);
int ssyr_(char *uplo, int *n, float *alpha, float *x, int *incx,
float *a, int *lda);
int ssyr2_(char *uplo, int *n, float *alpha, float *x, int *incx,
float *y, int *incy, float *a, int *lda);
int ssyr2k_(char *uplo, char *trans, int *n, int *k, float *alpha,
float *a, int *lda, float *b, int *ldb, float *beta,
float *c, int *ldc);
int ssyrk_(char *uplo, char *trans, int *n, int *k, float *alpha,
float *a, int *lda, float *beta, float *c, int *ldc);
int stbmv_(char *uplo, char *trans, char *diag, int *n, int *k,
float *a, int *lda, float *x, int *incx);
int stbsv_(char *uplo, char *trans, char *diag, int *n, int *k,
float *a, int *lda, float *x, int *incx);
int stpmv_(char *uplo, char *trans, char *diag, int *n, float *ap,
float *x, int *incx);
int stpsv_(char *uplo, char *trans, char *diag, int *n, float *ap,
float *x, int *incx);
int strmm_(char *side, char *uplo, char *transa, char *diag, int *m,
int *n, float *alpha, float *a, int *lda, float *b,
int *ldb);
int strmv_(char *uplo, char *trans, char *diag, int *n, float *a,
int *lda, float *x, int *incx);
int strsm_(char *side, char *uplo, char *transa, char *diag, int *m,
int *n, float *alpha, float *a, int *lda, float *b,
int *ldb);
int strsv_(char *uplo, char *trans, char *diag, int *n, float *a,
int *lda, float *x, int *incx);
int zaxpy_(int *n, dcomplex *ca, dcomplex *cx, int *incx, dcomplex *cy,
int *incy);
int zcopy_(int *n, dcomplex *cx, int *incx, dcomplex *cy, int *incy);
int zdscal_(int *n, double *sa, dcomplex *cx, int *incx);
int zgbmv_(char *trans, int *m, int *n, int *kl, int *ku,
dcomplex *alpha, dcomplex *a, int *lda, dcomplex *x, int *incx,
dcomplex *beta, dcomplex *y, int *incy);
int zgemm_(char *transa, char *transb, int *m, int *n, int *k,
dcomplex *alpha, dcomplex *a, int *lda, dcomplex *b, int *ldb,
dcomplex *beta, dcomplex *c, int *ldc);
int zgemv_(char *trans, int *m, int *n, dcomplex *alpha, dcomplex *a,
int *lda, dcomplex *x, int *incx, dcomplex *beta, dcomplex *y,
int *incy);
int zgerc_(int *m, int *n, dcomplex *alpha, dcomplex *x, int *incx,
dcomplex *y, int *incy, dcomplex *a, int *lda);
int zgeru_(int *m, int *n, dcomplex *alpha, dcomplex *x, int *incx,
dcomplex *y, int *incy, dcomplex *a, int *lda);
int zhbmv_(char *uplo, int *n, int *k, dcomplex *alpha, dcomplex *a,
int *lda, dcomplex *x, int *incx, dcomplex *beta, dcomplex *y,
int *incy);
int zhemm_(char *side, char *uplo, int *m, int *n, dcomplex *alpha,
dcomplex *a, int *lda, dcomplex *b, int *ldb, dcomplex *beta,
dcomplex *c, int *ldc);
int zhemv_(char *uplo, int *n, dcomplex *alpha, dcomplex *a, int *lda,
dcomplex *x, int *incx, dcomplex *beta, dcomplex *y, int *incy);
int zher_(char *uplo, int *n, double *alpha, dcomplex *x, int *incx,
dcomplex *a, int *lda);
int zher2_(char *uplo, int *n, dcomplex *alpha, dcomplex *x, int *incx,
dcomplex *y, int *incy, dcomplex *a, int *lda);
int zher2k_(char *uplo, char *trans, int *n, int *k, dcomplex *alpha,
dcomplex *a, int *lda, dcomplex *b, int *ldb, double *beta,
dcomplex *c, int *ldc);
int zherk_(char *uplo, char *trans, int *n, int *k, double *alpha,
dcomplex *a, int *lda, double *beta, dcomplex *c, int *ldc);
int zhpmv_(char *uplo, int *n, dcomplex *alpha, dcomplex *ap, dcomplex *x,
int *incx, dcomplex *beta, dcomplex *y, int *incy);
int zhpr_(char *uplo, int *n, double *alpha, dcomplex *x, int *incx,
dcomplex *ap);
int zhpr2_(char *uplo, int *n, dcomplex *alpha, dcomplex *x, int *incx,
dcomplex *y, int *incy, dcomplex *ap);
int zrotg_(dcomplex *ca, dcomplex *cb, double *c, dcomplex *s);
int zscal_(int *n, dcomplex *ca, dcomplex *cx, int *incx);
int zswap_(int *n, dcomplex *cx, int *incx, dcomplex *cy, int *incy);
int zsymm_(char *side, char *uplo, int *m, int *n, dcomplex *alpha,
dcomplex *a, int *lda, dcomplex *b, int *ldb, dcomplex *beta,
dcomplex *c, int *ldc);
int zsyr2k_(char *uplo, char *trans, int *n, int *k, dcomplex *alpha,
dcomplex *a, int *lda, dcomplex *b, int *ldb, dcomplex *beta,
dcomplex *c, int *ldc);
int zsyrk_(char *uplo, char *trans, int *n, int *k, dcomplex *alpha,
dcomplex *a, int *lda, dcomplex *beta, dcomplex *c, int *ldc);
int ztbmv_(char *uplo, char *trans, char *diag, int *n, int *k,
dcomplex *a, int *lda, dcomplex *x, int *incx);
int ztbsv_(char *uplo, char *trans, char *diag, int *n, int *k,
dcomplex *a, int *lda, dcomplex *x, int *incx);
int ztpmv_(char *uplo, char *trans, char *diag, int *n, dcomplex *ap,
dcomplex *x, int *incx);
int ztpsv_(char *uplo, char *trans, char *diag, int *n, dcomplex *ap,
dcomplex *x, int *incx);
int ztrmm_(char *side, char *uplo, char *transa, char *diag, int *m,
int *n, dcomplex *alpha, dcomplex *a, int *lda, dcomplex *b,
int *ldb);
int ztrmv_(char *uplo, char *trans, char *diag, int *n, dcomplex *a,
int *lda, dcomplex *x, int *incx);
int ztrsm_(char *side, char *uplo, char *transa, char *diag, int *m,
int *n, dcomplex *alpha, dcomplex *a, int *lda, dcomplex *b,
int *ldb);
int ztrsv_(char *uplo, char *trans, char *diag, int *n, dcomplex *a,
int *lda, dcomplex *x, int *incx);

49
liblinear/blas/daxpy.c Normal file
View File

@@ -0,0 +1,49 @@
#include "blas.h"
int daxpy_(int *n, double *sa, double *sx, int *incx, double *sy,
int *incy)
{
long int i, m, ix, iy, nn, iincx, iincy;
register double ssa;
/* constant times a vector plus a vector.
uses unrolled loop for increments equal to one.
jack dongarra, linpack, 3/11/78.
modified 12/3/93, array(1) declarations changed to array(*) */
/* Dereference inputs */
nn = *n;
ssa = *sa;
iincx = *incx;
iincy = *incy;
if( nn > 0 && ssa != 0.0 )
{
if (iincx == 1 && iincy == 1) /* code for both increments equal to 1 */
{
m = nn-3;
for (i = 0; i < m; i += 4)
{
sy[i] += ssa * sx[i];
sy[i+1] += ssa * sx[i+1];
sy[i+2] += ssa * sx[i+2];
sy[i+3] += ssa * sx[i+3];
}
for ( ; i < nn; ++i) /* clean-up loop */
sy[i] += ssa * sx[i];
}
else /* code for unequal increments or equal increments not equal to 1 */
{
ix = iincx >= 0 ? 0 : (1 - nn) * iincx;
iy = iincy >= 0 ? 0 : (1 - nn) * iincy;
for (i = 0; i < nn; i++)
{
sy[iy] += ssa * sx[ix];
ix += iincx;
iy += iincy;
}
}
}
return 0;
} /* daxpy_ */

50
liblinear/blas/ddot.c Normal file
View File

@@ -0,0 +1,50 @@
#include "blas.h"
double ddot_(int *n, double *sx, int *incx, double *sy, int *incy)
{
long int i, m, nn, iincx, iincy;
double stemp;
long int ix, iy;
/* forms the dot product of two vectors.
uses unrolled loops for increments equal to one.
jack dongarra, linpack, 3/11/78.
modified 12/3/93, array(1) declarations changed to array(*) */
/* Dereference inputs */
nn = *n;
iincx = *incx;
iincy = *incy;
stemp = 0.0;
if (nn > 0)
{
if (iincx == 1 && iincy == 1) /* code for both increments equal to 1 */
{
m = nn-4;
for (i = 0; i < m; i += 5)
stemp += sx[i] * sy[i] + sx[i+1] * sy[i+1] + sx[i+2] * sy[i+2] +
sx[i+3] * sy[i+3] + sx[i+4] * sy[i+4];
for ( ; i < nn; i++) /* clean-up loop */
stemp += sx[i] * sy[i];
}
else /* code for unequal increments or equal increments not equal to 1 */
{
ix = 0;
iy = 0;
if (iincx < 0)
ix = (1 - nn) * iincx;
if (iincy < 0)
iy = (1 - nn) * iincy;
for (i = 0; i < nn; i++)
{
stemp += sx[ix] * sy[iy];
ix += iincx;
iy += iincy;
}
}
}
return stemp;
} /* ddot_ */

62
liblinear/blas/dnrm2.c Normal file
View File

@@ -0,0 +1,62 @@
#include <math.h> /* Needed for fabs() and sqrt() */
#include "blas.h"
double dnrm2_(int *n, double *x, int *incx)
{
long int ix, nn, iincx;
double norm, scale, absxi, ssq, temp;
/* DNRM2 returns the euclidean norm of a vector via the function
name, so that
DNRM2 := sqrt( x'*x )
-- This version written on 25-October-1982.
Modified on 14-October-1993 to inline the call to SLASSQ.
Sven Hammarling, Nag Ltd. */
/* Dereference inputs */
nn = *n;
iincx = *incx;
if( nn > 0 && iincx > 0 )
{
if (nn == 1)
{
norm = fabs(x[0]);
}
else
{
scale = 0.0;
ssq = 1.0;
/* The following loop is equivalent to this call to the LAPACK
auxiliary routine: CALL SLASSQ( N, X, INCX, SCALE, SSQ ) */
for (ix=(nn-1)*iincx; ix>=0; ix-=iincx)
{
if (x[ix] != 0.0)
{
absxi = fabs(x[ix]);
if (scale < absxi)
{
temp = scale / absxi;
ssq = ssq * (temp * temp) + 1.0;
scale = absxi;
}
else
{
temp = absxi / scale;
ssq += temp * temp;
}
}
}
norm = scale * sqrt(ssq);
}
}
else
norm = 0.0;
return norm;
} /* dnrm2_ */

44
liblinear/blas/dscal.c Normal file
View File

@@ -0,0 +1,44 @@
#include "blas.h"
int dscal_(int *n, double *sa, double *sx, int *incx)
{
long int i, m, nincx, nn, iincx;
double ssa;
/* scales a vector by a constant.
uses unrolled loops for increment equal to 1.
jack dongarra, linpack, 3/11/78.
modified 3/93 to return if incx .le. 0.
modified 12/3/93, array(1) declarations changed to array(*) */
/* Dereference inputs */
nn = *n;
iincx = *incx;
ssa = *sa;
if (nn > 0 && iincx > 0)
{
if (iincx == 1) /* code for increment equal to 1 */
{
m = nn-4;
for (i = 0; i < m; i += 5)
{
sx[i] = ssa * sx[i];
sx[i+1] = ssa * sx[i+1];
sx[i+2] = ssa * sx[i+2];
sx[i+3] = ssa * sx[i+3];
sx[i+4] = ssa * sx[i+4];
}
for ( ; i < nn; ++i) /* clean-up loop */
sx[i] = ssa * sx[i];
}
else /* code for increment not equal to 1 */
{
nincx = nn * iincx;
for (i = 0; i < nincx; i += iincx)
sx[i] = ssa * sx[i];
}
}
return 0;
} /* dscal_ */

95
liblinear/liblinear.vcxproj Executable file
View File

@@ -0,0 +1,95 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
</ItemGroup>
<ItemGroup>
<ClCompile Include="blas\daxpy.c" />
<ClCompile Include="blas\ddot.c" />
<ClCompile Include="blas\dnrm2.c" />
<ClCompile Include="blas\dscal.c" />
<ClCompile Include="linear.cpp" />
<ClCompile Include="tron.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="blas\blas.h" />
<ClInclude Include="blas\blasp.h" />
<ClInclude Include="linear.h" />
<ClInclude Include="tron.h" />
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{A7BE3D76-F20C-40C5-8986-DE4028B3B57D}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>liblinear</RootNamespace>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<OutDir>.</OutDir>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<OutDir>.</OutDir>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
</ItemDefinitionGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

2382
liblinear/linear.cpp Normal file

File diff suppressed because it is too large Load Diff

18
liblinear/linear.def Normal file
View File

@@ -0,0 +1,18 @@
LIBRARY liblinear
EXPORTS
train @1
cross_validation @2
save_model @3
load_model @4
get_nr_feature @5
get_nr_class @6
get_labels @7
predict_values @8
predict @9
predict_probability @10
free_and_destroy_model @11
free_model_content @12
destroy_param @13
check_parameter @14
check_probability_model @15
set_print_string_function @16

73
liblinear/linear.h Normal file
View File

@@ -0,0 +1,73 @@
#ifndef _LIBLINEAR_H
#define _LIBLINEAR_H
#ifdef __cplusplus
extern "C" {
#endif
struct feature_node
{
int index;
double value;
};
struct problem
{
int l, n;
int *y;
struct feature_node **x;
double bias; /* < 0 if no bias term */
};
enum { L2R_LR, L2R_L2LOSS_SVC_DUAL, L2R_L2LOSS_SVC, L2R_L1LOSS_SVC_DUAL, MCSVM_CS, L1R_L2LOSS_SVC, L1R_LR, L2R_LR_DUAL }; /* solver_type */
struct parameter
{
int solver_type;
/* these are for training only */
double eps; /* stopping criteria */
double C;
int nr_weight;
int *weight_label;
double* weight;
};
struct model
{
struct parameter param;
int nr_class; /* number of classes */
int nr_feature;
double *w;
int *label; /* label of each class */
double bias;
};
struct model* train(const struct problem *prob, const struct parameter *param);
void cross_validation(const struct problem *prob, const struct parameter *param, int nr_fold, int *target);
int predict_values(const struct model *model_, const struct feature_node *x, double* dec_values);
int predict(const struct model *model_, const struct feature_node *x);
int predict_probability(const struct model *model_, const struct feature_node *x, double* prob_estimates);
int save_model(const char *model_file_name, const struct model *model_);
struct model *load_model(const char *model_file_name);
int get_nr_feature(const struct model *model_);
int get_nr_class(const struct model *model_);
void get_labels(const struct model *model_, int* label);
void free_model_content(struct model *model_ptr);
void free_and_destroy_model(struct model **model_ptr_ptr);
void destroy_param(struct parameter *param);
const char *check_parameter(const struct problem *prob, const struct parameter *param);
int check_probability_model(const struct model *model);
void set_print_string_function(void (*print_func) (const char*));
#ifdef __cplusplus
}
#endif
#endif /* _LIBLINEAR_H */

218
liblinear/predict.c Normal file
View File

@@ -0,0 +1,218 @@
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include "linear.h"
struct feature_node *x;
int max_nr_attr = 64;
struct model* model_;
int flag_predict_probability=0;
void exit_input_error(int line_num)
{
fprintf(stderr,"Wrong input format at line %d\n", line_num);
exit(1);
}
static char *line = NULL;
static int max_line_len;
static char* readline(FILE *input)
{
int len;
if(fgets(line,max_line_len,input) == NULL)
return NULL;
while(strrchr(line,'\n') == NULL)
{
max_line_len *= 2;
line = (char *) realloc(line,max_line_len);
len = (int) strlen(line);
if(fgets(line+len,max_line_len-len,input) == NULL)
break;
}
return line;
}
void do_predict(FILE *input, FILE *output, struct model* model_)
{
int correct = 0;
int total = 0;
int nr_class=get_nr_class(model_);
double *prob_estimates=NULL;
int j, n;
int nr_feature=get_nr_feature(model_);
if(model_->bias>=0)
n=nr_feature+1;
else
n=nr_feature;
if(flag_predict_probability)
{
int *labels;
if(!check_probability_model(model_))
{
fprintf(stderr, "probability output is only supported for logistic regression\n");
exit(1);
}
labels=(int *) malloc(nr_class*sizeof(int));
get_labels(model_,labels);
prob_estimates = (double *) malloc(nr_class*sizeof(double));
fprintf(output,"labels");
for(j=0;j<nr_class;j++)
fprintf(output," %d",labels[j]);
fprintf(output,"\n");
free(labels);
}
max_line_len = 1024;
line = (char *)malloc(max_line_len*sizeof(char));
while(readline(input) != NULL)
{
int i = 0;
int target_label, predict_label;
char *idx, *val, *label, *endptr;
int inst_max_index = 0; // strtol gives 0 if wrong format
label = strtok(line," \t\n");
if(label == NULL) // empty line
exit_input_error(total+1);
target_label = (int) strtol(label,&endptr,10);
if(endptr == label || *endptr != '\0')
exit_input_error(total+1);
while(1)
{
if(i>=max_nr_attr-2) // need one more for index = -1
{
max_nr_attr *= 2;
x = (struct feature_node *) realloc(x,max_nr_attr*sizeof(struct feature_node));
}
idx = strtok(NULL,":");
val = strtok(NULL," \t");
if(val == NULL)
break;
errno = 0;
x[i].index = (int) strtol(idx,&endptr,10);
if(endptr == idx || errno != 0 || *endptr != '\0' || x[i].index <= inst_max_index)
exit_input_error(total+1);
else
inst_max_index = x[i].index;
errno = 0;
x[i].value = strtod(val,&endptr);
if(endptr == val || errno != 0 || (*endptr != '\0' && !isspace(*endptr)))
exit_input_error(total+1);
// feature indices larger than those in training are not used
if(x[i].index <= nr_feature)
++i;
}
if(model_->bias>=0)
{
x[i].index = n;
x[i].value = model_->bias;
i++;
}
x[i].index = -1;
if(flag_predict_probability)
{
int j;
predict_label = predict_probability(model_,x,prob_estimates);
fprintf(output,"%d",predict_label);
for(j=0;j<model_->nr_class;j++)
fprintf(output," %g",prob_estimates[j]);
fprintf(output,"\n");
}
else
{
predict_label = predict(model_,x);
fprintf(output,"%d\n",predict_label);
}
if(predict_label == target_label)
++correct;
++total;
}
printf("Accuracy = %g%% (%d/%d)\n",(double) correct/total*100,correct,total);
if(flag_predict_probability)
free(prob_estimates);
}
void exit_with_help()
{
printf(
"Usage: predict [options] test_file model_file output_file\n"
"options:\n"
"-b probability_estimates: whether to output probability estimates, 0 or 1 (default 0)\n"
);
exit(1);
}
int main(int argc, char **argv)
{
FILE *input, *output;
int i;
// parse options
for(i=1;i<argc;i++)
{
if(argv[i][0] != '-') break;
++i;
switch(argv[i-1][1])
{
case 'b':
flag_predict_probability = atoi(argv[i]);
break;
default:
fprintf(stderr,"unknown option: -%c\n", argv[i-1][1]);
exit_with_help();
break;
}
}
if(i>=argc)
exit_with_help();
input = fopen(argv[i],"r");
if(input == NULL)
{
fprintf(stderr,"can't open input file %s\n",argv[i]);
exit(1);
}
output = fopen(argv[i+2],"w");
if(output == NULL)
{
fprintf(stderr,"can't open output file %s\n",argv[i+2]);
exit(1);
}
if((model_=load_model(argv[i+1]))==0)
{
fprintf(stderr,"can't open model file %s\n",argv[i+1]);
exit(1);
}
x = (struct feature_node *) malloc(max_nr_attr*sizeof(struct feature_node));
do_predict(input, output, model_);
free_and_destroy_model(&model_);
free(line);
free(x);
fclose(input);
fclose(output);
return 0;
}

340
liblinear/train.c Normal file
View File

@@ -0,0 +1,340 @@
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include "linear.h"
#define Malloc(type,n) (type *)malloc((n)*sizeof(type))
#define INF HUGE_VAL
void print_null(const char *s) {}
void exit_with_help()
{
printf(
"Usage: train [options] training_set_file [model_file]\n"
"options:\n"
"-s type : set type of solver (default 1)\n"
" 0 -- L2-regularized logistic regression (primal)\n"
" 1 -- L2-regularized L2-loss support vector classification (dual)\n"
" 2 -- L2-regularized L2-loss support vector classification (primal)\n"
" 3 -- L2-regularized L1-loss support vector classification (dual)\n"
" 4 -- multi-class support vector classification by Crammer and Singer\n"
" 5 -- L1-regularized L2-loss support vector classification\n"
" 6 -- L1-regularized logistic regression\n"
" 7 -- L2-regularized logistic regression (dual)\n"
"-c cost : set the parameter C (default 1)\n"
"-e epsilon : set tolerance of termination criterion\n"
" -s 0 and 2\n"
" |f'(w)|_2 <= eps*min(pos,neg)/l*|f'(w0)|_2,\n"
" where f is the primal function and pos/neg are # of\n"
" positive/negative data (default 0.01)\n"
" -s 1, 3, 4 and 7\n"
" Dual maximal violation <= eps; similar to libsvm (default 0.1)\n"
" -s 5 and 6\n"
" |f'(w)|_1 <= eps*min(pos,neg)/l*|f'(w0)|_1,\n"
" where f is the primal function (default 0.01)\n"
"-B bias : if bias >= 0, instance x becomes [x; bias]; if < 0, no bias term added (default -1)\n"
"-wi weight: weights adjust the parameter C of different classes (see README for details)\n"
"-v n: n-fold cross validation mode\n"
"-q : quiet mode (no outputs)\n"
);
exit(1);
}
void exit_input_error(int line_num)
{
fprintf(stderr,"Wrong input format at line %d\n", line_num);
exit(1);
}
static char *line = NULL;
static int max_line_len;
static char* readline(FILE *input)
{
int len;
if(fgets(line,max_line_len,input) == NULL)
return NULL;
while(strrchr(line,'\n') == NULL)
{
max_line_len *= 2;
line = (char *) realloc(line,max_line_len);
len = (int) strlen(line);
if(fgets(line+len,max_line_len-len,input) == NULL)
break;
}
return line;
}
void parse_command_line(int argc, char **argv, char *input_file_name, char *model_file_name);
void read_problem(const char *filename);
void do_cross_validation();
struct feature_node *x_space;
struct parameter param;
struct problem prob;
struct model* model_;
int flag_cross_validation;
int nr_fold;
double bias;
int main(int argc, char **argv)
{
char input_file_name[1024];
char model_file_name[1024];
const char *error_msg;
parse_command_line(argc, argv, input_file_name, model_file_name);
read_problem(input_file_name);
error_msg = check_parameter(&prob,&param);
if(error_msg)
{
fprintf(stderr,"Error: %s\n",error_msg);
exit(1);
}
if(flag_cross_validation)
{
do_cross_validation();
}
else
{
model_=train(&prob, &param);
if(save_model(model_file_name, model_))
{
fprintf(stderr,"can't save model to file %s\n",model_file_name);
exit(1);
}
free_and_destroy_model(&model_);
}
destroy_param(&param);
free(prob.y);
free(prob.x);
free(x_space);
free(line);
return 0;
}
void do_cross_validation()
{
int i;
int total_correct = 0;
int *target = Malloc(int, prob.l);
cross_validation(&prob,&param,nr_fold,target);
for(i=0;i<prob.l;i++)
if(target[i] == prob.y[i])
++total_correct;
printf("Cross Validation Accuracy = %g%%\n",100.0*total_correct/prob.l);
free(target);
}
void parse_command_line(int argc, char **argv, char *input_file_name, char *model_file_name)
{
int i;
void (*print_func)(const char*) = NULL; // default printing to stdout
// default values
param.solver_type = L2R_L2LOSS_SVC_DUAL;
param.C = 1;
param.eps = INF; // see setting below
param.nr_weight = 0;
param.weight_label = NULL;
param.weight = NULL;
flag_cross_validation = 0;
bias = -1;
// parse options
for(i=1;i<argc;i++)
{
if(argv[i][0] != '-') break;
if(++i>=argc)
exit_with_help();
switch(argv[i-1][1])
{
case 's':
param.solver_type = atoi(argv[i]);
break;
case 'c':
param.C = atof(argv[i]);
break;
case 'e':
param.eps = atof(argv[i]);
break;
case 'B':
bias = atof(argv[i]);
break;
case 'w':
++param.nr_weight;
param.weight_label = (int *) realloc(param.weight_label,sizeof(int)*param.nr_weight);
param.weight = (double *) realloc(param.weight,sizeof(double)*param.nr_weight);
param.weight_label[param.nr_weight-1] = atoi(&argv[i-1][2]);
param.weight[param.nr_weight-1] = atof(argv[i]);
break;
case 'v':
flag_cross_validation = 1;
nr_fold = atoi(argv[i]);
if(nr_fold < 2)
{
fprintf(stderr,"n-fold cross validation: n must >= 2\n");
exit_with_help();
}
break;
case 'q':
print_func = &print_null;
i--;
break;
default:
fprintf(stderr,"unknown option: -%c\n", argv[i-1][1]);
exit_with_help();
break;
}
}
set_print_string_function(print_func);
// determine filenames
if(i>=argc)
exit_with_help();
strcpy(input_file_name, argv[i]);
if(i<argc-1)
strcpy(model_file_name,argv[i+1]);
else
{
char *p = strrchr(argv[i],'/');
if(p==NULL)
p = argv[i];
else
++p;
sprintf(model_file_name,"%s.model",p);
}
if(param.eps == INF)
{
if(param.solver_type == L2R_LR || param.solver_type == L2R_L2LOSS_SVC)
param.eps = 0.01;
else if(param.solver_type == L2R_L2LOSS_SVC_DUAL || param.solver_type == L2R_L1LOSS_SVC_DUAL || param.solver_type == MCSVM_CS || param.solver_type == L2R_LR_DUAL)
param.eps = 0.1;
else if(param.solver_type == L1R_L2LOSS_SVC || param.solver_type == L1R_LR)
param.eps = 0.01;
}
}
// read in a problem (in libsvm format)
void read_problem(const char *filename)
{
int max_index, inst_max_index, i;
long int elements, j;
FILE *fp = fopen(filename,"r");
char *endptr;
char *idx, *val, *label;
if(fp == NULL)
{
fprintf(stderr,"can't open input file %s\n",filename);
exit(1);
}
prob.l = 0;
elements = 0;
max_line_len = 1024;
line = Malloc(char,max_line_len);
while(readline(fp)!=NULL)
{
char *p = strtok(line," \t"); // label
// features
while(1)
{
p = strtok(NULL," \t");
if(p == NULL || *p == '\n') // check '\n' as ' ' may be after the last feature
break;
elements++;
}
elements++; // for bias term
prob.l++;
}
rewind(fp);
prob.bias=bias;
prob.y = Malloc(int,prob.l);
prob.x = Malloc(struct feature_node *,prob.l);
x_space = Malloc(struct feature_node,elements+prob.l);
max_index = 0;
j=0;
for(i=0;i<prob.l;i++)
{
inst_max_index = 0; // strtol gives 0 if wrong format
readline(fp);
prob.x[i] = &x_space[j];
label = strtok(line," \t\n");
if(label == NULL) // empty line
exit_input_error(i+1);
prob.y[i] = (int) strtol(label,&endptr,10);
if(endptr == label || *endptr != '\0')
exit_input_error(i+1);
while(1)
{
idx = strtok(NULL,":");
val = strtok(NULL," \t");
if(val == NULL)
break;
errno = 0;
x_space[j].index = (int) strtol(idx,&endptr,10);
if(endptr == idx || errno != 0 || *endptr != '\0' || x_space[j].index <= inst_max_index)
exit_input_error(i+1);
else
inst_max_index = x_space[j].index;
errno = 0;
x_space[j].value = strtod(val,&endptr);
if(endptr == val || errno != 0 || (*endptr != '\0' && !isspace(*endptr)))
exit_input_error(i+1);
++j;
}
if(inst_max_index > max_index)
max_index = inst_max_index;
if(prob.bias >= 0)
x_space[j++].value = prob.bias;
x_space[j++].index = -1;
}
if(prob.bias >= 0)
{
prob.n=max_index+1;
for(i=1;i<prob.l;i++)
(prob.x[i]-2)->index = prob.n;
x_space[j-2].index = prob.n;
}
else
prob.n=max_index;
fclose(fp);
}

235
liblinear/tron.cpp Normal file
View File

@@ -0,0 +1,235 @@
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include "tron.h"
#ifndef min
template <class T> static inline T min(T x,T y) { return (x<y)?x:y; }
#endif
#ifndef max
template <class T> static inline T max(T x,T y) { return (x>y)?x:y; }
#endif
#ifdef __cplusplus
extern "C" {
#endif
extern double dnrm2_(int *, double *, int *);
extern double ddot_(int *, double *, int *, double *, int *);
extern int daxpy_(int *, double *, double *, int *, double *, int *);
extern int dscal_(int *, double *, double *, int *);
#ifdef __cplusplus
}
#endif
static void default_print(const char *buf)
{
fputs(buf,stdout);
fflush(stdout);
}
void TRON::info(const char *fmt,...)
{
char buf[BUFSIZ];
va_list ap;
va_start(ap,fmt);
vsprintf(buf,fmt,ap);
va_end(ap);
(*tron_print_string)(buf);
}
TRON::TRON(const function *fun_obj, double eps, int max_iter)
{
this->fun_obj=const_cast<function *>(fun_obj);
this->eps=eps;
this->max_iter=max_iter;
tron_print_string = default_print;
}
TRON::~TRON()
{
}
void TRON::tron(double *w)
{
// Parameters for updating the iterates.
double eta0 = 1e-4, eta1 = 0.25, eta2 = 0.75;
// Parameters for updating the trust region size delta.
double sigma1 = 0.25, sigma2 = 0.5, sigma3 = 4;
int n = fun_obj->get_nr_variable();
int i, cg_iter;
double delta, snorm, one=1.0;
double alpha, f, fnew, prered, actred, gs;
int search = 1, iter = 1, inc = 1;
double *s = new double[n];
double *r = new double[n];
double *w_new = new double[n];
double *g = new double[n];
for (i=0; i<n; i++)
w[i] = 0;
f = fun_obj->fun(w);
fun_obj->grad(w, g);
delta = dnrm2_(&n, g, &inc);
double gnorm1 = delta;
double gnorm = gnorm1;
if (gnorm <= eps*gnorm1)
search = 0;
iter = 1;
while (iter <= max_iter && search)
{
cg_iter = trcg(delta, g, s, r);
memcpy(w_new, w, sizeof(double)*n);
daxpy_(&n, &one, s, &inc, w_new, &inc);
gs = ddot_(&n, g, &inc, s, &inc);
prered = -0.5*(gs-ddot_(&n, s, &inc, r, &inc));
fnew = fun_obj->fun(w_new);
// Compute the actual reduction.
actred = f - fnew;
// On the first iteration, adjust the initial step bound.
snorm = dnrm2_(&n, s, &inc);
if (iter == 1)
delta = min(delta, snorm);
// Compute prediction alpha*snorm of the step.
if (fnew - f - gs <= 0)
alpha = sigma3;
else
alpha = max(sigma1, -0.5*(gs/(fnew - f - gs)));
// Update the trust region bound according to the ratio of actual to predicted reduction.
if (actred < eta0*prered)
delta = min(max(alpha, sigma1)*snorm, sigma2*delta);
else if (actred < eta1*prered)
delta = max(sigma1*delta, min(alpha*snorm, sigma2*delta));
else if (actred < eta2*prered)
delta = max(sigma1*delta, min(alpha*snorm, sigma3*delta));
else
delta = max(delta, min(alpha*snorm, sigma3*delta));
info("iter %2d act %5.3e pre %5.3e delta %5.3e f %5.3e |g| %5.3e CG %3d\n", iter, actred, prered, delta, f, gnorm, cg_iter);
if (actred > eta0*prered)
{
iter++;
memcpy(w, w_new, sizeof(double)*n);
f = fnew;
fun_obj->grad(w, g);
gnorm = dnrm2_(&n, g, &inc);
if (gnorm <= eps*gnorm1)
break;
}
if (f < -1.0e+32)
{
info("warning: f < -1.0e+32\n");
break;
}
if (fabs(actred) <= 0 && prered <= 0)
{
info("warning: actred and prered <= 0\n");
break;
}
if (fabs(actred) <= 1.0e-12*fabs(f) &&
fabs(prered) <= 1.0e-12*fabs(f))
{
info("warning: actred and prered too small\n");
break;
}
}
delete[] g;
delete[] r;
delete[] w_new;
delete[] s;
}
int TRON::trcg(double delta, double *g, double *s, double *r)
{
int i, inc = 1;
int n = fun_obj->get_nr_variable();
double one = 1;
double *d = new double[n];
double *Hd = new double[n];
double rTr, rnewTrnew, alpha, beta, cgtol;
for (i=0; i<n; i++)
{
s[i] = 0;
r[i] = -g[i];
d[i] = r[i];
}
cgtol = 0.1*dnrm2_(&n, g, &inc);
int cg_iter = 0;
rTr = ddot_(&n, r, &inc, r, &inc);
while (1)
{
if (dnrm2_(&n, r, &inc) <= cgtol)
break;
cg_iter++;
fun_obj->Hv(d, Hd);
alpha = rTr/ddot_(&n, d, &inc, Hd, &inc);
daxpy_(&n, &alpha, d, &inc, s, &inc);
if (dnrm2_(&n, s, &inc) > delta)
{
info("cg reaches trust region boundary\n");
alpha = -alpha;
daxpy_(&n, &alpha, d, &inc, s, &inc);
double std = ddot_(&n, s, &inc, d, &inc);
double sts = ddot_(&n, s, &inc, s, &inc);
double dtd = ddot_(&n, d, &inc, d, &inc);
double dsq = delta*delta;
double rad = sqrt(std*std + dtd*(dsq-sts));
if (std >= 0)
alpha = (dsq - sts)/(std + rad);
else
alpha = (rad - std)/dtd;
daxpy_(&n, &alpha, d, &inc, s, &inc);
alpha = -alpha;
daxpy_(&n, &alpha, Hd, &inc, r, &inc);
break;
}
alpha = -alpha;
daxpy_(&n, &alpha, Hd, &inc, r, &inc);
rnewTrnew = ddot_(&n, r, &inc, r, &inc);
beta = rnewTrnew/rTr;
dscal_(&n, &beta, d, &inc);
daxpy_(&n, &one, r, &inc, d, &inc);
rTr = rnewTrnew;
}
delete[] d;
delete[] Hd;
return(cg_iter);
}
double TRON::norm_inf(int n, double *x)
{
double dmax = fabs(x[0]);
for (int i=1; i<n; i++)
if (fabs(x[i]) >= dmax)
dmax = fabs(x[i]);
return(dmax);
}
void TRON::set_print_string(void (*print_string) (const char *buf))
{
tron_print_string = print_string;
}

34
liblinear/tron.h Normal file
View File

@@ -0,0 +1,34 @@
#ifndef _TRON_H
#define _TRON_H
class function
{
public:
virtual double fun(double *w) = 0 ;
virtual void grad(double *w, double *g) = 0 ;
virtual void Hv(double *s, double *Hs) = 0 ;
virtual int get_nr_variable(void) = 0 ;
virtual ~function(void){}
};
class TRON
{
public:
TRON(const function *fun_obj, double eps = 0.1, int max_iter = 1000);
~TRON();
void tron(double *w);
void set_print_string(void (*i_print) (const char *buf));
private:
int trcg(double delta, double *g, double *s, double *r);
double norm_inf(int n, double *x);
double eps;
int max_iter;
function *fun_obj;
void info(const char *fmt,...);
void (*tron_print_string)(const char *buf);
};
#endif

344
libnetutil/ARPHeader.cc Normal file
View File

@@ -0,0 +1,344 @@
/***************************************************************************
* ARPHeader.cc -- The ARPHeader Class represents an ARP packet. It *
* contains methods to set any header field. In general, these methods do *
* error checkings and byte order conversion. *
* *
***********************IMPORTANT NMAP LICENSE TERMS************************
* *
* The Nmap Security Scanner is (C) 1996-2011 Insecure.Com LLC. Nmap is *
* also a registered trademark of Insecure.Com LLC. This program is free *
* software; you may redistribute and/or modify it under the terms of the *
* GNU General Public License as published by the Free Software *
* Foundation; Version 2 with the clarifications and exceptions described *
* below. This guarantees your right to use, modify, and redistribute *
* this software under certain conditions. If you wish to embed Nmap *
* technology into proprietary software, we sell alternative licenses *
* (contact sales@insecure.com). Dozens of software vendors already *
* license Nmap technology such as host discovery, port scanning, OS *
* detection, and version detection. *
* *
* Note that the GPL places important restrictions on "derived works", yet *
* it does not provide a detailed definition of that term. To avoid *
* misunderstandings, we consider an application to constitute a *
* "derivative work" for the purpose of this license if it does any of the *
* following: *
* o Integrates source code from Nmap *
* o Reads or includes Nmap copyrighted data files, such as *
* nmap-os-db or nmap-service-probes. *
* o Executes Nmap and parses the results (as opposed to typical shell or *
* execution-menu apps, which simply display raw Nmap output and so are *
* not derivative works.) *
* o Integrates/includes/aggregates Nmap into a proprietary executable *
* installer, such as those produced by InstallShield. *
* o Links to a library or executes a program that does any of the above *
* *
* The term "Nmap" should be taken to also include any portions or derived *
* works of Nmap. This list is not exclusive, but is meant to clarify our *
* interpretation of derived works with some common examples. Our *
* interpretation applies only to Nmap--we don't speak for other people's *
* GPL works. *
* *
* If you have any questions about the GPL licensing restrictions on using *
* Nmap in non-GPL works, we would be happy to help. As mentioned above, *
* we also offer alternative license to integrate Nmap into proprietary *
* applications and appliances. These contracts have been sold to dozens *
* of software vendors, and generally include a perpetual license as well *
* as providing for priority support and updates as well as helping to *
* fund the continued development of Nmap technology. Please email *
* sales@insecure.com for further information. *
* *
* As a special exception to the GPL terms, Insecure.Com LLC grants *
* permission to link the code of this program with any version of the *
* OpenSSL library which is distributed under a license identical to that *
* listed in the included docs/licenses/OpenSSL.txt file, and distribute *
* linked combinations including the two. You must obey the GNU GPL in all *
* respects for all of the code used other than OpenSSL. If you modify *
* this file, you may extend this exception to your version of the file, *
* but you are not obligated to do so. *
* *
* If you received these files with a written license agreement or *
* contract stating terms other than the terms above, then that *
* alternative license agreement takes precedence over these comments. *
* *
* Source is provided to this software because we believe users have a *
* right to know exactly what a program is going to do before they run it. *
* This also allows you to audit the software for security holes (none *
* have been found so far). *
* *
* Source code also allows you to port Nmap to new platforms, fix bugs, *
* and add new features. You are highly encouraged to send your changes *
* to nmap-dev@insecure.org for possible incorporation into the main *
* distribution. By sending these changes to Fyodor or one of the *
* Insecure.Org development mailing lists, it is assumed that you are *
* offering the Nmap Project (Insecure.Com LLC) the unlimited, *
* non-exclusive right to reuse, modify, and relicense the code. Nmap *
* will always be available Open Source, but this is important because the *
* inability to relicense code has caused devastating problems for other *
* Free Software projects (such as KDE and NASM). We also occasionally *
* relicense the code to third parties as discussed above. If you wish to *
* specify special license conditions of your contributions, just say so *
* when you send them. *
* *
* This program is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* General Public License v2.0 for more details at *
* http://www.gnu.org/licenses/gpl-2.0.html , or in the COPYING file *
* included with Nmap. *
* *
***************************************************************************/
/* This code was originally part of the Nping tool. */
#include "ARPHeader.h"
/******************************************************************************/
/* CONTRUCTORS, DESTRUCTORS AND INITIALIZATION METHODS */
/******************************************************************************/
ARPHeader::ARPHeader() {
this->reset();
} /* End of ARPHeader constructor */
ARPHeader::~ARPHeader() {
} /* End of ARPHeader destructor */
/** Sets every attribute to its default value */
void ARPHeader::reset(){
memset (&this->h, 0, sizeof(nping_arp_hdr_t));
this->length=ARP_HEADER_LEN;
} /* End of reset() */
/******************************************************************************/
/* PacketElement:: OVERWRITTEN METHODS */
/******************************************************************************/
/** @warning This method is essential for the superclass getBinaryBuffer()
* method to work. Do NOT change a thing unless you know what you're doing */
u8 *ARPHeader::getBufferPointer(){
return (u8*)(&h);
} /* End of getBufferPointer() */
/** Stores supplied packet in the internal buffer so the information
* can be accessed using the standard get & set methods.
* @warning The ARPHeader class is able to hold a maximum of 28 bytes.
* If the supplied buffer is longer than that, only the first 28 bytes will be
* stored in the internal buffer.
* @warning Supplied len MUST be at least 28 bytes (ARP header length).
* @return OP_SUCCESS on success and OP_FAILURE in case of error */
int ARPHeader::storeRecvData(const u8 *buf, size_t len){
if(buf==NULL || len<ARP_HEADER_LEN){
return OP_FAILURE;
}else{
this->reset(); /* Re-init the object, just in case the caller had used it already */
this->length=ARP_HEADER_LEN;
memcpy(&(this->h), buf, ARP_HEADER_LEN);
}
return OP_SUCCESS;
} /* End of storeRecvData() */
/* Returns a protocol identifier. This is used by packet parsing funtions
* that return linked lists of PacketElement objects, to determine the protocol
* the object represents. */
int ARPHeader::protocol_id() const {
return HEADER_TYPE_ARP;
} /* End of protocol_id() */
/** Determines if the data stored in the object after an storeRecvData() call
* is valid and safe to use. This mainly checks the length of the data but may
* also test the value of certain protocol fields to ensure their correctness.
* @return the length, in bytes, of the header, if its found to be valid or
* OP_FAILURE (-1) otherwise. */
int ARPHeader::validate(){
if( this->length!=ARP_HEADER_LEN)
return OP_FAILURE;
else
return ARP_HEADER_LEN;
} /* End of validate() */
/** Prints the contents of the header and calls print() on the next protocol
* header in the chain (if there is any).
* @return OP_SUCCESS on success and OP_FAILURE in case of error. */
int ARPHeader::print(FILE *output, int detail) const {
fprintf(output, "ARP[]");
if(this->next!=NULL){
print_separator(output, detail);
next->print(output, detail);
}
return OP_SUCCESS;
} /* End of print() */
/******************************************************************************/
/* PROTOCOL-SPECIFIC METHODS */
/******************************************************************************/
/** Sets HardwareType.
* @return OP_SUCCESS on success and OP_FAILURE in case of error. */
int ARPHeader::setHardwareType(u16 val){
this->h.ar_hrd=htons(val);
return OP_SUCCESS;
} /* End of setHardwareType() */
/** Sets HardwareType to ETHERNET.
* @return OP_SUCCESS on success and OP_FAILURE in case of error. */
int ARPHeader::setHardwareType(){
this->h.ar_hrd=htons(HDR_ETH10MB);
return OP_SUCCESS;
} /* End of setHardwareType() */
/** Returns value of attribute h.ar_hrd */
u16 ARPHeader::getHardwareType(){
return ntohs(this->h.ar_hrd);
} /* End of getHardwareType() */
/** Sets ProtocolType.
* @return OP_SUCCESS on success and OP_FAILURE in case of error. */
int ARPHeader::setProtocolType(u16 val){
this->h.ar_pro=htons(val);
return OP_SUCCESS;
} /* End of setProtocolType() */
/** Sets ProtocolType.
* @return OP_SUCCESS on success and OP_FAILURE in case of error. */
int ARPHeader::setProtocolType(){
this->h.ar_pro=htons(0x0800); /* DEFAULT: IPv4 */
return OP_SUCCESS;
} /* End of setProtocolType() */
/** Returns value of attribute h.ar_pro */
u16 ARPHeader::getProtocolType(){
return ntohs(this->h.ar_pro);
} /* End of getProtocolType() */
/** Sets HwAddrLen.
* @return OP_SUCCESS on success and OP_FAILURE in case of error. */
int ARPHeader::setHwAddrLen(u8 val){
this->h.ar_hln=val;
return OP_SUCCESS;
} /* End of setHwAddrLen() */
/** Sets HwAddrLen.
* @return OP_SUCCESS on success and OP_FAILURE in case of error. */
int ARPHeader::setHwAddrLen(){
this->h.ar_hln=ETH_ADDRESS_LEN;
return OP_SUCCESS;
} /* End of setHwAddrLen() */
/** Returns value of attribute h.ar_hln */
u8 ARPHeader::getHwAddrLen(){
return this->h.ar_hln;
} /* End of getHwAddrLen() */
/** Sets ProtoAddrLen.
* @return OP_SUCCESS on success and OP_FAILURE in case of error. */
int ARPHeader::setProtoAddrLen(u8 val){
this->h.ar_pln=val;
return OP_SUCCESS;
} /* End of setProtoAddrLen() */
/** Sets ProtoAddrLen.
* @return OP_SUCCESS on success and OP_FAILURE in case of error. */
int ARPHeader::setProtoAddrLen(){
this->h.ar_pln=IPv4_ADDRESS_LEN; /* DEFAULT: IPv4 */
return OP_SUCCESS;
} /* End of setProtoAddrLen() */
/** Returns value of attribute h.ar_pln */
u8 ARPHeader::getProtoAddrLen(){
return this->h.ar_pln;
} /* End of getProtoAddrLen() */
/** Sets OpCode.
* @return OP_SUCCESS on success and OP_FAILURE in case of error. */
int ARPHeader::setOpCode(u16 val){
this->h.ar_op=htons(val);
return OP_SUCCESS;
} /* End of setOpCode() */
/** Returns value of attribute h.ar_op */
u16 ARPHeader::getOpCode(){
return ntohs(this->h.ar_op);
} /* End of getOpCode() */
/** Sets SenderMAC.
* @return OP_SUCCESS on success and OP_FAILURE in case of error. */
int ARPHeader::setSenderMAC(const u8 * val){
if(val==NULL)
return OP_FAILURE;
memcpy(this->h.data, val, ETH_ADDRESS_LEN);
return OP_SUCCESS;
} /* End of setSenderMAC() */
/** Returns value of attribute h.ar_sha */
u8 * ARPHeader::getSenderMAC(){
return this->h.data;
} /* End of getSenderMAC() */
/** Sets SenderIP.
* @return OP_SUCCESS on success and OP_FAILURE in case of error. */
int ARPHeader::setSenderIP(struct in_addr val){
memcpy(this->h.data+6, &val.s_addr, 4);
return OP_SUCCESS;
} /* End of setSenderIP() */
/** Returns value of attribute h.ar_sip */
u32 ARPHeader::getSenderIP(){
u32 *p = (u32 *)(this->h.data+6);
return *p;
} /* End of getSenderIP() */
/** Sets TargetMAC.
* @return OP_SUCCESS on success and OP_FAILURE in case of error. */
int ARPHeader::setTargetMAC(u8 * val){
if(val==NULL)
return OP_FAILURE;
memcpy(this->h.data+10, val, ETH_ADDRESS_LEN);
return OP_SUCCESS;
} /* End of setTargetMAC() */
/** Returns value of attribute h.ar_tha */
u8 * ARPHeader::getTargetMAC(){
return this->h.data+10;
} /* End of getTargetMAC() */
/** Sets TargetIP.
* @return OP_SUCCESS on success and OP_FAILURE in case of error. */
int ARPHeader::setTargetIP(struct in_addr val){
memcpy(this->h.data+16, &val.s_addr, 4);
return OP_SUCCESS;
} /* End of setTargetIP() */
/** Returns value of attribute h.ar_tip */
u32 ARPHeader::getTargetIP(){
u32 *p = (u32 *)(this->h.data+16);
return *p;
} /* End of getTargetIP() */

251
libnetutil/ARPHeader.h Normal file
View File

@@ -0,0 +1,251 @@
/***************************************************************************
* ARPHeader.h -- The ARPHeader Class represents an ARP packet. It *
* contains methods to set any header field. In general, these methods do *
* error checkings and byte order conversion. *
* *
***********************IMPORTANT NMAP LICENSE TERMS************************
* *
* The Nmap Security Scanner is (C) 1996-2011 Insecure.Com LLC. Nmap is *
* also a registered trademark of Insecure.Com LLC. This program is free *
* software; you may redistribute and/or modify it under the terms of the *
* GNU General Public License as published by the Free Software *
* Foundation; Version 2 with the clarifications and exceptions described *
* below. This guarantees your right to use, modify, and redistribute *
* this software under certain conditions. If you wish to embed Nmap *
* technology into proprietary software, we sell alternative licenses *
* (contact sales@insecure.com). Dozens of software vendors already *
* license Nmap technology such as host discovery, port scanning, OS *
* detection, and version detection. *
* *
* Note that the GPL places important restrictions on "derived works", yet *
* it does not provide a detailed definition of that term. To avoid *
* misunderstandings, we consider an application to constitute a *
* "derivative work" for the purpose of this license if it does any of the *
* following: *
* o Integrates source code from Nmap *
* o Reads or includes Nmap copyrighted data files, such as *
* nmap-os-db or nmap-service-probes. *
* o Executes Nmap and parses the results (as opposed to typical shell or *
* execution-menu apps, which simply display raw Nmap output and so are *
* not derivative works.) *
* o Integrates/includes/aggregates Nmap into a proprietary executable *
* installer, such as those produced by InstallShield. *
* o Links to a library or executes a program that does any of the above *
* *
* The term "Nmap" should be taken to also include any portions or derived *
* works of Nmap. This list is not exclusive, but is meant to clarify our *
* interpretation of derived works with some common examples. Our *
* interpretation applies only to Nmap--we don't speak for other people's *
* GPL works. *
* *
* If you have any questions about the GPL licensing restrictions on using *
* Nmap in non-GPL works, we would be happy to help. As mentioned above, *
* we also offer alternative license to integrate Nmap into proprietary *
* applications and appliances. These contracts have been sold to dozens *
* of software vendors, and generally include a perpetual license as well *
* as providing for priority support and updates as well as helping to *
* fund the continued development of Nmap technology. Please email *
* sales@insecure.com for further information. *
* *
* As a special exception to the GPL terms, Insecure.Com LLC grants *
* permission to link the code of this program with any version of the *
* OpenSSL library which is distributed under a license identical to that *
* listed in the included docs/licenses/OpenSSL.txt file, and distribute *
* linked combinations including the two. You must obey the GNU GPL in all *
* respects for all of the code used other than OpenSSL. If you modify *
* this file, you may extend this exception to your version of the file, *
* but you are not obligated to do so. *
* *
* If you received these files with a written license agreement or *
* contract stating terms other than the terms above, then that *
* alternative license agreement takes precedence over these comments. *
* *
* Source is provided to this software because we believe users have a *
* right to know exactly what a program is going to do before they run it. *
* This also allows you to audit the software for security holes (none *
* have been found so far). *
* *
* Source code also allows you to port Nmap to new platforms, fix bugs, *
* and add new features. You are highly encouraged to send your changes *
* to nmap-dev@insecure.org for possible incorporation into the main *
* distribution. By sending these changes to Fyodor or one of the *
* Insecure.Org development mailing lists, it is assumed that you are *
* offering the Nmap Project (Insecure.Com LLC) the unlimited, *
* non-exclusive right to reuse, modify, and relicense the code. Nmap *
* will always be available Open Source, but this is important because the *
* inability to relicense code has caused devastating problems for other *
* Free Software projects (such as KDE and NASM). We also occasionally *
* relicense the code to third parties as discussed above. If you wish to *
* specify special license conditions of your contributions, just say so *
* when you send them. *
* *
* This program is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* General Public License v2.0 for more details at *
* http://www.gnu.org/licenses/gpl-2.0.html , or in the COPYING file *
* included with Nmap. *
* *
***************************************************************************/
/* This code was originally part of the Nping tool. */
#ifndef __ARPHEADER_H__
#define __ARPHEADER_H__ 1
#include "NetworkLayerElement.h"
/* Lengths */
#define ARP_HEADER_LEN 28
#define IPv4_ADDRESS_LEN 4
#define ETH_ADDRESS_LEN 6
/* Hardware Types */
#define HDR_RESERVED 0 /* [RFC5494] */
#define HDR_ETH10MB 1 /* Ethernet (10Mb) */
#define HDR_ETH3MB 2 /* Experimental Ethernet (3Mb) */
#define HDR_AX25 3 /* Amateur Radio AX.25 */
#define HDR_PRONET_TR 4 /* Proteon ProNET Token Ring */
#define HDR_CHAOS 5 /* Chaos */
#define HDR_IEEE802 6 /* IEEE 802 Networks */
#define HDR_ARCNET 7 /* ARCNET [RFC1201] */
#define HDR_HYPERCHANNEL 8 /* Hyperchannel */
#define HDR_LANSTAR 9 /* Lanstar */
#define HDR_AUTONET 10 /* Autonet Short Address */
#define HDR_LOCALTALK 11 /* LocalTalk */
#define HDR_LOCALNET 12 /* LocalNet (IBM PCNet or SYTEK LocalNET) */
#define HDR_ULTRALINK 13 /* Ultra link */
#define HDR_SMDS 14 /* SMDS */
#define HDR_FRAMERELAY 15 /* Frame Relay */
#define HDR_ATM 16 /* Asynchronous Transmission Mode (ATM) */
#define HDR_HDLC 17 /* HDLC */
#define HDR_FIBRE 18 /* Fibre Channel [RFC4338] */
#define HDR_ATMb 19 /* Asynchronous Transmission Mode (ATM) */
#define HDR_SERIAL 20 /* Serial Line */
#define HDR_ATMc 21 /* Asynchronous Transmission Mode [RFC2225] */
#define HDR_MILSTD 22 /* MIL-STD-188-220 */
#define HDR_METRICOM 23 /* Metricom */
#define HDR_IEEE1394 24 /* IEEE 1394.199 */
#define HDR_MAPOS 25 /* MAPOS [RFC2176] */
#define HDR_TWINAXIAL 26 /* Twinaxial */
#define HDR_EUI64 27 /* EUI-64 */
#define HDR_HIPARP 28 /* HIPARP */
#define HDR_ISO7816 29 /* IP and ARP over ISO 7816-3 */
#define HDR_ARPSEC 30 /* ARPSec */
#define HDR_IPSEC 31 /* IPsec tunnel */
#define HDR_INFINIBAND 32 /* InfiniBand (TM) */
#define HDR_TIA102 33 /* TIA-102 Project 25 Common Air Interface */
#define HDR_WIEGAND 34 /* Wiegand Interface */
#define HDR_PUREIP 35 /* Pure IP */
#define HDR_HW_EXP1 36 /* HW_EXP1 [RFC5494] */
#define HDR_HW_EXP2 37 /* HW_EXP2 [RFC5494] */
/* Operation Codes */
#define OP_ARP_REQUEST 1 /* ARP Request */
#define OP_ARP_REPLY 2 /* ARP Reply */
#define OP_RARP_REQUEST 3 /* Reverse ARP Request */
#define OP_RARP_REPLY 4 /* Reverse ARP Reply */
#define OP_DRARP_REQUEST 5 /* DRARP-Request */
#define OP_DRARP_REPLY 6 /* DRARP-Reply */
#define OP_DRARP_ERROR 7 /* DRARP-Error */
#define OP_INARP_REQUEST 8 /* InARP-Request */
#define OP_INARP_REPLY 9 /* InARP-Reply */
#define OP_ARPNAK 10 /* ARP-NAK */
#define OP_MARS_REQUEST 11 /* MARS-Request */
#define OP_MARS_MULTI 12 /* MARS-Multi */
#define OP_MARS_MSERV 13 /* MARS-MServ */
#define OP_MARS_JOIN 14 /* MARS-Join */
#define OP_MARS_LEAVE 15 /* MARS-Leave */
#define OP_MARS_NAK 16 /* MARS-NAK */
#define OP_MARS_UNSERV 17 /* MARS-Unserv */
#define OP_MARS_SJOIN 18 /* MARS-SJoin */
#define OP_MARS_SLEAVE 19 /* MARS-SLeave */
#define OP_MARS_GL_REQ 20 /* MARS-Grouplist-Request */
#define OP_MARS_GL_REP 21 /* MARS-Grouplist-Reply */
#define OP_MARS_REDIR_MAP 22 /* MARS-Redirect-Map */
#define OP_MAPOS_UNARP 23 /* MAPOS-UNARP [RFC2176] */
#define OP_EXP1 24 /* OP_EXP1 [RFC5494] */
#define OP_EXP2 25 /* OP_EXP2 [RFC5494] */
#define OP_RESERVED 65535 /* Reserved [RFC5494] */
class ARPHeader : public NetworkLayerElement {
private:
struct nping_arp_hdr{
u16 ar_hrd; /* Hardware Type. */
u16 ar_pro; /* Protocol Type. */
u8 ar_hln; /* Hardware Address Length. */
u8 ar_pln; /* Protocol Address Length. */
u16 ar_op; /* Operation Code. */
u8 data[20];
// Cannot use these because the fucking alignment screws up
// everything. I miss ANSI C.
//u8 ar_sha[6]; /* Sender Hardware Address. */
//u32 ar_sip; /* Sender Protocol Address (IPv4 address). */
//u8 ar_tha[6]; /* Target Hardware Address. */
//u32 ar_tip; /* Target Protocol Address (IPv4 address). */
}__attribute__((__packed__));
typedef struct nping_arp_hdr nping_arp_hdr_t;
nping_arp_hdr_t h;
public:
/* Misc */
ARPHeader();
~ARPHeader();
void reset();
u8 *getBufferPointer();
int storeRecvData(const u8 *buf, size_t len);
int protocol_id() const;
int validate();
int print(FILE *output, int detail) const;
/* Hardware Type */
int setHardwareType(u16 t);
int setHardwareType();
u16 getHardwareType();
/* Protocol Type */
int setProtocolType(u16 t);
int setProtocolType();
u16 getProtocolType();
/* Hardware Address Length */
int setHwAddrLen(u8 v);
int setHwAddrLen();
u8 getHwAddrLen();
/* Hardware Address Length */
int setProtoAddrLen(u8 v);
int setProtoAddrLen();
u8 getProtoAddrLen();
/* Operation Code */
int setOpCode(u16 c);
u16 getOpCode();
/* Sender Hardware Address */
int setSenderMAC(const u8 *m);
u8 *getSenderMAC();
/* Sender Protocol address */
int setSenderIP(struct in_addr i);
u32 getSenderIP();
/* Target Hardware Address */
int setTargetMAC(u8 *m);
u8 *getTargetMAC();
/* Target Protocol Address */
int setTargetIP(struct in_addr i);
u32 getTargetIP();
}; /* End of class ARPHeader */
#endif /* __ARPHEADER_H__ */

View File

@@ -0,0 +1,102 @@
/***************************************************************************
* ApplicationLayerElement.h -- Class ApplicationLayerElement is a *
* generic class that represents an application layer protocol header or *
* any kind of payload or buffer. Classes like RawData inherit from it. *
* *
***********************IMPORTANT NMAP LICENSE TERMS************************
* *
* The Nmap Security Scanner is (C) 1996-2011 Insecure.Com LLC. Nmap is *
* also a registered trademark of Insecure.Com LLC. This program is free *
* software; you may redistribute and/or modify it under the terms of the *
* GNU General Public License as published by the Free Software *
* Foundation; Version 2 with the clarifications and exceptions described *
* below. This guarantees your right to use, modify, and redistribute *
* this software under certain conditions. If you wish to embed Nmap *
* technology into proprietary software, we sell alternative licenses *
* (contact sales@insecure.com). Dozens of software vendors already *
* license Nmap technology such as host discovery, port scanning, OS *
* detection, and version detection. *
* *
* Note that the GPL places important restrictions on "derived works", yet *
* it does not provide a detailed definition of that term. To avoid *
* misunderstandings, we consider an application to constitute a *
* "derivative work" for the purpose of this license if it does any of the *
* following: *
* o Integrates source code from Nmap *
* o Reads or includes Nmap copyrighted data files, such as *
* nmap-os-db or nmap-service-probes. *
* o Executes Nmap and parses the results (as opposed to typical shell or *
* execution-menu apps, which simply display raw Nmap output and so are *
* not derivative works.) *
* o Integrates/includes/aggregates Nmap into a proprietary executable *
* installer, such as those produced by InstallShield. *
* o Links to a library or executes a program that does any of the above *
* *
* The term "Nmap" should be taken to also include any portions or derived *
* works of Nmap. This list is not exclusive, but is meant to clarify our *
* interpretation of derived works with some common examples. Our *
* interpretation applies only to Nmap--we don't speak for other people's *
* GPL works. *
* *
* If you have any questions about the GPL licensing restrictions on using *
* Nmap in non-GPL works, we would be happy to help. As mentioned above, *
* we also offer alternative license to integrate Nmap into proprietary *
* applications and appliances. These contracts have been sold to dozens *
* of software vendors, and generally include a perpetual license as well *
* as providing for priority support and updates as well as helping to *
* fund the continued development of Nmap technology. Please email *
* sales@insecure.com for further information. *
* *
* As a special exception to the GPL terms, Insecure.Com LLC grants *
* permission to link the code of this program with any version of the *
* OpenSSL library which is distributed under a license identical to that *
* listed in the included docs/licenses/OpenSSL.txt file, and distribute *
* linked combinations including the two. You must obey the GNU GPL in all *
* respects for all of the code used other than OpenSSL. If you modify *
* this file, you may extend this exception to your version of the file, *
* but you are not obligated to do so. *
* *
* If you received these files with a written license agreement or *
* contract stating terms other than the terms above, then that *
* alternative license agreement takes precedence over these comments. *
* *
* Source is provided to this software because we believe users have a *
* right to know exactly what a program is going to do before they run it. *
* This also allows you to audit the software for security holes (none *
* have been found so far). *
* *
* Source code also allows you to port Nmap to new platforms, fix bugs, *
* and add new features. You are highly encouraged to send your changes *
* to nmap-dev@insecure.org for possible incorporation into the main *
* distribution. By sending these changes to Fyodor or one of the *
* Insecure.Org development mailing lists, it is assumed that you are *
* offering the Nmap Project (Insecure.Com LLC) the unlimited, *
* non-exclusive right to reuse, modify, and relicense the code. Nmap *
* will always be available Open Source, but this is important because the *
* inability to relicense code has caused devastating problems for other *
* Free Software projects (such as KDE and NASM). We also occasionally *
* relicense the code to third parties as discussed above. If you wish to *
* specify special license conditions of your contributions, just say so *
* when you send them. *
* *
* This program is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* General Public License v2.0 for more details at *
* http://www.gnu.org/licenses/gpl-2.0.html , or in the COPYING file *
* included with Nmap. *
* *
***************************************************************************/
/* This code was originally part of the Nping tool. */
#ifndef APPLICATIONLAYERELEMENT_H
#define APPLICATIONLAYERELEMENT_H 1
#include "PacketElement.h"
class ApplicationLayerElement : public PacketElement {
};
#endif

101
libnetutil/DataLinkLayerElement.h Executable file
View File

@@ -0,0 +1,101 @@
/***************************************************************************
* DataLinkLayerElement.h -- Class DataLinkLayerElement is a generic *
* class that represents a data link layer protocol header (and maybe a *
* footer) Classes like EthernetHeader inherit from it. *
* *
***********************IMPORTANT NMAP LICENSE TERMS************************
* *
* The Nmap Security Scanner is (C) 1996-2011 Insecure.Com LLC. Nmap is *
* also a registered trademark of Insecure.Com LLC. This program is free *
* software; you may redistribute and/or modify it under the terms of the *
* GNU General Public License as published by the Free Software *
* Foundation; Version 2 with the clarifications and exceptions described *
* below. This guarantees your right to use, modify, and redistribute *
* this software under certain conditions. If you wish to embed Nmap *
* technology into proprietary software, we sell alternative licenses *
* (contact sales@insecure.com). Dozens of software vendors already *
* license Nmap technology such as host discovery, port scanning, OS *
* detection, and version detection. *
* *
* Note that the GPL places important restrictions on "derived works", yet *
* it does not provide a detailed definition of that term. To avoid *
* misunderstandings, we consider an application to constitute a *
* "derivative work" for the purpose of this license if it does any of the *
* following: *
* o Integrates source code from Nmap *
* o Reads or includes Nmap copyrighted data files, such as *
* nmap-os-db or nmap-service-probes. *
* o Executes Nmap and parses the results (as opposed to typical shell or *
* execution-menu apps, which simply display raw Nmap output and so are *
* not derivative works.) *
* o Integrates/includes/aggregates Nmap into a proprietary executable *
* installer, such as those produced by InstallShield. *
* o Links to a library or executes a program that does any of the above *
* *
* The term "Nmap" should be taken to also include any portions or derived *
* works of Nmap. This list is not exclusive, but is meant to clarify our *
* interpretation of derived works with some common examples. Our *
* interpretation applies only to Nmap--we don't speak for other people's *
* GPL works. *
* *
* If you have any questions about the GPL licensing restrictions on using *
* Nmap in non-GPL works, we would be happy to help. As mentioned above, *
* we also offer alternative license to integrate Nmap into proprietary *
* applications and appliances. These contracts have been sold to dozens *
* of software vendors, and generally include a perpetual license as well *
* as providing for priority support and updates as well as helping to *
* fund the continued development of Nmap technology. Please email *
* sales@insecure.com for further information. *
* *
* As a special exception to the GPL terms, Insecure.Com LLC grants *
* permission to link the code of this program with any version of the *
* OpenSSL library which is distributed under a license identical to that *
* listed in the included docs/licenses/OpenSSL.txt file, and distribute *
* linked combinations including the two. You must obey the GNU GPL in all *
* respects for all of the code used other than OpenSSL. If you modify *
* this file, you may extend this exception to your version of the file, *
* but you are not obligated to do so. *
* *
* If you received these files with a written license agreement or *
* contract stating terms other than the terms above, then that *
* alternative license agreement takes precedence over these comments. *
* *
* Source is provided to this software because we believe users have a *
* right to know exactly what a program is going to do before they run it. *
* This also allows you to audit the software for security holes (none *
* have been found so far). *
* *
* Source code also allows you to port Nmap to new platforms, fix bugs, *
* and add new features. You are highly encouraged to send your changes *
* to nmap-dev@insecure.org for possible incorporation into the main *
* distribution. By sending these changes to Fyodor or one of the *
* Insecure.Org development mailing lists, it is assumed that you are *
* offering the Nmap Project (Insecure.Com LLC) the unlimited, *
* non-exclusive right to reuse, modify, and relicense the code. Nmap *
* will always be available Open Source, but this is important because the *
* inability to relicense code has caused devastating problems for other *
* Free Software projects (such as KDE and NASM). We also occasionally *
* relicense the code to third parties as discussed above. If you wish to *
* specify special license conditions of your contributions, just say so *
* when you send them. *
* *
* This program is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* General Public License v2.0 for more details at *
* http://www.gnu.org/licenses/gpl-2.0.html , or in the COPYING file *
* included with Nmap. *
* *
***************************************************************************/
/* This code was originally part of the Nping tool. */
#ifndef DATALINKLAYERELEMENT_H
#define DATALINKLAYERELEMENT_H 1
#include "PacketElement.h"
class DataLinkLayerElement : public PacketElement {
};
#endif

View File

@@ -0,0 +1,126 @@
/***************************************************************************
* DestOptsHeader.cc -- The DestOptsHeader Class represents an IPv6 *
* Destination Options extension header. *
***********************IMPORTANT NMAP LICENSE TERMS************************
* *
* The Nmap Security Scanner is (C) 1996-2011 Insecure.Com LLC. Nmap is *
* also a registered trademark of Insecure.Com LLC. This program is free *
* software; you may redistribute and/or modify it under the terms of the *
* GNU General Public License as published by the Free Software *
* Foundation; Version 2 with the clarifications and exceptions described *
* below. This guarantees your right to use, modify, and redistribute *
* this software under certain conditions. If you wish to embed Nmap *
* technology into proprietary software, we sell alternative licenses *
* (contact sales@insecure.com). Dozens of software vendors already *
* license Nmap technology such as host discovery, port scanning, OS *
* detection, and version detection. *
* *
* Note that the GPL places important restrictions on "derived works", yet *
* it does not provide a detailed definition of that term. To avoid *
* misunderstandings, we consider an application to constitute a *
* "derivative work" for the purpose of this license if it does any of the *
* following: *
* o Integrates source code from Nmap *
* o Reads or includes Nmap copyrighted data files, such as *
* nmap-os-db or nmap-service-probes. *
* o Executes Nmap and parses the results (as opposed to typical shell or *
* execution-menu apps, which simply display raw Nmap output and so are *
* not derivative works.) *
* o Integrates/includes/aggregates Nmap into a proprietary executable *
* installer, such as those produced by InstallShield. *
* o Links to a library or executes a program that does any of the above *
* *
* The term "Nmap" should be taken to also include any portions or derived *
* works of Nmap. This list is not exclusive, but is meant to clarify our *
* interpretation of derived works with some common examples. Our *
* interpretation applies only to Nmap--we don't speak for other people's *
* GPL works. *
* *
* If you have any questions about the GPL licensing restrictions on using *
* Nmap in non-GPL works, we would be happy to help. As mentioned above, *
* we also offer alternative license to integrate Nmap into proprietary *
* applications and appliances. These contracts have been sold to dozens *
* of software vendors, and generally include a perpetual license as well *
* as providing for priority support and updates as well as helping to *
* fund the continued development of Nmap technology. Please email *
* sales@insecure.com for further information. *
* *
* As a special exception to the GPL terms, Insecure.Com LLC grants *
* permission to link the code of this program with any version of the *
* OpenSSL library which is distributed under a license identical to that *
* listed in the included docs/licenses/OpenSSL.txt file, and distribute *
* linked combinations including the two. You must obey the GNU GPL in all *
* respects for all of the code used other than OpenSSL. If you modify *
* this file, you may extend this exception to your version of the file, *
* but you are not obligated to do so. *
* *
* If you received these files with a written license agreement or *
* contract stating terms other than the terms above, then that *
* alternative license agreement takes precedence over these comments. *
* *
* Source is provided to this software because we believe users have a *
* right to know exactly what a program is going to do before they run it. *
* This also allows you to audit the software for security holes (none *
* have been found so far). *
* *
* Source code also allows you to port Nmap to new platforms, fix bugs, *
* and add new features. You are highly encouraged to send your changes *
* to nmap-dev@insecure.org for possible incorporation into the main *
* distribution. By sending these changes to Fyodor or one of the *
* Insecure.Org development mailing lists, it is assumed that you are *
* offering the Nmap Project (Insecure.Com LLC) the unlimited, *
* non-exclusive right to reuse, modify, and relicense the code. Nmap *
* will always be available Open Source, but this is important because the *
* inability to relicense code has caused devastating problems for other *
* Free Software projects (such as KDE and NASM). We also occasionally *
* relicense the code to third parties as discussed above. If you wish to *
* specify special license conditions of your contributions, just say so *
* when you send them. *
* *
* This program is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* General Public License v2.0 for more details at *
* http://www.gnu.org/licenses/gpl-2.0.html , or in the COPYING file *
* included with Nmap. *
* *
***************************************************************************/
/* This code was originally part of the Nping tool. */
#include "DestOptsHeader.h"
#include <assert.h>
/******************************************************************************/
/* CONTRUCTORS, DESTRUCTORS AND INITIALIZATION METHODS */
/******************************************************************************/
DestOptsHeader::DestOptsHeader() {
this->reset();
} /* End of DestOptsHeader constructor */
DestOptsHeader::~DestOptsHeader() {
} /* End of DestOptsHeader destructor */
/** Prints the contents of the header and calls print() on the next protocol
* header in the chain (if there is any).
* @return OP_SUCCESS on success and OP_FAILURE in case of error. */
int DestOptsHeader::print(FILE *output, int detail) const {
fprintf(output, "DestOpts[%d,%d]", this->h.nh, this->h.len);
// TODO: @todo : Implement this
if(this->next!=NULL){
print_separator(output, detail);
next->print(output, detail);
}
return OP_SUCCESS;
} /* End of print() */
/* Returns a protocol identifier. This is used by packet parsing funtions
* that return linked lists of PacketElement objects, to determine the protocol
* the object represents. */
int DestOptsHeader::protocol_id() const {
return HEADER_TYPE_IPv6_OPTS;
} /* End of protocol_id() */

117
libnetutil/DestOptsHeader.h Normal file
View File

@@ -0,0 +1,117 @@
/***************************************************************************
* DestOptsHeader.h -- The DestOptsHeader Class represents an IPv6 *
* Destination Options extension header. *
***********************IMPORTANT NMAP LICENSE TERMS************************
* *
* The Nmap Security Scanner is (C) 1996-2011 Insecure.Com LLC. Nmap is *
* also a registered trademark of Insecure.Com LLC. This program is free *
* software; you may redistribute and/or modify it under the terms of the *
* GNU General Public License as published by the Free Software *
* Foundation; Version 2 with the clarifications and exceptions described *
* below. This guarantees your right to use, modify, and redistribute *
* this software under certain conditions. If you wish to embed Nmap *
* technology into proprietary software, we sell alternative licenses *
* (contact sales@insecure.com). Dozens of software vendors already *
* license Nmap technology such as host discovery, port scanning, OS *
* detection, and version detection. *
* *
* Note that the GPL places important restrictions on "derived works", yet *
* it does not provide a detailed definition of that term. To avoid *
* misunderstandings, we consider an application to constitute a *
* "derivative work" for the purpose of this license if it does any of the *
* following: *
* o Integrates source code from Nmap *
* o Reads or includes Nmap copyrighted data files, such as *
* nmap-os-db or nmap-service-probes. *
* o Executes Nmap and parses the results (as opposed to typical shell or *
* execution-menu apps, which simply display raw Nmap output and so are *
* not derivative works.) *
* o Integrates/includes/aggregates Nmap into a proprietary executable *
* installer, such as those produced by InstallShield. *
* o Links to a library or executes a program that does any of the above *
* *
* The term "Nmap" should be taken to also include any portions or derived *
* works of Nmap. This list is not exclusive, but is meant to clarify our *
* interpretation of derived works with some common examples. Our *
* interpretation applies only to Nmap--we don't speak for other people's *
* GPL works. *
* *
* If you have any questions about the GPL licensing restrictions on using *
* Nmap in non-GPL works, we would be happy to help. As mentioned above, *
* we also offer alternative license to integrate Nmap into proprietary *
* applications and appliances. These contracts have been sold to dozens *
* of software vendors, and generally include a perpetual license as well *
* as providing for priority support and updates as well as helping to *
* fund the continued development of Nmap technology. Please email *
* sales@insecure.com for further information. *
* *
* As a special exception to the GPL terms, Insecure.Com LLC grants *
* permission to link the code of this program with any version of the *
* OpenSSL library which is distributed under a license identical to that *
* listed in the included docs/licenses/OpenSSL.txt file, and distribute *
* linked combinations including the two. You must obey the GNU GPL in all *
* respects for all of the code used other than OpenSSL. If you modify *
* this file, you may extend this exception to your version of the file, *
* but you are not obligated to do so. *
* *
* If you received these files with a written license agreement or *
* contract stating terms other than the terms above, then that *
* alternative license agreement takes precedence over these comments. *
* *
* Source is provided to this software because we believe users have a *
* right to know exactly what a program is going to do before they run it. *
* This also allows you to audit the software for security holes (none *
* have been found so far). *
* *
* Source code also allows you to port Nmap to new platforms, fix bugs, *
* and add new features. You are highly encouraged to send your changes *
* to nmap-dev@insecure.org for possible incorporation into the main *
* distribution. By sending these changes to Fyodor or one of the *
* Insecure.Org development mailing lists, it is assumed that you are *
* offering the Nmap Project (Insecure.Com LLC) the unlimited, *
* non-exclusive right to reuse, modify, and relicense the code. Nmap *
* will always be available Open Source, but this is important because the *
* inability to relicense code has caused devastating problems for other *
* Free Software projects (such as KDE and NASM). We also occasionally *
* relicense the code to third parties as discussed above. If you wish to *
* specify special license conditions of your contributions, just say so *
* when you send them. *
* *
* This program is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* General Public License v2.0 for more details at *
* http://www.gnu.org/licenses/gpl-2.0.html , or in the COPYING file *
* included with Nmap. *
* *
***************************************************************************/
/* This code was originally part of the Nping tool. */
#ifndef __DESTOPTS_HEADER_H__
#define __DESTOPTS_HEADER_H__ 1
#include "HopByHopHeader.h"
class DestOptsHeader : public HopByHopHeader {
private:
/* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Next Header | Hdr Ext Len | |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +
| |
. .
. Options .
. .
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */
// Implemented in HopByHopHeader.h
public:
DestOptsHeader();
~DestOptsHeader();
int print(FILE *output, int detail) const;
int protocol_id() const;
}; /* End of class DestOptsHeader */
#endif

250
libnetutil/EthernetHeader.cc Executable file
View File

@@ -0,0 +1,250 @@
/***************************************************************************
* EthernetHeader.cc -- The EthernetHeader Class represents an Ethernet *
* header and footer. It contains methods to set the different header *
* fields. These methods tipically perform the necessary error checks and *
* byte order conversions. *
* *
***********************IMPORTANT NMAP LICENSE TERMS************************
* *
* The Nmap Security Scanner is (C) 1996-2011 Insecure.Com LLC. Nmap is *
* also a registered trademark of Insecure.Com LLC. This program is free *
* software; you may redistribute and/or modify it under the terms of the *
* GNU General Public License as published by the Free Software *
* Foundation; Version 2 with the clarifications and exceptions described *
* below. This guarantees your right to use, modify, and redistribute *
* this software under certain conditions. If you wish to embed Nmap *
* technology into proprietary software, we sell alternative licenses *
* (contact sales@insecure.com). Dozens of software vendors already *
* license Nmap technology such as host discovery, port scanning, OS *
* detection, and version detection. *
* *
* Note that the GPL places important restrictions on "derived works", yet *
* it does not provide a detailed definition of that term. To avoid *
* misunderstandings, we consider an application to constitute a *
* "derivative work" for the purpose of this license if it does any of the *
* following: *
* o Integrates source code from Nmap *
* o Reads or includes Nmap copyrighted data files, such as *
* nmap-os-db or nmap-service-probes. *
* o Executes Nmap and parses the results (as opposed to typical shell or *
* execution-menu apps, which simply display raw Nmap output and so are *
* not derivative works.) *
* o Integrates/includes/aggregates Nmap into a proprietary executable *
* installer, such as those produced by InstallShield. *
* o Links to a library or executes a program that does any of the above *
* *
* The term "Nmap" should be taken to also include any portions or derived *
* works of Nmap. This list is not exclusive, but is meant to clarify our *
* interpretation of derived works with some common examples. Our *
* interpretation applies only to Nmap--we don't speak for other people's *
* GPL works. *
* *
* If you have any questions about the GPL licensing restrictions on using *
* Nmap in non-GPL works, we would be happy to help. As mentioned above, *
* we also offer alternative license to integrate Nmap into proprietary *
* applications and appliances. These contracts have been sold to dozens *
* of software vendors, and generally include a perpetual license as well *
* as providing for priority support and updates as well as helping to *
* fund the continued development of Nmap technology. Please email *
* sales@insecure.com for further information. *
* *
* As a special exception to the GPL terms, Insecure.Com LLC grants *
* permission to link the code of this program with any version of the *
* OpenSSL library which is distributed under a license identical to that *
* listed in the included docs/licenses/OpenSSL.txt file, and distribute *
* linked combinations including the two. You must obey the GNU GPL in all *
* respects for all of the code used other than OpenSSL. If you modify *
* this file, you may extend this exception to your version of the file, *
* but you are not obligated to do so. *
* *
* If you received these files with a written license agreement or *
* contract stating terms other than the terms above, then that *
* alternative license agreement takes precedence over these comments. *
* *
* Source is provided to this software because we believe users have a *
* right to know exactly what a program is going to do before they run it. *
* This also allows you to audit the software for security holes (none *
* have been found so far). *
* *
* Source code also allows you to port Nmap to new platforms, fix bugs, *
* and add new features. You are highly encouraged to send your changes *
* to nmap-dev@insecure.org for possible incorporation into the main *
* distribution. By sending these changes to Fyodor or one of the *
* Insecure.Org development mailing lists, it is assumed that you are *
* offering the Nmap Project (Insecure.Com LLC) the unlimited, *
* non-exclusive right to reuse, modify, and relicense the code. Nmap *
* will always be available Open Source, but this is important because the *
* inability to relicense code has caused devastating problems for other *
* Free Software projects (such as KDE and NASM). We also occasionally *
* relicense the code to third parties as discussed above. If you wish to *
* specify special license conditions of your contributions, just say so *
* when you send them. *
* *
* This program is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* General Public License v2.0 for more details at *
* http://www.gnu.org/licenses/gpl-2.0.html , or in the COPYING file *
* included with Nmap. *
* *
***************************************************************************/
/* This code was originally part of the Nping tool. */
#include "EthernetHeader.h"
/******************************************************************************/
/* CONTRUCTORS, DESTRUCTORS AND INITIALIZATION METHODS */
/******************************************************************************/
EthernetHeader::EthernetHeader(){
this->reset();
} /* End of EthernetHeader constructor */
EthernetHeader::~EthernetHeader(){
} /* End of EthernetHeader destructor */
/** Sets every attribute to its default value */
void EthernetHeader::reset(){
memset(&this->h, 0, sizeof(nping_eth_hdr_t));
this->length=ETH_HEADER_LEN;
} /* End of reset() */
/** @warning This method is essential for the superclass getBinaryBuffer()
* method to work. Do NOT change a thing unless you know what you're doing */
u8 * EthernetHeader::getBufferPointer(){
return (u8*)(&h);
} /* End of getBufferPointer() */
/******************************************************************************/
/* PacketElement:: OVERWRITTEN METHODS */
/******************************************************************************/
/** Stores supplied packet in the internal buffer so the information
* can be accessed using the standard get & set methods.
* @warning The EthernetHeader class is able to hold a maximum of 14 bytes.
* If the supplied buffer is longer than that, only the first 14 bytes will be
* stored in the internal buffer.
* @warning Supplied len MUST be at least 14 bytes (Ethernet header length).
* @return OP_SUCCESS on success and OP_FAILURE in case of error */
int EthernetHeader::storeRecvData(const u8 *buf, size_t len){
if(buf==NULL || len<ETH_HEADER_LEN){
return OP_FAILURE;
}else{
this->reset(); /* Re-init the object, just in case the caller had used it already */
this->length=ETH_HEADER_LEN;
memcpy(&(this->h), buf, ETH_HEADER_LEN);
}
return OP_SUCCESS;
} /* End of storeRecvData() */
/* Returns a protocol identifier. This is used by packet parsing funtions
* that return linked lists of PacketElement objects, to determine the protocol
* the object represents. */
int EthernetHeader::protocol_id() const {
return HEADER_TYPE_ETHERNET;
} /* End of protocol_id() */
/** Determines if the data stored in the object after an storeRecvData() call
* is valid and safe to use. This mainly checks the length of the data but may
* also test the value of certain protocol fields to ensure their correctness.
* @return the length, in bytes, of the header, if its found to be valid or
* OP_FAILURE (-1) otherwise. */
int EthernetHeader::validate(){
if( this->length!=ETH_HEADER_LEN)
return OP_FAILURE;
else
return ETH_HEADER_LEN;
} /* End of validate() */
/** Prints the contents of the header and calls print() on the next protocol
* header in the chain (if there is any).
* @return OP_SUCCESS on success and OP_FAILURE in case of error. */
int EthernetHeader::print(FILE *output, int detail) const {
fprintf(output, "Eth[");
for(int i=0; i<6; i++){
fprintf(output, "%02x", this->h.eth_smac[i]);
if(i<5)
fprintf(output, ":");
}
fprintf(output, " > ");
for(int i=0; i<6; i++){
fprintf(output, "%02x", this->h.eth_dmac[i]);
if(i<5)
fprintf(output, ":");
}
if(detail>=PRINT_DETAIL_MED)
fprintf(output, " Type=%04x", this->getEtherType());
fprintf(output, "]");
if(this->next!=NULL){
print_separator(output, detail);
next->print(output, detail);
}
return OP_SUCCESS;
} /* End of print() */
/******************************************************************************/
/* PROTOCOL-SPECIFIC METHODS */
/******************************************************************************/
/** Sets Source MAC address
* @warning Supplied buffer must contain at least 6 bytes */
int EthernetHeader::setSrcMAC(const u8 *m){
if(m==NULL)
netutil_fatal("EthernetHeader::setSrcMAC(u8*): NULL value supplied ");
memcpy(h.eth_smac, m, 6);
return OP_SUCCESS;
} /* End of setSrcMAC() */
/** Returns source port in HOST byte order
* @warning Returned pointer points directly to a Class internal buffer. If
* contents are changed, the instance of the class will be affected. */
const u8* EthernetHeader::getSrcMAC() const {
return this->h.eth_smac;
} /* End of getSrcMAC() */
/** Sets Destination MAC address
* @warning Supplied buffer must contain at least 6 bytes */
int EthernetHeader::setDstMAC(u8 *m){
if(m==NULL)
netutil_fatal("EthernetHeader::setDstMAC(u8 *): NULL value supplied ");
memcpy(h.eth_dmac, m, 6);
return OP_SUCCESS;
} /* End of setDstMAC() */
/** Returns destination port in HOST byte order */
const u8 *EthernetHeader::getDstMAC() const {
return this->h.eth_dmac;
} /* End of getDstMAC() */
int EthernetHeader::setEtherType(u16 val){
h.eth_type=htons(val);
return OP_SUCCESS;
} /* End of setEtherType() */
/** Returns destination port in HOST byte order */
const u16 EthernetHeader::getEtherType() const {
return ntohs(this->h.eth_type);
} /* End of getEtherType() */

164
libnetutil/EthernetHeader.h Executable file
View File

@@ -0,0 +1,164 @@
/***************************************************************************
* EthernetHeader.h -- The EthernetHeader Class represents an Ethernet *
* header and footer. It contains methods to set the different header *
* fields. These methods tipically perform the necessary error checks and *
* byte order conversions. *
* *
***********************IMPORTANT NMAP LICENSE TERMS************************
* *
* The Nmap Security Scanner is (C) 1996-2011 Insecure.Com LLC. Nmap is *
* also a registered trademark of Insecure.Com LLC. This program is free *
* software; you may redistribute and/or modify it under the terms of the *
* GNU General Public License as published by the Free Software *
* Foundation; Version 2 with the clarifications and exceptions described *
* below. This guarantees your right to use, modify, and redistribute *
* this software under certain conditions. If you wish to embed Nmap *
* technology into proprietary software, we sell alternative licenses *
* (contact sales@insecure.com). Dozens of software vendors already *
* license Nmap technology such as host discovery, port scanning, OS *
* detection, and version detection. *
* *
* Note that the GPL places important restrictions on "derived works", yet *
* it does not provide a detailed definition of that term. To avoid *
* misunderstandings, we consider an application to constitute a *
* "derivative work" for the purpose of this license if it does any of the *
* following: *
* o Integrates source code from Nmap *
* o Reads or includes Nmap copyrighted data files, such as *
* nmap-os-db or nmap-service-probes. *
* o Executes Nmap and parses the results (as opposed to typical shell or *
* execution-menu apps, which simply display raw Nmap output and so are *
* not derivative works.) *
* o Integrates/includes/aggregates Nmap into a proprietary executable *
* installer, such as those produced by InstallShield. *
* o Links to a library or executes a program that does any of the above *
* *
* The term "Nmap" should be taken to also include any portions or derived *
* works of Nmap. This list is not exclusive, but is meant to clarify our *
* interpretation of derived works with some common examples. Our *
* interpretation applies only to Nmap--we don't speak for other people's *
* GPL works. *
* *
* If you have any questions about the GPL licensing restrictions on using *
* Nmap in non-GPL works, we would be happy to help. As mentioned above, *
* we also offer alternative license to integrate Nmap into proprietary *
* applications and appliances. These contracts have been sold to dozens *
* of software vendors, and generally include a perpetual license as well *
* as providing for priority support and updates as well as helping to *
* fund the continued development of Nmap technology. Please email *
* sales@insecure.com for further information. *
* *
* As a special exception to the GPL terms, Insecure.Com LLC grants *
* permission to link the code of this program with any version of the *
* OpenSSL library which is distributed under a license identical to that *
* listed in the included docs/licenses/OpenSSL.txt file, and distribute *
* linked combinations including the two. You must obey the GNU GPL in all *
* respects for all of the code used other than OpenSSL. If you modify *
* this file, you may extend this exception to your version of the file, *
* but you are not obligated to do so. *
* *
* If you received these files with a written license agreement or *
* contract stating terms other than the terms above, then that *
* alternative license agreement takes precedence over these comments. *
* *
* Source is provided to this software because we believe users have a *
* right to know exactly what a program is going to do before they run it. *
* This also allows you to audit the software for security holes (none *
* have been found so far). *
* *
* Source code also allows you to port Nmap to new platforms, fix bugs, *
* and add new features. You are highly encouraged to send your changes *
* to nmap-dev@insecure.org for possible incorporation into the main *
* distribution. By sending these changes to Fyodor or one of the *
* Insecure.Org development mailing lists, it is assumed that you are *
* offering the Nmap Project (Insecure.Com LLC) the unlimited, *
* non-exclusive right to reuse, modify, and relicense the code. Nmap *
* will always be available Open Source, but this is important because the *
* inability to relicense code has caused devastating problems for other *
* Free Software projects (such as KDE and NASM). We also occasionally *
* relicense the code to third parties as discussed above. If you wish to *
* specify special license conditions of your contributions, just say so *
* when you send them. *
* *
* This program is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* General Public License v2.0 for more details at *
* http://www.gnu.org/licenses/gpl-2.0.html , or in the COPYING file *
* included with Nmap. *
* *
***************************************************************************/
/* This code was originally part of the Nping tool. */
#ifndef ETHERNETHEADER_H
#define ETHERNETHEADER_H 1
#include "DataLinkLayerElement.h"
/* Ether Types. (From RFC 5342 http://www.rfc-editor.org/rfc/rfc5342.txt) */
#define ETHTYPE_IPV4 0x0800 /* Internet Protocol Version 4 */
#define ETHTYPE_ARP 0x0806 /* Address Resolution Protocol */
#define ETHTYPE_FRAMERELAY 0x0808 /* Frame Relay ARP */
#define ETHTYPE_PPTP 0x880B /* Point-to-Point Tunneling Protocol */
#define ETHTYPE_GSMP 0x880C /* General Switch Management Protocol */
#define ETHTYPE_RARP 0x8035 /* Reverse Address Resolution Protocol */
#define ETHTYPE_IPV6 0x86DD /* Internet Protocol Version 6 */
#define ETHTYPE_MPLS 0x8847 /* MPLS */
#define ETHTYPE_MPS_UAL 0x8848 /* MPLS with upstream-assigned label */
#define ETHTYPE_MCAP 0x8861 /* Multicast Channel Allocation Protocol */
#define ETHTYPE_PPPOE_D 0x8863 /* PPP over Ethernet Discovery Stage */
#define ETHTYPE_PPOE_S 0x8864 /* PPP over Ethernet Session Stage */
#define ETHTYPE_CTAG 0x8100 /* Customer VLAN Tag Type */
#define ETHTYPE_EPON 0x8808 /* Ethernet Passive Optical Network */
#define ETHTYPE_PBNAC 0x888E /* Port-based network access control */
#define ETHTYPE_STAG 0x88A8 /* Service VLAN tag identifier */
#define ETHTYPE_ETHEXP1 0x88B5 /* Local Experimental Ethertype */
#define ETHTYPE_ETHEXP2 0x88B6 /* Local Experimental Ethertype */
#define ETHTYPE_ETHOUI 0x88B7 /* OUI Extended Ethertype */
#define ETHTYPE_PREAUTH 0x88C7 /* Pre-Authentication */
#define ETHTYPE_LLDP 0x88CC /* Link Layer Discovery Protocol (LLDP) */
#define ETHTYPE_MACSEC 0x88E5 /* Media Access Control Security */
#define ETHTYPE_MVRP 0x88F5 /* Multiple VLAN Registration Protocol */
#define ETHTYPE_MMRP 0x88F6 /* Multiple Multicast Registration Protocol */
#define ETHTYPE_FRRR 0x890D /* Fast Roaming Remote Request */
#define ETH_HEADER_LEN 14
class EthernetHeader : public DataLinkLayerElement {
private:
struct nping_eth_hdr{
u8 eth_dmac[6];
u8 eth_smac[6];
u16 eth_type;
}__attribute__((__packed__));
typedef struct nping_eth_hdr nping_eth_hdr_t;
nping_eth_hdr_t h;
public:
EthernetHeader();
~EthernetHeader();
void reset();
u8 *getBufferPointer();
int storeRecvData(const u8 *buf, size_t len);
int protocol_id() const;
int validate();
int print(FILE *output, int detail) const;
int setSrcMAC(const u8 *m);
const u8 *getSrcMAC() const;
int setDstMAC(u8 *m);
const u8 *getDstMAC() const;
int setEtherType(u16 val);
const u16 getEtherType() const;
};
#endif

View File

@@ -0,0 +1,243 @@
/***************************************************************************
* FragmentHeader.cc -- The FragmentHeader Class represents an IPv6 *
* Hop-by-Hop extension header. *
***********************IMPORTANT NMAP LICENSE TERMS************************
* *
* The Nmap Security Scanner is (C) 1996-2011 Insecure.Com LLC. Nmap is *
* also a registered trademark of Insecure.Com LLC. This program is free *
* software; you may redistribute and/or modify it under the terms of the *
* GNU General Public License as published by the Free Software *
* Foundation; Version 2 with the clarifications and exceptions described *
* below. This guarantees your right to use, modify, and redistribute *
* this software under certain conditions. If you wish to embed Nmap *
* technology into proprietary software, we sell alternative licenses *
* (contact sales@insecure.com). Dozens of software vendors already *
* license Nmap technology such as host discovery, port scanning, OS *
* detection, and version detection. *
* *
* Note that the GPL places important restrictions on "derived works", yet *
* it does not provide a detailed definition of that term. To avoid *
* misunderstandings, we consider an application to constitute a *
* "derivative work" for the purpose of this license if it does any of the *
* following: *
* o Integrates source code from Nmap *
* o Reads or includes Nmap copyrighted data files, such as *
* nmap-os-db or nmap-service-probes. *
* o Executes Nmap and parses the results (as opposed to typical shell or *
* execution-menu apps, which simply display raw Nmap output and so are *
* not derivative works.) *
* o Integrates/includes/aggregates Nmap into a proprietary executable *
* installer, such as those produced by InstallShield. *
* o Links to a library or executes a program that does any of the above *
* *
* The term "Nmap" should be taken to also include any portions or derived *
* works of Nmap. This list is not exclusive, but is meant to clarify our *
* interpretation of derived works with some common examples. Our *
* interpretation applies only to Nmap--we don't speak for other people's *
* GPL works. *
* *
* If you have any questions about the GPL licensing restrictions on using *
* Nmap in non-GPL works, we would be happy to help. As mentioned above, *
* we also offer alternative license to integrate Nmap into proprietary *
* applications and appliances. These contracts have been sold to dozens *
* of software vendors, and generally include a perpetual license as well *
* as providing for priority support and updates as well as helping to *
* fund the continued development of Nmap technology. Please email *
* sales@insecure.com for further information. *
* *
* As a special exception to the GPL terms, Insecure.Com LLC grants *
* permission to link the code of this program with any version of the *
* OpenSSL library which is distributed under a license identical to that *
* listed in the included docs/licenses/OpenSSL.txt file, and distribute *
* linked combinations including the two. You must obey the GNU GPL in all *
* respects for all of the code used other than OpenSSL. If you modify *
* this file, you may extend this exception to your version of the file, *
* but you are not obligated to do so. *
* *
* If you received these files with a written license agreement or *
* contract stating terms other than the terms above, then that *
* alternative license agreement takes precedence over these comments. *
* *
* Source is provided to this software because we believe users have a *
* right to know exactly what a program is going to do before they run it. *
* This also allows you to audit the software for security holes (none *
* have been found so far). *
* *
* Source code also allows you to port Nmap to new platforms, fix bugs, *
* and add new features. You are highly encouraged to send your changes *
* to nmap-dev@insecure.org for possible incorporation into the main *
* distribution. By sending these changes to Fyodor or one of the *
* Insecure.Org development mailing lists, it is assumed that you are *
* offering the Nmap Project (Insecure.Com LLC) the unlimited, *
* non-exclusive right to reuse, modify, and relicense the code. Nmap *
* will always be available Open Source, but this is important because the *
* inability to relicense code has caused devastating problems for other *
* Free Software projects (such as KDE and NASM). We also occasionally *
* relicense the code to third parties as discussed above. If you wish to *
* specify special license conditions of your contributions, just say so *
* when you send them. *
* *
* This program is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* General Public License v2.0 for more details at *
* http://www.gnu.org/licenses/gpl-2.0.html , or in the COPYING file *
* included with Nmap. *
* *
***************************************************************************/
/* This code was originally part of the Nping tool. */
#include "FragmentHeader.h"
#include <assert.h>
/******************************************************************************/
/* CONTRUCTORS, DESTRUCTORS AND INITIALIZATION METHODS */
/******************************************************************************/
FragmentHeader::FragmentHeader() {
this->reset();
} /* End of FragmentHeader constructor */
FragmentHeader::~FragmentHeader() {
} /* End of FragmentHeader destructor */
/** Sets every attribute to its default value */
void FragmentHeader::reset(){
memset(&this->h, 0, sizeof(nping_ipv6_ext_fragment_hdr_t));
this->length=8;
} /* End of reset() */
/******************************************************************************/
/* PacketElement:: OVERWRITTEN METHODS */
/******************************************************************************/
/** @warning This method is essential for the superclass getBinaryBuffer()
* method to work. Do NOT change a thing unless you know what you're doing */
u8 *FragmentHeader::getBufferPointer(){
return (u8*)(&this->h);
} /* End of getBufferPointer() */
/** Stores supplied packet in the internal buffer so the information
* can be accessed using the standard get & set methods.
* @warning The FragmentHeader class is able to hold a maximum of
* sizeof(nping_icmpv6_hdr_t) bytes. If the supplied buffer is longer than
* that, only the first 1508 bytes will be stored in the internal buffer.
* @warning Supplied len MUST be at least 8 bytes (min ICMPv6 header length).
* @return OP_SUCCESS on success and OP_FAILURE in case of error */
int FragmentHeader::storeRecvData(const u8 *buf, size_t len){
if(buf==NULL || len<FRAGMENT_HEADER_LEN){
this->length=0;
return OP_FAILURE;
}else{
int stored_len = MIN(FRAGMENT_HEADER_LEN, len);
this->reset(); /* Re-init the object, just in case the caller had used it already */
this->length=stored_len;
memcpy(&(this->h), buf, stored_len);
}
return OP_SUCCESS;
} /* End of storeRecvData() */
/* Returns a protocol identifier. This is used by packet parsing funtions
* that return linked lists of PacketElement objects, to determine the protocol
* the object represents. */
int FragmentHeader::protocol_id() const {
return HEADER_TYPE_IPv6_FRAG;
} /* End of protocol_id() */
/** Determines if the data stored in the object after an storeRecvData() call
* is valid and safe to use. This mainly checks the length of the data but may
* also test the value of certain protocol fields to ensure their correctness.
* @return the length, in bytes, of the header, if its found to be valid or
* OP_FAILURE (-1) otherwise. */
int FragmentHeader::validate(){
/* Check the object's length makes sense*/
if(this->length != FRAGMENT_HEADER_LEN){
return OP_FAILURE;
}
/* There is not much to check for here, since header fields may take any
* value. We could certainly check the NextHeader value, but let's leave
* that for the class user. */
return this->length;
} /* End of validate() */
/** Prints the contents of the header and calls print() on the next protocol
* header in the chain (if there is any).
* @return OP_SUCCESS on success and OP_FAILURE in case of error. */
int FragmentHeader::print(FILE *output, int detail) const {
fprintf(output, "Fragment[%d, %d]", this->h.nh, this->h.id);
// TODO: @todo : Implement this
if(this->next!=NULL){
print_separator(output, detail);
next->print(output, detail);
}
return OP_SUCCESS;
} /* End of print() */
/******************************************************************************/
/* PROTOCOL-SPECIFIC METHODS */
/******************************************************************************/
/** Set Next Header field */
int FragmentHeader::setNextHeader(u8 val){
this->h.nh = val;
return OP_SUCCESS;
} /* End of setNextHeader() */
/** Returns next header id */
u8 FragmentHeader::getNextHeader(){
return this->h.nh;
} /* End of getNextHeader() */
/** Set Offset field */
int FragmentHeader::setOffset(u16 val){
this->h.off_res_flag[0]=(u8)(val >> 8);
this->h.off_res_flag[1]=(u8)((this->h.off_res_flag[1] & 0x7) | (val & ~0x7));
return OP_SUCCESS;
} /* End of setOffset() */
/** Returns fragment offset */
u16 FragmentHeader::getOffset(){
return ((this->h.off_res_flag[0] << 8) + this->h.off_res_flag[1]) & 0xfff8;
} /* End of getOffset() */
/* Sets the "More Fragments" flag. */
int FragmentHeader::setM(bool m_flag){
if(m_flag)
this->h.off_res_flag[1]= (u8)((this->h.off_res_flag[1] & ~0x01) | 0x01);
else
this->h.off_res_flag[1]= (u8)((this->h.off_res_flag[1] & ~0x1));
return OP_SUCCESS;
} /* End of setM() */
/* Returns true if the "More Fragments" flag is set; false otherwise. */
bool FragmentHeader::getM(){
return (this->h.off_res_flag[1] & 0x01);
} /* End of getM() */
/** Set the fragment identifier */
int FragmentHeader::setIdentification(u32 val){
this->h.id=htonl(val);
return OP_SUCCESS;
} /* End of setIdentification() */
/** Returns the fragment identifier*/
u32 FragmentHeader::getIdentification(){
return ntohl(this->h.id);
} /* End of getIdentification.() */

144
libnetutil/FragmentHeader.h Normal file
View File

@@ -0,0 +1,144 @@
/***************************************************************************
* FragmentHeader.h -- The FragmentHeader Class represents an IPv6 *
* Hop-by-Hop extension header. *
***********************IMPORTANT NMAP LICENSE TERMS************************
* *
* The Nmap Security Scanner is (C) 1996-2011 Insecure.Com LLC. Nmap is *
* also a registered trademark of Insecure.Com LLC. This program is free *
* software; you may redistribute and/or modify it under the terms of the *
* GNU General Public License as published by the Free Software *
* Foundation; Version 2 with the clarifications and exceptions described *
* below. This guarantees your right to use, modify, and redistribute *
* this software under certain conditions. If you wish to embed Nmap *
* technology into proprietary software, we sell alternative licenses *
* (contact sales@insecure.com). Dozens of software vendors already *
* license Nmap technology such as host discovery, port scanning, OS *
* detection, and version detection. *
* *
* Note that the GPL places important restrictions on "derived works", yet *
* it does not provide a detailed definition of that term. To avoid *
* misunderstandings, we consider an application to constitute a *
* "derivative work" for the purpose of this license if it does any of the *
* following: *
* o Integrates source code from Nmap *
* o Reads or includes Nmap copyrighted data files, such as *
* nmap-os-db or nmap-service-probes. *
* o Executes Nmap and parses the results (as opposed to typical shell or *
* execution-menu apps, which simply display raw Nmap output and so are *
* not derivative works.) *
* o Integrates/includes/aggregates Nmap into a proprietary executable *
* installer, such as those produced by InstallShield. *
* o Links to a library or executes a program that does any of the above *
* *
* The term "Nmap" should be taken to also include any portions or derived *
* works of Nmap. This list is not exclusive, but is meant to clarify our *
* interpretation of derived works with some common examples. Our *
* interpretation applies only to Nmap--we don't speak for other people's *
* GPL works. *
* *
* If you have any questions about the GPL licensing restrictions on using *
* Nmap in non-GPL works, we would be happy to help. As mentioned above, *
* we also offer alternative license to integrate Nmap into proprietary *
* applications and appliances. These contracts have been sold to dozens *
* of software vendors, and generally include a perpetual license as well *
* as providing for priority support and updates as well as helping to *
* fund the continued development of Nmap technology. Please email *
* sales@insecure.com for further information. *
* *
* As a special exception to the GPL terms, Insecure.Com LLC grants *
* permission to link the code of this program with any version of the *
* OpenSSL library which is distributed under a license identical to that *
* listed in the included docs/licenses/OpenSSL.txt file, and distribute *
* linked combinations including the two. You must obey the GNU GPL in all *
* respects for all of the code used other than OpenSSL. If you modify *
* this file, you may extend this exception to your version of the file, *
* but you are not obligated to do so. *
* *
* If you received these files with a written license agreement or *
* contract stating terms other than the terms above, then that *
* alternative license agreement takes precedence over these comments. *
* *
* Source is provided to this software because we believe users have a *
* right to know exactly what a program is going to do before they run it. *
* This also allows you to audit the software for security holes (none *
* have been found so far). *
* *
* Source code also allows you to port Nmap to new platforms, fix bugs, *
* and add new features. You are highly encouraged to send your changes *
* to nmap-dev@insecure.org for possible incorporation into the main *
* distribution. By sending these changes to Fyodor or one of the *
* Insecure.Org development mailing lists, it is assumed that you are *
* offering the Nmap Project (Insecure.Com LLC) the unlimited, *
* non-exclusive right to reuse, modify, and relicense the code. Nmap *
* will always be available Open Source, but this is important because the *
* inability to relicense code has caused devastating problems for other *
* Free Software projects (such as KDE and NASM). We also occasionally *
* relicense the code to third parties as discussed above. If you wish to *
* specify special license conditions of your contributions, just say so *
* when you send them. *
* *
* This program is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* General Public License v2.0 for more details at *
* http://www.gnu.org/licenses/gpl-2.0.html , or in the COPYING file *
* included with Nmap. *
* *
***************************************************************************/
/* This code was originally part of the Nping tool. */
#ifndef __FRAGMENT_HEADER_H__
#define __FRAGMENT_HEADER_H__ 1
#include "IPv6ExtensionHeader.h"
#define FRAGMENT_HEADER_LEN 8
class FragmentHeader : public IPv6ExtensionHeader {
private:
/* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Next Header | Reserved | Fragment Offset |Res|M|
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Identification |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */
struct nping_ipv6_ext_fragment_hdr{
u8 nh;
u8 res1;
u8 off_res_flag[2];
u32 id;
}__attribute__((__packed__));
typedef struct nping_ipv6_ext_fragment_hdr nping_ipv6_ext_fragment_hdr_t;
nping_ipv6_ext_fragment_hdr_t h;
public:
FragmentHeader();
~FragmentHeader();
void reset();
u8 *getBufferPointer();
int storeRecvData(const u8 *buf, size_t len);
int protocol_id() const;
int validate();
int print(FILE *output, int detail) const;
/* Protocol specific methods */
int setNextHeader(u8 val);
u8 getNextHeader();
int setOffset(u16 val);
u16 getOffset();
int setM(bool m_flag);
bool getM();
int setIdentification(u32 val);
u32 getIdentification();
}; /* End of class FragmentHeader */
#endif

View File

@@ -0,0 +1,418 @@
/***************************************************************************
* HopByHopHeader.cc -- The HopByHopHeader Class represents an IPv6 *
* Hop-by-Hop extension header. *
***********************IMPORTANT NMAP LICENSE TERMS************************
* *
* The Nmap Security Scanner is (C) 1996-2011 Insecure.Com LLC. Nmap is *
* also a registered trademark of Insecure.Com LLC. This program is free *
* software; you may redistribute and/or modify it under the terms of the *
* GNU General Public License as published by the Free Software *
* Foundation; Version 2 with the clarifications and exceptions described *
* below. This guarantees your right to use, modify, and redistribute *
* this software under certain conditions. If you wish to embed Nmap *
* technology into proprietary software, we sell alternative licenses *
* (contact sales@insecure.com). Dozens of software vendors already *
* license Nmap technology such as host discovery, port scanning, OS *
* detection, and version detection. *
* *
* Note that the GPL places important restrictions on "derived works", yet *
* it does not provide a detailed definition of that term. To avoid *
* misunderstandings, we consider an application to constitute a *
* "derivative work" for the purpose of this license if it does any of the *
* following: *
* o Integrates source code from Nmap *
* o Reads or includes Nmap copyrighted data files, such as *
* nmap-os-db or nmap-service-probes. *
* o Executes Nmap and parses the results (as opposed to typical shell or *
* execution-menu apps, which simply display raw Nmap output and so are *
* not derivative works.) *
* o Integrates/includes/aggregates Nmap into a proprietary executable *
* installer, such as those produced by InstallShield. *
* o Links to a library or executes a program that does any of the above *
* *
* The term "Nmap" should be taken to also include any portions or derived *
* works of Nmap. This list is not exclusive, but is meant to clarify our *
* interpretation of derived works with some common examples. Our *
* interpretation applies only to Nmap--we don't speak for other people's *
* GPL works. *
* *
* If you have any questions about the GPL licensing restrictions on using *
* Nmap in non-GPL works, we would be happy to help. As mentioned above, *
* we also offer alternative license to integrate Nmap into proprietary *
* applications and appliances. These contracts have been sold to dozens *
* of software vendors, and generally include a perpetual license as well *
* as providing for priority support and updates as well as helping to *
* fund the continued development of Nmap technology. Please email *
* sales@insecure.com for further information. *
* *
* As a special exception to the GPL terms, Insecure.Com LLC grants *
* permission to link the code of this program with any version of the *
* OpenSSL library which is distributed under a license identical to that *
* listed in the included docs/licenses/OpenSSL.txt file, and distribute *
* linked combinations including the two. You must obey the GNU GPL in all *
* respects for all of the code used other than OpenSSL. If you modify *
* this file, you may extend this exception to your version of the file, *
* but you are not obligated to do so. *
* *
* If you received these files with a written license agreement or *
* contract stating terms other than the terms above, then that *
* alternative license agreement takes precedence over these comments. *
* *
* Source is provided to this software because we believe users have a *
* right to know exactly what a program is going to do before they run it. *
* This also allows you to audit the software for security holes (none *
* have been found so far). *
* *
* Source code also allows you to port Nmap to new platforms, fix bugs, *
* and add new features. You are highly encouraged to send your changes *
* to nmap-dev@insecure.org for possible incorporation into the main *
* distribution. By sending these changes to Fyodor or one of the *
* Insecure.Org development mailing lists, it is assumed that you are *
* offering the Nmap Project (Insecure.Com LLC) the unlimited, *
* non-exclusive right to reuse, modify, and relicense the code. Nmap *
* will always be available Open Source, but this is important because the *
* inability to relicense code has caused devastating problems for other *
* Free Software projects (such as KDE and NASM). We also occasionally *
* relicense the code to third parties as discussed above. If you wish to *
* specify special license conditions of your contributions, just say so *
* when you send them. *
* *
* This program is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* General Public License v2.0 for more details at *
* http://www.gnu.org/licenses/gpl-2.0.html , or in the COPYING file *
* included with Nmap. *
* *
***************************************************************************/
/* This code was originally part of the Nping tool. */
#include "HopByHopHeader.h"
#include <assert.h>
/******************************************************************************/
/* CONTRUCTORS, DESTRUCTORS AND INITIALIZATION METHODS */
/******************************************************************************/
HopByHopHeader::HopByHopHeader() {
this->reset();
} /* End of HopByHopHeader constructor */
HopByHopHeader::~HopByHopHeader() {
} /* End of HopByHopHeader destructor */
/** Sets every attribute to its default value */
void HopByHopHeader::reset(){
memset(&this->h, 0, sizeof(nping_ipv6_ext_hopbyhop_hdr_t));
curr_option=(u8*)this->h.options;
this->length=2;
this->addOption(EXTOPT_PADN, 4, (const u8*)"\x00\x00\x00\x00");
} /* End of reset() */
/******************************************************************************/
/* PacketElement:: OVERWRITTEN METHODS */
/******************************************************************************/
/** @warning This method is essential for the superclass getBinaryBuffer()
* method to work. Do NOT change a thing unless you know what you're doing */
u8 *HopByHopHeader::getBufferPointer(){
return (u8*)(&this->h);
} /* End of getBufferPointer() */
/** Stores supplied packet in the internal buffer so the information
* can be accessed using the standard get & set methods.
* @warning The HopByHopHeader class is able to hold a maximum of
* sizeof(nping_icmpv6_hdr_t) bytes. If the supplied buffer is longer than
* that, only the first 1508 bytes will be stored in the internal buffer.
* @warning Supplied len MUST be at least 8 bytes (min ICMPv6 header length).
* @return OP_SUCCESS on success and OP_FAILURE in case of error */
int HopByHopHeader::storeRecvData(const u8 *buf, size_t len){
if(buf==NULL || len<HOPBYHOP_MIN_HEADER_LEN){
this->length=0;
return OP_FAILURE;
}else{
/* Store the first 4 bytes, so we can access the HdrExtLen field. */
memcpy(&(this->h), buf, 4);
/* Check that the HdrExtLen field makes sense:
* 1) Check that it carries as many octets as it claims
* 2) Check that we don't exceed our internal storage space. */
if( ((unsigned int)(this->h.len+1))*8 > len || (this->h.len+1)*8 > HOPBYHOP_MAX_HEADER_LEN){
this->length=0;
return OP_FAILURE;
}else{
int mylen=(this->h.len+1)*8;
this->reset();
this->length=mylen;
memcpy(&(this->h), buf, this->length);
return OP_SUCCESS;
}
}
return OP_FAILURE;
} /* End of storeRecvData() */
/* Returns a protocol identifier. This is used by packet parsing funtions
* that return linked lists of PacketElement objects, to determine the protocol
* the object represents. */
int HopByHopHeader::protocol_id() const {
return HEADER_TYPE_IPv6_HOPOPT;
} /* End of protocol_id() */
/** Determines if the data stored in the object after an storeRecvData() call
* is valid and safe to use. This mainly checks the length of the data but may
* also test the value of certain protocol fields to ensure their correctness.
* @return the length, in bytes, of the header, if its found to be valid or
* OP_FAILURE (-1) otherwise. */
int HopByHopHeader::validate(){
nping_ipv6_ext_hopbyhop_opt_t *curr_opt=NULL;
u8 *curr_pnt=(u8 *)this->h.options;
int bytes_left=this->length-2;
/* Check the object's length makes sense*/
if(this->length%8!=0 || this->length < HOPBYHOP_MIN_HEADER_LEN || this->length > HOPBYHOP_MAX_HEADER_LEN){
return OP_FAILURE;
}
/* Check the header's length field. It should match the object's length */
if( (this->h.len+1)*8 != this->length){
return OP_FAILURE;
}
/* Now validate the TLV-encoded options. */
while(bytes_left>0){
/* Use the opts structure as a template to access current option */
curr_opt=(nping_ipv6_ext_hopbyhop_opt_t *)curr_pnt;
/* Let's see what we have. */
switch(curr_opt->type){
/* Pad1
+-+-+-+-+-+-+-+-+
| 0 |
+-+-+-+-+-+-+-+-+ */
case EXTOPT_PAD1:
curr_pnt++; /* Skip one octet */
bytes_left++;
break;
/* PadN
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+- - - - - - - - -
| 1 | Padding Len | Padding
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+- - - - - - - - - */
case EXTOPT_PADN:
/* Check we have as many octets as the option advertises */
if(bytes_left<2+curr_opt->len)
return OP_FAILURE;
curr_pnt+=2+curr_opt->len;
bytes_left-=2+curr_opt->len;
break;
/* Jumbo Payload Option (RFC 2675).
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Option Type | Opt Data Len |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Jumbo Payload Length |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */
case EXTOPT_JUMBO:
/* Jumbo has a fixed length of 4 octets (plus 2). */
if(curr_opt->len!=4)
return OP_FAILURE;
/* Check if we actually have all the octets */
if(bytes_left<2+4)
return OP_FAILURE;
curr_pnt+=6;
bytes_left-=6;
break;
/* Tunnel Encapsulation limit (RFC 2473).
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Option Type | 1 | Tun Encap Lim |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */
case EXTOPT_TUNENCAPLIM:
/* This one also has a fixed length. */
if(curr_opt->len!=1)
return OP_FAILURE;
/* Check if we actually have all the octets */
if(bytes_left<2+1)
return OP_FAILURE;
curr_pnt+=3;
bytes_left-=3;
break;
/* Router Alert (RFC 2711).
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Option Type | 2 | Value (2 octets) |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */
case EXTOPT_ROUTERALERT:
/* Fixed length (two octets)*/
if(curr_opt->len!=2)
return OP_FAILURE;
/* Check that we actually have all the octets */
if(bytes_left<2+2)
return OP_FAILURE;
curr_pnt+=4;
bytes_left-=4;
break;
/* Quick-Start (RFC 4782).
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Option | Length=6 | Func. | Rate | Not Used |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| QS Nonce | R |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */
case EXTOPT_QUICKSTART:
/* Fixed length (two octets)*/
if(curr_opt->len!=6)
return OP_FAILURE;
/* Check that we actually have all the octets */
if(bytes_left<2+6)
return OP_FAILURE;
curr_pnt+=8;
bytes_left-=8;
break;
/* CALIPSO (RFC 5570).
+----------------------------+
| Option Type | Option Length|
+-------------+---------------+-------------+--------------+
| CALIPSO Domain of Interpretation |
+-------------+---------------+-------------+--------------+
| Cmpt Length | Sens Level | Checksum (CRC-16) |
+-------------+---------------+-------------+--------------+
| Compartment Bitmap (Optional; variable length) |
+-------------+---------------+-------------+--------------+ */
case EXTOPT_CALIPSO:
/* The length of the CALIPSO option is variable because the
* Compartment Bitmap is not mandatory. However, the length
* must be at least 8. */
if(curr_opt->len<8)
return OP_FAILURE;
/* Check that we actually have all the octets */
if(bytes_left<2+curr_opt->len)
return OP_FAILURE;
curr_pnt+=2+curr_opt->len;
bytes_left-=2+curr_opt->len;
break;
/* Home Address (RFC 6275).
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Option Type | Option Length |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+ +
| |
+ Home Address +
| |
+ +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+*/
case EXTOPT_HOMEADDR:
/* Fixed length of 16 */
if(curr_opt->len!=16)
return OP_FAILURE;
/* Check if we actually have all the octets */
if(bytes_left<2+16)
return OP_FAILURE;
curr_pnt+=18;
bytes_left-=18;
break;
/* Option Type Unknown */
default:
/* If we don't know the option, we can still try to validate it,
* checking if the OptionLength contains something reasonable. */
/* Fixed length of 16 */
if(bytes_left<2+curr_opt->len)
return OP_FAILURE;
curr_pnt+=2+curr_opt->len;
bytes_left-=2+curr_opt->len;
break;
}
}
return this->length;
} /* End of validate() */
/** Prints the contents of the header and calls print() on the next protocol
* header in the chain (if there is any).
* @return OP_SUCCESS on success and OP_FAILURE in case of error. */
int HopByHopHeader::print(FILE *output, int detail) const {
fprintf(output, "HopByHop[%d,%d]", this->h.nh, this->h.len);
// TODO: @todo : Implement this
if(this->next!=NULL){
print_separator(output, detail);
next->print(output, detail);
}
return OP_SUCCESS;
} /* End of print() */
/******************************************************************************/
/* PROTOCOL-SPECIFIC METHODS */
/******************************************************************************/
/** Set Next Header field */
int HopByHopHeader::setNextHeader(u8 val){
this->h.nh = val;
return OP_SUCCESS;
} /* End of setNextHeader() */
/** Returns next header id */
u8 HopByHopHeader::getNextHeader(){
return this->h.nh;
} /* End of getNextHeader() */
/* Add TLV encoded option */
int HopByHopHeader::addOption(u8 type, u8 len, const u8 *data){
/* Make sure we don't screw up due to buffer length issues */
if(data==NULL)
return OP_FAILURE;
if ( (this->length+len+2) > HOPBYHOP_MAX_HEADER_LEN ) /* No space for more */
return OP_FAILURE;
/* Store the option */
curr_option[0]=type;
curr_option[1]=len;
memcpy(curr_option+2, data, len);
/* Update internal option offset and object's length */
curr_option+=(len+2);
this->length+=(len+2);
this->addPadding();
return OP_SUCCESS;
} /* End of addOption() */
/* If the current length of the extension header is not a multiple of 8 octets,
* this method adds the neccessary padding (either PadN or Pad1 options)*/
int HopByHopHeader::addPadding(){
u8 zeroes[8]={0,0,0,0,0,0,0,0};
int required_octets=8-(this->length%8);
/* Make sure we have enough space for the padding. */
if ( (this->length+required_octets) > HOPBYHOP_MAX_HEADER_LEN )
return OP_FAILURE;
/* Insert Pad1 or PadN to fill the necessary octets */
if(required_octets>0 && required_octets<8){
if(required_octets==1){
curr_option[0]=EXTOPT_PAD1;
curr_option++;
this->length++;
}else{
this->addOption(EXTOPT_PADN, required_octets-2, zeroes );
}
}
assert(this->length%8==0);
this->h.len=(this->length/8)-1;
return OP_SUCCESS;
} /* End of addPadding() */

153
libnetutil/HopByHopHeader.h Normal file
View File

@@ -0,0 +1,153 @@
/***************************************************************************
* HopByHopHeader.h -- The HopByHopHeader Class represents an IPv6 *
* Hop-by-Hop extension header. *
***********************IMPORTANT NMAP LICENSE TERMS************************
* *
* The Nmap Security Scanner is (C) 1996-2011 Insecure.Com LLC. Nmap is *
* also a registered trademark of Insecure.Com LLC. This program is free *
* software; you may redistribute and/or modify it under the terms of the *
* GNU General Public License as published by the Free Software *
* Foundation; Version 2 with the clarifications and exceptions described *
* below. This guarantees your right to use, modify, and redistribute *
* this software under certain conditions. If you wish to embed Nmap *
* technology into proprietary software, we sell alternative licenses *
* (contact sales@insecure.com). Dozens of software vendors already *
* license Nmap technology such as host discovery, port scanning, OS *
* detection, and version detection. *
* *
* Note that the GPL places important restrictions on "derived works", yet *
* it does not provide a detailed definition of that term. To avoid *
* misunderstandings, we consider an application to constitute a *
* "derivative work" for the purpose of this license if it does any of the *
* following: *
* o Integrates source code from Nmap *
* o Reads or includes Nmap copyrighted data files, such as *
* nmap-os-db or nmap-service-probes. *
* o Executes Nmap and parses the results (as opposed to typical shell or *
* execution-menu apps, which simply display raw Nmap output and so are *
* not derivative works.) *
* o Integrates/includes/aggregates Nmap into a proprietary executable *
* installer, such as those produced by InstallShield. *
* o Links to a library or executes a program that does any of the above *
* *
* The term "Nmap" should be taken to also include any portions or derived *
* works of Nmap. This list is not exclusive, but is meant to clarify our *
* interpretation of derived works with some common examples. Our *
* interpretation applies only to Nmap--we don't speak for other people's *
* GPL works. *
* *
* If you have any questions about the GPL licensing restrictions on using *
* Nmap in non-GPL works, we would be happy to help. As mentioned above, *
* we also offer alternative license to integrate Nmap into proprietary *
* applications and appliances. These contracts have been sold to dozens *
* of software vendors, and generally include a perpetual license as well *
* as providing for priority support and updates as well as helping to *
* fund the continued development of Nmap technology. Please email *
* sales@insecure.com for further information. *
* *
* As a special exception to the GPL terms, Insecure.Com LLC grants *
* permission to link the code of this program with any version of the *
* OpenSSL library which is distributed under a license identical to that *
* listed in the included docs/licenses/OpenSSL.txt file, and distribute *
* linked combinations including the two. You must obey the GNU GPL in all *
* respects for all of the code used other than OpenSSL. If you modify *
* this file, you may extend this exception to your version of the file, *
* but you are not obligated to do so. *
* *
* If you received these files with a written license agreement or *
* contract stating terms other than the terms above, then that *
* alternative license agreement takes precedence over these comments. *
* *
* Source is provided to this software because we believe users have a *
* right to know exactly what a program is going to do before they run it. *
* This also allows you to audit the software for security holes (none *
* have been found so far). *
* *
* Source code also allows you to port Nmap to new platforms, fix bugs, *
* and add new features. You are highly encouraged to send your changes *
* to nmap-dev@insecure.org for possible incorporation into the main *
* distribution. By sending these changes to Fyodor or one of the *
* Insecure.Org development mailing lists, it is assumed that you are *
* offering the Nmap Project (Insecure.Com LLC) the unlimited, *
* non-exclusive right to reuse, modify, and relicense the code. Nmap *
* will always be available Open Source, but this is important because the *
* inability to relicense code has caused devastating problems for other *
* Free Software projects (such as KDE and NASM). We also occasionally *
* relicense the code to third parties as discussed above. If you wish to *
* specify special license conditions of your contributions, just say so *
* when you send them. *
* *
* This program is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* General Public License v2.0 for more details at *
* http://www.gnu.org/licenses/gpl-2.0.html , or in the COPYING file *
* included with Nmap. *
* *
***************************************************************************/
/* This code was originally part of the Nping tool. */
#ifndef __HOP_BY_HOP_HEADER_H__
#define __HOP_BY_HOP_HEADER_H__ 1
#include "IPv6ExtensionHeader.h"
#define HOP_BY_HOP_MAX_OPTIONS_LEN 256*8
#define HOPBYHOP_MIN_HEADER_LEN 8
#define HOPBYHOP_MAX_HEADER_LEN (HOPBYHOP_MIN_HEADER_LEN + HOP_BY_HOP_MAX_OPTIONS_LEN)
#define HOPBYHOP_MAX_OPTION_LEN 256
class HopByHopHeader : public IPv6ExtensionHeader {
protected:
/* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Next Header | Hdr Ext Len | |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +
| |
. .
. Options .
. .
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */
struct nping_ipv6_ext_hopbyhop_hdr{
u8 nh;
u8 len;
u8 options[HOP_BY_HOP_MAX_OPTIONS_LEN];
}__attribute__((__packed__));
typedef struct nping_ipv6_ext_hopbyhop_hdr nping_ipv6_ext_hopbyhop_hdr_t;
/* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+- - - - - - - - -
| Option Type | Opt Data Len | Option Data
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+- - - - - - - - - */
struct nping_ipv6_ext_hopbyhop_opt{
u8 type;
u8 len;
u8 data[HOPBYHOP_MAX_OPTION_LEN];
}__attribute__((__packed__));
typedef struct nping_ipv6_ext_hopbyhop_opt nping_ipv6_ext_hopbyhop_opt_t;
nping_ipv6_ext_hopbyhop_hdr_t h;
u8 *curr_option;
public:
HopByHopHeader();
~HopByHopHeader();
void reset();
u8 *getBufferPointer();
int storeRecvData(const u8 *buf, size_t len);
int protocol_id() const;
int validate();
int print(FILE *output, int detail) const;
/* Protocol specific methods */
int setNextHeader(u8 val);
u8 getNextHeader();
int addOption(u8 type, u8 len, const u8 *data);
int addPadding();
}; /* End of class HopByHopHeader */
#endif

114
libnetutil/ICMPHeader.h Normal file
View File

@@ -0,0 +1,114 @@
/***************************************************************************
* ICMPHeader.h -- Class ICMPHeader is a generic class for the ICMP *
* protocol. Its aim is to provide a little bit of abstraction from the *
* underlying ICMP version. Classes like ICMPv4Header or ICMPv6Header *
* inherit from it. *
* *
***********************IMPORTANT NMAP LICENSE TERMS************************
* *
* The Nmap Security Scanner is (C) 1996-2010 Insecure.Com LLC. Nmap is *
* also a registered trademark of Insecure.Com LLC. This program is free *
* software; you may redistribute and/or modify it under the terms of the *
* GNU General Public License as published by the Free Software *
* Foundation; Version 2 with the clarifications and exceptions described *
* below. This guarantees your right to use, modify, and redistribute *
* this software under certain conditions. If you wish to embed Nmap *
* technology into proprietary software, we sell alternative licenses *
* (contact sales@insecure.com). Dozens of software vendors already *
* license Nmap technology such as host discovery, port scanning, OS *
* detection, and version detection. *
* *
* Note that the GPL places important restrictions on "derived works", yet *
* it does not provide a detailed definition of that term. To avoid *
* misunderstandings, we consider an application to constitute a *
* "derivative work" for the purpose of this license if it does any of the *
* following: *
* o Integrates source code from Nmap *
* o Reads or includes Nmap copyrighted data files, such as *
* nmap-os-db or nmap-service-probes. *
* o Executes Nmap and parses the results (as opposed to typical shell or *
* execution-menu apps, which simply display raw Nmap output and so are *
* not derivative works.) *
* o Integrates/includes/aggregates Nmap into a proprietary executable *
* installer, such as those produced by InstallShield. *
* o Links to a library or executes a program that does any of the above *
* *
* The term "Nmap" should be taken to also include any portions or derived *
* works of Nmap. This list is not exclusive, but is meant to clarify our *
* interpretation of derived works with some common examples. Our *
* interpretation applies only to Nmap--we don't speak for other people's *
* GPL works. *
* *
* If you have any questions about the GPL licensing restrictions on using *
* Nmap in non-GPL works, we would be happy to help. As mentioned above, *
* we also offer alternative license to integrate Nmap into proprietary *
* applications and appliances. These contracts have been sold to dozens *
* of software vendors, and generally include a perpetual license as well *
* as providing for priority support and updates as well as helping to *
* fund the continued development of Nmap technology. Please email *
* sales@insecure.com for further information. *
* *
* As a special exception to the GPL terms, Insecure.Com LLC grants *
* permission to link the code of this program with any version of the *
* OpenSSL library which is distributed under a license identical to that *
* listed in the included docs/licenses/OpenSSL.txt file, and distribute *
* linked combinations including the two. You must obey the GNU GPL in all *
* respects for all of the code used other than OpenSSL. If you modify *
* this file, you may extend this exception to your version of the file, *
* but you are not obligated to do so. *
* *
* If you received these files with a written license agreement or *
* contract stating terms other than the terms above, then that *
* alternative license agreement takes precedence over these comments. *
* *
* Source is provided to this software because we believe users have a *
* right to know exactly what a program is going to do before they run it. *
* This also allows you to audit the software for security holes (none *
* have been found so far). *
* *
* Source code also allows you to port Nmap to new platforms, fix bugs, *
* and add new features. You are highly encouraged to send your changes *
* to nmap-dev@insecure.org for possible incorporation into the main *
* distribution. By sending these changes to Fyodor or one of the *
* Insecure.Org development mailing lists, it is assumed that you are *
* offering the Nmap Project (Insecure.Com LLC) the unlimited, *
* non-exclusive right to reuse, modify, and relicense the code. Nmap *
* will always be available Open Source, but this is important because the *
* inability to relicense code has caused devastating problems for other *
* Free Software projects (such as KDE and NASM). We also occasionally *
* relicense the code to third parties as discussed above. If you wish to *
* specify special license conditions of your contributions, just say so *
* when you send them. *
* *
* This program is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* General Public License v2.0 for more details at *
* http://www.gnu.org/licenses/gpl-2.0.html , or in the COPYING file *
* included with Nmap. *
* *
***************************************************************************/
/* This code was originally part of the Nping tool. */
#ifndef __ICMPHEADER_H__
#define __ICMPHEADER_H__ 1
#include "PacketElement.h"
class ICMPHeader : public PacketElement {
public:
virtual u8 getType() const = 0;
virtual int setType(u8 val) = 0;
virtual u8 getCode() const = 0;
virtual int setCode(u8 val) = 0;
virtual bool isError() const = 0;
};
#endif /* __ICMPHEADER_H__ */

1209
libnetutil/ICMPv4Header.cc Executable file

File diff suppressed because it is too large Load Diff

561
libnetutil/ICMPv4Header.h Executable file
View File

@@ -0,0 +1,561 @@
/***************************************************************************
* ICMPv4Header.h -- The ICMPv4Header Class represents an ICMP version 4 *
* packet. It contains methods to set any header field. In general, these *
* methods do error checkings and byte order conversion. *
* *
***********************IMPORTANT NMAP LICENSE TERMS************************
* *
* The Nmap Security Scanner is (C) 1996-2011 Insecure.Com LLC. Nmap is *
* also a registered trademark of Insecure.Com LLC. This program is free *
* software; you may redistribute and/or modify it under the terms of the *
* GNU General Public License as published by the Free Software *
* Foundation; Version 2 with the clarifications and exceptions described *
* below. This guarantees your right to use, modify, and redistribute *
* this software under certain conditions. If you wish to embed Nmap *
* technology into proprietary software, we sell alternative licenses *
* (contact sales@insecure.com). Dozens of software vendors already *
* license Nmap technology such as host discovery, port scanning, OS *
* detection, and version detection. *
* *
* Note that the GPL places important restrictions on "derived works", yet *
* it does not provide a detailed definition of that term. To avoid *
* misunderstandings, we consider an application to constitute a *
* "derivative work" for the purpose of this license if it does any of the *
* following: *
* o Integrates source code from Nmap *
* o Reads or includes Nmap copyrighted data files, such as *
* nmap-os-db or nmap-service-probes. *
* o Executes Nmap and parses the results (as opposed to typical shell or *
* execution-menu apps, which simply display raw Nmap output and so are *
* not derivative works.) *
* o Integrates/includes/aggregates Nmap into a proprietary executable *
* installer, such as those produced by InstallShield. *
* o Links to a library or executes a program that does any of the above *
* *
* The term "Nmap" should be taken to also include any portions or derived *
* works of Nmap. This list is not exclusive, but is meant to clarify our *
* interpretation of derived works with some common examples. Our *
* interpretation applies only to Nmap--we don't speak for other people's *
* GPL works. *
* *
* If you have any questions about the GPL licensing restrictions on using *
* Nmap in non-GPL works, we would be happy to help. As mentioned above, *
* we also offer alternative license to integrate Nmap into proprietary *
* applications and appliances. These contracts have been sold to dozens *
* of software vendors, and generally include a perpetual license as well *
* as providing for priority support and updates as well as helping to *
* fund the continued development of Nmap technology. Please email *
* sales@insecure.com for further information. *
* *
* As a special exception to the GPL terms, Insecure.Com LLC grants *
* permission to link the code of this program with any version of the *
* OpenSSL library which is distributed under a license identical to that *
* listed in the included docs/licenses/OpenSSL.txt file, and distribute *
* linked combinations including the two. You must obey the GNU GPL in all *
* respects for all of the code used other than OpenSSL. If you modify *
* this file, you may extend this exception to your version of the file, *
* but you are not obligated to do so. *
* *
* If you received these files with a written license agreement or *
* contract stating terms other than the terms above, then that *
* alternative license agreement takes precedence over these comments. *
* *
* Source is provided to this software because we believe users have a *
* right to know exactly what a program is going to do before they run it. *
* This also allows you to audit the software for security holes (none *
* have been found so far). *
* *
* Source code also allows you to port Nmap to new platforms, fix bugs, *
* and add new features. You are highly encouraged to send your changes *
* to nmap-dev@insecure.org for possible incorporation into the main *
* distribution. By sending these changes to Fyodor or one of the *
* Insecure.Org development mailing lists, it is assumed that you are *
* offering the Nmap Project (Insecure.Com LLC) the unlimited, *
* non-exclusive right to reuse, modify, and relicense the code. Nmap *
* will always be available Open Source, but this is important because the *
* inability to relicense code has caused devastating problems for other *
* Free Software projects (such as KDE and NASM). We also occasionally *
* relicense the code to third parties as discussed above. If you wish to *
* specify special license conditions of your contributions, just say so *
* when you send them. *
* *
* This program is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* General Public License v2.0 for more details at *
* http://www.gnu.org/licenses/gpl-2.0.html , or in the COPYING file *
* included with Nmap. *
* *
***************************************************************************/
/* This code was originally part of the Nping tool. */
#ifndef ICMPv4HEADER_H
#define ICMPv4HEADER_H 1
#include "ICMPHeader.h"
/* ICMP types and codes. These defines were originally taken from Slirp 1.0
* source file ip_icmp.h http://slirp.sourceforge.net/ (BSD licensed) and
* then, partially modified for Nping */
#define ICMP_ECHOREPLY 0 /* Echo reply */
#define ICMP_UNREACH 3 /* Destination unreachable: */
#define ICMP_UNREACH_NET 0 /* --> Bad network */
#define ICMP_UNREACH_HOST 1 /* --> Bad host */
#define ICMP_UNREACH_PROTOCOL 2 /* --> Bad protocol */
#define ICMP_UNREACH_PORT 3 /* --> Bad port */
#define ICMP_UNREACH_NEEDFRAG 4 /* --> DF flag caused pkt drop */
#define ICMP_UNREACH_SRCFAIL 5 /* --> Source route failed */
#define ICMP_UNREACH_NET_UNKNOWN 6 /* --> Unknown network */
#define ICMP_UNREACH_HOST_UNKNOWN 7 /* --> Unknown host */
#define ICMP_UNREACH_ISOLATED 8 /* --> Source host isolated */
#define ICMP_UNREACH_NET_PROHIB 9 /* --> Prohibited access */
#define ICMP_UNREACH_HOST_PROHIB 10 /* --> Prohibited access */
#define ICMP_UNREACH_TOSNET 11 /* --> Bad TOS for network */
#define ICMP_UNREACH_TOSHOST 12 /* --> Bad TOS for host */
#define ICMP_UNREACH_COMM_PROHIB 13 /* --> Prohibited communication */
#define ICMP_UNREACH_HOSTPRECEDENCE 14 /* --> Host precedence violation */
#define ICMP_UNREACH_PRECCUTOFF 15 /* --> Precedence cutoff */
#define ICMP_SOURCEQUENCH 4 /* Source Quench. */
#define ICMP_REDIRECT 5 /* Redirect: */
#define ICMP_REDIRECT_NET 0 /* --> For the network */
#define ICMP_REDIRECT_HOST 1 /* --> For the host */
#define ICMP_REDIRECT_TOSNET 2 /* --> For the TOS and network */
#define ICMP_REDIRECT_TOSHOST 3 /* --> For the TOS and host */
#define ICMP_ECHO 8 /* Echo request */
#define ICMP_ROUTERADVERT 9 /* Router advertisement */
#define ICMP_ROUTERADVERT_MOBILE 16 /* Used by mobile IP agents */
#define ICMP_ROUTERSOLICIT 10 /* Router solicitation */
#define ICMP_TIMXCEED 11 /* Time exceeded: */
#define ICMP_TIMXCEED_INTRANS 0 /* --> TTL==0 in transit */
#define ICMP_TIMXCEED_REASS 1 /* --> TTL==0 in reassembly */
#define ICMP_PARAMPROB 12 /* Parameter problem */
#define ICMM_PARAMPROB_POINTER 0 /* --> Pointer shows the problem */
#define ICMP_PARAMPROB_OPTABSENT 1 /* --> Option missing */
#define ICMP_PARAMPROB_BADLEN 2 /* --> Bad datagram length */
#define ICMP_TSTAMP 13 /* Timestamp request */
#define ICMP_TSTAMPREPLY 14 /* Timestamp reply */
#define ICMP_INFO 15 /* Information request */
#define ICMP_INFOREPLY 16 /* Information reply */
#define ICMP_MASK 17 /* Address mask request */
#define ICMP_MASKREPLY 18 /* Address mask reply */
#define ICMP_TRACEROUTE 30 /* Traceroute */
#define ICMP_TRACEROUTE_SUCCESS 0 /* --> Dgram sent to next router */
#define ICMP_TRACEROUTE_DROPPED 1 /* --> Dgram was dropped */
#define ICMP_DOMAINNAME 37 /* Domain name request */
#define ICMP_DOMAINNAMEREPLY 38 /* Domain name reply */
#define ICMP_SECURITYFAILURES 40 /* Security failures */
#define ICMP_STD_HEADER_LEN 8
#define ICMP_MAX_PAYLOAD_LEN 1500
#define MAX_ROUTER_ADVERT_ENTRIES (((ICMP_MAX_PAYLOAD_LEN-4)/8)-1)
class ICMPv4Header : public ICMPHeader {
private:
/**********************************************************************/
/* COMMON ICMPv4 packet HEADER */
/**********************************************************************/
/* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Type | Code | Checksum |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+ Message Body +
| | */
struct nping_icmpv4_hdr {
u8 type; /* ICMP Message Type */
u8 code; /* ICMP Message Code */
u16 checksum; /* Checksum */
u8 data[ICMP_MAX_PAYLOAD_LEN];
}__attribute__((__packed__));
typedef struct nping_icmpv4_hdr nping_icmpv4_hdr_t;
/**********************************************************************/
/* ICMPv4 MESSAGE SPECIFIC HEADERS */
/**********************************************************************/
/* Destination Unreachable Message
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Type | Code | Checksum |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| unused |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Internet Header + 64 bits of Original Data Datagram |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */
struct icmp4_dest_unreach_msg{
u32 unused;
//u8 original_dgram[?];
}__attribute__((__packed__));
typedef struct icmp4_dest_unreach_msg icmp4_dest_unreach_msg_t;
/* Time Exceeded Message
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Type | Code | Checksum |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| unused |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Internet Header + 64 bits of Original Data Datagram |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */
struct icmp4_time_exceeded_msg{
u32 unused;
//u8 original_dgram[?];
}__attribute__((__packed__));
typedef struct icmp4_time_exceeded_msg icmp4_time_exceeded_msg_t;
/* Parameter Problem Message
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Type | Code | Checksum |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Pointer | unused |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Internet Header + 64 bits of Original Data Datagram |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */
struct icmp4_parameter_problem_msg{
u8 pointer;
u8 unused[3];
//u8 original_dgram[?];
}__attribute__((__packed__));
typedef struct icmp4_parameter_problem_msg icmp4_parameter_problem_msg_t;
/* Source Quench Message
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Type | Code | Checksum |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| unused |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Internet Header + 64 bits of Original Data Datagram |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */
struct icmp4_source_quench_msg{
u32 unused;
//u8 original_dgram[?];
}__attribute__((__packed__));
typedef struct icmp4_source_quench_msg icmp4_source_quench_msg_t;
/* Redirect Message
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Type | Code | Checksum |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Gateway Internet Address |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Internet Header + 64 bits of Original Data Datagram |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */
struct icmp4_redirect_msg{
struct in_addr gateway_address;
//u8 original_dgram[?];
}__attribute__((__packed__));
typedef struct icmp4_redirect_msg icmp4_redirect_msg_t;
/* Echo Request/Reply Message
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Type | Code | Checksum |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Identifier | Sequence Number |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Data ...
+-+-+-+-+- */
struct icmp4_echo_msg{
u16 identifier;
u16 sequence;
//u8 data[?];
}__attribute__((__packed__));
typedef struct icmp4_echo_msg icmp4_echo_msg_t;
/* Timestamp Request/Reply Message
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Type | Code | Checksum |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Identifier | Sequence Number |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Originate Timestamp |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Receive Timestamp |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Transmit Timestamp |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */
struct icmp4_timestamp_msg{
u16 identifier;
u16 sequence;
u32 originate_ts;
u32 receive_ts;
u32 transmit_ts;
}__attribute__((__packed__));
typedef struct icmp4_timestamp_msg icmp4_timestamp_msg_t;
/* Information Request/Reply Message
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Type | Code | Checksum |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Identifier | Sequence Number |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */
struct icmp4_information_msg{
u16 identifier;
u16 sequence;
}__attribute__((__packed__));
typedef struct icmp4_information_msg icmp4_information_msg_t;
/* ICMP Router Advertisement Message
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Type | Code | Checksum |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Num Addrs |Addr Entry Size| Lifetime |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Router Address[1] |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Preference Level[1] |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Router Address[2] |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Preference Level[2] |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| . |
| . |
| . | */
struct icmp4_router_advert_entry{
struct in_addr router_addr;
u32 preference_level;
}__attribute__((__packed__));
typedef struct icmp4_router_advert_entry icmp4_router_advert_entry_t;
struct icmp4_router_advert_msg{
u8 num_addrs;
u8 addr_entry_size;
u16 lifetime;
icmp4_router_advert_entry_t adverts[MAX_ROUTER_ADVERT_ENTRIES];
}__attribute__((__packed__));
typedef struct icmp4_router_advert_msg icmp4_router_advert_msg_t;
/* ICMP Router Solicitation Message
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Type | Code | Checksum |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Reserved |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */
struct icmp4_router_solicit_msg{
u32 reserved;
}__attribute__((__packed__));
typedef struct icmp4_router_solicit_msg icmp4_router_solicit_msg_t;
/* ICMP Security Failures Message
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Type | Code | Checksum |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Reserved | Pointer |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
~ Original Internet Headers + 64 bits of Payload ~
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */
struct icmp4_security_failures_msg{
u16 reserved;
u16 pointer;
//u8 original_headers[?];
}__attribute__((__packed__));
typedef struct icmp4_security_failures_msg icmp4_security_failures_msg_t;
/* ICMP Address Mask Request/Reply Message
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Type | Code | Checksum |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Identifier | Sequence Number |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Address Mask |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */
struct icmp4_address_mask_msg{
u16 identifier;
u16 sequence;
struct in_addr address_mask;
}__attribute__((__packed__));
typedef struct icmp4_address_mask_msg icmp4_address_mask_msg_t;
/* ICMP Traceroute Message
+---------------+---------------+---------------+---------------+
| Type | Code | Checksum |
+---------------+---------------+---------------+---------------+
| ID Number | unused |
+---------------+---------------+---------------+---------------+
| Outbound Hop Count | Return Hop Count |
+---------------+---------------+---------------+---------------+
| Output Link Speed |
+---------------+---------------+---------------+---------------+
| Output Link MTU |
+---------------+---------------+---------------+---------------+ */
struct icmp4_traceroute_msg{
u16 id_number;
u16 unused;
u16 outbound_hop_count;
u16 return_hop_count;
u32 output_link_speed;
u32 output_link_mtu;
}__attribute__((__packed__));
typedef struct icmp4_traceroute_msg icmp4_traceroute_msg_t;
/* ICMP Domain Name Request Message
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Type | Code | Checksum |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Identifier | Sequence Number |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */
struct icmp4_domain_name_request_msg{
u16 identifier;
u16 sequence;
}__attribute__((__packed__));
typedef struct icmp4_domain_name_request_msg icmp4_domain_name_request_msg_t;
/* ICMP Domain Name Reply Message
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Type | Code | Checksum |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Identifier | Sequence Number |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Time-To-Live |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Names ...
+-+-+-+-+-+-+-+- */
struct icmp4_domain_name_reply_msg{
u16 identifier;
u16 sequence;
s16 ttl; /* Signed! */
u8 names[ICMP_MAX_PAYLOAD_LEN-8];
}__attribute__((__packed__));
typedef struct icmp4_domain_name_reply_msg icmp4_domain_name_reply_msg_t;
/* Main data structure */
nping_icmpv4_hdr_t h;
/* Helper pointers */
icmp4_dest_unreach_msg_t *h_du;
icmp4_time_exceeded_msg_t *h_te;
icmp4_parameter_problem_msg_t *h_pp;
icmp4_source_quench_msg_t *h_sq;
icmp4_redirect_msg_t *h_r;
icmp4_echo_msg_t *h_e;
icmp4_timestamp_msg_t *h_t;
icmp4_information_msg_t *h_i;
icmp4_router_advert_msg_t *h_ra;
icmp4_router_solicit_msg_t *h_rs;
icmp4_security_failures_msg_t *h_sf;
icmp4_address_mask_msg_t *h_am;
icmp4_traceroute_msg_t *h_trc;
icmp4_domain_name_request_msg_t *h_dn;
icmp4_domain_name_reply_msg_t *h_dnr;
/* Internal counts */
int routeradventries;
int domainnameentries;
public:
/* PacketElement:: Mandatory methods */
ICMPv4Header();
~ICMPv4Header();
void reset();
u8 *getBufferPointer();
int storeRecvData(const u8 *buf, size_t len);
int protocol_id() const;
int validate();
int print(FILE *output, int detail) const;
/* ICMP Type */
int setType(u8 val);
u8 getType() const;
bool validateType();
bool validateType(u8 val);
/* ICMP Code */
int setCode(u8 c);
u8 getCode() const;
bool validateCode();
bool validateCode(u8 type, u8 code);
/* Checksum */
int setSum();
int setSum(u16 s);
u16 getSum() const;
/* Unused and reserved fields */
int setUnused(u32 val);
u32 getUnused() const;
int setReserved( u32 val );
u32 getReserved() const;
/* Redirect */
int setGatewayAddress(struct in_addr ipaddr);
struct in_addr getGatewayAddress() const;
/* Parameter problem */
int setParameterPointer(u8 val);
u8 getParameterPointer() const;
/* Router advertisement */
int setNumAddresses(u8 val);
u8 getNumAddresses() const;
int setAddrEntrySize(u8 val);
u8 getAddrEntrySize() const;
int setLifetime(u16 val);
u16 getLifetime() const;
int addRouterAdvEntry(struct in_addr raddr, u32 pref);
u8 *getRouterAdvEntries(int *num) const;
int clearRouterAdvEntries();
/* Echo/Timestamp/Mask */
int setIdentifier(u16 val);
u16 getIdentifier() const;
int setSequence(u16 val);
u16 getSequence() const;
/* Timestamp only */
int setOriginateTimestamp(u32 t);
u32 getOriginateTimestamp() const;
int setReceiveTimestamp(u32 t);
u32 getReceiveTimestamp() const;
int setTransmitTimestamp(u32 t);
u32 getTransmitTimestamp() const;
/* Mask only */
int setAddressMask(struct in_addr mask);
struct in_addr getAddressMask() const;
/* Security Failures */
int setSecurityPointer(u16 val);
u16 getSecurityPointer() const;
/* Traceroute */
int setIDNumber(u16 val);
u16 getIDNumber() const;
int setOutboundHopCount(u16 val);
u16 getOutboundHopCount() const;
int setReturnHopCount(u16 val);
u16 getReturnHopCount() const;
int setOutputLinkSpeed(u32 val);
u32 getOutputLinkSpeed() const;
int setOutputLinkMTU(u32 val);
u32 getOutputLinkMTU() const;
/* Misc */
int getICMPHeaderLengthFromType( u8 type ) const;
const char *type2string(int type, int code) const;
bool isError() const;
}; /* End of class ICMPv4Header */
#endif

1158
libnetutil/ICMPv6Header.cc Executable file

File diff suppressed because it is too large Load Diff

690
libnetutil/ICMPv6Header.h Executable file
View File

@@ -0,0 +1,690 @@
/***************************************************************************
* ICMPv6Header.h -- The ICMPv6Header Class represents an ICMP version 6 *
* packet. It contains methods to set any header field. In general, these *
* methods do error checkings and byte order conversion. *
* *
***********************IMPORTANT NMAP LICENSE TERMS************************
* *
* The Nmap Security Scanner is (C) 1996-2011 Insecure.Com LLC. Nmap is *
* also a registered trademark of Insecure.Com LLC. This program is free *
* software; you may redistribute and/or modify it under the terms of the *
* GNU General Public License as published by the Free Software *
* Foundation; Version 2 with the clarifications and exceptions described *
* below. This guarantees your right to use, modify, and redistribute *
* this software under certain conditions. If you wish to embed Nmap *
* technology into proprietary software, we sell alternative licenses *
* (contact sales@insecure.com). Dozens of software vendors already *
* license Nmap technology such as host discovery, port scanning, OS *
* detection, and version detection. *
* *
* Note that the GPL places important restrictions on "derived works", yet *
* it does not provide a detailed definition of that term. To avoid *
* misunderstandings, we consider an application to constitute a *
* "derivative work" for the purpose of this license if it does any of the *
* following: *
* o Integrates source code from Nmap *
* o Reads or includes Nmap copyrighted data files, such as *
* nmap-os-db or nmap-service-probes. *
* o Executes Nmap and parses the results (as opposed to typical shell or *
* execution-menu apps, which simply display raw Nmap output and so are *
* not derivative works.) *
* o Integrates/includes/aggregates Nmap into a proprietary executable *
* installer, such as those produced by InstallShield. *
* o Links to a library or executes a program that does any of the above *
* *
* The term "Nmap" should be taken to also include any portions or derived *
* works of Nmap. This list is not exclusive, but is meant to clarify our *
* interpretation of derived works with some common examples. Our *
* interpretation applies only to Nmap--we don't speak for other people's *
* GPL works. *
* *
* If you have any questions about the GPL licensing restrictions on using *
* Nmap in non-GPL works, we would be happy to help. As mentioned above, *
* we also offer alternative license to integrate Nmap into proprietary *
* applications and appliances. These contracts have been sold to dozens *
* of software vendors, and generally include a perpetual license as well *
* as providing for priority support and updates as well as helping to *
* fund the continued development of Nmap technology. Please email *
* sales@insecure.com for further information. *
* *
* As a special exception to the GPL terms, Insecure.Com LLC grants *
* permission to link the code of this program with any version of the *
* OpenSSL library which is distributed under a license identical to that *
* listed in the included docs/licenses/OpenSSL.txt file, and distribute *
* linked combinations including the two. You must obey the GNU GPL in all *
* respects for all of the code used other than OpenSSL. If you modify *
* this file, you may extend this exception to your version of the file, *
* but you are not obligated to do so. *
* *
* If you received these files with a written license agreement or *
* contract stating terms other than the terms above, then that *
* alternative license agreement takes precedence over these comments. *
* *
* Source is provided to this software because we believe users have a *
* right to know exactly what a program is going to do before they run it. *
* This also allows you to audit the software for security holes (none *
* have been found so far). *
* *
* Source code also allows you to port Nmap to new platforms, fix bugs, *
* and add new features. You are highly encouraged to send your changes *
* to nmap-dev@insecure.org for possible incorporation into the main *
* distribution. By sending these changes to Fyodor or one of the *
* Insecure.Org development mailing lists, it is assumed that you are *
* offering the Nmap Project (Insecure.Com LLC) the unlimited, *
* non-exclusive right to reuse, modify, and relicense the code. Nmap *
* will always be available Open Source, but this is important because the *
* inability to relicense code has caused devastating problems for other *
* Free Software projects (such as KDE and NASM). We also occasionally *
* relicense the code to third parties as discussed above. If you wish to *
* specify special license conditions of your contributions, just say so *
* when you send them. *
* *
* This program is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* General Public License v2.0 for more details at *
* http://www.gnu.org/licenses/gpl-2.0.html , or in the COPYING file *
* included with Nmap. *
* *
***************************************************************************/
/* This code was originally part of the Nping tool. */
#ifndef ICMPv6HEADER_H
#define ICMPv6HEADER_H 1
#include "ICMPHeader.h"
/******************************************************************************/
/* IMPORTANT INFORMATION ON HOW TO USE THIS CLASS. */
/******************************************************************************/
/* This class represents an ICMPv6 messages. ICMPv6 messages may be of
* different types. Each type has its own header and possibly a variable
* length data field. Information messages have an "invoking packet" field
* which is the IP packet that triggered the emission of the ICMPv6 message.
* Other messages may contain a "data" field, like echo requests an replies.
* Some others may contain ICMPv6 Options.
*
* So the thing is, that this class only represents fixed-length ICMPv6
* headers and does NOT offer storage for ANY variable-length field. This
* fields may be added to the ICMPv6 header using instances of the RawData
* class the ICMPv6Option class or even the IPv6Header class (in those cases
* where a whole packet is appendend to the ICMPv6 message).
*
* So, how does this work? Let's look at some examples.
*
* 1. Imagine we need to build an ICMP echo request message that includes some
* arbitrary data to be echoed. We could do the following:
*
* u8 final_packet[1024]; <-- Buffer to store the resulting packet
* u32 final_packet_len=0; <-- Length of the resulting packet
* ICMPv6Header header; <-- The ICMPv6 fixed-length part
* RawData data; <-- The data to append to the echo message
*
* header.setType(ICMPv6_ECHO); <-- Set ICMPv6 type to "Echo request"
* data.store("1234567890"); <-- Store data we need to send.
* header.setNextElement(&data); <-- Tell ICMPv6Header what's after it
* header.setSum(); <-- Compute the checksum
*
* final_packet_len=header.dumpToBinaryBuffer(fina_packet, 1024);
* send_packet(final_packet, final_packet_len)
*
* 2. If we are sending a parameter problem message and we need to include the
* invoking datagram, we can call setNextElement() passing an IPv6Header
* pointer.
*
* u8 final_packet[1024]; <-- Buffer to store the resulting packet
* u32 final_packet_len=0; <-- Length of the resulting packet
* ICMPv6Header header; <-- The ICMPv6 fixed-length part
* IPv6Header ipv6; <-- The IPv6 packet that triggered ICMPv6
*
* header.setType(ICMPv6_PARAMPROB); <-- Set ICMPv6 type to "Param Problem"
* header.setNextElement(&ipv6); <-- Tell ICMPv6Header what's after it
* header.setSum(); <-- Compute the checksum
*
* Note that here we don't show how the ipv6 object is set.
*
* 3. If we are sending a router solicitation message, we'll call
* setNextElement() passing an IPv6Options Pointer.
*
* u8 final_packet[1024]; <-- Buffer to store the resulting packet
* u32 final_packet_len=0; <-- Length of the resulting packet
* ICMPv6Header header; <-- The ICMPv6 fixed-length part
* IPv6Options opts1; <-- IPv6 options
* IPv6Options opts2; <-- IPv6 options
* IPv6Options opts3; <-- IPv6 options
*
* header.setType(ICMPv6_ROUTERSOLICIT); <-- Set ICMPv6 type
*
* opts1.setXXXX(); <-- Set up the options
* .
* .
* .
* opts3.setYYYY();
*
* opts2.setNextElement(&opts3); <-- Link the options
* opts1.setNextElement(&opts2);
* header.setNextElement(&opts1);
* header.setNextElement(&ipv6); <-- Link the first option to the ICMPv6
* header.setSum(); <-- Compute the checksum
*
* And so on...
*
*/
/* Packet header diagrams included in this file have been taken from the
* following IETF RFC documents: RFC 4443, RFC 2461, RFC 2894 */
/* ICMP types and codes.
* The following types and codes have been defined by IANA. A complete list
* may be found at http://www.iana.org/assignments/icmpv6-parameters
*
* Definitions on the first level of indentation are ICMPv6 Types.
* Definitions on the second level of indentation (values enclosed in
* parenthesis) are ICMPv6 Codes */
#define ICMPv6_UNREACH 1 /* Destination unreachable [RFC 2463, 4443] */
#define ICMPv6_UNREACH_NO_ROUTE (0) /* --> No route to destination */
#define ICMPv6_UNREACH_PROHIBITED (1) /* --> Communication administratively prohibited */
#define ICMPv6_UNREACH_BEYOND_SCOPE (2) /* --> Beyond scope of source address [RFC4443] */
#define ICMPv6_UNREACH_ADDR_UNREACH (3) /* --> Address unreachable */
#define ICMPv6_UNREACH_PORT_UNREACH (4) /* --> Port unreachable */
#define ICMPv6_UNREACH_SRC_ADDR_FAILED (5) /* --> Source address failed ingress/egress policy [RFC4443] */
#define ICMPv6_UNREACH_REJECT_ROUTE (6) /* --> Reject route to destination [RFC4443] */
#define ICMPv6_PKTTOOBIG 2 /* Packet too big [RFC 2463, 4443] */
#define ICMPv6_TIMXCEED 3 /* Time exceeded [RFC 2463, 4443] */
#define ICMPv6_TIMXCEED_HOP_EXCEEDED (0) /* --> Hop limit exceeded in transit */
#define ICMPv6_TIMXCEED_REASS_EXCEEDED (1) /* --> Fragment reassembly time exceeded */
#define ICMPv6_PARAMPROB 4 /* Parameter problem [RFC 2463, 4443] */
#define ICMPv6_PARAMPROB_FIELD (0) /* --> Erroneous header field encountered */
#define ICMPv6_PARAMPROB_NEXT_HDR (1) /* --> Unrecognized Next Header type encountered */
#define ICMPv6_PARAMPROB_OPTION (2) /* --> Unrecognized IPv6 option encountered */
#define ICMPv6_ECHO 128 /* Echo request [RFC 2463, 4443] */
#define ICMPv6_ECHOREPLY 129 /* Echo reply [RFC 2463, 4443] */
#define ICMPv6_GRPMEMBQUERY 130 /* Group Membership Query [RFC 2710] */
#define ICMPv6_GRPMEMBREP 131 /* Group Membership Report [RFC 2710] */
#define ICMPv6_GRPMEMBRED 132 /* Group Membership Reduction [RFC 2710] */
#define ICMPv6_ROUTERSOLICIT 133 /* Router Solicitation [RFC 2461] */
#define ICMPv6_ROUTERADVERT 134 /* Router Advertisement [RFC 2461] */
#define ICMPv6_NGHBRSOLICIT 135 /* Neighbor Solicitation [RFC 2461] */
#define ICMPv6_NGHBRADVERT 136 /* Neighbor Advertisement [RFC 2461] */
#define ICMPv6_REDIRECT 137 /* Redirect [RFC 2461] */
#define ICMPv6_RTRRENUM 138 /* Router Renumbering [RFC 2894] */
#define ICMPv6_RTRRENUM_COMMAND (0) /* --> Router Renumbering Command */
#define ICMPv6_RTRRENUM_RESULT (1) /* --> Router Renumbering Result */
#define ICMPv6_RTRRENUM_SEQ_RESET (255) /* Sequence Number Reset */
#define ICMPv6_NODEINFOQUERY 139 /* ICMP Node Information Query [RFC 4620] */
#define ICMPv6_NODEINFOQUERY_IPv6ADDR (0) /* --> The Data field contains an IPv6 address */
#define ICMPv6_NODEINFOQUERY_NAME (1) /* --> The Data field contains a name */
#define ICMPv6_NODEINFOQUERY_IPv4ADDR (2) /* --> The Data field contains an IPv4 address */
#define ICMPv6_NODEINFORESP 140 /* ICMP Node Information Response [RFC 4620] */
#define ICMPv6_NODEINFORESP_SUCCESS (0) /* --> A successful reply. */
#define ICMPv6_NODEINFORESP_REFUSED (1) /* --> The Responder refuses to supply the answer */
#define ICMPv6_NODEINFORESP_UNKNOWN (2) /* --> The Qtype of the Query is unknown */
#define ICMPv6_INVNGHBRSOLICIT 141 /* Inverse Neighbor Discovery Solicitation Message [RFC 3122] */
#define ICMPv6_INVNGHBRADVERT 142 /* Inverse Neighbor Discovery Advertisement Message [RFC 3122] */
#define ICMPv6_MLDV2 143 /* MLDv2 Multicast Listener Report [RFC 3810] */
#define ICMPv6_AGENTDISCOVREQ 144 /* Home Agent Address Discovery Request Message [RFC 3775] */
#define ICMPv6_AGENTDISCOVREPLY 145 /* Home Agent Address Discovery Reply Message [RFC 3775] */
#define ICMPv6_MOBPREFIXSOLICIT 146 /* Mobile Prefix Solicitation [RFC 3775] */
#define ICMPv6_MOBPREFIXADVERT 147 /* Mobile Prefix Advertisement [RFC 3775] */
#define ICMPv6_CERTPATHSOLICIT 148 /* Certification Path Solicitation [RFC 3971] */
#define ICMPv6_CERTPATHADVERT 149 /* Certification Path Advertisement [RFC 3971] */
#define ICMPv6_EXPMOBILITY 150 /* Experimental mobility protocols [RFC 4065] */
#define ICMPv6_MRDADVERT 151 /* MRD, Multicast Router Advertisement [RFC 4286] */
#define ICMPv6_MRDSOLICIT 152 /* MRD, Multicast Router Solicitation [RFC 4286] */
#define ICMPv6_MRDTERMINATE 153 /* MRD, Multicast Router Termination [RFC 4286] */
#define ICMPv6_FMIPV6 154 /* FMIPv6 messages [RFC 5568] */
/* Node Information parameters */
/* -> Query types */
#define NI_QTYPE_NOOP 0
#define NI_QTYPE_UNUSED 1
#define NI_QTYPE_NODENAME 2
#define NI_QTYPE_NODEADDRS 3
#define NI_QTYPE_IPv4ADDRS 4
/* -> Misc */
#define NI_NONCE_LEN 8
/* Nping ICMPv6Header Class internal definitions */
#define ICMPv6_COMMON_HEADER_LEN 4
#define ICMPv6_MIN_HEADER_LEN 8
#define ICMPv6_UNREACH_LEN (ICMPv6_COMMON_HEADER_LEN+4)
#define ICMPv6_PKTTOOBIG_LEN (ICMPv6_COMMON_HEADER_LEN+4)
#define ICMPv6_TIMXCEED_LEN (ICMPv6_COMMON_HEADER_LEN+4)
#define ICMPv6_PARAMPROB_LEN (ICMPv6_COMMON_HEADER_LEN+4)
#define ICMPv6_ECHO_LEN (ICMPv6_COMMON_HEADER_LEN+4)
#define ICMPv6_ECHOREPLY_LEN (ICMPv6_COMMON_HEADER_LEN+4)
#define ICMPv6_ROUTERSOLICIT_LEN (ICMPv6_COMMON_HEADER_LEN+4)
#define ICMPv6_ROUTERADVERT_LEN (ICMPv6_COMMON_HEADER_LEN+12)
#define ICMPv6_NGHBRSOLICIT_LEN (ICMPv6_COMMON_HEADER_LEN+20)
#define ICMPv6_NGHBRADVERT_LEN (ICMPv6_COMMON_HEADER_LEN+20)
#define ICMPv6_REDIRECT_LEN (ICMPv6_COMMON_HEADER_LEN+36)
#define ICMPv6_RTRRENUM_LEN (ICMPv6_COMMON_HEADER_LEN+12)
#define ICMPv6_NODEINFO_LEN (ICMPv6_COMMON_HEADER_LEN+12)
#define ICMPv6_MLD_LEN (ICMPv6_COMMON_HEADER_LEN+20)
/* This must the MAX() of all values defined above*/
#define ICMPv6_MAX_MESSAGE_BODY (ICMPv6_REDIRECT_LEN-ICMPv6_COMMON_HEADER_LEN)
class ICMPv6Header : public ICMPHeader {
/**********************************************************************/
/* COMMON ICMPv6 packet HEADER */
/**********************************************************************/
/* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Type | Code | Checksum |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+ Message Body +
| | */
struct nping_icmpv6_hdr{
u8 type;
u8 code;
u16 checksum;
u8 data[ICMPv6_MAX_MESSAGE_BODY];
}__attribute__((__packed__));
typedef struct nping_icmpv6_hdr nping_icmpv6_hdr_t;
/**********************************************************************/
/* ICMPv6 MESSAGE SPECIFIC HEADERS */
/**********************************************************************/
/* Destination Unreachable Message
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Type | Code | Checksum |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Unused |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| As much of invoking packet |
+ as possible without the ICMPv6 packet +
| exceeding the minimum IPv6 MTU [IPv6] | */
struct dest_unreach_msg{
u32 unused;
//u8 invoking_pkt[?];
}__attribute__((__packed__));
typedef struct dest_unreach_msg dest_unreach_msg_t;
/* Packet Too Big Message
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Type | Code | Checksum |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| MTU |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| As much of invoking packet |
+ as possible without the ICMPv6 packet +
| exceeding the minimum IPv6 MTU [IPv6] | */
struct pkt_too_big_msg{
u32 mtu;
//u8 invoking_pkt[?];
}__attribute__((__packed__));
typedef struct pkt_too_big_msg pkt_too_big_msg_t;
/* Time Exceeded Message
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Type | Code | Checksum |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Unused |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| As much of invoking packet |
+ as possible without the ICMPv6 packet +
| exceeding the minimum IPv6 MTU [IPv6] | */
struct time_exceeded_msg{
u32 unused;
//u8 invoking_pkt[?];
}__attribute__((__packed__));
typedef struct time_exceeded_msg time_exceeded_msg_t;
/* Parameter Problem Message
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Type | Code | Checksum |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Pointer |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| As much of invoking packet |
+ as possible without the ICMPv6 packet +
| exceeding the minimum IPv6 MTU [IPv6] | */
struct parameter_problem_msg{
u32 pointer;
//u8 invoking_pkt[?];
}__attribute__((__packed__));
typedef struct parameter_problem_msg parameter_problem_msg_t;
/* Echo Request/Response Messages
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Type | Code | Checksum |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Identifier | Sequence Number |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Data ...
+-+-+-+-+- */
struct echo_msg{
u16 id;
u16 seq;
//u8 data[?];
}__attribute__((__packed__));
typedef struct echo_msg echo_msg_t;
/* Router Advertisement Message
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Type | Code | Checksum |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Cur Hop Limit |M|O|H|Prf|P|R|R| Router Lifetime |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Reachable Time |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Retrans Timer |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Options ...
+-+-+-+-+-+-+-+-+-+-+-+- */
struct router_advert_msg{
u8 current_hop_limit;
u8 autoconfig_flags; /* See RFC 5175 */
u16 router_lifetime;
u32 reachable_time;
u32 retransmission_timer;
//u8 icmpv6_options[?];
}__attribute__((__packed__));
typedef struct router_advert_msg router_advert_msg_t;
/* Router Solicitation Message
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Type | Code | Checksum |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Reserved |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Options ...
+-+-+-+-+-+-+-+-+-+-+-+- */
struct router_solicit_msg{
u32 reserved;
//u8 icmpv6_options[?];
}__attribute__((__packed__));
typedef struct router_solicit_msg router_solicit_msg_t;
/* Neighbor Advertisement Message
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Type | Code | Checksum |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|R|S|O| Reserved |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+ +
| |
+ Target Address +
| |
+ +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Options ...
+-+-+-+-+-+-+-+-+-+-+-+- */
struct neighbor_advert_msg{
u8 flags;
u8 reserved[3];
u8 target_address[16];
//u8 icmpv6_options[?];
}__attribute__((__packed__));
typedef struct neighbor_advert_msg neighbor_advert_msg_t;
/* Neighbor Solicitation Message
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Type | Code | Checksum |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Reserved |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+ +
| |
+ Target Address +
| |
+ +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Options ...
+-+-+-+-+-+-+-+-+-+-+-+- */
struct neighbor_solicit_msg{
u32 reserved;
u8 target_address[16];
//u8 icmpv6_options[?];
}__attribute__((__packed__));
typedef struct neighbor_solicit_msg neighbor_solicit_msg_t;
/* Redirect Message
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Type | Code | Checksum |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Reserved |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+ +
| |
+ Target Address +
| |
+ +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+ +
| |
+ Destination Address +
| |
+ +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Options ...
+-+-+-+-+-+-+-+-+-+-+-+- */
struct redirect_msg{
u32 reserved;
u8 target_address[16];
u8 destination_address[16];
//u8 icmpv6_options[?];
}__attribute__((__packed__));
typedef struct redirect_msg redirect_msg_t;
/* Router Renumbering Header
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Type | Code | Checksum |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| SequenceNumber |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| SegmentNumber | Flags | MaxDelay |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| reserved |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
/ RR Message Body /
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */
struct router_renumbering_msg{
u32 seq;
u8 segment_number;
u8 flags;
u16 max_delay;
u32 reserved;
//u8 rr_msg_body[?];
}__attribute__((__packed__));
typedef struct router_renumbering_msg router_renumbering_msg_t;
/* Node Information Queries
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Type | Code | Checksum |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Qtype | Flags |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+ Nonce +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
/ Data /
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */
struct nodeinfo_msg{
u16 qtype;
u16 flags;
u8 nonce[NI_NONCE_LEN];
//u8 data[?];
}__attribute__((__packed__));
typedef struct nodeinfo_msg nodeinfo_msg_t;
/* Multicast Listener Discovery
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Type | Code | Checksum |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Maximum Response Delay | Reserved |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+ +
| |
+ Multicast Address +
| |
+ +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */
struct mld_msg{
u16 max_response_delay;
u16 reserved;
u8 mcast_address[16];
}__attribute__((__packed__));
typedef struct mld_msg mld_msg_t;
nping_icmpv6_hdr_t h;
/* Helper pointers */
dest_unreach_msg_t *h_du;
pkt_too_big_msg_t *h_ptb;
time_exceeded_msg_t *h_te;
parameter_problem_msg_t *h_pp;
echo_msg_t *h_e;
router_advert_msg_t *h_ra;
router_solicit_msg_t *h_rs;
neighbor_advert_msg_t *h_na;
neighbor_solicit_msg_t *h_ns;
redirect_msg_t *h_r;
router_renumbering_msg_t *h_rr;
nodeinfo_msg_t *h_ni;
mld_msg_t *h_mld;
public:
ICMPv6Header();
~ICMPv6Header();
void reset();
u8 *getBufferPointer();
int storeRecvData(const u8 *buf, size_t len);
int protocol_id() const;
int validate();
int print(FILE *output, int detail) const;
/* ICMP Type */
int setType(u8 val);
u8 getType() const;
bool validateType();
bool validateType(u8 val);
/* Code */
int setCode(u8 c);
u8 getCode() const;
bool validateCode();
bool validateCode(u8 type, u8 code);
/* Checksum */
int setSum();
int setSum(u16 s);
int setSumRandom();
u16 getSum();
int setReserved(u32 val);
u32 getReserved();
int setUnused(u32 val);
u32 getUnused();
int setFlags(u8 val);
u8 getFlags();
int setMTU(u32 mtu);
u32 getMTU();
/* Parameter problem */
int setPointer(u32 val);
u32 getPointer();
/* Echo */
int setIdentifier(u16 val);
u16 getIdentifier();
int setSequence(u16 val);
int setSequence(u32 val);
u32 getSequence();
/* Router Advertisement */
int setCurrentHopLimit(u8 val);
u8 getCurrentHopLimit();
int setRouterLifetime(u16 val);
u16 getRouterLifetime();
int setReachableTime(u32 val);
u32 getReachableTime();
int setRetransmissionTimer(u32 val);
u32 getRetransmissionTimer();
int setTargetAddress(struct in6_addr addr);
struct in6_addr getTargetAddress();
int setDestinationAddress(struct in6_addr addr);
struct in6_addr getDestinationAddress();
int setSegmentNumber(u8 val);
u8 getSegmentNumber();
int setMaxDelay(u16 val);
u16 getMaxDelay();
/* Node Information Queries */
int setQtype(u16 val);
u16 getQtype();
int setNodeInfoFlags(u16 val);
u16 getNodeInfoFlags();
int setG(bool flag_value=true);
bool getG();
int setS(bool flag_value=true);
bool getS();
int setL(bool flag_value=true);
bool getL();
int setC(bool flag_value=true);
bool getC();
int setA(bool flag_value=true);
bool getA();
int setT(bool flag_value=true);
bool getT();
int setNonce(const u8 *nonce);
u8 *getNonce();
/* Multicast Listener Discovery */
int setMulticastAddress(struct in6_addr addr);
struct in6_addr getMulticastAddress();
/* Misc */
int getHeaderLengthFromType(u8 type);
bool isError() const;
}; /* End of class ICMPv6Header */
#endif

357
libnetutil/ICMPv6Option.cc Executable file
View File

@@ -0,0 +1,357 @@
/***************************************************************************
* ICMPv6Option.cc -- The ICMPv6Option Class represents an ICMP version 6 *
* option. It contains methods to set any header field. In general, these *
* methods do error checkings and byte order conversion. *
* *
***********************IMPORTANT NMAP LICENSE TERMS************************
* *
* The Nmap Security Scanner is (C) 1996-2011 Insecure.Com LLC. Nmap is *
* also a registered trademark of Insecure.Com LLC. This program is free *
* software; you may redistribute and/or modify it under the terms of the *
* GNU General Public License as published by the Free Software *
* Foundation; Version 2 with the clarifications and exceptions described *
* below. This guarantees your right to use, modify, and redistribute *
* this software under certain conditions. If you wish to embed Nmap *
* technology into proprietary software, we sell alternative licenses *
* (contact sales@insecure.com). Dozens of software vendors already *
* license Nmap technology such as host discovery, port scanning, OS *
* detection, and version detection. *
* *
* Note that the GPL places important restrictions on "derived works", yet *
* it does not provide a detailed definition of that term. To avoid *
* misunderstandings, we consider an application to constitute a *
* "derivative work" for the purpose of this license if it does any of the *
* following: *
* o Integrates source code from Nmap *
* o Reads or includes Nmap copyrighted data files, such as *
* nmap-os-db or nmap-service-probes. *
* o Executes Nmap and parses the results (as opposed to typical shell or *
* execution-menu apps, which simply display raw Nmap output and so are *
* not derivative works.) *
* o Integrates/includes/aggregates Nmap into a proprietary executable *
* installer, such as those produced by InstallShield. *
* o Links to a library or executes a program that does any of the above *
* *
* The term "Nmap" should be taken to also include any portions or derived *
* works of Nmap. This list is not exclusive, but is meant to clarify our *
* interpretation of derived works with some common examples. Our *
* interpretation applies only to Nmap--we don't speak for other people's *
* GPL works. *
* *
* If you have any questions about the GPL licensing restrictions on using *
* Nmap in non-GPL works, we would be happy to help. As mentioned above, *
* we also offer alternative license to integrate Nmap into proprietary *
* applications and appliances. These contracts have been sold to dozens *
* of software vendors, and generally include a perpetual license as well *
* as providing for priority support and updates as well as helping to *
* fund the continued development of Nmap technology. Please email *
* sales@insecure.com for further information. *
* *
* As a special exception to the GPL terms, Insecure.Com LLC grants *
* permission to link the code of this program with any version of the *
* OpenSSL library which is distributed under a license identical to that *
* listed in the included docs/licenses/OpenSSL.txt file, and distribute *
* linked combinations including the two. You must obey the GNU GPL in all *
* respects for all of the code used other than OpenSSL. If you modify *
* this file, you may extend this exception to your version of the file, *
* but you are not obligated to do so. *
* *
* If you received these files with a written license agreement or *
* contract stating terms other than the terms above, then that *
* alternative license agreement takes precedence over these comments. *
* *
* Source is provided to this software because we believe users have a *
* right to know exactly what a program is going to do before they run it. *
* This also allows you to audit the software for security holes (none *
* have been found so far). *
* *
* Source code also allows you to port Nmap to new platforms, fix bugs, *
* and add new features. You are highly encouraged to send your changes *
* to nmap-dev@insecure.org for possible incorporation into the main *
* distribution. By sending these changes to Fyodor or one of the *
* Insecure.Org development mailing lists, it is assumed that you are *
* offering the Nmap Project (Insecure.Com LLC) the unlimited, *
* non-exclusive right to reuse, modify, and relicense the code. Nmap *
* will always be available Open Source, but this is important because the *
* inability to relicense code has caused devastating problems for other *
* Free Software projects (such as KDE and NASM). We also occasionally *
* relicense the code to third parties as discussed above. If you wish to *
* specify special license conditions of your contributions, just say so *
* when you send them. *
* *
* This program is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* General Public License v2.0 for more details at *
* http://www.gnu.org/licenses/gpl-2.0.html , or in the COPYING file *
* included with Nmap. *
* *
***************************************************************************/
/* This code was originally part of the Nping tool. */
#include "ICMPv6Option.h"
ICMPv6Option::ICMPv6Option() {
this->reset();
} /* End of ICMPv6Option constructor */
ICMPv6Option::~ICMPv6Option() {
} /* End of ICMPv6Option destructor */
/** Sets every class attribute to zero */
void ICMPv6Option::reset(){
memset(&this->h, 0, sizeof(nping_icmpv6_option_t));
h_la = (link_addr_option_t *)this->h.data;
h_pi = (prefix_info_option_t *)this->h.data;
h_r = (redirect_option_t *)this->h.data;
h_mtu = (mtu_option_t *)this->h.data;
} /* End of reset() */
/** @warning This method is essential for the superclass getBinaryBuffer()
* method to work. Do NOT change a thing unless you know what you're doing */
u8 *ICMPv6Option::getBufferPointer(){
return (u8*)(&this->h);
} /* End of getBufferPointer() */
/** Stores supplied packet in the internal buffer so the information
* can be accessed using the standard get & set methods.
* @warning The ICMPv6Option class is able to hold a maximum of
* sizeof(nping_icmpv6_option_t) bytes. If the supplied buffer is longer than
* that, only the first sizeof(nping_icmpv6_option_t) bytes will be stored in
* the internal buffer.
* @warning Supplied len MUST be at least ICMPv6_OPTION_MIN_HEADER_LEN bytes
* @return OP_SUCCESS on success and OP_FAILURE in case of error */
int ICMPv6Option::storeRecvData(const u8 *buf, size_t len){
if(buf==NULL || len<ICMPv6_OPTION_MIN_HEADER_LEN){
return OP_FAILURE;
}else{
int stored_len = MIN( sizeof(nping_icmpv6_option_t), len);
this->reset(); /* Re-init the object, just in case the caller had used it already */
this->length=stored_len;
memcpy(&(this->h), buf, stored_len);
}
return OP_SUCCESS;
} /* End of storeRecvData() */
int ICMPv6Option::protocol_id() const {
return HEADER_TYPE_ICMPv6_OPTION;
}
int ICMPv6Option::setType(u8 val){
this->h.type=val;
this->length = getHeaderLengthFromType(val);
this->h.length = this->length / 8;
return OP_SUCCESS;
} /* End of setType() */
u8 ICMPv6Option::getType(){
return this->h.type;
} /* End of getType() */
bool ICMPv6Option::validateType(u8 val){
switch( val ){
case ICMPv6_OPTION_SRC_LINK_ADDR:
case ICMPv6_OPTION_TGT_LINK_ADDR:
case ICMPv6_OPTION_PREFIX_INFO:
case ICMPv6_OPTION_REDIR_HDR:
case ICMPv6_OPTION_MTU:
return true;
break;
default:
return false;
break;
}
return false;
} /* End of validateType() */
int ICMPv6Option::setLength(u8 val){
this->h.length=val;
return OP_SUCCESS;
} /* End of setLength() */
u8 ICMPv6Option::getLength(){
return this->h.length;
} /* End of getLength() */
int ICMPv6Option::setLinkAddress(u8* val){
if(val==NULL)
return OP_FAILURE;
switch(this->h.type){
case ICMPv6_OPTION_SRC_LINK_ADDR:
case ICMPv6_OPTION_TGT_LINK_ADDR:
memcpy(this->h_la->link_addr, val, ICMPv6_OPTION_LINK_ADDRESS_LEN);
return OP_SUCCESS;
break;
default:
return OP_FAILURE;
break;
}
} /* End of setLinkAddress() */
u8 *ICMPv6Option::getLinkAddress(){
switch(this->h.type){
case ICMPv6_OPTION_SRC_LINK_ADDR:
case ICMPv6_OPTION_TGT_LINK_ADDR:
return this->h_la->link_addr;
break;
default:
return NULL;
break;
}
} /* End of getLinkAddress() */
int ICMPv6Option::setPrefixLength(u8 val){
if(this->h.type!=ICMPv6_OPTION_PREFIX_INFO)
return OP_FAILURE;
this->h_pi->prefix_length=val;
return OP_SUCCESS;
} /* End of setPrefixLength() */
u8 ICMPv6Option::getPrefixLength(){
if(this->h.type!=ICMPv6_OPTION_PREFIX_INFO)
return 0;
else
return this->h_pi->prefix_length;
} /* End of getPrefixLength() */
int ICMPv6Option::setFlags(u8 val){
if(this->h.type!=ICMPv6_OPTION_PREFIX_INFO)
return OP_FAILURE;
this->h_pi->flags=val;
return OP_SUCCESS;
} /* End of setFlags() */
u8 ICMPv6Option::getFlags(){
if(this->h.type!=ICMPv6_OPTION_PREFIX_INFO)
return 0;
else
return this->h_pi->flags;
} /* End of getFlags() */
int ICMPv6Option::setValidLifetime(u32 val){
if(this->h.type!=ICMPv6_OPTION_PREFIX_INFO)
return OP_FAILURE;
this->h_pi->valid_lifetime=htonl(val);
return OP_SUCCESS;
} /* End of setValidLifetime() */
u32 ICMPv6Option::getValidLifetime(){
if(this->h.type!=ICMPv6_OPTION_PREFIX_INFO)
return 0;
else
return ntohl(this->h_pi->valid_lifetime);
} /* End of getValidLifetime() */
int ICMPv6Option::setPreferredLifetime(u32 val){
if(this->h.type!=ICMPv6_OPTION_PREFIX_INFO)
return OP_FAILURE;
this->h_pi->preferred_lifetime=htonl(val);
return OP_SUCCESS;
} /* End of setPreferredLifetime() */
u32 ICMPv6Option::getPreferredLifetime(){
if(this->h.type!=ICMPv6_OPTION_PREFIX_INFO)
return 0;
else
return ntohl(this->h_pi->preferred_lifetime);
} /* End of getPreferredLifetime() */
int ICMPv6Option::setPrefix(u8 *val){
if(val==NULL || this->h.type!=ICMPv6_OPTION_PREFIX_INFO)
return OP_FAILURE;
else
memcpy(this->h_pi->prefix, val, 16);
return OP_SUCCESS;
} /* End of setPrefix() */
u8 *ICMPv6Option::getPrefix(){
if(this->h.type!=ICMPv6_OPTION_PREFIX_INFO)
return NULL;
else
return this->h_pi->prefix;
} /* End of getPrefix() */
int ICMPv6Option::setMTU(u32 val){
if(this->h.type!=ICMPv6_OPTION_MTU)
return OP_FAILURE;
this->h_mtu->mtu=htonl(val);
return OP_SUCCESS;
} /* End of setMTU() */
u32 ICMPv6Option::getMTU(){
if(this->h.type!=ICMPv6_OPTION_MTU)
return 0;
else
return ntohl(this->h_mtu->mtu);
} /* End of getMTU() */
/******************************************************************************/
/* MISCELLANEOUS STUFF */
/******************************************************************************/
/** Returns the standard ICMPv6 optiom length for the supplied option type.
* @warning Return value corresponds strictly to the ICMPv7 option header, this
* is, the minimum length of the OPTION, variable length payload is never
* included. For example, an ICMPv6 Redirect option has a fixed header of 8
* bytes but then it may contain an IPv6 header. We only return 8
* because we don't know in advance the total number of bytes for the message.
* Same applies to the rest of types. */
int ICMPv6Option::getHeaderLengthFromType(u8 type){
switch( type ){
case ICMPv6_OPTION_SRC_LINK_ADDR:
return ICMPv6_OPTION_SRC_LINK_ADDR_LEN;
break;
case ICMPv6_OPTION_TGT_LINK_ADDR:
return ICMPv6_OPTION_TGT_LINK_ADDR_LEN;
break;
case ICMPv6_OPTION_PREFIX_INFO:
return ICMPv6_OPTION_PREFIX_INFO_LEN;
break;
case ICMPv6_OPTION_REDIR_HDR:
return ICMPv6_OPTION_REDIR_HDR_LEN;
break;
case ICMPv6_OPTION_MTU:
return ICMPv6_OPTION_MTU_LEN;
break;
/* Packets with non RFC-Compliant option types will be represented as an
* 8-byte ICMPv6 option. */
default:
return ICMPv6_OPTION_MIN_HEADER_LEN;
break;
}
} /* End of getHeaderLengthFromType() */

266
libnetutil/ICMPv6Option.h Executable file
View File

@@ -0,0 +1,266 @@
/***************************************************************************
* ICMPv6Option.h -- The ICMPv6Option Class represents an ICMP version 6 *
* option. It contains methods to set any header field. In general, these *
* methods do error checkings and byte order conversion. *
* *
***********************IMPORTANT NMAP LICENSE TERMS************************
* *
* The Nmap Security Scanner is (C) 1996-2011 Insecure.Com LLC. Nmap is *
* also a registered trademark of Insecure.Com LLC. This program is free *
* software; you may redistribute and/or modify it under the terms of the *
* GNU General Public License as published by the Free Software *
* Foundation; Version 2 with the clarifications and exceptions described *
* below. This guarantees your right to use, modify, and redistribute *
* this software under certain conditions. If you wish to embed Nmap *
* technology into proprietary software, we sell alternative licenses *
* (contact sales@insecure.com). Dozens of software vendors already *
* license Nmap technology such as host discovery, port scanning, OS *
* detection, and version detection. *
* *
* Note that the GPL places important restrictions on "derived works", yet *
* it does not provide a detailed definition of that term. To avoid *
* misunderstandings, we consider an application to constitute a *
* "derivative work" for the purpose of this license if it does any of the *
* following: *
* o Integrates source code from Nmap *
* o Reads or includes Nmap copyrighted data files, such as *
* nmap-os-db or nmap-service-probes. *
* o Executes Nmap and parses the results (as opposed to typical shell or *
* execution-menu apps, which simply display raw Nmap output and so are *
* not derivative works.) *
* o Integrates/includes/aggregates Nmap into a proprietary executable *
* installer, such as those produced by InstallShield. *
* o Links to a library or executes a program that does any of the above *
* *
* The term "Nmap" should be taken to also include any portions or derived *
* works of Nmap. This list is not exclusive, but is meant to clarify our *
* interpretation of derived works with some common examples. Our *
* interpretation applies only to Nmap--we don't speak for other people's *
* GPL works. *
* *
* If you have any questions about the GPL licensing restrictions on using *
* Nmap in non-GPL works, we would be happy to help. As mentioned above, *
* we also offer alternative license to integrate Nmap into proprietary *
* applications and appliances. These contracts have been sold to dozens *
* of software vendors, and generally include a perpetual license as well *
* as providing for priority support and updates as well as helping to *
* fund the continued development of Nmap technology. Please email *
* sales@insecure.com for further information. *
* *
* As a special exception to the GPL terms, Insecure.Com LLC grants *
* permission to link the code of this program with any version of the *
* OpenSSL library which is distributed under a license identical to that *
* listed in the included docs/licenses/OpenSSL.txt file, and distribute *
* linked combinations including the two. You must obey the GNU GPL in all *
* respects for all of the code used other than OpenSSL. If you modify *
* this file, you may extend this exception to your version of the file, *
* but you are not obligated to do so. *
* *
* If you received these files with a written license agreement or *
* contract stating terms other than the terms above, then that *
* alternative license agreement takes precedence over these comments. *
* *
* Source is provided to this software because we believe users have a *
* right to know exactly what a program is going to do before they run it. *
* This also allows you to audit the software for security holes (none *
* have been found so far). *
* *
* Source code also allows you to port Nmap to new platforms, fix bugs, *
* and add new features. You are highly encouraged to send your changes *
* to nmap-dev@insecure.org for possible incorporation into the main *
* distribution. By sending these changes to Fyodor or one of the *
* Insecure.Org development mailing lists, it is assumed that you are *
* offering the Nmap Project (Insecure.Com LLC) the unlimited, *
* non-exclusive right to reuse, modify, and relicense the code. Nmap *
* will always be available Open Source, but this is important because the *
* inability to relicense code has caused devastating problems for other *
* Free Software projects (such as KDE and NASM). We also occasionally *
* relicense the code to third parties as discussed above. If you wish to *
* specify special license conditions of your contributions, just say so *
* when you send them. *
* *
* This program is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* General Public License v2.0 for more details at *
* http://www.gnu.org/licenses/gpl-2.0.html , or in the COPYING file *
* included with Nmap. *
* *
***************************************************************************/
/* This code was originally part of the Nping tool. */
#ifndef __ICMPv6OPTION_H__
#define __ICMPv6OPTION_H__ 1
#include "NetworkLayerElement.h"
/* Packet header diagrams included in this file have been taken from the
* following IETF RFC documents: RFC 2461, RFC 2894 */
/* The following codes have been defined by IANA. A complete list may be found
* at http://www.iana.org/assignments/icmpv6-parameters */
/* ICMPv6 Option Types */
#define ICMPv6_OPTION_SRC_LINK_ADDR 1
#define ICMPv6_OPTION_TGT_LINK_ADDR 2
#define ICMPv6_OPTION_PREFIX_INFO 3
#define ICMPv6_OPTION_REDIR_HDR 4
#define ICMPv6_OPTION_MTU 5
/* Nping ICMPv6Options Class internal definitions */
#define ICMPv6_OPTION_COMMON_HEADER_LEN 2
#define ICMPv6_OPTION_MIN_HEADER_LEN 8
#define ICMPv6_OPTION_SRC_LINK_ADDR_LEN (ICMPv6_OPTION_COMMON_HEADER_LEN+6)
#define ICMPv6_OPTION_TGT_LINK_ADDR_LEN (ICMPv6_OPTION_COMMON_HEADER_LEN+6)
#define ICMPv6_OPTION_PREFIX_INFO_LEN (ICMPv6_OPTION_COMMON_HEADER_LEN+30)
#define ICMPv6_OPTION_REDIR_HDR_LEN (ICMPv6_OPTION_COMMON_HEADER_LEN+6)
#define ICMPv6_OPTION_MTU_LEN (ICMPv6_OPTION_COMMON_HEADER_LEN+6)
/* This must the MAX() of all values defined above*/
#define ICMPv6_OPTION_MAX_MESSAGE_BODY (ICMPv6_OPTION_PREFIX_INFO_LEN-ICMPv6_OPTION_COMMON_HEADER_LEN)
#define ICMPv6_OPTION_LINK_ADDRESS_LEN 6
class ICMPv6Option : public NetworkLayerElement {
private:
/**********************************************************************/
/* COMMON ICMPv6 OPTION HEADER */
/**********************************************************************/
struct nping_icmpv6_option{
u8 type;
u8 length;
u8 data[ICMPv6_OPTION_MAX_MESSAGE_BODY];
}__attribute__((__packed__));
typedef struct nping_icmpv6_option nping_icmpv6_option_t;
/**********************************************************************/
/* ICMPv6 OPTION FORMATS */
/**********************************************************************/
/* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Type | Length | ... |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
~ ... ~
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */
/* Source/Target Link-layer Address
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Type | Length | Link-Layer Address ...
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */
struct link_addr_option{
u8 link_addr[6];
}__attribute__((__packed__));
typedef struct link_addr_option link_addr_option_t;
/* Prefix Information
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Type | Length | Prefix Length |L|A| Reserved1 |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Valid Lifetime |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Preferred Lifetime |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Reserved2 |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+ +
| |
+ Prefix +
| |
+ +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */
struct prefix_info_option{
u8 prefix_length;
u8 flags;
u32 valid_lifetime;
u32 preferred_lifetime;
u32 reserved;
u8 prefix[16];
}__attribute__((__packed__));
typedef struct prefix_info_option prefix_info_option_t;
/* Redirect Header
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Type | Length | Reserved |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Reserved |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
~ IP header + data ~
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */
struct redirect_option{
u16 reserved_1;
u32 reserved_2;
//u8 invoking_pkt[?];
}__attribute__((__packed__));
typedef struct redirect_option redirect_option_t;
/* MTU
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Type | Length | Reserved |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| MTU |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */
struct mtu_option{
u16 reserved;
u32 mtu;
}__attribute__((__packed__));
typedef struct mtu_option mtu_option_t;
nping_icmpv6_option_t h;
link_addr_option_t *h_la;
prefix_info_option_t *h_pi;
redirect_option_t *h_r;
mtu_option_t *h_mtu;
public:
ICMPv6Option();
~ICMPv6Option();
void reset();
u8 *getBufferPointer();
int storeRecvData(const u8 *buf, size_t len);
int protocol_id() const;
int setType(u8 val);
u8 getType();
bool validateType(u8 val);
int setLength(u8 val);
u8 getLength();
int setLinkAddress(u8* val);
u8 *getLinkAddress();
int setPrefixLength(u8 val);
u8 getPrefixLength();
int setFlags(u8 val);
u8 getFlags();
int setValidLifetime(u32 val);
u32 getValidLifetime();
int setPreferredLifetime(u32 val);
u32 getPreferredLifetime();
int setPrefix(u8 *val);
u8 *getPrefix();
int setMTU(u32 val);
u32 getMTU();
int getHeaderLengthFromType(u8 type);
}; /* End of class ICMPv6Option */
#endif

142
libnetutil/ICMPv6RRBody.cc Executable file
View File

@@ -0,0 +1,142 @@
/***************************************************************************
* ICMPv6RRBody.h -- The ICMPv6RRBody Class represents an ICMP version 6 *
* Router Renumbering message body. It contains methods to set any header *
* field. In general, these methods do error checkings and byte order *
* conversions. *
* *
***********************IMPORTANT NMAP LICENSE TERMS************************
* *
* The Nmap Security Scanner is (C) 1996-2011 Insecure.Com LLC. Nmap is *
* also a registered trademark of Insecure.Com LLC. This program is free *
* software; you may redistribute and/or modify it under the terms of the *
* GNU General Public License as published by the Free Software *
* Foundation; Version 2 with the clarifications and exceptions described *
* below. This guarantees your right to use, modify, and redistribute *
* this software under certain conditions. If you wish to embed Nmap *
* technology into proprietary software, we sell alternative licenses *
* (contact sales@insecure.com). Dozens of software vendors already *
* license Nmap technology such as host discovery, port scanning, OS *
* detection, and version detection. *
* *
* Note that the GPL places important restrictions on "derived works", yet *
* it does not provide a detailed definition of that term. To avoid *
* misunderstandings, we consider an application to constitute a *
* "derivative work" for the purpose of this license if it does any of the *
* following: *
* o Integrates source code from Nmap *
* o Reads or includes Nmap copyrighted data files, such as *
* nmap-os-db or nmap-service-probes. *
* o Executes Nmap and parses the results (as opposed to typical shell or *
* execution-menu apps, which simply display raw Nmap output and so are *
* not derivative works.) *
* o Integrates/includes/aggregates Nmap into a proprietary executable *
* installer, such as those produced by InstallShield. *
* o Links to a library or executes a program that does any of the above *
* *
* The term "Nmap" should be taken to also include any portions or derived *
* works of Nmap. This list is not exclusive, but is meant to clarify our *
* interpretation of derived works with some common examples. Our *
* interpretation applies only to Nmap--we don't speak for other people's *
* GPL works. *
* *
* If you have any questions about the GPL licensing restrictions on using *
* Nmap in non-GPL works, we would be happy to help. As mentioned above, *
* we also offer alternative license to integrate Nmap into proprietary *
* applications and appliances. These contracts have been sold to dozens *
* of software vendors, and generally include a perpetual license as well *
* as providing for priority support and updates as well as helping to *
* fund the continued development of Nmap technology. Please email *
* sales@insecure.com for further information. *
* *
* As a special exception to the GPL terms, Insecure.Com LLC grants *
* permission to link the code of this program with any version of the *
* OpenSSL library which is distributed under a license identical to that *
* listed in the included docs/licenses/OpenSSL.txt file, and distribute *
* linked combinations including the two. You must obey the GNU GPL in all *
* respects for all of the code used other than OpenSSL. If you modify *
* this file, you may extend this exception to your version of the file, *
* but you are not obligated to do so. *
* *
* If you received these files with a written license agreement or *
* contract stating terms other than the terms above, then that *
* alternative license agreement takes precedence over these comments. *
* *
* Source is provided to this software because we believe users have a *
* right to know exactly what a program is going to do before they run it. *
* This also allows you to audit the software for security holes (none *
* have been found so far). *
* *
* Source code also allows you to port Nmap to new platforms, fix bugs, *
* and add new features. You are highly encouraged to send your changes *
* to nmap-dev@insecure.org for possible incorporation into the main *
* distribution. By sending these changes to Fyodor or one of the *
* Insecure.Org development mailing lists, it is assumed that you are *
* offering the Nmap Project (Insecure.Com LLC) the unlimited, *
* non-exclusive right to reuse, modify, and relicense the code. Nmap *
* will always be available Open Source, but this is important because the *
* inability to relicense code has caused devastating problems for other *
* Free Software projects (such as KDE and NASM). We also occasionally *
* relicense the code to third parties as discussed above. If you wish to *
* specify special license conditions of your contributions, just say so *
* when you send them. *
* *
* This program is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* General Public License v2.0 for more details at *
* http://www.gnu.org/licenses/gpl-2.0.html , or in the COPYING file *
* included with Nmap. *
* *
***************************************************************************/
/* This code was originally part of the Nping tool. */
#include "ICMPv6RRBody.h"
ICMPv6RRBody::ICMPv6RRBody() {
this->reset();
} /* End of ICMPv6RRBody constructor */
ICMPv6RRBody::~ICMPv6RRBody() {
} /* End of ICMPv6RRBody destructor */
/** Sets every class attribute to zero */
void ICMPv6RRBody::reset(){
memset(&this->h, 0, sizeof(nping_icmpv6_rr_body_t));
h_mp = (rr_match_prefix_t *)this->h.data;
h_up = (rr_use_prefix_t *)this->h.data;
h_r = (rr_result_msg_t *)this->h.data;
} /* End of reset() */
/** @warning This method is essential for the superclass getBinaryBuffer()
* method to work. Do NOT change a thing unless you know what you're doing */
u8 *ICMPv6RRBody::getBufferPointer(){
return (u8*)(&this->h);
} /* End of getBufferPointer() */
/** Stores supplied packet in the internal buffer so the information
* can be accessed using the standard get & set methods.
* @warning The ICMPv6RRBody class is able to hold a maximum of
* sizeof(nping_icmpv6_rr_body_t) bytes. If the supplied buffer is longer than
* that, only the first sizeof(nping_icmpv6_rr_body_t) bytes will be stored in
* the internal buffer.
* @warning Supplied len MUST be at least ICMPv6_RR_MIN_LENGTH bytes
* @return OP_SUCCESS on success and OP_FAILURE in case of error */
int ICMPv6RRBody::storeRecvData(const u8 *buf, size_t len){
if(buf==NULL || len<ICMPv6_RR_MIN_LENGTH){
return OP_FAILURE;
}else{
int stored_len = MIN( sizeof(nping_icmpv6_rr_body_t), len);
this->reset(); /* Re-init the object, just in case the caller had used it already */
this->length=stored_len;
memcpy(&(this->h), buf, stored_len);
}
return OP_SUCCESS;
} /* End of storeRecvData() */

231
libnetutil/ICMPv6RRBody.h Executable file
View File

@@ -0,0 +1,231 @@
/***************************************************************************
* ICMPv6RRBody.cc -- The ICMPv6RRBody Class represents an ICMP version 6 *
* Router Renumbering message body. It contains methods to set any header *
* field. In general, these methods do error checkings and byte order *
* conversions. *
* *
***********************IMPORTANT NMAP LICENSE TERMS************************
* *
* The Nmap Security Scanner is (C) 1996-2011 Insecure.Com LLC. Nmap is *
* also a registered trademark of Insecure.Com LLC. This program is free *
* software; you may redistribute and/or modify it under the terms of the *
* GNU General Public License as published by the Free Software *
* Foundation; Version 2 with the clarifications and exceptions described *
* below. This guarantees your right to use, modify, and redistribute *
* this software under certain conditions. If you wish to embed Nmap *
* technology into proprietary software, we sell alternative licenses *
* (contact sales@insecure.com). Dozens of software vendors already *
* license Nmap technology such as host discovery, port scanning, OS *
* detection, and version detection. *
* *
* Note that the GPL places important restrictions on "derived works", yet *
* it does not provide a detailed definition of that term. To avoid *
* misunderstandings, we consider an application to constitute a *
* "derivative work" for the purpose of this license if it does any of the *
* following: *
* o Integrates source code from Nmap *
* o Reads or includes Nmap copyrighted data files, such as *
* nmap-os-db or nmap-service-probes. *
* o Executes Nmap and parses the results (as opposed to typical shell or *
* execution-menu apps, which simply display raw Nmap output and so are *
* not derivative works.) *
* o Integrates/includes/aggregates Nmap into a proprietary executable *
* installer, such as those produced by InstallShield. *
* o Links to a library or executes a program that does any of the above *
* *
* The term "Nmap" should be taken to also include any portions or derived *
* works of Nmap. This list is not exclusive, but is meant to clarify our *
* interpretation of derived works with some common examples. Our *
* interpretation applies only to Nmap--we don't speak for other people's *
* GPL works. *
* *
* If you have any questions about the GPL licensing restrictions on using *
* Nmap in non-GPL works, we would be happy to help. As mentioned above, *
* we also offer alternative license to integrate Nmap into proprietary *
* applications and appliances. These contracts have been sold to dozens *
* of software vendors, and generally include a perpetual license as well *
* as providing for priority support and updates as well as helping to *
* fund the continued development of Nmap technology. Please email *
* sales@insecure.com for further information. *
* *
* As a special exception to the GPL terms, Insecure.Com LLC grants *
* permission to link the code of this program with any version of the *
* OpenSSL library which is distributed under a license identical to that *
* listed in the included docs/licenses/OpenSSL.txt file, and distribute *
* linked combinations including the two. You must obey the GNU GPL in all *
* respects for all of the code used other than OpenSSL. If you modify *
* this file, you may extend this exception to your version of the file, *
* but you are not obligated to do so. *
* *
* If you received these files with a written license agreement or *
* contract stating terms other than the terms above, then that *
* alternative license agreement takes precedence over these comments. *
* *
* Source is provided to this software because we believe users have a *
* right to know exactly what a program is going to do before they run it. *
* This also allows you to audit the software for security holes (none *
* have been found so far). *
* *
* Source code also allows you to port Nmap to new platforms, fix bugs, *
* and add new features. You are highly encouraged to send your changes *
* to nmap-dev@insecure.org for possible incorporation into the main *
* distribution. By sending these changes to Fyodor or one of the *
* Insecure.Org development mailing lists, it is assumed that you are *
* offering the Nmap Project (Insecure.Com LLC) the unlimited, *
* non-exclusive right to reuse, modify, and relicense the code. Nmap *
* will always be available Open Source, but this is important because the *
* inability to relicense code has caused devastating problems for other *
* Free Software projects (such as KDE and NASM). We also occasionally *
* relicense the code to third parties as discussed above. If you wish to *
* specify special license conditions of your contributions, just say so *
* when you send them. *
* *
* This program is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* General Public License v2.0 for more details at *
* http://www.gnu.org/licenses/gpl-2.0.html , or in the COPYING file *
* included with Nmap. *
* *
***************************************************************************/
/* This code was originally part of the Nping tool. */
#ifndef ICMPv6HEADER_H
#define ICMPv6HEADER_H 1
#include "NetworkLayerElement.h"
/* Packet header diagrams included in this file have been taken from the
* following IETF RFC documents: RFC 2894 */
/* Nping ICMPv6RRBody Class internal definitions */
#define ICMPv6_RR_MATCH_PREFIX_LEN 24
#define ICMPv6_RR_USE_PREFIX_LEN 32
#define ICMPv6_RR_RESULT_MSG_LEN 24
/* This must the MAX() of all values defined above*/
#define ICMPv6_RR_MAX_LENGTH (ICMPv6_RR_USE_PREFIX_LEN)
#define ICMPv6_RR_MIN_LENGTH (ICMPv6_RR_MATCH_PREFIX_LEN)
class ICMPv6RRBody : public NetworkLayerElement {
private:
/**********************************************************************/
/* COMMON ICMPv6 OPTION HEADER */
/**********************************************************************/
struct nping_icmpv6_rr_body{
u8 data[ICMPv6_RR_MAX_LENGTH];
}__attribute__((__packed__));
typedef struct nping_icmpv6_rr_body nping_icmpv6_rr_body_t;
/**********************************************************************/
/* ICMPv6 OPTION FORMATS */
/**********************************************************************/
/* Match-Prefix Part
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| OpCode | OpLength | Ordinal | MatchLen |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| MinLen | MaxLen | reserved |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+- -+
| |
+- MatchPrefix -+
| |
+- -+
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
struct rr_match_prefix{
u8 op_code;
u8 op_length;
u8 ordinal;
u8 match_length;
u8 min_length;
u8 max_length;
u16 reserved;
u8 match_prefix[16];
}__attribute__((__packed__));
typedef struct rr_match_prefix rr_match_prefix_t;
/* Use-Prefix Part
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| UseLen | KeepLen | FlagMask | RAFlags |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Valid Lifetime |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Preferred Lifetime |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|V|P| reserved |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+- -+
| |
+- UsePrefix -+
| |
+- -+
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
struct rr_use_prefix{
u8 use_len;
u8 keep_len;
u8 flag_mask;
u8 ra_flags;
u32 valid_lifetime;
u32 preferred_lifetime;
u8 flags;
u8 reserved[3];
u8 use_prefix[16];
}__attribute__((__packed__));
typedef struct rr_use_prefix rr_use_prefix_t;
/* Result Message
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| reserved |B|F| Ordinal | MatchedLen |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| InterfaceIndex |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+- -+
| |
+- MatchedPrefix -+
| |
+- -+
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */
struct rr_result_msg{
u8 reserved;
u8 flags;
u8 ordinal;
u8 matched_length;
u32 interface_index;
u8 matched_prefix[16];
}__attribute__((__packed__));
typedef struct rr_result_msg rr_result_msg_t;
nping_icmpv6_rr_body_t h;
rr_match_prefix_t *h_mp;
rr_use_prefix_t *h_up;
rr_result_msg_t *h_r;
public:
ICMPv6RRBody();
~ICMPv6RRBody();
void reset();
u8 *getBufferPointer();
int storeRecvData(const u8 *buf, size_t len);
}; /* End of class ICMPv6RRBody */
#endif

654
libnetutil/IPv4Header.cc Normal file
View File

@@ -0,0 +1,654 @@
/***************************************************************************
* IPv4Header.cc -- The IPv4Header Class represents an IPv4 datagram. It *
* contains methods to set any header field. In general, these methods do *
* error checkings and byte order conversion. *
* *
***********************IMPORTANT NMAP LICENSE TERMS************************
* *
* The Nmap Security Scanner is (C) 1996-2011 Insecure.Com LLC. Nmap is *
* also a registered trademark of Insecure.Com LLC. This program is free *
* software; you may redistribute and/or modify it under the terms of the *
* GNU General Public License as published by the Free Software *
* Foundation; Version 2 with the clarifications and exceptions described *
* below. This guarantees your right to use, modify, and redistribute *
* this software under certain conditions. If you wish to embed Nmap *
* technology into proprietary software, we sell alternative licenses *
* (contact sales@insecure.com). Dozens of software vendors already *
* license Nmap technology such as host discovery, port scanning, OS *
* detection, and version detection. *
* *
* Note that the GPL places important restrictions on "derived works", yet *
* it does not provide a detailed definition of that term. To avoid *
* misunderstandings, we consider an application to constitute a *
* "derivative work" for the purpose of this license if it does any of the *
* following: *
* o Integrates source code from Nmap *
* o Reads or includes Nmap copyrighted data files, such as *
* nmap-os-db or nmap-service-probes. *
* o Executes Nmap and parses the results (as opposed to typical shell or *
* execution-menu apps, which simply display raw Nmap output and so are *
* not derivative works.) *
* o Integrates/includes/aggregates Nmap into a proprietary executable *
* installer, such as those produced by InstallShield. *
* o Links to a library or executes a program that does any of the above *
* *
* The term "Nmap" should be taken to also include any portions or derived *
* works of Nmap. This list is not exclusive, but is meant to clarify our *
* interpretation of derived works with some common examples. Our *
* interpretation applies only to Nmap--we don't speak for other people's *
* GPL works. *
* *
* If you have any questions about the GPL licensing restrictions on using *
* Nmap in non-GPL works, we would be happy to help. As mentioned above, *
* we also offer alternative license to integrate Nmap into proprietary *
* applications and appliances. These contracts have been sold to dozens *
* of software vendors, and generally include a perpetual license as well *
* as providing for priority support and updates as well as helping to *
* fund the continued development of Nmap technology. Please email *
* sales@insecure.com for further information. *
* *
* As a special exception to the GPL terms, Insecure.Com LLC grants *
* permission to link the code of this program with any version of the *
* OpenSSL library which is distributed under a license identical to that *
* listed in the included docs/licenses/OpenSSL.txt file, and distribute *
* linked combinations including the two. You must obey the GNU GPL in all *
* respects for all of the code used other than OpenSSL. If you modify *
* this file, you may extend this exception to your version of the file, *
* but you are not obligated to do so. *
* *
* If you received these files with a written license agreement or *
* contract stating terms other than the terms above, then that *
* alternative license agreement takes precedence over these comments. *
* *
* Source is provided to this software because we believe users have a *
* right to know exactly what a program is going to do before they run it. *
* This also allows you to audit the software for security holes (none *
* have been found so far). *
* *
* Source code also allows you to port Nmap to new platforms, fix bugs, *
* and add new features. You are highly encouraged to send your changes *
* to nmap-dev@insecure.org for possible incorporation into the main *
* distribution. By sending these changes to Fyodor or one of the *
* Insecure.Org development mailing lists, it is assumed that you are *
* offering the Nmap Project (Insecure.Com LLC) the unlimited, *
* non-exclusive right to reuse, modify, and relicense the code. Nmap *
* will always be available Open Source, but this is important because the *
* inability to relicense code has caused devastating problems for other *
* Free Software projects (such as KDE and NASM). We also occasionally *
* relicense the code to third parties as discussed above. If you wish to *
* specify special license conditions of your contributions, just say so *
* when you send them. *
* *
* This program is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* General Public License v2.0 for more details at *
* http://www.gnu.org/licenses/gpl-2.0.html , or in the COPYING file *
* included with Nmap. *
* *
***************************************************************************/
/* This code was originally part of the Nping tool. */
#include "IPv4Header.h"
/******************************************************************************/
/* CONTRUCTORS, DESTRUCTORS AND INITIALIZATION METHODS */
/******************************************************************************/
IPv4Header::IPv4Header() {
this->reset();
} /* End of IPv4Header constructor */
IPv4Header::~IPv4Header() {
} /* End of IPv4Header destructor */
/** Sets every attribute to its default value */
void IPv4Header::reset() {
memset(&this->h, 0, sizeof(nping_ipv4_hdr_t));
this->ipoptlen=0;
this->length=20; /* Initial value 20. This will be incremented if options are used */
this->setVersion();
this->setHeaderLength();
this->setTOS(IPv4_DEFAULT_TOS);
this->setIdentification(IPv4_DEFAULT_ID);
this->setTTL(IPv4_DEFAULT_TTL);
this->setNextProto(IPv4_DEFAULT_PROTO);
this->setTotalLength();
} /* End of IPv4Header destructor */
/******************************************************************************/
/* PacketElement:: OVERWRITTEN METHODS */
/******************************************************************************/
/** @warning This method is essential for the superclass getBinaryBuffer()
* method to work. Do NOT change a thing unless you know what you're doing */
u8 *IPv4Header::getBufferPointer(){
return (u8*)(&h);
} /* End of getBufferPointer() */
/** Stores supplied packet in the internal buffer so the information
* can be accessed using the standard get & set methods.
* @warning The IPv4Header class is able to hold a maximum of 60 bytes. If the
* supplied buffer is longer than that, only the first 60 bytes will be stored
* in the internal buffer.
* @warning Supplied len MUST be at least 20 bytes (min IP header length).
* @return OP_SUCCESS on success and OP_FAILURE in case of error */
int IPv4Header::storeRecvData(const u8 *buf, size_t len){
if(buf==NULL || len<IP_HEADER_LEN){
return OP_FAILURE;
}else{
int stored_len = MIN((IP_HEADER_LEN + MAX_IP_OPTIONS_LEN), len);
this->reset(); /* Re-init the object, just in case the caller had used it already */
this->length=stored_len;
memcpy(&(this->h), buf, stored_len);
}
return OP_SUCCESS;
} /* End of storeRecvData() */
/* Returns a protocol identifier. This is used by packet parsing funtions
* that return linked lists of PacketElement objects, to determine the protocol
* the object represents. */
int IPv4Header::protocol_id() const {
return HEADER_TYPE_IPv4;
} /* End of protocol_id() */
/** Performs some VERY BASIC checks that intend to validate the information
* stored in the internal buffer, as a valid protocol header.
* @warning If the information stored in the object has been set through a
* call to storeRecvData(), the object's internal length count may be updated
* if the validation is successful.
* @return the length, in bytes, of the header, if its found to be valid or
* OP_FAILURE (-1) otherwise. */
int IPv4Header::validate(){
if(this->getVersion()!=4)
return OP_FAILURE;
else if( this->getHeaderLength()<5)
return OP_FAILURE;
else if( this->getHeaderLength()*4 > this->length)
return OP_FAILURE;
this->length=this->getHeaderLength()*4;
return this->length;
} /* End of validate() */
/** Prints the contents of the header and calls print() on the next protocol
* header in the chain (if there is any).
* @return OP_SUCCESS on success and OP_FAILURE in case of error. */
int IPv4Header::print(FILE *output, int detail) const {
static char ipstring[256];
memset(ipstring, 0, 256);
struct in_addr addr;
int frag_off = 8 * this->getFragOffset() & 8191; /* 2^13 - 1 */;
char ipinfo[512] = ""; /* Temp info about IP. */
char fragnfo[64] = ""; /* Temp info about fragmentation. */
fprintf(output, "IPv4[");
this->getSourceAddress(&addr);
inet_ntop(AF_INET, &addr, ipstring, sizeof(ipstring));
fprintf(output, "%s", ipstring);
fprintf(output, " >");
this->getDestinationAddress(&addr);
inet_ntop(AF_INET, &addr, ipstring, sizeof(ipstring));
fprintf(output, " %s", ipstring);
/* Is this a fragmented packet? is it the last fragment? */
if (frag_off || this->getMF()) {
Snprintf(fragnfo, sizeof(fragnfo), " frag offset=%d%s", frag_off, this->getMF() ? "+" : "");
}
/* Create a string with information relevant to the specified level of detail */
if( detail == PRINT_DETAIL_LOW ){
Snprintf(ipinfo, sizeof(ipinfo), "ttl=%d id=%d iplen=%d%s%s%s%s",
this->getTTL(), this->getIdentification(), this->getTotalLength(), fragnfo,
this->getHeaderLength()==5?"":" ipopts={",
this->getHeaderLength()?"":format_ip_options(this->h.options , MIN(this->getHeaderLength()*4, this->length-IP_HEADER_LEN)),
this->getHeaderLength()?"":"}");
}else if( detail == PRINT_DETAIL_MED ){
Snprintf(ipinfo, sizeof(ipinfo), "ttl=%d id=%d proto=%d csum=0x%04X iplen=%d%s%s%s%s",
this->getTTL(), this->getIdentification(),
this->getNextProto(), this->getSum(),
this->getTotalLength(), fragnfo,
this->getHeaderLength()==5?"":" ipopts={",
this->getHeaderLength()==5?"":format_ip_options(this->h.options , MIN(this->getHeaderLength()*4, this->length-IP_HEADER_LEN)),
this->getHeaderLength()==5?"":"}");
}else if( detail>=PRINT_DETAIL_HIGH ){
Snprintf(ipinfo, sizeof(ipinfo), "ver=%d ihl=%d tos=0x%02x iplen=%d id=%d%s%s%s%s foff=%d%s ttl=%d proto=%d csum=0x%04X%s%s%s",
this->getVersion(), this->getHeaderLength(),
this->getTOS(), this->getTotalLength(),
this->getIdentification(),
(this->getRF() ||this->getDF()||this->getMF()) ? " flg=" : "",
(this->getRF()) ? "x" : "",
(this->getDF() )? "D" : "",
(this->getMF() )? "M": "",
frag_off, (this->getMF()) ? "+" : "",
this->getTTL(), this->getNextProto(),
this->getSum(),
this->getHeaderLength()==5?"":" ipopts={",
this->getHeaderLength()==5?"":format_ip_options(this->h.options , MIN(this->getHeaderLength()*4, this->length-IP_HEADER_LEN)),
this->getHeaderLength()==5?"":"}");
}
fprintf(output, " %s]", ipinfo);
if(this->next!=NULL){
print_separator(output, detail);
next->print(output, detail);
}
return OP_SUCCESS;
} /* End of print() */
/******************************************************************************/
/* PROTOCOL-SPECIFIC METHODS */
/******************************************************************************/
int IPv4Header::setVersion(){
h.ip_v = 4;
return 4;
} /* End of setVersion() */
u8 IPv4Header::getVersion() const {
return (u8)h.ip_v;
} /* End of getVersion() */
int IPv4Header::setHeaderLength(){
h.ip_hl = 5 + (ipoptlen/4);
return OP_SUCCESS;
} /* End of setHeaderLength() */
int IPv4Header::setHeaderLength(u8 l){
h.ip_hl = l;
return OP_SUCCESS;
} /* End of setHeaderLength() */
u8 IPv4Header::getHeaderLength() const {
return h.ip_hl;
} /* End of getHeaderLength() */
int IPv4Header::setTOS(u8 v){
h.ip_tos = v;
return OP_SUCCESS;
} /* End of setTOS() */
u8 IPv4Header::getTOS() const {
return h.ip_tos;
} /* End of getTOS() */
int IPv4Header::setTotalLength(){
int mylen = 4*getHeaderLength();
int otherslen=0;
if (next!=NULL)
otherslen=next->getLen();
h.ip_len=htons( mylen+otherslen );
return OP_SUCCESS;
} /* End of setTotalLength() */
/** @warning Supplied value MUST be in host byte order because it will get
* converted by this method using htons() */
int IPv4Header::setTotalLength(u16 l){
h.ip_len = htons(l);
return OP_SUCCESS;
} /* End of setTotalLength() */
/** @warning Returned value is already in host byte order. */
u16 IPv4Header::getTotalLength() const {
return ntohs(h.ip_len);
} /* End of getTotalLength() */
/** Sets identification field to a random value */
int IPv4Header::setIdentification(){
h.ip_id=get_random_u16();
return OP_SUCCESS;
} /* End of setIdentification() */
/** @warning Supplied value MUST be in host byte order because it will get
* converted by this method using htons() */
int IPv4Header::setIdentification(u16 i){
h.ip_id = htons(i);
return OP_SUCCESS;
} /* End of setIdentification() */
/** @warning Returned value is already in host byte order. */
u16 IPv4Header::getIdentification() const {
return ntohs(h.ip_id);
} /* End of getIdentification() */
/** Sets fragment offset field to a random value */
int IPv4Header::setFragOffset(){
/* TODO: Should we check here that i<8192 ? */
h.ip_off=get_random_u16();
return OP_SUCCESS;
} /* End of setFragOffset() */
/** @warning Supplied value MUST be in host byte order because it will get
* converted by this method using htons() */
int IPv4Header::setFragOffset(u16 i){
/* TODO: Should we check here that i<8192 ? */
h.ip_off = htons(i);
return OP_SUCCESS;
} /* End of setFragOffset() */
/** @warning Returned value is already in host byte order. */
u16 IPv4Header::getFragOffset() const {
return ntohs(h.ip_off);
} /* End of getFragOffset() */
/** Set RF flag */
int IPv4Header::setRF(){
h.ip_off |= htons(IP_RF);
return OP_SUCCESS;
} /* End of setRF() */
/** Unset RF flag */
int IPv4Header::unsetRF(){
h.ip_off ^= htons(IP_RF);
return OP_SUCCESS;
} /* End of unsetRF() */
/** Get RF flag */
bool IPv4Header::getRF() const {
return h.ip_off & htons(IP_RF);
} /* End of getRF() */
/** Set MF flag */
int IPv4Header::setMF(){
h.ip_off |= htons(IP_MF);
return OP_SUCCESS;
} /* End of setMF() */
/** Unset MF flag */
int IPv4Header::unsetMF(){
h.ip_off ^= htons(IP_MF);
return OP_SUCCESS;
} /* End of unsetMF() */
/* Get MF flag */
bool IPv4Header::getMF() const {
return h.ip_off & htons(IP_MF);
} /* End of getMF() */
/** Set DF flag */
int IPv4Header::setDF(){
h.ip_off |= htons(IP_DF);
return OP_SUCCESS;
} /* End of setDF() */
/** Unset DF flag */
int IPv4Header::unsetDF(){
h.ip_off ^= htons(IP_DF);
return OP_SUCCESS;
} /* End of unsetDF() */
/** Get DF flag */
bool IPv4Header::getDF() const {
return h.ip_off & htons(IP_DF);
} /* End of getDF) */
/** Sets TTL field to a random value */
int IPv4Header::setTTL(){
h.ip_ttl=get_random_u8();
return OP_SUCCESS;
} /* End of setTTL() */
/** @warning Supplied value MUST be in host byte order because it will get
* converted by this method using htons() */
int IPv4Header::setTTL(u8 t){
h.ip_ttl = t;
return OP_SUCCESS;
} /* End of setTTL() */
/** @warning Returned value is already in host byte order. */
u8 IPv4Header::getTTL() const {
return h.ip_ttl;
} /* End of getTTL() */
/** Sets field "next protocol" to the supplied value.
* @warning: No error checks are made. Make sure the supplied value
* corresponds to an actual IANA number. Check
* http://www.iana.org/assignments/protocol-numbers/ for more details. */
int IPv4Header::setNextProto(u8 p){
h.ip_p = p;
return OP_SUCCESS;
} /* End of setNextProto() */
/** Sets field "next protocol" to the number that corresponds to the supplied
* protocol name. Currently onyl TCP, UDP and ICMP are supported. Any
* help to extend this functionality would be appreciated. For a list of all
* proto names and numbers check:
* http://www.iana.org/assignments/protocol-numbers/ */
int IPv4Header::setNextProto(const char *p){
if (p==NULL){
printf("setNextProto(): NULL pointer supplied\n");
return OP_FAILURE;
}
if( !strcasecmp(p, "TCP") )
h.ip_p=6; /* 6=IANA number for proto TCP */
else if( !strcasecmp(p, "UDP") )
h.ip_p=17; /* 17=IANA number for proto UDP */
else if( !strcasecmp(p, "ICMP") )
h.ip_p=1; /* 1=IANA number for proto ICMP */
else{
printf("setNextProto(): Invalid protocol number\n");
return OP_FAILURE;
}
return OP_SUCCESS;
} /* End of setNextProto() */
/** Returns next protocol number */
u8 IPv4Header::getNextProto() const {
return h.ip_p;
} /* End of getNextProto() */
u8 IPv4Header::getNextHeader() const {
return this->getNextProto();
} /* End of getNextHeader() */
int IPv4Header::setNextHeader(u8 val){
return this->setNextProto(val);
} /* End of setNextHeader() */
/** Computes the IPv4 header checksum and sets the ip_sum field to the right
* value. */
int IPv4Header::setSum(){
h.ip_sum = 0;
/* ip_checksum() comes from libdnet */
ip_checksum((void*)&h, 20 + ipoptlen );
return OP_SUCCESS;
} /* End of setSum() */
/** @warning Sum is set to supplied value with NO byte ordering conversion
* performed.
* @warning If sum is supplied this way, no error checks are made. Caller is
* responsible for the correctness of the value. */
int IPv4Header::setSum(u16 s){
h.ip_sum = s;
return OP_SUCCESS;
} /* End of setSum() */
/** Set the checksum field to a random value */
int IPv4Header::setSumRandom(){
h.ip_sum=get_random_u16();
return OP_SUCCESS;
} /* End of setRandomSum() */
/** Returns the value of the checksum field.
* @warning The returned value is in NETWORK byte order, no conversion is
* performed */
u16 IPv4Header::getSum() const {
return h.ip_sum;
} /* End of getSum() */
/** Sets destination IP address.
* @warning Destination IP must be supplied in NETWORK byte order. Usually
* all regular library functions return IPs in network byte order so there
* should be no need to worry. */
int IPv4Header::setDestinationAddress(u32 d){
h.ip_dst.s_addr = d;
return OP_SUCCESS;
} /* End of getDestinationAddress() */
/** Sets destination IP address.
* @warning Destination IP must be supplied in NETWORK byte order. Usually
* all regular library functions return IPs in network byte order so there
* should be no need to worry. */
int IPv4Header::setDestinationAddress(struct in_addr d){
h.ip_dst=d;
return OP_SUCCESS;
} /* End of getDestinationAddress() */
/** Returns destination IP address.
* @warning Returned value is in NETWORK byte order. */
const u8 *IPv4Header::getDestinationAddress() const {
return (u8 *)(&h.ip_dst.s_addr);
} /* End of getDestinationAddress() */
/** Returns destination IP address.
* @warning Returned value is in NETWORK byte order. */
struct in_addr IPv4Header::getDestinationAddress(struct in_addr *result) const {
if(result!=NULL)
*result=this->h.ip_dst;
return h.ip_dst;
} /* End of getDestinationAddress() */
/** Sets source IP address.
* @warning Destination IP must be supplied in NETWORK byte order. Usually
* all regular library functions return IPs in network byte order so there
* should be no need to worry. */
int IPv4Header::setSourceAddress(u32 d){
h.ip_src.s_addr = d;
return OP_SUCCESS;
} /* End of setSourceAddress() */
/** Sets source IP address.
* @warning Destination IP must be supplied in NETWORK byte order. Usually
* all regular library functions return IPs in network byte order so there
* should be no need to worry. */
int IPv4Header::setSourceAddress(struct in_addr d){
h.ip_src=d;
return OP_SUCCESS;
} /* End of setSourceAddress() */
/** Returns source ip
* @warning Returned value is in NETWORK byte order. */
const u8 *IPv4Header::getSourceAddress() const {
return (u8 *)(&h.ip_src.s_addr);
} /* End of getSourceAddress() */
/** Returns source ip
* @warning Returned value is in NETWORK byte order. */
struct in_addr IPv4Header::getSourceAddress(struct in_addr *result) const {
if(result!=NULL)
*result=this->h.ip_src;
return h.ip_src;
} /* End of getSourceAddress() */
/** Returns the length of an IPv4 address. */
u16 IPv4Header::getAddressLength() const {
return 4;
} /* End of getAddressLength()*/
int IPv4Header::setOpts(const char *txt){
int foo=0;
int bar=0;
int ret=0;
u8 buffer[128];
char errstr[256];
if(txt==NULL){
printf("setOpts(): NULL pointer supplied.\n");
return OP_FAILURE;
}
/* Parse IP options */
if((ret=parse_ip_options(txt, buffer, 128, &foo, &bar, errstr, sizeof(errstr)))==OP_FAILURE){
printf("%s\n", errstr);
return OP_FAILURE;
}else{
/* Copy options to our IP header */
memcpy(h.options, buffer, ret);
this->ipoptlen=ret;
this->length += ret;
this->setHeaderLength();
}
return OP_SUCCESS;
} /* End of setOpts() */
const u8 *IPv4Header::getOpts() const {
return h.options;
} /* End of getOpts() */
const u8 *IPv4Header::getOpts(int *len) const {
if(len==NULL)
printf("getOpts(): NULL pointer supplied.\n");
*len=ipoptlen;
return h.options;
} /* End of getOpts() */
int IPv4Header::printOptions() const {
char *p=format_ip_options(this->h.options, this->ipoptlen);
printf("%s", p);
return OP_SUCCESS;
} /* End of printOptions() */
const char *IPv4Header::getOptionsString() const {
return format_ip_options(this->h.options, this->ipoptlen);
} /* End of getOptionsString() */

250
libnetutil/IPv4Header.h Normal file
View File

@@ -0,0 +1,250 @@
/***************************************************************************
* IPv4Header.h -- The IPv4Header Class represents an IPv4 datagram. It *
* contains methods to set any header field. In general, these methods do *
* error checkings and byte order conversion. *
* *
***********************IMPORTANT NMAP LICENSE TERMS************************
* *
* The Nmap Security Scanner is (C) 1996-2011 Insecure.Com LLC. Nmap is *
* also a registered trademark of Insecure.Com LLC. This program is free *
* software; you may redistribute and/or modify it under the terms of the *
* GNU General Public License as published by the Free Software *
* Foundation; Version 2 with the clarifications and exceptions described *
* below. This guarantees your right to use, modify, and redistribute *
* this software under certain conditions. If you wish to embed Nmap *
* technology into proprietary software, we sell alternative licenses *
* (contact sales@insecure.com). Dozens of software vendors already *
* license Nmap technology such as host discovery, port scanning, OS *
* detection, and version detection. *
* *
* Note that the GPL places important restrictions on "derived works", yet *
* it does not provide a detailed definition of that term. To avoid *
* misunderstandings, we consider an application to constitute a *
* "derivative work" for the purpose of this license if it does any of the *
* following: *
* o Integrates source code from Nmap *
* o Reads or includes Nmap copyrighted data files, such as *
* nmap-os-db or nmap-service-probes. *
* o Executes Nmap and parses the results (as opposed to typical shell or *
* execution-menu apps, which simply display raw Nmap output and so are *
* not derivative works.) *
* o Integrates/includes/aggregates Nmap into a proprietary executable *
* installer, such as those produced by InstallShield. *
* o Links to a library or executes a program that does any of the above *
* *
* The term "Nmap" should be taken to also include any portions or derived *
* works of Nmap. This list is not exclusive, but is meant to clarify our *
* interpretation of derived works with some common examples. Our *
* interpretation applies only to Nmap--we don't speak for other people's *
* GPL works. *
* *
* If you have any questions about the GPL licensing restrictions on using *
* Nmap in non-GPL works, we would be happy to help. As mentioned above, *
* we also offer alternative license to integrate Nmap into proprietary *
* applications and appliances. These contracts have been sold to dozens *
* of software vendors, and generally include a perpetual license as well *
* as providing for priority support and updates as well as helping to *
* fund the continued development of Nmap technology. Please email *
* sales@insecure.com for further information. *
* *
* As a special exception to the GPL terms, Insecure.Com LLC grants *
* permission to link the code of this program with any version of the *
* OpenSSL library which is distributed under a license identical to that *
* listed in the included docs/licenses/OpenSSL.txt file, and distribute *
* linked combinations including the two. You must obey the GNU GPL in all *
* respects for all of the code used other than OpenSSL. If you modify *
* this file, you may extend this exception to your version of the file, *
* but you are not obligated to do so. *
* *
* If you received these files with a written license agreement or *
* contract stating terms other than the terms above, then that *
* alternative license agreement takes precedence over these comments. *
* *
* Source is provided to this software because we believe users have a *
* right to know exactly what a program is going to do before they run it. *
* This also allows you to audit the software for security holes (none *
* have been found so far). *
* *
* Source code also allows you to port Nmap to new platforms, fix bugs, *
* and add new features. You are highly encouraged to send your changes *
* to nmap-dev@insecure.org for possible incorporation into the main *
* distribution. By sending these changes to Fyodor or one of the *
* Insecure.Org development mailing lists, it is assumed that you are *
* offering the Nmap Project (Insecure.Com LLC) the unlimited, *
* non-exclusive right to reuse, modify, and relicense the code. Nmap *
* will always be available Open Source, but this is important because the *
* inability to relicense code has caused devastating problems for other *
* Free Software projects (such as KDE and NASM). We also occasionally *
* relicense the code to third parties as discussed above. If you wish to *
* specify special license conditions of your contributions, just say so *
* when you send them. *
* *
* This program is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* General Public License v2.0 for more details at *
* http://www.gnu.org/licenses/gpl-2.0.html , or in the COPYING file *
* included with Nmap. *
* *
***************************************************************************/
/* This code was originally part of the Nping tool. */
#ifndef IPV4HEADER_H
#define IPV4HEADER_H 1
#include "NetworkLayerElement.h"
#define IP_RF 0x8000 /* Reserved fragment flag */
#define IP_DF 0x4000 /* Dont fragment flag */
#define IP_MF 0x2000 /* More fragments flag */
#define IP_OFFMASK 0x1fff /* Mask for fragmenting bits */
#define IP_HEADER_LEN 20 /* Length of the standard header */
#define MAX_IP_OPTIONS_LEN 40 /* Max Length for IP Options */
/* Default header values */
#define IPv4_DEFAULT_TOS 0
#define IPv4_DEFAULT_ID 0
#define IPv4_DEFAULT_TTL 64
#define IPv4_DEFAULT_PROTO 6 /* TCP */
class IPv4Header : public NetworkLayerElement {
private:
/*
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|Version| IHL |Type of Service| Total Length |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Identification |Flags| Fragment Offset |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Time to Live | Protocol | Header Checksum |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Source Address |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Destination Address |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Options | Padding |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
struct nping_ipv4_hdr {
#if WORDS_BIGENDIAN
u8 ip_v:4; /* Version */
u8 ip_hl:4; /* Header length */
#else
u8 ip_hl:4; /* Header length */
u8 ip_v:4; /* Version */
#endif
u8 ip_tos; /* Type of service */
u16 ip_len; /* Total length */
u16 ip_id; /* Identification */
u16 ip_off; /* Fragment offset field */
u8 ip_ttl; /* Time to live */
u8 ip_p; /* Protocol */
u16 ip_sum; /* Checksum */
struct in_addr ip_src; /* Source IP address */
struct in_addr ip_dst; /* Destination IP address */
u8 options[MAX_IP_OPTIONS_LEN]; /* IP Options */
}__attribute__((__packed__));
typedef struct nping_ipv4_hdr nping_ipv4_hdr_t;
nping_ipv4_hdr_t h;
int ipoptlen; /**< Length of IP options */
public:
/* Misc */
IPv4Header();
~IPv4Header();
void reset();
u8 *getBufferPointer();
int storeRecvData(const u8 *buf, size_t len);
int protocol_id() const;
int validate();
int print(FILE *output, int detail) const;
/* IP version */
int setVersion();
u8 getVersion() const;
/* Header Length */
int setHeaderLength();
int setHeaderLength(u8 l);
u8 getHeaderLength() const;
/* Type of Service */
int setTOS(u8 v);
u8 getTOS() const;
/* Total lenght of the datagram */
int setTotalLength();
int setTotalLength(u16 l);
u16 getTotalLength() const;
/* Identification value */
int setIdentification();
int setIdentification(u16 i);
u16 getIdentification() const;
/* Fragment Offset */
int setFragOffset();
int setFragOffset(u16 f);
u16 getFragOffset() const;
/* Flags */
int setRF();
int unsetRF();
bool getRF() const;
int setDF();
int unsetDF();
bool getDF() const;
int setMF();
int unsetMF();
bool getMF() const;
/* Time to live */
int setTTL();
int setTTL(u8 t);
u8 getTTL() const;
/* Next protocol */
int setNextProto(u8 p);
int setNextProto(const char *p);
u8 getNextProto() const;
int setNextHeader(u8 val);
u8 getNextHeader() const;
/* Checksum */
int setSum();
int setSum(u16 s);
int setSumRandom();
u16 getSum() const;
/* Destination IP */
int setDestinationAddress(u32 d);
int setDestinationAddress(struct in_addr d);
const u8 *getDestinationAddress() const;
struct in_addr getDestinationAddress(struct in_addr *result) const;
/* Source IP */
int setSourceAddress(u32 d);
int setSourceAddress(struct in_addr d);
const u8 *getSourceAddress() const;
struct in_addr getSourceAddress(struct in_addr *result) const;
u16 getAddressLength() const;
/* IP Options */
int setOpts(const char *txt);
const u8 *getOpts() const;
const u8 *getOpts(int *len) const;
int printOptions() const;
const char *getOptionsString() const;
}; /* End of class IPv4Header */
#endif

View File

@@ -0,0 +1,112 @@
/***************************************************************************
* IPv6ExtensionHeader.h -- The IPv6ExtensionHeader class represents *
* a generic class for IPv6 extension headers. Specific headers (like *
* Hop-by-Hop or Routing) inherit from this class. *
***********************IMPORTANT NMAP LICENSE TERMS************************
* *
* The Nmap Security Scanner is (C) 1996-2011 Insecure.Com LLC. Nmap is *
* also a registered trademark of Insecure.Com LLC. This program is free *
* software; you may redistribute and/or modify it under the terms of the *
* GNU General Public License as published by the Free Software *
* Foundation; Version 2 with the clarifications and exceptions described *
* below. This guarantees your right to use, modify, and redistribute *
* this software under certain conditions. If you wish to embed Nmap *
* technology into proprietary software, we sell alternative licenses *
* (contact sales@insecure.com). Dozens of software vendors already *
* license Nmap technology such as host discovery, port scanning, OS *
* detection, and version detection. *
* *
* Note that the GPL places important restrictions on "derived works", yet *
* it does not provide a detailed definition of that term. To avoid *
* misunderstandings, we consider an application to constitute a *
* "derivative work" for the purpose of this license if it does any of the *
* following: *
* o Integrates source code from Nmap *
* o Reads or includes Nmap copyrighted data files, such as *
* nmap-os-db or nmap-service-probes. *
* o Executes Nmap and parses the results (as opposed to typical shell or *
* execution-menu apps, which simply display raw Nmap output and so are *
* not derivative works.) *
* o Integrates/includes/aggregates Nmap into a proprietary executable *
* installer, such as those produced by InstallShield. *
* o Links to a library or executes a program that does any of the above *
* *
* The term "Nmap" should be taken to also include any portions or derived *
* works of Nmap. This list is not exclusive, but is meant to clarify our *
* interpretation of derived works with some common examples. Our *
* interpretation applies only to Nmap--we don't speak for other people's *
* GPL works. *
* *
* If you have any questions about the GPL licensing restrictions on using *
* Nmap in non-GPL works, we would be happy to help. As mentioned above, *
* we also offer alternative license to integrate Nmap into proprietary *
* applications and appliances. These contracts have been sold to dozens *
* of software vendors, and generally include a perpetual license as well *
* as providing for priority support and updates as well as helping to *
* fund the continued development of Nmap technology. Please email *
* sales@insecure.com for further information. *
* *
* As a special exception to the GPL terms, Insecure.Com LLC grants *
* permission to link the code of this program with any version of the *
* OpenSSL library which is distributed under a license identical to that *
* listed in the included docs/licenses/OpenSSL.txt file, and distribute *
* linked combinations including the two. You must obey the GNU GPL in all *
* respects for all of the code used other than OpenSSL. If you modify *
* this file, you may extend this exception to your version of the file, *
* but you are not obligated to do so. *
* *
* If you received these files with a written license agreement or *
* contract stating terms other than the terms above, then that *
* alternative license agreement takes precedence over these comments. *
* *
* Source is provided to this software because we believe users have a *
* right to know exactly what a program is going to do before they run it. *
* This also allows you to audit the software for security holes (none *
* have been found so far). *
* *
* Source code also allows you to port Nmap to new platforms, fix bugs, *
* and add new features. You are highly encouraged to send your changes *
* to nmap-dev@insecure.org for possible incorporation into the main *
* distribution. By sending these changes to Fyodor or one of the *
* Insecure.Org development mailing lists, it is assumed that you are *
* offering the Nmap Project (Insecure.Com LLC) the unlimited, *
* non-exclusive right to reuse, modify, and relicense the code. Nmap *
* will always be available Open Source, but this is important because the *
* inability to relicense code has caused devastating problems for other *
* Free Software projects (such as KDE and NASM). We also occasionally *
* relicense the code to third parties as discussed above. If you wish to *
* specify special license conditions of your contributions, just say so *
* when you send them. *
* *
* This program is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* General Public License v2.0 for more details at *
* http://www.gnu.org/licenses/gpl-2.0.html , or in the COPYING file *
* included with Nmap. *
* *
***************************************************************************/
/* This code was originally part of the Nping tool. */
#ifndef __IPv6_EXTENSION_HEADER_H__
#define __IPv6_EXTENSION_HEADER_H__ 1
#include "PacketElement.h"
/* Extension header option codes */
#define EXTOPT_PAD1 0x00 /* Pad1 (RFC 2460) */
#define EXTOPT_PADN 0x01 /* PadN (RFC 2460) */
#define EXTOPT_JUMBO 0xC2 /* Jumbo Payload (RFC 2675) */
#define EXTOPT_TUNENCAPLIM 0x04 /* Tunnel Encapsulation Limit (RFC 2473) */
#define EXTOPT_ROUTERALERT 0x05 /* Router Alert (RFC 2711) */
#define EXTOPT_QUICKSTART 0x26 /* Quick-Start (RFC 4782) */
#define EXTOPT_CALIPSO 0x07 /* CALIPSO (RFC 5570) */
#define EXTOPT_HOMEADDR 0xC9 /* Home Address (RFC 6275) */
class IPv6ExtensionHeader : public PacketElement {
};
#endif

511
libnetutil/IPv6Header.cc Executable file
View File

@@ -0,0 +1,511 @@
/***************************************************************************
* IPv6Header.cc -- The IPv6Header Class represents an IPv4 datagram. It *
* contains methods to set any header field. In general, these methods do *
* error checkings and byte order conversion. *
* *
***********************IMPORTANT NMAP LICENSE TERMS************************
* *
* The Nmap Security Scanner is (C) 1996-2011 Insecure.Com LLC. Nmap is *
* also a registered trademark of Insecure.Com LLC. This program is free *
* software; you may redistribute and/or modify it under the terms of the *
* GNU General Public License as published by the Free Software *
* Foundation; Version 2 with the clarifications and exceptions described *
* below. This guarantees your right to use, modify, and redistribute *
* this software under certain conditions. If you wish to embed Nmap *
* technology into proprietary software, we sell alternative licenses *
* (contact sales@insecure.com). Dozens of software vendors already *
* license Nmap technology such as host discovery, port scanning, OS *
* detection, and version detection. *
* *
* Note that the GPL places important restrictions on "derived works", yet *
* it does not provide a detailed definition of that term. To avoid *
* misunderstandings, we consider an application to constitute a *
* "derivative work" for the purpose of this license if it does any of the *
* following: *
* o Integrates source code from Nmap *
* o Reads or includes Nmap copyrighted data files, such as *
* nmap-os-db or nmap-service-probes. *
* o Executes Nmap and parses the results (as opposed to typical shell or *
* execution-menu apps, which simply display raw Nmap output and so are *
* not derivative works.) *
* o Integrates/includes/aggregates Nmap into a proprietary executable *
* installer, such as those produced by InstallShield. *
* o Links to a library or executes a program that does any of the above *
* *
* The term "Nmap" should be taken to also include any portions or derived *
* works of Nmap. This list is not exclusive, but is meant to clarify our *
* interpretation of derived works with some common examples. Our *
* interpretation applies only to Nmap--we don't speak for other people's *
* GPL works. *
* *
* If you have any questions about the GPL licensing restrictions on using *
* Nmap in non-GPL works, we would be happy to help. As mentioned above, *
* we also offer alternative license to integrate Nmap into proprietary *
* applications and appliances. These contracts have been sold to dozens *
* of software vendors, and generally include a perpetual license as well *
* as providing for priority support and updates as well as helping to *
* fund the continued development of Nmap technology. Please email *
* sales@insecure.com for further information. *
* *
* As a special exception to the GPL terms, Insecure.Com LLC grants *
* permission to link the code of this program with any version of the *
* OpenSSL library which is distributed under a license identical to that *
* listed in the included docs/licenses/OpenSSL.txt file, and distribute *
* linked combinations including the two. You must obey the GNU GPL in all *
* respects for all of the code used other than OpenSSL. If you modify *
* this file, you may extend this exception to your version of the file, *
* but you are not obligated to do so. *
* *
* If you received these files with a written license agreement or *
* contract stating terms other than the terms above, then that *
* alternative license agreement takes precedence over these comments. *
* *
* Source is provided to this software because we believe users have a *
* right to know exactly what a program is going to do before they run it. *
* This also allows you to audit the software for security holes (none *
* have been found so far). *
* *
* Source code also allows you to port Nmap to new platforms, fix bugs, *
* and add new features. You are highly encouraged to send your changes *
* to nmap-dev@insecure.org for possible incorporation into the main *
* distribution. By sending these changes to Fyodor or one of the *
* Insecure.Org development mailing lists, it is assumed that you are *
* offering the Nmap Project (Insecure.Com LLC) the unlimited, *
* non-exclusive right to reuse, modify, and relicense the code. Nmap *
* will always be available Open Source, but this is important because the *
* inability to relicense code has caused devastating problems for other *
* Free Software projects (such as KDE and NASM). We also occasionally *
* relicense the code to third parties as discussed above. If you wish to *
* specify special license conditions of your contributions, just say so *
* when you send them. *
* *
* This program is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* General Public License v2.0 for more details at *
* http://www.gnu.org/licenses/gpl-2.0.html , or in the COPYING file *
* included with Nmap. *
* *
***************************************************************************/
/* This code was originally part of the Nping tool. */
#include "IPv6Header.h"
/******************************************************************************/
/* CONTRUCTORS, DESTRUCTORS AND INITIALIZATION METHODS */
/******************************************************************************/
IPv6Header::IPv6Header() {
this->reset();
} /* End of IPv6Header constructor */
IPv6Header::~IPv6Header() {
} /* End of IPv6Header destructor */
/** Sets every attribute to its default value */
void IPv6Header::reset(){
memset(&this->h, 0, sizeof(nping_ipv6_hdr_t));
this->length=IPv6_HEADER_LEN;
this->setVersion();
this->setTrafficClass(IPv6_DEFAULT_TCLASS);
this->setFlowLabel(IPv6_DEFAULT_FLABEL);
this->setHopLimit(IPv6_DEFAULT_HOPLIM);
this->setNextHeader(IPv6_DEFAULT_NXTHDR); /* No next header */
this->setPayloadLength(0);
} /* End of reset() */
/******************************************************************************/
/* PacketElement:: OVERWRITTEN METHODS */
/******************************************************************************/
/** @warning This method is essential for the superclass getBinaryBuffer()
* method to work. Do NOT change a thing unless you know what you're doing */
u8 *IPv6Header::getBufferPointer(){
return (u8*)(&h);
} /* End of getBufferPointer() */
/** Stores supplied packet in the internal buffer so the information
* can be accessed using the standard get & set methods.
* @warning The IPv6Header class is able to hold a maximum of 40 bytes. If the
* supplied buffer is longer than that, only the first 40 bytes will be stored
* in the internal buffer.
* @warning Supplied len MUST be at least 40 bytes (IPv6 header length).
* @return OP_SUCCESS on success and OP_FAILURE in case of error */
int IPv6Header::storeRecvData(const u8 *buf, size_t len){
if(buf==NULL || len<IPv6_HEADER_LEN){
return OP_FAILURE;
}else{
this->reset(); /* Re-init the object, just in case the caller had used it already */
this->length=IPv6_HEADER_LEN;
memcpy(&(this->h), buf, IPv6_HEADER_LEN);
}
return OP_SUCCESS;
} /* End of storeRecvData() */
/* Returns a protocol identifier. This is used by packet parsing funtions
* that return linked lists of PacketElement objects, to determine the protocol
* the object represents. */
int IPv6Header::protocol_id() const {
return HEADER_TYPE_IPv6;
} /* End of protocol_id() */
/** Determines if the data stored in the object after an storeRecvData() call
* is valid and safe to use. This mainly checks the length of the data but may
* also test the value of certain protocol fields to ensure their correctness.
* @return the length, in bytes, of the header, if its found to be valid or
* OP_FAILURE (-1) otherwise. */
int IPv6Header::validate(){
if( this->length!=IPv6_HEADER_LEN)
return OP_FAILURE;
else
return IPv6_HEADER_LEN;
} /* End of validate() */
/** Prints the contents of the header and calls print() on the next protocol
* header in the chain (if there is any).
* @return OP_SUCCESS on success and OP_FAILURE in case of error. */
int IPv6Header::print(FILE *output, int detail) const {
fprintf(output, "IPv6[]");
if(this->next!=NULL){
print_separator(output, detail);
next->print(output, detail);
}
return OP_SUCCESS;
} /* End of print() */
/******************************************************************************/
/* PROTOCOL-SPECIFIC METHODS */
/******************************************************************************/
/** Set Version field (4 bits). */
int IPv6Header::setVersion(u8 val){
union{
struct firstbyte{
#if WORDS_BIGENDIAN
u8 ver:4;
u8 tclass:4;
#else
u8 tclass:4;
u8 ver:4;
#endif
}halfbyte;
u8 fullbyte;
}header1stbyte;
header1stbyte.fullbyte = h.ip6_start[0];
header1stbyte.halfbyte.ver=val;
h.ip6_start[0]=header1stbyte.fullbyte;
return OP_SUCCESS;
} /* End of setVersion() */
/** Set Version field to value 6. */
int IPv6Header::setVersion(){
this->setVersion(6);
return OP_SUCCESS;
} /* End of setVersion() */
/** Returns an 8bit number containing the value of the Version field. */
u8 IPv6Header::getVersion() const {
union{
struct firstbyte{
#if WORDS_BIGENDIAN
u8 ver:4;
u8 tclass:4;
#else
u8 tclass:4;
u8 ver:4;
#endif
}halfbyte;
u8 fullbyte;
}header1stbyte;
header1stbyte.fullbyte = h.ip6_start[0];
return (u8)header1stbyte.halfbyte.ver;
} /* End of getVersion() */
int IPv6Header::setTrafficClass(u8 val){
union{
struct firstbyte{
#if WORDS_BIGENDIAN
u8 ver:4;
u8 tclass1:4;
#else
u8 tclass1:4;
u8 ver:4;
#endif
}halfbyte;
u8 fullbyte;
}header1stbyte;
union{
struct firstbyte{
#if WORDS_BIGENDIAN
u8 tclass2:4;
u8 flow:4;
#else
u8 flow:4;
u8 tclass2:4;
#endif
}halfbyte;
u8 fullbyte;
}header2ndbyte;
/* Store old contents */
header1stbyte.fullbyte = h.ip6_start[0];
header2ndbyte.fullbyte = h.ip6_start[1];
/* Fill the two 4bit halves */
header1stbyte.halfbyte.tclass1=val>>4;
header2ndbyte.halfbyte.tclass2=val;
/* Write the bytes back to the header */
h.ip6_start[0]=header1stbyte.fullbyte;
h.ip6_start[1]=header2ndbyte.fullbyte;
return OP_SUCCESS;
} /* End of setTrafficClass() */
u8 IPv6Header::getTrafficClass() const {
union{
struct firstbyte{
#if WORDS_BIGENDIAN
u8 ver:4;
u8 tclass1:4;
#else
u8 tclass1:4;
u8 ver:4;
#endif
}halfbyte;
u8 fullbyte;
}header1stbyte;
union{
struct firstbyte{
#if WORDS_BIGENDIAN
u8 tclass2:4;
u8 flow:4;
#else
u8 flow:4;
u8 tclass2:4;
#endif
}halfbyte;
u8 fullbyte;
}header2ndbyte;
union{
struct firstbyte{
#if WORDS_BIGENDIAN
u8 tclass1:4;
u8 tclass2:4;
#else
u8 tclass2:4;
u8 tclass1:4;
#endif
}halfbyte;
u8 fullbyte;
}finalbyte;
header1stbyte.fullbyte = h.ip6_start[0];
header2ndbyte.fullbyte = h.ip6_start[1];
finalbyte.halfbyte.tclass1=header1stbyte.halfbyte.tclass1;
finalbyte.halfbyte.tclass2=header2ndbyte.halfbyte.tclass2;
return finalbyte.fullbyte;
} /* End of getTrafficClass() */
int IPv6Header::setFlowLabel(u32 val){
u32 netbyte = htonl(val);
u8 *pnt=(u8*)&netbyte;
union{
struct firstbyte{
#if WORDS_BIGENDIAN
u8 tclass2:4;
u8 flow:4;
#else
u8 flow:4;
u8 tclass2:4;
#endif
}halfbyte;
u8 fullbyte;
}header2ndbyte;
header2ndbyte.fullbyte = h.ip6_start[1];
header2ndbyte.halfbyte.flow=pnt[1];
h.ip6_start[1]=header2ndbyte.fullbyte;
h.ip6_start[2]=pnt[2];
h.ip6_start[3]=pnt[3];
return OP_SUCCESS;
} /* End of setFlowLabel() */
u32 IPv6Header::getFlowLabel() const {
u32 hostbyte=0;
u8 *pnt=(u8*)&hostbyte;
union{
struct firstbyte{
#if WORDS_BIGENDIAN
u8 tclass2:4;
u8 flow:4;
#else
u8 flow:4;
u8 tclass2:4;
#endif
}halfbyte;
u8 fullbyte;
}header2ndbyte;
header2ndbyte.fullbyte = h.ip6_start[1];
pnt[0]=0;
pnt[1]=header2ndbyte.halfbyte.flow;
pnt[2]=h.ip6_start[2];
pnt[3]=h.ip6_start[3];
hostbyte=ntohl(hostbyte);
return hostbyte;
} /* End of getFlowLabel() */
int IPv6Header::setPayloadLength(u16 val){
this->h.ip6_len = htons(val);
return OP_SUCCESS;
} /* End of setPayloadLength() */
int IPv6Header::setPayloadLength(){
int otherslen=0;
if (next!=NULL)
otherslen=next->getLen();
setPayloadLength( otherslen );
return OP_SUCCESS;
} /* End of setTotalLength() */
u16 IPv6Header::getPayloadLength() const {
return ntohs(this->h.ip6_len);
} /* End of getPayloadLength() */
int IPv6Header::setNextHeader(u8 val){
this->h.ip6_nh = val;
return OP_SUCCESS;
} /* End of setNextHeader() */
u8 IPv6Header::getNextHeader() const {
return this->h.ip6_nh;
} /* End of getNextHeader() */
/** Sets field "next header" to the number that corresponds to the supplied
* protocol name. Currently onyl TCP, UDP and ICMP are supported. Any
* help to extend this functionality would be appreciated. For a list of all
* proto names and numbers check:
* http://www.iana.org/assignments/protocol-numbers/ */
int IPv6Header::setNextHeader(const char *p){
if (p==NULL){
printf("setNextProto(): NULL pointer supplied\n");
return OP_FAILURE;
}
if( !strcasecmp(p, "TCP") )
setNextHeader(6); /* 6=IANA number for proto TCP */
else if( !strcasecmp(p, "UDP") )
setNextHeader(17); /* 17=IANA number for proto UDP */
else if( !strcasecmp(p, "ICMPv6"))
setNextHeader(58); /* 58=IANA number for proto ICMPv6 */
else
netutil_fatal("setNextProto(): Invalid protocol number\n");
return OP_SUCCESS;
} /* End of setNextHeader() */
int IPv6Header::setHopLimit(u8 val){
this->h.ip6_hopl = val;
return OP_SUCCESS;
} /* End of setHopLimit() */
u8 IPv6Header::getHopLimit() const {
return this->h.ip6_hopl;
} /* End of getHopLimit() */
int IPv6Header::setSourceAddress(u8 *val){
if(val==NULL)
netutil_fatal("setSourceAddress(): NULL value supplied.");
memcpy(this->h.ip6_src, val, 16);
return OP_SUCCESS;
} /* End of setSourceAddress() */
int IPv6Header::setSourceAddress(struct in6_addr val){
memcpy(this->h.ip6_src, val.s6_addr, 16);
return OP_SUCCESS;
} /* End of setSourceAddress() */
const u8 *IPv6Header::getSourceAddress() const {
return this->h.ip6_src;
} /* End of getSourceAddress() */
/** Returns source IPv6 address
* @warning Returned value is in NETWORK byte order. */
struct in6_addr IPv6Header::getSourceAddress(struct in6_addr *result) const {
struct in6_addr myaddr;
memset(&myaddr, 0, sizeof(myaddr));
memcpy(myaddr.s6_addr, this->h.ip6_src, 16);
if(result!=NULL)
*result=myaddr;
return myaddr;
} /* End of getSourceAddress() */
int IPv6Header::setDestinationAddress(u8 *val){
if(val==NULL)
netutil_fatal("setDestinationAddress(): NULL value supplied.");
memcpy(this->h.ip6_dst, val, 16);
return OP_SUCCESS;
} /* End of setDestinationAddress() */
int IPv6Header::setDestinationAddress(struct in6_addr val){
memcpy(this->h.ip6_dst, val.s6_addr, 16);
return OP_SUCCESS;
} /* End of setDestinationAddress() */
/** Returns destination IPv6 address. */
const u8 *IPv6Header::getDestinationAddress() const {
return this->h.ip6_dst;
} /* End of getDestinationAddress() */
/** Returns destination IPv6 address
* @warning Returned value is in NETWORK byte order. */
struct in6_addr IPv6Header::getDestinationAddress(struct in6_addr *result) const {
struct in6_addr myaddr;
memset(&myaddr, 0, sizeof(myaddr));
memcpy(myaddr.s6_addr, this->h.ip6_dst, 16);
if(result!=NULL)
*result=myaddr;
return myaddr;
} /* End of getDestinationAddress() */
/** Returns the length of an IPv4 address. */
u16 IPv6Header::getAddressLength() const {
return 16;
} /* End of getAddressLength()*/

203
libnetutil/IPv6Header.h Normal file
View File

@@ -0,0 +1,203 @@
/***************************************************************************
* IPv6Header.h -- The IPv6Header Class represents an IPv6 datagram. It *
* contains methods to set any header field. In general, these methods do *
* error checkings and byte order conversion. *
* *
***********************IMPORTANT NMAP LICENSE TERMS************************
* *
* The Nmap Security Scanner is (C) 1996-2011 Insecure.Com LLC. Nmap is *
* also a registered trademark of Insecure.Com LLC. This program is free *
* software; you may redistribute and/or modify it under the terms of the *
* GNU General Public License as published by the Free Software *
* Foundation; Version 2 with the clarifications and exceptions described *
* below. This guarantees your right to use, modify, and redistribute *
* this software under certain conditions. If you wish to embed Nmap *
* technology into proprietary software, we sell alternative licenses *
* (contact sales@insecure.com). Dozens of software vendors already *
* license Nmap technology such as host discovery, port scanning, OS *
* detection, and version detection. *
* *
* Note that the GPL places important restrictions on "derived works", yet *
* it does not provide a detailed definition of that term. To avoid *
* misunderstandings, we consider an application to constitute a *
* "derivative work" for the purpose of this license if it does any of the *
* following: *
* o Integrates source code from Nmap *
* o Reads or includes Nmap copyrighted data files, such as *
* nmap-os-db or nmap-service-probes. *
* o Executes Nmap and parses the results (as opposed to typical shell or *
* execution-menu apps, which simply display raw Nmap output and so are *
* not derivative works.) *
* o Integrates/includes/aggregates Nmap into a proprietary executable *
* installer, such as those produced by InstallShield. *
* o Links to a library or executes a program that does any of the above *
* *
* The term "Nmap" should be taken to also include any portions or derived *
* works of Nmap. This list is not exclusive, but is meant to clarify our *
* interpretation of derived works with some common examples. Our *
* interpretation applies only to Nmap--we don't speak for other people's *
* GPL works. *
* *
* If you have any questions about the GPL licensing restrictions on using *
* Nmap in non-GPL works, we would be happy to help. As mentioned above, *
* we also offer alternative license to integrate Nmap into proprietary *
* applications and appliances. These contracts have been sold to dozens *
* of software vendors, and generally include a perpetual license as well *
* as providing for priority support and updates as well as helping to *
* fund the continued development of Nmap technology. Please email *
* sales@insecure.com for further information. *
* *
* As a special exception to the GPL terms, Insecure.Com LLC grants *
* permission to link the code of this program with any version of the *
* OpenSSL library which is distributed under a license identical to that *
* listed in the included docs/licenses/OpenSSL.txt file, and distribute *
* linked combinations including the two. You must obey the GNU GPL in all *
* respects for all of the code used other than OpenSSL. If you modify *
* this file, you may extend this exception to your version of the file, *
* but you are not obligated to do so. *
* *
* If you received these files with a written license agreement or *
* contract stating terms other than the terms above, then that *
* alternative license agreement takes precedence over these comments. *
* *
* Source is provided to this software because we believe users have a *
* right to know exactly what a program is going to do before they run it. *
* This also allows you to audit the software for security holes (none *
* have been found so far). *
* *
* Source code also allows you to port Nmap to new platforms, fix bugs, *
* and add new features. You are highly encouraged to send your changes *
* to nmap-dev@insecure.org for possible incorporation into the main *
* distribution. By sending these changes to Fyodor or one of the *
* Insecure.Org development mailing lists, it is assumed that you are *
* offering the Nmap Project (Insecure.Com LLC) the unlimited, *
* non-exclusive right to reuse, modify, and relicense the code. Nmap *
* will always be available Open Source, but this is important because the *
* inability to relicense code has caused devastating problems for other *
* Free Software projects (such as KDE and NASM). We also occasionally *
* relicense the code to third parties as discussed above. If you wish to *
* specify special license conditions of your contributions, just say so *
* when you send them. *
* *
* This program is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* General Public License v2.0 for more details at *
* http://www.gnu.org/licenses/gpl-2.0.html , or in the COPYING file *
* included with Nmap. *
* *
***************************************************************************/
/* This code was originally part of the Nping tool. */
#ifndef IPV6HEADER_H
#define IPV6HEADER_H 1
#include "NetworkLayerElement.h"
#define IPv6_HEADER_LEN 40
/* Default header values */
#define IPv6_DEFAULT_TCLASS 0
#define IPv6_DEFAULT_FLABEL 0
#define IPv6_DEFAULT_HOPLIM 64
#define IPv6_DEFAULT_NXTHDR 6 /* TCP */
class IPv6Header : public NetworkLayerElement {
private:
/* IPv6 Header Format:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|Version| Traffic Class | Flow Label |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Payload Length | Next Header | Hop Limit |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+-- --+
| |
+-- Source Address --+
| |
+-- --+
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+-- --+
| |
+-- Destination Address --+
| |
+-- --+
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
struct nping_ipv6_hdr {
u8 ip6_start[4]; /* Version, Traffic and Flow */
u16 ip6_len; /* Payload length */
u8 ip6_nh; /* Next Header */
u8 ip6_hopl; /* Hop Limit */
u8 ip6_src[16]; /* Source IP Address */
u8 ip6_dst[16]; /* Destination IP Address */
}__attribute__((__packed__));
typedef struct nping_ipv6_hdr nping_ipv6_hdr_t;
nping_ipv6_hdr_t h;
public:
/* Misc */
IPv6Header();
~IPv6Header();
void reset();
u8 *getBufferPointer();
int storeRecvData(const u8 *buf, size_t len);
int protocol_id() const;
int validate();
int print(FILE *output, int detail) const;
/* IP version */
int setVersion();
int setVersion(u8 val);
u8 getVersion() const;
/* Traffic class */
int setTrafficClass(u8 val);
u8 getTrafficClass() const;
/* Flow Label */
int setFlowLabel(u32 val);
u32 getFlowLabel() const;
/* Payload Length */
int setPayloadLength(u16 val);
int setPayloadLength();
u16 getPayloadLength() const;
/* Next Header */
int setNextHeader(u8 val);
int setNextHeader(const char *p);
u8 getNextHeader() const;
/* Hop Limit */
int setHopLimit(u8 val);
u8 getHopLimit() const;
/* Source Address */
int setSourceAddress(u8 *val);
int setSourceAddress(struct in6_addr val);
const u8 *getSourceAddress() const;
struct in6_addr getSourceAddress(struct in6_addr *result) const;
/* Destination Address*/
int setDestinationAddress(u8 *val);
int setDestinationAddress(struct in6_addr val);
const u8 *getDestinationAddress() const;
struct in6_addr getDestinationAddress(struct in6_addr *result) const;
u16 getAddressLength() const;
};
#endif

View File

@@ -14,8 +14,8 @@ LIBPCAPDIR = @libpcapdir@
TARGET = libnetutil.a TARGET = libnetutil.a
SRCS = $(srcdir)/netutil.cc SRCS = $(srcdir)/netutil.cc $(srcdir)/PacketElement.cc $(srcdir)/NetworkLayerElement.cc $(srcdir)/ARPHeader.cc $(srcdir)/PacketElement.cc $(srcdir)/NetworkLayerElement.cc $(srcdir)/TransportLayerElement.cc $(srcdir)/ARPHeader.cc $(srcdir)/EthernetHeader.cc $(srcdir)/ICMPv4Header.cc $(srcdir)/ICMPv6Header.cc $(srcdir)/IPv4Header.cc $(srcdir)/IPv6Header.cc $(srcdir)/TCPHeader.cc $(srcdir)/UDPHeader.cc $(srcdir)/RawData.cc $(srcdir)/HopByHopHeader.cc $(srcdir)/DestOptsHeader.cc $(srcdir)/FragmentHeader.cc $(srcdir)/RoutingHeader.cc $(srcdir)/PacketParser.cc $(srcdir)/npacket.cc
OBJS = netutil.o OBJS = netutil.o PacketElement.o NetworkLayerElement.o TransportLayerElement.o ARPHeader.o EthernetHeader.o ICMPv4Header.o ICMPv6Header.o IPv4Header.o IPv6Header.o TCPHeader.o UDPHeader.o RawData.o HopByHopHeader.o DestOptsHeader.o FragmentHeader.o RoutingHeader.o PacketParser.o npacket.o
all: $(TARGET) all: $(TARGET)

View File

@@ -0,0 +1,93 @@
/***************************************************************************
* NetworkLayerElement.cc -- Class NetworkLayerElement is a generic class *
* that represents a network layer protocol header. Classes like IPv4Header*
* or IPv6Header inherit from it. *
* *
***********************IMPORTANT NMAP LICENSE TERMS************************
* *
* The Nmap Security Scanner is (C) 1996-2011 Insecure.Com LLC. Nmap is *
* also a registered trademark of Insecure.Com LLC. This program is free *
* software; you may redistribute and/or modify it under the terms of the *
* GNU General Public License as published by the Free Software *
* Foundation; Version 2 with the clarifications and exceptions described *
* below. This guarantees your right to use, modify, and redistribute *
* this software under certain conditions. If you wish to embed Nmap *
* technology into proprietary software, we sell alternative licenses *
* (contact sales@insecure.com). Dozens of software vendors already *
* license Nmap technology such as host discovery, port scanning, OS *
* detection, and version detection. *
* *
* Note that the GPL places important restrictions on "derived works", yet *
* it does not provide a detailed definition of that term. To avoid *
* misunderstandings, we consider an application to constitute a *
* "derivative work" for the purpose of this license if it does any of the *
* following: *
* o Integrates source code from Nmap *
* o Reads or includes Nmap copyrighted data files, such as *
* nmap-os-db or nmap-service-probes. *
* o Executes Nmap and parses the results (as opposed to typical shell or *
* execution-menu apps, which simply display raw Nmap output and so are *
* not derivative works.) *
* o Integrates/includes/aggregates Nmap into a proprietary executable *
* installer, such as those produced by InstallShield. *
* o Links to a library or executes a program that does any of the above *
* *
* The term "Nmap" should be taken to also include any portions or derived *
* works of Nmap. This list is not exclusive, but is meant to clarify our *
* interpretation of derived works with some common examples. Our *
* interpretation applies only to Nmap--we don't speak for other people's *
* GPL works. *
* *
* If you have any questions about the GPL licensing restrictions on using *
* Nmap in non-GPL works, we would be happy to help. As mentioned above, *
* we also offer alternative license to integrate Nmap into proprietary *
* applications and appliances. These contracts have been sold to dozens *
* of software vendors, and generally include a perpetual license as well *
* as providing for priority support and updates as well as helping to *
* fund the continued development of Nmap technology. Please email *
* sales@insecure.com for further information. *
* *
* As a special exception to the GPL terms, Insecure.Com LLC grants *
* permission to link the code of this program with any version of the *
* OpenSSL library which is distributed under a license identical to that *
* listed in the included docs/licenses/OpenSSL.txt file, and distribute *
* linked combinations including the two. You must obey the GNU GPL in all *
* respects for all of the code used other than OpenSSL. If you modify *
* this file, you may extend this exception to your version of the file, *
* but you are not obligated to do so. *
* *
* If you received these files with a written license agreement or *
* contract stating terms other than the terms above, then that *
* alternative license agreement takes precedence over these comments. *
* *
* Source is provided to this software because we believe users have a *
* right to know exactly what a program is going to do before they run it. *
* This also allows you to audit the software for security holes (none *
* have been found so far). *
* *
* Source code also allows you to port Nmap to new platforms, fix bugs, *
* and add new features. You are highly encouraged to send your changes *
* to nmap-dev@insecure.org for possible incorporation into the main *
* distribution. By sending these changes to Fyodor or one of the *
* Insecure.Org development mailing lists, it is assumed that you are *
* offering the Nmap Project (Insecure.Com LLC) the unlimited, *
* non-exclusive right to reuse, modify, and relicense the code. Nmap *
* will always be available Open Source, but this is important because the *
* inability to relicense code has caused devastating problems for other *
* Free Software projects (such as KDE and NASM). We also occasionally *
* relicense the code to third parties as discussed above. If you wish to *
* specify special license conditions of your contributions, just say so *
* when you send them. *
* *
* This program is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* General Public License v2.0 for more details at *
* http://www.gnu.org/licenses/gpl-2.0.html , or in the COPYING file *
* included with Nmap. *
* *
***************************************************************************/
/* This code was originally part of the Nping tool. */
#include "NetworkLayerElement.h"

View File

@@ -0,0 +1,123 @@
/***************************************************************************
* NetworkLayerElement.h -- Class NetworkLayerElement is a generic class *
* that represents a network layer protocol header. Classes like IPv4Header*
* or IPv6Header inherit from it. *
* *
***********************IMPORTANT NMAP LICENSE TERMS************************
* *
* The Nmap Security Scanner is (C) 1996-2011 Insecure.Com LLC. Nmap is *
* also a registered trademark of Insecure.Com LLC. This program is free *
* software; you may redistribute and/or modify it under the terms of the *
* GNU General Public License as published by the Free Software *
* Foundation; Version 2 with the clarifications and exceptions described *
* below. This guarantees your right to use, modify, and redistribute *
* this software under certain conditions. If you wish to embed Nmap *
* technology into proprietary software, we sell alternative licenses *
* (contact sales@insecure.com). Dozens of software vendors already *
* license Nmap technology such as host discovery, port scanning, OS *
* detection, and version detection. *
* *
* Note that the GPL places important restrictions on "derived works", yet *
* it does not provide a detailed definition of that term. To avoid *
* misunderstandings, we consider an application to constitute a *
* "derivative work" for the purpose of this license if it does any of the *
* following: *
* o Integrates source code from Nmap *
* o Reads or includes Nmap copyrighted data files, such as *
* nmap-os-db or nmap-service-probes. *
* o Executes Nmap and parses the results (as opposed to typical shell or *
* execution-menu apps, which simply display raw Nmap output and so are *
* not derivative works.) *
* o Integrates/includes/aggregates Nmap into a proprietary executable *
* installer, such as those produced by InstallShield. *
* o Links to a library or executes a program that does any of the above *
* *
* The term "Nmap" should be taken to also include any portions or derived *
* works of Nmap. This list is not exclusive, but is meant to clarify our *
* interpretation of derived works with some common examples. Our *
* interpretation applies only to Nmap--we don't speak for other people's *
* GPL works. *
* *
* If you have any questions about the GPL licensing restrictions on using *
* Nmap in non-GPL works, we would be happy to help. As mentioned above, *
* we also offer alternative license to integrate Nmap into proprietary *
* applications and appliances. These contracts have been sold to dozens *
* of software vendors, and generally include a perpetual license as well *
* as providing for priority support and updates as well as helping to *
* fund the continued development of Nmap technology. Please email *
* sales@insecure.com for further information. *
* *
* As a special exception to the GPL terms, Insecure.Com LLC grants *
* permission to link the code of this program with any version of the *
* OpenSSL library which is distributed under a license identical to that *
* listed in the included docs/licenses/OpenSSL.txt file, and distribute *
* linked combinations including the two. You must obey the GNU GPL in all *
* respects for all of the code used other than OpenSSL. If you modify *
* this file, you may extend this exception to your version of the file, *
* but you are not obligated to do so. *
* *
* If you received these files with a written license agreement or *
* contract stating terms other than the terms above, then that *
* alternative license agreement takes precedence over these comments. *
* *
* Source is provided to this software because we believe users have a *
* right to know exactly what a program is going to do before they run it. *
* This also allows you to audit the software for security holes (none *
* have been found so far). *
* *
* Source code also allows you to port Nmap to new platforms, fix bugs, *
* and add new features. You are highly encouraged to send your changes *
* to nmap-dev@insecure.org for possible incorporation into the main *
* distribution. By sending these changes to Fyodor or one of the *
* Insecure.Org development mailing lists, it is assumed that you are *
* offering the Nmap Project (Insecure.Com LLC) the unlimited, *
* non-exclusive right to reuse, modify, and relicense the code. Nmap *
* will always be available Open Source, but this is important because the *
* inability to relicense code has caused devastating problems for other *
* Free Software projects (such as KDE and NASM). We also occasionally *
* relicense the code to third parties as discussed above. If you wish to *
* specify special license conditions of your contributions, just say so *
* when you send them. *
* *
* This program is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* General Public License v2.0 for more details at *
* http://www.gnu.org/licenses/gpl-2.0.html , or in the COPYING file *
* included with Nmap. *
* *
***************************************************************************/
/* This code was originally part of the Nping tool. */
#ifndef NETWORKLAYERELEMENT_H
#define NETWORKLAYERELEMENT_H 1
#include "PacketElement.h"
/// class NetworkLayerElement -
class NetworkLayerElement : public PacketElement {
public:
virtual u16 getAddressLength(){
return 0;
}
virtual u8 *getSourceAddress(){
return NULL;
}
virtual u8 *getDestinationAddress(){
return NULL;
}
virtual int setNextHeader(u8 val){
return 0;
}
virtual u8 getNextHeader(){
return 0;
}
};
#endif

101
libnetutil/PacketElement.cc Normal file
View File

@@ -0,0 +1,101 @@
/***************************************************************************
* PacketElement.cc -- The PacketElement Class is a generic class that *
* represents a protocol header or a part of a network packet. Many other *
* classes inherit from it (NetworkLayerElement, TransportLayerElement, *
* etc). *
* *
***********************IMPORTANT NMAP LICENSE TERMS************************
* *
* The Nmap Security Scanner is (C) 1996-2011 Insecure.Com LLC. Nmap is *
* also a registered trademark of Insecure.Com LLC. This program is free *
* software; you may redistribute and/or modify it under the terms of the *
* GNU General Public License as published by the Free Software *
* Foundation; Version 2 with the clarifications and exceptions described *
* below. This guarantees your right to use, modify, and redistribute *
* this software under certain conditions. If you wish to embed Nmap *
* technology into proprietary software, we sell alternative licenses *
* (contact sales@insecure.com). Dozens of software vendors already *
* license Nmap technology such as host discovery, port scanning, OS *
* detection, and version detection. *
* *
* Note that the GPL places important restrictions on "derived works", yet *
* it does not provide a detailed definition of that term. To avoid *
* misunderstandings, we consider an application to constitute a *
* "derivative work" for the purpose of this license if it does any of the *
* following: *
* o Integrates source code from Nmap *
* o Reads or includes Nmap copyrighted data files, such as *
* nmap-os-db or nmap-service-probes. *
* o Executes Nmap and parses the results (as opposed to typical shell or *
* execution-menu apps, which simply display raw Nmap output and so are *
* not derivative works.) *
* o Integrates/includes/aggregates Nmap into a proprietary executable *
* installer, such as those produced by InstallShield. *
* o Links to a library or executes a program that does any of the above *
* *
* The term "Nmap" should be taken to also include any portions or derived *
* works of Nmap. This list is not exclusive, but is meant to clarify our *
* interpretation of derived works with some common examples. Our *
* interpretation applies only to Nmap--we don't speak for other people's *
* GPL works. *
* *
* If you have any questions about the GPL licensing restrictions on using *
* Nmap in non-GPL works, we would be happy to help. As mentioned above, *
* we also offer alternative license to integrate Nmap into proprietary *
* applications and appliances. These contracts have been sold to dozens *
* of software vendors, and generally include a perpetual license as well *
* as providing for priority support and updates as well as helping to *
* fund the continued development of Nmap technology. Please email *
* sales@insecure.com for further information. *
* *
* As a special exception to the GPL terms, Insecure.Com LLC grants *
* permission to link the code of this program with any version of the *
* OpenSSL library which is distributed under a license identical to that *
* listed in the included docs/licenses/OpenSSL.txt file, and distribute *
* linked combinations including the two. You must obey the GNU GPL in all *
* respects for all of the code used other than OpenSSL. If you modify *
* this file, you may extend this exception to your version of the file, *
* but you are not obligated to do so. *
* *
* If you received these files with a written license agreement or *
* contract stating terms other than the terms above, then that *
* alternative license agreement takes precedence over these comments. *
* *
* Source is provided to this software because we believe users have a *
* right to know exactly what a program is going to do before they run it. *
* This also allows you to audit the software for security holes (none *
* have been found so far). *
* *
* Source code also allows you to port Nmap to new platforms, fix bugs, *
* and add new features. You are highly encouraged to send your changes *
* to nmap-dev@insecure.org for possible incorporation into the main *
* distribution. By sending these changes to Fyodor or one of the *
* Insecure.Org development mailing lists, it is assumed that you are *
* offering the Nmap Project (Insecure.Com LLC) the unlimited, *
* non-exclusive right to reuse, modify, and relicense the code. Nmap *
* will always be available Open Source, but this is important because the *
* inability to relicense code has caused devastating problems for other *
* Free Software projects (such as KDE and NASM). We also occasionally *
* relicense the code to third parties as discussed above. If you wish to *
* specify special license conditions of your contributions, just say so *
* when you send them. *
* *
* This program is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* General Public License v2.0 for more details at *
* http://www.gnu.org/licenses/gpl-2.0.html , or in the COPYING file *
* included with Nmap. *
* *
***************************************************************************/
/* This code was originally part of the Nping tool. */
#include "PacketElement.h"
PacketElement::PacketElement(){
next=NULL; /* It's very important these get initialized to NULL */
prev=NULL;
length=0;
} /* End of PacketElement constructor */

299
libnetutil/PacketElement.h Normal file
View File

@@ -0,0 +1,299 @@
/***************************************************************************
* PacketElement.h -- The PacketElement Class is a generic class that *
* represents a protocol header or a part of a network packet. Many other *
* classes inherit from it (NetworkLayerElement, TransportLayerElement, *
* etc). *
* *
***********************IMPORTANT NMAP LICENSE TERMS************************
* *
* The Nmap Security Scanner is (C) 1996-2011 Insecure.Com LLC. Nmap is *
* also a registered trademark of Insecure.Com LLC. This program is free *
* software; you may redistribute and/or modify it under the terms of the *
* GNU General Public License as published by the Free Software *
* Foundation; Version 2 with the clarifications and exceptions described *
* below. This guarantees your right to use, modify, and redistribute *
* this software under certain conditions. If you wish to embed Nmap *
* technology into proprietary software, we sell alternative licenses *
* (contact sales@insecure.com). Dozens of software vendors already *
* license Nmap technology such as host discovery, port scanning, OS *
* detection, and version detection. *
* *
* Note that the GPL places important restrictions on "derived works", yet *
* it does not provide a detailed definition of that term. To avoid *
* misunderstandings, we consider an application to constitute a *
* "derivative work" for the purpose of this license if it does any of the *
* following: *
* o Integrates source code from Nmap *
* o Reads or includes Nmap copyrighted data files, such as *
* nmap-os-db or nmap-service-probes. *
* o Executes Nmap and parses the results (as opposed to typical shell or *
* execution-menu apps, which simply display raw Nmap output and so are *
* not derivative works.) *
* o Integrates/includes/aggregates Nmap into a proprietary executable *
* installer, such as those produced by InstallShield. *
* o Links to a library or executes a program that does any of the above *
* *
* The term "Nmap" should be taken to also include any portions or derived *
* works of Nmap. This list is not exclusive, but is meant to clarify our *
* interpretation of derived works with some common examples. Our *
* interpretation applies only to Nmap--we don't speak for other people's *
* GPL works. *
* *
* If you have any questions about the GPL licensing restrictions on using *
* Nmap in non-GPL works, we would be happy to help. As mentioned above, *
* we also offer alternative license to integrate Nmap into proprietary *
* applications and appliances. These contracts have been sold to dozens *
* of software vendors, and generally include a perpetual license as well *
* as providing for priority support and updates as well as helping to *
* fund the continued development of Nmap technology. Please email *
* sales@insecure.com for further information. *
* *
* As a special exception to the GPL terms, Insecure.Com LLC grants *
* permission to link the code of this program with any version of the *
* OpenSSL library which is distributed under a license identical to that *
* listed in the included docs/licenses/OpenSSL.txt file, and distribute *
* linked combinations including the two. You must obey the GNU GPL in all *
* respects for all of the code used other than OpenSSL. If you modify *
* this file, you may extend this exception to your version of the file, *
* but you are not obligated to do so. *
* *
* If you received these files with a written license agreement or *
* contract stating terms other than the terms above, then that *
* alternative license agreement takes precedence over these comments. *
* *
* Source is provided to this software because we believe users have a *
* right to know exactly what a program is going to do before they run it. *
* This also allows you to audit the software for security holes (none *
* have been found so far). *
* *
* Source code also allows you to port Nmap to new platforms, fix bugs, *
* and add new features. You are highly encouraged to send your changes *
* to nmap-dev@insecure.org for possible incorporation into the main *
* distribution. By sending these changes to Fyodor or one of the *
* Insecure.Org development mailing lists, it is assumed that you are *
* offering the Nmap Project (Insecure.Com LLC) the unlimited, *
* non-exclusive right to reuse, modify, and relicense the code. Nmap *
* will always be available Open Source, but this is important because the *
* inability to relicense code has caused devastating problems for other *
* Free Software projects (such as KDE and NASM). We also occasionally *
* relicense the code to third parties as discussed above. If you wish to *
* specify special license conditions of your contributions, just say so *
* when you send them. *
* *
* This program is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* General Public License v2.0 for more details at *
* http://www.gnu.org/licenses/gpl-2.0.html , or in the COPYING file *
* included with Nmap. *
* *
***************************************************************************/
/* This code was originally part of the Nping tool. */
#ifndef PACKETELEMENT_H
#define PACKETELEMENT_H 1
#include "nbase.h"
#include "netutil.h"
#define HEADER_TYPE_IPv6_HOPOPT 0 /* IPv6 Hop-by-Hop Option */
#define HEADER_TYPE_ICMPv4 1 /* ICMP Internet Control Message */
#define HEADER_TYPE_IGMP 2 /* IGMP Internet Group Management */
#define HEADER_TYPE_IPv4 4 /* IPv4 IPv4 encapsulation */
#define HEADER_TYPE_TCP 6 /* TCP Transmission Control */
#define HEADER_TYPE_EGP 8 /* EGP Exterior Gateway Protocol */
#define HEADER_TYPE_UDP 17 /* UDP User Datagram */
#define HEADER_TYPE_IPv6 41 /* IPv6 IPv6 encapsulation */
#define HEADER_TYPE_IPv6_ROUTE 43 /* IPv6-Route Routing Header for IPv6 */
#define HEADER_TYPE_IPv6_FRAG 44 /* IPv6-Frag Fragment Header for IPv6 */
#define HEADER_TYPE_GRE 47 /* GRE General Routing Encapsulation */
#define HEADER_TYPE_ESP 50 /* ESP Encap Security Payload */
#define HEADER_TYPE_AH 51 /* AH Authentication Header */
#define HEADER_TYPE_ICMPv6 58 /* IPv6-ICMP ICMP for IPv6 */
#define HEADER_TYPE_IPv6_NONXT 59 /* IPv6-NoNxt No Next Header for IPv6 */
#define HEADER_TYPE_IPv6_OPTS 60 /* IPv6-Opts IPv6 Destination Options */
#define HEADER_TYPE_EIGRP 88 /* EIGRP */
#define HEADER_TYPE_ETHERNET 97 /* Ethernet */
#define HEADER_TYPE_L2TP 115 /* L2TP Layer Two Tunneling Protocol */
#define HEADER_TYPE_SCTP 132 /* SCTP Stream Control Transmission P. */
#define HEADER_TYPE_IPv6_MOBILE 135 /* Mobility Header */
#define HEADER_TYPE_MPLS_IN_IP 137 /* MPLS-in-IP */
#define HEADER_TYPE_ARP 2054 /* ARP Address Resolution Protocol */
#define HEADER_TYPE_ICMPv6_OPTION 9997 /* ICMPv6 option */
#define HEADER_TYPE_NEP 9998 /* Nping Echo Protocol */
#define HEADER_TYPE_RAW_DATA 9999 /* Raw unknown data */
#define PRINT_DETAIL_LOW 1
#define PRINT_DETAIL_MED 2
#define PRINT_DETAIL_HIGH 3
#define DEFAULT_PRINT_DETAIL (PRINT_DETAIL_LOW)
#define DEFAULT_PRINT_DESCRIPTOR stdout
class PacketElement {
protected:
int length;
PacketElement *next; /**< Next PacketElement (next proto header) */
PacketElement *prev; /**< Prev PacketElement (previous proto header) */
public:
PacketElement();
virtual ~PacketElement(){
} /* End of PacketElement destructor */
/** This function MUST be overwritten on ANY class that inherits from
* this one. Otherwise getBinaryBuffer will fail */
virtual u8 * getBufferPointer(){
netutil_fatal("getBufferPointer(): Attempting to use superclass PacketElement method.\n");
return NULL;
} /* End of getBufferPointer() */
/** Returns a buffer that contains the header of the packet + all the
* lower level headers and payload. Returned buffer should be ok to be
* passes to a send() call to be transferred trough a socket.
* @return a pointer to a free()able buffer that contains packet's binary
* data.
* @warning If there are linked elements, their getBinaryBuffer() method
* will be called recursively and the buffers that they return WILL be
* free()d as soon as we copy the data in our own allocated buffer.
* @warning Calls to this method may not ve very efficient since they
* always involved a few malloc()s and free()s. If you want efficiency
* use dumpToBinaryBuffer(); */
virtual u8 * getBinaryBuffer(){
u8 *ourbuff=NULL;
u8 *othersbuff=NULL;
u8 *totalbuff=NULL;
long otherslen=0;
/* Get our own buffer address */
if ( (ourbuff=getBufferPointer()) == NULL ){
netutil_fatal("getBinaryBuffer(): Couldn't get own data pointer\n");
}
if( next != NULL ){ /* There is some other packet element */
othersbuff = next->getBinaryBuffer();
otherslen=next->getLen();
totalbuff=(u8 *)safe_zalloc(otherslen + length);
memcpy(totalbuff, ourbuff, length);
memcpy(totalbuff+length, othersbuff, otherslen);
free(othersbuff);
}else{
totalbuff=(u8 *)safe_zalloc(length);
memcpy(totalbuff, ourbuff, length);
}
return totalbuff;
} /* End of getBinaryBuffer() */
virtual int dumpToBinaryBuffer(u8* dst, int maxlen){
u8 *ourbuff=NULL;
long ourlength=0;
/* Get our own buffer address and length */
if ( (ourbuff=getBufferPointer()) == NULL || (ourlength=this->length) < 0 )
netutil_fatal("getBinaryBuffer(): Couldn't get own data pointer\n");
/* Copy our part of the buffer */
if ( maxlen < ourlength )
netutil_fatal("getBinaryBuffer(): Packet exceeds maximum length %d\n", maxlen);
memcpy( dst, ourbuff, ourlength);
/* If there are more elements, tell them to copy their part */
if( next!= NULL ){
next->dumpToBinaryBuffer(dst+ourlength, maxlen-ourlength);
}
return this->getLen();
} /* End of dumpToBinaryBuffer() */
/** Does the same as the previous one but it stores the length of the
* return buffer on the memory pointed by the supplied int pointer. */
virtual u8 * getBinaryBuffer(int *len){
u8 *buff = getBinaryBuffer();
if( len != NULL )
*len = getLen();
return buff;
} /* End of getBinaryBuffer() */
/** Returns the lenght of this PacketElement + the length of all the
* PacketElements that are next to it (are linked trough the "next"
* attribute). So for example, if we have IPv4Header p1, linked to
* a TCPHeader p2, representing a simple TCP SYN with no options,
* a call to p1.getLen() will return 20 (IP header with no options) + 20
* (TCP header with no options) = 40 bytes. */
int getLen() const {
/* If we have some other packet element linked, get its length */
if (next!=NULL)
return length + next->getLen();
else
return length;
} /* End of getLen() */
/** Returns the address of the next PacketElement that is linked to this */
virtual PacketElement *getNextElement() const {
return next;
} /* End of getNextElement() */
/** Links current object with the next header in the protocol chain. Note
* that this method also links the next element with this one, calling
* setPrevElement(). */
virtual int setNextElement(PacketElement *n){
next=n;
if(next!=NULL)
next->setPrevElement(this);
return OP_SUCCESS;
} /* End of setNextElement() */
/** Sets attribute prev with the supplied pointer value.
* @warning Supplied pointer must point to a PacketElement object or
* an object that inherits from it. */
virtual int setPrevElement(PacketElement *n){
this->prev=n;
return OP_SUCCESS;
} /* End of setPrevElement() */
/** Returns the address of the previous PacketElement that is linked to
* this one.
* @warning In many cases this function will return NULL since there is
* a high probability that the user of this class does not link
* PacketElements in both directions. Normally one would set attribute
* "next" of an IPHeader object to the TCPHeader that follows it, but
* not the other way around. */
virtual PacketElement *getPrevElement(){
return prev;
} /* End of getPrevElement() */
/** This method should be overwritten by any class that inherits from
* PacketElement. It should print the object contents and then call
* this->next->print(), providing this->next!=NULL */
virtual int print(FILE *output, int detail) const {
if(this->next!=NULL)
this->next->print(output, detail);
return OP_SUCCESS;
} /* End of printf() */
virtual int print() const {
return print(DEFAULT_PRINT_DESCRIPTOR, DEFAULT_PRINT_DETAIL);
}
virtual int print(int detail) const {
return print(DEFAULT_PRINT_DESCRIPTOR, detail);
}
virtual void print_separator(FILE *output, int detail) const {
fprintf(output, " ");
}
/* Returns the type of protocol an object represents. This method MUST
* be overwritten by all children. */
virtual int protocol_id() const = 0;
};
#endif

1708
libnetutil/PacketParser.cc Normal file

File diff suppressed because it is too large Load Diff

162
libnetutil/PacketParser.h Normal file
View File

@@ -0,0 +1,162 @@
/***************************************************************************
* PacketParser.h -- The PacketParser Class offers methods to parse *
* received network packets. Its main purpose is to facilitate the *
* conversion of raw sequences of bytes into chains of objects of the *
* PacketElement family. *
* *
***********************IMPORTANT NMAP LICENSE TERMS************************
* *
* The Nmap Security Scanner is (C) 1996-2010 Insecure.Com LLC. Nmap is *
* also a registered trademark of Insecure.Com LLC. This program is free *
* software; you may redistribute and/or modify it under the terms of the *
* GNU General Public License as published by the Free Software *
* Foundation; Version 2 with the clarifications and exceptions described *
* below. This guarantees your right to use, modify, and redistribute *
* this software under certain conditions. If you wish to embed Nmap *
* technology into proprietary software, we sell alternative licenses *
* (contact sales@insecure.com). Dozens of software vendors already *
* license Nmap technology such as host discovery, port scanning, OS *
* detection, and version detection. *
* *
* Note that the GPL places important restrictions on "derived works", yet *
* it does not provide a detailed definition of that term. To avoid *
* misunderstandings, we consider an application to constitute a *
* "derivative work" for the purpose of this license if it does any of the *
* following: *
* o Integrates source code from Nmap *
* o Reads or includes Nmap copyrighted data files, such as *
* nmap-os-db or nmap-service-probes. *
* o Executes Nmap and parses the results (as opposed to typical shell or *
* execution-menu apps, which simply display raw Nmap output and so are *
* not derivative works.) *
* o Integrates/includes/aggregates Nmap into a proprietary executable *
* installer, such as those produced by InstallShield. *
* o Links to a library or executes a program that does any of the above *
* *
* The term "Nmap" should be taken to also include any portions or derived *
* works of Nmap. This list is not exclusive, but is meant to clarify our *
* interpretation of derived works with some common examples. Our *
* interpretation applies only to Nmap--we don't speak for other people's *
* GPL works. *
* *
* If you have any questions about the GPL licensing restrictions on using *
* Nmap in non-GPL works, we would be happy to help. As mentioned above, *
* we also offer alternative license to integrate Nmap into proprietary *
* applications and appliances. These contracts have been sold to dozens *
* of software vendors, and generally include a perpetual license as well *
* as providing for priority support and updates as well as helping to *
* fund the continued development of Nmap technology. Please email *
* sales@insecure.com for further information. *
* *
* As a special exception to the GPL terms, Insecure.Com LLC grants *
* permission to link the code of this program with any version of the *
* OpenSSL library which is distributed under a license identical to that *
* listed in the included docs/licenses/OpenSSL.txt file, and distribute *
* linked combinations including the two. You must obey the GNU GPL in all *
* respects for all of the code used other than OpenSSL. If you modify *
* this file, you may extend this exception to your version of the file, *
* but you are not obligated to do so. *
* *
* If you received these files with a written license agreement or *
* contract stating terms other than the terms above, then that *
* alternative license agreement takes precedence over these comments. *
* *
* Source is provided to this software because we believe users have a *
* right to know exactly what a program is going to do before they run it. *
* This also allows you to audit the software for security holes (none *
* have been found so far). *
* *
* Source code also allows you to port Nmap to new platforms, fix bugs, *
* and add new features. You are highly encouraged to send your changes *
* to nmap-dev@insecure.org for possible incorporation into the main *
* distribution. By sending these changes to Fyodor or one of the *
* Insecure.Org development mailing lists, it is assumed that you are *
* offering the Nmap Project (Insecure.Com LLC) the unlimited, *
* non-exclusive right to reuse, modify, and relicense the code. Nmap *
* will always be available Open Source, but this is important because the *
* inability to relicense code has caused devastating problems for other *
* Free Software projects (such as KDE and NASM). We also occasionally *
* relicense the code to third parties as discussed above. If you wish to *
* specify special license conditions of your contributions, just say so *
* when you send them. *
* *
* This program is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* General Public License v2.0 for more details at *
* http://www.gnu.org/licenses/gpl-2.0.html , or in the COPYING file *
* included with Nmap. *
* *
***************************************************************************/
/* This code was originally part of the Nping tool. */
#ifndef __PACKETPARSER_H__
#define __PACKETPARSER_H__ 1
#include "ApplicationLayerElement.h"
#include "ARPHeader.h"
#include "DataLinkLayerElement.h"
#include "EthernetHeader.h"
#include "ICMPHeader.h"
#include "ICMPv4Header.h"
#include "ICMPv6Header.h"
#include "ICMPv6Option.h"
#include "ICMPv6RRBody.h"
#include "IPv4Header.h"
#include "IPv6Header.h"
#include "NetworkLayerElement.h"
#include "PacketElement.h"
#include "RawData.h"
#include "TCPHeader.h"
#include "TransportLayerElement.h"
#include "UDPHeader.h"
#include "HopByHopHeader.h"
#include "DestOptsHeader.h"
#include "FragmentHeader.h"
#include "RoutingHeader.h"
#define LINK_LAYER 2
#define NETWORK_LAYER 3
#define TRANSPORT_LAYER 4
#define APPLICATION_LAYER 5
#define EXTHEADERS_LAYER 6
typedef struct header_type_string{
u32 type;
const char *str;
}header_type_string_t;
typedef struct packet_type{
u32 type;
u32 length;
}pkt_type_t;
class PacketParser {
private:
public:
/* Misc */
PacketParser();
~PacketParser();
void reset();
static const char *header_type2string(int val);
static pkt_type_t *parse_packet(const u8 *pkt, size_t pktlen, bool eth_included);
static int dummy_print_packet_type(const u8 *pkt, size_t pktlen, bool eth_included); /* TODO: remove */
static int dummy_print_packet(const u8 *pkt, size_t pktlen, bool eth_included); /* TODO: remove */
static int payload_offset(const u8 *pkt, size_t pktlen, bool link_included);
static PacketElement *split(const u8 *pkt, size_t pktlen, bool eth_included);
static PacketElement *split(const u8 *pkt, size_t pktlen);
static int freePacketChain(PacketElement *first);
static const char *test_packet_parser(PacketElement *test_pkt);
static bool is_response(PacketElement *sent, PacketElement *rcvd);
}; /* End of class PacketParser */
#endif /* __PACKETPARSER_H__ */

211
libnetutil/RawData.cc Normal file
View File

@@ -0,0 +1,211 @@
/***************************************************************************
* RawData.cc -- The RawData Class represents a network packet payload. It *
* is essentially a single buffer that may contain either random data or *
* caller supplied data. This class can be used, for example, to be linked *
* to a UDP datagram. *
* *
***********************IMPORTANT NMAP LICENSE TERMS************************
* *
* The Nmap Security Scanner is (C) 1996-2011 Insecure.Com LLC. Nmap is *
* also a registered trademark of Insecure.Com LLC. This program is free *
* software; you may redistribute and/or modify it under the terms of the *
* GNU General Public License as published by the Free Software *
* Foundation; Version 2 with the clarifications and exceptions described *
* below. This guarantees your right to use, modify, and redistribute *
* this software under certain conditions. If you wish to embed Nmap *
* technology into proprietary software, we sell alternative licenses *
* (contact sales@insecure.com). Dozens of software vendors already *
* license Nmap technology such as host discovery, port scanning, OS *
* detection, and version detection. *
* *
* Note that the GPL places important restrictions on "derived works", yet *
* it does not provide a detailed definition of that term. To avoid *
* misunderstandings, we consider an application to constitute a *
* "derivative work" for the purpose of this license if it does any of the *
* following: *
* o Integrates source code from Nmap *
* o Reads or includes Nmap copyrighted data files, such as *
* nmap-os-db or nmap-service-probes. *
* o Executes Nmap and parses the results (as opposed to typical shell or *
* execution-menu apps, which simply display raw Nmap output and so are *
* not derivative works.) *
* o Integrates/includes/aggregates Nmap into a proprietary executable *
* installer, such as those produced by InstallShield. *
* o Links to a library or executes a program that does any of the above *
* *
* The term "Nmap" should be taken to also include any portions or derived *
* works of Nmap. This list is not exclusive, but is meant to clarify our *
* interpretation of derived works with some common examples. Our *
* interpretation applies only to Nmap--we don't speak for other people's *
* GPL works. *
* *
* If you have any questions about the GPL licensing restrictions on using *
* Nmap in non-GPL works, we would be happy to help. As mentioned above, *
* we also offer alternative license to integrate Nmap into proprietary *
* applications and appliances. These contracts have been sold to dozens *
* of software vendors, and generally include a perpetual license as well *
* as providing for priority support and updates as well as helping to *
* fund the continued development of Nmap technology. Please email *
* sales@insecure.com for further information. *
* *
* As a special exception to the GPL terms, Insecure.Com LLC grants *
* permission to link the code of this program with any version of the *
* OpenSSL library which is distributed under a license identical to that *
* listed in the included docs/licenses/OpenSSL.txt file, and distribute *
* linked combinations including the two. You must obey the GNU GPL in all *
* respects for all of the code used other than OpenSSL. If you modify *
* this file, you may extend this exception to your version of the file, *
* but you are not obligated to do so. *
* *
* If you received these files with a written license agreement or *
* contract stating terms other than the terms above, then that *
* alternative license agreement takes precedence over these comments. *
* *
* Source is provided to this software because we believe users have a *
* right to know exactly what a program is going to do before they run it. *
* This also allows you to audit the software for security holes (none *
* have been found so far). *
* *
* Source code also allows you to port Nmap to new platforms, fix bugs, *
* and add new features. You are highly encouraged to send your changes *
* to nmap-dev@insecure.org for possible incorporation into the main *
* distribution. By sending these changes to Fyodor or one of the *
* Insecure.Org development mailing lists, it is assumed that you are *
* offering the Nmap Project (Insecure.Com LLC) the unlimited, *
* non-exclusive right to reuse, modify, and relicense the code. Nmap *
* will always be available Open Source, but this is important because the *
* inability to relicense code has caused devastating problems for other *
* Free Software projects (such as KDE and NASM). We also occasionally *
* relicense the code to third parties as discussed above. If you wish to *
* specify special license conditions of your contributions, just say so *
* when you send them. *
* *
* This program is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* General Public License v2.0 for more details at *
* http://www.gnu.org/licenses/gpl-2.0.html , or in the COPYING file *
* included with Nmap. *
* *
***************************************************************************/
/* This code was originally part of the Nping tool. */
#include "RawData.h"
/******************************************************************************/
/* CONTRUCTORS, DESTRUCTORS AND INITIALIZATION METHODS */
/******************************************************************************/
RawData::RawData(){
this->reset();
} /* End of RawData contructor */
RawData::~RawData(){
if(this->data!=NULL){
free(this->data);
this->data=NULL;
}
} /* End of RawData destructor */
/** Sets every attribute to its default value */
void RawData::reset(){
this->data=NULL;
this->length=0;
} /* End of reset() */
/******************************************************************************/
/* PacketElement:: OVERWRITTEN METHODS */
/******************************************************************************/
u8 * RawData::getBufferPointer(){
return this->getBufferPointer(NULL);
} /* End of getBufferPointer() */
u8 * RawData::getBufferPointer(int *mylen){
if(mylen!=NULL)
*mylen=this->length;
return this->data;
} /* End of getBufferPointer() */
/** Added for consistency with the rest of classes of the PacketElement family. */
int RawData::storeRecvData(const u8 *buf, size_t len){
return this->store(buf, len);
} /* End of storeRecvData() */
/* Returns a protocol identifier. This is used by packet parsing funtions
* that return linked lists of PacketElement objects, to determine the protocol
* the object represents. */
int RawData::protocol_id() const {
return HEADER_TYPE_RAW_DATA;
} /* End of protocol_id() */
/** Determines if the data stored in the object after an storeRecvData() call
* is valid and safe to use. This mainly checks the length of the data but may
* also test the value of certain protocol fields to ensure their correctness.
* @return the length, in bytes, of the header, if its found to be valid or
* OP_FAILURE (-1) otherwise. */
int RawData::validate(){
return this->length;
} /* End of validate() */
/** Prints the contents of the header and calls print() on the next protocol
* header in the chain (if there is any).
* @return OP_SUCCESS on success and OP_FAILURE in case of error. */
int RawData::print(FILE *output, int detail) const {
if(detail<=PRINT_DETAIL_MED){
fprintf(output, "Data[");
fprintf(output, "%d byte%s]", this->length, (this->length!=1)? "s":"");
}else{
// Print hex dump
fprintf(output, "Data[--HEXDUMP-- %d byte%s]", this->length, (this->length!=1)? "s":"");
// @todo UNIMPLEMENTED. I don't want to use libnetutil's print_hexdump()
// here because it introduces dependencies.
}
if(this->next!=NULL){
print_separator(output, detail);
next->print(output, detail);
}
return OP_SUCCESS;
} /* End of print() */
/******************************************************************************/
/* PROTOCOL-SPECIFIC METHODS */
/******************************************************************************/
int RawData::store(const u8 *buf, size_t len){
/* If buffer had already been set, try to reuse it. */
if(this->data!=NULL){
if( this->length >= (int)len ){
memcpy(this->data, buf, len);
this->length=(int)len;
return OP_SUCCESS;
}else{
free(this->data);
}
}
if( (this->data=(u8 *)calloc(len, sizeof(u8)))==NULL )
return OP_FAILURE;
memcpy(this->data, buf, len);
this->length=(int)len;
return OP_SUCCESS;
} /* End of store() */
int RawData::store(const char *str){
if(str==NULL)
return OP_FAILURE;
else
return this->store((const u8*)str, strlen(str));
} /* End of store() */

121
libnetutil/RawData.h Normal file
View File

@@ -0,0 +1,121 @@
/***************************************************************************
* RawData.h -- The RawData Class represents a network packet payload. It *
* is essentially a single buffer that may contain either random data or *
* caller supplied data. This class can be used, for example, to be linked *
* to a UDP datagram. *
* *
***********************IMPORTANT NMAP LICENSE TERMS************************
* *
* The Nmap Security Scanner is (C) 1996-2011 Insecure.Com LLC. Nmap is *
* also a registered trademark of Insecure.Com LLC. This program is free *
* software; you may redistribute and/or modify it under the terms of the *
* GNU General Public License as published by the Free Software *
* Foundation; Version 2 with the clarifications and exceptions described *
* below. This guarantees your right to use, modify, and redistribute *
* this software under certain conditions. If you wish to embed Nmap *
* technology into proprietary software, we sell alternative licenses *
* (contact sales@insecure.com). Dozens of software vendors already *
* license Nmap technology such as host discovery, port scanning, OS *
* detection, and version detection. *
* *
* Note that the GPL places important restrictions on "derived works", yet *
* it does not provide a detailed definition of that term. To avoid *
* misunderstandings, we consider an application to constitute a *
* "derivative work" for the purpose of this license if it does any of the *
* following: *
* o Integrates source code from Nmap *
* o Reads or includes Nmap copyrighted data files, such as *
* nmap-os-db or nmap-service-probes. *
* o Executes Nmap and parses the results (as opposed to typical shell or *
* execution-menu apps, which simply display raw Nmap output and so are *
* not derivative works.) *
* o Integrates/includes/aggregates Nmap into a proprietary executable *
* installer, such as those produced by InstallShield. *
* o Links to a library or executes a program that does any of the above *
* *
* The term "Nmap" should be taken to also include any portions or derived *
* works of Nmap. This list is not exclusive, but is meant to clarify our *
* interpretation of derived works with some common examples. Our *
* interpretation applies only to Nmap--we don't speak for other people's *
* GPL works. *
* *
* If you have any questions about the GPL licensing restrictions on using *
* Nmap in non-GPL works, we would be happy to help. As mentioned above, *
* we also offer alternative license to integrate Nmap into proprietary *
* applications and appliances. These contracts have been sold to dozens *
* of software vendors, and generally include a perpetual license as well *
* as providing for priority support and updates as well as helping to *
* fund the continued development of Nmap technology. Please email *
* sales@insecure.com for further information. *
* *
* As a special exception to the GPL terms, Insecure.Com LLC grants *
* permission to link the code of this program with any version of the *
* OpenSSL library which is distributed under a license identical to that *
* listed in the included docs/licenses/OpenSSL.txt file, and distribute *
* linked combinations including the two. You must obey the GNU GPL in all *
* respects for all of the code used other than OpenSSL. If you modify *
* this file, you may extend this exception to your version of the file, *
* but you are not obligated to do so. *
* *
* If you received these files with a written license agreement or *
* contract stating terms other than the terms above, then that *
* alternative license agreement takes precedence over these comments. *
* *
* Source is provided to this software because we believe users have a *
* right to know exactly what a program is going to do before they run it. *
* This also allows you to audit the software for security holes (none *
* have been found so far). *
* *
* Source code also allows you to port Nmap to new platforms, fix bugs, *
* and add new features. You are highly encouraged to send your changes *
* to nmap-dev@insecure.org for possible incorporation into the main *
* distribution. By sending these changes to Fyodor or one of the *
* Insecure.Org development mailing lists, it is assumed that you are *
* offering the Nmap Project (Insecure.Com LLC) the unlimited, *
* non-exclusive right to reuse, modify, and relicense the code. Nmap *
* will always be available Open Source, but this is important because the *
* inability to relicense code has caused devastating problems for other *
* Free Software projects (such as KDE and NASM). We also occasionally *
* relicense the code to third parties as discussed above. If you wish to *
* specify special license conditions of your contributions, just say so *
* when you send them. *
* *
* This program is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* General Public License v2.0 for more details at *
* http://www.gnu.org/licenses/gpl-2.0.html , or in the COPYING file *
* included with Nmap. *
* *
***************************************************************************/
/* This code was originally part of the Nping tool. */
#ifndef RAWDATA_H
#define RAWDATA_H 1
#include "ApplicationLayerElement.h"
class RawData : public ApplicationLayerElement {
private:
u8 *data;
public:
RawData();
~RawData();
void reset();
u8 *getBufferPointer();
int storeRecvData(const u8 *buf, size_t len);
int protocol_id() const;
int validate();
int print(FILE *output, int detail) const;
u8 *getBufferPointer(int *mylen);
int store(const u8 *buf, size_t len);
int store(const char *str);
};
#endif

340
libnetutil/RoutingHeader.cc Normal file
View File

@@ -0,0 +1,340 @@
/***************************************************************************
* RoutingHeader.cc -- The RoutingHeader Class represents an IPv6 Routing *
* extension header. *
***********************IMPORTANT NMAP LICENSE TERMS************************
* *
* The Nmap Security Scanner is (C) 1996-2011 Insecure.Com LLC. Nmap is *
* also a registered trademark of Insecure.Com LLC. This program is free *
* software; you may redistribute and/or modify it under the terms of the *
* GNU General Public License as published by the Free Software *
* Foundation; Version 2 with the clarifications and exceptions described *
* below. This guarantees your right to use, modify, and redistribute *
* this software under certain conditions. If you wish to embed Nmap *
* technology into proprietary software, we sell alternative licenses *
* (contact sales@insecure.com). Dozens of software vendors already *
* license Nmap technology such as host discovery, port scanning, OS *
* detection, and version detection. *
* *
* Note that the GPL places important restrictions on "derived works", yet *
* it does not provide a detailed definition of that term. To avoid *
* misunderstandings, we consider an application to constitute a *
* "derivative work" for the purpose of this license if it does any of the *
* following: *
* o Integrates source code from Nmap *
* o Reads or includes Nmap copyrighted data files, such as *
* nmap-os-db or nmap-service-probes. *
* o Executes Nmap and parses the results (as opposed to typical shell or *
* execution-menu apps, which simply display raw Nmap output and so are *
* not derivative works.) *
* o Integrates/includes/aggregates Nmap into a proprietary executable *
* installer, such as those produced by InstallShield. *
* o Links to a library or executes a program that does any of the above *
* *
* The term "Nmap" should be taken to also include any portions or derived *
* works of Nmap. This list is not exclusive, but is meant to clarify our *
* interpretation of derived works with some common examples. Our *
* interpretation applies only to Nmap--we don't speak for other people's *
* GPL works. *
* *
* If you have any questions about the GPL licensing restrictions on using *
* Nmap in non-GPL works, we would be happy to help. As mentioned above, *
* we also offer alternative license to integrate Nmap into proprietary *
* applications and appliances. These contracts have been sold to dozens *
* of software vendors, and generally include a perpetual license as well *
* as providing for priority support and updates as well as helping to *
* fund the continued development of Nmap technology. Please email *
* sales@insecure.com for further information. *
* *
* As a special exception to the GPL terms, Insecure.Com LLC grants *
* permission to link the code of this program with any version of the *
* OpenSSL library which is distributed under a license identical to that *
* listed in the included docs/licenses/OpenSSL.txt file, and distribute *
* linked combinations including the two. You must obey the GNU GPL in all *
* respects for all of the code used other than OpenSSL. If you modify *
* this file, you may extend this exception to your version of the file, *
* but you are not obligated to do so. *
* *
* If you received these files with a written license agreement or *
* contract stating terms other than the terms above, then that *
* alternative license agreement takes precedence over these comments. *
* *
* Source is provided to this software because we believe users have a *
* right to know exactly what a program is going to do before they run it. *
* This also allows you to audit the software for security holes (none *
* have been found so far). *
* *
* Source code also allows you to port Nmap to new platforms, fix bugs, *
* and add new features. You are highly encouraged to send your changes *
* to nmap-dev@insecure.org for possible incorporation into the main *
* distribution. By sending these changes to Fyodor or one of the *
* Insecure.Org development mailing lists, it is assumed that you are *
* offering the Nmap Project (Insecure.Com LLC) the unlimited, *
* non-exclusive right to reuse, modify, and relicense the code. Nmap *
* will always be available Open Source, but this is important because the *
* inability to relicense code has caused devastating problems for other *
* Free Software projects (such as KDE and NASM). We also occasionally *
* relicense the code to third parties as discussed above. If you wish to *
* specify special license conditions of your contributions, just say so *
* when you send them. *
* *
* This program is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* General Public License v2.0 for more details at *
* http://www.gnu.org/licenses/gpl-2.0.html , or in the COPYING file *
* included with Nmap. *
* *
***************************************************************************/
/* This code was originally part of the Nping tool. */
#include "RoutingHeader.h"
#include <assert.h>
/******************************************************************************/
/* CONTRUCTORS, DESTRUCTORS AND INITIALIZATION METHODS */
/******************************************************************************/
RoutingHeader::RoutingHeader() {
this->reset();
} /* End of RoutingHeader constructor */
RoutingHeader::~RoutingHeader() {
} /* End of RoutingHeader destructor */
/** Sets every attribute to its default value */
void RoutingHeader::reset(){
memset(&this->h, 0, sizeof(nping_ipv6_ext_routing_hdr_t));
this->length=ROUTING_HEADER_MIN_LEN;
this->curr_addr=(u8 *)this->h.data;
} /* End of reset() */
/******************************************************************************/
/* PacketElement:: OVERWRITTEN METHODS */
/******************************************************************************/
/** @warning This method is essential for the superclass getBinaryBuffer()
* method to work. Do NOT change a thing unless you know what you're doing */
u8 *RoutingHeader::getBufferPointer(){
return (u8*)(&this->h);
} /* End of getBufferPointer() */
/** Stores supplied packet in the internal buffer so the information
* can be accessed using the standard get & set methods.
* @warning The RoutingHeader class is able to hold a maximum of
* sizeof(nping_icmpv6_hdr_t) bytes. If the supplied buffer is longer than
* that, only the first 1508 bytes will be stored in the internal buffer.
* @warning Supplied len MUST be at least 8 bytes (min ICMPv6 header length).
* @return OP_SUCCESS on success and OP_FAILURE in case of error */
int RoutingHeader::storeRecvData(const u8 *buf, size_t len){
if(buf==NULL || len<ROUTING_HEADER_MIN_LEN){
this->length=0;
return OP_FAILURE;
}else{
/* Store the first 4 bytes, so we can access lenght and routing type */
memcpy(&(this->h), buf, 4);
/* Our behaviour is different depending on the routing type. */
switch(this->h.type){
/* Routing Type 0 (deprecated by RFC 5095)*/
case 0:
/* Type 0 has a variable length, but the value of its HdrExtLen
* field must be even (because it must be a multiple of the
* IPv6 address size). We also make sure that the received buffer
* has as many bytes as the HdrExtLen field says it has, and
* that it doesn't exceed the maximum number of octets we
* can store in this object. */
if(this->h.len%2==1 || ((unsigned int)(this->h.len+1))*8 > len || (this->h.len+1)*8 > ROUTING_HEADER_MAX_LEN){
this->length=0;
return OP_FAILURE;
}else{
int pkt_len=(this->h.len+1)*8;
this->reset();
this->length=pkt_len;
memcpy(&(this->h), buf, this->length);
return OP_SUCCESS;
}
break;
/* Routing Type 2 (For IPv6 Mobility. See RFC 6275) */
case 2:
/* Type 2 has a fixed length. If we have that many octets, store
* them. We'll perform validation later in validate(). */
if(len<ROUTING_TYPE_2_HEADER_LEN){
this->length=0;
return OP_FAILURE;
}else{
this->reset();
memcpy(&(this->h), buf, ROUTING_TYPE_2_HEADER_LEN);
this->length=ROUTING_TYPE_2_HEADER_LEN;
return OP_SUCCESS;
}
break;
/* Unknown routing type */
default:
/* If this is some routing type that we don't know about, we'll have
* to store as much data as the header says it has. Obvioulsy, we
* check that we received as much data as the HdrExtLen advertises,
* and that we don't exceed our own internal limit. */
if( ((unsigned int)(this->h.len+1))*8 > len || (this->h.len+1)*8 > ROUTING_HEADER_MAX_LEN){
this->length=0;
return OP_FAILURE;
}else{
this->reset();
this->length=(this->h.len+1)*8;
memcpy(&(this->h), buf, this->length);
return OP_SUCCESS;
}
break;
}
}
return OP_FAILURE;
} /* End of storeRecvData() */
/* Returns a protocol identifier. This is used by packet parsing funtions
* that return linked lists of PacketElement objects, to determine the protocol
* the object represents. */
int RoutingHeader::protocol_id() const {
return HEADER_TYPE_IPv6_ROUTE;
} /* End of protocol_id() */
/** Determines if the data stored in the object after an storeRecvData() call
* is valid and safe to use. This mainly checks the length of the data but may
* also test the value of certain protocol fields to ensure their correctness.
* @return the length, in bytes, of the header, if its found to be valid or
* OP_FAILURE (-1) otherwise. */
int RoutingHeader::validate(){
/* Check the object's length makes sense*/
if(this->length < ROUTING_HEADER_MIN_LEN || this->length%8!=0) {
return OP_FAILURE;
}
switch(this->h.type){
/* Routing Type 0 (deprecated by RFC 5095)*/
case 0:
/* Here we check that:
* 1) The length in HdrExtLen is even.
* 2) The length in HdrExtLen matches the octects stored in this object.
* 3) The length in HdrExtLen does not exceed our internal limit. */
if(this->h.len%2==1 || (this->h.len+1)*8 != this->length || (this->h.len+1)*8 > ROUTING_HEADER_MAX_LEN){
return OP_FAILURE;
}
/* Also, for Type 0, the value in the SegmentsLeft field should be less
* than or equal to the number of addresses in the packet. We verify
* that using the value of the HDrExtLen field which, divided by two,
* yields the number of addresses in the packet. It certainly doesn't
* make sense for the packet to say there are 5 hops left when we
* have less than 5 IPv6 addresses. We allow it to be less than
* the number of addresses present in the packet because the RFC 2460
* only talkes about segleft being greater than HDrExtLen/2, not less. */
if(this->h.segleft > this->h.len/2){
return OP_FAILURE;
}
break;
/* Routing Type 2 (For IPv6 Mobility. See RFC 6275) */
case 2:
/* Check that we have the exact number of octets we expect. */
if(this->length!= ROUTING_TYPE_2_HEADER_LEN){
return OP_FAILURE;
}
/* Also check that the HdrExtLen and SegmentsLeft fields have the
* value that RFC 6275 dictates. */
if(this->h.segleft!=1 || this->h.len!=2){
return OP_FAILURE;
}
break;
/* Unknown routing type */
default:
/* If this is some routing type that we don't know about, we just
* check that the length makes sense because we cannot make assumptions
* about the semantics of other fields. */
if( this->length!=(this->h.len+1)*8 || (this->h.len+1)*8>ROUTING_HEADER_MAX_LEN){
return OP_FAILURE;
}
break;
}
return this->length;
} /* End of validate() */
/** Prints the contents of the header and calls print() on the next protocol
* header in the chain (if there is any).
* @return OP_SUCCESS on success and OP_FAILURE in case of error. */
int RoutingHeader::print(FILE *output, int detail) const {
fprintf(output, "Routing[nh=%d len=%d type=%d segleft=%d]", this->h.nh, this->h.len, this->h.type, this->h.segleft);
// TODO: @todo : Implement this
if(this->next!=NULL){
print_separator(output, detail);
next->print(output, detail);
}
return OP_SUCCESS;
} /* End of print() */
/******************************************************************************/
/* PROTOCOL-SPECIFIC METHODS */
/******************************************************************************/
/** Set Next Header field */
int RoutingHeader::setNextHeader(u8 val){
this->h.nh = val;
return OP_SUCCESS;
} /* End of setNextHeader() */
/** Returns next header id */
u8 RoutingHeader::getNextHeader(){
return this->h.nh;
} /* End of getNextHeader() */
/** Set routing type */
int RoutingHeader::setRoutingType(u8 val){
this->h.type = val;
return OP_SUCCESS;
} /* End of setRoutingType() */
/** Returns the routing type */
u8 RoutingHeader::getRoutingType(){
return this->h.type;
} /* End of getRoutingType() */
/** Set number of segments left */
int RoutingHeader::setSegmentsLeft(u8 val){
this->h.segleft = val;
return OP_SUCCESS;
} /* End of setSegmentsLeft() */
/** Returns the number of segments left */
u8 RoutingHeader::getSegmentsLeft(){
return this->h.segleft;
} /* End of getSegmentsLeft() */
/** Set number of segments left */
int RoutingHeader::addAddress(struct in6_addr val){
/* Check we don't exceed max length */
if((this->length + 16)>ROUTING_HEADER_MAX_LEN)
return OP_FAILURE;
memcpy(this->curr_addr, val.s6_addr, 16);
this->curr_addr+=16;
this->h.len+=2;
this->length+=16;
return OP_SUCCESS;
} /* End of setSegmentsLeft() */

207
libnetutil/RoutingHeader.h Normal file
View File

@@ -0,0 +1,207 @@
/***************************************************************************
* RoutingHeader.h -- The RoutingHeader Class represents an IPv6 Routing *
* extension header. *
***********************IMPORTANT NMAP LICENSE TERMS************************
* *
* The Nmap Security Scanner is (C) 1996-2011 Insecure.Com LLC. Nmap is *
* also a registered trademark of Insecure.Com LLC. This program is free *
* software; you may redistribute and/or modify it under the terms of the *
* GNU General Public License as published by the Free Software *
* Foundation; Version 2 with the clarifications and exceptions described *
* below. This guarantees your right to use, modify, and redistribute *
* this software under certain conditions. If you wish to embed Nmap *
* technology into proprietary software, we sell alternative licenses *
* (contact sales@insecure.com). Dozens of software vendors already *
* license Nmap technology such as host discovery, port scanning, OS *
* detection, and version detection. *
* *
* Note that the GPL places important restrictions on "derived works", yet *
* it does not provide a detailed definition of that term. To avoid *
* misunderstandings, we consider an application to constitute a *
* "derivative work" for the purpose of this license if it does any of the *
* following: *
* o Integrates source code from Nmap *
* o Reads or includes Nmap copyrighted data files, such as *
* nmap-os-db or nmap-service-probes. *
* o Executes Nmap and parses the results (as opposed to typical shell or *
* execution-menu apps, which simply display raw Nmap output and so are *
* not derivative works.) *
* o Integrates/includes/aggregates Nmap into a proprietary executable *
* installer, such as those produced by InstallShield. *
* o Links to a library or executes a program that does any of the above *
* *
* The term "Nmap" should be taken to also include any portions or derived *
* works of Nmap. This list is not exclusive, but is meant to clarify our *
* interpretation of derived works with some common examples. Our *
* interpretation applies only to Nmap--we don't speak for other people's *
* GPL works. *
* *
* If you have any questions about the GPL licensing restrictions on using *
* Nmap in non-GPL works, we would be happy to help. As mentioned above, *
* we also offer alternative license to integrate Nmap into proprietary *
* applications and appliances. These contracts have been sold to dozens *
* of software vendors, and generally include a perpetual license as well *
* as providing for priority support and updates as well as helping to *
* fund the continued development of Nmap technology. Please email *
* sales@insecure.com for further information. *
* *
* As a special exception to the GPL terms, Insecure.Com LLC grants *
* permission to link the code of this program with any version of the *
* OpenSSL library which is distributed under a license identical to that *
* listed in the included docs/licenses/OpenSSL.txt file, and distribute *
* linked combinations including the two. You must obey the GNU GPL in all *
* respects for all of the code used other than OpenSSL. If you modify *
* this file, you may extend this exception to your version of the file, *
* but you are not obligated to do so. *
* *
* If you received these files with a written license agreement or *
* contract stating terms other than the terms above, then that *
* alternative license agreement takes precedence over these comments. *
* *
* Source is provided to this software because we believe users have a *
* right to know exactly what a program is going to do before they run it. *
* This also allows you to audit the software for security holes (none *
* have been found so far). *
* *
* Source code also allows you to port Nmap to new platforms, fix bugs, *
* and add new features. You are highly encouraged to send your changes *
* to nmap-dev@insecure.org for possible incorporation into the main *
* distribution. By sending these changes to Fyodor or one of the *
* Insecure.Org development mailing lists, it is assumed that you are *
* offering the Nmap Project (Insecure.Com LLC) the unlimited, *
* non-exclusive right to reuse, modify, and relicense the code. Nmap *
* will always be available Open Source, but this is important because the *
* inability to relicense code has caused devastating problems for other *
* Free Software projects (such as KDE and NASM). We also occasionally *
* relicense the code to third parties as discussed above. If you wish to *
* specify special license conditions of your contributions, just say so *
* when you send them. *
* *
* This program is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* General Public License v2.0 for more details at *
* http://www.gnu.org/licenses/gpl-2.0.html , or in the COPYING file *
* included with Nmap. *
* *
***************************************************************************/
/* This code was originally part of the Nping tool. */
#ifndef __ROUTING_HEADER_H__
#define __ROUTING_HEADER_H__ 1
#include "IPv6ExtensionHeader.h"
#define ROUTING_HEADER_MIN_LEN 8
#define ROUTING_HEADER_MAX_LEN (8 + 256*8)
#define ROUTING_MAX_DATA_LEN 256*8
#define ROUTING_TYPE_2_HEADER_LEN 24
#define ROUTING_TYPE_0_MIN_LEN 8
class RoutingHeader : public IPv6ExtensionHeader {
private:
/*
1) Generic Routing Header:
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Next Header | Hdr Ext Len | Routing Type | Segments Left |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
. .
. type-specific data .
. .
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2) Type 0 Routing header:
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Next Header | Hdr Ext Len | Routing Type=0| Segments Left |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Reserved |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+ +
| |
+ Address[1] +
| |
+ +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+ +
| |
+ Address[2] +
| |
+ +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
. . .
. . .
. . .
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+ +
| |
+ Address[n] +
| |
+ +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
3) Type 2 Routing header:
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Next Header | Hdr Ext Len=2 | Routing Type=2|Segments Left=1|
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Reserved |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+ +
| |
+ Home Address +
| |
+ +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */
struct nping_ipv6_ext_routing_hdr{
u8 nh;
u8 len;
u8 type;
u8 segleft;
u32 reserved;
u8 data[ROUTING_MAX_DATA_LEN];
}__attribute__((__packed__));
typedef struct nping_ipv6_ext_routing_hdr nping_ipv6_ext_routing_hdr_t;
nping_ipv6_ext_routing_hdr_t h;
u8 *curr_addr;
public:
RoutingHeader();
~RoutingHeader();
void reset();
u8 *getBufferPointer();
int storeRecvData(const u8 *buf, size_t len);
int protocol_id() const;
int validate();
int print(FILE *output, int detail) const;
/* Protocol specific methods */
int setNextHeader(u8 val);
u8 getNextHeader();
int setRoutingType(u8 val);
u8 getRoutingType();
int setSegmentsLeft(u8 val);
u8 getSegmentsLeft();
int addAddress(struct in6_addr val);
}; /* End of class RoutingHeader */
#endif

963
libnetutil/TCPHeader.cc Normal file
View File

@@ -0,0 +1,963 @@
/***************************************************************************
* TCPHeader.cc -- The TCPHeader Class represents a TCP packet. It *
* contains methods to set the different header fields. These methods *
* tipically perform the necessary error checks and byte order *
* conversions. *
* *
***********************IMPORTANT NMAP LICENSE TERMS************************
* *
* The Nmap Security Scanner is (C) 1996-2011 Insecure.Com LLC. Nmap is *
* also a registered trademark of Insecure.Com LLC. This program is free *
* software; you may redistribute and/or modify it under the terms of the *
* GNU General Public License as published by the Free Software *
* Foundation; Version 2 with the clarifications and exceptions described *
* below. This guarantees your right to use, modify, and redistribute *
* this software under certain conditions. If you wish to embed Nmap *
* technology into proprietary software, we sell alternative licenses *
* (contact sales@insecure.com). Dozens of software vendors already *
* license Nmap technology such as host discovery, port scanning, OS *
* detection, and version detection. *
* *
* Note that the GPL places important restrictions on "derived works", yet *
* it does not provide a detailed definition of that term. To avoid *
* misunderstandings, we consider an application to constitute a *
* "derivative work" for the purpose of this license if it does any of the *
* following: *
* o Integrates source code from Nmap *
* o Reads or includes Nmap copyrighted data files, such as *
* nmap-os-db or nmap-service-probes. *
* o Executes Nmap and parses the results (as opposed to typical shell or *
* execution-menu apps, which simply display raw Nmap output and so are *
* not derivative works.) *
* o Integrates/includes/aggregates Nmap into a proprietary executable *
* installer, such as those produced by InstallShield. *
* o Links to a library or executes a program that does any of the above *
* *
* The term "Nmap" should be taken to also include any portions or derived *
* works of Nmap. This list is not exclusive, but is meant to clarify our *
* interpretation of derived works with some common examples. Our *
* interpretation applies only to Nmap--we don't speak for other people's *
* GPL works. *
* *
* If you have any questions about the GPL licensing restrictions on using *
* Nmap in non-GPL works, we would be happy to help. As mentioned above, *
* we also offer alternative license to integrate Nmap into proprietary *
* applications and appliances. These contracts have been sold to dozens *
* of software vendors, and generally include a perpetual license as well *
* as providing for priority support and updates as well as helping to *
* fund the continued development of Nmap technology. Please email *
* sales@insecure.com for further information. *
* *
* As a special exception to the GPL terms, Insecure.Com LLC grants *
* permission to link the code of this program with any version of the *
* OpenSSL library which is distributed under a license identical to that *
* listed in the included docs/licenses/OpenSSL.txt file, and distribute *
* linked combinations including the two. You must obey the GNU GPL in all *
* respects for all of the code used other than OpenSSL. If you modify *
* this file, you may extend this exception to your version of the file, *
* but you are not obligated to do so. *
* *
* If you received these files with a written license agreement or *
* contract stating terms other than the terms above, then that *
* alternative license agreement takes precedence over these comments. *
* *
* Source is provided to this software because we believe users have a *
* right to know exactly what a program is going to do before they run it. *
* This also allows you to audit the software for security holes (none *
* have been found so far). *
* *
* Source code also allows you to port Nmap to new platforms, fix bugs, *
* and add new features. You are highly encouraged to send your changes *
* to nmap-dev@insecure.org for possible incorporation into the main *
* distribution. By sending these changes to Fyodor or one of the *
* Insecure.Org development mailing lists, it is assumed that you are *
* offering the Nmap Project (Insecure.Com LLC) the unlimited, *
* non-exclusive right to reuse, modify, and relicense the code. Nmap *
* will always be available Open Source, but this is important because the *
* inability to relicense code has caused devastating problems for other *
* Free Software projects (such as KDE and NASM). We also occasionally *
* relicense the code to third parties as discussed above. If you wish to *
* specify special license conditions of your contributions, just say so *
* when you send them. *
* *
* This program is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* General Public License v2.0 for more details at *
* http://www.gnu.org/licenses/gpl-2.0.html , or in the COPYING file *
* included with Nmap. *
* *
***************************************************************************/
/* This code was originally part of the Nping tool. */
#include "TCPHeader.h"
#include <assert.h>
/******************************************************************************/
/* CONTRUCTORS, DESTRUCTORS AND INITIALIZATION METHODS */
/******************************************************************************/
TCPHeader::TCPHeader(){
this->reset();
} /* End of TCPHeader constructor */
TCPHeader::~TCPHeader(){
} /* End of TCPHeader destructor */
/** Sets every attribute to its default value */
void TCPHeader::reset(){
memset(&this->h, 0, sizeof(nping_tcp_hdr_t));
this->length=TCP_HEADER_LEN; /* Initial value 20. This will be incremented if options are used */
this->tcpoptlen=0;
this->setSourcePort(TCP_DEFAULT_SPORT);
this->setDestinationPort(TCP_DEFAULT_DPORT);
this->setSeq(TCP_DEFAULT_SEQ);
this->setAck(TCP_DEFAULT_ACK);
this->setFlags(TCP_DEFAULT_FLAGS);
this->setWindow(TCP_DEFAULT_WIN);
this->setUrgPointer(TCP_DEFAULT_URP);
this->setOffset();
} /* End of reset() */
/******************************************************************************/
/* PacketElement:: OVERWRITTEN METHODS */
/******************************************************************************/
/** @warning This method is essential for the superclass getBinaryBuffer()
* method to work. Do NOT change a thing unless you know what you're doing */
u8 * TCPHeader::getBufferPointer(){
return (u8*)(&h);
} /* End of getBufferPointer() */
/** Stores supplied packet in the internal buffer so the information
* can be accessed using the standard get & set methods.
* @warning The TCPHeader class is able to hold a maximum of 60 bytes. If the
* supplied buffer is longer than that, only the first 60 bytes will be stored
* in the internal buffer.
* @warning Supplied len MUST be at least 20 bytes (min TCP header length).
* @return OP_SUCCESS on success and OP_FAILURE in case of error */
int TCPHeader::storeRecvData(const u8 *buf, size_t len){
if(buf==NULL || len<TCP_HEADER_LEN){
return OP_FAILURE;
}else{
int stored_len = MIN((TCP_HEADER_LEN + MAX_TCP_OPTIONS_LEN), len);
this->reset(); /* Re-init the object, just in case the caller had used it already */
this->length=stored_len;
if(stored_len>TCP_HEADER_LEN)
this->tcpoptlen=stored_len-TCP_HEADER_LEN;
memcpy(&(this->h), buf, stored_len);
}
return OP_SUCCESS;
} /* End of storeRecvData() */
/* Returns a protocol identifier. This is used by packet parsing funtions
* that return linked lists of PacketElement objects, to determine the protocol
* the object represents. */
int TCPHeader::protocol_id() const {
return HEADER_TYPE_TCP;
} /* End of protocol_id() */
/** Determines if the data stored in the object after an storeRecvData() call
* is valid and safe to use. This mainly checks the length of the data but may
* also test the value of certain protocol fields to ensure their correctness.
* @warning If the information stored in the object has been set through a
* call to storeRecvData(), the object's internal length count may be updated
* if the validation is successful.
* @return the length, in bytes, of the header, if its found to be valid or
* OP_FAILURE (-1) otherwise. */
int TCPHeader::validate(){
if(this->getOffset()<5)
return OP_FAILURE;
else if(this->getOffset()*4 > this->length)
return OP_FAILURE;
this->length=this->getOffset()*4;
return this->length;
} /* End of validate() */
/** Prints the contents of the header and calls print() on the next protocol
* header in the chain (if there is any).
* @return OP_SUCCESS on success and OP_FAILURE in case of error. */
int TCPHeader::print(FILE *output, int detail) const {
char optinfo[256];
fprintf(output, "TCP[");
fprintf(output, "%d", this->getSourcePort());
fprintf(output, " >");
fprintf(output, " %d", this->getDestinationPort());
fprintf(output, " %s%s%s%s%s%s%s%s",
!this->getSYN() ? "" : "S",
!this->getFIN() ? "" : "F",
!this->getRST() ? "" : "R",
!this->getPSH() ? "" : "P",
!this->getACK() ? "" : "A",
!this->getURG() ? "" : "U",
!this->getECN() ? "" : "E",
!this->getCWR() ? "" : "C"
);
fprintf(output, " seq=%lu", (long unsigned int)this->getSeq() );
if(detail>=PRINT_DETAIL_HIGH){
fprintf(output, " ack=%lu", (long unsigned int)this->getAck() );
fprintf(output, " off=%d", this->getOffset() );
fprintf(output, " res=%d", this->h.th_x2);
}
fprintf(output, " win=%hu", this->getWindow() );
if(detail>=PRINT_DETAIL_MED)
fprintf(output, " csum=0x%04X", ntohs( this->getSum() ));
if(detail>=PRINT_DETAIL_HIGH)
fprintf(output, " urp=%d", this->getUrgPointer() );
if(this->tcpoptlen>0 && (this->length >= TCP_HEADER_LEN+this->tcpoptlen) && this->tcpoptlen<=MAX_TCP_OPTIONS_LEN){
this->__tcppacketoptinfo(this->h.options, this->tcpoptlen, optinfo, sizeof(optinfo)-1);
optinfo[255]='\0';
fprintf(output, " %s", optinfo);
}
fprintf(output, "]");
if(this->next!=NULL){
print_separator(output, detail);
next->print(output, detail);
}
return OP_SUCCESS;
} /* End of print() */
/* Get an ASCII information about a tcp option which is pointed by
optp, with a length of len. The result is stored in the result
buffer. The result may look like "<mss 1452,sackOK,timestamp
45848914 0,nop,wscale 7>" */
void TCPHeader::__tcppacketoptinfo(const u8 *optp, int len, char *result, int bufsize) const {
assert(optp);
assert(result);
char *p, ch;
const u8 *q;
int opcode;
u16 tmpshort;
u32 tmpword1, tmpword2;
unsigned int i=0;
p = result;
*p = '\0';
q = optp;
ch = '<';
while (len > 0 && bufsize > 2) {
Snprintf(p, bufsize, "%c", ch);
bufsize--;
p++;
opcode = *q++;
if (!opcode) { /* End of List */
Snprintf(p, bufsize, "eol");
bufsize -= strlen(p);
p += strlen(p);
len--;
} else if (opcode == 1) { /* No Op */
Snprintf(p, bufsize, "nop");
bufsize -= strlen(p);
p += strlen(p);
len--;
} else if (opcode == 2) { /* MSS */
if (len < 4)
break; /* MSS has 4 bytes */
q++;
memcpy(&tmpshort, q, 2);
Snprintf(p, bufsize, "mss %u", ntohs(tmpshort));
bufsize -= strlen(p);
p += strlen(p);
q += 2;
len -= 4;
} else if (opcode == 3) { /* Window Scale */
if (len < 3)
break; /* Window Scale option has 3 bytes */
q++;
Snprintf(p, bufsize, "wscale %u", *q);
bufsize -= strlen(p);
p += strlen(p);
q++;
len -= 3;
} else if (opcode == 4) { /* SACK permitted */
if (len < 2)
break; /* SACK permitted option has 2 bytes */
Snprintf(p, bufsize, "sackOK");
bufsize -= strlen(p);
p += strlen(p);
q++;
len -= 2;
} else if (opcode == 5) { /* SACK */
unsigned sackoptlen = *q;
if ((unsigned) len < sackoptlen)
break;
/* This would break parsing, so it's best to just give up */
if (sackoptlen < 2)
break;
q++;
if ((sackoptlen - 2) == 0 || ((sackoptlen - 2) % 8 != 0)) {
Snprintf(p, bufsize, "malformed sack");
bufsize -= strlen(p);
p += strlen(p);
} else {
Snprintf(p, bufsize, "sack %d ", (sackoptlen - 2) / 8);
bufsize -= strlen(p);
p += strlen(p);
for (i = 0; i < sackoptlen - 2; i += 8) {
memcpy(&tmpword1, q + i, 4);
memcpy(&tmpword2, q + i + 4, 4);
Snprintf(p, bufsize, "{%u:%u}", tmpword1, tmpword2);
bufsize -= strlen(p);
p += strlen(p);
}
}
q += sackoptlen - 2;
len -= sackoptlen;
} else if (opcode == 8) { /* Timestamp */
if (len < 10)
break; /* Timestamp option has 10 bytes */
q++;
memcpy(&tmpword1, q, 4);
memcpy(&tmpword2, q + 4, 4);
Snprintf(p, bufsize, "timestamp %u %u", ntohl(tmpword1),
ntohl(tmpword2));
bufsize -= strlen(p);
p += strlen(p);
q += 8;
len -= 10;
}
ch = ',';
}
if (len > 0) {
*result = '\0';
return;
}
Snprintf(p, bufsize, ">");
}
/******************************************************************************/
/* PROTOCOL-SPECIFIC METHODS */
/******************************************************************************/
/** Sets source port.
* @warning Port must be supplied in host byte order. This method performs
* byte order conversion using htons() */
int TCPHeader::setSourcePort(u16 p){
h.th_sport = htons(p);
return OP_SUCCESS;
} /* End of setSourcePort() */
/** Returns source port in HOST byte order */
u16 TCPHeader::getSourcePort() const {
return ntohs(h.th_sport);
} /* End of getSourcePort() */
/** Sets destination port.
* @warning Port must be supplied in host byte order. This method performs
* byte order conversion using htons() */
int TCPHeader::setDestinationPort(u16 p){
h.th_dport = htons(p);
return OP_SUCCESS;
} /* End of setDestinationPort() */
/** Returns destination port in HOST byte order */
u16 TCPHeader::getDestinationPort() const {
return ntohs(h.th_dport);
} /* End of getDestinationPort() */
/** Sets sequence number.
* @warning Seq number must be supplied in host byte order. This method
* performs byte order conversion using htonl() */
int TCPHeader::setSeq(u32 p){
h.th_seq = htonl(p);
return OP_SUCCESS;
} /* End of setSeq() */
/** Returns sequence number in HOST byte order */
u32 TCPHeader::getSeq() const {
return ntohl(h.th_seq);
} /* End of getSeq() */
/** Sets acknowledgement number.
* @warning ACK number must be supplied in host byte order. This method
* performs byte order conversion using htonl() */
int TCPHeader::setAck(u32 p){
h.th_ack = htonl(p);
return OP_SUCCESS;
} /* End of setAck() */
/** Returns ACK number in HOST byte order */
u32 TCPHeader::getAck() const {
return ntohl(h.th_ack);
} /* End of getAck() */
/* TODO: Test this method. It may not work becuasse th_off is supposed to
* be 4 bits long and arg o is 8.
* UPDATE: It seems to work just fine. However, let's keep this note just
* in case problems arise. */
int TCPHeader::setOffset(u8 o){
h.th_off = o;
return OP_SUCCESS;
} /* End of setOffset() */
int TCPHeader::setOffset(){
h.th_off = 5 + tcpoptlen/4;
return OP_SUCCESS;
} /* End of setOffset() */
/** Returns offset value */
u8 TCPHeader::getOffset() const {
return h.th_off;
} /* End of getOffset() */
/* Sets the 4-bit reserved field (Note that there are not 4 reserved bits anymore
* as RFC 3540 introduces a new TCP flag, so calling this will overwrite
* the value of such flag. */
int TCPHeader::setReserved(u8 r){
h.th_x2 = r;
return OP_SUCCESS;
}
u8 TCPHeader::getReserved() const {
return h.th_x2;
}
/** Sets TCP flags */
int TCPHeader::setFlags(u8 f){
h.th_flags = f;
return OP_SUCCESS;
} /* End of setFlags() */
/** Returns the 8bit flags field of the TCP header */
u8 TCPHeader::getFlags() const {
return h.th_flags;
} /* End of getFlags() */
/* Returns the 16bit flags field of the TCP header. As RFC 3540 defines a new
* flag (NS), we no longer can store all TCP flags in a single octet, so
* this method returns the flags as a two-octet unsigned integer. */
u16 TCPHeader::getFlags16() const {
/* Obtain the value of dataoff+reserved+flags in host byte order */
u16 field=ntohs(*(u16 *)(((u8 *)&this->h)+12));
/* Erase the contents of the data offset field */
field = field & 0x0FFF;
return field;
} /* End of getFlags16() */
/** Sets flag CWR
* @return Previous state of the flag */
bool TCPHeader::setCWR(){
u8 prev = h.th_flags & TH_CWR;
h.th_flags |= TH_CWR;
return prev;
} /* End of setCWR() */
/** Unsets flag CWR
* @return Previous state of the flag */
bool TCPHeader::unsetCWR(){
u8 prev = h.th_flags & TH_CWR;
h.th_flags ^= TH_CWR;
return prev;
} /* End of unsetCWR() */
/** Get CWR flag */
bool TCPHeader::getCWR() const {
return h.th_flags & TH_CWR;
} /* End of getCWR() */
/** Sets flag ECE/ECN
* @return Previous state of the flag */
bool TCPHeader::setECE(){
u8 prev = h.th_flags & TH_ECN;
h.th_flags |= TH_ECN;
return prev;
} /* End of setECE() */
/** Unsets flag ECE/ECN
* @return Previous state of the flag */
bool TCPHeader::unsetECE(){
u8 prev = h.th_flags & TH_ECN;
h.th_flags ^= TH_ECN;
return prev;
} /* End of unsetECE() */
/** Get CWR flag */
bool TCPHeader::getECE() const {
return h.th_flags & TH_ECN;
} /* End of getECE() */
/** Same as setECE() but with a different name since there are two possible
* ways to call this flag
* @return Previous state of the flag */
bool TCPHeader::setECN(){
u8 prev = h.th_flags & TH_ECN;
h.th_flags |= TH_ECN;
return prev;
} /* End of setECN() */
/** Unsets flag ECE/ECN
* @return Previous state of the flag */
bool TCPHeader::unsetECN(){
u8 prev = h.th_flags & TH_ECN;
h.th_flags ^= TH_ECN;
return prev;
} /* End of unsetECN() */
/** Get ECN flag */
bool TCPHeader::getECN() const {
return h.th_flags & TH_ECN;
} /* End of getECN() */
/** Sets flag URG
* @return Previous state of the flag */
bool TCPHeader::setURG(){
u8 prev = h.th_flags & TH_URG;
h.th_flags |= TH_URG;
return prev;
} /* End of setURG() */
/** Unsets flag URG
* @return Previous state of the flag */
bool TCPHeader::unsetURG(){
u8 prev = h.th_flags & TH_URG;
h.th_flags ^= TH_URG;
return prev;
} /* End of unsetURG() */
/** Get URG flag */
bool TCPHeader::getURG() const {
return h.th_flags & TH_URG;
} /* End of getURG() */
/** Sets flag ACK
* @return Previous state of the flag */
bool TCPHeader::setACK(){
u8 prev = h.th_flags & TH_ACK;
h.th_flags |= TH_ACK;
return prev;
} /* End of setACK() */
/** Unsets flag ACK
* @return Previous state of the flag */
bool TCPHeader::unsetACK(){
u8 prev = h.th_flags & TH_ACK;
h.th_flags ^= TH_ACK;
return prev;
} /* End of unsetACK() */
/** Get ACK flag */
bool TCPHeader::getACK() const {
return h.th_flags & TH_ACK;
} /* End of getACK() */
/** Sets flag PSH
* @return Previous state of the flag */
bool TCPHeader::setPSH(){
u8 prev = h.th_flags & TH_PSH;
h.th_flags |= TH_PSH;
return prev;
} /* End of setPSH() */
/** Unsets flag PSH
* @return Previous state of the flag */
bool TCPHeader::unsetPSH(){
u8 prev = h.th_flags & TH_PSH;
h.th_flags ^= TH_PSH;
return prev;
} /* End of unsetPSH() */
/** Get PSH flag */
bool TCPHeader::getPSH() const {
return h.th_flags & TH_PSH;
} /* End of getPSH() */
/** Sets flag RST
* @return Previous state of the flag */
bool TCPHeader::setRST(){
u8 prev = h.th_flags & TH_RST;
h.th_flags |= TH_RST;
return prev;
} /* End of setRST() */
/** Unsets flag RST
* @return Previous state of the flag */
bool TCPHeader::unsetRST(){
u8 prev = h.th_flags & TH_RST;
h.th_flags ^= TH_RST;
return prev;
} /* End of unsetRST() */
/** Get RST flag */
bool TCPHeader::getRST() const {
return h.th_flags & TH_RST;
} /* End of getRST() */
/** Sets flag SYN
* @return Previous state of the flag */
bool TCPHeader::setSYN(){
u8 prev = h.th_flags & TH_SYN;
h.th_flags |= TH_SYN;
return prev;
} /* End of setSYN() */
/** Unsets flag SYN
* @return Previous state of the flag */
bool TCPHeader::unsetSYN(){
u8 prev = h.th_flags & TH_SYN;
h.th_flags ^= TH_SYN;
return prev;
} /* End of unsetSYN() */
/** Get SYN flag */
bool TCPHeader::getSYN() const {
return h.th_flags & TH_SYN;
} /* End of getSYN() */
/** Sets flag FIN
* @return Previous state of the flag */
bool TCPHeader::setFIN(){
u8 prev = h.th_flags & TH_FIN;
h.th_flags |= TH_FIN;
return prev;
} /* End of setFIN() */
/** Unsets flag FIN
* @return Previous state of the flag */
bool TCPHeader::unsetFIN(){
u8 prev = h.th_flags & TH_FIN;
h.th_flags ^= TH_FIN;
return prev;
} /* End of unsetFIN() */
/** Get FIN flag */
bool TCPHeader::getFIN() const {
return h.th_flags & TH_FIN;
} /* End of getFIN() */
/** Sets window size.
* @warning Win number must be supplied in host byte order. This method
* performs byte order conversion using htons() */
int TCPHeader::setWindow(u16 p){
h.th_win = htons(p);
return OP_SUCCESS;
} /* End of setWindow() */
/** Returns window size in HOST byte order. */
u16 TCPHeader::getWindow() const {
return ntohs(h.th_win);
} /* End of getWindow() */
/** Sets urgent pointer.
* @warning Pointer must be supplied in host byte order. This method
* performs byte order conversion using htons() */
int TCPHeader::setUrgPointer(u16 l){
h.th_urp = htons(l);
return OP_SUCCESS;
} /* End of setUrgPointer() */
/** Returns Urgent Pointer in HOST byte order. */
u16 TCPHeader::getUrgPointer() const {
return ntohs(h.th_urp);
} /* End of getUrgPointer() */
int TCPHeader::setSum(struct in_addr src, struct in_addr dst){
int bufflen;
u8 aux[ MAX_TCP_PAYLOAD_LEN ];
/* FROM: RFC 1323: TCP Extensions for High Performance, March 4, 2009
*
* "With IP Version 4, the largest amount of TCP data that can be sent in
* a single packet is 65495 bytes (64K - 1 - size of fixed IP and TCP
* headers)".
*
* In theory TCP should not worry about the practical max payload length
* because it is supposed to be independent of the network layer. However,
* since TCP does not have any length field and we need to allocate a
* buffer, we are using that value. (Note htat in UDPHeader.cc we do just
* the opposite, forget about the practical limitation and allow the
* theorical limit for the payload. */
h.th_sum = 0;
/* Copy packet contents to a buffer */
bufflen=dumpToBinaryBuffer(aux, MAX_TCP_PAYLOAD_LEN);
/* Compute checksum */
h.th_sum = ipv4_pseudoheader_cksum(&src, &dst, IPPROTO_TCP, bufflen, (char *)aux);
return OP_SUCCESS;
} /* End of setSum() */
/** @warning Sum is set to supplied value with NO byte ordering conversion
* performed. */
int TCPHeader::setSum(u16 s){
h.th_sum = s;
return OP_SUCCESS;
} /* End of setSum() */
int TCPHeader::setSum(){
this->h.th_sum=0;
this->h.th_sum = this->compute_checksum();
return OP_SUCCESS;
} /* End of setSum() */
/** Set the TCP checksum field to a random value, which may accidentally
* match the correct checksum */
int TCPHeader::setSumRandom(){
h.th_sum=get_random_u16();
return OP_SUCCESS;
} /* End of setSumRandom() */
/** Set the TCP checksum field to a random value. It takes the source and
* destination address to make sure the random generated sum does not
* accidentally match the correct checksum. This function only handles
* IPv4 address. */
int TCPHeader::setSumRandom(struct in_addr source, struct in_addr destination){
u16 correct_csum=0;
/* Compute the correct checksum */
this->setSum(source, destination);
correct_csum=this->getSum();
/* Generate numbers until one does not match the correct sum */
while( (h.th_sum=get_random_u16())==correct_csum);
return OP_SUCCESS;
} /* End of setSumRandom() */
/** Returns the TCP checksum field in NETWORK byte order */
u16 TCPHeader::getSum() const {
return h.th_sum;
} /* End of getSum() */
/* Copies the supplied buffer into the TCP options field. Note that the supplied
* buffer MUST NOT exceed MAX_TCP_OPTIONS_LEN octets and should be a multiple of
* four. If it is not a multiple of four, no error will be returned but the
* behaviour is unspecified. If this method is called passing NULL and zero
* ( t.setOptions(NULL, 0), any existing options are cleared, and the object's
* internal length is updated accordingly. Also, note that a call to setOptions()
* involves an automatic call to setOffset(), which updates the Offset field
* to take into account the new header length. If you need to set a bogus
* data offset, you can do so after calling setOptions(), but not before.
* It returns OP_SUCCESS on success and OP_FAILURE in case of error */
int TCPHeader::setOptions(const u8 *optsbuff, size_t optslen){
/* NULL and length=0 means delete existing options */
if(optsbuff==NULL && optslen==0){
this->tcpoptlen=0;
this->length=TCP_HEADER_LEN;
memset(this->h.options, 0, MAX_TCP_OPTIONS_LEN);
return OP_SUCCESS;
/* Make sure params are safe to use */
}else if(optsbuff==NULL || optslen==0 || optslen>MAX_TCP_OPTIONS_LEN){
return OP_FAILURE;
/* Copy supplied buffer into the options field, and update the offset field. */
}else{
memcpy(this->h.options, optsbuff, optslen);
this->tcpoptlen=optslen;
this->length=TCP_HEADER_LEN+optslen;
this->setOffset();
return OP_SUCCESS;
}
} /* End of setOptions() */
/* Returns a pointer to the start of the TCP options field. If the supplied
* "optslen" pointer is not NULL, the length of the options will be stored
* there. */
const u8 *TCPHeader::getOptions(size_t *optslen) const {
if(optslen!=NULL)
*optslen=this->tcpoptlen;
return this->h.options;
} /* End of getOptions() */
/* Returns the index-th option in the TCP header. On success it returns a
* structure filled with option information. If there is no index-th option,
* it returns a structure with st.value==NULL. Note that this function does
* not perform strict validity checking. It does check that the length claimed
* by the options does not exceed the available buffer but it does not check,
* for example, that the MSS option always contains a length of 4. Also,
* if the returned option type is TCPOPT_EOL or TCPOPT_NOOP, the len field
* would be set to zero and the "value" field should NOT be accessed, as it
* will not contain reliable information. */
nping_tcp_opt_t TCPHeader::getOption(unsigned int index) const {
nping_tcp_opt_t *curr_opt=NULL;
u8 *curr_pnt=(u8 *)this->h.options;
int bytes_left=this->length - TCP_HEADER_LEN;
assert((this->length - TCP_HEADER_LEN) == this->tcpoptlen);
unsigned int optsfound=0;
nping_tcp_opt_t result;
memset(&result, 0, sizeof(nping_tcp_opt_t));
while(bytes_left>0){
/* Use the opts structure as a template to access current option. It is
* OK to use it because we only access the first two elements. */
curr_opt=(nping_tcp_opt_t *)curr_pnt;
/* If we are right in the option that the caller wants, just return it */
if(optsfound==index){
result.type=curr_opt->type;
if(result.type==TCPOPT_EOL || result.type==TCPOPT_NOOP)
result.len=1;
else
result.len=curr_opt->len;
result.value=(u8 *)curr_pnt+2;
return result;
}
/* Otherwise, we have to parse it, so we can skip it and access the next
* option */
switch(curr_opt->type){
/* EOL or NOOP
+-+-+-+-+-+-+-+-+
| X |
+-+-+-+-+-+-+-+-+ */
case TCPOPT_EOL:
case TCPOPT_NOOP:
curr_pnt++; /* Skip one octet */
bytes_left--;
break;
/* TLV encoded option */
default:
/* If we don't have as many octets as the option advertises, the
* option is bogus. Return failure. */
if(bytes_left<curr_opt->len)
return result;
curr_pnt+=curr_opt->len;
bytes_left-=curr_opt->len;
break;
}
optsfound++;
}
return result;
}
/* Returns a textual representation of a TCP Options code */
const char *TCPHeader::optcode2str(u8 optcode){
switch(optcode){
case TCPOPT_EOL:
return "EOL";
case TCPOPT_NOOP:
return "NOOP";
case TCPOPT_MSS:
return "MSS";
case TCPOPT_WSCALE:
return "WScale";
case TCPOPT_SACKOK:
return "SAckOK";
case TCPOPT_SACK:
return "SAck";
case TCPOPT_ECHOREQ:
return "EchoReq";
case TCPOPT_ECHOREP:
return "EchoRep";
case TCPOPT_TSTAMP:
return "TStamp";
case TCPOPT_POCP:
return "POCP";
case TCPOPT_POSP:
return "POSP";
case TCPOPT_CC:
return "CC";
case TCPOPT_CCNEW:
return "CC.NEW";
case TCPOPT_CCECHO:
return "CC.ECHO";
case TCPOPT_ALTCSUMREQ:
return "AltSumReq";
case TCPOPT_ALTCSUMDATA:
return "AltSumData";
case TCPOPT_MD5:
return "MD5";
case TCPOPT_SCPS:
return "SCPS";
case TCPOPT_SNACK:
return "SNAck";
case TCPOPT_QSRES:
return "QStart";
case TCPOPT_UTO:
return "UTO";
case TCPOPT_AO:
return "AO";
default:
return "Unknown";
}
} /* End of optcode2str() */

290
libnetutil/TCPHeader.h Normal file
View File

@@ -0,0 +1,290 @@
/***************************************************************************
* TCPHeader.h -- The TCPHeader Class represents a TCP packet. It contains *
* methods to set the different header fields. These methods tipically *
* perform the necessary error checks and byte order conversions. *
* *
***********************IMPORTANT NMAP LICENSE TERMS************************
* *
* The Nmap Security Scanner is (C) 1996-2011 Insecure.Com LLC. Nmap is *
* also a registered trademark of Insecure.Com LLC. This program is free *
* software; you may redistribute and/or modify it under the terms of the *
* GNU General Public License as published by the Free Software *
* Foundation; Version 2 with the clarifications and exceptions described *
* below. This guarantees your right to use, modify, and redistribute *
* this software under certain conditions. If you wish to embed Nmap *
* technology into proprietary software, we sell alternative licenses *
* (contact sales@insecure.com). Dozens of software vendors already *
* license Nmap technology such as host discovery, port scanning, OS *
* detection, and version detection. *
* *
* Note that the GPL places important restrictions on "derived works", yet *
* it does not provide a detailed definition of that term. To avoid *
* misunderstandings, we consider an application to constitute a *
* "derivative work" for the purpose of this license if it does any of the *
* following: *
* o Integrates source code from Nmap *
* o Reads or includes Nmap copyrighted data files, such as *
* nmap-os-db or nmap-service-probes. *
* o Executes Nmap and parses the results (as opposed to typical shell or *
* execution-menu apps, which simply display raw Nmap output and so are *
* not derivative works.) *
* o Integrates/includes/aggregates Nmap into a proprietary executable *
* installer, such as those produced by InstallShield. *
* o Links to a library or executes a program that does any of the above *
* *
* The term "Nmap" should be taken to also include any portions or derived *
* works of Nmap. This list is not exclusive, but is meant to clarify our *
* interpretation of derived works with some common examples. Our *
* interpretation applies only to Nmap--we don't speak for other people's *
* GPL works. *
* *
* If you have any questions about the GPL licensing restrictions on using *
* Nmap in non-GPL works, we would be happy to help. As mentioned above, *
* we also offer alternative license to integrate Nmap into proprietary *
* applications and appliances. These contracts have been sold to dozens *
* of software vendors, and generally include a perpetual license as well *
* as providing for priority support and updates as well as helping to *
* fund the continued development of Nmap technology. Please email *
* sales@insecure.com for further information. *
* *
* As a special exception to the GPL terms, Insecure.Com LLC grants *
* permission to link the code of this program with any version of the *
* OpenSSL library which is distributed under a license identical to that *
* listed in the included docs/licenses/OpenSSL.txt file, and distribute *
* linked combinations including the two. You must obey the GNU GPL in all *
* respects for all of the code used other than OpenSSL. If you modify *
* this file, you may extend this exception to your version of the file, *
* but you are not obligated to do so. *
* *
* If you received these files with a written license agreement or *
* contract stating terms other than the terms above, then that *
* alternative license agreement takes precedence over these comments. *
* *
* Source is provided to this software because we believe users have a *
* right to know exactly what a program is going to do before they run it. *
* This also allows you to audit the software for security holes (none *
* have been found so far). *
* *
* Source code also allows you to port Nmap to new platforms, fix bugs, *
* and add new features. You are highly encouraged to send your changes *
* to nmap-dev@insecure.org for possible incorporation into the main *
* distribution. By sending these changes to Fyodor or one of the *
* Insecure.Org development mailing lists, it is assumed that you are *
* offering the Nmap Project (Insecure.Com LLC) the unlimited, *
* non-exclusive right to reuse, modify, and relicense the code. Nmap *
* will always be available Open Source, but this is important because the *
* inability to relicense code has caused devastating problems for other *
* Free Software projects (such as KDE and NASM). We also occasionally *
* relicense the code to third parties as discussed above. If you wish to *
* specify special license conditions of your contributions, just say so *
* when you send them. *
* *
* This program is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* General Public License v2.0 for more details at *
* http://www.gnu.org/licenses/gpl-2.0.html , or in the COPYING file *
* included with Nmap. *
* *
***************************************************************************/
/* This code was originally part of the Nping tool. */
#ifndef __TCPHEADER_H__
#define __TCPHEADER_H__ 1
#include "TransportLayerElement.h"
/* TCP FLAGS */
#define TH_FIN 0x01
#define TH_SYN 0x02
#define TH_RST 0x04
#define TH_PSH 0x08
#define TH_ACK 0x10
#define TH_URG 0x20
#define TH_ECN 0x40
#define TH_CWR 0x80
/* TCP OPTIONS */
#define TCPOPT_EOL 0 /* End of Option List (RFC793) */
#define TCPOPT_NOOP 1 /* No-Operation (RFC793) */
#define TCPOPT_MSS 2 /* Maximum Segment Size (RFC793) */
#define TCPOPT_WSCALE 3 /* WSOPT - Window Scale (RFC1323) */
#define TCPOPT_SACKOK 4 /* SACK Permitted (RFC2018) */
#define TCPOPT_SACK 5 /* SACK (RFC2018) */
#define TCPOPT_ECHOREQ 6 /* Echo (obsolete) (RFC1072)(RFC6247) */
#define TCPOPT_ECHOREP 7 /* Echo Reply (obsolete) (RFC1072)(RFC6247) */
#define TCPOPT_TSTAMP 8 /* TSOPT - Time Stamp Option (RFC1323) */
#define TCPOPT_POCP 9 /* Partial Order Connection Permitted (obsol.) */
#define TCPOPT_POSP 10 /* Partial Order Service Profile (obsolete) */
#define TCPOPT_CC 11 /* CC (obsolete) (RFC1644)(RFC6247) */
#define TCPOPT_CCNEW 12 /* CC.NEW (obsolete) (RFC1644)(RFC6247) */
#define TCPOPT_CCECHO 13 /* CC.ECHO (obsolete) (RFC1644)(RFC6247) */
#define TCPOPT_ALTCSUMREQ 14 /* TCP Alternate Checksum Request (obsolete) */
#define TCPOPT_ALTCSUMDATA 15 /* TCP Alternate Checksum Data (obsolete) */
#define TCPOPT_MD5 19 /* MD5 Signature Option (obsolete) (RFC2385) */
#define TCPOPT_SCPS 20 /* SCPS Capabilities */
#define TCPOPT_SNACK 21 /* Selective Negative Acknowledgements */
#define TCPOPT_QSRES 27 /* Quick-Start Response (RFC4782) */
#define TCPOPT_UTO 28 /* User Timeout Option (RFC5482) */
#define TCPOPT_AO 29 /* TCP Authentication Option (RFC5925) */
/* Internal constants */
#define TCP_HEADER_LEN 20
#define MAX_TCP_OPTIONS_LEN 40
#define MAX_TCP_PAYLOAD_LEN 65495 /**< Max len of a TCP packet */
/* Default header values */
#define TCP_DEFAULT_SPORT 20
#define TCP_DEFAULT_DPORT 80
#define TCP_DEFAULT_SEQ 0
#define TCP_DEFAULT_ACK 0
#define TCP_DEFAULT_FLAGS 0x02
#define TCP_DEFAULT_WIN 8192
#define TCP_DEFAULT_URP 0
/*
+--------+--------+---------+--------...
| Type | Len | Value
+--------+--------+---------+--------...
*/
struct nping_tcp_opt {
u8 type; /* Option type code. */
u8 len; /* Option length. */
u8 *value; /* Option value */
}__attribute__((__packed__));
typedef struct nping_tcp_opt nping_tcp_opt_t;
class TCPHeader : public TransportLayerElement {
private:
/*
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Source Port | Destination Port |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Sequence Number |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Acknowledgment Number |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Offset| Res. |C|E|U|A|P|R|S|F| Window |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Checksum | Urgent Pointer |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Options | Padding |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
struct nping_tcp_hdr {
u16 th_sport; /* Source port */
u16 th_dport; /* Destination port */
u32 th_seq; /* Sequence number */
u32 th_ack; /* Acknowledgement number */
#if WORDS_BIGENDIAN
u8 th_off:4; /* Data offset */
u8 th_x2:4; /* Reserved */
#else
u8 th_x2:4; /* Reserved */
u8 th_off:4; /* Data offset */
#endif
u8 th_flags; /* Flags */
u16 th_win; /* Window size */
u16 th_sum; /* Checksum */
u16 th_urp; /* Urgent pointer */
u8 options[MAX_TCP_OPTIONS_LEN ]; /* Space for TCP Options */
}__attribute__((__packed__));
typedef struct nping_tcp_hdr nping_tcp_hdr_t;
nping_tcp_hdr_t h;
int tcpoptlen; /**< Length of TCP options */
void __tcppacketoptinfo(const u8 *optp, int len, char *result, int bufsize) const;
public:
TCPHeader();
~TCPHeader();
void reset();
u8 *getBufferPointer();
int storeRecvData(const u8 *buf, size_t len);
int protocol_id() const;
int validate();
int print(FILE *output, int detail) const;
int setSourcePort(u16 p);
u16 getSourcePort() const;
int setDestinationPort(u16 p);
u16 getDestinationPort() const;
int setSeq(u32 p);
u32 getSeq() const;
int setAck(u32 p);
u32 getAck() const;
int setOffset(u8 o);
int setOffset();
u8 getOffset() const;
int setReserved(u8 r);
u8 getReserved() const;
int setFlags(u8 f);
u8 getFlags() const;
u16 getFlags16() const;
bool setCWR();
bool unsetCWR();
bool getCWR() const;
bool setECE();
bool unsetECE();
bool getECE() const;
bool setECN();
bool unsetECN();
bool getECN() const;
bool setURG();
bool unsetURG();
bool getURG() const;
bool setACK();
bool unsetACK();
bool getACK() const;
bool setPSH();
bool unsetPSH();
bool getPSH() const;
bool setRST();
bool unsetRST();
bool getRST() const;
bool setSYN();
bool unsetSYN();
bool getSYN() const;
bool setFIN();
bool unsetFIN();
bool getFIN() const;
int setWindow(u16 p);
u16 getWindow() const;
int setUrgPointer(u16 l);
u16 getUrgPointer() const;
int setSum(u16 s);
int setSum(struct in_addr source, struct in_addr destination);
int setSum();
int setSumRandom();
int setSumRandom(struct in_addr source, struct in_addr destination);
u16 getSum() const;
int setOptions(const u8 *optsbuff, size_t optslen);
const u8 *getOptions(size_t *optslen) const;
nping_tcp_opt_t getOption(unsigned int index) const;
static const char *optcode2str(u8 optcode);
}; /* End of class TCPHeader */
#endif /* __TCPHEADER_H__ */

View File

@@ -0,0 +1,156 @@
/***************************************************************************
* TransportLayerElement.cc -- Class TransportLayerElement is a generic *
* class that represents a transport layer protocol header. Classes like *
* TCPHeader or UDPHeader inherit from it. *
* *
***********************IMPORTANT NMAP LICENSE TERMS************************
* *
* The Nmap Security Scanner is (C) 1996-2011 Insecure.Com LLC. Nmap is *
* also a registered trademark of Insecure.Com LLC. This program is free *
* software; you may redistribute and/or modify it under the terms of the *
* GNU General Public License as published by the Free Software *
* Foundation; Version 2 with the clarifications and exceptions described *
* below. This guarantees your right to use, modify, and redistribute *
* this software under certain conditions. If you wish to embed Nmap *
* technology into proprietary software, we sell alternative licenses *
* (contact sales@insecure.com). Dozens of software vendors already *
* license Nmap technology such as host discovery, port scanning, OS *
* detection, and version detection. *
* *
* Note that the GPL places important restrictions on "derived works", yet *
* it does not provide a detailed definition of that term. To avoid *
* misunderstandings, we consider an application to constitute a *
* "derivative work" for the purpose of this license if it does any of the *
* following: *
* o Integrates source code from Nmap *
* o Reads or includes Nmap copyrighted data files, such as *
* nmap-os-db or nmap-service-probes. *
* o Executes Nmap and parses the results (as opposed to typical shell or *
* execution-menu apps, which simply display raw Nmap output and so are *
* not derivative works.) *
* o Integrates/includes/aggregates Nmap into a proprietary executable *
* installer, such as those produced by InstallShield. *
* o Links to a library or executes a program that does any of the above *
* *
* The term "Nmap" should be taken to also include any portions or derived *
* works of Nmap. This list is not exclusive, but is meant to clarify our *
* interpretation of derived works with some common examples. Our *
* interpretation applies only to Nmap--we don't speak for other people's *
* GPL works. *
* *
* If you have any questions about the GPL licensing restrictions on using *
* Nmap in non-GPL works, we would be happy to help. As mentioned above, *
* we also offer alternative license to integrate Nmap into proprietary *
* applications and appliances. These contracts have been sold to dozens *
* of software vendors, and generally include a perpetual license as well *
* as providing for priority support and updates as well as helping to *
* fund the continued development of Nmap technology. Please email *
* sales@insecure.com for further information. *
* *
* As a special exception to the GPL terms, Insecure.Com LLC grants *
* permission to link the code of this program with any version of the *
* OpenSSL library which is distributed under a license identical to that *
* listed in the included docs/licenses/OpenSSL.txt file, and distribute *
* linked combinations including the two. You must obey the GNU GPL in all *
* respects for all of the code used other than OpenSSL. If you modify *
* this file, you may extend this exception to your version of the file, *
* but you are not obligated to do so. *
* *
* If you received these files with a written license agreement or *
* contract stating terms other than the terms above, then that *
* alternative license agreement takes precedence over these comments. *
* *
* Source is provided to this software because we believe users have a *
* right to know exactly what a program is going to do before they run it. *
* This also allows you to audit the software for security holes (none *
* have been found so far). *
* *
* Source code also allows you to port Nmap to new platforms, fix bugs, *
* and add new features. You are highly encouraged to send your changes *
* to nmap-dev@insecure.org for possible incorporation into the main *
* distribution. By sending these changes to Fyodor or one of the *
* Insecure.Org development mailing lists, it is assumed that you are *
* offering the Nmap Project (Insecure.Com LLC) the unlimited, *
* non-exclusive right to reuse, modify, and relicense the code. Nmap *
* will always be available Open Source, but this is important because the *
* inability to relicense code has caused devastating problems for other *
* Free Software projects (such as KDE and NASM). We also occasionally *
* relicense the code to third parties as discussed above. If you wish to *
* specify special license conditions of your contributions, just say so *
* when you send them. *
* *
* This program is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* General Public License v2.0 for more details at *
* http://www.gnu.org/licenses/gpl-2.0.html , or in the COPYING file *
* included with Nmap. *
* *
***************************************************************************/
/* This code was originally part of the Nping tool. */
#include "TransportLayerElement.h"
#include "IPv4Header.h"
#include "IPv6Header.h"
/** Computes and returns the Internet checksum.
* @warning This method requires the object to be linked to either an IPv6Header
* object or an IPv4Header one, so the caller must ensure that objects are
* properly linked with calls to setNextElement() like this:
*
* IPv6Header ip6;
* TCPHeader tcp;
* [...] # Set header fields
* ip6.setNextElement(&tcp);
* tcp.setSum();
*
* Note that there can be a number of other headers (like IPv6 extension headers)
* between the transport header and the network one, but all of them need to
* be linked in order for this method to traverse the list of headers and find
* the IP source and destination address, required to compute the checksum. So
* things like the following are OK:
*
* IPv6Header ip6;
* HopByHopHeader hop;
* RoutingHeader rte;
* FragmentHeader frg;
* UDPHeader udp;
* [...] # Set whatever header fields you need
* ip6.setNextElement(&hop);
* hop.setNextElement(&rte);
* rte.setNextElement(&frg);
* frg.setNextElement(&udp);
* udp.setSum(); # setSum() will be able to reach the IPv6Header. */
u16 TransportLayerElement::compute_checksum(){
PacketElement *hdr;
hdr=this->getPrevElement();
u16 final_sum=0;
/* Traverse the list of headers backwards until we find an IP header */
while(hdr!=NULL){
if (hdr->protocol_id()==HEADER_TYPE_IPv6){
IPv6Header *v6hdr=(IPv6Header *)hdr;
struct in6_addr i6src, i6dst;
memcpy(i6src.s6_addr, v6hdr->getSourceAddress(), 16);
memcpy(i6dst.s6_addr, v6hdr->getDestinationAddress(), 16);
u8 *buff=(u8 *)safe_malloc(this->getLen());
this->dumpToBinaryBuffer(buff, this->getLen());
final_sum=ipv6_pseudoheader_cksum(&i6src, &i6dst, this->protocol_id(), this->getLen(), buff);
free(buff);
return final_sum;
}else if(hdr->protocol_id()==HEADER_TYPE_IPv4){
IPv4Header *v4hdr=(IPv4Header *)hdr;
struct in_addr i4src, i4dst;
memcpy(&(i4src.s_addr), v4hdr->getSourceAddress(), 4);
memcpy(&(i4dst.s_addr), v4hdr->getDestinationAddress(), 4);
u8 *buff=(u8 *)safe_malloc(this->getLen());
this->dumpToBinaryBuffer(buff, this->getLen());
final_sum=ipv4_pseudoheader_cksum(&i4src, &i4dst, this->protocol_id(), this->getLen(), buff);
free(buff);
return final_sum;
}else{
hdr=hdr->getPrevElement();
}
}
return 0;
} /* End of setSum() */

View File

@@ -0,0 +1,121 @@
/***************************************************************************
* TransportLayerElement.cc -- Class TransportLayerElement is a generic *
* class that represents a transport layer protocol header. Classes like *
* TCPHeader or UDPHeader inherit from it. *
* *
***********************IMPORTANT NMAP LICENSE TERMS************************
* *
* The Nmap Security Scanner is (C) 1996-2011 Insecure.Com LLC. Nmap is *
* also a registered trademark of Insecure.Com LLC. This program is free *
* software; you may redistribute and/or modify it under the terms of the *
* GNU General Public License as published by the Free Software *
* Foundation; Version 2 with the clarifications and exceptions described *
* below. This guarantees your right to use, modify, and redistribute *
* this software under certain conditions. If you wish to embed Nmap *
* technology into proprietary software, we sell alternative licenses *
* (contact sales@insecure.com). Dozens of software vendors already *
* license Nmap technology such as host discovery, port scanning, OS *
* detection, and version detection. *
* *
* Note that the GPL places important restrictions on "derived works", yet *
* it does not provide a detailed definition of that term. To avoid *
* misunderstandings, we consider an application to constitute a *
* "derivative work" for the purpose of this license if it does any of the *
* following: *
* o Integrates source code from Nmap *
* o Reads or includes Nmap copyrighted data files, such as *
* nmap-os-db or nmap-service-probes. *
* o Executes Nmap and parses the results (as opposed to typical shell or *
* execution-menu apps, which simply display raw Nmap output and so are *
* not derivative works.) *
* o Integrates/includes/aggregates Nmap into a proprietary executable *
* installer, such as those produced by InstallShield. *
* o Links to a library or executes a program that does any of the above *
* *
* The term "Nmap" should be taken to also include any portions or derived *
* works of Nmap. This list is not exclusive, but is meant to clarify our *
* interpretation of derived works with some common examples. Our *
* interpretation applies only to Nmap--we don't speak for other people's *
* GPL works. *
* *
* If you have any questions about the GPL licensing restrictions on using *
* Nmap in non-GPL works, we would be happy to help. As mentioned above, *
* we also offer alternative license to integrate Nmap into proprietary *
* applications and appliances. These contracts have been sold to dozens *
* of software vendors, and generally include a perpetual license as well *
* as providing for priority support and updates as well as helping to *
* fund the continued development of Nmap technology. Please email *
* sales@insecure.com for further information. *
* *
* As a special exception to the GPL terms, Insecure.Com LLC grants *
* permission to link the code of this program with any version of the *
* OpenSSL library which is distributed under a license identical to that *
* listed in the included docs/licenses/OpenSSL.txt file, and distribute *
* linked combinations including the two. You must obey the GNU GPL in all *
* respects for all of the code used other than OpenSSL. If you modify *
* this file, you may extend this exception to your version of the file, *
* but you are not obligated to do so. *
* *
* If you received these files with a written license agreement or *
* contract stating terms other than the terms above, then that *
* alternative license agreement takes precedence over these comments. *
* *
* Source is provided to this software because we believe users have a *
* right to know exactly what a program is going to do before they run it. *
* This also allows you to audit the software for security holes (none *
* have been found so far). *
* *
* Source code also allows you to port Nmap to new platforms, fix bugs, *
* and add new features. You are highly encouraged to send your changes *
* to nmap-dev@insecure.org for possible incorporation into the main *
* distribution. By sending these changes to Fyodor or one of the *
* Insecure.Org development mailing lists, it is assumed that you are *
* offering the Nmap Project (Insecure.Com LLC) the unlimited, *
* non-exclusive right to reuse, modify, and relicense the code. Nmap *
* will always be available Open Source, but this is important because the *
* inability to relicense code has caused devastating problems for other *
* Free Software projects (such as KDE and NASM). We also occasionally *
* relicense the code to third parties as discussed above. If you wish to *
* specify special license conditions of your contributions, just say so *
* when you send them. *
* *
* This program is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* General Public License v2.0 for more details at *
* http://www.gnu.org/licenses/gpl-2.0.html , or in the COPYING file *
* included with Nmap. *
* *
***************************************************************************/
/* This code was originally part of the Nping tool. */
#ifndef TRANSPORTLAYERELEMENT_H
#define TRANSPORTLAYERELEMENT_H 1
#include "PacketElement.h"
/// class TransportLayerElement -
class TransportLayerElement : public PacketElement {
public:
/* Returns source port. */
virtual u16 getSourcePort() const = 0;
/* Sets source port. */
virtual int setSourcePort(u16 val) = 0;
/* Returns destination port. */
virtual u16 getDestinationPort() const = 0;
/* Sets destination port. */
virtual int setDestinationPort(u16 val) = 0;
/* Sets checksum. */
virtual int setSum(u16 val) = 0;
protected:
u16 compute_checksum();
};
#endif

329
libnetutil/UDPHeader.cc Normal file
View File

@@ -0,0 +1,329 @@
/***************************************************************************
* UDPHeader.cc -- The UDPHeader Class represents a UDP packet. It *
* contains methods to set the different header fields. These methods *
* tipically perform the necessary error checks and byte order *
* conversions. *
* *
***********************IMPORTANT NMAP LICENSE TERMS************************
* *
* The Nmap Security Scanner is (C) 1996-2011 Insecure.Com LLC. Nmap is *
* also a registered trademark of Insecure.Com LLC. This program is free *
* software; you may redistribute and/or modify it under the terms of the *
* GNU General Public License as published by the Free Software *
* Foundation; Version 2 with the clarifications and exceptions described *
* below. This guarantees your right to use, modify, and redistribute *
* this software under certain conditions. If you wish to embed Nmap *
* technology into proprietary software, we sell alternative licenses *
* (contact sales@insecure.com). Dozens of software vendors already *
* license Nmap technology such as host discovery, port scanning, OS *
* detection, and version detection. *
* *
* Note that the GPL places important restrictions on "derived works", yet *
* it does not provide a detailed definition of that term. To avoid *
* misunderstandings, we consider an application to constitute a *
* "derivative work" for the purpose of this license if it does any of the *
* following: *
* o Integrates source code from Nmap *
* o Reads or includes Nmap copyrighted data files, such as *
* nmap-os-db or nmap-service-probes. *
* o Executes Nmap and parses the results (as opposed to typical shell or *
* execution-menu apps, which simply display raw Nmap output and so are *
* not derivative works.) *
* o Integrates/includes/aggregates Nmap into a proprietary executable *
* installer, such as those produced by InstallShield. *
* o Links to a library or executes a program that does any of the above *
* *
* The term "Nmap" should be taken to also include any portions or derived *
* works of Nmap. This list is not exclusive, but is meant to clarify our *
* interpretation of derived works with some common examples. Our *
* interpretation applies only to Nmap--we don't speak for other people's *
* GPL works. *
* *
* If you have any questions about the GPL licensing restrictions on using *
* Nmap in non-GPL works, we would be happy to help. As mentioned above, *
* we also offer alternative license to integrate Nmap into proprietary *
* applications and appliances. These contracts have been sold to dozens *
* of software vendors, and generally include a perpetual license as well *
* as providing for priority support and updates as well as helping to *
* fund the continued development of Nmap technology. Please email *
* sales@insecure.com for further information. *
* *
* As a special exception to the GPL terms, Insecure.Com LLC grants *
* permission to link the code of this program with any version of the *
* OpenSSL library which is distributed under a license identical to that *
* listed in the included docs/licenses/OpenSSL.txt file, and distribute *
* linked combinations including the two. You must obey the GNU GPL in all *
* respects for all of the code used other than OpenSSL. If you modify *
* this file, you may extend this exception to your version of the file, *
* but you are not obligated to do so. *
* *
* If you received these files with a written license agreement or *
* contract stating terms other than the terms above, then that *
* alternative license agreement takes precedence over these comments. *
* *
* Source is provided to this software because we believe users have a *
* right to know exactly what a program is going to do before they run it. *
* This also allows you to audit the software for security holes (none *
* have been found so far). *
* *
* Source code also allows you to port Nmap to new platforms, fix bugs, *
* and add new features. You are highly encouraged to send your changes *
* to nmap-dev@insecure.org for possible incorporation into the main *
* distribution. By sending these changes to Fyodor or one of the *
* Insecure.Org development mailing lists, it is assumed that you are *
* offering the Nmap Project (Insecure.Com LLC) the unlimited, *
* non-exclusive right to reuse, modify, and relicense the code. Nmap *
* will always be available Open Source, but this is important because the *
* inability to relicense code has caused devastating problems for other *
* Free Software projects (such as KDE and NASM). We also occasionally *
* relicense the code to third parties as discussed above. If you wish to *
* specify special license conditions of your contributions, just say so *
* when you send them. *
* *
* This program is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* General Public License v2.0 for more details at *
* http://www.gnu.org/licenses/gpl-2.0.html , or in the COPYING file *
* included with Nmap. *
* *
***************************************************************************/
/* This code was originally part of the Nping tool. */
#include "UDPHeader.h"
/******************************************************************************/
/* CONTRUCTORS, DESTRUCTORS AND INITIALIZATION METHODS */
/******************************************************************************/
UDPHeader::UDPHeader(){
this->reset();
} /* End of UDPHeader constructor */
UDPHeader::~UDPHeader(){
} /* End of UDPHeader destructor */
/** Sets every attribute to its default value */
void UDPHeader::reset(){
this->length=UDP_HEADER_LEN;
this->setSourcePort(UDP_DEFAULT_SPORT);
this->setDestinationPort(UDP_DEFAULT_DPORT);
this->setTotalLength(UDP_HEADER_LEN);
this->setSum(0);
} /* End of reset() */
/******************************************************************************/
/* PacketElement:: OVERWRITTEN METHODS */
/******************************************************************************/
/** @warning This method is essential for the superclass getBinaryBuffer()
* method to work. Do NOT change a thing unless you know what you're doing */
u8 * UDPHeader::getBufferPointer(){
return (u8*)(&h);
} /* End of getBufferPointer() */
/** Stores supplied packet in the internal buffer so the information
* can be accessed using the standard get & set methods.
* @warning The UDPHeader class is able to hold a maximum of 8 bytes. If the
* supplied buffer is longer than that, only the first 8 bytes will be stored
* in the internal buffer.
* @warning Supplied len MUST be at least 8 bytes (UDP header length).
* @return OP_SUCCESS on success and OP_FAILURE in case of error */
int UDPHeader::storeRecvData(const u8 *buf, size_t len){
if(buf==NULL || len<UDP_HEADER_LEN){
return OP_FAILURE;
}else{
this->reset(); /* Re-init the object, just in case the caller had used it already */
this->length=UDP_HEADER_LEN;
memcpy(&(this->h), buf, UDP_HEADER_LEN);
}
return OP_SUCCESS;
} /* End of storeRecvData() */
/* Returns a protocol identifier. This is used by packet parsing funtions
* that return linked lists of PacketElement objects, to determine the protocol
* the object represents. */
int UDPHeader::protocol_id() const {
return HEADER_TYPE_UDP;
} /* End of protocol_id() */
/** Determines if the data stored in the object after an storeRecvData() call
* is valid and safe to use. This mainly checks the length of the data but may
* also test the value of certain protocol fields to ensure their correctness.
* @return the length, in bytes, of the header, if its found to be valid or
* OP_FAILURE (-1) otherwise. */
int UDPHeader::validate(){
if( this->length!=UDP_HEADER_LEN)
return OP_FAILURE;
else
return UDP_HEADER_LEN;
} /* End of validate() */
/** Prints the contents of the header and calls print() on the next protocol
* header in the chain (if there is any).
* @return OP_SUCCESS on success and OP_FAILURE in case of error. */
int UDPHeader::print(FILE *output, int detail) const {
fprintf(output, "UDP[");
fprintf(output, "%d", this->getSourcePort());
fprintf(output, " >");
fprintf(output, " %d", this->getDestinationPort());
if(detail>=PRINT_DETAIL_HIGH)
fprintf(output, " len=%d", (int)this->getTotalLength() );
if(detail>=PRINT_DETAIL_MED)
fprintf(output, " csum=0x%04X", ntohs( this->getSum() ));
fprintf(output, "]");
if(this->next!=NULL){
print_separator(output, detail);
next->print(output, detail);
}
return OP_SUCCESS;
} /* End of print() */
/******************************************************************************/
/* PROTOCOL-SPECIFIC METHODS */
/******************************************************************************/
/** Sets source port.
* @warning Port must be supplied in host byte order. This method performs
* byte order conversion using htons() */
int UDPHeader::setSourcePort(u16 p){
h.uh_sport = htons(p);
return OP_SUCCESS;
} /* End of setSrcPort() */
/** Returns source port in HOST byte order */
u16 UDPHeader::getSourcePort() const {
return ntohs(h.uh_sport);
} /* End of getSrcPort() */
/** Sets destination port.
* @warning Port must be supplied in host byte order. This method performs
* byte order conversion using htons() */
int UDPHeader::setDestinationPort(u16 p){
h.uh_dport = htons(p);
return OP_SUCCESS;
} /* End of setDstPort() */
/** Returns destination port in HOST byte order */
u16 UDPHeader::getDestinationPort() const {
return ntohs(h.uh_dport);
} /* End of getDstPort() */
int UDPHeader::setSum(struct in_addr src, struct in_addr dst){
int bufflen;
u8 aux[ 65535-8 ];
/* FROM: RFC 5405 Unicast UDP Usage Guidelines, November 2008
* "A UDP datagram is carried in a single IP packet and is hence limited to
* a maximum payload of 65,507 bytes for IPv4 and 65,527 bytes for IPv6"
*
* So, UDP is supposed to be able to carry 65535-8 bytes but in fact it can
* only carry 65,507 or 65,527. However, we are not taking that into account
* here because UDP is supposed to be independent of IPv4, IPv6 or
* whatever other network layer protocol is used to carry the UDP datagrams.*/
h.uh_sum = 0;
/* Copy packet contents to a buffer */
bufflen=dumpToBinaryBuffer(aux, 65536-8 );
/* Compute checksum */
h.uh_sum = ipv4_pseudoheader_cksum(&src, &dst, IPPROTO_UDP,bufflen, (char *) aux);
return OP_SUCCESS;
} /* End of setSum() */
/** @warning Sum is set to supplied value with NO byte ordering conversion
* performed. */
int UDPHeader::setSum(u16 s){
h.uh_sum = s;
return OP_SUCCESS;
} /* End of setSum() */
int UDPHeader::setSum(){
this->h.uh_sum=0;
this->h.uh_sum = this->compute_checksum();
return OP_SUCCESS;
} /* End of setSum() */
/** Set the UDP checksum field to a random value, which may accidentally
* match the correct checksum */
int UDPHeader::setSumRandom(){
h.uh_sum=(1 + (get_random_u16()%(65535-1))); /* Discard value zero */
return OP_SUCCESS;
} /* End of setSumRandom() */
/** Set the UDP checksum field to a random value. It takes the source and
* destination address to make sure the random generated sum does not
* accidentally match the correct checksum. This function only handles
* IPv4 address. */
int UDPHeader::setSumRandom(struct in_addr source, struct in_addr destination){
u16 correct_csum=0;
/* Compute the correct checksum */
this->setSum(source, destination);
correct_csum=this->getSum();
/* Generate numbers until one does not match the correct sum */
while( (h.uh_sum=(1 + (get_random_u16()%(65535-1))))==correct_csum);
return OP_SUCCESS;
} /* End of setSumRandom() */
u16 UDPHeader::getSum() const {
return h.uh_sum;
} /* End of getSum() */
int UDPHeader::setTotalLength(){
int mylen = 8;
int otherslen=0;
if (next!=NULL)
otherslen=next->getLen();
/* FROM: RFC 5405 Unicast UDP Usage Guidelines, November 2008
* "A UDP datagram is carried in a single IP packet and is hence limited to
* a maximum payload of 65,507 bytes for IPv4 and 65,527 bytes for IPv6"
*
* So, UDP is supposed to be able to carry 65535-8 bytes but in fact it can
* only carry 65,507 or 65,527. However, we are not taking that into account
* here because UDP is supposed to be independent of IPv4, IPv6 or
* whatever other network layer protocol is used to carry the UDP datagrams.*/
if ((mylen+otherslen) > 65535 || (mylen+otherslen)<8 ){
printf("UDPHeader::setTotalLenght(): Invalid length.\n");
return OP_FAILURE;
}
h.uh_ulen=htons( mylen+otherslen );
return OP_SUCCESS;
} /* End of setTotalLenght() */
/** @warning Supplied value MUST be in HOST byte order */
int UDPHeader::setTotalLength(u16 l){
this->h.uh_ulen=htons(l);
return OP_SUCCESS;
} /* End of setTotalLenght() */
/** @warning Returned value is in HOST byte order */
u16 UDPHeader::getTotalLength() const {
return ntohs(this->h.uh_ulen);
} /* End of getTotalLenght() */

158
libnetutil/UDPHeader.h Normal file
View File

@@ -0,0 +1,158 @@
/***************************************************************************
* UDPHeader.h -- The UDPHeader Class represents a UDP packet. It contains *
* methods to set the different header fields. These methods tipically *
* perform the necessary error checks and byte order conversions. *
* *
***********************IMPORTANT NMAP LICENSE TERMS************************
* *
* The Nmap Security Scanner is (C) 1996-2011 Insecure.Com LLC. Nmap is *
* also a registered trademark of Insecure.Com LLC. This program is free *
* software; you may redistribute and/or modify it under the terms of the *
* GNU General Public License as published by the Free Software *
* Foundation; Version 2 with the clarifications and exceptions described *
* below. This guarantees your right to use, modify, and redistribute *
* this software under certain conditions. If you wish to embed Nmap *
* technology into proprietary software, we sell alternative licenses *
* (contact sales@insecure.com). Dozens of software vendors already *
* license Nmap technology such as host discovery, port scanning, OS *
* detection, and version detection. *
* *
* Note that the GPL places important restrictions on "derived works", yet *
* it does not provide a detailed definition of that term. To avoid *
* misunderstandings, we consider an application to constitute a *
* "derivative work" for the purpose of this license if it does any of the *
* following: *
* o Integrates source code from Nmap *
* o Reads or includes Nmap copyrighted data files, such as *
* nmap-os-db or nmap-service-probes. *
* o Executes Nmap and parses the results (as opposed to typical shell or *
* execution-menu apps, which simply display raw Nmap output and so are *
* not derivative works.) *
* o Integrates/includes/aggregates Nmap into a proprietary executable *
* installer, such as those produced by InstallShield. *
* o Links to a library or executes a program that does any of the above *
* *
* The term "Nmap" should be taken to also include any portions or derived *
* works of Nmap. This list is not exclusive, but is meant to clarify our *
* interpretation of derived works with some common examples. Our *
* interpretation applies only to Nmap--we don't speak for other people's *
* GPL works. *
* *
* If you have any questions about the GPL licensing restrictions on using *
* Nmap in non-GPL works, we would be happy to help. As mentioned above, *
* we also offer alternative license to integrate Nmap into proprietary *
* applications and appliances. These contracts have been sold to dozens *
* of software vendors, and generally include a perpetual license as well *
* as providing for priority support and updates as well as helping to *
* fund the continued development of Nmap technology. Please email *
* sales@insecure.com for further information. *
* *
* As a special exception to the GPL terms, Insecure.Com LLC grants *
* permission to link the code of this program with any version of the *
* OpenSSL library which is distributed under a license identical to that *
* listed in the included docs/licenses/OpenSSL.txt file, and distribute *
* linked combinations including the two. You must obey the GNU GPL in all *
* respects for all of the code used other than OpenSSL. If you modify *
* this file, you may extend this exception to your version of the file, *
* but you are not obligated to do so. *
* *
* If you received these files with a written license agreement or *
* contract stating terms other than the terms above, then that *
* alternative license agreement takes precedence over these comments. *
* *
* Source is provided to this software because we believe users have a *
* right to know exactly what a program is going to do before they run it. *
* This also allows you to audit the software for security holes (none *
* have been found so far). *
* *
* Source code also allows you to port Nmap to new platforms, fix bugs, *
* and add new features. You are highly encouraged to send your changes *
* to nmap-dev@insecure.org for possible incorporation into the main *
* distribution. By sending these changes to Fyodor or one of the *
* Insecure.Org development mailing lists, it is assumed that you are *
* offering the Nmap Project (Insecure.Com LLC) the unlimited, *
* non-exclusive right to reuse, modify, and relicense the code. Nmap *
* will always be available Open Source, but this is important because the *
* inability to relicense code has caused devastating problems for other *
* Free Software projects (such as KDE and NASM). We also occasionally *
* relicense the code to third parties as discussed above. If you wish to *
* specify special license conditions of your contributions, just say so *
* when you send them. *
* *
* This program is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* General Public License v2.0 for more details at *
* http://www.gnu.org/licenses/gpl-2.0.html , or in the COPYING file *
* included with Nmap. *
* *
***************************************************************************/
/* This code was originally part of the Nping tool. */
#ifndef UDPHEADER_H
#define UDPHEADER_H 1
#include "TransportLayerElement.h"
#define UDP_HEADER_LEN 8
/* Default header values */
#define UDP_DEFAULT_SPORT 53
#define UDP_DEFAULT_DPORT 53
class UDPHeader : public TransportLayerElement {
private:
/*
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Source Port | Destination Port |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Length | Checksum |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
struct nping_udp_hdr{
u16 uh_sport;
u16 uh_dport;
u16 uh_ulen;
u16 uh_sum;
}__attribute__((__packed__));
typedef struct nping_udp_hdr nping_udp_hdr_t;
nping_udp_hdr_t h;
public:
UDPHeader();
~UDPHeader();
void reset();
u8 *getBufferPointer();
int storeRecvData(const u8 *buf, size_t len);
int protocol_id() const;
int validate();
int print(FILE *output, int detail) const;
int setSourcePort(u16 p);
u16 getSourcePort() const;
int setDestinationPort(u16 p);
u16 getDestinationPort() const;
int setTotalLength();
int setTotalLength(u16 l);
u16 getTotalLength() const;
int setSum(struct in_addr source, struct in_addr destination);
int setSum(u16 s);
int setSum();
int setSumRandom();
int setSumRandom(struct in_addr source, struct in_addr destination);
u16 getSum() const;
}; /* End of class UDPHeader */
#endif

View File

@@ -74,10 +74,52 @@
</ClCompile> </ClCompile>
</ItemDefinitionGroup> </ItemDefinitionGroup>
<ItemGroup> <ItemGroup>
<ClCompile Include="ARPHeader.cc" />
<ClCompile Include="DestOptsHeader.cc" />
<ClCompile Include="EthernetHeader.cc" />
<ClCompile Include="FragmentHeader.cc" />
<ClCompile Include="HopByHopHeader.cc" />
<ClCompile Include="ICMPv4Header.cc" />
<ClCompile Include="ICMPv6Header.cc" />
<ClCompile Include="ICMPv6Option.cc" />
<ClCompile Include="ICMPv6RRBody.cc" />
<ClCompile Include="IPv4Header.cc" />
<ClCompile Include="IPv6Header.cc" />
<ClCompile Include="netutil.cc" /> <ClCompile Include="netutil.cc" />
<ClCompile Include="NetworkLayerElement.cc" />
<ClCompile Include="PacketElement.cc" />
<ClCompile Include="PacketParser.cc" />
<ClCompile Include="RawData.cc" />
<ClCompile Include="RoutingHeader.cc" />
<ClCompile Include="TCPHeader.cc" />
<ClCompile Include="TransportLayerElement.cc" />
<ClCompile Include="UDPHeader.cc" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ClInclude Include="ApplicationLayerElement.h" />
<ClInclude Include="ARPHeader.h" />
<ClInclude Include="DataLinkLayerElement.h" />
<ClInclude Include="DestOptsHeader.h" />
<ClInclude Include="EthernetHeader.h" />
<ClInclude Include="FragmentHeader.h" />
<ClInclude Include="HopByHopHeader.h" />
<ClInclude Include="ICMPHeader.h" />
<ClInclude Include="ICMPv4Header.h" />
<ClInclude Include="ICMPv6Header.h" />
<ClInclude Include="ICMPv6Option.h" />
<ClInclude Include="ICMPv6RRBody.h" />
<ClInclude Include="IPv4Header.h" />
<ClInclude Include="IPv6Header.h" />
<ClInclude Include="netutil.h" /> <ClInclude Include="netutil.h" />
<ClInclude Include="NetworkLayerElement.h" />
<ClInclude Include="npacket.h" />
<ClInclude Include="PacketElement.h" />
<ClInclude Include="PacketParser.h" />
<ClInclude Include="RawData.h" />
<ClInclude Include="RoutingHeader.h" />
<ClInclude Include="TCPHeader.h" />
<ClInclude Include="TransportLayerElement.h" />
<ClInclude Include="UDPHeader.h" />
</ItemGroup> </ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" /> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets"> <ImportGroup Label="ExtensionTargets">

View File

@@ -1677,14 +1677,18 @@ int islocalhost(const struct sockaddr_storage *const ss) {
/* Determines whether the supplied address corresponds to a private, /* Determines whether the supplied address corresponds to a private,
* non-Internet-routable address. See RFC1918 for details. * non-Internet-routable address. See RFC1918 for details.
* Returns 1 if the address is private or 0 otherwise. */ * Returns 1 if the address is private or 0 otherwise. */
int isipprivate(const struct in_addr *const addr) { int isipprivate(const struct sockaddr_storage *addr) {
const struct sockaddr_in *sin;
char *ipc; char *ipc;
unsigned char i1, i2; unsigned char i1, i2;
if (!addr) if (!addr)
return 0; return 0;
if (addr->ss_family != AF_INET)
return 0;
sin = (struct sockaddr_in *) addr;
ipc = (char *) &(addr->s_addr); ipc = (char *) &(sin->sin_addr.s_addr);
i1 = ipc[0]; i1 = ipc[0];
i2 = ipc[1]; i2 = ipc[1];

View File

@@ -106,6 +106,10 @@ extern "C" {
#include "dnet.h" #include "dnet.h"
/* It is VERY important to never change the value of these two constants.
* Specially, OP_FAILURE should never be positive, as some pieces of code take
* that for granted. */
enum { OP_FAILURE = -1, OP_SUCCESS = 0 }; enum { OP_FAILURE = -1, OP_SUCCESS = 0 };
@@ -383,7 +387,7 @@ int islocalhost(const struct sockaddr_storage *const ss);
/* Determines whether the supplied address corresponds to a private, /* Determines whether the supplied address corresponds to a private,
* non-Internet-routable address. See RFC1918 for details. * non-Internet-routable address. See RFC1918 for details.
* Returns 1 if the address is private or 0 otherwise. */ * Returns 1 if the address is private or 0 otherwise. */
int isipprivate(const struct in_addr *const addr); int isipprivate(const struct sockaddr_storage *addr);
/* Takes binary data found in the IP Options field of an IPv4 packet /* Takes binary data found in the IP Options field of an IPv4 packet
* and returns a string containing an ASCII description of the options * and returns a string containing an ASCII description of the options

119
libnetutil/npacket.cc Normal file
View File

@@ -0,0 +1,119 @@
/***************************************************************************
* netutil.h -- The main include file exposing the external API for *
* libnetutil, a library that provides network-related functions or *
* classes that make it easier to handle things like network interfaces, *
* routing tables, raw packet manipulation, etc. The lib was originally *
* written for use in the Nmap Security Scanner ( http://nmap.org ). *
* *
***********************IMPORTANT NMAP LICENSE TERMS************************
* *
* The Nmap Security Scanner is (C) 1996-2011 Insecure.Com LLC. Nmap is *
* also a registered trademark of Insecure.Com LLC. This program is free *
* software; you may redistribute and/or modify it under the terms of the *
* GNU General Public License as published by the Free Software *
* Foundation; Version 2 with the clarifications and exceptions described *
* below. This guarantees your right to use, modify, and redistribute *
* this software under certain conditions. If you wish to embed Nmap *
* technology into proprietary software, we sell alternative licenses *
* (contact sales@insecure.com). Dozens of software vendors already *
* license Nmap technology such as host discovery, port scanning, OS *
* detection, and version detection. *
* *
* Note that the GPL places important restrictions on "derived works", yet *
* it does not provide a detailed definition of that term. To avoid *
* misunderstandings, we consider an application to constitute a *
* "derivative work" for the purpose of this license if it does any of the *
* following: *
* o Integrates source code from Nmap *
* o Reads or includes Nmap copyrighted data files, such as *
* nmap-os-db or nmap-service-probes. *
* o Executes Nmap and parses the results (as opposed to typical shell or *
* execution-menu apps, which simply display raw Nmap output and so are *
* not derivative works.) *
* o Integrates/includes/aggregates Nmap into a proprietary executable *
* installer, such as those produced by InstallShield. *
* o Links to a library or executes a program that does any of the above *
* *
* The term "Nmap" should be taken to also include any portions or derived *
* works of Nmap. This list is not exclusive, but is meant to clarify our *
* interpretation of derived works with some common examples. Our *
* interpretation applies only to Nmap--we don't speak for other people's *
* GPL works. *
* *
* If you have any questions about the GPL licensing restrictions on using *
* Nmap in non-GPL works, we would be happy to help. As mentioned above, *
* we also offer alternative license to integrate Nmap into proprietary *
* applications and appliances. These contracts have been sold to dozens *
* of software vendors, and generally include a perpetual license as well *
* as providing for priority support and updates as well as helping to *
* fund the continued development of Nmap technology. Please email *
* sales@insecure.com for further information. *
* *
* As a special exception to the GPL terms, Insecure.Com LLC grants *
* permission to link the code of this program with any version of the *
* OpenSSL library which is distributed under a license identical to that *
* listed in the included docs/licenses/OpenSSL.txt file, and distribute *
* linked combinations including the two. You must obey the GNU GPL in all *
* respects for all of the code used other than OpenSSL. If you modify *
* this file, you may extend this exception to your version of the file, *
* but you are not obligated to do so. *
* *
* If you received these files with a written license agreement or *
* contract stating terms other than the terms above, then that *
* alternative license agreement takes precedence over these comments. *
* *
* Source is provided to this software because we believe users have a *
* right to know exactly what a program is going to do before they run it. *
* This also allows you to audit the software for security holes (none *
* have been found so far). *
* *
* Source code also allows you to port Nmap to new platforms, fix bugs, *
* and add new features. You are highly encouraged to send your changes *
* to nmap-dev@insecure.org for possible incorporation into the main *
* distribution. By sending these changes to Fyodor or one of the *
* Insecure.Org development mailing lists, it is assumed that you are *
* offering the Nmap Project (Insecure.Com LLC) the unlimited, *
* non-exclusive right to reuse, modify, and relicense the code. Nmap *
* will always be available Open Source, but this is important because the *
* inability to relicense code has caused devastating problems for other *
* Free Software projects (such as KDE and NASM). We also occasionally *
* relicense the code to third parties as discussed above. If you wish to *
* specify special license conditions of your contributions, just say so *
* when you send them. *
* *
* This program is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* General Public License v2.0 for more details at *
* http://www.gnu.org/licenses/gpl-2.0.html , or in the COPYING file *
* included with Nmap. *
* *
***************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
/* Uncomment the following lines to enable debugging output */
//#ifndef NPACKET_DEBUG
//#define NPACKET_DEBUG 1
//#endif
/* Print debug messages to stdout and then return. A newline
* character is printed automatically after the supplied text.*/
void npacket_debug(const char *str, ...){
#ifdef NPACKET_DEBUG
va_list list;
char errstr[1025];
memset(errstr,0, 1024);
va_start(list, str);
fflush(stdout);
vfprintf(stdout, str, list);
fprintf(stdout,"\n");
va_end(list);
#endif
} /* End of npacket_debug() */

128
libnetutil/npacket.h Normal file
View File

@@ -0,0 +1,128 @@
/***************************************************************************
* netutil.h -- The main include file exposing the external API for *
* libnetutil, a library that provides network-related functions or *
* classes that make it easier to handle things like network interfaces, *
* routing tables, raw packet manipulation, etc. The lib was originally *
* written for use in the Nmap Security Scanner ( http://nmap.org ). *
* *
***********************IMPORTANT NMAP LICENSE TERMS************************
* *
* The Nmap Security Scanner is (C) 1996-2011 Insecure.Com LLC. Nmap is *
* also a registered trademark of Insecure.Com LLC. This program is free *
* software; you may redistribute and/or modify it under the terms of the *
* GNU General Public License as published by the Free Software *
* Foundation; Version 2 with the clarifications and exceptions described *
* below. This guarantees your right to use, modify, and redistribute *
* this software under certain conditions. If you wish to embed Nmap *
* technology into proprietary software, we sell alternative licenses *
* (contact sales@insecure.com). Dozens of software vendors already *
* license Nmap technology such as host discovery, port scanning, OS *
* detection, and version detection. *
* *
* Note that the GPL places important restrictions on "derived works", yet *
* it does not provide a detailed definition of that term. To avoid *
* misunderstandings, we consider an application to constitute a *
* "derivative work" for the purpose of this license if it does any of the *
* following: *
* o Integrates source code from Nmap *
* o Reads or includes Nmap copyrighted data files, such as *
* nmap-os-db or nmap-service-probes. *
* o Executes Nmap and parses the results (as opposed to typical shell or *
* execution-menu apps, which simply display raw Nmap output and so are *
* not derivative works.) *
* o Integrates/includes/aggregates Nmap into a proprietary executable *
* installer, such as those produced by InstallShield. *
* o Links to a library or executes a program that does any of the above *
* *
* The term "Nmap" should be taken to also include any portions or derived *
* works of Nmap. This list is not exclusive, but is meant to clarify our *
* interpretation of derived works with some common examples. Our *
* interpretation applies only to Nmap--we don't speak for other people's *
* GPL works. *
* *
* If you have any questions about the GPL licensing restrictions on using *
* Nmap in non-GPL works, we would be happy to help. As mentioned above, *
* we also offer alternative license to integrate Nmap into proprietary *
* applications and appliances. These contracts have been sold to dozens *
* of software vendors, and generally include a perpetual license as well *
* as providing for priority support and updates as well as helping to *
* fund the continued development of Nmap technology. Please email *
* sales@insecure.com for further information. *
* *
* As a special exception to the GPL terms, Insecure.Com LLC grants *
* permission to link the code of this program with any version of the *
* OpenSSL library which is distributed under a license identical to that *
* listed in the included docs/licenses/OpenSSL.txt file, and distribute *
* linked combinations including the two. You must obey the GNU GPL in all *
* respects for all of the code used other than OpenSSL. If you modify *
* this file, you may extend this exception to your version of the file, *
* but you are not obligated to do so. *
* *
* If you received these files with a written license agreement or *
* contract stating terms other than the terms above, then that *
* alternative license agreement takes precedence over these comments. *
* *
* Source is provided to this software because we believe users have a *
* right to know exactly what a program is going to do before they run it. *
* This also allows you to audit the software for security holes (none *
* have been found so far). *
* *
* Source code also allows you to port Nmap to new platforms, fix bugs, *
* and add new features. You are highly encouraged to send your changes *
* to nmap-dev@insecure.org for possible incorporation into the main *
* distribution. By sending these changes to Fyodor or one of the *
* Insecure.Org development mailing lists, it is assumed that you are *
* offering the Nmap Project (Insecure.Com LLC) the unlimited, *
* non-exclusive right to reuse, modify, and relicense the code. Nmap *
* will always be available Open Source, but this is important because the *
* inability to relicense code has caused devastating problems for other *
* Free Software projects (such as KDE and NASM). We also occasionally *
* relicense the code to third parties as discussed above. If you wish to *
* specify special license conditions of your contributions, just say so *
* when you send them. *
* *
* This program is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* General Public License v2.0 for more details at *
* http://www.gnu.org/licenses/gpl-2.0.html , or in the COPYING file *
* included with Nmap. *
* *
***************************************************************************/
/* $Id: npacket.h 18098 2010-06-14 11:50:12Z luis $ */
#ifndef __NPACKET_H__
#define __NPACKET_H__ 1
#include "ApplicationLayerElement.h"
#include "ARPHeader.h"
#include "DataLinkLayerElement.h"
#include "EthernetHeader.h"
#include "ICMPHeader.h"
#include "ICMPv4Header.h"
#include "ICMPv6Header.h"
#include "ICMPv6Option.h"
#include "ICMPv6RRBody.h"
#include "IPv4Header.h"
#include "IPv6Header.h"
#include "NetworkLayerElement.h"
#include "PacketElement.h"
#include "RawData.h"
#include "TCPHeader.h"
#include "TransportLayerElement.h"
#include "UDPHeader.h"
#include "HopByHopHeader.h"
#include "DestOptsHeader.h"
#include "FragmentHeader.h"
#include "RoutingHeader.h"
#include "PacketParser.h"
void npacket_debug(const char *str, ...)
__attribute__ ((noreturn))
__attribute__ ((format (printf, 1, 2)));
#endif /* __NPACKET_H__ */

View File

@@ -175,6 +175,9 @@ them both to 0; an emulation function will be used. */
/* Define to the one symbol short name of this package. */ /* Define to the one symbol short name of this package. */
#undef PACKAGE_TARNAME #undef PACKAGE_TARNAME
/* Define to the home page for this package. */
#undef PACKAGE_URL
/* Define to the version of this package. */ /* Define to the version of this package. */
#undef PACKAGE_VERSION #undef PACKAGE_VERSION

View File

@@ -1,8 +1,9 @@
Microsoft Visual Studio Solution File, Format Version 11.00 Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010 # Visual C++ Express 2010
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "nmap", "nmap.vcxproj", "{361719F0-AB42-4C93-9DE8-7D2144B96625}" Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "nmap", "nmap.vcxproj", "{361719F0-AB42-4C93-9DE8-7D2144B96625}"
ProjectSection(ProjectDependencies) = postProject ProjectSection(ProjectDependencies) = postProject
{99157C3F-39F6-4663-99D7-1D9C1484494E} = {99157C3F-39F6-4663-99D7-1D9C1484494E} {99157C3F-39F6-4663-99D7-1D9C1484494E} = {99157C3F-39F6-4663-99D7-1D9C1484494E}
{A7BE3D76-F20C-40C5-8986-DE4028B3B57D} = {A7BE3D76-F20C-40C5-8986-DE4028B3B57D}
EndProjectSection EndProjectSection
EndProject EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "nsock", "..\nsock\nsock.vcxproj", "{F8D6D1E3-D4EA-402C-98AA-168E5309BAF4}" Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "nsock", "..\nsock\nsock.vcxproj", "{F8D6D1E3-D4EA-402C-98AA-168E5309BAF4}"
@@ -21,6 +22,8 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "nping", "..\nping\nping.vcx
EndProject EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libnetutil", "..\libnetutil\libnetutil.vcxproj", "{99157C3F-39F6-4663-99D7-1D9C1484494E}" Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libnetutil", "..\libnetutil\libnetutil.vcxproj", "{99157C3F-39F6-4663-99D7-1D9C1484494E}"
EndProject EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "liblinear", "..\liblinear\liblinear.vcxproj", "{A7BE3D76-F20C-40C5-8986-DE4028B3B57D}"
EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Win32 = Debug|Win32 Debug|Win32 = Debug|Win32
@@ -76,6 +79,12 @@ Global
{99157C3F-39F6-4663-99D7-1D9C1484494E}.Ncat Static|Win32.ActiveCfg = Release|Win32 {99157C3F-39F6-4663-99D7-1D9C1484494E}.Ncat Static|Win32.ActiveCfg = Release|Win32
{99157C3F-39F6-4663-99D7-1D9C1484494E}.Release|Win32.ActiveCfg = Release|Win32 {99157C3F-39F6-4663-99D7-1D9C1484494E}.Release|Win32.ActiveCfg = Release|Win32
{99157C3F-39F6-4663-99D7-1D9C1484494E}.Release|Win32.Build.0 = Release|Win32 {99157C3F-39F6-4663-99D7-1D9C1484494E}.Release|Win32.Build.0 = Release|Win32
{A7BE3D76-F20C-40C5-8986-DE4028B3B57D}.Debug|Win32.ActiveCfg = Debug|Win32
{A7BE3D76-F20C-40C5-8986-DE4028B3B57D}.Debug|Win32.Build.0 = Debug|Win32
{A7BE3D76-F20C-40C5-8986-DE4028B3B57D}.Ncat Static|Win32.ActiveCfg = Release|Win32
{A7BE3D76-F20C-40C5-8986-DE4028B3B57D}.Ncat Static|Win32.Build.0 = Release|Win32
{A7BE3D76-F20C-40C5-8986-DE4028B3B57D}.Release|Win32.ActiveCfg = Release|Win32
{A7BE3D76-F20C-40C5-8986-DE4028B3B57D}.Release|Win32.Build.0 = Release|Win32
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE

View File

@@ -54,7 +54,7 @@
</Midl> </Midl>
<ClCompile> <ClCompile>
<Optimization>Disabled</Optimization> <Optimization>Disabled</Optimization>
<AdditionalIncludeDirectories>..\liblua;.;..;../nbase;../libpcre;winip;..\nsock\include;pcap-include;..\libdnet-stripped\include;OpenSSL\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> <AdditionalIncludeDirectories>..\liblua;.;..;../nbase;../libpcre;winip;..\nsock\include;pcap-include;..\libdnet-stripped\include;OpenSSL\include;..\liblinear;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> <PreprocessorDefinitions>WIN32;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PreprocessToFile>false</PreprocessToFile> <PreprocessToFile>false</PreprocessToFile>
<PreprocessSuppressLineNumbers>false</PreprocessSuppressLineNumbers> <PreprocessSuppressLineNumbers>false</PreprocessSuppressLineNumbers>
@@ -73,10 +73,10 @@
<CompileAs>CompileAsCpp</CompileAs> <CompileAs>CompileAsCpp</CompileAs>
</ClCompile> </ClCompile>
<Link> <Link>
<AdditionalDependencies>liblua.lib;nsock.lib;libpcre.lib;nbase.lib;libdnet-stripped.lib;ws2_32.lib;IPHlpAPI.Lib;wpcap.lib;packet.lib;advapi32.lib;libeay32.lib;ssleay32.lib;shell32.lib;libnetutil.lib</AdditionalDependencies> <AdditionalDependencies>liblua.lib;nsock.lib;libpcre.lib;nbase.lib;libdnet-stripped.lib;liblinear.lib;ws2_32.lib;IPHlpAPI.Lib;wpcap.lib;packet.lib;advapi32.lib;libeay32.lib;ssleay32.lib;shell32.lib;libnetutil.lib</AdditionalDependencies>
<OutputFile>.\Debug\nmap.exe</OutputFile> <OutputFile>.\Debug\nmap.exe</OutputFile>
<SuppressStartupBanner>true</SuppressStartupBanner> <SuppressStartupBanner>true</SuppressStartupBanner>
<AdditionalLibraryDirectories>lib;..\liblua;..\libpcre;..\nsock;..\nbase;..\libdnet-stripped;../libnetutil;OpenSSL\lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories> <AdditionalLibraryDirectories>lib;..\liblua;..\libpcre;..\nsock;..\nbase;..\libdnet-stripped;../libnetutil;OpenSSL\lib;..\liblinear;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<IgnoreSpecificDefaultLibraries>%(IgnoreSpecificDefaultLibraries)</IgnoreSpecificDefaultLibraries> <IgnoreSpecificDefaultLibraries>%(IgnoreSpecificDefaultLibraries)</IgnoreSpecificDefaultLibraries>
<DelayLoadDLLs>packet.dll;wpcap.dll;iphlpapi.dll;%(DelayLoadDLLs)</DelayLoadDLLs> <DelayLoadDLLs>packet.dll;wpcap.dll;iphlpapi.dll;%(DelayLoadDLLs)</DelayLoadDLLs>
<GenerateDebugInformation>true</GenerateDebugInformation> <GenerateDebugInformation>true</GenerateDebugInformation>
@@ -100,7 +100,7 @@
<ClCompile> <ClCompile>
<Optimization>MaxSpeed</Optimization> <Optimization>MaxSpeed</Optimization>
<InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion> <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
<AdditionalIncludeDirectories>.;..;../liblua;../nbase;../libpcre;winip;..\nsock\include;pcap-include;..\libdnet-stripped\include;OpenSSL\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> <AdditionalIncludeDirectories>.;..;../liblua;../nbase;../libpcre;winip;..\nsock\include;pcap-include;..\libdnet-stripped\include;OpenSSL\include;..\liblinear;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> <PreprocessorDefinitions>WIN32;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<StringPooling>true</StringPooling> <StringPooling>true</StringPooling>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary> <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
@@ -115,10 +115,10 @@
<CompileAs>CompileAsCpp</CompileAs> <CompileAs>CompileAsCpp</CompileAs>
</ClCompile> </ClCompile>
<Link> <Link>
<AdditionalDependencies>liblua.lib;nsock.lib;libpcre.lib;nbase.lib;libdnet-stripped.lib;ws2_32.lib;IPHlpAPI.Lib;wpcap.lib;packet.lib;advapi32.lib;libeay32.lib;ssleay32.lib;shell32.lib;libnetutil.lib</AdditionalDependencies> <AdditionalDependencies>liblua.lib;nsock.lib;libpcre.lib;nbase.lib;libdnet-stripped.lib;liblinear.lib;ws2_32.lib;IPHlpAPI.Lib;wpcap.lib;packet.lib;advapi32.lib;libeay32.lib;ssleay32.lib;shell32.lib;libnetutil.lib</AdditionalDependencies>
<OutputFile>.\Release/nmap.exe</OutputFile> <OutputFile>.\Release/nmap.exe</OutputFile>
<SuppressStartupBanner>true</SuppressStartupBanner> <SuppressStartupBanner>true</SuppressStartupBanner>
<AdditionalLibraryDirectories>lib;..\liblua;..\libpcre;..\nsock;..\nbase;..\libdnet-stripped;../libnetutil;OpenSSL\lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories> <AdditionalLibraryDirectories>lib;..\liblua;..\libpcre;..\nsock;..\nbase;..\libdnet-stripped;../libnetutil;OpenSSL\lib;..\liblinear;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<IgnoreSpecificDefaultLibraries>%(IgnoreSpecificDefaultLibraries)</IgnoreSpecificDefaultLibraries> <IgnoreSpecificDefaultLibraries>%(IgnoreSpecificDefaultLibraries)</IgnoreSpecificDefaultLibraries>
<DelayLoadDLLs>packet.dll;wpcap.dll;iphlpapi.dll;%(DelayLoadDLLs)</DelayLoadDLLs> <DelayLoadDLLs>packet.dll;wpcap.dll;iphlpapi.dll;%(DelayLoadDLLs)</DelayLoadDLLs>
<ProgramDatabaseFile>.\Release/nmap.pdb</ProgramDatabaseFile> <ProgramDatabaseFile>.\Release/nmap.pdb</ProgramDatabaseFile>
@@ -134,6 +134,8 @@
<ItemGroup> <ItemGroup>
<ClCompile Include="..\charpool.cc" /> <ClCompile Include="..\charpool.cc" />
<ClCompile Include="..\FingerPrintResults.cc" /> <ClCompile Include="..\FingerPrintResults.cc" />
<ClCompile Include="..\FPEngine.cc" />
<ClCompile Include="..\FPmodel.cc" />
<ClCompile Include="..\idle_scan.cc" /> <ClCompile Include="..\idle_scan.cc" />
<ClCompile Include="..\MACLookup.cc" /> <ClCompile Include="..\MACLookup.cc" />
<ClCompile Include="..\main.cc" /> <ClCompile Include="..\main.cc" />
@@ -185,6 +187,7 @@
<ItemGroup> <ItemGroup>
<ClInclude Include="..\charpool.h" /> <ClInclude Include="..\charpool.h" />
<ClInclude Include="..\FingerPrintResults.h" /> <ClInclude Include="..\FingerPrintResults.h" />
<ClInclude Include="..\FPEngine.h" />
<ClInclude Include="..\global_structures.h" /> <ClInclude Include="..\global_structures.h" />
<ClInclude Include="..\idle_scan.h" /> <ClInclude Include="..\idle_scan.h" />
<ClInclude Include="..\MACLookup.h" /> <ClInclude Include="..\MACLookup.h" />

13
nmap.cc
View File

@@ -940,8 +940,7 @@ void parse_options(int argc, char **argv) {
o.script = 1; o.script = 1;
#endif #endif
if (o.isr00t) { if (o.isr00t) {
if (o.af() == AF_INET) o.osscan++;
o.osscan++;
o.traceroute = true; o.traceroute = true;
} }
break; break;
@@ -1306,8 +1305,10 @@ void apply_delayed_options() {
if (delayed_options.pre_host_timeout != -1) o.host_timeout = delayed_options.pre_host_timeout; if (delayed_options.pre_host_timeout != -1) o.host_timeout = delayed_options.pre_host_timeout;
if (o.osscan) if (o.osscan) {
o.reference_FPs = parse_fingerprint_reference_file("nmap-os-db"); o.reference_FPs = parse_fingerprint_reference_file("nmap-os-db");
o.os_labels_ipv6 = load_fp_matches();
}
validate_scan_lists(ports,o); validate_scan_lists(ports,o);
o.ValidateOptions(); o.ValidateOptions();
@@ -1945,8 +1946,10 @@ int nmap_main(int argc, char *argv[]) {
} }
} }
if (o.osscan) if (o.osscan){
os_scan2(Targets); OSScan os_engine;
os_engine.os_scan(Targets);
}
if (o.traceroute) if (o.traceroute)
traceroute(Targets); traceroute(Targets);

4
nmap.h
View File

@@ -252,8 +252,8 @@ void *realloc();
#ifndef NMAP_VERSION #ifndef NMAP_VERSION
/* Edit this definition only within the quotes, because it is read from this /* Edit this definition only within the quotes, because it is read from this
file by the makefiles. */ file by the makefiles. */
#define NMAP_VERSION "5.59BETA3" #define NMAP_VERSION "5.59BETA1"
#define NMAP_NUM_VERSION "5.59.0.3" #define NMAP_NUM_VERSION "5.59.0.1"
#endif #endif
/* User configurable #defines: */ /* User configurable #defines: */

View File

@@ -184,7 +184,7 @@ void set_hostinfo(lua_State *L, Target *currenths) {
lua_newtable(L); lua_newtable(L);
// this will run at least one time and at most 8 times, see if condition // this will run at least one time and at most 8 times, see if condition
for(i = 0; FPR->accuracy[i] == 1; i++) { for(i = 0; FPR->accuracy[i] == 1; i++) {
lua_pushstring(L, FPR->prints[i]->OS_name); lua_pushstring(L, FPR->matches[i]->OS_name);
lua_rawseti(L, -2, i+1); lua_rawseti(L, -2, i+1);
} }
lua_setfield(L, -2, "os"); lua_setfield(L, -2, "os");

View File

@@ -206,8 +206,6 @@ FingerPrintDB::~FingerPrintDB() {
} }
FingerPrint::FingerPrint() { FingerPrint::FingerPrint() {
line = 0;
OS_name = NULL;
} }
const struct AVal *FingerTest::getattrbyname(const char *name) const { const struct AVal *FingerTest::getattrbyname(const char *name) const {
@@ -460,11 +458,11 @@ double compare_fingerprints(FingerPrint *referenceFP, FingerPrint *observedFP,
/* Takes a fingerprint and looks for matches inside the passed in /* Takes a fingerprint and looks for matches inside the passed in
reference fingerprint DB. The results are stored in in FPR (which reference fingerprint DB. The results are stored in in FPR (which
must point to an instantiated FingerPrintResults class) -- results must point to an instantiated FingerPrintResultsIPv4 class) -- results
will be reverse-sorted by accuracy. No results below will be reverse-sorted by accuracy. No results below
accuracy_threshhold will be included. The max matches returned is accuracy_threshhold will be included. The max matches returned is
the maximum that fits in a FingerPrintResults class. */ the maximum that fits in a FingerPrintResultsIPv4 class. */
void match_fingerprint(FingerPrint *FP, FingerPrintResults *FPR, void match_fingerprint(FingerPrint *FP, FingerPrintResultsIPv4 *FPR,
FingerPrintDB *DB, double accuracy_threshold) { FingerPrintDB *DB, double accuracy_threshold) {
double FPR_entrance_requirement = accuracy_threshold; /* accuracy must be double FPR_entrance_requirement = accuracy_threshold; /* accuracy must be
at least this big at least this big
@@ -474,10 +472,10 @@ void match_fingerprint(FingerPrint *FP, FingerPrintResults *FPR,
double acc; double acc;
int state; int state;
int skipfp; int skipfp;
int max_prints = sizeof(FPR->prints) / sizeof(FingerPrint *); int max_prints = sizeof(FPR->matches) / sizeof(FPR->matches[0]);
int idx; int idx;
double tmp_acc=0.0, tmp_acc2; /* These are temp buffers for list swaps */ double tmp_acc=0.0, tmp_acc2; /* These are temp buffers for list swaps */
FingerPrint *tmp_FP = NULL, *tmp_FP2; FingerMatch *tmp_FP = NULL, *tmp_FP2;
assert(FP); assert(FP);
assert(FPR); assert(FPR);
@@ -495,12 +493,12 @@ void match_fingerprint(FingerPrint *FP, FingerPrintResults *FPR,
state = 0; state = 0;
for (idx=0; idx < FPR->num_matches; idx++) { for (idx=0; idx < FPR->num_matches; idx++) {
if (strcmp(FPR->prints[idx]->OS_name, (*current_os)->OS_name) == 0) { if (strcmp(FPR->matches[idx]->OS_name, (*current_os)->match.OS_name) == 0) {
if (FPR->accuracy[idx] >= acc) { if (FPR->accuracy[idx] >= acc) {
skipfp = 1; /* Skip it -- a higher version is already in list */ skipfp = 1; /* Skip it -- a higher version is already in list */
} else { } else {
/* We must shift the list left to delete this sucker */ /* We must shift the list left to delete this sucker */
memmove(FPR->prints + idx, FPR->prints + idx + 1, memmove(FPR->matches + idx, FPR->matches + idx + 1,
(FPR->num_matches - 1 - idx) * sizeof(FingerPrint *)); (FPR->num_matches - 1 - idx) * sizeof(FingerPrint *));
memmove(FPR->accuracy + idx, FPR->accuracy + idx + 1, memmove(FPR->accuracy + idx, FPR->accuracy + idx + 1,
(FPR->num_matches - 1 - idx) * sizeof(double)); (FPR->num_matches - 1 - idx) * sizeof(double));
@@ -528,18 +526,18 @@ void match_fingerprint(FingerPrint *FP, FingerPrintResults *FPR,
if (state == 1) { if (state == 1) {
/* Push tmp_acc and tmp_FP onto the next idx */ /* Push tmp_acc and tmp_FP onto the next idx */
tmp_acc2 = FPR->accuracy[idx+1]; tmp_acc2 = FPR->accuracy[idx+1];
tmp_FP2 = FPR->prints[idx+1]; tmp_FP2 = FPR->matches[idx+1];
FPR->accuracy[idx+1] = tmp_acc; FPR->accuracy[idx+1] = tmp_acc;
FPR->prints[idx+1] = tmp_FP; FPR->matches[idx+1] = tmp_FP;
tmp_acc = tmp_acc2; tmp_acc = tmp_acc2;
tmp_FP = tmp_FP2; tmp_FP = tmp_FP2;
} else if (FPR->accuracy[idx + 1] < acc) { } else if (FPR->accuracy[idx + 1] < acc) {
/* OK, I insert the sucker into the next slot ... */ /* OK, I insert the sucker into the next slot ... */
tmp_acc = FPR->accuracy[idx+1]; tmp_acc = FPR->accuracy[idx+1];
tmp_FP = FPR->prints[idx+1]; tmp_FP = FPR->matches[idx+1];
FPR->prints[idx+1] = *current_os; FPR->matches[idx+1] = &(*current_os)->match;
FPR->accuracy[idx+1] = acc; FPR->accuracy[idx+1] = acc;
state = 1; state = 1;
} }
@@ -595,8 +593,9 @@ static const char *dist_method_fp_string(enum dist_calc_method method)
top of a fingerprint. Gives info which might be useful when the top of a fingerprint. Gives info which might be useful when the
FPrint is submitted (eg Nmap version, etc). Result is written (up FPrint is submitted (eg Nmap version, etc). Result is written (up
to ostrlen) to the ostr var passed in */ to ostrlen) to the ostr var passed in */
static void WriteSInfo(char *ostr, int ostrlen, bool isGoodFP, void WriteSInfo(char *ostr, int ostrlen, bool isGoodFP,
const struct in_addr * const addr, int distance, const char *engine_id,
const struct sockaddr_storage *addr, int distance,
enum dist_calc_method distance_calculation_method, enum dist_calc_method distance_calculation_method,
const u8 *mac, int openTcpPort, const u8 *mac, int openTcpPort,
int closedTcpPort, int closedUdpPort) { int closedTcpPort, int closedUdpPort) {
@@ -629,8 +628,8 @@ static void WriteSInfo(char *ostr, int ostrlen, bool isGoodFP,
if (mac) if (mac)
Snprintf(macbuf, sizeof(macbuf), "%%M=%02X%02X%02X", mac[0], mac[1], mac[2]); Snprintf(macbuf, sizeof(macbuf), "%%M=%02X%02X%02X", mac[0], mac[1], mac[2]);
Snprintf(ostr, ostrlen, "SCAN(V=%s%%D=%d/%d%%OT=%s%%CT=%s%%CU=%s%%PV=%c%s%s%%G=%c%s%%TM=%X%%P=%s)", Snprintf(ostr, ostrlen, "SCAN(V=%s%%E=%s%%D=%d/%d%%OT=%s%%CT=%s%%CU=%s%%PV=%c%s%s%%G=%c%s%%TM=%X%%P=%s)",
NMAP_VERSION, ltime->tm_mon + 1, ltime->tm_mday, NMAP_VERSION, engine_id, ltime->tm_mon + 1, ltime->tm_mday,
otbuf, ctbuf, cubuf, isipprivate(addr) ? 'Y' : 'N', dsbuf, dcbuf, isGoodFP ? 'Y' : 'N', otbuf, ctbuf, cubuf, isipprivate(addr) ? 'Y' : 'N', dsbuf, dcbuf, isGoodFP ? 'Y' : 'N',
macbuf, (int) timep, NMAP_PLATFORM); macbuf, (int) timep, NMAP_PLATFORM);
} }
@@ -804,7 +803,7 @@ static bool FingerTest_lessthan(const FingerTest* a, const FingerTest* b) {
are included only once. If wrapit is true, the string is wrapped for are included only once. If wrapit is true, the string is wrapped for
submission. */ submission. */
const char *mergeFPs(FingerPrint *FPs[], int numFPs, bool isGoodFP, const char *mergeFPs(FingerPrint *FPs[], int numFPs, bool isGoodFP,
const struct in_addr * const addr, int distance, const struct sockaddr_storage *addr, int distance,
enum dist_calc_method distance_calculation_method, enum dist_calc_method distance_calculation_method,
const u8 *mac, int openTcpPort, int closedTcpPort, const u8 *mac, int openTcpPort, int closedTcpPort,
int closedUdpPort, bool wrapit) { int closedUdpPort, bool wrapit) {
@@ -872,7 +871,7 @@ const char *mergeFPs(FingerPrint *FPs[], int numFPs, bool isGoodFP,
p = str; p = str;
/* Lets start by writing the fake "SCAN" test for submitting fingerprints */ /* Lets start by writing the fake "SCAN" test for submitting fingerprints */
WriteSInfo(p, sizeof(str), isGoodFP, addr, distance, distance_calculation_method, mac, openTcpPort, closedTcpPort, closedUdpPort); WriteSInfo(p, sizeof(str), isGoodFP, "4", addr, distance, distance_calculation_method, mac, openTcpPort, closedTcpPort, closedUdpPort);
p = p + strlen(str); p = p + strlen(str);
if (!wrapit) if (!wrapit)
*p++ = '\n'; *p++ = '\n';
@@ -997,16 +996,16 @@ static void parse_classline(FingerPrint *FP, char *thisline, int lineno) {
end = strchr(begin, '\0'); end = strchr(begin, '\0');
os_class.Device_Type = string_pool_substr_strip(begin, end); os_class.Device_Type = string_pool_substr_strip(begin, end);
FP->OS_class.push_back(os_class); FP->match.OS_class.push_back(os_class);
} }
static void parse_cpeline(FingerPrint *FP, char *thisline, int lineno) { static void parse_cpeline(FingerPrint *FP, char *thisline, int lineno) {
const char *cpe; const char *cpe;
if (FP->OS_class.empty()) if (FP->match.OS_class.empty())
fatal("\"CPE\" line without preceding \"Class\" at line %d", lineno); fatal("\"CPE\" line without preceding \"Class\" at line %d", lineno);
OS_Classification& osc = FP->OS_class.back(); OS_Classification& osc = FP->match.OS_class.back();
if (thisline == NULL || strncmp(thisline, "CPE ", 4) != 0) if (thisline == NULL || strncmp(thisline, "CPE ", 4) != 0)
fatal("Bogus line #%d (%s) passed to %s()", lineno, thisline, __func__); fatal("Bogus line #%d (%s) passed to %s()", lineno, thisline, __func__);
@@ -1050,7 +1049,7 @@ FingerPrint *parse_single_fingerprint(char *fprint_orig) {
if (strncmp(thisline, "Fingerprint ", 12) == 0) { if (strncmp(thisline, "Fingerprint ", 12) == 0) {
/* Ignore a second Fingerprint line if it appears. */ /* Ignore a second Fingerprint line if it appears. */
if (FP->OS_name == NULL) { if (FP->match.OS_name == NULL) {
p = thisline + 12; p = thisline + 12;
while (*p && isspace((int) (unsigned char) *p)) while (*p && isspace((int) (unsigned char) *p))
p++; p++;
@@ -1061,9 +1060,9 @@ FingerPrint *parse_single_fingerprint(char *fprint_orig) {
while (q > p && isspace((int) (unsigned char) *(--q))) while (q > p && isspace((int) (unsigned char) *(--q)))
; ;
FP->OS_name = (char *) cp_alloc(q - p + 2); FP->match.OS_name = (char *) cp_alloc(q - p + 2);
memcpy(FP->OS_name, p, q - p + 1); memcpy(FP->match.OS_name, p, q - p + 1);
FP->OS_name[q - p + 1] = '\0'; FP->match.OS_name[q - p + 1] = '\0';
} }
} else if (strncmp(thisline, "MatchPoints", 11) == 0) { } else if (strncmp(thisline, "MatchPoints", 11) == 0) {
p = thisline + 11; p = thisline + 11;
@@ -1150,7 +1149,7 @@ fparse:
current = new FingerPrint; current = new FingerPrint;
if (parsingMatchPoints) { if (parsingMatchPoints) {
current->OS_name = NULL; current->match.OS_name = NULL;
DB->MatchPoints = current; DB->MatchPoints = current;
} else { } else {
DB->prints.push_back(current); DB->prints.push_back(current);
@@ -1168,12 +1167,12 @@ fparse:
if (q < p) if (q < p)
fatal("Parse error on line %d of fingerprint: %s", lineno, line); fatal("Parse error on line %d of fingerprint: %s", lineno, line);
current->OS_name = (char *) cp_alloc(q - p + 2); current->match.OS_name = (char *) cp_alloc(q - p + 2);
memcpy(current->OS_name, p, q - p + 1); memcpy(current->match.OS_name, p, q - p + 1);
current->OS_name[q - p + 1] = '\0'; current->match.OS_name[q - p + 1] = '\0';
} }
current->line = lineno; current->match.line = lineno;
/* Now we read the fingerprint itself */ /* Now we read the fingerprint itself */
while (fgets(line, sizeof(line), fp)) { while (fgets(line, sizeof(line), fp)) {

View File

@@ -144,18 +144,24 @@ double compare_fingerprints(FingerPrint *referenceFP, FingerPrint *observedFP,
/* Takes a fingerprint and looks for matches inside the passed in /* Takes a fingerprint and looks for matches inside the passed in
reference fingerprint DB. The results are stored in in FPR (which reference fingerprint DB. The results are stored in in FPR (which
must point to an instantiated FingerPrintResults class) -- results must point to an instantiated FingerPrintResultsIPv4 class) -- results
will be reverse-sorted by accuracy. No results below will be reverse-sorted by accuracy. No results below
accuracy_threshhold will be included. The max matches returned is accuracy_threshhold will be included. The max matches returned is
the maximum that fits in a FingerPrintResults class. */ the maximum that fits in a FingerPrintResultsIPv4 class. */
void match_fingerprint(FingerPrint *FP, FingerPrintResults *FPR, void match_fingerprint(FingerPrint *FP, FingerPrintResultsIPv4 *FPR,
FingerPrintDB *DB, double accuracy_threshold); FingerPrintDB *DB, double accuracy_threshold);
/* Returns true if perfect match -- if num_subtests & num_subtests_succeeded are non_null it updates them. if shortcircuit is zero, it does all the tests, otherwise it returns when the first one fails */ /* Returns true if perfect match -- if num_subtests & num_subtests_succeeded are non_null it updates them. if shortcircuit is zero, it does all the tests, otherwise it returns when the first one fails */
void freeFingerPrint(FingerPrint *FP); void freeFingerPrint(FingerPrint *FP);
void WriteSInfo(char *ostr, int ostrlen, bool isGoodFP,
const char *engine_id,
const struct sockaddr_storage *addr, int distance,
enum dist_calc_method distance_calculation_method,
const u8 *mac, int openTcpPort,
int closedTcpPort, int closedUdpPort);
const char *mergeFPs(FingerPrint *FPs[], int numFPs, bool isGoodFP, const char *mergeFPs(FingerPrint *FPs[], int numFPs, bool isGoodFP,
const struct in_addr * const addr, int distance, const struct sockaddr_storage *addr, int distance,
enum dist_calc_method distance_calculation_method, enum dist_calc_method distance_calculation_method,
const u8 *mac, int openTcpPort, int closedTcpPort, const u8 *mac, int openTcpPort, int closedTcpPort,
int closedUdpPort, bool wrapit); int closedUdpPort, bool wrapit);

View File

@@ -97,6 +97,7 @@
#include "NmapOps.h" #include "NmapOps.h"
#include "Target.h" #include "Target.h"
#include "utils.h" #include "utils.h"
#include "FPEngine.h"
#include <dnet.h> #include <dnet.h>
#include <list> #include <list>
@@ -755,8 +756,8 @@ static void endRound(OsScanInfo *OSI, HostOsScan *HOS, int roundNum) {
HOS->makeFP(hsi->hss); HOS->makeFP(hsi->hss);
hsi->FPs[roundNum] = hsi->hss->getFP(); hsi->FPs[roundNum] = hsi->hss->getFP();
hsi->target->FPR->FPs[roundNum] = hsi->FPs[roundNum]; hsi->FPR->FPs[roundNum] = hsi->FPs[roundNum];
hsi->target->FPR->numFPs = roundNum + 1; hsi->FPR->numFPs = roundNum + 1;
double tr = hsi->hss->timingRatio(); double tr = hsi->hss->timingRatio();
hsi->target->FPR->maxTimingRatio = MAX(hsi->target->FPR->maxTimingRatio, tr); hsi->target->FPR->maxTimingRatio = MAX(hsi->target->FPR->maxTimingRatio, tr);
match_fingerprint(hsi->FPs[roundNum], &hsi->FP_matches[roundNum], match_fingerprint(hsi->FPs[roundNum], &hsi->FP_matches[roundNum],
@@ -768,7 +769,7 @@ static void endRound(OsScanInfo *OSI, HostOsScan *HOS, int roundNum) {
if (roundNum > 0) { if (roundNum > 0) {
if(o.verbose) log_write(LOG_STDOUT, "WARNING: OS didn't match until try #%d\n", roundNum + 1); if(o.verbose) log_write(LOG_STDOUT, "WARNING: OS didn't match until try #%d\n", roundNum + 1);
} }
match_fingerprint(hsi->target->FPR->FPs[roundNum], hsi->target->FPR, match_fingerprint(hsi->FPR->FPs[roundNum], hsi->FPR,
o.reference_FPs, OSSCAN_GUESS_THRESHOLD); o.reference_FPs, OSSCAN_GUESS_THRESHOLD);
hsi->isCompleted = true; hsi->isCompleted = true;
} }
@@ -810,7 +811,7 @@ static void findBestFPs(OsScanInfo *OSI) {
/* Now lets find the best match */ /* Now lets find the best match */
bestacc = 0; bestacc = 0;
bestaccidx = 0; bestaccidx = 0;
for(i=0; i < hsi->target->FPR->numFPs; i++) { for(i=0; i < hsi->FPR->numFPs; i++) {
if (hsi->FP_matches[i].overall_results == OSSCAN_SUCCESS && if (hsi->FP_matches[i].overall_results == OSSCAN_SUCCESS &&
hsi->FP_matches[i].num_matches > 0 && hsi->FP_matches[i].num_matches > 0 &&
hsi->FP_matches[i].accuracy[0] > bestacc) { hsi->FP_matches[i].accuracy[0] > bestacc) {
@@ -824,7 +825,7 @@ static void findBestFPs(OsScanInfo *OSI) {
// Now we redo the match, since target->FPR has various data (such as // Now we redo the match, since target->FPR has various data (such as
// target->FPR->numFPs) which is not in FP_matches[bestaccidx]. This is // target->FPR->numFPs) which is not in FP_matches[bestaccidx]. This is
// kinda ugly. // kinda ugly.
match_fingerprint(hsi->target->FPR->FPs[bestaccidx], hsi->target->FPR, match_fingerprint(hsi->FPR->FPs[bestaccidx], (FingerPrintResultsIPv4 *) hsi->target->FPR,
o.reference_FPs, OSSCAN_GUESS_THRESHOLD); o.reference_FPs, OSSCAN_GUESS_THRESHOLD);
} }
} }
@@ -833,17 +834,17 @@ static void findBestFPs(OsScanInfo *OSI) {
static void printFP(OsScanInfo *OSI) { static void printFP(OsScanInfo *OSI) {
list<HostOsScanInfo *>::iterator hostI; list<HostOsScanInfo *>::iterator hostI;
HostOsScanInfo *hsi = NULL; HostOsScanInfo *hsi = NULL;
FingerPrintResults *FPR; FingerPrintResultsIPv4 *FPR;
for(hostI = OSI->incompleteHosts.begin(); hostI != OSI->incompleteHosts.end(); hostI++) { for(hostI = OSI->incompleteHosts.begin(); hostI != OSI->incompleteHosts.end(); hostI++) {
hsi = *hostI; hsi = *hostI;
FPR = hsi->target->FPR; FPR = hsi->FPR;
log_write(LOG_NORMAL|LOG_SKID_NOXLT|LOG_STDOUT, log_write(LOG_NORMAL|LOG_SKID_NOXLT|LOG_STDOUT,
"No OS matches for %s by new os scan system.\n\nTCP/IP fingerprint:\n%s", "No OS matches for %s by new os scan system.\n\nTCP/IP fingerprint:\n%s",
hsi->target->targetipstr(), hsi->target->targetipstr(),
mergeFPs(FPR->FPs, FPR->numFPs, true, mergeFPs(FPR->FPs, FPR->numFPs, true,
hsi->target->v4hostip(), hsi->target->distance, hsi->target->TargetSockAddr(), hsi->target->distance,
hsi->target->distance_calculation_method, hsi->target->distance_calculation_method,
hsi->target->MACAddress(), hsi->target->MACAddress(),
FPR->osscan_opentcpport, FPR->osscan_closedtcpport, FPR->osscan_opentcpport, FPR->osscan_closedtcpport,
@@ -871,7 +872,7 @@ static int expireUnmatchedHosts(OsScanInfo *OSI, list<HostOsScanInfo *> *unMatch
if (HOS->target->FPR->OmitSubmissionFP()) if (HOS->target->FPR->OmitSubmissionFP())
max_tries = min(max_tries, STANDARD_OS2_TRIES); max_tries = min(max_tries, STANDARD_OS2_TRIES);
if (HOS->target->FPR->numFPs >= max_tries) { if (HOS->FPR->numFPs >= max_tries) {
/* We've done all the OS2 tries we're going to do ... move this /* We've done all the OS2 tries we're going to do ... move this
to unMatchedHosts */ to unMatchedHosts */
HOS->target->stopTimeOutClock(&now); HOS->target->stopTimeOutClock(&now);
@@ -886,108 +887,6 @@ static int expireUnmatchedHosts(OsScanInfo *OSI, list<HostOsScanInfo *> *unMatch
} }
/* You should call os_scan2 rather than this function, as that version handles
chunking so you don't do too many targets in parallel */
static int os_scan_2(vector<Target *> &Targets) {
// Hosts which haven't matched and have been removed from
// incompleteHosts because they have exceeded the number of
// retransmissions the host is allowed.
list<HostOsScanInfo *> unMatchedHosts;
int itry;
if (Targets.size() == 0) {
return 1;
}
init_perf_values();
OsScanInfo OSI(Targets);
if (OSI.numIncompleteHosts() == 0) {
/* no one will be scanned */
return 1;
}
OSI.starttime = o.TimeSinceStart();
startTimeOutClocks(&OSI);
HostOsScan HOS(Targets[0]);
itry = 0;
begin_sniffer(&HOS, Targets); /* initial the pcap session handler in HOS */
while(OSI.numIncompleteHosts() != 0) {
if (itry > 0) sleep(1);
if (itry == 3) usleep(1500000); /* Try waiting a little longer just in case it matters */
if (o.verbose) {
char targetstr[128];
bool plural = (OSI.numIncompleteHosts() != 1);
if (!plural) {
(*(OSI.incompleteHosts.begin()))->target->NameIP(targetstr, sizeof(targetstr));
} else Snprintf(targetstr, sizeof(targetstr), "%d hosts", (int) OSI.numIncompleteHosts());
log_write(LOG_STDOUT, "%s OS detection (try #%d) against %s\n", (itry == 0)? "Initiating" : "Retrying", itry + 1, targetstr);
log_flush_all();
}
startRound(&OSI, &HOS, itry);
doSeqTests(&OSI, &HOS);
doTUITests(&OSI, &HOS);
endRound(&OSI, &HOS, itry);
expireUnmatchedHosts(&OSI, &unMatchedHosts);
itry++;
}
/* Now move the unMatchedHosts array back to IncompleteHosts */
if (!unMatchedHosts.empty())
OSI.incompleteHosts.splice(OSI.incompleteHosts.begin(), unMatchedHosts);
if (OSI.numIncompleteHosts()) {
/* For host that doesn't have a perfect match, we do the following
things. */
/* Find the most matching item in the db. */
findBestFPs(&OSI);
/* Print the fp in debug mode.
Normally let output.cc to print the FP. */
if(o.debugging > 1)
printFP(&OSI);
}
return 0;
}
/* This is the primary OS detection function. If many Targets are
passed in (the threshold is based on timing level), they are
processed as smaller groups to improve accuracy */
void os_scan2(vector<Target *> &Targets) {
unsigned int max_os_group_sz = 20;
double fudgeratio = 1.2; /* Allow a slightly larger final group rather than finish with a tiny one */
vector<Target *> tmpTargets;
unsigned int startidx = 0;
if (o.timing_level == 4)
max_os_group_sz = (unsigned int) (max_os_group_sz * 1.5);
if (o.timing_level > 4 || Targets.size() <= max_os_group_sz * fudgeratio) {
os_scan_2(Targets);
return;
}
/* We need to split it up */
while(startidx < Targets.size()) {
int diff = Targets.size() - startidx;
if (diff > max_os_group_sz * fudgeratio) {
diff = max_os_group_sz;
}
tmpTargets.assign(Targets.begin() + startidx, Targets.begin() + startidx + diff);
os_scan_2(tmpTargets);
startidx += diff;
}
return;
}
/****************************************************************************** /******************************************************************************
* Implementation of class OFProbe * * Implementation of class OFProbe *
******************************************************************************/ ******************************************************************************/
@@ -3364,12 +3263,14 @@ HostOsScanInfo::HostOsScanInfo(Target *t, OsScanInfo *OsSI) {
OSI = OsSI; OSI = OsSI;
FPs = (FingerPrint **) safe_zalloc(o.maxOSTries() * sizeof(FingerPrint *)); FPs = (FingerPrint **) safe_zalloc(o.maxOSTries() * sizeof(FingerPrint *));
FP_matches = (FingerPrintResults *) safe_zalloc(o.maxOSTries() * sizeof(FingerPrintResults)); FP_matches = (FingerPrintResultsIPv4 *) safe_zalloc(o.maxOSTries() * sizeof(FingerPrintResultsIPv4));
timedOut = false; timedOut = false;
isCompleted = false; isCompleted = false;
if (target->FPR == NULL) if (target->FPR == NULL) {
target->FPR = new FingerPrintResults; this->FPR = new FingerPrintResultsIPv4;
target->FPR = this->FPR;
}
target->osscanSetFlag(OS_PERF); target->osscanSetFlag(OS_PERF);
hss = new HostOsScanStats(t); hss = new HostOsScanStats(t);
@@ -3521,3 +3422,180 @@ int OsScanInfo::removeCompletedHosts() {
} }
return hostsRemoved; return hostsRemoved;
} }
/******************************************************************************
* Implementation of class OSScan() *
******************************************************************************/
/* Constructor */
OSScan::OSScan() {
this->reset();
return;
}
/* Destructor */
OSScan::~OSScan() {
return;
}
/* Function that initializes internal variables */
void OSScan::reset(){
}
/* This function takes a group of targets and divides it in chunks if there are
* too many to be processed at the same time. The threshold is based on Nmap's
* timing level (when timing level is above 4, no chunking is performed).
* The reason targets are processed in smaller groups is to improve accuracy. */
int OSScan::chunk_and_do_scan(vector<Target *> &Targets, int family) {
unsigned int max_os_group_sz = 20;
double fudgeratio = 1.2; /* Allow a slightly larger final group rather than finish with a tiny one */
vector<Target *> tmpTargets;
unsigned int startidx = 0;
if (o.timing_level == 4)
max_os_group_sz = (unsigned int) (max_os_group_sz * 1.5);
if (o.timing_level > 4 || Targets.size() <= max_os_group_sz * fudgeratio) {
if(family==AF_INET6)
os_scan_ipv6(Targets);
else
os_scan_ipv4(Targets);
return OP_SUCCESS;
}
/* We need to split it up */
while(startidx < Targets.size()) {
int diff = Targets.size() - startidx;
if (diff > max_os_group_sz * fudgeratio) {
diff = max_os_group_sz;
}
tmpTargets.assign(Targets.begin() + startidx, Targets.begin() + startidx + diff);
if(family==AF_INET6)
os_scan_ipv6(Targets);
else
os_scan_ipv4(Targets);
startidx += diff;
}
return OP_SUCCESS;
}
/* Performs the OS detection for IPv4 hosts. This method should not be called
* directly. os_scan() should be used instead, as it handles chunking so
* you don't do too many targets in parallel */
int OSScan::os_scan_ipv4(vector<Target *> &Targets) {
int itry=0;
/* Hosts which haven't matched and have been removed from incompleteHosts because
* they have exceeded the number of retransmissions the host is allowed. */
list<HostOsScanInfo *> unMatchedHosts;
/* Check we have at least one target*/
if (Targets.size() == 0) {
return OP_FAILURE;
}
/* Init the necessary objects to perform the detection */
init_perf_values();
OsScanInfo OSI(Targets);
if (OSI.numIncompleteHosts() == 0) {
/* no one will be scanned */
return OP_FAILURE;
}
OSI.starttime = o.TimeSinceStart();
startTimeOutClocks(&OSI);
HostOsScan HOS(Targets[0]);
/* Initialize the pcap session handler in HOS */
begin_sniffer(&HOS, Targets);
while(OSI.numIncompleteHosts() != 0) {
if (itry > 0) sleep(1);
if (itry == 3) usleep(1500000); /* Try waiting a little longer just in case it matters */
if (o.verbose) {
char targetstr[128];
bool plural = (OSI.numIncompleteHosts() != 1);
if (!plural) {
(*(OSI.incompleteHosts.begin()))->target->NameIP(targetstr, sizeof(targetstr));
} else Snprintf(targetstr, sizeof(targetstr), "%d hosts", (int) OSI.numIncompleteHosts());
log_write(LOG_STDOUT, "%s OS detection (try #%d) against %s\n", (itry == 0)? "Initiating" : "Retrying", itry + 1, targetstr);
log_flush_all();
}
startRound(&OSI, &HOS, itry);
doSeqTests(&OSI, &HOS);
doTUITests(&OSI, &HOS);
endRound(&OSI, &HOS, itry);
expireUnmatchedHosts(&OSI, &unMatchedHosts);
itry++;
}
/* Now move the unMatchedHosts array back to IncompleteHosts */
if (!unMatchedHosts.empty())
OSI.incompleteHosts.splice(OSI.incompleteHosts.begin(), unMatchedHosts);
if (OSI.numIncompleteHosts()) {
/* For hosts that don't have a perfect match, find the closest fingerprint
* in the DB and, if we are in debugging mode, print them. */
findBestFPs(&OSI);
if(o.debugging > 1)
printFP(&OSI);
}
return OP_SUCCESS;
}
/* Performs the OS detection for IPv6 hosts. This method should not be called
* directly. os_scan() should be used instead, as it handles chunking so
* you don't do too many targets in parallel */
int OSScan::os_scan_ipv6(vector<Target *> &Targets) {
/* Object instantiation */
FPEngine6 fp6;
/* Safe checks. */
if (Targets.size() == 0) {
return OP_FAILURE;
}
return fp6.os_scan(Targets);
}
/* This function performs the OS detection. It processes the supplied list of
* targets and classifies it into two groups: IPv4 and IPv6 targets. Then,
* OS detection is carried out for those two separate groups. It returns
* OP_SUCCESS on success or OP_FAILURE in case of error. */
int OSScan::os_scan(vector<Target *> &Targets){
vector<Target *> ip4_targets;
vector<Target *> ip6_targets;
int res4=OP_SUCCESS, res6=OP_SUCCESS;
/* Make sure we have at least one target */
if(Targets.size()<=0)
return OP_FAILURE;
/* Classify targets into two groups: IPv4 and IPv6 */
for(size_t i=0; i<Targets.size(); i++){
if(Targets[i]->af()==AF_INET6)
ip6_targets.push_back(Targets[i]);
else
ip4_targets.push_back(Targets[i]);
}
/* Do IPv4 OS Detection */
if( ip4_targets.size()>0 )
res4=this->os_scan_ipv4(ip4_targets);
/* Do IPv6 OS Detection */
if( ip6_targets.size()>0 )
res6=this->os_scan_ipv6(ip6_targets);
/* If both scans were succesful, return OK */
if(res4==OP_SUCCESS && res6==OP_SUCCESS)
return OP_SUCCESS;
else
return OP_FAILURE;
}

View File

@@ -511,13 +511,34 @@ class HostOsScanInfo {
~HostOsScanInfo(); ~HostOsScanInfo();
Target *target; /* The target */ Target *target; /* The target */
FingerPrintResultsIPv4 *FPR;
OsScanInfo *OSI; /* The OSI which contains this HostOsScanInfo */ OsScanInfo *OSI; /* The OSI which contains this HostOsScanInfo */
FingerPrint **FPs; /* Fingerprints of the host */ FingerPrint **FPs; /* Fingerprints of the host */
FingerPrintResults *FP_matches; /* Fingerprint-matching results */ FingerPrintResultsIPv4 *FP_matches; /* Fingerprint-matching results */
bool timedOut; /* Did it time out? */ bool timedOut; /* Did it time out? */
bool isCompleted; /* Has the OS detection been completed? */ bool isCompleted; /* Has the OS detection been completed? */
HostOsScanStats *hss; /* Scan status of the host in one scan round */ HostOsScanStats *hss; /* Scan status of the host in one scan round */
}; };
/** This is the class that performs OS detection (both IPv4 and IPv6).
* Using it is simple, just call os_scan() passing a list of targets.
* The results of the detection will be stored inside the supplied
* target objects. */
class OSScan {
private:
int ip_ver; /* IP version for the OS Scan (4 or 6) */
int chunk_and_do_scan(vector<Target *> &Targets, int family);
int os_scan_ipv4(vector<Target *> &Targets);
int os_scan_ipv6(vector<Target *> &Targets);
public:
OSScan();
~OSScan();
void reset();
int os_scan(vector<Target *> &Targets);
};
#endif /*OSSCAN2_H*/ #endif /*OSSCAN2_H*/

210
output.cc
View File

@@ -114,6 +114,7 @@
#include <set> #include <set>
#include <vector> #include <vector>
#include <list> #include <list>
#include <sstream>
/* Workaround for lack of namespace std on HP-UX 11.00 */ /* Workaround for lack of namespace std on HP-UX 11.00 */
namespace std {}; namespace std {};
@@ -1499,7 +1500,7 @@ static void printosclassificationoutput(const struct
// Now to create the fodder for normal output // Now to create the fodder for normal output
for (classno = 0; classno < OSR->OSC_num_matches; classno++) { for (classno = 0; classno < OSR->OSC_num_matches; classno++) {
/* We have processed enough if any of the following are true */ /* We have processed enough if any of the following are true */
if ((!guess && OSR->OSC_Accuracy[classno] < 1.0) || if ((!guess && classno >= OSR->OSC_num_perfect_matches) ||
OSR->OSC_Accuracy[classno] <= OSR->OSC_Accuracy[0] - 0.1 || OSR->OSC_Accuracy[classno] <= OSR->OSC_Accuracy[0] - 0.1 ||
(OSR->OSC_Accuracy[classno] < 1.0 && classno > 9)) (OSR->OSC_Accuracy[classno] < 1.0 && classno > 9))
break; break;
@@ -1563,14 +1564,14 @@ static void printosclassificationoutput(const struct
log_write(LOG_PLAIN, "Device type: "); log_write(LOG_PLAIN, "Device type: ");
for (classno = 0; classno < numtypes; classno++) for (classno = 0; classno < numtypes; classno++)
log_write(LOG_PLAIN, "%s%s", types[classno], (classno < numtypes - 1) ? "|" : ""); log_write(LOG_PLAIN, "%s%s", types[classno], (classno < numtypes - 1) ? "|" : "");
log_write(LOG_PLAIN, "\nRunning%s: ", (familyaccuracy[0] < 1.0) ? " (JUST GUESSING)" : ""); log_write(LOG_PLAIN, "\nRunning%s: ", OSR->OSC_num_perfect_matches == 0 ? " (JUST GUESSING)" : "");
for (familyno = 0; familyno < numfamilies; familyno++) { for (familyno = 0; familyno < numfamilies; familyno++) {
if (familyno > 0) if (familyno > 0)
log_write(LOG_PLAIN, ", "); log_write(LOG_PLAIN, ", ");
log_write(LOG_PLAIN, "%s", fullfamily[familyno]); log_write(LOG_PLAIN, "%s", fullfamily[familyno]);
if (*familygenerations[familyno]) if (*familygenerations[familyno])
log_write(LOG_PLAIN, " %s", familygenerations[familyno]); log_write(LOG_PLAIN, " %s", familygenerations[familyno]);
if (familyaccuracy[familyno] < 1.0) if (familyno >= OSR->OSC_num_perfect_matches)
log_write(LOG_PLAIN, " (%.f%%)", log_write(LOG_PLAIN, " (%.f%%)",
floor(familyaccuracy[familyno] * 100)); floor(familyaccuracy[familyno] * 100));
} }
@@ -1609,28 +1610,187 @@ void printmacinfo(Target *currenths) {
/* A convenience wrapper around mergeFPs. */ /* A convenience wrapper around mergeFPs. */
static const char *merge_fpr(const FingerPrintResults *FPR, const char *FingerPrintResultsIPv4::merge_fpr(const Target *currenths,
const Target *currenths, bool isGoodFP, bool wrapit) const {
bool isGoodFP, bool wrapit) { return mergeFPs(this->FPs, this->numFPs, isGoodFP, currenths->TargetSockAddr(),
return mergeFPs(FPR->FPs, FPR->numFPs, isGoodFP, currenths->v4hostip(),
currenths->distance, currenths->distance,
currenths->distance_calculation_method, currenths->distance_calculation_method,
currenths->MACAddress(), FPR->osscan_opentcpport, currenths->MACAddress(), this->osscan_opentcpport,
FPR->osscan_closedtcpport, FPR->osscan_closedudpport, this->osscan_closedtcpport, this->osscan_closedudpport,
wrapit); wrapit);
} }
/* Run-length encode a string in chunks of two bytes. The output sequence
AA{n} means to repeat AA n times. The input must not contain '{' or '}'
characters. */
static std::string run_length_encode(const std::string &s) {
std::ostringstream result;
const char *p, *q;
unsigned int reps;
p = s.c_str();
while (*p != '\0' && *(p + 1) != '\0') {
for (q = p + 2; *q == *p && *(q + 1) == *(p + 1); q += 2)
;
reps = (q - p) / 2;
if (reps < 3)
result << std::string(p, q);
else
result << std::string(p, 2) << "{" << reps << "}";
p = q;
}
if (*p != '\0')
result << std::string(p);
return result.str();
}
static std::string wrap(const std::string &s) {
const static char *prefix = "OS:";
std::string t, buf;
int i, len, prefixlen;
size_t p;
t = s;
/* Remove newlines. */
p = 0;
while ((p = t.find("\n", p)) != std::string::npos)
t.erase(p, 1);
len = t.size();
prefixlen = strlen(prefix);
assert(FP_RESULT_WRAP_LINE_LEN > prefixlen);
for (i = 0; i < len; i += FP_RESULT_WRAP_LINE_LEN - prefixlen) {
buf.append(prefix);
buf.append(t, i, FP_RESULT_WRAP_LINE_LEN - prefixlen);
buf.append("\n");
}
return buf;
}
static void scrub_packet(PacketElement *pe, unsigned char fill) {
unsigned char fillbuf[16];
memset(fillbuf, fill, sizeof(fillbuf));
for (; pe != NULL; pe = pe->getNextElement()) {
if (pe->protocol_id() == HEADER_TYPE_IPv6) {
IPv6Header *ipv6 = (IPv6Header *) pe;
ipv6->setSourceAddress(fillbuf);
ipv6->setDestinationAddress(fillbuf);
} else if (pe->protocol_id() == HEADER_TYPE_ICMPv6) {
ICMPv6Header *icmpv6 = (ICMPv6Header *) pe;
in6_addr *addr = (in6_addr *) fillbuf;
if (icmpv6->getType() == ICMPV6_NEIGHBOR_ADVERTISEMENT)
icmpv6->setTargetAddress(*addr);
}
}
}
static std::string get_scrubbed_buffer(const FPResponse *resp) {
std::ostringstream result;
PacketElement *scrub1, *scrub2;
u8 *buf1, *buf2;
int len1, len2;
unsigned int i;
scrub1 = PacketParser::split(resp->buf, resp->len);
assert(scrub1 != NULL);
scrub_packet(scrub1, 0x00);
scrub2 = PacketParser::split(resp->buf, resp->len);
assert(scrub2 != NULL);
scrub_packet(scrub2, 0xFF);
buf1 = scrub1->getBinaryBuffer(&len1);
buf2 = scrub2->getBinaryBuffer(&len2);
assert(resp->len == (unsigned int) len1);
assert(resp->len == (unsigned int) len2);
result.fill('0');
result << std::hex;
for (i = 0; i < resp->len; i++) {
if (resp->buf[i] == buf1[i] && resp->buf[i] == buf2[i]) {
result.width(2);
result << (unsigned int) resp->buf[i];
} else {
result << "XX";
}
}
free(buf1);
free(buf2);
PacketParser::freePacketChain(scrub1);
PacketParser::freePacketChain(scrub2);
return result.str();
}
const char *FingerPrintResultsIPv6::merge_fpr(const Target *currenths,
bool isGoodFP, bool wrapit) const {
static char str[10240];
const FingerPrintResultsIPv6 *FPR;
std::ostringstream result;
std::string output;
unsigned int i;
/* Write the SCAN line. */
WriteSInfo(str, sizeof(str), isGoodFP, "6", currenths->TargetSockAddr(),
currenths->distance, currenths->distance_calculation_method,
currenths->MACAddress(), this->osscan_opentcpport,
this->osscan_closedtcpport, this->osscan_closedudpport);
result << str << "\n";
FPR = (FingerPrintResultsIPv6 *) currenths->FPR;
assert(FPR->begin_time.tv_sec != 0);
for (i = 0; i < sizeof(FPR->fp_responses) / sizeof(FPR->fp_responses[0]); i++) {
const FPResponse *resp;
std::string scrubbed;
resp = this->fp_responses[i];
if (resp == NULL)
continue;
scrubbed = get_scrubbed_buffer(resp);
if (wrapit)
scrubbed = run_length_encode(scrubbed);
result << resp->probe_id << "(P=" << scrubbed;
assert(resp->senttime.tv_sec != 0);
result << "%ST=" << TIMEVAL_FSEC_SUBTRACT(resp->senttime, FPR->begin_time);
assert(resp->rcvdtime.tv_sec != 0);
result << "%RT=" << TIMEVAL_FSEC_SUBTRACT(resp->rcvdtime, FPR->begin_time);
result << ")\n";
}
result << "EXTRA(";
result << "FL=";
result.fill('0');
result << std::hex;
result.width(5);
result << FPR->flow_label;
result << ")\n";
output = result.str();
if (wrapit) {
output = wrap(output);
}
Strncpy(str, output.c_str(), sizeof(str));
return str;
}
static void write_merged_fpr(const FingerPrintResults *FPR, static void write_merged_fpr(const FingerPrintResults *FPR,
const Target *currenths, const Target *currenths,
bool isGoodFP, bool wrapit) { bool isGoodFP, bool wrapit) {
log_write(LOG_NORMAL | LOG_SKID_NOXLT | LOG_STDOUT, log_write(LOG_NORMAL | LOG_SKID_NOXLT | LOG_STDOUT,
"TCP/IP fingerprint:\n%s\n", "TCP/IP fingerprint:\n%s\n",
merge_fpr(FPR, currenths, isGoodFP, wrapit)); FPR->merge_fpr(currenths, isGoodFP, wrapit));
/* Added code here to print fingerprint to XML file any time it would be /* Added code here to print fingerprint to XML file any time it would be
printed to any other output format */ printed to any other output format */
xml_open_start_tag("osfingerprint"); xml_open_start_tag("osfingerprint");
xml_attribute("fingerprint", "%s", merge_fpr(FPR, currenths, isGoodFP, wrapit)); xml_attribute("fingerprint", "%s", FPR->merge_fpr(currenths, isGoodFP, wrapit));
xml_close_empty_tag(); xml_close_empty_tag();
xml_newline(); xml_newline();
} }
@@ -1691,22 +1851,22 @@ void printosscanoutput(Target *currenths) {
/* Success, not too many perfect matches. */ /* Success, not too many perfect matches. */
if (FPR->num_perfect_matches > 0) { if (FPR->num_perfect_matches > 0) {
/* Some perfect matches. */ /* Some perfect matches. */
for (i = 0; FPR->accuracy[i] == 1; i++) { for (i = 0; i < FPR->num_perfect_matches; i++) {
xml_open_start_tag("osmatch"); xml_open_start_tag("osmatch");
xml_attribute("name", "%s", FPR->prints[i]->OS_name); xml_attribute("name", "%s", FPR->matches[i]->OS_name);
xml_attribute("accuracy", "100"); xml_attribute("accuracy", "%d", (int) (FPR->accuracy[i] * 100));
xml_attribute("line", "%d", FPR->prints[i]->line); xml_attribute("line", "%d", FPR->matches[i]->line);
xml_close_empty_tag(); xml_close_empty_tag();
xml_newline(); xml_newline();
} }
log_write(LOG_MACHINE, "\tOS: %s", FPR->prints[0]->OS_name); log_write(LOG_MACHINE, "\tOS: %s", FPR->matches[0]->OS_name);
for (i = 1; FPR->accuracy[i] == 1; i++) for (i = 1; i < FPR->num_perfect_matches; i++)
log_write(LOG_MACHINE, "|%s", FPR->prints[i]->OS_name); log_write(LOG_MACHINE, "|%s", FPR->matches[i]->OS_name);
log_write(LOG_PLAIN, "OS details: %s", FPR->prints[0]->OS_name); log_write(LOG_PLAIN, "OS details: %s", FPR->matches[0]->OS_name);
for (i = 1; FPR->accuracy[i] == 1; i++) for (i = 1; i < FPR->num_perfect_matches; i++)
log_write(LOG_PLAIN, ", %s", FPR->prints[i]->OS_name); log_write(LOG_PLAIN, ", %s", FPR->matches[i]->OS_name);
log_write(LOG_PLAIN, "\n"); log_write(LOG_PLAIN, "\n");
if (o.debugging || o.verbose > 1) if (o.debugging || o.verbose > 1)
@@ -1721,17 +1881,17 @@ void printosscanoutput(Target *currenths) {
/* Print the best guesses available */ /* Print the best guesses available */
for (i = 0; i < 10 && i < FPR->num_matches && FPR->accuracy[i] > FPR->accuracy[0] - 0.10; i++) { for (i = 0; i < 10 && i < FPR->num_matches && FPR->accuracy[i] > FPR->accuracy[0] - 0.10; i++) {
xml_open_start_tag("osmatch"); xml_open_start_tag("osmatch");
xml_attribute("name", "%s", FPR->prints[i]->OS_name); xml_attribute("name", "%s", FPR->matches[i]->OS_name);
xml_attribute("accuracy", "%d", (int) (FPR->accuracy[i] * 100)); xml_attribute("accuracy", "%d", (int) (FPR->accuracy[i] * 100));
xml_attribute("line", "%d", FPR->prints[i]->line); xml_attribute("line", "%d", FPR->matches[i]->line);
xml_close_empty_tag(); xml_close_empty_tag();
xml_newline(); xml_newline();
} }
log_write(LOG_PLAIN, "Aggressive OS guesses: %s (%.f%%)", log_write(LOG_PLAIN, "Aggressive OS guesses: %s (%.f%%)",
FPR->prints[0]->OS_name, floor(FPR->accuracy[0] * 100)); FPR->matches[0]->OS_name, floor(FPR->accuracy[0] * 100));
for (i = 1; i < 10 && FPR->num_matches > i && FPR->accuracy[i] > FPR->accuracy[0] - 0.10; i++) for (i = 1; i < 10 && FPR->num_matches > i && FPR->accuracy[i] > FPR->accuracy[0] - 0.10; i++)
log_write(LOG_PLAIN, ", %s (%.f%%)", FPR->prints[i]->OS_name, floor(FPR->accuracy[i] * 100)); log_write(LOG_PLAIN, ", %s (%.f%%)", FPR->matches[i]->OS_name, floor(FPR->accuracy[i] * 100));
log_write(LOG_PLAIN, "\n"); log_write(LOG_PLAIN, "\n");
} }

View File

@@ -371,6 +371,14 @@ o [Nsock] Consider adding server support to Nsock so it can accept
followed by a nonblocking accept(). Then Nping gives the SD's to followed by a nonblocking accept(). Then Nping gives the SD's to
Nsock to manage. Nsock to manage.
o Consider implementing both global and per-host congestion control in
the IPv6 OS detection engine. Currently it handles congestion globally
(one CWND and SSTHRESH shared by all hosts). This works fine but it
may not be the most efficient approach: if the congestion is not
in our network segment but in a target's and we are os-scanning
hosts in different networks, then all hosts get "penalized" because
there is congestion in another network, not in theirs.
o [Nsock] Consider implementing a nsock_pcap_close() function or making o [Nsock] Consider implementing a nsock_pcap_close() function or making
nsp_delete() call pcap_close() when pcap IODs are used. Currently valgrind nsp_delete() call pcap_close() when pcap IODs are used. Currently valgrind
warns about a socket descriptor left opened (at least in Nping). warns about a socket descriptor left opened (at least in Nping).