1 
2 /***************************************************************************
3  * ncrack_telnet.cc -- ncrack module for the TELNET protocol               *
4  *                                                                         *
5  ***********************IMPORTANT NMAP LICENSE TERMS************************
6  *                                                                         *
7  * The Nmap Security Scanner is (C) 1996-2019 Insecure.Com LLC ("The Nmap  *
8  * Project"). Nmap is also a registered trademark of the Nmap Project.     *
9  * This program is free software; you may redistribute and/or modify it    *
10  * under the terms of the GNU General Public License as published by the   *
11  * Free Software Foundation; Version 2 ("GPL"), BUT ONLY WITH ALL OF THE   *
12  * CLARIFICATIONS AND EXCEPTIONS DESCRIBED HEREIN.  This guarantees your   *
13  * right to use, modify, and redistribute this software under certain      *
14  * conditions.  If you wish to embed Nmap technology into proprietary      *
15  * software, we sell alternative licenses (contact sales@nmap.com).        *
16  * Dozens of software vendors already license Nmap technology such as      *
17  * host discovery, port scanning, OS detection, version detection, and     *
18  * the Nmap Scripting Engine.                                              *
19  *                                                                         *
20  * Note that the GPL places important restrictions on "derivative works",  *
21  * yet it does not provide a detailed definition of that term.  To avoid   *
22  * misunderstandings, we interpret that term as broadly as copyright law   *
23  * allows.  For example, we consider an application to constitute a        *
24  * derivative work for the purpose of this license if it does any of the   *
25  * following with any software or content covered by this license          *
26  * ("Covered Software"):                                                   *
27  *                                                                         *
28  * o Integrates source code from Covered Software.                         *
29  *                                                                         *
30  * o Reads or includes copyrighted data files, such as Nmap's nmap-os-db   *
31  * or nmap-service-probes.                                                 *
32  *                                                                         *
33  * o Is designed specifically to execute Covered Software and parse the    *
34  * results (as opposed to typical shell or execution-menu apps, which will *
35  * execute anything you tell them to).                                     *
36  *                                                                         *
37  * o Includes Covered Software in a proprietary executable installer.  The *
38  * installers produced by InstallShield are an example of this.  Including *
39  * Nmap with other software in compressed or archival form does not        *
40  * trigger this provision, provided appropriate open source decompression  *
41  * or de-archiving software is widely available for no charge.  For the    *
42  * purposes of this license, an installer is considered to include Covered *
43  * Software even if it actually retrieves a copy of Covered Software from  *
44  * another source during runtime (such as by downloading it from the       *
45  * Internet).                                                              *
46  *                                                                         *
47  * o Links (statically or dynamically) to a library which does any of the  *
48  * above.                                                                  *
49  *                                                                         *
50  * o Executes a helper program, module, or script to do any of the above.  *
51  *                                                                         *
52  * This list is not exclusive, but is meant to clarify our interpretation  *
53  * of derived works with some common examples.  Other people may interpret *
54  * the plain GPL differently, so we consider this a special exception to   *
55  * the GPL that we apply to Covered Software.  Works which meet any of     *
56  * these conditions must conform to all of the terms of this license,      *
57  * particularly including the GPL Section 3 requirements of providing      *
58  * source code and allowing free redistribution of the work as a whole.    *
59  *                                                                         *
60  * As another special exception to the GPL terms, the Nmap Project grants  *
61  * permission to link the code of this program with any version of the     *
62  * OpenSSL library which is distributed under a license identical to that  *
63  * listed in the included docs/licenses/OpenSSL.txt file, and distribute   *
64  * linked combinations including the two.                                  *
65  *                                                                         *
66  * The Nmap Project has permission to redistribute Npcap, a packet         *
67  * capturing driver and library for the Microsoft Windows platform.        *
68  * Npcap is a separate work with it's own license rather than this Nmap    *
69  * license.  Since the Npcap license does not permit redistribution        *
70  * without special permission, our Nmap Windows binary packages which      *
71  * contain Npcap may not be redistributed without special permission.      *
72  *                                                                         *
73  * Any redistribution of Covered Software, including any derived works,    *
74  * must obey and carry forward all of the terms of this license, including *
75  * obeying all GPL rules and restrictions.  For example, source code of    *
76  * the whole work must be provided and free redistribution must be         *
77  * allowed.  All GPL references to "this License", are to be treated as    *
78  * including the terms and conditions of this license text as well.        *
79  *                                                                         *
80  * Because this license imposes special exceptions to the GPL, Covered     *
81  * Work may not be combined (even as part of a larger work) with plain GPL *
82  * software.  The terms, conditions, and exceptions of this license must   *
83  * be included as well.  This license is incompatible with some other open *
84  * source licenses as well.  In some cases we can relicense portions of    *
85  * Nmap or grant special permissions to use it in other open source        *
86  * software.  Please contact fyodor@nmap.org with any such requests.       *
87  * Similarly, we don't incorporate incompatible open source software into  *
88  * Covered Software without special permission from the copyright holders. *
89  *                                                                         *
90  * If you have any questions about the licensing restrictions on using     *
91  * Nmap in other works, we are happy to help.  As mentioned above, we also *
92  * offer an alternative license to integrate Nmap into proprietary         *
93  * applications and appliances.  These contracts have been sold to dozens  *
94  * of software vendors, and generally include a perpetual license as well  *
95  * as providing support and updates.  They also fund the continued         *
96  * development of Nmap.  Please email sales@nmap.com for further           *
97  * information.                                                            *
98  *                                                                         *
99  * If you have received a written license agreement or contract for        *
100  * Covered Software stating terms other than these, you may choose to use  *
101  * and redistribute Covered Software under those terms instead of these.   *
102  *                                                                         *
103  * Source is provided to this software because we believe users have a     *
104  * right to know exactly what a program is going to do before they run it. *
105  * This also allows you to audit the software for security holes.          *
106  *                                                                         *
107  * Source code also allows you to port Nmap to new platforms, fix bugs,    *
108  * and add new features.  You are highly encouraged to send your changes   *
109  * to the dev@nmap.org mailing list for possible incorporation into the    *
110  * main distribution.  By sending these changes to Fyodor or one of the    *
111  * Insecure.Org development mailing lists, or checking them into the Nmap  *
112  * source code repository, it is understood (unless you specify            *
113  * otherwise) that you are offering the Nmap Project the unlimited,        *
114  * non-exclusive right to reuse, modify, and relicense the code.  Nmap     *
115  * will always be available Open Source, but this is important because     *
116  * the inability to relicense code has caused devastating problems for     *
117  * other Free Software projects (such as KDE and NASM).  We also           *
118  * occasionally relicense the code to third parties as discussed above.    *
119  * If you wish to specify special license conditions of your               *
120  * contributions, just say so when you send them.                          *
121  *                                                                         *
122  * This program is distributed in the hope that it will be useful, but     *
123  * WITHOUT ANY WARRANTY; without even the implied warranty of              *
124  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the Nmap      *
125  * license file for more details (it's in a COPYING file included with     *
126  * Nmap, and also available from https://svn.nmap.org/nmap/COPYING)        *
127  *                                                                         *
128  ***************************************************************************/
129 
130 
131 #include "ncrack.h"
132 #include "nsock.h"
133 #include "NcrackOps.h"
134 #include "Service.h"
135 #include "modules.h"
136 #include <list>
137 
138 
139 /* Telnet Commands */
140 #define IAC   255   /* interpret as command: */
141 #define DONT  254   /* you are not to use option */
142 #define DO    253   /* please, you use option */
143 #define WONT  252 	/* I won't use option */
144 #define WILL  251 	/* I will use option */
145 #define SB    250   /* interpret as subnegotiation */
146 #define	SE    240   /* end sub negotiation */
147 
148 /* Telnet Options */
149 #define LINEMODE 34
150 
151 #define WILL_LINEMODE "\xff\xfb\x22"
152 #define DO_LINEMODE "\xff\xfd\x22"
153 
154 
155 extern NcrackOps o;
156 
157 extern void ncrack_read_handler(nsock_pool nsp, nsock_event nse, void *mydata);
158 extern void ncrack_write_handler(nsock_pool nsp, nsock_event nse, void *mydata);
159 extern void ncrack_timer_handler(nsock_pool nsp, nsock_event nse, void *mydata);
160 extern void ncrack_module_end(nsock_pool nsp, void *mydata);
161 
162 typedef struct telnet_info {
163   bool linemode; /* true if peer supports linemode */
164   /* Some devices don't even bother to answer our question of whether they
165    * support linemode or not, and thus we need a separate boolean to tell us
166    * if we sent a request, so we can try only once.
167    */
168   bool asked_for_linemode;
169   bool linemode_not_supported;  /* peer told us that he doesn't support linemode */
170   bool can_start_auth;
171   char *userptr;
172   char *passptr;
173 } telnet_info;
174 
175 
176 enum states { TELNET_INIT, TELNET_OPTIONS_1, TELNET_OPTIONS_2, TELNET_AUTH, TELNET_ECHO_USER,
177   TELNET_PASS_R, TELNET_PASS_W, TELNET_FINI };
178 
179 void
ncrack_telnet(nsock_pool nsp,Connection * con)180 ncrack_telnet(nsock_pool nsp, Connection *con)
181 {
182   char lbuf[BUFSIZE]; /* local buffer */
183   /* We can't let nsock handle the size by looking at '\0'
184    * because telnet uses 0 as a valid value for options
185    * (e.g binary transmission option) */
186   size_t lbufsize;
187   nsock_iod nsi = con->niod;
188   telnet_info *info = NULL;
189   size_t datasize;
190   char *recvbufptr = NULL;
191   size_t recvbuflen = 0;
192   char *localbufptr = lbuf;
193   if (con->misc_info)
194     info = (telnet_info *) con->misc_info;
195 
196   switch (con->state)
197   {
198     case TELNET_INIT:
199       con->peer_might_close = false;
200       con->misc_info = (telnet_info *)safe_zalloc(sizeof(telnet_info));
201       con->state = TELNET_OPTIONS_1;
202       nsock_read(nsp, nsi, ncrack_read_handler, 50000, con);
203       break;
204 
205     case TELNET_OPTIONS_1:
206 
207       recvbufptr = (char *)con->inbuf->get_dataptr();
208       recvbuflen = con->inbuf->get_len();
209 
210       /* Telnet Option Parsing */
211       while (*recvbufptr == (char) IAC
212           && ((size_t)(recvbufptr - (char *)con->inbuf->get_dataptr()) < recvbuflen)
213           && ((localbufptr - lbuf) < BUFSIZE - 3)) {
214 
215         /* For every option other than linemode we reject it */
216         if (recvbufptr[1] == (char) WILL) {
217           if (recvbufptr[2] == (char) LINEMODE) {
218             /* reply is needed only when we haven't asked explicitly if the peer
219              * supports linemode itself
220              */
221             if (info->asked_for_linemode == false) {
222               memcpy(localbufptr, WILL_LINEMODE, sizeof(WILL_LINEMODE));
223               localbufptr += 3;
224             }
225             info->linemode = true;
226           } else {
227             snprintf(localbufptr, 4, "%c%c%c", IAC, DONT, recvbufptr[2]);
228             localbufptr += 3;
229           }
230           recvbufptr += 3;
231 
232         } else if (recvbufptr[1] == (char) WONT) {
233           if (recvbufptr[2] == LINEMODE) {
234             info->linemode = false;
235             info->linemode_not_supported = true;
236           } else {
237             snprintf(localbufptr, 4, "%c%c%c", IAC, DONT, recvbufptr[2]);
238             localbufptr += 3;
239           }
240           recvbufptr += 3;
241 
242         } else if (recvbufptr[1] == (char) DONT) {
243           if (recvbufptr[2] == LINEMODE) {
244             info->linemode = false;
245             info->linemode_not_supported = true;
246           }
247           snprintf(localbufptr, 4, "%c%c%c", IAC, WONT, recvbufptr[2]);
248           localbufptr += 3;
249           recvbufptr += 3;
250 
251         } else if (recvbufptr[1] == (char) DO) {
252           if (recvbufptr[2] == LINEMODE) {
253             if (info->asked_for_linemode == false) {
254               memcpy(localbufptr, WILL_LINEMODE, sizeof(WILL_LINEMODE));
255               localbufptr += 3;
256             }
257             info->linemode = true;
258           } else {
259             snprintf(localbufptr, 4, "%c%c%c", IAC, WONT, recvbufptr[2]);
260             localbufptr += 3;
261           }
262           recvbufptr += 3;
263 
264           /* We just ignore any suboption we receive */
265         } else if (recvbufptr[1] == (char) SB) {
266           while (*recvbufptr != (char) SE
267               && (size_t)((recvbufptr - (char *)con->inbuf->get_dataptr())) < recvbuflen)
268             recvbufptr++;
269           recvbufptr++;
270         }
271       }
272 
273       /* If peer didn't sent linemode as part of its options and didn't sent a
274        * command saying he doesn't support it and this is the first time we
275        * request it from him, then try to ask him explicitly if
276        * he supports it.
277        */
278       if (info->linemode == false
279           && info->linemode_not_supported == false
280           && info->asked_for_linemode == false) {
281         if ((localbufptr - lbuf) < BUFSIZE - 3) {
282           memcpy(localbufptr, WILL_LINEMODE, sizeof(WILL_LINEMODE));
283           info->asked_for_linemode = true;
284           localbufptr += 3;
285         }
286       }
287 
288       datasize = recvbuflen - (recvbufptr - (char *)con->inbuf->get_dataptr());
289 
290       /* Now check for banner and login prompt */
291       if (datasize > 0) {
292         if (o.debugging > 8) {
293           //memprint(recvbufptr, datasize);
294           //printf("\n");
295         }
296         /* If we see a certain pattern that denotes that we can start
297          * authentication then we note that down. */
298         if (memsearch(recvbufptr, "login", datasize)
299             || memsearch(recvbufptr, "username", datasize))
300           info->can_start_auth = true;
301       }
302 
303       lbufsize = localbufptr - lbuf;
304 
305       con->state = TELNET_OPTIONS_2;
306       /* If we have something to send then do so. Else just wait until you
307        * receive a relevant authentication pattern to start cracking.
308        */
309       if (localbufptr != lbuf) {
310         nsock_write(nsp, nsi, ncrack_write_handler, 10000, con, lbuf, lbufsize);
311       } else {
312         if (info->can_start_auth == true)
313           con->state = TELNET_AUTH;
314         /* That's a bit of a hack, but we need the module to be called again
315          * with a changed state without issuing a read or write this time. And
316          * thus we create a timer event with a timeout of 0 milliseconds */
317         nsock_timer_create(nsp, ncrack_timer_handler, 0, con);
318       }
319       break;
320 
321     case TELNET_OPTIONS_2:
322       delete con->inbuf;
323       con->inbuf = NULL;
324 
325       con->state = TELNET_OPTIONS_1;
326       nsock_read(nsp, nsi, ncrack_read_handler, 10000, con);
327       break;
328 
329     case TELNET_AUTH:
330       if (info->linemode) {
331         con->state = TELNET_PASS_R;
332         snprintf(lbuf, sizeof(lbuf), "%s\r", con->user);
333         nsock_write(nsp, nsi, ncrack_write_handler, 10000, con, lbuf, -1);
334       } else {
335         con->state = TELNET_ECHO_USER;
336         /* Since our peer doesn't support linemode, we need to send each
337          * character of the username in individual packets. We send 1 byte
338          * and wait for the server's echo and so on...
339          */
340         if (con->inbuf) {
341           recvbufptr = (char *)con->inbuf->get_dataptr();
342           recvbuflen = con->inbuf->get_len();
343         }
344 
345         if (!info->userptr)
346           info->userptr = con->user;
347 
348         /* OK, here's the deal: we need to account for the fact that some
349          * telnet daemons (hint: cisco routers) send the initial login prompt
350          * and then start sending telnet options. Since we have already, sent
351          * the first username character by now, we will just have to ignore
352          * those options, and wait until we see our character echoed back in
353          * order to go on sending the rest of the username.
354          */
355         if (con->inbuf && info->userptr > con->user
356             && (size_t)((info->userptr - con->user)) != strlen(con->user)) {
357           /* Some telnet daemons send the echo reply with a \0 byte in front of
358            * the echoed characted. Damn inconsistencies. */
359           if ((recvbuflen > 2 && recvbufptr[1] != *(info->userptr - 1))
360               || (recvbuflen == 1 && recvbufptr[0] != *(info->userptr - 1))) {
361             nsock_timer_create(nsp, ncrack_timer_handler, 0, con);
362             break;
363           }
364         }
365 
366         /* we can move on to reading the password prompt */
367         if (recvbufptr && info->userptr > con->user &&
368             memsearch(recvbufptr, "\r", recvbuflen)) {
369           if (memsearch(recvbufptr, "password", recvbuflen))
370             con->state = TELNET_PASS_W;
371           else
372             con->state = TELNET_PASS_R;
373           nsock_timer_create(nsp, ncrack_timer_handler, 0, con);
374           break;
375         }
376 
377         if ((size_t)(info->userptr - con->user) == strlen(con->user)) {
378           lbuf[0] = '\r';
379           lbuf[1] = '\0';
380           nsock_write(nsp, nsi, ncrack_write_handler, 10000, con, lbuf, 2);
381         } else {
382           lbuf[0] = info->userptr[0];
383           info->userptr++;
384           nsock_write(nsp, nsi, ncrack_write_handler, 10000, con, lbuf, 1);
385         }
386       }
387       break;
388 
389     case TELNET_ECHO_USER:
390       delete con->inbuf;
391       con->inbuf = NULL;
392 
393       con->state = TELNET_AUTH;
394       nsock_read(nsp, nsi, ncrack_read_handler, 10000, con);
395       break;
396 
397     case TELNET_PASS_R:
398       delete con->inbuf;
399       con->inbuf = NULL;
400 
401       con->state = TELNET_PASS_W;
402       nsock_read(nsp, nsi, ncrack_read_handler, 10000, con);
403       break;
404 
405     case TELNET_PASS_W:
406       /* After some testing, it seems that we can send the password
407        * as one packet, even if linemode is disabled. */
408       con->state = TELNET_FINI;
409       snprintf(lbuf, sizeof(lbuf), "%s\r", con->pass);
410       con->peer_might_close = true;
411       nsock_write(nsp, nsi, ncrack_write_handler, 10000, con, lbuf, -1);
412       break;
413 
414     case TELNET_FINI:
415       if (con->inbuf) {
416         recvbufptr = (char *)con->inbuf->get_dataptr();
417         recvbuflen = con->inbuf->get_len();
418       }
419 
420       if (memsearch(recvbufptr, "incorrect", recvbuflen)
421           || memsearch(recvbufptr, "fail", recvbuflen)) {
422         con->auth_success = false;
423         con->state = TELNET_AUTH;
424         info->userptr = NULL;
425         info->passptr = NULL;
426         con->peer_might_close = false;
427 
428         /*
429          * If telnetd sent the final answer along with the new login prompt
430          * (something which happens with some daemons), then we don't need to
431          * check if the peer has closed the connection because obviously he hasn't!
432          */
433         if (memsearch(recvbufptr, "login", recvbuflen)
434             || memsearch(recvbufptr, "username", recvbuflen))
435           con->peer_alive = true;
436 
437         delete con->inbuf;
438         con->inbuf = NULL;
439 
440         return ncrack_module_end(nsp, con);
441 
442       } else if (memsearch(recvbufptr, ">", recvbuflen)
443           || memsearch(recvbufptr, "$", recvbuflen)
444           || memsearch(recvbufptr, "#", recvbuflen)) {
445         con->auth_success = true;
446 
447         delete con->inbuf;
448         con->inbuf = NULL;
449 
450         return ncrack_module_end(nsp, con);
451 
452       } else {  /* wait for more replies */
453 
454         delete con->inbuf;
455         con->inbuf = NULL;
456 
457         con->state = TELNET_FINI;
458         nsock_read(nsp, nsi, ncrack_read_handler, 10000, con);
459       }
460   }
461 
462 }
463 
464