Поиск по блогу

среда, 1 октября 2014 г.

Танцы с бубном Telnet

После того, как я прочитал, что альтернативой Stem (SIGNAL NEWNYM ... Python API Tor) может служить telnetlib, стало очевидным, что надо понимать, как работает (и юзается) Telnet. Здесь собраны ответы на все (почти) мои вопросы... даже по работе с "кривой" консолью в w8.

Вот решение, котороя я в конце концов попробовал и успокоился Telnetting to a Web Server

Здесь в видео автор использовал свой сайт, чтобы продемострировать подключение.

Оказалось, что его сайт до сих пор жив. HTML5 Sample Page Я просто тупо повторил ео действия..., и подключился к его сайту.

Здесь попробуем изложить основные правила:
1. Сокет устанавливается автоматически (?), точнее, TCP переговоры уже проведены
2. Вводим далее GET /HTTP1.1 ... построчно, нажимая после каждой "Enter"
3. Если нажать "Enter" два раза, то сервер начнет обрабатывать запрос (после пустой строки)
4. В w8 (у меня) старый текст не стирается - новый поверх старого
5. не забыть включить "set localecho"

In []:
telnet stungeye.com 80 
# Или с предварительным входом в
telnet 
Microsoft Telnet> o stungeye.com 80
Подключение к stungeye.com...
In []:
#После этого начинаешь набирать 
# get /school/telnet/index.php http/1.1
# и получаешь ошибку 404 (Сервер не может понять выш запрос)

После этого набираешь две волшебных строчки

In []:
get /school/telnet/index.php http/1.1
host: stungeye.com

И все заработало!!! Это какие-то танцы с бубном. Во-первых, после каждой строчки надо нажимать на Enter жважды !!! Зачем эти понты? Оказывается, чтобы можно было ввести две строчки (как показано выше) ... И надо, оказывается, указывать host: stungeye.com

In []:
HTTP/1.1 200 OK
Date: Wed, 01 Oct 2014 10:44:33 GMT
Server: Apache
X-Powered-By: PHP/5.2.4-2ubuntu5.19
Content-Length: 208
Content-Type: text/html; charset=UTF-8

<!DOCTYPE html>
               <html lang="en">
                               <head>
                                         <meta charset="utf-8" />
                                                                     <title>HTML5 Sample Page</title>
                                                                                                     </head>
                                                                                                            <body>

le Page</h1>
                <p>This is some sample test.</p>
                                                   </body>
                                                          </html>


Подключение к узлу утеряно.

Нажмите любую клавишу...

