is there a way to execute data without saving it to a file and then execute it??

i have researched all the net and i found nothing.
i want something like if is possible to execute data.
like load data into the memory and then execute like is was it a .exe file.

something like:

data : string;

data:='MZP.....................@...............................................!..L.!..This program must be run under Win32..$7........................................................................................................................................PE..L....^B*.................<...h.......I.......P....@.........................../..................@...........................@..:0...............................e..................................................................................CODE....@:.......<.................. ..`DATA.....<...P...<...@..............@...BSS..................|...................idata..:0...@...2...|..............@....tls.....................................rdata..............................@..P.reloc...e.......f..................@..P.rsrc...............................@..P............../.......-.............@..P..................................................................................................................................................................@...Boolean...........@..False.True.@.,.@...WideChar..........'



executeDataIntoMemory(data);

500 points!!
becoolnikeAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

BlackTigerXCommented:
this has been asked many times

it is *not* possible, unless of course the "data" is some form of script that your program would interprete
Pierre CorneliusCommented:
You could save the data to a temporary file and then use ShellExecute to run it.
2266180Commented:
Actually you can :D But it's a dirty and hard work to do.

In the old days this would have been a no problem, but nowadays it's a hell of a big problem. Why? Because of the "buffer overrun". There are a lot if fixes for that in operating systems and now even in processors (I read somehwre that AMD is putting some execute bit flag for the memory into their 64bit processors)

In general use, you have 2 possibilities:
- using writeprocessmemory (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/debug/base/writeprocessmemory.asp) (and you put the data into the process memory of your executing program ... stinky :) )
- using ASM (playing with the IP register ;) )

The hard stuff is that you will have to control everything related to that memory so that the OS can cope with it. That means you need to have a lot of knoledge about how the OS is working with : memory, code, data, etc.

The basic scketch is like this:

- load the data into memory
- have a type : myproc = procedure;
- initialize a variable of that type to the address of the data to be executed
- run the variable
ex:
type myf = procedure;

procedure a;
var b:myf;
begin
  b:=addr(a);
  beep;
  sleep(1000);
  b;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  a;
end;

but you will point b to the begining of the loaded data (which must be a procedure of the declared form, in this case "procedure myprocedure; begin end; or something".

Of course, you will not be able to execute programs like this (exe files, etc) because you must first parse the executable and load it into memory just as the OS does and only after that you can change the IP register to point to the begining of the program to be exeecuted. Dirty stuff.

If you succeed imlementing it, give us a post ;)
Good Luck.
JavaScript Best Practices

Save hours in development time and avoid common mistakes by learning the best practices to use for JavaScript.

becoolnikeAuthor Commented:
i've heard about shellcodes, im not sured whats that.

Pierre CorneliusCommented:
When you say "shellcodes" are you referring to "ShellExecute"?
2266180Commented:
No. he means something that is based on (is using) something from the "low level" tehniques I wrote above
see more here: http://en.wikipedia.org/wiki/Shellcode
Pierre CorneliusCommented:
Here's an example of how to do what I said in my previous post:
=========================================

Pas file
=====

unit main;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, ShellApi;

type
  TForm2 = class(TForm)
    btnRun: TButton;
    btnSetData: TButton;
    Label1: TLabel;
    memData: TMemo;
    dlgOpen: TOpenDialog;
    procedure btnSetDataClick(Sender: TObject);
    procedure btnRunClick(Sender: TObject);
  end;

var
  Form2: TForm2;
  Data: array of byte;

implementation

{$R *.dfm}

procedure TForm2.btnSetDataClick(Sender: TObject);
var f: TFileStream;
    s: string;
    i: integer;
begin
  if dlgOpen.Execute then
  begin
    f:= TFileStream.Create(dlgOpen.FileName, fmOpenRead);
    try
      f.Seek(0, soFromBeginning);
      SetLength(data, f.Size);
      f.Read(Data[0], f.Size);

      SetLength(s, f.size);
      Move(Data[0], s[1], f.Size);
      for i:= 1 to f.Size do
        if s[i] = #0 then s[i]:= ' ';
      memData.Text:= s;
    finally
      f.Free;
    end;
  end;
end;

procedure TForm2.btnRunClick(Sender: TObject);
var f: TFileStream;
    exe: string;
