memo: Debian8(jessie)でLetsEncrypt（ドメインの契約から）

***syakesaba.com***
Let'sEncrypt試したメモ。およそ2時間。

#ドメイン入手
お名前.comでドメインを買う。DNSサービスも使う。設定は以下

```
$ORIGIN syakesaba.com.
$TTL 86400
syakesaba.com. 86400 IN SOA 01.dnsv.jp. hostmaster.dnsv.jp. 1486869463 3600 900 604800 300
syakesaba.com. 86400 IN NS 01.dnsv.jp.
syakesaba.com. 86400 IN NS 02.dnsv.jp.
syakesaba.com. 86400 IN NS 03.dnsv.jp.
syakesaba.com. 86400 IN NS 04.dnsv.jp.
syakesaba.com. 3600 IN A 153.120.17.24
mail.syakesaba.com. 3600 IN A 153.120.17.24
www.syakesaba.com. 3600 IN A 153.120.17.24
syakesaba.com. 3600 IN MX 10 mail.syakesaba.com.
syakesaba.com. 3600 IN TXT "v=spf1 +ip4:153.120.17.24 ~all"
```
初年 1,123円 次年度から年度ごとにどんどん増額されるだろう

# サーバ入手
さくらのVPSで固定IP: 153.120.17.24をGET。
スペックはdebian8 jessie 1CORE 20GB 1GBにした。セットアップは超適当。
1ヶ月2000円以下になると思う。

ホスト名の設定は以下

```
#vi /etc/hostname
syakesaba.com

#vi /etc/hosts
127.0.0.1       localhost syakesaba.com www.syakesaba.com
153.120.17.24 syakesaba.com www.syakesaba.com
# The following lines are desirable for IPv6 capable hosts
::1     ip6-localhost ip6-loopback
fe00::0 localhost ip6-localnet ip6-loopback
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
```

# nginxの入手・設定
<https://www.nginx.com/resources/wiki/start/topics/tutorials/install/>

```
wget "http://nginx.org/keys/nginx_signing.key"
sudo apt-key add nginx_signing.key
sudo echo "
deb http://nginx.org/packages/debian/ jessie nginx
deb-src http://nginx.org/packages/debian/ jessie nginx
" >> /etc/apt/sources.list
sudo apt-get update
sudo apt-get install nginx
```

<https://www.nginx.com/resources/wiki/start/topics/examples/systemd/>

```
echo "
[Unit]
Description=The NGINX HTTP and reverse proxy server
After=syslog.target network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
PIDFile=/run/nginx.pid
ExecStartPre=/usr/sbin/nginx -t -c /etc/nginx/nginx.conf
ExecStart=/usr/sbin/nginx -c /etc/nginx/nginx.conf
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true

[Install]
WantedBy=multi-user.target
" > /lib/systemd/system/nginx.service

```

systemctlで扱えるように修正

```
systemctl unmask nginx
systemctl enable nginx
```

# nginxのdefaultのマスターConfigは以下

```
cat /etc/nginx/nginx.conf
########################
user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;
}
######################
```

## Tweekの実施
ファイルデスクリプタとか。
<http://www.mk-mode.com/octopress/2014/04/13/nginx-file-discriptor-limit/>

```
echo 'fs.file-max=200000' >> /etc/sysctl.conf

# http://qiita.com/iwai/items/1e29adbdd269380167d2
echo 'net.ipv4.ip_local_port_range=18000 65535' >> /etc/sysctl.conf
echo 'net.ipv4.tcp_tw_reuse=1' >> /etc/sysctl.conf
echo 'net.ipv4.ip_dynaddr=1' >> /etc/sysctl.conf
echo 'net.ipv4.tcp_rfc1337=1' >> /etc/sysctl.conf
echo 'net.ipv4.tcp_fin_timeout=10' >> /etc/sysctl.conf
echo 'net.ipv4.tcp_keepalive_probes=5' >> /etc/sysctl.conf
echo 'net.ipv4.tcp_slow_start_after_idle=0' >> /etc/sysctl.conf
echo 'net.ipv4.tcp_max_syn_backlog=1024' >> /etc/sysctl.conf
echo 'net.core.somaxconn=65535' >> /etc/sysctl.conf

sysctl -p
```

## Tweekの実施（nginx側）
<http://raichel.hatenablog.com/entry/2015/11/20/%E3%83%9E%E3%82%B7%E3%83%B3%E3%82%B9%E3%83%9A%E3%83%83%E3%82%AF%E5%88%A5%E3%81%AEnginx_conf%E6%8E%A8%E5%A5%A8%E8%A8%AD%E5%AE%9A(%E7%B0%A1%E6%98%93ver)>

```
vi /etc/nginx/nginx.conf
# XXX:APPEND
worker_processes auto; #XXX num of core
worker_rlimit_nofile 640; #XXX calc: con128 * worker5 = 640
worker_priority -5; #XXX MGMT
#worker_cpu_affinity 01 10; #XXX i have no core
#XXX:APPEND
events {
    multi_accept on; #XXX better as it is
    worker_connections 128; #XXX num core *128?
}
```

動くか試す

```
systemctl restart nginx
```

## More Tweek
<http://qiita.com/white_aspara25/items/bc9d9b9b2dc0a673169a>

```
chmod 755 /var/log/nginx

vi /etc/nginx/nginx.conf
#XXX:APPEND
http {
	server_tokens off;
}
```