Получается, что консоль работает отвратительно (новые команды надо вводить поверх старого текста, нажимать на "Ввод" дважды, редактировать строчку ввода нельзя, поскольку код управляющих клавиш (например, BackSpace) как-то "напрямую" передается на сервер ...

Иногда вводимого текста просто не видно (несмотря на то, что ...echo on)

И ко всему этому добавляются настройки публичных серверов (типа Google.ru), которые не хотят разговаривать с подозрительными юзер-агентами типа Telnet...

А теперь все по порядку. Как я пытался понять Telnet

Итак, я просмотрел первый видеролик (в начале этого поста), нашел два своих "старых поста". После этого обратил внимание на запись (в "Не нашел...") о том, что надо включить локальное эхо, влючил эхо, начал логинится и подвис:

In []:
Microsoft Telnet> set ?
bsasdel     символ <BackSpace> будет отправляться как символ <Delete>
crlf        режим возврата каретки; приводит к отправке символов CR & LF
delasbs     символ <Delete> будет отправляться как символ <BackSpace>
escape x    где x - символ переключения в режим telnet-терминала и обратно
localecho   включение локального эха.
logfile x   где x - файл входа текущего клиента в систему
logging     выполнение входа в систему
mode x      где x - консоль или поток
ntlm        включение проверки подлинности NTLM.
term x      где x - ansi, vt100, vt52, или vtnt

Microsoft Telnet> set localecho
Вывод локального эха - включен

Microsoft Telnet> o 127.0.0.1 9151
Подключение к 127.0.0.1...

Вот оно... "подвисание" происходит именно так... При нажатии любой клавиши выдается сообщение о необходимости аутентификации и о том, что соединение потеряно. Я бы и рад:

In []:
 AUTHENTICATE \r\n

Но куда бы эту строчку вставить? Догадался во втором окне cmd распечатать соединения, обнаружил слушателя на порту 23, что навело на мысль о том, что я забыл отключить прошлый раз telnet-server (возмутительное разгильдяйство).

In []:
C:\Users\kiss\Anaconda>netstat /?

Отображение статистики протокола и текущих сетевых подключений TCP/IP.

NETSTAT [-a] [-b] [-e] [-f] [-n] [-o] [-p протокол] [-r] [-s] [-x] [-t]
        [интервал]

  -a            Отображение всех подключений и портов прослушивания.
  -b            Отображение исполняемого файла, участвующего в создании
                каждого подключения или порта прослушивания. Иногда известные
                исполняемые файлы содержат множество независимых
                компонентов. Тогда отображается последовательность компонентов,
                участвующих в создании подключения или порта прослушивания. В
                этом случае имя исполняемого файла находится снизу в скобках
                [], сверху находится вызванный им компонент, и так до тех
                пор, пока не достигнут TCP/IP. Заметьте, что такой подход
                может занять много времени и требует достаточных разрешений.
  -e            Отображение статистики Ethernet. Может применяться вместе
                с параметром -s.
  -f            Отображение полного имени домена (FQDN) для внешних адресов.
  -n            Отображение адресов и номеров портов в числовом формате.
  -o            Отображение ИД процесса каждого подключения.
  -p протокол   Отображение подключений для протокола, задаваемых этим
                параметром. Допустимые значения: TCP, UDP, TCPv6 или UDPv6.
                Если используется вместе с параметром -s для отображения
                статистики по протоколам, допустимы следующие значения:
                IP, IPv6, ICMP, ICMPv6, TCP, TCPv6, UDP или UDPv6.
  -r            Отображение содержимого таблицы маршрутов.
  -s            Отображение статистики по протоколам.  По умолчанию статистика
                отображается для протоколов IP, IPv6, ICMP, ICMPv6, TCP, TCPv6,
                UDP и UDPv6. Параметр -p позволяет указать подмножество
                выводимых данных.
  -t            Отображение состояния разгрузки для текущего подключения.
  -x            Отображение подключений, прослушивателей и общих конечных точек
                NetworkDirect.
  -y            Отображение шаблона подключений TCP для всех подключений.
                Не может использоваться вместе с другими параметрами.
  interval      Повторное отображение выбранной статистики с паузой
                между отображениями, заданной интервалом
                в секундах.  Чтобы прекратить повторное отображение
                статистики, нажмите клавиши CTRL+C.
                Если этот параметр опущен, netstat напечатает текущую
                информацию о конфигурации один раз.

Кроме того, оказалось, что контрольный порт TOR (9151) уже используют два каких-то нахала

In []:
C:\Users\kiss\Anaconda>netstat -an
Активные подключения

  Имя    Локальный адрес        Внешний адрес          Состояние
...
...
TCP    127.0.0.1:9150         0.0.0.0:0              LISTENING
TCP    127.0.0.1:9151         0.0.0.0:0              LISTENING
TCP    127.0.0.1:9151         127.0.0.1:51571        ESTABLISHED
TCP    127.0.0.1:9151         127.0.0.1:51579        ESTABLISHED
....

Далее я прекратил самостоятельные эксперименты и решил найти решение моих проблем на StackOverflow

В чем, собственно, мои проблемы? Я просто не могу запустить telnet в windows. После набора "o mail.ru 80" пояявляется надпись типа "...соединение с сервером..." и все подвисает. Если попытаться нажать на Enter, то курсор перемещается в левый верхний угол, но старый текст при этом остается в консоли, ...очевидно, что это ненормально. Изначально Telnet создавался для взаимодействий сервер-клиент..., но с тех пор устарел..., поэтому, после того, как я не смог быстро найти мануалы в сети, было решено искать на StackOverflow

Здесь я нашел почти все ответы How HTTP servers accepts Telnet

Telnet has no particular codes, all it does is opening a TCP socket to the remote host, and then sends it the input from stdin and prints the responses to stdout.

If you run

In []:
$ telnet stackoverflow.com 80

you get a command prompt where you can send text or bytes to a remote server and view the answers in real-time.

Но сокет сокетом, а некоторые переговоры Telnet проводит... и нам не показывает.

....You are right in saying that telnet is its own protocol, which is described in a couple of RFC's. You can take a look at wikipedia to see which ones exactly and some other resources that explain the protocol.

Basically it works like this: when you use telnet to connect to a server, it will show every printable character the server sends to you. And everything you type will be sent back to the server. This is how you can retrieve web pages when connecting to a web server: you send a command that a http server accepts and get the correct result.

Now, there are a few telnet specifics option. IIRC, you won't send them to the server unless the server sends them first. Those options are used to enable/disable local echo (think about passwords, you don't want those visible when logging in), negotiate terminal size, negotiate end of line type.