begin
  if Length(Data) = 0
    then raise exception.Create('Data variable not yet loaded');

  exe:= ExtractFilePath(ParamStr(0))+'\Temp.exe';
  if FileExists(exe) then DeleteFile(exe);
  f:= TFileStream.Create(exe, fmCreate);
  try
    f.Position:= 0;
    f.Write(Data[0], Length(Data));
  finally
    f.Free;
  end;
  ShellExecute(0, pchar('open'), pchar(exe), nil, pchar(ExtractFilePath(exe)), SW_SHOW);
end;

end.



dfm file
=====
object Form2: TForm2
  Left = 192
  Top = 114
  Width = 696
  Height = 480
  Caption = 'Form2'
  Color = clBtnFace
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -11
  Font.Name = 'MS Sans Serif'
  Font.Style = []
  OldCreateOrder = False
  DesignSize = (
    688
    446)
  PixelsPerInch = 96
  TextHeight = 13
  object Label1: TLabel
    Left = 8
    Top = 48
    Width = 89
    Height = 13
    Caption = '"Data" variable'
    Font.Charset = DEFAULT_CHARSET
    Font.Color = clWindowText
    Font.Height = -11
    Font.Name = 'MS Sans Serif'
    Font.Style = [fsBold]
    ParentFont = False
  end
  object btnRun: TButton
    Left = 168
    Top = 8
    Width = 153
    Height = 25
    Caption = 'Run app from "data" variable'
    TabOrder = 0
    OnClick = btnRunClick
  end
  object btnSetData: TButton
    Left = 8
    Top = 8
    Width = 153
    Height = 25
    Caption = 'Set "data" variable'
    TabOrder = 1
    OnClick = btnSetDataClick
  end
  object memData: TMemo
    Left = 8
    Top = 64
    Width = 673
    Height = 377
    Anchors = [akLeft, akTop, akRight, akBottom]
    TabOrder = 2
  end
  object dlgOpen: TOpenDialog
    DefaultExt = '*.exe'
    FileName = '*.exe'
    Filter = 'Executable files (*.exe)|*.exe'
    Title = 'Select file to set "Data" variable to'
    Left = 368
    Top = 16
  end
end


Kind regards
Pierre
aikimarkCommented:
1. Maybe...how's your assembler skills? :-)
If you output 'assembled code', you can transfer execution to these executable.
Note: assembled code is the binary load module of ASM statements

2. If you are working with the .Net framework, you can output statements in any
acceptable language and compile it or output IL code and compile it.  Both of these
methods would invoke the JIT compiler, usually launched from a command prompt,
via a ShellExecute method.

3. If you are running on an NTFS partition, you can output the executable module
to a hidden NTFS stream (special folder).

4. If you have access to a RAMdisk (in-memory disk area), you could load the executable
module there.

5. You can use the Microsoft java scripting object to execute VB script code on-the-fly
at interpretation speeds.

6. You can use one of the Delphi scripting/macro engines to execute some Delphi statements
on-the-fly at interpretation speeds.
DeltaAzizCommented:
someone said: with computer nothing is impossible

so, it's possible, look at this example:

http://www.geocities.com/deltaaziz/expert/exec1.zip


All credit goes to Aphex, athor of the original source code.

This is my first post :) and i want the 500 points :)

Regards

DeltaAziz
aikimarkCommented:
DeltaAziz,

Very interesting.  What does the DLL do?  There is very little documentation
in your linked zip file.

Trying to understand this, I did encounter a VB project that uses some of
Aphex's work to delete a running executable.
http://www.pscode.com/vb/scripts/ShowCode.asp?txtCodeId=44907&lngWId=1

I would like to understand the 'magic', since part of your link uses a file and
the question seems to preclude file use.
DeltaAzizCommented:
Hi again!

the DLL execute the program in memery after doing some fix,
and the Pro.exe can be included in test file as Data...

Ok,ehere another example:
http://www.geocities.com/deltaaziz/expert/exec2.zip

it's realy a nice piece of code, to use in a protection for example
and i'm still waiting for my point 500 :)

Regards

DeltaAziz
DeltaAzizCommented:
Well, the one who asked this question put  500 points
but after looking to his profile,  "becoolnike" have 0 points!!!

aikimarkCommented:
DeltaAziz,

The points you saw on the questioner's profile are expert points, those earned from
answering questions asked by others.  These expert points are different from the
points one uses to award to those of us who answer their questions.  The system
at Experts-Exchange.com is supposed to prevent question askers from over-
commiting their points.
DeltaAzizCommented:
aikimark,

