Closed23

Logwatchを(再)構築する

Alice RoseAlice Rose

なんか気づいたらLogwatchからメール来なくなってた
調査してみたけど原因がよくわからないので面倒になってきたので一度まっさらにして入れ直す


8月から来てなかったのに気づいてなかったのも我ながらどうかと思うが

Alice RoseAlice Rose
sudo apt install logwatch
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
The following additional packages will be installed:
  libdate-manip-perl postfix
Suggested packages:
  libsys-cpu-perl libsys-meminfo-perl procmail postfix-mysql postfix-pgsql postfix-ldap postfix-pcre postfix-lmdb postfix-sqlite
  sasl2-bin | dovecot-common resolvconf postfix-cdb postfix-mta-sts-resolver postfix-doc
The following NEW packages will be installed:
  libdate-manip-perl logwatch postfix
0 upgraded, 3 newly installed, 0 to remove and 29 not upgraded.
Need to get 2572 kB of archives.
After this operation, 19.2 MB of additional disk space will be used.
Do you want to continue? [Y/n] y
Get:1 http://jp.archive.ubuntu.com/ubuntu jammy-updates/main amd64 postfix amd64 3.6.4-1ubuntu1.3 [1248 kB]
Get:2 http://jp.archive.ubuntu.com/ubuntu jammy/main amd64 libdate-manip-perl all 6.86-1 [946 kB]
Get:3 http://jp.archive.ubuntu.com/ubuntu jammy/main amd64 logwatch all 7.5.6-1ubuntu1 [378 kB]
Fetched 2572 kB in 2s (1611 kB/s)
Preconfiguring packages ...
Selecting previously unselected package postfix.
(Reading database ... 170199 files and directories currently installed.)
Preparing to unpack .../postfix_3.6.4-1ubuntu1.3_amd64.deb ...
Unpacking postfix (3.6.4-1ubuntu1.3) ...
Selecting previously unselected package libdate-manip-perl.
Preparing to unpack .../libdate-manip-perl_6.86-1_all.deb ...
Unpacking libdate-manip-perl (6.86-1) ...
Selecting previously unselected package logwatch.
Preparing to unpack .../logwatch_7.5.6-1ubuntu1_all.deb ...
Unpacking logwatch (7.5.6-1ubuntu1) ...
Setting up postfix (3.6.4-1ubuntu1.3) ...
Adding group `postfix' (GID 121) ...
Done.
Adding system user `postfix' (UID 114) ...
Adding new user `postfix' (UID 114) with group `postfix' ...
Not creating home directory `/var/spool/postfix'.
Creating /etc/postfix/dynamicmaps.cf
Adding group `postdrop' (GID 122) ...
Done.
setting myhostname: ********
setting alias maps
setting alias database
mailname is not a fully qualified domain name.  Not changing /etc/mailname.
setting destinations: $myhostname, ********, localhost.localdomain, , localhost
setting relayhost: 
setting mynetworks: 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
setting mailbox_size_limit: 0
setting recipient_delimiter: +
setting inet_interfaces: all
setting inet_protocols: all
WARNING: /etc/aliases exists, but does not have a root alias.
Progress: [ 54%] [##############################################################......................................................] 
Postfix (main.cf) is now set up with a default configuration.  If you need to 
make changes, edit /etc/postfix/main.cf (and others) as needed.  To view 
Postfix configuration values, see postconf(1).

After modifying main.cf, be sure to run 'systemctl reload postfix'.

Running newaliases
Created symlink /etc/systemd/system/multi-user.target.wants/postfix.service → /lib/systemd/system/postfix.service.
Setting up libdate-manip-perl (6.86-1) ...
Setting up logwatch (7.5.6-1ubuntu1) ...#################################################.............................................] 
Processing triggers for ufw (0.36.1-4ubuntu0.1) ...########################################################...........................] 
Processing triggers for man-db (2.10.2-1) ...################################################################################.........] 
Processing triggers for rsyslog (8.2112.0-2ubuntu2.2) ...
Scanning processes...                                                                                                                     
Scanning candidates...                                                                                                                    
Scanning processor microcode...                                                                                                           
Scanning linux images...                                                                                                                  

Running kernel seems to be up-to-date.

The processor microcode seems to be up-to-date.

Restarting services...
 systemctl restart fail2ban.service irqbalance.service packagekit.service polkit.service thermald.service udisks2.service upower.service
Service restarts being deferred:
 systemctl restart ModemManager.service
 systemctl restart networkd-dispatcher.service
 systemctl restart unattended-upgrades.service

No containers need to be restarted.

No user sessions are running outdated binaries.

No VM guests are running outdated hypervisor (qemu) binaries on this host.

なんかピンクの画面出てきたけどとりあえずデフォルトのまま進めた

Alice RoseAlice Rose

一時ディレクトリを作る

sudo mkdir /var/cache/logwatch
Alice RoseAlice Rose

初期のコンフィグファイルは/usr/share/logwatch/default.conf/logwatch.conf
これを/etc/logwatch/confへコピーしてから弄る

########################################################
# This was written and is maintained by:
#    Kirk Bauer <kirk@kaybee.org>
#
# Please send all comments, suggestions, bug reports,
#    etc, to kirk@kaybee.org.
#
########################################################

# NOTE:
#   All these options are the defaults if you run logwatch with no
#   command-line arguments.  You can override all of these on the
#   command-line.

# You can put comments anywhere you want to.  They are effective for the
# rest of the line.

# this is in the format of <name> = <value>.  Whitespace at the beginning
# and end of the lines is removed.  Whitespace before and after the = sign
# is removed.  Everything is case *insensitive*.

# Yes = True  = On  = 1
# No  = False = Off = 0

# Default Log Directory
# All log-files are assumed to be given relative to this directory.
LogDir = /var/log

# You can override the default temp directory (/tmp) here
TmpDir = /var/cache/logwatch

#Output/Format Options
#By default Logwatch will print to stdout in text with no encoding.
#To make email Default set Output = mail to save to file set Output = file
Output = stdout
#To make Html the default formatting Format = html
Format = text
#To make Base64 [aka uuencode] Encode = base64
Encode = none

# Default person to mail reports to.  Can be a local account or a
# complete email address.  Variable Output should be set to mail, or
# --output mail should be passed on command line to enable mail feature.
MailTo = root
# WHen using option --multiemail, it is possible to specify a different
# email recipient per host processed.  For example, to send the report
# for hostname host1 to user@example.com, use:
#Mailto_host1 = user@example.com
# Multiple recipients can be specified by separating them with a space.

# Default person to mail reports from.  Can be a local account or a
# complete email address.
MailFrom = Logwatch

# if set, the results will be saved in <filename> instead of mailed
# or displayed. Be sure to set Output = file also.
#Filename = /tmp/logwatch

# Use archives?  If set to 'Yes', the archives of logfiles
# (i.e. /var/log/messages.1 or /var/log/messages.1.gz) will
# be searched in addition to the /var/log/messages file.
# This usually will not do much if your range is set to just
# 'Yesterday' or 'Today'... it is probably best used with Range = All
# By default this is now set to Yes. To turn off Archives uncomment this.
#Archives = No

# The default time range for the report...
# The current choices are All, Today, Yesterday
Range = yesterday

# The default detail level for the report.
# This can either be Low, Med, High or a number.
# Low = 0
# Med = 5
# High = 10
Detail = Low


# The 'Service' option expects either the name of a filter
# (in /usr/share/logwatch/scripts/services/*) or 'All'.
# The default service(s) to report on.  This should be left as All for
# most people.
Service = All
# You can also disable certain services (when specifying all)
Service = "-zz-network"     # Prevents execution of zz-network service, which
                            # prints useful network configuration info.
Service = "-zz-sys"         # Prevents execution of zz-sys service, which
                            # prints useful system configuration info.
Service = "-eximstats"      # Prevents execution of eximstats service, which
                            # is a wrapper for the eximstats program.
# If you only cared about FTP messages, you could use these 2 lines
# instead of the above:
#Service = ftpd-messages   # Processes ftpd messages in /var/log/messages
#Service = ftpd-xferlog    # Processes ftpd messages in /var/log/xferlog
# Maybe you only wanted reports on PAM messages, then you would use:
#Service = pam_pwdb        # PAM_pwdb messages - usually quite a bit
#Service = pam             # General PAM messages... usually not many

# You can also choose to use the 'LogFile' option.  This will cause
# logwatch to only analyze that one logfile.. for example:
#LogFile = messages
# will process /var/log/messages.  This will run all the filters that
# process that logfile.  This option is probably not too useful to
# most people.  Setting 'Service' to 'All' above analyzes all LogFiles
# anyways...

#
# By default we assume that all Unix systems have sendmail or a sendmail-like MTA.
# The mailer code prints a header with To: From: and Subject:.
# At this point you can change the mailer to anything that can handle this output
# stream.
# TODO test variables in the mailer string to see if the To/From/Subject can be set
# From here with out breaking anything. This would allow mail/mailx/nail etc..... -mgt
mailer = "/usr/sbin/sendmail -t"

#
# With this option set to a comma separated list of hostnames, only log entries
# for these particular hosts will be processed.  This can allow a log host to
# process only its own logs, or Logwatch can be run once per a set of hosts
# included in the logfiles.
# Example: HostLimit = hosta,hostb,myhost
#
# The default is to report on all log entries, regardless of its source host.
# Note that some logfiles do not include host information and will not be
# influenced by this setting.
#
#HostLimit = myhost

#
# By default /var/adm is searched after LogDir.
#AppendVarAdmToLogDirs = 1

#
# By default /var/log is to be searched after LogDir and /var/adm/ .
#AppendVarLogToLogDirs = 1

#
# By default the current working directory is searched last after LogDir, /var/adm/, and /var/log/ .
#AppendCWDToLogDirs = 1

# vi: shiftwidth=3 tabstop=3 et```
Alice RoseAlice Rose

いっぱい入っているコメントが不要な場合は下記で抜粋したファイルを生成出来る

cd /etc/logwatch/conf/
cat /usr/share/logwatch/default.conf/logwatch.conf | grep -v -e '#' -e '^$' | sudo tee logwatch.conf

スッキリ

TmpDir = /var/cache/logwatch
Output = stdout
Format = text
Encode = none
MailTo = root
MailFrom = Logwatch
Range = yesterday
Detail = Low
Service = All
mailer = "/usr/sbin/sendmail -t"

でもちゃんと全量抜粋出来てるか自信がないので普通にコピーして使う

sudo cp /usr/share/logwatch/default.conf/logwatch.conf ./logwatch.conf
Alice RoseAlice Rose

コンフィグ弄る

  • 通知先をメールにする
# Output/Format Options
# By default Logwatch will print to stdout in text with no encoding.
# To make email Default set Output = mail to save to file set Output = file
- Output = stdout
+ Output = mail
  • 宛先を指定(後でpostfixからgmailに送れるようにする)
# Default person to mail reports to.  Can be a local account or a
# complete email address.  Variable Output should be set to mail, or
# --output mail should be passed on command line to enable mail feature.
- MailTo = root
+ MailTo = ********@gmail.com
  • レポート内容の詳細度を上げる
    鬱陶しかったら下げてもいいけど上げて困ることは多分ない
# The default detail level for the report.
# This can either be Low, Med, High or a number.
# Low = 0
# Med = 5
# High = 10
- Detail = Low
+ Detail = High
Alice RoseAlice Rose

動いてるか見てみる

sudo logwatch --output stdout

すごい時間かかるけど出力はされるので動いてる様子

 ################### Logwatch 7.5.6 (07/23/21) #################### 
        Processing Initiated: Tue Dec 10 11:23:22 2024
        Date Range Processed: yesterday
                              ( 2024-Dec-09 )
                              Period is day.
        Detail Level of Output: 10
        Type of Output/Format: stdout / text
        Logfiles for Host: ********
 ################################################################## 
 
 --------------------- Cron Begin ------------------------ 

 Commands Run:
    User postgres:
       /usr/bin/bash /var/lib/postgresql/backup.sh: 1 Time(s)
    User root:
          cd / && run-parts --report /etc/cron.hourly: 24 Time(s)
       command -v debian-sa1 > /dev/null && debian-sa1 1 1: 144 Time(s)
       command -v debian-sa1 > /dev/null && debian-sa1 60 2: 1 Time(s)
       setfacl -R -m u:promtail:rX /var/log: 24 Time(s)
       test -e /run/systemd/system || SERVICE_MODE=1 /sbin/e2scrub_all -A -r: 1 Time(s)
       test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily ): 1 Time(s)
    User sharkey:
       /usr/bin/bash /home/sharkey/backup.sh: 1 Time(s)
    User ********:
       /usr/bin/bash /home/********/batch/transfer_sharkey_backup.sh: 1 Time(s)
 
 ---------------------- Cron End -------------------------

