Jarred Capellman / Random Texels Manipulating 1s and 0s since 1995

19Feb/120

IIS Fingerprinting with C#

Posted by Jarred Capellman

Continuing my work on my secret project, I've been really intrigued on how nmap's ability to determine the Operating System and Web Server of the host you are scanning. With every test I had done with it, it had always returned exactly what was running, even the more obscure hosts like that of those on IRIX. So I started my research into what would be necessary.

From what I have read so far, you have really two main options for detection. You can either use the return values of an ICMP request or if they are running IIS, using the WebResponse Headers to determine the version of IIS running (Apache will return something like Apache/1.3.23). Digging into ICMP, I realized that would require a good bit more reading so I chose the later for Stage 1 of my detection mechanism.

First off you need to create and return the WebResponse Header:

private string getHttpServerHeader(string ipAddress) {
     WebRequest webRequest = WebRequest.Create("http://" + ipAddress);
     WebResponse webResponse = null;

     string ServerHeader = String.Empty;

     try {
         webResponse = webRequest.GetResponse();
     } catch (WebException ex) {
          if (ex.Response.Headers != null) {
               ServerHeader = ex.Response.Headers["Server"];
          }
     } finally {
          if (webResponse != null) {
               webResponse.Close();
          }
     }

     return ServerHeader;
}

Then using the string result of that function:

private string getWebServerName(string server) {
    // IIS Detection from HTTP.SYS
    if (server.StartsWith("Microsoft-HTTPAPI")) {
        switch(server.Split('/')[1]) {
            case "1.0":
                return "IIS 6.0";
            case "2.0":
                return "IIS 6.0/7.x";
        }
    }

    // IIS Detection not from HTTP.SYS
    if (server.StartsWith("Microsoft-IIS")) {
        return "IIS " + server.Split('/')[1];
    }

    // If no conditional has trapped the Server entry, most likely the Web Server is either Apache or a masked IIS Server
    return server;
}

In reading about Fingerprinting it occurred to me that within IIS itself you can mask it with a custom Server Header like "WS" for instance. I doubt it would prevent a true attack, but it might save a couple bytes per connection over Microsoft-IIS 7.5 :)

18Feb/120

The requested protocol has not been configured into the system, or no implementation for it exists…

Posted by Jarred Capellman

Just got that lovely exception when attempting to do a UDP Socket connection. It's been years since I had done Socket programming and forgot one little gotcha, you have to switch the SocketType to Dgram instead of Stream.

So for instance if you wanted to create a TCP socket object in .NET:

Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

or on UDP:

Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
18Feb/120

Windows Phone 7 ObservableCollection populating a Listbox Asynchronously

Posted by Jarred Capellman

I've been working on a small-ish scale project for the last week now off and on, I'll be announcing it officially probably next week. But anyway, I was running into a problem the main function of the app taking quite a while to process. Given that the performance of the app is entirely dependent on the 3G, 4G, LTE or WiFi connection strength of the phone I wanted to assume the worst when it gets released. Therefore I started looking around for a way to as the the results were returned have the Listbox update asynchronously. Previously with the Windows Phone 7 apps I have developed I simply have had a "Loading" Indicator and a second or two later it would go away, so there really wasn't a need for a "better" solution until now.

Hunting around the WP7 SDK, I came across exactly what I was looking for: Observable Collections. In the "default" solution I had noticed this collection type previously, but always removed it in lieu of a Generic List Collection of whatever object I was using. The only caveat I found when using this approach is that you have to use the Dispatcher to update the collection on the UI Thread.

That being said here's a quick code sample:

In your Button or Page_Load Event set your Listbox ItemSource to the ObservableCollection you're going to populate:

lstBxResults.ItemsSource = App.ViewModel.Results;

Inside your ViewModel loop or asynchronously task (like a WCF service call for instance), wrap the addition of the result inside a Dispatcher Invoke:

System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => {
     Results.Add(new YourObject(e.Result));
});

With those 2 blocks you'll have your Listbox updated as they get added to the ObservableCollection from whatever time consuming task your phone is doing. Hope that helps someone out.

8Feb/120

Getting a picture from Android to a WCF Service

Posted by Jarred Capellman

