728x90
반응형

ALB는 대상 응답에 서버 헤더가 없는 경우에만 awselb/2.0 값을 갖는 서버 헤더 정보를 추가한다.

이 때 서버 헤더를 비활성화(enabled false)할 경우, 헤더 정보를 추가하지 않도록 설정하여 awselb/2.0과 같은 서버 정보가 노출되는 것을 방지할 수 있다.

 자동 스캐닝 도구나 공격자가 특정 서버 소프트웨어에서 발견된 취약점을 악용하는 것을 방지한다.

while true; do 
    echo "============= $(date '+%Y-%m-%d %H:%M:%S') ============="
    curl -k -I -w "time: %{time_total}s\n" https://ALB-1234567890.us-east-1.elb.amazonaws.com
    echo "====================================================="
    sleep 1
done

 

ALB server response header 설정(save changes) 후 적용되기까지 10초 정도 소요

- 리스너 단위 설정, Edit listener attributes

=====================================================
============= 2025-05-19 16:50:52 =============
HTTP/2 503 
server: awselb/2.0
date: Mon, 19 May 2025 07:50:53 GMT
content-type: text/html
content-length: 162

time: 0.582316s
=====================================================
============= 2025-05-19 16:50:54 =============
HTTP/2 503 
date: Mon, 19 May 2025 07:50:55 GMT
content-type: text/html
content-length: 162

time: 0.599829s
=====================================================

 

true: server header on

false: server header off

aws elbv2 modify-listener-attributes \
  --listener-arn ARN \
  --attributes Key="routing.http.response.server.enabled",Value=false

 

 

References:

[1] Application Load Balancer에 대한 HTTP 헤더 수정 - 헤더 비활성화 - https://docs.aws.amazon.com/ko_kr/elasticloadbalancing/latest/application/header-modification.html#disable-header
[2] AWS Application Load Balancer introduces header modification for enhanced traffic control and security - https://aws.amazon.com/about-aws/whats-new/2024/11/aws-application-load-balancer-header-modification-enhanced-traffic-control-security/
[3] Securing your web applications and optimizing their performance with AWS Application Load Balancer - https://aws.amazon.com/blogs/networking-and-content-delivery/securing-your-web-applications-and-optimizing-their-performance-with-aws-application-load-balancer/?nc1=h_ls

 

728x90
728x90

'Networking > AWS' 카테고리의 다른 글

[AWS] Direct Connect 설정  (0) 2025.05.19
[AWS] EC2 SSM Agent connection lost  (0) 2025.05.12
BIND server 구성  (0) 2025.04.17
[AWS] 사설 인증서 생성 및 등록  (0) 2025.04.16
[AWS] Create an IPAM pool with accounts in an organization  (0) 2025.04.10
728x90
반응형

DX 로케이션 경유하여 AWS와 사설 네트워크를 연결

AWS Cloud -(AWS 백본)- AWS DX location - IDC

 

1) DX 연결

: Connections > State: ordering > Accept

- Pending available: 계정과 물리 연결이 활성화됨

AWS Cloud - AWS DX <-> onPrem 간 호스팅 연결 활성화

 

2) Direct Connect Gateway(DXGW) 생성

: Direct Connect gateways > Create > dxgw1, ASN 65011

- DXGW - AWS DX

 

3) DXGW에 VGW(VGW1, VGW2) 연결

: 생성한 GW ID 클릭(dxgw1) > Gateway associations - Associate > Gateways: VGW1, VGW2

(Allowed prefiexs를 입력하지 않으면 자동으로 VPC1과 VPC2의 CIDR 대역이 자동으로 할당됨, DXGW는 이렇게 허용된 접두사를 온프렘(고객 라우터)으로 전파(광고)) > 5~7분 대기(State: associated로 변경됨)

- AWS Cloud 내 VPC - VGW - DXGW 연결

 

4) Private VIF 생성 (on DX1/DX2)

: Virtual Interfaces > Create > 인터페이스 유형 선택, dx1-pri-v157, connection/DXGW/VLAN, ASN(65000)

+ Additional settings: user/Amazon router peer IP, BGP 인증키 입력 후 생성

- AWS DX <-> onPrem connect 간 VIF 생성

 

5) 온프렘 라우터 설정 (VLAN 인터페이스 및 BGP Peering 설정)

# 라우터 버전 정보 확인
show version
# 설정 모드 진입
config terminal # or conf t
# 명령어 입력(exec) 모드로 나오기
end

 

라우터 콘솔 명령 - 인터페이스 IP 설정

- dot1Q: IEEE 802.1Q 표준, 802.1Q VLAN 태깅을 사용하여 VLAN 157에 대한 캡슐화 설정

# (config)#
interface InterfaceEthernet1.157
# (config-subif)#
encapsulation dot1Q 157
ip address 10.0.1.1 255.255.255.252
end

 

show ip interface brief
sh ip int br

 

Interface              IP-Address      OK? Method Status                Protocol
InterfaceEthernet1       unassigned      YES NVRAM  up                    up   
InterfaceEthernet1.157   10.0.1.1        YES manual up                    up

 

AWS 라우터까지 통신 확인

#ping 10.0.1.2
Type escape sequence to abort.
Sending 5, 100-byte ICMP Echos to 10.0.1.2, timeout is 2 seconds:
!!!!!
Success rate is 100 percent (5/5), round-trip min/avg/max = 1/1/2 ms

 

Your router peer IP: 10.0.1.1/30

Amazon router peer IP: 10.0.1.2/30

 

라우터에서 BGP peering 설정

- AWS console의 VIF 정보를 확인하여 BGP 설정

 

# AS 번호는 네트워크를 식별하는 고유 번호
# 64512-65534는 프라이빗 AS 번호 범위

# (config)#
# BGP 라우팅 프로세스 시작, 65000은 자신의 AS(Autonomous System) 번호
router bgp 65000
# (config-router)#
# BGP 피어(neighbor) 설정, 10.0.1.2: peer router의 ip 주소, 65011: 피어의 AS 번호
neighbor 10.0.1.2 remote-as 65011
neighbor 10.0.1.2 password BGPauthPW123!
# BGP로 광고할 네트워크 설정, 자신의 네트워크를 다른 AS에 알림
network 172.20.0.0 mask 255.255.0.0
end

 

 

 

(1) show ip bgp summary

AWS BGP peer 라우터(10.0.1.2)와 Peering이 정상적으로 이루어졌는지 확인

정상인 경우 'State/PfxRcd'에 전달받은 Prefix의 개수가 표시됨

# bgp peer(neighbor) 연결 상태
show ip bgp summary
# results
BGP router identifier 172.20.57.1, local AS number 65000
BGP table version is 4, main routing table version 4
3 network entries using 744 bytes of memory
3 path entries using 408 bytes of memory
2/2 BGP path/bestpath attribute entries using 576 bytes of memory
1 BGP AS-PATH entries using 24 bytes of memory
0 BGP route-map cache entries using 0 bytes of memory
0 BGP filter-list cache entries using 0 bytes of memory
BGP using 1752 total bytes of memory
BGP activity 3/0 prefixes, 3/0 paths, scan interval 60 secs
3 networks peaked at 18:02:26 May 14 2025 KST (4d19h ago)

Neighbor        V           AS MsgRcvd MsgSent   TblVer  InQ OutQ Up/Down  State/PfxRcd
10.0.1.2        4        65011   14335   15133        4    0    0 4d19h           2

 

(2) show ip bgp

AWS 측 라우터(10.0.1.2)로부터 전달받은 Prefix를 확인

VGW1와 VGW2에 연결된 VPC1와 VPC2의 CIDR 대역(10.1.1.0/24, 10.1.2.0/24)이 온프렘 라우터로 전파된 것 확인

# bgp로 전달 받은 경로
show ip bgp

BGP table version is 4, local router ID is 172.20.57.1
Status codes: s suppressed, d damped, h history, * valid, > best, i - internal, 
              r RIB-failure, S Stale, m multipath, b backup-path, f RT-Filter, 
              x best-external, a additional-path, c RIB-compressed, 
              t secondary path, L long-lived-stale,
Origin codes: i - IGP, e - EGP, ? - incomplete
RPKI validation codes: V valid, I invalid, N Not found

     Network          Next Hop            Metric LocPrf Weight Path
 *>   10.1.1.0/24      10.0.1.2                               0 65011 i
 *>   10.1.2.0/24      10.0.1.2                               0 65011 i
 *>   172.20.0.0       0.0.0.0                  0         32768 i

# 라우터에서 참조하는 라우팅 경로
show ip route

 

 

on-prem과 EC2 instance 통신 확인 (ping test)

- VPC(10.1.1.0/24) 내 EC2 인스턴스 IP 주소: 10.1.1.10

 

728x90
728x90
728x90
반응형

SSM Agent 서비스 상태 문제

  • SSM Agent 서비스가 중지되었거나 충돌이 발생했을 수 있음
  • 다음 명령어로 확인/재시작 가능:
# Amazon Linux, RHEL의 경우
sudo systemctl status amazon-ssm-agent
sudo systemctl restart amazon-ssm-agent

# 로그 확인
sudo tail -f /var/log/amazon/ssm/amazon-ssm-agent.log

# Ubuntu의 경우
sudo service amazon-ssm-agent status
sudo service amazon-ssm-agent restart

인스턴스 리소스 문제

  • 메모리 부족이나 CPU 과부하로 인해 Agent가 제대로 작동하지 않을 수 있음
  • 시스템 리소스 사용량 확인 필요

SSM Agent 버전 문제

  • Agent 버전이 오래되었거나 업데이트 중 문제가 발생했을 수 있음
  • 최신 버전으로 재설치 시도:
sudo yum install -y amazon-ssm-agent  # Amazon Linux
sudo apt-get install amazon-ssm-agent # Ubuntu

 

---

System Manager

VPC 엔드포인트 사용의 대체 방법은 관리형 인스턴스에서 아웃바운드 인터넷 액세스를 허용하는 것

이 경우 관리형 인스턴스는 다음 엔드포인트에 대한 HTTPS(포트 443) 아웃바운드 트래픽도 허용해야 한다.

  • ssm.region.amazonaws.com
  • ssmmessages.region.amazonaws.com
  • ec2messages.region.amazonaws.com

 

References

[1] Systems Manager용 VPC 엔드포인트를 사용하여 EC2 인스턴스의 보안 개선 - https://docs.aws.amazon.com/ko_kr/systems-manager/latest/userguide/setup-create-vpc.html

 

Systems Manager용 VPC 엔드포인트를 사용하여 EC2 인스턴스의 보안 개선 - AWS Systems Manager

온프레미스 방화벽을 사용하고 Patch Manager를 사용하려는 경우 해당 방화벽에서 적절한 패치 기준 엔드포인트에 대한 액세스도 허용해야 합니다.

docs.aws.amazon.com

 

728x90
728x90
728x90
반응형

개념

Mininet

네트워크 토폴로지를 하나의 컴퓨터 안에서 가상으로 생성할 수 있는 네트워크 시뮬레이터

- 실제 네트워크 장비 없이도, PC 하나만으로 가상의 호스트(PC), 스위치, 링크 등을 만들어서 실제 네트워크처럼 테스트할 수 있게 해주는 도구

- h1~h8 같은 가상 장치를 만들고, 이 장치들을 SDN 스위치에 연결해서, 네트워크 트래픽을 만들어주는 역할

 

Ryu

Python으로 만들어진 오픈소스 SDN 컨트롤러 프레임워크로, OpenFlow 같은 프로토콜을 통해 네트워크 장비를 제어한다.

- 네트워크의 두뇌. 예전엔 스위치가 알아서 패킷을 처리했지만, SDN에선 스위치가 먼저 컨트롤러(Ryu)에 물어보고, 그에 따라 동작

- MTD 알고리즘을 실행해서 IP 주소나 포트를 무작위로 바꾸고, 네트워크 흐름을 제어해서 스위치에 명령을 내림

 

Open vSwitch (OVS)

리눅스에서 돌아가는 가상 스위치 소프트웨어로, SDN 환경에서 OpenFlow 프로토콜을 지원한다.

- 실제 스위치를 쓰지 않고, 소프트웨어로 만든 스위치. 물리적인 네트워크 없이도 SDN 실험을 하기 위한 방안

- 가상 호스트들을 연결해주는 스위치 역할을 하며, Ryu 컨트롤러의 명령에 따라 패킷을 전송하거나 차단

 

1단계: EC2 인스턴스 생성

Amazon Machine Image (AMI): Ubuntu Server 24.04 LTS (HVM), SSD Volume Type

Instance type: t3.xlarge (4 vCPU, 16 GiB Memory)

SSD (8GiB gp3 Root volume, 3000 IOPS, Not encrypted)

 

- security group SSH 22 my ip / ICMP All

SSH로 EC2 접속

chmod 400 your-key.pem  # 권한 변경
ssh -i "your-key.pem" ubuntu@<EC2 퍼블릭 IPv4 주소>.compute-1.amazonaws.com

2단계: 실험 환경 설치

# 1. 필수 패키지 설치
sudo apt update
sudo apt install -y git python3-pip openvswitch-switch net-tools curl

# 2. Mininet 설치
git clone https://github.com/mininet/mininet
cd mininet

