XSS는 공격자가 웹 페이지에 악성 스크립트를 삽입하여 다른 사용자의 정보를 탈취하는 기법입니다.
예제
다음은 XSS 공격에 취약한 댓글 폼 예제입니다.
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>댓글 폼</title>
</head>
<body>
<h2>댓글 작성</h2>
<form method="POST" action="comment.php">
이름: <input type="text" name="name"><br>
댓글: <textarea name="comment"></textarea><br>
<input type="submit" value="댓글 작성">
</form>
<h2>댓글 목록</h2>
<div id="comments">
<?php
$comments = file_get_contents('comments.txt');
echo $comments;
?>
</div>
</body>
</html>
php 예제
<?php
$name = $_POST['name'];
$comment = $_POST['comment'];
file_put_contents('comments.txt', "<p><strong>$name:</strong> $comment</p>", FILE_APPEND);
header('Location: index.html');
?>
사용자가
<script>alert('XSS');</script>
와 같은 값을 입력하면 XSS 공격이 발생할 수 있습니다.
방어
XSS를 방어하기 위해 사용자 입력을 적절히 이스케이프 처리합니다.
<?php
$name = htmlspecialchars($_POST['name'], ENT_QUOTES, 'UTF-8');
$comment = htmlspecialchars($_POST['comment'], ENT_QUOTES, 'UTF-8');
file_put_contents('comments.txt', "<p><strong>$name:</strong> $comment</p>", FILE_APPEND);
header('Location: index.html');
?>
Your website is an excellent resource for professionals in related fields.
Pretty nice post. I just stumbled upon your blog and
wished to say that I have truly loved browsing your weblog posts.
After all I will be subscribing for your feed and I’m hoping you write again soon!
Your expertise shines through in this piece; I’m awe-inspired.