Linux Basic For Hacker

나다·2023년 6월 18일
0

1. Getting started with the basics

Binaries

  • can be executed
  • /usr/bin , /usr/sbin

Case sensitivity

  • Unlike Windows, Linux filesystem is case sensitive

The Linux Filesystem

/root : home directory of the all-powerful root user
/etc : Linux configuration files - files that control when and how programs start up
/home : user's home directory
/mnt : where other filesystems are attached or mounted to the file system
/media : where CDs and USB devices are usually attached and mounted to the filesystem
/bin : application binaries reside
/lib : where you'll file libraries

Basic Command In Linux

Checking Your Login with whoami

root@b8e18b02148d:/# whoami
root

Referencing Manual Pages with man

root@b8e18b02148d:/# man vim
VIM(1)                                                     General Commands Manual                                                    VIM(1)

NAME
       vim - Vi IMproved, a programmer's text editor

SYNOPSIS
       vim [options] [file ..]
       vim [options] -
       vim [options] -t tag
       vim [options] -q [errorfile]

       ex
       view
       gvim gview evim eview
       rvim rview rgvim rgview

DESCRIPTION
       Vim  is a text editor that is upwards compatible to Vi.  It can be used to edit all kinds of plain text.  It is especially useful for
       editing programs.

       There are a lot of enhancements above Vi: multi level undo, multi windows and buffers, syntax  highlighting,  command  line  editing,
       filename  completion, on-line help, visual selection, etc..  See ":help vi_diff.txt" for a summary of the differences between Vim and
       
-- snip --

Searching with locate

root@b8e18b02148d:/# locate vim
  • easiest command to use
  • will go through entire filesystem and locate every occurence of that word
  • not perfect
  • sometimes the results of locate can be overwhelming (giving too much information)
  • use a database that is usually only updated once a day
  • if you just created a file a few minutes or a few hours ago, it might not appear in this list until the next day

Finding Binaries with whereis

root@b8e18b02148d:/bin# whereis chown
chown: /usr/bin/chown /usr/share/man/man1/chown.1.gz
  • looking for binary file
  • location of binary, source, man page

Fincing Binaries in the PATH variable with which

  • even more specific
  • only returns the location of the binaries in the PATH variable in Linux
root@b8e18b02148d:/bin# echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

root@b8e18b02148d:/bin# which man
/usr/bin/man
  • search will not find a match
  • can remedy this limitation by using wildcard
root@b8e18b02148d:/etc# find /etc -type  f -name issue.\*
/etc/issue.net

Filtering with grep

  • using cat command for appending some sentences or see all file contents
root@b8e18b02148d:~# cat test
Hacking is the most valuable skill set of the 21st century!
  • appending using cat
  • after typing all the sentences just press ctrl+D for finishing
root@b8e18b02148d:~# cat >> test
hello this is new line using cat that is appending command
-- ctrl + D --
root@b8e18b02148d:~# cat test
Hacking is the most valuable skill set of the 21st century!
hello this is new line using cat that is appending command
  • if want to overwrite the file with new information
  • simply use the cat command with single redirect again
root@b8e18b02148d:~# cat > test
I will overwrite this file using redirect! :)
-- ctrl + D --

root@b8e18b02148d:~# cat test
I will overwrite this file using redirect! :)

2. Text Manipulation

  • everything you deal with directly is a file
  • most often these will be text file

Finding the head

root@b8e18b02148d:/etc# head deluser.conf
# /etc/deluser.conf: `deluser' configuration.

# Remove home directory and mail spool when user is removed
REMOVE_HOME = 0

# Remove all files on the system owned by the user to be removed
REMOVE_ALL_FILES = 0

# Backup files before removing them. This options has only an effect if
# REMOVE_HOME or REMOVE_ALL_FILES is set.

Numbering the lines

root@b8e18b02148d:/etc# nl deluser.conf
     1	# /etc/deluser.conf: `deluser' configuration.

     2	# Remove home directory and mail spool when user is removed
     3	REMOVE_HOME = 0

     4	# Remove all files on the system owned by the user to be removed
     5	REMOVE_ALL_FILES = 0

     6	# Backup files before removing them. This options has only an effect if
     7	# REMOVE_HOME or REMOVE_ALL_FILES is set.
     8	BACKUP = 0

     9	# target directory for the backup file
    10	BACKUP_TO = "."

    11	# delete a group even there are still users in this group
    12	ONLY_IF_EMPTY = 0

    13	# exclude these filesystem types when searching for files of a user to backup
    14	EXCLUDE_FSTYPES = "(proc|sysfs|usbfs|devpts|tmpfs|afs)"
root@b8e18b02148d:/etc#
  • sed to replace every occurrence
root@b8e18b02148d:/# sed s/word/g /etc/delname.conf > new.conf

Viewing Files with more and less

Controlling the Display with more

  • display a page of a file at a time and lets you page down through it using the ENTER key
root@b8e18b02148d:/etc/default# more useradd
# Default values for useradd(8)
#
# The SHELL variable specifies the default login shell on your
# system.
# Similar to DSHELL in adduser. However, we use "sh" here because
# useradd is a low level utility and should be as general
# as possible
SHELL=/bin/sh
#
# The default group for users
# 100=users on Debian systems
# Same as USERS_GID in adduser
# This argument is used when the -n flag is specified.
# The default behavior (when -n and -g are not specified) is to create a
# primary user group with the same name as the user being added to the
# system.
# GROUP=100
#
# The default home directory. Same as DHOME for adduser
# HOME=/home
#
# The number of days after a password expires until the account
# is permanently disabled
# INACTIVE=-1
--More--(67%)

Display and Filtering with less

