Linux で DNS-over-HTTPS を利用する

Android で DNS-over-HTTPS が簡単に出来るようになりました.

Linuxだどうなんだろうと以下の`dns-over-https` を試してみました.ここでは Debian sid amd64 で試していますが,公式の手順には Ubuntu 18.04 LTS, macOS の手順が載っています.

導入例
$ sudo apt install git golang
$ git clone https://github.com/m13253/dns-over-https.git
$ cd dns-over-https
$ make
$ sudo checkinstall
規定値のサーバは Google Public DNS になっている.変更したい場合は設定ファイル( /etc/dns-over-https/doh-client.conf )を編集
$ sudo edit /etc/dns-over-https/doh-client.conf
CleanBrowsingのセキュリティフィルターを利用する場合の設定例
diff --git a/dns-over-https/doh-client.conf b/dns-over-https/doh-client.conf
index 3b5de14..1791397 100644
--- a/dns-over-https/doh-client.conf
+++ b/dns-over-https/doh-client.conf
@@ -11,7 +11,7 @@ listen = [
 upstream_google = [

     # Google's productive resolver, good ECS, bad DNSSEC
-    "https://dns.google.com/resolve",
+    #"https://dns.google.com/resolve",

     # CloudFlare's resolver, bad ECS, good DNSSEC
     #"https://cloudflare-dns.com/dns-query",
@@ -39,6 +39,9 @@ upstream_ietf = [
     # Blog: https://blog.cloudflare.com/welcome-hidden-resolver/
     #"https://dns4torpnlfs2ifuz2s2yf3fc7rdmsbhm6rw75euj35pac6ap25zgqad.onion/dns-query",

+    # CleanBrowsing https://cleanbrowsing.org/dnsoverhttps
+    "https://doh.cleanbrowsing.org/doh/security-filter/"
+
 ]

 # Bootstrap DNS server to resolve the address of the upstream resolver
起動
$ sudo systemctl restart doh-client
名前が引けるのを確認
$ dig @127.0.0.1 | grep SERVER
;; SERVER: 127.0.0.1#53(127.0.0.1)
trace
$ dig +trace matoken.org @127.0.0.1

; <<>> DiG 9.11.4-P2-3-Debian <<>> +trace matoken.org @127.0.0.1
;; global options: +cmd
.                       24820   IN      NS      m.root-servers.net.
.                       24820   IN      NS      b.root-servers.net.
.                       24820   IN      NS      c.root-servers.net.
.                       24820   IN      NS      d.root-servers.net.
.                       24820   IN      NS      e.root-servers.net.
.                       24820   IN      NS      f.root-servers.net.
.                       24820   IN      NS      g.root-servers.net.
.                       24820   IN      NS      h.root-servers.net.
.                       24820   IN      NS      i.root-servers.net.
.                       24820   IN      NS      j.root-servers.net.
.                       24820   IN      NS      a.root-servers.net.
.                       24820   IN      NS      k.root-servers.net.
.                       24820   IN      NS      l.root-servers.net.
;; Received 239 bytes from 127.0.0.1#53(127.0.0.1) in 1334 ms

org.                    172800  IN      NS      a0.org.afilias-nst.info.
org.                    172800  IN      NS      a2.org.afilias-nst.info.
org.                    172800  IN      NS      b0.org.afilias-nst.org.
org.                    172800  IN      NS      b2.org.afilias-nst.org.
org.                    172800  IN      NS      c0.org.afilias-nst.info.
org.                    172800  IN      NS      d0.org.afilias-nst.org.
org.                    86400   IN      DS      9795 7 1 364DFAB3DAF254CAB477B5675B10766DDAA24982
org.                    86400   IN      DS      9795 7 2 3922B31B6F3A4EA92B19EB7B52120F031FD8E05FF0B03BAFCF9F891B FE7FF8E5
org.                    86400   IN      RRSIG   DS 8 1 86400 20181018050000 20181005040000 2134 . bYogBWKVV1SnjoHjS5LnLBE1mWC6UwkYT6muOjcHnuMNzJM1DY3YhSCT d9QOYlvvprUyD37xYIQ10BUZQ8hcNpnQ2TPUTNzd621lsqth6QK8zDN6 eP5AvZXlPy+9wni71rJIHy1wzepn9yrh3jp70zZhnEVxxgItWaYzsayY Jf+UfFQPmOKX0gn0GqcQ09CSZHdZhwbUT2AT1Rs0atkj6VaOy2TT1aQ1 gAtGF+5uA4uqLJegiEe/zneTeyuNE5QDQWKUNaeWEDE9kxylhv6m/3vE tQ8EHFpzOL9x+ed25LNcnRXH8K/xCW43R1FyaVNaA6xcsvGHCysqLneI v/RYMQ==
;; Received 813 bytes from 193.0.14.129#53(k.root-servers.net) in 210 ms

matoken.org.            86400   IN      NS      ns-cloud-d2.googledomains.com.
matoken.org.            86400   IN      NS      ns-cloud-d4.googledomains.com.
matoken.org.            86400   IN      NS      ns-cloud-d1.googledomains.com.
matoken.org.            86400   IN      NS      ns-cloud-d3.googledomains.com.
h9p7u7tr2u91d0v0ljs9l1gidnp90u3h.org. 86400 IN NSEC3 1 1 1 D399EAAB H9PARR669T6U8O1GSG9E1LMITK4DEM0T NS SOA RRSIG DNSKEY NSEC3PARAM
h9p7u7tr2u91d0v0ljs9l1gidnp90u3h.org. 86400 IN RRSIG NSEC3 7 2 86400 20181026101800 20181005091800 1862 org. edCrqcIYiHlMMzuacuX0DlobcQkymqClpK5C4QLzsNWtvp942bFRjbb2 WDX/6TsHO0noBNoKH2i+TU70WqpW7sVsXbjV9nkeLMZjxz/VLyAJOXWk 2ITvZwhjbe96lCSAIafm824pBx94ruieKZ2Yj8pYTBIrhDBoffjPhuem 44k=
a85qqkk8n39d1c6m55g8ucjhm6u3jjcs.org. 86400 IN NSEC3 1 1 1 D399EAAB A86TS1MQ34BR2A3D3CT8D5SCHKAPPBPJ NS DS RRSIG
a85qqkk8n39d1c6m55g8ucjhm6u3jjcs.org. 86400 IN RRSIG NSEC3 7 2 86400 20181022152743 20181001142743 1862 org. G15dhaW+53QBX9nTtsIUCnSRrMO0FCkQJE3jydb6hmRQEA328trp9OqK 6fuvl+RZBhBFeMeJV1Tz0Uezp9YvymfRWwdHiiFFLy3KBt5cTZJUXxTZ jXnMT9PoHZcIVJzN65vqQHDI2MzWYoQYr1WoKmJxOC5FQzFctZElyzEq fNQ=
;; Received 654 bytes from 199.19.56.1#53(a0.org.afilias-nst.info) in 217 ms

matoken.org.            120     IN      A       153.121.44.87
;; Received 56 bytes from 216.239.38.109#53(ns-cloud-d4.googledomains.com) in 388 ms

パケットキャプチャしてみる

  • 通常のDNS

dig 2quepghecPeuj.matoken.org
$ sudo tcpdump -n -nn -t -l -A -s0 2>/dev/null | grep 2quepghecPeuj.matoken.org
IP 192.168.2.203.49026 > 192.168.2.211.53: 49901+ [1au] A? 2quepghecPeuj.matoken.org. (66)
E..^.,..@.0t...........5.J..... .........2quepghecPeuj.matoken.org.......).........
E...z.@.@.8f.........5...w............. .2quepghecPeuj.matoken.org..............x...y,W........2....ns-cloud-d2.googledomains.com.........2....ns-cloud-d4.S........2....ns-cloud-d1.S........2....ns-cloud-d3.S.........d.... m.G.......+...."m.........D....$m.r......#P....&m............ .H`H..2.......m.G......+W.. .H`H..4.......m............ .H`H..6.......m.r......Ov.. .H`H..8.......m..)........
^C
  • DNS over HTTPS

名前は見当たらない

dig 2quepghecPeuj.matoken.org @127.0.0.1
$ sudo tcpdump -n -nn -t -l -A -s0 2>/dev/null | grep 2quepghecPeuj.matoken.org
^C

loopback 部分はHTTPSになる前の部分は見える

dig 2quepghecPeuj.matoken.org @127.0.0.1
$ sudo tcpdump -i lo -n -nn -t -l -A -s0 2>/dev/null | grep 2quepghecPeuj.matoken.org
IP 127.0.0.1.52265 > 127.0.0.1.53: 25766+ [1au] A? 2quepghecPeuj.matoken.org. (66)
E..^C...@.8..........).5.J.]d.. .........2quepghecPeuj.matoken.org.......).........
E..bD(@.@..`.........5.).N.ad............2quepghecPeuj.matoken.org..............w...y,W..)........
^C
永続化
$ sudo systemctl enable doh-client

後は /etc/network/interfaces や NetworkManager で DNS server に 127.0.0.1 を指定する.

環境
$ dpkg-query -W git golang dnsutils
dnsutils        1:9.11.4.P2+dfsg-3
git     1:2.19.0-1
golang  2:1.10~5
$ lsb_release -d
Description:    Debian GNU/Linux unstable (sid)
$ uname -m
x86_64

Dropbox を FUSE mount する dbxfs のアクセストークンを gpg で暗号化する

昨日dbxfs を試したのですが,アクセストークンのgpg での暗号化が出来ませんでした.

するとTwitterで情報をもらい,手動でDropbox app を作成してアクセストークンを入手する必要があるそうです.早速試してみたところうまく行きました!

Dropbox の App Console にアクセスして,Create app で新しいアプリを作成します.
情報を入力してアプリを生成.

44379184824 11e5e5faf4

生成したアプリで Generated access token を押してアクセストークンを生成

43285861640 b2abfddc92 m

dbxfs設定ファイルの場所確認
$ ~/.local/bin/dbxfs --print-default-config-file
/home/matoken/.config/dbxfs/config.json
生成したアクセストークンを gpg で暗号化してファイルに格納.
$ echo -n 'ItBeOfobAlbofEicHefvemsajKicsEjcekDomBaHee-shwijreijKimyatIfnebir' | gpg -r EAA13B982D937827 -e -o /home/matoken/.config/dbxfs/token.gpg
暗号化したアクセストークンファイルを設定ファイルで指定する
$ jq . /home/matoken/.config/dbxfs/config.json
{
  "access_token_command": [
	"gpg",
	"--decrypt",
	"/home/matoken/.config/dbxfs/token.gpg"
  ],
  "send_error_reports": true,
  "asked_send_error_reports": true
}
mount 時に gpg で decrypt されて mount される
$ ~/.local/bin/dbxfs ~/fuse/dbxfs
Running 'gpg --decrypt /home/matoken/.config/dbxfs/token.gpg' for access token
gpg: 4096-ビットRSA鍵, ID EAA13B982D937827, 日付2015-06-11に暗号化されました
	  "K.I.Matohara <matoken@gmail.com>"
$ mount|grep dbxfs
dbxfs on /home/matoken/fuse/dbxfs type fuse (rw,nosuid,nodev,relatime,user_id=1000,group_id=1000,default_permissions)
$ ls /home/matoken/fuse/dbxfs
   :
$ fusermount -u ~/fuse/dbxfs

うまくいきました :)

環境
$ grep ^Version: ~/.local/lib/python3.6/site-packages/dbxfs-1.0.4.dist-info/METADATA
Version: 1.0.4
$ dpkg-query -W gpg libfuse2 python3-pip
gpg     2.2.10-2
libfuse2:amd64  2.9.8-2
python3-pip     9.0.1-2.3
$ lsb_release -d
Description:    Debian GNU/Linux unstable (sid)
$ uname -m
x86_64

macOS, Linux で Dropbox を fuse mount する dbxfs を少し試す

Dropbox を FUSE mount 出来る dbxfs というものを見つけたので試してみました.

Doropbox の Linux client はファイルシステムがext4のみと制限されます.dbxfs であればおそらくこの制限も問題ないのではないかと思います.(未確認)

The Dropbox folder will need to be on an ext4-formatted hard drive or partition
Note: ecryptfs is not supported, but Dropbox will continue to sync with supported file systems that are encrypted via full disk encryption (e.g. LUKS)

導入
$ sudo apt install libfuse2 python3-pip
help
$ ~/.local/bin/dbxfs -h
usage: dbxfs [-h] [-f] [-v] [-s] [-n] [-l SMB_LISTEN_ADDRESS] [-c CONFIG_FILE]
			 [-e ENCRYPTED_FOLDERS] [--print-default-config-file]
			 [mount_point]

positional arguments:
  mount_point

optional arguments:
  -h, --help            show this help message and exit
  -f, --foreground      keep filesystem server in foreground
  -v, --verbose         show log messages, use twice for maximum verbosity
  -s, --smb             force mounting via SMB
  -n, --smb-no-mount    export filesystem via SMB but don't mount it
  -l SMB_LISTEN_ADDRESS, --smb-listen-address SMB_LISTEN_ADDRESS
						address that SMB service should listen on, append
						colon to specify port
  -c CONFIG_FILE, --config-file CONFIG_FILE
						config file path
  -e ENCRYPTED_FOLDERS, --encrypted-folder ENCRYPTED_FOLDERS
						relative paths of encrypted folders, can be used
						multiple times. requires safefs
  --print-default-config-file
						print default config file path to standard out and
						quit
初回mount
$ ~/.local/bin/dbxfs ~/fuse/dbxfs
We need an access token. Perform the following steps:
1. Go to https://www.dropbox.com/oauth2/authorize?response_type=code&client_id=vinkudorurc8kno
2. Click "Allow" (you may have to log in first)
3. Copy the authorization code.
Enter authoritization code (Ctrl-C to quit): NodigIOndefkiwitshOrackazEuweavirtyedCibEdI
We're all connected. Do you want to save your credentials for future runs? [Y/n] Y
Would you like to help us improve dbxfs by providing anonymous error reports? [Y/n] Y
Mount point "/home/matoken/fuse/dbxfs" doesn't exist, do you want to create it? [Y/n] Y
  1. のurl をブラウザで開いて認証を行う
    認証後の画面で cli-dbxfs のアクセスを許可する.

45084023501 7cfd7c4058

許可後に表示されるトークンを 3. の後ろにコピー&ペーストする.

  • We’re all connected. Do you want to save your credentials for future runs?
    次回以降のために資格情報を保存するか?
  • Would you like to help us improve dbxfs by providing anonymous error reports?
    匿名のエラー報告を行いdbxfsに改善の支援を行うか?
  • Mount point “/home/matoken/fuse/dbxfs” doesn’t exist, do you want to create it?
    マウントポイントが存在しないので作成するか?
マウント確認
$ ls ~/fuse/dbxfs/
アンマウントする
$ fusermount -u ~/fuse/dbxfs
資格情報を保存していた場合2回目以降のマウントは何も聞かれない
$ ~/.local/bin/dbxfs ~/fuse/dbxfs

.

アクセストークンをpgpファイルに格納することも出来るようだが手元の環境では未だうまく行っていない(多分何か勘違いをしている)

EDIT: やはり使い方が間違っていた.次の記事に書いた -> Dropbox を FUSE mount する dbxfs のアクセストークンを gpg で暗号化する – matoken’s meme

設定ファイルの場所確認
$ ~/.local/bin/dbxfs --print-default-config-file
/home/matoken/.config/dbxfs/config.json
アクセストークンをpgpファイルにする
$ jq . /home/matoken/.config/dbxfs/config.json
{
  "keyring_user": "yigwulbaf6shnutugaivkilj",
  "send_error_reports": true,
  "asked_send_error_reports": true
}
$ gpg -r EAA13B982D937827 -e /home/matoken/.config/dbxfs/config.json
$ ls -l /home/matoken/.config/dbxfs/config.json*
-rw-r--r-- 1 matoken matoken 115 10月  4 07:19 /home/matoken/.config/dbxfs/config.json
-rw-r--r-- 1 matoken matoken 685 10月  4 07:22 /home/matoken/.config/dbxfs/config.json.gpg
$ shred /home/matoken/.config/dbxfs/config.json
$ echo '"access_token_command": ["gpg", "--decrypt", "/home/matoken/.config/dbxfs/config.json.gpg"]' > /home/matoken/.config/dbxfs/config.json
マウント
$ ~/.local/bin/dbxfs ~/fuse/dbxfs
Running 'gpg --decrypt /home/matoken/.config/dbxfs/config.json.gpg' for access token
gpg: 4096-ビットRSA鍵, ID EAA13B982D937827, 日付2015-06-11に暗号化されました
      "K.I.Matohara <matoken@gmail.com>"
Traceback (most recent call last):
  File "/home/matoken/.local/bin/dbxfs", line 11, in <module>
    sys.exit(main())
  File "/home/matoken/.local/lib/python3.6/site-packages/dbxfs/main.py", line 212, in main
    dropbox.Dropbox(access_token).users_get_current_account()
  File "/home/matoken/.local/lib/python3.6/site-packages/dropbox/base.py", line 4245, in users_get_current_account
    None,
  File "/home/matoken/.local/lib/python3.6/site-packages/dropbox/dropbox.py", line 274, in request
    timeout=timeout)
  File "/home/matoken/.local/lib/python3.6/site-packages/dropbox/dropbox.py", line 365, in request_json_string_with_retry
    timeout=timeout)
  File "/home/matoken/.local/lib/python3.6/site-packages/dropbox/dropbox.py", line 449, in request_json_string
    timeout=timeout,
  File "/home/matoken/.local/lib/python3.6/site-packages/requests/sessions.py", line 559, in post
    return self.request('POST', url, data=data, json=json, **kwargs)
  File "/home/matoken/.local/lib/python3.6/site-packages/requests/sessions.py", line 498, in request
    prep = self.prepare_request(req)
  File "/home/matoken/.local/lib/python3.6/site-packages/requests/sessions.py", line 441, in prepare_request
    hooks=merge_hooks(request.hooks, self.hooks),
  File "/home/matoken/.local/lib/python3.6/site-packages/requests/models.py", line 310, in prepare
    self.prepare_headers(headers)
  File "/home/matoken/.local/lib/python3.6/site-packages/requests/models.py", line 444, in prepare_headers
    check_header_validity(header)
  File "/home/matoken/.local/lib/python3.6/site-packages/requests/utils.py", line 941, in check_header_validity
    raise InvalidHeader("Invalid return character or leading space in header: %s" % name)
requests.exceptions.InvalidHeader: Invalid return character or leading space in header: Authorization

持ち運びモバイルPCだと辛いでしょうが,据え置きデスクトップ環境などのオンラインのマシンでは便利そうです.

環境
$ grep ^Version: ~/.local/lib/python3.6/site-packages/dbxfs-1.0.4.dist-info/METADATA
Version: 1.0.4
$ dpkg-query -W libfuse2 python3-pip
libfuse2:amd64  2.9.8-2
python3-pip     9.0.1-2.3
$ lsb_release -d
Description:    Debian GNU/Linux unstable (sid)
$ uname -m
x86_64

Nautilus が起動しなくなって困る

Nautilus が起動しなくなりました.nemo は起動するんだけど……
$ nautilus

(nautilus:16178): Tracker-ERROR **: 19:36:23.259: Unable to find default domain ontology rule /usr/share/tracker/domain-ontologies/default.rule
Trace/breakpoint trap
このファイルはなんだろうと中を覗こうとしたら存在しない
$ lv /usr/share/tracker/domain-ontologies/default.rule
/usr/share/tracker/domain-ontologies/default.rule: No such file or directory
tracker pkg に含まれるらしい
$ apt-file search /usr/share/tracker/domain-ontologies/default.rule
tracker: /usr/share/tracker/domain-ontologies/default.rule
インデックスや検索関連
$ apt show tracker
Package: tracker
Version: 2.1.4-1
Priority: optional
Section: utils
Maintainer: Debian GNOME Maintainers <pkg-gnome-maintainers@lists.alioth.debian.org>
Installed-Size: 3,453 kB
Depends: libc6 (>= 2.4), libglib2.0-0 (>= 2.45.3), libtracker-control-2.0-0 (= 2.1.4-1), libtracker-sparql-2.0-0 (= 2.1.4-1), dconf-gsettings-backend | gsettings-backend, shared-mime-info, libglib2.0-bin, default-dbus-session-bus | dbus-session-bus
Recommends: tracker-miner-fs
Homepage: https://wiki.gnome.org/Projects/Tracker
Tag: implemented-in::c, interface::commandline, interface::daemon,
 network::client, network::server, role::program, scope::utility,
 use::organizing, use::searching, works-with::db, works-with::file,
 works-with::pim
Download-Size: 1,009 kB
APT-Manual-Installed: yes
APT-Sources: http://ftp.jp.debian.org/debian sid/main amd64 Packages
Description: メタデータデータベース、索引付けおよび検索ツール
 Tracker は、メタデータとタグに関連付けられた第一クラスオブジェクト用の
 先進的なフレームワークです。全てのメタデータ、タグ、共有オブジェクト
 データベース、検索ツールと索引に対する統一されたソリューションを提供します。

N: 追加レコードが 1 件あります。表示するには '-a' スイッチを付けてください。
導入したら起動するようになりました
$ sudo apt install tracker
環境
$ dpkg-query -W $(dpkg -l nautilus* | grep ^ii | awk {'print $2'} ) tracker nemo
nautilus        3.30.0-4
nautilus-actions        3.2.3-1+b2
nautilus-compare        0.0.4+po1-1
nautilus-data   3.30.0-4
nautilus-filename-repairer      0.2.0-1
nautilus-gtkhash        1.1.1-3.1
nautilus-hide   0.2.3-4
nautilus-image-converter        0.3.1~git20110416-2
nautilus-image-manipulator      1.3-2
nautilus-scripts-manager        2.0-1
nautilus-share  0.7.3-2
nautilus-wipe   0.3-1
nemo    3.8.5-1
tracker 2.1.4-1
$ lsb_release -d
Description:    Debian GNU/Linux unstable (sid)
$ uname -m
x86_64

ssh環境での誤ったシステム停止を防ぐmolly-guard

最近 shutdown の man を見比べたりしてたのですが,そのときに systemd, sysvinit 以外に molly-guard という見知らぬものが.

$ apt-file search /sbin/shutdown
molly-guard: /sbin/shutdown
systemd-sysv: /sbin/shutdown
sysvinit-core: /sbin/shutdown

パッケージ情報をみると shutdown コマンドなどを置き換えて ssh 接続時には確認のためにホスト名を聞くようになるようです.
これにより手元のPCの再起動をしたつもりがリモートのサーバを再起動してしまうなどといったことが防げるようになります.

$ apt show molly-guard
Package: molly-guard
Version: 0.6.4
Priority: extra
Section: admin
Maintainer: Francois Marier <francois@debian.org>
Installed-Size: 57.3 kB
Depends: procps
Enhances: init, kexec-tools, mosh, openssh-server, pm-utils, systemd, sysvinit, upstart
Tag: implemented-in::shell, interface::commandline, network::server,
 protocol::ssh, role::program, scope::utility
Download-Size: 13.8 kB
APT-Manual-Installed: yes
APT-Sources: http://ftp.jp.debian.org/debian stretch/main amd64 Packages
Description: protects machines from accidental shutdowns/reboots
 The package installs a shell script that overrides the existing
 shutdown/reboot/halt/poweroff/coldreboot/pm-hibernate/pm-suspend* commands
 and first runs a set of scripts, which all have to exit successfully,
 before molly-guard invokes the real command.
 .
 One of the scripts checks for existing SSH sessions. If any of the four
 commands are called interactively over an SSH session, the shell script
 prompts you to enter the name of the host you wish to shut down. This should
 adequately prevent you from accidental shutdowns and reboots.
 .
 molly-guard diverts the real binaries to /lib/molly-guard/.  You can bypass
 molly-guard by running those binaries directly.

早速試してみます.

$ sudo apt install molly-guard
    :
package diverts others to: /lib/molly-guard/coldreboot
/sbin/halt
package diverts others to: /lib/molly-guard/halt
/sbin/pm-hibernate
/sbin/pm-suspend
/sbin/pm-suspend-hybrid
/sbin/poweroff
package diverts others to: /lib/molly-guard/poweroff
/sbin/reboot
package diverts others to: /lib/molly-guard/reboot
/sbin/shutdown
package diverts others to: /lib/molly-guard/shutdown

このあたりのコマンドが置き換わっています.

$ ls -l /sbin | grep molly
lrwxrwxrwx 1 root root        28 Aug 16  2016 coldreboot -> /lib/molly-guard/molly-guard
lrwxrwxrwx 1 root root        28 Aug 16  2016 halt -> /lib/molly-guard/molly-guard
lrwxrwxrwx 1 root root        28 Aug 16  2016 pm-hibernate -> /lib/molly-guard/molly-guard
lrwxrwxrwx 1 root root        28 Aug 16  2016 pm-suspend -> /lib/molly-guard/molly-guard
lrwxrwxrwx 1 root root        28 Aug 16  2016 pm-suspend-hybrid -> /lib/molly-guard/molly-guard
lrwxrwxrwx 1 root root        28 Aug 16  2016 poweroff -> /lib/molly-guard/molly-guard
lrwxrwxrwx 1 root root        28 Aug 16  2016 reboot -> /lib/molly-guard/molly-guard
lrwxrwxrwx 1 root root        28 Aug 16  2016 shutdown -> /lib/molly-guard/molly-guard

コマンド類は /lib/molly-guard 以下に退避されるようです.

sysvinit
$ ls -lA /lib/molly-guard
total 48
-rwxr-xr-x 1 root root 18952 Feb 13  2017 halt
-rwxr-xr-x 1 root root  2767 Aug 16  2016 molly-guard
lrwxrwxrwx 1 root root     4 Feb 13  2017 poweroff -> halt
lrwxrwxrwx 1 root root     4 Feb 13  2017 reboot -> halt
-rwxr-xr-x 1 root root 23368 Feb 13  2017 shutdown
systemd
$ ls -lA /lib/molly-guard
total 4
lrwxrwxrwx 1 root root   14 Jun 14 05:20 halt -> /bin/systemctl
-rwxr-xr-x 1 root root 2767 Aug 16  2016 molly-guard
lrwxrwxrwx 1 root root   14 Jun 14 05:20 poweroff -> /bin/systemctl
lrwxrwxrwx 1 root root   14 Jun 14 05:20 reboot -> /bin/systemctl
lrwxrwxrwx 1 root root   14 Jun 14 05:20 shutdown -> /bin/systemctl

ssh 経由で shutdown(sysvinit) を試みるとこのように hostname を求められます.ここで誤った hostname を書くと shutdown がキャンセルされました.

$ sudo shutdown -f -P -h +10 "kernel update (`uname -r`)"
W: molly-guard: SSH session detected!
Please type in hostname of the machine to shutdown: desktop
Good thing I asked; I won't shutdown debian ...
W: aborting shutdown due to 30-query-hostname exiting with code 1.

正しい hostname を指定すると shutdown が呼ばれます.

$ sudo shutdown -f -P -h +10 "kernel update (`uname -r`)"
W: molly-guard: SSH session detected!
Please type in hostname of the machine to shutdown: debian

Broadcast message from root@debian (pts/0) (Thu Sep 27 06:15:28 2018):

kernel update (4.9.0-3-amd64)
The system is going DOWN for system halt in 10 minutes!
^C
Shutdown cancelled.

ssh経由でない場合は molly-guard はすぐに shutdown を呼びます.

$ sudo shutdown -f -P -h +10 'poweroff'
^C
Shutdown cancelled.

環境

$ dpkg-query -W systemd-sysv molly-guard
molly-guard     0.6.4
systemd-sysv    232-25+deb9u4
$ dpkg-query -W sysvinit-core
sysvinit-core   2.88dsf-59.9
$ cat /etc/os-release
PRETTY_NAME="Debian GNU/Linux 9 (stretch)"
NAME="Debian GNU/Linux"
VERSION_ID="9"
VERSION="9 (stretch)"
ID=debian
HOME_URL="https://www.debian.org/"
SUPPORT_URL="https://www.debian.org/support"
BUG_REPORT_URL="https://bugs.debian.org/"
$ cat /etc/debian_version
9.5
$ uname -m
x86_64

qcow2 イメージをマウント

qemuやKVMでよく使われるqcow2イメージのマウントを行いました.

イメージの確認
$ sudo qemu-img info /var/lib/libvirt/images/Debian.qcow2
image: /var/lib/libvirt/images/Debian.qcow2
file format: qcow2
virtual size: 20G (21474836480 bytes)
disk size: 20G
cluster_size: 65536
Format specific information:
	compat: 1.1
	lazy refcounts: true
	refcount bits: 16
	corrupt: false
nbd モジュールの読み込み
$ sudo modprobe nbd
qcow2 イメージのバインド
$ sudo qemu-nbd -c /dev/nbd0 /var/lib/libvirt/images/Debian.qcow2
$ sudo fdisk -l /dev/nbd0
ディスク /dev/nbd0: 20 GiB, 21474836480 バイト, 41943040 セクタ
単位: セクタ (1 * 512 = 512 バイト)
セクタサイズ (論理 / 物理): 512 バイト / 512 バイト
I/O サイズ (最小 / 推奨): 512 バイト / 512 バイト
ディスクラベルのタイプ: dos
ディスク識別子: 0x3c0808c8

デバイス    起動 開始位置 終了位置   セクタ サイズ Id タイプ
/dev/nbd0p1 *        2048   499711   497664   243M 83 Linux
/dev/nbd0p2        501758 41940991 41439234  19.8G  5 拡張領域
/dev/nbd0p5        501760 41940991 41439232  19.8G 83 Linux
kpartx でデバイスマッピング
$ sudo kpartx /dev/nbd0
nbd0p1 : 0 497664 /dev/nbd0 2048
nbd0p2 : 0 2 /dev/nbd0 501758
nbd0p5 : 0 41439232 /dev/dm-1 2
dm-crypt で暗号化されているのでデバイスをオープン
$ sudo cryptsetup open /dev/nbd0p5 crypt
Enter passphrase for /dev/nbd0p5:
lvm領域なのでスキャンする
$ sudo lvmdiskscan
    :
  /dev/mapper/crypt                                     [     <19.76 GiB] LVM physical volume
  /dev/nbd0p5                                           [     <19.76 GiB]
  /dev/debian-vg/root                                   [      18.75 GiB]
  /dev/debian-vg/swap_1                                 [       1.00 GiB]
    :
マウントして内容確認
$ sudo mount -o ro /dev/debian-vg/root /mnt
$ ls /mnt/
bin   dev  home        initrd.img.old  lib64       media  opt   root  sbin  sys  usr  vmlinuz
boot  etc  initrd.img  lib             lost+found  mnt    proc  run   srv   tmp  var  vmlinuz.old
Table of Contents

環境

$ dpkg-query -W kpartx qemu-utils fdisk cryptsetup lvm2 mount linux-image-`uname -r`
cryptsetup      2:2.0.4-2
fdisk   2.32.1-0.1
kpartx  0.7.7-1
linux-image-4.18.0-1-amd64      4.18.8-1
lvm2    2.02.176-4.1
mount   2.32.1-0.1
qemu-utils      1:2.12+dfsg-3
$ lsb_release -d
Description:    Debian GNU/Linux unstable (sid)
$ uname -m
x86_64

Linuxの Google Chrome/Chromium でサインインと同期を無効にする

を見てなるほどと思ったのだけど,macOS, Windows の手順はあるけれどLinux の手順がないなてことで調べてみました.

参考にしたのはこちら.

/etc/opt/chrome, /etc/opt/chromium 以下に json 形式で設定ファイルを設定するだけでした.

Google Chrome の場合

ディレクトリ作成
$ sudo mkdir -p /etc/opt/chrome/policies/managed /etc/opt/chrome/policies/recommended
/etc/opt/chrome/policies/managed/disablesync.json に設定ファイル設置
{
        "SyncDisabled":true,
        "RestrictSigninToPattern":".*@example.com"
}

Chromium の場合

ディレクトリ作成
$ sudo mkdir -p /etc/opt/chromium/policies/managed /etc/opt/chromium/policies/recommended
/etc/opt/chromium/policies/managed/disablesync.json に設定ファイル設置
{
        "SyncDisabled":true,
        "RestrictSigninToPattern":".*@example.com"
}

環境

$ dpkg-query -W google-chrome-stable chromium
chromium        69.0.3497.92-1
google-chrome-stable    69.0.3497.100-1
$ lsb_release -d
Description:    Debian GNU/Linux unstable (sid)
$ uname -m
x86_64

CLI なワンタイムパスワードマネージャの cloak を試す

Rust製のコマンドラインで動作するワンタイムパスワードマネージャです.TOTP/HOTP に対応しています.

Table of Contents

導入

Rust package managerのcargoを導入
$ sudo apt install cargo
cargoでcloakを導入
$ cargo install cloak

~/.cargo/ 以下に導入される

試してみる

help
$ ~/.cargo/bin/cloak --help
cloak 0.1.0
Evans Murithi <murithievans80@gmail.com>
A Command Line OTP Authenticator application.

USAGE:
	cloak [SUBCOMMAND]

FLAGS:
	-h, --help       Prints help information
	-V, --version    Prints version information

SUBCOMMANDS:
	add               Add a new account
	delete            Delete an account
	help              Prints this message or the help of the given subcommand(s)
	list              List OTP for all accounts
	recovery_codes    View recovery codes for an account
	view              View the OTP for an account
add サブコマンドで登録する
$ ~/.cargo/bin/cloak add --help
cloak-add
Add a new account

USAGE:
	cloak add [FLAGS] [OPTIONS] <account> <key>

FLAGS:
	-h, --help       Prints help information
		--hotp       Counter based account
		--totp       Time based account (default)
	-V, --version    Prints version information

OPTIONS:
	-a, --algorithm <ALGORITHM>    Algorithm to use to generate the OTP code [possible values: SHA1, SHA256, SHA384,
								   SHA512, SHA512_256]

ARGS:
	<account>    Name of the account
	<key>        Secret key of the OTP
$ ~/.cargo/bin/cloak add matoken@home.nextcloud M0KMYFVOZY7AGX47
Account successfully created
登録情報確認
$ ~/.cargo/bin/cloak list
Account: matoken@home.nextcloud
TOTP: 538273
アカウントを指定してTOTPトークン表示
$ ~/.cargo/bin/cloak view matoken@home.nextcloud
370696
設定ファイルには生で情報が格納されるので取扱注意
$ cat ~/.cloak/accounts
["matoken@home.nextcloud"]
key = "M0KMYFVOZY7AGX47"
totp = true
hash_function = "SHA1"
アクセス権もそのままでは危ないので注意
$ ls -l ~/.cloak/accounts
-rw-r--r-- 1 matoken matoken 87  9月 22 06:19 /home/matoken/.cloak/accounts
$ chmod -R go-rx ~/.cloak
$ chattr +s ~/.cloak/accounts
$ ls -la ~/.cloak
合計 12
drwx------  2 matoken matoken 4096  9月 22 06:19 .
drwxr-xr-x 62 matoken matoken 4096  9月 23 19:58 ..
-rw-------  1 matoken matoken   87  9月 22 06:19 accounts

秘密鍵が平文でそのままファイルに格納されるので最低でもecryptfsは設定しておかないとかなな感じ?

私は現在はoathtoolを使ったscriptを使っています.秘密鍵はファイルに手で書いて暗号化しておきscript実行時に復号してoathtoolに渡してTOTP表示という感じ.若しくはKeePassCX.

環境

$ ~/.cargo/bin/cloak -V
cloak 0.1.0
$ dpkg-query -W cargo
cargo   0.29.0-1
$ lsb_release -d
Description:    Debian GNU/Linux unstable (sid)
$ uname -m
x86_64

デーモンの起動しないSMTPクライアントの msmtp を試す(sSMTP乗り換え)

sSMTP から msmtp へ

現在メールを受け取らずメールを送信するだけのホストではsSMTPをよく使っています.MTAはeximやPostfix等でも良いのですが,デーモンが起動しないのでその分セキュアで設定も楽です.
しかし,sSMTPは最近メンテされていません,Debian などのディストリビューションではまだメンテナンスされていますが新機能が入ったりはしないでしょう.

ssmtp is unmaintained. Consider using something like msmtp instead.
バージョンも据え置きでUpstreamも無さそう
$ w3m -dump https://packages.qa.debian.org/s/ssmtp.html|grep versions -A11
versions ... ...pool

o-o-stable
    save 2.64-7
oldstable
    save 2.64-8
stable
    save 2.64-8
unstable
    save 2.64-8
Ubuntu
    2.64-8ubuntu2
$ apt show ssmtp 2>/dev/null |grep Homepage
Homepage: http://packages.qa.debian.org/s/ssmtp.html

そこで,alternativeto.net で挙げられている msmtp を試してみました.

以下では色々試していますが,システムメールを送るだけなら msmtp, msmtp-mta pkg を導入,/etc/msmtprc の設定だけでokです.

msmtp の導入

Debian sid/Ubuntu 18.04 LTS などではパッケージがあったのでこれを導入しました.

$ sudo apt install msmtp

mstpの設定

設定例が /usr/share/doc/msmtp/examples/ 以下にあるので
システム設定の場合は msmtprc-system.example`/etc/msmtprc にcpして設定.
ユーザ設定の場合は msmtprc-user.example~/.msmtprc にcpして設定する.

システムでの設定例

以下の例では root が読み書きできて,一般ユーザのmatokenアカウントは読み込みが可能な設定ファイル /etc/msmtprc を作成している.
defaults セクションに共通設定を書き,account セクションにメールサーバ固有の設定を書く.account セクションは複数書けて,account default に規定account を指定する.以下の例ではgmail が規定値となる.

/etc/msmtprc の作成
$ sudo install /dev/null /etc/msmtprc -o root -g root -m 600
$ sudo setfacl -m u:matoken:r /etc/msmtprc
$ getfacl /etc/msmtprc
getfacl: Removing leading '/' from absolute path names
# file: etc/msmtprc
# owner: root
# group: root
user::rw-
user:matoken:r--
group::---
mask::r--
other::---

$ sudo vi /etc/msmtprc
$ sudo grep -v ^# /etc/msmtprc

defaults
syslog on
aliases /etc/aliases

tls on
tls_trust_file /etc/ssl/certs/ca-certificates.crt
auth on
syslog LOG_MAIL

account gmail
host smtp.gmail.com
port 587
from example@gmail.com
user example
password porseypacdoadwif

account default : gmail

※gmailの多要素認証を利用している場合は以下からアプリパスワードを生成する.(使い回しができちゃうけれど流出したときの影響を考えて設定毎に発行する)

ユーザでの設定

ユーザの設定ファイルは`~/.msmtprc` 若しくは $XDG_CONFIG_HOME/msmtp/config でシステムと違い,alias file と log を適当なファイルにした.
アカウントも増やしてみた.
gmailのアプリパスワードも新たに発行した.

~/.msmtprc の作成
$ install /dev/null ~/.msmtprc -o matoken -g matoken -m 600
$ vi ~/.msmtprc
$ grep -v ^# ~/.msmtprc

defaults
logfile ~/.msmtp.log
aliases ~/.msmtp.aliases

tls on
tls_trust_file /etc/ssl/certs/ca-certificates.crt
auth on
syslog LOG_MAIL

account gmail
host smtp.gmail.com
port 587
from example@gmail.com
user example
password igeinleedafchygy

account yandex
tls_starttls off
host smtp.yandex.com
port 465
from example@yandex.com
user example
password throjfeekdewxeib

account nifty
tls_starttls off
host smtp.nifty.com
port 465
from example@nifty.com
user aaa99999
password 9Z#9999X

account default : gmail

送信テスト

msmtp コマンドで送信テストが出来る.
-a オプションでアカウントが指定できる.
-C オプションで設定ファイルが指定できる.(システムとユーザの設定を両方テストする)

$ echo "hello system msmtp" | msmtp -C /etc/msmtprc matohara@gmail.com
$ echo "hello user msmtp" | msmtp -C ~/.msmtprc -a gmail matohara@gmail.com

大抵のMTAでは . でmail body 終了となるが,msmtpでは`.`は普通にbody に含まれる.Ctrl + d で終了.

$ msmtp -a gmail matohara@gmail.com
Subject: hello

msmtp test
.
dot では終了にならない
Ctrl+d で終了
^d

aliases file

msmtp設定ファイルの alias で設定できる.

$ grep alias ~/.msmtprc
aliases ~/.msmtp.alias
$ sudo grep alias /etc/msmtprc
aliases /etc/aliases

このalias fileは通常のaliases ファイルと同じ形式の plain text で newaliases コマンドでの変換は不要.

メールアドレスは複数指定できる.default という名前は規定アドレスとなる.

root: hoge@example.com, fuga@example.com
default: piyo@example.com

以前のaliases ファイルを流用して以下のようにしてみたところ,

# /etc/aliases
mailer-daemon: postmaster
postmaster: root
nobody: root
hostmaster: root
usenet: root
news: root
webmaster: root
www: root
ftp: root
abuse: root
noc: root
security: root
root: matohara@gmail.com
default: matohara@gmail.com

以下のようにエラーとなった.alias先はユーザ名ではエラーとなるよう.

$ echo hello | sudo msmtp -C /etc/msmtprc root
msmtp: /etc/aliases: line 2: invalid address 'postmaster'

以下のようにそれぞれにメールアドレスを指定すると期待した動作となった.

$ sudo sed -i -e 's/ root$\| postmaster$/matohara@gmail.com/' /etc/aliases
$ cat /etc/aliases
# /etc/aliases
mailer-daemon:matohara@gmail.com
postmaster:matohara@gmail.com
nobody:matohara@gmail.com
hostmaster:matohara@gmail.com
usenet:matohara@gmail.com
news:matohara@gmail.com
webmaster:matohara@gmail.com
www:matohara@gmail.com
ftp:matohara@gmail.com
abuse:matohara@gmail.com
noc:matohara@gmail.com
security:matohara@gmail.com
root: matohara@gmail.com
default: matohara@gmail.com

パスワードをGnuPG暗号化ファイルに格納して利用する

パスワードをgpgで暗号化したファイルに格納することが可能.この場合アカウントごとにファイルが必要なのが少し面倒.
password porseypacdoadwif の場合 porseypacdoadwif 部分だけを暗号化してファイルに格納する.(はじめpassword も含めてしまい失敗した)

$ grep ^password\  ~/.msmtprc | head -1 | awk {'print $2'} | gpg2 --default-recipient-self -e - > ~/.msmtp-password-gmail.gpg
$ grep ^password\  ~/.msmtprc | head -2 | tail -1 | awk {'print $2'} | gpg2 --default-recipient-self -e - > ~/.msmtp-password-yandex.gpg
$ grep ^password\  ~/.msmtprc | tail -1 | awk {'print $2'} | gpg2 --default-recipient-self -e - > ~/.msmtp-password-nifty.gpg

msmtprc の password を削除して,代わりに passwordeval gpg2 --no-tty -q -d 暗号ファイル と設定を変更する.

$ grep ^passworde ~/.msmtprc
passwordeval gpg2 --no-tty -q -d ~/.msmtp-password-gmail.gpg
passwordeval gpg2 --no-tty -q -d ~/.msmtp-password-yandex.gpg
passwordeval gpg2 --no-tty -q -d ~/.msmtp-password-nifty.gpg

後はこれまでのようにmsmtpを呼ぶとgpg-agentが起動する.

※システム側はシステムメールが送れなくなるのでこの設定をしないほうがいいと思う.

パスワードをopenssl暗号化ファイルに格納

システムメールでgpg agentを利用するのは多分無理なのでopensslで暗号化してみる.パスワードはNICのmac addressにしてある.気休めレベルだけど試しに設定.
マシンが乗っ取られた場合はどうしようもないけれど /etc/msmtprc, /etc/msmtp-password ファイル流出時の時間稼ぎくらいにはなる?
NIC が使っていないものも含め増減したり変更になった場合は復元できなくなるので注意.

mac address をパスワードとしてopensslで暗号化
$ umask 0077; grep ^password\  /etc/msmtprc | head -1 | awk {'print $2'} | sudo openssl enc -e -md sha256 -aes-256-cbc -a -A -salt -pbkdf2 -in /dev/stdin -out /etc/msmtp-password -pass pass:`hwinfo --network | grep 'Permanent HW Address' | sed 's/^.*: //' | sort -n | tr -d '\n'`
復元テスト
$ sudo openssl enc -d -md sha256 -aes-256-cbc -a -A -salt -pbkdf2 -in /etc/msmtp-password -pass pass:`hwinfo --network | grep 'Permanent HW Address' | sed 's/^.*: //' | sort -n | tr -d '\n'`
igeinleedafchygy
/etc/msmtprc の password を削除して passwordeval に書き換え
$ grep passworde /etc/msmtprc
passwordeval openssl enc -d -md sha256 -aes-256-cbc -a -A -salt -pbkdf2 -in /etc/msmtp-password -pass pass:`hwinfo --network | grep 'Permanent HW Address' | sed 's/^.*: //' | sort -n | tr -d '\n'`

※ifconfigやiproute2を使わずhwinfoを使ってPermanent HW Addressを使っているのはmac address偽装対策

MTA パッケージの導入

msmtp コマンドでメールが送信できるようになったら,msmtp-mta pkg を導入する.これでsendmailコマンドにシンボリックリンクが張られて同様に利用できるようになる.システムメールも飛ぶようになる.

$ sudo apt install msmtp-mta
$ ls -l /usr/sbin/sendmail
lrwxrwxrwx 1 root root 12 11月 29  2016 /usr/sbin/sendmail -> ../bin/msmtp

オフライン時にmsmtpを利用する

msmtpはオフライン時に実行するとエラーとなる.通常は常にオンラインなので問題はないが,持ち運びNotePCなどではオフラインオンラインが発生してメールの送信に失敗することがある.

$ echo 'hoge' | msmtp -a gmail matoken@gmail.com
msmtp: cannot locate host smtp.gmail.com: 名前またはサービスが不明です
msmtp: could not send mail (account gmail from /etc/msmtprc)

/usr/share/doc/msmtp/examples/ 以下の msmtpq 若しくは msmtpqueue に格納されているscriptを利用することでオフライン時にキューとして貯めておいてオンライン時に送信といったことが出来る.

どちらもsendmailと置き換えが可能なので,ネットワークダウン時に`/usr/sbin/sendmail`をこれに置き換えてオンライン時に戻してqueueをフラッシュするようにするといいかもしれない.

Debian/Ubuntuなら以下のあたりで,

  • /etc/network/if-down.d/
    /usr/sbin/sendmail を msmtpq or msmtpqueue に向ける

  • /etc/network/if-pre-up.d/
    /usr/sbin/sendmail を msmtp に向ける

  • /etc/network/if-up.d/
    queueをフラッシュ

NetworkManagerだと /etc/NetworkManager/dispatcher.d/ 以下で同じことが出来る.

msmtpq

圧縮されているmsmtpqを展開して実行権を付与する
$ sudo gunzip /usr/share/doc/msmtp/examples/msmtpq/msmtpq.gz
$ sudo chmod 755 /usr/share/doc/msmtp/examples/msmtpq/msmtpq
使いやすい場所にシンボリックリンクを張る
$ sudo ln -s /usr/share/doc/msmtp/examples/msmtpq/msmtpq /usr/local/bin/msmtpq
$ sudo ln -s /usr/share/doc/msmtp/examples/msmtpq/msmtp-queue /usr/local/bin/msmtp-queue
queueとlogディレクトリを作成
$ install -d -m 700 ~/.msmtp.queue
$ install -d -m 700 ~/log
オフライン時に送信しようとする
$ echo 'msmtpq' | msmtpq -C ~/.msmtprc -a gmail matoken@gmail.com
  mail for [ -C /home/matoken/.msmtprc -a gmail matoken@gmail.com ] : couldn't be sent - host not connected
  enqueued mail as : [ 2018-09-18-06.21.48 ] ( -C /home/matoken/.msmtprc -a gmail matoken@gmail.com ) : successful
queueを確認する
$ msmtp-queue -d

  mail  num=[ 1 ]  id=[ 2018-09-18-06.21.18 ]

  mail  num=[ 2 ]  id=[ 2018-09-18-06.21.48 ]
queueをフラッシュする
$ msmtp-queue -r
  mail [ 1 ] [ 2018-09-18-06.21.18 ] from queue ; send was successful ; purged from queue
  mail [ 2 ] [ 2018-09-18-06.21.48 ] from queue ; send was successful ; purged from queue
$ msmtp-queue -d

  no mail in queue

msmtpqueue

使いやすい場所にシンボリックリンクを張る
$ sudo ln -s /usr/share/doc/msmtp/examples/msmtpqueue/msmtp-enqueue.sh /usr/local/bin/msmtp-enqueue.sh
$ sudo ln -s /usr/share/doc/msmtp/examples/msmtpqueue/msmtp-listqueue.sh /usr/local/bin/msmtp-listqueue.sh
~$ sudo ln -s /usr/share/doc/msmtp/examples/msmtpqueue/msmtp-runqueue.sh /usr/local/bin/msmtp-runqueue.sh
`msmtp`コマンドの代わりに`msmtp-enqueue.sh`を使う
$ echo 'queue' | msmtp-enqueue.sh -C ~/.msmtprc -a gmail matoken@gmail.com
queueを確認する
$ msmtp-listqueue.sh
No mail in queue
今回のようにメールの内容がbodyだけでFrom, To, Subject が存在しないとこのscriptはうまく機能しない><
         egrep -s --colour -h '(^From:|^To:|^Subject:)' "$i" || echo "No mail in queue";
直接`~/.msmtpqueue/`を確認するとqueueが溜まっているのがわかる
$ ls -lA ~/.msmtpqueue/
合計 8
-rw------- 1 matoken matoken  7  9月 18 00:15 2018-09-18-00.15.53.mail
-rw------- 1 matoken matoken 53  9月 18 00:15 2018-09-18-00.15.53.msmtp
Subjectの付いたメールがある時
$ msmtp-listqueue.sh
No mail in queue

Subject: offline><
オンライン時にqueueをフラッシュする
$ msmtp-runqueue.sh
*** Sending 2018-09-18-00.15.53.mail to -C /home/matoken/.msmtprc -a gmail matoken@gmail.com ...
2018-09-18-00.15.53.mail sent successfully
*** Sending 2018-09-18-00.27.21.mail to -C /home/matoken/.msmtprc -a gmail matoken@gmail.com ...
2018-09-18-00.27.21.mail sent successfully

#sudoの場合も ~root/.msmtpqueue/ だった.

tips

gmailで以下のエラーとなった場合 tls_starttls on ( tls onのときの既定値? )と設定すると送信できた
$ echo "hello msmtp" | sudo msmtp -a gmail matohara@gmail.com
msmtp: envelope from address matohara@gmail.com not accepted by the server
msmtp: server message: 530 5.7.0 Must issue a STARTTLS command first. k126-v6sm14991126pgk.26 - gsmtp
msmtp: could not send mail (account gmail from /etc/msmtprc)
Yandexでメール送信時に帰ってこない場合 tls_starttls off と設定すると送信できた
niftyで以下のエラーとなった場合 tls_starttls off と設定すると送信できた
msmtp: network read error: 接続が相手からリセットされました
msmtp: could not send mail (account nifty from /etc/msmtprc)

試した環境

環境1(Raspberry Pi 2B/Raspbian stretch)
$ dpkg-query -W msmtp msmtp-mta gnupg2 openssl
gnupg2  2.1.18-8~deb9u2
msmtp   1.6.6-1
msmtp-mta       1.6.6-1
openssl 1.1.0f-3+deb9u2
$ lsb_release -d
Description:    Raspbian GNU/Linux 9.4 (stretch)
$ uname -m
armv7l
環境2(Ubuntu 18.04 LTS)
$ dpkg-query -W msmtp msmtp-mta gnupg2 openssl
gnupg2  2.2.4-1ubuntu1.1
msmtp   1.6.6-1
msmtp-mta       1.6.6-1
openssl 1.1.0g-2ubuntu4.1
$ lsb_release -d
Description:    Ubuntu 18.04.1 LTS
$ uname -m
x86_64
環境3(Debian sid)
$ dpkg-query -W msmtp msmtp-mta gnupg2 openssl
gnupg2  2.2.10-1
msmtp   1.6.7-1
msmtp-mta
openssl 1.1.1-1
$ lsb_release -d
Description:    Debian GNU/Linux unstable (sid)
$ uname -m
x86_64

crontab から送信される電子メールの件名を指定したい

crontab で実行されたコマンドの出力はメールで送られますが,このときの件名は「Cron <ユーザ名@ホスト名> 実行コマンド」のようになります.

crontab 例
15 7 * * *  echo "cron subject"
メール例
Subject: Cron <matoken@T430s> echo "cron subject"

cron subject
1つのhostからこんなメール飛んで来るとどれがどれかわかりづらい
Cron <matoken@T430s> nice -n 19 ionice -c 3 rsync -avxze "ssh -i……
Cron <root@T430s> nice -n 19 ionice -c 3 rsync -avxze "ssh -i……
Cron <root@T430s> nice -n 19 ionice -c 3 rsync -avxze "ssh -i……

分かりづらいので自分で件名を付けたいところです.

: を利用する

: は shell の組み込み関数で何もせず正常終了します.
コマンドなので # と違い,; の後にコマンドを書くとその後のコマンドは解釈されます.

$ :           #何もしない
$ : hoge
$ : echo hoge
$ : rm -rf *
$ : $(hostname)  #コマンドも展開せず何もしない
$ : `whoami`
$ : hoge; echo fuga   #;の後は解釈される
fuga
$ # hoge
$ # hoge; echo fuga

これをcrontabの頭に書くとこういう感じになります.

crontab
29 6 * * *  : cron subject; echo "hello"
mail
Subject: Cron <matoken@T430s> : cron subject; echo "hello"

hello

少しわかりやすくなりました.

mailコマンドを利用する

これはちょっと反則な感じがするのですが件名にコマンド実行結果を入れたり,頭の部分も書き換えたい場合はcronだけではできなさそうなのでmailコマンド経由で送信してみます.今回mailutilsのmailコマンドを利用しましたが,bsd-mailxやmutt等々ももちろん使えます.

crontab
45 6 * * *  echo "cron test" | mail -s "$(hostname)@$(whoami) cron Subject : $(date +\%F)" matoken+cron@example.com
mail
Subject: T430s@matoken cron Subject : 2018-09-13
X-Mailer: mail (GNU Mailutils 3.4)

cron test

mail コマンドの -s オプション部分が件名になります.その後ろが宛先のメールアドレス.bodyはcronの出力をパイプから受け取ります.

STDERR が別メールで届く

STDERR の出力があった場合cronでメールが送られてしまいます.mailコマンドと合わせて1度に2通届くことに.
実行コマンドの後ろに 2>&1 を付けて STDERR を STDOUT に渡してmailコマンドだけにします.

crontab
45 6 * * *  echo "cron test" 2>&1 | mail -s "$(hostname)@$(whoami) cron Subject : $(date +\%F)" matoken+cron@example.com

出力がなくてもメールが届く

crontab の場合コマンドの出力がなければメールが送られませんが,このコマンドでは NULL でもメールが送信されます.
未解決.

余録

cronで一切メールを送りたくない

場合crontabで MAILTO=”” を設定する
MAILTO=""

指定したコマンドだけメールを送りたくない

STDOUT と STDERR を /dev/null に捨てる
20 6 * * *  echo "cron subject" > /dev/null 2>&1

メールが届かない

/var/spool/mail/ユーザ名 のローカルにはメールがどとくけど,インターネット上のメールアドレスを指定しても届かない場合メールサーバの設定が出来ていないかもしれません.メールサーバ(sSMTP/msmtp等はデーモンが起動しないのでメールを受け取らず送信するだけならおすすめ)を設定してから再度試してみましょう.

環境1
$ man cron | grep -m1 cron
       cron - daemon to execute scheduled commands (Vixie Cron)
$ dpkg-query -W cron mailutils
cron    3.0pl1-128.1ubuntu1
mailutils       1:3.4-1
$ lsb_release -d
Description:    Ubuntu 18.04.1 LTS
$ uname -m
x86_64
環境2
$ man cron | grep -m1 cron
       cron - 予定されたコマンドを実行するデーモン(Vixie Cron)
$ dpkg-query -W cron mailutils
cron    3.0pl1-130
mailutils       1:3.4-1+b1
$ lsb_release -d
Description:    Debian GNU/Linux unstable (sid)
$ uname -m
x86_64