この記事で構築するメールサーバの機能 [さくらのVPS/CentOS7]

  • 送信(SMTP-OUTBOUND)
    • SMTP Submission(587/tcp)
    • SMTP over TLS(465/tcp)
    • STARTTLS
    • SMTP-AUTH
    • Virus Check
    • SPF, DKIM, DMARC, ARC
  • 受信(SMTP-INBOUND)
    • SMTP(25/tcp)
    • STARTTLS
    • Virus, Spam Check
    • SPF, DKIM, DMARC, ARC 認証
    • メールフィルタリング(Sieve)
  • 参照
    • POP over TLS(995/tcp)
    • IMAP over TLS(993/tcp)
  • Webmail
    • Roundcube(フィルタリング設定/ログインのパスワード変更/Vacation機能)
    • Rainloop
  • アカウント管理
    • phpldapadmin
    • マルチドメインにも対応可能
    • Thunderbird の Autoconfig に対応
    • メーリングリスト

・メールサーバのフロント部分に nginx-mail-proxy を使用している理由

  1. 容易にSMTP/POP/IMAP認証失敗時に入力されたパスワードを syslog に出力できる(ボットから入力されるパスワードを収集できる)
  2. TLS証明書の更新に dovecot の設定を変更しなくてよい
  3. dovecot-director や dovecot-proxy を私が使ったことがない

24. Mastodonサーバ構築 [さくらのVPS/CentOS7]

・Mastodon のインストール

Mastodon は サブディレクトリ環境では動作しないため、VirtualHostで対応する

#-- 変数に必要な値を代入
VHOST=mstdn.masdon.life
DOMAIN=masdon.life
#-- admin@masdon.life のパスワード
PASSWORD=********
IPV4=$(ip addr show eth0 | awk '/inet /{print $2}' | awk -F\/ '{print $1}' | head -1)
IPV6=$(ip addr show eth0 | awk '/inet6 /&&/global/{print $2}' | awk -F\/ '{print $1}')

#-- 正引きを追加
cat <<_EOL_>> /etc/nsd/zone/${DOMAIN}.zone
mstdn                   IN      A       ${IPV4}
mstdn                   IN      AAAA    ${IPV6}
_EOL_

#-- シリアル更新
vi /etc/nsd/zone/${ZONE}.zone

systemctl restart nsd

#-- 既存の TLS証明書に mstdn.masdon.life を追加
certbot -n certonly --webroot -w /var/www/html/http_root -d ${DOMAIN} -d ${VHOST} -m admin@${DOMAIN} --agree-tos --expand

systemctl reload postfix nginx

#-- Mastodon インストール
curl -sL https://rpm.nodesource.com/setup_10.x | bash -
yum install -y http://li.nux.ro/download/nux/dextop/el7/x86_64/nux-dextop-release-0-5.el7.nux.noarch.rpm
yum install -y ImageMagick ffmpeg rubygem-redis authd nodejs {openssl,readline,zlib,libxml2,libxslt,protobuf,ffmpeg,libidn,libicu}-devel protobuf-compiler
npm install -g yarn

su - postgres -c "createuser --createdb mastodon"

useradd mastodon
SETUP=/home/mastodon/setup.sh

cat <<_EOL_> ${SETUP}
REPO=https://github.com/sstephenson
git clone \${REPO}/rbenv.git ~/.rbenv
echo 'export PATH="~/.rbenv/bin:/usr/pgsql-11/bin:$PATH"' >> ~/.bash_profile
source ~/.bash_profile
rbenv init - >> ~/.bash_profile
source ~/.bash_profile
git clone \${REPO}/ruby-build.git ~/.rbenv/plugins/ruby-build
git clone https://github.com/tootsuite/mastodon.git live
cd live
git checkout \$(git tag|grep -v rc|tail -1)
cd ..
RV=\$(cat live/.ruby-version)
rbenv install \${RV}
rbenv global \${RV}
rbenv rehash
cd live
#-- エラーとなったのでバージョンを指定
# gem install bundler
gem install bundler 1.17.3
bundle install --deployment --without development test