root@b8e18b02148d:/etc/default# less useradd
# Default values for useradd(8)
#
# The SHELL variable specifies the default login shell on your
# system.
# Similar to DSHELL in adduser. However, we use "sh" here because
# useradd is a low level utility and should be as general
# as possible
SHELL=/bin/sh
#
# The default group for users
# 100=users on Debian systems
# Same as USERS_GID in adduser
# This argument is used when the -n flag is specified.
# The default behavior (when -n and -g are not specified) is to create a
# primary user group with the same name as the user being added to the
# system.
# GROUP=100
#
# The default home directory. Same as DHOME for adduser
# HOME=/home
#
# The number of days after a password expires until the account
# is permanently disabled
# INACTIVE=-1
useradd

3. Analyzing and Managing Networks

Analyzing Networks with ifconfig

root@b8e18b02148d:~# ifconfig
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 172.17.0.2  netmask 255.255.0.0  broadcast 172.17.255.255
        ether 02:42:ac:11:00:02  txqueuelen 0  (Ethernet)
        RX packets 275  bytes 363170 (363.1 KB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 229  bytes 12743 (12.7 KB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        loop  txqueuelen 1000  (Local Loopback)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
  • short for Ethernet0
  • first wired network connection
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
  • the type of network being used (Ethernet) is listed next
        ether 02:42:ac:11:00:02  txqueuelen 0  (Ethernet)
  • the globally unique address stamped on every piece of network hardware

  • NIC usually referred to as the MAC address

  • information on the IP address

  • Bcast (Broadcast address) : send out information to all IPs on the subnet

  • network mask (netmask) : determine what part of the IP address is connected to the local network

        inet 172.17.0.2  netmask 255.255.0.0  broadcast 172.17.255.255
  • loopback address : localhost
  • special software address that connects you to your own system
  • software and services not running on your system can't use it
lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
  • generally represented with the IP address 127.0.0.1

this is not presented in here though..

  • wlan0 : WAN LAN, wireless interface or adapter
  • also displays the MAC address of that device (HWaddr)

checkng Wireless Network Devices with iwconfig

  • if you have an external USB
  • you can use the iwconfig command to gather crucial information for wireless hacking
  • such as the adapter's IP address, MAC address etc
root@b8e18b02148d:~# iwconfig
lo        no wireless extensions.

tunl0     no wireless extensions.

ip6tnl0   no wireless extensions.

eth0      no wireless extensions.
  • wlan0 : lean what 802.11 IEEE wireless standards our device is capable of b and g
  • b and g : two early wireless communication standards
  • Most wireless devices now include n as well (n is the latest standard)

Changing your network information

Changing your IP Address

  • can do that using ifconfig command
root@b8e18b02148d:~# sudo ifconfig eth0 192.168.181.115
root@b8e18b02148d:~# ifconfig eth0 192.168.181.115 netmask 255.255.0.0 broadcast 192.168.1.255

spoofing your MAC address

  • also use ifconfig to change MAC Address
  • changing MAC address to spoof a different MAC address is almost trivial and newtralizeds those security measures
ifconfig eth0 down
ifconfig eth0 hw ether 00:11:22:33:44:55 
ifconfig eth0 up
  • can't do this cuz of permission error but it will work if you solve that problems

Assigning New IP Address form the DHCP Server

  • DHCP (Dynamic Host Configuration Protocol) server that runs a daemon = dhcpd

DHCP Server

  • Assgins IP Address to all the systems on the subnet
  • keeps log files of which IP address is allocated to which machine at any one time
  • this makes it a great resource for forensic analysts to trace hackers with after an attack

Understanding how the DHCP server works

  • connect to the internet from a LAN

  • must have a DHCP assigned IP

  • after setting static IP address must get a new DHCP-assigned IP address

  • this will happen when reboot the system

  • To request IP address from DHCP

  • simply call the DHCP server with the command dhclient

root@b8e18b02148d:~# dhclient eth0
  • dhclient command send a DHCPDISCOVER request from the network interface specified
  • recieves an offer (DHCPOFFER) from the DHCP server
  • confirm the IP assignment to the DHCP server with a dhcp request

Manipulating the Domain Name System

Examining DNS with dig

  • DNS is the service that translates a domain name to appropriate IP
    address
root@b8e18b02148d:~# dig google.com

; <<>> DiG 9.18.12-0ubuntu0.22.04.1-Ubuntu <<>> google.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 64143
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0

;; QUESTION SECTION:
;google.com.			IN	A

;; ANSWER SECTION:
google.com.		268	IN	A	142.250.76.142

;; Query time: 35 msec
;; SERVER: 192.168.65.5#53(192.168.65.5) (UDP)
;; WHEN: Sun Jun 18 04:47:51 UTC 2023
;; MSG SIZE  rcvd: 44
  • ADDITIONAL SECTION : dig query reveals the IP address of DNS server serving gogle.com
  • also using dig command to get information on email server connected to a domain by adding the mx option
root@b8e18b02148d:~# dig google.com mx

; <<>> DiG 9.18.12-0ubuntu0.22.04.1-Ubuntu <<>> google.com mx
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 9266
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0

;; QUESTION SECTION:
;google.com.			IN	MX

;; ANSWER SECTION:
google.com.		307	IN	MX	10 smtp.google.com.

;; Query time: 43 msec
;; SERVER: 192.168.65.5#53(192.168.65.5) (UDP) 
# nameserver ipv4
# /etc/resolv.config 에서 정의

;; WHEN: Sun Jun 18 04:50:43 UTC 2023
;; MSG SIZE  rcvd: 49
  • The most common Linux DNS server is the Berkeley Internet Name Domain (BIND)

Changing Your DNS Server

root@b8e18b02148d:~# vi /etc/resolv.conf
# DNS requests are forwarded to the host. DHCP DNS options are ignored.
nameserver 192.168.65.5
root@b8e18b02148d:~# vi /etc/hosts
127.0.0.1       localhost
::1     localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
172.17.0.2      b8e18b02148d
  • edit this file and make own dns
192.168.181.131 bankofamerica.com
  • traffic on your LAN that visit bankofamerica.com to your webserver at 192.168.181.131

4. Adding and Removing Software

Using apt to Handle Software

Searching for a Package

root@b8e18b02148d:/# apt-cache search vim
vim - Vi IMproved - enhanced vi editor
vim-common - Vi IMproved - Common files
vim-doc - Vi IMproved - HTML documentation
vim-runtime - Vi IMproved - Runtime files
vim-tiny - Vi IMproved - enhanced vi editor - compact version
apvlv - PDF viewer with Vim-like behaviour

-- snip --

Removing Software

  • remove command doesn't remove the configuration files

  • reinstall the same package in the futer without configuring

  • purge remove configuration files

root@b8e18b02148d:/# apt purge {pakcage_name}
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
--snip--
  • when you installed package, you installed serveral dependencies or libraries with it that package requires in order to run
  • now that you're removing package, those other libraires or dependencies are not longer required
  • so they can be removed by running apt autoremove
root@b8e18b02148d:/# apt autoremove {package_name}
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
--snip--

Adding Repositories to Your sources.list File

  • repositories your system will search for software are sotred in sources.list file
root@b8e18b02148d:/etc/apt# ls
apt.conf.d   keyrings       sources.list    trusted.gpg.d
auth.conf.d  preferences.d  sources.list.d
root@b8e18b02148d:/etc/apt# vi sources.list

# See http://help.ubuntu.com/community/UpgradeNotes for how to upgrade to
# newer versions of the distribution.
deb http://archive.ubuntu.com/ubuntu/ jammy main restricted
# deb-src http://archive.ubuntu.com/ubuntu/ jammy main restricted

## Major bug fix updates produced after the final release of the
## distribution.
deb http://archive.ubuntu.com/ubuntu/ jammy-updates main restricted
# deb-src http://archive.ubuntu.com/ubuntu/ jammy-updates main restricted

--snip--
  • main : contains supported open source software

  • universe : contains community-maintained open source software

  • multiverse : contains software restricted by copyright or other legal issue

  • restricted : contains proprietary device drivers

  • backports : contains packages from later release

  • When you ask to download a new software package

  • the system looks through your repositories listed in source.list

  • and selects the most recent version of the desired package

  • to add a repository, just edit the source.list file by adding the name of the repository to the list

5. Controlling file and Directory Permissions

Different Types of Users

  • root user is all powerful > basically anything on system
  • other users are usually collected into groups

Granting Permissions

  • r : Permission to read
  • w : Permission to write
  • x : Permission to execute

Granting Ownership to an individual user

$ chown bob /tmp/bobsfile

Granting Ownership to a Group

$ chgrp security newIDs

Checking Permissions

root@b8e18b02148d:/etc/apt# ls -al
total 44
drwxr-xr-x 1 root root 4096 Jun 18 05:54 .
drwxr-xr-x 1 root root 4096 Jun 18 05:09 ..
drwxr-xr-x 1 root root 4096 Jun 18 03:46 apt.conf.d
drwxr-xr-x 2 root root 4096 Apr  8  2022 auth.conf.d
drwxr-xr-x 2 root root 4096 Apr  8  2022 keyrings
drwxr-xr-x 2 root root 4096 Apr  8  2022 preferences.d
-rw-r--r-- 1 root root 2403 Jun  5 14:05 sources.list
drwxr-xr-x 2 root root 4096 Apr  8  2022 sources.list.d
drwxr-xr-x 2 root root 4096 Jun  5 14:05 trusted.gpg.d
  • d : file type (directory)
  • rwxrwxrwx : permission on this file or directoy
  • 1 : number of link
  • root root : owner group of the file
  • 4096 : size of the file in bytes
  • Jun 18 05:54 : When the file was created or last modified

Setting More Secure Default Permissions with Masks

  • Linux automatically assigns base permissions
  • usually 666 for file and 777 for directories
  • you can change the default permissions allocated to files and directories
  • create by each user with the umask
  • umask : represents the premissions you want to remove from the base permissions on a file or directory to make them more secure

  • 3 digit octal number

  • substracted from the premissions number to give the new permissions status

  • umask is not universal to all users on the system
  • each user can set a personal default umask value for the files in their .profile file
  • to change the umask value for a user, edit /home/username/.profile

Special Permissions

Granting Temporary Root Permissions with SUID

  • a user can execute a file only if they have permission to execute that particular file
  • but if you want to change password you have to access to the /etc/shadow file
  • it requires root uesr privileges in order to execute
  • so you can't change password
  • Soooooooo temporarily grant the owner's privileges to execute the file with setting SUID bit

SUID : any user can execute the file with the permissions of the owner

  • to set the SUID you chmod 4XXX (X is original permission octal digit)

Granting the root user's group permissions SGID

  • also grant temporary elevated permissions, but it grants the permissions of the file owner's group
  • SGID bit : 2 before the regular permissions

ex) applied to a directory

  • bit is set on a directory
  • ownership of new files created in that directory goes to the directory creator's group
  • very useful when a directory is shared by multiple users
  • all users in that group can execute the file not just a single user

The outmoded sticky bit

  • permission bit that you can set on a directory to allow a user to delete or rename files within the directory

    sitcky bit is a legacy of older unix system, ignore in mordern systems

$ find / -user root -perm -4000

6. Process Management

  • Process : simply a program that's running and using resource

Viewing Processes

root@b8e18b02148d:~# ps aux
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root         1  0.0  0.1   4624  3628 pts/0    Ss+  04:19   0:00 /bin/bash
root        10  0.0  0.1   4624  3884 pts/1    Ss+  04:19   0:00 /bin/bash
root       612  0.0  0.1   4624  3876 pts/2    Ss+  05:39   0:00 /bin/bash
root       640  0.0  0.1   4624  3844 pts/3    Ss   05:52   0:00 /bin/bash
root       660  0.0  0.0   7060  1564 pts/3    R+   06:25   0:00 ps aux
  • USER : the user who invoked the process
  • PID : The Process ID
  • %CPU : The percent of CPU this process is using
  • %MEM : The precent of memory this process is usig
  • COMMAND : The name of the command that started the process

Finding the Greedies Processes with top

root@b8e18b02148d:~# top

top - 06:29:49 up 2 days, 23:40,  0 users,  load average: 0.01, 0.02, 0.00
Tasks:   5 total,   1 running,   4 sleeping,   0 stopped,   0 zombie
%Cpu(s):  0.1 us,  0.3 sy,  0.0 ni, 99.6 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
MiB Mem :   1985.3 total,    144.7 free,    246.2 used,   1594.4 buff/cache
MiB Swap:   1024.0 total,    818.1 free,    205.9 used.   1396.0 avail Mem

  PID USER      PR  NI    VIRT    RES    SHR S  %CPU  %MEM     TIME+ COMMAND
    1 root      20   0    4624   3628   3076 S   0.0   0.2   0:00.03 bash
   10 root      20   0    4624   3884   3224 S   0.0   0.2   0:00.29 bash
  612 root      20   0    4624   3876   3288 S   0.0   0.2   0:00.04 bash
  640 root      20   0    4624   3844   3240 S   0.0   0.2   0:00.05 bash
  661 root      20   0    7304   3472   2928 R   0.0   0.2   0:00.00 top

Managing Processes

Changing Process Priority with nice

  • can use nice to suggest that a process should be elevated in priority
  • nice range : -20 ~ +19 (default : 0)
  • high nice value > low priority

Setting the Priority When Starting a Process

$ nice -n -10 /bin/slowprocess
  • increasing its priority and allocating it more resource

Changing the Priority of a Running Process with renice

$ renice 19 5581

Kill Process

Running Processes in the background

$ do someting &
  • & : change to background process

Moving a Process to the Foreground

$ fg 1234
  • move a process running in the background to the foreground
  • use fg command

Scheduling processes

kali >at 7:20am
at >/root/myscanningscript

7. Managing User Environment Variables

Viewing and Modifying Environment Variables

root@b8e18b02148d:~# env
HOSTNAME=b8e18b02148d
PWD=/root
HOME=/root

-- snip --
  • environment variables are always uppercase

Viewing All environment variables

  • user-defined variables and command alias
root@b8e18b02148d:/# set | more

BASH=/bin/bash
BASHOPTS=checkwinsize:cmdhist:complete_fullquote:expand_aliases:extquote:force_f
ignore:globasciiranges:histappend:hostcomplete:interactive_comments:progcomp:pro
mptvars:sourcepath
BASH_ALIASES=()
BASH_ARGC=([0]="0")
-- snip --

Chaging Variable Values of a Session

root@b8e18b02148d:/# HISTSIZE=10
root@b8e18b02148d:/# echo $HISTSIZE
10

Making Variable Value Changes Permanent

  • Save legacy environment
$ set > file.txt
  • After changed a variable, the change permanent by entering export
$ export HISTSIZE
  • this code snippet will set your HISTSIZE variable value and export it to all your environments

Changing Your Shell Prompt

\u : the name of the current user
\h : the hostname
\w : the base name of the current working directory

PS1="World Best Hacker: $"
export PS1='C:\w> '

Changing Your PATH

  • defualt PATH is /user/local/sbin /usr/local/bin
$ echo $PAT

Adding to the PATH Variable

  • downloaded and installed a new tool

  • let's say newhackingtool into the /root/newhackingtool directory

  • you could only use commands from that tool when you're in that directory

  • To be able to use this new tool from any directory

  • you need to add the directory holding this tool to your PATH variable

$ PATH=$PATH:/root/newhackingtool
  • now you can execute newhackingtool application from anywhere on your system

Creating a User-Defined Variable

$ MYNEWVARIABLE="Hacking is the most valuable skill set in the 21st century"
$ echo $MYNEWVARIABLE
$ unset MYNEWVARIABLE

Permanent Edit Variable

  • if you want to apply it permanently
  • edit bashrc and using source command for apply immediately
root@b8e18b02148d:~# vi .bashrc
root@b8e18b02148d:~# source .bashrc

9. compressing and archiving

What is compressing?

  • Lossy compression : very effective in reducing the size of file, but the integrity of the information is lost

ex) mp3, mp4, jpg etc

