Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A bare-bones example of how to write alternate data streams with C#
using Microsoft.Win32.SafeHandles;
using System;
using System.IO;
using System.Runtime.InteropServices;
namespace AlternateDataStreams
{
class Program
{
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern SafeFileHandle CreateFile(
string lpFileName,
EFileAccess dwDesiredAccess,
EFileShare dwShareMode,
IntPtr lpSecurityAttributes,
ECreationDisposition dwCreationDisposition,
EFileAttributes dwFlagsAndAttributes,
IntPtr hTemplateFile);
static void Main(string[] args)
{
string basePath = @"c:\Users\tekhe\temp\";
string baseFile = "funwithfiles.txt";
//First create a vanilla text file
File.WriteAllText(Path.Combine(basePath, baseFile), "This is the normal, unnamed data stream.");
//Write an image to the ADS
CreateFileWithAlternateDataStream(basePath, baseFile, ":TheKitten", "kitten.jpg");
//Write a PDF to the ADS
CreateFileWithAlternateDataStream(basePath, baseFile, ":PDFSample", "pentest.pdf");
Console.WriteLine("Done");
Console.ReadKey();
}
static void CreateFileWithAlternateDataStream(string basePath, string baseFile, string streamName, string fileToWrite)
{
var sfh = CreateFile(basePath + baseFile + streamName,
EFileAccess.GenericRead | EFileAccess.GenericWrite,
EFileShare.Read,
IntPtr.Zero,
ECreationDisposition.CreateAlways,
EFileAttributes.Normal,
IntPtr.Zero);
if (sfh.IsInvalid)
{
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
}
using (FileStream fs = new FileStream(sfh, FileAccess.Write))
{
byte[] filebytes = File.ReadAllBytes(Path.Combine(basePath, fileToWrite));
fs.Write(filebytes, 0, filebytes.Length);
}
sfh.Close();
}
}
}
[Flags]
enum EFileAccess : uint
{
GenericRead = 0x80000000,
GenericWrite = 0x40000000,
GenericExecute = 0x20000000,
GenericAll = 0x10000000
}
[Flags]
public enum EFileShare : uint
{
None = 0x00000000,
Read = 0x00000001,
Write = 0x00000002,
Delete = 0x00000004
}
public enum ECreationDisposition : uint
{
New = 1,
CreateAlways = 2,
OpenExisting = 3,
OpenAlways = 4,
TruncateExisting = 5
}
[Flags]
public enum EFileAttributes : uint
{
Normal = 0x00000080
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.