Remko Weijnen's Blog (Remko's Blog)

About Virtualization, VDI, SBC, Application Compatibility and anything else I feel like

Archive for the ‘Programming’ Category

Terminal Server Internals

Hello, my name is Danila Galimov and i will write here sometimes 🙂

My first post is about communications between Terminal Server sessions and Terminal Server service process (termsrv.exe/dll). Terminal Server service needs to communicate with each session for many tasks, such as sending window message, getting message reply and so on. So, on init, Terminal Server creates a SmSsWinStationApiPort port in global namespace and runs a few WinStationLpcThread threads, which are listening on port and are used to process port messages. When csrss.exe is started, it parses its command line, which usually looks like:

%SystemRoot%\system32\csrss.exe ObjectDirectory=\Windows SharedSection=4096,4096,1024 Windows=On SubSystemType=Windows ServerDll=basesrv,1 ServerDll=winsrv:UserServerDllInitialization,3 ServerDll=winsrv:ConServerDllInitialization,2 ProfileControl=Off MaxRequestThreads=16

and loads the required dlls (winsrv.dll in our case). Initialization of winsrv.dll creates a thread, which connects to SmSsWinStationApiPort port and does the loop for processing Terminal Server messages until it receives WinStationTerminate message.

We’ll try to fool Terminal Server (more…)

Working with bitfields in Delphi

Recently I needed to convert a C header file to Delphi which contained bitfields. Let’s take a look at a sample structure that contains bitfields:

It means that there is a DWORD (Cardinal) dwValue1 followed by a bitfield with the size of a ULONG (32 bits). In this bitfield 4 values are defined (BitValue1..4) which are used as boolean’s because the value can offcourse be 0 or 1. Since Delphi doesn’t know a bitfield type the question is how to translate it. Usually it would mean that we simply treat the whole bitfield value as a ULONG and extract the required properties by applying a bitmask (shl/shr). Starting from BDS2006 we can define a record with propertes and use getters and setters. Using this technique we can present boolean values to the user:

Code completion shows that the record has one DWORD Value and 4 Boolean Values which is just what we want!
CodeCompletion

Offcourse we need to implement the Getters and Setters:

We can even add a constructor to it, this can be used to e.g. initialize the record (in the example below we fill with zeroes). Note that only a constructor with at least one argument can be used:

So why not use a class instead of record? The answer is that a class is just a pointer we can never pass this to a function, procedure or api call that expects a record. But if we want to support older Delphi versions, like Delphi 6 or Delphi 7 and even Delphi 2005, which are still used a lot we need to find another solution. I came up with (ab)using sets to emulate bitfields, we can do this because a set is actually a set of bits (limited to 256 bits). The example structure could look like this if we use sets:

We can use normal set operations to get and set bitvalues:

