How to remove iexplor.vbs trojan

virus-vert-psdToday, after a long period of silence, I write back to my blog to talk about a virus that spread year ago, but re-appeared today in a new variant. The virus is not detected by anti virus like Kaspersky or Avast.

The virus spreads over usb dongle, mainly in copy centers. As a note, I would like to inform you that copy center is the worst place to bring a usb key in the world. Plugging your usb dongle in a copy center PC is just like licking a metro bar. The solution is to host file on a public drive on the web without registration required (you don’t want to loose your credential when loggin-in with them in the copy center)

The virus proxy the files copied on the disk. When you’ll copy a file, they will be marked as hidden and shortcut will be created. The shortcut point to the VBS virus and will then open your files, that’s the way he spreads on the host machine.

Once in place, if you delete the vbs file, he will come back. We’ll see how to identify the process responsible for that, killing it and then cleaning the key.

  1. First, download sysinternal suite from here.
  2. Then, unzip and launch procmon.
  3. Once started, go to your usb key and delete the folder containing the vbs script.
    If you don’t see it and only see the shortcuts, you’ll need to enable “view hiddent files” and disable “hide system protected files” in the explorer paramaters.
  4. Once deleted, wait for the file to re-appear.
  5. Go back to procmon and input the shortcut CTRL+E. That will stop the capture
  6. Now search (CTRL+F) for the name of the vbs, in our case iexplor, but may differ.
  7. Write the process id of the entry found in the first columns
  8. Launch procexp from sysinternals and sort the process by id
  9. Kill the process you’ve found with procmon (DELETE)
  10. Now you can delete the files on the usb key  and clean the virus.

 

Integrate Syncrosoft Metro Studio 2 in your development process.

syncmslogoAs a lot of WPF developer, I love the free Metro Studio from Synchrosoft. Most of my WPF projects, professional or not, use it at a moment or another. But, out of the box, the integration between Metro Studio and Visual Studio is not great. At the end of this article you’ll be able to regenerate dynamically your resource file on project build. Also you’ll be able to do this on a build server as we don’t need Metro Studio to be installed on the build machine.

The issue

Here’s a usual situation:

  • Create a project in Metro Studio and pick icons.
  • Configure some basic styling stuff.
  • Copy paste the generated output to visual studio.
  • Adapt the templates to match the needs or just extract the path information
  • Tweak the styling.

There’s a lot of issues when working that way. If you want theming, if you want to add/remove/update icons, if you want to change the overall style… The generate xaml feature of MetroStudio is nice but it’s a real trap too. In fact, the only useful information from MetroStudio are the path. So our goal will be to retrieve them and manage on our side all the styling.

The solution

First, let’s take a look at how Metro Studio manage his project. Here’s a “.metrop” xml structure :

<IconProject Version="2.0" Name="LogiX">
    <Icon Name="AddApplicationPath" GroupName="Office" Data="M21.686602,15.029519C20.406802,... And so on" HasCharacterMap="false" IsDirty="false" ExportCommand="MetroGraphicsPackage.IconCommand">
        <Settings FontFamily="Webdings" Character=">" 
				  IconBrush="#FFFFFFFF" 
				  FlipCommand="MetroGraphicsPackage.IconCommand" 
				  FlipX="1" 
				  FlipY="1" 
				  ContentHeight="26" 
				  ContentWidth="26" 
				  SizeIndex="4" 
				  MainWidth="48" 
				  Angle="0" 
				  MainHeight="48" 
				  Padding="11" 
				  CustomSize="48" 
				  MaximumPadding="15" 
				  BackgroundBrush="#FF67C2EA" 
				  IconShape="Square" 
				  IsBackgroundVisible="true" />
    </Icon>
</IconProject> 

A metrop file is a basic xml file containing all the informations about an icon. Including the path data.

To retrieve them and produce a resource dictionary with them decided to use XSLT.

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" version="2.0">
	<xsl:template match="/">
		<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:system="clr-namespace:System;assembly=mscorlib">
			<xsl:for-each select="/IconProject/Icon">
				<system:String>
					<xsl:attribute name="x:Key">
						<xsl:value-of select="@Name"/>
					</xsl:attribute>
					<xsl:value-of select="@Data" />
				</system:String>
			</xsl:for-each>
		</ResourceDictionary>
	</xsl:template>
