flat assembler
Message board for the users of flat assembler.

Index > Windows > Windows service example?

Author
Thread Post new topic Reply to topic
bzdashek



Joined: 15 Feb 2012
Posts: 147
Location: Tolstokvashino, Russia
bzdashek
Good day, everyone.

I used search, but my search didn't get me anywhere. Google points to .NET examples of service creation.

So, does anyone have a simple example of windows service? What functions are mandatory for it that should be exported?

Anything would do - C/C++ or ASM.

Here are some examples on .NET, in case someone would need those:
Example 1
Example 2
Post 20 Dec 2012, 10:04
View user's profile Send private message Reply with quote
Lummis



Joined: 25 Nov 2012
Posts: 15
Location: Canada
Lummis
Hi. No one answered yet, but I'll follow with a question instead! lol
What is a Windows Service? I looked a bit, but this stuff doesn't show & tell what the heck they are really talking about... http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicebase
AND are there 'general solutions' to porting to the Windows 'calls'?
THX.
Post 20 Dec 2012, 12:07
View user's profile Send private message Reply with quote
marcinzabrze12



Joined: 07 Aug 2011
Posts: 60
marcinzabrze12
service:

Code:
format pe console 
       entry    main
include 'win32ax.inc'
include 'n\codehelp.inc'
include 'n\SERVICE.INC'

        SERVICE_CONTROL_SHUTDOWN                       = 00000005h
        SERVICE_CONTROL_CREATE_OUT_FILE                = 00000096h

section '.idata' import data readable
library msvcrt, 'msvcrt.dll', kernel32, 'kernel32.dll',\
        user32, 'user32.dll', advapi32, 'advapi32.dll',\
        shell32, 'shell32.dll'
  include 'api\msvcrt.inc'
  include 'api\kernel32.inc'
  include 'api\user32.inc'
  include 'api\advapi32.inc'
  include 'api\shell32.inc'


section '.data' data readable writeable


        serviceName              db     'mainservice', 0
        serviceStatus            SERVICE_STATUS
        serviceStatusHandle      dd     ?
;       -------------------------------------------------------------
        pathBuffer               db     MAX_PATH dup 0
        newthreadID              dd     ?
        newthreadHandle          dd     ?
        outFileName              db     'outfile.asm', 0
        outFileHandle            dd     ?
;       -------------------------------------------------------------



;     ==========================================================================
section '.code' code readable executable
;     ==========================================================================



proc    SvcHandlerEx   dwControl, dwEventType, lpEventData, lpContext
pushfd

        mov     eax, [dwControl]
        cmp     eax, SERVICE_CONTROL_PAUSE
        je      .service_pause
        cmp     eax, SERVICE_CONTROL_CONTINUE
        je      .service_continue
        cmp     eax, SERVICE_CONTROL_STOP
        je      .service_stop
        cmp     eax, SERVICE_CONTROL_SHUTDOWN
        je      .service_stop
        popfd
        ret

      .service_pause:
        mov     dword [serviceStatus.dwCurrentState], SERVICE_PAUSED
        jmp     .finish

      .service_continue:
        mov     dword [serviceStatus.dwCurrentState], SERVICE_RUNNING
        jmp     .finish

      .service_stop:
        mov     dword [serviceStatus.dwCurrentState], SERVICE_STOPPED

      .finish:
        invoke  SetServiceStatus, [serviceStatusHandle], serviceStatus
        mov     eax, NO_ERROR
        popfd
        ret
endp




proc    ServiceMain  argc:DWORD, argv:DWORD
pushfd

        mov     dword [serviceStatus.dwServiceType], SERVICE_WIN32_OWN_PROCESS
        mov     dword [serviceStatus.dwCurrentState], SERVICE_RUNNING
        mov     dword [serviceStatus.dwControlsAccepted], SERVICE_ACCEPT_PAUSE_CONTINUE or SERVICE_ACCEPT_STOP or SERVICE_ACCEPT_SHUTDOWN
        mov     dword [serviceStatus.dwWin32ExitCode], NO_ERROR
        mov     dword [serviceStatus.dwServiceSpecificExitCode], 0
        mov     dword [serviceStatus.dwCheckPoint], 0
        mov     dword [serviceStatus.dwWaitHint], 0
        invoke  RegisterServiceCtrlHandlerExA, serviceName, SvcHandlerEx, NULL
        mov     [serviceStatusHandle], eax
        invoke  SetServiceStatus, eax, serviceStatus
        popfd
        ret
