🆕 Introducing HTB CDEP: Certified Detection Engineering Principal Learn More

Python for Blue Team

mini-module tag Mini-Module

The "Python for Blue Team" module focuses on equipping cybersecurity professionals within the Blue Team with practical Python skills tailored for effective threat detection and strategic defense methodologies.

Created by letsdefendio

Hard Defensive
Image

Summary

The Python for Blue Team module is designed for cybersecurity professionals within the Blue Team and Incident responders seeking to enhance Python skills. Throughout this module, students will develop proficiency in Python programming for advanced threat detection and defense, enhanced skills in utilizing Python for cybersecurity analysis and defensive strategies, and advanced understanding of Python's application in a cybersecurity context.

Recommended prior knowledge:

  • Basic understanding of Python programming language

  • Familiarity with cybersecurity concepts and defensive strategies

Web Scraping with Python


What is Web Scraping and Why Should We Know?

Web scraping is the process of parsing the HTML content of a website and extracting data from that content. Web scraping is usually done using automated software or scripts. These scripts typically do the same thing a web browser might do: open a website, find certain information, and collect or store that information in the most effective way.

Web scraping is very useful and widely used in many scenarios. Its use in the security perspective is already our topic, but it would be eye-opening to give examples of other issues where it can be useful:

Data Science and Machine Learning

Most machine learning models need data, and web scraping can be used to collect this data. For example, a person may need to analyze the sentiment of social media comments and use web scraping to collect these comments.

Market Research

Companies and individual researchers can use web scraping to gather information about online product prices, product features, consumer reviews, and more. This can be used to track trends, look at competitor prices, or perform market analysis.

Web Content Scraping

A person or company may use web scraping to gather information about a particular topic. For example, a person can collect all recipes and put them together in a single database.

Data Integration

Web scraping can also be used to collect data from different sites and combine it in one place. This can be used to create a news portal or a price comparison site that provides information from different sources.

Warning: Before continuing with the topic, it is important to remember that Web Scraping applications may cause legal responsibilities. For example, a website's terms of use may prohibit scraping on that site. Additionally, the use of collected data may also be subject to various data protection and privacy laws. Therefore, when starting a web scraping project, it is important to consider these aspects.

Python is an ideal tool for web scraping with its extensive library support and ease of use. In this part of the training, we will cover the basic concepts of web scraping with Python and look at some examples that security professionals can use in their daily work.


Tools for Python Web Scraping

There are many libraries for web scraping in Python such as “Beautiful Soup”, “Scrapy” and “Requests”.

Beautiful Soup

It is a Python library used for web scraping. It is used to parse HTML and XML files.

In fact, “Beautiful Soup” is not a scraper on its own, but a parsing library. Its main power is HTML, XML, etc. It can parse many formats automatically and does not compromise on performance. It needs a library like “requests”, etc. to work.

Although it is a very powerful tool, it is not preferred in very large projects.

Scrapy

It is a more powerful and feature-packed web scraping library than Beautiful Soup. It has various features such as parsing, processing requests, and storing data.

This tool does everything Beautiful Soup does, plus includes its own request libraries. Although it is a bit complicated to learn, it offers highly advanced support in large and complex projects, from optimization of requests to user-agent manipulations, from data storage automation to middleware integrations.

Requests

It is used to send HTTP requests in Python. This library is used to retrieve the content of a web page. There is no parser mechanism in itself. Although it is quite sufficient in cases where the raw response meets your needs, it can be quite tiring as you will be left with string functions to perform complex operations on the returned response.

Python is a wide world to which many developers contribute, and therefore, apart from the ones we have mentioned, there are dozens of different libraries/frameworks, etc. available that are specialized for various purposes. Although we cannot explain all of them here, we recommend that you investigate these options when you have a web scraping project.


Beautiful Soup

Let's start by making a sample of Beautiful Soup together. Let our code be like this:

import requests from bs4 
import BeautifulSoup 
URL = "https://letsdefend.io" 
page = requests.get(URL) 
soup = BeautifulSoup(page.content, "html.parser") 
results = soup.find("meta", {"name":"description"}) 

