Official workarounds: handle to console window

Say that you have a console application and you want to get a handle to your console window. If your process was the one to create the console window then you're lucky, as you can use EnumWindows to find it. But what if your process is a child process borrowing the console window from another process? Don't worry, Microsoft has the answer: http://support.microsoft.com/kb/124103

Basically it's this: temporarily change title of console window to something unique – then wait some time to ensure that the title has changed, and then search for a window with that title. Thank you Microsoft, that seems completely sane and not the least bit fragile in any way…

PHP: There are more reasons to deactivate display_errors than just hiding the structure of your code.

Consider this small PHP script:

<?php
$dir = $_GET['dir'];
if (substr($dir, 0, 2) == '..' || strpos($dir, '/..') !== false || strpos($dir, "\\..") !== false)
    die;
?>
<!doctype html>
<html>
<head><title>Show dir</title></head>
<body>
<?php
if ($dh = opendir(dirname(__FILE__)."/$dir")) {
    while (($file = readdir($dh)) !== false) {
        echo 'filename: '.htmlspecialchars($file)." : filetype: " . filetype($dir . $file) . "\n";
    }
    closedir($dh);
} ?>

Looks fairly innocent, right?
Well it has a hidden XSS vulnerability if display_errors is activated and error_reporting contains E_WARNING. Consider the generated code when calling it with this querystring:

?dir=<script>window.alert('foobar!');</script>

What happens? Well the path (most likely) doesn't exists, so opendir gives a warning of level E_WARNING – containing the unescaped path that couldn't be found:

<!doctype html>
<html>
<head><title>Show dir</title></head>
<body>

Warning: opendir(/var/www/<script>window.alert('foobar!');</script>): failed to open dir: No such file or directory in /var/www/test.php on line 11
</body>
</html>

Uhm php, maybe you could at least escape the error messages when the content type currently being outputted is text/html?…

__declspec(thread) on windows

Microsoft Visual C++ Compiler v.100 (the one for Visual Studio 2010) compiles the main function of the following short program:

__declspec(thread) int i = 0;

int main() {
    i++;
}

To this:

int main(int argc, char **argv) {
00CC1890  push        ebp
00CC1891  mov         ebp,esp
00CC1893  sub         esp,0C0h
00CC1899  push        ebx
00CC189A  push        esi
00CC189B  push        edi
00CC189C  lea         edi,[ebp+FFFFFF40h]
00CC18A2  mov         ecx,30h
00CC18A7  mov         eax,0CCCCCCCCh
00CC18AC  rep stos    dword ptr es:[edi]
	i++;
00CC18AE  mov         eax,dword ptr ds:[00CC8194h]
00CC18B3  mov         ecx,dword ptr fs:[0000002Ch]
00CC18BA  mov         edx,dword ptr [ecx+eax*4]
00CC18BD  mov         eax,dword ptr [edx+00000104h]
00CC18C3  add         eax,1
00CC18C6  mov         ecx,dword ptr ds:[00CC8194h]
00CC18CC  mov         edx,dword ptr fs:[0000002Ch]
00CC18D3  mov         ecx,dword ptr [edx+ecx*4]
00CC18D6  mov         dword ptr [ecx+00000104h],eax
}
00CC18DC  xor         eax,eax
00CC18DE  pop         edi
00CC18DF  pop         esi
00CC18E0  pop         ebx
00CC18E1  mov         esp,ebp
00CC18E3  pop         ebp
00CC18E4  ret

So what is going on here? The interesting part here is this:

ecx,dword ptr fs:[0000002Ch]

What is at fs:[0000002Ch]? The fs segment is offset to start at the start of the Thread Environment Block (TEB). Microsoft won't tell you much except for "don't touch". Wikipedia has more information. Offset 2Ch is a pointer to the Thread Local Storage (TLS) slots. So it stores a TLS index at 00CC8194h, looks up the data at that TLS slot, which apparently is a pointer to an array of thread local values for that thread – where the variable i is placed at offset 104h.

So Microsoft tells us that the TEB is an internal structure subject to change from one Windows version to another, and toying around with it is a big no-no. And yet their compiler happily generates code that directly accesses this "internal implementation detail".

Hipocrisy much?

Has the webservice client lost the connection?

How do you tell if an exception from a call to a webservice is caused by an IO error?

        public static bool IsIoException(Exception e)
        {
            return (e is TimeoutException || e is CommunicationException || e is EndpointNotFoundException) && !(e is FaultException);
        }

Easy, right?

FaultException is derived from CommunicationException, but it occours when the server sends a SOAP fault back, so definitely not a communication problem (at least between client and webservice). I'm not sure why an EndpointNotFoundException would be thrown because of not being able to talk with the host, but I've seen it happen after unplugging my ethernet cable…

So why exactly can't I just have one sort of exception to catch? Am I not supposed to handle a lost connection in a graceful way?

Oww Microsoft thou art a heartless bitch…

 

In .NET windows forms you can't not have a default button on a dialog

I haven't tested if this only applies to forms shown with ShowDialog or to every form, but the form will always have a default (accept) button – the one receiving enter presses.

Setting the AcceptButton property to null will nevertheless select a button as the default button. Actually the AcceptButton property is complety ignored. Don't believe anything on the MSDN page. The only thing that decides which button receives an enter press is which control has focus.

So what can you do if you don't want a button to has focus when first showing the form? A control must have focus, and it must be visible. But nothing stops you from placing it in an invisible position such as setting Left to -1000. Set it as the form's ActiveControl and set TabStop to false, meaning that the user won't get back to the dummy button when tabbing around.

So why do I have to configure the time on my GPS device?

I don't own a stand-alone GPS device myself, but my dad does. A TomTom something. I do however own a Samsung Galaxy S2 myself with a builtin GPS. What they have in common is that you have to tell them the time of day. Now I can use a NTP sync app on my phone and have it synchronize to gain an accuracy of within 10ms under good conditions.

The thing is – they already know the current date and time. They already know it with *a lot* more precision. They just don't use that information.

The principle behind GPS is really quite simple. Every satellite have an onboard ceasium based atomic clock, so that they know the time with a very high precision. They constantly broadcast their time and location. As we know the speed of light (or radiowaves) we can calculate the distance to the satellite if we ourself knows the time. Now if we know the position and distance of three satellites, we can with some simple trigonometry calculate our own position. If we know the position and time of more than three satellites but not our own time, we can actually compute both our own time and position.

Actually we don't even have to know our position very well to find the time with very high accuracy. So we don't even have to get a fix on enough satellites to know our position. As the speed of light is about 300,000,000 m/s we will just by knowing our position to within 300 km know the time to within 1 ms of precision. GPS will usually let us know our position to within 20 m which gives us a time precision of about 67 ns (yes, nanoseconds), and the location services on android can usually tell you your position with even more precision by taking other parameters into account. But even without knowing our position at all we could still get the time with more than about 100 ms precision from any satellite, as their orbit altitude are around 20200 km.

So why again do I have to tell my GPS device the current date and time?