*** 以下略***

これがメールで送られてくるようになれば良い

Alice RoseAlice Rose

postfixのデフォルトコンフィグを/etc/postfix/main.cfへ配置

cp /usr/share/postfix/main.cf.dist /etc/postfix/main.cf
Alice RoseAlice Rose

sudoで/etc/postfix/sasl_passwd を作って以下を記述

[smtp.gmail.com]:587 (gmailのアカウント)@gmail.com:(発行したアプリパスワード)

アプリパスワードのスペースってトリムしていいのかな
パスワードにスペース含むは多分ないだろうからトリムしておく
だめなら後で泣きながらやり直す

Alice RoseAlice Rose

ハッシュ化する

sudo chmod 600 /etc/postfix/sasl_passwd
sudo postmap /etc/postfix/sasl_passwd
postmap: fatal: bad string length 0 < 1: setgid_group =

なんか怒られた くそが

Alice RoseAlice Rose

main.cfの下記行をコメントアウト

# setgid_group: The group for mail submission and queue management
# commands.  This must be a group name with a numerical group ID that
# is not shared with other accounts, not even with the Postfix account.
#
- setgid_group =
+ #setgid_group =
Alice RoseAlice Rose

/etc/postfixsasl_passwd.dbが爆誕する

ls
.rw-r--r--   60 root 10 Dec 10:48 dynamicmaps.cf
drwxr-xr-x    - root 29 Jan 17:02 dynamicmaps.cf.d
.rw-r--r--  27k root 10 Dec 12:22 main.cf
.rw-r--r--  27k root 10 Dec 10:48 main.cf.proto
lrwxrwxrwx    - root 10 Dec 10:49 makedefs.out -> /usr/share/postfix/makedefs.out
.rw-r--r-- 6.5k root 10 Dec 10:48 master.cf
.rw-r--r-- 6.5k root 10 Dec 10:48 master.cf.proto
.rwxr-xr-x  30k root 29 Jan 17:02 post-install
.rw-r--r--  10k root 29 Jan 17:02 postfix-files
drwxr-xr-x    - root 29 Jan 17:02 postfix-files.d
.rwxr-xr-x  11k root 29 Jan 17:02 postfix-script
drwxr-xr-x    - root 29 Jan 17:02 sasl
.rw-------   68 root 10 Dec 12:15 sasl_passwd
.rw-------  12k root 10 Dec 12:22 sasl_passwd.db
Alice RoseAlice Rose

