Archive for March 18, 2011

SQL Hash Functions

It took me awhile to find how to create MD5 and SHA-1 hashes in SQL Server:

SELECT HASHBYTES(‘MD5’, ‘HASH THIS TEXT’)
SELECT HASHBYTES(‘SHA1’, ‘HASH THIS TEXT’)

Compiling LINQ Queries

The performance of LINQ queries can suffer greatly when an application performs the same query multiple times with different parameters. A good example of this situation occurs when your query is inside of a loop as shown below:

foreach (Company company in CompanyList)
{
     var customers = (from c in context.Customers
               where c.CompanyID == company.ID
               select c); 

     Console.WriteLine(customers.Count);
}

Each iteration of the above loop requires that the query be translated into SQL. This process becomes increasingly costly based on the number of iterations and the complexity of the query.

To increase the performance, .NET’s LINQ implementation allows us to preform compiled queries. Compiled queries require the use of a Generic Function whose implementation contains the LINQ query to execute.

private static Func<DBDataContext, Guid, Customer>
     GetCustomers = CompiledQuery.Compile(
     (DBDataContext context, Guid companyID) =>
               from c in context.Customers
               where c.CompanyID== companyID
               select c);

This function will compile the LINQ query only once. Subsequent calls to the function will reuse the existing compiled query. This greatly increases the performance of subsequent queries and avoids excessive recompilation. You can call the procedure using a standard function call:

foreach (Company company in CompanyList)
{
     var customers = GetCustomers(context, company.ID); 

     Console.WriteLine(customers.Count);
}

For more information: http://msdn.microsoft.com/en-us/library/bb399335.aspx

Quine–McCluskey Software

Anybody who has ever done binary simplification on more than four variables has probably used the Quine-McCluskey method of binary simplification. You also know how time consuming and error prone this process can be by hand:

quine_mccluskey
For a project in my Computer Architecture class I designed software which can perform the steps of binary simplification for you. Hopefully you can find this software as useful as I did!

Download.

CompTIA A+ Study Guide

A quick little study guide I made up nearly 5 years ago for the A+ exam.

Download.

DLL Redirection Tutorial

WARNING: If you do not understand what you are doing you WILL really screw up your system. I take no responsibility for this.

Did you ever need to intercept DLL functions that are part of the Windows API? There are many good reasons for doing this; application debugging, process spying, clocking, etc. Even more powerful than function interception is the ability to modify the response of function calls back to the application. This is precisely what DLL Proxying (also known as DLL Hijacking) allows you to do.

In the following tutorial we are going to intercept Mozilla Firefox’s function call to the Windows Socket Library, “wsock32.dll”. The function is called “gethostbyname”. This function is invoked each time Firefox performs a DNS lookup of a domain name. Once this function is intercepted, our proxy DLL will log each URL that Firefox requests, outputting each request to a log file.

Read more

SSIS: UNC Share Authentication

One common request that I receive while creating SSIS packages for customers is to export some data to a Shared Folder without mapping a drive letter to the share. Usually, I must use different credentials to connect to this share. Below is a code snippet which will connect to the specified share using supplied credentials. Both the share and authentication information are stored as SSIS User Variables.

string strServer = Dts.Variables[“ServerName”].Value.ToString();
string strShare = Dts.Variables[“ServerShare”].Value.ToString();
string strUsername = Dts.Variables[“ServerUsername”].Value.ToString();
string strPassword = Dts.Variables[“ServerPassword”].Value.ToString();
Process pNetDelete = new Process();
pNetDelete.StartInfo.CreateNoWindow = true;
pNetDelete.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
pNetDelete.StartInfo.UseShellExecute = false;
pNetDelete.StartInfo.FileName = “net”;
pNetDelete.StartInfo.Arguments = string.Format(“use /DELETE {0}\
{1} /Y”,  strServer, strShare);
pNetDelete.Start();
pNetDelete.WaitForExit();
Process pNetShare = new Process();
pNetShare.StartInfo.CreateNoWindow = true;
pNetShare.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
pNetShare.StartInfo.UseShellExecute = false;
pNetShare.StartInfo.RedirectStandardError = true;
pNetShare.StartInfo.RedirectStandardOutput = true;
pNetShare.StartInfo.FileName = “net”;
pNetShare.StartInfo.Arguments = string.Format(“use \\{0}\{1} /u:"{2}" "{3}"”,
        strServer, strShare, strUsername, strPassword);
