Solved

Convert/transform/metamorphosize an executable into a Windows service.

Posted on 2013-12-31
32
815 Views
Last Modified: 2014-01-23
I'm looking for an application that can convert/transform/metamorphosize an executable into a Windows service.  I'm not interested in a primary helper service that launches a secondary executable (ie such as Srvany.exe or nssm.exe).  What I'm hoping for is that someone, somewhere, somehow has created a handy application that alters an existing exe by adding some wrapper code thereby transmutating the existing exe into a service control aware application.  Does any such utility exist?
0
Comment
Question by:U-R-S
  • 13
  • 7
  • 4
  • +2
32 Comments
 
LVL 25

Expert Comment

by:SStory
ID: 39752214
I would really doubt it. Services don't interact with the U/I and most .exe files do. They also need to start and restart themselves.

I assume you don't have the code and it isn't dotnet? If it is then the best best would be to rework it into a service that takes into account removing U/I and sending that to Event log, etc.
0
 

Author Comment

by:U-R-S
ID: 39752471
The whole point of this question is to avoid having to rework the code into a service.

The existing executable that I have in mind does not have any UI and already runs successfully as a service under Srvany.exe.   Whether it uses dotnet or not is immaterial.  The starting and restarting feature is indicative of a service control aware application which is precisely the code that needs to be wrapped around the existing executable.
0
 
LVL 25

Expert Comment

by:SStory
ID: 39752671
I understood your point.

Do the options in the sc command help in actions to take on crashing?
0
 

Author Comment

by:U-R-S
ID: 39752869
A point of clarification, assume the executable that is to undergo transfiguration already meets the criteria for operating in a service environment (i.e.  no user interface, inputs via file/registry/command line/etc, outputs via log file/event log/email alerts/etc).

In a nut shell, take an existing exe that operates perfectly well under srvany.exe (no need to consider sc command options, no issues of crashing) and merge the functionality of srvany.exe into the existing exe to forge a new stand-alone service executable.
0
 
LVL 25

Expert Comment

by:SStory
ID: 39752964
Oh! You want to actually modify the existing .exe.  One note: if it is signed this would invalidate the signature if even possible. Hmm.  I honestly don't know but since this is a lot like something malware would do I'd say your antimalware and antivirus will probably complain. Sorry I can't help, but at least you've clearly spelled out the problem. Maybe another will be able to help you if possible. I would think not.
0
 
LVL 45

Expert Comment

by:aikimark
ID: 39753014
what language did you use to develop your executable application?
0
 

Author Comment

by:U-R-S
ID: 39753042
Yes, I want to actually modify the existing exe.  I was hoping that point was made painfully obvious up front by the use of multiple descriptive words in the title and body of the post all meaning to modify or to alter.    :)

Yes, of course if the exe was signed it would invalidate the signature.  Not a concern, it is not.  It is a simple power basic compiled executable that I wrote long ago that I would like to convert to a single stand-alone exe service.

Yes, if any antimalware or antivirus software complains of the change, I would give it permission to make the change or simply disable it during the modification process.  It's my app, my code, and I desire for it to be changed.
0
 

Author Comment

by:U-R-S
ID: 39753059
The original language should be inconsequential.  The only requirement would be that the existing exe is a true Windows Portable Executable (PE) formatted file.

How I imagine this utility working:
1) Append the service handling wrapper code to the end of the executable.
2) Insert as the very first instruction a jump statement that transfers control to the appended code.
3) Alter the PE header for the new code size such that the dynamic linker properly maps the entire file into memory.
0
 
LVL 45

Expert Comment

