String handling is one of the most error-prone aspects of programming in C and C++. Errors in dealing with strings account for most of the buffer overruns that result in security problems. In many languages, a string is an elementary type, and several of the issues that cause problems in C and C++, such as buffer overruns and problems with illegal pointers, don't occur as easily in these other languages. Perhaps if C had been written with a string type, we might have fewer problems with strings.

Let's examine strings and take a look at three C library calls that can compromise the security of your code. Don't despair, I'll also introduce you to the Standard Template Library (STL) and explain how it can help you avoid some of these security vulnerabilities in your code. As I pointed out last time, the contents of this column assume that the reader has a basic familiarity with programming in C.

What's a String?
A string is a series of characters ending with a null (‘\0’) character that lets the program know where to terminate the string. A Unicode string is a series of wide characters (WCHAR) that also terminates with a null character. At the lower levels (e.g., kernel level) of Windows 2000 (Win2K) and Windows NT, a UNICODE_STRING type often represents strings. This structure maintains information about the length of the string and the maximum size of the buffer. Dealing with kernel-level code is beyond the scope of this article, but you should be aware that this approach represents another way of string handling. Almost without exception, the C library calls, which deal with single-byte characters, have equivalents to properly deal with Unicode strings, and the same pitfalls apply to both single-byte and Unicode strings. Let's begin by examining some of the available library calls, starting with strcpy().

Fun with strcpy()
The first library call, strcpy(), is defined as

char* strcpy(char* dest, const char* src);

A quick look at how C and C++ implement this function and a little thought about what parameters aren’t passed into this function gives a good view of the problems that can occur. What happens if src of dest is null? Ker-boom, it throws an unhandled exception or overwrites the stack. What if the string that src points to is longer than the dest buffer can hold? You'll overwrite past the end of the dest buffer, and if dest is a static buffer, declared on the stack like buf in the following example:

 //this is the wrong way
void foo(char* inp)
\{
   char buf\[25\];

      strcpy(buf, inp);
      //do more processing of buf
\}

Buffer overruns are the sort of thing an attacker loves to find in your code. Once inp fills up buf, it starts overwriting the stack and can usually cause your program to execute whatever code the attacker wants. Consider a related problem: What if inp isn’t null-terminated? Now, our not-very-bright strcpy() function takes everything in inp and stuffs it into buf, past the end of buf, and keeps going until it triggers an exception handler. For these reasons, many programmers ban strcpy() from their applications.

Fortunately, you can improve the situation and still use strcpy():