Had a fun time today getting a picture taken from an Android 2.3.4 HTC Vivid to my Mobile WCF Platform. Oddly enough, I could not find any tutorials on it for Monodroid like there are for MonoTouch. Piecing together several stackoverflow posts, I finally figured it out. Here is a possible solution (most likely not the best):

At the top of your class, add the following:

private string _imageUri;
private ImageView imageView;

private Boolean isMounted {
            get {
                return Android.OS.Environment.ExternalStorageState.Equals(Android.OS.Environment.MediaMounted);
            }
        }

Inside your Button Click Event:

     var uri = ContentResolver.Insert(isMounted ? Android.Provider.MediaStore.Images.Media.ExternalContentUri : Android.Provider.MediaStore.Images.Media.InternalContentUri, new ContentValues());
     _imageUri = uri.ToString();
     var i = new Intent(Android.Provider.MediaStore.ActionImageCapture);
     i.PutExtra(Android.Provider.MediaStore.ExtraOutput, uri);
     StartActivityForResult(i, 0);

Right below your Click Event function (or anywhere inside the Activity Class you're in):

protected override void OnActivityResult(int requestCode, Result resultCode, Intent data) {
            if (resultCode == Result.Ok && requestCode == 0) {
                imageView = FindViewById<ImageView>(Resource.Id.ivThumbnail);
                imageView.DrawingCacheEnabled = true;

                imageView.SetImageURI(Android.Net.Uri.Parse(_imageUri));

                btnUploadImage.Visibility = ViewStates.Visible;
            }
        }

Then inside your "Upload Button Click" function:

Bitmap bitmap = imageView.GetDrawingCache(true);
MemoryStream ms = new MemoryStream();

// Note anything less than 50 will result in very pixelated images from what I've seen
bitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Jpeg, 100, ms);

// At this point set your Byte[] variable/property with ms.ToArray();
// for instance I have a SyncFile object with a FileData Property, so I use
// SyncFile sFile = new SyncFile() { FileData = ms.ToArray(); };

Effectively this code captures a picture, puts it in an ImageView as a thumbnail on the Activity and then upon hitting your Upload Button it converts the image into a Byte Array after compressing it (or not like in my case) and from there call your WCF service upload function.

Hopefully that helped someone out.

6Feb/120

Accessing Activity from TabActivity using Monodroid

Posted by Jarred Capellman

Monodroid gave me headaches this afternoon, trying to mimic the Pivots on Windows Phone 7 on Android using the TabActivity. You would think you access an Activity after attaching it to a TabActivity. Well the answer is you can, but figuring it out on Monodroid will make your hair go gray. After digging through the Java based Android Documentation I finally figured it out. I don't know if this is the right way, but it works:

Declare an enumeration object with each of your tabs:

public enum TABS {
   BasicInformation = 0,
   Detailinformation = 1,
   OptionalInforation = 2
};

Then add an abstract class to each of your Activity Objects:

public abstract class MyDroidActivity : Activity {
   public abstract bool SaveActivity();

   // Any other custom code you had
}
</code>

<strong>Then inside your inherited <code>Activity</code>:</strong>
<code>
public class BasicInfoActivity : MyDroidActivity {
   public override bool SaveActivity() {
         // Error handling to return false if for instance the fields weren't populated
   }
}

Then in your TabActivity Class:

private void SaveAllTabs() {
   TabHost.CurrentTab = (int)TABS.BasicInformation;

   BasicInformation biTab = (BasicInformation)LocalActivityManager.GetActivity(TabHost.CurrentTabTag);

if (!biTab.SaveActivity()) {
return;
}

// And continue with your other Tabs
}

Not the most elegant, but works. The inherited class and enumerations are not necessary, but helps keep things in order, especially if you have a larger application in my opinion.

28Jan/120

Cloud Based Web Rendering?

Posted by Jarred Capellman

Last night when working on my Silicon Graphics Origin 300 and suffering with an old version Mozilla circa 2005 as seen below:

Mozilla 1.7.12 on IRIX