# pip3 install pycodestyle
sudo ./util/install.sh -a  # 모든 패키지 설치 옵션, 시간 소요 (3분 내외) -> Enjoy Mininet!

# or
# 핵심 패키지 설치
sudo apt update
sudo apt install -y openvswitch-switch openvswitch-common openvswitch-testcontroller \
    python3-pip python3-setuptools net-tools iproute2 curl git tcpdump

# Mininet 실행 스크립트 수동 설치
sudo make install

# Mininet 정상 동작 확인
sudo mn --test pingall

# 결과 예시:
# *** Ping: testing ping reachability
# h1 -> h2 h3 h4 ...
# *** Results: 0% dropped (28/28 received)
$ sudo mn --test pingall
*** Creating network
*** Adding controller
*** Adding hosts:
h1 h2 
*** Adding switches:
s1 
*** Adding links:
(h1, s1) (h2, s1) 
*** Configuring hosts
h1 h2 
*** Starting controller
c0 
*** Starting 1 switches
s1 ...
*** Waiting for switches to connect
s1 
*** Ping: testing ping reachability
h1 -> h2 
h2 -> h1 
*** Results: 0% dropped (2/2 received)
*** Stopping 1 controllers
c0 
*** Stopping 2 links
..
*** Stopping 1 switches
s1 
*** Stopping 2 hosts
h1 h2 
*** Done
completed in 5.329 seconds
# 3. Ryu 설치
pip3 install ryu

# 4. 설치 확인
mn --version   # Mininet 버전 출력
# 2.3.1b4
ryu-manager --version  # Ryu 버전 출력

3단계: 네트워크 토폴로지 구성 (Mininet)

가상 호스트 및 스위치 생성

sudo mn --controller=remote --topo=tree,depth=2,fanout=2 --switch ovsk,protocols=OpenFlow13

 

depth = 2 (루트 스위치 + 중간 스위치)

fanout = 4 (각 중간 스위치에 4개 호스트 연결) - 16개 호스트 생성됨

 

1명의 컨트롤러와 2단계 트리 구조의 스위치-호스트 네트워크를 자동으로 생성

총 8개 호스트(h1h8), 3개 스위치(s1s3) 생성

Ryu 컨트롤러는 외부에서 연결됨

$ sudo mn --controller=remote --topo=tree,depth=2,fanout=2 --switch ovsk,protocols=OpenFlow13
*** Creating network
*** Adding controller
Unable to contact the remote controller at 127.0.0.1:6653
Unable to contact the remote controller at 127.0.0.1:6633
Setting remote controller to 127.0.0.1:6653
*** Adding hosts:
h1 h2 h3 h4 
*** Adding switches:
s1 s2 s3 
*** Adding links:
(s1, s2) (s1, s3) (s2, h1) (s2, h2) (s3, h3) (s3, h4) 
*** Configuring hosts
h1 h2 h3 h4 
*** Starting controller
c0 
*** Starting 3 switches
s1 s2 s3 ...
*** Starting CLI:
mininet> 

 

Ryu 컨트롤러용 기본 코드 (simple_switch_13 + MTD 기능)

/home/ubuntu/
└── ryu-apps/
    ├── mtd_controller.py
    ├── myfirewall.py
    └── other_apps.py

 

mtd_controller.py

from ryu.base import app_manager
from ryu.controller import ofp_event
from ryu.controller.handler import CONFIG_DISPATCHER, MAIN_DISPATCHER, set_ev_cls
from ryu.ofproto import ofproto_v1_3
from ryu.lib.packet import packet, ethernet, ipv4
from ryu.controller.handler import HANDSHAKE_DISPATCHER
import random
import time
import threading

class SimpleMTD(app_manager.RyuApp):
    OFP_VERSIONS = [ofproto_v1_3.OFP_VERSION]

    def __init__(self, *args, **kwargs):
        super(SimpleMTD, self).__init__(*args, **kwargs)
        self.mac_to_port = {}
        self.ip_pool = ["10.0.0." + str(i) for i in range(1, 10)]
        self.ip_map = {}
        self.mtd_interval = 30  # 매 30초마다 IP 변경
        threading.Thread(target=self.ip_randomizer).start()

    def ip_randomizer(self):
        while True:
            time.sleep(self.mtd_interval)
            self.logger.info("MTD: 무작위 IP 재할당 시작")
            self.ip_map = {}  # 기존 맵 제거
            for host_id in range(1, 9):
                self.ip_map[f"h{host_id}"] = random.choice(self.ip_pool)
            self.logger.info(f"새로운 IP 매핑: {self.ip_map}")

    @set_ev_cls(ofp_event.EventOFPSwitchFeatures, CONFIG_DISPATCHER)
    def switch_features_handler(self, ev):
        datapath = ev.msg.datapath
        ofproto = datapath.ofproto
        parser = datapath.ofproto_parser

        match = parser.OFPMatch()
        actions = [parser.OFPActionOutput(ofproto.OFPP_CONTROLLER,
                                          ofproto.OFPCML_NO_BUFFER)]
        self.add_flow(datapath, 0, match, actions)

    def add_flow(self, datapath, priority, match, actions):
        ofproto = datapath.ofproto
        parser = datapath.ofproto_parser

        inst = [parser.OFPInstructionActions(ofproto.OFPIT_APPLY_ACTIONS,
                                             actions)]
        mod = parser.OFPFlowMod(datapath=datapath, priority=priority,
                                 match=match, instructions=inst)
        datapath.send_msg(mod)

    @set_ev_cls(ofp_event.EventOFPPacketIn, MAIN_DISPATCHER)
    def _packet_in_handler(self, ev):
        msg = ev.msg
        datapath = msg.datapath
        ofproto = datapath.ofproto
        parser = datapath.ofproto_parser

        in_port = msg.match['in_port']
        pkt = packet.Packet(msg.data)
        eth = pkt.get_protocols(ethernet.ethernet)[0]

        dst = eth.dst
        src = eth.src

        dpid = datapath.id
        self.mac_to_port.setdefault(dpid, {})

        self.mac_to_port[dpid][src] = in_port
        out_port = self.mac_to_port[dpid].get(dst, ofproto.OFPP_FLOOD)

        actions = [parser.OFPActionOutput(out_port)]

        # 흐름 추가
        match = parser.OFPMatch(in_port=in_port, eth_dst=dst, eth_src=src)
        self.add_flow(datapath, 1, match, actions)

        # 패킷 전송
        out = parser.OFPPacketOut(datapath=datapath,
                                  buffer_id=msg.buffer_id,
                                  in_port=in_port,
                                  actions=actions,
                                  data=msg.data)
        datapath.send_msg(out)

 

기본적인 스위칭 기능을 하면서, 30초마다 호스트 IP를 무작위로 바꾸는 역할

실시간 IP 변경은 단순히 로그로 표시되고, 실제 호스트 IP를 바꾸지는 않음

4단계: Ryu 실행

ryu-manager mtd_controller.py

 

# eventlet 라이브러리의 ALREADY_HANDLED를 불러올 수 없을 경우에는, eventlet 버전 다운그레이드

pip install eventlet==0.30.2

# ryu를 찾을 수 없는 경우
pip install ryu "eventlet<0.31"

 

# 호환성 문제 (실험 환경: Python 3.8, eventlet 0.30.x)

# Python 3.8 설치
sudo apt update
sudo apt install -y software-properties-common
sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt update
sudo apt install -y python3.8 python3.8-venv python3.8-dev

# Ryu용 가상환경 생성
python3.8 -m venv ~/ryu-env
source ~/ryu-env/bin/activate

# 필요한 패키지 설치
pip install --upgrade pip
pip install ryu==4.34 eventlet==0.30.2
# eventlet==0.30.2는 Python 3.8 환경에서 Ryu와 안정적으로 호환됨

# 가상환경 만들기
python3.8 -m venv ryu-env
source ryu-env/bin/activate
# prompt: (ryu-env) ubuntu@ip-...:~$

# (가상환경 내) Ryu, eventlet 설치
pip install --upgrade pip
pip install ryu==4.34 eventlet==0.30.2 six==1.16.0

# 안될 경우,
git clone https://github.com/faucetsdn/ryu.git
cd ryu
git checkout tags/v4.34 -b v4.34

pip install setuptools==59.5.0
pip install . --no-use-pep517

# 현재 디렉토리 등록
echo "export PYTHONPATH=." >> ~/ryu-apps/ryu-env/bin/activate

# 재실행
ryu-manager mtd_controller.py

 

# 버전 오류 시

# 1. pip, setuptools, wheel 다운그레이드
pip install --upgrade pip
pip install "setuptools==56.0.0" "wheel==0.36.2"

# 2. 안정적인 조합 설치
pip install "ryu==4.30" "eventlet==0.30.2"
$ python --version		# Python 3.8.20
$ pip show ryu			# Version: 4.30
$ pip show setuptools		# Version: 56.0.0
$ pip show eventlet		# Version: 0.30.2

5단계: 실험 진행

# RTT 측정
mininet> h1 ping h2

# 정찰 공격 시뮬레이션
mininet> h3 nmap -sP 10.0.0.0/24
  • 실제 IP 변경은 iptables NAT 규칙으로 시뮬레이션 가능
  • 실제 SCADA/PLC 장비 대신 Modbus 시뮬레이터 (ex. mbtget)로 구성 가능
mininet> h1 ping -c 10 h2
PING 10.0.0.2 (10.0.0.2) 56(84) bytes of data.
64 bytes from 10.0.0.2: icmp_seq=1 ttl=64 time=0.059 ms
64 bytes from 10.0.0.2: icmp_seq=2 ttl=64 time=0.053 ms
64 bytes from 10.0.0.2: icmp_seq=3 ttl=64 time=0.053 ms
64 bytes from 10.0.0.2: icmp_seq=4 ttl=64 time=0.060 ms
64 bytes from 10.0.0.2: icmp_seq=5 ttl=64 time=0.054 ms
64 bytes from 10.0.0.2: icmp_seq=6 ttl=64 time=0.058 ms
64 bytes from 10.0.0.2: icmp_seq=7 ttl=64 time=0.052 ms
64 bytes from 10.0.0.2: icmp_seq=8 ttl=64 time=0.055 ms
64 bytes from 10.0.0.2: icmp_seq=9 ttl=64 time=0.053 ms
64 bytes from 10.0.0.2: icmp_seq=10 ttl=64 time=0.062 ms

--- 10.0.0.2 ping statistics ---
10 packets transmitted, 10 received, 0% packet loss, time 9205ms
rtt min/avg/max/mdev = 0.052/0.055/0.062/0.003 ms
mininet> h3 nmap -sP 10.0.0.0/24
Starting Nmap 7.80 ( 
https://nmap.org
 ) at 2025-04-22 13:52 UTC
Nmap scan report for 10.0.0.1
Host is up (0.022s latency).
MAC Address: 56:DF:00:DC:C1:17 (Unknown)
Nmap scan report for 10.0.0.2
Host is up (0.020s latency).
MAC Address: E2:2C:BE:AF:84:BD (Unknown)
Nmap scan report for 10.0.0.4
Host is up (0.014s latency).
MAC Address: 92:A7:6C:25:F8:8B (Unknown)
Nmap scan report for 10.0.0.3
Host is up.
Nmap done: 256 IP addresses (4 hosts up) scanned in 27.95 seconds

 

 

728x90
728x90

'Networking > Network' 카테고리의 다른 글

