2. 개발노트 2주차

Daitnu·2019년 11월 15일
3

2주차

들어가며

개발노트 1주차 블로그를 읽어 보시고 그대로 따라해 주셨다면 메일을 nodemailer를 통해 메일을 보내고 메일을 받으면 /etc/dovecot/conf.d/10-mail.conf파일 내에 mail_location에 적으신 위치에서 메일을 찾으실 수 있으실 것입니다.

하지만 지금의 방식은 리눅스의 계정을 추가해야만 메일의 계정이 추가되는, 즉 본인의 리눅스 계정이 메일 계정이 되는 방식입니다. (리눅스 계정이 hohoya라면 메일 계정은 hohoya@daitnu.com)

지금의 방식으로는 웹 메일 서비스를 만드는 데에 한계가 있습니다.

웹 클라이언트가 회원가입을 할 때 마다 리눅스의 계정이 추가되는 방식이기 때문입니다.

웹 메일 서비스를 구축하기 위해서는 리눅스 계정을 메일 계정으로 다루는 것이 아닌 user라는 데이터베이스에 존재하는 아이디가 메일 계정으로 다루어져야 할 필요가 있었습니다.

이번 2주차에서는 user라는 데이터베이스에 존재하는 아이디가 메일 계정으로 다루어지게끔 설정해 주는 작업, NginxHTTPS를 설정하는 작업, HTTP 요청을 HTTPS로 리다이렉션 시켜주는 작업, 마지막으로 daitnu.com 이메일에 메일이 들어올 경우 쉘 프로그램을 실행하는 작업을 진행하였습니다.

Install Package

$ sudo apt-get install postfix postfix-mysql dovecot-core dovecot-imapd dovecot-pop3d dovecot-lmtpd dovecot-mysql mysql-server

MySQL


MySQL 설정

  1. MySQL 설치
    $ sudo mysql_secure_installation

