반응형

출처: http://www.hahwul.com/2015/07/web-hacking-xsscross-site-script.html


웹 해킹으로 먹고 살기에 어김없이 보던 중 최근 WVS 결과를 보고 재미있는 사실을 알았습니다.
바로 XSS 와 함께 Cross Frame Script를 보게되었는데, XFS는 처음 들어본 단어였습니다.

XSS와 유사하지만 약간 달라서 XFS라고 명시하고 따로 부르는 듯 합니다.
찾아보니 OWASP에서도 정확하게 명시되어 있었네요..

XFS란?

Cross-Frame Scripting (XFS) is a method of exploiting Cross-site Scripting (XSS). In an XFS attack, the attacker exploits a specific cross-frame-scripting bug in a web browser to access private data on a third-party website. The attacker induces the browser user to navigate to a web page the attacker controls; the attacker's page loads a third-party page in an HTML frame; and then javascript executing in the attacker's page steals data from the third-party page.
XFS also sometimes is used to describe an XSS attack which uses an HTML frame in the attack. For example, an attacker might exploit a Cross Site Scripting Flaw to inject a frame into a third-party web page; or an attacker might create a page which uses a frame to load a third-party page with an XSS flaw.
-OWASP web site-

XSS와 XFS 차이


둘의 차이는 간단합니다. 더 말하자면 XSS가 발생범위가 더 크다고 봅니다. XFS가 발생하는 부분에는 대다수 XSS가 동일하게 들어가기 때문입니다.
XFS는 웹에서 받은 파라미터를 iframe 태그 내 src 속성에 전달하여 사용하는 과정에서 취약점이 발생합니다.

/viewer?page=/test/index.html 과 같은 형태로 viewer 페이지에 page 파라미터를 통해 전달할 때 아래와 같이 노출되는 기능이 있다고 가정합니다.

output
<iframe src="/test/index.html" width=100 height=100></iframe>

위와 같은 형태라면 page 파라미터를 조작하여 공격자가 의도한 페이지로 iframe 링크를 걸 수 있는 XFS 공격구문 구성이 가능합니다.

XFS(Cross Frame Script)
/viewer?page=http://www.codeblack.net

output
<iframe src="http://www.codeblack.net" width=100 height=100></iframe>

해당 부분에서 XSS의 경우에는 javascript 를 이용하거나 html 태그, 속성을 이용하여 공격이 가능할 것입니다.
XSS(Cross Site Script)

input : /viewer?page=javascript:alert(45)
output : <iframe src="javascript:alert(45)" width=100 height=100></iframe>

input : /viewer?page="><script>alert(45)</script><hahwul a="1
output : <iframe src=""><script>alert(45)</script><hahwul a="1" width=100 height=100></iframe>

input : /viewer?page=xss" onload=alert(45) a="
output : <iframe src="xss" onload=alert(45) a="" width=100 height=100></iframe>

두 취약점 모두 유사한 형태이지만 XFS는 단순히 frame 을 통해 다른 도메인으로 연결이 가능할 때 취약하고, XSS는 좀 더 넓게 다른 도메인 및
페이지내에서 스크립트 실행이 직접적으로 가능한 경우도 포함하기 때문에 XSS가 더 risk 가 높은 취약점이라고 이야기 할 수 있습니다.

비슷한 듯 다른 두 공격방법에 대한 이야기였습니다. 감사합니다 :)

반응형
반응형

출처: http://www.hahwul.com/2015/06/web-hacking-hex-encoding-xss.html


웹 취약점 분석 중 가장 많이 발견되는 XSS 취약점에 관한 이야기입니다.
대체로 쉽게 필터링 없이 들어가는 사례도 많았지만 분석했던 대다수의 서비스는 강한 필터링이 적용되어 있었습니다.
그러나 이 필터링에도 규칙이 존재하며 해커는 필터링 규칙을 파악할 시 쉽게 우회가 가능합니다.

여러가지 우회 상황 중 이번에는 HEX Encoding 을 통한 필터링 우회를 볼까합니다.

1. HEX Encoding이란?

