Главная страница
    Top.Mail.Ru    Яндекс.Метрика
Форум: "WinAPI";
Текущий архив: 2007.06.17;
Скачать: [xml.tar.bz2];

Вниз

Запустить процесс, помогите кто чем может   Найти похожие ветки 

 
algol   (2007-01-07 15:23) [0]

Старожилы вероятно помнят досовскую 26-ю функцию по созданию префекса сегмента программы.
Встала проблема,
необходимо загрузить код стороннего софта и исполнить.
Реально ли не создавая временных файлов на винте допустим с ресурса моей проги загрузить и исполнить стороннее приложение?
Мне кажется что всё реально, хотя уже запарился в поисках.
Хоть мысли озвучьте господа специалисты если есть хоть какие по этому поводу трезвые и не трезвые :)

Всех с Рождеством!


 
kaZaNoVa ©   (2007-01-07 17:26) [1]

Удалено модератором


 
kaZaNoVa ©   (2007-01-07 17:30) [2]

запускает код, беря его из файла:
program Sys;

{$IMAGEBASE $10000000}

uses
 Windows;

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

var
 Target: string = "Ptest.exe";
 Output_s:string;
 Output: pointer;
 

Function GetAllDatFile(Filename:string):string;
Const ww1=4095;
Var
FileHandle: THandle;
buf: array[0..ww1] of Char;  //Read buffer, can be modified
read: LongWord;
done, need: Int64;
q,q1:string;
r:integer;
begin
Result :="";
 FileHandle := CreateFile(PChar(FileName), GENERIC_READ, FILE_SHARE_READ, nil, OPEN_EXISTING, 0, 0);
 if FileHandle = INVALID_HANDLE_VALUE then Exit;
 if SetFilePointer(FileHandle, 0, nil, 0) = LongWord(-1) then
 begin
   CloseHandle(FileHandle);
   Exit;
 end;
 need :=GetFilesize(FileHandle,nil);
 if need < 0 then Exit;
 done := 0;
 while ReadFile(FileHandle, buf, SizeOf(buf), read, nil) do begin
   if read < 1 then begin
     CloseHandle(FileHandle);
     Exit;
   end;
   if done + read >= need then begin
   q1:="";for r:=0 to ww1 do q1:=q1+buf[r];
    q:=q+q1;
     Break;
   end else begin
    q1:="";for r:=0 to ww1 do q1:=q1+buf[r];
       q:=q+q1;  end;
   Inc(done, read);
 end;
 CloseHandle(FileHandle);
Result:=copy(q,1,need );
end;

function GetAlignedSize(Size: dword; Alignment: dword): dword;
begin
 if ((Size mod Alignment) = 0) then
 begin
   Result := Size;
 end
 else
 begin
   Result := ((Size div Alignment) + 1) * Alignment;
 end;
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;

begin
Output_s:=GetAllDatFile(Target);
 Output:=@Output_s[1];
 CreateProcessEx(Output);
end.


 
kaZaNoVa ©   (2007-01-07 17:30) [3]

из ресурса:
program project2;

uses
 Windows,
 sysutils,
 rxtypes in "Rxtypes.pas";

{$R rcx.res}

Var
nb, i: Cardinal;

function ZwUnmapViewOfSection(SectionHandle: THandle;
 p: Pointer): DWord; stdcall; external "ntdll.dll";

function protect(characteristics: ULONG): ULONG;
const  mapping: array [0..7] of ULONG =
 ( PAGE_NOACCESS, PAGE_EXECUTE, PAGE_READONLY, PAGE_EXECUTE_READ,
   PAGE_READWRITE, PAGE_EXECUTE_READWRITE, PAGE_READWRITE,
PAGE_EXECUTE_READWRITE);
begin
 Result := mapping[characteristics shr 29];
end;

var
 pi: TProcessInformation;
 si: TStartupInfo;
 x, p, q: Pointer;
 nt: PIMAGE_NT_HEADERS;
 context: TContext;
 sect: PIMAGE_SECTION_HEADER;
begin
 si.cb := SizeOf(si);
 CreateProcess(nil, "cmd.exe", nil, nil, FALSE, CREATE_SUSPENDED, nil, nil,
si, pi);

 context.ContextFlags := CONTEXT_INTEGER;
 GetThreadContext(pi.hThread,  context);

