Home

 

Welcome to CSharpTest.Net

I hope that digging through these pages will provide you with some useful information and possibly some useful tools to help you further your development endeavours. General announcements are below and you can find a complete list of postings under the Blog link above. Please feel free to contact me by posting here or sending an email to my first name, Roger, at this domain.
 
 
Thanks for stopping by,
 
 
– Roger
 

 

In this post we are going to explore some great new features introduced in the latest release of the protobuf-csharp-port project. We are going to build both an IIS service to handle requests as well as a sample client. Let’s get started.

Prerequisites
Let’s start by fetching a copy of the protobuf-csharp-port binaries. We can manually download these and unpack them, use NuGet installed in VS2010, or download the NuGet Bootstrapper. I’m going to use the later approach and download NuGet.exe and run the following command:

C:\Projects\ProtoService>NuGet.exe install google.protocolbuffers -x
Successfully installed 'Google.ProtocolBuffers 2.4.1.473'.

Service Definition
With our only dependencies out of the way we are going to need to define some messages and a service. We will start with a new project in visual studio, for ease of demonstration I’ve created an ASP.NET project. To create our service definition we are going to create an empty text file and save it with a “.proto” extension. Be sure to use the File->Save As… menu on this text file, click the down arrow next to the Save button and select “Save with Encoding…”. Near the bottom choose “US-ASCII – Codepage 20127″. This is required by the protoc compiler as it does not support text BOM (Byte order mark). Now that we have a text file let’s create a message for the request and response and the service using the protobuffer definition language:

package ProtoService;

message SearchRequest {
  required string query = 1;
  optional int32 page_number = 2;
  optional int32 result_per_page = 3;
}
message SearchResponse {
  repeated group Result = 1 {
    required string url = 2;
    optional string title = 3;
    repeated string snippets = 4;
  }
}
message ErrorResult {
  required string error_text = 536870911; //max field-id
}
service SearchService {
  rpc Search (SearchRequest) returns (SearchResponse);
}

Code Generation
Now with this saved to “ProtoService.proto” we can run the ProtoGen.exe command-line tool we downloaded with NuGet earlier. ProtoGen will automatically detect that it has been given a “.proto” text file and run the protoc.exe compiler from the same directory as ProtoGen.exe. If you’re including files and setting options defined by google or the csharp port you will need to have the google directory from {Package}\content\protos copied to the location of your proto files. Since this is a stand-alone proto and not including others we don’t need to create a directory structure. Ready to build, let’s run ProtoGen now to create our generated code:

C:\Projects\ProtoService>Google.ProtocolBuffers\tools\ProtoGen.exe -service_generator_type=IRPCDISPATCH ProtoService.proto

The service_generator_type tells the ProtoGen what type of service classes/interfaces we are interested in, the value IRPCDISPATCH generates both interfaces and client/server stubs. There are lots of other options both for protoc and protogen, running ProtoGen.exe /? will list all of them. In addition this can be done directly from VStudio 2005~2010 via the CmdTool.exe integration described here for ProtoGen.exe.

Project References
Now we should find that ProtoService.cs has been created for us. Let’s now add this generated source file to our project and reference the two assemblies we need. Both of our required dependencies are located in Google.ProtocolBuffers\lib\net35, called Google.ProtocolBuffers.dll and Google.ProtocolBuffers.Serialization.dll. After we have added the two references and the generated source file we should able to compile the project. Note: if you get some warnings about CLSCompliant you can either attribute your project as CLSCompliant(true) or add the option “-cls_compliance=false” to the protogen.exe command line above.

Service Implementation
The first code we will write will be our service implementation. The code generator has defined an interface for us to implement called ISearchService. Let’s stub out that implementation now in a class called ServiceImplementation:

class ServiceImplmentation : ISearchService
{
    public SearchResponse Search(SearchRequest searchRequest)
    {
        // Create the response builder
        return SearchResponse.CreateBuilder()
            // Add a result to the response
            .AddResult(
                SearchResponse.Types.Result.CreateBuilder()
                .SetUrl("http://example.com")
                .Build()
                )
            // Build the result message
            .Build();
    }
}

Of course you’re service implementation will be a lot more complicated than this, but this will suffice for demonstration purposes. Go ahead and build your project and then let’s move on to creating the IIS handler.

IIS Handler
Our IHttpHandler implementation could be reduced to a single line call to HttpCallMethod if we chose. The following implementation adds handling of GET requests by parsing of uri query string values and some rudimentary exception handling.