[Route53] name servers  (0) 2025.02.07
[essential#03] Wireshark  (0) 2025.02.07
[essentials#02] Telnet  (0) 2025.02.06
[essentials#01] Server-Client communication using Netcat  (0) 2025.02.06
[AWS] setting up Nginx SSL  (0) 2024.07.30
728x90
반응형

DNS 서버(BIND) 구축 방법

 

1. BIND 설치

- BIND (Berkeley Internet Name Domain)

# 설치
yum -y install bind bind-chroot bind-utils

 

2. 기본 설정 파일 수정 (/etc/named.conf)

# named.conf 수정
sudo vi /etc/named.conf

options {
        listen-on port 53 { any; };  # fixed
        listen-on-v6 port 53 { none; };  # or default (::1;)
        directory       "/var/named";
        dump-file      "/var/named/data/cache_dump.db";
        statistics-file "/var/named/data/named_stats.txt";
        memstatistics-file "/var/named/data/named_mem_stats.txt";
        allow-query     { any; };  # fixed
        recursion yes;
        
        dnssec-validation auto;
        auth-nxdomain no;  # fixed
};

요청한 도메인이 존재하지 않을 때 반환하는 DNS 코드 - no: RFC 표준 준수 (권장)

 

3. zone 파일 생성

# /var/named/example.com.zone 생성
sudo vi /var/named/example.com.zone

$TTL    86400
@       IN      SOA     ns1.example.com. admin.example.com. (
                        2023011001      ; Serial
                        3600            ; Refresh
                        1800            ; Retry
                        604800          ; Expire
                        86400 )         ; Minimum TTL

@       IN      NS      ns1.example.com.
@       IN      A       192.168.1.10
ns1     IN      A       192.168.1.10
www     IN      A       192.168.1.20

 

4. zone 설정을 named.conf에 추가

# /etc/named.conf에 추가
zone "example.com" IN {
        type master;
        file "example.com.zone";
        allow-update { none; };
};

    

 

5. 권한 및 소유권 설정

sudo chown root:named /var/named/example.com.zone
sudo chmod 640 /var/named/example.com.zone

 

6. 서비스 시작 및 자동 시작 설정

# 문법 체크
sudo named-checkconf
sudo named-checkzone example.com /var/named/example.com.zone
# - zone example.com/IN: loaded serial 2023011001
# - OK

# 서비스 시작
sudo systemctl start named
sudo systemctl enable named
# - reated symlink /etc/systemd/system/multi-user.target.wants/named.service → /usr/lib/systemd/system/named.service.
sudo systemctl status named

 

7. 방화벽 설정

    # firewalld 사용시
sudo firewall-cmd --permanent --add-port=53/tcp
sudo firewall-cmd --permanent --add-port=53/udp
sudo firewall-cmd --reload

# iptables 사용시
sudo iptables -A INPUT -p udp --dport 53 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 53 -j ACCEPT

    

 

8. 테스트

    # 로컬 테스트
dig @localhost example.com

# 특정 레코드 조회
dig www.example.com @localhost

 

# 결과

 

$ dig @localhost example.com

; <<>> DiG 9.18.33 <<>> @localhost example.com
; (1 server found)
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 45673
;; flags: qr aa rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 1232
; COOKIE: a2fd5717dacbb8b201000000680b4c743807764a3f2cf3a6 (good)
;; QUESTION SECTION:
;example.com.                   IN      A

;; ANSWER SECTION:
example.com.            86400   IN      A       192.168.1.10

;; Query time: 0 msec
;; SERVER: 127.0.0.1#53(localhost) (UDP)
;; WHEN: Fri Apr 25 08:48:52 UTC 2025
;; MSG SIZE  rcvd: 84

 

$ dig @localhost www.example.com

; <<>> DiG 9.18.33 <<>> 
http://www.example.com
 @localhost
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 38254
;; flags: qr aa rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 1232
; COOKIE: e731811333abbe1101000000680b4ca5b60e5eccc01d1049 (good)
;; QUESTION SECTION:
;
http://www.example.com.
 IN      A

;; ANSWER SECTION:
http://www.example.com.
 86400   IN      A       192.168.1.20

;; Query time: 0 msec
;; SERVER: 127.0.0.1#53(localhost) (UDP)
;; WHEN: Fri Apr 25 08:49:41 UTC 2025
;; MSG SIZE  rcvd: 88

 

728x90
728x90
728x90
반응형

1. 사설 인증서 생성 (OpenSSL 사용)

# 1. 개인키(private key) 생성
openssl genrsa -out private.key 2048

# 2. CSR(Certificate Signing Request) 생성
openssl req -new -key private.key -out csr.pem

# 3. 자체 서명된 인증서 생성 (유효기간 365일)
openssl x509 -req -days 365 -in csr.pem -signkey private.key -out certificate.crt

 

2. AWS Certificate Manager(ACM)에 사설 인증서 가져오기

# 1. 인증서 체인 파일 생성 (certificate.crt 내용 복사)
cat certificate.crt > chain.pem

 

AWS Certificate Manager console 접속

Import certificate

Certificate details

Certificate body

certificate.crt 내용 붙여넣기

 
Certificate private key
프라이빗 키: private.key 내용 붙여넣기
 
Certificate chain - optionalInfo
인증서 체인: chain.pem 내용 붙여넣기
 
Import certificate

3. ALB에 인증서 등록

AWS Console에서:

  1. EC2 > Load Balancers
  2. 대상 ALB 선택
  3. "리스너" 탭 선택
  4. HTTPS 리스너 추가 또는 수정
    • 프로토콜: HTTPS
    • 포트: 443
    • 기본 작업: 대상 그룹 선택
    • 보안 정책: ELBSecurityPolicy-2016-08 (권장)
    • 인증서: 방금 가져온 사설 인증서 선택

CLI를 이용한 ALB 인증서 등록:

# 인증서 ARN 확인
aws acm list-certificates

# ALB 리스너에 인증서 추가
aws elbv2 add-listener-certificates \
    --listener-arn [리스너-ARN] \
    --certificates CertificateArn=[인증서-ARN]
# 인증서 정보 확인
openssl x509 -in certificate.crt -text -noout

# HTTPS 연결 테스트
curl -v https://saraheee.site
 
 
728x90
728x90
728x90
반응형

 

1. AWS Organizations structure 생성

 

2. Amazon VPC IP Address Manager console

- Planning > Organization settings > choose Delegate

Your IPAM is not discovering your organiziation's resources. For IPAM to discover resources in your entire organization you must delegate an account in your organization as the IPAM administrator. You cannot delegate the organization management account as the IPAM administrator.

 

3. IPAM 생성

 

4. IPAM 풀 생성

최상위 - 리전 - 사전 프로덕션 개발 풀

 

5. IPAM 풀 공유

- Resource Access Manager console - Settings > Enable sharing with AWS Organizations

- Amazon VPC IP Address Manager console - (Planning) Pools > choose Name (Pool ID) > Resource sharing > Create resource share

> Create resource share

  > Select resource type: IPAM Pools

  > Principals: Allow sharing only within your organization, select principal type: Organizational unit (OU)

 

References:

[1] Tutorial: Create an IPAM and pools using the console - https://docs.aws.amazon.com/vpc/latest/ipam/tutorials-get-started-console.html

 

Tutorial: Create an IPAM and pools using the console - Amazon Virtual Private Cloud

For the purposes of this tutorial, the instructions will tell you to name IPAM resources in a particular way, create IPAM resources in specific Regions, and use specific IP address CIDR ranges for your pools. This is intended to streamline the choices avai

docs.aws.amazon.com

 

728x90
728x90
728x90
반응형


ALB는 수신하는 트래픽 처리를 위해 Scaling 동작을 수행하며 ALB 서비스 도메인에 대한 IP 주소가 동적으로 변경된다 [1].

1) Global Accelerator를 사용하면 고정 IP 확보는 가능하나 비용 효율적이지 않다 [2].

Global Accelerator 생성 시 기본적으로 2개의 고정 IP가 자동으로 할당된다. ALB를 엔드포인트로 추가하여 Global Accelerator의 두 고정 IP를 통해 ALB로 트래픽이 전달되도록 설정하실 수 있다.

 

2) ALB 앞 NLB를 사용하여 NLB의 대상으로 ALB를 연결할 수 있도록 배치하여 고정 IP를 사용하는 것과 동일한 효과를 얻을 수 있다 [3].

 

1), 2) 상세 내역 [4]

 

3) 2025-03-07 업데이트된 내역을 통해,
ALB가 IPAM과의 통합을 통해 ALB 노드에 IP 주소 할당을 위한 Public IPv4 주소 풀을 제공할 수 있게 되었다.
고객 소유의 BYOIPs (Bring Your Own IP addresses) 또는 Amazon에서 제공하는 인접한 IPv4 주소 블록으로 구성할 수 있는 공용 VPC IP Address Manager (IPAM) 풀을 구성할 수 있다.
이 때 ALB의 IP 주소는 IPAM 풀에서 소싱되며, 혹여 공용 IPAM 풀이 고갈되면 자동으로 AWS 관리형 IP 주소로 전환된다.

nslookup
> ipam-alb-3168xxx70.us-east-1.elb.amazonaws.com
Server:		10.148.65.xx
Address:	10.148.65.xx#53

Non-authoritative answer:
Name:	ipam-alb-3168xxx70.us-east-1.elb.amazonaws.com
Address: 18.97.9.137
Name:	ipam-alb-3168xxx70.us-east-1.elb.amazonaws.com
Address: 18.97.9.177
>

 

참고 사항으로, ELB 서비스가 사용하는 공인 IP는 하기 링크의 ip-ranges.json 파일에서 확인 가능하다.
us-east-1 리전에 ELB가 있는 경우, 서비스=EC2, 지역=us-east-1인 IP 주소 범위를 찾아 화이트리스트에 추가해야 한다.

(하지만 서비스가 지속적으로 성장하고 확장함에 따라 ip-ranges.json 파일도 변경될 수 있다.)

https://ip-ranges.amazonaws.com/ip-ranges.json

 

References:

[1] Application Load Balancers - 가용 영역 서브넷 - https://docs.aws.amazon.com/ko_kr/elasticloadbalancing/latest/application/application-load-balancers.html#availability-zones

[2] AWS Global Accelerator 구성 요소 - https://docs.aws.amazon.com/ko_kr/global-accelerator/latest/dg/introduction-components.html

[3] Network Load Balancer의 대상으로 Application Load Balancer 사용 - https://docs.aws.amazon.com/ko_kr/elasticloadbalancing/latest/network/application-load-balancer-target.html

[4] 애플리케이션 로드 밸런서(ALB)에 고정 IP 주소 설정 및 사용하기 - https://aws.amazon.com/ko/blogs/korea/using-static-ip-addresses-for-application-load-balancers/

[5] Application Load Balancer announces integration with Amazon VPC IPAM - https://aws.amazon.com/about-aws/whats-new/2025/03/application-load-balancer-integration-vpc-ipam/

[6] Blog: VPC IPAM을 사용하여 Application Load Balancer 고정 IP 사용하기 - https://zigispace.net/1320

 

728x90
728x90
728x90
반응형

Route53 Hybrid DNS

1. VPC 생성

- cloud: 10.0.0.0/16

- onprem: 192.168.0.0/16

- subnets, route tables, nat gateways 생성

2. 인스턴스 생성

cloud-app-server

- sg: ssh anywhere, icmp 192.168.0.0/16

onprem-app-server

- sg: ssh 192.168.0.0/16, icmp 10.0.0.0/16

onprem-vpn-server

- sg: ssh anywhere, dns (udp) 192.168.0.0/16, icmp 192.168.0.0/16

3. VPN 설정

1) Virtual private gateway (cloud-vgw)

2) Customer gateways (onprem-cgw) - onprem-vpn-server의 public IP address (Specify the IP address for your customer gateway device's external interface.)

3) VGW - attach to VPC: cloud-vpc

4) Site-to-Site VPN connections (cloud-onprem-vpn-connection)

- Routing options: Static

- Static IP prefixes: 192.168.0.0/16 (onprem-vpn range)

5) download VPN connections configurations - Platform: Openswan

4. SSH 접속

brew install putty
putty

Auth - Credentials - keypair.pem 경로

Session - Saved Sessions

IP: onprem-vpn-server's public IP

login as: ec2-user

ssh -i "ap-south-1-keypair.pem" ec2-user@35.x.x.x
 % sudo su
sh-3.2# ssh -i "ap-south-1-keypair.pem" ec2-user@35.154.187.78
The authenticity of host '35.x.x.x (35.x.x.x)' can't be established.
ED25519 key fingerprint is SHA256:qOx9yHXTxD6xaC9BfiT/Y5/82Ml/mVZzr5hNXnw9FQ8.
This key is not known by any other names.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '35.x.x.x' (ED25519) to the list of known hosts.
   ,     #_
   ~\_  ####_        Amazon Linux 2023
  ~~  \_#####\
  ~~     \###|
  ~~       \#/ ___   https://aws.amazon.com/linux/amazon-linux-2023
   ~~       V~' '->
    ~~~         /
      ~~._.   _/
         _/ _/
       _/m/'
[ec2-user@ip-192-168-0-220 ~]$
sudo yum install libreswan
sudo vi /etc/sysctl.conf

1) Open /etc/sysctl.conf and ensure that its values match the following:
   net.ipv4.ip_forward = 1
   net.ipv4.conf.default.rp_filter = 0
   net.ipv4.conf.default.accept_source_route = 0

2) Apply the changes in step 1 by executing the command 'sysctl -p'

sudo sysctl -p

3) Open /etc/ipsec.conf and look for the line below. Ensure that the # in front of the line has been removed, then save and exit the file.
    #include /etc/ipsec.d/*.conf

이미 제거된 상태로 저장됨

cat /etc/ipsec.conf

4) Create a new file at /etc/ipsec.d/aws.conf if doesn't already exist, and then open it. Append the following configuration to the end in the file:
 #leftsubnet= is the local network behind your openswan server, and you will need to replace the <LOCAL NETWORK> below with this value (don't include the brackets). If you have multiple subnets, you can use 0.0.0.0/0 instead.
 #rightsubnet= is the remote network on the other side of your VPN tunnel that you wish to have connectivity with, and you will need to replace <REMOTE NETWORK> with this value (don't include brackets).

conn Tunnel1
authby=secret
auto=start
left=%defaultroute
leftid=35.x.x.x
right=13.x.x.x
type=tunnel
ikelifetime=8h
keylife=1h
phase2alg=aes128-sha1;modp1024
ike=aes128-sha1;modp1024
auth=esp
keyingtries=%forever
keyexchange=ike
leftsubnet=<LOCAL NETWORK>
rightsubnet=<REMOTE NETWORK>
dpddelay=10
dpdtimeout=30
dpdaction=restart_by_peer

