Category Archives: C#

Honeywell Total Connect (Windows Phone) Information / Source Code

Been a while since I posted here. Have had a crazy past year so I have not had time to do much on this blog. But I am back for a topic that I have been getting emailed about a lot since my previous post about the Total Connect tool I made for Windows Phone.

Be aware: The information in this post is for educational purposes only. While the app is free, I do still respect Honeywell and their services. Please do not abuse this information. Use at your own risk. I am not liable for what happens when you use anything posted here or referenced by me.

Obtaining The APK Locally
The link to the APK on the play store can be found here: https://play.google.com/store/apps/details?id=com.alarmnet.tc2
We can see that the file name is ‘com.alarmnet.tc2’, Just add .apk to the name and Google. You will find a dozen sites with the APK. You can also root your phone to gain access etc. but I will not cover that here.

Decompilg The APK
Now that we have the APK we need to decompile it. You can use the following tools to accomplish this:
– dex2jar: https://code.google.com/p/dex2jar/

With this tool, you can easily convert the .dex file inside the .apk file (it is just a .zip file!) back to a usable jar file.
Simply drag and drop the .dex file onto ‘d2j-dex2jar.bat’ and you’re done.

Next to decompile the Jar to readable source code I used:
– Jd-Gui: http://jd-gui.softpedia.com/

Again simply open the .jar now with this tool and you will see the decompiled source.

Understanding The Source
While I do recommend looking through the entire thing to get accustom to their setup, I will point out what is important.
– com\alarmnet\tc2\rcmobile\rcConn.java
– com\alarmnet\tc2\rcmobile\rcSecure.java

Both of these files contain the service call data and connection flow that we will need to follow in our application. I really recommend studying these because their method of handling the connection is fairly convoluted in my opinion.

Making The Connection (Service Call Flow)
Now that we have the source, we can analyze the setup of the service calls and how they are handled. For one, we see the main service object can be found here:
https://rs.alarmnet.com/tc21api/tc2.asmx

They were nice enough to use a Windows service so this makes things a bit easier while working with it at least. 🙂

To make a login request, we have a two step process:
– AuthenticateUserLogin : Which does what it sounds like, it auths our login information.
– GetSessionDetails : Obtains information about our session. (ie. Session Id, Module Flags, Security Locations, User Info)

To even login, we are required to give the service some information:
– Our Application Id
– Our Application Version

Given that the Windows phone does not have an appId/version for this, we use the Android one to fake the call. In the case of the code I wrote, the version info was:
– Application Id: 34857971
– Application Version: 2.2.0

The next step is to keep the session activated and alive. After we login, the app creates a thread to keep pinging the service. Inside that thread, the app was calling KeepAlive and GetPanelMetaDataAndFullStatusByDeviceID.

Thankfully, we are given the nice usage of async callbacks for everything when we reference their service. So we can make a fairly decent setup that can be UI friendly.

Arming Our Security System (And Disarming..)
Next was seeing how we arm and disarm the system. Here I found that the call was made to ArmSecuritySystem. This handled both arming for away and stay modes. This takes a number of params which I am not 100% sure if the user id param was required or not. I would recommend not sending it at all if you do not have to. My examples sent it just to be safe when I was testing this setup.

Following suit, to disarm the system we have a similar call: DisarmSecuritySystem

Status Information And The Like
Finally, with the information obtained status codes and bitmasks were all that was left to obtain the information data. When querying for the panel status in the keep alive, we can get a number of results that mean different things (based on different security systems):

  • 10200 – Disarmed
  • 10211 – Disarmed (bypass)
  • 10201 – Armed Away
  • 10202 – Armed Away (bypass)
  • 10205 – Armed Away (instant)
  • 10206 – Armed Away (instant-bypass)
  • 10203 – Armed Stay
  • 10204 – Armed Stay (bypass)
  • 10209 – Armed Stay (instant)
  • 10210 – Armed Stay (instant-bypass)
  • 10307 – Arming
  • 10308 – Disarming