void bar(char* inp)
\{
   char buf\[25\];
   
   //first check to see if inp is illegal – if you don’t do this, strlen
   //call below blows up
   if(inp <h1><a name="_NULL_assert_false_printf_#147_Cannot_process_a_null_pointer_n_#148_return_use_lt_not_lt_that_way_you_have_room_for_a_termination_character_if_strlen_inp_lt_sizeof_buf_strcpy_buf_inp_do_more_processing_else_printf_Hey_That_string_is_too_long_n_pre_p_The_first_thing_you_need_to_do_is_determine_whether_inp_is_a_legal_string_if_not_you_need_to_throw_an_assert_if_you_re_in_a_debug_build_to_let_the_programmer_know_that_a_problem_exists_in_the_calling_function_You_ve_just_eliminated_one_gotcha_Next_check_to_see_whether_the_string_is_too_long_for_your_buffer_and_complain_if_it_is_Since_strlen_also_blows_up_when_passed_a_null_pointer_you_ll_want_to_check_for_that_condition_before_checking_the_string_length_Note_the_use_of_the_sizeof_operator_which_helps_keep_you_from_making_mistakes_if_you_later_decide_to_change_the_size_of_buf_#151_this_operator_automatically_takes_into_account_any_such_changes_As_a_last_point_you_need_to_reduce_the_length_of_the_inp_string_to_be_one_character_less_than_the_size_of_the_buffer_to_leave_room_for_the_null_character_p_p_So_what_can_go_wrong_The_most_likely_problem_you_ll_encounter_is_that_inp_really_isn_#146_t_null_terminated_and_as_a_result_the_strlen_call_will_blow_up_Another_problem_is_that_the_inp_pointer_might_not_be_valid_#151_checking_for_NULL_is_nice_but_the_pointer_might_still_be_illegal_For_example_the_pointer_might_point_into_kernel_space_point_too_low_into_user_space_lt_64KB_or_be_complete_junk_However_if_you_do_too_much_checking_your_code_will_run_slowly_so_you_have_to_make_some_compromises_However_as_Steve_Maguire_points_out_in_his_book_Writing_Solid_Code_ISBN_1556155514_if_you_#146_re_running_around_dereferencing_null_pointers_execution_speed_is_the_least_of_your_worries_p_p_So_what_does_this_code_do_right_If_you_get_any_obvious_errors_or_enter_a_string_that_s_too_long_you_#146_ll_fail_gracefully_note_the_error_and_return_execution_to_the_caller_A_more_complete_example_would_return_unique_errors_to_the_caller_but_I_ve_simplified_the_code_in_this_example_p_p_font_class_subhead_Is_strncpy_Better_font_br_The_second_library_call_strncpy_is_defined_as_p_pre_char_strncpy_char_dest_const_char_src_size_t_count_pre_p_On_the_surface_this_one_looks_better_than_strcpy_#151_at_least_it_wants_to_know_how_many_characters_you_#146_d_like_to_stuff_into_the_buffer_However_when_you_take_a_closer_look_you_see_that_it_still_has_problems_For_example_strncpy_still_doesn_t_address_the_problem_of_dest_or_src_being_null_and_if_you_lie_to_it_about_the_character_count_things_can_get_ugly_fast_Let_#146_s_look_at_some_code_to_illustrate_its_usage_p_pre_void_baz_const_char_inp_char_buf_25_always_check_the_validity_of_your_inputs_if_inp_"> NULL)
    \{
       assert(false);
       printf(“Cannot process a null pointer!!!\n”);
       return;
    \}
   
    //use <, not <= - that way you have room for a termination character
   if(strlen(inp) < sizeof(buf))
   \{
      strcpy(buf, inp);
      //do more processing
   \}
   else
   \{
      printf("Hey! That string is too long!\n");
   \}
\}
</a></h1>