endp

;       ================================================================================================================================
;               MAIN    MAIN    MAIN    MAIN    MAIN    MAIN    MAIN    MAIN    MAIN    MAIN    MAIN    MAIN    MAIN    MAIN    MAIN
;       ================================================================================================================================
proc    main  argc:DWORD, lpszArgv:DWORD
pushfd

        locals
              svc   SERVICE_TABLE_ENTRY
                    dd NULL
                    dd NULL
        endl

        mov     [svc.lpServiceName], serviceName
        mov     [svc.lpServiceProc], ServiceMain
        lea     eax, [svc]
        invoke  StartServiceCtrlDispatcher, eax
        xor     eax, eax
        popfd
        ret
endp
;       ================================================================================================================================
;               MAIN    MAIN    MAIN    MAIN    MAIN    MAIN    MAIN    MAIN    MAIN    MAIN    MAIN    MAIN    MAIN    MAIN    MAIN
;       ================================================================================================================================









section '.reloc' fixups data discardable
                                                  




instalator:

Code:

entry    start
include 'win32ax.inc'
include 'n\codehelp.inc'
include 'n\SERVICE.INC'

section '.idata' import data readable
library kernel32, 'kernel32.dll', user32, 'user32.dll', advapi32, 'advapi32.dll'
include 'api\kernel32.inc'
include 'api\user32.inc'
include 'api\advapi32.inc'



section '.data' data readable writeable

        hinstance               dd      ?
        serviceName             db      'MAINSERVICE', 0
        serviceType             dd      SERVICE_WIN32_OWN_PROCESS
        serviceBinaryPath       db      'C:\Users\neptun\Desktop\SVC\mainservice.exe', 0
        serviceDescription      db      'USLUGA TESTOWA:  <WAWRZYNIAKMARCINCODE@GMAIL.COM>', 0

;       -------------------------------------------------------------------------------
          hnService              dd      ?
          idesc                 SERVICE_DESCRIPTION
;       -------------------------------------------------------------------------------


;     ==========================================================================
section '.code' code readable writeable executable
;     ==========================================================================
start:

;          ---------------------------------------------------------------------------------------
           stdcall      ServiceInstall, serviceName, serviceName, serviceBinaryPath,\
                        SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_IGNORE
           test         eax, eax
           jnz          @f
                        SHOWERROR       'mainservice install error'
                        EXITPROCESS
           @@:          MSG     'SUCCESS - USLUGA ZOSTALA ZAINSTALOWANA I URUCHOMIONA', 'mainservice install'
;          ---------------------------------------------------------------------------------------
           stdcall      ServiceSetDescription, serviceName, serviceDescription
           .if          eax = FALSE
                        SHOWERROR       'ServiceSetDescription() Error:'
                        EXITPROCESS
           .endif
           MSG          'Ustanowiono opis uslugi.'
           EXITPROCESS


                                        
    



uninstall it:


Code:
format pe gui 4.0
entry    start
include 'win32ax.inc'
include 'n\codehelp.inc'
include 'n\PRIVILEGES.INC'
include 'n\SERVICE.INC'

section '.idata' import data readable
library kernel32, 'kernel32.dll', user32, 'user32.dll', advapi32, 'advapi32.dll'
include 'api\kernel32.inc'
include 'api\user32.inc'
include 'api\advapi32.inc'



section '.data' data readable writeable

        hinstance               dd      ?
        serviceName             db      'MAINSERVICE', 0
        serviceType             dd      SERVICE_WIN32_OWN_PROCESS