pNetShare.Start();
pNetShare.WaitForExit();
string strError = pNetShare.StandardError.ReadToEnd();
if (pNetShare.ExitCode != 0)
{
    bool fireAgain = false;
    Dts.TaskResult = (int)ScriptResults.Failure;
    Dts.Events.FireInformation(999, “Networking Authentication”,
    strError.Replace(Environment.NewLine, ” “), string.Empty, 0, ref fireAgain);
}
else
    Dts.TaskResult = (int)ScriptResults.Success;

Note: Using this method you will have to store the passwords as clear text variables. I would recommend implementing an encryption function to use with this approach.

Arduino Diecimila!

arduino

Any suggestions for projects?

Fedora – Creating Vanilla Kernels

We all know there are many benefits of building a custom kernel for your linux system. For example, I have reduced my kernel size by almost 50%, optimized it specifically for my Pentium-M chip, and increased my overall system speed. The downside to building your own kernel? TIME. LOTS OF TIME. Building can take almost an hour on my Thinkpad-T40 running at 1.5ghz, and I rarely get it perfect on the first try.

First you need to install development packages, download the source, and decompress it:

su -
yum install ncurses-devel
cd /usr/src
wget http://www.kernel.org/pub/linux/kernel/v2.6/linux-2.6.26.3.tar.bz2
bzip2 -d linux-2.6.26.3.tar.bz2
tar -xvf linux-2.6.23.3.tar
cd linux-2.6.23.3

Next we need to clean the build environment (from any previous [partial] builds and configurations):

make mrproper

Now we can configure the build. (here you can choose what to build into your kernel; objects can either be statically linked or loaded modularly). Another option is to install all of the neccessary files for xconfig, a GUI based kernel configuration utility.

make menuconfig

Finally we build the kernel, install the kernel modules, and install the new kernel (register it with the boot loader):

make
make modules_install
make install

Your new kernel is installed and ready to be used. Reboot your machine, and you should be able to boot into the new kernel by selecting it from the grub boot menu. If you can’t boot, it is usually because of a a kernel panic (you missed something in the configuration). Try, try, and try again until you get it right.

Note about configuration files. The configuration you created was saved in /usr/src/linux…/.config. If you are going to rebuild the source another time, you should backup this file before running make mrproper because that command will wipe out your configuration. The command can then be copied back into the directory before running make menuconfig. This lets you continue making changes where you left off.

Enjoy! I’ll be posting my custom thinkpad configuration on here in a few days for any of you Thinkpad users, along with some tricks for the eeepc.

The Methods of Windows Rootkits

Long ago I wrote my senior research paper which described the ways in which Rootkits are infecting systems and how they can remain hidden from the operating system itself.  Let me know what you think.

http://sourcesecure.net/Articles/Rootkits.pdf

The article has been published in the Journal of Applied Security Research.  If you wish, you can purchase a copy.

SSIS: ConnectionManager To SqlConnection

I spent a decent amount of time trying to figure out how to get the DTS ConnectionManager to give me a SQL Connection. I used the following code to grab a SQL Connection from the connection manager:

SqlConnection sConnection = (SqlConnection)Dts.Connections[“MYDB”].AcquireConnection(null);

We pass NULL into the AquireConnection method to specify that we will not be using an existing transaction. Once the SQLConnection is instantiated, it is usually in the OPEN state and does not require you to call the Open() method it.

Easy enough. Just remember to ALWAYS use this method with an ADO.NET connection. Using anything else will result in an error in an InvalidCastException:

Error: System.InvalidCastException: Unable to cast COM object of type ‘System.__ComObject’ to class type ‘System.Data.SqlClient.SqlConnection’.