Python Ethical Hacking from Scratch

1 (1 reviews total)
By Fahad Ali Sarwar
    Advance your knowledge in tech with a Packt subscription

  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Chapter 1: Introduction to Hacking

About this book

Penetration testing enables you to evaluate the security or strength of a computer system, network, or web application that an attacker can exploit. With this book, you'll understand why Python is one of the fastest-growing programming languages for penetration testing. You'll find out how to harness the power of Python and pentesting to enhance your system security.

Developers working with Python will be able to put their knowledge and experience to work with this practical guide. Complete with step-by-step explanations of essential concepts and practical examples, this book takes a hands-on approach to help you build your own pentesting tools for testing the security level of systems and networks. You'll learn how to develop your own ethical hacking tools using Python and explore hacking techniques to exploit vulnerabilities in networks and systems. Finally, you'll be able to get remote access to target systems and networks using the tools you develop and modify as per your own requirements.

By the end of this ethical hacking book, you'll have developed the skills needed for building cybersecurity tools and learned how to secure your systems by thinking like a hacker.

Publication date:
June 2021
Publisher
Packt
Pages
214
ISBN
9781838829506

 

Chapter 1: Introduction to Hacking

This chapter will give you a quick introduction to the nuts and bolts of hacking. You will start exploring what the world of hacking entails and what it really takes to become a hacker. You will learn about what skill set is needed to become a successful hacker in the real world. We will also discuss some legal aspects of hacking and penetration testing and how you can avoid getting into legal trouble. Then, we will explore what the different kinds of hackers are and what categories they fall into. In the later sections of this chapter, we will explore the general steps and guidelines we should follow in order to carry out a successful attack. Lastly, we will conclude this chapter by talking about different attack vectors. We will talk about both technical and personal penetration testing techniques.

In this chapter, the following topics will be covered:

  • What's all the fuss about hackers?
  • What is hacking?
  • Becoming a successful hacker
  • Types of hackers
  • Hacking phases and methodology
  • Careers in cybersecurity
  • Types of attacks

    Disclaimer

    All the information provided in this book is purely for educational purposes. The book aims to serve as a starting point for learning penetration testing. Use the information provided in this book at your own discretion. The author and publisher hold no responsibility for any malicious use of the work provided in this book and cannot be held responsible for any damages caused by the work presented in this book.

    Penetration testing or attacking a target without previous written consent is illegal and should be avoided at all costs. It is the reader's responsibility to be compliant with all their local, federal, state, and international laws.

 

What's all the fuss about hackers?

What comes to your mind when you think of the word hacker? In recent decades, the word hacker has almost become synonymous with the notion of a genius computer nerd who can get access to any system within seconds and can control anything. From someone who can control traffic signals through their computer to someone penetrating the Pentagon's network, the world of movies and fiction has created a specific image of a hacker. Like everything else in movies, this is just a work of fiction; the real world of hacking and penetration testing is quite different and vastly more complex and challenging.

The real world is filled with unknowns. Carrying out a successful attack on a victim requires a lot of patience, hard work, dedication, and probably a bit of luck. The world of computer security and hacking is a constant cat-and-mouse chase. Developers create a product, hackers try to break it and find vulnerabilities and exploit them, developers find out about these vulnerabilities and develop a patch for them, hackers find new vulnerabilities, and this cycle continues. Both actors try to outsmart each other in this constant race. With each iteration, the process becomes more and more complex, and attacks are becoming more and more sophisticated to bypass detection mechanisms. Similarly, detection mechanisms are also getting smarter and smarter. You can clearly see a pattern here.

 

What is hacking?

In this section, we will learn what hacking is and the relevant terminologies used in the industry. Knowledge of these items is essential to understanding the world of penetration testing, so it is a good idea to go through them at this point. The word hacking refers to the process of getting unauthorized access to a system. The system could be either a personal computer or a network in an organization. You will often see the words hacking and penetration testing being used interchangeably in this book. Hacking is a more commonly understood umbrella term used for a lot of things. The focus of this book will be more on penetration testing, commonly referred to as ethical hacking, in which you have permission to attack the target. Penetration testing, or pen-testing for short, is an authorized simulated attack on a target. This is usually done to find the potential weaknesses and vulnerabilities in a system so that they are exposed before they can be exploited by malicious actors.

Most recognized companies have some kind of penetration testing programs in place to find weaknesses in their ecosystem. Authorized individuals and cybersecurity companies are paid to carry out attacks on their assets to detect potential weak points. These attackers often make a complete report of weaknesses and vulnerabilities, which helps these companies to patch them out. The following is a list of different nomenclature used in the industry:

  • Hacker: Someone who is acting to get unauthorized access to a system/network.
  • Target: An entity that is being attacked for malicious or testing purposes.
  • Asset: Any hardware, software, or data that is owned by an organization that could potentially come under attack.
  • Pen-test: The process of trying to infiltrate the system in order to test out its strengths and weaknesses.
  • Vulnerability: A weakness in a system that can potentially be used to take control of the target's machine.
  • Exploit: A program, code, or script that could take advantage of a system's vulnerability.
  • Malware: A program intended for malicious purposes.
  • Remote shell: A program that gives you control of the victim's machine remotely.