HEX 인코딩은 "&#x" 문자열을 통해 웹에서 hex 데이터를 표현하는 방법입니다. 편하게 부르기 위해 hex 인코딩이라 칭하지만
대부분의 인코딩 디코딩 툴에서는 HTML 으로 표기하는 경우가 많습니다.

2. 간단한 XSS 필터 및 일반적인 XSS 구문 삽입 


원리는 간단합니다. A를 나타내는 hex 값인 41에 &#x를 붙여주게 되면 &#x41 즉 텍스트 A를 의미하게 됩니다.
대부분의 XSS 필터는 입력값에 대해 특수문자를 &lt; &gt; 등으로 변환하여 공격자가 스크립트를 사용할 수 없도록 하는데요,
이러한 필터링 부분이 사용자 입력에 대해 검증한다면 공격자는 인코딩된 데이터를 이용해 필터링 규칙을 우회할 수 있습니다.

예를들어 아래와 같이 XSS 필터링 함수가 구현되어 있다고 생각해봅시다.

<?
 function XSSFilter($inputString)
 {
  $output = str_replace("<","&lt;",$inputString);
  $output = str_replace(">","&gt;",$output);
  return $output;
 }
?>

<?

 $sqlIn = $_GET['title'];
 $sqlIn = XSSFilter($sqlIn);
 db_connect($sqlIn);  // 뭐 이런식으로 있다고 가정합시다.

?>


대충 써내려간 코드라 아마 실제로 실행 안될수도 있습니다..

아무튼 위와 같은 경우에서는 get으로 title 파라미터에 값을 전송하여 db_connect를 통해 게시글에 글을 쓴다고 했을 때
< > 문자열에 대해서 필터링 되어 들어가게 됩니다. 대부분의 게시판은 태그 사용이 필요하기 때문에 주로 삽입 구간에서 XSS 필터를 적용합니다.

/?title=<script>alert(45)</script>   와 같은 형태로 공격구문을 넣었을 때 게시글에는 필터링되어 아래와 같이 나타나게 될 것입니다.

&lt;script&gt;alert(45)&lt;/script&gt;

3. HEX Encoding 을 통한 XSS


위에서 했던 방법과는 약간 다른 방법으로 XSS 구문 삽입을 시도해보겠습니다.
동일하게 title 파라미터에 스크립트 구문을 넣지만, hex 형태로 넣어보겠습니다.

/?title=%26%23x003C;script%26%23x003E;alert(45)%26%23x003C;/script%26%23x003E;     // & 는 파라미터 구분자이기 때문에 URL 인코딩을 적용해야합니다.
                                                                   // GET으로 전송 시 URL 인코딩이 자동으로 적용되지만 &, # 같은 특수기호는 직접  인코딩을 해줘야합니다.
/?title=%26%23x003C;script%26%23x003E;alert(45)%26%23x003C;/script%26%23x003E;     

위와 같이 전송 시 아까 만든 XSSFilter 함수는 str_replace 함수에서 문자열들이 걸러지지 않습니다.
이대로 DB 저장 후 게시판 같은 곳에서 노출이 될 때 hex 인코딩이 풀어져 나타난다면 아래와 같이 완전한 스크립트 구문이 나타납니다.

<script>alert(45)</script>

4. XSS 우회

사실 XSS 우회 방법에 대해서는 정해진게 없다고 생각됩니다. 기본적으로 인코딩이 많이 알려져 있지만 실제로 가장 중요하다고 생각되는건
XSS 필터 함수의 규칙인 것 같습니다. BBT(BlackBoxTest)에서는 코드를 볼 수 없기 때문에 반복적인 테스트와 추측 등을 통해 규칙을 유추하고
그 안에서 헛점을 찾아 규칙을 우회하여야만 XSS 공격에 성공할 수 있습니다.

반응형
반응형

출처: http://www.hahwul.com/2015/03/xss-html-event-handler-xsscross-site.html


XSS 테스트 시 많이 사용하는 방법인 이벤트 핸들러를 사용하는 방법입니다.
주로 < > 에 대한 필터링이 적용되어 있거나 싱글쿼터, 더블쿼터에 대한 필터링이 없을 경우 이벤트 핸들러를 이용하여 XSS 구문 삽입을 시도할 수 있습니다.