動くか試す

```
systemctl restart nginx
```

# certbotのインストール
<https://www.digitalocean.com/community/tutorials/how-to-secure-nginx-with-let-s-encrypt-on-debian-8>

```
echo 'deb http://ftp.debian.org/debian jessie-backports main' | sudo tee /etc/apt/sources.list.d/backports.list
sudo apt-get update
sudo apt-get install certbot -t jessie-backports
```

## コンテンツフォルダの変更

```
vi /etc/nginx/conf.d/default.conf
#REPLACE
server {
        server_name localhost syakesaba.com www.syakesaba.com #XXX
        #XXX
        location / {
                root /var/www/html
        }
}
#APPEND
server {
        #XXX
        location ~ /.well-known {
                root /var/www/html
                allow all;
        }
}

mkdir -p /var/www/html
chown -R nginx:nginx /var/www/html
```

###動くか試す

```
sudo systemctl restart nginx
```

## certbotのアクティベーション
```
sudo certbot certonly -a webroot --webroot-path=/var/www/html  -d syakesaba.com -d www.syakesaba.com

#IMPORTANT NOTES:
# - Congratulations! Your certificate and chain have been saved at
#   /etc/letsencrypt/live/syakesaba.com/fullchain.pem. Your cert will
#  expire on 2017-05-13. To obtain a new or tweaked version of this
# certificate in the future, simply run certbot again. To
# non-interactively renew *all* of your certificates, run "certbot
#  renew"
# - If you like Certbot, please consider supporting our work by:
#
#   Donating to ISRG / Let's Encrypt:   https://letsencrypt.org/donate
#   Donating to EFF:                    https://eff.org/donate-le

ls -la /etc/letsencrypt/live/syakesaba.com/
#合計 8
#drwxr-xr-x 2 root root 4096  2月 12 13:17 .
#drwx------ 3 root root 4096  2月 12 13:17 ..
#lrwxrwxrwx 1 root root   37  2月 12 13:17 cert.pem -> ../../archive/syakesaba.com/cert1.pem
#lrwxrwxrwx 1 root root   38  2月 12 13:17 chain.pem -> ../../archive/syakesaba.com/chain1.pem
#lrwxrwxrwx 1 root root   42  2月 12 13:17 fullchain.pem -> ../../archive/syakesaba.com/fullchain1.pem
#lrwxrwxrwx 1 root root   40  2月 12 13:17 privkey.pem -> ../../archive/syakesaba.com/privkey1.pem
```

## SSLのDH値生成
```
openssl dhparam -out /etc/ssl/certs/dhparam.pem 2048
```

## nginxへSSLの有効化

```
vi /etc/nginx/conf.d/ssl-syakesaba.com.conf
###
ssl_certificate /etc/letsencrypt/live/syakesaba.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/syakesaba.com/privkey.pem;
###

vi /etc/nginx/conf.d/ssl.conf
###
# from https://cipherli.st/ and https://raymii.org/s/tutorials/Strong_SSL_Security_On_nginx.html

ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
ssl_ciphers "EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH";
ssl_ecdh_curve secp384r1;
ssl_session_cache shared:SSL:10m;
ssl_session_tickets off;
ssl_stapling on;
ssl_stapling_verify on;
resolver 8.8.8.8 8.8.4.4 valid=300s;
resolver_timeout 5s;
# Disable preloading HSTS for now.  You can use the commented out header line that includes
# the "preload" directive if you understand the implications.
#add_header Strict-Transport-Security "max-age=63072000; includeSubdomains; preload";
add_header Strict-Transport-Security "max-age=63072000; includeSubdomains";
add_header X-Frame-Options DENY;
add_header X-Content-Type-Options nosniff;

ssl_dhparam /etc/ssl/certs/dhparam.pem;
###

vi /etc/nginx/conf.d/default.conf
#APPEND
server {
    listen 443 ssl default_server; #XXX
    listen [::]:443 ssl default_server; #XXX
    include conf.d/ssl-syakesaba.com.conf; #XXX
    include conf.d/ssl.conf; #XXX
}
```

### 動くか試す

```
systemctl restart nginx
```

### 実際にアクセスする

```
http://www.syakesaba.com/
https://www.syakesaba.com/

# https://www.ssllabs.com/ssltest/analyze.html?d=www.syakesaba.com&latest
```

# １ヶ月に一回定期的に更新させる

```
cat /etc/cron.d/certbot
###
# /etc/cron.d/certbot: crontab entries for the certbot package
#
# Upstream recommends attempting renewal twice a day
#
# Eventually, this will be an opportunity to validate certificates
# haven't been revoked, etc.  Renewal will only occur if expiration
# is within 30 days.
SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

0 */12 * * * root test -x /usr/bin/certbot -a \! -d /run/systemd/system && perl -e 'sleep int(rand(3600))' && certbot -q renew
###

vi  /etc/cron.d/certbot
#REPLACE
0 */12 * * * root test -x /usr/bin/certbot -a \! -d /run/systemd/system && perl -e 'sleep int(rand(3600))' && certbot -q renew && perl -e 'sleep int(rand(3600))'  && /bin/systemctl restart nginx
```

# 結果
<img width="1007" alt="スクリーンショット 2017-02-12 13.40.59.png" src="https://qiita-image-store.s3.amazonaws.com/0/123740/f99b514f-b2fa-7060-a0a0-0590b2772ec9.png">

運用面は知らん