These listed terms will be used in the following chapters. It is necessary to get familiar with these terms as we go into more details. One term you will often see when reading literature regarding penetration testing is the CIA triad (which stands for confidentiality, integrity, and availability):

Figure 1.1 – CIA triad

Figure 1.1 – CIA triad

Most aspects of the hacking process involve breaching one or more of these aspects. Let's explore these terms in detail.

Confidentiality

Confidentiality refers to an organization's attempt to keep its data private. This means that nobody should have access to the data without authorization, even inside the organization. Organizations often have access control that dictates which level of access each user has to their data. The access levels are usually divided into these categories:

Confidentiality is violated when people get access to infrastructure that they are not supposed to, for example, an ex-employee of a company logging in to the system using their previous credentials or guests getting a higher access level than necessary in the network. To ensure confidentiality, it is imperative that strict controls are in place to avoid violating confidentiality criteria. Confidentiality is also violated if someone has access to company data but doesn't cause any damage. Take a look at the following example:

Figure 1.2 – Violation of confidentiality

Figure 1.2 – Violation of confidentiality

Let's say that John sends a message to Jack on a network. This message is only intended for Jack and no one else. The network is shared with various users. An unknown person, Mr. X, is also present in the network and he is listening to all the traffic on the network (also called sniffing). The principle of confidentiality indicates that only Jack should be able to decode this message. If Mr. X intercepts this package, reads it, and then just forwards it to Jack without modifying anything on the message, the confidentiality principle is said to be violated even though both John and Jack don't know that their traffic is intercepted. Network sniffing/monitoring violates the confidentiality principle.

Integrity

The integrity principle ensures that data has not been tampered with in any form and is reliable. Data integrity should be ensured in both static and transaction modes. Static integrity means that all files in the system remain intact and any unauthorized modification should be detected immediately. It also requires that data integrity should be maintained when transferred over a medium. Different techniques are used to ensure data integrity. One of the most common examples is the use of a checksum. A checksum is a string of characters that are calculated for a file to ensure it's not been modified. You will often see checksums associated with files downloaded from the internet. Once a file is downloaded, you can calculate the checksum and compare it with the checksum present on the website; if both of them are equal, it means that data integrity was maintained during downloading. If even one bit has been changed during downloading, the whole checksum string would change. It is often used to prevent file spoofing/masking attacks where hackers intercept your download requests and instead of downloading your requested files, download malicious malware on your PC. You should always compare the checksums of files to ensure that the files you download are in fact the same as those present on the server.

In order to better understand the principle of integrity, let's take a look at the following example:

Figure 1.3 – Violation of the integrity principle

Figure 1.3 – Violation of the integrity principle

Let's say John sends a message to Jack that they should meet at 4 P.M. Mr. X is again intercepting the network traffic in a way that all the traffic between these two goes through Mr. X. Mr. X reads the message from John, changes the time from 4 P.M. to 6 P.M., and sends the message to Jack. Jack receives the message and thinks that John wants to meet at 6 P.M. instead of 4 P.M. Jack has no way of knowing the actual message. In this scenario, the principles of integrity and confidentiality are both violated. Mr. X was able to read and change the data.

Availability

The last principle of availability requires that the data is available to authorized users when requested. Denial of Service (DoS) attacks violate this principle. In DoS attacks, the attackers try to overwhelm the system with a burst of requests so as to make the servers/systems unavailable for legitimate users. This is one of the most common attacks on websites. Attackers bombard the website servers with requests, eventually taking them down. A wait period of a few seconds is now usually put in place for requests to be processed to discourage DoS attacks. Availability simply means that networks, systems, and servers are online when the user needs them. Disruption of even a few minutes can cause havoc for the organization. Let's take the same example to understand this better:

Figure 1.4 – Violating availability by DoS

Figure 1.4 – Violating availability by DoS

Let's say again that John sends a message to Jack on the same network that Mr. X is intercepting. John sends a message to Jack to meet at 4 P.M. However, Mr. X intercepts this message and instead of forwarding it does nothing. John thinks that the message has been sent. However, Jack will never receive this message. In this case, the principle of availability is violated, because the message is not available to Jack. Another variation of violation of the availability principle is delaying messages. Let's say John sends an emergency message to Jack regarding some tasks that must be completed within a certain time frame. Mr. X delays the message so that the message is received by Jack after the passage of this time frame. Even though the correct message is received by John, the delay effectively renders the message useless. This is also a serious violation of the availability principle.

To keep systems secure and reliable, the CIA triad is very important. The goal of every cybersecurity expert is to maintain the system according to the CIA characteristics. Any violation of these principles leads to a breach in the cybersecurity of the system. Next, let's see what it takes to become a successful hacker.

 

Becoming a successful hacker

In order to become a successful penetration tester, you will need a specific skill set. The first thing you will need is a strong desire to learn new technologies. The world of computing is changing at a very rapid pace and every few years, old tools and technologies are replaced. You can't use one successful exploit and expect it to be useful 10 years down the line. This book will focus mostly on developing your own tools. You won't be able to hack NASA with the tools developed in this book and that is not the idea of this book. This book is meant to serve as a starting point for you. The knowledge of the techniques and tools described in this book will help you to get started and then the sky is the limit.