Tarring Files Together

  • combine them into an arcive
  • archiving files, use tar
  • Tar = tape archive
    • prehistoric days of computing from many files, which is then referred to as an archive, tar file, tarball
$ tar -cvf HackersArise.tar hackersarise1 hackersarise2 hackersarise3
  • c : create
  • v : verbose, show list the files that tar is dealing with
  • f : write to the following file
$ tar -tvf HackerArise.tar
  • t : show content list, without extracting them
$ tar -xvf HackersArise.tar
  • x : extract tar file

  • if you don't want to show list of files just remove v option in upper example command

Compressing file

  • tar make have one archived file

  • but is bigger than the sum of the original files

  • What if you want to compress those file for ease of transport?

  • gzip : .tar.gz, .tgz

  • bzip2 : .tar.bz2

  • compress : .tar.z

Compressing with gzip

$ gzip HackersArise.*
  • You can compress your HackersArise.tar file by entering upper example
  • wildcard * : file extension
  • HackerArise.tar is replaced by HackerArise.tar.gz
$ gunzip HackerArise.*

Compressing with bzip2

$ bzip2 HackersArise.*
$ bunzip2 HackersArise.*

Compressing with compress

$ compress HackersArise.*
$ uncompress HackersArise.*

Creating Bit-by-Bit or Physical Copies of Storage Devices

  • dd : makes a bit-by-bit copy of a file, a filesystem, or even an entire hard drive

  • even deleted files are copied, making for easy discovery and recovery

  • will allow to copy the entire hard drive or a storage device to system

  • forensic investigators will likely to this command

  • deleted files and other artifacts will be found

  • this is very slow