print(results)

When we run it, it is very likely that you will get an output like this:

Image

The message here says that the “bs4” library is not yet installed on our system, so we cannot use BeatifulSoup. What we need to do is simple:

pip3 install bs4

Image

When we wanted to install the bs4 library with pip3 in our Ubuntu 20.4 environment, we received a notification saying that pip3 was not installed yet. Fortunately, there is a notification right below telling us what to do. We immediately ran the sudo apt install python3-pip

command, and then we installed the bs4 library on our system with the pip3 install bs4 command:

Image

In the later parts of the module, the missing libraries in your system will appear again, in this case, you will need to proceed by installing the missing libraries with pip3, just like we have done here. Now we can get back to work. We think our script will now work:

Image

Now let's examine what we did line by line:

import requests from bs4 
import BeautifulSoup

In these two lines, the modules required for the operation of the code are included. The "requests" module allows communicating with web servers using the HTTP protocol. "BeautifulSoup" is used to parse HTML and XML documents.

In the next line, we assign the URL of the target website to a variable.

URL = "https://letsdefend.io"

In the next line, an HTTP GET request is sent to the specified URL using the "requests.get()" method. The response to this request is thrown into a variable called "page".

page = requests.get(URL)

In the next line, we create an instance of the BeautifulSoup class. We use BeautifulSoup to parse the content of the retrieved web page. We obtain the content with "page.content" and parse it in HTML format with "html.parser".

soup = BeautifulSoup(page.content, "html.parser")

In the next line, using the "find" method of the BeautifulSoup library, we look for the "meta" tag and the element whose "name" property is "description" in the HTML document. We assign the first match found to the "results" variable.

results = soup.find("meta", {"name":"description"})

And finally, we print the result to the screen:

print(results)

Scrapy

Now let's take a look at how things work with Scrapy:

We first need to create a project with Scrapy. We created our project by naming it “letsdefend_scraper”:

Image

When we ran this command, scrapy created a project directory for us and automatically placed the directories it needed to run in the project directory:

Image

Now all we need to do is to write the code for our purpose and save it in the spiders directory in the project directory.

Let's continue by saving the following code in the spiders directory under the name description_spider.py:

import scrapy

class DescriptionSpider(scrapy.Spider):
    name = 'description'
    start_urls = ['https://letsdefend.io']

    def start_requests(self):
        for url in self.start_urls:
            yield scrapy.Request(url, callback=self.parse_description)

    def parse_description(self, response):
        description = response.xpath('//meta[@name="description"]/@content').get()
        print("Description:", description)

When we run the command, scrapy crawl description

at the letsdefend_scraper directory we will get an output like the following (we have highlighted the part we are looking for with a gray background for you):

Image

The output looks very complicated, right? Our suggestion to you is to examine and understand the working logic of Scrapy on each line in this output. Then, all you have to do is to add the

–nolog parameter

to the end of your command to see the cleaner output you requested:

Image


Requests

We already used requests above, with page = requests.get(URL) in Line 4 of our BeatifulSoup example. Then we processed the response by giving it to BeatifulSoup's HTML parser. We don't actually need this for simple tasks that don't require Performance and Optimization. We can parse the data we are looking for by using Python's built-in string functions within the content we receive with Python requests.

Let's look at an example:

import scrapy 
class DescriptionSpider(scrapy.Spider): 
    name = 'description' 
    start_urls = ['https://letsdefend.io'] 

def start_requests(self): 
    for url in self.start_urls: 
    yield scrapy.Request(url, callback=self.parse_description) 

def parse_description(self, response): 
    description = response.xpath('//meta[@name="description"]/@content').get()
    print("Description: ", description)

When we save and run the above code as “request.py”, we get the following output:

Image

In this part of the training, we have covered what web scraping is, important items to know about web scraping and some tools and usage examples that can be used for web scraping in Python. In the next part of the training, we will be learning about the Web Scraping Lab with Python topic.

Sign Up / Log In to Unlock the Module

Please Sign Up or Log In to unlock the module and access the rest of the sections.

Relevant Paths