main.cfに下記を追記

smtp_use_tls = yes
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_sasl_tls_security_options = noanonymous

そしたら一回postfixを再起動して反映する

sudo systemctl restart postfix
systemctl status postfix
● postfix.service - Postfix Mail Transport Agent
     Loaded: loaded (/lib/systemd/system/postfix.service; enabled; vendor preset: enabled)
     Active: active (exited) since Tue 2024-12-10 12:25:41 JST; 18s ago
       Docs: man:postfix(1)
    Process: 659869 ExecStart=/bin/true (code=exited, status=0/SUCCESS)
   Main PID: 659869 (code=exited, status=0/SUCCESS)
        CPU: 2ms

Dec 10 12:25:41 ******** systemd[1]: Starting Postfix Mail Transport Agent...
Dec 10 12:25:41 ******** systemd[1]: Finished Postfix Mail Transport Agent.

いつも思うけどactive(exited) はいいのか悪いのかわからない

Alice RoseAlice Rose

テストメール発射

echo 'Hellow World!' | mail -s ****@gmail.com

何も来ない

Alice RoseAlice Rose
tail -f /var/log/mail.log
Dec 10 10:49:02 ******** postfix/postfix-script[585380]: starting the Postfix mail system
Dec 10 10:49:02 ******** postfix/master[585382]: daemon started -- version 3.6.4, configuration /etc/postfix
Dec 10 12:17:14 ******** postfix/postmap[653346]: fatal: bad string length 0 < 1: setgid_group = 
Dec 10 12:25:39 ******** postfix[659783]: fatal: bad string length 0 < 1: sendmail_path = 
Dec 10 12:25:40 ******** postfix/master[585382]: terminating on signal 15
Dec 10 12:25:40 ******** postfix[659865]: fatal: bad string length 0 < 1: sendmail_path =