When we arm or disarm the system, we can get a specific result return of: 4500
When this occurs the system wants us to force-request the current panels last command state. When we do this, that service call can have the following returns:

  • 0 – Success
  • -4502 – Invalid pin. (Yes, that is a negative result.)
  • 4501 – Repoll Required (Command is currently scheduled.)

Also when we call the GetPanelMetaDataAndFullStatusByDeviceID method, we are given the current panels zone data. These zones can have a series of flags in their status mask. The status codes are as follow for the zones:

  • 0 – Normal
  • 1 – Bypassed
  • 2 – Faulted
  • 8 – Trouble
  • 16 – Tampered
  • 32 – Supervision Failed

Putting It All Together

When I first started working on this I made a simple test application which can be seen here:

After getting the test app to work fairly well, I moved to working on the demo phone app I created. Which can be seen here:

Getting it to work simply for myself was great. I was happy to get it in a somewhat working manner. However, I am by no means a Windows Phone developer. This was my first solo app project for the WP7 platform and I can honestly say my last. I am not a fan of Windows Phones at all and I have since gotten rid of mine and moved to Android.

About The Source Code
The source code is in a beta “working” state. Meaning, things are thrown together just to get it to work and test things out kind of state. I did not take the time to fully cleanup the code, it may [read: does] still have errors and problems. I cannot guarantee it will work for everyone and such. The following sources will be of my original test application (proof of concept) and the phone app.

I do wish that people at least honor me by giving me credits if you use this source code. I also do request that you do not sell your app, if you make one, for money. Honeywell offers this service free of charge on all other platforms, there is no reason to nickle and dime people for a simple feature-set like this.

Windows Proof of Concept Client: https://github.com/atom0s/HoneywellWindowsPoC
Windows Phone 7 Proof of Concept App: https://github.com/atom0s/HoneywellWP7PoC

Honeywell Total Connect Windows Phone

After my recent move to my partners house, I learned he has a security system that is manufactured through Honeywell. Within the first week of living at the new house he had set me up with my own security code and login to use the system so I can come and go freely as needed. Sadly, I learned quickly that my phone (Windows Phone, HTC Trophy) does not have any type of app to communicate with the system like iPhone, Android, and Blackberry do.

So I endeavored a bit to see what all the app does on the Android phone by getting my hands on the APK via Google. Doing a little research you can find the app on the Google market here:
https://play.google.com/store/apps/details?id=com.alarmnet.tc2

The URL tells us the name of the app file as well being:
com.alarmnet.tc2

So slap on the extension .apk and Google away to find the actual file.


Getting The Goods

The next step after obtaining the .apk file is getting it back to readable code. To do this I found a toolkit called dex2jar found here:
https://code.google.com/p/dex2jar/

With this, you can easily convert the .dex file inside the .apk (its just a .zip file) back to the usable .jar file.
Simply drag and drop the .dex onto the ‘d2j-dex2jar.bat’ and you’re done.

Next I used jd-gui.exe to decompile the .jar back to usable code, you can find that here:
http://jd-gui.softpedia.com/

With that you can load the .jar and then save all the sources via the File menu. This will produce the .java files that are readable source code again.


Whats Important To Us

Now that I was able to get the source back, I started looking for what would be useful to me. Quickly, I came across:
com\alarmnet\tc2\rcmobile\rcConn.java
com\alarmnet\tc2\rcmobile\rcSecure.java

Both of which have very useful information pertaining to the app. Through tracing functions in these two files I quickly found out that the application was communicating with a WCF service via SOAP calls. The service location is found here:
https://rs.alarmnet.com/tc21api/tc2.asmx


Call Flow — Making It Work

Given that I have the full src to the Android app now, I took time to analyze things to see if there was any small quirks I had to follow, and sure enough there are. To start, logging in is a two-step process:
AuthenticateUserLogin -> GetSessionDetails

The session details include information about the users access to the security system including:

  • Session ID
  • Module Flags
  • Security Locations
  • User Information

The Security Locations include information about each device that the user has access to (panels etc) inside that location. All of which are needed when making various other calls to the security service.