Those are commands that are a few bytes long and start with byte 255 (called IAC, interpret as command). When you connect to a telnet server, your client will interpret those and reply accordingly, all automatically in the background, without showing you those commands.

Although not specific to telnet, a telnet server can also send ANSI escape sequences. Those are used for colors, bold, cursor positioning, ... A telnet client will also interpret those (or just pass them on to the terminal emulator you're using, like xterm).

If you want something "lower-level" than telnet, which won't interpret telnet options and actually display what you get, you may want to take a look at netcat

Три очень важных утверждения

Telnet is just an easy interactive way to open a TCP connection to a listening socket.

Because the telnet client blindly sends what you type to that socket, it can theoretically emulate any other protocol on top of TCP.

Actually the fact that non printable chars are interpreted by the keyboard driver is the only limit.

Получается, что TCP connection устанавливается (все же) автоматически. А вот, чтобы дальше сформировать заголовок к HTTP-запросу, надо использовать клавиатуру.

HTTP does not use non printable chars except to delimit between the HTTP header and the body with two consecutive "line breaks" (i.e. a "blank line"). Please note that I'm not talking about the HTML body tag here, but the payload (e.g SOAP body).

No magic here basically.

Let's see the dynamic of things. HTTP supports a number of commands like GET, POST, PUT etc... Each command has its syntax and there is an associated response with an agreed upon syntax and well defined error codes.

When you connect to an HTTP server using telnet, you open the socket connection and the server forks a thread to manage the dialog with your client. You can then mimic a browser by typing the command that the browser would send. Each time you strike the CR key, the client submits the line to the server.

If a command contains several lines, you can enter several lines, each of them corresponding to a line of the command header. Once you strike two CR in a row (i.e. an empty line), the command header is deemed complete by the server and the response is put together and sent back to your client.

Because a telnet client's life goal is to echo received characters (unless told otherwise), then you can see the response header and body on your terminal window.

Telnet stops there. A browser would render the HTML (if the response is an HTML page). I hope that clarifies it all.

Далее отличный пример

You can query a http server using telnet, I often do as a quick and nasty test telnet doesnt send any codes. it just makes the connection, but there are telnet specific codes you can send if you require do this...

In []:
telnet server.com 80
GET http/1.0 /^m
host: server.com^m
^m

... servers response
#  ^m = enter key

# I have done this is done in linux in windows it may be different. !!!

Telnet commands от technet.microsoft.com

Command

Description

open

Use open hostname portnumber to establish a Telnet connection to a host.

close

Use the close command to close an existing Telnet connection.

display

Use the display command to view the current settings for the Telnet client.

The display command lists the current operating parameters. If you are in a Telnet session (connected to a Telnet server), to modify the parameters, press CTRL+]. This escapes from the Telnet session. (To return to the Telnet session, press ENTER.) The following operating parameters are available:

  • WILL AUTH (NTLM Authentication)

  • WONT AUTH 

  • WILL TERM TYPE 

  • WONT TERM TYPE 

  • LOCALECHO off 

  • LOCALECHO on 

quit

Use the quit command to exit from Telnet.

set

Use the set command to set the terminal type for the connection, turn on local echo, set authentication to NTLM, set the escape character, and set up logging.

  • SET NTLM turns on NTLM.

    While you are using NTLM Authentication, you are not prompted for a logon name and password when connecting from a remote computer.

  • SET LOCALECHO turns on local echoing.

  • SET TERM {ANSI|VT100|VT52|VTNT} sets the terminal type to the appropriate terminal type.

    Use the VT100 terminal type if you are running normal command-line applications. Use the VTNT terminal type if you are running advanced command-line applications, such as edit.

  • ESCAPE Character sets the key sequence to use for switching from session to command mode. For example, to set CTRL+P as your escape character, type set escape, press CTRL+P, and then press ENTER.

  • LOGFILE FileName sets the file to be used for logging Telnet activity. The log file must be on your local computer.

    Logging begins automatically when you set this option.

  • LOGGING turns on logging.

    If no log file is set, an error message is displayed.

