Apache httpd 2.4 + Brotli(mod_brotli)インストールメモ

Linux
Linux
スポンサーリンク

Brotli は、Google が開発した新しい圧縮アルゴリズムです。Apache httpd など、インターネット通信で広く使われている圧縮形式 Deflateと処理速度は同じですが、圧縮率は約20%も向上しています。そこで今回は、CentOS7.3 (1611) に Apache httpd 2.4.27 と Brotli(mod_brotli)をインストールする手順をまとめてみました。

かなり前置きが長くなりました(^^;) とにかく Brotli のインストール方法を知りたい! という方にはお手数ですが、 前置きをスキップ をクリックしてください。

Brotli について

Brotli は HTTPS が必須!

各種ブラウザで Brotli 圧縮を使うには、HTTPS通信が必要ですので、WEBサーバーには SSL/TLS の設定が必須です。最近の傾向として HTTP/2(これも元々はGoogleが開発した新しい通信プロトコルです) のような新しい仕組みを使うには HTTPS が必須となる傾向がありますね。

Brotli の読み方は?

ブロトリー?、ブロットリ??、 まだ新しい圧縮アルゴリズムだけあって、日本での「Brotli」の読み方は決まっていないようですが、Googleの開発者ブログでこんな一節を見かけました。ちなみに Brötli は「ブレトリ」と読みます。

Zopfli と同様、新しいアルゴリズムにはスイスのパンにちなんだ名前が付けられています。Brötli とは、スイスのドイツ語で「小さいパン」を意味します。

インターネット用の新しい圧縮アルゴリズム、Brotli のご紹介 | Google Developers Japan より引用

ブラウザの Brotli 対応状況