After being logged in, the session id returned has to be kept alive using another call:
KeepAlive

This call keeps the session active on the service end and allows us to keep making various other calls to the service without having to login again. From the look of it, sessions only have to be pinged once every 2 minutes as seen by the keep alive timer code here:

  public void startKeepAliveTimer()
  {
    this.timer = new Timer();
    this.cmdtimer = new CmdTimer();
    this.timer.schedule(this.cmdtimer, 60000L, 120000L);
  }

Next, we have to keep querying the panel for status information, arm status, etc. However I didn’t see a clear-cut method of how the Android app did this. So I instead assumed 10 seconds would be enough between each query. Which can be obtained using the service call:
GetPanelMetaDataAndFullStatusByDeviceID


Phase 1 — Trial and Error

My first night coding, I made a quick test app to see if I could really login to the service. Which I was greeted with the need of two more specific pieces of information. The login call looks like this:

AuthenticateUserLogin(username, password, applicationId, applicationVersion);

Clearly we do not have a real appId and appVersion for the Windows Phone since there is none. So we have to improvise and use what we have. Inside the Android app I found the Android values. The application id was found in a .java file with the line of code being:

KSoapUtils.createElementAndSetEscapedText(localElement3, "ApplicationID", "ipv", Integer.valueOf(34857971));

The application version was a little more tricky since its stored in the AndroidManifest.xml. Which is also encrypted separately. To decompile the xml I found a tool called apktool:
https://code.google.com/p/android-apktool/

To get the info that I needed here, you can use the command:
java -jar apktool.jar decode -s com.alarmnet.tc2.apk

This will decode just the resources which includes the needed AndroidManifest.xml file. Now that its decoded I found the version value near the top which was:
android:versionName=”2.2.0″

So now the login call can be made using:

AuthenticateUserLogin(this.txtUsername.Text, this.txtPassword.Text, 34857971, "2.2.0");

Next up was handling the returns. After some analysis, I figured that all commands return a base object that has a ResultCode and ResultData. From there I figured all returns expect ResultCode to equal 0 to be successful. Otherwise it was an error and then ResultData would be filled with the error string. This made coding the handlers a bit easy.

My resulting test project looked like this:

The project was simple and only included a few features which were:

  • Login To Service
  • Obtain Session Info
  • Query Panel Status
  • Query Zone Status’ (To see faults, trips, issues, etc.)
  • Disarm, Arm (Away), and Arm (Stay) the system.

The disarming and arming of the system both use the users 4-digit pin-code to properly work as well.


Phase 2 — Phone Version

Today started phase 2 which was bringing the v1 beta onto the phone, with a more appealing look. For this I used the assets and resources from the Android version of the application for my phone app. After a few hours of tinkering and such, I found out that the service calls in the Windows Phone turned into async calls which was I not expecting. So I had to land up rewriting my base entirely to work with this. Although I prefer working with async anyway, it was just not expected.

After a bit of work, I made two basic screens that are fully functional so far which are the login and main security panel screens, seen here:

At this time I do not have any other features working or implemented. I do plan to add the usage log and the zone information screens soon, but outside that I do not have a system with cameras and other features to get those working.

I also do not have a AppHub developer account to push this onto the market place either. (It would be free, perhaps with ads or something to make some money for my time.) But at this time it was more of a project for myself.

Feel free to ask questions if you have any. 🙂

Misc Tutorials I’ve Recently Written

Here are some various articles/tutorials I’ve written in the past ~2 years:

C# Loader Hooking With Mono.Cecil
Click Here!

Terraria 1.1.2 – Decompiling / Recompiling
Click Here!

Creating Packet Editor / Proxy In C#
Click Here!

TSGE – Terraria Save Game Editor
Click Here!

Terraria 1.1.2 – Dumping Data and Textures
Click Here!

Terraria 1.1.2 – Collector Edition Bunny
Click Here!

XNA Hooking Through Reflection / Reference
Click Here!

Terraria – Steamless Loading