Uri encoded requests are allowed for simple messages (non-nested simple types) and allow us to test right from a browser. This also allows javascript to use a GET request and pass parameters. The MIME type constant ‘ContentFormUrlEncoded’ is defined as “application/x-www-form-urlencoded” which is also the mime type used by HTML forms. This means that web clients can also simply post an HTML form to the service to execute a method, the constraint of simple types remains for forms as well.

class ServiceHandler : IHttpHandler
{
    public bool IsReusable { get { return true; } }
    public void ProcessRequest(HttpContext context)
    {
        MessageFormatOptions defaultOptions = new MessageFormatOptions();
        // Capture the request stream and content-type
        Stream requestStream = context.Request.InputStream;
        string requestType = context.Request.ContentType;

        if (context.Request.HttpMethod == "GET")
        {
            // If the call is an HTTP/GET, we will use URI encoding and the query string
            requestType = MessageFormatOptions.ContentFormUrlEncoded;
            requestStream = new MemoryStream(Encoding.UTF8.GetBytes(context.Request.Url.Query));
        }

        // Parse the HTTP accept header to determine the content-type of the response
        context.Response.ContentType = (context.Request.AcceptTypes ?? new string[0])
                                       .Select(m => m.Split(';')[0])
                                       .FirstOrDefault(m => defaultOptions.MimeInputTypes.ContainsKey(m))
                                       ?? defaultOptions.DefaultContentType;

        // Create the server-side stub to dispatch the call by method name
        using (IRpcServerStub stub = new SearchService.ServerStub(new ServiceImplmentation()))
        {
            try
            {
                // The URI's last path segment will be used for the method name
                string[] path = context.Request.Url.Segments;
                // Use the extension method defined in Google.ProtocolBuffers.Extensions to process
                // the request and write the response back to the client.
                stub.HttpCallMethod(
                        path[path.Length - 1],
                        defaultOptions,
                        requestType,
                        requestStream,
                        context.Response.ContentType,
                        context.Response.OutputStream
                    );
            }
            catch(Exception error)
            {
                // If something fails we will create an ErrorResult and serialze it with the requested
                // content-type obtained earlier while returning an HTTP 500 error.
                context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                ErrorResult.CreateBuilder()
                    .SetErrorText(error.Message)
                    .Build()
                    .WriteTo(defaultOptions, context.Response.ContentType, context.Response.OutputStream);
            }
        }
    }
}

IIS Handler Configuration
The IIS 7x handler configuration is very straight-forward. We are binding the path to be a ‘child’ of our service description proto file “ProtoService.proto”. This, combined with the mimeMap below, allows the user to discover our service definition so that they can interact with it. So it’s time to get working, build the project and update the web.config with the following:

  <system.webServer>
    <staticContent>
      <mimeMap fileExtension=".proto" mimeType="text/plain"/>
    </staticContent>
    <handlers>
      <add name="SearchService" preCondition="integratedMode" verb="GET,POST" path="/ProtoService.proto/*"
           type="ProtoService.ServiceHandler, ProtoService, Version=1.0, Culture=neutral" />
    </handlers>
  </system.webServer>

Getting Results
Make sure you are running in IIS, this will not work in Cassini. Open up your browser (NOT IE) and enter the URL: http://localhost/protoservice.proto/Search?query=asdf You should see the following XML response:

<root>
  <result>
    <url>http://example.com</url>
  </result>
</root>