$ dd if=inputfile of=outputfile
$ dd if=/dev/sdb of=/root/flashcopy
  • sdb : flash drive

  • /root/flashcopy : name of file you want to copy the physical copy to

  • you can use multiple useful option with dd command

$ dd if=/dev/media of=/root/flashcopy bs=4096 conv:noerror
  • bs : sector size (4KB in here) / defualt 512 byte
  • conv:noerror : ignore the error message and continue to copy even if errors are encountered

10. Filesystem and Storage Device management

The Device Directory /dev

  • special directory that contains files represneting each attached device
root@b8e18b02148d:/dev# ls -al
total 4
drwxr-xr-x 5 root root    360 Jun 18 03:50 .
drwxr-xr-x 1 root root   4096 Jun 18 03:42 ..
crw--w---- 1 root tty  136, 0 Jun 18 03:50 console
lrwxrwxrwx 1 root root     11 Jun 18 03:50 core -> /proc/kcore
lrwxrwxrwx 1 root root     13 Jun 18 03:50 fd -> /proc/self/fd
crw-rw-rw- 1 root root   1, 7 Jun 18 03:50 full
drwxrwxrwt 2 root root     40 Jun 18 03:50 mqueue
crw-rw-rw- 1 root root   1, 3 Jun 18 03:50 null
lrwxrwxrwx 1 root root      8 Jun 18 03:50 ptmx -> pts/ptmx
drwxr-xr-x 2 root root      0 Jun 18 03:50 pts
crw-rw-rw- 1 root root   1, 8 Jun 18 03:50 random
drwxrwxrwt 2 root root     40 Jun 18 03:50 shm
lrwxrwxrwx 1 root root     15 Jun 18 03:50 stderr -> /proc/self/fd/2
lrwxrwxrwx 1 root root     15 Jun 18 03:50 stdin -> /proc/self/fd/0
lrwxrwxrwx 1 root root     15 Jun 18 03:50 stdout -> /proc/self/fd/1
crw-rw-rw- 1 root root   5, 0 Jun 18 04:29 tty
crw-rw-rw- 1 root root   1, 9 Jun 18 03:50 urandom
crw-rw-rw- 1 root root   1, 5 Jun 18 03:50 zero
  • some device can recognize

  • but others have rather cryptic names

  • sda : hard drive partitions, USB, flash drive