Settings like minimal enum size and record alignment are important because we need to asssure that te record size matches the C structure’s size (especially when using structures with a lot of bitfields. I choose to do this with a litte trick, first I declare some constants:

We use these constants to force the correct size, in the example the bitfield was a ULONG which is 32 bits. We add the al32Bit constant to the bitfield:

So I thought I had it figured out… until I came to this line in the C header file:

So we have a bitfield consisting off multiple bits! This gave me some headaches but I finally came up with the following approach

We need a helper function to retreive the numeric value of ColorDepth:

The helper function is used like this:

Some limitations remain, although I don’t think you are likely to encouter these:

  • A Delphi Set can contain at most 256 values.
  • The ValueFromBitSet function returns an Int64, so values that do not fit in an Int64 cannot be returned.
  • Values in a Set need a unique name.

How rdp passwords are encrypted 2

Several months ago I wrote about encrypting and decrypting RDP passwords. I left one thing open: encrypting the password up to the full 1329 bytes as mstsc does.

Many people were curious about it so I hope the answer is not a disappointment because it’s actually really simple (but I took me a while to figure that out nonetheless). In what I figure is an attempt to hide the password length mstsc always fills up the password with zeroes until it has 512 bytes length.

Then the password is encrypted like I described earlier which gives us a 1328 bytes password hash. So we have one mystery left, how to reach the 1329 bytes size which still is a strange value since the password is in Unicode which takes 2 bytes per char (so the size should be even).

As it turns out, mstsc just adds a zero!

RDP v2 Screenshot

Remote Desktop Password Encryption & Decryption Tool (66185 downloads )

Vista SP1 changes to Terminal Server API

In a previous article I wrote about changes in utildll in vista that breaked compatibality for Terminal Server. Even though release notes for Service Pack 1 don’t indicate changes or fixes in this area my testing shows that Microsoft has taken over the Windows 2008 implementation of utildll to Vista.

This is a good thing, because applications depending on utildll work again. I have updated JwaWinsta for SP1, all Vista versions of the utildll functions are renamed to VistaRTM and all Safe functions were updated to check for SP1. This means that the Safe functions can be used on all OS versions and Service packs! You are strongly advised to use only the Safe functions.

Some observations with SP1: 

  • I quickly tested TSAdmin as well and it seems to work again, only noticable flaw is that the console sessions returns an idle time of 17642 days (Reported Last Input Time is 01-01-1601 but utildll’s ElapsedTimeString function doesn’t account for dates this long in the past).
  • WTSApi32.dll contains some new functions like WTSStartRemoteControlSession and WTSStopRemoteControlSession (which are wrappers to WinStationShadow).
  • The WTSWaitSystemEvent bug I wrote about earlier is still present. I advise to check for winsta.dll version >= 6.0.6000.20664 in code when using this API and advise user to install the Hotfix.

Update: I just tried to install hotfix KB941561 but this fail with the error: The update does not apply to your system. If you do want to get this bug fixed you need to manually replace winsta.dll (take ownership and set permissions to full control). winsta.dll from hotfix KB941561 (X86) (4362 downloads )

TSAdminEx Progress

I just wanted to show some of the progress that I made in development of TSAdminEx. I thought the best way would be to show some screenshots. Which reminds me I installed a nice Javascript to enlarge the thumbnails, click to see it…

Edit: A beta is ready!

This screenshot shows TSAdminEx after startup. In the Left Treeview you can see the This Computer, Favorites and All Listed Servers icon. On Startup all available domains are enumerated.
Here you see the Users tab. If you move the mouse over some columns you can get extra info in the hint. In this hint you get the actual shadow permissions of the highlighted session.
This is the Sessions tab where extra details of a session are shown. By default you can see sessions statistics such as Incomingbytes and Outgoingbytes, this makes it easy to identify sessions that have much traffic.Interesting detail is that the Remote Address column lists the real ip address that is connected to Terminal Server! Hovering the mouse also shows the port number.
Now the Process tab is my favorite! It lists far more details than TSAdmin and also some usefull columns that cannot be show with TSAdmin or any documented Terminal Server API!The Process Age columns shows how long the process is running. You can compare this with the CPU Time column to see how much CPU Time the process has allocated since startup.The Mem Usage shows the amount of physical RAM a process uses while the VM Size column shows the amount of Private Bytes (Virtual Memory) a process uses.
If you click on a domain in the Left Treeview, TSAdminEx will enumerate all Terminal Servers for that domain. You can continue using and even enumerate multiple domains, because enumeration is done from seperate threads!
If you select (highlight) a particular session the appropriate toolbar buttons are enabled or disabled automically indicating the actions that can be performed on the selected session.
And offcourse, an about dialog…

Hope you like it! Comments are open…

Using WTSWaitSystemEvent

If you develop an application for Terminal Server you might want to react on session events. This means that your application is notified when a user logs on, logs off or becomes idle. This can be done with the WTSWaitSystemEvent function. Implementing it is rather simple and could look something like this:

Notice that you would probably do this from a seperate thread otherwise you will block the main thread. To stop waiting for Events you send a special event:

Please note that there are at least 2 issues with this API, one with Windows 2000 and one with Windows Vista. On Windows 2000 events are reported twice for each actual event. Microsoft’s resolution?

The application should expect the event twice, and filter out the second occurrence.

Now how do we solve this? I would suggest introducing a small delay after an event trigger, this way you will probably not receive the duplicate event.

On Windows Vista there’s another issue: After you set the value of the EventMask parameter to WTS_EVENT_FLUSH in the WTSWaitSystemEvent function, no pending calls to the function return on a Windows Vista-based computer. Now what does this mean? It means that after sending WTS_EVENT_FLUSH the thread never responds! So there’s actually no nice way to end the thread, the only escape is a call to TerminateThread.

Microsoft does offer a hotfix, so my suggestion is a check on startup that will notify the user that he/she needs to install the hotfix. A version check can be done on winsta.dll, the version before the fix is 6.0.6000.16386. Hotfix version is 6.0.6000.20664. According to this article the fix will be included in Vista SP1.

References:

Undocumented API’s from Utildll

Several of Microsoft’s Terminal Server tools use undocumented API’s from Utildll.dll. For instance Terminal Server Admin uses it to get a localised connect state string and to format time strings like idle time, logon time etc.

Functions below seems to be the most usefull ones, I will add those to the JwaWinsta unit:

  • function StrConnectState (returns localised string of the given ConnectState)
  • DateTimeString (returns formatted date timestring according to user’s timesettings)
  • function CurrentDateTimeString (like the name says)
  • function ElapsedTimeString (returns formatted string with elapsed time as in TSAdmin)
  • function CalculateElapsedTime (returns elapsed time in seconds)
  • function CalculateDiffTime (returns time difference in seconds)
  • function GetUnknownString (returns localised “unknown” string)

Citrix has it’s own version of this DLL called CUtildll.dll which is similar but uses (Citrix) MUI for localising strings.

Delphi and Terminal Server Aware

When an application is not Terminal Server aware (also known as a legacy application), Terminal Server makes certain modifications to the legacy application to make it work properly in a multiuser environment. For example, Terminal Server will create a virtual Windows folder, such that each user gets a Windows folder instead of getting the system’s Windows directory. This gives users access to their own INI files. In addition, Terminal Server makes some adjustments to the registry for a legacy application. These modifications slow the loading of the legacy application on Terminal Server and require up to 8 MegaBytes extra memory. This behaviour can be avoided if the TSAware flag is present in the PE header of an executable as can be read here at MSDN.

But how do we set this property in Delphi?

In Windows.pas we can see that the constant is defined:

But how to use this in your application?
Add the line

somewhere below the uses clause and we’re done!

Offcourse you are now responsible for making your application Terminal Server compliant which according to Microsoft means: If an application is Terminal Server aware, it must neither rely on INI files nor write to the HKEY_CURRENT_USER registry during setup.

More undocumented Terminal Server API’s

I added some more undocumented API’s to my Jwawinsta unit, the unit is now becoming a collection of the undocumented API’s in winsta.dll.

These are the functions I added:

  • WinStationDisconnect
  • WinStationGetProcessSid
  • CachedGetUserFromSid (exported by utildll.dll)

I also added some more parts of the undocumented structure returned by WinStationQueryInformationW, it now contains:

  • Session State
  • WinStationName
  • SessionId
  • ConnectTime
  • DisconnectTime
  • LastInputTime
  • LogonTime
  • OutgoingFrames
  • OutgoingBytes
  • OutgoingCompressedBytes
  • IncomingCompressedBytes
  • IncomingFrames
  • IncomingBytes
  • Domain
  • Username
  • CurrentTime

Command Prompt IconA little while ago I wrote an article on launching a process in another Terminal Session (https://www.remkoweijnen.nl/blog/2007/10/20/how-to-launch-a-process-in-a-terminal-session/).

The article didn’t have a demo app yet so I’ve attached it here. (more…)

Blogroll


Categories


Archives