ex 1) iptables -t nat -A PREROUTING -j DNAT -p tcp --dport 22222 --to-destination 172.27.0.208:22
해석 NAT 테이블을 사용하여 PREROUTING 정책을 추가한다(DNAT), 매치되는 22222포트를 사용하는 패킷은 DNAT로 처리하고 타겟은 172.27.0.208:22로 한다.
ex 2) iptables -t nat -A POSTROUTING -j SNAT -o eth0 -d 172.27.0.0/24 --to-source 172.27.0.162
해석 NAT 테이블을 사용하여 POSTROUTING 정책을 추가한다(SNAT), eth0 인터페이스로 나가는 172.27.0.0/24의 모든 ip 대역은 172.27.0.162의 주소로 변환된다.
테이블 : 사용할 테이블 기본은 filter
filter : 방화벽
nat : 주소 변환
mangle : 패킷 데이터 변경 특수 규칙 OR 성능향상 TOS
raw : 넷필터의 연결추적 하위시스템과 독립적 동작 규칙
액션 : 정책의 변경 추가 삭제 등
-A : APPEND 정책 추가
-I : INSERT 정책 삽입
-D : DELETE 정책 삭제
-R : REPLACE 정책 교체
-F : FLUSH 모든 정책 삭제
-P : POLICY 기본 정책 설정
-:L : LIST 정책 나열
체인 : 정책의 대해 어떤 행동을 취할 것인가?
INPUT : 호스트를 향한 모든 패킷 (입력)
OUTPUT : 호스트에서 발생하는 모든 패킷 (출력)
FORWARD : 호스트가 목적지가 아닌 패킷, 경유지 (라우터)
PREROUTING : 외부 패킷의 목적지 변경 INPUT으로 가야할 패킷을 FORWARDING
POSTROUTING : 패킷이 OUTPUT에서 ip , port를 변경
매치 : 출발지, 목적지, 인터페이스 등 지정
-s : 출발지 매칭, 도메인 IP 주소 ,넷마스크 값을 이용하여 표기 (--source, --src)
-d : 목적지 매칭, 도메인 IP 주소, 넷마스크 값을 이용하여 표기 (--destination, --dst)
-p : 프로토콜과 매칭 대소문자는 구분하지 않음 ( TCP, UDP, ICMP 등)
-i : 입력 인터페이스와 매칭 ( --in-interface)
-o : 출력 인터페이스와 매칭 (--out-interface)
-j : 매치되는 패킷을 어떻게 처리할지 지정 (--jump)
타겟 : 패킷이 규칙과 일치할 때 매치가 취하는 정책
ACCEPT : 패킷 허용
DROP : 패킷을 버림
REJECT : 패킷을 버리고 응답 패킷 전송
LOG : 패킷을 syslog에 기록
SNAT --to [주소] : 소스 IP를 변환
DNAT --to [주소] : 목적지 IP를 변환
RETURN : 호출 체인 내에서 패킷 처리를 계속함
참조 nat 기능 사용 시, /etc/sysctl.conf에 net.ipv4.ip_forward=1 추가해야함
자주 사용하는 명령어 1. iptables -nL -t {테이블} : 테이블 조회 2. iptables -F -t {테이블} : 테이블 초기화 3. iptables save > /etc/sysconfig/iptables : 정책 저장 4. iptables -t {테이블} -L {정책} --line-numbers : 테이블의 정책을 번호로 출력 5. iptables -t {테이블} -D {정책} 숫자 : 선택한 테이블의 정책 삭제
# CentOS-Base.repo
#
# The mirror system uses the connecting IP address of the client and the
# update status of each mirror to pick mirrors that are updated to and
# geographically close to the client. You should use this for CentOS updates
# unless you are manually picking other mirrors.
#
# If the mirrorlist= does not work for you, as a fall back you can try the
# remarked out baseurl= line instead.
#
#
[base]
name=CentOS-$releasever - Base
mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=os&infra=$infra
#baseurl=http://mirror.centos.org/centos/$releasever/os/$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
#released updates
[updates]
name=CentOS-$releasever - Updates
mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=updates&infra=$infra
#baseurl=http://mirror.centos.org/centos/$releasever/updates/$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
#additional packages that may be useful
[extras]
name=CentOS-$releasever - Extras
mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=extras&infra=$infra
#baseurl=http://mirror.centos.org/centos/$releasever/extras/$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
#additional packages that extend functionality of existing packages
[centosplus]
name=CentOS-$releasever - Plus
mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=centosplus&infra=$infra
#baseurl=http://mirror.centos.org/centos/$releasever/centosplus/$basearch/
gpgcheck=1
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
- 카카오
[base]
name=CentOS-$releasever - Base
baseurl= http://mirror.kakao.com/centos/$releasever/os/$basearch/
gpgcheck=1
enabled=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
#released updates
[updates]
name=CentOS-$releasever - Updates
baseurl= http://mirror.kakao.com/centos/$releasever/updates/$basearch
gpgcheck=1
enabled=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
#additional packages that may be useful
[extras]
name=CentOS-$releasever - Extras
baseurl= http://mirror.kakao.com/centos/$releasever/extras/$basearch
gpgcheck=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
#additional packages that extend functionality of existing packages
[centosplus]
name=CentOS-$releasever - Plus
baseurl= http://mirror.kakao.com/centos/$releasever/centosplus/$basearch
gpgcheck=1
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
- 네이버
[base]
name=CentOS-$releasever - Base
baseurl=https://mirror.navercorp.com/centos/$releasever/os/$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
#released updates
[updates]
name=CentOS-$releasever - Updates
baseurl=https://mirror.navercorp.com/centos/$releasever/updates/$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
#additional packages that may be useful
[extras]
name=CentOS-$releasever - Extras
baseurl=https://mirror.navercorp.com/centos/$releasever/extras/$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
#additional packages that extend functionality of existing packages
[centosplus]
name=CentOS-$releasever - Plus
baseurl=https://mirror.navercorp.com/centos/$releasever/centosplus/$basearch/
gpgcheck=1
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
OpenSSL 1.1.0 changed the behavior of install rules. You should specify both --prefix and --openssldir to ensure make install works as expected. The takeaway is /usr/local/ssl is used by default, and it can be overridden with both --prefix and --openssldir. The rule of thumb applies for path overrides: specify both --prefix and --openssldir.
해당 문서를 참고하였을 때, 1.1.0 이상 버전을 설치 할 때는 prefix와 openssldir을 지정하여야 작동 확인이 가능하다고 명시되어 있습니다. 따라서 되도록이면 경로 지정을 하는게 좋습니다.
prefix : OpenSSL을 설치 할 디렉토리 openssldir : OpenSSL에 구성될 기본 인증서 및 키 저장소
zlib의 경우 데이터 압축으로 인해 네트워크의 전송 데이터를 줄일 수 있고, SSL/TLS 이전 버전의 호환성을 유지 할 수 있지만, CRIM 공격에 취약하므로 zlib는 사용하지 않겠습니다.
[root@test123 openssl-1.1.1w]# ./config --prefix=/usr/local/openssl --openssldir=/usr/local/ssl no-ssl2 no-ssl3
Operating system: x86_64-whatever-linux2
Configuring OpenSSL version 1.1.1w (0x1010117fL) for linux-x86_64
Using os-specific seed configuration
Creating configdata.pm
Creating Makefile
**********************************************************************
*** ***
*** OpenSSL has been successfully configured ***
*** ***
*** If you encounter a problem while building, please open an ***
*** issue on GitHub <https://github.com/openssl/openssl/issues> ***
*** and include the output from the following command: ***
*** ***
*** perl configdata.pm --dump ***
*** ***
*** (If you are new to OpenSSL, you might want to consult the ***
*** 'Troubleshooting' section in the INSTALL file first) ***
*** ***
**********************************************************************
[root@test123 openssl-1.1.1w]# make && make test
OpenSSL의 경로는 /bin/openssl, 버전은 CentOS7 기본 배포 버전인 OpenSSL 1.0.2k-fips 입니다.
요구사항을 모두 갖추었으니, 컴파일을 진행하겠습니다.
./configure --prefix=패키지를 설치 할 경로 --with-ssl-dir=OpenSSL이 설치된 위치 --with-pam --sysconfdir=sshd 설정 경로 --with-kerberos5
./configure --prefix=/opt/openssh --with-pam --sysconfdir=/etc/ssh --with-kerberos5
make && make install
#--with-ssl-dir 옵션은 별도로 컴파일 설치를 하지 않았기에 생략하였습니다.
간혹 PAM이 작동하지 않을 경우에는 --with-md5-passwords 옵션을 추가하여 조치를 취할 수 있습니다.
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ WARNING: UNPROTECTED PRIVATE KEY FILE! @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Permissions 0640 for '/etc/ssh/ssh_host_rsa_key' are too open.
It is required that your private key files are NOT accessible by others.
This private key will be ignored.
Unable to load host key "/etc/ssh/ssh_host_rsa_key": bad permissions
Unable to load host key: /etc/ssh/ssh_host_rsa_key
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ WARNING: UNPROTECTED PRIVATE KEY FILE! @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Permissions 0640 for '/etc/ssh/ssh_host_ecdsa_key' are too open.
It is required that your private key files are NOT accessible by others.
This private key will be ignored.
Unable to load host key "/etc/ssh/ssh_host_ecdsa_key": bad permissions
Unable to load host key: /etc/ssh/ssh_host_ecdsa_key
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ WARNING: UNPROTECTED PRIVATE KEY FILE! @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Permissions 0640 for '/etc/ssh/ssh_host_ed25519_key' are too open.
It is required that your private key files are NOT accessible by others.
This private key will be ignored.
Unable to load host key "/etc/ssh/ssh_host_ed25519_key": bad permissions
Unable to load host key: /etc/ssh/ssh_host_ed25519_key
sshd: no hostkeys available -- exiting.
컴파일을 끝내고 설치까지 완료하니까 다음과 같은 오류 메시지가 출력되었습니다.
기본적으로 생성되어있는 SSH 키파일에 대한 권한 오류로 저는 별도로 수정하였습니다.
chmod 400 /etc/ssh/ssh_*
다음과 같이 버전 확인을 하였을 때, 정상적으로 설치된 것을 확인 할 수 있습니다.
/opt/openssh/bin/ssh -V
OpenSSH_9.3p2, OpenSSL 1.0.2k-fips 26 Jan 2017
맨 처음 openssh를 제거하였을 때, 변경되었던 기존 설정 값을 전부 원복하여 줍니다.
# $OpenBSD: sshd_config,v 1.100 2016/08/15 12:32:04 naddy Exp $
# This is the sshd server system-wide configuration file. See
# sshd_config(5) for more information.
# This sshd was compiled with PATH=/usr/local/bin:/usr/bin
# The strategy used for options in the default sshd_config shipped with
# OpenSSH is to specify options with their default value where
# possible, but leave them commented. Uncommented options override the
# default value.
# If you want to change the port on a SELinux system, you have to tell
# SELinux about this change.
# semanage port -a -t ssh_port_t -p tcp #PORTNUMBER
#
#Port 22
#AddressFamily any
#ListenAddress 0.0.0.0
#ListenAddress ::
HostKey /etc/ssh/ssh_host_rsa_key
#HostKey /etc/ssh/ssh_host_dsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
HostKey /etc/ssh/ssh_host_ed25519_key
# Ciphers and keying
#RekeyLimit default none
# Logging
#SyslogFacility AUTH
SyslogFacility AUTHPRIV
#LogLevel INFO
# Authentication:
#LoginGraceTime 2m
PermitRootLogin no
#StrictModes yes
#MaxAuthTries 6
#MaxSessions 10
#PubkeyAuthentication yes
# The default is to check both .ssh/authorized_keys and .ssh/authorized_keys2
# but this is overridden so installations will only check .ssh/authorized_keys
AuthorizedKeysFile .ssh/authorized_keys
#AuthorizedPrincipalsFile none
#AuthorizedKeysCommand none
#AuthorizedKeysCommandUser nobody
# For this to work you will also need host keys in /etc/ssh/ssh_known_hosts
#HostbasedAuthentication no
# Change to yes if you don't trust ~/.ssh/known_hosts for
# HostbasedAuthentication
#IgnoreUserKnownHosts no
# Don't read the user's ~/.rhosts and ~/.shosts files
#IgnoreRhosts yes
# To disable tunneled clear text passwords, change to no here!
PasswordAuthentication no
#PermitEmptyPasswords no
# Change to no to disable s/key passwords
#ChallengeResponseAuthentication yes
ChallengeResponseAuthentication no
# Kerberos options
#KerberosAuthentication no
#KerberosOrLocalPasswd yes
#KerberosTicketCleanup yes
#KerberosGetAFSToken no
#KerberosUseKuserok yes
# GSSAPI options
GSSAPIAuthentication yes
GSSAPICleanupCredentials no
#GSSAPIStrictAcceptorCheck yes
#GSSAPIKeyExchange no
#GSSAPIEnablek5users no
# Set this to 'yes' to enable PAM authentication, account processing,
# and session processing. If this is enabled, PAM authentication will
# be allowed through the ChallengeResponseAuthentication and
# PasswordAuthentication. Depending on your PAM configuration,
# PAM authentication via ChallengeResponseAuthentication may bypass
# the setting of "PermitRootLogin without-password".
# If you just want the PAM account and session checks to run without
# PAM authentication, then enable this but set PasswordAuthentication
# and ChallengeResponseAuthentication to 'no'.
# WARNING: 'UsePAM no' is not supported in Red Hat Enterprise Linux and may cause several
# problems.
UsePAM yes
#AllowAgentForwarding yes
#AllowTcpForwarding yes
#GatewayPorts no
X11Forwarding yes
#X11DisplayOffset 10
#X11UseLocalhost yes
#PermitTTY yes
#PrintMotd yes
#PrintLastLog yes
#TCPKeepAlive yes
#UseLogin no
#UsePrivilegeSeparation sandbox
#PermitUserEnvironment no
#Compression delayed
#ClientAliveInterval 0
#ClientAliveCountMax 3
#ShowPatchLevel no
#UseDNS yes
#PidFile /var/run/sshd.pid
#MaxStartups 10:30:100
#PermitTunnel no
#ChrootDirectory none
#VersionAddendum none
# no default banner path
#Banner none
# Accept locale-related environment variables
AcceptEnv LANG LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY LC_MESSAGES
AcceptEnv LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE LC_MEASUREMENT
AcceptEnv LC_IDENTIFICATION LC_ALL LANGUAGE
AcceptEnv XMODIFIERS
# override default of no subsystems
Subsystem sftp /usr/libexec/openssh/sftp-server
# Example of overriding settings on a per-user basis
#Match User anoncvs
# X11Forwarding no
# AllowTcpForwarding no
# PermitTTY no
# ForceCommand cvs server
Match User root
Banner /etc/ssh/banner_centos
- /etc/pam.d/sshd
#%PAM-1.0
auth required pam_sepermit.so
auth substack password-auth
auth include postlogin
# Used with polkit to reauthorize users in remote sessions
-auth optional pam_reauthorize.so prepare
account required pam_nologin.so
account include password-auth
password include password-auth
# pam_selinux.so close should be the first session rule
session required pam_selinux.so close
session required pam_loginuid.so
# pam_selinux.so open should only be followed by sessions to be executed in the user context
session required pam_selinux.so open env_params
session required pam_namespace.so
session optional pam_keyinit.so force revoke
session include password-auth
session include postlogin
# Used with polkit to reauthorize users in remote sessions
-session optional pam_reauthorize.so prepare
다음은 sshd 서비스를 다음과 같이 등록하였습니다.
cat <<EOF > /etc/systemd/system/sshd.service
[Unit]
Description=OpenSSH server 9.3p2
Wants=sshd-keygen.service
[Service]
ExecStart=/bin/sshd -D
ExecReload=/bin/kill -HUP $MAINPID
KillMode=process
Restart=on-failure
RestartSec=42s
[Install]
WantedBy=multi-user.target
EOF
[root@test123 ~]# systemctl daemon-reload
[root@test123 ~]# systemctl restart sshd
[root@test123 ~]# systemctl status sshd
● sshd.service - OpenSSH server 9.3p2
Loaded: loaded (/etc/systemd/system/sshd.service; disabled; vendor preset: enabled)
Active: active (running) since Tue 2023-09-19 15:20:03 KST; 15min ago
Main PID: 24446 (sshd)
CGroup: /system.slice/sshd.service
└─24446 sshd: /bin/sshd -D [listener] 0 of 10-100 startups