If you type something that doesn’t make sense, or generates an error, (ie. http://localhost/protoservice.proto/BadMethodName) you will see an error message like this:

<root>
<error_text>Method 'ProtoService.ISearchService.BadMethodName' not found.</error_text>
</root>

Client Proxy
Now that we have a working service, building a simple client proxy for C# binary protobuffers is really easy. First we need an implementation of the client proxy dispatch interface, IRpcDispatch. I’m going to use the WebClient here simply because it’s easy; however, production systems more often use the HttpWebRequest class.

class HttpProxy : IRpcDispatch
{
    readonly Uri _baseUri;
    public HttpProxy(Uri baseUri) { _baseUri = baseUri; }

    public TMessage CallMethod<TMessage, TBuilder>(string method, IMessageLite request, IBuilderLite<TMessage, TBuilder> response)
        where TMessage : IMessageLite<TMessage, TBuilder>
        where TBuilder : IBuilderLite<TMessage, TBuilder>
    {
        WebClient client = new WebClient();
        client.Headers[HttpRequestHeader.ContentType] = MessageFormatOptions.ContentTypeProtoBuffer;
        client.Headers[HttpRequestHeader.Accept] = MessageFormatOptions.ContentTypeProtoBuffer;
        byte[] result = client.UploadData(new Uri(_baseUri, method), request.ToByteArray());
        return response.MergeFrom(result).Build();
    }
}

Once we have this defined we can now instantiate and call the proxy.

SearchRequest result;
SearchResponse result;
using(SearchService svc = new SearchService(new HttpProxy(new Uri("http://localhost/protoservice.proto/"))))
    result = svc.Search(SearchRequest.CreateBuilder().SetQuery("bar").Build());

foreach (SearchResponse.Types.Result r in result.ResultList)
    Console.WriteLine(r.Url);

Alternative Client Formats
This proxy uses protobuffers but it could easily be adapted to use json or xml just by changing the content-type and and accept headers and serializing accordingly. To Serialize a protobuffer message as xml or json the following extensions can be used:

//XML
string xmlResult = client.UploadString(new Uri(_baseUri, method), request.ToXml());
return response.MergeFromXml(
    System.Xml.XmlReader.Create(new StringReader(xmlResult)))
    .Build();

//JSON
string jsonResult = client.UploadString(new Uri(_baseUri, method), request.ToJson());
return response.MergeFromJson(jsonResult).Build();

Lastly there are two more extension methods that can do this by simply providing a stream and a mime-type. This is demonstrated above in the catch block of our http handler. Here are the extension method prototypes that can be used:

public static void WriteTo(this IMessageLite message, MessageFormatOptions options, string contentType,
                           Stream output);

public static TBuilder MergeFrom<TBuilder>(this TBuilder builder, MessageFormatOptions options,
                                           string contentType, Stream input) where TBuilder : IBuilderLite;

Closing Remarks
I’m very biased here since I wrote most of this capability; however, I am constantly amazed at how easy protobuffers are to use. Google’s Protocol Buffers are very powerful and extremely fast. I’ve been using them for two years now and I can’t imagine writing a serialization or remoting solution without them.

 

Keeping in line with our previous post “How to prevent users from killing your service or process” and continuing down the road of securing our service this post looks at the prevention of debugging. There are a lot of anti-debugging posts out there, most of them written in C++ and assembly and are therefor of little use to the managed world. One of the most complete I’ve seen is from Symantec “Windows Anti-Debug Reference | Symantec Connect Community” and an interesting one on stackoverflow “What is your favourite anti-debugging trick?“. These both fall short on providing any solution that is both easy to implement and built with managed code.

Let’s face it nothing is going to be bullet proof in this arena, and certainly not the solution I’m going to suggest. Yet it is easy and will prevent someone from attaching a debugger after the program is running. I’m really not concerned with trying to prevent a debug-session from startup. Why? Because you can’t. The debugger can jump past any code you have that tries to verify that a debugger is not currently active. Besides this it provides me very little value, I want to protect an actively running process (a service). If the user has the rights to stop it in the first place (i.e. they are an admin) then there isn’t anything I can do to stop them from debugging.

What I want is to prevent someone from attaching a debugger to this service to protect potentially sensitive information. How? Well as it turns out the easiest way to prevent a debug session from starting is with a debug session. So what we need is to debug ourselves! Oh wait you can’t :( but what you can do is easily spawn another process to debug this process while we debug that new process. This reciprocal or circular debug session will prevent either process from being debugged. Further, any attempt to kill either process will immediately terminate the other process thus thwarting an effort to kill one debugger so that you can attach one.

To accomplish this in managed code we have two choices, either using the managed debugger API or the native win32 debugger API. It turns out that the managed debugger is excessively complicated and requires an extraordinary amount of COM code to pull it off (see the mdbg sample) So I chose to go with a raw win32 debug session and see if we could pull that off easily with a few PInvoke calls. Sure enough, this is really easy.

So let’s jump in and take a look at the debugging API calls we are going to need…

const int DBG_CONTINUE = 0x00010002;
const int DBG_EXCEPTION_NOT_HANDLED = unchecked((int)0x80010001);

enum DebugEventType : int
{
    CREATE_PROCESS_DEBUG_EVENT = 3, //Reports a create-process debugging event. The value of u.CreateProcessInfo specifies a CREATE_PROCESS_DEBUG_INFO structure.
    CREATE_THREAD_DEBUG_EVENT = 2, //Reports a create-thread debugging event. The value of u.CreateThread specifies a CREATE_THREAD_DEBUG_INFO structure.
    EXCEPTION_DEBUG_EVENT = 1, //Reports an exception debugging event. The value of u.Exception specifies an EXCEPTION_DEBUG_INFO structure.
    EXIT_PROCESS_DEBUG_EVENT = 5, //Reports an exit-process debugging event. The value of u.ExitProcess specifies an EXIT_PROCESS_DEBUG_INFO structure.
    EXIT_THREAD_DEBUG_EVENT = 4, //Reports an exit-thread debugging event. The value of u.ExitThread specifies an EXIT_THREAD_DEBUG_INFO structure.
    LOAD_DLL_DEBUG_EVENT = 6, //Reports a load-dynamic-link-library (DLL) debugging event. The value of u.LoadDll specifies a LOAD_DLL_DEBUG_INFO structure.
    OUTPUT_DEBUG_STRING_EVENT = 8, //Reports an output-debugging-string debugging event. The value of u.DebugString specifies an OUTPUT_DEBUG_STRING_INFO structure.
    RIP_EVENT = 9, //Reports a RIP-debugging event (system debugging error). The value of u.RipInfo specifies a RIP_INFO structure.
    UNLOAD_DLL_DEBUG_EVENT = 7, //Reports an unload-DLL debugging event. The value of u.UnloadDll specifies an UNLOAD_DLL_DEBUG_INFO structure.
}

[StructLayout(LayoutKind.Sequential)]
struct DEBUG_EVENT
{
    [MarshalAs(UnmanagedType.I4)]
    public DebugEventType dwDebugEventCode;
    public int dwProcessId;
    public int dwThreadId;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1024)]
    public byte[] bytes;
}