;     ==========================================================================
section '.code' code readable writeable executable
;     ==========================================================================
start:
           stdcall      ServiceUninstall, serviceName
           .if          eax = 0
                        SHOWERROR       'ServiceUninstall()   ERROR:'
                        EXITPROCESS
           .endif
           MSG          'successik'
           EXITPROCESS

                                                
    


the all uses main procedures like ServiceInstall, ServiceUninstall ... from this file:
https://docs.google.com/open?id=0Bzkm-XARAFtnX044NlpMa2FSdU0
Post 20 Dec 2012, 19:24
View user's profile Send private message Reply with quote
bzdashek



Joined: 15 Feb 2012
Posts: 147
Location: Tolstokvashino, Russia
bzdashek
Thanks, Marcin!

I too wasn't sitting on my arse - here's another example:

Code:
; serv.exe 
format PE GUI 4.0 
entry start

include 'C:\fasmw\INCLUDE\win32a.inc'
;------------------------------------------
;structures
;------------------------------------------
struct SERVICE_STATUS
   dwServiceType           dd ?
        dwCurrentState          dd ?
        dwControlsAccepted              dd ?
        dwWin32ExitCode         dd ?
        dwServiceSpecificExitCode       dd ?
        dwCheckPoint            dd ?
        dwWaitHint              dd ?
ends
;------------------------------------------
;constants
;------------------------------------------
    SERVICE_CONTROL_SHUTDOWN        = 000000005h
        SERVICE_WIN32_OWN_PROCESS       = 000000010h
        SERVICE_RUNNING         = 000000004h
        SERVICE_ACCEPT_SHUTDOWN = 000000004h

    NO_ERROR                        = 000000000h
        ERROR_SERVICE_DOES_NOT_EXIST    = 000001060h


        SC_MANAGER_CONNECT              = 00001h
    SC_MANAGER_CREATE_SERVICE       = 00002h
    SC_MANAGER_ENUMERATE_SERVICE    = 00004h
    SC_MANAGER_LOCK         = 00008h
    SC_MANAGER_QUERY_LOCK_STATUS    = 00010h
    SC_MANAGER_MODIFY_BOOT_CONFIG   = 00020h

        SC_MANAGER_ALL_ACCESS   = STANDARD_RIGHTS_REQUIRED + \
                             SC_MANAGER_CONNECT  + \
                                    SC_MANAGER_CREATE_SERVICE + \
                              SC_MANAGER_ENUMERATE_SERVICE + \
                                   SC_MANAGER_LOCK  + \
                               SC_MANAGER_QUERY_LOCK_STATUS + \
                                   SC_MANAGER_MODIFY_BOOT_CONFIG

   SERVICE_QUERY_CONFIG    = 00001h
    SERVICE_CHANGE_CONFIG   = 00002h
    SERVICE_QUERY_STATUS    = 00004h
    SERVICE_ENUMERATE_DEPENDENTS  = 00008h
      SERVICE_START           = 00010h
    SERVICE_STOP            = 00020h
    SERVICE_PAUSE_CONTINUE  = 00040h
    SERVICE_INTERROGATE             = 00080h
    SERVICE_USER_DEFINED_CONTROL    = 00100h

        SERVICE_ALL_ACCESS        = STANDARD_RIGHTS_REQUIRED      + \
                              SERVICE_QUERY_CONFIG      + \
                              SERVICE_CHANGE_CONFIG      + \
                             SERVICE_QUERY_STATUS      + \
                              SERVICE_ENUMERATE_DEPENDENTS  + \
                          SERVICE_START        + \
                           SERVICE_STOP        + \
                            SERVICE_PAUSE_CONTINUE      + \
                            SERVICE_INTERROGATE      + \
                               SERVICE_USER_DEFINED_CONTROL


        SERVICE_START  = 00010h
     SERVICE_AUTO_START  = 000000002h

        WAIT_FOR = 60*60*1000   ; - @07 2 G0A