The first thing you need in order to become successful in this field is knowledge of computer systems and computer networks. You won't be able to get very far without them. This book assumes that you have familiarity with computer networks and so on. When necessary, new terms will be explained. This book also assumes that you have a fundamental knowledge of the Python programming language. We will use Python 3 in this book.

Knowledge of these two components should be enough to follow this book. The world of penetration testing is quite huge and to be a hacker that stands out among the crowd, you will need to master a lot of technologies. This includes Linux, databases, hardware and memory access, reverse engineering, cryptography, networking, and analytical skills. You should be proactive and be able to think quickly on your feet if you want to be successful.

Most of the systems present today are online and web-based hacking is one of the most prevalent forms of penetration testing. This means that knowledge of how the web works is essential in order to become a penetration tester. Fundamental knowledge of web-based technologies such as HTML, JavaScript, PHP, and SQL is essential. These topics will not be covered in this book as they do not fit into the scope of the book; however, in practical life, knowledge of these tools is quite useful for penetration testing.

One of the critical skills needed for a successful ethical hacker is to think like a hacker. So, what does it means to think like a hacker? The goal of hackers is to break into a system. A computer system is designed in an intuitive way so most people will be able to interact with it using minimal effort. All the security aspects of a system are designed with this methodology in mind. To be able to break into a system, your thinking process should be somewhat counter-intuitive or rather creative. You need to be able to identify weak points to be attacked that could help you to compromise the system.

Creating a tool that could help you to attack some system is one side of the hacking process while being able to successfully deploy your malware onto the target system without being detected is the other half of the equation. This is almost as important as the hacking tool itself. Once you identify a target, your goal will be to think of a methodology by which you can deploy it to the system. There are many methods of deploying your code depending on what kind of access you can get to the system. These methods, such as phishing and Trojan horses, will be discussed later. Don't worry if these terms sound unfamiliar to you. Once you have gone through this book, you will be familiar with most of these terms.

Hacking requires you to be constantly up to date with the new technologies. The landscape in cybersecurity changes very abruptly and you need to be well versed in these changes. A good idea is to follow forums and websites dedicated to these matters. Hundreds of exploits are discovered and patched every day; you need to be at the right place at the right time to take advantage of them. The window of opportunity is often very small. A term commonly used in the cybersecurity space is zero-day exploit. Zero-day exploit refers to a vulnerability that has not been patched yet. Often, a very limited number of people are aware of these and they tend to not disclose them so they can take maximum advantage of them. Once an exploit is out in the public, chances are that it will be patched very quickly, in some instances even in a couple of days:

Figure 1.5 – Hacking skills pyramid

Figure 1.5 – Hacking skills pyramid

The preceding diagram shows the skills pyramid according to the expertise of an ethical hacker. Reaching the top requires a combination of experience, analytical skills, and, most importantly, in-depth knowledge of computer systems.

Legality

The rule of thumb in penetration testing is that you should not be attacking a system you are not supposed to. Even if you work in a cybersecurity firm as a penetration tester, you must get written permission in order to test out the security of the system. Without written consent, you can get into a lot of legal trouble. Penetration testing often involves attacking the system with different attack vectors, which could often result in breaking the system. If you do not have prior permission, you will be liable for damages caused to their infrastructure.

Pen-testing encompasses a wide variety of tests. In practical cases, the written contract of consent for testing must explicitly define the scope of the test. It should mention what type of tests will be performed and what systems/assets will be targeted in the test. The testing should strictly remain confined to these predefined objectives. For example, testing for software code should not include testing the network security unless explicitly mentioned.

Pen-testing could be done on production or live systems. If the asset under test is a live system, the user must be properly notified regarding the test and the potential damages associated with the test. Pen-testing is performed in different environments. Sometimes the users in the organization are aware of the pen-testing going on, and in other cases, only the top management knows about it so that they can test which individuals are a potential threat to the organization. If the users in the organization are already aware that a pen-test will be performed, it is a good idea to notify them in advance of the time of the test so that it doesn't interfere with the day-to-day activities of the organization. Next, let's learn about the types of hackers.

 

Types of hackers

As mentioned earlier, there is a specific image attached with the term hacker. However, in real life, hackers are categorized into various categories depending on the type of actions they perform. In the coming sections, we will explain the different types of hackers, what kind of experience they require, and what the legal aspects related to each type are.

White hat hackers

Aim: Defending the business and assets of an organization from external and malicious attacks.

White hat hackers refer to cybersecurity experts or penetration testers whose goal is to test the security of information systems. They are also called ethical hackers or the good guys. Their intention is to defend against malicious hackers, which will be discussed in a moment. White hat hackers use the same tools and technologies and have the same expertise regarding breaking into systems. The only difference lies in their intention. Their goal is to enhance the strength of the system and protect it from outside attacks.

