이 문서는 MongoDB Community Edition 를 리눅스 플랫폼에서 시작과 운영에 필요한 구성 파일 mongod.conf 의 설정을 다루고 있다. 이를 통해 데이터베이스 서비스를 동작시키고, 인증한 사용자로서 클라이언트 프로그램으로 접속하기 위한 기본 인증방식을 구성하는 것을 정리하고 있다.
이 문서는 Arm64 기반 CPU를 사용하는 Raspberry Pi, Odroid, PINE64, OrangePi 등 SBC 지원 보드 계열 위에서 Ubuntu/Debian 에서 설치 및 사용 가능한 MongoDB Community Edition 4.2 버전을 설치하고 구성하는 과정을 정리하고 있다.
이 문서는 Ubuntu/Debian 계열 정규 배포본에 3.x 버전을 지원하지 않는 플랫폼에 MongoDB Community Edition 3.6 버전을 설치하는 과정을 정리하고 있다. 내용의 기초는 MongoDB Community Edition 3.6 버전을 Amd64, Arm64 지원하는 64bit OS에 설치해 사용하기 위해서 Install MongoDB Community Edition, on-ubuntu를 따라서 진행하고 경험상 필요한 부분을 추가로 정리했다.
awk란 이름은 이 유틸리티를 작성한 A.V.Aho, P.J. Weinberger, B. Kernigham의 머리글자를 따온 것으로 주로 패턴의 검색과 조작을 주목적으로 만들어진 것이다. 즉 파일의 각 줄에 필드(field)를 인식할 수 있는 패턴 매칭 기능을 가지고 이들 필드를 자유자재로 조작 가능한 유틸리티를 작성하고자 만든 것이다.
| 패턴 | 설명 | | —————— | ——————————————————————————————————————————————————————————————– | — | ————————————————————————————————————————— | | BEGIN | 입력화일을 읽어들이기 전에 옆에 제시되는 문자을 실행시키도록 한다. | | END | awk가 모든 입력을 처리한 후, 옆에 제시되는 문장을 실행시키도록 한다. | | expression | 식을 평가한 후 이 식이 참, 즉 non-zero이거나 non-null인 경우 문장을 실행한다. | | /re/ | 정규식과 일치하는 문자열을 포함하고 있는 라인에서 문장을 실행한다. | | compound-pattern | 복합패턴이라는 것으로 &&(and), | | (or) , !(not) 그리고 괄호에 의해 연결시킨 것이다. expression의 경우와 마찬가지로 복합 패턴도 참인 경우의 문장을 실행시킨다. | | pattern1, pattern2 | 이러한 패턴을 범위 패턴이라 한다. 현재 처리되고 있는 라인이 pattern1과 일치되고, 다음에 따라오 는 라인 중 임의의 라인이 pattern2와 일치할 때, 범위 패턴은 두 라인 사이의 각 라인과 일치한다. |
awk에서 찾은 내용은 다음 변수에 저장되어 있다.
변수
내 용
FILENAME
현재 처리되고 있는 입력 파일의 이름
FS
입력 필드 분리문자
NR
현재 레코드(행)의 번호
NF
현재 레코드(행)의 필드의 갯수
OFS
출력되는 필드의 분리문자
auth.log 패턴 분석
1 2
Apr 16 06:43:04 homepi sshd[20198]: User root from 222.73.37.31 not allowed because not listed in AllowUsers Apr 16 06:43:07 homepi sshd[20198]: Failed password for invalid user root from 222.73.37.31 port 41030 ssh2
sshd 접속하는 root 접속 요청을 찾으려면,
1
awk '/sshd|root/' /var/log/auth.log # sshd,root 가 있는 줄을 출력
awk '/^north/' datafile # north로 시작하는 줄 출력 awk '/^(no | so)/' datafile : no 또는 so 로 시작하는 줄 출력
awk '$5 ~ /\.[7-9]+/' datafile : 다섯 번째 필드가 마침표 다음엣 7과 9사이 숫자가 하나 이상 나오는 레코드 출력 awk '$2 !~ /E/ { print $1, $2 }' datafile : 두 번째 필드에 E 패턴이 없는 레코드의 첫 번째와 두 번째 필드 출력 awk '$3 ~ /^Joel/{ print $3 " is a nice guy."} ' datafile : 세 번째 필드가 Joel로 시작하면 " is a nice guy"와 함께 출력 awk '$8 ~ /[0-9][0-9]$/ { print $8 }' datafile : 여덟 번째 필드가 두 개의 숫자이면 그 필드가 출력 awk '$4 ~ /Chin$/ { print "The price is $" $8 "." }' datafile : 네 번째 필드가 Chine으로 끝나면 "The price is $" 8번 필드 및 마침표가 출력 awk -F: '{ print $1 } ' datafile : -F 옵션은 입력 필드를 ':'로 구별. awk -F"[ :]"'{ print $1, $2 } ' datafile : 입력 필드로 스페이스와 ':'를 필드 구별자로 사용 awk -f awk_script.file datafile : -f 옵션은 awk 스크립트 파일 사용할 때 씀.
① expressions ② print expression-list ③ printf(format, expression-list) ④ if (expression) statement ⑤ if (expression) statement else statement ⑥ while (expression) statement ⑦ for (expression; expression; expression) statement ⑧ for (variable in array) statement ⑨ do statement while (expression) ⑩ break ⑪ continue ⑫ next ⑬ exit ⑭ exit expression ⑮ {statement}
jail.conf: jail 이라 불리는 모니터링할 대상에 대한 기본 옵션과 행위를 선언한다.
action.d/iptables-multiport.conf: fila2ban 이 jail에 맞게 거부(Ban)한 IP를 다루는 기본 액션이다.
fail2ban.local : fail2ban 주요 설정 파일
jail.local: jail 설정 파일
jaild.d/defaults-debian.conf: jail enable/disable
paths-common.conf: 로그 파일 경로
paths-debian.conf: 로그 파일 경로
설정
fail2ban은 jail 을 구성하고 jail의 filter 그리고 action으로 나뉘어 있다.
fail2ban.conf 구성
fail2ban.conf는 기본 구성 변수로 loggin, socket 그리고 PID 파일 등등이 설정된다. 별도의 파일로 Jail을 구성할 때 fail2ban.local 같은 이름을 사용하고 새로 설정되는 값은 기본 설정 값을 재정의 하게 된다.
단 같은 [default] 섹션이 존재하면 구성된 내용 적용이 잘 안된다.
다음 스크립을 사용하면 모둔 변수를 주석 처리하고 수정할 옵션만 복사해 준다.
1
sed 's/\(^[[:alpha:]]\)/# \1/' fail2ban.conf | sudo tee fail2ban.local 1&> /dev/null
fail2ban.local 파일은 다음과 같은 내용을 담을 것이다.
loglevel: The level of detail that Fail2ban’s logs provide can be set to 1 (error), 2 (warn), 3 (info), or 4 (debug).
logtarget: Logs actions into a specific file. The default value of /var/log/fail2ban.log puts all logging into the defined file. Alternately, you can change the value to STDOUT, which will output any data; STDERR, which will output any errors; SYSLOG, which is message-based logging; and FILE, which outputs to a file.
socket: The location of the socket file.
pidfile: The location of the PID file.
jail.conf
/etc/fail2ban/jail.conf 는 데몬, 서비스에 대한 jail을 구성한다. jail은 log를 읽어 불필요한 것을 찾아 낸다. 다음은 jail.conf에서 주석이 달린 jail.local을 생성해 준다.
1
sed 's/\(^[[:alpha:]]\)/# \1/' jail.conf | sudo tee jail.local 1&> /dev/null
If using CentOS or Fedora open jail.local and set the backend to systemd. This is not necessary on Debian 8, even though it is a SystemD system.
/etc/fail2ban/jail.local
1
backend = systemd
화이트리스트 IP
먼저 검출된 IP 중에 무시할 영역, 화이트리스트를 선언해 줍니다. 리스트는 ‘,’로 구분하고 서브넷 혹은 IP주소를 입력한다.
1 2
[DEFAULT] ignoreip = 127.0.0.1/8 192.168.0.1/24
차단 시간과 재시도 횟수
bantime, findtime, maxretry 은 차단 시간에 대한 구성이다.
1 2 3
bantime = 2592000 findtime = 600 maxretry = 3
bantime: 검출된 IP가 접속 차단 시간을 초단위로 선언해 준다. -1 이면 영속적으로 밴 된다.
fail2ban에 검출되는 jail이 있으면 이메일 설정에 따라 메일로 경고를 받을 수 있다.
destemail: The email address where you would like to receive the emails.
sendername: The name under which the email shows up.
sender: The email address from which Fail2ban will send emails.
그리고 action 설정을 조절할 필요가 있다, 이것은 ban 상황이 기준점에 닿으면 발생한다. 기본 액션 %(action_)s은 사용자만 ban 한다. action_mw 액션은 ban을 실행하고 WhoIS 리포트로 메일을 보내준다. action_mwl은 모든 로그까지 함께 보내준다.
You will also need to adjudst the action setting, which defines what actions occur when the threshold for ban is met. The default, %(action_)s, only bans the user. action_mw will ban and send an email with a WhoIs report; while action_mwl will ban and send an email with the WhoIs report and all relevant lines in the log file. This can also be changed on a jail-specific basis.
1
action = %(action_)s
1
$ sudo service fail2ban restart
각 서버스에 대한 Jail 설정
필터를 이용해 Jail을 만들어 의심스런 접근을 막아 보자. 앞서 복사한 jail.local 파일에는 주요 서비스가 모두 선언되어 있고 sshd 만 활성화 되어 있다.
enabled: Determines whether or not the filter is turned on.
port: The port Fail2ban should be referencing in regards to the service. If using the default port, then the service name can be placed here. If using a non-traditional port, this should be the port number. For example, if you moved your SSH port to 3456, you would replace ssh with 3456.
filter: The name of the file located in /etc/fail2ban/filter.d that contains the failregex information used to parse log files appropriately. The .conf suffix need not be included.
logpath: Gives the location of the service’s logs.
maxretry: Will override the global maxretry for the defined service. findtime and bantime can also be added. action: This can be added as an additional setting, if the default action is not suitable for the jail. Additional actions can be found in the action.d folder.
각 서비스에 대한 jail은 jail.d에 설정 파일을 구성해도 된다.
(1) sshd
Brute-force Attack과 같은 접근을 차단하는 필터로 로그에 아래와 유사한 패턴이 나오면 IP를 검출한다.
Jul 22 06:56:50 foo sshd[14984]: Failed password for invalid user a from xxx.xxx.xxx.xxx port 55452 ssh2
jail.config 혹은 jail.local 에서 기본으로 활성화 되어 있다.
(2) ssh-ddos
sshd-ddos Filter를 사용해 SSH Service를 Scanning하거나 telnet으로 접속할 떄 발생하는 Message를 검사하여 해당 IP의 접근을 차단할 수 있습니다.
이 Filter로 검출되는 /var/log/auth.log의 Message는 다음과 같습니다.
Jul 23 13:16:25 foo sshd[21989]: Did not receive identification string from xxx.xxx.xxx.xxx
Jail 설정을 위해서 다음과 같이 입력합니다.
1 2
[sshd-ddos] enabled = true
혹은 $ sudo vi /etc/fail2ban/jail.d/sshd-ddos.conf
1
$ sudo service fail2ban restart
Failregrexs
다양한 필터를 사용할 수있다. 의심스런 동작을 Filter로 선언해서 사용하는데 해당 필터를 점검해야할 필요가 있다. 다음
$ sudo fail2ban-client status Status |- Number of jail: 6 `- Jail list: nginx-noproxy, nginx-noscript, nginx-nohome, nginx-badbots, ssh-ddos, ssh
그리고 iptable의 서비스로 방화벽 규칙에 fail2ban 규칙이 동작중인지 확인한다.
1 2 3 4 5 6 7 8 9 10 11 12
$ sudo iptables -S ...
-A fail2ban-nginx-badbots -j RETURN -A fail2ban-nginx-nohome -j RETURN -A fail2ban-nginx-noproxy -j RETURN -A fail2ban-nginx-noscript -j RETURN -A fail2ban-ssh -j RETURN -A fail2ban-ssh-ddos -j RETURN
...
그리고 fail2ban 의 jail 실행 상태를 자세히 보고 싶므면 status 뒤에 jail 이름을 주면 된다.
1 2 3 4 5 6 7 8 9 10
$ sudo fail2ban-client status nginx-badbots Status for the jail: nginx-badbots |- filter | |- File list: /var/log/nginx/access.log | |- Currently failed: 0 | `- Total failed: 0 `- action |- Currently banned: 0 | `- IP list: `- Total banned: 0
Testing
의심스런 동작을 Filter로 선언해서 사용하는데 해당 필터를 점검해야할 필요가 있다. 다음
nginx 인증 요구시 잘못된 인증을 시도하면 fail2ban 규칙에 따라 접근이 금지당한다. 그리고 jail 규칙이 잘 적용 됐는지 결과를 다음 같이 확인할 수 있다:
1 2 3 4 5 6 7 8 9 10 11
$ sudo fail2ban-client status nginx-http-auth Output Status for the jail: nginx-http-auth |- filter | |- File list: /var/log/nginx/error.log | |- Currently failed: 0 | \- Total failed: 12 \- action |- Currently banned: 1 | \- IP list: 111.111.111.111 \- Total banned: 1
인증 규칙에 어긋나는 접근을 시도한 IP인 111.111.111.111을 확인 할 수 잇다. 금지된 IP는 해당 jail을 이용해 다음 같이 해제할 수 있다.
1
$ sudo fail2ban-client set nginx-http-auth unbanip 111.111.111.111
MongoDB 설치후 데이터베이스 위치, 로그, 인증 등에 관련한 서버 구성과 설정을 정리한다.
MongoDB 2.6 과 MongoDB Community Edition 3.x 버전을 사용했다.
mongoDB 접근제어
mongoDB 는 설치과정 중에 인증과 관련해 설정하는 부분이 없어서 설치 후 누구나 DB에 접속 할 수 있다. 인증을 추가해 데이터베이스 관리자와 데이터베이스 사용자로 구분해서 이용하고, 각 데이터베이스의 사용자는 허가된 역할(Role)을 가지고 데이터베이스에 접근 가능하도록 구성한다.