sudo vi /etc/ipsec.d/aws.conf
conn Tunnel1
        authby=secret
        auto=start
        left=%defaultroute
        leftid=35.x.x.x
        right=13.x.x.x
        type=tunnel
        ikelifetime=8h
        keylife=1h
        phase2alg=aes256-sha1;modp2048
        ike=aes256-sha1;modp2048
        keyingtries=%forever
        keyexchange=ike
        leftsubnet=192.168.0.0/16
        rightsubnet=10.0.0.0/16
        dpddelay=10
        dpdtimeout=30
        dpdaction=restart_by_peer

5) Create a new file at /etc/ipsec.d/aws.secrets if it doesn't already exist, and append this line to the file (be mindful of the spacing!):
35.x.x.x 13.x.x.x: PSK "TOC3RK--------------------IUtns"

sudo vi /etc/ipsec.d/aws.secrets

Tunnel 1 구성 완료

sudo systemctl start ipsec.service
sudo systemctl status ipsec.service

5. Route Tables 설정 (propagation)

cloud-vpc-private-rt > Route propagation > Propagation: Enable

또는 Routes 편집 (cloud-vgw)

cloud-vpc-public-rt도 동일하게 설정

6. VPN 서버의 목적지 비활성화

Instances: onprem-vpn-server > Actions - Networking - Change Source / destination check > check Stop > Save

Route tables: cloud-vpc-public-rt > 10.0.0.0/16 instance (onprem-vpn-server)

7. Cloud Instance 접속

cloud-app-server public IP

ssh -i "ap-south-1-keypair.pem" ec2-user@3.x.x.x

 

ping (onprem-app-server)

 

From Cloud EC2 instance - Ping to on-premises App server private IP

Cloud EC2 -> VGW -> VPN Tunnel 1 -> VPN server -> App server

 

728x90
728x90
728x90
반응형

도메인 등록을 위한 DNS 서비스를 변경하고 싶은 경우 퍼블릭 호스팅 영역의 이름 서버를 가져온다.

 

1) Route 53 console의 Hosted zones 내비게이션 바 클릭 > Hosted zone name 클릭

2) Hosted zone details의 Name servers 4개 저장

3) Route 53 console의 Domains - Registered domains 내비게이션 바 클릭

4) Actions - Edit name servers

 

5) 2)에서 저장한 name servers 입력 후 저장

 

[1] 퍼블릭 호스팅 영역에 대한 이름 서버 가져오기 - https://docs.aws.amazon.com/ko_kr/Route53/latest/DeveloperGuide/GetInfoAboutHostedZone.html

728x90
728x90
728x90
반응형

1. AWS VPC

VPC를 사용하면 논리적으로 격리된 가상 네트워크에서 AWS 리소스를 시작할 수 있다. 이 가상 네트워크는 AWS의 확장 가능한 인프라를 사용한다는 이점과 함께 고객의 자체 데이터 센터에서 운영하는 기존 네트워크와 유사하다.

서브넷: VPC의 IP 주소 범위, 단일 가용 영역에 상주

라우팅: 라우팅 테이블을 사용해서 서브넷 또는 게이트웨이의 네트워크 트래픽이 전달되는 위치를 결정

게이트웨이 및 엔드포인트: 게이트웨이는 VPC를 다른 네트워크에 연결, 인터넷 게이트웨이를 사용하여 VPC를 인터넷에 연결

피어링 연결: VPC 피어링 연결을 사용하여 두 VPC의 리소스 간 트래픽을 라우팅

VPC 흐름 로그: VPC의 네트워크 인터페이스로 들어오고 나가는 IP 트래픽에 대한 정보를 캡처

2. Security in VPC

보안 그룹: 리소스 수준(예: EC2 인스턴스)에서 특정 인바운드 및 아웃바운드 트래픽을 허용, 인스턴스를 시작할 때 하나 이상의 보안 그룹과 연결할 수 있다. VPC의 각 인스턴스는 서로 다른 보안 그룹 세트에 속할 수 있다.

네트워크 액세스 제어 목록(ACL): 네트워크 ACL은 서브넷 수준에서 특정 인바운드 또는 아웃바운드 트래픽을 허용하거나 거부한다.

흐름 로그: VPC의 네트워크 인터페이스에서 양방향으로 이동하는 IP 트래픽에 대한 정보를 캡처한다. VPC, 서브넷 또는 개별 네트워크 인터페이스에 대한 흐름 로그를 생성할 수 있다.

흐름 로그 데이터는 CloudWatch logs 또는 Amazon S3에 게시되며 과도하게 제한하거나 과도하게 허용하는 보안 그룹과 네트워크 ACL 규칙을 진단하는 데 도움이 된다.

트래픽 미러링: Amazon EC2 인스턴스의 탄력적 네트워크 인터페이스에서 네트워크 트래픽을 복사할 수 있다.

3. VPC Peering

VPC는 사용자의 AWS 계정 전용 가상 네트워크이다. AWS 클라우드에서 다른 가상 네트워크와 논리적으로 분리되어 있다.

VPC 피어링 연결은 프라이빗 IPv4 주소 또는 IPv6 주소를 사용하여 두 VPC 간에 트래픽을 라우팅할 수 있도록 하기 위한 두 VPC 사이의 네트워크 연결이다.

동일한 네트워크에 속하는 경우와 같이 VPC의 인스턴스가 서로 통신할 수 있다. 사용자의 자체 VPC 또는 다른 AWS 계정의 VPC와 VPC 피어링 연결을 만들 수 있으며, VPC는 상이한 리전에 있을 수 있다.

VPC의 기존 인프라를 사용하여 VPC 피어링 연결을 생성한다. 이는 게이트웨이도, VPN 연결도 아니며 물리적 하드웨어 각각에 의존하지 않는다. 그러므로 통신 또는 대역폭 병목에 대한 단일 지점 장애가 없다.

4. VPC Flowlogs

VPC 흐름 로그는 VPC의 네트워크 인터페이스에서 전송되고 수신되는 IP 트래픽에 대한 정보를 수집할 수 있는 기능이다. 흐름 로그 데이터가 게시될 수 있는 위치는 Amazon CloudWatch Logs, Amazon S3 또는 Amazon Data Firehose이다.

흐름 로그를 생성하면 구성한 로그 그룹, 버킷 또는 전송 스트림의 흐름 로그 레코드를 검색하고 볼 수 있다.

5. VPC PrivateLink

VPC에 인터넷 게이트웨이를 추가하여 인터넷 액세스를 허용하거나 VPN 연결을 추가하여 온프레미스 네트워크 액세스를 허용할 수 있다.

VPC의 클라이언트가 프라이빗 IP 주소를 사용하여 다른 VPCs의 서비스 및 리소스에 연결할 수 있도록 AWS PrivateLink 하려면 해당 서비스 및 리소스가 VPC에서 직접 호스팅된 것처럼 사용한다.

6. NAT Instance

NAT 인스턴스는 Network Address Translation(NAT)을 제공한다. NAT 인스턴스를 사용하면 프라이빗 서브넷의 리소스가 인터넷이나 온프레미스 네트워크와 같은 VPC 외부의 대상과 통신할 수 있다. 프라이빗 서브넷의 리소스는 인터넷으로 향하는 아웃바운드 IPv4 트래픽을 시작할 수 있지만 인터넷에서 시작된 인바운드 트래픽을 수신할 수는 없다.

NAT 인스턴스는 퍼블릭 인터넷에 있어야 하며, NAT 인스턴스에는 퍼블릭 IP 주소 또는 탄력적 IP 주소가 있어야 한다.

7. NAT Gateway

NAT 게이트웨이는 NAT 서비스로, 프라이빗 서브넷의 인스턴스가 VPC 외부의 서브넷에 연결할 수 있지만 외부 서비스에서 이러한 인스턴스와의 연결을 시작할 수 없도록 NAT 게이트웨이를 사용할 수 있다.

퍼블릭 - (기본값) 퍼블릭 서브넷의 인스턴스는 퍼블릭 NAT 게이트웨이를 통해 인터넷에 연결할 수 이지만 인터넷에서 원치 않는 연결을 수신할 수 없다. 퍼블릭 서브넷에서 퍼블릭 NAT 게이트웨이를 생성하고 생성 시 탄력적 IP 주소를 NAT 게이트웨이와 연결해야 한다.

프라이빗 - 프라이빗 서브넷 인스턴스는 프라이빗 NAT 게이트웨이를 통해 다른 VPC 또는 온프레미스 네트워크에 연결할 수 있다.

8. IPv6 migration

IPv4만을 지원하는 기존 VPC와 서브넷에서 IPv4만을 사용하도록 구성된 리소스가 있으면 VPC 및 리소스에 대한 IPv6 지원을 추가할 수 있다.

 

References: 

1. AWS VPC - http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_Introduction.html

2. Security in VPC - http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_Security.html
3. VPC Peering - http://docs.aws.amazon.com/AmazonVPC/latest/PeeringGuide/Welcome.html
4. VPC Flowlogs - http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/flow-logs.html
5. VPC PrivateLink - http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/vpc-endpoints.html
6. NAT Instance - http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_NAT_Instance.html
7. NAT Gateway - http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/vpc-nat-gateway.html
8. IPv6 migration - http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/vpc-migrate-ipv6.html

 

728x90
728x90
728x90
반응형

특정 도메인을 담당하는 적절한 네임 서버로 DNS 쿼리를 전달하는 과정에서 DNS 쿼리를 해결하는 데 필수적인 권한 있는 네임 서버의 이름을 확인하기 위해 NS(네임 서버) 레코드를 참조한다.
이 특정 도메인에 대한 권한은 다른 네임 서버에 위임할 때 도메인의 권한 있는 네임 서버(실제 DNS 레코드를 갖고 있는 서버)인지 확인하기 위해 필요하며, 
해당 도메인이 신뢰할 수 있는지 확인하기 위해 각 도메인마다 DNS 레코드 관리를 담당하는 네임 서버가 존재한다.

예를 들어, 아래와 같이 'example.com'에서 레코드명 'sub.example.com'의 NS 레코드가 생성된 상태에서, 권한 있는 'sub.example.com' 도메인의 호스팅 영역을 찾기 위해 네임 서버가 아래와 같은 'sub.example.com' 호스팅 영역을 조회한다.

이 때, 하위 도메인 'sub.example.com'에 대한 네임 서버 변경이 가능한 경우 도메인의 고유한 권한을 확인할 수 없으므로, 상위 도메인 'example.com'의 'sub.example.com'에 대한 NS 레코드를 일치시켜야 한다.

 

References:

DNS에서 NS(이름 서버) 레코드의 기능은 무엇입니까? - https://ko.eitca.org/cybersecurity/eitc-is-wsa-windows-server-administration/system-administration-in-windows-server/resource-record-types/examination-review-resource-record-types/what-is-the-function-of-a-name-server-ns-record-in-dns/

 

DNS에서 NS(이름 서버) 레코드의 기능은 무엇입니까? - EITCA 아카데미

NS(이름 서버) 레코드는 Windows Server 관리에 사용되는 DNS(Domain Name System)의 중요한 구성 요소입니다. 이는 도메인 이름의 전반적인 관리 및 확인에서 특정 기능을 제공합니다. 이러한 맥락에서 NS

ko.eitca.org

 

728x90
728x90

'Networking > Network' 카테고리의 다른 글

