7.06.2011

I Got Busy, But Well...

I was planning to write a couple of articles about custom controls and 3D with Opengl (i already started writing one).
well i got a bit busy, but i promise i'll post them soon.
i'll also update the downloads page with demo source codes for every article in the blog.
Brahim.

Re : I've been away for so long now, it's 28th noverber, so...
I got really busy in studies, and work on oDesk, so i really didn't have time to add whatever to the blog, even that article about GDI+ is still in the drafts folder, but i'm sure i'll finish it as soon as i get some free time.
See ya.

6.24.2011

Image Effect : Bluring - Fast with Graphics Drawing

one of the famous effects that we can apply to images is Blur. it is used to reduce "noise" and details.
you can read here about Gaussian blur in this wiki article.

one basic blurring consist in adding to the rgb values of a pixel, all rgb values of the pixels surrounding it.
another article explaining it well, and its implementation in Visual Basic on CodeProject.

the problem - for me - is the speed. this method is slow. so after a second thought, why treating pixel by pixel? let's try blurring the hole image at the same time.

Here is what i came up with :

Sub BlurBitmap(ByRef image As Bitmap, Optional ByVal BlurForce As Integer = 1)
        'We get a graphics object from the image
        Dim g As Graphics = Graphics.FromImage(image)
        'declare an ImageAttributes to use it when drawing
        Dim att As New ImageAttributes
        'declare a ColorMatrix
        Dim m As New ColorMatrix
        ' set Matrix33 to 0.5, which represents the opacity. so the drawing will be semi-trasparent.
        m.Matrix33 = 0.5F
        'Setting this ColorMatrix to the ImageAttributes.
        att.SetColorMatrix(m)
        'drawing the image on it self, but not in the same coordinates, in a way that every pixel will be drawn on the pixels arround it.
        For x = -BlurForce To BlurForce
            For y = -BlurForce To BlurForce
                'Drawing image on it self using out ImageAttributes to draw it semi-transparent.
                g.DrawImage(image, New Rectangle(x, y, image.Width, image.Height), 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, att)
            Next
        Next
        'disposing ImageAttributes and Graphics. the effect is then applied. 
        att.Dispose()
        g.Dispose()
    End Sub





Testing :
I find this way faster than treating a it pixel per pixel. try changing the value of BlurForce (which should be an integer > 0) and check the effect. have fun with it!

Any comments are very welcome.

Handling Registry in DotNet - RegNotifyChangeKeyValue

In other programming languages, it is most likely a must to use the registry Api's, listed on msdn Here.
But using dotnet, thanks to the Microsoft.Win32.Registry Class, we have all methods needed to Open a key, enumerate keys, create or delete keys, or even enumerating values, reading names, values, adding, modifying and deleting. there are various examples on msdn for almost every method of this class, they could really show you the simplicity of handling registry.

Probably the function that i find important and "missing" in this class is the ability to monitor changes in the registry.
therefor, we are going to use the RegNotifyChangeKeyValue as we do in any other language.
but first, we are going to use RegOpenKeyEx to open the key with the KEY_NOTIFY.

Here is an exemple :

Private Declare Function RegNotifyChangeKeyValue Lib "advapi32.dll" (ByVal hKey As IntPtr, _
ByVal watchSubtree As Boolean, ByVal dwNotifyFilter As Integer, ByVal hEvent As IntPtr, _
ByVal fAsynchronous As Boolean) As Integer

Private Declare Auto Function RegOpenKeyEx Lib "advapi32.dll" ( _
ByVal hKey As IntPtr, _
ByVal lpSubKey As String, _
ByVal ulOptions As Integer, _
ByVal samDesired As Integer, _
ByRef phkResult As Integer) As Integer

Const REG_NOTIFY_CHANGE_LAST_SET As Integer = &H4L
Const HKEY_CURRENT_USER As Integer = &H80000001
Const KEY_NOTIFY As Integer = &H10 
Const ERROR_SUCCESS As Integer = 0


Sub RegNotifyChange()
        Dim regkey As IntPtr
        If RegOpenKeyEx(HKEY_CURRENT_USER, "Software\Microsoft\Windows", 0, KEY_NOTIFY, regkey) = ERROR_SUCCESS Then
            If RegNotifyChangeKeyValue(regkey, False, REG_NOTIFY_CHANGE_LAST_SET, Nothing, False) = ERROR_SUCCESS Then
                MsgBox("Change!")
            Else
                MsgBox("RegNotifyChangeKeyValue Failed.")
            End If
        Else
            MsgBox("RegOpenKeyEx Failed.")
        End If
    End Sub

