Python Ethical Hacking from Scratch - Fahad Ali Sarwar - E-Book

Python Ethical Hacking from Scratch E-Book

Fahad Ali Sarwar

0,0
31,19 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

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.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 228

Veröffentlichungsjahr: 2021

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Python Ethical Hacking from Scratch

Think like an ethical hacker, avoid detection, and successfully develop, deploy, detect, and avoid malware

Fahad Ali Sarwar

BIRMINGHAM—MUMBAI

Python Ethical Hacking from Scratch

Copyright © 2021 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Group Product Manager: Wilson D'souza

Publishing Product Manager: Vijin Boricha

Senior Editor: Rahul D'souza

Content Development Editor: Nihar Kapadia

Technical Editor: Nithik Cheruvakodan

Copy Editor: Safis Editing

Project Coordinator: Shagun Saini

Proofreader: Safis Editing

Indexer: Manju Arasan

Production Designer: Jyoti Chauhan

First published: July 2021

Production reference: 1270521

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham

B3 2PB, UK.

ISBN 978-1-83882-950-6

www.packt.com

Contributors

About the author

Fahad Ali Sarwar teaches 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 chose to focus on it due to the features it offers.

About the reviewers

Omar Ahmed specializes in application and network penetration testing. He has performed dozens of ethical hacking engagements for clients in a wide variety of industries, including government, finance, retail, and manufacturing. Omar has had unique opportunities to assess the security of new applications and technologies ranging from web-enabled e-business applications to proprietary applications.

His security career started in 2012, concentrating on network and application security. Omar has excelled in penetration testing, application assessments, social engineering (both physical and virtual), vulnerability assessments, and log analysis. You can reach out to him on Twitter at @mistspark.

Marquel Waites is a cyber analyst and military veteran, with 21 years of leadership experience in the United States Army and a future career goal of becoming a director of IT security (CISO). He has achieved measurable results while leading organizations of more than 100 people in dynamic, fast-paced environments. He possesses a comprehensive background in financial management operations, cybersecurity operations, incident response coordination, security analytics and monitoring, cybersecurity policy and technical compliance, and cybersecurity risk and vulnerability management. Marquel has managed risk on multiple lines to protect assets, property, and equipment valued at more than $256M while exceeding the expectations of senior executive stakeholders. He is the recipient of multiple awards for outstanding performance and professionalism. His career is supported by a Bachelor of Science degree in information technology management from Trident University, a Master of Science degree in cybersecurity policy from Colorado Technical University, and a Master of Science in cybersecurity and cloud security architecture from EC Council University. He holds numerous certifications, including Certified Ethical Hacker, Certified Network Defense Architect, and Security+.

I would like to thank Packt for giving me the opportunity to review this book, and I hope this book helps everyone professionally. I would like to thank all the professors at EC Council University and the Coalfire team for continually inspiring me to become a better cybersecurity professional.

Table of Contents

Preface

Section 1: The Nuts and Bolts of Ethical Hacking – The Basics

Chapter 1: Introduction to Hacking

What's all the fuss about hackers?

What is hacking?

Confidentiality

Integrity

Availability

Becoming a successful hacker

Legality

Types of hackers

White hat hackers

Black hat hackers

Gray hat hackers

Nation-state hackers

Corporate spies

Hacktivists

Script kiddies

Hacking phases and methodology

Planning

Reconnaissance

Scanning

Identifying weaknesses

Attacking and gaining access

Maintaining access

Post exploitation

Covering tracks

Reporting

Careers in cybersecurity

Systems security administration

Security architect

Penetration tester

Forensic analyst

Chief information security officer

Types of attacks

System control

Social engineering

Baiting

Phishing

Summary

Chapter 2: Getting Started – Setting Up a Lab Environment

Technical requirements

Setting up VirtualBox

Installing virtual OSes

Attack machine OS

Installing Python

Installing Python on Windows

Installing Python on Kali Linux

Integrated development environment

Setting up networking

Updating Kali

Using virtual environments

Summary

Section 2: Thinking Like a Hacker – Network Information Gathering and Attacks

Chapter 3: Reconnaissance and Information Gathering

What is a computer network?

Components of a basic computer network

Node

Server

Transmission media

Network interface card

Hub

Switch

Router

Gateway

Firewall

Classifying network

Local area network

Personal area network

Metropolitan area networks

Wide area network

Internet

Network stack

Introduction to OSI model

Complete cycle

TCP/IP model

Mapping the OSI and TCP/IP stack

Network entities

Private IP address

IPv4 versus IPv6

MAC address

Ports

Protection

Changing our MAC address

Creating a Python script

Summary

Chapter 4: Network Scanning

Introduction to networking

Data representation in digital systems

Data encapsulation

The packet delivery process