;--------------------------------------------
;data section
;--------------------------------------------
section '.data' readable writeable

  ws              WSADATA
     addr            sockaddr_in
 sSi             STARTUPINFO
 sPi             PROCESS_INFORMATION

     hSocket         dd ?
        hWorkSocket     dd ?

    ServiceName     db 'PolYan',0
     DisplayName     db 'System Service Configuration',0
       status          SERVICE_STATUS
      hService                dd ?
        ServiceTableEntry       dd ServiceName, ServiceMain, 0, 0
   hSC1            dd ?
        hSC2            dd ?

    hSession                dd ?
;============================================

;--------------------------------------------
;code section
;--------------------------------------------
section '.text' readable executable
start:
 invoke  OpenSCManager, 0, 0, SC_MANAGER_ALL_ACCESS
  mov     [hSC1], eax
 or      eax, eax
    jnz     @F
  jmp     endOpenSCManager
@@:
 invoke  OpenService, [hSC1], ServiceName, SERVICE_START
     mov     [hSC2], eax
 or      eax, eax
    jz      @F
  invoke  CloseServiceHandle, eax
     jmp     endOpenSCManager
@@:

     invoke  GetCommandLine
      invoke  CreateService, [hSC1], ServiceName, DisplayName,\
                          SERVICE_ALL_ACCESS,\
                               SERVICE_WIN32_OWN_PROCESS,\
                                SERVICE_AUTO_START, 0,\
                            eax, NULL, NULL,\
                          NULL, NULL, NULL
    mov     [hSC2], eax
 or      eax, eax
    jnz     @F
  jmp     endOpenSCManager
@@:
 invoke  StartService, [hSC2], 0, NULL
       invoke  CloseServiceHandle, [hSC2]

endOpenSCManager:
     invoke  CloseServiceHandle, [hSC1]

      invoke  StartServiceCtrlDispatcher, ServiceTableEntry
       or      eax, eax
    jnz     exitProcess
 stdcall ServiceMain, dword 0, dword NULL

exitProcess:
    invoke  ExitProcess, 0
;-----------------------------------------------------------------
;-----------------------------------------------------------------
;-----------------------------------------------------------------

proc ServiceMain, dwNU1, dwNU2
      ;Register service
   invoke  RegisterServiceCtrlHandler, ServiceName, Handler
    mov     [hService], eax
     ;Set service status
 invoke  RtlZeroMemory, status, sizeof.SERVICE_STATUS
        mov     [status.dwServiceType], SERVICE_WIN32_OWN_PROCESS
   mov     [status.dwCurrentState], SERVICE_RUNNING
    mov     [status.dwControlsAccepted], SERVICE_ACCEPT_SHUTDOWN
        mov     [status.dwWin32ExitCode], NO_ERROR

      invoke  SetServiceStatus, [hService], status
;-----------------------Begin---Here you can insert you code-
__next:
        invoke  Sleep,  WAIT_FOR 
   jmp     __next
;-----------------------End----------------------------------

endp
;------------------------------------------------------------
;------------------------------------------------------------
;------------------------------------------------------------
;Handle message for service
proc Handler, dwAction
     cmp     [dwAction], SERVICE_CONTROL_SHUTDOWN
        jnz     @F
  invoke  ExitProcess, 0
@@:
   ret
endp
;============================================

section '.idata' import data readable writeable
library  winsock, 'WS2_32.DLL',\
  kernel,  'KERNEL32.DLL',\
  advapi,  'ADVAPI32.DLL'


import kernel,\
  ExitProcess,  'ExitProcess',\
  CloseHandle,  'CloseHandle',\
  RtlZeroMemory,  'RtlZeroMemory',\
  GlobalAlloc,  'GlobalAlloc',\
  SetStdHandle,  'SetStdHandle',\
  CreateProcess,  'CreateProcessA',\
  GetEnvironmentVariable, 'GetEnvironmentVariableA',\
  GetLastError,  'GetLastError',\
  GetCommandLine,  'GetCommandLineA',\
  GetStartupInfo,  'GetStartupInfoA',\
  Sleep,  'Sleep'



