# Nasa
###### tags: `Linux`
## DHCP(Dynamic Host Configuration Protocol)
### 觀念
1. Allow a server to dynamically distribute network configuration to client.
3. DHCP server and PC clients on the the same LAN segment
4. When DHCP send configuration infomation to the client, the information is sent with lease time.
5. During the lease time, the DHCP server cannot assign that IP address to any other clients.
6. Make configuration changes to all of the clients on the network in a limited amount of time.
7. Client starts to renew a lease when half of the lease time
8. Requests the renewal by sending a DHCPREQUEST message to the server
### 實作
1. Install: `apt install isc-dhcp-server`
2. specify the interfaces listen: /etc/default/isc-dhcp-server

3. IPv4: /etc/dhcp/dhcpd.conf

```
default-lease-time 600;
max-lease-time 7200;
host clt {
hardware ethernet 00:0c:29:80:8c:9b;
fixed-address 192.168.3.100;
}
subnet 192.168.3.0 netmask 255.255.255.0 {
range 192.168.3.100 192.168.3.200;
option routers 192.168.3.254;
option domain-name-servers 10.100.100.57;
}
```
6. `systemctl restart isc-dhcp-server`
7. `systemctl status isc-dhcp-server`
8. In client machine: `dhclient -v or netplan apply`
9. isc-dhcp monitoring: `dhcp-lease-list`
## DNS(Domain Name System)
1. Tree architecture – “domain” and “subdomain”
- Divided into categories
- Solves name collision
2. Distributed database
- Each site maintains a segment of the DB
- Each site opens its information via network
3. Client-Server architecture
- Name servers provide information (Name Server)
- Clients make queries to server (Resolver)
4. The complete configuration of named consists of
- The config file
- e.g. named.conf, named.conf.options, named.conf.default-zones, named.conf.local
5. Zone data file
- The DNS Database
- Address mappings for each host
- Collections of individual DNS data records
### DNS database
1. Maintained and stored on the domain’s master name server
2. Often called zone files
3. asic format
4. [name] [ttl] [class] type data
- name: the entity that the RR describes
- Can be relative or absolute
- ttl: time in second of this RR’s validity in cache
- class: network type
- IN for Internet
- CH for ChaosNet
- HS for Hesiod
5. Special characters
- `;` (comment)
- `@` (The current domain name)
- `()` (allow data to span lines)
- `*` (wildcard character, name field only)
6. Zone records: identify domains and name servers
- SOA: Start Of Authority
- Defines a DNS zone of authority, each zone has exactly one SOA record
- Specify the name of the zone, the technical contact and various timeout information
- Format:
- [zone] IN SOA [server-name] [administrator’s mail] ( serial, refresh, retry, expire, ttl )
- NS: Name Server
- Format
- zone [ttl] [IN] NS hostname
- Usually follow the SOA record
- Goal
- Identify the authoritative server for a zone
- Delegate subdomains to other organization’s NS
7. Basic records: map names to addresses and route mails
- A:
- IPv4 Address
- Format:
- hostname [ttl] [IN] A ipv4addr
- Provide mapping from hostname to IPv4 address\
- Load balance (decided by client)
- AAAA:
- IPv6 Address
- Format
- hostname [ttl] [IN] AAAA ipv6addr
- Provide mapping from hostname to IPv6 address
- Load balance (decided by client)
- PTR:
- Perform the reverse mapping from IP address to hostname
- Special top-level domain for IPv4: in-addr.arpa
- Used to create a naming tree from IPv4 address to hostnames
- Special top-level domain for IPv6: ip6.arpa
- Used to create a naming tree from IPv6 address to hostnames
- Format
- addr [ttl] [IN] PTR hostname
- MX
8. Optional records: extra information to host or domain
- CNAME
- TXT
- SRV
9. 
### Bind9
#### Download
1. Install bind9: `apt-get install bind9`
2. Install dnsutils (nslookup, dig, …): `apt-get install dnsutils`
#### Configuration file
1. /etc/bind/named.conf: don't edit this file
- 位了可以 forward 到 .nasa
- 將 dnssec-validation auto; 改成 dnssec-validation no;
2. /etc/bind/named.conf.option
- A config for bind global options: e.g. Set forwarders
3. /etc/bind/named.conf.default-zones: don't edit this file,
- 把所有東西用`view "default-zones"{}`包起來就好
```
// prime the server with knowledge of the root servers
view "default-zones"{
match-clients { any; };
zone "." {
type hint;
file "/usr/share/dns/root.hints";
};
// be authoritative for the localhost forward and reverse zones, and for
// broadcast zones as per RFC 1912
zone "localhost" {
type master;
file "/etc/bind/db.local";
};
zone "127.in-addr.arpa" {
type master;
file "/etc/bind/db.127";
};
zone "0.in-addr.arpa" {
type master;
file "/etc/bind/db.0";
};
zone "255.in-addr.arpa" {
type master;
file "/etc/bind/db.255";
};
};
```
4. /etc/bind/named.conf.local: A config to define your own zone.
```
//
// Do any local configuration here
//
// Consider adding the 1918 zones here, if they are not used in your
// organization
//include "/etc/bind/zones.rfc1918";
view "LAN" {
match-clients { 192.168.3.0/24; };
zone "p76101584.nasa" {
type master;
file "/etc/bind/db.p76101584.nasa_lan";
allow-query { any; };
allow-update { none; };
};
};
view "WAN"{
match-clients { any; };
zone "p76101584.nasa" {
type master;
file "/etc/bind/db.p76101584.nasa_wan";
allow-query { any; };
allow-update { none; };
};
};
```
5. /etc/bind/db.p76101584.nasa_lan
```
$TTL 604800
$ORIGIN p76101584.nasa.
@ IN SOA www.p76101584.nasa. root.p76101584.nasa. (
2
604800
86400
2419200
604800
)
@ IN NS www.p76101584.nasa.
www IN A 192.168.3.1
@ IN A 192.168.3.1
```
6. /etc/bind/db.p76101584.nasa_wan
```
$TTL 604800
$ORIGIN p76101584.nasa.
@ IN SOA www.p76101584.nasa. root.p76101584.nasa. (
2
604800
86400
2419200
604800
)
@ IN NS www.p76101584.nasa.
www IN A 10.100.100.57
@ IN A 10.100.100.57
```
7. `sudo /etc/init.d/named restart`: bind設定完要重啟
8. `sudo /etc/init.d/named status` : bind狀態要 active
## Log
- Throw away all log files
- Rotate log files at periodic intervals
- Archiving log files
- Common directory /var/log
- Read software configuration files
- Nginx log at /var/log/nginx/
- See /etc/rsyslog.conf
## network
### Set up network
- location: /etc/netplan/00-installer-config.yaml
- `sudo netplan apply`
### Http
- HTTP is stateless: there is no link between two requests being successively carried out on the same connection
- HTTP cookies allow the use of stateful sessions
#### HTTP Version
- HTTP/1.1: the standardized protocol
- HTTP/2: A protocol for greater performance
- Derived from SPDY by Google, 2010
- Binary protocol
- Multiplexing: parallel requests can be made over the same connection
- Header compression
- Server push
- HTTP/3: HTTP over QUIC
- Quick UDP Internet Connection (QUIC), designed by Google
- Use UDP
- Fewer round-trips
- Major Google’s services are using HTTP/3 now
### HTTP Response Status