This module progresses you towards the following Paths

Programming for Cybersecurity

Gain essential coding skills for cybersecurity, across PowerShell, Bash, Python, and Go, to protect against digital threats and enhance your abilities in the ever-evolving field of cyber defense.

Hard Path Sections 63 Sections
Required: 410
Reward: +90
Path Modules
Medium
Path Sections 10 Sections
Reward: +10 NEW
The "Introduction to Python" module is designed to familiarize detection engineers in cybersecurity with the Python programming language, enabling them to effectively apply it in the context of threat detection and analysis.
Python for Blue Team
mini module tag Mini-Module
Hard
Path Sections 8 Sections
Reward: +10 NEW
The "Python for Blue Team" module focuses on equipping cybersecurity professionals within the Blue Team with practical Python skills tailored for effective threat detection and strategic defense methodologies.
Medium
Path Sections 7 Sections
Reward: +10 NEW
This module is designed to provide detection engineers in the cybersecurity field with a foundational understanding of Bash scripting, enabling them to bolster their capabilities in threat detection and incident response.
Hard
Path Sections 6 Sections
Reward: +10 NEW
The "Advanced Bash Scripting" module is designed to improve participants' knowledge and skills in using complex scripting techniques for cybersecurity. It aims to enable individuals to effectively tackle intricate security challenges by employing advanced scripting methodologies.
Hard
Path Sections 7 Sections
Reward: +10 NEW
The "Bash Scripting for Blue Team" module focuses on providing the essential scripting skills required for cybersecurity defense, specifically tailored for the Blue Team. It aims to equip individuals with the practical knowledge needed to proactively manage and defend against security threats.
Easy
Path Sections 7 Sections
Reward: +10 NEW
The "Introduction to PowerShell" module is designed to provide participants with a fundamental understanding of PowerShell, covering installation, basic command usage, file and directory operations, optimization techniques, and effective error handling for a well-rounded learning experience.
Hard
Path Sections 6 Sections
Reward: +10 NEW
The "PowerShell for Analysis" module is designed to equip cybersecurity professionals with the skills to leverage PowerShell's scripting capabilities for thorough and effective analysis of data, enabling robust threat investigations within cybersecurity.
Hard
Path Sections 7 Sections
Reward: +10 NEW
The "Advanced PowerShell for Blue Team" module is designed to improve participants' knowledge of using advanced PowerShell techniques. This module is specifically customized to enhance cybersecurity defense strategies for the Blue Team.
Go for Cybersecurity
mini module tag Mini-Module
Medium
Path Sections 5 Sections
Reward: +10 NEW
Discover how to detect and thwart malicious activity across various domains with our specialized Golang for Cybersecurity module. Gain the expertise to analyze, identify, and counter potential threats lurking within emails, networks, systems, and files. Through practical exercises and real-world examples, learners will master the application of Golang to fortify their cybersecurity defenses and safeguard critical digital assets.

Google Cybersecurity Certificate Preparation

The Google Cybersecurity Certificate Preparation Path equips learners with the foundational knowledge and practical skills needed to succeed in the Google Cybersecurity Certificate and to build a credible footing for an entry-level cybersecurity role. The path moves from core security principles into the hands-on competencies that employers expect, covering cybersecurity best practices, scripting and Linux fundamentals, threat and vulnerability management, and the essentials of working with a SIEM.