This book aims to help you to become an ethical hacker and help improve the security of the system. Becoming a successful ethical hacker requires years of expertise in learning technologies, understand the thinking process of hackers, and patience. Cybersecurity analysts and penetration testers are some of the highest-paid jobs in the field of computer science.

Black hat hackers

Aim: Breaking into the system with malicious intentions.

Black hat hackers are usually criminals whose motive is to either get financial gain or cause harm to someone with personal, institutional, or national objectives. Black hat hackers try to hide their identity as much as possible; they mostly use pseudonyms to identify themselves. Hacking with malicious intentions is illegal in most countries. Black hat hackers are very hard to detect in a system unless they choose to reveal themselves. A lot of the time, they maintain remote access to systems without the actual owner of the asset knowing about their presence. They are also very good at covering their tracks. Most of them only reveal themselves when the damage has been done. A lot of the time, black hat hackers are a part of different criminal organizations. This makes them even more difficult to capture.

In strict terms, black hat hacker refers to someone whose primary objective is financial gain. The term black hat hacker is derived from the fact that in old western movies, the bad guys would often wear black hats, thus the convention of using black hat for hackers gained popularity.

Gray hat hackers

Aim: Personal motivations or for fun.

The real world is not binary and neither are hackers. Gray hat refers to hackers that operate in somewhat muddy territory. They have the same skillset as white hat or black hat hackers; however, their motivation is usually not financial. Gray hat hackers like to play around with systems just for the sake of fun and enjoyment. Most of the time, they are harmless and even expose the system vulnerabilities to the people responsible. They break into the system just because they can.

Gray hat hackers also like to snoop around systems testing their strengths, and once they discover potential weaknesses, they usually notify the administrators and offer their services for correcting the issues with a service fee. This is a way for them to make money. The legality of this practice is questionable; however, for some, this is a way to earn a handsome amount of money.

As mentioned earlier, the boundary between gray hat hackers and black hat hackers is quite fuzzy. You should be very careful with it. A single mistake or miscalculation can cause significant issues. There is also the danger of gray hat hackers eventually crossing into black hat category.

These are the three main categories of hackers. However, in real life, there are also other terms used that can fall into one of these categories depending on who you ask. It's hard to classify them into a single category, so they will be mentioned separately in the following section.

Nation-state hackers

Aim: Attacking the cyber assets of an enemy.

With the increased dependence of countries on computer-based systems, the need to both protect and attack cyber systems is becoming extremely important. With conventional means of warfare becoming more and more potent and limited in nature, the use of cyber warfare is gaining significance. Nation-state hackers is a term used for a team of hackers focused on damaging the cyber assets of an opposing country.

The history of nation-state or state-sponsored hackers goes back to the early times of computing. Countries have been using hacking as a means of achieving their strategic objectives for a long time. The job of state-sponsored hackers is to penetrate the enemy systems, gain information, plant backdoors for remote control, and even destroy their critical infrastructure. Several high-profile attempts have been made in this aspect and the threat is very real. Just imagine what would happen if an enemy state were to take control of someone's nuclear plant. This plot is not out of some science fiction movies. This has happened in real life as well.

Take the example of the Stuxnet virus, which infected the Iranian nuclear facilities. Stuxnet was a very complicated malware that infected the Supervisory Control and Data Acquisition (SCADA) systems. SCADA systems are used for the monitoring and control of large-scale industrial systems. The virus exploited a vulnerability in the programmable logic controllers (PLCs) used in the facility. The malware was very discreet and only became active if the target system was the Iranian nuclear facility. Even though it infected a large chunk of computer systems, it mostly remained dormant and only activated itself when it reached its intended target. According to most researchers, the complexity of the attack indicated that it was not the job of some criminal organization but a team of highly specialized programmers requiring months of development. These types of resources are often only at the disposal of national-level hackers. Stuxnet took control of the centrifuge speed control signals and starting spinning centrifuges at such high speeds that it eventually led to a breakdown. Stuxnet also intercepted speed status messages going to the SCADA systems so it would make it seem like centrifuges were operating at normal speeds while in reality, they were spinning at far higher speeds. This made Stuxnet very hard to detect and it stayed undetected for quite some time, hampering the nuclear progress in the facility, before finally being detected in 2010.

Corporate spies

Aim: To get a competitive edge.

A lot of business value of companies lies in the intellectual property (IP) they own. This IP sometimes defines the worth of a company. In recent years, companies have been subject to corporate attacks, where attempts have been made to steal their IP. With increased competitiveness in the business world, corporate espionage is becoming a daily occurrence. Companies are subject to attacks from corporate hackers, who aim to steal sensitive information, including IP, business plans, patents, financial data, and customer data, to gain a competitive edge. These attacks can come from competitors directly or they can hire professional hackers for this purpose.

These types of hackers usually fall in the black hat category. However, due to the nature of hacks, they are sometimes classified into a category of their own. The only difference in corporate hackers is that their primary target is usually their competitor, while in other cases the target could be anyone.

Hacktivists

Aim: To make a political/social statement.

