# 今週何知った? week:11 [![hackmd-github-sync-badge](https://hackmd.io/CFlTER5rRHy37AW44sisZw/badge)](https://hackmd.io/CFlTER5rRHy37AW44sisZw) > [name=makicamel] ## コンテンツセキュリティポリシー (CSP) ### コンテンツセキュリティポリシーとは > コンテンツセキュリティポリシー (CSP) は、クロスサイトスクリプティング (XSS) やデータインジェクション攻撃などのような、特定の種類の攻撃を検知し、影響を軽減するために追加できるセキュリティレイヤーです。 > これらの攻撃はデータの窃取からサイトの改ざん、マルウェアの拡散に至るまで、様々な目的に用いられます。 > [コンテンツセキュリティポリシー (CSP) - HTTP | MDN](https://developer.mozilla.org/ja/docs/Web/HTTP/CSP) ref [ブラウザ互換性](https://developer.mozilla.org/ja/docs/Web/HTTP/CSP#browser_compatibility) ### CSP がしてくれること - XSS 攻撃の軽減 allowlist で許可したドメインのスクリプトのみ実行し、他の(インラインスクリプトや HTML 属性値のイベントハンドラも)スクリプトをすべて無視する - パケット盗聴攻撃の軽減 通信に使うプロトコルを指定することにより、すべてのコンテンツを HTTPS で取得するよう指定できる #### XSS とは - 原因 - 悪意あるユーザによる HTML や JavaScript の注入・変形 - 対策 - HTML の文法上特別な意味を持つ記号(`<` `&` `"`)をエスケープする - レスポンスの文字エンコーディングを指定する - XSS 脆弱性がある場合の影響例 - クッキーの値を盗まれ、なりすまし被害にあう - 悪意あるスクリプトを実行させられ、サイト利用者の権限で Web アプリケーションの機能を悪用される - メールや SNS などのリンクから iframe を利用した偽サイトに誘導される。フィッシングにより個人情報を盗まれる - html を注入することにより正規 Web アプリケーションの画面の書き換えを行い、個人情報を盗まれる ### CSP を有効にするには 詳しいポリシーの記述に関しては後述 - [Content-Security-Policy HTTP ヘッダー](https://developer.mozilla.org/ja/docs/Web/HTTP/Headers/Content-Security-Policy)を返す ``` Content-Security-Policy: <policy-directive>; <policy-directive> ``` - meta タグで指定する ```html <meta http-equiv="Content-Security-Policy" content="default-src 'self'; img-src https://*; child-src 'none';"> ``` ### ポリシーの記述 - [`default-src`](https://developer.mozilla.org/ja/docs/Web/HTTP/Headers/Content-Security-Policy/default-src) - 指定のないリソースに対するフォールバック - インラインスクリプトへ適用 - [`script-src`](https://developer.mozilla.org/ja/docs/Web/HTTP/Headers/Content-Security-Policy/script-src) - JavaScript の情報のソース - `<script>` 要素 - ※ インラインのスクリプト・イベントハンドラもブロックする - ※ インラインのスクリプトを許可するために nonce-source を使用できる ```html <!-- header --> Content-Security-Policy: script-src 'nonce-2726c7f26c' <!-- body --> <script nonce="2726c7f26c"> var inline = 1; </script> ``` - [`style-src`](https://developer.mozilla.org/ja/docs/Web/HTTP/Headers/Content-Security-Policy/style-src) #### ポリシーの適用例 - `default-src 'self'` - サイト自身のドメイン(サブドメインを除く)のコンテンツのみ許可する - `default-src 'self' *.trusted.com` - サイト自身のドメインに加え、信頼されたドメインとそのすべてのサブドメインのコンテンツを許可する - `default-src https://onlinebanking.jumbobank.com` - ドメインを単一オリジンに制限し、かつ https のみ許可する - `default-src 'self'; report-uri http://reportcollector.example.com/collector.cgi` - 違反内容を報告先サーバに送信する --- > [name=ken3ypa] ## CGI について調べたい ### 動機 - CGI入りのプログラムを触ることになりそう - が、なにそれよくしらない、みたいな状態 - すこーしだけ素振りして感覚を掴んでおきたい ### CGI Common Gateway Interfaceの略。 クライアント側のWebブラウザからのリクエストに応じてWebサーバが外部プログラムを呼び出し、その処理結果をHTTPを通じてクライアントにレスポンスとして返す仕組みのこと。 ### なぜ登場したか Webの最初期、ホームページは静的なコンテンツしか返せなかった。Webサーバはあらかじめ用意されたコンテンツを返すのが主機能で、単体では動的なコンテンツを返すことができなかったため。 しかしWebの発展により、動的コンテンツを扱いたい需要が高まった。そこで考案・導入されたのがCGI。CGIを導入することでWebサーバと外部プログラムが連携でき、動的なコンテンツを返せるようなった。 これにより「Webアプリケーション」の作成が可能になり、主に掲示板・アクセスカウンタ・Wikiなどで使われた ### なぜ廃れたか リクエストがあるたびWebサーバとは別の外部プログラム(プロセス)が起動・終了する仕組みであるため、アクセス数が増えると負荷が大きく、性能のボトルネックになった。 そのため、プログラムをWebサーバ内部で実行される仕組みにとってかわられた 一応、FastCGIという、プロセスを使い捨てずにメモリ上に展開しておくことでパフォーマンス上の問題をクリアした仕様もあるにはある模様。 ### やってみる WebサーバからCGIを実行する。mac に Apache が標準インストールされているので、今回はこちらを利用 Apache から CGI を実行できるようにするのが目標 #### 環境 ``` $ httpd -version Server version: Apache/2.4.51 (Unix) Server built: Nov 3 2021 03:45:38 ``` #### 登場人物 - Apache HTTP Server (httpd) - Apache SoftWare Foundation が開発したオープンソースのWebサーバ - Apache Control(apachectl) - Apacheを操作するためのコマンド - httpd.conf - Apacheの主要な設定を記載するファイル ``` $ apachectl -help Usage: /usr/sbin/httpd [-D name] [-d directory] [-f file] [-C "directive"] [-c "directive"] [-k start|restart|graceful|graceful-stop|stop] [-v] [-V] [-h] [-l] [-L] [-t] [-T] [-S] [-X] Options: -D name : define a name for use in <IfDefine name> directives -d directory : specify an alternate initial ServerRoot -f file : specify an alternate ServerConfigFile -C "directive" : process directive before reading config files -c "directive" : process directive after reading config files -e level : show startup errors of level (see LogLevel) -E file : log startup errors to file -v : show version number -V : show compile settings -h : list available command line options (this page) -l : list compiled in modules -L : list available configuration directives -t -D DUMP_VHOSTS : show parsed vhost settings -t -D DUMP_RUN_CFG : show parsed run settings -S : a synonym for -t -D DUMP_VHOSTS -D DUMP_RUN_CFG -t -D DUMP_MODULES : show all loaded modules -M : a synonym for -t -D DUMP_MODULES -t -D DUMP_INCLUDES: show all included configuration files -t : run syntax check for config files -T : start without DocumentRoot(s) check -X : debug mode (only one worker, do not detach) ``` #### 流れ 1: Apacheを起動する `$ sudo apachectl start` これでWebサーバが立ち上がり `http://localhost` にアクセスすることが可能になる。 ``` $ sudo apachectl start $ ps aux | grep httpd ken 2894 0.0 0.0 4268288 664 s012 S+ 9:21PM 0:00.00 grep --color=auto httpd _www 2871 0.0 0.0 4318916 1112 ?? S 9:21PM 0:00.00 /usr/sbin/httpd -D FOREGROUND root 2865 0.0 0.1 4318944 10544 ?? Ss 9:21PM 0:00.35 /usr/sbin/httpd -D FOREGROUND ``` また、stop / restart は下記コマンド ``` $ sudo apachectl stop $ sudo apachectl restart ``` 2: 設定ファイルを確認・書き換えてCGIを実行できるようにする - 設定ファイルが設置されてある`/etc/apache2//httpd.conf` を確認 - ドキュメントルートは下記パスに設定されている ``` # DocumentRoot: The directory out of which you will serve your # documents. By default, all requests are taken from this directory, but # symbolic links and aliases may be used to point to other locations. # DocumentRoot "/Library/WebServer/Documents" <Directory "/Library/WebServer/Documents"> ``` ``` $ ls -la /Library/WebServer/Documents total 80 drwxr-xr-x 5 root wheel 160 11 10 2019 . drwxr-xr-x 5 root wheel 160 11 10 2019 .. -rw-r--r-- 1 root wheel 3726 11 10 2019 PoweredByMacOSX.gif -rw-r--r-- 1 root wheel 31958 11 10 2019 PoweredByMacOSXLarge.gif -rw-r--r-- 1 root wheel 52 3 19 13:37 index.html.en ``` - `http://localhost/` にアクセスした場合、ここにある `index.html.en` のHTMLが返る - また、外部プログラムを格納するディレクトリは `/Library/WebServer/CGI-Executables/` となっている ``` # ScriptAlias: This controls which directories contain server scripts. # ScriptAliases are essentially the same as Aliases, except that # documents in the target directory are treated as applications and # run by the server when requested rather than as documents sent to the # client. The same rules about trailing "/" apply to ScriptAlias # directives as to Alias. # ScriptAliasMatch ^/cgi-bin/((?!(?i:webobjects)).*$) "/Library/WebServer/CGI-Executables/$1" ``` - 上記パスにCGIプログラムを設置した場合、 /cgi-bin/ファイル名 + 拡張子 にリクエストすることで、プログラムが実行される - `.cgi` 以外の拡張子のファイルを読み込ませたい場合は、`AddHandler` に拡張子を追加する ``` # # AddHandler allows you to map certain file extensions to "handlers": # actions unrelated to filetype. These can be either built into the server # or added with the Action directive (see below) # # To use CGI scripts outside of ScriptAliased directories: # (You will also need to add "ExecCGI" to the "Options" directive.) # AddHandler cgi-script .cgi .rb .pl ``` - `/CGI-Executables`配下に下記のCGIファイルを設置 ``` #!/usr/bin/perl $msg1 = "Good Morning"; $msg2 = 'Good Afternoon'; $msg3 = 'Good Evening'; ($ss, $mn, $hh, $dd, $mm, $yy) = localtime(time); $yy += 1900; $mm++; if ($hh > 2 and $hh < 12) { $msg = $msg1; } else { if ($hh > 11 and $hh < 19) { $msg = $msg2; } else { $msg = $msg3; } } print "Content-type: text/html\n\n"; print "<html>\n"; print "<p>$msg</p>\n"; print "<p>current_time:<span>$hh:$mn:$ss</span><p>\n"; print "</html>\n"; exit(0); ``` - http://localhost/cgi-bin/test.cgi にアクセスすると、現在時刻とその時間帯にあわせた文字列が返る ### 参考にしたサイト - https://httpd.apache.org/docs/2.2/en/howto/cgi.html - https://weblabo.oscasierra.net/apache-macos-usage/ - http://sak.cool.coocan.jp/w_sak3/doc/sysbrd/pe_kj04.htm