I started wondering, these machines can function as a Web Server, MySQL server, firewall etc especially my Quad R14k Origin 300, yet web browsing is seriously lacking on them. Firefox 2 is available over at nekoware, but that is painfully slow. Granted I don't use my Origin for web browsing, but when I was using a R12k 400mhz Octane as my primary machine a few years ago as I am sure others around the world are doing it was painful. This problem I don't think is solely for those on EOL'd Silicon Graphics machines, but any older piece of hardware that does everything but web browsing decently. Thinking back to the Amazon Silk platform, using less powerful hardware, but a brilliant software platform, Amazon is able to deliver more with less.

The problem arises for the rest of the market because of the diversity of the PC/Workstation market. The way I see it you've got 2 approaches to a "universal" cloud web renderer. You could either:

  1. Write a custom lightweight browser tied to an external WCF/Soap Web Service
  2. Write a packet filter inspector for each platform to intercept requests and return them from a WCF/Soap service either through Firefox Extensions or a lower level implementation, almost like a mini-proxy

Plan A has major problems because you've got various incarnations of Linux, IRIX, Solaris, VMS, Windows etc, all with various levels of Java and .NET/Mono support (if any), so a Java or .NET/Mono implementation is probably not the right choice. Thus you're left trying to make a portable C/C++ application. To cut down on work, I'd probably use a platform independent library like Gsoap to handle the web service calls. But either way the amount of work would be considerable.

Plan B, I've never done anything like before, but I would imagine would be a lot less work than Plan A.

I spent 2 hours this morning playing around with a WCF service and a WPF application doing kind of like Plan A.

jcW3CLOUD in action

But instead of writing my own browser, I simply used the WebBrowser control, which is just Internet Explorer.

The Web Service itself is simply:

public JCW3CLOUDPage renderPage(string URL) {
     using (WebClient wc = new WebClient()) {
          JCW3CLOUDPage page = new JCW3CLOUDPage();

          if (!URL.StartsWith("http://")) {
               URL = "http://" + URL;
          }

          page.HTML = wc.DownloadString(URL);

          return page;
      }
}

It simply makes a web request based on the URL from the client, converts the HTML page to a String object and I pass it into a JCW3CLOUDPage object (which would also contain images, although I did not implement image support).

Client side (ignoring the WPF UI code):

private JCW3CLOUDReference.JCW3CLOUDClient _client = new JCW3CLOUDReference.JCW3CLOUDClient();

var page = _client.renderPage(url);

int request = getUniqueID();

StreamWriter sw = new StreamWriter(System.AppDomain.CurrentDomain.BaseDirectory + request + ".html");
sw.Write(page.HTML);
sw.Close();

wbMain.Navigate(System.AppDomain.CurrentDomain.BaseDirectory + request + ".html");

It simply makes the WCF request based on the property and then returns the HTML and writes it to a temporary HTML file for the WebBrowser control to read from. Nothing special, you'd probably want to add handling for specific pages, images and caching, but this was far more than I wanted to play with. Hopefully it'll help someone get started on something cool. It does not handle requests from with the WebBrowser control, so you would need to override that as well. Otherwise only the initial request would be returned from the "Cloud", but subsequent requests would be made normally.

This project would be way too much for myself to handle, but it did bring up some interesting thoughts:

  1. Handling Cloud based rendering, would keeping images/css/etc stored locally and doing modified date checks on every request be faster than simply pulling down each request fully?
  2. Would the extra costs incurred to the 3G/4G providers make it worthwhile?
  3. Would zipping content and unzipping them outway the processing time on both ends (especially if there was very limited space on the client)
  4. Is there really a need/want for such a product? Who would fund such a project, would it be open source?
23Jan/120

Can do with Telerik’s Kendo

Posted by Jarred Capellman

After playing around with Google Charts and doing some extensive C#/SQL integration with it for a dashboard last summer, I figured I'd give Telerik's Kendo a shot. If you're not familiar with Telerik, they produce very useful controls for WinForm, WPF, WP7 and ASP.NET controls (in addition to many others). If you do .NET programming, their product will save you time and money guaranteed. That being said, I started work on the first module for jcDAL last night and wanted to add some cool bar graphs to the web interface for the analyzer. About 15 minutes of reading through one of their examples I had data coming over a WCF service into the Kendo API to display this:

jcDBAnalyzer Screengrab showcasing Kendo

So far so good, I'll report back with any issues, but so far I am very pleased. A lot of the headaches I had with Google Charts I haven't had yet (+1 for Telerik).