다음의 물음들에 Y라고 답해주세요

  • Remove anonymous users?
  • Disallow root login remotely?
  • Remove test database and access to it?
  • Reload privilege tables now?
  1. 데이터베이스 생성
    $ sudo mysqladmin -u root -p create mailserver
  1. MySQL 로그인
    sudo mysql -u root -p
  1. MySQL user 생성 및 권한 부여
    GRANT SELECT ON mailserver.* TO 'mailuser'@'127.0.0.1' IDENTIFIED BY 'mailuserpass';
  1. 변경 사항 저장
    FLUSH PRIVILEGES;
  1. mailserver데이터베이스 선택
    USE mailserver;
  1. 메일을 받을 도메인을 위한 테이블 생성
    CREATE TABLE `virtual_domains` (
      `id` int(11) NOT NULL auto_increment,
      `name` varchar(50) NOT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
  1. 모든 이메일 주소와 비밀번호를 저장할 테이블 생성
    CREATE TABLE `virtual_users` (
      `id` int(11) NOT NULL auto_increment,
      `domain_id` int(11) NOT NULL,
      `password` varchar(106) NOT NULL,
      `email` varchar(100) NOT NULL,
      PRIMARY KEY (`id`),
      UNIQUE KEY `email` (`email`),
      FOREIGN KEY (domain_id) REFERENCES virtual_domains(id) ON DELETE CASCADE
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
  1. 이메일 alias를 위한 테이블 생성
    CREATE TABLE `virtual_aliases` (
      `id` int(11) NOT NULL auto_increment,
      `domain_id` int(11) NOT NULL,
      `source` varchar(100) NOT NULL,
      `destination` varchar(100) NOT NULL,
      PRIMARY KEY (`id`),
      FOREIGN KEY (domain_id) REFERENCES virtual_domains(id) ON DELETE CASCADE
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

데이터 추가

  1. 도메인 테이블에 데이터 추가
    INSERT INTO `mailserver`.`virtual_domains`
      (`id` ,`name`)
    VALUES
      ('1', 'example.com'),
      ('2', 'hostname.example.com'),
      ('3', 'hostname'),
      ('4', 'localhost.example.com');

example.comhostname은 자신의 세팅에 맞춰주세요

  1. user 테이블에 이메일 주소 추가
    INSERT INTO `mailserver`.`virtual_users`
      (`id`, `domain_id`, `password` , `email`)
    VALUES
      ('1', '1', ENCRYPT('password', CONCAT('$6$', SUBSTRING(SHA(RAND()), -16))), 'email1@example.com'),
      ('2', '1', ENCRYPT('password', CONCAT('$6$', SUBSTRING(SHA(RAND()), -16))), 'email2@example.com');

domain_idvirtual_domains 테이블의 id를 참조합니다

  1. alias 테이블에 데이터 추가
    INSERT INTO `mailserver`.`virtual_aliases`
      (`id`, `domain_id`, `source`, `destination`)
    VALUES
      ('1', '1', 'alias@example.com', 'email1@example.com');

Postfix


$ sudo cp /etc/postfix/main.cf /etc/postfix/main.cf.orig

먼저 추후에 돌이킬 수 없는 오류 발생 시 되돌아가기 위한 백업을 해주세요

$ vim /etc/postfix/main.cf

# See /usr/share/postfix/main.cf.dist for a commented, more complete version

# Debian specific:  Specifying a file name will cause the first
# line of that file to be used as the name.  The Debian default
# is /etc/mailname.
#myorigin = /etc/mailname

smtpd_banner = $myhostname ESMTP $mail_name (Ubuntu)
biff = no

# appending .domain is the MUA's job.
append_dot_mydomain = no

# Uncomment the next line to generate "delayed mail" warnings
#delay_warning_time = 4h

readme_directory = no

# TLS parameters
smtpd_tls_cert_file=/etc/letsencrypt/live/example.com/fullchain.pem
smtpd_tls_key_file=/etc/letsencrypt/live/example.com/privkey.pem
smtpd_use_tls=yes
smtpd_tls_auth_only = yes
smtp_tls_security_level = may
smtpd_tls_security_level = may
smtpd_sasl_security_options = noanonymous, noplaintext
smtpd_sasl_tls_security_options = noanonymous

# Authentication
smtpd_sasl_type = dovecot
smtpd_sasl_path = private/auth
smtpd_sasl_auth_enable = yes

# See /usr/share/doc/postfix/TLS_README.gz in the postfix-doc package for
# information on enabling SSL in the smtp client.

# Restrictions
smtpd_helo_restrictions =
        permit_mynetworks,
        permit_sasl_authenticated,
        reject_invalid_helo_hostname,
        reject_non_fqdn_helo_hostname
smtpd_recipient_restrictions =
        permit_mynetworks,
        permit_sasl_authenticated,
        reject_non_fqdn_recipient,
        reject_unknown_recipient_domain,
        reject_unlisted_recipient,
        reject_unauth_destination
smtpd_sender_restrictions =
        permit_mynetworks,
        permit_sasl_authenticated,
        reject_non_fqdn_sender,
        reject_unknown_sender_domain
smtpd_relay_restrictions =
        permit_mynetworks,
        permit_sasl_authenticated,
        defer_unauth_destination

# See /usr/share/doc/postfix/TLS_README.gz in the postfix-doc package for
# information on enabling SSL in the smtp client.

myhostname = example.com
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
mydomain = example.com
myorigin = $mydomain
mydestination = localhost
relayhost =
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
mailbox_size_limit = 0
recipient_delimiter = +
inet_interfaces = all
inet_protocols = all

# Handing off local delivery to Dovecot's LMTP, and telling it where to store mail
virtual_transport = lmtp:unix:private/dovecot-lmtp

# Virtual domains, users, and aliases
virtual_mailbox_domains = mysql:/etc/postfix/mysql-virtual-mailbox-domains.cf
virtual_mailbox_maps = mysql:/etc/postfix/mysql-virtual-mailbox-maps.cf
virtual_alias_maps = mysql:/etc/postfix/mysql-virtual-alias-maps.cf,
        mysql:/etc/postfix/mysql-virtual-email2email.cf

# Even more Restrictions and MTA params
disable_vrfy_command = yes
strict_rfc821_envelopes = yes
#smtpd_etrn_restrictions = reject
#smtpd_reject_unlisted_sender = yes
#smtpd_reject_unlisted_recipient = yes
smtpd_delay_reject = yes
smtpd_helo_required = yes
smtp_always_send_ehlo = yes
#smtpd_hard_error_limit = 1
smtpd_timeout = 30s
smtp_helo_timeout = 15s
smtp_rcpt_timeout = 15s
smtpd_recipient_limit = 40
minimal_backoff_time = 180s
maximal_backoff_time = 3h

# Reply Rejection Codes
invalid_hostname_reject_code = 550
non_fqdn_reject_code = 550
unknown_address_reject_code = 550
unknown_client_reject_code = 550
unknown_hostname_reject_code = 550
unverified_recipient_reject_code = 550
unverified_sender_reject_code = 550

example.com은 자신의 도메인으로 변경해주세요

$ vim /etc/postfix/mysql-virtual-mailbox-domains.cf

user = mailuser
password = mailuserpass
hosts = 127.0.0.1
dbname = mailserver
query = SELECT 1 FROM virtual_domains WHERE name='%s'

$ vim /etc/postfix/mysql-virtual-mailbox-maps.cf

user = mailuser
password = mailuserpass
hosts = 127.0.0.1
dbname = mailserver
query = SELECT 1 FROM virtual_users WHERE email='%s'

$ vim /etc/postfix/mysql-virtual-alias-maps.cf

user = mailuser
password = mailuserpass
hosts = 127.0.0.1
dbname = mailserver
query = SELECT destination FROM virtual_aliases WHERE source='%s'

$ vim /etc/postfix/mysql-virtual-email2email.cf

user = mailuser
password = mailuserpass
hosts = 127.0.0.1
dbname = mailserver
query = SELECT email FROM virtual_users WHERE email='%s'

여기까지 설정 후 postfix를 재시작 해줍니다

$ sudo systemctl restart postfix

$ sudo postmap -q example.com mysql:/etc/postfix/mysql-virtual-mailbox-domains.cf
# 1
$ sudo postmap -q email1@example.com mysql:/etc/postfix/mysql-virtual-mailbox-maps.cf
# 1
$ sudo postmap -q alias@example.com mysql:/etc/postfix/mysql-virtual-alias-maps.cf
# email1@example.com

각각의 명령어를 실행해 본다면 주석으로 달아놓은 내용이 출력되게 됩니다.

해당 내용과 다르거나 오류가 발생한다면 다시 한번 설정 해보아 주시길 바랍니다

세번째 주석은 alias@example.com에 연결되는 destination메일이 출력된 것입니다.

$ sudo cp /etc/postfix/master.cf /etc/postfix/master.cf.orig

[main.cf](http://main.cf) 파일과 마찬가지로 복구를 위해 백업을 해주세요

$ vim /etc/postfix/master.cf

# Postfix master process configuration file.  For details on the format
# of the file, see the master(5) manual page (command: "man 5 master" or
# on-line: http://www.postfix.org/master.5.html).
#
# Do not forget to execute "postfix reload" after editing this file.
#
# ==========================================================================
# service type  private unpriv  chroot  wakeup  maxproc command + args
#               (yes)   (yes)   (yes)    (never) (100)
# ==========================================================================
smtp      inet  n       -       n       -       -       smtpd
#smtp      inet  n       -       -       -       1       postscreen
#smtpd     pass  -       -       -       -       -       smtpd
#dnsblog   unix  -       -       -       -       0       dnsblog
#tlsproxy  unix  -       -       -       -       0       tlsproxy
submission inet n       -       y      -       -       smtpd
  -o syslog_name=postfix/submission
  -o smtpd_tls_security_level=encrypt
  -o smtpd_sasl_auth_enable=yes
  -o smtpd_sasl_type=dovecot
  -o smtpd_sasl_path=private/auth
  -o smtpd_reject_unlisted_recipient=no
  -o smtpd_client_restrictions=permit_sasl_authenticated,reject
  -o milter_macro_daemon_name=ORIGINATING
smtps     inet  n       -       -       -       -       smtpd
  -o syslog_name=postfix/smtps
  -o smtpd_tls_wrappermode=yes
  -o smtpd_sasl_auth_enable=yes
  -o smtpd_sasl_type=dovecot
  -o smtpd_sasl_path=private/auth
  -o smtpd_client_restrictions=permit_sasl_authenticated,reject
  -o milter_macro_daemon_name=ORIGINATING
 ...

다음과 같이 smtp, submission, smtps 부분에 해당하는 line은 모두 주석 해제 해주세요

submission 밑의 -o(option), smtps 밑의 -o(option)부분도 모두 빠짐 없이 주석 해제해 주세요

그 후에 위의 코드와 다른 점이 있다면 똑같이 바꿔주세요

$ sudo chmod -R o-rwx /etc/postfix

/etc/postfix폴더의 권한을 설정해 주세요 other에 속한 유저들의 접근을 막기 위함 입니다.

$ sudo systemctl restart postfix

마지막으로 postfix를 재시작 해주세요

Dovecot


$ sudo cp /etc/dovecot/dovecot.conf /etc/dovecot/dovecot.conf.orig
$ sudo cp /etc/dovecot/conf.d/10-mail.conf /etc/dovecot/conf.d/10-mail.conf.orig
$ sudo cp /etc/dovecot/conf.d/10-auth.conf /etc/dovecot/conf.d/10-auth.conf.orig
$ sudo cp /etc/dovecot/dovecot-sql.conf.ext /etc/dovecot/dovecot-sql.conf.ext.orig
$ sudo cp /etc/dovecot/conf.d/10-master.conf /etc/dovecot/conf.d/10-master.conf.orig
$ sudo cp /etc/dovecot/conf.d/10-ssl.conf /etc/dovecot/conf.d/10-ssl.conf.orig

다음 명령어를 실행하여 백업을 해주세요

$ vim /etc/dovecot/dovecot.conf

## Dovecot configuration file
# ...
# Enable installed protocols
!include_try /usr/share/dovecot/protocols.d/*.protocol
protocols = imap imaps pop3 pop3s lmtp
# ...
postmaster_address=postmaster at example.com

protocols = ...이렇게 적혀있는 라인으로 가셔서 프로토콜을 추가해 주시고

!include_try부분을 주석 해제해 주세요

그 후에 마지막 줄로 가셔서 postmaster_address부분을 추가해 주세요

$ vim /etc/dovecot/conf.d/10-mail.conf

# ...
mail_location = maildir:/var/mail/vhosts/%d/%n/
# ...
mail_privileged_group = mail
# ...

다음과 같이 들어온 메일의 저장 위치를 지정해 줍니다

$ sudo mkdir -p /var/mail/vhosts/example.com

example.com은 자신의 도메인에 맞게 수정해 주세요

$ sudo groupadd -g 5000 vmail
$ sudo useradd -g vmail -u 5000 vmail -d /var/mail

5000번의 ID, vmail이라는 이름을 가진 그룹을 만들어 주시고 또 vmail이라는 이름을 가진 유저를 만들어 주세요 이 vmail 유저는 서버의 메일을 읽을 수 있게 지정할 것입니다

$ sudo chown -R vmail:vmail /var/mail

/var/mail폴더의 소유 그룹과 유저를 지정해줍니다

vmail:vmail은 유저:그룹이라고 생각해 주시면 됩니다

$ vim /etc/dovecot/conf.d/10-auth.conf

# ...
disable_plaintext_auth = yes
# ...
auth_mechanisms = plain login
# ...
!include auth-system.conf.ext
# ...
!include auth-sql.conf.ext
# ...

다음과 같이 주석 해제 및 수정해 주세요

파일 이름처럼 유저의 authentication에 대한 파일입니다

$ vim /etc/dovecot/conf.d/auth-sql.conf.ext

# ...
passdb {
  driver = sql
  args = /etc/dovecot/dovecot-sql.conf.ext
}
# ...
#userdb {
#  driver = sql
#  args = /etc/dovecot/dovecot-sql.conf.ext
#}
# ...
userdb {
  driver = static
  args = uid=vmail gid=vmail home=/var/mail/vhosts/%d/%n
}
# ...

다음과 같이 주석 해제 및 수정해 주세요

authentication과 storage information에 관련한 파일입니다

$ vim /etc/dovecot/dovecot-sql.conf.ext

# ...
driver = mysql
# ...
connect = host=127.0.0.1 dbname=mailserver user=mailuser password=mailuserpass
# ...
default_pass_scheme = SHA512-CRYPT
# ...
password_query = SELECT email as user, password FROM virtual_users WHERE email='%u';
# ...

다음과 같이 주석 해제 및 수정해 주세요

자신의 MySQL 연결에 관련한 파일입니다

dbname, user, password를 자신의 MySQL에 맞게 설정해 주세요

password_queryvirtual_users테이블에 있는 이메일 주소를 이메일 계정의 username 인증 정보로 사용합니다

aliasusername으로 사용하기 위해서는 virtual_aliases 테이블에 sourcedestination이메일 주소를 추가해 주세요. 그 후에 위의 password_query를 다음과 같이 바꿔주세요

password_query = SELECT email as user, password FROM virtual_users 
                 WHERE email=(SELECT destination FROM virtual_aliases 
                              WHERE source = '%u');
# 한줄로 작성해주세요

$ sudo chown -R vmail:dovecot /etc/dovecot
$ sudo chmod -R o-rwx /etc/dovecot

/etc/dovecot폴더의 소유자 및 그룹 그리고 권한을 다음과 같이 변경해 주세요

$ vim /etc/dovecot/conf.d/10-master.conf

# ...
service imap-login {
  inet_listener imap {
    port = 0
  }
  inet_listener imaps {
    port = 993
    ssl = yes
  }
  # ...
}
# ...
service pop3-login {
  inet_listener pop3 {
    port = 0
  }
  inet_listener pop3s {
    port = 995
    ssl = yes
  }
}
# ...

저희는 imappop3대신 imapspop3s를 사용할 것이기 때문에 imappop3의 포트 번호를 0으로 수정해 주세요

# ...
service lmtp {
  unix_listener /var/spool/postfix/private/dovecot-lmtp {
    #mode = 0666i
    mode = 0600
    user = postfix
    group = postfix
  }
# ...
}

그리고 service lmtp부분을 찾아서 위와 같이 변경해 주세요

# ...
service auth {
  # ...
  unix_listener /var/spool/postfix/private/auth {
    mode = 0660
    user = postfix
    group = postfix
  }

  unix_listener auth-userdb {
    mode = 0600
    user = vmail
  }
# ...
  user = dovecot
}
# ...

service auth부분도 위와 같이 변경해 주세요

# ...
service auth-worker {
  # ...
  user = vmail
}

service auth-worker부분도 다음과 같이 변경후 저장해 주세요

$ vim /etc/dovecot/conf.d/10-ssl.conf

# ...
# SSL/TLS support: yes, no, required. <doc/wiki/SSL.txt>
ssl = required
# ...
ssl_cert = </etc/letsencrypt/live/example.com/fullchain.pem
ssl_key = </etc/letsencrypt/live/example.com/privkey.pem

example.com을 자신의 도메인에 맞게 변경해 주세요

$ sudo systemctl restart dovecot

dovecot을 재시작해 주세요

POP3S 접속 테스트


$ openssl s_client -showcerts -connect mail.your-domain.com:995

user user-email
+OK

pass password
+OK Logged in.

list
1 2646
2 2728
# ...
# (mail-id) (mail-size)

retr 1
# ... mail contents
# retr (mail-id)

stat
+OK 23 57836
# (mail-counts) (mail-size-sum)

quit
+OK Loggin out.

IMAPS의 포트 번호는 993입니다

IMAPS의 명령어는 POP3S의 명령어와 다릅니다

Nginx + HTTPS + Nodejs


Nginx Installation

$ sudo wget http://nginx.org/keys/nginx_signing.key
$ sudo apt-key add nginx_signing.key
$ sudo apt update
$ sudo apt install nginx

Nginx가 가동 중인 것을 확인하고 시스템 재시작시에 자동으로 시작하게 만들어 주세요

$ sudo systemctl start nginx
$ sudo systemctl enable nginx

NodeJS 설치 방법은 1편에 있으니 스킵 하도록 하겠습니다

NodeJS express앱을 만들어 주세요

// app.js
const express = require('express');
const app = express();

app.get('/', (req, res) => res.send('Hello World!'));
app.listen(3000, () => console.log('Node.js app listening'));

Nginx 리버스 프록시 설정

$ vim /etc/nginx/sites-available/node-server

server {
  listen 443 ssl;
  server_name www.example.com;
  ssl_certificate /etc/letsencrypt/live/www.example.com/fullchain.pem;
  ssl_certificate_key /etc/letsencrypt/live/www.example.com/privkey.pem;
  location / {
    proxy_pass http://127.0.0.1:3000;
  }
}

www.example.com 도메인으로 1편에서 mail.example.com으로 letsencrypt를 활용하여 ssl인증서를 받았던 방법 그대로 www.example.com으로도 인증서를 받아줍니다

$ sudo ln -s /etc/nginx/sites-available/node-server /etc/nginx/sites-enabled/node-server

nginx에서는 sites-available에 있는 파일을 소프트 심볼릭 링크로 sites-enabled폴더 내에 넣는 방식을 택하고 있습니다. 똑같이 저희가 만든 설정 파일을 심볼릭 링크로 sites-enabled내에 넣어 줍니다.

HTTPS 설정을 해주었으니 HTTP를 통해 들어오는 요청은 HTTPS로 리다이렉션 시켜주려 합니다

$ vim /etc/nginx/sites-available/default

server {
  listen 80 default_server;
  listen [::] 80 default_server;
  server_name www.daitnu.com;
  location / {
    return 301 https://www.daitnu.com;
  }
}

80 PORT로 들어오는 요청은 응답코드를 301로, 리다이렉션 주소는 https://www.daitnu.com

이라는 의미입니다

응답코드 301(영구이동) - 요청한 페이지를 새 위치로 영구적으로 이동했다. GET 또는 HEAD 요청에 대한 응답으로 이 응답을 표시하면 요청자가 자동으로 새 위치로 전달된다.

여기까지 설정하였으면 Nginx에 관련된 설정은 모두 마치셨습니다

Nginx를 재시작해 주세요

$ sudo systemctl restart nginx

Postfix Filter를 이용한 Mail Hooks(Shell) 만들기


$ vim /etc/postfix/master.cf

smtp      inet  n       -       y       -       -       smtpd
  -o content_filter=filter:dummy
#smtp      inet  n       -       y       -       1       postscreen
# ...
lmtp      unix  -       -       y       -       -       lmtp
anvil     unix  -       -       y       -       1       anvil
scache    unix  -       -       y       -       1       scache
filter    unix  -       n       n       -       10      pipe
  flags=Rq user=filter null_sender=
  argv=/var/spool/filter/filename.sh -f ${sender} -- ${recipient}

/etc/postfix/master.cf 파일에filter부분을 추가해 줍니다

filename.sh은 원하시는 파일 명으로 바꾸어 주세요

$ sudo useradd filter
$ mkdir /var/spool/filter

filter라는 유저를 만들어 준 후에 /var/spool/filter폴더를 만들어 줍니다

$ vim /var/spool/filter/filename.sh

#!/bin/sh

# Simple shell-based filter. It is meant to be invoked as follows:
#       /path/to/script -f sender recipients...

# Localize these. The -G option does nothing before Postfix 2.3.
INSPECT_DIR=/var/spool/filter
SENDMAIL="/usr/sbin/sendmail -G -i" # NEVER NEVER NEVER use "-t" here.

# Exit codes from <sysexits.h>
EX_TEMPFAIL=75
EX_UNAVAILABLE=69

# Clean up when done or when aborting.
trap "rm -f in.$$" 0 1 2 3 15

# Start processing.
cd $INSPECT_DIR || {
    echo $INSPECT_DIR does not exist; exit $EX_TEMPFAIL; }

cat >in.$$ || {
    echo Cannot save mail to file; exit $EX_TEMPFAIL; }

# Specify your content filter here.
$INSPECT_DIR/shell.sh <in.$$ || {
   echo Message content rejected; exit $EX_UNAVAILABLE; }

$SENDMAIL "$@" <in.$$ || {
   echo Unable to send mail; exit $EX_UNAVAILABLE;
}

exit $?

여기까지 작성했다면 이제 자신의 도메인으로 메일이 들어오면 $INSPECT_DIR/shell.sh파일을 실행하라는 명령어를 작성했다라고 생각하시면 됩니다

이제 shell.sh 파일에서 메일을 어떻게 받을 수 있는지에 대하여 알아보겠습니다

$ vim /var/spool/filter/shell.sh

#!/bin/sh

cat $1 > asd            # -- 1번
node test.js "`cat $1`" # -- 2번

메일은 쉘에서 $1으로 들어오게 되는데 파일로 들어오게 됩니다

그렇기 때문에 파일의 내용을 출력해 줄 cat이라는 명령어를 사용해 주었습니다

1번은 들어온 메일의 내용을 asd라는 파일에 작성하는 예제입니다(리디렉션)

2번은 test.js파일에서 메일을 하나의 인자로 받아 사용하는 예제입니다

NodeJS에서 인자를 받는 방법은 여기를 참고해주세요

여기까지 하셨다면 마지막 한가지 작업인 소유자 변경을 해주시면 됩니다

저희는 /etc/postfix/master.cf파일 내에서 filter설정해 줄 때 userfilter로 설정해 주었습니다

이 말은 filter라는 유저가 $INSPECT_DIR/shell.sh파일을 실행 해달라는 것을 의미하기 때문에 소유자를 filter로 바꾸어 주셔야 메일 서버가 메일을 전송 받았을 때 filter라는 유저로 들어와서 $INSPECT_DIR/shell.sh 파일을 실행할 수 있게 됩니다

$ sudo chown -R filter:filter /var/spool/filter

위의 명령어로 filter 폴더를 포함한 하위에 존재하는 전체 파일을 filter유저의 소유로 바꾸어 줍니다 이렇게까지 설정하시고 마지막으로 postfixdovecot을 재실행 시켜 주시면 메일 서버에 대한 모든 설정을 마치신 것입니다

$ sudo systemctl restart postfix
$ sudo systemctl restart dovecot

감사합니다 (_ _)

References


Email with Postfix, Dovecot, and MySQL

Node js에 관한 것 아무거나 3편, Node에서 NGINX를 리버스 프록시로 사용하기 (번역)

nginx 에 HTTPS/SSL 적용하기

Nginx를 사용하여 프록시 서버 만들기

Processing Emails with a script in Postfix

Postfix After-Queue Content Filter

HTTP 상태 코드

profile
부스트캠프 4기 멤버십 6조 개발노트

0개의 댓글