yarn install --pure-lockfile
cp .env.production{.sample,}
export RAILS_ENV=production SAFETY_ASSURED=1
SKB=\$(bundle exec rake secret)
PS=\$(bundle exec rake secret)
OS=\$(bundle exec rake secret)
sed -i -e "s/_HOST=[rd].*/_HOST=localhost/" \
-e "s/=postgres$/=mastodon/" \
-e "s/^LOCAL_DOMAIN.*/LOCAL_DOMAIN=${VHOST}/" \
-e "s/^LOCAL_HTTPS.*/LOCAL_HTTPS=true/" \
-e "s/^SMTP_SERVER.*/SMTP_SERVER=${DOMAIN}/" \
-e "s/^SMTP_PORT=587/SMTP_PORT=465/" \
-e "s/^SMTP_LOGIN/SMTP_LOGIN=admin@${DOMAIN}/" \
-e "s/^SMTP_PASSWORD/SMTP_PASSWORD=${PASSWORD}/" \
-e "s/^#SMTP_AUTH_METHOD.*/SMTP_AUTH_METHOD=plain/" \
-e "s/^#SMTP_TLS=true/SMTP_TLS=true/" \
-e "s/^SMTP_FROM_ADDRESS.*/SMTP_FROM_ADDRESS=admin@${DOMAIN}/" \
-e "s/^SECRET_KEY_BASE=/SECRET_KEY_BASE=\${SKB}/" \
-e "s/^OTP_SECRET=/OTP_SECRET=\${OS}/" .env.production

export \$(bundle exec rake mastodon:webpush:generate_vapid_key)
sed -i -e "s/^VAPID_PRIVATE_KEY=/VAPID_PRIVATE_KEY=\${VAPID_PRIVATE_KEY}/" \
-e "s/^VAPID_PUBLIC_KEY=/VAPID_PUBLIC_KEY=\${VAPID_PUBLIC_KEY}/" .env.production

bundle exec rails db:setup
bundle exec rails assets:precompile
_EOL_

chmod 755 ${SETUP}
chown mastodon. ${SETUP}
su - mastodon -c "/bin/bash ${SETUP}"

chmod 770 /home/mastodon
usermod -aG mastodon nginx

cp /home/mastodon/live/dist/mastodon-*.service /etc/systemd/system/
systemctl enable mastodon-{web,sidekiq,streaming}
systemctl start mastodon-{web,sidekiq,streaming}

cat <<'_EOL_'>/etc/nginx/conf.d/${VHOST}.conf
map $http_upgrade $connection_upgrade {
  default upgrade;
  ''      close;
}

proxy_cache_path /var/cache/nginx_mastodon levels=1:2 keys_zone=CACHE:10m inactive=7d max_size=1g;