18Jan/120

AMP + C# = what I wanted to see for years

Posted by Jarred Capellman

I was reading about AMP the other night, basically a light weight C++ wrapper that is used to offload tasks to your GPU. I was going to brush off my C++ skills tonight, but luckily I don't have to after reading this article. WinRT makes using C++ libraries a breeze, finally you don't have to use p/invoke. I'll definitely be playing around with this as soon as my Visual Studio 11 installation issues get resolved.

A word to the wise, if you're installing Windows 8, install it with the Developer Tools. I made the mistake of installing the non-developer tools Windows 8 Developer Preview, which doesn't install the necessary SDK for C++ compiling. If you're only doing C#, I had no trouble programming/compiling WPF and WCF apps.

15Jan/120

jcBENCH Android Port Released

Posted by Jarred Capellman

After some additional work getting used to the XAML-ish layout I'm done with the initial jcBENCH Android port. You can download it from here. You will need Android 2.2 or higher for it to run.

jcBENCH Android

I've only tested this on a Dual 1.2ghz HTC Vivid. However, the results were interesting. Comparing single-threaded and multi-threaded operations was curious. Running it in multi-threaded mode was actually 3 times slower. I'm not sure if the way the Task Parallel Library was implemented on Monodroid was done poorly or if there is a bug in the detection for how many cores/cpus there are inside the Mono implementation or not, but something isn't right. Single threaded versus my HTC Titan 1.5ghz SnapDragon it lost out by ~23%. Which makes sense, 300mhz difference or 20% comparing single cores to each other.

All that being said I'm content with jcBENCH for the moment until I hear feedback or come up with more features to add.

14Jan/120

IronPython + PLINQ?

Posted by Jarred Capellman

Spent the afternoon reading IronPython documentation and finally got a chance to play with it a bit. I have to hand it to Microsoft for making it extremely easy:

var ipy = Python.CreateRuntime();
dynamic pyTest = ipy.UseFile("test.py");

Only 2 lines of code to have access to a python script. For me this opens new doors for scripting operations I still typically write in PHP because of the simplicity of opening notepad and pushing it out to an IIS server running PHP. Now I can write a few line C# app with an interface to run whichever script I wish to run.

Being curious about performance, I ported jcBENCH to use IronPython. To put it simply, the math operations pale in comparison to native C# math operations. The actual overhead in creating the Python Interpreter was negligible if anyone was curious even on an AMD C-50 (Dual 1ghz) Netbook with a OCZ Vertex 2 SSD.

Porting it did bring an interesting idea, this could work for a workflow process. The ability to process multiple workflows utilizing PLINQ, but with the flexibility to adjust the logic in script and not in the C# code.

11Jan/120

Other jcBENCH news and jcDAL

Posted by Jarred Capellman

After some more thought about jcBENCH and what its real purpose was I am going to drop the Solaris and IRIX ports. Solaris has a Mono port, but I only have Sun Blade 100 which has a single cpu. Not expecting a ton of performance from that. IRIX on the other hand, I have a Quad R14k 500 Origin 300, but no port of Mono exists. So I could port it to Java, but then you really couldn't compare benchmarks between the Mono/.NET versions. I am about 50% done with the Android port and am just waiting for the OpenSuse 12.1 compatible MonoDevelop release so I can get started on the Linux Port.

After those 2 ports are completed I am thinking of starting something entirely new that I have been thinking about the last couple years. Those that deal with a SQL database and write a data layer for his or her .NET project, know the shortcomings or doing either:

  1. Using an ADO.NET Entity Model, adding your Tables, Views and Stored Procedures and then use that as is or extend it with some business logic
  2. Use an all custom data layer using the base DataTable, DataRows etc, wrap your objects with partial classes and create a "factory"

Both approaches have their pros and cons, the first takes a lot of less time, but you also have a lot less control and could be costly with all of the overhead. Both however will eventually fall apart down the road. The reason, they were built for one audience and one production server or servers. How many times have you gone to your IT Manager and asked for a new Database server because it was quicker then really go back to the architecture of your data layer. As time goes on, this could happen over and over again. I have personally witnessed such an event. A system was designed and built for around 50 internal users, on a single cpu web server and a dual Xeon database server. Over 5 years later, the code has remained the same yet it's been moved to 6 different servers with ever increasing speed.

