2003년 4월 17일 목요일

안전한 프로그래밍을 위한 도구

[ZDNet]
http://www.zdnet.co.kr/programming/lecture/etc/article.jsp?id=59370&page=2&forum=1

안전한 프로그래밍을 위한 도구

강유 (마이크로소프트웨어)
2003/03/14
  

지난번 강좌(도전!「버그 제로」프로그래밍)에서는 안전한 프로그래밍을 하기 위해 주의해야 할 점에 대해 알아봤다.

앞의 강좌가 조금 어렵게 느껴지는 독자도 있을 것이다. 하지만 안전한 프로그래밍을 위한 도구를 사용하면 그런 독자들도 쉽게 소스 코드의 문제점을 파악할 수 있다. 그러면 소스 코드의 문제점을 검사하기 위한 툴에 대해 알아보자.

소스코드를 검사해 문제를 집어내는「ITS4」
ITS4는 Cigital에서 만든 툴로서 C/C++ 소스 코드를 검사해 문제점이 있는 코드를 찾아준다. ITS4의 소스코드를 www.cigital.com/its4에서 구할 수 있다. 그러면 ITS4를 리눅스 시스템에 설치해 실행하는 과정을 알아보자.

[1] ITS4 설치 파일(its4-1.1.1.tgz)을 사용자의 홈 디렉토리로 다운로드한다.
[2] 다음 명령을 실행해 파일의 압축을 푼 다음 its4 디렉토리로 이동한다.
   > tar xvzf its4-1.1.1.tgz
   > cd its4
[3] > ./configure; make; make install 명령을 실행해 컴파일하고 its4를 시스템에 설치한다.
[4] 앞의 명령을 실행했으면 /usr/local/bin/its4라는 실행 파일이 생겼을 것이다.

its4가 어떤 문제점을 찾아내는지 검사해 보자. 검사를 제대로 하는지 확인하기 위해 필자가 직접 예제 코드를 작성했다. 예제 코드는 의도적으로 문제가 생길 만한 함수를 많이 집어넣은 코드다.


   [리스트 1] list.cpp - 검사 툴을 테스트할 예제 코드


