'웹프로그램'에 해당되는 글 6건

  1. 2009.12.08 안전한 PHP 프로그래밍 (첨부파일 다운 & include 함수)
  2. 2009.10.30 웹 어플리케이션 보안 취약점 테스트 (1)
  3. 2009.10.23 웹분석에 유용한 프락시(Proxy) 툴 (1)
2009. 12. 8. 16:42

안전한 PHP 프로그래밍 (첨부파일 다운 & include 함수)

1. 게시판 첨부파일 다운로드 개발시 주의점

국내 대형 IDC 운영사 사이트의 한 게시판에서 첨부파일 다운로드할 때, 내부 파일까지 다운로드할 수 있는 취약점이 있었다.
즉, /etc/ 이하의 파일이나 웹서버 설정 파일, 로그 등을 원하면 쉽게 받아볼 수 있는 취약점이었다.

이를테면 이런식이다. URL/download.html?path=/etc&file=resolv.conf&savename=resolv.txt
(물론 위처럼 직접적으로 URL을 표시하지 않았지만, 눈치만 있으면 쉽게 알 수 있음)
/etc/resolv.conf 를 받아서 PC에 resolv.txt 이름으로 저장하라는 예이다.
'어서오세요. 저희는 개방적인 마인드로 서버의 모든 것을 네티즌에게 원하는대로 다 드립니다.'라고 얘기하는 꼴이다.

이런 취약점을 통해

1) 시스템 사양 파악
  - 퍼미션에 둔감한 SE들이 상당히 많다.
  - 설정 파일 등 OS가 제공하는 기본 퍼미션을 그대로 사용하는 경우가 많다. 그러나 일반 user가 읽지 않아도 되는 파일이 상당히 많고, 실행하지 할 필요가 없는 파일도 매우 많다. 서비스 전에 미리 이런 파일들의 퍼미션을 강화하는게 좋다.
2) 내부 정보의 유출 (서버에 내부 정보 파일이 있다면)
3) 서버의 사양과 설정 파악으로, 시스템의 또다른 취약점까지 발견할 수 있는 위험도 있다.

첨부파일 다운로드시 다음과 같이 프로그래밍을 한다. (개인적으로 정리한 것)

1) 다운로드시 서버내 다운로드 경로를 URL로 지정하는 부분은 없앤다. 다운로드 로드 경로는 웹프로그램 내부 설정을 통해 처리해야.
2) /, \ 이나 .. 등 의 디렉토리 이동과 관련된 것은 사용하지 못하도록 한다. (필터링)
3) 파일명을 지정하지 않도록 하거나, (no=1 이면 게시물 1번의 파일 정보를 DB에서 읽어 다운로드시켜주면 된다.)
4) 암호화 처리하여 지정하게 한다.


2. php프로그래밍에서 include 취약

php에서 include() 함수를 사용할 때 주의하지 않아서, 내부 파일(local inclusion)이나 원격지 파일(remote file inclusion)을 include할 수 있는 취약한 사이트들이 있다.

의도적으로 URL을 통해 값을 넘겨받아 처럼) include하도록 개발하는 경우도 있다.
이를테면 왼쪽 메뉴는 고정인데, 오른쪽 내용만 바뀌는 페이지의 경우 include(page/$inc); 처럼 아주 단순하게 만들어 놓고, URL에는 사이트주소?inc=page1과 같이 처리하는 곳도 있다는 것이다. 유저를 너무나 신뢰하는, 믿음이 강한 개발자다.

1) include되면 원하는 서버 설정 파일을 볼 수 있는 것은 기본이다.

2) local include가 될 때 command를 실행할 수 있는 방법도 있다.
(원격지 파일을 include할 수 없더라도 command를 실행할 수 있음)

웹서버의 웹로그를 이용하는 방법이다. 특정한 방식으로 웹요청을 하여 웹로그에 <? ?> 등의 php tag가 저장되도록 하고, 이 웹로그 파일을 include되도록 하면 된다.
URL에 <? phpinfo(); ?> 를 요청하면 이게 %NN 처럼 인코딩되어 로그에 남기 때문에, 효과가 없다. 따라서 User Agent, Referer, 아파치 인증부분을 통해서 요청한다.

-
XAS(Cross Agent Scripting), XRS 취약점에 대해 (2009.3, 글 좋은진호)

위 XAS, XRS 취약점을 이용하듯이 웹요청을 하면, 웹로그에 <? phpinfo(); ?> 를 남길 수 있다. 위 글대로 요청할 때 웹로그에는 다음과 같이 남는다. 이해되는가? 이제 include에 이 로그파일만 지정해주면 php 명령을 실행할 수 있다. 물론 log파일을 읽을 수 있도록 퍼미션이 된 경우.
코드:

# 공개가 불필요한 부분은 ???로 변경해서 표시했다.

???.???.???.??? - - [??/???/2009:11:47:01 +0900] "GET / HTTP/1.1" 200 3901 "<script>alert('hello')</script>" "Mozilla/5.0 (X11; U; Linux i686; ko; rv:1.9.0.4) Gecko/200??????? Firefox/3.?.?"

-
Local File Inclusion - Tricks of the Trade (글 xeraph)

위의 글은 apache의 인증 부분을 필드에 <? .. ?> 와 같은 명령을 남기는 트릭입니다. 대단한 트릭이다. 어떻게 저런 생각을...

include 취약점을 없애기 위해 다음과 같이 프로그래밍을 한다. (개인적으로 정리한 것)

1) allow_url_include = off. php 5.2.x에서는 allow_url_include가 off로 되어 있다. 그 이전 버전 사용할 때, allow_url_fopen 로 설정하는데, 원격지 파일을 include나 fopen하는 경우가 없다면 off로 한다.
2) include() 함수에 사용되는 변수는 유저가 직접적으로(URL로) 설정할 수 없도록 한다.
3) include() 함수에 사용되는 변수값은 http :// , ftp :// 나 /, \, .. 등 을 필터링 처리한다.
4) 가능하면 register_globals = off


3. 안전한 php 프로그래밍에 관한 글들

-
PHP Security (Error reporting, SQL injections, XSS, file inclusion, XSRF 등)
-
PHP Security: Fortifying Your Website- Power Tips, Tools & How to’s
  ( Register_Globals, Error Reporting, XSS, File Inclusion, PHP Security Tools(PhpSecInfo, PHP Security Scanner, Spike PHP Security Audit Tool) 등)
-
PHP Security (PHP_SELF, Email Header Injection, Including Files, Error Reporting 등)
-
Remote File Inclusion


※ 참여자 : RedBaron, 범냉이, 티니, 좋은진호
※ 11.2(월)에 했던 커피닉스 이야기 중 비중 있는 부분을 별도로 정리했다.

출처 : http://coffeenix.net

Trackback 0 Comment 0
2009. 10. 30. 15:56

웹 어플리케이션 보안 취약점 테스트

WebScarab

Developed by the Open Web Application Security Project (OWASP), WebScarab is first and foremost a proxy used to analyze browser requests and server replies. In addition to serving as a tool for packet analysis, you can use it to "fuzz" sites, looking for some of the same exploits mentioned above. To use WebScarab, you first configure proxy settings in your Web browser. For Mozilla Firefox, perform these steps (see Firefox keyboard shortcuts for the alternative accessible steps):

  1. Click Tools > Options > Advanced > Network.
  2. Click Settings.
    The Connection Settings window opens.
  3. Select the Manual proxy configuration option.
  4. For both HTTP Proxy and SSL Proxy, type localhost, and set the port to 8008.
  5. Make sure the No proxy for box is empty, then click OK.

Figure 1. Firefox connection settings

For Windows® Internet Explorer®, perform the following steps (see Internet Explorer keyboard shortcuts in the IE Help menu for the alternative accessible steps):

  1. Click Tools > Internet Options > Connections.
  2. Click LAN Settings to open the Proxy Settings window.
  3. Under Proxy Servers, select the Use a proxy server for your LAN check box, then click Advanced.
  4. For HTTP and Secure, type localhost for the proxy address to use, then type 8008 for the port.
  5. Make sure the Exceptions box is empty, then click OK.

Figure 2. Setting the proxy

Now, you are ready to scan a Web site.

Scan your site with WebScarab

The following examples use the Hacme Casino site, which is built by Foundstone with certain vulnerabilities so that it can be used for training purposes. The site comes packaged with Apache Tomcat, as well, so you can run it locally if you wish.

Next, open WebScarab. Once you launch it, you will see only two tabs: Summary and Intercept. Because you want to use WebScarab for fuzzing, change the view by clicking Tools > Use full-featured interface > OK. You will then be asked to restart WebScarab. When you have done so, you can begin with the interface shown in Figure 3. (WebScarab provides a list of keyboard shortcuts—unfortunately only two.)


Figure 3. The WebScarab interface

To start your new session, click File > New. You are presented with a box that asks where you would like to save your session. Select or create the storage directory, then click OK. When you use WebScarab with Hacme Casino, start the server before opening your browser. Then, in the browser's address bar, type http://localhost:3000.