Medium Path Sections 224 Sections
Required: 1120
Reward: +240
Path Modules
SOC Fundamentals
mini module tag Mini-Module
Fundamental
Path Sections 10 Sections
Reward: +10
This module provides comprehensive coverage of SOC Fundamentals concepts and techniques. Topics covered include Common Mistakes made by SOC Analysts, EDR - Endpoint Detection and Response, Introduction to SOC, Log Management, SIEM and Analyst Relationship, and more.
Network Log Analysis
mini module tag Mini-Module
Hard
Path Sections 10 Sections
Reward: +10
This module provides comprehensive coverage of Network Log Analysis concepts and techniques. Topics covered include DNS Log Analysis, Firewall Log Analysis, Generic Log Analysis (Netflow), IDSIPS Log Analysis, Introduction to Network Log Analysis, and more.
Easy
Path Sections 6 Sections
Reward: +10 NEW
Delve into the art of network packet analysis in this comprehensive module. Gain essential skills to diagnose network issues, detect security threats, and optimize network performance. Learn protocols, tools, and techniques to capture, analyze, and interpret network traffic. Uncover hidden insights from packet headers and payloads, troubleshoot latency and congestion, and enhance network security. Whether you're a network administrator, security analyst, or IT professional, this module equips you with the knowledge and hands-on experience to excel in network packet analysis.
Medium
Path Sections 7 Sections
Reward: +10 NEW
This module is designed to provide detection engineers in the cybersecurity field with a foundational understanding of Bash scripting, enabling them to bolster their capabilities in threat detection and incident response.
Hard
Path Sections 7 Sections
Reward: +10 NEW
The "Bash Scripting for Blue Team" module focuses on providing the essential scripting skills required for cybersecurity defense, specifically tailored for the Blue Team. It aims to equip individuals with the practical knowledge needed to proactively manage and defend against security threats.
Hard
Path Sections 7 Sections
Reward: +10 NEW
The "Vulnerability Management" module is a comprehensive training program focusing on identifying, assessing, and managing system vulnerabilities within the realm of cybersecurity. It offers in-depth insights into various vulnerability management strategies, techniques, and tools essential for building robust defense systems. Participants will gain practical knowledge to proactively identify, prioritize, and mitigate vulnerabilities, minimizing potential risks and fortifying cybersecurity measures effectively within organizational infrastructures. The module aims to empower cybersecurity professionals and IT personnel with the skills to protect systems against potential threats and enhance overall cybersecurity posture.
Medium
Path Sections 13 Sections
Reward: +10
This module provides comprehensive coverage of Introduction to Cryptology concepts and techniques. Topics covered include Base64 EncodingDecoding, Basic Concepts of Cryptology, Cryptographic Attacks, Digital Signatures, Hash Functions, and more.
Medium
Path Sections 13 Sections
Reward: +10
Elevate your cybersecurity capabilities with our Incident Response on Linux module. This program provides thorough training on detecting, analyzing, and mitigating security threats in Linux environments. Tailored for IT professionals, system administrators, incident responders and security analysts, the module offers practical, hands-on experience to strengthen your incident response skills. By mastering essential tools and techniques, you’ll be equipped to safeguard networks and protect data effectively.
Medium
Path Sections 13 Sections
Reward: +10
Enhance your cybersecurity expertise with our Incident Response on Windows module. Dive into essential techniques for detecting, analyzing, and mitigating security threats on Windows systems. Gain hands-on experience and practical knowledge to handle incidents swiftly and efficiently.
Medium
Path Sections 10 Sections
Reward: +10 NEW
The "Introduction to Python" module is designed to familiarize detection engineers in cybersecurity with the Python programming language, enabling them to effectively apply it in the context of threat detection and analysis.
Python for Blue Team
mini module tag Mini-Module
Hard
Path Sections 8 Sections
Reward: +10 NEW
The "Python for Blue Team" module focuses on equipping cybersecurity professionals within the Blue Team with practical Python skills tailored for effective threat detection and strategic defense methodologies.
Network Security
mini module tag Mini-Module
Medium
Path Sections 10 Sections
Reward: +10 NEW
During this module section, we'll explore the intricacies of network security, focusing on practical security strategies and techniques to enhance your ability to protect digital systems effectively.
Medium
Path Sections 11 Sections
Reward: +10 NEW
"Network Design and Security Products" is a comprehensive module focused on the intricate world of network architecture and the critical role security products play within it. This module delves into the strategic planning and implementation of robust network infrastructures, with an emphasis on security considerations. Students will gain insights into the fundamentals of network design, including network topologies, protocols, and scalability. They will also explore the latest advancements in security products, such as firewalls, intrusion detection systems, web application firewalls (WAF), and encryption technologies. Throughout the module, students will learn to assess potential network vulnerabilities and develop strategies to mitigate risks.
Network Fundamentals
mini module tag Mini-Module
Fundamental
Path Sections 10 Sections
Reward: +10 NEW
This module provides comprehensive coverage of Network Fundamentals concepts and techniques. Topics covered include About Network Fundamentals Module, IP Addressing Mechanism, Introduction to Network Fundamentals, Network Address Translation (NAT), Network Devices, and more.
Easy
Path Sections 12 Sections
Reward: +10 NEW
This module provides comprehensive coverage of Network Fundamentals II concepts and techniques. Topics covered include Address Resolution Protocol (ARP), Basic Concepts, Internet Control Message Protocol (ICMP), Internet Protocol (IP), Introduction to Network Fundamentals 2, and more.
Network Protocols
mini module tag Mini-Module
Easy
Path Sections 8 Sections
Reward: +10 NEW
This module provides comprehensive coverage of Network Protocols concepts and techniques. Topics covered include Domain Name System (DNS) - 1, Domain Name System (DNS) - 2, Introduction to Network Protocols, Telnet (Teletype Network) Protocol, Transmission Control Protocol (TCP) - 1, and more.
Network Protocols - 2
mini module tag Mini-Module
Easy
Path Sections 8 Sections
Reward: +10 NEW
This module will teach you how application-level protocols work and how you can use it as SOC Analyst or Incident Responder. As an investigator, you need to know the basics of these protocols to use it as evidence.
SIEM 101
mini module tag Mini-Module
Fundamental
Path Sections 6 Sections
Reward: +10 NEW
This module provides comprehensive coverage of SIEM 101 concepts and techniques. Topics covered include Alerting, Log Aggregation and Parsing, Log Collection, Log Storage, SIEM Introduction.
Security Solutions
mini module tag Mini-Module
Easy
Path Sections 14 Sections
Reward: +10
This module provides comprehensive coverage of Security Solutions concepts and techniques. Topics covered include Antivirus Software (AV), Asset Management Solutions, Data Loss Prevention (DLP), Email Security Solutions, Endpoint Detection and Response (EDR), and more.
Medium
Path Sections 6 Sections
Reward: +10
In this module, we will cover how to handle cybersecurity incidents properly, incident response processes with its proper order along with the recommendations of the "Computer Security Incident Handling Guide".
Easy
Path Sections 6 Sections
Reward: +10 NEW
The "Security Audit and Testing" module offers a comprehensive understanding of assessing and enhancing digital security through rigorous auditing and testing procedures. Participants delve into techniques for identifying vulnerabilities, conducting risk assessments, and employing industry-standard tools to evaluate the resilience of networks, applications, and databases. Through practical applications and theoretical knowledge, students learn to interpret audit findings, prioritize security measures, and develop actionable strategies to mitigate risks effectively. This module equips learners with essential skills to safeguard sensitive information and maintain organizational integrity in today's interconnected digital environment.
Linux for Blue Team
mini module tag Mini-Module
Fundamental
Path Sections 14 Sections
Reward: +10 NEW
This module provides comprehensive coverage of Linux for Blue Team concepts and techniques. Topics covered include About This Course, Archive File Formats, Basic Terminal Commands - 1, Basic Terminal Commands - 2, Introduction to Linux, and more.
Secure Network Design
mini module tag Mini-Module
Medium
Path Sections 9 Sections
Reward: +10 NEW
The "Secure Network Design" module offers comprehensive insights into designing and implementing networks that prioritize security, equipping cyber people with the expertise to create resilient and protected digital infrastructures against evolving cyber threats. Through a blend of theoretical concepts and practical applications, participants will gain a deep understanding of network architecture, access controls, and risk management strategies, enabling them to develop and maintain secure communication channels within a dynamic and interconnected technological environment.
Job Hunting
mini module tag Mini-Module
Medium
Path Sections 6 Sections
Reward: +10
This module provides comprehensive coverage of Job Hunting concepts and techniques. Topics covered include Getting Ready for the Interview, How and Where to Look for a Job, How to Prepare a Cybersecurity Resume, Introduction to Job Hunting, What Should You Expect, and more.