[DllImport("Kernel32.dll", SetLastError = true)]
static extern bool DebugActiveProcess(int dwProcessId);
[DllImport("Kernel32.dll", SetLastError = true)]
static extern bool WaitForDebugEvent([Out] out DEBUG_EVENT lpDebugEvent, int dwMilliseconds);
[DllImport("Kernel32.dll", SetLastError = true)]
static extern bool ContinueDebugEvent(int dwProcessId, int dwThreadId, int dwContinueStatus);
[DllImport("Kernel32.dll", SetLastError = true)]
public static extern bool IsDebuggerPresent();

The structure DEBUG_EVENT above is actually only 96 bytes in total and the bytes 12 to 96 are actually a union. I did not need any real details about the specifics so I chose to use slam a blob here and not worry about it. The byte array could be reduced in theory to 84 bytes but I really didn’t care since we are only going to create a single one of these. The rest is pretty strait-forward PInvoke junk, nothing fancy.

Using the methods above to debug a process looks something like the following code:

// Start a thread to perform the debug loop
new Thread(DebuggerThread) { IsBackground = true, Name = "DebuggerThread" }
    .Start(processId);
// Debugging thread main loop
static void DebuggerThread(object arg)
{
    DEBUG_EVENT evt = new DEBUG_EVENT();
    evt.bytes = new byte[1024];
    // Attach to the process we provided the thread as an argument
    if (!DebugActiveProcess((int)arg))
        throw new Win32Exception();

    while (true)
    {
        // wait for a debug event
        if (!WaitForDebugEvent(out evt, -1))
            throw new Win32Exception();
        // return DBG_CONTINUE for all events but the exception type
        int continueFlag = DBG_CONTINUE;
        if (evt.dwDebugEventCode == DebugEventType.EXCEPTION_DEBUG_EVENT)
            continueFlag = DBG_EXCEPTION_NOT_HANDLED;
        // continue running the debugee
        ContinueDebugEvent(evt.dwProcessId, evt.dwThreadId, continueFlag);
    }
}

Frankly I had no idea how trivial this was to do. Once I had this working I was able to quickly build a method that takes my program arguments and detects if it is a parent or child process and act appropriately. For the child we need only debug our parent process, for the parent we need to both spawn the child and debug it. Ideally this would be done as a single step since it is possible to start a process as a debugee; however, I didn’t bother to figure out how to do that. If you know and don’t mind sharing please drop a comment. Since I do know how to start a process and I know how to debug an active process I chose that approach. It doesn’t seem like it would be any more or less secure, but I could be wrong on that point. Anyway the following is what my process start-up looks like…