1> #include <stdio.h>
2>
3> int main(void)
4> {
5>        int my_val;
6>        char buf[32]
7>        FILE * fp;
8>
9>        strcpy( buf, argv[1]);
10>
11>       printf( *buf = %s \n"m buf );
12>
13>        fp = fopen("list1.out", "w");
14>        fprintf( fp, "buf = %s \n", buf);
15>        fprintf( fp, "hello, world" );
16>
17>        fclose(fp);
18>
19>        return 0;
20> }





그러면 its4를 이용해 이 소스 코드를 분석해 보자. 리눅스 명령행에서 its4를 실행한 결과가 [화면]에 나와 있다. [화면]에서 알 수 있는 것처럼 its4에서는 문제있는 함수의 목록을 출력해 준다. 물론 its4가 출력한 결과가 모두 맞는 것은 아니다. 그렇지만 its4를 사용하면 코드 검사 시간을 많이 줄일 수 있다.



[화면] 리눅스에서 list4를 실행한 결과

C는 물론 PHP, 파이썬까지 검사하는「RATS」
RATS는 Secure Software Solutions에서 만든 오픈소스 툴이다. RATS를 사용하면 C, C++, Perl, PHP, 파이썬 소스 코드의 버그를 발견할 수 있다. RATS는 유닉스용과 윈도우용 모두 나와 있기 때문에 플랫폼에 구애받지 않고 사용 가능하다.

RATS를 사용해 윈도우 환경에서 소스 코드 검사를 해 보자. 먼저 www.securesoftware.com/download_form_rats.htm에서 rats-2.1-win32.zip 파일을 다운로드하고 압축을 푼다. 그러면 rats.exe 파일이 생길 것이다. rats를 사용하려면 expat이라는 XML 파싱 라이브러리를 먼저 시스템에 설치해야 한다. Expat은 prdownloads.sourceforge.net/expat/expat_win32bin_1_95_6.exe?download(expat_win32bin 버전 1.95.6)에서 받을 수 있다. 그럼 rats를 통해 앞서 소개했던 list1.cpp를 분석해 보자. 그 결과는 다음과 같다.

여기서 볼 수 있는 것처럼 rats에서는 위험이 있을 가능성이 있는 두 줄의 코드를 찾아냈다. [화면]과 앞의 코드를 비교해 보면 its4가 더 많은 문제점을 찾아내는 것을 알 수 있다.


체계적인 소스코드 검사 툴「Splint」
Splint는 미국 버지니아 대학에서 만든 C 소스 코드 검사 툴이다. Splint는 Splint 홈페이지(lclint.cs.virginia.edu)에서 구할 수 있다. Splint는 대학에서 만든 툴답게 다른 툴에 비해 훨씬 체계적으로 소스코드 검사를 할 수 있다는 장점이 있지만 사용하기가 조금 복잡하다는 단점이 있다. 관심있는 사람은 홈페이지를 방문하기 바란다.


   [리스트 2] rats 실행 결과


D:\RATS\rats-2.1-win32\rats-2.1>rats list1.cpp
Entries in perl database:33
Entries in python database: 62
Entries in c database: 334
Entries in php database: 55
Analyzing list1.cpp
list1.cpp:6: High: fixed size local buffer
Extra care should be taken to ensure that character arrays that are allocated on the stack are used safely. they are prime targets for buffer overflow attacks.

list1.cpp:9: High: strcpy
Check to ne sure that argument 2 passed to this function call will not copy more data than can be handled, resulting in a bugger overflow.

Total lines analyzed: 21
Total time 0.01600 seconds
1312 lines per second





Flawfinder
Flawfinder는 데이빗 휠러(David Wheeler)가 만든 C 소스 코드 검사 프로그램이다. Flawfinder는 오픈소스로 공개돼 있으며 www.dwheeler.com/flawfinder에서 구할 수 있다. Flawfinder 실행 결과는 다음과 같다. 출력 결과를 보면 Flawfinder에서도 strcpy와 정적 버퍼, 그리고 fopen 함수의 문제점을 보고하는 것을 알 수 있다.





[securityx@bastion flawfinder-1.21]$ ./flawfinder list1.cppFlawfinder version 1.21, (C) 2001-2002 David A. Wheeler.Number of dangerous functions in C/C++ ruleset: 127
Examining list1.cpp
list1.cpp:9 [4] (buffer) strcpy:
    Does not check for buffer overflows when copying to
    destination. Consider using strncpy or strlcpy (warning,
    strncpy is easily misused).
list1.cpp:6 [2] (buffer) char:
    Statically-sized arrays can be overflowed. Perform bounds
    checking, use functions that limit length, or ensure that the
    size is larger than the maximum possible length.
list1.cpp:13 [2] (misc) fopen:
    Check when opening files - can an attacker redirect it
    (via symlinks), force the opening of special file type
    (e.g., device files), move things around to create a race
    condition, control its ancestors, or change its contents?.

Number of hits = 3
Number of Lines Analyzed = 20 in 0.67 seconds (120 lines/second)
Not every hit is necessarily a security vulnerability.
There may be other security vulnerabilities; review your code!


지금까지 여러 소스 코드 검사 툴에 대해 살펴봤다. 소스 코드 검사 툴을 사용할 때 꼭 기억해야 할 것은 툴이 전부는 아니라는 것이다. 비록 툴을 사용하면 빠른 시간에 코드를 검사할 수 있다는 장점이 있긴 하지만 툴에서 검사한 내용을 테스트하고 분석하는 것은 사람 몫이다. 가장 이상적인 것은 툴로 먼저 검사를 해서 대부분의 문제점을 파악한 뒤 그 문제점에 대해 사람이 수동으로 검사하는 것이다.@

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

http://www.securesoftware.com/download_rats.htm
    
  
Welcome to RATS – Rough Auditing Tool for Security

RATS – Rough Auditing Tool for Security – is an open source tool developed and maintained by Secure Software security engineers. RATS is a tool for scanning C, C++, Perl, PHP and Python source code and flagging common security related programming errors such as buffer overflows and TOCTOU (Time Of Check, Time Of Use) race conditions.

RATS scanning tool provides a security analyst with a list of potential trouble spots on which to focus, along with describing the problem, and potentially suggest remedies. It also provides a relative assessment of the potential severity of each problem, to better help an auditor prioritize. This tool also performs some basic analysis to try to rule out conditions that are obviously not problems

As its name implies, the tool performs only a rough analysis of source code. It will not find every error and will also find things that are not errors. Manual inspection of your code is still necessary, but greatly aided with this tool.

RATS is free software. You may copy, distribute, and modify it under the terms of the GNU Public License.

Latest Release: 2.1

Source tarball: rats-2.1.tar.gz
Win32 Binary: rats-2.1-win32.zip

Requirements
------------
RATS requires expat to be installed in order to build and run. Expat is often installed in /usr/local/lib and /usr/local/include. On some systems, you will need to specify --with-expat-lib and --with-expat-include options to configure so that it can find your installation of the library and header.

Expat can be found at: http://expat.sourceforge.net/

Installation
------------
Building and installation of RATS is simple. To build, you simply need to run the configuration shell script in the distribution's top-level directory:

./configure

The configuration script is a standard autoconf generation configuration script and accepts many options. Run configure with the --help option to see what options are available.

Once the configuration script has completed successfully, simply run make in the distribution's top-level directory to build the program:

make

By default, RATS will be installed to /usr/local/bin and its vulnerability database will be installed to /usr/local/lib. You may change the installation directories of both with the --prefix option to configure. You may optionally use the --bindir and --datadir to
specify more precise locations for the files that are installed.

To install after building, simply run make with the install target:

make install

This will copy the built binary, rats, to the binary installation directory and the vulnerability database, rats.xml, to the data installation directory.

Running RATS
------------
Once you have built and installed RATS, it's time to start auditing your software! RATS accepts a few command line options that will be described here and accepts a list of files to audit on the command line. If no files to audit are specified, stdin will be used.

usage: rats [-d ] [-h] [-r] [-w ] [-x] [file1 file2 ... filen]


Options explained:
-d Specifies a vulnerability database to be loaded. You may
have multiple -d options and each database specified will
be loaded.
-h Displays a brief usage summary
-i Causes a list of function calls that were used which
accept external input to be produced at the end of the
vulnerability report.
-l Force the specified language to be used regardless of
filename extension. Currently valid language names are
"c", "perl", "php" and "python".
-r Causes references to vulnerable function calls that are not
being used as calls themselves to be reported.
-w Sets the warning level. Valid levels are 1, 2 or 3.
Warning level 1 includes only default and high severity
Level 2 includes medium severity. Level 2 is the default
warning level 3 includes low severity vulnerabilities.
-x Causes the default vulnerability databases (which are in
the installation data directory, /usr/local/lib by default)
to not be loaded.

When started, RATS will scan each file specified on the command line and produce a report when scanning is complete. What vulnerabilities are reported in the final report depend on the data contained in the vulnerability database or databases that are used and the warning level in use.

For each vulnerability, the list of files and line numbers where it occured is given, followed by a brief description of the vulnerability and suggested action.

Contact
-------
RATS is authored, maintained and distributed by Secure Software, Inc. All bug reports, patches, database contributions, comments, etc. should be sent to rats@securesoftware.com.

댓글 없음:

댓글 쓰기