うーん?
他にも不要な設定が残ってるみたい

Alice RoseAlice Rose

再度/etc/postfix/main.cf開いてこの辺一通りコメントアウトする

# INSTALL-TIME CONFIGURATION INFORMATION
#
# The following parameters are used when installing a new Postfix version.
# 
# sendmail_path: The full pathname of the Postfix sendmail command.
# This is the Sendmail-compatible mail posting interface.
#
- sendmail_path =
+ #sendmail_path =

# newaliases_path: The full pathname of the Postfix newaliases command.
# This is the Sendmail-compatible command to build alias databases.
#
- newaliases_path =
+ #newaliases_path =

# mailq_path: The full pathname of the Postfix mailq command.  This
# is the Sendmail-compatible mail queue listing command.
# 
- #mailq_path =
+ #mailq_path =

# setgid_group: The group for mail submission and queue management
# commands.  This must be a group name with a numerical group ID that
# is not shared with other accounts, not even with the Postfix account.
#
#setgid_group =

# html_directory: The location of the Postfix HTML documentation.
#
- html_directory =
+ #html_directory =

# manpage_directory: The location of the Postfix on-line manual pages.
#
- manpage_directory =
+ #manpage_directory =

# sample_directory: The location of the Postfix sample configuration files.
# This parameter is obsolete as of Postfix 2.1.
#
- sample_directory =
+ #sample_directory =

