1 /***************************************************************************
2  * portlist.h -- Functions for manipulating various lists of ports         *
3  * maintained internally by Nmap.                                          *
4  *                                                                         *
5  ***********************IMPORTANT NMAP LICENSE TERMS************************
6  *                                                                         *
7  * The Nmap Security Scanner is (C) 1996-2020 Insecure.Com LLC ("The Nmap  *
8  * Project"). Nmap is also a registered trademark of the Nmap Project.     *
9  *                                                                         *
10  * This program is distributed under the terms of the Nmap Public Source   *
11  * License (NPSL). The exact license text applying to a particular Nmap    *
12  * release or source code control revision is contained in the LICENSE     *
13  * file distributed with that version of Nmap or source code control       *
14  * revision. More Nmap copyright/legal information is available from       *
15  * https://nmap.org/book/man-legal.html, and further information on the    *
16  * NPSL license itself can be found at https://nmap.org/npsl. This header  *
17  * summarizes some key points from the Nmap license, but is no substitute  *
18  * for the actual license text.                                            *
19  *                                                                         *
20  * Nmap is generally free for end users to download and use themselves,    *
21  * including commercial use. It is available from https://nmap.org.        *
22  *                                                                         *
23  * The Nmap license generally prohibits companies from using and           *
24  * redistributing Nmap in commercial products, but we sell a special Nmap  *
25  * OEM Edition with a more permissive license and special features for     *
26  * this purpose. See https://nmap.org/oem                                  *
27  *                                                                         *
28  * If you have received a written Nmap license agreement or contract       *
29  * stating terms other than these (such as an Nmap OEM license), you may   *
30  * choose to use and redistribute Nmap under those terms instead.          *
31  *                                                                         *
32  * The official Nmap Windows builds include the Npcap software             *
33  * (https://npcap.org) for packet capture and transmission. It is under    *
34  * separate license terms which forbid redistribution without special      *
35  * permission. So the official Nmap Windows builds may not be              *
36  * redistributed without special permission (such as an Nmap OEM           *
37  * license).                                                               *
38  *                                                                         *
39  * Source is provided to this software because we believe users have a     *
40  * right to know exactly what a program is going to do before they run it. *
41  * This also allows you to audit the software for security holes.          *
42  *                                                                         *
43  * Source code also allows you to port Nmap to new platforms, fix bugs,    *
44  * and add new features.  You are highly encouraged to submit your         *
45  * changes as a Github PR or by email to the dev@nmap.org mailing list     *
46  * for possible incorporation into the main distribution. Unless you       *
47  * specify otherwise, it is understood that you are offering us very       *
48  * broad rights to use your submissions as described in the Nmap Public    *
49  * Source License Contributor Agreement. This is important because we      *
50  * fund the project by selling licenses with various terms, and also       *
51  * because the inability to relicense code has caused devastating          *
52  * problems for other Free Software projects (such as KDE and NASM).       *
53  *                                                                         *
54  * The free version of Nmap is distributed in the hope that it will be     *
55  * useful, but WITHOUT ANY WARRANTY; without even the implied warranty of  *
56  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Warranties,        *
57  * indemnification and commercial support are all available through the    *
58  * Npcap OEM program--see https://nmap.org/oem.                            *
59  *                                                                         *
60  ***************************************************************************/
61 
62 /* $Id: portlist.h 38078 2020-10-02 16:12:22Z dmiller $ */
63 
64 #ifndef PORTLIST_H
65 #define PORTLIST_H
66 
67 #include "nbase.h"
68 #ifndef NOLUA
69 #include "nse_main.h"
70 #endif
71 
72 #include "portreasons.h"
73 
74 #include <vector>
75 
76 /* port states */
77 #define PORT_UNKNOWN 0
78 #define PORT_CLOSED 1
79 #define PORT_OPEN 2
80 #define PORT_FILTERED 3
81 #define PORT_TESTING 4
82 #define PORT_FRESH 5
83 #define PORT_UNFILTERED 6
84 #define PORT_OPENFILTERED 7 /* Like udp/fin/xmas/null/ipproto scan with no response */
85 #define PORT_CLOSEDFILTERED 8 /* Idle scan */
86 #define PORT_HIGHEST_STATE 9 /* ***IMPORTANT -- BUMP THIS UP WHEN STATES ARE
87                                 ADDED *** */
88 const char *statenum2str(int state);
89 
90 #define TCPANDUDPANDSCTP IPPROTO_MAX
91 #define UDPANDSCTP (IPPROTO_MAX + 1)
92 
93 enum serviceprobestate {
94   PROBESTATE_INITIAL=1, // No probes started yet
95   PROBESTATE_NULLPROBE, // Is working on the NULL Probe
96   PROBESTATE_MATCHINGPROBES, // Is doing matching probe(s)
97   PROBESTATE_NONMATCHINGPROBES, // The above failed, is checking nonmatches
98   PROBESTATE_FINISHED_HARDMATCHED, // Yay!  Found a match
99   PROBESTATE_FINISHED_SOFTMATCHED, // Well, a soft match anyway
100   PROBESTATE_FINISHED_NOMATCH, // D'oh!  Failed to find the service.
101   PROBESTATE_FINISHED_TCPWRAPPED, // We think the port is blocked via tcpwrappers
102   PROBESTATE_EXCLUDED, // The port has been excluded from the scan
103   PROBESTATE_INCOMPLETE // failed to complete (error, host timeout, etc.)
104 };
105 
106 enum service_detection_type { SERVICE_DETECTION_TABLE, SERVICE_DETECTION_PROBED };
107 
108 enum service_tunnel_type { SERVICE_TUNNEL_NONE, SERVICE_TUNNEL_SSL };
109 
110 // Move some popular TCP ports to the beginning of the portlist, because
111 // that can speed up certain scans.  You should have already done any port
112 // randomization, this should prevent the ports from always coming out in the
113 // same order.
114 void random_port_cheat(u16 *ports, int portcount);
115 
116 struct serviceDeductions {
117   serviceDeductions();
118   void populateFullVersionString(char *buf, size_t n) const;
119 
120   char *name; // will be NULL if can't determine
121   // Confidence is a number from 0 (least confident) to 10 (most
122   // confident) expressing how accurate the service detection is
123   // likely to be.
124   int name_confidence;
125   // Any of these 6 can be NULL if we weren't able to determine it
126   char *product;
127   char *version;
128   char *extrainfo;
129   char *hostname;
130   char *ostype;
131   char *devicetype;
132   std::vector<char *> cpe;
133   // SERVICE_TUNNEL_NONE or SERVICE_TUNNEL_SSL
134   enum service_tunnel_type service_tunnel;
135   // if we should give the user a service fingerprint to submit, here it is.  Otherwise NULL.
136   char *service_fp;
137   enum service_detection_type dtype; // definition above
138 };
139 
140 class Port {
141  friend class PortList;
142 
143  public:
144   Port();
145   void freeService(bool del_service);
146   void freeScriptResults(void);
147   void getNmapServiceName(char *namebuf, int buflen) const;
148 
149   u16 portno;
150   u8 proto;
151   u8 state;
152   state_reason_t reason;
153 
154 #ifndef NOLUA
155   ScriptResults scriptResults;
156 #endif
157 
158  private:
159   /* This is allocated only on demand by PortList::setServiceProbeResults
160      to save memory for the many closed or filtered ports that don't need it. */
161   serviceDeductions *service;
162 };
163 
164 
165 /* Needed enums to address some arrays. This values
166  * should never be used directly. Use INPROTO2PORTLISTPROTO macro */
167 enum portlist_proto {	// PortList Protocols
168   PORTLIST_PROTO_TCP	= 0,
169   PORTLIST_PROTO_UDP	= 1,
170   PORTLIST_PROTO_SCTP	= 2,
171   PORTLIST_PROTO_IP	= 3,
172   PORTLIST_PROTO_MAX	= 4
173 };
174 
175 class PortList {
176  public:
177   PortList();
178   ~PortList();
179   /* Set ports that will be scanned for each protocol. This function
180    * must be called before any PortList object will be created. */
181   static void initializePortMap(int protocol, u16 *ports, int portcount);
182   /* Free memory used by port_map. It should be done somewhere before quitting*/
183   static void freePortMap();
184 
185   void setDefaultPortState(u8 protocol, int state);
186   void setPortState(u16 portno, u8 protocol, int state);
187   int getPortState(u16 portno, u8 protocol);
188   int forgetPort(u16 portno, u8 protocol);
189   bool portIsDefault(u16 portno, u8 protocol);
190   /* Saves an identification string for the target containing these
191      ports (an IP address might be a good example, but set what you
192      want).  Only used when printing new port updates.  Optional.  A
193      copy is made. */
194   void setIdStr(const char *id);
195   /* A function for iterating through the ports.  Give NULL for the
196    first "afterthisport".  Then supply the most recent returned port
197    for each subsequent call.  When no more matching ports remain, NULL
198    will be returned.  To restrict returned ports to just one protocol,
199    specify IPPROTO_TCP, IPPROTO_UDP or UPPROTO_SCTP for
200    allowed_protocol. A TCPANDUDPANDSCTP for allowed_protocol matches
201    either. A 0 for allowed_state matches all possible states. This
202    function returns ports in numeric order from lowest to highest,
203    except that if you ask for TCP, UDP & SCTP, all TCP ports will be
204    returned before we start returning UDP and finally SCTP ports */
205   Port *nextPort(const Port *cur, Port *next,
206                  int allowed_protocol, int allowed_state);
207 
208   int setStateReason(u16 portno, u8 proto, reason_t reason, u8 ttl, const struct sockaddr_storage *ip_addr);
209 
210   int numscriptresults; /* Total number of scripts which produced output */
211 
212   /* Get number of ports in this state. This a sum for protocols. */
213   int getStateCounts(int state) const;
214   /* Get number of ports in this state for requested protocol. */
215   int getStateCounts(int protocol, int state) const;
216 
217   // sname should be NULL if sres is not
218   // PROBESTATE_FINISHED_MATCHED. product,version, and/or extrainfo
219   // will be NULL if unavailable. Note that this function makes its
220   // own copy of sname and product/version/extrainfo.  This function
221   // also takes care of truncating the version strings to a
222   // 'reasonable' length if necessary, and cleaning up any unprintable
223   // chars. (these tests are to avoid annoying DOS (or other) attacks
224   // by malicious services).  The fingerprint should be NULL unless
225   // one is available and the user should submit it.  tunnel must be
226   // SERVICE_TUNNEL_NONE (normal) or SERVICE_TUNNEL_SSL (means ssl was
227   // detected and we tried to tunnel through it ).
228   void setServiceProbeResults(u16 portno, int protocol,
229                               enum serviceprobestate sres, const char *sname,
230                               enum service_tunnel_type tunnel, const char *product,
231                               const char *version, const char *hostname,
232                               const char *ostype, const char *devicetype,
233                               const char *extrainfo,
234                               const std::vector<const char *> *cpe,
235                               const char *fingerprint);
236 
237   // pass in an allocated struct serviceDeductions (don't worry about initializing, and
238   // you don't have to free any internal ptrs.  See the serviceDeductions definition for
239   // the fields that are populated.  Returns 0 if at least a name is available.
240   void getServiceDeductions(u16 portno, int protocol, struct serviceDeductions *sd) const;
241 
242 #ifndef NOLUA
243   void addScriptResult(u16 portno, int protocol, const ScriptResult& sr);
244 #endif
245 
246   /* Cycles through the 0 or more "ignored" ports which should be
247    consolidated for Nmap output.  They are returned sorted by the
248    number of ports in the state, starting with the most common.  It
249    should first be called with PORT_UNKNOWN to obtain the most popular
250    ignored state (if any).  Then call with that state to get the next
251    most popular one.  Returns the state if there is one, but returns
252    PORT_UNKNOWN if there are no (more) states which qualify for
253    consolidation */
254   int nextIgnoredState(int prevstate);
255 
256   /* Returns true if a state should be ignored (consolidated), false otherwise */
257   bool isIgnoredState(int state);
258 
259   int numIgnoredStates();
260   int numIgnoredPorts();
261   int numPorts() const;
262   bool hasOpenPorts() const;
263 
264   /* Returns true if service scan is done and portno is found to be tcpwrapped, false otherwise */
265   bool isTCPwrapped(u16 portno) const;
266 
267  private:
268   void mapPort(u16 *portno, u8 *protocol) const;
269   /* Get Port structure from PortList structure.*/
270   const Port *lookupPort(u16 portno, u8 protocol) const;
271   Port *createPort(u16 portno, u8 protocol);
272   /* Set Port structure to PortList structure.*/
273   void  setPortEntry(u16 portno, u8 protocol, Port *port);
274 
275   /* A string identifying the system these ports are on.  Just used for
276      printing open ports, if it is set with setIdStr() */
277   char *idstr;
278   /* Number of ports in each state per each protocol. */
279   int state_counts_proto[PORTLIST_PROTO_MAX][PORT_HIGHEST_STATE];
280   Port **port_list[PORTLIST_PROTO_MAX];
281  protected:
282   /* Maps port_number to index in port_list array.
283    * Only functions: getPortEntry, setPortEntry, initializePortMap and
284    * nextPort should access this structure directly. */
285   static u16 *port_map[PORTLIST_PROTO_MAX];
286   static u16 *port_map_rev[PORTLIST_PROTO_MAX];
287   /* Number of allocated elements in port_list per each protocol. */
288   static int port_list_count[PORTLIST_PROTO_MAX];
289   Port default_port_state[PORTLIST_PROTO_MAX];
290 };
291 
292 #endif
293 
294