static void Main(string[] args)
{
    NativeDebug.DebugSelf(args);
    ... stuff ...
}
public static void DebugSelf(string[] args)
{
    Process self = Process.GetCurrentProcess();
    // Child process?
    if (args.Length == 2 && args[0] == "--debug-attach")
    {
        int owner = int.Parse(args[1]);
        Process pdbg = Process.GetProcessById(owner);
        new Thread(KillOnExit) { IsBackground = true, Name = "KillOnExit" }.Start(pdbg);
        //Wait for our parent to debug us
        WaitForDebugger();
        //Start debugging our parent process
        DebuggerThread(owner);
        //Now is a good time to die.
        Environment.Exit(1);
    }
    else // else we are the Parent process...
    {
        ProcessStartInfo psi =
            new ProcessStartInfo(Environment.GetCommandLineArgs()[0], "--debug-attach " + self.Id)
                {
                    UseShellExecute = false,
                    CreateNoWindow = true,
                    ErrorDialog = false,
                    WindowStyle = ProcessWindowStyle.Hidden
                };
        // Start the child process
        Process pdbg = Process.Start(psi);
        if (pdbg == null)
            throw new ApplicationException("Unable to debug");
        // Monitor the child process
        new Thread(KillOnExit) {IsBackground = true, Name = "KillOnExit"}.Start(pdbg);
        // Debug the child process
        new Thread(DebuggerThread) {IsBackground = true, Name = "DebuggerThread"}.Start(pdbg.Id);
        // Wait for the child to debug us
        WaitForDebugger();
    }
}
static void WaitForDebugger()
{
    DateTime start = DateTime.Now;
    while (!IsDebuggerPresent())
    {
        if ((DateTime.Now - start).TotalMinutes > 1)
            throw new TimeoutException("Debug operation timeout.");
        Thread.Sleep(1);
    }
}
static void KillOnExit(object process)
{
    ((Process)process).WaitForExit();
    Environment.Exit(1);
}

So we’ve written about 100 lines of code or so and spent almost no time at all getting it up and running, a good ROI for this kind of stuff. It worked quite well even running under the NETWORK SERVICE account as a service. It certainly stops me from debugging it although I’m certainly not what I’d call an accomplished hacker. Given the time and effort to put this together I’d have to call it a win for active debugger prevention. The down side of course is that there are now two processes running and trying to tell them apart is difficult at first launch.

If you’re going to do something like this, I would suggest adding an ‘if (!IsDebuggerPresent())’ to the else clause of our DebugSelf method above. This would allow you to launch with a debugger but not to attach one at a later time. Have fun with it and as with any code on this site, “Don’t blame me”. I didn’t make you use it ;)

My own intentions for this are to make a reasonable effort to secure a service running in a controlled but insecure environment. I would never ship something like this to a customer and hope you would not either. Preventing a consumer from accessing software they purchased is not at all what I’m after. IMHO if information is on their machine it is theirs to debug and view all they want.

One more thing, in case you are wondering this was not my idea. I read about doing this in a security article some years ago but I can’t seem to locate it.

 

Before I say another word, I have read “The arms race between programs and users” and wholeheartedly agree. You can not, and should not, attempt to stop an Administrator from killing your process or stopping your service. That is not what we are trying to do here, we are trying to prevent Joe User from disrupting our process.

So let’s get started, to do this we want to adjust our process’ access control list. The individual rights we can grant and deny are discussed on MSDN in the articled titled “Process Security and Access Rights“. Though most of that article is about creating a process with specific rights, in this case we want to modify the rights of our current process. To do this we are going to PInvoke GetKernelObjectSecurity to obtain the DACL (Discretionary Access Control List), modify it using the RawSecurityDescriptor, and finally write it back using the SetKernelObjectSecurity API. This should be somewhat familiar to those of you that followed that part of building our service.

Step 1 – Obtaining the process DACL

[DllImport("advapi32.dll", SetLastError = true)]
static extern bool GetKernelObjectSecurity(IntPtr Handle, int securityInformation, [Out] byte[] pSecurityDescriptor,
                                           uint nLength, out uint lpnLengthNeeded);

public static RawSecurityDescriptor GetProcessSecurityDescriptor(IntPtr processHandle)
{
    const int DACL_SECURITY_INFORMATION = 0x00000004;
    byte[] psd = new byte[0];
    uint bufSizeNeeded;
    // Call with 0 size to obtain the actual size needed in bufSizeNeeded
    GetKernelObjectSecurity(processHandle, DACL_SECURITY_INFORMATION, psd, 0, out bufSizeNeeded);
    if (bufSizeNeeded < 0 || bufSizeNeeded > short.MaxValue)
        throw new Win32Exception();
    // Allocate the required bytes and obtain the DACL
    if (!GetKernelObjectSecurity(processHandle, DACL_SECURITY_INFORMATION,
                                        psd = new byte[bufSizeNeeded], bufSizeNeeded, out bufSizeNeeded))
        throw new Win32Exception();
    // Use the RawSecurityDescriptor class from System.Security.AccessControl to parse the bytes:
    return new RawSecurityDescriptor(psd, 0);
}

And you thought that was going to be hard? Of course we also need to be able to save the DACL. So…

Part 2 – Updating the process DACL