unset

Use unset to turn off local echo or to set authentication to logon/password prompt.

  • UNSET NLM turns off NLM.

  • UNSET LOCALECHO turns off local echoing.

status

Use the status command to determine whether the Telnet client is connected.

CTRL+]

Press CTRL+] to move to the Telnet command prompt from a connected session.

enter

Use the enter command from the command prompt to go to the connected session (if it exists).

?/help

Prints Help information.

How to activate telnet in windows 7 without administration

This is not necessarily the answer to activate telnet, but this does answer how to get telnet working from commandlline on windows 7 without having admin privileges and without putty.

Answer is pretty simple:

Install cygwin with inetutils for telnet http://www.question-defense.com/2010/11/30/install-telnet-using-cygwin-on-windows-7, Add cygwin bin to my local env PATH variable http://superuser.com/questions/25037/change-environment-variables-as-standard-user-windows-7

In []:
#I want to issue then following requests to a telnet session:

telnet www.example.com 80

GET / HTTP/1.1\r\nHost: www.example.com\r\nConnection: close\r\n\r\n

# Telnet doesn't seem to recognise the '\r\n' as a carriage return and just sends the lot on to the remote host. 
# What should I put in place of '\r\n' to render a carriage return in the telnet terminal. 
# It does work when I paste the following into the terminal:

GET / HTTP/1.1
Host: www.example.com
Connection: close

# followed by two presses of the RETURN key. Is there a hex code I can send to telnet i.e. \0x01 or something like that?

# Can I change the options of the TELNET shell to show what I pasted also? 
# I can't find a way to do SET LOCALECHO since I'm opening the TELNET shell and connecting at the same time.

# Thanks for any help on this.
In []:
# /r/n is a perfectly acceptable carriage return line feed character for ANSI, 
# which is what most telnet clients communicate in. Are you applying the @ sign in front of your string?

#ie:

@"GET / HTTP/1.1\r\nHost: www.example.com\r\nConnection: close\r\n\r\n";  

# If you are trying to type in /r/n and pasting that input in raw, 
# then the telnet component will often assume you wanted the characters sent as they are type(not as new lines) 
# and do so accordingly.
In []:
# I am using Ubuntu telnet client. I am trying to send 2 lines over the telnet connection that I have made.

# For example:

> telnet en.wikipedia.org 80
  GET /wiki/Main_Page http/1.1   <CR>                            // line 1
  Host: en.wikipedia.org         <CR>                            // line 2
  <CR>
# where CR stands for carriage return. The problem is after typing line 1, press CR , 
# that line will be sent over the telnet connection. I can not be able to send line 2 immediately after that.

#Can somebody help?

When you are operating in a Telnet client, sending a newline or carriage return control code to the client, will send it directly to the host.

The easiest way to do what you want would be to copy/paste the HTTP GET request from another text editor, so that the newlines are embedded in the text.

to clarify, it seems that pressing the enter-key when in a telnet session will always send either or ***.

The only way to transmit just at the end of a line is to copy/paste it from somewhere else like an editor

In []:
# You can set the crlf option in telnet. You can do this by, 
# during your telnet session, typing the escape character (^]), and then "toggle crlf". 
# A perhaps cleaner way is to specify this before making the connection:

$ telnet
telnet> toggle crlf
Will send carriage returns as telnet <CR><LF>.
telnet> open mailhost smtp

Здесь есть ссылки на статьи, в которых утверждается, что нельзя использовать backspace (надо копипастить), исполльзовать тот же регистр, кроме того, Гугл может просто не разговаривать с Telnet user-agent

Нет, гугл разговаривает, вот пример, которыя я повторил, и Гугл выдал мне ссылку с переадресацией. Пока я думал, что с ней делать, Гугл перестал ждать и разорвал соещдинение.



Посты чуть ниже также могут вас заинтересовать

Комментариев нет:

Отправить комментарий