2017年8月1日時点では、Firefox、Chrom、Edge など主要なブラウザが Brotli 圧縮に対応しています。Safari については次期OSの macOS10.13(High Sierra)モバイルでは iOS11で Brotli に対応予定です。(http://caniuse.com/#search=Brotliより引用)

ブラウザの Brotli 対応状況

「BREACH」攻撃ってなんだ?

Apache の mod_brotli ドキュメントには「BREACH」攻撃への注意喚起が書かれています。

BREACH攻撃への注意喚起

あまり聞きなれない攻撃ですが、BREACH攻撃は、圧縮前のデータサイズと圧縮後のデータサイズをなんども比較することによって暗号化されたデータを解読する攻撃手法です。これは、Brotli 圧縮の利用に限ったことではなく、Deflateで圧縮されたデータをHTTPSで送信する場合にもこの BREACH攻撃は可能になります。

とはいえ、BREACH攻撃を実行するには攻撃対象とするユーザーのブラウザ上で任意のJavaScriptのコードを実行できる必要がありますので、なかなか難易度は高いと言えます。

また、攻撃対象はレスポンスボディに限られるため、WEBアプリケーションで、「パスワードなど重要な情報はWEBページに表示しない」「CSRF対策用などのトークンはランダムな値を使う」といった一般的なセキュリティ対策を行なっていれば、BREACH攻撃の実行をほぼ不可能にできます。

開発ツールのインストール

前置きが長くなりましたが、ここから Apache httpd 2.4.27 と Brotli(mod_brotli)のインストール手順です。サーバーOSは CentOS7.3 (1611) です。

Apache httpd や各種ライブラリをソースからコンパイルしますので、CentOS7.3 (1611) を「最小限のインストール」でインストールしている場合は、基本コマンドと開発ツールをインストールしておきましょう。

yum -y groupinstall base
yum -y groupinstall development

OpenSSL 1.1.0 のインストール

まずはじめに OpenSSLのコンパイルに必要なパッケージをインストールしておきます。

yum -y install zlib-devel
yum -y install perl-core

OpenSSLのインストール

cd /usr/local/src/
wget https://www.openssl.org/source/openssl-1.1.0f.tar.gz
tar xvzf openssl-1.1.0f.tar.gz
cd openssl-1.1.0f/
./config --prefix=/usr/local/openssl-1.1.0f shared zlib
make depend
make
make test
make install

OpenSSL1.1.0 のライブラリにパスを通しておきます。

echo /usr/local/openssl-1.1.0f/lib > /etc/ld.so.conf.d/openssl110f.conf
ldconfig

Brotli のインストール

Brotli のコンパイルに cmake を使いますので、インストールしておきます。

yum -y install cmake

Google の GitHub リポジトリから Brotli をダウンロードします。

cd /usr/local/src/
git clone https://github.com/google/brotli.git

Brotli をコンパイルしてインストールします。

cd brotli/
mkdir out && cd out
../configure-cmake
make
make test
make install

Brotli のライブラリが /usr/local/lib 以下にインストールされますので、こちらもライブラリのパスに追加しておきます。

echo /usr/local/lib > /etc/ld.so.conf.d/usr-local-lib.conf
ldconfig

Apache httpd インストールの下準備

Apache httpd のコンパイルに必要なパッケージをインストールしておきます。

yum -y install pcre-devel
yum -y install expat-devel

また、Apache 2.4系をソースコードからインストールする場合は、APR と APR-util が必要になりますので、インストールしておきます。

APR

cd /usr/local/src/
wget http://ftp.jaist.ac.jp/pub/apache//apr/apr-1.6.2.tar.gz
tar xvzf apr-1.6.2.tar.gz
cd apr-1.6.2/
./configure
make
make install

APR-util

cd /usr/local/src/
wget http://ftp.jaist.ac.jp/pub/apache//apr/apr-util-1.6.0.tar.gz
tar xvzf apr-util-1.6.0.tar.gz
cd apr-util-1.6.0/
./configure --with-apr=/usr/local/apr
make
make install

Apache httpd 2.4.27 と mod_brotli のインストール

Apache httpd は、バージョン 2.4.26 から Brotli に対応しています。ここのところ httpd 2.4 は、頻繁にバグフィックスや脆弱性対応がされています。インストールの前に最新バージョンを確認しておきましょう。

Apache httpd のソースコードのダウンロード

cd /usr/local/src/
wget http://ftp.riken.jp/net/apache//httpd/httpd-2.4.27.tar.gz

ダウンロードしたソースコードを解凍して、ディレクトリを移動します。

tar xvzf httpd-2.4.27.tar.gz
cd httpd-2.4.27/

--enable-brotli オプションで Brotli を有効にして、--with-brotli で Brotli のライブラリがインストールされているパスを指定ます。また、冒頭にも書きましたが Brotli は HTTPS 通信が必須のため --enable-ssl で SSL/TLS も有効にします。

./configure \
--enable-brotli \
--with-brotli=/usr/local/lib \
--enable-ssl \
--with-ssl=/usr/local/openssl-1.1.0f \
--enable-so \
--enable-mods-shared=all \
--enable-mpms-shared=all
 
make
make install

以上で Apache と mod_brotli が /usr/local/apache2/ 以下にインストールされました。続いてSSL/TLSサーバー証明書の作成と、Apacheの設定を行います。

自己署名のSSL/TLSサーバー証明書の作成(HTTPS用)

正規の認証局が発行したサーバー証明書を、無料で取得することもできます。よければご参照ください → Let's Encrypt サーバー証明書の取得と自動更新設定メモ

Brotli は事実上 HTTPS が必須になりますので、Apacheの設定の前に、SSLサーバー証明書を作成しておきます。

秘密鍵の作成

openssl genrsa 2048 > server.key

CSR(証明書署名要求)の作成(入力するのは2箇所だけです)

openssl req -new -key server.key > server.csr
 
Country Name (2 letter code) [XX]:JP
State or Province Name (full name) []:<空エンター>
Locality Name (eg, city) [Default City]:<空エンター>
Organization Name (eg, company) [Default Company Ltd]:<空エンター>
Organizational Unit Name (eg, section) []:<空エンター>
Common Name (eg, your name or your server's hostname) []:www.example.com
Email Address []:<空エンター>
 
Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:<空エンター>
An optional company name []:<空エンター>

SSLサーバー証明書の作成(有効期限10年)

openssl x509 -days 3650 -req -signkey server.key < server.csr > server.crt

秘密鍵とSSL証明書を移動

mv -i server.key /etc/pki/tls/private/
mv -i server.crt /etc/pki/tls/certs/

パーミッションを変更

chmod 600 /etc/pki/tls/private/server.key
chmod 600 /etc/pki/tls/certs/server.crt

CSRを削除

rm server.csr

Apache httpd の設定

オリジナルの設定ファイルをバックアップ

mv -i /usr/local/apache2/conf/httpd.conf /usr/local/apache2/conf/httpd.conf.org
mv -i /usr/local/apache2/conf/extra/httpd-ssl.conf /usr/local/apache2/conf/extra/httpd-ssl.conf.org

・設定ファイルを作成します
vim /usr/local/apache2/conf/httpd.conf

vim /usr/local/apache2/conf/extra/httpd-ssl.conf

httpd-ssl.conf の 27行目あたりからが Brotli の設定です。

SetOutputFilter BROTLI_COMPRESS
 Brotli 圧縮を有効にします。

SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png)$ no-brotli
 圧縮の効果があまりない画像ファイル(gif/jpeg/png)の Brotli 圧縮を無効にします。

BrotliCompressionQuality 5
 圧縮品質の設定です。ここで指定する値が大きいほど圧縮率は高くなりますが、圧縮処理は遅くなります。初期値は「5」で 0 から 11 の値が指定できます。
 
BrotliCompressionWindow 18
 圧縮ウィンドウサイズの設定です。ここで指定する値が大きいほど圧縮率は高くなりますが、多くのメモリが必要になります。初期値は「18」で 10 から 24 の値が指定できます。
 
BrotliFilterNote Input instream
BrotliFilterNote Output outstream
BrotliFilterNote Ratio ratio
LogFormat '"%r" %{outstream}n/%{instream}n (%{ratio}n%%)' brotli
CustomLog "logs/brotli_log" brotli

 上記は Brotli の圧縮率をログに出力するための設定です。圧縮品質やウィンドウサイズを調整するときに役に立ちそうですね。

(公式マニュアル)mod_brotli - Apache HTTP Server Version 2.5

systemd サービスファイルの作成

Apache httpd 用の systemd サービスファイル(起動スクリプトのようなもの)を作成します。

vim /etc/systemd/system/httpd.service

[Unit]
Description=The Apache HTTP Server
After=network.target remote-fs.target nss-lookup.target
 
[Service]
Type=forking
ExecStart=/usr/local/apache2/bin/apachectl start
ExecReload=/usr/local/apache2/bin/apachectl graceful
ExecStop=/usr/local/apache2/bin/apachectl stop
 
[Install]
WantedBy=multi-user.target

作成したサービスファイルを systemd に反映

systemctl daemon-reload

systemd に反映されているか確認

systemctl list-unit-files | grep httpd
httpd.service disabled ←この表示があればOK

起動

systemctl start httpd

自動起動設定

systemctl enable httpd

firewalld設定

HTTP(80/tcp) と HTTPS(443/tcp) を開けておきます。

firewall-cmd --add-port=80/tcp --permanent
firewall-cmd --add-port=443/tcp --permanent
firewall-cmd --reload

・確認
firewall-cmd --list-all

public (default, active)
interfaces: enp0s3 enp0s8
sources:
services: dhcpv6-client ssh
ports: 443/tcp 80/tcp ←この表示があればOK
(略)

ログのローテーション設定

・設定ファイルを作成します
vim /etc/logrotate.d/httpd

/usr/local/apache2/logs/*log { 
    daily 
    missingok 
    dateext 
    rotate 60 
    create 644 daemon daemon
    sharedscripts 
    postrotate 
        /bin/systemctl reload httpd.service > /dev/null 2>/dev/null || true
    endscript 
}

・確認します
logrotate -dv /etc/logrotate.d/httpd
-----(下記のような表示であればOKです)-----

reading config file /etc/logrotate.d/httpd
 
Handling 1 logs
 
rotating pattern: /usr/local/apache2/logs/*log after 1 days (60 rotations)
empty log files are rotated, old logs are removed
(略)

設定は以上です。お疲れ様でした!!

Brotli 圧縮の動作確認

Googel Chrome(バージョン50からデフォルトで有効)など Brotli 圧縮に対応したブラウザで HTTPS接続すると、圧縮方式(レスポンスヘッダのコンテンツエンコード)が Brotli を示す「br」であることが確認できると思います。

ブラウザでレスポンスヘッダのコンテンツエンコードを確認

おわりに

2014年のGoogleのHTTPSランキングシグナル導入、HTTP/2通信プロトコルの事実上HTTPS接続の必須、ChromeやFirefoxの通信が暗号化されないHTTP接続への警告、そしてこの Brotli の HTTPS接続の必須など、もはやWEBサーバーのSSL/TLSの設定は当たり前になりつつありますね。

この記事をシェアする
あぱーブログをフォローする
スポンサーリンク
スポンサーリンク

コメント

',b.captions&&s){var u=J("figcaption");u.id="baguetteBox-figcaption-"+t,u.innerHTML=s,l.appendChild(u)}e.appendChild(l);var c=J("img");c.onload=function(){var e=document.querySelector("#baguette-img-"+t+" .baguetteBox-spinner");l.removeChild(e),!b.async&&n&&n()},c.setAttribute("src",r),c.alt=a&&a.alt||"",b.titleTag&&s&&(c.title=s),l.appendChild(c),b.async&&n&&n()}}function X(){return M(o+1)}function D(){return M(o-1)}function M(e,t){return!n&&0<=e&&e=k.length?(b.animation&&O("right"),!1):(q(o=e,function(){z(o),V(o)}),R(),b.onChange&&b.onChange(o,k.length),!0)}function O(e){l.className="bounce-from-"+e,setTimeout(function(){l.className=""},400)}function R(){var e=100*-o+"%";"fadeIn"===b.animation?(l.style.opacity=0,setTimeout(function(){m.transforms?l.style.transform=l.style.webkitTransform="translate3d("+e+",0,0)":l.style.left=e,l.style.opacity=1},400)):m.transforms?l.style.transform=l.style.webkitTransform="translate3d("+e+",0,0)":l.style.left=e}function z(e){e-o>=b.preload||q(e+1,function(){z(e+1)})}function V(e){o-e>=b.preload||q(e-1,function(){V(e-1)})}function U(e,t,n,o){e.addEventListener?e.addEventListener(t,n,o):e.attachEvent("on"+t,function(e){(e=e||window.event).target=e.target||e.srcElement,n(e)})}function W(e,t,n,o){e.removeEventListener?e.removeEventListener(t,n,o):e.detachEvent("on"+t,n)}function G(e){return document.getElementById(e)}function J(e){return document.createElement(e)}return[].forEach||(Array.prototype.forEach=function(e,t){for(var n=0;n","http://www.w3.org/2000/svg"===(e.firstChild&&e.firstChild.namespaceURI)}(),m.passiveEvents=function i(){var e=!1;try{var t=Object.defineProperty({},"passive",{get:function(){e=!0}});window.addEventListener("test",null,t)}catch(n){}return e}(),function a(){if(r=G("baguetteBox-overlay"))return l=G("baguetteBox-slider"),u=G("previous-button"),c=G("next-button"),void(d=G("close-button"));(r=J("div")).setAttribute("role","dialog"),r.id="baguetteBox-overlay",document.getElementsByTagName("body")[0].appendChild(r),(l=J("div")).id="baguetteBox-slider",r.appendChild(l),(u=J("button")).setAttribute("type","button"),u.id="previous-button",u.setAttribute("aria-label","Previous"),u.innerHTML=m.svg?f:"<",r.appendChild(u),(c=J("button")).setAttribute("type","button"),c.id="next-button",c.setAttribute("aria-label","Next"),c.innerHTML=m.svg?g:">",r.appendChild(c),(d=J("button")).setAttribute("type","button"),d.id="close-button",d.setAttribute("aria-label","Close"),d.innerHTML=m.svg?p:"×",r.appendChild(d),u.className=c.className=d.className="baguetteBox-button",function n(){var e=m.passiveEvents?{passive:!1}:null,t=m.passiveEvents?{passive:!0}:null;U(r,"click",x),U(u,"click",E),U(c,"click",C),U(d,"click",B),U(l,"contextmenu",A),U(r,"touchstart",T,t),U(r,"touchmove",N,e),U(r,"touchend",L),U(document,"focus",P,!0)}()}(),S(e),function s(e,a){var t=document.querySelectorAll(e),n={galleries:[],nodeList:t};return w[e]=n,[].forEach.call(t,function(e){a&&a.filter&&(y=a.filter);var t=[];if(t="A"===e.tagName?[e]:e.getElementsByTagName("a"),0!==(t=[].filter.call(t,function(e){if(-1===e.className.indexOf(a&&a.ignoreClass))return y.test(e.href)})).length){var i=[];[].forEach.call(t,function(e,t){var n=function(e){e.preventDefault?e.preventDefault():e.returnValue=!1,H(i,a),I(t)},o={eventHandler:n,imageElement:e};U(e,"click",n),i.push(o)}),n.galleries.push(i)}}),n.galleries}(e,t)},show:M,showNext:X,showPrevious:D,hide:j,destroy:function e(){!function n(){var e=m.passiveEvents?{passive:!1}:null,t=m.passiveEvents?{passive:!0}:null;W(r,"click",x),W(u,"click",E),W(c,"click",C),W(d,"click",B),W(l,"contextmenu",A),W(r,"touchstart",T,t),W(r,"touchmove",N,e),W(r,"touchend",L),W(document,"focus",P,!0)}(),function t(){for(var e in w)w.hasOwnProperty(e)&&S(e)}(),W(document,"keydown",F),document.getElementsByTagName("body")[0].removeChild(document.getElementById("baguetteBox-overlay")),w={},h=[],o=0}}})
タイトルとURLをコピーしました