[DllImport("advapi32.dll", SetLastError = true)]
static extern bool SetKernelObjectSecurity(IntPtr Handle, int securityInformation, [In] byte[] pSecurityDescriptor);

public static void SetProcessSecurityDescriptor(IntPtr processHandle, RawSecurityDescriptor dacl)
{
    const int DACL_SECURITY_INFORMATION = 0x00000004;
    byte[] rawsd = new byte[dacl.BinaryLength];
    dacl.GetBinaryForm(rawsd, 0);
    if (!SetKernelObjectSecurity(processHandle, DACL_SECURITY_INFORMATION, rawsd))
        throw new Win32Exception();
}

Cool, that was easy, so we are ready now right? Not quite, we still need to get the process handle. A simple thing for our own process:

Part 3 – Getting the current process

[DllImport("kernel32.dll")]
public static extern IntPtr GetCurrentProcess();

It just gets easier and easier. Since this is the current process there (AFAIK) is not any reason to duplicate handle and request additional permissions. This handle should have access to do anything. So the only thing left before we can modify the permissions is to define what those permissions are.

Part 4 – Process access rights

[Flags]
public enum ProcessAccessRights
{
    PROCESS_CREATE_PROCESS =0x0080, //	Required to create a process.
    PROCESS_CREATE_THREAD = 0x0002, //	Required to create a thread.
    PROCESS_DUP_HANDLE = 0x0040, //	Required to duplicate a handle using DuplicateHandle.
    PROCESS_QUERY_INFORMATION = 0x0400, //	Required to retrieve certain information about a process, such as its token, exit code, and priority class (see OpenProcessToken, GetExitCodeProcess, GetPriorityClass, and IsProcessInJob).
    PROCESS_QUERY_LIMITED_INFORMATION = 0x1000, //	Required to retrieve certain information about a process (see QueryFullProcessImageName). A handle that has the PROCESS_QUERY_INFORMATION access right is automatically granted PROCESS_QUERY_LIMITED_INFORMATION. Windows Server 2003 and Windows XP/2000:  This access right is not supported.
    PROCESS_SET_INFORMATION = 0x0200, //	Required to set certain information about a process, such as its priority class (see SetPriorityClass).
    PROCESS_SET_QUOTA = 0x0100, //	Required to set memory limits using SetProcessWorkingSetSize.
    PROCESS_SUSPEND_RESUME = 0x0800, //	Required to suspend or resume a process.
    PROCESS_TERMINATE = 0x0001, //	Required to terminate a process using TerminateProcess.
    PROCESS_VM_OPERATION = 0x0008, //	Required to perform an operation on the address space of a process (see VirtualProtectEx and WriteProcessMemory).
    PROCESS_VM_READ = 0x0010, //	Required to read memory in a process using ReadProcessMemory.
    PROCESS_VM_WRITE = 0x0020, //	Required to write to memory in a process using WriteProcessMemory.
    DELETE = 0x00010000, //	Required to delete the object.
    READ_CONTROL = 0x00020000, //	Required to read information in the security descriptor for the object, not including the information in the SACL. To read or write the SACL, you must request the ACCESS_SYSTEM_SECURITY access right. For more information, see SACL Access Right.
    SYNCHRONIZE = 0x00100000, //	The right to use the object for synchronization. This enables a thread to wait until the object is in the signaled state.
    WRITE_DAC = 0x00040000, //	Required to modify the DACL in the security descriptor for the object.
    WRITE_OWNER = 0x00080000, //	Required to change the owner in the security descriptor for the object.
    STANDARD_RIGHTS_REQUIRED = 0x000f0000,
    PROCESS_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0xFFF),//	All possible access rights for a process object.
}

Part 5 – Put it all together

// Get the current process handle
IntPtr hProcess = GetCurrentProcess();
// Read the DACL
var dacl = GetProcessSecurityDescriptor(hProcess);
// Insert the new ACE
dacl.DiscretionaryAcl.InsertAce(
    0,
    new CommonAce(
        AceFlags.None,
        AceQualifier.AccessDenied,
        (int)ProcessAccessRights.PROCESS_ALL_ACCESS,
        new SecurityIdentifier(WellKnownSidType.WorldSid, null),
        false,
        null)
);
// Save the DACL
SetProcessSecurityDescriptor(hProcess, dacl);

The ace we’ve added now will try to deny access to the “Everyone” group (aka WorldSid) to do anything with our process. We need not fear that we are interrupting an administrator’s ability to perform any action they desire. They will have any access required that’s why we call them administrators :) As I said in the beginning, we are not trying to stop Administrators, we just want to make sure they are an administrator if they plan to modify or kill this process.

We could of course be more discrete about the rights we are trying to deny, that is entirely up to you.

 

