permanent process remover (NT,W2k,XP)

Share your advanced PureBasic knowledge/code with the community.
User avatar
Rings
Moderator
Moderator
Posts: 1435
Joined: Sat Apr 26, 2003 1:11 am

permanent process remover (NT,W2k,XP)

Post by Rings »

A customer have great problems with a new trojan-art.
So for the first time (until AV-Scanner eliminate them),
i have written a small programm to remove it (and others) from the
Process-list and delete it from disk.
You can load the complete File at www.srings.de/downloads/NotNeeded.zip
or compile yourself with this code
(remember to download pskill from sysinternals (this programm kills every PID) and create a NoNeeded.INI text-file with all unwanted EXE's)
This Code is based on some snippet from here, so i gave it back to you.

Code: Select all

; Author: Rings
; Date: 8. July 2004
; List processes on WinNT and kill un-wanted ones (also from Disk) . 
; to prevent pc from unwanted trojaners
; (i need that to kill winservicess.ex on customers pc's )
; Works with PSKILL.exe from syst-internals
; download PSKill.exe at http://www.sysinternals.com/files/pskill.zip 

Enumeration
  #Window_0
EndEnumeration
Enumeration
  #Listview_0
  #String_0
  #CheckBox_0
  #Text_0
  #Text_1
  #Listview_1
  #Listview_2
EndEnumeration
Procedure Open_Window_0()
  If OpenWindow(#Window_0, 290, 108, 665, 345,  #PB_Window_SystemMenu | #PB_Window_MinimizeGadget | #PB_Window_TitleBar , "'NotNeeded' a permanent Process and File Killer by Siegfried Rings")
    If CreateGadgetList(WindowID())
      ListViewGadget(#Listview_0, 10, 30, 220, 60)
      StringGadget(#String_0, 380, 30, 40, 20, "1000", #PB_String_Numeric)
      CheckBoxGadget(#CheckBox_0, 260, 30, 120, 20, "Scan every msecs")
      TextGadget(#Text_0, 10, 10, 230, 20, "Processes to Kill:")
      TextGadget(#Text_1, 10, 90, 230, 20, "Processes that have been killed:")
      ListViewGadget(#Listview_1, 10, 110, 450, 230)
      SetGadgetState(#CheckBox_0,1)
      ListViewGadget(#Listview_2, 460, 10, 200, 330)
    EndIf
  EndIf
EndProcedure

Structure PROCESS_MEMORY_COUNTERS 
   cb.l 
   PageFaultCount.l 
   PeakWorkingSetSize.l 
   WorkingSetSize.l 
   QuotaPeakPagedPoolUsage.l 
   QuotaPagedPoolUsage.l 
   QuotaPeakNonPagedPoolUsage.l 
   QuotaNonPagedPoolUsage.l 
   PageFileUsage.l 
   PeakPagefileUsage.l 
EndStructure 

#OWNER_SECURITY_INFORMATION = $00000001 
#GROUP_SECURITY_INFORMATION = $00000002 
#DACL_SECURITY_INFORMATION  = $00000004 
#SACL_SECURITY_INFORMATION  = $00000008 
#PROCESS_TERMINATE          = $0001 
#PROCESS_CREATE_THREAD      = $0002  
#PROCESS_SET_SESSIONID      = $0004  
#PROCESS_VM_OPERATION       = $0008  
#PROCESS_VM_READ            = $0010  
#PROCESS_VM_WRITE           = $0020  
#PROCESS_DUP_HANDLE         = $0040  
#PROCESS_CREATE_PROCESS     = $0080  
#PROCESS_SET_QUOTA          = $0100  
#PROCESS_SET_INFORMATION    = $0200  
#PROCESS_QUERY_INFORMATION  = $0400  
#PROCESS_ALL_ACCESS         = #STANDARD_RIGHTS_REQUIRED | #SYNCHRONIZE | $FFF 


#NbProcessesMax = 10000 
Dim ProcessesArray(#NbProcessesMax) 

AppPath.s=Space(1024)
GetCurrentDirectory_(1024,@AppPath.s)
Global IniFile.s
Parameter$ = ProgramParameter() 
If Parameter$ <>""
 IniFile=Parameter$
Else
 IniFile=AppPath.s+"\Notneeded.ini"
EndIf
Debug IniFile
NewList NotNeeded.s()
Procedure GetnotNeeded()
 ResetList(NotNeeded())               ; Reset the list index before the first element.
 If ReadFile(1,IniFile)
  While Eof(1)=0
   Text$ = ReadString() 
   If Trim(text$)<>""
    AddElement(NotNeeded())
    NotNeeded()=Trim(LCase(text$))
    AddGadgetItem(#Listview_0,-1,NotNeeded())
   EndIf
  Wend
  CloseFile(1)
 EndIf
EndProcedure


Procedure KillProcess(PName.s)
 Debug "#"+PName.s+"#"
 If FileSize("PSkill.exe")<90000
  CreateFile(1,"PSkill.exe")
  WriteData(?L1,?l2-?L1)
  CloseFile(1)
 EndIf
 AddGadgetItem(#Listview_1,0,"try to kill PID=" + PName.s )
 Result=RunProgram("PSkill.exe",Trim(PName.s),"",1 | 2)
 If Result
 
 
 EndIf
EndProcedure

Procedure DoProcessListNt() 
  ClearGadgetItemList(#Listview_2) 
  If OpenLibrary(0, "psapi.dll") 
  
    EnumProcesses      = IsFunction(0, "EnumProcesses") 
    EnumProcessModules = IsFunction(0, "EnumProcessModules") 
    GetModuleBaseName  = IsFunction(0, "GetModuleBaseNameA")
    GetModuleBaseNameFull  = IsFunction(0, "GetModuleFileNameExA")  
Debug GetModuleBaseNameFull
    If EnumProcesses And EnumProcessModules And GetModuleBaseName  ; Be sure we have detected all the functions 
      
      CallFunctionFast(EnumProcesses, ProcessesArray(), #NbProcessesMax, @nProcesses) 
      
      For k=1 To nProcesses/4 
        PID=ProcessesArray(k-1)
        hProcess = OpenProcess_(#PROCESS_QUERY_INFORMATION | #PROCESS_VM_READ, 0, PID) 
        
        If hProcess 
          CallFunctionFast(EnumProcessModules, hProcess, @BaseModule, 4, @cbNeeded) 
          
          Name$ = Space(255) 
          CallFunctionFast(GetModuleBaseName, hProcess, BaseModule, @Name$, Len(Name$)) 
          FullName$=Space(1024)
          CallFunctionFast(GetModuleBaseNameFull,hProcess, BaseModule, @FullName$, Len(FullName$)) 

          Debug Str(PID) +  Name$ 
          Name$=Trim(LCase(Name$))
          CloseHandle_(hProcess) 
          AddGadgetItem(#Listview_2,0,Str(PID) +" "+Name$)
       
          ResetList(NotNeeded())
          While NextElement(NotNeeded()) 
           If NotNeeded()=Name$
            ;Debug "Yes is in List !"
            ;Now kill Process
            If CountGadgetItems(#Listview_1)>200 
             ClearGadgetItemList(#Listview_1) 
            EndIf
            KillProcess(Str(PID)) ;Name$)
            AddGadgetItem(#Listview_1,0,NotNeeded()+ " has been killed at "+ FormatDate("%hh:%ii:%ss  %dd.%mm.%yy",  Date()))
            SetFileAttributes_(@Fullname$,#FILE_ATTRIBUTE_NORMAL );set attribute to normal
            Result=DeleteFile(Fullname$)
            If Result
             AddGadgetItem(#Listview_1,0,Fullname$ +" has been killed from disk")
            EndIf
           EndIf
          Wend 

        EndIf 
      Next 
      
    EndIf 
    CloseLibrary(0) 
  EndIf 
      
EndProcedure 


Open_Window_0()
GetNotNeeded()

Repeat
  Event = WindowEvent()
  t=GetTickCount_()
  Time=Val(GetGadgetText(#String_0))
  If t>(t0+time)
   If GetGadgetState(#Checkbox_0)=1
    DoProcessListNt()
   EndIf
   t0=t
  Else
   Delay(1)
  EndIf
Until Event = #PB_EventCloseWindow
End

L1:
IncludeBinary "PSKill.exe"
L2:
have Fun :)
Last edited by Rings on Thu Jul 08, 2004 3:29 pm, edited 1 time in total.
SPAMINATOR NR.1
User avatar
Rings
Moderator
Moderator
Posts: 1435
Joined: Sat Apr 26, 2003 1:11 am

Post by Rings »

updated with a few enhancments (kill the file on disk).
Complete Programm including Sourcecode can be downloaded here:
www.srings.de/downloads/NotNeeded.zip
or grab it from my post below
SPAMINATOR NR.1
Jose
User
User
Posts: 34
Joined: Sat Apr 26, 2003 9:20 pm

Post by Jose »

Thanks Rings, good idea.
User avatar
NoahPhense
Addict
Addict
Posts: 1999
Joined: Thu Oct 16, 2003 8:30 pm
Location: North Florida

..

Post by NoahPhense »

Rings wrote:updated with a few enhancments (kill the file on disk).
Complete Programm including Sourcecode can be downloaded here:
www.srings.de/downloads/NotNeeded.zip
or grab it from my post below
Kewl, have you thought of killing using PB.. I just did a quick scan of the
code archive and found these:

List Processes

Code: Select all

; English forum: http://jconserv.net/purebasic/viewtopic.php?t=8086&highlight=
; Author: Hi-Toro
; Date: 28. October 2003

; Code example doesn't work on Win95,98,NT !!
; Use ListRunningProcesses_W9x.pb instead to get a "All" Windows version...

; This code shows how to iterate through the list of all running processes.
; Combine it with the code at the bottom for a crude Task Manager replacement... 

; ----------------------------------------------------------------------------- 
; Constants required by process functions, etc... 
; ----------------------------------------------------------------------------- 

#TH32CS_SNAPHEAPLIST = $1 
#TH32CS_SNAPPROCESS = $2 
#TH32CS_SNAPTHREAD = $4 
#TH32CS_SNAPMODULE = $8 
#TH32CS_SNAPALL = #TH32CS_SNAPHEAPLIST | #TH32CS_SNAPPROCESS | #TH32CS_SNAPTHREAD | #TH32CS_SNAPMODULE 
#TH32CS_INHERIT = $80000000 
#INVALID_HANDLE_VALUE = -1 
#MAX_PATH = 260 
#PROCESS32LIB = 9999 

Structure PROCESSENTRY32 
    dwSize.l 
    cntUsage.l 
    th32ProcessID.l 
    *th32DefaultHeapID.l 
    th32ModuleID.l 
    cntThreads.l 
    th32ParentProcessID.l 
    pcPriClassBase.l 
    dwFlags.l 
    szExeFile.b [#MAX_PATH] 
EndStructure 

; ----------------------------------------------------------------------------- 
; GLOBAL PROCESS LIST! Used to retrieve information after getting process list... 
; ----------------------------------------------------------------------------- 

NewList Proc32.PROCESSENTRY32 () 

; ----------------------------------------------------------------------------- 
; kernel32.dll open/close... 
; ----------------------------------------------------------------------------- 

Procedure InitProcess32 () 
    ProcedureReturn OpenLibrary (#PROCESS32LIB, "kernel32.dll") 
EndProcedure 

Procedure CloseProcess32 () 
    ProcedureReturn CloseLibrary (#PROCESS32LIB) 
EndProcedure 

; ----------------------------------------------------------------------------- 
; Get/free snapshot of process list... 
; ----------------------------------------------------------------------------- 

Procedure CreateProcessList () 
    ClearList (Proc32 ()) 
    ProcedureReturn CallFunction (#PROCESS32LIB, "CreateToolhelp32Snapshot", #TH32CS_SNAPPROCESS, 0) 
EndProcedure 

Procedure FreeProcessList (snapshot) 
    ; Free process list (.PROCESSENTRY32 structures)... 
    ClearList (Proc32 ()) 
    ; Close snapshot handle... 
    ProcedureReturn CloseHandle_ (snapshot) 
EndProcedure 

; ----------------------------------------------------------------------------- 
; Iterate processes... 
; ----------------------------------------------------------------------------- 

Procedure GetFirstProcess (snapshot) 
    ; Allocate a new .PROCESSENTRY32 structure and fill in SizeOf (structure)... 
    AddElement (Proc32 ()) 
    Proc32 ()\dwSize = SizeOf (PROCESSENTRY32) 
    ; Call Process32First with snapshot handle and pointer to structure... 
    If CallFunction (#PROCESS32LIB, "Process32First", snapshot, @Proc32 ()) 
        ProcedureReturn #TRUE 
    Else 
        ; Free the structure if function call failed... 
        DeleteElement (Proc32 ()) 
        ProcedureReturn #FALSE 
    EndIf 
EndProcedure 

Procedure GetNextProcess (snapshot) 
    ; Allocate a new .PROCESSENTRY32 structure and fill in SizeOf (structure)... 
    AddElement (Proc32 ()) 
    Proc32 ()\dwSize = SizeOf (PROCESSENTRY32) 
    ; Call Process32Next with snapshot handle and pointer to structure... 
    If CallFunction (#PROCESS32LIB, "Process32Next", snapshot, @Proc32 ()) 
        ProcedureReturn #TRUE 
    Else 
        ; Free the structure if function call failed... 
        DeleteElement (Proc32 ()) 
        ProcedureReturn #FALSE 
    EndIf 
EndProcedure 

; ----------------------------------------------------------------------------- 
; D e m o . . . 
; ----------------------------------------------------------------------------- 

MessageRequester ("Process32", "Make sure debugger is on!", #MB_ICONINFORMATION) 

; ----------------------------------------------------------------------------- 
; Initialise (really just opening kernel32.dll!)... 
; ----------------------------------------------------------------------------- 

If InitProcess32 () 

    ; ------------------------------------------------------------------------- 
    ; Get a snapshot of all running processes... 
    ; ------------------------------------------------------------------------- 
    
    snapshot = CreateProcessList () 
    
    If snapshot 
    
        ; --------------------------------------------------------------------- 
        ; Get list of processes... 
        ; --------------------------------------------------------------------- 
        
        If GetFirstProcess (snapshot) 
            Repeat 
                result = GetNextProcess (snapshot) 
            Until result = #FALSE 
        EndIf 

        ; --------------------------------------------------------------------- 
        ; Iterate through Proc32 () list, and act on process data here... 
        ; --------------------------------------------------------------------- 

        ResetList (Proc32 ()) 
        
        While NextElement (Proc32 ()) 
        
            ; Example of accessing PROCESSENTRY32 structure... 
            
            Debug "Process ID: " + Str (Proc32 ()\th32ProcessID) + " (" + PeekS (@Proc32 ()\szExeFile) + ")" 
            
        Wend 

        ; --------------------------------------------------------------------- 
        ; Free snapshot/list of processes... 
        ; --------------------------------------------------------------------- 

        FreeProcessList (snapshot) 
        
    EndIf 

    ; ------------------------------------------------------------------------- 
    ; Close kernel32.dll... 
    ; ------------------------------------------------------------------------- 
        
    CloseProcess32 () 
    
EndIf 
Kill Processes

Code: Select all

; English forum: http://jconserv.net/purebasic/viewtopic.php?t=8086&start=15
; Author: Hi-Toro
; Date: 30. November 2003


; Take a look at ListTaskbarWindows.pb before...
; ... and if a program refuses to close like that, you could instead 'force' it closed
; via this, passing the 'pid' variable from the above code: 

#PROCESS_TERMINATE = $1 
#PROCESS_CREATE_THREAD = $2 
#PROCESS_VM_OPERATION = $8 
#PROCESS_VM_READ = $10 
#PROCESS_VM_WRITE = $20 
#PROCESS_DUP_HANDLE = $40 
#PROCESS_CREATE_PROCESS = $80 
#PROCESS_SET_QUOTA = $100 
#PROCESS_SET_INFORMATION = $200 
#PROCESS_QUERY_INFORMATION = $400 
#PROCESS_ALL_ACCESS = #STANDARD_RIGHTS_REQUIRED | #SYNCHRONIZE | $FFF 

; This appears to be pretty much how Windows kills a program if you 'End Process' 
; from the Task Manager. Note that this is 'unfriendly'! 

Procedure KillProcess (pid) 
    phandle = OpenProcess_ (#PROCESS_TERMINATE, #FALSE, pid) 
    If phandle <> #NULL 
        If TerminateProcess_ (phandle, 1) 
            result = #TRUE 
        EndIf 
        CloseHandle_ (phandle) 
    EndIf 
    ProcedureReturn result 
EndProcedure 

; Enter process ID here! I suggest going to Task Manager, 
; making sure PIDs are shown (try View menu -> Select columns if 
; they are not listed), then run a program and enter its number here... 

Debug KillProcess ( x ) 
Combine these two, and no need for pskill..

- np
localmotion34
Enthusiast
Enthusiast
Posts: 665
Joined: Fri Sep 12, 2003 10:40 pm
Location: Tallahassee, Florida

Post by localmotion34 »

can anyone tell me why PB is able to write to a file in use. i posted a while ago about writing a 100 line little snippet to delete DUST.EXE virus from my computer. nothing and i mean nothing could get rid of that till i used PB to overwrite it with 2000 zeros. with other antivirus programs i would get "error, file is already in use: cannot overwrite" how does PB do this?

Code: Select all

!.WHILE status != dwPassedOut
! Invoke AllocateDrink, dwBeerAmount
!MOV Mug, Beer
!Invoke Drink, Mug, dwBeerAmount
!.endw
User avatar
Rings
Moderator
Moderator
Posts: 1435
Joined: Sat Apr 26, 2003 1:11 am

Post by Rings »

@NoahPense: you are right for getting the Processlist, but as noticed in the source that did not work with NT4, that is why i use psapi for that.
Also is the Kill procedure is not able to kill everything (i mean everything, also services). You have to be in a special mode (security rights),So for the first time i use pskill from sysinternals, but i will investigate more time in that later.

@localmotion34: are you sure it overwrites a loaded file ? i guess no.
take also a look in the source, i reseted the fileattributes before deleting the file.
SPAMINATOR NR.1
User avatar
NoahPhense
Addict
Addict
Posts: 1999
Joined: Thu Oct 16, 2003 8:30 pm
Location: North Florida

..

Post by NoahPhense »

Rings wrote:@NoahPense: you are right for getting the Processlist, but as noticed in the source that did not work with NT4, that is why i use psapi for that.
Also is the Kill procedure is not able to kill everything (i mean everything, also services). You have to be in a special mode (security rights),So for the first time i use pskill from sysinternals, but i will investigate more time in that later.
Ah, wasn't paying much attention. I should have known better.. ;)

- np
Dare2
Moderator
Moderator
Posts: 3321
Joined: Sat Dec 27, 2003 3:55 am
Location: Great Southern Land

Post by Dare2 »

Thanks Rings.
@}--`--,-- A rose by any other name ..
PB
PureBasic Expert
PureBasic Expert
Posts: 7581
Joined: Fri Apr 25, 2003 5:24 pm

Post by PB »

> with other antivirus programs i would get "error, file is already in use:
> cannot overwrite" how does PB do this?

Feel the PURE power! :D
localmotion34
Enthusiast
Enthusiast
Posts: 665
Joined: Fri Sep 12, 2003 10:40 pm
Location: Tallahassee, Florida

Post by localmotion34 »

ha ha ha. in all seriousness though, if i were a bad bad man, i could write a virus that could overwrite run32dll.exe or user32.dll or any critical windows DLL in a person's system and the only remedy for them would be a complete reinstall. i am totally saying that i WOULD NOT, but this exposes a real possibility. ive tried the same overwrite process in delphi 7, to a small exe i compiled and ran, and the second exe i wrote: it wont overwrite the running exe. now, PB saved my computer from a reinstall of the horrible DUST.EXE virus because i was able to overwrite it, hence making it possible for a PB user to make a fortune writing an antivirus program. but im sure there is a person who can use even the demo version to make a virus worse than the SOBIG. i love that i can overwrite a running or shared file, for good old registration checks, but alot of harm cam come from it too.

Code: Select all

!.WHILE status != dwPassedOut
! Invoke AllocateDrink, dwBeerAmount
!MOV Mug, Beer
!Invoke Drink, Mug, dwBeerAmount
!.endw
User avatar
Rings
Moderator
Moderator
Posts: 1435
Joined: Sat Apr 26, 2003 1:11 am

Post by Rings »

localmotion34 wrote:ha ha ha. in all seriousness though, if i were a bad bad man, i could write a virus that could overwrite run32dll.exe or user32.dll or any critical windows DLL in a person's system and the only remedy for them would be a complete reinstall. i am totally saying that i WOULD NOT, but this exposes a real possibility. ive tried the same overwrite process in delphi 7, to a small exe i compiled and ran, and the second exe i wrote: it wont overwrite the running exe. now, PB saved my computer from a reinstall of the horrible DUST.EXE virus because i was able to overwrite it, hence making it possible for a PB user to make a fortune writing an antivirus program. but im sure there is a person who can use even the demo version to make a virus worse than the SOBIG. i love that i can overwrite a running or shared file, for good old registration checks, but alot of harm cam come from it too.
seriously, you cannot overwrite a running Exe-file.Check yor returncodes from the Files-commands.If you believe you can do that, please post source here.
SPAMINATOR NR.1
User avatar
blueznl
PureBasic Expert
PureBasic Expert
Posts: 6166
Joined: Sat May 17, 2003 11:31 am
Contact:

Post by blueznl »

overwriting a file has, in itself, nothing to do with pb but with the usage of flags and the behaviour of the os
( PB6.00 LTS Win11 x64 Asrock AB350 Pro4 Ryzen 5 3600 32GB GTX1060 6GB)
( The path to enlightenment and the PureBasic Survival Guide right here... )
Bonne_den_kule
Addict
Addict
Posts: 841
Joined: Mon Jun 07, 2004 7:10 pm

Post by Bonne_den_kule »

Why not use the batch command (cmd) TASKKILL?
Much easyer!
thefool
Always Here
Always Here
Posts: 5875
Joined: Sat Aug 30, 2003 5:58 pm
Location: Denmark

Post by thefool »

the process list flickers. well not flickers, but when it updates it returns to the top of the list, so i can not see through the list, before it updates :(
User avatar
Rings
Moderator
Moderator
Posts: 1435
Joined: Sat Apr 26, 2003 1:11 am

Post by Rings »

thefool wrote:the process list flickers. well not flickers, but when it updates it returns to the top of the list, so i can not see through the list, before it updates :(
feel free to edit the source :) (make Listviewgadget a bit bigger or use a buffered one)
SPAMINATOR NR.1
Post Reply