• The tadpole operators explained

Last time,¹ I introduced the tadpole operators. As you have probably figured out by now, it was a joke. There are no new tadpole operators.

But the sample code works. What's going on?

The tadpole operators are pseudo-operators, like the goes to operator or the sproing operator: They take advantage of existing language features, and come with a creative story.

The tadpole operators exploit two's complement arithmetic and overflow.² The `__ENABLE_EXPERIMENTAL_TADPOLE_OPERATORS` is just a red herring.

Start with the identity for two's complement negation

```-x = ~x + 1
```

then move the `-x` to the right hand side and the `~x` to the left hand side:

```-~x = x + 1
```

If that was too fast for you, we can do it a different way: start with the identity for two's complement negation

```-x = ~x + 1
```

subtract 1 from both sides

```-x - 1 = ~x
```

and finally, negate both sides

```x + 1 = -~x
```

```-x = ~x + 1
```

and substitute `x = -y`:

```-(-y) = ~-y + 1
```

subtract `1` from both sides and simplify `-(-y)` to `y`.

```y - 1 = ~-y
```

Update: Justin Olbrantz (Quantam) and Ben Voigt provide a simpler derivation, starting with the identity for two's complement negation.

 `-x = ~x + 1` Rearrange terms `~x = -x - 1` Let `x = ~y` Let `x = -y` `-~y = ~(~y) + 1` `~-y = -(-y) - 1` `-~y = y + 1` `~-y = y - 1`

¹Why didn't I post it on April 1st? Well, for one thing, April 1st is overcrowded. Second, it would have interfered with the run-up to the //build conference. And third, yesterday was a holiday in the United States, and I tend to schedule lighter fare on holidays.

²This means that they don't work on a machine that does not use two's complement, or one which checks overflow. Still, maybe they'll be useful if you're entering the IOCCC or some other contest which values minimal code size or obfuscation (or both).

• New C++ experimental feature: The tadpole operators

How often have you had to write code like this:

```x = (y + 1) % 10;
x = (y + 1) * (z - 1);
x = (wcslen(s) + 1) * sizeof(wchar_t);
```

Since the `+` and `-` operators have such low precedence, you end up having to parenthesize them a lot, which can lead to heavily nested code that is hard to read.

Visual Studio 2015 RC contains a pair of experimental operators, nicknamed tadpole operators. They let you add and subtract one from an integer value without needing parentheses.

```x = -~y % 10;
x = -~y * ~-z;
x = -~wcslen(s) * sizeof(wchar_t);
```

They're called tadpole operators because they look like a tadpole swimming toward or away from the value. The tilde is the tadpole's head and the hyphen is the tail.

Syntax Meaning Mnemonic
`-~y` `y + 1` Tadpole swimming toward a value makes it bigger
`~-y` `y - 1` Tadpole swimming away from a value makes it smaller

To enable the experimental tadpole operators, add this line to the top of your C++ file

```#define __ENABLE_EXPERIMENTAL_TADPOLE_OPERATORS
```

For example, here's a simple program that illustrates the tadpole operators.

```#define __ENABLE_EXPERIMENTAL_TADPOLE_OPERATORS
#include <ios>
#include <iostream>
#include <istream>

int __cdecl main(int, char**)
{
int n = 3;
std::cout << "3 + 1 = " << -~n << std::endl;
std::cout << "(3 - 1) * (3 + 1) " << ~-n * -~n << std::endl;
return 0;
}
```

Remember that these operators are still experimental. They are not officially part of C++, but you can play with them and give your feedback here learn more about them here.

• So you decided to call SHFileOperation from a service, at least remember to disable copy hooks

I noted some time ago that it is highly inadvisable to call `SHFile­Operation` from a service, and then I thought about it some more and concluded, it's flat-out wrong, at least in the case where you call it while impersonating.