server {
  listen 80;
  listen [::]:80;
  server_name _VHOST_;
  root /home/mastodon/live/public;
  location /.well-known/acme-challenge/ { allow all; }
  location / { return 301 https://$host$request_uri; }
}

server {
  listen 443 ssl http2;
  listen [::]:443 ssl http2;
  server_name _VHOST_;

  include /etc/nginx/default.d/_DOMAIN__ssl.conf;
  access_log /var/log/nginx/_VHOST__access.log main;
  error_log  /var/log/nginx/_VHOST__error.log  error;
  server_tokens off;
  charset     utf-8;

  ssl_session_cache shared:WEB:10m;
  add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
  ssl_stapling on ;
  ssl_stapling_verify on ;

  keepalive_timeout    70;
  sendfile             on;
  client_max_body_size 80m;

  root /home/mastodon/live/public;

  gzip on;
  gzip_disable "msie6";
  gzip_vary on;
  gzip_proxied any;
  gzip_comp_level 6;
  gzip_buffers 16 8k;
  gzip_http_version 1.1;
  gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

  add_header Strict-Transport-Security "max-age=31536000";

  location / {
    try_files $uri @proxy;
  }

  location ~ ^/(emoji|packs|system/accounts/avatars|system/media_attachments/files) {
    add_header Cache-Control "public, max-age=31536000, immutable";
    add_header Strict-Transport-Security "max-age=31536000";
    try_files $uri @proxy;
  }

  location /sw.js {
    add_header Cache-Control "public, max-age=0";
    add_header Strict-Transport-Security "max-age=31536000";
    try_files $uri @proxy;
  }

  location @proxy {
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto https;
    proxy_set_header Proxy "";
    proxy_pass_header Server;

    proxy_pass http://127.0.0.1:3000;
    proxy_buffering on;
    proxy_redirect off;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection $connection_upgrade;

    proxy_cache CACHE;
    proxy_cache_valid 200 7d;
    proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
    add_header X-Cached $upstream_cache_status;
    add_header Strict-Transport-Security "max-age=31536000";

    tcp_nodelay on;
  }

  location /api/v1/streaming {
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto https;
    proxy_set_header Proxy "";

    proxy_pass http://127.0.0.1:4000;
    proxy_buffering off;
    proxy_redirect off;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection $connection_upgrade;

    tcp_nodelay on;
  }

  error_page 500 501 502 503 504 /500.html;
}
_EOL_

sed -i -e "s/_DOMAIN_/${DOMAIN}/" \
       -e "s/_VHOST_/${VHOST}/" /etc/nginx/conf.d/${VHOST}.conf

systemctl start nginx

23. DBサーバ構築 – PostgreSQL [さくらのVPS/CentOS7]

・PostgreSQLの用途

  1. Mastodon

・PostgreSQLのインストール

yum install -y https://download.postgresql.org/pub/repos/yum/11/redhat/rhel-7-x86_64/pgdg-centos11-11-2.noarch.rpm
yum install -y postgresql11-{server,contrib,devel}

export PGSETUP_INITDB_OPTIONS="--encoding=UTF-8 --no-locale"
/usr/pgsql-11/bin/postgresql-11-setup initdb

cp -p /var/lib/pgsql/11/data/pg_hba.conf{,.org}

sed -i -e 's/^local.*/local all all trust/' \
	-e "s/ident$/trust/" /var/lib/pgsql/11/data/pg_hba.conf

systemctl enable postgresql-11
systemctl start postgresql-11

VPNクライアント構築 – strongswan/xl2tpd [Raspberry Pi]

・目的

Raspberry pi 3 Model B+ に VPNクライアントをインストールし、さくらのVPSに構築したVPNサーバと接続する

#-- 必要なアプリケーションのインストール
apt-get install xl2tpd strongswan ike-scan

#-- strongswan の設定
#-- ***.***.***.*** には VPNサーバのIPアドレスを入力する
cp -p /etc/ipsec.conf{,.org}
cat <<_EOL_> /etc/ipsec.conf
config setup
include /var/lib/strongswan/ipsec.conf.inc
conn %default
    keyingtries=0
conn sakura
    keyexchange=ikev1
    authby=secret
    right=***.***.***.***
    ike=3des-sha1-modp1024!
    esp=3des-sha1!
    auto=start
    left=%any
    leftprotoport=udp/1701
    rightprotoport=udp/1701
    type=transport
_EOL_

#-- 共通パスフレーズ の設定
cat <<_EOL_>/etc/ipsec.secrets
: PSK "PreSharedKey"
_EOL_

#-- xl2tpd の設定
cat <<_EOL_>>/etc/xl2tpd/xl2tpd.conf
[lac sakura]
lns = ***.***.***.***
ppp debug = yes
pppoptfile = /etc/ppp/options.l2tpd.client
length bit = yes
autodial = yes
redial = yes
redial timeout = 10
max redials = 6
_EOL_

#-- name には VPN接続のアカウント、password はパスワードを入力する
cat <<_EOL_>/etc/ppp/options.l2tpd.client
name *****@****.***
password ********
ipcp-accept-local
ipcp-accept-remote
refuse-eap
require-pap
noccp
noauth
idle 1800
mtu 1410
mru 1410
defaultroute
usepeerdns
debug
connect-delay 5000
_EOL_

#-- strongswant と xl2tpd の起動設定
systemctl enable ipsec xl2tpd
systemctl start ipsec xl2tpd

#-- VPNサーバと接続
echo "c sakura" > /var/run/xl2tpd/l2tp-control

22. Jupyter Notebook構築 [さくらのVPS/CentOS7]

・Jupyter Notebook のインストール

#-- jupyter notebook のログインするパスワードを設定
PASSWORD=********
JPUSER=jupyter
JPHOME="/home/${JPUSER}"
JPPORT=8081

yum install -y openssl-devel readline-devel sqlite-devel

adduser ${JPUSER}
git clone https://github.com/yyuu/pyenv ${JPHOME}/.pyenv
echo 'export PYENV_ROOT="${HOME}/.pyenv"' >> ${JPHOME}/.bash_profile
echo 'export PATH="${PYENV_ROOT}/bin:${PATH}"' >> ${JPHOME}/.bash_profile
echo 'eval "$(pyenv init -)"' >> ${JPHOME}/.bash_profile
chown -R ${JPUSER}. ${JPHOME}/.pyenv

#-- python3
su -l ${JPUSER} -c "yes | pyenv install anaconda3-5.3.1"
su -l ${JPUSER} -c "pyenv global anaconda3-5.3.1"
su -l ${JPUSER} -c "pyenv rehash"
su -l ${JPUSER} -c "yes | conda create --name py3.7 python=3.7 anaconda"

cat <<_EOF_> /tmp/ana3.sh
source /home/${JPUSER}/.pyenv/versions/anaconda3-5.3.1/bin/activate py3.7
conda install jupyter ipykernel
jupyter kernelspec install-self --user
pip install chainer
_EOF_

su -l ${JPUSER} -c "/bin/bash /tmp/ana3.sh"

#-- python2
su -l ${JPUSER} -c "yes | pyenv install anaconda2-5.3.1"
su -l ${JPUSER} -c "pyenv global anaconda2-5.3.1"
su -l ${JPUSER} -c "pyenv rehash"
su -l ${JPUSER} -c "yes | conda create --name py2.7 python=2.7 anaconda"

cat <<_EOF_> /tmp/ana2.sh
source /home/${JPUSER}/.pyenv/versions/anaconda2-5.3.1/bin/activate py2.7
conda install jupyter ipykernel
jupyter kernelspec install-self --user
pip install chainer
_EOF_
su -l ${JPUSER} -c "/bin/bash /tmp/ana2.sh"

#-- 設定作成
su -l ${JPUSER} -c "jupyter notebook --generate-config"
hashedp=$(su -l ${JPUSER} -c "python -c 'from notebook.auth import passwd; print(passwd(\"${PASSWORD}\",\"sha256\"))'")

cat <<_EOF_>>  ${JPHOME}/.jupyter/jupyter_notebook_config.py
c.NotebookApp.password = '${hashedp}'
c.NotebookApp.port = ${JPPORT}
c.NotebookApp.open_browser = False
c.NotebookApp.ip = '127.0.0.1'
c.NotebookApp.notebook_dir = '${JPHOME}'
c.NotebookApp.base_url = 'https://masdon.life/notebook/'
c.NotebookApp.base_url = 'notebook/'
_EOF_

#-- 起動スクリプト作成
cat <<_EOF_> /etc/systemd/system/jupyter.service
[Unit]
Description = jupyter daemon

[Service]
ExecStart = /home/${JPUSER}/.pyenv/shims/jupyter notebook
Restart = always
Type = simple
User = ${JPUSER}

[Install]
WantedBy = multi-user.target
_EOF_

#-- 起動
systemctl enable jupyter
systemctl start jupyter

#-- nginx の設定作成
cat <<'_EOF_' > /etc/nginx/conf.d/https.d/notebook.conf
  location ^~ /notebook {
    location /notebook/ {
      proxy_pass       http://localhost:8081;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header Host $http_host;
      proxy_http_version 1.1;
      proxy_redirect off;
      proxy_buffering off;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection "upgrade";
      proxy_read_timeout 86400;
    }
  }
_EOF_

systemctl reload nginx

URLは https://masdon.life/notebook/

21. pukiwiki構築 [さくらのVPS/CentOS7]

・pukiwiki のインストール

#-- 変数に必要な値を代入
HTTPS_DOCROOT=/var/www/html/https_root

#-- pukiwiki のインストール
cd ~/work/src/
curl -L -o pukiwiki-1.5.1_utf8.zip 'https://ja.osdn.net/frs/redir.php?m=iij&f=pukiwiki%2F64807%2Fpukiwiki-1.5.1_utf8.zip'

unzip pukiwiki-1.5.1_utf8.zip
mv pukiwiki-1.5.1_utf8 ${HTTPS_DOCROOT}/pukiwiki-1.5.1_utf8
ln -s pukiwiki-1.5.1_utf8 ${HTTPS_DOCROOT}/pukiwiki
chown nginx. ${HTTPS_DOCROOT}/pukiwiki-1.5.1_utf8

#--管理者パスワードを作成して pukiwiki.ini.php の $adminpass に設定する
printf "********" | md5sum
vi ${HTTPS_DOCROOT}/pukiwiki-1.5.1_utf8/pukiwiki.ini.php

$adminpass = '{x-php-md5}*********************************';

#-- nginx の設定でメールアドレスでのbasic認証を設定
cat <<'_EOF_'> /etc/nginx/conf.d/https.d/pukiwiki.conf
  location ^~ /pukiwiki {
    location ~ /pukiwiki/.*\.php$ {
      auth_ldap "Basic Auth Location";
      auth_ldap_servers ldap1;
      fastcgi_pass 127.0.0.1:9000;
      fastcgi_index index.php;
      fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
      include fastcgi_params;
    }

    location ~ /pukiwiki/ {
      auth_ldap "Basic Auth Location";
      auth_ldap_servers ldap1;
    }
  }
_EOF_

systemctl restart nginx

20. CMS構築 – WordPress/baserCMS [さくらのVPS/CentOS7]

・WordPress のインストール

#-- 変数に必要な値を代入
HTTPS_DOCROOT=/var/www/html/https_root

#-- wordpress のインストール
cd ~/work/src/
curl -L -o wordpress.tar.gz http://wordpress.org/latest.tar.gz
tar xvzf wordpress.tar.gz
mv wordpress ${HTTPS_DOCROOT}/wordpress
chown -R nginx. ${HTTPS_DOCROOT}/wordpress

#-- wordpress database の作成
mysql -e "create database wordpress character set utf8 collate utf8_bin;"
#-- database の password は お好みで
mysql -e "GRANT ALL PRIVILEGES ON wordpress.* TO 'wpuser'@'localhost' IDENTIFIED BY 'wppassword' ;"
mysql -e "FLUSH PRIVILEGES;"

#-- wordpress の設定
cp -p ${HTTPS_DOCROOT}/wordpress/wp-config-sample.php ${HTTPS_DOCROOT}/wordpress/wp-config.php

sed -i -e 's/database_name_here/wordpress/' \
       -e 's/username_here/wpuser/' \
       -e 's/password_here/wppassword/' ${HTTPS_DOCROOT}/wordpress/wp-config.php

cat <<'_EOL_' > /etc/nginx/conf.d/https.d/wordpress.conf
  location ^~ /wordpress {
    location /wordpress/wp-content/uploads {
      location ~ \.php$ {
          deny all;
      }
    }

    location /wordpress/ {
      try_files $uri $uri/ /index.php?$args;
    }

    location ~ \.php$ {
      fastcgi_pass 127.0.0.1:9000;
      fastcgi_index index.php;
      fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
      include fastcgi_params;
    }

    location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
      expires max;
      log_not_found off;
    }
  }