Disclaimer: Usage of a method to load the game list this allows you to run without Steam. This means the game can be copied onto other machines without purchasing it. I do not condone in piracy. I simply made this because I was sick of Steam for a while. I take no responsibility in what you do with this information.

Since Terraria is a managed application, we can easily import it into a project and reference the main class. With this we can initiate an instance of the main class and effectively load the game through our own app. With this we can skip the entire launching method that is called by the application when it’s asked to start (Main(..)).

So in turn we land up with:

using System;
using System.IO;
using System.Reflection;
using Microsoft.Xna.Framework;

namespace tLock
{
#if WINDOWS || XBOX
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

            // Set Terraria's Path..
            String strRealPath = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86) + "\Steam\steamapps\common\terraria"; //"C:\Program Files (x86)\Steam\steamapps\common\terraria";
            Directory.SetCurrentDirectory(strRealPath);

            // Run our game..
            var tLock = Assembly.GetExecutingAssembly().GetType("tLock.Hook", true, true);
            (Activator.CreateInstance(tLock) as Game).Run();
        }

        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            using (FileStream fStream = new FileStream("errorlog.txt", FileMode.CreateNew, FileAccess.ReadWrite))
            {
                using (StreamWriter sWriter = new StreamWriter(fStream))
                {
                    sWriter.Write(((Exception)e.ExceptionObject).Message);
                }
            }
        }
    }
#endif
}

Then we need to add our hook class which tells the game were to locate the content. This also allows you alter the game while it plays to do a ton of other stuff. (Not covered in this post though.)

Hook.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Terraria;

namespace tLock
{
    public class Hook : Terraria.Main
    {
        protected override void Initialize()
        {
            // Reset the content directory..
            Content.RootDirectory = Environment.CurrentDirectory + "\Content\";

            // Base initialization..
            base.Initialize();
        }

        protected override void LoadContent()
        {
            base.LoadContent();
        }

        protected override void Update(GameTime gameTime)
        {
            base.Update(gameTime);
        }

        protected override void Draw(GameTime gameTime)
        {
            base.Draw(gameTime);
        }
    }
}

Once compiled, drop in the same directory as Terraria.exe and use your app to launch the game. Tada~ no more Steam

Ashita Launcher

About The Project

Since joining the Ashita project a while back, the loader/injector for the project was always a bit underwhelming. It was tossed together just to work with the basic injection method to focus time on the core hook of the project. Because of this I always had some ideas in mind of redoing it and bringing life to the loader as well as making it a central tool for configuring the profiles so non-computer literate users could make use of of the project with ease.

I started the Ashita Launcher as a side project that I worked on in my spare time while working on the core hook of the project too.

Ashita Launcher is coded in C# using WPF. It makes use of the following libraries:

  • GalaSoft MVVM Light (WPF4)
  • MahApps.Metro

Features

The Ashita Launcher has the basic needs of injecting the Ashita Core hook into the Final Fantasy XI process (pol.exe) but also extends into a full configuration editor as well as semi-automatic updater.

Users are greeted at launch with a list of currently found profiles in their Config\Boot folder:
laucher

Following this, users can select a configuration and edit it to allow for easy alterations:
editor

This project is open source and can be found here:
https://github.com/atom0s/AshitaLauncher

about

Native CLR Hosting (With separate AppDomains per-module.)

Notice: All error handling / checking has been stripped from the code to make things as basic and easy to understand. Majority of the calls made in the below code are to COM objects which use HRESULT returns. Always check your returns before continuing to help prevent crashes!

One of the biggest, I consider, issues with .NET and plugins is that you can’t truly unload a managed module without fully shutting down the application domain it is ran within. Things linger in memory and the garbage collection only does so much. In C/C++ the simple FreeLibrary handles this but we don’t have that luxury in C#. Instead, the easiest way to truly get unloading plugins is by loading each one into it’s own AppDomain.