Now, I'm sure that my opinion won't dissuade many of you, but if you decide to do it anyway, at least disable shell copy hooks by passing the `FOFX_NO­COPY­HOOKS` flag to `IFile­Operation::Set­Operation­Flags`. (We've met this flag before.)

By default, shell copy hooks are active during shell file operations, and this creates a number of problems when called from a service.

First of all, those copy hooks are unlikely to be designed to handle being run in a service. (When you write your own shell extension, do you make sure it also works when run in a service?) They're probably going to try to log the file activity, possibly to a back-end service, or maybe check with a back-end service whether this file copy should be allowed, and if not, they're probably going to display a dialog box saying "The file cannot be moved/copied/deleted because I'm a mean person who hates you due to restrictions imposed by your administrator." (Or worse, they may secretly copy the file to an undisclosed location before allowing the operation through.)

Second of all, you probably don't want those copy hooks intefering with your file operation, whatever it is. Your service is trying to clean up files, or it's moving files around for its own internal purposes, and if a copy hook showed up and blocked the operation, your service is now in a weird inconsistent state.

Note that I still consider `SHFile­Operation` inadvisable from a service. I'm just trying to stop you from digging your hole any deeper than it already is.

• If you can set enforcement for a rule, you can set up lack of enforcement

One of the things you can do with an internal tool I've been calling Program Q is run a program any time somebody wants to add or modify a record. The program has wide latitude in what it can do. It can inspect the record being added/modified, maybe record side information in another table, and one of the things it can decide to do is to reject the operation.

We have set up a validator in our main table to ensure that the widget being added or modified is priced within the approver's limit. But sometimes, there is an urgent widget request and we want to be able to bypass the validation temporarily. Is there a way to disable the validator just for a specific record, or to disable it for all records temporarily?

If you can set up a program to validate a record, you can also set up a program to not validate a record.

Suppose your current validator for adding a widget goes like this:

```if (record.approver.limit < record.price) {
record.Reject("Price exceeds approver's limit");
return;
}
... other tests go here ...
```

And say you want to be able to allow emergency requests to go through even though, say, all approvers are unavailable. Because, maybe, the widget is on fire.

You could decide that a widget whose description begins with the word EMERGENCY is exempt from all validation, but it generates email to a special mailing list.

```if (record.description.beginsWith("EMERGENCY"))
{
// emergency override: send email
// and bypass the rest of validation
return;
}
if (record.approver.limit < record.price) {
record.Reject("Price exceeds approver's limit");
return;
}
... other tests go here ...
```

Of course, the EMERGENCY rule was completely arbitrary. You can come up with whatever rules you like. The point is: If you wrote the rules, you can also write the rules so that they have exceptions.

• When you inadvertently become a collector of something you really aren't all that into

As I was heading home at the end of the day, I ran into one of my colleagues who was also going home, and he was carrying a Star Wars-themed metal lunchbox similar to this one. For those who didn't grow up in the United States, these metal lunchboxes are the type of things elementary school children use to carry their lunch to school.

I remarked, "Nice lunchbox."

My colleague explained, "Yeah, I sort of ended up as the lunchbox guy. It started when somebody gave me a lunchbox as a semi-humorous gift, and I kept it on my shelf. Then other people saw that I had a metal lunchbox and concluded, 'Oh, he must collect metal lunchboxes,' and they started giving me metal lunchboxes. And before I knew it, I became an unwitting collector of metal lunchboxes."

The same thing happened to a different colleague of mine. As his first birthday after he got married approached, his new in-laws asked his wife, "What does Bob like?"

His wife shrugged. "I dunno. He kind of likes Coca-Cola?"

That year, he got a vintage Coca-Cola serving tray. The next year, he got a Coca-Cola clock. And then Coca-Cola drinking glasses. And so on.

Eventually, he had to ask his wife to tell her family, "Okay, you can stop now. Bob doesn't like Coca-Cola that much."

• It rather involved being on the other side of this airtight hatchway: Code injection via QueueUserAPC

A security vulnerability report arrived that took the following form:

The `Queue­User­APC` function can be used to effect an elevation of privilege, as follows:

1. Identify a process you wish to attack.
2. Obtain access to a thread with `THREAD_SET_­CONTEXT` access.
3. Make some educated guesses as to what DLLs are loaded in that process. Start with `kernel32.dll`, since you're going to need it in step 5.
4. From the attacking process, scan the memory of those DLLs looking for a backslash, followed by something that can pass for a path and file name. Such strings are relatively abundant because there are a lot of registry paths hard-coded into those binaries. Suppose you found the string `\Windows NT\Current­Version\App­Compat­Flags`. Even though ASLR randomizes DLL placement, the placement is consistent among all processes, so an address calculated in one process is highliy likely to be valid in all processes.
5. Create a DLL called `C:\Windows NT\Current­Version\App­Compat­Flags.dll`. Put your payload in this DLL.
6. From the attacking thread, call `Queue­User­APC` with the address of `Load­LibraryW` as the function pointer, the victim thread as the thread handle, and a pointer to the fixed string identified in part 4 as the last parameter.
7. The next time the victim thread processes APCs, it will pass `\Windows NT\Current­Version\App­Compat­Flags` to the `Load­LibraryW` function, which will load the payload DLL, thereby effecting code injection and consequent elevation of privilege.

Note that this attack fails if the victim thread never waits alertably, which is true of most threads.

If you have been paying attention, the alarm bells probably went off at step 2. If you have `THREAD_SET_­CONTEXT` access to a thread, then you pwn that thread. There's no need to use `Queue­User­APC` to make the thread do your bidding. You already have enough to make the thread dance to your music. In other words, you are already on the other side of the airtight hatchway.

Here's how: Look for a code sequence that goes

```    push someregister
```

Use the `­Set­Thread­Context` function to set the pushed register equal to the address of the string you found in step 4, and set the instruction pointer to the code fragment. The thread will then resume execution at the specified instruction pointer: It pushes the address of the string, and then it calls `Load­LibraryW`. Bingo, your DLL loads, and you didn't even have to wait for the thread to wait alertably.

On non-x86 platforms, this is even easier: Since all other platforms use register-based calling conventions, you merely have to load the address of the string into the "first parameter" register (`rcx` for x64) and set the instruction pointer to the beginning of `Load­LibaryW`.

By default, `THREAD_SET_­CONTEXT` access is granted only to the user, and never to lower integrity levels. In other words, a low IL process cannot get `THREAD_SET_­CONTEXT` access to a medium or high integrity thread, and a medium IL process cannot get access to a high integrity thread. This means that, by default, you can only get `THREAD_SET_­CONTEXT` access to threads that have equivalent permissions to what you already have, so there is no elevation.

• Determining programmatically whether a file was built with LAA, ASLR, DEP, or OS-assisted /GS

Today's Little Program parses a module to determine whether or not it was built with the following flags:

Remember, Little Programs do little error checking. In particular, this Little Program does no range checking, so a malformed binary can result in wild pointers.

```#include <windows.h>
#include <imagehlp.h>
#include <stdio.h> // horrors! mixing stdio and C++!
#include <stddef.h>

class MappedImage
{
public:
bool MapImage(const char* fileName);
void ProcessResults();
~MappedImage();

private:
WORD GetCharacteristics();

template<typename T>
WORD GetDllCharacteristics();

template<typename T>

private:
HANDLE file_ = INVALID_HANDLE_VALUE;
HANDLE mapping_ = nullptr;
void *imageBase_ = nullptr;
int bitness_ = 0;
};

bool MappedImage::MapImage(const char* fileName)
{
file_ = CreateFile(fileName, GENERIC_READ,
NULL,
OPEN_EXISTING,
0,
NULL);
if (file_ == INVALID_HANDLE_VALUE) return false;

mapping_ = CreateFileMapping(file_, NULL, PAGE_READONLY,
0, 0, NULL);
if (!mapping_) return false;

imageBase_ = MapViewOfFile(mapping_, FILE_MAP_READ, 0, 0, 0);
if (!imageBase_) return false;

if (!headers_) return false;
if (headers_->Signature != IMAGE_NT_SIGNATURE) return false;

case IMAGE_NT_OPTIONAL_HDR32_MAGIC: bitness_ = 32; break;
case IMAGE_NT_OPTIONAL_HDR64_MAGIC: bitness_ = 64; break;
default: return false;
}

return true;
}

MappedImage::~MappedImage()
{
if (imageBase_) UnmapViewOfFile(imageBase_);
if (mapping_) CloseHandle(mapping_);
if (file_ != INVALID_HANDLE_VALUE) CloseHandle(file_);
}

WORD MappedImage::GetCharacteristics()
{
}

template<typename T>
WORD MappedImage::GetDllCharacteristics()
{
}

template<typename T>
{
ULONG size;
T *data = static_cast<T*>(ImageDirectoryEntryToDataEx(
&size, NULL));
if (!data) return false;
ULONG minSize = offsetof(T, SecurityCookie) +
if (size < minSize) return false;
if (data->Size < minSize) return false;
return data->SecurityCookie != 0;
}

void MappedImage::ProcessResults()
{
printf("%d-bit binary\n", bitness_);
auto Characteristics = GetCharacteristics();
printf("Large address aware: %s\n",
? "Yes" : "No");

auto DllCharacteristics = bitness_ == 32

printf("ASLR: %s\n",
(DllCharacteristics & IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE)
? "Yes" : "No");
printf("ASLR^2: %s\n",
(DllCharacteristics & IMAGE_DLLCHARACTERISTICS_HIGH_ENTROPY_VA)
? "Yes" : "No");
printf("DEP: %s\n",
(DllCharacteristics & IMAGE_DLLCHARACTERISTICS_NX_COMPAT)
? "Yes" : "No");
printf("TS Aware: %s\n",
(DllCharacteristics & IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE)
? "Yes" : "No");

? "Yes" : "No");
}

int __cdecl main(int argc, char**argv)
{
MappedImage mappedImage;
if (mappedImage.MapImage(argv[1])) {
mappedImage.ProcessResults();
}
return 0;
}
```

Let's see what happened.

First we use the `Map­Image` method to load the binary and map it into memory. While we're at it, we sniff at the headers to determine whether it is a 32-bit or 64-bit binary.

The `Get­Characteristics` method merely extracts the `Characteristics` from the `File­Header`. This is easy because the `File­Header` is the same for 32-bit and 64-bit binaries.

The `Get­Dll­Characteristics` method has two versions depending on the image bitness. In both cases, it extracts the `Dll­Characteristics` field, but the location of the field depends on the structure.

The `Has­Security­Cookie` method also has two versions depending on the image bitness. The minimum size necessary to get OS-assisted stack overflow protection is the size that encompasses the `Security­Cookie` member, and in order to get that extra protection, the member needs to be nonzero.

What is OS-assisted stack overflow protection?

First, I'm going to assume that you've read Compiler Security Checks In Depth.

Okay, welcome back.

In theory, `/GS` could be implemented entirely in application code, with no need for operating system assistance. And in fact, that's what happens when the executable is run on older versions of Windows (like Windows 98 or Windows 2000). But the module can tell the operating system, "Hey, here is where I put my security cookie," and if the operating system understands this field, then it will go in and make the security cookie even more randomer than random by mixing in some cryptographically secure random bits.

Okay, so that's the program. Note that some of these flags are meaningless in DLLs, so be careful to interpret the output correctly.

• MapGenericMask is just a convenience function for converting generic access to specific access, according to the instructions you provide

For some reason, people call the `Map­Generic­Mask` function in order to calculate what access mask to pass to request access to something. That's not what `Map­Generic­Mask` is for. The `Map­Generic­Mask` function is to assist the server side of the access, not the client side.

As the documentation says, the `Map­Generic­Mask` function maps the generic access rights in an access mask to specific and standard access rights. The function applies a mapping supplied in a `GENERIC_MAPPING` structure.

This is further explained in the remarks:

After calling the Map­Generic­Mask function, the access mask pointed to by the Access­Mask parameter has none of its generic bits (GenericRead, GenericWrite, GenericExecute, or GenericAll) or undefined bits¹ set, although it can have other bits set. If bits other than the generic bits are provided on input, this function does not clear them.

What this function does is take the `Access­Mask` parameter and convert all of the `GENERIC_*` bits into object-specific bits, as defined by the `GENERIC_MAPPING`.

In other words, the code for the `Map­Generic­Mask` function looks basically like this:

```void MapGenericMask(
PGENERIC_MAPPING GenericMapping
)
{

if (*AccessMask & GENERIC_WRITE)

if (*AccessMask & GENERIC_EXECUTE)

if (*AccessMask & GENERIC_ALL)

GENERIC_WRITE | GENERIC_ALL);
}
```

The function takes the access mask and sees if any of the generic access bits are set. If so, then it replaces them with the corresponding specific access bits provided by the `Generic­Mapping` parameter.

Note that this function doesn't tell you anything you don't already know. It's just a helper function to make access checks easier to implement: If you are a component that manages an object and you need to perform an access check, you use `Map­Generic­Access` to convert all the generic access requests into specific requests according to the rules you specified in your `GENERIC_MAPPING`, and the rest of your code only needs to deal with specific requests.

For example, we saw some time ago that a hypothetical Gizmo object could map `GENERIC_READ` to operations that query information from a Gizmo without modifying it, map `GENERIC_WRITE` to operations that alter the gizmo properties, map `GENERIC_EXECUTE` to operations that enable or disable the Gizmo, and map `GENERIC_ALL` to include all Gizmo operations.

And if you needed to do a security check on a Gizmo, you would do something like this:

```BOOL IsGizmoAccessGranted(
HTOKEN Token,
PSECURITY_DESCRIPTOR SecurityDescriptor,
DWORD AccessDesired,
PDWORD AccessAllowed)
{

BOOL AccessGranted = FALSE;
PRIVILEGE_SET PrivilegeSet;
DWORD PrivilegeSetSize = sizeof(PrivilegeSet);

return AccessCheck(SecurityDescriptor,
Token,
AccessDesired,
&GizmoGenericMapping,
&PrivilegeSet,
&PrivilegeSetSize,
AccessAllowed,
&AccessGranted) && AccessGranted;
}
```

When somebody wants to access a Gizmo, you use `Map­Generic­Mask` to convert all the generic requests to specific requests. You then pass that request to `Access­Check`, along with token for the user making the request and the security descriptor for the widget. The `Access­Check` function does the heavy lifting of seeing which ACEs apply to the user specified by the token, then verifying that all the requested accesses have an Allow ACE, and that none of the requested accesses have a Deny ACE. It also takes care of the `MAXIMMUM_ALLOWED` access request by simply returning all the accesses that are allowed and not denied.

The point of the `Map­Generic­Mask` function is to make life a little easier for the code that enforces security.

On the other hand, the `Map­Generic­Mask` function is not particularly useful on the side that is requesting access. If you are requesting generic read access, just pass `GENERIC_READ`. The code that does the security check will convert the `GENERIC_READ` into the access masks that are specific to the object you are trying to access. (And it will most likely use the `Map­Generic­Mask` function to do it.)

¹ That extra phrase "or undefined bits" is contradicted by the subsequent sentence "If bits other than the generic bits are provided on input, the function does not clear them." The second sentence is correct; the extra phrase "or undefined bits" is incorrect and should be removed.

• Low-level hooks have thread affinity, so make sure you keep an eye on the thread

A customer was having a problem with their automated testing tool.

We have an automation testing tool that, among other things, installs a low-level mouse hook. Sometimes, the hook takes too long to process an action, and it gets unhooked. We have a watchdog thread that tries to detect when this has happened, and in response, it kicks off a task on the thread pool to re-register the low-level hook. The call to register the low-level hook succeeds, but the hook apparently didn't get installed correctly because it never fires. What are we doing wrong?

Recall that low-level hooks have thread affinity. This is spelled out in the documentation.

This hook is called in the context of the thread that installed it. The call is made by sending a message to the thread that installed the hook. Therefore, the thread that installed the hook must have a message loop.

So there are two mistakes here.

First, the hook is installed from a thread pool task, which means that the hook is associated with the thread pool thread. One of the characteristics of the thread pool is that threads come and go based on demand. If there is no thread pool activity for a while, the thread pool will probably start trimming threads, and it it decides to get rid of the thread that installed the hook, and the hook disappears with it.

The second mistake is that the hook is installed from a thread pool task. Sure, the hook registers successfully, but then when you return back to the thread pool, there's no guarantee that anybody on that thread is going to pump messages any time soon.

Indeed, odds are that it won't.

Tasks queued up on the thread pool tend not to be UI tasks, because, well, they're on the thread pool, not the UI thread. Therefore, there is no expectation that they will pump messages. Furthermore, if the thread goes idle, the thread pool is probably not going to pump messages; it's just going to put the thread to sleep until the next task is queued up.

The customer thanked us for the explanation. I'm not sure what they are going to do about it, but I hope they're going to solve their problem not by patching up their watchdog thread but rather by fixing their low-level mouse hook so it doesn't exceeed the low-level hook timeout. For example, they could have the low-level hook post its events to another thread, then return immediately. That other thread can then do the expensive processing asynchronously. (This assumes that they are using the low-level hook only for monitoring the mouse rather than trying to intercept and block it.)

• Why don't you forward WM_GETMINMAXINFO and clamp the results?

I'm going to assume the question is really "Why don't you forward `WM_GET­MIN­MAX­INFO` before clamping the results?" rather than "Why did you bother writing all this code in the first place? Why not simply forward `WM_GET­MIN­MAX­INFO` and clamp the results?"¹
The answer is that forwarding `WM_GET­MIN­MAX­INFO` doesn't do anything. As noted in the documentation, the incoming `MIN­MAX­INFO` structure already has the default values on entry. The default handler for the `WM_GET­MIN­MAX­INFO` message returns without doing anything, since all the default handler does is accept the defaults.
¹ In case the question really was "Why did you bother writing all this code in the first place...": Go ahead and delete all the changes aside from the initial version of the `On­Get­Min­Max­Info` handler. You'll see the problems called out in the text: The resize arrows appear when the mouse hovers over the corners and the left and right edges. And if you maximize the window onto a secondary monitor, and that monitor's height is different from the height of the primary monitor, it maximizes to the wrong height.