Explaining the code :
we need to open a registry key with the notify access, so we can tell RegNotifyChangeKeyValue to "notify" us whenever something changed.
we call RegOpenKeyEx with HKEY_CURRENT_USER as the root key, which is already opened.
our subkey for exemple will be "Software\Microsoft\Windows". set 0 for the reserved parameter, KEY_NOTIFY for desired Access, and our variable regkey where the handle will be stored.
after that, we call RegNotifyChangeKeyValue with the specified opened key. we set true if want to monitor subkeys also, in this case we dont (for example). Then, when need to specify a filter, which can be a combination of REG_NOTIFY_CHANGE_NAME, REG_NOTIFY_CHANGE_ATTRIBUTES, REG_NOTIFY_CHANGE_LAST_SET and REG_NOTIFY_CHANGE_SECURITY, they are all described in the RegNotifyChangeKeyValue page. in our case, all we need is to monitor changes in values only.
in the next parameter, we need to specify whether we want to "fire" an event when a change occurs, so we set hEvent to a handle of an event, and fAsynchronous to True. in our case, where fAsynchronous is set to false, the calling thread will sleep after the call, and the function will only return when a change occurs. in this case hEvent is ignored.

Debugging :
When this method is called, the thread will be waiting for the function to return, in other words, will be waiting for a specific changes in the registry, a messagebox will pop up, and our sub will exit. if we want to continue to monitor changes, we can keep calling RegNotifyChangeKeyValue in a loop, but it is better to use another thread for the job, because this thread will be busy.

After Finishing using the key, it is best to call RegCloseKey to close the handle.

6.18.2011

Listing All Tcp connections on Local Computer

For this part of code, it will be based on this Api called GetExtendedTcpTable.
What we are going to do is, to try and retrieve every tcp connection, its state, its local and remote adresses and ports, and it's owning process. We could also use GetTcpTable to for the same job, but i noticed that it is only available in Vista, so we'll go with GetExtendedTcpTable for now, as it is working on both Vista and Xp Sp2.

Let's start with coding, here is a detailed module about what we need, so create a new module and paste this :

Imports System.Runtime.InteropServices
Imports System.Net.NetworkInformation
Imports System.Net