[AWS] 실험 환경 구성#1  (0) 2025.04.23
[essential#03] Wireshark  (0) 2025.02.07
[essentials#02] Telnet  (0) 2025.02.06
[essentials#01] Server-Client communication using Netcat  (0) 2025.02.06
[AWS] setting up Nginx SSL  (0) 2024.07.30
728x90
반응형

Capturing Traffic

$ sudo tcpdump -i eth0 -nn -s0 -v port 80

-i eth0: eth0 인터페이스에서 패킷 캡처

-nn: 호스트명, 포트 번호를 DNS 리졸빙하지 않고 숫자로 표시

-s0: 패킷의 전체 내용을 캡처 (스냅샷 길이 제한 없음)

-v: 상세 출력 모드

port 80: HTTP 트래픽(80번 포트)만 캡처

$ sudo tcpdump -i eth0 -s0 -w test.pcap

-i eth0: eth0 인터페이스에서 패킷 캡처

-s0: 패킷의 전체 내용 캡처

-w test.pcap: 캡처한 패킷을 test.pcap 파일로 저장

$ sudo tcpdump -i eth0 -w /var/tmp/rotate.pcap -W 3 -C 10 -s 150 &

-i eth0: eth0 인터페이스에서 패킷 캡처

-w /var/tmp/rotate.pcap: 캡처 파일 저장 경로

-W 3: 최대 3개의 파일로 순환 저장

-C 10: 각 캡처 파일 크기를 10MB로 제한

-s 150: 각 패킷당 캡처할 바이트 수를 150으로 제한

&: 백그라운드에서 실행

 

터미널에서 pcap 내용 조회

tcpdump -r test.pcap -v

Create and Applying Filters

Statistics > Conversations - DisplayFilters

필터링하고 싶은 패킷 - Prepare as Filter

A B 클릭 시

> ip.src==10.40.7.87 && tcp.srcport==58690 && ip.dst==17.57.145.151 && tcp.dstport==5223

Advanced Feature Color Traffic

View > Coloring Rules...

Decode

패킷 우측 Decode As..: Wireshark에서 패킷을 다른 프로토콜로 강제 해석(디코딩)하도록 하는 기능

- 비표준 포트 사용 시 (예: HTTP가 기본 80 포트가 아닌 8080 포트를 사용할 때)

Expert Information

Analyze > Expert Information

네트워크 트래픽을 분석하여 잠재적인 문제나 이상 징후를 감지

- Error (빨간색): 심각한 문제, TCP 재전송, 손상된 체크섬 등

- Warning (노란색): 잠재적 문제, TCP 윈도우 크기 0, 중복 ACK 등

- Note (파란색): 비정상적이지만 문제는 아닌 상황, TCP 윈도우 업데이트, 비표준 포트 사용 등

- Chat (회색): 일반적인 정보, TCP 연결 시작/종료 등

Interpret TCP Graphs

Statistics > I/O Graphs

시간에 따른 네트워크 트래픽을 그래프로 시각화하는 도구

Statistics > TCP Stream Graphs > Throughput

TCP 연결의 처리량을 시각화하여 보여주는 도구

Window Scaling

Win=1024

 

 

728x90
728x90

'Networking > Network' 카테고리의 다른 글

[AWS] 실험 환경 구성#1  (0) 2025.04.23
[Route53] name servers  (0) 2025.02.07
[essentials#02] Telnet  (0) 2025.02.06
[essentials#01] Server-Client communication using Netcat  (0) 2025.02.06
[AWS] setting up Nginx SSL  (0) 2024.07.30
728x90
반응형

VPC DNS resolver 우선 순위

0. DNS firewall (R53 전용 Network Firewall)

 

1. Route 53 Resolver 규칙
   - 명시적으로 정의된 Outbound 규칙
   - 도메인 기반 포워딩 규칙


2. Private Hosted Zone
   - VPC와 연결된 프라이빗 호스팅 영역

$ dig example.com

; <<>> DiG 9.11.4-P2-RedHat-9.11.4-26.P2.amzn2.13.9 <<>> example.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 63355
;; flags: qr rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 1, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 4096
;; QUESTION SECTION:
;saraheee.site.                 IN      A

;; AUTHORITY SECTION:
saraheee.site.          900     IN      SOA     ns-1536.awsdns-00.co.uk. awsdns-hostmaster.amazon.com. 1 7200 900 1209600 86400

;; Query time: 1 msec
;; SERVER: 192.168.0.2#53(192.168.0.2)
;; WHEN: Thu Feb 06 07:15:42 UTC 2025
;; MSG SIZE  rcvd: 129


3. Default VPC Resolver
   - VPC의 기본 .2 리졸버

$ cat /etc/resolv.conf
options timeout:2 attempts:5
; generated by /usr/sbin/dhclient-script
search anycompany.corp
nameserver 192.168.2.250
nameserver 192.168.0.2

 

4. Public DNS resolve 시도 (Route 53 Public Hosted Zone 포함)

$ dig example.com
; <<>> DiG 9.18.28 <<>> example.com;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 6753
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 4096
;; QUESTION SECTION:
;saraheee.site.                 IN      A

;; ANSWER SECTION:
saraheee.site.          30      IN      A       8.8.8.8

;; Query time: 1610 msec
;; SERVER: 10.0.0.2#53(10.0.0.2) (UDP)
;; WHEN: Thu Feb 06 07:15:47 UTC 2025;; MSG SIZE  rcvd: 58

 

아웃바운드 엔드포인트가 구성된 Resolver 규칙이 있는 경우, 프라이빗 호스팅 영역과 동일한 VPC에 연결되어 있을 때 리졸버 규칙이 우선적으로 적용될 수 있다.

다만 Private hosted zone이 VPC 내부에서만 작동하는 DNS라, dig +trace 시 공개적인 DNS 해석 과정이 포함된 root DNS와는 독립적으로 작동한다.

 

728x90
728x90
728x90
반응형

# 최대 홉 수 조정

traceroute -m 255 google.com

$ traceroute -m 255 google.com         
traceroute to google.com (172.217.161.206), 255 hops max, 40 byte packets
 1  10.40.6.2 (10.40.6.2)  9.359 ms  4.503 ms  4.032 ms
 2  10.40.240.0 (10.40.240.0)  4.312 ms  7.856 ms  4.707 ms
 3  10.40.0.11 (10.40.0.11)  7.454 ms  4.417 ms  5.650 ms
 4  10.128.2.139 (10.128.2.139)  6.526 ms  4.745 ms  6.370 ms
 5  15.248.4.57 (15.248.4.57)  8.095 ms  7.118 ms  5.761 ms
 6  * * *
 7  * * *
 8  * * *
 9  99.82.179.80 (99.82.179.80)  33.133 ms  33.374 ms  33.518 ms
10  99.82.179.81 (99.82.179.81)  34.269 ms  33.815 ms
    99.82.179.83 (99.82.179.83)  30.787 ms
11  192.178.108.209 (192.178.108.209)  35.272 ms  34.049 ms
    216.239.59.149 (216.239.59.149)  27.305 ms
12  108.170.235.5 (108.170.235.5)  34.331 ms
    108.170.235.7 (108.170.235.7)  38.985 ms
    108.170.235.5 (108.170.235.5)  34.198 ms
13  kix07s03-in-f14.1e100.net (172.217.161.206)  33.920 ms  33.770 ms  33.259 ms

 

# 패킷 크기 조정

traceroute google.com 70

$ traceroute google.com 70
traceroute to google.com (172.217.161.206), 64 hops max, 70 byte packets
 1  10.40.6.2 (10.40.6.2)  11.566 ms  5.021 ms  5.796 ms
...

 

# 패킷 테스트 횟수 조정

traceroute -q1 google.com

$ traceroute -q1 google.com
traceroute to google.com (172.217.161.206), 64 hops max, 40 byte packets
 1  10.40.6.2 (10.40.6.2)  5.512 ms
...

# DNS 역방향 조회 건너뛰기

traceroute -n google.com

$  traceroute -n google.com
traceroute to google.com (172.217.161.206), 64 hops max, 40 byte packets
 1  10.40.6.2  7.717 ms  2.673 ms  3.887 ms
 2  10.40.240.0  5.463 ms  2.376 ms  3.898 ms
 3  10.40.0.11  4.332 ms  6.298 ms  4.902 ms
 4  10.128.2.139  4.251 ms  5.431 ms  3.800 ms
 5  15.248.4.57  7.327 ms  6.855 ms  5.558 ms
 6  * * *
 7  * * *
 8  * * *
 9  99.82.179.82  28.092 ms  28.069 ms
    99.82.179.80  33.980 ms
10  99.82.179.81  33.186 ms
    99.82.179.83  29.556 ms
    99.82.179.81  32.288 ms
11  192.178.108.209  36.233 ms
    216.239.59.149  27.248 ms
    192.178.110.61  27.490 ms
12  108.170.235.7  35.891 ms
    108.170.235.5  35.220 ms
    108.170.235.7  34.109 ms
13  172.217.161.206  33.306 ms  34.519 ms  32.720 ms

 

format:

hop_number host_name (IP_address) packet_round_trip_times

hop_number: 경유 순서

host_name: 호스트 이름 (역방향 조회 결과)

IP_address: IP 주소

packet_round_trip_times: 왕복 시간 (기본 3회 측정)

 

asterisks (*): 경로상 문제가 없음을 의미

 

Tutorial: Troubleshooting with Traceroute

https://www.youtube.com/watch?v=WL0ZTcfSvB4

 

How To Use Traceroute and MTR to Diagnose Network Issues

https://www.digitalocean.com/community/tutorials/how-to-use-traceroute-and-mtr-to-diagnose-network-issues

 

$ mtr google.com

$ mtr --report google.com

 

728x90
728x90

'Networking > Network' 카테고리의 다른 글

[Route53] name servers  (0) 2025.02.07
[essential#03] Wireshark  (0) 2025.02.07
[essentials#01] Server-Client communication using Netcat  (0) 2025.02.06
[AWS] setting up Nginx SSL  (0) 2024.07.30
VPN - Site-to-Site, Client VPN  (0) 2024.02.13
728x90
반응형

Layer 4: https://www.youtube.com/playlist?list=PLelEzczSdJkCukp60g0DOGr7aruKyS6Rs
Layer 5:
why TLS and SSL - 
https://www.youtube.com/watch?v=SJJmoDZ3il8
How the negotiation works - https://www.youtube.com/watch?v=n_d1rCXNrx0
RE:Invent talk about TLS - https://www.youtube.com/watch?v=8AODa_AazY4

1. Connection

1. run in the server mode

nc -l 2389

서버가 2389 포트에서 연결 대기 시작

-l: 리스닝 모드로 실행

 

2. used in client mode

nc localhost 2389

클라이언트가 서버의 2389 포트로 연결 시도, localhost (or 서버IP)

 

서버IP 확인

# private ip
ifconfig
ip addr

# public ip
curl ifconfig.me
wget -q0- ifconfig.me
(whatismyip.com)

# ipv6
curl -6 ifconfig.me

 

3. 통신 테스트

# at client side
HI, server
# displayed at server side
HI, server

클라이언트가 메시지 전송, 서버 측에서 동일한 메시지 수신 확인

 

특징: 양방향 통신, 텍스트 기반, 간단한 소켓 통신 테스트에 유용, 실시간 메시지 전송/수신

2. File Transfer

1. initial setup

# client side - Create source file
$ echo "hello test" > testfile
$ cat testfile
hello test

# server side - Empty destination file
$ touch test

클라이언트 측 testfile이라는 파일이 있고, 내용은 hello test

서버 측 빈 test 파일이 존재

수신된 데이터를 test 파일로 리다이렉션, 서버 측의 test 파일에서는 클라이언트가 보낸 "hello test" 내용이 저장됨

3. Timeout

-w 플래그를 통해 연결 타임아웃을 설정할 수 있음

# server side
nc -l 2389

# client side
nc -w 10 localhost 2389

4. IPv6 connect

-4 또는 -6 플래그는 netcat 유틸리티가 어떤 유형의 주소를 사용해야 하는지 지정한다.

(-4 없이 IPv4 주소를 적을 경우 연결 가능)

# server side
nc -4 -l 2389

# client side
nc -4 localhost 2389

5. Disable reading from STDIN

1) -d 플래그: stdin(표준 입력)에서 읽기를 비활성화

클라이언트에서 서버로 데이터 전송을 막음

(연결 수립 이후 텍스트 입력해야 함, 마지막 hi는 -d와 관계없이 무시됨)

2) -k 플래그: (keep listening) 서버 측 옵션, 클라이언트가 연결을 종료해도 서버는 계속 실행되어 새로운 클라이언트 연결 대기 상태 유지

→ 다중 클라이언트 연결 가능, 서버 수동 종료 전까지 계속 실행

3) -q 플래그: EOF(파일이나 데이터 스트림의 끝, 데이터 전송이 완료되었음을 알리는 시그널) 수신 후 5초간 대기

→ -w 플래그로 대체됨

# server side
nc -l 2389 > received_file.txt

# client side
 date; cat file.txt | nc -w 5 localhost 2389; date

4) -u 플래그: UDP 옵션 (서버와 클라이언트 모두 설정)

$ netstat -an | grep 2389
udp4 0 0 127.0.0.1.61430 127.0.0.1.2389
udp4 0 0 127.0.0.1.2389 127.0.0.1.61430

 

 

728x90
728x90

'Networking > Network' 카테고리의 다른 글

[essential#03] Wireshark  (0) 2025.02.07
[essentials#02] Telnet  (0) 2025.02.06
[AWS] setting up Nginx SSL  (0) 2024.07.30
VPN - Site-to-Site, Client VPN  (0) 2024.02.13
보안 그룹과 네트워크 ACL(Stateful vs Stateless)  (0) 2024.02.12
728x90
반응형

 

본인 IP 조회

curl ifconfig.me

 

1. 데이터베이스 계정에 RDS DB 인스턴스 및 RDS 프록시 생성

2. RDS Proxy 엔드포인트에 할당된 IP 주소 식별

- dig (proxy endpoint arn) 의 Answer section

3. 데이터베이스 계정에 PrivateLink 엔드포인트 서비스 생성

1) 데이터베이스 계정에 타겟 그룹 생성

2) 데이터베이스 계정에 Network Load Balancer 생성

3) 데이터베이스 계정에 VPC 엔드포인트 서비스 생성

4. 고객 계정에서 VPC 엔드포인트 생성

5. 연결 테스트

 

psql -h <db-endpoint> -p <port-number> -d <db-name> -U <username> -W

 

psql -h nlbdb-database-ee.cluster-c78suu4aug2x.us-east-1.rds.amazonaws.com -p 5432 -d nlbdb-database-ee -U postgres

 

References:

[] Connect to an AWS RDS PostgreSQL database using PSQL - https://onticdani.medium.com/connect-to-an-aws-rds-postgresql-database-using-psql-750c00b5ceb2

[] Access Amazon RDS across AWS accounts using AWS PrivateLink, Network Load Balancer, and Amazon RDS Proxy - https://aws.amazon.com/ko/blogs/database/access-amazon-rds-across-aws-accounts-using-aws-privatelink-network-load-balancer-and-amazon-rds-proxy/
[] Use Amazon RDS Proxy and AWS PrivateLink to access Amazon RDS databases across AWS Organizations at American Family Insurance Group - https://aws.amazon.com/blogs/database/use-amazon-rds-proxy-and-aws-privatelink-to-access-amazon-rds-databases-across-aws-organizations-at-american-family-insurance-group/

 

728x90
728x90

'Networking > AWS' 카테고리의 다른 글

[AWS] VPC - Basic docs  (0) 2025.02.10
[AWS] VPC DNS resolver 우선 순위  (0) 2025.02.06
[AWS] SAA-C03#12: Route 53 (2)  (0) 2024.08.07
[AWS] SAA-C03#11: Route 53 (1)  (0) 2024.08.07
[AWS] ANS-C01#02: VPC fundamentals  (2) 2024.07.24
728x90
반응형

Route 53 - Routing Policies

라우팅 정책은 Route 53가 DNS 쿼리에 응답하는 것을 도움, DNS 관점(DNS는 트래픽 라우팅하지 않음, 트래픽은 DNS를 통과하지 않음)
- 로드 밸런서가 트래픽을 백엔드 EC2 인스턴스에 라우팅하는 것과는 다름
- DNS는 DNS 쿼리에만 응답하게 되고 클라이언트들은 이를 통해 HTTP 쿼리 등을 어떻게 처리해야 하는지를 알 수 있게 됨
- DNS는 호스트 이름들을 클라이언트가 실제 사용 가능한 엔드 포인트로 변환하는 것을 도움
Route 53이 지원하는 라우팅 정책: 단순, 가중치 기반, 장애 조치, 지연 시간 기반, 지리적, 다중 값 응답, 지리 근접 라우팅 정책
(Simple, Weighted, Failover, Latency based, Geolocation, Multi-Value Answer, Geoproximity (using Route 53 Traffic Flow feature)

Routing Policies - Simple

트래픽을 단일 리소스로 보내는 방식
클라이언트가 foo.example.com으로 가고자 한다면 Route 53이 IP 주소를 알려주는 것 (A 레코드 주소)
동일한 레코드에 여러 개의 값을 지정하는 것도 가능함. DNS에 의해 다중 값을 받은 경우에는 클라이언트 쪽에서 그 중 하나를 무작위로 고르게 됨 (e.g., 클라이언트가 foo.example.com으로 가기를 요청하고, Route 53은 세 개의 IP 주소로 답할 때(A 레코드에 임베딩된 주소), 클라이언트가 셋 중 하나를 골라 라우팅에 적용함)
단순 라우팅 정책에 별칭 레코드를 함께 사용하면 하나의 AWS 리소스만을 대상으로 지정할 수 있음 - 그렇기 때문에 상태 확인은 불가

Hands-on#04. Simple

value IP 추가하면서 테스트

Routing Policies - Weighted

가중치를 활용해 요청의 일부 비율을 특정 리소스로 보내는 식의 제어가 가능
한 DNS 이름 하에 있는 다른 레코드들과 비교했을 때 해당 레코드로 트래픽을 얼마나 보낼지, 각 레코드에 상대적으로 가중치를 할당함
이렇게 하면 DNS 레코드들은 동일한 이름과 유형을 가져야 하고 상태 확인과도 관련될 수 있음
사용되는 경우: 서로 다른 지역들에 걸쳐 로드 밸런싱을 할 때, 적은 양의 트래픽을 보내 새 애플리케이션을 테스트하는 경우
- 가중치 0의 값을 보내게 되면 특정 리소스에 트래픽 보내기를 중단해 가중치를 바꿀 수 있음
- 만약 모든 리소스 레코드 가중치의 값이 0인 경우는 모든 레코드가 다시 동일한 가중치를 갖게 됨

Hands-on#05. Weighted

Record ID: 가중치 레코드 설정에서 이 특정 레코드를 식별하기 위해 사용됨
- simple 레코드는 여러 개의 IP 주소를 가진 반면 weighted 세 개의 레코드는 각각 하나의 값을 가짐

Routing Policies - Latency-based

지연 시간이 가장 짧은, 가장 가까운 리소스로 리다이렉팅하는 정책
지연 시간에 민감한 웹사이트나 애플리케이션이 있는 경우 유용한 정책
지연 시간은 유저가 레코드로 가장 가까운 식별된 AWS 리전에 연결하기까지 걸리는 시간을 기반으로 측정
(e.g., 유저가 독일에 있고 미국에 있는 리소스의 지연 시간이 가장 짧다면, 해당 유저는 미국으로 리다이렉팅이 될 것)
- 두 개의 다른 리전에 애플리케이션을 배포할 때

Hands-on#06. Latency-based

별칭이 해당 IP가 어느 지역에 있는 EC2 인스턴스에서 왔다는 것을 알 수 없기 때문에,
값에 IP 주소를 입력해도 이 IP의 리전을 표시해줘야 함

Route 53 - Health Checks

상태 확인은 공용 리소스에 대한 상태를 확인하는 방법
e.g., (다중 지역 셋업) 서로 다른 두 지역에 하나씩 로드 밸런서가 있고 둘은 모두 공용 로드 밸런서임, 그리고 그 둘의 뒤에서 애플리케이션이 작동 중 - 지역 레벨에서 고가용성을 원하는 상황
- Route 53을 이용해 DNS 레코드를 만들 것
- 유저가 mydomain.com과 같은 URL을 이용해 접속하면 해당 유저는 가장 가까운 로드 밸런서로 연결됨 (지연 시간 기반 레코드)
만약 한 지역이 사용 불가능 상태면 유저를 보내고 싶지 않기 때문에 Route 53에서 상태 확인을 생성해야 함
- 두 지역의 상태 확인을 Route 53의 레코드와 연결할 수 있음 (DNS의 장애 조치를 자동화하기 위한 작업)
세 가지의 상태 확인(Health Check)이 가능함
- 각 상태 확인은 각자의 메트릭을 사용하는데 CloudWatch의 지표에서도 확인 가능
1) 공용 엔드 포인트를 모니터링하는 상태 확인
- 애플리케이션, 서버, 다른 AWS 리소스
2) 다른 상태 확인을 모니터링하는 상태 확인 (계산된 상태 확인)
3) CloudWatch 경보의 상태를 모니터링하는 상태 확인
- 제어가 쉽고 개인 리소스들에 유용함