by:aikimark
ID: 39753111
Generally, such wrappers are the first instructions executed and eventually pass control to the wrapped executable (think UPX http://upx.sourceforge.net/)

If you have the Windows server 2003 resource kit, look for the srvany.exe program.  Depending on your application and target OS, you might be able to get what you need with that utility.
Note: you will also need to use Regedit to tweak the registry to create a
HKLM\SYSTEM\CurrentControlSet\Services\MyService\Parameters key with a string value of "Application" with your application-service path as data.

You might be able to do this with your existing software.  Try running SC.exe from your command prompt.
0
 
LVL 45

Expert Comment

by:aikimark
ID: 39753117
The original language is not inconsequential.
0
 

Author Comment

by:U-R-S
ID: 39753150
Yes, aikimark, I agree, upx is an excellent example of how I would imagine this utility working.  It wraps an exe with its packing code into a stand-alone single executable.  Does upx pack the exe differently based on the original language?  Perhaps I am too naive, but I would suspect not since the goal of all compilers would be to create a standard executable that Windows can load.  The Windows PE format is the common denominator.  A standard Windows executable should be able to be wrapped in a standard way (just as a file infecting virus is able to wrap its code around a Windows exe in a single standard way).

BTW, I'm fully aware of srvany.exe as my original question and follow up comments mention.  I have tried srvany.exe and it works perfectly fine.  My desire is to be minimalistic, plain and simple.  

If no such utility exists currently, so be it.  It just seems like there exists a desire out there from others as well as myself and I was hoping someone already had put forth the effort to build it.
0
 
LVL 25

Expert Comment

by:SStory
ID: 39753736
I suppose that would be cool if it existed. I could also see it appending to the end and jumping there. However if you have the code a vb.net version as a service may be simpler than finding such a beast. (just my 2 cents worth)
Is it that you just have to have it in one single file? If not a vb.net app that just handled the service parts and called your .exe could be easily developed as well.
Other than this I don't know of such a piece of software, but hope you find what you need.
0
 
LVL 45

Expert Comment

by:aikimark
ID: 39753962
.Net and Java are good examples of executable programs that are not typically distributed as PE files, so "yes", it can make a difference.

What is the detailed nature of the problem you are trying to solve? You are already aware of tools that will do what you described in your question and you understand the general approach to wrapping executable files.  At this point, I'm not sure I fully understand the problem(s) you are trying to address.
0
 

Author Comment

by:U-R-S
ID: 39754241
From my understanding, every Windows .exe file is by definition of the Windows Portable Executable (PE) format.  Do you have a good example of an executable file that is not?  Yes, one can "execute" files such as scripts but they are not themselves true executables.  They are instead associated with executable handlers (i.e. launch a .vbs script file it is processed by the handlers WScript.exe or CScript.exe).

Yes, I fully realize there are several ways to solve the issue of creating a windows service.  I could use a service stub launcher (i.e Srvany.exe, nssm.exe, Exe2Service,exe, ServiceEx.exe, SrvStart.exe) or recode the application in a variety of different languages so that it is service control aware.  These are not the solutions I'm interested in.  

This is a very simple lightweight app that already exists as a single exe, calls only native API's, and has absolutely no dependencies.  I would prefer not to recode it, complicate it, bloat it, tie it to Dot Net or other run time dependencies, nor require reg hacks to make it work.

The detailed nature of the problem that I'm trying to solve is simply this, convert an existing stand-alone exe into a new stand-alone service control aware exe.  I don't know how to describe it any simpler than that.  The sum total of my effort to accomplish this I was hoping would be  1) Download utility.  2) Run utility to convert my exe.  3) Install my new service exe.

After giving up on searching the Internet, I came to Experts Exchange in the hopes that someone in a dark corner had built such an animal.  Unfortunately it appears not.  Pending further comments, I think the solution to my question is, there exists no solution to date.
0
 
LVL 25

Expert Comment

by:SStory
ID: 39754558
He's right DotNet and java have byte code that is translated by a JIT compiler upon execution and put into machine code.
0
Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

 
LVL 74

Expert Comment

by:käµfm³d 👽
ID: 39754570
@aikimark

.Net and Java are good examples of executable programs that are not typically distributed as PE files, so "yes", it can make a difference.
Actually, .NET assemblies are PE files  ; )

http://msdn.microsoft.com/en-us/library/8dkk3ek4(v=vs.110).aspx
0
 
LVL 25

Accepted Solution

by:
SStory earned 333 total points
ID: 39754859
"Metadata is stored in one section of a .NET Framework portable executable (PE) file, while Microsoft intermediate language (MSIL) is stored in another section of the PE file. The metadata portion of the file contains a series of table and heap data structures. The MSIL portion contains MSIL and metadata tokens that reference the metadata portion of the PE file."  (From the link above)
While this is true, the actual dotnet code is MSIL.  I'm not sure what hacking that sort of file would do.  However, that is not the point either.

Here's something on injecting your code
http://www.codeproject.com/Articles/12532/Inject-your-code-to-a-Portable-Executable-file

What code you'd need for the service I don't know.
0
 
LVL 86

Assisted Solution