import advapi,\
  RegisterServiceCtrlHandler, 'RegisterServiceCtrlHandlerA',\
  SetServiceStatus,  'SetServiceStatus',\
  OpenSCManager,  'OpenSCManagerA',\
  OpenService,  'OpenServiceA',\
  CloseServiceHandle,  'CloseServiceHandle',\
  CreateService,  'CreateServiceA',\
  StartService,  'StartServiceA',\
  StartServiceCtrlDispatcher, 'StartServiceCtrlDispatcherA'
    
Post 20 Dec 2012, 19:57
View user's profile Send private message Reply with quote
typedef



Joined: 25 Jul 2010
Posts: 2913
Location: 0x77760000
typedef
Here. I quickly wrote this for you. Took me about an hour or so.

All it does is prints string using OutputDebugString


Description:
Download
Filename: typedef_win32_service.zip
Filesize: 3.84 KB
Downloaded: 126 Time(s)

Post 20 Dec 2012, 22:04
View user's profile Send private message Reply with quote
bzdashek



Joined: 15 Feb 2012
Posts: 147
Location: Tolstokvashino, Russia
bzdashek
typedef wrote:
Here. I quickly wrote this for you. Took me about an hour or so.

All it does is prints string using OutputDebugString

Thanks a lot, typedef. Yay, it's full of commentaries!

Thanks, everyone, I'll proceed with creating my service.
Post 21 Dec 2012, 05:07
View user's profile Send private message Reply with quote
Lummis



Joined: 25 Nov 2012
Posts: 15
Location: Canada
Lummis
I also found stuff in fasm's source and include files, ... + reading the win32 help...
Thx guys.
Post 23 Dec 2012, 14:09
View user's profile Send private message Reply with quote
bzdashek



Joined: 15 Feb 2012
Posts: 147
Location: Tolstokvashino, Russia
bzdashek
Lummis wrote:
I also found stuff in fasm's source and include files, ... + reading the win32 help...
Thx guys.

You might want to take a look at this thread, if you haven't already done so:
http://board.flatassembler.net/topic.php?t=13931

It contains extended includes by madmatt, containing all thinkable and unthinkable structures you might ever need.
Post 23 Dec 2012, 15:02
View user's profile Send private message Reply with quote
upsurt



Joined: 14 Jan 2014
Posts: 51
upsurt
that's very helpful! thank you alot!

how can I add a timer (1 second) to the windows service, to performe an action every second?
Post 16 Apr 2014, 14:22
View user's profile Send private message Reply with quote
edfed



Joined: 20 Feb 2006
Posts: 4237
Location: 2018
edfed
Google->MSDN->SetTimer ????
Post 16 Apr 2014, 22:02
View user's profile Send private message Visit poster's website Reply with quote
typedef



Joined: 25 Jul 2010
Posts: 2913
Location: 0x77760000
typedef
Don't use timers. If you have to use timers use threaded ones otherwise just use a thread.
Post 17 Apr 2014, 23:22
View user's profile Send private message Reply with quote
revolution
When all else fails, read the source


Joined: 24 Aug 2004
Posts: 17259
Location: In your JS exploiting you and your system
revolution
typedef wrote:
Don't use timers. If you have to use timers use threaded ones otherwise just use a thread.
Why?
Post 17 Apr 2014, 23:25
View user's profile Send private message Visit poster's website Reply with quote
edfed



Joined: 20 Feb 2006
Posts: 4237
Location: 2018
edfed
timers in windows seems to still be threads.... means the SetTimer function (if you go in msdn to be sure) will run independentlly from the setter application.

to be really sure, and without reading the msdn, you can also try it, the simple way to do it is to loop continuouslly you main program on an intense computation, and do the same with the timer.

if the main runs correctlly without delay, and the timer too, then, they run separatelly.... something like that.
Post 18 Apr 2014, 08:09
View user's profile Send private message Visit poster's website Reply with quote
Display posts from previous:
Post new topic Reply to topic

Jump to:  


< Last Thread | Next Thread >
Forum Rules:
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
You cannot attach files in this forum
You can download files in this forum


Copyright © 1999-2020, Tomasz Grysztar.

Powered by rwasa.