Hacktivist is a term combining the words activist and hacker. These types of attacks are usually carried out in order to make a political statement. The aim of these hackers is to make a call for social change or to bring attention to some issue. In contrast to black hat hackers, who try to be as discreet as possible, hacktivists try to gain maximum attention while hiding their real identity. Their goal is to spread their message to the masses. In the majority of hacktivism cases, there is no financial motivation for the hackers. They use the same tools and techniques as other hackers. Hacktivism is the digital equivalent of a political protest. With changing political dynamics, politics is making inroads into the digital space and hacktivism provides a pathway for some people to make their statement.

Hacktivists use different methods to attract attention. Sometimes they disrupt services, for example, carrying out a DoS attack on a company or government website. Other times, they gain access to critical and sensitive information and leak this classified information to the public, causing significant embarrassment for the government or company. One of the major leaks in recent years is the WikiLeaks fiasco.

One thing that should be noted here is that from a legal perspective, there is no difference between hacktivism and black hat hacking. Even if you are participating in some activity for a noble cause and you get caught, you will be tried for the same crimes as a black hat hacker. Therefore, a lot of hackers tend to stay anonymous and use pseudonyms for their activism.

One of the most famous hacking organizations associated with hacktivism is Anonymous. They have allegedly carried out numerous attacks against different governmental organizations to state their sympathy to a cause or opposition to certain legislation. Anonymous calls itself a decentralized organization with people coming together to support a common cause. They have often been dubbed as freedom fighters and the Robin Hood of the digital paradigm. The decentralized nature of this collective means that it has become very hard to crack down on it:

Figure 1.6 – Emblem associated with Anonymous

Figure 1.6 – Emblem associated with Anonymous

Different individuals and small organizations have claimed responsibility for managing the operations of this organization; however, the true nature of this organization remains a mystery. There are other organizations as well, such as LulzSec and Fancy Bear, whose operations are much more dedicated in nature and have caused significant difficulties for cybersecurity professionals.

Script kiddies

In cybersecurity spaces, the term script kiddie refers to beginner hackers who do not have in-depth knowledge about cybersecurity or hacking in general. They often tend to use prebuilt tools for hacking purposes much like a black box approach. They don't essentially know how the hacking tool works internally but they just use it. Script kiddies sometimes lack programming knowledge to build their own tools and rely on existing tools for hacking purposes. The term script kiddie comes from the fact that they use pre-built scripts or programs to carry out attacks.

Script kiddies often acquire a hacking tool such as a reverse shell and deploy it by watching internet tutorials. Their goal is not to learn the process but the final objective, which is to take control of the target system. As long as the tool works, they are not interested in how it works.

A common mistake often made by cybersecurity professionals is to not take script kiddies seriously. A well-deployed attack even from a script kiddie can cause huge damage to the assets. For an attacker to carry out a successful attack, they do not have to know every detail of the script they are using. Just the right angle of attack is sufficient to carry out a successful attack. There are a huge number of tools available online both free and paid that could help someone to carry out attacks. There are hacking organizations that make these tools especially to sell them to script kiddies for carrying out attacks. So, do not think that someone with little knowledge about developing tools is not a threat. In fact, they are as much of a threat as an experienced hacker. The success of an attack depends on both the attacker as well as the tools used.

 

Hacking phases and methodology

With the required knowledge obtained, the process of hacking begins. Like any other well-organized task, hacking has its own sequence of steps that need to be followed to carry out a successful attack. Real-life hacking is a painstaking process and requires a lot of work. From gathering information to attacking to covering your tracks, each step needs to be executed perfectly. One lapse could potentially expose your identity and compromise the whole process. Figure 1.7 shows the different phases of hacking that will be discussed in detail:

Figure 1.7 – Hacking steps

Figure 1.7 – Hacking steps

In the following sections, we are going to take a look at each step, in detail.

Planning

The first step of anything is proper planning. Time spent on proper planning could potentially save a lot of time wasted due to improper planning. The importance of planning cannot be stressed enough. In the following chapter, we will focus on penetration testing methodology, that is, testing how easy it is to penetrate a system or a network. We will perform an attack on a fiction organization called Famous Organization Limited and inside the organization, we will focus on a fictional person, let's call him Mr. Target. In a professional penetration testing scheme, you will need to create a proper workflow in the planning process and maintain all the relevant information obtained during the process in an orderly manner to be used for reporting purposes.

The next step is to identify the target person or system to be attacked. From a penetration testing point of view, here we will define the scope of the test, what it encompasses, its limitations, and the like. Before penetration testing is performed, we should make sure that the system under test is ready for testing. This includes ensuring that testing would not cause a breakdown of the critical infrastructure of an organization.

Before starting the penetration testing program, it should also be clearly mentioned who will be performing the attack and what kind of oversight will be present. The boundaries of what the penetration test includes and what is not included should be clearly defined. Test objectives and timelines should be properly mentioned beforehand. Penetration testing should be aligned with the company's objectives. In some cases, simulated scenarios are also tested where we want to see how an attack would impact the company's day-to-day operations. The planning stage should also determine what kind of penetration test is required.

Reconnaissance