by:jkr
jkr earned 167 total points
ID: 39766076
While what you want to achieve is technically possible, you are gonna hit some walls while making it work. Walls in terms of tools not made for that. When you strip down the functionality of o Windows' service to it's bones (see e.g. http://www.codeproject.com/Articles/1697/Beginner-s-introductory-guide-to-writing-installin - "" ), you will end up with the following essetial points:

- you'll need a SERVICE_TABLE_ENTRY data structure (http://msdn.microsoft.com/en-us/library/windows/desktop/ms686001(v=vs.85).aspx)
- that structure will have to at least reference the service's 'ServiceMain()' function (http://msdn.microsoft.com/en-us/library/windows/desktop/ms685138(v=vs.85).aspx) that you will have to add

Now, while this 'ServiceMain()' can be quite generic (i.e. does not necessarily require any tailored functionality, that is, unless you need that), the problem is dynamically creating that SERVICE_TABLE_ENTRY on the fly and adding/linking that to the existing executably. This is no biggy if you have written source code that you can edit, but there are no automated tools for that. With e.g. Visual Studio Express (http://go.microsoft.com/fwlink/p/?LinkId=240162) you could easily add a

SERVICE_TABLE_ENTRY g_SvcTbl[]=
{
	{_T("MyService"),(LPSERVICE_MAIN_FUNCTION)ServiceMain},
	{NULL,NULL}
};

Open in new window


plus the 'ServiceMain()' code itself, you'd have to at least be able to add a call to 'StartServiceCtrlDispatcher(g_SvcTbl);' to the executable's entry point. Again, that's something easy to do if you have the source code. But I guess this already illustrates well why it's hard to do that in an automated way. Even if you were willing to write/create tools that utilize the components the Windows SDK has to build/create/modify PE executables, you will always end up to see that last step being virtually impossible to perform by normal means. Means that do not include creating a disassembly of the module in question, injecting the entry and the call and recompiling it again.

So, to sum that up: An comparatively 'easy' task if you have the code, very hard up to impossible if you don't.
0
 

Author Comment

by:U-R-S
ID: 39771213
Given recent responses, I see the difficulty in creation such a utility as initially proposed.  I'm wondering if a compromise might be in order.  

What if this imaginary utility wrapped a service stub around the existing exe without altering the existing exe in anyway.  In essence it would be like packaging Srvany.exe as an appendage to the existing exe that when launched would unwrap the existing exe and spawn it as a child process.

The net result would be 2 process running in memory, the Srvany stub and the original exe, but the intent of my initial inquiry would be met, one neatly packaged stand-alone executable.
0
 
LVL 74

Expert Comment

by:käµfm³d 👽
ID: 39771231
Is the executable by chance a .NET assembly?
0
 

Author Comment

by:U-R-S
ID: 39771287
No, as mentioned earlier its a Power Basic compiled exe.
0
 

Author Comment

by:U-R-S
ID: 39771335
Also as mentioned earlier, the hope is that this utility would operate on any existing Windows exe much in the same way as UPX does (http://upx.sourceforge.net/).  I realize that UPX does not currently pack .NET assemblies, but others utilities exist that do (http://madebits.com/netz/), so it certainly is possible.
0
 
LVL 86

Expert Comment

by:jkr
ID: 39771382
>>without altering the existing exe in anyway.

That's not possible if you want a 'standalone' service'

>>In essence it would be like packaging Srvany.exe as an appendage to the existing exe that
>>when launched would unwrap the existing exe and spawn it as a child process.

Then you could just use a self-extracting executable that comes with srvany.exe also in the package - would be way simpler.
0
 

Author Comment

by:U-R-S
ID: 39772038
@jkr

The proposed stand-alone executable would encapsulate the entire OriginalExe unaltered and would be packed as following:

StandAloneService.exe
    [ServiceStubCode]
    [OriginalExe]

A self-extracting executable that comes with srvany.exe would not solve this issue for 2 reasons:
1)  The self-extracting executable would not be service control aware.
2)  The service stub code packed inside StandAloneService.exe is not the actual Srvany.exe but it operates in a similar manner as Srvany.exe.

The flow chart of ServiceStubCode during service start would be as such:
1)  Respond to the service control manager request to start the service.
2)  Unpack OriginalExe.
3)  Launch OriginalExe as a child process.
0
 
LVL 86

Expert Comment

by:jkr
ID: 39772891
I don't get the problem. Of course you have to install the service or any controlled executable under svrany's regime, but that can be done being the extractor itself. For what it is worth, if you are still considering to get a native service, I start to miss the 'hire me' button :-D
No, seriously, I have a feeling that you are barking up the wrong tree.
0
 

Author Comment

by:U-R-S
ID: 39773361
@jkr