Times have changed and will continue to change, workloads vary from day to day, servers are swapped in and out, so my solution, an adaptive, dynamic data layer. One that profiles itself and uses that data to analyze the server to use either single threaded LINQ queries or PLINQ queries if the added overhead of using PLINQ would out way the time it would take only using one cpu. In addition using Microsoft's AppFabric to cache the commonly used intensive queries that maybe only get run once an hour and the data doesn't change for 24. This doesn't come without a price of course, having only architected this model in my head, I can't say for certain how much overhead the profiling will be. Over the next couple months, I'll be developing this so stay tuned. jcBENCH as you might have guessed was kind of a early test scenario of testing various platforms and how they handled multi-threaded tasks of varying intensity.

3Jan/120

jcBENCH Released

Posted by Jarred Capellman

It's been a very long time since I released something, so without further adieu, I present jcBENCH. It's a floating point CPU benchmark. Down the road I hope to add further tests, this was just something I wrote on the airplane coming back from San Francisco.

You'll need to have .NET 4 installed, if you don't have it, click here. Or you can get it from Windows Update.

Click here to download the latest version. I'll make an installer in a few days, just unzip it somewhere on your machine and run.

Upon running it, the results get automatically uploaded to my server, a results page will be created shortly.

13Sep/110

WCF + ASP.NET + AppFabric (Velocity) Caching == Awesome

Posted by Jarred Capellman

Just getting started on a WCF Service that is going to be handling all of the business logic for the company I work for. With the amount of data, caching was a necessity. Was playing around with Membase last week, couldn't quite get it to work properly and then started yesterday afternoon with AppFabric. Microsoft's own answer to caching (among other things). It installs pretty easily, the built in IIS extensions are very cool. However the setup isn't for the faint of heart. To sum it up:

  1. Install AppFabric on your SQL Server with all of the options
  2. Then install AppFabric on your Web Server and create your WCF and ASP.NET sites
  3. From the PowerShell Cache console type: New-Cache (Where is the name you want to call it, so it could be: New-Cache RandomTexels
  4. Verify it got created by: Get-Cache If you don't see it or get an error make sure the AppFabric Cache Service is running, open up the Run Window (Windows Key + R) and type: services.msc. It should be one of the top items depending on your setup.
  5. After configuring your other server for .NET 4, usual web site permissions and settings in IIS then do this command: Grant-CacheAllowedClientAccount DOMAIN\WEBSERVER$ Replace DOMAIN with your domain name (ie MOJO) and WEBSERVER with the physical name of your webserver. So for instance: Grant-CacheAllowedClientAccount MOJO\BIGWS$ for a domain callled MOJO and a WebServer called BIGWS.

There's plenty of code examples o,,ut there, but as I create the architecture for this WCF I'll discuss my findings.

Tagged as: , , , No Comments
12Jun/110

Fun with WPF…

Posted by Jarred Capellman

I've diving into WPF the last couple of weeks focusing on the 2D animation elements, but today I started on the 3D aspect.  Easy enough, it's accelerated in Direct 3D so I could probably throw a ton of polygons/textures at it versus the old GDI+ method I'm used to.  I added in 3D support to my new engine I started to write a few weeks ago this morning.  It didn't take much, just had to re-learn the 3D thought process as far as programming is concerned since it had been a while since I had done 3D graphics programming. Ran into a small hickup though when rendering out some 3D Terrain:

Very Bland Looking Terrain

It was almost as if the texture coordinates from 3ds max didn't carry over to the xaml file. After opening 3ds max 2011 back up, I noticed I hadn't created a UV Map for it, I was simply using the standard 3ds max texture coordinates. Voilla...

Better looking Terrain

Not bad, but not 2011 good either.  512x512 textures were acceptable 5-6 years ago, but 2048x2048 is the new "standard" from what I gather. Googling around a bit, found a 2048x2048 uncompressed texture, applied it over the terrain...

Much better terrain

It looks kinda weird with the trees not parallaxing, but the level of detail is much improved.  I still need to add in support for detail texturing, but it's a good base.

Tagged as: , No Comments