Continued from “Building a Windows Service – Part 6: Adding resources and event logging

So let’s recap our goals for this project:

  • Building a service that can also be used from the console
  • Proper event logging of service startup/shutdown and other activities
  • Allowing multiple instances by using command-line arguments
  • Self installation of service and event log
  • Proper event logging of service exceptions and errors
  • Controlling of start-up, shutdown and restart options
  • Handling custom service commands, power, and session events
  • Customizing service security and access control

Yep, we are on the mark there and have demonstrated most of these in the past few posts. The goal not stated directly has always been to to create a new project template. We had a bit of cleaning up to do before we could deal with that. I’m not going to cover this clean up in the same level of detail as before, but here are a few words about how this has changed from the previous posts:

  1. I’ve added an application icon and manifest. This brought to light that the generator for the win32 resources was not preserving the manifest, nor was it correctly locating the icon when I moved the resources file. To get this working I’ve built a custom version of the CSharpTest.Net.Generators executable.
  2. For all the good it does, I’ve added an UnhandledException event listener on the AppDomain to attempt to log the exception. As you probably know this is unreliable at best ;)
  3. I’ve split all the resources into three parts, messages that are written, exceptions that log, and normal non-logging string resources. These have been to a Resources folder and all resource/event specific stuff is now located there.
  4. The remainder of the service stub class, “ServiceImplementation” has been filled out to include power and session events, custom commands, etc. The appropriate logging and plumbing has been introduced into the ServiceProcess class to support these new methods.
  5. There are a couple of other small changes and always bugs, and I’ve had to fix a few from the previous posts.

The end result is a clean easy to use project template for Visual Studio 2008. This can easily be upgraded to 2010 if you desire. The project is currently using the 2.0 Framework to allow the greatest flexibility, but obviously once you create the project from the template it can be changed.

zip Download the Visual Studio Service Project Template
To use the template place it in the following path for 2008:
%UserProfile%\My Documents\Visual Studio 2008\Templates\ProjectTemplates\Visual C#

Once installed, create a new project, locate the template “ServiceTemplate” and create a project. Since the project name is used heavily throughout the template you should avoid names that contain non-alpha-numeric text or are longer than 64 characters. You can always rename the project file, assembly, and default namespace later, but start with a simple name. After the project has been created there are two things to do from the command line. Assuming a working directory at the root of the project the following commands should be run:

C:\Projects\MyService> Tools\CmdTool.exe register
C:\Projects\MyService> Tools\CmdTool.exe build MyService.csproj
Generating C:\Projects\MyService\Resources\Exceptions.resx
Generating C:\Projects\MyService\Resources\FormatString.resx
Generating C:\Projects\MyService\Resources\Messages.resx

Now you can build and run the project with the ‘install’ command and away you go. Modify the ServiceImplementation class to provide the service implementation. Adjust the default IsolateDomain, and ShadowCopy settings to your desired defaults. Don’t forget if you want to debug service start-up you can run the command “start {servicename} DEBUG!” and, if the service is not running, a debug break-point will be triggered.

It’s not often I have to create a windows service, yet each time it takes me several days to work all this out. I hope this will save you some time as well, enjoy.

PS: If you’ve missed any of the previous posts, here they are:

 

So I ran into this article entitled “How to Create a Personal Encryption Scheme to Easily Hide Your Data in Plain Sight” on lifehacker.

I just want to say:
This is a REALLY bad idea.

The recommendation is to create you’re very own personal ‘encryption‘ system to encode you’re personal information in plain site. The problem is they don’t suggest using encryption at all, rather they suggest obfuscation of the data. So what is the difference? Well let’s first talk about what is Obfuscation:

Obfuscation (or beclouding) is the hiding of intended meaning in communication, making communication confusing, wilfully ambiguous, and harder to interpret.

So from this the key thing to take away is that Obfuscation means that it makes it difficult to interpret. Now let’s look at what the definition of encryption:

In cryptography, encryption is the process of transforming information (referred to as plaintext) using an algorithm (called a cipher) to make it unreadable to anyone except those possessing special knowledge, usually referred to as a key.

So encryption makes data “unreadable” whereas obfuscation makes it “difficult”. That is a good start for a definition but these lines are somewhat gray. There are ‘encryption’ systems that have proven weak such as DES. So if I can decrypt cipher-text encoded by DES, does that mean DES is just Obfuscation? Hrmm. Well if you look at this another way, even strong algorithms (AES, PKI, etc) can be brute forced given infinite time and resources. So does this extend to these algorithms as well? Are then all encryption algorithms just a means of obfuscation at varying levels of difficulty? Well strictly speaking yes; however, the level of difficulty to brute force AES is so far past our current abilities that it is, for now, unbreakable.