Health Checks - Monitor an Endpoint

ALB에 대한 특정 지역의 상태 확인을 한다고 하면, 전 세계로부터 15개 정도의 AWS 상태 확인이 옴
→ 우리가 루트를 설정한 공용 엔드 포인트로 모두 요청을 보냄
→ 엔드 포인트의 상태를 확인하고 임계값을 정상 혹은 비정상으로 설정함 (200 OK 코드 또는 우리가 정의한 코드를 받으면 리소스는 정상으로 간주됨)
- 간격: 30초마다 정기적으로 확인 혹은 10초마다(더 높은 비용)
- 지원 프로토콜: HTTP, HTTPS, TCP
- 18% 이상의 상태 확인이 엔드 포인트를 정상이라고 판단하면 Route 53도 이를 정상이라고 간주함
- 상태 확인에 사용될 위치 선택 가능
- 로드 밸런서로부터 2xx나 3xx의 코드를 받아야만 통과가 됨
텍스트 기반 응답일 경우 상태 확인은 응답의 처음 5120 byte를 확인함 (응답 자체에 해당 텍스트가 있는지 보기 위해)
상태 확인의 작동이 가능하려면 상태 확인이 ALB나 엔드 포인트에 접근이 가능해야 함
Route 53의 상태 확인 IP 주소 범위에서 들어오는 모든 요청을 허용해야 함 (주소 범위는 https://ip-ranges.amazonaws.com/ip-ranges.json 참고)

Route 53 - Calculated Health Checks

여러 개의 상태 확인 결과를 하나로 합쳐주는 기능
- 조건: OR, AND, NOT
하위 상태 확인을 256개까지 모니터링할 수 있고 상위 상태 확인이 통과하기 위해 몇 개의 상태 확인을 통과해야 하는지도 지정할 수 있음
→ 상태 확인이 실패하는 일 없이 상위 상태 확인이 웹사이트를 유지 관리하도록 하는 경우

Health Checks - Private Hosted Zones

개인의 리소스를 모니터링하는 것은 어려울 수 있음
Route 53 상태 확인이 공용 웹에 있기 때문에 health checkers는 VPC 외부에 있음
개인 엔드 포인트에 접근 불가능 (개인 VPC나 온프레미스 리소스)
그래서 CloudWatch 지표를 만들어 CloudWatch 알람을 할당하는 식으로 이 문제를 해결할 수 있음
→ CloudWatch 경보를 상태 확인에 할당할 수 있음 (CloudWatch 메트릭을 이용해 개인 서브넷 안에 있는 EC2 인스턴스를 모니터링하는 것)
메트릭이 침해되는 경우 CloudWatch 알람을 생성하게 되고, 알람이 ALARM 상태가 되면 상태 확인은 자동으로 비정상이 됨
→ 개인 리소스에 대한 상태 확인 완료

Hands-on#07. Health Check

1) 엔드 포인트가 될 region 인스턴스의 상태 확인을 생성 (세 리전 모두)
path: /health (엔드 포인트 자체의 상태에 대한 응답)
Advanced configuration: String matching - 첫 5120 바이트 문자열을 비교할지 여부를 선택
2) 특정 region에 있는 한 인스턴스의 보안 그룹에서 80번 포트를 차단하고 security groups의 HTTP 관련 rule을 삭제 (상태 확인 장애를 발생시킴)
3) create health check - name: calculated / status of other health checks (calculated health check)
4) create health check - state of CloudWatch alarm
- 개인 EC2 인스턴스의 상태를 모니터링할 수 있음
- 개인 리소스의 상태 확인을 Route 53 상태 확인에 연결하는 것

Routing Policies - Failover (Active-Passive)

장애 조치에 관한 것
Route 53에 대해 하나는 기본 EC2 인스턴스, 하나는 보조 EC2 인스턴스(재해 복구 EC2 인스턴스)일 때
상태 확인과 기본 레코드를 연결하는데 필수적
상태 확인이 비정상이면 자동으로 Route 53은 두번째의 EC2 인스턴스로 장애 조치하며 결과를 보내기 시작함
보조 EC2 인스턴스도 상태 확인을 연결할 수 있지만 기본과 보조가 각각 하나씩만 있을 수 있음
→ 클라이언트의 DNS 요청은 정상으로 생각되는 리소스를 자동으로 얻음

Hands-on#08. Failover

상태 확인을 통해 장애 조치 레코드를 생성 (호스팅 영역에서 레코드를 생성)
보안 그룹 수정하여 장애 조치가 실행되는 위치를 확인

Routing Policies - Geolocation

사용자의 실제 위치를 기반으로 함 (지연 시간 기반의 정책과는 다르게)
사용자가 특정 대륙이나 국가 또는 어떤 주에 있는지 지정하는 것이며, 가장 정확한 위치가 선택되어 그 IP로 라우팅되는 것
일치하는 위치가 없는 경우는 기본 레코드를 생성해야 함
사용 사례: 콘텐츠 분산을 제한하고 로드 밸런싱 등을 실행하는 웹사이트 현지화
- 상태 확인과 연결할 수 있음
e.g., 유럽의 지도에서, 독일의 유저가 독일어 버전의 앱을 포함한 IP로 접속되도록 독일의 지리 레코드를 정의할 수 있음, 프랑스는 프랑스어의 버전의 앱을 가진 IP로 가야 함, 그 외의 다른 곳은 앱에서 영어 버전이 포함된 기본 IP로 이동해야 함

Hands-on#09. Geolocation

Location이 다른 IP에 대해 테스트

Geoproximity Routing Policy

사용자와 리소스의 지리적 위치를 기반으로 트래픽을 리소스로 라우팅함
이 정책으로 편향값을 사용해 특정 위치를 기반으로 리소스를 더 많은 트래픽을 이동하는 것
→ 지리적 위치를 변경하려면 편향값을 지정해야 함, 특정 리소스에 더 많은 트래픽을 보내려면 편향값을 증가시켜서 확장하면 됨, 리소스에 트래픽을 줄이려면 편향값을 음수로 축소시키면 됨
리소스는 AWS의 리소스로 속한 특정 리전을 지정하면 목록에서 자동으로 올바른 라우팅을 계산하거나, AWS 리소스가 아닌 온프레미스 데이터 센터의 경우 위도와 경도를 지정해서 AWS가 위치를 파악하도록 해야 함
기능을 선택하는데 편향 활용을 위해 고급 Route 53 트래픽 플로우를 사용함
- 편향이 없다면, 사용자 위치에서 가장 가까운 리소스 리전으로 이동하는 것
- 편향으로 인해 다른 방식으로 사용자를 다른 리전으로 라우팅할 수 있음, 편향으로 해당 리소스에 더 많은 사용자와 트래픽이 발생함 (편향이 높을 경우)
예를 들어, 전 세계로 리소스를 설정하고 특정 리전에 더 많은 트래픽을 더 보내야 한다고 하면 지리 근접 라우팅 정책을 사용해 특정 리전의 편향을 증가시키면 더 많은 사용자가 생기게 되고 특정 리전에 더 많은 트래픽이 발생하게 됨
- 지리 근접 라우팅은 편향을 증가시켜 한 리전에서 다른 리전으로 트래픽을 보낼 때 유용하다는 것