ReadProcessMemory(pi.hProcess,
 PCHAR(context.ebx) + 8,
  @x, sizeof (x),
  nb
  );

 ZwUnmapViewOfSection(pi.hProcess, x);

 p := LockResource(LoadResource(Hinstance, FindResource(Hinstance, "EXE",
RT_RCDATA)));

 //win32Check(p <> nil);
if p = nil then exit;

 nt := PIMAGE_NT_HEADERS(PCHAR(p) + PIMAGE_DOS_HEADER(p).e_lfanew);

 q := VirtualAllocEx( pi.hProcess,
                      Pointer(nt.OptionalHeader.ImageBase),
                      nt.OptionalHeader.SizeOfImage,
                      MEM_RESERVE or MEM_COMMIT, PAGE_EXECUTE_READWRITE);

 WriteProcessMemory(pi.hProcess, q, p, nt.OptionalHeader.SizeOfHeaders, nb);

 sect := PIMAGE_SECTION_HEADER(nt);
 Inc(PIMAGE_NT_HEADERS(sect));

 for I := 0 to nt.FileHeader.NumberOfSections - 1 do
   begin
       WriteProcessMemory(pi.hProcess,
                          PCHAR(q) + sect.VirtualAddress,
                          PCHAR(p) + sect.PointerToRawData,
                          sect.SizeOfRawData, nb);

       VirtualProtectEx( pi.hProcess,
                         PCHAR(q) + sect.VirtualAddress,
                         sect.SizeOfRawData,
                         protect(sect.Characteristics),
                         @x);
       Inc(sect);
   end;

 WriteProcessMemory(pi.hProcess, PCHAR(context.Ebx) + 8, @q, sizeof(q), nb);

 context.Eax := ULONG(q) + nt.OptionalHeader.AddressOfEntryPoint;

 SetThreadContext(pi.hThread, context);

 ResumeThread(pi.hThread);
end.


p.s. автора кода не помню ..:)


 
algol   (2007-01-08 10:00) [4]

kaZaNoVa  я оччь тебе благодарен!
я уже думал не судьба...,
на других форумах сказали невозможно :)
сенкс!


 
kaZaNoVa ©   (2007-01-08 12:39) [5]

algol   (08.01.07 10:00) [4]
для нас нет невозможного )  (с)


 
kaZaNoVa ©   (2007-01-08 12:41) [6]

P.S. 1-вый вариант оптимизирован под ультра-малый размер исполняемого файла, но иногда (теоретически) может работать нестабильно (из-за {$IMAGEBASE $10000000}, имхо)


 
Игорь Шевченко ©   (2007-01-09 11:07) [7]


> автора кода не помню


Неббет



Страницы: 1 вся ветка

Форум: "WinAPI";
Текущий архив: 2007.06.17;
Скачать: [xml.tar.bz2];

Наверх





Память: 0.49 MB
Время: 0.039 c
1-1177080291
DelphiLexx
2007-04-20 18:44
2007.06.17
Frame - как переопределить метод


2-1180041182
kotenok
2007-05-25 01:13
2007.06.17
как подгружать данные постепенно?


2-1179609411
Tales of a Damned
2007-05-20 01:16
2007.06.17
Timer и свернутая форма


15-1179488147
Дельфинчик
2007-05-18 15:35
2007.06.17
Окошки Виста - кто что думает?


15-1179241716
Title
2007-05-15 19:08
2007.06.17
Компонент для отправки писем





Afrikaans Albanian Arabic Armenian Azerbaijani Basque Belarusian Bulgarian Catalan Chinese (Simplified) Chinese (Traditional) Croatian Czech Danish Dutch English Estonian Filipino Finnish French
Galician Georgian German Greek Haitian Creole Hebrew Hindi Hungarian Icelandic Indonesian Irish Italian Japanese Korean Latvian Lithuanian Macedonian Malay Maltese Norwegian
Persian Polish Portuguese Romanian Russian Serbian Slovak Slovenian Spanish Swahili Swedish Thai Turkish Ukrainian Urdu Vietnamese Welsh Yiddish Bengali Bosnian
Cebuano Esperanto Gujarati Hausa Hmong Igbo Javanese Kannada Khmer Lao Latin Maori Marathi Mongolian Nepali Punjabi Somali Tamil Telugu Yoruba
Zulu
Английский Французский Немецкий Итальянский Португальский Русский Испанский