July 31, 2010

Using DateTime parameters with ado.net

Filed under: .NET — Kevmar @ 6:03 pm

When I add parameters to a command object, I like to use the new DBParameter(string name, object value) constructor.  It is simple and it works.  It can figure out the data type by the value object most of the time.  I run into issues with DateTime objects doing it this way.  I never can remember the trick I use to fix it eithe

Today I was doing some ADO.net with an access database and fought with this issue for a while because I forgot about it.  I wanted to blame it on Access.  I don’t do data connections to Access that often so little things in my syntax mess me up.  After I remembered this was an issue, I was able to find a solution.

When I add the DateTime param I call its ToString() method so the string value gets set in the parameter.  Then I set the DbType = DbType.DateTime for that parameter.  So I have code that looks like this.

command.Parameters.Add(new OleDbParameter("@notes", notes));
command.Parameters.Add(new OleDbParameter("@eventDate", eventDate.ToString());
command.Parameters["@eventDate"].DbType = DbType.DateTime;

July 28, 2010

My redirected favorites are broken in IE

Filed under: Error — Kevmar @ 3:08 pm

I ran into this issue where my redirected favorites in IE 8 broke.  They broke bad for everyone.  IE would list nothing in the favorites drop down and the links bar was also empty.  Attempts to add a new favorite would fail.  I could not even create a favorites folder from within the favorites manager.

This started out very intermittent.  The same user could go from one computer to another. It would work on some and not on others.  It would work for our IT group every time.  The first common connection I made was the use of offline files.  We don’t like offline files. We find it causes us nothing but problems.  I will save those for another time.  I did find that machines that had offline files off had this issue.  If offline files are turned on, the problem went away.

We recently started over with our group policies as we rolled out Server 2008 and Windows 7.  We used the new folder redirection feature to redirect documents to the home folder and set favorites to fallow the home folder.  By default this enabled offline files to sync those locations.  There was a registry setting that disabled this default behavior that we later found and set.  But this still left offline files running.  It may be on by default.  I don’t remember any more.

Because offline files was on for most people this problem was fairly rare.  We finally had enough problems with offline files that we decided to kill it for everyone.  The resulting problem was everyone lost favorites.   So I set out to find a solution.  The better I wrapped my head around this the stranger it felt.

The other important detail was that our network administrators did not have this problem.  So that led me to permissions.  Our users only have security to home folders, not the folder structure under them.  Before we would map the UNC path of the profile to the N: drive.  Then we would point everything to N: including documents.  The new way to do it in group policy wants to use the UNC path as the redirection point.  That is introducing issues with some apps.  IE favorites included.

The problem goes away if I give the user full access all the way from the root of the share to the home folder location.  This is a bit much but it does work.  With this information in mind, I set out to see the minimum permissions that I needed to grant the users for this to work.  If I get the user just read access to the folders it worked.  Here is the list of minimum permissions that those sub folders needed to have.

List folder / read data
Read attributes
Read permissions

That looked like a simple enough solution but something still didn’t feel right.  If that is what the issues was, then I should have been able to find lots of other people with this problem.  For as much as I searched for this and as little as I was able to find, I knew something else was strange.  After some more experiments, I narrowed this down to be a very rare and unusual bug.

I found that I only had to set those permissions on the folder under the home folder.  None of the other parent folders needed any permissions at all.

I also found that the depth of the home folder made a difference.  If I moved the users home folder up just one directory location (with out any special permissions) the problem went away.  I even created a new folder structure of the same depth on the same root share to test this out.  It had the same results.

I also found that not using DFS (distributed file system) would also make this problem go away.  Same folder depth but not located on a dfs share.

So if we left Offline Files on, or used a folder structure that was one folder shallower, or did not use DFS, or did not redirect favorites with the server 2008 redirection policy, or did not use IE, then we never would have had this problem. I can see why it was so hard for me to find information on this.  I hope that the next person dealing with this is able to find this post and something in here will give them a glue to solve whatever issue they have.  I expect I am missing some simple detail but I was able to get it working in the end.

If you wanted to know how deep our home folders are, they UNC path looks something like this:  \\domain.name\rootshare\home\depart\username

July 12, 2010

Network Adapters with Powershell

Filed under: Script — Tags: — Kevmar @ 6:26 am

One of the first things I discovered with Windows 7 was that they moved access to network adapters. I had some quick way to get to it and now I need to visit a few more screens. Today a coworker was talking about that same issue. He wanted a faster way to get to it. My response was, “I bet we can do that with Powershell”. The most common reason we end up looking at network adapters is to change ip settings to static or to DHCP. The only other things we do can be done with IPConfig. So I set out to write a little powershell that would give a computer a static IP address.

This turned out to be very simple with the Win32_NetworkAdapterConfiguration WMI object. I can use it to manage everything that was done with the GUI. The usual way we set static addresses is by first taking the dhcp address, entering it as static to the computer, then go into the dhcp server and exclude that address.

Set-NetworkStatic.ps1

$NICs = Get-WMIObject Win32_NetworkAdapterConfiguration | where{$_.IPEnabled -eq “TRUE”}
Foreach($NIC in $NICs) {

    $IP =$NIC.IPAddress -match "\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b"

    $Subnet = $NIC.IPSubnet -match "\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b"

    $Gateway = $NIC.DefaultIPGateway
    $DNSServers = $NIC.DNSServerSearchOrder
    $Domain = $NIC.DNSDomain

    $NIC.EnableStatic($IP, $Subnet)
    $NIC.SetGateways($Gateway)
    $NIC.SetDNSServerSearchOrder($DNSServers)
    $NIC.SetDynamicDNSRegistration(“TRUE”)
    $NIC.SetDNSDomain($Domain)
}

And then a second script to set it back to DHCP.

Set-NetworkDHCP.ps1

$NICs = Get-WMIObject Win32_NetworkAdapterConfiguration | where{$_.IPEnabled -eq “TRUE”}
Foreach($NIC in $NICs) {

    $NIC.EnableDHCP()
    $NIC.SetDNSServerSearchOrder()
}

July 8, 2010

Chaocipher: the algorithm in C#

Filed under: .NET — Tags: , — Kevmar @ 11:47 pm

Here is the Chaocipher implementation in C#. Its the exact same logic that I used in my PowerShell script I posted a few days ago.

//Kevin Marquette
// www.ithinkincode.com

   public string GetChaocipher(string message, string leftAlphabet, string rightAlphabet, bool encrypt)
        {
            Regex messageTest = new Regex( "^[A-Z]+");
            Regex alphaTest = new Regex( "^[A-Z]{26}");
            //Validate Input
            if( !messageTest.IsMatch(message))
            {
                return "Message is not Valid";
            }
            if(!alphaTest.IsMatch( leftAlphabet))
            {
                return "Left is not Valid";
            }

            if(!alphaTest.IsMatch( rightAlphabet))
            {
                return "Right is not Valid";
            }

            // I want to use a linked list to manage the rotations
            List left = new List();
            List right = new List();

            // convert left and right to linked lists
            for(int i=0;i < 26; i++)
            {
                left.Add(leftAlphabet[i]);
                right.Add(rightAlphabet[i]);
            }

            string cipher = "";

            //for each letter in the message
            for(int index=0; index != message.Length; index++)
            {
                print(left);
                //Find the plain text letter and shift it to the front
                while((message[index] != right[0] && encrypt == true) || (message[index] != left[0] && encrypt != true) )
                    {
                    right.Add(right[0]); right.RemoveAt(0); // Shift left
                    left.Add(left[0]);    left.RemoveAt(0); // Shift Left
                    }
                if(encrypt == true)
                    {cipher += left[0];}
                else
                    {cipher += right[0];}

                // move from zenith + 1 to nadar (zenith + 13) position
                left.Insert(14,left[1]);
                left.RemoveAt(1);

                // rotate right one more letter
                right.Add(right[0]);   right.RemoveAt(0);  //Shift left

                // move from zenith + 2 to nadar (zenith + 13) position
                right.Insert(14,right[2]);
                right.RemoveAt(2);

            }
            return cipher;
        }

July 7, 2010

Chaocipher: Interactive Web Form

Filed under: Uncategorized — Kevmar @ 7:06 pm

After my quick implementation of Chaocipher in PowerShell, I decided to redo it in JavaScript as an interactive form.  My JavaScript was a bit more rusty than I expected.  The code is not near as clean as I would have liked it to be.

Message:
Left Alpha:
Right Alpha:
Encrypt:
Results:

July 5, 2010

Chaocipher: the algorithm in PowerShell

Filed under: Script — Tags: — Kevmar @ 5:24 pm

Cypher Mysteries just revealed a old substitution cypher from 1918. Here is a detailed example on how to work the method by hand.  After I read both of those sites I decided to flesh out the code for it in PowerShell.  This turned out to be very easy to put to code.  Review the linked example then take a look at my PowerShell sample.

I used ArrayLists to hold the left and right alphabets. When I thought about the circular nature and shifting of the alphabets, linked lists where the first things to come to mind. I think this sample can easily be translated in to other languages.

# Kevin Marquette
# www.ithinkincode.com
$cipher = ""

for($index=0; $index -ne $message.length;$index++)
{
    # Find the plain text letter and shift it to the front
    while($message[$index] -ne $right[0])
        {
        $right.Add($right[0]); $right.removeat(0); # Shift left
        $left.add($left[0]);    $left.removeat(0); # Shift Left
        }
    $cipher += $left[0];   

    # move from zenith + 1 to nadar (zenith + 13) position
    $left.insert(14,$left[1]);
    $left.removeat(1);

    # rotate right one more letter
    $right.Add($right[0]);   $right.removeat(0);  #Shift left

    # move from zenith + 2 to nadar (zenith + 13) position
    $right.insert(14,$right[2]);
    $right.removeat(2);
}

Write-Host $cipher;

Thats the base implementation of the Chaocipher. Here is my full implementation that also includes decryption.

# Kevin Marquette
# www.ithinkincode.com

function get-chaocipher([string]$message = "WELLDONEISBETTERTHANWELLSAID", [string]$leftalphabet = "HXUCZVAMDSLKPEFJRIGTWOBNYQ", [string]$rightalphabet="PTLNBQDEOYSFAVZKGJRIHWXUMC", [bool]$encrypt=1)
{
Write-Host "Message: $message";
Write-Host "Left: $leftalphabet";
Write-Host "Right: $rightalphabet";
Write-Host "Encrypt: $encrypt";

# Validate Input
if($message -cmatch "^[A-Z]+$")
    {Write-Host "Message is Valid";}
else
    {
    Write-Host "Message is not Valid";
    return;
    }
if($leftalphabet -cmatch "^[A-Z]{26}$")
    {Write-Host "Left is Valid";}
else
    {
    Write-Host "Left is not Valid";
    return;
    }
if($rightalphabet -cmatch "^[A-Z]{26}$")
    {Write-Host "Right is Valid";}
else
    {
    Write-Host "Right is not Valid";
    return;
    }

# I want to use a linked list to manage the rotations
$left = New-Object System.Collections.ArrayList
$right = New-Object System.Collections.ArrayList
$cipher = New-Object System.Collections.ArrayList

# convert left and right to linked lists
for($i=0;$i -le 25; $i++)
    {
        $left.add($leftalphabet[$i]);
        $right.add($rightalphabet[$i]);
    }

$cipher = ""

#for each letter in the message
for($index=0; $index -ne $message.length;$index++)
{
    # Find the plain text letter and shift it to the front
    while(($message[$index] -ne $right[0] -and $encrypt -eq 1) -or ($message[$index] -ne $left[0] -and $encrypt -ne 1) )
        {
        $right.Add($right[0]); $right.removeat(0); # Shift left
        $left.add($left[0]);    $left.removeat(0); # Shift Left
        }
    if($encrypt -eq 1)
        {$cipher += $left[0];}
    else
        {$cipher += $right[0];}

    # move from zenith + 1 to nadar (zenith + 13) position
    $left.insert(14,$left[1]);
    $left.removeat(1);

    # rotate right one more letter
    $right.Add($right[0]);   $right.removeat(0);  #Shift left

    # move from zenith + 2 to nadar (zenith + 13) position
    $right.insert(14,$right[2]);
    $right.removeat(2);
}
Write-Host $cipher;
}

#encrypt
get-chaocipher "WELLDONEISBETTERTHANWELLSAID" "HXUCZVAMDSLKPEFJRIGTWOBNYQ" "PTLNBQDEOYSFAVZKGJRIHWXUMC" 1
#decrypt
get-chaocipher "OAHQHCNYNXTSZJRRHJBYHQKSOUJY" "HXUCZVAMDSLKPEFJRIGTWOBNYQ" "PTLNBQDEOYSFAVZKGJRIHWXUMC" 0

Decryption is as simple as checking from the other list. All the other steps are the same.

July 4, 2010

Sever 2008 UAC and Folder Security Issues

Filed under: Error,Servers,Thoughts — Tags: — Kevmar @ 10:01 am

I ran into an interesting issue on our 2008 file server. When I was logged in as myself I did not have access to several folders that used for various shares. I was given an prompt that would allow me to gain access to them. If I continued, it would modify the permissions on every object in that folder adding my name to everything. But when I checked the permissions, the other groups (that I was a member of) were still on the folder.

The thing that made this stranger was my access was correct if I connected from a share on another computer. This was only a problem if I was on the physical server. I also discovered that the domain administrator account did not have this issue. It looked like server 2008 was not resolving group membership on folders. Domain Admins had full control of the folder and I was a member of that group.

For a while I would just login as the domain admin. After a little hunting I found that UAC was causing the issues. I didn’t even consider User Account Control because of the way it mucked up the permissions. The solution is to disable UAC and reboot. Once I did that, the problem went away.

I feel strongly that UAC is bugged in the way it handles this situation. When UAC is off and you click on a folder, your group permissions are checked and you are granted access. The system does not automatically add your name to the folder you try to open. Your group membership is enough to grant you access. That is how it should be. Now in the situation where UAC is turned on, you are prompted to grant yourself permissions. I don’t mind that it has to prompt you, but the action it takes after the prompt is the problem. It should check the group membership and see that you have access then let you go on. But what it does instead is give you full permissions directly even when your group membership is correct.

Who would think that this is the desired operation? I would expect most people that discover that this happened, the first thing they do is remove themselves from the security permissions. The other problem that I ran into what waiting for it to propagate those permissions. This can take a very long time when its on the root share for all your users.

This functionality also acts differently from other situations where UAC is protecting the system. If I try to do operations on the program files folder on a Windows 7 computer, I am prompted to make my changes but the underlying security is never changed.

UAC is one of those features that I want to embrace but it keeps shooting its self in the foot.

June 26, 2010

Signing Powershell and Applications the easy way

Filed under: Script — Tags: , — Kevmar @ 4:19 pm

My last post showed you an easy way to sign windows scripting host files. The same thing is available for Powershell and other executables. I found a lot of complicated way to sign applications before I figured out that Powershell can sign them too. This still assumes you have a Code Singing Cert already. Here is my Powershell signing script

$cert = @(gci cert:\currentuser\my -CodeSigningCert )[0]
Set-AuthenticodeSignature $args[0] $cert

I save that in a file called SignScript.ps1 on my computer where my cert is installed into the local store. The script I want signed is passed as $args[0] from the command line like this:

PS C:\> .\SignScript.ps1 myScript.ps1
PS C:\> .\SignScript.ps1 myApp.exe

I take this one step further by adding a sign option on the right click context menu from explorer. This is very easy to set up if you get it working from the command line. From regedit, open HKEY_CLASS_ROOT, and find Microsoft.PowerShellScript.1 (and exefile). Under the key called Shell, add a key called “Sign”. This is what will show up in the context menu. Under the key you added, add a new key called “command”. Then set the default value on that “command” key to match this .reg file.

[HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\Shell\Sign\Command]
@="\"C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe\" \"-file\" \"C:\\Scratch\\Scripts\\SignScript.ps1\" \"%1\""

[HKEY_CLASSES_ROOT\exefile\shell\Sign\command]
@="\"C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe\" \"-file\" \"C:\\Scratch\\Scripts\\SignScript.ps1\" \"%1\""

Now when you right click a .ps1 or .exe file, you can digitally sign it.

Signing scripts the easy way: VBS, JS, WScript, CScript

Filed under: Script,Uncategorized — Tags: — Kevmar @ 4:06 pm

If you have a code signing cert, it is very easy to sign scripts.  Here is the VBS script I use to sign them with.

Set objSigner = WScript.CreateObject("Scripting.Signer")
objSigner.SignFile WScript.Arguments(0), "Kevin Marquette"

I save that in a file called SignScript.vbs on my computer where my cert is installed into the local store. My cert is named “Kevin Marquette” and the script I want signed is passed as arg0 from the command line like this:

c:\> SignScript myScript.vbs

I take this one step further by adding a sign option on the right click context menu from explorer. This is very easy to set up if you get it working from the command line. From regedit, open HKEY_CLASS_ROOT, and find VBSFile (or JSFile). Under the key called Shell, add a key called “Sign”. This is what will show up in the context menu. Under the key you added, add a new key called “command”. Then set the default value on that “command” key to match this .reg file.

[HKEY_CLASSES_ROOT\VBSFile\Shell\Sign\command]
@="\"c:\\windows\\System32\\CScript.exe\" C:\\Scripts\\SignScript.vbs \"%1\""

Now when you right click a .vbs file, you can sign it.

June 1, 2010

MSI Deployment Rate.

Filed under: Uncategorized — Kevmar @ 9:34 am

How fast do MSI installs get deployed out to the network?  Lets take a look at the process.  You build a new MSI and assign it to every computer in your network with AD.  The next time the computer refreshes its policies it will now about the MSI to be installed.  The MSI will be installed when the computer gets rebooted.  If the computer refreshes the policy on a reboot then it will go ahead and install the MSI.  So the simple answer is on the next reboot.

But when is the next reboot?  In a large network you have lots of different users that have different habits.  Some power off at night and others just lock the computer.  I decided that knowing how fast my network gets MSI installed loaded would be a good piece of information to have.  So I set out to test it.

I was just about to deploy an asset tracking solution using MSI to all of our computers.  Once the client was installed on the computer it would check in to report its information.  This is what gave me the idea.  I could tell exactly when every computer reported in.  So I pushed out the MSI and started tracking the numbers.

We are currently having issues with our Windows 7 computers pulling policies correctly so I tracked Win7 and WinXP numbers.  It is a strange issue that I will save for another time.  I collected the data on business days from 5/20/2010 to 6/1/2010 for a total of 8 samples.  I had a total of 320 computers report in and that was in the range of 300-330 that I expected.  I did about 15 installs by hand verifying and testing the MSI.

The next day after I started deployment, I had 35% of the computers load the software.  I would get fewer and fewer reports each day after that.

This chart shows how many computers loaded the MSI over time.  Point 2 is the first day after I deployed the MSI.  The large jump at point 8 was the result of me sending out a computer reboot command.

This is the rate of deployment.  How many were deployed each day.  Again you can see the network wide reboot on data point 8.  The installs were getting slower and slower.  Performing the reboot after 7 days picked up 26% of the computers.

The first night picked up 35% of the computers. The next 2 days picked up another 24%. Days 4,5, and 6 picked up 13%.  The 26% required me to reboot them after 7 days. I expect that the last 26% were in our clinics and labs.  This is good information to know.  Next time I will start with the reboot and see how long the rest take.

Your results will vary.

Older Posts »

Powered by WordPress