Routing Policies - IP-based Routing

클라이언트 IP 주소를 기반으로 라우팅을 정의함 → Route 53에서 CIDR 목록을 정의함 (클라이언트 IP 범위) → CIDR에 따라 트래픽을 어느 로케이션으로 보내야 하는지를 정함
- 이것을 사용하면 성능을 최적화할 수 있음, IP를 미리 알고 있기 때문
- 네트워크 비용을 절감할 수 있음, IP가 어디에서 오는지 알기 때문
예를 들어 특정 ISP가 특정 IP 주소 셋을 사용하는걸 안다면 특정 엔드포인트로 라우팅할 수 있음
e.g., Route 53에서 두 로케이션을 서로 다른 두 CIDR 블록으로 정의함 (location-1: 203.x.x.x/24, location-2: 200.x.x.x/24)
→ 로케이션을 레코드에 연결 (record name: example.com / value: 1.2.3.4 and 5.6.7.8 / IP-based: location1 and location2)
- 이 값들은 두 개의 EC2 인스턴스의 공용 IP를 나타냄
→ 사용자 A가 location-1 CIDR blocks에 속하는 특정 IP로 들어오면 첫번째 EC2 인스턴스인 IP 1.2.3.4로 보내짐
+ 사용자 B가 location-2에 속하는 IP 주소로 들어오면 리디렉션되어 IP 5.6.7.8의 EC2 인스턴스에 대한 DNS 쿼리 응답을 받게 됨

Routing Policies - Multi-Value

- 트래픽을 다중 리소스로 라우팅할 때 사용함, 그래서 Route 53은 다중 값과 리소스를 반환함
- 상태 확인과 연결하면 다중 값 정책에서 반환되는 유일한 리소스는 정상 상태 확인과 관련이 있음
- 각 다중 값 쿼리에 최대 8개의 정상 레코드가 반환됨
- ELB와 유사해 보이지만 ELB를 대체할 수는 없음 (클라이언트 측면의 로드 밸런싱)
e.g., example.com에서 다중 A 레코드를 설정하고 상태 확인과 연결함
클라이언트에서 다중 값 쿼리를 실행하면 최대 8개의 레코드를 수신하게 되고 클라이언트는 하나를 선택함, 하지만 최소한 상태 확인과 결합하면 반환되는 8개 레코드 중 1개 혹은 최대 8개의 레코드가 정상일 것을 알고 있음
그래서 클라이언트는 안전한 쿼리를 가질 수 있음
e.g., 다중 값이 있는 단순한 라우팅의 경우에는 단순 라우팅 정책은 상태 확인을 허용하지 않기 때문에 단순 라우팅 정책의 쿼리가 반환하는 리소스 중 하나는 비정상일 가능성이 있음, 이것이 다중 값이 조금 더 강력한 레코드 유형인 이유

Hands-on#10. Multi-Value

세 리전에 대한 multi
Health checks에서 Invert health check status 체크하여 정상에서 비정상으로 변경

Domain Registar vs. DNS Service

도메인 이름 레지스트라를 통해 원하는 도메인 이름을 구매할 수 있음, 레지스트라를 통해 도메인을 등록하면 DNS 레코드 관리를 위한 DNS 서비스를 제공함, 그래서 Amazon 호스트 이름으로 DNS 이름을 등록했다면 DNS 레코드 관리를 위한 Route 53 호스팅 존을 가짐
도메인 이름을 등록하면 네임 서버 옵션이 생기는데 사용자 정의 이름 서버를 지정할 수 있음 (Route 53에서 원하는 도메인의 공용 호스팅 영역을 생성하고 호스팅 영역 상세의 우측 네임 서버를 구매한 사이트(GoDaddy 등)에서 변경해야 함)
GoDaddy에서 사용할 이름 서버에 관한 쿼리에 응답하면 네임 서버가 Amazon의 Route 53 이름 서버를 가리키고 그렇게 Route 53을 사용해서 해당 콘솔에서 직접 전체 DNS 레코드를 관리함
- 정리: 도메인을 타사 등록 대행사에서 구매해도 DNS 서비스 제공자로 Route 53을 사용 가능한데, 사용하려면 Route 53에서 공용 호스팅 영역을 생성한 뒤 도메인을 구매한 타사 웹사이트에서 NS 혹은 이름 서버를 업데이트하면 Route 53 이름 서버를 가리키게 됨
→ 도메인 이름 레지스트라는 모두 비슷해 보이지만 DNS 서비스가 다름

 

References

Udemy, Ultimate AWS Certified Solutions Architect Associate SAA-C03, Section 10: Route 53

 

728x90
728x90
728x90
반응형

DNS: Domain Name System which translates the human friendly hostnames into the machine IP addresses

DNS Terminologies (관련 용어)

Domain Registrar(도메인 이름 등록하는 곳): Amazon Route 53, GoDaddy, ...

DNS Records: A, AAAA, CNAME, NS, ...

Zone File: contains DNS records

Name Server: resolves DNS queries

1) Web Browser가 example.com에 접근하기 위해서는 Local DNS server에 물어볼 것
* Local DNS Server: 보통 회사에 의해 할당되고 관리되거나 ISP에 동적으로 할당됨
2) Local DNS Server가 이 쿼리를 본 적이 없다면 먼저 ICANN에 관리된 Root DNS Server에 물어볼 것
→ .com은 알고 있음 (.com NS 1.2.3.4) 반환
3) 1.2.3.4에 있는 .com 도메인 서버에게 쿼리의 답을 요청 (TLD DNS Server, Managed by IANA, Branch of ICANN)
→ DNS 서버는 example.com을 모르지만 example.com 이라는 서버는 알고 있음 (example.com NS 5.6.7.8)
4) 로컬 DNS 서버(서브도메인의 DNS 서버)에 질의: 도메인 네임 레지스트라(Route 53 등)에 의해 관리되는 서버, 최종 서버
→ example.com에 대해 알고 있음. example.com은 A 레코드이고 이것의 결과로 IP 9.10.11.12를 얻음

Route 53

a highly, available, scalable, fully managed and authoritative DNS, DNS 레코드를 업데이트할 수 있음
DNS 레코드를 아마존 Route 53의 호스팅 존에 쓰려고 함, 클라이언트가 example.com을 요청하면 Route 53 서비스가 IP 54.22.33.44를 찾고 있다고 응답함 → 클라이언트는 바로 EC2 인스턴스에 접근함, Route 53도 도메인 이름 레지스트라로 도메인 이름을 example.com으로 등록함
Route 53에서 여러 DNS 레코드를 정의하고 레코드를 통해 특정 도메인으로 라우팅하는 방법을 정의함
각 레코드는 도메인이나 example.com과 같은 서브도메인 이름과 같은 정보를 포함함
* TTL: DNS 리졸버에서 레코드가 캐싱되는 시간

Route 53 - Record Types

A - maps a hostname to IPv4
AAAA - maps a hostname to IPv6
CNAME - maps a hostname to another hostname
- 대상 호스트 이름은 A나 AAAA 레코드가 될 수 있음
- Route 53에서 DNS namespace 또는 Zone Apex의 상위 노드에 대한 CNAME을 생성할 수 없음
(e.g., example.com에 대한 CNAME을 만들 수는 없지만, www.example.com에 대한 CNAME 레코드는 만들 수 있음)
NS - Name Servers for the Hosted Zone
- 서버의 DNS 이름 또는 IP 주소로 호스팅 존에 대한 DNS 쿼리에 응답할 수 있음
- 트래픽이 도메인으로 라우팅되는 방식을 제어함

Route 53 - Hosted Zones

a container for records, 도메인과 서브도메인으로 가는 트래픽의 라우팅 방식을 정의함
Public Hosted Zones - 쿼리에 도메인 이름 application1.mypublicdomain.com의 IP가 무엇인지 알 수 없음
Private Hosted Zones - 공개되지 않은 도메인 이름을 지원, 가상 프라이빗 클라우드(VPC)만이 URL을 resolve할 수 있음(e.g., application1.company.internal)

Route 53 - Public vs. Private Hosted Zones

Public Hosted Zones: 공개된 클라이언트로부터 온 쿼리에 응답할 수 있음, 웹 브라우저에서 example.com을 요청하면 IP를 반환함
- 퍼블릭 레코드를 위한 호스팅 존
Private Hosted Zones: 해당 VPC에만 동작, 비공개 도메인 이름의 프라이빗 리소스를 식별할 수 있음
- 프라이빗 리소스, 예컨대, VPC에서만 쿼리할 수 있음

EC2 인스턴스가 1개 있고, webapp.example.internal을 식별하고자 함
또 다른 EC2 인스턴스에서는 api.example.internal을 식별하기 원하고 데이터베이스에서는 db.example.internal을 식별하고자 함
private hosted zone에 등록하고자 하는데, 첫번째 EC2 인스턴스가 api.example.internal을 요청하는 경우 프라이빗 호스팅 존은 프라이빗 IP 10.0.0.10이라는 답을 갖고 있음. EC2 인스턴스는 데이터베이스에 연결이 필요할 수도 있는 두번째 EC2 인스턴스에 연결하여 db.example.internal이 무엇인지 물어보면 프라이빗 호스팅 존은 프라이빗 IP를 알려줌

Hands-on#01. Route 53 setting up

1) Registered domains
2) Hosted zones - Create record A
3) cloudshell

sudo yum install -y bind-utils
nslookup domain.com
dig domain.com

4) Create EC2 Instances
- 서로 다른 리전에 세 인스턴스 생성(e.g., NRT, ICN, KIX - Tokyo, Seoul, Osaka)
- proceed without a key pair
- allow HTTP traffic from the internet

#!/bin/bash
yum update -y
yum install -y httpd
systemctl start httpd
systemctl enable httpd
EC2_AVAIL_ZONE=$(curl -s http://169.254.169.254/meta-data/placement/availability-zone)
echo “<h1>Hello World from $(hostname -f) in AZ $EC2_AVAIL_ZONE </h1>” > /var/www/html/index.html

- Hello World 뒤에 인스턴스 정보를 출력할 것, 인스턴스가 시작되는 가용 영역도 포함시키는 과정에서 환경 변수 $EC2_AVAIL_ZONE을 사용
5) Create Load Balancer (DemoRoute53ALB)
- create TG
6) open addresses & LB에서 DNS name이 프로비저닝 되었는지 확인
ap-northeast-1(Tokyo): 54.199.162.15x
ap-northeast-2(Seoul): 43.201.64.18x
ap-northeast-3(Osaka): 13.208.191.12x

Route 53 - Records TTL (Time To Live)

클라이언트가 DNS Route 53와 웹 서버에 접속한다고 할 때,
myapp.example.com에서 DNS 요청을 보내면 DNS로부터 회신을 받음 (회신 내용: A 레코드, IP 주소, TTL(300초 정도))
TTL은 클라이언트에게 이 결과를 캐시하도록 요청함 (클라이언트는 300초 동안 결과를 캐시함)
→ 클라이언트가 재요청을 보내거나 같은 호스트 이름으로 접속할 경우, 클라이언트는 답변을 캐시에 저장해서 답을 알기 때문에 DNS 시스템에게 쿼리를 보내지 않아도 된다는 의미
하지만 캐시에도 시간이 소요되어 캐시 TTL이 발생, DNS 요청 쿼리를 계속해서 자주 보내는 상황을 원치 않기 때문
저장된 답변을 이용함으로써 웹 서버에 접속이 가능하고 HTTP 요청 및 회신을 보낼 수 있음
1) High TTL - e.g., 24 hr
TTL을 24시간으로 높게 설정하면 결과가 24시간 동안 캐시되므로 Route 53의 트래픽은 현저히 적음 (클라이언트가 요청을 적게 보냄)
-> 클라이언트가 오래된 레코드를 받을 가능성이 있음 (레코드를 바꾸고자 한다면 모든 클라이언트들이 새 레코드를 캐시에 저장할 때까지 24시간을 기다려야 한다는 뜻)
2) Low TTL - e.g., 60 sec.
TTL을 60초 정도로 짧게 설정한다면 DNS에는 트래픽 양의 많아져서 비용이 많이 듦 (Route 53에 들어오는 요청의 양에 따라 요금이 책정되기 때문)
오래된 레코드의 보관 시간은 짧아짐 -> 레코드 변경이 빨라짐

Hands-on#02. TTL

1) Create A record - IP region
2) record name으로 사이트 접속 혹은 cloudshell nslookup or dig
3) edit Record value
- 레코드 캐시가 만료될 때까지 확인

CNAME vs Alias

AWS 리소스(로드밸런서나 CloudFrond 등)를 사용하는 경우 호스트 이름이 노출됨, 그리고 보유한 도메인에 호스트 이름을 매핑하고자 할 수 있음
myapp.mydomain.com에 로드 밸런서를 매핑하는 경우 두 가지 옵션이 있는데,
1) CNAME 레코드로 호스트 이름이 다른 호스트 이름으로 향하도록 할 수 있음 (e.g., app.mydomain.com  blabla.anything.com)
- 루트 도메인 이름이 아닌 경우에만 가능 (aka. something.mydomain.com)
2) Alias: Route 53에 한정하여, 호스트 이름이 특정 AWS 리소스로 향하도록 할 수 있음 (e.g., app.mydomain.com  blabla.amazonaws.com)
- 루트 도메인과 비루트 도메인 모두에 작동함 (aka. mydomain.com, mydomain.com을 별칭으로 사용해 AWS 리소스로 향하도록 할 수 있음)
- 무료, 자체적으로 상태 확인 가능