Once the target has been identified and the planning stage is completed, we move forward to starting the penetration testing process. In the simplest terms, reconnaissance means gathering information about the target individual as well as the organization. Before any penetration attack is carried out, our goal would be to gain as much information about the target as we can. The more information we have about the target, the more opportunities we have to carry out a successful attack. There are two methods of information gathering, listed as follows:

  • Passive information gathering
  • Active information gathering

Let's study them in the following sub-sections.

Passive reconnaissance

Passive reconnaissance, as the name indicates, is a method of gathering information about the target individual and company by means of passive sources, without directly interacting with the intended target. This is the safest form of information gathering because there is no interaction with the target so it cannot be traced back to you. Passive reconnaissance includes gathering information from public sources. This could include gathering information available on the internet. Passive information itself is usually harmless, but combined with attack vectors, it can be exploited. For example, let's say that you visit the social media profile of the target and find out that the person is very interested in dogs. This information itself is not very useful. But if you send them an email containing a phishing link (phishing will be explained in a moment) containing some information about dogs, it is more likely that the target will click on this link and eventually compromise the system. Passive reconnaissance is usually done through search engines and public databases. Passive reconnaissance is much slower and usually gives limited technical data about the target. Although it is slower, the risk of getting caught in passive reconnaissance is very low.

Active reconnaissance

In active reconnaissance, you engage with the target directly, either personally or through the computer. Active reconnaissance is much faster and gives a lot of information about the target, albeit at the cost of higher risk. Active reconnaissance includes finding information about the system used by the target as well as other technical specifications associated with the target's system. The following is a list of the most used information sought in active reconnaissance; however, this is not a comprehensive list:

  • IP address: The internet protocol address of the target, both private and public.
  • MAC address: Field identifying the hardware interface used by the target to connect to the network.
  • Ports: Port scanning is one of the most frequently used tools in active reconnaisance. Open ports in the system can be used for initiating a connection with the target without their knowledge.
  • Services/software running on the target machine: Having knowledge of the different services running on a target could be a good starting point for initiating attacks. If a service running on the target has a known vulnerability, it could be easily exploited.
  • Operating system fingerprinting: Determining the operating system used by the target.

These are the most common pieces of information sought in active reconnaissance. You should be very careful with active reconnaissance. Make sure that your identity is completely hidden while performing active reconnaissance. Most modern systems have intrusion detection systems (IDSes). They often keep a log of every attempt made to scan the system. If you are not anonymous, your identity can be easily revealed. Firewalls and IDSes often block unwanted port scans.

Scanning

As mentioned, scanning includes getting technical information about network topology and the target. Understanding the network topology helps you to pivot once you have gained access to the system. Creating a list of active hosts along with the target machine is an important aspect of the scanning process. Detecting firewalls and routers in the network can also be helpful. One of the main goals of scanning is to identify vulnerabilities, either by finding open ports or detecting vulnerable services running on the system. A lot of commercial tools are available for scanning purposes. One of the most famous tools for network reconnaissance is NMAP. NMAP has a Python API that could be used to create automated scanning testing. We will discuss some examples of using the NMAP API in Python in later sections.

Network and port scanning are very noisy processes in terms of generating a lot of network requests. Modern IDSes are very quick to detect them. This means that the slower the scanning process is, the more chance there is of it being successful. Sweeping the network to detect live hosts is one example of this. Application services and version detection are also considered an important aspect of network scanning, though it is a more complicated task.

A packet sniffer is another tool that helps you to monitor network traffic. If you are connected to the same network as the target, it can provide insights into the network traffic, which could help to identify potential opportunities for attack. One of the most famous and free network sniffing tools is Wireshark. It helps you to monitor and see network traffic in detail.

Identifying weaknesses

Network scanning and reconnaissance would give you a lot of information. It is necessary that you keep track of all the information obtained in a structured manner, which would help you to identify relevant information. In practical cases, hackers work on information gathering for an extended period lasting from a few months to even years. Once you are confident that you have sufficient information, you can proceed forward to the next step, which is identifying weaknesses. This step includes examining all the information obtained in the previous step and determining which information could be useful for carrying out an attack.

Attacking and gaining access

Once you have identified the weaknesses, the next step is to start thinking about an attack strategy. There is no hard definition of what an attack strategy would look like. If you want to gain control of the remote system via the command line, you can use either a forward shell or a reverse shell. Most operating systems in use today provide a command-line interface to their functionalities. In Windows, you can access it through the Cmd.exe or powershell.exe programs. In the case of Linux, you can use Bash. You can execute nearly any task on the operating system with the command-line interface and therefore having a command line or command-line interface to the target is extremely dangerous. If you have a command-line process running on the target machine that you can control on your own system, you can essentially do anything with the victim/target machine.

Forward shell

In the forward shell, the attacker tries to initiate a connection to the target machine. In modern systems, this type of strategy is quite hard as IDSes and firewalls of the target system usually block all unwanted incoming connections unless otherwise specified in the firewall rules. This makes this strategy quite difficult to execute.

Reverse shell

In a reverse shell, the attacker plants the malware program into the system in some manner and then once the program is executed on the victim's machine, it initiates a connection back to the hacker, thus giving them full control. These attacks are quite successful since it is very hard for an IDS to differentiate between a legitimate process and a malicious process.