Once you open the browser, you should start seeing some activity in WebScarab, because WebScarab is capturing all the requests and replies between the browser and the server. Because you want to use the fuzzing feature to test for vulnerabilities, first look at where the different vulnerabilities can exist. Start by looking at the login as a potential exploit. To test the login, you should record the interaction that takes place between the browser and the server. There is no need for a successful login here, so you can enter whatever you like for the user name and password: For this example, enter casino for both the user name and password, then click Login.

Of course, the login will be unsuccessful, but that is not what you're interested in. Instead, go back to WebScarab. In the Path column, right-click account\login, then click Use as fuzz template, as shown in Figure 4.


Figure 4. The fuzzing template

Modifying the all_attack.txt file

Add the lines 'or 'x'='x and ') or 1=1-- to the file, because they are basic SQL injection strings and will work in this example.

Perform the following steps:

  1. Click the Fuzzer tab at the top of the WebScarab interface.
  2. Click Source.
  3. Browse to the location of your dictionary. (I used all_attack.txt)
  4. Provide a description of the source, then click Add.
  5. Click Close to return to the Fuzzer window.

Now, go to the user_login parameter and click in the area under the Fuzz Source column. Because you have only loaded one source—All attack—select it from the drop-down menu. Do the same for the user_password parameter, as shown in Figure 5.


Figure 5. Selecting the attack file

Now that you have defined the source, click Start to begin the process. The fuzzer inserts the parameters from the file into both the user name and password inputs. You should see some activity on the screen as the tool completes each attempt. Typically, you would need to examine each ID in the results to analyze what takes place with each attempt. However, because you know that the added strings will produce a result, you can see what can happen when the fuzzer is successful.

Double-click the first string in the example, shown in Figure 6.


Figure 6. Finding a vulnerability

Note that in the top circle, the value for user_login and user_password is ‘) OR 1=1--. Next, note that the location has changed from http://localhost:3000, which is the home page, to http://localhost:3000/lobby/games, which is what a user who successfully logged in would see. What does this mean? It means that your site is vulnerable. Because ‘) OR 1=1-- is an SQL string, the site is vulnerable to an SQL injection. Scroll through the results using the Next button, and look for that value. Notice that the location here remains http://localhost:3000. You know from this result that inserting this type of string would not result in a successful login attempt, so the site is not vulnerable to this type of attack.


Paros Proxy

Another useful tool for security testing is Paros Proxy. Like WebScarab, Paros captures conversations between the browser and the server for analysis. You can also use it to test for vulnerabilities on a site. To run Paros, you must change the port number used in the proxy settings of your browser. For WebScarab, you used 8008; change this port to 8080 before running Paros, or the tool won’t work. For this exercise, the example uses WebGoat, another tool from OWASP. Like Hacme Casino, WebGoat runs using the Tomcat server as a local host. For the purposes of this article, WebGoat shows more vulnerabilities in the Paros scan than would Hacme Casino.

Using multiple scanners

Anyone testing his or her own sites should learn from this that different scanners may show different results for the same site. That is why professional pen-testers use multiple tools when working.

After changing the port, open Paros. Then, perform these steps:

  1. In the WebGoat folder, double-click WebGoat.ba to start Tomcat.
  2. Open your browser, then type http://localhost/WebGoat/attack.
  3. Type guest for the user name and password.
  4. Click Start WebGoat.

Now, go back to Paros and start your scan of the WebGoat site. Of course, you can use your own site instead by entering its URL in the address bar.

In Paros, expand the Sites folder to see http://localhost in the tree. Expand this folder to bring up WebGoat. Highlight WebGoat, and then click Analyse Scan. This immediately begins the scan of the site. Large sites may take a while, but this one should only take a few seconds. Once it starts scanning, the bottom pane changes to the Alerts tab automatically (see Figure 7). When the scan is complete, click OK in the pop-up window that tells you where to find the report.


Figure 7. Viewing alerts

You can expand the alerts to show them in greater detail. You can also view the report, which offers much more information. First, however, save the scan results by clicking File > Save As, choosing a location and file name for your scan, and then clicking Save.

To view a report, click Report > Last Scan Report. Click OK in the pop-up window, and a new browser tab opens with the report of the scan results, as shown in Figure 8. This report provides a great deal of information regarding each vulnerability detected, including a reference to the OWASP page that deals with the specific exploit.


Figure 8. The Paros report