Introduction to Scapy

Installing Scapy

Understanding how Scapy works

Network scanner using Scapy

Address Resolution Protocol

ARP scanner using Scapy

Summary

Chapter 5: Man in the Middle Attacks

Why do we need ARP?

ARP poisoning

Building an ARP spoof program

Arp spoof project

Monitoring traffic

Encrypted traffic

Restoring ARP tables manually

Decrypting the network traffic

HTTPS versus HTTP

Bypassing HTTPS

Summary

Section 3: Malware Development

Chapter 6: Malware Development

Understanding RATs

Forward shell

Reverse shell

Socket programming in Python

Sockets

Creating a socket in Python

socket.socket() API

socket.bind() API

socket.listen() API

socket.accept() API

socket.connect()

socket.send()

Socket.recv()

socket.close()

Fitting it altogether

Creating malware

Hacker server

Victim's client

Running commands remotely on the victim's machine

Navigating directories

Summary

Chapter 7: Advanced Malware

Building a keylogger file transfer

Downloading the victim file to the hacker

Uploading files to the victim

Taking screenshots

Keylogger

Summary

Chapter 8: Post Exploitation

Packaging the malware

Understanding the pyinstaller library

Understanding trojans

Adding an icon to an executable

Creating your own trojan

Attack over a public IP

Cracking passwords

Stealing passwords

Creating botnets

Summary

Chapter 9: System Protection and Perseverance

Persistence system protection

Intrusion detection systems

IDS detection mechanisms

Bypassing an IDS

Persistence

Summary

Why subscribe?

Other Books You May Enjoy

Preface

Ethical hacking is a vast field, and with the increased need for cybersecurity in modern organizations, the demand for ethical hackers and penetration testers is increasing rapidly. This book aims to get you started on your journey in cybersecurity. Python is a general-purpose programming language that was developed by Guido van Rossum in 1991. Since then, it has gained an enormous fanbase. Python is consistently ranked as the most preferred and most powerful programming language by hackers, and being able to use it for penetration testing is a highly desired skill for professionals. There is so much to learn about cybersecurity that it takes many years of experience to get the hang of things in this field. There is hardly any other field that changes as rapidly as cybersecurity. In this book, we will start our journey by learning about the basics of hacking, and later in the book, we will focus on learning how hackers build their own tools.

Who this book is for

This book is intended for people who want to learn about ethical hacking by developing tools themselves instead of just using prebuilt tools; you will learn how to build hacking tools from scratch. This book is also intended for Python developers who want to dive into the world of ethical hacking.

What this book covers

Chapter 1, Introduction to Hacking, is where you will learn the fundamentals of hacking.

Chapter 2, Getting Started – Setting Up a Lab Environment, sees you set up a lab environment.

Chapter 3, Reconnaissance and Information Gathering, covers getting to know the victim.

Chapter 4, Network Scanning, teaches you how to explore local networks.

Chapter 5, Man in the Middle Attacks, goes into depth on how to attack a local network.

Chapter 6, Malware Development, covers developing your own malware.

Chapter 7, Advanced Malware, explores developing advanced features.

Chapter 8, Post Exploitation, looks at exploiting the victim machine.

Chapter 9, System Protection and Perseverance, is all about protecting your system against external attacks.

To get the most out of this book

To get the most out of this book, try to follow all the examples included. This book is designed to be hands-on, so practicing the development exercises will help you gain proper insight into attack methodologies. This book assumes that you are familiar with the Python programming language.

If you are using the digital version of this book, we advise you to type the code yourself or access the code via the GitHub repository (link available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.

Download the example code files

You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/Python-Ethical-Hacking. In case there's an update to the code, it will be updated on the existing GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Download the color images

We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: http://www.packtpub.com/sites/default/files/downloads/9781838829506_ColorImages.pdf.

Conventions used

There are a number of text conventions used throughout this book.

Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "This will open a dialog box, and you can select the kali machine ova file you just downloaded."

A block of code is set as follows:

    subprocess.run(

        ["ifconfig", "eth0"],

        shell=True,

    )

Any command-line input or output is written as follows:

sudo dpkg -i /path/to/file

Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "Press Yes and you will see the following screen."

Tips or important notes

Appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at [email protected].

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Reviews

Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!

For more information about Packt, please visit packt.com.

Section 1: The Nuts and Bolts of Ethical Hacking – The Basics

This part of the book deals with the basic concepts you need to understand before embarking on this journey. It deals with the basic knowledge and skillset you need in order to fully take advantage of this book. It gives a short overview of the field of ethical hacking and what it entails.

This part of the book comprises the following chapters:

Chapter 1, Introduction to HackingChapter 2, Getting Started – Setting Up a Lab Environment

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 hackerTypes 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

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

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

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

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.