LoginSignup
2
3

【注意】ポップアップ JS ライブラリ「Lightbox 2」での XSS 対策について

Posted at

今回は、画像のポップアップ表示で有名な JavaScript ライブラリ「Lightbox 2」を使用する際に自分がハマった点を紹介します。といっても、たいしたことは書けませんが、笑

概要

キャプションとして data-titleで設定した内容がデフォルトでサニタライズされない。HTML 出力時にはエスケープされていたとしても。

xss-sample.html
<!-- 開くと、javascript が実行されます -->
<a href="https://image.example.com/path/to/image.jpeg"
    data-lightbox="group1"
    data-title="&lt;script&gt;alert('xss');&lt;/script&gt;">
Open Image
</a>

対策

方法1. オプションを設定する(おすすめ)

sanitizeTitleオプションをtrueに設定しましょう。

example.js
lightbox.option({
    'sanitizeTitle': true
})

方法2. 二重にエスケープする

example.php
$user_devil_text = "<script>alert('xss');</script>";
print htmlspecialchars( htmlspecialchars($user_devil_text, ENT_QUOTES) , ENT_QUOTES);

理由

lightbox.js 本体を見てみると、sanitizeTitleオプションを設定しないとhtmlとして出力されてしまうようです。

image.png
※ 上の画像は、GitHub でのソースコードのスクリーンショットにマーカーしたものです

公式サイトのオプション一覧には載ってませんが、実はライブラリを見ると、コメントアウトされた注意書きがあります。

If the caption data is trusted, for example you are hardcoding it in, then leave this to false.
This will free you to add html tags, such as links, in the caption.

If the caption data is user submitted or from some other untrusted source, then set this to true to prevent xss and other injection attacks.

だいたいこんなことが書いてあります:
・キャプションを信頼できるものであれば false のままにしておいてください。html タグを自由に使えます。
・ユーザーや他の信頼できないソースから送信されたものである場合は、true に設定してください。

おわり

意外と気付かず、そのまま使ってしまいがちだと思うので、お気を付けください。
なに? jQuery なんて古いって、、?

参考資料

この記事を書くにあたって、参考にした資料です。(順不同)

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3