</xsl:stylesheet>

The path is stored in a string object, much more flexible than in a path. If you want to generate entire controls or use other attribute from the metrop file, you just need to adapt the xslt file. But you should be careful IMHO. If you decide to generate more complex code with the xslt you’ll need someone to maintain it too in the future. As it’s a WPF application the other persons working on the project will be able to maintain the styles using the path in string but not always able to maintain complex XLST sheets. Also it can be hard to debug and the debug can quickly require additional tools like Oxygen XML Developer or similar.

To apply the stylesheet to the metrop file I use msxsl.exe, a lightweight (25kb) tool from Microsoft allowing you to apply xslt to xml file. And to call the tool I simply add the following prebuild event line to execute it :

"$(ProjectDir)/Resources/Tools/msxsl.exe"
"$(ProjectDir)/Resources/Icons/LogiX.metrop"
"$(ProjectDir)/Resources/Icons/Generate.xslt"
-o "$(ProjectDir)/Resources/Icons/IconsPath.xaml"

In a generic way :

"<Path to msxsl.exe>" "<Metrop file path>" "<Xslt file path>" -o "<Output xaml file>"

Now, everytime you do modification in metro studio you’ll just need to rebuild the project.

Also don’t forget to include your output xaml file in your solution. For my part I usually also include the metrop file and add the generated xaml as a dependent generated item. To do this simply edit your csproj file like the following. For the parent metrop file, just include it as none action (in my case located in “Resources\Icons\LogiX.metrop”):

<None Include="Resources\Icons\LogiX.metrop" />

And here’s the entry for the generated xaml page, changes are in Bold. Basically we say to visual studio that this is an autogenerated item and the parent is LogiX.metrop :

<Page Include="Resources\Icons\IconsPath.xaml">
      <SubType>Designer</SubType>
      <AutoGen>True</AutoGen>
      <DependentUpon>LogiX.metrop</DependentUpon>
      <Generator>MSBuild:Compile</Generator>
</Page>

And here’s the result in the solution explorer:

screendepautogen

Also, to complete this easy integration, you can add metrop studio as a custom editor for the metrop files, allowing you to directly open the project from visual studio. Right click on the metrop file, “Open With…”, “Add”, browse MetroStudio executable, press “Ok”, now select the newly created item in the list and press “Set as default” and then Ok, now when you double click metrop files they’re opened with MetroStudio.

Example

Here’s a template for a button. Basically the button is filled with the icon. To use it, you’ll need to set the style and the path as the content of the button.


<Style TargetType="{x:Type Button}" x:Key="MetroIconButtonStyle">
	<Setter Property="Template">
		<Setter.Value>
			<ControlTemplate TargetType="Button">
				<Viewbox>
					<Grid Width="48" Height="48">
						<Grid>
							<Rectangle Fill="{DynamicResource IconBackground}" x:Name="bg"/>
						</Grid>
						<ContentPresenter x:Name="contentPresenter" Width="30" Height="30" />
					</Grid>
				</Viewbox>
				<ControlTemplate.Triggers>
					<Trigger Property="IsMouseOver" Value="True">
						<Setter TargetName="contentPresenter" Property="Opacity" Value="1" />
						<Setter TargetName="bg" Property="Opacity" Value=".7" />
						<Setter TargetName="bg" Property="Fill" Value="{DynamicResource IconBackgroundOver}" />
					</Trigger>
					<Trigger Property="IsMouseOver" Value="False">
						<Setter TargetName="contentPresenter" Property="Opacity" Value=".7" />
						<Setter TargetName="bg" Property="Opacity" Value="1" />
						<Setter TargetName="bg" Property="Fill" Value="{DynamicResource IconBackground}" />
					</Trigger>
					<Trigger Property="IsPressed" Value="True">
						<Setter TargetName="contentPresenter" Property="Opacity" Value="1" />
						<Setter TargetName="bg" Property="Opacity" Value="1" />
						<Setter TargetName="bg" Property="Fill" Value="{DynamicResource IconBackgroundPressed}" />
					</Trigger>
				</ControlTemplate.Triggers>
			</ControlTemplate>
		</Setter.Value>
	</Setter>
	<Setter Property="ContentTemplate">
		<Setter.Value>
			<DataTemplate>                
				<Path Data="{Binding}" Stretch="Uniform" Fill="{DynamicResource IconForeground}" RenderTransformOrigin="0.5,0.5" />
			</DataTemplate>
		</Setter.Value>
	</Setter>