Doing this with the use of ‘mixed’ code is simple and documented, however doing this in pure native C++ is not. It involves working with the COM interfaces of the CLR and such which does not have much documentation, and after a certain pointer, there is none. There also is a lack of examples showing how to do it online / open source. For someone like me, I personally enjoy both .NET (C#) and C/C++, however, I enjoy them being separate. I do not like VC++, the look and feel of the code is just wrong to me. I do not use it, and do not plan to use it. (This is my opinion, I’m sure yours will differ, that’s not the point of this post.)

Anyway, getting into the code. To start, this article will be based around how I implemented things, and what for. So a little back story. I work on a project that is an injected hook into a popular MMORPG. The purpose of this hook is to extend the ability of the game to make it better enjoyable to play. The focus is not cheating related, but the project does not limit what the users can do with the plugin interface that is exposed. The project is fully coded in C++ and the extension SDK exposes a collection of interfaces that the users can use to interact with the core hook. This is done by the hook loading plugins and passing a core object pointer to them which is casted to the core interface object.

With this I created an extension for our hook called ‘Bootstrap’. The purpose of this extension is to load the CLR into the process as well as creating new appdomains for each C# extension that it loads. I wanted to ensure that these plugins can be fully unloaded during runtime because being an MMO, the game does take up it’s own amount of resources and such. Keeping things clean and limited help out a lot.

So we have:

Hook &lt;- -&gt; Bootstrap Extension &lt;- -&gt; Managed Extension(s)

When Bootstrap first starts, we want to ensure we load the CLR runtime first and immediately.
I do that with the following little bit of code:

// Bind to the given runtime..
ICorRuntimeHost* lpRuntimeHost = NULL;
CorBindToRuntimeEx( L&quot;v4.0.30319&quot;, L&quot;wks&quot;, 0, CLSID_CorRuntimeHost, IID_PPV_ARGS( &amp;lpRuntimeHost ) );

// Attempt to start the runtime..
lpRuntimeHost-&gt;Start();

Next, when a managed plugin is requested to start, Bootstrap will do some minor checking to ensure the file exists and such. Once it ensures the plugins not already loaded and it exists on disk, it will attempt to load it.

The next step is to load this plugin into its own AppDomain. For starters, I wrote a simple wrapper to hold the important interfaces that this plugin created when being loaded like this:

struct managedplugin_t
{
    std::wstring                m_PluginName;
    std::wstring                m_PluginPath;

    CComPtr&lt;IUnknown&gt;           m_AppDomainSetupUnknown;
    CComQIPtr&lt;IAppDomainSetup&gt;  m_AppDomainSetup;

    CComPtr&lt;IUnknown&gt;           m_AppDomainUnknown;
    CComPtr&lt;_AppDomain&gt;         m_AppDomain;

    CComPtr&lt;_Assembly&gt;          m_AppAssembly;
    CComVariant                 m_AppVariant;
    
    CComPtr&lt;IAshitaExtension&gt;   m_AppInstance;

    bool                        m_IsDirect3DReady;

    managedplugin_t()
    {
        this-&gt;m_PluginName              = L&quot;&quot;;
        this-&gt;m_PluginPath              = L&quot;&quot;;
        this-&gt;m_AppDomainSetupUnknown   = NULL;
        this-&gt;m_AppDomainUnknown        = NULL;
        this-&gt;m_AppDomain               = NULL;
        this-&gt;m_AppAssembly             = NULL;
        this-&gt;m_AppVariant              = NULL;
        this-&gt;m_AppInstance             = NULL;
        this-&gt;m_IsDirect3DReady         = false;
    }
};

Next, the first step is to create a new AppDomain. We want to create a DomainSetup object first to set some properties for the domain, such as where it will resolve its assemblies from and such. Afterward we create the domain with this new setup information:

// Create a new AppDomain setup object for the new domain..
this-&gt;m_RuntimeHost-&gt;CreateDomainSetup( &amp;plugin-&gt;m_AppDomainSetupUnknown );

// Fill some basic structure info about this domain..
plugin-&gt;m_AppDomainSetup = plugin-&gt;m_AppDomainSetupUnknown;
plugin-&gt;m_AppDomainSetup-&gt;put_ApplicationBase( CComBSTR( this-&gt;m_PluginBasePath.c_str() ) );
plugin-&gt;m_AppDomainSetup-&gt;put_ShadowCopyFiles( CComBSTR( &quot;true&quot; ) );
plugin-&gt;m_AppDomainSetup-&gt;put_ApplicationName( CComBSTR( pluginName.c_str() ) );

// Create the new AppDomain..
this-&gt;m_RuntimeHost-&gt;CreateDomainEx( pluginName.c_str(), plugin-&gt;m_AppDomainSetupUnknown, NULL, &amp;plugin-&gt;m_AppDomainUnknown );

// Obtain the actual AppDomain object..
plugin-&gt;m_AppDomainUnknown-&gt;QueryInterface( __uuidof( mscorlib::_AppDomain ), (void**)&amp;plugin-&gt;m_AppDomain );

Now we want to load the plugin file into this AppDomain. My method was to have users create their plugins a specific way. Each plugin is loaded by its name, and then it must use a public class named ‘Main’ that inherits my C# implementation of our IAshitaExtension base class. This way I can forward all the C++ plugin calls to the C# plugins. So we load the plugin now like this:

// Load the plugin module into the AppDomain..
plugin-&gt;m_AppDomain-&gt;Load_2( CComBSTR( mainInterface.c_str() ), &amp;plugin-&gt;m_AppAssembly );

// Create instaoce of the 'Main' class object..
plugin-&gt;m_AppAssembly-&gt;CreateInstance_2( CComBSTR( mainInterface.append( L&quot;.Main&quot; ).c_str() ), true, &amp;plugin-&gt;m_AppVariant );

// Obtain instance of our base class from this newly created instance..
plugin-&gt;m_AppVariant.punkVal-&gt;QueryInterface( __uuidof( IAshitaExtension ), (void**)&amp;plugin-&gt;m_AppInstance );

One major thing to note here. For some reason CreateInstance_2 does not return properly. If it fails to create an instance of the given object, it will still return S_OK. You need to check the VARIANT object it returns and ensure it is valid. You can do this by checking it like:

if (plugin-&gt;m_AppVariant.vt == VT_EMPTY || plugin-&gt;m_AppVariant.vt == VT_ERROR)
{
    /** Object is invalid.. **/
}

Next is understanding the relationship between C++ and C# in our extensions. As I said above, the C# extensions inherit a managed base class, which looks like this:

namespace ManagedExample
{
    public class Main : AshitaBase
    {
        public override bool Load(IntPtr ashitaCore)
        {
        }
    }
}

The way this works is that AshitaBase is actually an abstract class.
This class inherits a base COM exposed interface, which in turn these look like this:

[ComVisible(true)]
[Guid(&quot;7805E68A-A028-433C-BB73-38D34D7208C5&quot;)]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IAshitaExtension
{
    [ComVisible(true)]
    [return: MarshalAs(UnmanagedType.I1)]
    bool Load(IntPtr ashitaCore);
}

public abstract class AshitaBase : IAshitaExtension
{
        public virtual bool Load(IntPtr ashitaCore)
        {
            return false;
        }
}

I had to use a COM exposed interface like this in order to be able to call things easily on the C++ side. With it setup like this, and with the above C++ code, we can now tell the C# plugin we loaded to call it’s Load function like this:

bool bReturn = false;
plugin-&gt;m_AppInstance-&gt;Load( (long)this-&gt;m_AshitaCore, (unsigned char*)&amp;bReturn );

And there we have it, CLR hosting in pure native C++ 🙂

There are some things with this that I am still trying to figure out, such as adding an UnhandledException handler to each AppDomain but I am unsure how to properly call the m_AppDomain->add_UnhandledException function at this time.

Feel free to leave comments, suggestions, etc. Hope this helps someone in the future.

Some minor things I forgot to mention, here are the includes and other definitions needed for this stuff:

#pragma comment( lib, &quot;mscoree.lib&quot; )
#include &lt;mscoree.h&gt;

#include &lt;atlbase.h&gt;
#include &lt;atlsafe.h&gt;
#include &lt;metahost.h&gt;

#import &quot;mscorlib.tlb&quot; raw_interfaces_only

// Import of my managed base class information..
#import &quot;../../build/Extensions/Managed/AshitaAPI.tlb&quot; no_namespace named_guids raw_interfaces_only

Desktop Cleanup – Old Code

Here’s a solution method for another internet challenge from here:
http://www.bright-shadows.net/challenges/programming/xor/tryout.php

I wrote a bot to auto-solve the answer as you have to submit the solution within a specific time, here is how to decrypt the answer:

        private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
        {
            if (webBrowser1.Url.ToString().Contains("http://www.bright-shadows.net/challenges/programming/xor/tryout.php"))
            {

                string strText = webBrowser1.DocumentText.Substring(webBrowser1.DocumentText.IndexOf(''') + 1);
                string strNewText = String.Empty;
                strText = strText.Remove(strText.Length - 1, 1);

                string strXor = "C12W4BERT954";
                int xorStep = 0;

                for (int x = 0; x < strText.Length; x++)
                {
                    if (xorStep >= strXor.Length)
                        xorStep = 0;

                    strNewText += (char)(strText[x] ^ strXor[xorStep]);
                    xorStep++;
                }

                webBrowser1.Navigate("http://www.bright-shadows.net/challenges/programming/xor/solution.php?solution=" + strNewText);
            }
        }

Desktop Cleanup – Old Code

This was some file scanner to log for a pattern inside a file dump.



        /// <summary>
        /// Attempts to compare the given pattern based on its mask to
        /// the current offset in the memory dump.
        /// 
        /// Credits:
        ///     atom0s  - For writing this function in C#
        ///     dom1n1k - Original version of this method. (C++)
        ///     Patrick - Updated; optimized versions. (C++)
        /// </summary>
        /// <param name="nOffset"></param>
        /// <param name="btMemoryDump"></param>
        /// <param name="btPattern"></param>
        /// <param name="strMask"></param>
        /// <returns></returns>
        private bool MaskCheck(int nOffset, byte[] btMemoryDump, byte[] btPattern, string strMask)
        {
            // Loop pattern and compare to memory dump.
            for (int x = 0; x < btPattern.Length; x++)
            {
                // Skip wildcards.
                if (strMask[x] == '?')
                    continue;

                // Compare current offset byte to pattern.
                if ((strMask[x] == 'x') && (btPattern[x] != btMemoryDump[nOffset + x]))
                    return false;
            }

            // Return true if pattern was found.
            return true;
        }

        /// <summary>
        /// Attempts to locate the given pattern inside the given memory dump.
        /// 
        /// Credits:
        ///     atom0s  - For writing this function in C#
        ///     dom1n1k - Original version of this method. (C++)
        ///     Patrick - Updated; optimized versions. (C++)
        /// </summary>
        /// <param name="btMemoryDump"></param>
        /// <param name="btPattern"></param>
        /// <param name="strMask"></param>
        /// <param name="nOffset"></param>
        /// <returns></returns>
        private IntPtr FindPattern(byte[] btMemoryDump, byte[] btPattern, string strMask, int nOffset)
        {
            try
            {
                // Some error checking.
                if (btMemoryDump.Length == 0 || btPattern.Length == 0 || (btPattern.Length != strMask.Length))
                    return IntPtr.Zero;

                // Loop dump and scan for pattern.
                for (int x = 0; x < btMemoryDump.Length; x++)
                {
                    // Check mask and pattern against location.
                    if (MaskCheck(x, btMemoryDump, btPattern, strMask))
                    {
                        // Return found position.
                        return new IntPtr(
                            x + nOffset
                            );
                    }
                }

                // Pattern was not found.
                return IntPtr.Zero;
            }
            catch (Exception ex)
            {
                return IntPtr.Zero;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                // Open and read file.
                BinaryReader binReader = new BinaryReader(new FileStream(
                    Application.StartupPath + "winmine.exe", FileMode.Open, FileAccess.Read));

                // Read file into byte array.
                byte[] btFileBytes = new byte[binReader.BaseStream.Length + 1];
                btFileBytes = binReader.ReadBytes((int)binReader.BaseStream.Length);

                // Close file.
                //
                //      If you wish to do more to the file at this point you will
                //      want to not close it here. You will also need to alter the
                //      access flags on the binReader to allow us to write back to
                //      the file if we wish.
                binReader.Close();

                // Scan array for specific pattern.
                IntPtr ptrOffset = FindPattern(btFileBytes,
                    new byte[] { 0x8b, 0x44, 0x24, 0x04, 0x01, 0x05, 0x94, 0x51, 0x00, 0x01 },
                    "xxxxxxxxxx",
                    0
                    );

                MessageBox.Show(String.Format("Pattern scan returned: {0:X}", ptrOffset.ToInt32()));
            }
            catch (Exception ex)
            {
                MessageBox.Show("Exception caught: nn" + ex.ToString());
            }
        }

Desktop Cleanup – Old Code

This was for some web challenge site. I forget the context of it but I think it had to do with mores code. I also don’t remember the site :/
(Note: I don’t even remember if this was the correct answer lol.)

            byte[] btData = new byte[] 
            {
                0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x11,0x10,0x00,0x00,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x01,0x10,0x11,0x00,0x00,0x01,0x10,0x01,0x01,0x01,0x00,0x01,0x00,0x00,0x11,0x00,0x00,0x10,0x01,0x00,0x00,0x11,0x01,0x00,0x00,0x10,0x01,0x00,0x01,0x00,0x10,0x00,0x00,0x00,0x01,0x00,0x01,0x00,0x11,0x00,0x00,0x10,0x01,0x01,0x00,0x01,0x01,0x01,0x00,0x10,0x01,0x00,0x01,0x10,0x10,0x01,0x01,0x00,0x11,0x01,0x00,0x11,0x10,0x01,0x00,0x10,0x00,0x00,0x00,0x11,0x11,0x00,0x01,0x10,0x10,0x01,0x00,0x11,0x11,0x01,0x10,0x00,0x01,0x01,0x10,0x11,0x00
            };

            int nPos = 0;
            for (int x = 0; x < btData.Length; x++)
            {
                btData[x] ^= 0x2B;

                nPos++;

                if (nPos == 4)
                    nPos = 0;
            }

            nPos = 0;

            string strPass = Encoding.ASCII.GetString(btData);
            strPass = strPass;

Desktop Cleanup – Old Code

Cleaning up my desktop some and deleting some of my old projects. So a few of the next posts will be fairly random bits of code from random projects.

BoringRPG – auto-login bot:

        /// <summary>
        /// Handles logging into the game site.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLogin_Click(object sender, EventArgs e)
        {
            string strUniqueKey = String.Empty;
            foreach (HtmlElement ele in wbBrowser.Document.Forms)
            {
                if (ele.OuterHtml.Contains("method=post action=/login"))
                {
                    Regex regEx = new Regex(@"id=csrf_token name=csrf_token value=([a-zA-Z0-9-]+) type=hidden", RegexOptions.IgnoreCase | RegexOptions.Multiline);
                    Match match = regEx.Match(ele.OuterHtml);
                    if (match.Success == true && match.Length > 0)
                        strUniqueKey = match.Groups[1].Value;
                }
            }

            byte[] btPostData = System.Text.Encoding.UTF8.GetBytes(String.Format("username={0}&password={1}&csrf_token={2}", txtUser.Text, txtPass.Text, strUniqueKey));
            wbBrowser.Navigate("http://www.boringrpg.com/login", "", btPostData, "Content-Type: application/x-www-form-urlencoded");
        }

This was to prove a point to an admin of this game. Given that the login token is random you can still parse it out of the page and automatically login to the game without any interaction. This was written a few months ago so their login method may have changed since then.