_EOL_

systemctl restart nginx

Web画面からインストールを続ける。管理者アカウントの設定もある為、直ぐに実施すること
https://masdon.life/wordpress/

・baserCMSのインストール

#-- 変数に必要な値を代入
HTTPS_DOCROOT=/var/www/html/https_root

#-- baserCMS の database を作成
mysql -e "create database basercms character set utf8 collate utf8_bin;"
#-- database の password は お好みで
mysql -e "GRANT ALL PRIVILEGES ON basercms.* TO 'basercms'@'localhost' IDENTIFIED BY 'baserpass' ;"
mysql -e "FLUSH PRIVILEGES;"

#-- baserCMS のインストール
cd ~/work/git
git clone https://github.com/baserproject/basercms.git
cp -pr basercms ${HTTPS_DOCROOT}/blog
#-- ******** は admin アカウントのパスワード
${HTTPS_DOCROOT}/blog/app/Console/cake bc_manager install \
  "https://masdon.life/blog" \
  mysql \
  admin \
  ******** \
  admin@masdon.life \
  --host localhost \
  --database "basercms" \
  --port 3306 \
  --login "basercms" \
  --password "baserpass" \
  --data 'bc_sample.default'

chown -R nginx. /var/www/html/https_root/blog

#-- nginx の設定追加
cat <<'_EOL_'> /etc/nginx/conf.d/https.d/blog.conf
    location /blog/theme/ {
        alias /var/www/html/https_root/blog/app/webroot/theme/;
    }

    location =/blog/ {
        rewrite ^ /blog/index.php;
    }
    location /blog {
        if ( !-e $request_filename ) {
            rewrite ^ /blog/index.php last;
        }
    }
