Checking Returns

Checking Returns

I shouldn't have to repeat this as it should be common sense, but all function calls that return errors should be checked. If a function doesn't return errors, it might be a good idea to test whether the operation really succeeded. A good example of this is checking a buffer after a strncpy to determine whether the string was truncated, as was detailed in Chapter 5. It is particularly critical to check the returns of critical security functions, such as impersonation functions like ImpersonateNamedPipeClient. Although it's simple to check many functions for errors, some functions have trinary returns (three possible return values) some of the sockets functions behave this way.

Consider the following code:

while(bytes = recv(sock, buf, len, 0)) WriteFile(hFile, buf, bytes, &written, NULL);

What's wrong with this picture? If you look at recv, you find that it typically returns 0 when there are no more bytes to read from a TCP connection. This assumes a graceful shutdown of the connection. If the connection aborts for some reason, bytes has just been set to -1 and WriteFile will attempt to write four gigabytes of memory into the file handle pointed to by hFile. Your application will throw an exception before that manages to happen, assuming you're not running a 64-bit version of the operating system.

If you didn't have enough problems already, there are a couple of functions where success just isn't enough. Consider the AdjustTokenPrivileges function. The documentation helpfully states:

If the function succeeds, the return value is nonzero. To determine whether the function adjusted all of the specified privileges, call GetLastError, which returns one of the following values when the function succeeds:

Value

Meaning

ERROR_SUCCESS

The function adjusted all specified privileges.

ERROR_NOT_ALL_ASSIGNED

The token does not have one or more of the privileges specified in the NewState parameter. The function may succeed with this error value even if no privileges were adjusted. The PreviousState parameter indicates the privileges that were adjusted.

Now if all you wanted to do was adjust one privilege, you might think that the function would fail if it couldn't adjust the only privilege it was asked to manipulate. Unfortunately, it will return TRUE, and you must call GetLastError to determine whether it actually adjusted the privilege properly. This is especially important when dropping privileges. The moral of the story is that if you're not extremely familiar with an API call's behavior, read the remarks section carefully you might find some interesting bugs.



Writing Secure Code
Writing Secure Code, Second Edition
ISBN: 0735617228
EAN: 2147483647
Year: 2001
Pages: 286

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net