Alternate Data Streams Example

posted 16 Jul 2010, 18:08 by Delphi Basics
Alternate Data Streams Example

This example shows you how to use a file's metadata to store an executable file inside another.

http://en.wikipedia.org/wiki/Fork_(filesystem)

{ Alternate Data Streams Example
  by steve10120
  http://hackhound.org }

function LeftStr(const AText: AnsiString; const ACount: Integer): AnsiString; overload;
begin
  Result := Copy(WideString(AText), 1, ACount);
end;

function RightStr(const AText: AnsiString; const ACount: Integer): AnsiString; overload;
begin
  Result := Copy(WideString(AText), Length(WideString(AText)) + 1 - ACount, ACount);
end;

function WriteADS(FileToWriteTo:string; FileToWrite:string):boolean;
var
hFile:        THandle;
dRead, dSize: DWORD;
dWritten:     DWORD;
Buffer:       AnsiString;
begin
  hFile := CreateFile(PChar(FileToWrite), GENERIC_READ, FILE_SHARE_READ, nil, OPEN_EXISTING, 0, 0);
  if hFile <> INVALID_HANDLE_VALUE then
    dSize := GetFileSize(hFile, nil);
    if dSize <> 0 then
    begin
      SetLength(Buffer, dSize);
      ReadFile(hFile, Buffer[1], dSize, dRead, nil);
      CloseHandle(hFile);
      hFile := CreateFile(PChar(LeftStr(FileToWriteTo, Length(FileToWriteTo) - 4) + ':' + RightStr(FileToWrite, Length(FileToWrite) - 3)), GENERIC_WRITE, FILE_SHARE_WRITE, nil, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
      WriteFile(hFile, Buffer[1], Length(Buffer), dWritten, nil);
      CloseHandle(hFile);
      ShellExecute(0, 'open', PChar(LeftStr(FileToWriteTo, Length(FileToWriteTo) - 4) + ':' + RightStr(FileToWrite, Length(FileToWrite) - 3)), nil, nil, 1);
    end;
end;

Usage:
WriteADS('C:\test.exe', 'C:\hjsplit.exe');
Comments