Automated static analysis, commonly referred to as Static Application Security Testing (SAST), can find some instances of this weakness by analyzing source code (or binary/compiled code) without having to execute it. Typically, this is done by building a model of data flow and control flow, then searching for potentially-vulnerable patterns that connect "sources" (origins of input) with "sinks" (destinations where the data interacts with external components, a lower layer such as the OS, etc.)
Off-by-one Error
An off-by-one error occurs when a program incorrectly calculates a boundary, such as a loop counter or array index, by being one unit too high or too low. This often leads to buffer overflows,…
What is CWE-193?
Real-world CVEs caused by CWE-193
-
Off-by-one error allows remote attackers to cause a denial of service and possibly execute arbitrary code via requests that do not contain newlines.
-
Off-by-one vulnerability in driver allows users to modify kernel memory.
-
Off-by-one error allows local users or remote malicious servers to gain privileges.
-
Off-by-one buffer overflow in function usd by server allows local users to execute arbitrary code as the server user via .htaccess files with long entries.
-
Off-by-one buffer overflow in version control system allows local users to execute arbitrary code.
-
Off-by-one error in FTP server allows a remote attacker to cause a denial of service (crash) via a long PORT command.
-
Off-by-one buffer overflow in FTP server allows local users to gain privileges via a 1024 byte RETR command.
-
Multiple buffer overflows in chat client allow remote attackers to cause a denial of service and possibly execute arbitrary code.
Parcours de l'attaquant étape par étape
- 1
The following code allocates memory for a maximum number of widgets. It then gets a user-specified number of widgets, making sure that the user does not request too many. It then initializes the elements of the array using InitializeWidget(). Because the number of widgets can vary for each request, the code inserts a NULL pointer to signify the location of the last widget.
- 2
However, this code contains an off-by-one calculation error (CWE-193). It allocates exactly enough space to contain the specified number of widgets, but it does not include the space for the NULL pointer. As a result, the allocated buffer is smaller than it is supposed to be (CWE-131). So if the user ever requests MAX_NUM_WIDGETS, there is an out-of-bounds write (CWE-787) when the NULL is assigned. Depending on the environment and compilation settings, this could cause memory corruption.
- 3
In this example, the code does not account for the terminating null character, and it writes one byte beyond the end of the buffer.
- 4
The first call to strncat() appends up to 20 characters plus a terminating null character to fullname[]. There is plenty of allocated space for this, and there is no weakness associated with this first call. However, the second call to strncat() potentially appends another 20 characters. The code does not account for the terminating null character that is automatically added by strncat(). This terminating null character would be written one byte beyond the end of the fullname[] buffer. Therefore an off-by-one error exists with the second strncat() call, as the third argument should be 19.
- 5
When using a function like strncat() one must leave a free byte at the end of the buffer for a terminating null character, thus avoiding the off-by-one weakness. Additionally, the last argument to strncat() is the number of characters to append, which must be less than the remaining space in the buffer. Be careful not to just use the total size of the buffer.
Vulnerable C
The following code allocates memory for a maximum number of widgets. It then gets a user-specified number of widgets, making sure that the user does not request too many. It then initializes the elements of the array using InitializeWidget(). Because the number of widgets can vary for each request, the code inserts a NULL pointer to signify the location of the last widget.
int i;
unsigned int numWidgets;
Widget **WidgetList;
numWidgets = GetUntrustedSizeValue();
if ((numWidgets == 0) || (numWidgets > MAX_NUM_WIDGETS)) {
ExitError("Incorrect number of widgets requested!");
}
WidgetList = (Widget **)malloc(numWidgets * sizeof(Widget *));
printf("WidgetList ptr=%p\n", WidgetList);
for(i=0; i<numWidgets; i++) {
WidgetList[i] = InitializeWidget();
}
WidgetList[numWidgets] = NULL;
showWidgets(WidgetList); Secure C
When using a function like strncat() one must leave a free byte at the end of the buffer for a terminating null character, thus avoiding the off-by-one weakness. Additionally, the last argument to strncat() is the number of characters to append, which must be less than the remaining space in the buffer. Be careful not to just use the total size of the buffer.
char firstname[20];
char lastname[20];
char fullname[40];
fullname[0] = '\0';
strncat(fullname, firstname, sizeof(fullname)-strlen(fullname)-1);
strncat(fullname, lastname, sizeof(fullname)-strlen(fullname)-1); How to prevent CWE-193
- Implementation When copying character arrays or using character manipulation methods, the correct size parameter must be used to account for the null terminator that needs to be added at the end of the array. Some examples of functions susceptible to this weakness in C include strcpy(), strncpy(), strcat(), strncat(), printf(), sprintf(), scanf() and sscanf().
How to detect CWE-193
Plexicus détecte automatiquement CWE-193 et ouvre une PR de correction en moins de 60 secondes.
Codex Remedium analyse chaque commit, identifie cette faiblesse précise et livre une pull request prête à être relue avec le correctif. Pas de tickets. Pas de transferts.
Frequently asked questions
Qu'est-ce que CWE-193 ?
An off-by-one error occurs when a program incorrectly calculates a boundary, such as a loop counter or array index, by being one unit too high or too low. This often leads to buffer overflows, memory corruption, or unexpected program behavior.
Quelle est la gravité de CWE-193 ?
MITRE n'a pas publié de note de probabilité d'exploitation pour cette faiblesse. Traitez-la comme un impact moyen jusqu'à ce que votre modèle de menace prouve le contraire.
Quels langages ou plateformes sont affectés par CWE-193 ?
MITRE lists the following affected platforms: C.
Comment puis-je prévenir CWE-193 ?
When copying character arrays or using character manipulation methods, the correct size parameter must be used to account for the null terminator that needs to be added at the end of the array. Some examples of functions susceptible to this weakness in C include strcpy(), strncpy(), strcat(), strncat(), printf(), sprintf(), scanf() and sscanf().
Comment Plexicus détecte et corrige CWE-193 ?
Le moteur SAST de Plexicus reconnaît la signature de flux de données de CWE-193 à chaque commit. Lorsqu'une correspondance est trouvée, notre agent Codex Remedium ouvre une PR de correction avec le code corrigé, les tests et un résumé d'une ligne pour le relecteur.
Où puis-je en savoir plus sur CWE-193 ?
MITRE publie la définition canonique à https://cwe.mitre.org/data/definitions/193.html. Vous pouvez également consulter la documentation OWASP et NIST pour des conseils adjacents.
Weaknesses related to CWE-193
Incorrect Calculation
This vulnerability occurs when software performs a calculation that produces wrong or unexpected results, which are then used to make…
Wrap-around Error
A wrap-around error happens when a variable exceeds the maximum value its data type can hold, causing it to unexpectedly reset to a very…
Incorrect Calculation of Buffer Size
This vulnerability occurs when a program miscalculates the amount of memory needed for a buffer, potentially leading to a buffer overflow…
Incorrect Bitwise Shift of Integer
This vulnerability occurs when a program attempts to shift an integer's bits by an invalid amount—either a negative number or a value…
Insufficient Precision or Accuracy of a Real Number
This vulnerability occurs when a program uses a data type or algorithm that cannot accurately represent or calculate the fractional part…
Incorrect Calculation of Multi-Byte String Length
This vulnerability occurs when software incorrectly measures the length of strings containing multi-byte or wide characters, leading to…
Integer Overflow or Wraparound
Integer overflow or wraparound occurs when a calculation produces a numeric result that exceeds the maximum value a variable can hold.…
Integer Underflow (Wrap or Wraparound)
Integer underflow occurs when a subtraction operation results in a value smaller than the data type's minimum limit, causing the value to…
Divide By Zero
A divide-by-zero error occurs when software attempts to perform a division operation where the denominator is zero.
Further reading
- MITRE — CWE-193 officiel https://cwe.mitre.org/data/definitions/193.html
- Third Generation Exploits https://view.officeapps.live.com/op/view.aspx?src=https%3A%2F%2Fwww.blackhat.com%2Fpresentations%2Fbh-europe-01%2Fhalvar-flake%2Fbh-europe-01-halvarflake.ppt&wdOrigin=BROWSELINK
- Off-by-one errors: a brief explanation https://marc.info/?l=secprog&m=108379742110553&w=2
- The Frame Pointer Overwrite https://phrack.org/issues/55/8
- Exploiting Software: How to Break Code https://www.amazon.com/Exploiting-Software-How-Break-Code/dp/0201786958
Arrêtez de payer par développeur.
Commencez à fermer la boucle.
Plexicus est l'ASPM natif IA qui scanne, filtre, corrige, penteste et explique — de façon autonome. Développeurs illimités, dépôts illimités, actions IA à usage équitable. Vrai niveau gratuit, €269/mo annuel quand vous êtes prêt.