Route 53 - Alias Records

AWS 리소스에만 매핑이 되어 있음
예를 들어 Route 53에서 example.com을 A 레코드의 별칭 레코드로 하고 그 값은 로드 밸런서의 DNS 이름을 지정하려 한다고 해보자.

기반이 되는 ALB에서 IP가 바뀌면 별칭 레코드는 바로 인식함
CNAME과 달리 별칭 레코드는 Zone Apex라는 DNS 네임 스페이스의 상위 노드로 사용될 수 있음
AWS 리소스를 위한 별칭 레코드의 타입은 항상 A 또는 AAAA (리소스는 IPv4나 IPv6 중 하나)
별칭 레코드를 사용하면 TTL을 설정할 수 없음 (Route 53에 의해 자동으로 설정됨)

Route 53 - Alias Records Targets

별칭 레코드의 대상은? ELB, CloudFront 배포, API Gateway, Elastic Beanstalk environments, S3 Websites(S3 버킷은 안됨, 버킷들이 웹사이트로 활성화될 시 S3 웹사이트는 가능), VPC Interface Endpoints, Global Accelerator accelerator, Route 53 record in the same hosted zone
- EC2의 DNS 이름은 별칭 레코드의 대상이 될 수 없음

Hands-on#03. CNAME vs. Alias

1) create CNAME record
- value: ALB DNS name
2) create A record
- Alias > Route traffic to ALB
- 별칭 레코드이기 때문에 Evaluate target health는 자동으로 Yes 체크되어 있음
3) create A record without subdomain

 

References

Udemy, Ultimate AWS Certified Solutions Architect Associate SAA-C03, Section 10: Route 53

 

728x90
728x90

'Networking > AWS' 카테고리의 다른 글

[AWS] VPC 엔드포인트 서비스를 RDS 프록시에 연결 (cross-account)  (0) 2024.12.10
[AWS] SAA-C03#12: Route 53 (2)  (0) 2024.08.07
[AWS] ANS-C01#02: VPC fundamentals  (2) 2024.07.24
[AWS] ANS-C01#01: ELB  (0) 2024.07.19
AWS products  (0) 2024.07.10
728x90
반응형

 

0. Connecting to an Instance

AWS CLI를 사용하여 인스턴스의 Linux OS 플랫폼 및 버전 정보 확인

uname
cat /proc/version

Linux version ~ ... ~ (Red Hat 11.4.1-2), ~ ...

Redhat 계열(centOS) - yum
Debian, Ubuntu - apt-get

1. Installing Nginx

nginx directory 생성
Nginx: 정적 컨텐츠를 제공해주는 프록시 서버

sudo yum install nginx
cd /etc && ls | grep nginx // check settings

sudo mkdir /etc/nginx/sites-available
sudo mkdir /etc/nginx/sites-enabled

 

2. Setting up config

1) nginx.conf 수정
: nginx 관련 설정을 블록 단위로 설정, sites-enable에 존재하는 파일 불러옴

sudo vi /etc/nginx/nginx.conf

    include /etc/nginx/sites-enabled/*.conf;

#    server {
#        listen       80;
#        listen       [::]:80;
#        server_name  _;
#        root         /usr/share/nginx/html;
#
#        # Load configuration files for the default server block.
#        include /etc/nginx/default.d/*.conf;
#
#        error_page 404 /404.html;
#        location = /404.html {
#        }
#
#        error_page 500 502 503 504 /50x.html;
#        location = /50x.html {
#        }
#    }

2) server 설정
: nginx 최신 버전을 따로 설치하지 않고 기본 설정된 repository에 있는 버전을 install nginx로 바로 설치한 경우에는 nginx 환경 설정 파일 위치가 /etc/nginx/sites-available/default로 설정됨,
최신 버전을 설치했을 경우 /etc/nginx/conf.d/default.conf [5]

sudo vi /etc/nginx/sites-available/default.conf

    server {
        listen 80;
        location / {
                root /project/nginx-project;  // path to deploy
                index index.html index.htm;
                try-files $url $url/ /index.html;
        }       
    }   

3) symbolic link 설정
: sites-enabled directory에 default.conf 바로가기 생성
sites-available에 존재하는 설정 파일들 중, 사용하는 설정 파일만 link해서 사용할 수 있도록 하는 디렉터리

cd /etc/nginx/sites-enabled
sudo ln -s /etc/nginx/sites-available/default.conf
ls -l

total 0
lrwxrwxrwx. 1 root root 39 Jul 30 04:42 default.conf → /etc/nginx/sites-available/default.conf
4) 웹서버 html 설정

sudo vi /project/nginx-project/index.html

<!DOCTYPE html>
<html>
<head>
    <title>Welcome to Nginx!</title>
</head>
<body>
    <h1>Welcome to Nginx!</h1>
    <p>If you see this page, the Nginx web server is successfully installed and working.</p>
    <p>Further configuration is required.</p>
</body>
</html>

3. Run the server

sudo systemctl start nginx

오류 시
status : Failed to start nginx.service - The nginx HTTP and reverse proxy server

sudo systemctl start nginx

Job for nginx.service failed because the control process exited with error code.
See "systemctl status nginx.service" and "journalctl -xeu nginx.service" for details.

: 80번 포트에 수신 대기중인 프로세스 삭제

fuser -k 80/tcp

4. Prepare SSL/TLS Certificate

- Generate a self-signed certificate or obtain a certificate from a Certificate Authority (CA)
1) Ensure that OpenSSL is installed on your operating system

openssl version

nginx가 ssl 적용이 가능한 모듈이 있는지 확인 (--with-http_ssl_module)

nginx -V

nginx version: nginx/1.24.0
built with OpenSSL 3.0.8 7 Feb 2023
TLS SNI support enabled
configure arguments: --prefix=/usr/share/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib64/nginx/modules --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --http-client-body-temp-path=/var/lib/nginx/tmp/client_body --http-proxy-temp-path=/var/lib/nginx/tmp/proxy --http-fastcgi-temp-path=/var/lib/nginx/tmp/fastcgi --http-uwsgi-temp-path=/var/lib/nginx/tmp/uwsgi --http-scgi-temp-path=/var/lib/nginx/tmp/scgi --pid-path=/run/nginx.pid --lock-path=/run/lock/subsys/nginx --user=nginx --group=nginx --with-compat --with-debug --with-file-aio --with-google_perftools_module --with-http_addition_module --with-http_auth_request_module --with-http_dav_module --with-http_degradation_module --with-http_flv_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_image_filter_module=dynamic --with-http_mp4_module --with-http_perl_module=dynamic --with-http_random_index_module --with-http_realip_module --with-http_secure_link_module --with-http_slice_module --with-http_ssl_module --with-http_stub_status_module --with-http_sub_module --with-http_v2_module --with-http_xslt_module=dynamic --with-mail=dynamic --with-mail_ssl_module --with-openssl-opt=enable-ktls --with-pcre --with-pcre-jit --with-stream=dynamic --with-stream_realip_module --with-stream_ssl_module --with-stream_ssl_preread_module --with-threads --with-cc-opt='-O2 -ftree-vectorize -flto=auto -ffat-lto-objects -fexceptions -g -grecord-gcc-switches -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -specs=/usr/lib/rpm/redhat/redhat-hardened-cc1 -fstack-protector-strong -specs=/usr/lib/rpm/redhat/redhat-annobin-cc1 -m64 -march=x86-64-v2 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection' —with-ld-opt='-Wl,-z,relro -Wl,—as-needed -Wl,-z,now -specs=/usr/lib/rpm/redhat/redhat-hardened-ld -specs=/usr/lib/rpm/redhat/redhat-annobin-cc1 -Wl,—build-id=sha1 -Wl,-dT,/builddir/build/BUILD/nginx-1.24.0/.package_note-nginx-1.24.0-1.amzn2023.0.2.x86_64.ld -Wl,-E’

2) 인증서 작업할 폴더 생성 (/usr/local/ssl)
3) Generate the Private Key
- Use the following OpenSSL command to generate the private key: 

openssl genrsa -des3 -out server.key 2048

Enter PEM pass phrase: 
> server.key 생성

4) Create a Certificate Signing Request (CSR)
- Use the following OpenSSL command to generate the certificate signing request (CSR) file: 

openssl req -new -key server.key -out server.csr

- During this process, you will be prompted to enter information such as country, state, city, company name, and domain name

5) Generate the Self-Signed Certificate
- Use the following OpenSSL command to generate the self-signed certificate: 

openssl x509 -req -days 3650 -in server.csr -signkey server.key -out server.crt

- -days 3650: 3650일짜리(10년) 인증서
- -in server.csr -signkey server.key: 개인 키와 서버 요청서를 가지고 인증서 server.crt 생성

5. Configure the Nginx configuration file

- Add the following HTTPS-related settings inside the server block: 
- Use the listen directive to specify port 443
- Use the ssl_certificate and ssl_certificate_key directives to specify the paths to the certificate files

> cd /etc/nginx/conf.d/
> sudo cp www.example.com.conf www.example.com.conf.bak
> sudo mkdir /etc/nginx/ssl
> sudo chmod 700 /etc/nginx/ssl
> sudo nano www.example.com.conf

server {
    listen       443 ssl;
    server_name  www.example.com;

    ssl_certificate /usr/local/ssl/server.crt;
    ssl_certificate_key /usr/local/ssl/server.key;
    
    ## omitted below
}

+ 공인 인증기관에서 발급하지 않은 인증서는 윈도우에서 host 파일을 수정하여 접근할 것
(참고)

vi /etc/nginx/conf.d/default.conf
vi /etc/nginx/sites-available/default.conf

    server {
            listen      443 ssl;
            server_name nginx-ssl-test.com;
            
            ssl_certificate     /usr/local/ssl/server.crt;
            ssl_certificate_key /usr/local/ssl/server.key;
            ssl_session_timeout 5m;
            ssl_protocols       SSLv2 SSLv3 TLSv1;
            ssl_ciphers         HIGH:!aNULL:!MD5;
            ssl_prefer_server_ciphers   on;
            
            location / {
                    root        /home/espeniel;
                    index       index.html index.htm;
            }       
    }   

6. Set up HTTP to HTTPS redirection

- Configure the server block to redirect HTTP (port 80) requests to HTTPS
- Use the return 301 directive to achieve the redirection

vi /etc/nginx/sites-available/default.conf

server {
    listen       80 default_server;
    server_name  nginx-ssl-test.com;
    return 301 https://$host$request_uri;
}

- nginx 서비스 확인

ps -ef | grep nginx

systemctl restart nginx

오류 시
(1) /usr/local/ssl/server.key 파일의 권한과 소유자 확인

sudo chmod 644 server.key
sudo chown nginx:nginx server.key

(2) openssl rsa -check -in /usr/local/ssl/server.key
(3) 로그 확인

sudo journalctl -u nginx

Jul 30 08:59:35 ip-172-31-39-33.ec2.internal nginx[3006]: nginx: [emerg] cannot load certificate key "/usr/local/ssl/server.key": PEM_read_bio_PrivateKey() failed (SSL: error:1400006B:UI routines::processing error:while reading strings error:0480006D:PEM routin>
Jul 30 08:59:35 ip-172-31-39-33.ec2.internal nginx[3006]: nginx: configuration file /etc/nginx/nginx.conf test failed

→ The private key has a passphrase requirement but nginx is not configured to use a passphrase.

7. delete key passphrase

1) Rename the existing server.key filename to server_pass.key

mv server.key server_pass.key

2) Create a new key without a passphrase requirement. It is assumed that the RSA key in use, otherwise adjust the command accordingly. When prompted, type the passphrase and press enter

openssl rsa -in server_pass.key -out server.key

3) Stop, start nginx service and check that no error message are displayed

8. local test
- www.example.com은 공인된 도메인이 아니라 사내에서 사용할 가상 도메인이므로 클라이언트 측 도메인에 대한 hosts 파일을 등록해야 함

9. (optional) Additional SSL/TLS-related Settings
- Use the ssl_session_cache and ssl_session_timeout directives to configure the SSL session cache
- Use the ssl_prefer_server_ciphers direcactive to prefer the server's cipher suites
- Use the add_header directive to add security-related headers

10. Test Configuration and Restart Nginx
- Use the nginx -t command to check the syntax of the configuration file
- Use the systemctl restart nginx command to restart the Nginx service

sudo nginx -t
sudo nginx -s reload

References:

[1] [AWS] EC2 인스턴스에 Nginx 적용하기
[2] [AWS] EC2 NGINX 설치하고 Config설정 및 배포하기
[3] OpenSSL로 개인키 발급 및 SSL 인증서 생성#1
[4] Nginx https 적용하기 openssl 사용, http https로 리다이렉트
[5] Ubuntu에서 Nginx SSL 인증서 설정하는 방법
[6] DPSearch - Nginx service fails to start after installing new SSL certificate

728x90
728x90

+ Recent posts