thank you for enlighting me,
try the second example

Regards

DeltaAziz
aikimarkCommented:
DeltaAziz,

You're welcome.

I'm too paranoid to try either of your examples without compiling the
deltaaziz.dll from its source or downloading from some trusted location,
such as SourceForge or Programmersheaven or Torry's (etc.).

As a general rule, Experts-Exchange.com likes to work at the source
level rather than at the executable level.
becoolnikeAuthor Commented:
wow it sees its posible not full comment at all just a piece of source.

data array sees to hold the exe data .

i like to know in what kind of traslation data was created it sees not hex or binary code.
DeltaAzizCommented:
Hi

Read your question:
"like load data into the memory and then execute like is was it a .exe file."

it's what do Example1, just load a file and execute it in memory.

in example 2: the EXE file is included as Array, it's just plain copy of each byte from file to the array.

Data: array [1..XXX] of byte

where XXX is size of EXE file.

in your question you wrote:
data : string;
data:='MZP.............';

i'v not used Data as String because the EXE may contain special Character like ' so it cause problems..


in short, you just need a Pointer, Gat/Alloc somemory, load your EXE in that memory, pass your Pointer to the procedure in DeltaAziz.Dll and that's All


an i'm still waiting for my first Points :)
Regards

DeltaAziz
becoolnikeAuthor Commented:
i only thing to finish with this post its to be answered well.

just gime that author of the dll or if the dll is open source.

due your asnwer still not pro.

anyways if u dont know ill give u the points.

thank u.
DeltaAzizCommented:
becoolnike:

my answer wan't pro!
i'll try to be more Pro in Future...

Ok, as i Wrote, the Original Idea/Source was writen by Aphex,
it's a program that download a file from internet using socket & execute it in memory
i removed the internet/socket code and changed it to a Dll

source is available

non-malicious and for legal, non-commercial, educational use only!

type
  TSections = array [0..0] of TImageSectionHeader;


function GetAlignedSize(Size: dword; Alignment: dword): dword;
begin
  if ((Size mod Alignment) = 0) then
    Result := Size;
  else
    Result := ((Size div Alignment) + 1) * Alignment;
end;

function ImageSize(Image: pointer): dword;
var
  Alignment: dword;
  ImageNtHeaders: PImageNtHeaders;
  PSections: ^TSections;
  SectionLoop: dword;
begin
  ImageNtHeaders := pointer(dword(dword(Image)) + dword(PImageDosHeader(Image)._lfanew));
  Alignment := ImageNtHeaders.OptionalHeader.SectionAlignment;
  if ((ImageNtHeaders.OptionalHeader.SizeOfHeaders mod Alignment) = 0) then
  begin
    Result := ImageNtHeaders.OptionalHeader.SizeOfHeaders;
  end
  else
  begin
    Result := ((ImageNtHeaders.OptionalHeader.SizeOfHeaders div Alignment) + 1) * Alignment;
  end;
  PSections := pointer(pchar(@(ImageNtHeaders.OptionalHeader)) + ImageNtHeaders.FileHeader.SizeOfOptionalHeader);
  for SectionLoop := 0 to ImageNtHeaders.FileHeader.NumberOfSections - 1 do
  begin
    if PSections[SectionLoop].Misc.VirtualSize <> 0 then
    begin
      if ((PSections[SectionLoop].Misc.VirtualSize mod Alignment) = 0) then
      begin
        Result := Result + PSections[SectionLoop].Misc.VirtualSize;
      end
      else
      begin
        Result := Result + (((PSections[SectionLoop].Misc.VirtualSize div Alignment) + 1) * Alignment);
      end;
    end;
  end;
end;

procedure CreateProcessEx(FileMemory: pointer);
var
  BaseAddress, Bytes, HeaderSize, InjectSize,  SectionLoop, SectionSize: dword;
  Context: TContext;
  FileData: pointer;
  ImageNtHeaders: PImageNtHeaders;
  InjectMemory: pointer;
  ProcInfo: TProcessInformation;
  PSections: ^TSections;
  StartInfo: TStartupInfo;
