In: Computer Science
Working with strings can lead to various security flaws and errors in software development using the C++ language. What are the common string manipulation errors that can be encountered? How can these errors be resolved and/or limited? What tips can be utilized to identify security vulnerabilities related to strings in C++? Be sure to provide an appropriate source code example to illustrate your points.
Working with strings in C++ may lead to manipulation errors and needs to be resolved. Some of the common errors include :
#include <iostream.h> int main() { char buff[12]; cin.width(12); cin >> buff; cout << "echo: " << buff << endl; } In some cases, String Truncation errors may lead to loss of data, or even software vulnerabilities too.
int main(int argc, char *argv[]) { int j = 0; char buff[128]; char *arg1 = argv[1]; while (arg1[j] != '\0' ) { buff[j] = arg1[j]; i++; } buff[j] = '\0'; printf("buff = %s\n", buff); }
int main(int argc, char* argv[]) { char x[16]; char y[16]; char z[32]; strcpy(x, "0123456789abcdef"); strcpy(y, "0123456789abcdef"); strcpy(z, x); strcat(z, y); printf("x = %s\n", x); return 0; }
void main(void) { char Pass[80]; puts("Enter 8 character password:"); gets(Pass); }
bool IsPasswordOk(void) { char Pass[12]; gets(Pass); if (!strcmp(Pass, "good password")) return(true); else return(false); } void main(void) { bool PswrdStatus; puts("Enter password:"); PswrdStatus = IsPasswordOk(); if (PswrdStatus == false) { puts("Access denied"); exit(-1); } else puts("Access granted"); } The get password program starts in the main() routine. The first line executed is the puts() call that prints out a string literal . The puts() function is defined in C++ as a character i/o function, is declared in stdio.h, and writes a string to the input stream pointed to by stdin followed by a newline character ('\n'). The IsPasswordOk() function is called to retrieve a password from the user . The function returns a boolean value: true if the password is valid, false if it is not. The value of PswrdStatus is tested and access is allowed or denied.The IsPasswordOk() function uses the gets() function to read characters from the input stream (pointed to by stdin) into the array pointed to by Password until an EOF is encountered or a newline character is read. Any newline character is discarded, and a null character is written immediately after the last character read into the array. The strcmp() function defined in string.h compares the string pointed to by Password to the string literal "good password" and returns an integer value of zero if the strings are equal and a nonzero integer value if they are not. The IsPasswordOk() function returns true if the password is "good password" and the main() function consequently grants access.