Although scanners are a good way to find possible vulnerabilities in a Web site, the best security companies always test possible vulnerabilities by hand for false positives. Testing for these possible exploits means actually going to the areas of your site that were reported as vulnerable, inserting SQL code or a script into the site itself to see what the response is, and then going into the site itself and plugging any exploits. Large firms often hire professional programmers who specialize in this type of testing (called vulnerability validation), but as a developer, you can perform some of these tests yourself. Not only will doing so help you secure your site a bit more, but it will help you as you build future sites.

False positives with SQL injection

Using the Hacme Casino site again, let's look at the vulnerability that WebScarab found: an SQL injection exploit at the login. With Hacme Casino running, enter the SQL code that WebScarab used successfully—‘) OR 1=1--—in the Login input area of the site. When you click Login, the account Andy_Aces is opened. Because 1=1 is going to be true, the most basic form of an SQL injection works here. As for Andy, he has the bad luck of being the first account in the database.

Just how did this work? In the back end, the database runs a query like this:

SELECT * FROM users WHERE (username=username AND password=password)

The bit of code injected through the Login box turned the valid query into this:

SELECT * FROM users WHERE (username=’’) OR 1=1—AND password=’’)

This query returns a successful login for the first user of the site, which is unfortunately Andy.

Of course, this example only scratches the surface of an SQL injection. As someone becomes more skilled in attacking Web sites, he or she can actually exploit this vulnerability to create users, change passwords, and extract sensitive data from the site. Protecting your site against these attacks involves taking a few steps:

  • Use parameterized queries or stored procedures to access a database as opposed to using string concatenation. Parameterized queries require that you define all the SQL code and then pass in each parameter to the query later. This allows the database to distinguish between code and data, so it doesn't matter what type user input is supplied. Stored procedures are similar to parameterized queries in that they require you to define the SQL code first, then pass in the parameters later. These elements differ in that the SQL code for a stored procedure is defined and stored in the database itself, then called from the application.
  • Sanitize user input by "whitelisting" the characters allowed. If you are asking for a name, only allow a-z and A-Z. For phone numbers, limit characters to 0-9. Use the appropriate validation technique supported by your database to do this.
  • Escape user-supplied input using the character escaping scheme set up by your database. Escaping special characters tells your database that the characters provided in the query are in fact data, not code. If all user-supplied input is then escaped using the proper scheme, the database will not confuse that input with SQL code you have written.
  • Don't give attackers any help. Make sure error messages don't give away information that can be later used against the site.

False positives with XSS

To demonstrate an example of an XSS attack, turn back to WebGoat. Start this site by clicking Cross Site Scripting > LAB: Cross Site Scripting > Stage 1: Stored XSS. Log in to the demo site—Goat Hills Financial—with a user name of Larry Stooge and the password larry. Now, an attacker would need to find somewhere to input a malicious script. The Search Staff function probably has a text box where someone can enter a name: Click Search Staff to reveal it, as shown in Figure 9.


Figure 9. An XSS entry point

In the Name box, type alert("You got me with XSS");. This script may only show an alert box like you see in Figure 10, but think about what could happen if the script could redirect a user to a fake human resources site where he or she had to enter a social security number, home address, bank information, and so on. Altering the action associated with the OK button can do this. For really creative malicious hackers, the sky is the limit if the user trusts them.


Figure 10. A successful XSS attack

To protect against XSS attacks, you need to scrub all inputs. If the input will later be used as parameters to operating system commands, scripts, and database queries, then it is essential that you do so. You can scrub user inputs by escaping untrusted data before allowing it to be inserted into HTML element content and HTML common attributes. OWASP recommends that all ASCII values less than 256 be escaped in the latter. JavaScript™ data values, HTML-style property values, and HTML value attributes can also be escaped. Of course, before you escape input data, make sure you have validated any input to your Web site. If you are looking for specific input values, numbers, letters, e-mail addresses, and the like, then only allow this type of data and refuse anything else.


원문 : http://www.ibm.com/developerworks

Trackback 0 Comment 1
  1. 한글번역 2009.12.11 09:17 address edit & del reply

    http://www.ibm.com/developerworks/kr/library/wa-appsecurity/index.html

2009. 10. 23. 10:28

웹분석에 유용한 프락시(Proxy) 툴

- Paros
 : http://www.parosproxy.org


- burpsuite
 : http://www.portswigger.net/suite



- WebScarab
 : http://www.owasp.org/index.php/Category:OWASP_WebScarab_Project


Trackback 0 Comment 1
  1. 고양이의 노래 2009.10.23 10:50 address edit & del reply

    bultsuite 오늘 메트로에서 대학전산망 해킹에 사용된 툴이라고 하던데 proxy툴이었군요. 저는 sniff류로 생각했었는데...