So what is Obfuscation?
If we intend to differentiate Obfuscation from Encryption we need a better definition for both. The above definitions are Wikipedia’s, here is what I would add:

Definition of Obfuscation: A process applied to information to intentionally make it difficult to reverse without knowing the algorithm that was applied.

In other words, knowing the process or algorithm that was used makes obfuscation significantly easier to decipher. Any of the examples in the lifehacker article are subject to this. Once I know the basic idea behind your obfuscation technique it’s easy to defeat. Take for example a letter substitution table. Let’s say we assign each letter to another random letter, a=j, b=f, c=u, etc. Now encode this post with that substitution table. It would be a trivial thing to decode even without knowing your ‘secret’ letter substitution table. Why? well just google it: letter substitution solver.

So what is encryption?

Definition of Encryption: A process applied to information that, even knowing the algorithm applied, requires a secret (key) to reverse it in a reasonable amount of time.

There now that seems to fit, even cryptographically weak algorithms like DES fit this description. They make it hard to decipher even knowing the algorithm applied unless you have the key. So this helps delineate the differences between obfuscation and encryption. Even if you use something that fits into the encryption bucket that does not make you’re data secure.

Measuring data security:
Data or information security is measure in time and each of the encryption algorithms we use have a measurable amount of time it would take to break them. This ‘time’ assumes no weaknesses in the key generation or the implementation algorithm. (Note: I’m not interested in chosen plain-text, related key, side channel, and other attacks that rely on behavior of the implementation, I’m talking about cipher-text at rest). This time can and does change, computers become faster, weaknesses in the algorithm itself are exposed, etc. This is very similar to what happened to DES in 1997, things change and what had seemed impossible suddenly became very feasible.

Ultimately no data is ‘perfectly secure’ even using a very good algorithm like AES. You should be aware that most of the time you’re data is more at risk from weak passwords that are used to create an encryption key rather than from weaknesses in the algorithm itself. This is why there are 100′s if not 1000′s of ways to crack winzip passwords. When passwords are not involved the generated pseudo-random keys require storage (you can’t remember it) and therefore the security of that storage location becomes the problem (see Keep it secret, Keep it safe).

Using a Personal Encryption Scheme?
Now back to the story we started with, How to Create a Personal Encryption Scheme to Easily Hide Your Data in Plain Sight. This, as I’ve already said, is a REALLY bad idea. So what should you do? There are 100′s of “Secure Note” applications for almost every platform still in use today. Pick one that allows full text passwords (not 4 digits) and use it. Anything that uses 4 digits is insecure by design having only a keyspace of 10,000 unique possibilities. By contrast, modern cryptography has a keyspace of at least 2^128 or 340,282,366,920,938,463,463,374,607,431,768,211,456 unique possibilities.

 
Benchmarking WCF compared to Protocol Buffers + RpcLibrary

So now that I’ve finally got around to releasing a protocol built on top of the RpcLibrary I thought it would be fun to re-run some benchmarks. The protocol has been around unreleased for almost a year waiting on some required changes in protobuf-csharp-port which have finally been published in a release. The protocol I’m [...]

 

Let’s face it the clever guys at Google have more bandwidth than the rest of the nation combined. What better to do with all that excess pipe ;) There are of course numerous posts about the performances of +1 buttons. If you missed them there is the ever popular Google +1 Button Performance Review, and [...]

 

A few weeks ago I published NuGet packages for version 1.11.924.348. CSharpTest.Net.BPlusTree CSharpTest.Net.Library CSharpTest.Net.Logging CSharpTest.Net.RpcLibrary   I also managed to get protobuf-csharp-port on board. I absolutely live by protobuffers. Google.ProtocolBuffers Google.ProtocolBuffersLite   Finally I recently published a complete protobuf services rpc layer build on the RpcLibrary and protobuf-csharp-port. Of course much of the code there [...]

 
BPlusTree performance at large volumes (200 meeLLLLion)

Ok I swear this is the last B+Tree chart, graph, or metric I’ll post… at least for a while. I wanted to hit new limits so I fired up 6 threads on my six-core and let them rip… After three hours I finally stopped the run to look at the results. Each of the six [...]

 
BPlusTree benchmarks and comparisons

Test Overview The benchmark results below are from a single thread on a process with the thread-affinity set except two. The BPlusTree(Threaded) and obviously MySql were not constrained. All data used during the test was generated before the test ran. The number displayed in the logarithmic horizontal axis is the average number of operations completed [...]