I'm purposely barking up this particular tree, the other trees in the forest have already been climbed.  As stated in earlier comments, I have already gotten my executable to run 100% perfectly fine using Srvany.exe and I certainly realize it could be recoded to be service control aware.  Also as stated in earlier comments, the whole point of this exercise is to determine if a utility currently exists that solves the issue in this particular way - "convert an existing stand-alone exe into a new stand-alone service control aware exe".

So far the sense is that such a utility does not exist.  We are beyond that point now and instead we're just considering the feasibility of such a utility and what would it take to achieve it.  I'm proposing this idea and ask is it feasible to build such a utility that would encapsulate the entire OriginalExe unaltered and pack it as such:

StandAloneService.exe
    [ServiceStubCode]
    [OriginalExe]

The flow chart of ServiceStubCode during service start would be as such:
1)  Respond to the service control manager request to start the service.
2)  Unpack OriginalExe.
3)  Launch OriginalExe as a child process.
0
 
LVL 25

Assisted Solution

by:SStory
SStory earned 333 total points
ID: 39773639
I don't know of a utility, but I can envision this. If you can write a vb.net application with simple service events, you could package the .exe inside of the final assembly and when it is first ran, write that exe to %temp% folder if it doesn't exist. Then use those service calls to manage it. This might work.

Here's how at Microsoft (msdn):
Create a project by using the Windows Service application template. This template creates a class for you that inherits from ServiceBase and writes much of the basic service code, such as the code to start the service.
Write the code for the OnStart and OnStop procedures, and override any other methods that you want to redefine.
Add the necessary installers for your service application. By default, a class that contains two or more installers is added to your application when you click the Add Installer link: one to install the process, and one for each associated service that your project contains.
Build your project.
Create a setup project to install your service, and then install it.
Access the Windows Services Control Manager and start your service.
http://msdn.microsoft.com/en-us/library/zt39148a(v=vs.110).aspx

And here is how to embed an existing exe into a vb.net app:
Example, if .exe is embedded in vb.net app:
Public Class Form1
    Private Sub Button1_Click(
        ByVal sender As System.Object,
        ByVal e As System.EventArgs) Handles Button1.Click
        Dim FileName As String = IO.Path.Combine(Application.StartupPath, "ColorCop.exe")
        Dim BytesToWrite() As Byte = My.Resources.ColorCop
        Dim FileStream As New System.IO.FileStream(FileName, System.IO.FileMode.OpenOrCreate)
        Dim BinaryWriter As New System.IO.BinaryWriter(FileStream)
        BinaryWriter.Write(BytesToWrite)
        BinaryWriter.Close()
        FileStream.Close()
        Process.Start(FileName)
    End Sub

Open in new window

(Code source: http://www.vbforums.com/showthread.php?692677-How-To-Embed-An-EXISTING-EXE-into-a-New-VB-Project)
0
 

Author Comment

by:U-R-S
ID: 39788912
The answer to my original question, “Does any such utility exist (that can convert/transform/metamorphosize an executable into a Windows service)?” seems to be  “No such utility exist presently.”    As such I will close this question.

For those looking for an alternative solution, the best available approaches are:
1)      Recode the existing executable yourself to be service control aware.
2)      Use a service stub launching program such as:  Srvany.exe, nssm.exe, Exe2Service,exe, ServiceEx.exe, SrvStart.exe
3)      Build the actual exe service wrapping utility yourself  (comments by SStory with links on how to inject code into an EXE and how to embed an existing exe into a vb.net app being the most helpful thus far).
0
 
LVL 86

Expert Comment

by:jkr
ID: 39798891
>>The solution to the question is there is no solution presently.

Well, I wrote "you can't do that". And as with the EE guidelines, that is a solution as well...
0
 

Author Comment

by:U-R-S
ID: 39799473
The solution to the question is there is no solution presently.  My final comment summarizes the current state of the issue at hand and offers alternatives and points to other experts comments which were awarded points accordingly.
0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

I previously wrote an article addressing the use of UBCD4WIN and SARDU. All are great, but I have always been an advocate of SARDU. Recently it was suggested that I go back and take a look at Easy2Boot in comparison.
Whether you've completed a degree in computer sciences or you're a self-taught programmer, writing your first lines of code in the real world is always a challenge. Here are some of the most common pitfalls for new programmers.
The goal of this video is to provide viewers with basic examples to understand and use conditional statements in the C programming language.
In this fifth video of the Xpdf series, we discuss and demonstrate the PDFdetach utility, which is able to list and, more importantly, extract attachments that are embedded in PDF files. It does this via a command line interface, making it suitable …

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now