예를 들어 아래와 같이  Request에 대해 Response가 도착한다면 이벤트 핸들러를 이용한 공격방법을 구상해볼 수 있습니다.

Request 
/test.html?search=test&no=aaa<br>111"11  


Response
<input type="image" value="aaa&lt;br&gt;111"11" src="123.jpg">


Attack Code
/test.html?search=test&no=" onload=alert(45)


onload를 이용하여 해당 구간(이미지)가 정상 로드 되었을 때 값이 실행되며 스크립트가 실행됩니다. 이미지 로드가 실패하는 구간이라면 onerror를 통해서도 가능하며, white list 기반 필터링이 아니라면 시도해 볼 수 있는 이벤트 핸들러는 매우 많습니다. (#1 참조)

테스트를 하다보면 삽입구간에서 hidden type 을 만나게 되는 경우도 많습니다.
< > 가 필터링되지 않는다면 "><script></script> 형태로 구문을 사용하여서 XSS에 성공할 수 있지만 그렇지 않은 경우 이벤트 핸들러로도 제어가 불가능한 부분이 많습니다.

<input value="" type="hidden">

위 같은 경우 hidden 속성으로 인해 사용 불가능한 속성이 다수 존재합니다.
다만 재미있는 경우는 type 속성이 삽입되는 구간보다 뒤에 있다면 type을 변조하여 쉽게 제어가 가능합니다.

Attack Request
/test.html?search=test&no=" type="text" onfocus=alert(45) autofocus test="


Response
<input value="" type="text" onfocus=alert(45) autofocus test="" type="hidden">


Reflected XSS 뿐만 아니라 Stored XSS에서도 이벤트 핸들러를 이용하는 경우도 많이 존재합니다.
새로운 공격 기술이나 취약점은 아니지만 다른 누군가에게는 도움이 될 수 있을거라 생각하여 작성해보았습니다. 

짧은 글이지만 재미있게 보셨다면 좋겠네요.
감사합니다 :)