_EOL_

systemctl reload nginx

管理ページ: https://masdon.life/blog/admin

19. VPNサーバの構築 – strongswan/xl2tpd/freeradius [さくらのVPS/CentOS7]

・VPNサーバの用途

  1. 外部からVPNサーバを経由して自宅環境にログインする
  2. radiko で大阪のラジオ放送を聴く

・strongswan, xl2tp, freeradius のインストール

#-- 変数に必要な値を代入
IPV4=$(ip addr show eth0 | awk '/inet /{print $2}' | sed 's#/.*##')

#-- strongswan, xl2tpd, freeradius をインストール
yum install -y xl2tpd strongswan freeradius freeradius-utils freeradius-ldap radiusclient-ng

#-- VPNで使用するIPアドレスを eth0 に 追加
cat <<_EOL_>> /etc/sysconfig/network-scripts/ifcfg-eth0
IPADDR1=192.168.0.1
PREFIX1=24
_EOL_

systemctl restart network

#-- strongwan の設定
cat <<_EOL_>> /etc/strongswan/ipsec.conf
conn %default
    auto=add
    keyexchange=ikev1
    ikelifetime=60m
    keylife=20m
    rekeymargin=3m
    authby=secret
    rekey=no
    keyingtries=3
    type=transport
    keyexchange=ikev1
    left=%defaultroute
    leftprotoport=udp/1701
    right=%any
    rightprotoport=udp/%any

conn L2TP
    left=${IPV4}
    # for Android 6
    ike=aes256-sha1-modp1024,3des-sha1-modp1024!
    esp=aes256-sha1,3des-sha1!
_EOL_

#-- 共通シークレットはお好みで
cat <<_EOL_>> /etc/strongswan/ipsec.secrets
: PSK "PreSharedKey"
_EOL_

cat <<_EOL_> /etc/strongswan/strongswan.conf
# strongswan.conf - strongSwan configuration file
#
# Refer to the strongswan.conf(5) manpage for details
#
# Configuration changes should be made in the included files