How Linux Represents Storage Devices

  • Linux use logical labels for drives that are then mounted on the filesystem

  • logical labels will vary depending on where the drives are mounted

  • same hard drive might have different labels at different times

  • Drives are sometimes split up into sections known as partitions

Drive Partitions

  • some drives can be split into partitions in order to manage and seperate information
  • linux labels each partition with a minor number that comes after the drive designation

$ fdisk -l
  • 3 devices make up the virtual disk from my virtual machine

  • 20GB drive with 3 partitions, including swap partition (sda5)

  • which acts like virtual RAM

  • filesystem : HPFS (High Performance File System) / NTFS (New Technology File System) / ExFAT (Extended File Allocation Table)

  • filesystem might indicate what kind of machine the drive war formatted on

  • old Windows system use FAT system

  • Linux most common are ext2, ext3, ext4

Character and Block Device

  • in /dev directory, first position contains either c or b
drwxr-xr-x 5 root root    360 Jun 18 03:50 .
crw--w---- 1 root tty  136, 0 Jun 18 03:50 console
lrwxrwxrwx 1 root root     15 Jun 18 03:50 stdout -> /proc/self/fd/1
  • c : Character device
  • b : Block device
  • l : Symbolic link file

List Block Devices and Information with lsblk

  • list block
  • each block device listed in /dev
  • similar to the output from fdisk -l
  • but it will also display devices with multiple partitions in a kind of tree