begin
  ImageNtHeaders := pointer(dword(dword(FileMemory)) + dword(PImageDosHeader(FileMemory)._lfanew));
  InjectSize := ImageSize(FileMemory);
  GetMem(InjectMemory, InjectSize);
  try
    FileData := InjectMemory;
    HeaderSize := ImageNtHeaders.OptionalHeader.SizeOfHeaders;
    PSections := pointer(pchar(@(ImageNtHeaders.OptionalHeader)) + ImageNtHeaders.FileHeader.SizeOfOptionalHeader);
    for SectionLoop := 0 to ImageNtHeaders.FileHeader.NumberOfSections - 1 do
    begin
      if PSections[SectionLoop].PointerToRawData < HeaderSize then HeaderSize := PSections[SectionLoop].PointerToRawData;
    end;
    CopyMemory(FileData, FileMemory, HeaderSize);
    FileData := pointer(dword(FileData) + GetAlignedSize(ImageNtHeaders.OptionalHeader.SizeOfHeaders, ImageNtHeaders.OptionalHeader.SectionAlignment));
    for SectionLoop := 0 to ImageNtHeaders.FileHeader.NumberOfSections - 1 do
    begin
      if PSections[SectionLoop].SizeOfRawData > 0 then
      begin
        SectionSize := PSections[SectionLoop].SizeOfRawData;
        if SectionSize > PSections[SectionLoop].Misc.VirtualSize then SectionSize := PSections[SectionLoop].Misc.VirtualSize;
        CopyMemory(FileData, pointer(dword(FileMemory) + PSections[SectionLoop].PointerToRawData), SectionSize);
        FileData := pointer(dword(FileData) + GetAlignedSize(PSections[SectionLoop].Misc.VirtualSize, ImageNtHeaders.OptionalHeader.SectionAlignment));
      end
      else
      begin
        if PSections[SectionLoop].Misc.VirtualSize <> 0 then FileData := pointer(dword(FileData) + GetAlignedSize(PSections[SectionLoop].Misc.VirtualSize, ImageNtHeaders.OptionalHeader.SectionAlignment));
      end;
    end;
    ZeroMemory(@StartInfo, SizeOf(StartupInfo));
    ZeroMemory(@Context, SizeOf(TContext));
    CreateProcess(nil, pchar(ParamStr(0)), nil, nil, False, CREATE_SUSPENDED, nil, nil, StartInfo, ProcInfo);
    Context.ContextFlags := CONTEXT_FULL;
    GetThreadContext(ProcInfo.hThread, Context);
    ReadProcessMemory(ProcInfo.hProcess, pointer(Context.Ebx + 8), @BaseAddress, 4, Bytes);
    VirtualAllocEx(ProcInfo.hProcess, pointer(ImageNtHeaders.OptionalHeader.ImageBase), InjectSize, MEM_RESERVE or MEM_COMMIT, PAGE_EXECUTE_READWRITE);
    WriteProcessMemory(ProcInfo.hProcess, pointer(ImageNtHeaders.OptionalHeader.ImageBase), InjectMemory, InjectSize, Bytes);
    WriteProcessMemory(ProcInfo.hProcess, pointer(Context.Ebx + 8), @ImageNtHeaders.OptionalHeader.ImageBase, 4, Bytes);
    Context.Eax := ImageNtHeaders.OptionalHeader.ImageBase + ImageNtHeaders.OptionalHeader.AddressOfEntryPoint;
    SetThreadContext(ProcInfo.hThread, Context);
    ResumeThread(ProcInfo.hThread);
  finally
    FreeMemory(InjectMemory);
  end;
end;


aikimark:
Enjoy :)


Regards,


DeltaAziz

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
becoolnikeAuthor Commented:
thank u .
i remember someone who said in some post that this wasnt posible.
aikimarkCommented:
I've learned something.  Thanks.

I've participated in another discussion or two here at Experts-Exchange that asked similar
questions.  No one knew how to do it, so we assumed it couldn't be done without
creating your own PE loader (which seemed VERY DIFFICULT).
DeltaAzizCommented:
Hi

You are welcome,
i'm happt that it helps
also happy cause it's my first post/point,

This site is Great
dMaCommented:
DeltaAziz are you still here? need to contakt you if possible.
send a mail to oscar@crytek.de thx.
DeltaAzizCommented:
Hi dMa
yeah i'm still alive
i just wrote you an e-mail: DeltaAziz*Gmail*com
jimswebCommented:
@DeltaAziz
If you are still around, can you please post a working sample of the solution that you have posted here?
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Delphi

From novice to tech pro — start learning today.