Attacks can also be carried out by exploiting some vulnerability in software running on the target machine. There are a lot of online resources that explain how you can create a payload (a piece of code that performs a malicious operation) and execute it on the target machine. One of the most widely used tools in this domain is Metasploit. It contains tons of preloaded exploits; once you have detected that a vulnerable service is running on the target PC, you can use Metasploit to create payloads that can be delivered to the target machine to gain access to these systems.

Maintaining access

Once you have entered the target machine, the goal should be to maintain persistent access to these systems. Hackers try to maintain access to the system for as long as possible without being detected. There are a lot of reasons why hackers would compromise a system. Sometimes they just gain access to a system to use it as a launchpad to attack other system infrastructure; in this case, they are usually not very concerned about being detected while carrying out something such as a Distributed Denial of Service (DDoS) attack from compromised machines. In other cases, they would stay on the compromised system in stealth mode, watching every activity and sometimes stealing data. Using sniffers, attackers could easily monitor network traffic, which can be very dangerous for the victims.

Once the attacker gets into a system with very primitive access, their immediate goal is to increase their access deep into the network or a system. This would ensure that the attacker has long-term access to the victim/target machine, and they can control it whenever they want. Another important aspect of maintaining long-term access is pivoting, in which you attack other machines present in the same local area network. This helps the attacker to maintain a strong foothold in the network and makes it difficult for the IDS to clean the tracks of the attacker.

Post exploitation

Once you have gained basic system access, it is always a good idea to enhance your access levels. For example, you can get basic user-level access to the system by exploiting a system vulnerability; however, most of the time, this kind of access will be very limited in nature and would not help you to penetrate further into the system. For example, in Windows, you cannot disable an antivirus or IDS using user-level privileges; you need to be an administrator in order to do this. In later sections, we will learn how to increase your access level from a normal user to a system admin, which would virtually give you complete control over the system.

Covering tracks

Covering tracks is an essential aspect of a successful penetration testing attack. In cybersecurity, the incident response team are the individuals whose goal is to limit the extent of the attack and provide restoration operations to the services. Once the hacker achieves their objectives, they should cover their tracks completely; otherwise, they can be easily detected by forensics. Common methods of covering tracks include removing logs and temporary files created during the attack phase and cleaning registry entries, caches, and in some cases browser history. A penetration tester should also be aware of logging mechanisms related to different operating systems. For example, the Windows operating system maintains the record of recently accessed and modified files using jump lists. Digital forensic experts use these technologies to determine the attacker and the extent of the attack on the system.

A lot of open source tools are available on the internet for covering tracks that perform a very good job at hiding your identity. For example, in Metasploit, you can use scripts such as clearv to clear up all event logs on Windows machines.

Another method to cover tracks is by using reverse HTTP shells. A shell is a code that executes user commands on a system. We will talk more about this in later chapters. In most computers, port 80 is used for HTTP packets; therefore, port 80 is open a lot of time in computers. It is very hard for firewalls to distinguish between legitimate and malicious packets over port 80. Using HTTP-based reverse shells, forensic analysts have a very hard time distinguishing hackers.

Once the hacker has gained access to the system, they will run various commands over the command-line interface. Once the objective is achieved, the hacker usually deletes the command history in order to avoid detection. This is done using the export HISTSIZE=0 command in Linux-based systems.

Reporting

The last phase of penetration testing or ethical hacking is to compile a report about all the weaknesses of the system as well as the achieved objectives of the penetration test. The pen-test report should list out all the necessary details regarding the attack. A penetration test report usually contains the following items.

Summary

The summary should summarize the pen-test briefly. It should explain the main reason for the pen-test. The following points should be considered while writing a summary report for a pen-test:

  • The purpose and objectives of the pen-test
  • The scope of the pen-test
  • A brief list of the tests performed
  • The findings of the pen-test
  • The conclusion of the pen-test

These tasks are explained as follows.

Introduction

In the introduction section, all the relevant information about the test environment should be explained. It should mention the timeline of the pen-test from the start to the end. How long did the pen-test take? It should mention the methodology and approach used to perform the pen-test. Which systems were targeted during the pen-test and finally, what kind of tests were performed?

Methodology

In this section, we should list all the procedures and methods used to attack the target. For example, how did we get information about the target and what information did we get? How was this information used in carrying out the attack? Which methods of delivering the payload were used? For example, did the attacker send a malicious PDF file to the target? It should also mention the difficulty level for the attacks, that is, which aspects were easy to attack and which sections were hard.

Findings

The findings section should mention the vulnerabilities and threats detected in the pen-test. It is a good idea to divide the number of vulnerabilities found into different levels based on their severity level. An example of this test would be to perform a vulnerability scan on the devices and detect whether any vulnerable service is running on the system. Finally, the findings should also mention the positives of the system as well, for example, strong firewall configuration and strong passwords. For serious vulnerabilities and threats, in-depth details should be mentioned. It is a good idea to attach necessary screenshots and findings to the document.

 

Careers in cybersecurity

