Preventing JavaScript Injection Attacks

보안 소식/주간 이슈 2009. 12. 7. 11:00 Posted by 알 수 없는 사용자
asp.net 환경에서 JavaScript Injection 취약점이 실행되는 것을 HTML Encode을 적용하여 예방할 수 있습니다.

다음은 website에 입력값이 들어올 때 HTML encode을 적용하여 JavaScript injection attack을 예방할수 있는 간단한 소스코드 입니다.

Index.aspx (HTML Encoded)
<%@ Page Language="VB" MasterPageFile="~/Views/Shared/Site.Master" AutoEventWireup="false" CodeBehind="Index.aspx.vb" Inherits="CustomerFeedback.Index"%>

<asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server">
     <h1>Customer Feedback</h1>
     <p>
          Please use the following form to enter feedback about our product.
     </p>

     <form method="post" action="/Home/Create">
          <label for="message">Message:</label>
          <br />
          <textarea name="message" cols="50" rows="2"></textarea>
          <br /><br />
          <input type="submit" value="Submit Feedback" />
     </form>

     <% For Each feedback As CustomerFeedback.Feedback In ViewData.Model%>
          <p>
          <%=feedback.EntryDate.ToShortTimeString()%>
          --
          <%=Html.Encode(feedback.Message)%>
          </p>
     <% Next %>

</asp:Content>

<%=Html.Encode(feedback.Message)%> 부분이 HTML encoded를 적용하게 됩니다.
<script>alert("a3sc");</script> → &lt;script&gt;alert(&quot;Boo!&quot;)&lt;/script&gt;

HTML encode가 적용되어 취약점이 실행되지 않은 화면입니다.


HomeController.cs (HTML Encoded)
Public Class HomeController
     Inherits System.Web.Mvc.Controller

     Private db As New FeedbackDataContext()

     Function Index()
          Return View(db.Feedbacks)
     End Function

     Function Create(ByVal message As String)
          ' Add feedback
          Dim newFeedback As New Feedback()
          newFeedback.Message = Server.HtmlEncode(message)
          newFeedback.EntryDate = DateTime.Now
          db.Feedbacks.InsertOnSubmit(newFeedback)
          db.SubmitChanges()

          ' Redirect
          Return RedirectToAction("Index")
     End Function

End Class

참고사이트
http://www.asp.net/learn/mvc/tutorial-06-vb.aspx