The first thing you need to do is determine whether inp is a legal string; if not, you need to throw an assert (if you're in a debug build) to let the programmer know that a problem exists in the calling function. You've just eliminated one gotcha. Next, check to see whether the string is too long for your buffer, and complain if it is. Since strlen() also blows up when passed a null pointer, you'll want to check for that condition before checking the string length. Note the use of the sizeof() operator, which helps keep you from making mistakes if you later decide to change the size of buf—this operator automatically takes into account any such changes. As a last point, you need to reduce the length of the inp string to be one character less than the size of the buffer to leave room for the null character.

So, what can go wrong? The most likely problem you'll encounter is that inp really isn’t null-terminated, and as a result, the strlen() call will blow up. Another problem is that the inp pointer might not be valid—checking for NULL is nice, but the pointer might still be illegal. For example, the pointer might point into kernel space, point too low into user space (<64KB), or be complete junk. However, if you do too much checking, your code will run slowly, so you have to make some compromises. However, as Steve Maguire points out in his book "Writing Solid Code", (ISBN: 1556155514), if you’re running around dereferencing null pointers, execution speed is the least of your worries.

So, what does this code do right? If you get any obvious errors or enter a string that's too long, you’ll fail gracefully, note the error, and return execution to the caller. A more complete example would return unique errors to the caller, but I've simplified the code in this example.

Is strncpy() Better?
The second library call, strncpy(), is defined as

char *strncpy( char *dest, const char *src, size_t count );

On the surface, this one looks better than strcpy()—at least it wants to know how many characters you’d like to stuff into the buffer. However, when you take a closer look, you see that it still has problems. For example, strncpy() still doesn't address the problem of dest or src being null, and if you lie to it about the character count, things can get ugly fast. Let’s look at some code to illustrate its usage:

void baz(const char* inp)
\{
   char buf\[25\];
   
   //always check the validity of your inputs
   if(inp  NULL)
   \{
      assert(false);
      printf("Yuck! You're passing a null     pointer!\n");
      return;
   \}
   
   strncpy(buf, inp, sizeof(buf)-1);
   //you always have to remember to null terminate
   buf\[sizeof(buf)-1\] = ‘\0’;
   //do more processing
   return;
\}

On the face of things, this function looks better. You don’t have to determine whether inp is too long, and you won’t overwrite the buffer—you'll just write one less byte than the buffer can hold. It also has the advantage of dealing properly with the case where inp isn’t null-terminated. Some people will argue that you should always use this function and never use strcpy(), but strncpy() has a few catches.

First, you have an additional step of ensuring that your buffer is null-terminated. Many programmers don’t read the fine print and forget this important step. If inp is too long, the function won't write the string's terminating null character in the buffer. If the function does write the terminating null character, you've just wasted an instruction.

Second, you need to consider the return of this function—all it gives you is a pointer to the destination string, and it doesn't reserve a value for an error. Imagine you've decided that if inp is longer than what can fit into the buffer, inp is junk and you should return an error (which I recommend in most cases). Using strncpy(), you can't easily determine this error, although I've seen various tricks that work, such as

//do this first
buf\[sizeof(buf)-1\] = '\0';
//tell strncpy that it can write into the whole buffer
strncpy(buf, inp, sizeof(buf));
   
//if the string was too long, this will be overwritten
if(buf\[sizeof(buf)-1\] != '\0')
\{
   printf("Inp string too long!\n");
   return;
\}

With this modification, you can armor the string handler against everything except some fairly unusual pointer errors. If you think this function seems like a lot of work to get a few characters safely into a buffer, you’re absolutely right.

_snprintf() to the Rescue
The third library call, _snprintf(), makes a lot of the code we've been examining easier to write and less error-prone. _snprintf() is defined as

int _snprintf( char *buffer, size_t count, const char *format \[, argument\] ... );

_snprintf() is also more versatile than the other two library calls, and you can do a lot of otherwise tricky string handling here. For example,

void foobar(const char* inp)
\{
   char buf\[25\];
   
   //check for illegal inputs
   if(inp <h1><a name="_NULL_assert_false_printf_Yuck_You_re_passing_a_null_pointer_n_return_if__snprintf_buf_sizeof_buf_1_s_inp_lt_0_printf_Input_string_too_long_n_return_else_always_null_terminate_buf_sizeof_buf_1_0_do_more_processing_return_pre_p_Note_that_you_still_have_to_determine_whether_inp_is_a_valid_pointer_and_you_always_have_to_remember_to_handle_the_case_where_inp_is_exactly_the_size_that_you_can_place_into_buf_and_use_sizeof_buf_1_not_the_entire_size_of_buf_I_find_this_code_a_lot_easier_to_read_and_understand_a_fact_that_other_programmers_who_have_to_work_on_your_code_will_appreciate_p_p_However_none_of_this_is_free__snprintf_is_more_versatile_e_g_you_can_use_it_to_convert_Unicode_to_and_from_single_byte_but_it_comes_with_more_overhead_For_example_if_performance_is_extremely_critical_such_as_in_an_embedded_system_you_might_not_want_to_use__snprintf_Another_problem_with_this_library_call_is_that_it_isn_#146_t_ANSI_standard_as_a_result_the_implementation_varies_between_Windows_based_and_UNIX_based_platforms_If_portability_is_a_concern_this_problem_can_be_sticky_because_not_all_UNIX_or_Linux_systems_offer_this_function_and_those_that_do_implement_it_in_different_ways_Some_implementations_return_the_number_of_bytes_that_you_need_in_your_buffer_if_an_error_occurs_and_some_implementations_always_null_terminate_If_portability_is_a_concern_verify_how_every_OS_you_#146_ll_support_deals_with_this_concern_and_consider_wrapping_it_When_you_wrap_a_function_you_create_a_function_that_behaves_the_same_to_the_outside_world_but_hides_the_differences_between_OSs_For_example_p_pre_int_My_snprintf_char_buffer_size_t_count_const_char_format_argument_#ifdef_WIN32_Do_things_the_Windows_way_#else_Do_things_the_UNIX_way_#endif_pre_p_When_you_compile_this_code_under_NT_or_UNIX_it_works_as_it_should_#151_the_rest_of_the_application_doesn_#146_t_have_to_include_the_#ifdef_stuff_everywhere_we_need_to_do_the_same_thing_In_this_case_we_#146_d_create_a_My_sprintf_which_is_actually_quite_difficult_because_of_the_variable_number_of_arguments_to__snprintf_p_p_font_class_subhead_STL_and_String_font_br_As_it_turns_out_C_and_the_STL_are_a_great_help_because_under_the_new_ANSI_C_specification_string_is_a_standard_data_type_and_many_common_jobs_related_to_strings_have_well_implemented_methods_that_help_Let_#146_s_look_at_the_code_p_pre_void_barbaz_const_char_inp_string_str_check_for_illegal_inputs_if_inp_"> NULL)
   \{
       assert(false);
                 printf("Yuck! You're passing a null     pointer!\n");
      return;
   \}
   
   if(_snprintf(buf, sizeof(buf)-1, "%s", inp) < 0)
   \{
      printf("Input string too long!\n");
      return;
    \}
    else
    \{
       //always null terminate
       buf\[sizeof(buf)-1\] = '\0';
    \}
    //do more processing
    return;
    \}
</a></h1>

Note that you still have to determine whether inp is a valid pointer, and you always have to remember to handle the case where inp is exactly the size that you can place into buf and use sizeof(buf)-1, not the entire size of buf. I find this code a lot easier to read and understand, a fact that other programmers who have to work on your code will appreciate.

However, none of this is free. _snprintf() is more versatile (e.g., you can use it to convert Unicode to and from single-byte), but it comes with more overhead. For example, if performance is extremely critical, such as in an embedded system, you might not want to use _snprintf(). Another problem with this library call is that it isn’t ANSI standard; as a result, the implementation varies between Windows-based and UNIX-based platforms. If portability is a concern, this problem can be sticky because not all UNIX (or Linux) systems offer this function, and those that do implement it in different ways. Some implementations return the number of bytes that you need in your buffer if an error occurs, and some implementations always null-terminate. If portability is a concern, verify how every OS you’ll support deals with this concern, and consider wrapping it. When you wrap a function, you create a function that behaves the same to the outside world, but hides the differences between OSs. For example,

int My_snprintf( char *buffer, size_t count, const char *format \[, argument\] ... )
    \{
    #ifdef WIN32
    Do things the Windows way
    #else
    Do things the UNIX way
    #endif
    \}

When you compile this code under NT or UNIX, it works as it should—the rest of the application doesn’t have to include the #ifdef stuff everywhere we need to do the same thing. In this case, we’d create a My_sprintf(), which is actually quite difficult because of the variable number of arguments to _snprintf.

STL and String
As it turns out, C++ and the STL are a great help because under the new ANSI C++ specification, string is a standard data type and many common jobs related to strings have well-implemented methods that help. Let’s look at the code:

 
void barbaz(const char* inp)
\{
   string str;
   //check for illegal inputs
   if(inp  NULL)
   \{
      assert(false);
                printf("Yuck! You're passing a null    pointer!\n");
      return;
    \}
   
     //this is easy!
          str = inp;
          //now check to see if it was too long, or had nothing in it
     if(str.length() > 25 || str.empty())
     \{
             printf("Input string invalid\n");
                  return;
     \}
     //do more processing
\}

Although this code doesn’t address the case where inp isn’t terminated, the following line will:

str.copy(inp, 26);

How your code handles long strings depends on whether you want to enforce a 25-character limit or just selected this limit because it was convenient.

I’ve shown you some of the perils of string handling, and the compromises you encounter using three C calls and a portion of the STL. Improper string handling frequently results in security problems, and I hope this information will help you avoid letting your code become part of an attack on someone’s computer.