root@b8e18b02148d:/dev# lsblk
NAME   MAJ:MIN RM  SIZE RO TYPE MOUNTPOINTS
nbd0    43:0    0    0B  0 disk
nbd1    43:32   0    0B  0 disk
nbd2    43:64   0    0B  0 disk
nbd3    43:96   0    0B  0 disk
nbd4    43:128  0    0B  0 disk
nbd5    43:160  0    0B  0 disk
nbd6    43:192  0    0B  0 disk
nbd7    43:224  0    0B  0 disk
vda    254:0    0 59.6G  0 disk
`-vda1 254:1    0 59.6G  0 part /etc/hosts
                                /etc/hostname
                                /etc/resolv.conf
nbd8    43:256  0    0B  0 disk
nbd9    43:288  0    0B  0 disk
nbd10   43:320  0    0B  0 disk
nbd11   43:352  0    0B  0 disk
nbd12   43:384  0    0B  0 disk
nbd13   43:416  0    0B  0 disk
nbd14   43:448  0    0B  0 disk
nbd15   43:480  0    0B  0 disk

Mounting and Unmounting

  • new versions of Linux autounmount storage device when they're attached

  • meaning the new flash drie or hard drive is automatically attaches to the filesystem

  • storage device must be first physically connected to the filesystem

  • and logically attached to the filesystem in order for the data to be made available to the operating system

  • mount point : directory tree where devices are attached

  • /mnt, /media : main mount point in Linux

  • /mnt : external USB, flash drives

  • /media : automatically mounted

Mounting Storage Devices Yourself

$ mount /dev/sdb1 /mnt
$ mount /dev/sdc1 /media
  • filesystem on a system that are mounted at boot-time are keypt in a file /etc/fstab (filesystem table)

Unmounting with unmount

  • before you remove a flash drive from your system
  • eject it to keep from causing damage to the files stored on the device
  • eject = unmount
$ umount /dev/sdb1

+) be careful, no n in here

Monitoring Filesystem

Getting information on Mounted Disks

  • df : disk free
root@b8e18b02148d:/dev# df
Filesystem     1K-blocks     Used Available Use% Mounted on
overlay         61255492 27925448  30188720  49% /
tmpfs              65536        0     65536   0% /dev
tmpfs            1016480        0   1016480   0% /sys/fs/cgroup
shm                65536        0     65536   0% /dev/shm
/dev/vda1       61255492 27925448  30188720  49% /etc/hosts
tmpfs            1016480        0   1016480   0% /proc/acpi
tmpfs            1016480        0   1016480   0% /sys/firmware

sd : SATA hard drive
a : first hard drive
1 : first partition on that drive

Checking for Errors

  • fsck = filesystem check
  • check filesystem for errors and repairs the damage
root@b8e18b02148d:/dev# fsck
fsck from util-linux 2.37.2
  • p : have fsck automatically repair any problems with the device
$ fsck -p /dev/sdb1

11. The logging system

The rsyslog Logging Daemon

root@b8e18b02148d:/dev# locate rsyslog
# in my ubuntu image there is no rsyslog configuration
joy@ip-172-31-27-193:~$ find / -type f -name rsyslog*
find: ‘/run/udisks2’: Permission denied
find: ‘/run/user/1005/inaccessible’: Permission denied
find: ‘/run/sudo’: Permission denied
find: ‘/run/cryptsetup’: Permission denied
find: ‘/run/multipath’: Permission denied
find: ‘/run/lvm’: Permission denied
find: ‘/run/systemd/ask-password-block’: Permission denied
find: ‘/run/systemd/unit-root’: Permission denied
find: ‘/run/systemd/inaccessible’: Permission denied
-- snip --

The rsyslog configuration file

  • /etc/rsyslog.conf
joy@ip-172-31-27-193:/etc$ head rsyslog.conf
# /etc/rsyslog.conf configuration file for rsyslog
#
# For more information install rsyslog-doc and see
# /usr/share/doc/rsyslog-doc/html/configuration/index.html
#
# Default logging rules can be found in /etc/rsyslog.d/50-default.conf


#################
#### MODULES ####

The rsyslog logging rules

  • Each line is a seperate logging rule that says what message are logged and where they're logged to
#
auth,authpriv.*             /var/log/auth.log
*.*;auth,authpriv.none      -/var/log/syslog
#cron.*                     /var/log/cron.log
daemon.*                    -/var/log/daemon.log
kern.*                      -/var/log/kern.log
1pr.*                       -/var/log/lpr.log
mail.*                      -/var/log/mail.log
user.*                      -/var/log/user.log
facility.priority           action
  • facility : keyword references the program
  • priority : determines what kind of messages to log for that program
  • action : references the location where the log will be sent

facility

  • auth,authpriv : Security/authorization messages
  • cron : Clock daemons
  • daemon : Other daemons
  • kern : Kernel messages
  • lpr : Printing System
  • mail : Mail System
  • user : Generic user-level messages

priority

  • debug, info, notice, warning, warn, error, err, crit, alert, emerge, panic
mail.* /var/log/mail

kern.crit /var/log/kernel

emerg :omusrmsg:*
  • emerge : critical priority or higher to /var/log/kernel
  • :omusrmsg:* : show this message to all the user who are logged on

Automatically Cleaning Up Logs with logrotate

  • process of regularly archiving log files by moving them to some other location, leaving you with a fresh log file
$ vi /etc/logrotate.conf

 see "man logrotate" for details
# rotate log files weekly
weekly

# use the adm group by default, since this is the owning group
# of /var/log/syslog.
su root adm

# keep 4 weeks worth of backlogs
rotate 4

# create new (empty) log files after rotating old ones
create

# uncomment this if you want your log files compressed 
#compress

-- snip --
  • weekly : any number after the rotate keyword always refer to weeks
  • rotate 4 : rotate logs every 4 weeks
  • create : new empty file is created when old ones are rotated out

ex)

  • /var/log.auth.1, /var/log.auth.2, /var/log.auth.3, /var/log.auth.4, /var/log.auth.5 (X)

Remaining Stealthy

Removing Evidence

  • want to remove any logs of your activity

  • simple open file and delete > easy to recover it by forensic

  • better and more secure solution : shred the log file

  • overwrite it several times, makeing it much harder to recover

$ shred -f -n 10 /var/log/auth.log.*
  • it overwrite file several times by default

Disabling logging

  • to disbale all logging
  • simply stop rsyslog daemon
$ service rsyslog stop
  • service : application that runs in the background waiting for you to use it

13. Becoming Secure and Anonymous

How the internet gives us away

  • When you send packet of data across the internet, it contains the IP addresses of the source and destination for the data

  • each packet hops through multiple internet routers until it finds its destination and then hops back to sender

  • There can be as many as 20-30 hops between the sender ans the destination

  • but usually any packet will find its way to the destination in fewer than 15 hops

  • see what hops a packet might make between you and the destination

root@b8e18b02148d:/# traceroute google.com
traceroute to google.com (142.250.206.238), 30 hops max, 60 byte packets
 1  172.17.0.1 (172.17.0.1)  2.618 ms  1.327 ms  1.248 ms
 2  192.168.0.1 (192.168.0.1)  5.614 ms  5.525 ms  5.456 ms
 3  1.232.165.1 (1.232.165.1)  12.219 ms  12.152 ms  12.083 ms
 4  * * *
 5  100.75.16.205 (100.75.16.205)  13.382 ms  13.351 ms  13.222 ms
 6  10.47.254.172 (10.47.254.172)  13.185 ms  5.525 ms  5.770 ms
 7  10.222.24.216 (10.222.24.216)  7.535 ms 10.222.20.110 (10.222.20.110)  9.494 ms 10.222.24.208 (10.222.24.208)  22.667 ms
 8  10.222.25.247 (10.222.25.247)  18.874 ms 10.222.22.97 (10.222.22.97)  18.491 ms 10.222.25.247 (10.222.25.247)  18.596 ms
 9  142.250.162.182 (142.250.162.182)  47.332 ms 72.14.196.26 (72.14.196.26)  50.849 ms *
10  * * *
11  142.250.226.6 (142.250.226.6)  48.279 ms 209.85.248.112 (209.85.248.112)  50.004 ms 172.253.70.182 (172.253.70.182)  39.998 ms
12  * kix06s10-in-f14.1e100.net (142.250.206.238)  32.838 ms 108.170.242.98 (108.170.242.98)  36.963 ms
  • 12 hops across the internet from me
  • results will likely be different because your request would be coming from a differen location

The Onion Router System

  • ONR (the US Office of Naval Research) set out to develop a method for anonymously navigating the internet for espionage purposes
  • plan was to set up a network of routers that was seperate from the internet's routers
  • could encrypt the traffic, and that only stored the unencrypted IP address of the previous router

How to Works

  • Tor encrypts the data, destination, and sender IP address of each packet
  • At each hop, the information is encrypted and then decrypted by the next hop when it's received
  • each packet contains information about only the previous hop along the path and not the IP address of the origin

Security Concern

  • Unite State, consider Tor network a threat to national security
  • NSA, runs its own Tor router, meaning that your traffic may be traversing the NSA's rouers when you use Tor
  • If your trffic is exiting the NSA's routers, exit node always knows your destination

Proxy Servers

  • proxies which are intermediate systems that act as middlemen for traffic
  • Proxy will likely log your traffic, but an investigator would have to get a subpoena or search warrant to obtain the logs
  • To make your traffic even harder to trace, you can use more than one proxy, proxy chain
$ proxychains nmap -sT -Pn <IP Address>

Setting Proxies in the Config File

$ vi /etc/proxychains.conf

socks4 114.134.186.12 22020
  • proxychains defaults to using Tor
  • Tor is usually ver slow (also NSA has broken Tor)

Virtual Private Networks

  • Using a VPN can certainly enhance your security and privacy

  • but it's not a guarantee of anonymity

  • The internet device you connect to must record or log your IP address to be able to properly send the data back to you

  • The strength of a VPN is

  • all your traffic is encrypted, protecting against snooping

  • your IP address is cloaked by the VPN IP address

  • but if they are pressured by espionage agencies or law enforcement, they might give up you identity

Enctypted Email

  • ProtonMail is enctypt the email
  • when exchanging email with non-ProtonMail uses, tere is the potential for some or all of the email not to be encrypted

14. Understanding and Insepcting Wireless networks

Wi-Fi Network

  • AP (Access Point) : device wireless users connect to for internet access
  • ESSID (Extended Service Set Identifier) : used for multiple APs in a wireless LAN
  • BSSID (Basic Service Set Identifier) : unique identifier of each AP, and it is the same as the MAC address of the device
  • SSID (Service Set Identifier) : name of the network
  • Channels : Wifi an operate on any one of 14 channels, in the united state, Wi-Fi is limited to channels 11 channels
  • Power : closer you are to he Wi-Fi AP, the greater the power and the easier the connection is to crack
  • Security : Primary security Protocol for Wi-Fi
    1. WEP (Wired Equivalent Privacy)
    2. WPA (Wi-Fi Protected Access)
    3. PSK (Pre-Shared Key)
  • Modes : managed, master, monitor
  • Wireless range : In the united state, Wi-Fi AP must legally broadcast its signal at an upper limit of 0.5 watt (100 meter)
  • Frequency : Wi-Fi is designed to operate on 2.4GHz and 5GHz (modern Wi-Fi often use both)

Basic Wireless Commands

$ iwconfig
lo no wireless extensions
   wlan0 IEEE 802.11bg  ESSID:off/any
         Mode:Managed  Access Point:Not-Associated   Tx-Power=20 dBm
         Retry short limit:7   RTS  thr:off   Fragment thr:off
         Encryption key:off
         Power Management:off
   eth0  no wireless extensions
  • Wi-fi interface is shown as wlan0
  • In kali Linux, Wi-Fi interfaces are usually designated as wlanX (X : number of that interface)
  • just the wireless interfaces, also known as network cards
  1. managed : ready to join or has joined an AP
  2. master : is ready to act as or already is an AP
  3. monitor :
$ iwlist wlan0 scan wlan0 Scan completed:
               Cell 01 - Address: 88:AD:43:75:B3:82
                         Channel:1
                         Frequency:2.412GHz (Channel 1)
						 Quality=70/70   Signal level =-38 dBm
                         Encryption key:off
                         ESSID:"Hackers-Arise"
$ nmcli dev wifi
  • nmcli (network manager command line interface) : View the Wi-Fi APs near you and their key data, as we did with iwlist, but this command gives us a little more information

How Bluetooth Works

  • universal protorol for low-power, near-field communication operating at 2.4-2.495GHz

  • minimum range of 10 meters but here is no limit to the upper range manufacturers may implement in their devices

  • Many devices have range as large as 100 meters

  • Connecting 2 Bluetooth devices is referred to as pairing

  • discoveable mode : Name, Class, List of services, Technical information

  • 2 devices pair, they exchange a secret or link key

  • Each stores this link key so it can identify the other in future pairing

  • Every device has a unique 48bit identifier (MAC-like address) and usually a manufacturer-assigned name

Bluetooth Scanning and Reconnaissance

$ apt install bluez 
  • hciconfig : very similarly to ifconfig in Linux
  • hcitool : inquiry tool can provide us with device information
  • hcidump : enables us to sniff the Bluetooth communication

Scanning for bluetooth devices with hcitool

$ hcitool scan
      72:6E:46:65:72:66      ANDROID BT
      22:C5:96:08:5D:32      SCH-I535
$ hcitool inq
Inquiring...
    24:C5:96:08:5D:32    clock offset:0x4e8b      class:0x5a020c
    76:6F:46:65:72:67    clock offset:0x21c0      class:0x5a020c

Scanning for services with sdptool

  • Service Discovery Protocol (SDP) is a bluetooth protocol for searching for Bluetooth service
  • Bluez provides the sdptool tool for browsing a device for the services it provided
$ sdptool browse 76:6E:46:63:72:66 Browsing 76:6E:46:63:72:66... Service RecHandle: 0x10002
Service Class ID List:
  ""(0x1800)
Protocol Descriptor List:
  "L2CAP"  (0x0100)
    PSM: 31
  "ATT" (0x0007)
    uint16: 0x0001
    uint16: 0x0005
-- snip --
  • this device support ATT Protocol (Low Energy Attribute Protocol)

Seeing Whether the Device Are reachable with 12ping

  • we've gathered the MAC addresses of all nearby devices
  • send out pings to these devices
$ l2ping 76:6E:46:63:72:66 -c 3

15. Managing the linux kernel and Loadable Kernel modules

Checking the Kernel Version

root@b8e18b02148d:/# cat /proc/version
Linux version 5.10.47-linuxkit (root@buildkitsandbox) (gcc (Alpine 10.2.1_pre1) 10.2.1 20201203, GNU ld (GNU Binutils) 2.35.2) #1 SMP Sat Jul 3 21:51:47 UTC 2021

Kernel Tuning with sysctl

  • modern linux kernel use the sysctl command to tune kernel options

/etc/sysctl.conf

root@b8e18b02148d:/# sysctl -a | less
abi.vsyscall32 = 1
debug.exception-trace = 1
debug.kprobes-optimization = 1
dev.cdrom.autoclose = 1
dev.cdrom.autoeject = 0
dev.cdrom.check_media = 0
-- snip --
$ sysctl -w net.ipv4.ip_forward=1
  • to make premanent changes to sysctl, edit configuration file /etc/sysctl.conf

Managing Kernel Modules

  • lsmod : list all the kernel modules
root@b8e18b02148d:/# lsmod
Module                  Size  Used by
xfrm_user              36864  1
xfrm_algo              16384  1 xfrm_user
grpcfuse               16384  0
vmw_vsock_virtio_transport    16384  2
vmw_vsock_virtio_transport_common    28672  1 vmw_vsock_virtio_transport
vsock                  36864  9 vmw_vsock_virtio_transport_common,vmw_vsock_virtio_transport
  • insmod : insert modules

  • we can load or insert a module with insmod and remove a module with rmmod

  • these commands are not perfect and may not take into account module dependencies

Finding More Information with modinfo

$ modinfo bluetooth
filename: /lib/modules/4.19.0-kali-amd64/kernel/net/bluetooth/bluetooth.ko alias: net-pf-31
license: GPL
version: 2.22
description:Bluetooth Core ver 2.22
author: Marcel Holtman <marcel@holtmann.org>
srcversion: 411D7802CC1783894E0D188
 depends:
intree:
vermagic:
parm:
parm:
rfkill, ecdh_generic, crc16
Y
4.19.0-kali1-amd64  SMP mod_unload modversions
disable_esco: Disable eSCO connection creation (bool)
disable_ertm: Disable enhanced retransmission mode (bool)

Adding and Removing Moduels with modprobe

  • LKM management
  • add a module to your kernel, use the modeprobe command with the -a (add) switch
$ modprobe -a <module name>
$ modprobe -r <module to be removed>

ex) install video module

$ modprobe -a HackersAriseNewVideo
$ dmesg | grep video
# dmesg : prints out the message buffer from the kernel
$ modprobe -r HackersAriseNewVideo

16. Automating Tasks with Job Scheduling

  • jobs : scrips or other tasks, that they want to run periodically

Scheduling an Event or Job to Run on an Automatic Basis

  • /etc/crontab : cron table file


  • @yearly, @annually, @monthly, @weekly, @daily, @midnight, @noon, @reboot

profile
매일 한걸음씩만 더 성장하기 위해 노력하고 있습니다.

0개의 댓글