Linux Basic for Hackers一书的阅读笔记。
Hackers-Arise
GETTING START
FINDING STUFF
locate
is the easiest: locate the keyword through the entire filesystem:
kali >locate aircrack-ng
/usr/bin/aircrack-ng
/usr/share/applications/kali-aircrack-ng.desktop
...
/var/lib/dpkg/info/aircrack-ng.mg5sums
locate
‘s results can be overwhelming, and it uses a database that usually updated once a day.
whereis
is to locate binary files.
which
only returns the location of the binaries in the PATH
variable in Linux.
find / -type f(for an ordinary file) -name apache2
补充:
搜索etc目录下所有以sh开头的文件:locate /etc/sh
搜索用户主目录下,所有以m开头的文件,并且忽略大小写:locate -i ~/m
相当于find -name
对自动生成的数据库/var/lib/locatedb
的搜索
通配符:?
单个字符 *
任何长度字符
kali >sed s/mysql/MySQL/g /etc/snort/snort.conf > snort2.conf
使sed查找替换关键词或字段
- s 参数提供搜索,你先提供想要搜索的关键词 (mysql) 然后提供想要替换成的关键词 (MySQL), 用斜杠
(/)分开。 - g 参数告诉 Linux 你希望全局替换,然后将结果保存到一个新文件 snort2.conf
concatenation with cat
cat
with a redirect symbol(>
):
cat > test
Linux will go into interactive mode and wait for you to start entering content. Press Ctrl-D to exit.
And use double redirect(>>
) to append more content to it: cat >> test
ANALYZING AND MANAGING NETWORKS
ifconfig eth0 192.168.111.11
ifconfig eth0 192.168.181.115 netmask 255.255.0.0 broadcast
192.168.1.255
kali >ifconfig eth0 down
kali >ifconfig eth0 hw ether 00:11:22:33:44:55
kali >ifconfig eth0 up
dhclient eth0
ADDING AND REMOVING SOFTWARE
apt-get remove ...
删除包
apt-get purge ...
删除包和配置文件
chmod u-w,o+x hashcat.hcstat
用户组u中删除w权限
设置SUID临时授予所有者的权限以执行该文件:在常规权限之前输入4 chmod 4644 filename
;SGID授予文件所有组的权限,组中成员均会有权限,文件权限属于文件夹创建者而不是文件创建者,在常规权限前输入2。
PROCESS MANAGEMENT
MANAGING PROCESSES
ps
without any options lists the processes started by the currently logged-in user and processes running on that terminal.
aux
shows all processes running on the system for all users.don’t prefix these options with a dash(-).
top
ordered by resources used rather than PID(started time).
nice
ranges from -20 to +19,with 0 being default value,low nice value tranlates into a high priority.Process inherits the nice
value of its parent process.
use renice
to alter the priority after process has started
# increase `nice` value by -10,increase its priority and allocate it more resources.
kali>nice -n -10 /bin/process
# give it a lower priority
kali>nice -n 10 /bin/process
# `renice` sets its value rather than increasing or decreasing,give it lower priority like:
kail>renice 20 6996(PID)
with top
utility running and press the R key,supply the PID and nice
value can also change the nice
value.
# restart a process with the HUP signal
kail>kill -1 PID
# absolute kill
kali>kill -9 PID
# name instead of PID
kali>killall -9 zombieprocess
or u can press K with top
utility running.
gedit .bashsrc &
: running processes in the background;fg PID
moves a process to the foreground.
at
daemon to schedule the execution:
kali >at 7:20am
at >/root/myscanningscript
MANAGING USER ENVIRONMENT VARIABLES
env
to view EV
set | more
to view all EV
HISTSIZE=0
can be stealthy 直接赋值
kali>PS1="World's Best Hacker: #"
kali>export PS1
# without export,it's only in this session
kali>export HISTSIZE
# for backup
kali>echo $HISTSIZE > ~/HISTSIZE.txt
kali>set > ~/env.txt
PATH variable:PATH=$PATH:/root/hackingtool
PATH=/root/hackingtool
will replace it rather than appending it.
unset xxx
deletes the variable along with its value.
BASH SCRIPTING
shell allows you to customize your tasks to your needs.
shebang(#!) chmod 755
-rwx-r-x-r-x
nmap -sT server (-p 3306)
common built-in bash commands
fg/bg
puts a job in the foreground/background
jobs
lists background jobs
set
lists all variables
COMPRESSING AND ARCHIVING
tar -cvf file.tar file1 file2 file3
- c means create
- v verbose, listing files(optional)
- f means write to the following file
tar -xvf file.tar
- x extract
compressing compare
different compression ratios:
- compress:fastest,larger
- bzip2:slowest,smallest
- gzip:between above
gunzip file.tar.gz
bunzip2 file.tar.bz2
uncompress file.tar.Z
bit-by-bit copies of storage devices
dd
command makes a bit-by-bit copy of a file,a filesystem,or even an entire hard drive.Even deleted files are copied,it can be used for forensic investigators.
dd
is very slow,cp
is commen command.
dd if=/dev/media of=/root/flashcopy bs=4096 conv:noerror
noerror
option continues to copy even if errors are encountered.bs
option allow you to determine the block size(the number of bytes read/written per block) of the data being copied.
FILESYSTEM AND STORAGE DEVICE MANAGEMENT
fdisk -l
lists all the partitions of all the drives.
Device files in the /dev directory,first position contains either c
or b
,each stands for character devices or block devices:
crw------- 1 root root 10, 59 Oct 29 2018 cpu_dma_latency
mounting and unmounting
Two mount points in Linux are /mnt
and /media
:
mount /dev/sdb1 /mnt
mount /dev/sdc1 /media
umount /dev/sdb1
monitoring filesystems
df
(disk free) provide us with basic information on any hard disks or mounted devices.Without any options,df
defaults to the first drive on your system. If you want to check a different drive,simply follow the df command with the drive representation you want to check (for example,df sdb
).
fsck
(filesystem check) checks the filesystem for errors and repairs the damage.(running device must be umount first)
-p
option automatically repairs any problems with the device:
fsck -p /dev/sdb1
THE LOGGING SYSTEM
RSYSLOG LOGGING DAEMON
Linux uses a daemon called syslogd
to automatically log events.
rsyslog
and syslog-ng
are used on different distributions of Linux.
kali> locate rsyslog
/etc/rsyslog.conf is the conf file and RULES
allows hacker to find out what is being logged and where those logs are written.
###############
#### RULES ####
###############
#cron.* /var/log/cron.log
daemon.* /var/log/daemon.log
mail.info /var/log/mail.info
mail.warn /var/log/mail.warn
mail.err /var/log/mail.err
# facility.priority action
each line is a separate logging rule that says what message are logged and where they’re logged to.
Generally log files are sent to the /var/log directory.
*.emerg*
will log all events of the emergency priority to all logged-on users. With this rules, Hackers can even disable specific logging rules.
AUTOMATICALLY CLEANING UP LOGS WITH LOGROTATE
System rotates log files using a cron
job that employs the logrotate
utility.
cat /etc/logrotate.conf # choose the regularity
man logrotate # learn to use
REMAINING STEALTHY (stealthy隐秘的)
compromise a Linux system 侵入系统
manually delete logs line by line will leave time gaps in log files, and can be recovered by others.
shred
(撕碎) is a built-in command for just this purpose.-f
option gives us permission.
shred -f -n 10 /var/log/auth.log.* # shred 10 times
Now the log files’ contents are indecipherable gibberish(难以破译的乱码):
Or disable logging requires root privileges:
service rsyslog stop
这里入侵系统后隐藏痕迹的方法给了两个,一个抹掉log一个禁止登录,既暴力也不全面。真正渗透测试中的反取证工作应该至少围绕以下方面:
- 还原文件的修改/访问/更改时间
- 修改 last, w, lastlog 日志
- 删除.viminfo
- 使用history -c 还原.bash_history
- 删除 ~/.ssh/known_hosts 中记录
invaluable 是无价的非常贵重的 不是无价值的
USING AND ABUSING SERVICES
Linux,
Apache, MySQL, and PHP or Perl forms a powerful and robust platform,known collectively as LAMP.
SSH is a replacement for the insecure telnet
that was so common years ago.
Metasploit uses PostgreSQL to store its modules and results of scans and exploits:
kali> service postgresql start
kali> msfconsole
msf> msfdb init
msf>db_status
BECOMING SECURE AND ANONYMOUS
relatively 相当地,相对地
traceroute
command will send out packets to the destination and trace the route of those packets.
traceroute google.com
THE ONION ROUTER SYSTEM
The Onion Router(Tor) Project: Setting up a network of routers that was separate from the internet’s routers,that could encrypt the traffic, and only stored the unencrypted IP address of the previous router.
Over 7000 routers around the world are thanks to volunteers who are allow their computers to be used by Tor. At each hop, the information is encrypted and then decrypted by the next hop.
Without being tracked by Big Brother.
infamous 声名狼藉的 邪恶的
ambitious 雄心勃勃的
The NSA runs its own Tor routers, it’s worse if your traffic is exiting the NSA’s routers because the exit router always konws your destination. The NSA also has a method known as traffic correlation, which involves looking for patterns in incoming and outgoing traffic.
PROXY SERVERS
You can set up proxychains to obscure your traffic, like scanning a site anonymously:
proxychains <the command you want proxied> <arguments>
proxychains nmap -sT -Pn <IP address>
/etc/proxychains.conf:
[ProxyList] # line 61
# add proxy here...
# meanwhile
# defaults set to "tor"
socks4 127.0.0.1 9050
9050 is the default Tor configuration; proxies can be added a few more.
Uncomment the dynamic_chain
line in /etc/proxychains
will enable dynamic chaining of our proxies;
random_chain
will randomly choose IP, uncomment chain_len
and give it a reasonable number:
# Make sense only if random_chain
chain_len = 3
Bruce Schneier said, “If something is free, you’re not the customer; you’re the product.”
VIRTUAL PRIVATE NETWORKS
A VPN can be effective in evading government-controlled content and information censors, or access limitations like Netflix, HBO, which limit access to IP originating from their own nation.
cloak 斗篷,掩盖,隐匿
ENCRYPTED EMAIL
Servers of the email provider(Google Yahoo etc.) have access to the unencrypted contents of your email.
ProtonMail
encrypts your email from end to end or browser to browser.
UNDERSTANDING AND INSPECTING WIRELESS NETWORKS
WI-FI NETWORKS
- SSID(service set identifier) is the name of the network.
- AP(access point) is the device user connect for internet access.
- ESSID(extended service set identifier)
- BSSID(basic service set identifier)
- Channels WI-FI can operate on any one of 14 channels, it is limited to 11 channel in the United States.
- Modes : managed,master,monitor
- Security : three primary security protocols, Wired Equivalent Privacy(WEP) was badly flawed and easily cracked; Wi-Fi Protected Axxess(WPA) was a bit more secure; WPA2-PSK is much more secure and uses a preshared key(PSK).
- Wireless range : a WiFi AP must boradcast its signal at an upper limit of 0.5 watts in US. It has a normal range of about 300 feet(100 meters).
- Frequency : WiFi is designed to oprate on 2.4GHz and 5GHz. Modern WiFi APs and wireless network cards often use both.
- Power : The closer you are to the WiFi AP, the greater the power, and the easier the connection is to crack.
iwconfig
only displays your wireless interfaces and their key data.
You can see all the wireless access points your network card can reach using the iwlist
command:
iwlist wlan0 scan //to see all the APs
nmcli
(network manager command line interface) can be used to view the WiFi APs near you and their key data. It gives us a little more info:
nmcli dev wifi //dev is short for devices
nmcli
can be used to connect to APs:
nmcli dev wifi connect (AP-SSID) password (password)
aircrack-ng教程 略
respectively 分别地
DETECTING AND CONNECTING TO BLUETOOTH
Bluetooth is a universal protocol for low-power, near-field communication operating at 2.4-2.485GHz using spread spctrum(扩展频谱), frequency hopping at 1600 hops per second.
The Bluetooth specification has a minimum range of 10 meters, upper range can be larger than 100 meters with special antennas.
We use BlueZ
to scan for Bluetooth signals:
kali >hciconfig
hci0: Type: BR/EDR Bus: USB
BD Address: 10:AE:60:58:F1:37 ACL MTU: 310:10 SCO MTU: 64:8
UP RUNNING PSCAN INQUIRY
RX bytes:131433 acl:45 sco:0 events:10519 errors:0
TX bytes:42881 acl:45 sco:0 commands:5081 errors:0
kali >hciconfig hci0 up
look for Bluetooth devices that are sending out discover beacons(in discovery mode):
kali >hcitool scan
Scanning...
72:6E:46:65:72:66 ANDROID BT
22:C5:96:08:5D:32 SCHI535
gather more info about detected devices with the inquiry function inq
:
kali >hcitool inq
Inquiring...
24:C6:96:08:5D:33 clock offset:0x4e8b class:0x5a020c
76:6F:46:65:72:67 clock offset:0x21c0 class:0x5a020c
Service Discovery Protocol(SDP) is a Bluetooth protocol for searching for Bluetooth service(Bluetooth is suite of services). BlueZ provides the sdptool
for browsing a device for the services it provides.
kali >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: 0x1
uint16: 0x5
l2ping (MACaddress)
can send out a ping.
MANAGING THE LINUX KERNEL AND LOADABLE KERNEL MODULES
Loadable Kernal Modules, or LKMs are rootkits usually embeds with. By which a hacker can take total control of the system and kernal.
check the kernal by uname -a
or cat /proc/version
kernal tuning with sysctl
remains effect only until you reboot the system, edit /etc/sysctl.conf
to make changes permanent.
kali >sysctl -a | less
dev.cdrom.autoclose = 1
dev.cdrom.autoeject = 0
dev.cdrom.check_media = 0
--snip--
some parameters can be useful to a hacker, for example doing MITM attack, enable packet forwarding:
kali >sysctl -w net.ipv4.ip_forward=1
and uncomment the line #net.ipv4.ip_forward=1
in /etc/sysctl.conf
to make this change permanent.
By adding net.ipv4.icmp_echo_ignore_all=1
and run sysctl -p
can disable ICMP echo requests.
MANAGING KERNEL MODULES
lsmod
command lists all the kernel modules.
We can load or insert a module with insmod
and remove a module with rmmod
. These commands may not take into account module dependencies and leave your kernel unstable. Modern distributions of Linux have added modprobe
, which automatically loads dependencies.
Finding more info about kernel modules: modinfo
followed by the name of the module you saw with lsmod
command. And the module dependencies will be listed. This is useful info when troubleshooting why a particular hardware device is not working.
kali > modprobe -a <module> # add
# point out the message buffer from the kernal to test whether the mod loaded properly
kali > dmesg | grep <module>
kali > modprobe -r <module> # remove
AUTOMATING TASKS WITH JOB SCHEDULING
crond
is a daemon which checks the cron
table. cron
table located at /etc/crontab
. cron
table has 7 fileds:
The first five are used to schedule the time to run the task, the sixth field specifies the user, and the seventh field is used for the absolute path to the command you want to execute:
FieldTime unit | Representation |
---|---|
1 Minute | 0–59 |
2 Hour | 0–23 |
3 Day of the month | 1–31 |
4 Month | 1–12 |
5 Day of the week | 0–7(Sunday(0) and Saturday(6)) |
run every night at 2:30 AM , Monday through Friday:
M H DOM MON DOW USER COMMAND
30 2 * * 1-5 root /root/myscanningscript
the fifth field defines a range by using a dash(-), also you can separate those days with commas(,):2,4
crontab -e
or leafpad /etc/crontab
to edit crontab.
Note that, Say you, vigilant
crontab shotcuts:
@yearly/@annually/@monthly/@weekly/@daily/@midnight/@noon/@reboot
@midnight user /usr/share/MySQLsscanner.sh
Using rc scripts to run jobs as startup
The kernal starts a daemon known as init
or init.d
after it initialized and loaded all its modules. This deamon then begins to run a number of scripts found in /etc/init.d/rc
Linux has multiple run levels that indicate what services should be started at bootup. Runlevel 1 is single-user mode and service such as networking are not started in runlevel 1. The rc scripts are set to run depending on what run level is selected:
- 0 Halt the system
- 1 Singleuser/minimal mode
- 2–5 Multiuser modes
- 6 Reboot the system
add services using update-rc.d
command from rc.d
script:
kali > update-rc.d <name of script or service> <remove|defaults|disable|enable>
kali > update-rc.d postgresql defaults
rcconf GUI:
kali > apt-get install rcconf
kali > rcconf
PYTHON SCRIPTING BASICS FOR HACKERS
A beginner hacker who simply uses tools created by someone else will be condemned to the realm of script kiddies.
PyPI (the Python Package Index) at http://www.pypi.org/.
kali > apt-get install python3-pip
kali > pip3 install <package name>
kali > pip3 show <package name> #version/location
the packages are automatically placed in /usr/local//lib/<python-version>/dist-packages
directory.
or download a package from PyPI, unpack it and run python setup.py install
.
terminology, demonstrate
Formatting is critically important in Python, particularly with your indentation levels. If you start with double indentation, you must be consistent with the double indentation throughout the entire block.
In Python each variable type is treated like a class. A class is a kind of template for creating objects : Object-Oriented Programming(OOP).
In Python there is no need to declare a variable before assigning a value to it.
# creating a TCP Listener
import socket
TCP_IP = "192.168.181.190"
TCP_PORT = 9999
BUFFER_SIZE = 100
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind((TCP_IP,TCP_PORT))
s.listen(1)
conn,addr = s.accept()
print('Connection address:',addr)
while 1:
data = conn.recv(BUFFER_SIZE)
if not data:break
print("Received data:",data)
conn.send(data) # echo
conn.close
This act of gathering information prior to a hack is often referred to as reconnaissance.
- Variables/Comments/Functions/Modules
- Lists/Sets/Dictionaries
- Control Statements/Loops/Exception handling
false negative, versatility