# readme_directory: The location of the Postfix README files.
#
- readme_directory =
+ #readme_directory =

素直に抜粋版使えばこんな罠に引っかからなかったのでは?という気がしてきた

また再起動して反映

sudo systemctl restart postfix
Alice RoseAlice Rose

なんかログが流れ出した
メールもちゃんと来た

Dec 10 12:40:59 ******** postfix/postfix-script[674863]: starting the Postfix mail system
Dec 10 12:40:59 ******** postfix/master[674865]: daemon started -- version 3.6.4, configuration /etc/postfix
Dec 10 12:40:59 ******** postfix/pickup[674866]: BEF655C23C1: uid=1000 from=<********@********>
Dec 10 12:40:59 ******** postfix/cleanup[674869]: BEF655C23C1: message-id=<20241210034059.BEF655C23C1@********.localdomain>
Dec 10 12:40:59 ******** postfix/qmgr[674867]: BEF655C23C1: from=<********@********>, size=343, nrcpt=1 (queue active)

これでpostfixがgmail使ってメール送れるようになった(言い回しがあっているかどうかは微妙だが)

Alice RoseAlice Rose

もいっちょテスト

sudo logwatch --output mail

4ヶ月ぶりくらいにメールが来た

Alice RoseAlice Rose

cronは勝手に登録してくれているらしいので何もしなくて良さそう
とりあえず明日の朝を待ってみることに

cat /etc/cron.daily/00logwatch
───────┬──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
       │ File: /etc/cron.daily/00logwatch
───────┼──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
   1   │ #!/bin/bash
   2   │ 
   3   │ #Check if removed-but-not-purged
   4   │ test -x /usr/share/logwatch/scripts/logwatch.pl || exit 0
   5   │ 
   6   │ #execute
   7   │ /usr/sbin/logwatch --output mail
   8   │ 
   9   │ #Note: It's possible to force the recipient in above command
  10   │ #Just pass --mailto address@a.com instead of --output mail
Alice RoseAlice Rose

ちゃんと朝にメールきてた

とりあえずこれで良しとします
おしまい

このスクラップは8日前にクローズされました