### Common HTTP Headers

### HTTPS: HTTP over TL
- HTTPS is a communication protocol that uses the HTTP and the SSL/TLS protocols to provide encrypted communication and secure identification of a Web server!
- [Uploading file..._awo6y1zce]()
### URL (Uniform Resource Locators)
- Specifie how and where to access a resource
- URLs are not HTTP-specific
- `scheme://[username:password@]hostname[:port][/path][?query][#anchor]`
- Examples:
- https://developer.mozilla.org/en-US/search?q=URL
- ftp://userid:password@ftp.mold.net.tw
- ldap://[2001:db8::7]/c=GB?objectClass?one
- mailto:John.Doe@example.com
- Well Known URL Scheme

### Common Request Methods

### GET vs POST

### curl
- `-X`: Specifies a custom request method to use
- `-o`: Write output to file
- `-H`: Extra header to include in the request when sending HTTP to a server
- `-d`: Send the specified data in a POST request to the HTTP server
- `--data-urlencode`: Send the specified data and perform URL-encoding
- `-k`: Allow curl to proceed connections considered insecure
- `-v`: Make curl verbose during the opration
- `-i`: Include the HTTP response headers in the output
## NAT(Network Address Translation)
- A method of mapping an IP address space into another IP address
- Modifying network address information in the IP header of packets while they are passes through a router
- Translation table
- Maps the inside local address to the inside global address
- Also contains mappings between outside global address and outside local address for inbound translations
- In TCP/IP, we covered the IPv4 crisis, private addresses, and what NAT is
- IPv4 addresses are running out
- No more IPv4 addresses to assign to organizations
- IP addresses were being allocated on a FCFS basis
- Solutions
- Short term
- Subnetting / CIDR
- NAT
- Long term
- IPv6
- You can use this command to get your public ip address.
- curl ifconfig.me
## Firewall
- Hardware/Software
- Choke point between secured and unsecured network
- Filter incoming and outgoing traffic
- Prevent communications which are forbidden by the security policy
- Incoming: protect and insulate the applications, services and machines
- SMB
- Telnet
- LDAP
- Outgoing: limit or disable access from the internal network
- TCP 80,443 port only
- NAT (Network Address Translation)
- Transport Layer Firewalls
- Filter attributes
- Source/destination IP
- Source/destination port
- TTL
- Protocols
- Application Layer Firewalls
- Work on the application level of the TCP/IP stack.
- Inspect all packets for improper content.
### iptable
1. tables: filter, nat, mangle, raw
2. Chains: When to do
- Under table
- PREROUTING, OUTPUT, FORWARD, INPUT, POSTROUTING
3. Rules: Rule you set
- Under chain
- ex: iptables -A INPUT -i lo -j ACCEPT
### Basic command
- Append rule: `iptables -t [table] -A [chain] [parameters]`
- Insert rule: `iptables -t [table] -I [chain] position [parameters]`
- Delete rule: `iptables -t [table] -D [chain] [rule_number]/[parameters]`
- List rules: `iptables -t [table] -L -nxv --line-number`
### Basic parameters
#### Init
- `-F`
- Flush all rules
- `-X`
- Flush all user-defined chains
- `-Z`
- Flush all statistics data for all chains
- `-P`
- Change the default policy of the target chain
- `iptables -t filter -P INPUT DROP`
- `-N`
- Create user-defined chain
- `iptables -t filter -N AAA`
- `iptables -t filter -A AAA -j LOG`
#### Modify
- `-A`, --append
- `-C`, --check
- `-D`, --delete
- `-I`, --insert
- `-R`, --replace
#### Jump
- `-j`, --jump
- To user-defined chain or target
- Example target: ACCEPT, DROP, REJECT, RETURN, SNAT, DNAT, MASQUERADE
- Example of jump to user-defined chain:
- iptables -t filter -N AAA
- iptables -t filter -A INPUT -j AAA
- Example of jump to target:
- iptables -t filter -A INPUT -j DROP
- `-g`, --goto
- Unlike the --jump option.
- For example:
- After the chain pointed to by -j is RETURN, it will return to the original chain
- After the chain pointed to by -g is RETURN, it will directly end the original chain.
#### Filter
- `-i`, `-o` [if] : incoming interface / outgoing interface
- `-i lan -o wan`
- `-s`, `-d` [net] : Source / Destination
- `-s 192.168.0.0/24 –d 140.113.1.1`
- `--sport`, `--dport` [port] : Source port / Destination port
- `--sport 22 --dport 80`
- `-p` [protocol] : tcp, udp, icmp, all
- ``-p icmp`
- `!` (not) : Invert matching
- `! -s 140.113.1.0/24`
- `! -i eth0`
- `! -p udp`
#### Example
- `iptables -t filter -A INPUT -j DROP`
- Drop all traffic when input at filter table.
- `iptables -t filter -A INPUT -s 192.168.100.0/24 -p tcp --dport 80 -j ACCEPT`
- Accept tcp traffic from source ip matching 192.168.100.0/24 (192.168.100.1,192.168.100.2...) to any destination ip with destination port 80 when input in filter table.
- `iptables -t filter -A OUTPUT -j ACCEPT`
- Accept all traffic when output at filter table
- `iptables -t mangle -A INPUT -p tcp --dport 22 -j LOG`
- Log tcp traffic with destination port 22 when input in mangle table.
### Module
- User may need special rule to filter packets
- Split several feature into different module
- Use -m to access module
- Use man iptables-extensions for information on all modules
#### -m state
- Set rules to apply to packets in the following states.
- Ex:
- `iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT`
- Accept packets that reply users requests.
- State
- NEW : New connection
- ESTABLISHED : Old connection
- RELATED : New connection create by ESTABLISHED session
- INVALID
#### -m multiport
- Set rules to apply to tcp or udp packets with following ports.
- Ex:
- We can merge multiple rules that only the difference in port into one rule.
- `iptables -A INPUT -i wan -p tcp -m tcp --dport 80 -j ACCEPT`
- `iptables -A INPUT -i wan -p tcp -m tcp --dport 443 -j ACCEPT`
- `iptables -A INPUT -i wan -p tcp -m tcp -m multiport --dports 80,443 -j ACCEPT`
### Filter Table
1. The default table of iptables command
2. For packets filter
- NPUT
- Packets that come in (to local)
- OUTPUT
- Packets that go out (from local)
- FORWARD
- Packets that pass through (from others to others)
3. After: NAT tables, Connection Tracking, Routing Decision
#### Targets
- ACCEPT: Accept this packet.
- DROP: Drop this packet.
- REJECT: Drop this packet and send a reject message back.
- RETURN: Leave this chain.
- LOG: Log this packet.
- ULOG
#### Example
- Drop all incoming packets except destination is 80 or 443 tcp packets and the packets that reply users requests.
- `iptables -t filter -A INPUT -p tcp -m tcp -m multiport --dports 80,443 -j ACCEPT`
- `iptables -t filter -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT`
- `iptables -t filter -A INPUT -j DROP`
- ACCEPT all incoming packets that come from lo(loopback) interface.
- `iptables -t filter -A INPUT -i lo -j ACCEPT`
- Drop all forward packet from LAN interface except destination is 80 or 443 tcp packets.
- `iptables -t filter -A FORWARD -i LAN -p tcp -m tcp -m multiport --dports 80,443 -j ACCEPT`
- `iptables -t filter -A FORWARD -i LAN -m state --state RELATED,ESTABLISHED -j ACCEPT`
- `iptables -t filter -A FORWARD -i LAN -j DROP`
### NAT tables
1. For NAT
- PREROUTING
- Packets that will go into the routing tables
- POSTROUTING
- Packets that have left the routing tables
- OUTPUT
- Packets that go out (from local)
2. For modify the IP and PORT in the packet.
3. After: Mangle table.
#### Targets
- Global
- NETMAP
- RETURN
- LOG
- ULOG
- Prerouting
- DNAT: Translate and map your destination IP:Port to the IP:Port you specified.
- REDIRECT
- Postrouting
- SNAT: Translate and map your source IP:Port to the IP:Port you specified.
- MASQUERADE: Translate and map your source ip to your outgoing interface's IP.
- Output
- REDIRECT
#### Example
- Remember to enable forward on your router. In this case we just enable ipv4 forward.
1. Add "net.ipv4.ip_forward=1" to /etc/sysctl.conf and use `sysctl -p`
- `echo "net.ipv4.ip_forward=1" >> /etc/sysctl.conf`
- `sysctl -p`
2. Check with `cat /proc/sys/net/ipv4/ip_forward`
- Set NAT on your router that make 192.168.0.0/24 private can use global IP.
- `iptables -t nat -A POSTROUTING -o wan -s 192.168.0.0/24 -j MASQUERADE`
- Set up port forwarding so that the web server(192.168.0.100) under NAT can be accessed by external.
- `iptables -t nat -A PREROUTING -i wan -p tcp -m tcp -m multiport --dports 80,443 -j DNAT --to 192.168.0.100`
### Mangle Table
1. For special purpose, e.g., add or remove some special tags from packets
- PREROUTING, OUTPUT, FORWARD, INPUT, POSTROUTING
2. After conntrack
#### Targets
- ACCEPT
- DROP
- REJECT
- MARK
- mark on packet
- TCPMSS
- Reset TCP MSS
- RETURN
- LOG
- ULOG
#### Example
- Policy Based Routing
- We can set one or more routing tables in linux and set which routing table is used under what conditions
- If source ip is 192.168.0.0/25 use A routing tables, else if source ip is 192.168.0.128/25 use B routing tables
```
# set the packets with mark 100 use routing table A
ip rule add fwmark 100 lookup A
# set the packets with mark 200 use routing table B
ip rule add fwmark 200 lookup B
iptables -t mangle -A PREROUTING -s 192.168.0.0/25 -j MARK --set-mark 100
iptables -t mangle -A PREROUTING -s 192.168.0.128/25 -j MARK --set-mark 200
```
### Raw Table
1. For something that you want to do before conntrack.
2. Better performance with fewer features (Because iptables hasn't started conntrack yet)
- PREROUTING, OUTPUT
#### Targets
- ACCEPT
- DROP
- NOTRACK
- Set a mark on packets that they should not be handled by the connection tracking system
- RETURN
- LOG
- ULOG
#### Example
- Set all tcp packet that destination port are 80 not be handled by the connection tracking system and Accept then in filter tables
- `iptables -t raw -A PREROUTING -d <host ip> -p tcp -m tcp --dport 80 -j NOTRACK`
- `iptables -t filter -A INPUT -p tcp -m tcp --dport 80 -m state --state UNTRACKED -j ACCEPT`
- Better performance because that all tcp packet that destination port are 80 don't need to be conntrack.
### File: /etc/iptables/rules.v4
```
# Generated by iptables-save v1.8.4 on Mon May 2 12:44:35 2022
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [122:20750]
-A INPUT -p icmp -j ACCEPT
-A INPUT -p udp --dport 53 -j ACCEPT
-A INPUT -p tcp -m tcp -m multiport --dports 22,80,53 -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -j DROP
COMMIT
*nat
:INPUT ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A POSTROUTING -s 192.168.3.100/24 -j MASQUERADE
-A PREROUTING -i wan -p tcp -m tcp --dport 80 -j DNAT --to 192.168.3.1
COMMIT
# Completed on Mon May 2 12:44:35 2022
# Generated by iptables-save v1.8.4 on Mon May 2 12:44:35 2022
*mangle
:PREROUTING ACCEPT [9755:2056033]
:INPUT ACCEPT [6568:1140318]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [6935:1769247]
:POSTROUTING ACCEPT [6935:1769247]
-A PREROUTING -p udp -m comment --comment "wg-quick(8) rule for wan" -j CONNMARK --restore-mark --nfmask 0xffffffff --ctmask 0xffffffff
-A FORWARD -p tcp -m tcp --tcp-flags SYN,RST SYN -j TCPMSS --clamp-mss-to-pmtu
-A POSTROUTING -p udp -m mark --mark 0xca6c -m comment --comment "wg-quick(8) rule for wan" -j CONNMARK --save-mark --nfmask 0xffffffff --ctmask 0xffffffff
COMMIT
# Completed on Mon May 2 12:44:35 2022
# Generated by iptables-save v1.8.4 on Mon May 2 12:44:35 2022
*raw
:PREROUTING ACCEPT [9755:2056033]
:OUTPUT ACCEPT [6935:1769247]
COMMIT
# Completed on Mon May 2 12:44:35 2022
```
- `sudo iptables-restore /etc/iptables/rules.v4`
## NGINX
- Asynchronous event-driven approach
- Ability to handle 10k simultaneous connections with low memory footprint
### Features
- Reverse proxy with caching
- Load balancing with health check function
- TLS/SSL support with SNI and OCSP stapling
- gRPC support
- WebSocket support
- HTTP/2 protocol support
- NGINX has one master process and several worker processes
- The main purpose of the master process is to read and evaluate configuration, and maintain worker processes
- Worker processes do actual processing of requests
- Configuration files are located in /etc/nginx
### 實作
- Installation: `sudo apt install nginx`
- Check configuration: `sudo nginx -t`
- NGINX Configuration Files:
- Main configuration
- /etc/nginx/nginx.conf
- Website settings
- /etc/nginx/sites-available/*
- /etc/nginx/sites-enabled/*
- /etc/nginx/conf.d/*.conf
- Example config file path: /etc/nginx/sites-available