</Style>

Usage

<Button Content="{DynamicResource AddApplicationIconPath}" Style="{StaticResource MetroIconButtonStyle}" />

Once it’s done…

Possible improvement would be to create a real MSBuild custom Task and integrate it to be able to use mscsl.exe as a custom generate build instead of a pre build event, but I’m not sure about the real benefit of the solution compared to the actual one, does it worth the price? It’s up to you J

That’s all! If you have questions to not hesitate to contact me.

Read serial input in C#

NET%20LogoHere’s a simple code snippet to read the serial inputs in C#. I had to use this code several times when working with arduino like devices.

Hope you’ll enjoy it.
Catch you next time and keep it bug free !

    using System;
    using System.IO.Ports;

    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            new Program();
        }

        // Create the serial port with basic settings
        // port name, bauds, parity, packet size and stop bits.
        private SerialPort port = new SerialPort("COM3", 115200, Parity.None, 8, StopBits.Two);

        private Program()
        {
            // Called when data received through serial
            port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);

            // Can crash if the port is already used, haven't found a way to detect it...
            try
            {
                // Start to listen
                port.Open();
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            // Just avoid console to return
            Console.ReadKey();
        }

        private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            // Write the incoming data
            Console.Write(port.ReadExisting());
        }
    }

Browser compatibility: Look at your market!

8Today I want to talk about a topic a bit touchy, the web browser backward compatibility. And in particular a strange behaviour: “The worldwide market share analysis followers”.

This is for me the biggest mistake in the web development when trying to figure out what to do and setup a backward compatibility plan. For the purpose of this article, I’ll take a case I personally had to face today. I’ve quickly developed with Bootstrap.js and JQuery a beautiful and reactive CV web site. It took me about 5 hours max, deployment to the Microsoft Azure cloud included. But before going live I would like to test it against different browsers to be sure about the displays. It’s okay for the Chromes, Firefox’s too, on my android tablet with integrated browser and chrome browser too, on my android samsung mobile too and then, the horror ! It totally sucks with IE 8 and lower… well… Let’s take a look at the famous “worldwide browser market shares” to figure out the impact of that. I use one of the reference analytics website, allowing me to export datas as csv and play a bit with Excel. The complete spreadsheet book is available for download at the end of this article. Here’s the world wide top 20 browsers in terms of market shares:

WWShares

Okay but who’s compatible? I’ve aggregated these market shares based on the compatibility and assuming that the ‘other’ part wasn’t compatible to face the worst case:

WWCompatible

Damn, 20%… I’ll need to take that in account… that’s pretty huge… So I’ll need to dev… STOP ! Who am I really targeting with my CV website? Well, future client and recruiters, mainly in Belgium… So let’s refine the results and take a look at the Belgian situation instead, perhaps it’s better:

BEShares BECompatible

Only 10% remaining… And now let’s refine again the analysis by testing the “others” in terms of compatibility :

BECompatibleOthers

Only 6% of possible incompatibility in the worst case… Well… That’s acceptable for me. The site will work fine in terms of content, just some features will be a bit ugly and the user experience will perhaps suck a bit, but anyway, most of the viewers will have great experience on it.

So will I spent the same amount of development time to the backward compatibility feature? Well, perhaps in the future, but it’s really not a priority.  If my target was the entire world, then yes I should, but let’s be honest, I don’t really care about Chinese or Russian recruiters. So what’s the point of these graphs excepted playing with Excel ?With this I really want to demonstrate you two things:

First, when you have to be backward compatible, don’t do it because you have to and everyone say it’s great to be, but because you have to. This point lead me to the second, always define and keep in mind your audience and don’t work based on “global datas” or techies chatting. That’s true for web development but also desktop applications, trainings, writing, everything! It sound obvious, but once again let’s be honest, who had never spend too much time on features or improvements who appears to be useless or minor once in production?

To conclude, keep that in mind: Know your target and it’s always better to develop for the future than develop for the past !

Catch you next time and keep it bug free !

You can download the Excel doc here

Truly random algorithm in C# – The chaotic user

NET%20LogoIf you’ve already use System.Random in a fine tuned app you’ve probably notice something strange. You get the same random values across sessions. Why ?
If you take a look at the code behind System.Random you’ll notice that it’s mainly based on CPU thick. If the same number of thick elapse each time you do the new/next you potentially get the same random number.
How can we put a kind of truly random, non predictable and chaotic randomness in the algo ? User mouse !
Indeed that’s perhaps the only chaotic stuff in a computer.
Some cryptographic algos use this and it’s not so hard to implement. Indeed it will work only on client app with access to the mouse object and require the user to move the mouse (or the algo will hang).

Here’s the pseudo-code algo I’ll implement :

define RealRandom := Limit += number
	sampleRate = 10 < Random < 20
	numberOfSample = 1 < Random < 10

	for(i < numberOfSample)
		// HERE COMES THE CHAOS !
		samples[i] = MousePositionY * MousePositionX;
		Wait MousePosition != datas[numberOfSample]
		Add 1 to i
		Wait sampleRate
	end

	foreach sample in samples
		returnValue += sample % limit
	end

	return returnValue % limit
end

And here’s the C# implementation.

public static class TrueRandom
{
    public static int NextRandom(int limit)
    {
        int SampleRate = (new Random()).Next(10, 20);
        int NumberOfSample = (new Random()).Next(1, 10);
        long result = 0;

        for(int i = 0; i < NumberOfSample; i++)
        {
            long sample = 0;
            do
            {
                sample = Cursor.Position.X * Cursor.Position.Y;
                Thread.Sleep(10);
            }
            while (sample == Cursor.Position.X * Cursor.Position.Y);
            result += sample % limit;
            Thread.Sleep(SampleRate);
        }

        return (int)result % limit; // Can't cause issue as limit is an integer so the modulo result will always be lower than Int32.MaxValue
    }
}

Catch you next time and keep it bug free !

Generate IIS application with Powershell based on a list

powershellHere’s another simple code snippet to create an IIS application, set the name, physical path, protocol and set the version of the runtime for the AppPool. In that case we use a list of objects representing the applications we have to create.

# First load the mgmt module
import-module webadministration 
foreach($Application in $Applications)
{
	# Check if the app is not already existing. If yes, delete it.
	if(Test-Path 'iis:\Sites\Default Web Site\'$Application.Name)
	{
		# Delete the existing application
		Remove-Item 'iis:\Sites\Default Web Site\'$Application.Name
	}
	# Create the new one
	New-Item 'iis:\Sites\Default Web Site\'$Application.Name -physicalPath $Application.Path -type Application
	# Set the protocol
	Set-ItemProperty 'iis:\Sites\Default Web Site\'$Application.Name  -Name "enabledProtocols" -Value "http,net.tcp"
}
# Set the runtime version
Set-ItemProperty 'iis:\AppPools\DefaultAppPool' -name managedRuntimeVersion -Value 'v4.0'

Catch you next time and keep it bug free !

3 ways to list installed software with Powershell

powershell Here’s 3 little code snippet to get the software installed on the local machine using powershell. Usefull when scripting setups and deployment !

Slow but really complete.

Get-WmiObject -Class Win32_Product

Based on the software in Add/Remove Programs. Fast but may miss some software.

Get-WmiObject -Class Win32Reg_AddRemovePrograms

Based on the software registering in the registry for uninstall. Fast but may miss some software.

Get-ChildItem HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall |
% {Get-ItemProperty $_.PsPath} |
where {$_.Displayname -and ($_.Displayname -match ".*")} |
sort Displayname | select DisplayName, Publisher

Catch you next time and keep it bug free !