#1 이벤트 핸들러 리스트(OWASP XSS Filter Evasion Cheat Sheet 내 일부)

  1. FSCommand() (attacker can use this when executed from within an embedded Flash object)
  2. onAbort() (when user aborts the loading of an image)
  3. onActivate() (when object is set as the active element)
  4. onAfterPrint() (activates after user prints or previews print job)
  5. onAfterUpdate() (activates on data object after updating data in the source object)
  6. onBeforeActivate() (fires before the object is set as the active element)
  7. onBeforeCopy() (attacker executes the attack string right before a selection is copied to the clipboard - attackers can do this with the execCommand("Copy")function)
  8. onBeforeCut() (attacker executes the attack string right before a selection is cut)
  9. onBeforeDeactivate() (fires right after the activeElement is changed from the current object)
  10. onBeforeEditFocus() (Fires before an object contained in an editable element enters a UI-activated state or when an editable container object is control selected)
  11. onBeforePaste() (user needs to be tricked into pasting or be forced into it using the execCommand("Paste") function)
  12. onBeforePrint() (user would need to be tricked into printing or attacker could use the print() or execCommand("Print") function).
  13. onBeforeUnload() (user would need to be tricked into closing the browser - attacker cannot unload windows unless it was spawned from the parent)
  14. onBeforeUpdate() (activates on data object before updating data in the source object)
  15. onBegin() (the onbegin event fires immediately when the element's timeline begins)
  16. onBlur() (in the case where another popup is loaded and window looses focus)
  17. onBounce() (fires when the behavior property of the marquee object is set to "alternate" and the contents of the marquee reach one side of the window)
  18. onCellChange() (fires when data changes in the data provider)
  19. onChange() (select, text, or TEXTAREA field loses focus and its value has been modified)
  20. onClick() (someone clicks on a form)
  21. onContextMenu() (user would need to right click on attack area)
  22. onControlSelect() (fires when the user is about to make a control selection of the object)
  23. onCopy() (user needs to copy something or it can be exploited using the execCommand("Copy") command)
  24. onCut() (user needs to copy something or it can be exploited using the execCommand("Cut") command)
  25. onDataAvailable() (user would need to change data in an element, or attacker could perform the same function)
  26. onDataSetChanged() (fires when the data set exposed by a data source object changes)
  27. onDataSetComplete() (fires to indicate that all data is available from the data source object)
  28. onDblClick() (user double-clicks a form element or a link)
  29. onDeactivate() (fires when the activeElement is changed from the current object to another object in the parent document)
  30. onDrag() (requires that the user drags an object)
  31. onDragEnd() (requires that the user drags an object)
  32. onDragLeave() (requires that the user drags an object off a valid location)
  33. onDragEnter() (requires that the user drags an object into a valid location)
  34. onDragOver() (requires that the user drags an object into a valid location)
  35. onDragDrop() (user drops an object (e.g. file) onto the browser window)
  36. onDragStart() (occurs when user starts drag operation)
  37. onDrop() (user drops an object (e.g. file) onto the browser window)
  38. onEnd() (the onEnd event fires when the timeline ends.
  39. onError() (loading of a document or image causes an error)
  40. onErrorUpdate() (fires on a databound object when an error occurs while updating the associated data in the data source object)
  41. onFilterChange() (fires when a visual filter completes state change)
  42. onFinish() (attacker can create the exploit when marquee is finished looping)
  43. onFocus() (attacker executes the attack string when the window gets focus)
  44. onFocusIn() (attacker executes the attack string when window gets focus)
  45. onFocusOut() (attacker executes the attack string when window looses focus)
  46. onHashChange() (fires when the fragment identifier part of the document's current address changed)
  47. onHelp() (attacker executes the attack string when users hits F1 while the window is in focus)
  48. onInput() (the text content of an element is changed through the user interface)
  49. onKeyDown() (user depresses a key)
  50. onKeyPress() (user presses or holds down a key)
  51. onKeyUp() (user releases a key)
  52. onLayoutComplete() (user would have to print or print preview)
  53. onLoad() (attacker executes the attack string after the window loads)
  54. onLoseCapture() (can be exploited by the releaseCapture() method)
  55. onMediaComplete() (When a streaming media file is used, this event could fire before the file starts playing)
  56. onMediaError() (User opens a page in the browser that contains a media file, and the event fires when there is a problem)
  57. onMessage() (fire when the document received a message)
  58. onMouseDown() (the attacker would need to get the user to click on an image)
  59. onMouseEnter() (cursor moves over an object or area)
  60. onMouseLeave() (the attacker would need to get the user to mouse over an image or table and then off again)
  61. onMouseMove() (the attacker would need to get the user to mouse over an image or table)
  62. onMouseOut() (the attacker would need to get the user to mouse over an image or table and then off again)
  63. onMouseOver() (cursor moves over an object or area)
  64. onMouseUp() (the attacker would need to get the user to click on an image)
  65. onMouseWheel() (the attacker would need to get the user to use their mouse wheel)
  66. onMove() (user or attacker would move the page)
  67. onMoveEnd() (user or attacker would move the page)
  68. onMoveStart() (user or attacker would move the page)
  69. onOffline() (occurs if the browser is working in online mode and it starts to work offline)
  70. onOnline() (occurs if the browser is working in offline mode and it starts to work online)
  71. onOutOfSync() (interrupt the element's ability to play its media as defined by the timeline)
  72. onPaste() (user would need to paste or attacker could use the execCommand("Paste") function)
  73. onPause() (the onpause event fires on every element that is active when the timeline pauses, including the body element)
  74. onPopState() (fires when user navigated the session history)
  75. onProgress() (attacker would use this as a flash movie was loading)
  76. onPropertyChange() (user or attacker would need to change an element property)
  77. onReadyStateChange() (user or attacker would need to change an element property)
  78. onRedo() (user went forward in undo transaction history)
  79. onRepeat() (the event fires once for each repetition of the timeline, excluding the first full cycle)
  80. onReset() (user or attacker resets a form)
  81. onResize() (user would resize the window; attacker could auto initialize with something like: <SCRIPT>self.resizeTo(500,400);</SCRIPT>)
  82. onResizeEnd() (user would resize the window; attacker could auto initialize with something like: <SCRIPT>self.resizeTo(500,400);</SCRIPT>)
  83. onResizeStart() (user would resize the window; attacker could auto initialize with something like: <SCRIPT>self.resizeTo(500,400);</SCRIPT>)
  84. onResume() (the onresume event fires on every element that becomes active when the timeline resumes, including the body element)
  85. onReverse() (if the element has a repeatCount greater than one, this event fires every time the timeline begins to play backward)
  86. onRowsEnter() (user or attacker would need to change a row in a data source)
  87. onRowExit() (user or attacker would need to change a row in a data source)
  88. onRowDelete() (user or attacker would need to delete a row in a data source)
  89. onRowInserted() (user or attacker would need to insert a row in a data source)
  90. onScroll() (user would need to scroll, or attacker could use the scrollBy() function)
  91. onSeek() (the onreverse event fires when the timeline is set to play in any direction other than forward)
  92. onSelect() (user needs to select some text - attacker could auto initialize with something like: window.document.execCommand("SelectAll");)
  93. onSelectionChange() (user needs to select some text - attacker could auto initialize with something like: window.document.execCommand("SelectAll");)
  94. onSelectStart() (user needs to select some text - attacker could auto initialize with something like: window.document.execCommand("SelectAll");)
  95. onStart() (fires at the beginning of each marquee loop)
  96. onStop() (user would need to press the stop button or leave the webpage)
  97. onStorage() (storage area changed)
  98. onSyncRestored() (user interrupts the element's ability to play its media as defined by the timeline to fire)
  99. onSubmit() (requires attacker or user submits a form)
  100. onTimeError() (user or attacker sets a time property, such as dur, to an invalid value)
  101. onTrackChange() (user or attacker changes track in a playList)
  102. onUndo() (user went backward in undo transaction history)
  103. onUnload() (as the user clicks any link or presses the back button or attacker forces a click)
  104. onURLFlip() (this event fires when an Advanced Streaming Format (ASF) file, played by a HTML+TIME (Timed Interactive Multimedia Extensions) media tag, processes script commands embedded in the ASF file)
  105. seekSegmentTime() (this is a method that locates the specified point on the element's segment time line and begins playing from that point. The segment consists of one repetition of the time line including reverse play using the AUTOREVERSE attribute.)

(OWASP)

반응형
반응형

출처:http://www.hahwul.com/2016/06/web-hacking-hiddenxss-xss-in-hidden.html


웹 취약점 진단에서 가장 만만하면서 가장 어려울때도 있는 XSS에 대한 이야기를 할까합니다. 그 중에서도 오늘은 hidden XSS. 즉 hidden 속성을 가진 태그에 대한 xss입니다.

앞서 간단하게 hidden 속성, 왜 hidden이 우회하기 힘든지 설명하고 각각 우회 방법에 대해 작성하였습니다.
읽으시기 전에 편한 이해를 위하여 코드 부분에 대한 설명부터 하겠습니다. (아래 양식으로 Case 별로 작성하였습니다.)


제약조건: # 우회하기 위해 필요한 조건
query:   # 공격(Attack) Query
output   # 결과
원문:    # 사용자 입력 구간이 들어가는 곳(Default code)
         # [USER INJECT] -> 공격 포인트(Attack point)
공격:    # qeury 입력으로 발생한 결과(공격으로 인한 output)

hidden 속성이란?

웹은 각각의 태그와 속성으로 이루어져서 사용자에게 알아보기 좋은 웹 UI를 제공해줍니다.
브라우저가 HTML을 해석하는 과정에서 hidden 속성을 만나게 되면 페이지에 노출하지 않게 됩니다.

다만 이 노출은 display:none과 약간 다른 성격을 가지는데요. display:none은 페이지에 보이지 않게하지만 hidden 속성은 존재 자체를 없애버립니다 =_=

그래서.. hidden이 들어간 태그에 대해서는 onmouseover, onclick, onfocus 등의 속성을 이용한 공격이 불가하게 되지요.

Hidden XSS 1 - 태그 탈출하기(Escape input tag)

가장 오랜된 방법이며 대체로 불가능한 경우가 많은 방법입니다.
단순히 hiddend을 나가기 위한 방법만이 아닌 XSS를 하기 위해서 많이들 사용하는 방법이며
quote('), double qoute(") 를 통해 삽입 구간이후로 나가 > < 등 특수문자로 tag 밖으로 나갑니다.


제약조건: 특수문자 우회(" ' < >)
query: "><img src="z" onerror="alert(45)">
output
원문: <input type="hidden" name="xsstest" value="[USER INJECT]">
공격: <input type="hidden" name="xsstest" value=""><img src="z" onerror="alert(45)">">




이 방법은 각 속성을 나갈 수 있는 더블퀘테이션, 쿼테이션이 필요하며 < >  와 같이 태그 문자열도 들어가서
많은 취약 조건이 필요합니다.

Hidden XSS 2 - type 속성 변조하기(Tampering type attribute)

이 방법은 사용자 입력이 type 속성보다 앞이 있을 때 가능합니다.
원래 선언된 type보다 먼저 type을 선언하여 hidden을 풀어서 xss를 수행합니다.


제약조건: user input이 type 속성보다 앞에 선언되어야 함 / 특수문자 우회(" or ')
query: " type="text" onfocus="alert(45)" autofocus a="
output
원문: <input name="xsstest" value="[USER INJECT]" type="hidden">
공격: <input name="xsstest" value="" type="text" onfocus="alert(45)" autofocus a="" type="hidden">

개발자의 간단한 실수(왜 type을 뒤에 썼을지..)로 인해서 우회가 가능한 case 이지요.



Hidden XSS 3 - 스타일 속성으로 태그 끌어내기(sytle="display:block")

세번째 방법은 구버전의 IE(6,7,8)과 Firefox 구버전에서 가능한 방법입니다.
아직 아주 구버전의 소프트웨어를 사용하는 사용자가 존재하기 때문에 같이 언급하면 좋을 것 같아 작성하였습니다.


제약조건: 패치 이전 브라우저(IE6/7/8, firefox 구버전) , 특수문자 우회(' or ")
query: " onmouseover="alert(45)" style="display:block;width:100%;height:1000px;" a="
output
원문: <input type="hidden" name="xsstest" value="[USER INJECT]">
공격: <input type="hidden" name="xsstest" value="" onmouseover="alert(45)" style="display:block;width:100%;height:1000px;" a="">

예전에 가능했던 방법이며 현재는 브라우저사에서 sytle보다 hidden을 우선으로 주었기 때문에 불가능합니다.

Hidden XSS 4 - accesskey + onclick을 통한 우회

작년 11월(2015)에 PortSwigger(burp 벤더)에서 블로그로 포스팅한 방법입니다.
바로 accesskey 속성을 이용한 우회방법이죠.


제약조건: 사용자가 XSS를 트리거해야함. (key input)
query: hwul" accesskey="X" onclick="alert(45)" a="
output
원문: <input type="hidden" name="xsstest" value="[USER INJECT]">
공격: <input type="hidden" name="xsstest" value="hwul" accesskey="X" onclick="alert(45)" a=" ">




이 방법은 키 입력을 이용한 XSS 방법입니다. 저도 생각도 못한 속성으로 풀어나갔네요.
물론 직접 영향력을 만들기는 약간 어렵습니다. (사용자가 키 입력으로 트리거 해야하기 때문에)

Vulnerability Trigger
Firefox - linux/windows : ALT+SHIFT+X
OS X - CTRL+ALT+X

사용자에게 입력을 유도할 수 있다면 좋은 우회방법이겠지요.

정리

앞에 3가지 방법은 hidden을 우회하기 위해서 많이 찾아보셨을 것 같습니다.
4번은 트리거 조건은 약간 있지만 우회가 가능하고 이것에 대해서 따로 패치도 없었기 때문에
진단/모의해킹 시 나름 유용하게 사용될 수 있을 것 같네요.

항상 가까운곳에 해답이 있다고 생각합니다. 찾다보면 자기만의 재미있는 우회 방법이 생겨나지요 :)

Reference

http://blog.portswigger.net/2015/11/xss-in-hidden-input-fields.html

반응형

+ Recent posts