Public Module TCPGet
'Api to get table
Declare Auto Function GetExtendedTcpTable Lib "iphlpapi.dll" (ByVal pTCPTable As IntPtr, ByRef OutLen As Integer, ByVal Sort As Boolean, ByVal IpVersion As Integer, ByVal dwClass As Integer, ByVal Reserved As Integer) As Integer
'const : we are asking for connections with ProcessIDs', all of them.
Const TCP_TABLE_OWNER_PID_ALL As Integer = 5
'represents a full table
<StructLayout(LayoutKind.Sequential)> _
Public Structure MIB_TCPTABLE_OWNER_PID
Public NumberOfEntries As Integer 'number of rows
Public Table As IntPtr 'array of tables
End Structure
'represents a row
<StructLayout(LayoutKind.Sequential)> _
Public Structure MIB_TCPROW_OWNER_PID
Public state As Integer 'state of the connection
Public localAddress As UInteger
Public LocalPort As Integer
Public RemoteAddress As UInteger
Public remotePort As Integer
Public PID As Integer 'Process ID
End Structure
'this a structure that we made to store a connection after formatting it
Structure TcpConnection
Public State As TcpState
Public localAddress As String
Public LocalPort As Integer
Public RemoteAddress As String
Public remotePort As Integer
Public Proc As String
End Structure
'Main Function
Function GetAllTCPConnections() As MIB_TCPROW_OWNER_PID()
GetAllTCPConnections = Nothing
'we need to know how much memory we need to store all the connections
Dim cb As Integer
'so we call GetExtendedTcpTable without a pointer to a table to get the size
GetExtendedTcpTable(Nothing, cb, False, 2, TCP_TABLE_OWNER_PID_ALL, 0)
'after getting the size, we allocate memory
Dim tcptable As IntPtr = Marshal.AllocHGlobal(cb)
'the call where we store the connections in that memory
If GetExtendedTcpTable(tcptable, cb, False, 2, TCP_TABLE_OWNER_PID_ALL, 0) = 0 Then
'we convert it to a MIB_TCPTABLE_OWNER_PID variable
Dim tab As MIB_TCPTABLE_OWNER_PID = Marshal.PtrToStructure(tcptable, GetType(MIB_TCPTABLE_OWNER_PID))
'and we make an array with a size of number of connections
Dim Mibs(tab.NumberOfEntries - 1) As MIB_TCPROW_OWNER_PID
'row represents the adress of a MIB_TCPROW in memory
Dim row As IntPtr
'for each connection
For i As Integer = 0 To tab.NumberOfEntries - 1
'adress = adress of table + 4(int32) + (size of a MIB_TCPROW * i)
row = New IntPtr(tcptable.ToInt32 + Marshal.SizeOf(tab.NumberOfEntries) + Marshal.SizeOf(GetType(MIB_TCPROW_OWNER_PID)) * i)
'convert pointer to a MIB_TCPROW, and store it in the array
Mibs(i) = Marshal.PtrToStructure(row, GetType(MIB_TCPROW_OWNER_PID))
Next
'returning the array
GetAllTCPConnections = Mibs
End If
'just before leaving, clean up your memory!
Marshal.FreeHGlobal(tcptable)
End Function
'MIB_TCPROW_OWNER_PID is not well formatted, we need to format it.
Function MIB_ROW_To_TCP(ByVal row As MIB_TCPROW_OWNER_PID) As TcpConnection
Dim tcp As New TcpConnection
tcp.State = DirectCast(row.state, TcpState) 'a State enum is better than an int
'IP adresses are stored in long format, we can simply convert it this way
Dim ipad As New IPAddress(row.localAddress)
tcp.localAddress = ipad.ToString
'also the port is in network byte order,we need to convert it as well
tcp.LocalPort = row.LocalPort / 256 + (row.LocalPort Mod 256) * 256
'another ip
ipad = New IPAddress(row.RemoteAddress)
tcp.RemoteAddress = ipad.ToString
'another port
tcp.remotePort = row.remotePort / 256 + (row.remotePort Mod 256) * 256
'for the process, all we get is the ID. Let's get also the name.
Dim p As Process = Process.GetProcessById(row.PID)
tcp.Proc = p.ProcessName & " (" & row.PID.ToString & ")"
'just freeing this variable since we don't need it anymore.
p.Dispose()
'done.
Return tcp
End Function
End Module

Let's Create a Listview as the following to display connections :


Now let's call our function and add each connection to this listview :

'Clear Items
        ListView1.Items.Clear()
        'For Each MIB_TCPROW
        For Each Row In GetAllTCPConnections()
            'We Convert It
            Dim Tcp As TcpConnection = MIB_ROW_To_TCP(Row)
            'Add SubItems to a ListViewItem
            Dim l As New ListViewItem(New String() {Tcp.State.ToString, Tcp.localAddress, Tcp.LocalPort, Tcp.RemoteAddress, Tcp.remotePort, Tcp.Proc})
            'Add The Item
            ListView1.Items.Add(l)
        Next

That's about it, we can now see all tcp connections thanks to this great API.
As for UDP Connections, we can use the GetExtendedUdpTable Function with MIB_UDPTABLE_OWNER_PID and MIB_UDPROW_OWNER_PID Structures with a very similar piece of code to list them in an array, and show them in a listview if you like so.

6.17.2011

Recovering Google Chrome Passwords


It was a while when i was curious about how my favorite web browser saves passwords.
i started browsing Chrome files, watching files that changes when i save a password.

after a few tries i found the file that stores the passes called web data (updated later to login data) in the Local Application Data Folder, which is an SQLite Database, wasn't that hard to find out with any DB Software.
after finding the table called "logins" that stores passwords, all we need to do is to read the "origin_url", "username_value" and "password_value" for each entry, but we need to decrypt the "password_value" using the CryptUnprotectData Api, without any pOptionalEntropy (Optionnal password, read CryptUnprotectData for more info). The other two values are stored as plain-text and no need to decrypt them.

There is planty of exemples about reading from SQLite DB, and also about using the CryptUnprotectData Api.

PS : Msdn recommands freeing memory of the pDataOut by calling LocalFree to free the pDataOut.pbData handle.

if anyone is having problem with sqlite reading or using CryptUnprotectData , Please Leave me a Comment i would be happy to help.


Check the Downloads page for the demo that includes reading from the database and decrypting.
i also included system.data.sqlite releases incase it failed due to compatibility issues.
you can also find it here : http://sourceforge.net/projects/sqlite-dotnet2/