Cybersecurity is a huge field and writing about every aspect of it would probably require another book. However, I will try to explain major trends in cybersecurity and what kind of skills you will need to master it. Some of the more common careers are listed in the following sections, although this is by no means an exhaustive list.

Systems security administration

Just like a system administrator whose job is to maintain and administer systems in an organization, the goal of a system security administrator is to focus on the administration of the system's security. Their job is to perform daily security tasks, such as system monitoring and backup management.

Security architect

Networks are one of the most important aspects of modern computer systems and more often than not, they are the entry point for attackers into an organization, thus managing, maintaining, and securing the network is extremely important for organizations. The job of the security architect includes problem reporting, breach analysis, and so on.

Penetration tester

As mentioned earlier, the goal of a penetration tester is to test the strength of an organization's defenses. In simple words, the goal of a penetration tester is to hack into the system and gain unauthorized access. The job of a penetration tester also includes detecting system vulnerabilities. Sometimes, penetration testers also work in incident response teams to defend against real threats. Penetration testers are often tasked with designing their own tools focused on the organization's requirements. Most of this book will follow the rough footsteps to become a penetration tester. A penetration tester is one of the highest-paid jobs in cybersecurity and requires a lot of skill.

Forensic analyst

As the name indicates, the job of a computer forensic analyst is to evaluate the digital assets and review the evidence in the case of a system breach. Their tasks include securing digital and physical proofs after a breach to be used in the analysis as well as to be potentially used in court against hackers. Forensic computer analysts must be sensitive to the security concerns of their employers or clients and follow closely all the privacy procedures when dealing with financial and personal information.

Chief information security officer

The chief information security officer (CISO) is usually an executive position. The CISO's job is to oversee the planning, coordinating, and directing of the system, network, and data security needs of the organization. Their job is to ensure security compliance, evaluate the threat landscape, and devise policies and controls to ensure the safety of the organization.

 

Types of attacks

There are several different types of cyber-attacks depending on how they are executed. The nature of these attacks can vary depending on various factors such as the intentions of the attacker and the tools that are used for the attack. More often than not, the purpose of these attacks is to either gain complete control of the system, to steal sensitive information, or both.

System control

Attacks would often like to take charge of the victim's computer and play around with it. This could either mean rendering the system useless for the victim or making a stealth attempt to gain access without the victim knowing about it. A very famous set of attacks in this category are called remote access tool attacks. These attacks provide the attacker with complete or near-complete control of the victim's PC remotely. We have already discussed forward and reverse shells, which are used for these purposes quite frequently.

Social engineering

Another popular kind of attack that often requires little to no technical knowledge is social engineering. In simple terms, social engineering means manipulating or tricking someone into giving you the information. Instead of writing lengthy code and exploiting technical weaknesses of the system, you can simply trick the person into giving you information to carry out a cyber-attack. There are two fundamental aspects of cybersecurity: one is a technical aspect and the other is a human aspect. A security system is as good as its weakest link. More often than not, the weakest link in the security of the system is people. No system is secure if you have the key to breaking it. Social engineering is not as simple as it seems. It requires patience and attention to detail. Some of the more common social engineering tricks are explained next.

Baiting

Baiting simply means luring the target to bait and then waiting for the target to make a mistake. For example, hackers often drop USB drives filled with malware near the offices of organizations and wait until some employee gets curious and plugs the USB into their computer. Once they do so, the rest of the job is done by the malware.

Phishing

Phishing is an attack technique in which attackers impersonate someone the target trusts. Usually, they try to take advantage of people's interests. For example, if someone is a football fan, they are more likely to open an email or a link related to the topic of football and thus provide the attacker with a means to attack the victim. A common example of this attack is clone websites hosted by the attacker. An attacker would send a fake link to the target that resembles a website known to the target. However, the website will be hosted by the attacker and instead of going to the real website, the target will be directed to this website. These cloned websites look very similar to the original ones and if you are not careful, it is very hard to distinguish. Since this cloned website is operated by the hacker, any data that the user enters goes to the hacker. A good way to detect these fake websites is to check the website name along with the protocol. A real website will mostly operate on the https protocol.

 

Summary

In this chapter, we learned about the basics of hacking and the different types of hackers in the real world. We then examined the hacking steps in detail and what each of these steps entails. At the end, we saw what the different careers in cybersecurity are and how this book can help us in these careers. Lastly, we explored the different aspects of social engineering and how it can be used to carry out attacks. In the next chapter, we will start learning about how to set up our lab environment and what tools we will use in this book.

About the Author

  • Fahad Ali Sarwar

    Fahad has been teaching ethical hacking and penetration testing on different online platforms with a solid student base. He's passionate about cybersecurity and ethical hacking tool development.

    Fahad is particularly enthusiastic about Python for its simplicity and ease of use and in this book he has chosen it as a language of preference due to its features.

    Browse publications by this author

Latest Reviews

(1 reviews total)
Not able to download the purchased product. Opened a support case and still waiting for feedback.

Recommended For You

Python Ethical Hacking from Scratch
Unlock this book and the full library for $5 a month*
Start now