charon {
    load_modular = yes
    plugins {
        include strongswan.d/charon/*.conf
    }
    dns1=127.0.0.1
    dns2=8.8.8.8
}

include strongswan.d/*.conf
_EOL_

#-- strongswan の起動
systemctl enable strongswan
systemctl start strongswan

#-- radius の設定 (LDAP認証)
sed -i -e "s/base_dn = 'dc=example,dc=org'/base_dn = ''/" \
 -e 's/filter = "(uid=.*/filter = "(mailRoutingAddress=%{%{Stripped-User-Name}:-%{User-Name}})"/' /etc/raddb/mods-available/ldap

ln -s ../mods-available/ldap /etc/raddb/mods-enabled/ldap

sed -i -e 's/-ldap/-ldap\n\tif ((ok || updated) \&\& User-Password) { update control { Auth-Type := ldap } }/' \
  -e 's/.*Auth-Type LDAP {/\tAuth-Type LDAP {\n\t\tldap\n\t}\n#\tAuth-Type LDAP {/' /etc/raddb/sites-available/default

cat <<_EOL_ >> /etc/raddb/dictionary
VALUE Auth-Type LDAP 5
_EOL_

#-- radiusd の起動
systemctl enable radiusd
systemctl start radiusd

#-- radiusclient の設定
ln -s radiusclient-ng /etc/radiusclient

sed -i -e 's/auth_order\tradius,local/auth_order\tradius/' -e 's/bindaddr.*/#bindaddr */' /etc/radiusclient-ng/radiusclient.conf

#-- testing123 は使ってないので何でもいいはず
cat <<_EOL_>> /etc/radiusclient-ng/servers
localhost testing123
_EOL_

#-- xl2tpd の設定 (192.168.0.101 から 192.168.0.200 をクライアントに割り当てる)
cat <<_EOL_>/etc/xl2tpd/xl2tpd.conf
[global]
listen-addr = ${IPV4}

[lns default]
ip range = 192.168.0.101-192.168.0.200
local ip = 192.168.0.1
require authentication = yes
name = LinuxVPNserver
pppoptfile = /etc/ppp/options.xl2tpd
length bit = yes
_EOL_

cat <<_EOL_>/etc/ppp/options.xl2tpd
ipcp-accept-local
ipcp-accept-remote
ms-dns  127.0.0.1
ms-dns  8.8.8.8
noccp
auth
idle 1800
mtu 1410
mru 1410
nodefaultroute
proxyarp
connect-delay 5000
require-pap
refuse-chap
refuse-mschap
refuse-mschap-v2
logfile /var/log/xl2tpd.log
plugin radius.so
plugin radattr.so
_EOL_

#-- xl2tpd の起動
systemctl enable xl2tpd
systemctl start xl2tpd

#-- firewall の解放
firewall-cmd --permanent --add-port={4500,500,1701}/udp
firewall-cmd --permanent --add-masquerade
firewall-cmd --reload

#-- kernel パラメーター設定変更
cat <<_EOL_>> /etc/sysctl.conf
# for vpn
net.ipv4.ip_forward = 1
_EOL_

sysctl -p

・クライアントの設定

サーバアドレス: 該当サーバのIPv4アドレス
アカウント名: メールアドレス
パスワード: メールアドレスのパスワード
共有シークレット: PreSharedKey

macOS と Android と IOS での接続確認済み

18. オンラインストレージサーバ構築 – Nextcloud [さくらのVPS/CentOS7]

・Nextcloud のインストール

#-- 変数に必要な値を代入
HTTPS_DOCROOT=/var/www/html/https_root

#-- 必要な phpパッケージをインストール
yum install -y php73-php-{zip,mcrypt,smbclient,imap,gmp,apcu,redis,memcached}
systemctl restart php73-php-fpm

#-- nextcloud のインストール
cd ~/work/git
git clone https://github.com/nextcloud/server.git nextcloud
cd nextcloud
VERSION=$(git tag | egrep -iv "rc|beta" | sed 's/^v//' | sort -n | tail -1)
git checkout v${VERSION}
git submodule update --init
cp -pr ~/work/git/nextcloud ${HTTPS_DOCROOT}/nextcloud
chown -R nginx. ${HTTPS_DOCROOT}/nextcloud/

#-- nextcloud の database を作成
mysql -e "create database nextcloud character set utf8 collate utf8_bin;"
#-- database の password は お好みで
mysql -e "GRANT ALL PRIVILEGES ON nextcloud.* TO 'ncuser'@'localhost' IDENTIFIED BY 'ncpassword' ;"
mysql -e "FLUSH PRIVILEGES;"

#-- nextcloud 用 nginx の設定作成
cat <<'_EOL_' > /etc/nginx/conf.d/https.d/nextcloud.conf
  # for nextcloud
  add_header X-Content-Type-Options nosniff;
  add_header X-XSS-Protection "1; mode=block";
  add_header X-Robots-Tag none;
  add_header X-Download-Options noopen;
  add_header X-Permitted-Cross-Domain-Policies none;
  add_header Referrer-Policy no-referrer;
  fastcgi_hide_header X-Powered-By;

  location = /robots.txt {
    allow all;
    log_not_found off;
    access_log off;
  }

  location ^~ /nextcloud {

    # set max upload size
    client_max_body_size 512M;
    fastcgi_buffers 64 4K;

    # Enable gzip but do not remove ETag headers
    gzip on;
    gzip_vary on;
    gzip_comp_level 4;
    gzip_min_length 256;
    gzip_proxied expired no-cache no-store private no_last_modified no_etag auth;
    gzip_types application/atom+xml application/javascript application/json application/ld+json application/manifest+json application/rss+xml application/vnd.geo+json application/vnd.ms-fontobject application/x-font-ttf application/x-web-app-manifest+json application/xhtml+xml application/xml font/opentype image/bmp image/svg+xml image/x-icon text/cache-manifest text/css text/plain text/vcard text/vnd.rim.location.xloc text/vtt text/x-component text/x-cross-domain-policy;

    # Uncomment if your server is build with the ngx_pagespeed module
    # This module is currently not supported.
    #pagespeed off;

    location /nextcloud {
      rewrite ^ /nextcloud/index.php$request_uri;
    }

    location ~ ^/nextcloud/(?:build|tests|config|lib|3rdparty|templates|data)/ {
      deny all;
    }
    location ~ ^/nextcloud/(?:\.|autotest|occ|issue|indie|db_|console) {
      deny all;
    }

    location ~ ^/nextcloud/(?:index|remote|public|cron|core/ajax/update|status|ocs/v[12]|updater/.+|ocs-provider/.+)\.php(?:$|/) {
      fastcgi_split_path_info ^(.+?\.php)(/.*)$;
      include fastcgi_params;
      fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
      fastcgi_param PATH_INFO $fastcgi_path_info;
      fastcgi_param HTTPS on;
      #Avoid sending the security headers twice
      fastcgi_param modHeadersAvailable true;
      fastcgi_param front_controller_active true;
      fastcgi_pass 127.0.0.1:9000;
      fastcgi_intercept_errors on;
      fastcgi_request_buffering off;
    }

    location ~ ^/nextcloud/(?:updater|ocs-provider)(?:$|/) {
      try_files $uri/ =404;
      index index.php;
    }

    # Adding the cache control header for js and css files
    # Make sure it is BELOW the PHP block
    location ~ \.(?:css|js|woff2?|svg|gif)$ {
      try_files $uri /nextcloud/index.php$request_uri;
      add_header Cache-Control "public, max-age=15778463";
      # Add headers to serve security related headers  (It is intended
      # to have those duplicated to the ones above)
      # Before enabling Strict-Transport-Security headers please read
      # into this topic first.
      # add_header Strict-Transport-Security "max-age=15768000;
      # includeSubDomains; preload;";
      add_header X-Content-Type-Options nosniff;
      add_header X-XSS-Protection "1; mode=block";
      add_header X-Robots-Tag none;
      add_header X-Download-Options noopen;
      add_header X-Permitted-Cross-Domain-Policies none;
      add_header Referrer-Policy no-referrer;

      # Optional: Don't log access to assets
      access_log off;
    }

    location ~ \.(?:png|html|ttf|ico|jpg|jpeg)$ {
      try_files $uri /nextcloud/index.php$request_uri;
      # Optional: Don't log access to other assets
      access_log off;
    }
  }
_EOL_

systemctl restart nginx

管理者アカウントをWeb画面から作成できるので直ぐに作成すること
https://masdon.life/nextcloud/
mysql を使用する場合は、ストレージとデータベースをクリックして必要な項目を入力する

・ Redis を使用する設定を追加

vi /var/www/html/https_root/nextcloud/config
-- 追加する設定 ここから
  'memcache.local' => '\OC\Memcache\Redis',
  'memcache.locking' => '\OC\Memcache\Redis',
  'redis' => array(
     'host' => 'localhost',
     'port' => 6379,
      )
-- ここまで

17. チャットサーバ構築 – mattermost [さくらのVPS/CentOS7]

・mattermostのインストール

#-- 変数に必要な値を代入
DOMAIN=masdon.life
#-- admin@masdon.life のパスワード
PASSWORD=********
VERSION=5.6.2
HTTPS_DOCROOT=/var/www/html/https_root

#-- mattermost のダウンロードとインストール
cd ~/work/src
curl -O https://releases.mattermost.com/${VERSION}/mattermost-team-${VERSION}-linux-amd64.tar.gz
tar xpf mattermost-team-${VERSION}-linux-amd64.tar.gz
mv mattermost /opt/
mkdir -p /opt/mattermost/data
adduser mattermost
chown -R mattermost. /opt/mattermost
chmod -R g+w /opt/mattermost

#-- mattermost database を作成 (データ投入は初回起動時に自動で行われる)
mysql -e "create database mattermost character set utf8 collate utf8_bin;"
#-- database の password は お好みで
mysql -e "GRANT ALL PRIVILEGES ON mattermost.* TO 'mmuser'@'localhost' IDENTIFIED BY 'mostest' ;"
mysql -e "FLUSH PRIVILEGES;"

#-- mattermost の設定
cp -p /opt/mattermost/config/config.json{,.org}
sed -i -e 's/dockerhost/127.0.0.1/' \
-e 's/mattermost_test/mattermost/' \
-e "s#SiteURL.*#SiteURL\": \"https://${DOMAIN}/mattermost/\",#" \
-e 's/SendEmailNotifications.*/SendEmailNotifications": true,/' \
-e 's/FeedbackName.*/FeedbackName": "Mattermost",/' \
-e "s/FeedbackEmail.*/FeedbackEmail\": \"admin@${DOMAIN}\",/" \
-e 's/EnableSMTPAuth.*/EnableSMTPAuth": true,/' \
-e "s/SMTPUsername.*/SMTPUsername\": \"admin@${DOMAIN}\",/" \
-e "s/SMTPPassword.*/SMTPPassword\": \"${PASSWORD}\",/" \
-e "s/SMTPServer.*/SMTPServer\": \"${DOMAIN}\",/" \
-e 's/SMTPPort.*/SMTPPort": "465",/' \
-e 's/RequireEmailVerification.*/RequireEmailVerification": true,/' \
-e 's/"en"/"ja"/' /opt/mattermost/config/config.json

sed -i -e '186s/ConnectionSecurity.*/ConnectionSecurity": "TLS",/' /opt/mattermost/config/config.json

sed -i -e 's#"Directory": "./data/"#"Directory": "/opt/mattermost/data/"#' \
-e 's#"Directory": "./plugins"#"Directory": "/opt/mattermost/plugins"#' \
-e 's#"ClientDirectory": "./client/plugins"#"Directory": "/opt/mattermost/client/plugins"#' /opt/mattermost/config/config.json

#-- mattermost の起動ルール
cat <<_EOF_> /etc/systemd/system/mattermost.service
[Unit]
Description=Mattermost
After=mysqld.service postfix.service

[Service]
Type=simple
WorkingDirectory=/opt/mattermost/bin
User=mattermost
ExecStart=/opt/mattermost/bin/mattermost
PIDFile=/var/spool/mattermost/pid/master.pid
LimitNOFILE=49152

[Install]
WantedBy=multi-user.target
_EOF_

#-- mattermost 起動
systemctl enable mattermost
systemctl start mattermost

#-- mattermost 用の nginx の設定追加
cp -p /etc/nginx/conf.d/https.conf{,.org}
cat <<'_EOF_'>> /etc/nginx/conf.d/https.conf

upstream backend {
  server 127.0.0.1:8065;
  keepalive 32;
}

proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=mattermost_cache:10m max_size=200m inactive=120m use_temp_path=off;
_EOF_

cat <<'_EOF_'> /etc/nginx/conf.d/https.d/mattermost.conf
  location ^~ /mattermost {
    location ~ /mattermost/api/v[0-9]+/(users/)?websocket$ {
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection "upgrade";
      client_max_body_size 50M;
      proxy_set_header Host $http_host;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-Forwarded-Proto $scheme;
      proxy_set_header X-Frame-Options SAMEORIGIN;
      proxy_buffers 256 16k;
      proxy_buffer_size 16k;
      client_body_timeout 60;
      send_timeout 300;
      lingering_timeout 5;
      proxy_connect_timeout 90;
      proxy_send_timeout 300;
      proxy_read_timeout 90s;
      proxy_pass http://backend;
    }

    location /mattermost/ {
      client_max_body_size 50M;
      proxy_set_header Connection "";
      proxy_set_header Host $http_host;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-Forwarded-Proto $scheme;
      proxy_set_header X-Frame-Options SAMEORIGIN;
      proxy_buffers 256 16k;
      proxy_buffer_size 16k;
      proxy_read_timeout 600s;
      proxy_cache mattermost_cache;
      proxy_cache_revalidate on;
      proxy_cache_min_uses 2;
      proxy_cache_use_stale timeout;
      proxy_cache_lock on;
      proxy_http_version 1.1;
      proxy_pass http://backend;
    }
  }
_EOF_

systemctl restart nginx

#-- mattermostの日本語全文検索対応
mysql mattermost -u mmuser -pmostest -e "ALTER TABLE \`Posts\` ENGINE = Mroonga;"

最初に作成するアカウントが管理者となる為、直ぐにアカウントを作成すること
https://masdon.life/mattermost/