<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[DevSecOpsGuides]]></title><description><![CDATA[DevSecOpsGuides]]></description><link>https://devsecopsguides.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Tue, 20 Oct 2026 15:42:15 GMT</lastBuildDate><atom:link href="https://devsecopsguides.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Top System Programming Vulnerabilities]]></title><description><![CDATA[In the code above, the gets() function doesn't perform any bounds checking on the input, which allows a buffer overflow if the user provides an input…]]></description><link>https://devsecopsguides.hashnode.dev/top-system-programming-vulnerabilities</link><guid isPermaLink="true">https://devsecopsguides.hashnode.dev/top-system-programming-vulnerabilities</guid><category><![CDATA[DevSecOps]]></category><category><![CDATA[Devops]]></category><category><![CDATA[secure coding]]></category><category><![CDATA[Security]]></category><category><![CDATA[programming]]></category><dc:creator><![CDATA[Reza Rashidi]]></dc:creator><pubDate>Mon, 06 Nov 2023 12:31:50 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1699274512240/f995d6dd-7e9a-48ac-b907-76642bd34c11.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-1-buffer-overflow"><strong>1. Buffer overflow</strong></h2>
<h3 id="heading-noncompliant-code-vulnerable-to-buffer-overflow"><strong>Noncompliant Code (Vulnerable to Buffer Overflow):</strong></h3>
<h4 id="heading-cpp"><strong>CPP</strong></h4>
<pre><code class="lang-plaintext">#include &lt;stdio.h&gt;

int main(int argc, char **argv)
{
  volatile int important_data = 0;
  char user_input[10];

  gets(user_input);  // Vulnerable function

  if(important_data != 0) {
    printf("Warning !!!, the 'important_data' was changed\n");
  } else {
    printf("the 'important_data' was not changed\n");
  }
}
</code></pre>
<p>In the code above, the gets() function doesn't perform any bounds checking on the input, which allows a buffer overflow if the user provides an input larger than user_input array's size.</p>
<h4 id="heading-c"><strong>C</strong></h4>
<pre><code class="lang-plaintext">#include &lt;stdio.h&gt;
#include &lt;string.h&gt;

int main() {
    char buffer[10];
    // The data_to_corrupt variable is placed right after the buffer in the stack.
    int data_to_corrupt = 0;

    printf("Enter a long string to cause a buffer overflow: ");
    // gets() is a dangerous function that does not check the length of the input.
    // It will continue to write data past the end of the buffer if the input is too long.
    gets(buffer);

    // If a buffer overflow occurred, data_to_corrupt may have been altered.
    if (data_to_corrupt != 0) {
        printf("Buffer overflow occurred! data_to_corrupt = %d\n", data_to_corrupt);
    } else {
        printf("No buffer overflow. data_to_corrupt = %d\n", data_to_corrupt);
    }

    return 0;
}
</code></pre>
<ul>
<li><p>buffer is a character array that can hold 10 bytes.</p>
</li>
<li><p>gets(buffer) is used to read a string from the standard input without checking the size, which can lead to a buffer overflow if the input is longer than 9 characters (plus the null terminator).</p>
</li>
<li><p>data_to_corrupt is an integer variable that will be placed in memory directly after buffer on the stack. If buffer overflows, data_to_corrupt can be overwritten with arbitrary values.</p>
</li>
</ul>
<h4 id="heading-rust"><strong>Rust</strong></h4>
<pre><code class="lang-plaintext">use std::io::{self, Read};

fn main() {
    let mut important_data = 0;
    let mut buffer = [0u8; 10];

    // Mimic unsafe behavior similar to gets() in C
    // This is unsafe and not recommended!
    unsafe {
        let buffer_ptr = buffer.as_mut_ptr();
        let buffer_size = buffer.len();
        let mut input = io::stdin().bytes();

        // Read bytes directly into the buffer without bounds checking
        for i in 0.. {
            if let Some(Ok(byte)) = input.next() {
                *buffer_ptr.add(i) = byte; // Potential buffer overflow if input &gt; 10 bytes
                if byte == b'\n' {
                    break;
                }
            } else {
                break;
            }
        }

        // Simulate a situation where the buffer overflow could overwrite important_data
        if buffer_size &lt; 12 {
            // This is where the overflow would affect important_data
            *buffer_ptr.add(11) = 0xFF; // Deliberately writing outside of the buffer
        }
    }

    if important_data != 0 {
        println!("Warning !!!, the 'important_data' was changed");
    } else {
        println!("The 'important_data' was not changed");
    }
}
</code></pre>
<ul>
<li><p>We use an unsafe block to allow us to perform raw pointer operations.</p>
</li>
<li><p>We create a raw pointer to the buffer and manually index into it, which is not bounds-checked.</p>
</li>
<li><p>We deliberately write outside the bounds of the buffer to simulate a buffer overflow that overwrites important_data.</p>
</li>
</ul>
<h3 id="heading-compliant-code-safe-from-buffer-overflow"><strong>Compliant Code (Safe from Buffer Overflow):</strong></h3>
<h4 id="heading-cpp-1"><strong>CPP</strong></h4>
<pre><code class="lang-plaintext">#include &lt;stdio.h&gt;

int main(int argc, char **argv)
{
  volatile int important_data = 0;
  char user_input[10];

  fgets(user_input, sizeof(user_input), stdin);  // Safe function

  if(important_data != 0) {
    printf("Warning !!!, the 'important_data' was changed\n");
  } else {
    printf("the 'important_data' was not changed\n");
  }
}
</code></pre>
<ul>
<li>In this compliant version, the fgets() function is used instead of gets(). The fgets() function takes a size argument which prevents reading more characters than the buffer can hold, hence preventing a buffer overflow.</li>
</ul>
<h4 id="heading-c-1"><strong>C</strong></h4>
<pre><code class="lang-plaintext">#include &lt;stdio.h&gt;
#include &lt;string.h&gt;

#define BUFFER_SIZE 10

int main() {
    char buffer[BUFFER_SIZE];
    int data_to_protect = 0;

    printf("Enter a string up to 9 characters: ");
    // Use fgets to prevent buffer overflow. It reads up to BUFFER_SIZE-1 characters
    // and appends a null terminator.
    if (fgets(buffer, BUFFER_SIZE, stdin) == NULL) {
        printf("Error reading input.\n");
        return 1; // Return an error code if input fails
    }

    // Remove newline character if present, as fgets includes it in the buffer.
    buffer[strcspn(buffer, "\n")] = 0;

    // The rest of your code remains unchanged
    if (data_to_protect != 0) {
        printf("Buffer overflow occurred! data_to_protect = %d\n", data_to_protect);
    } else {
        printf("No buffer overflow. data_to_protect = %d\n", data_to_protect);
    }

    return 0; // Return a success code
}
</code></pre>
<ul>
<li><p>BUFFER_SIZE is defined as the size of the buffer, including space for the null terminator.</p>
</li>
<li><p>fgets(buffer, BUFFER_SIZE, stdin) is used to read input from stdin. It reads up to BUFFER_SIZE - 1 characters and appends a null terminator, preventing buffer overflow.</p>
</li>
<li><p>buffer[strcspn(buffer, "\n")] = 0; is used to remove the newline character that fgets() reads and includes in the buffer if there is one.</p>
</li>
<li><p>The data_to_protect variable should remain unchanged if the input is within the buffer's limits, demonstrating that no buffer overflow has occurred.</p>
</li>
</ul>
<h4 id="heading-rust-1"><strong>Rust</strong></h4>
<pre><code class="lang-plaintext">use std::io;

fn main() {
    let mut important_data = 0;
    let mut user_input = String::new();

    println!("Please enter some input (up to 9 characters): ");

    // Read input from the user safely
    match io::stdin().read_line(&amp;mut user_input) {
        Ok(_) =&gt; {
            // Truncate the input to the first 9 characters to prevent overflow
            user_input.truncate(9);

            // Here we would have logic that could potentially change important_data
            // For the sake of this example, let's say if the user types "change",
            // we change the important_data to 1.
            if user_input.trim() == "change" {
                important_data = 1;
            }
        },
        Err(error) =&gt; println!("Error reading input: {}", error),
    }

    // Check if important_data has been changed
    if important_data != 0 {
        println!("Warning: the 'important_data' was changed");
    } else {
        println!("The 'important_data' was not changed");
    }
}
</code></pre>
<ul>
<li><p>We use String::new() to create a new, empty String for user_input.</p>
</li>
<li><p>We use io::stdin().read_line(&amp;mut user_input) to safely read a line of input from the user into user_input. This method handles buffer sizing and grows as needed, preventing buffer overflow.</p>
</li>
<li><p>We use user_input.truncate(9) to ensure that only the first 9 characters of the input (if any) are considered, preventing any logic that follows from acting on unexpected data.</p>
</li>
<li><p>We use user_input.trim() to remove any leading or trailing whitespace, which is common when dealing with user input from the console.</p>
</li>
</ul>
<p>2. Integer overflow and underflow</p>
<h3 id="heading-noncompliant-code-vulnerable-to-integer-overflow"><strong>Noncompliant Code (Vulnerable to Integer Overflow):</strong></h3>
<h4 id="heading-cpp-2"><strong>CPP</strong></h4>
<pre><code class="lang-plaintext">#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;

int main() {
    unsigned int nresp;
    char **response;

    scanf("%u", &amp;nresp);  // Read an unsigned integer from input

    // This may cause an integer overflow if nresp is very large
    response = (char**) malloc(nresp * sizeof(char*));  

    if (response == NULL) {
        printf("Memory allocation failed!\n");
        return 1;
    }

    // ... rest of the code ...

    free(response);
    return 0;
}
</code></pre>
<p>If nresp is a large value, multiplying it by sizeof(char*) can cause an overflow, resulting in a smaller memory allocation than expected.</p>
<h4 id="heading-c-2"><strong>C</strong></h4>
<pre><code class="lang-plaintext">#include &lt;stdio.h&gt;
#include &lt;limits.h&gt;

int main() {
    unsigned int uint_max = UINT_MAX;
    unsigned int overflowed_value = uint_max + 1;

    printf("Maximum value for unsigned int: %u\n", uint_max);
    printf("Value after overflow: %u\n", overflowed_value);

    int int_max = INT_MAX;
    int overflowed_int_value = int_max + 1;

    printf("Maximum value for int: %d\n", int_max);
    printf("Value after overflow: %d\n", overflowed_int_value);

    return 0;
}
</code></pre>
<p>UINT_MAX is the maximum value for an unsigned integer, and INT_MAX is the maximum value for a signed integer.</p>
<p>Adding 1 to UINT_MAX causes an overflow in the unsigned integer, which is well-defined in C: it wraps around to 0.</p>
<p>Adding 1 to INT_MAX causes an overflow in the signed integer, which is undefined behavior in C. The program may wrap around to INT_MIN, but since it's undefined, it could also crash or behave unpredictably.</p>
<h4 id="heading-rust-2"><strong>Rust</strong></h4>
<pre><code class="lang-plaintext">fn main() {
    let large_value: u32 = std::u32::MAX - 1;
    let addend: u32 = 2;

    // This is unsafe and will cause undefined behavior if the assumption is wrong
    unsafe {
        let result = large_value.unchecked_add(addend);
        println!("Result of the overflow: {}", result);
    }
}
</code></pre>
<p>unchecked_add is used within an unsafe block. This method is unsafe because it does not check for overflow, allowing for silent wraparound.</p>
<p>This code will compile and run without panicking even in debug mode, but it is considered undefined behavior according to Rust's safety rules.</p>
<h3 id="heading-compliant-code-protected-from-integer-overflow"><strong>Compliant Code (Protected from Integer Overflow):</strong></h3>
<h4 id="heading-cpp-3"><strong>CPP</strong></h4>
<pre><code class="lang-plaintext">#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;
#include &lt;limits.h&gt;

int main() {
    unsigned int nresp;
    char **response;

    scanf("%u", &amp;nresp);  // Read an unsigned integer from input

    // Check for potential integer overflow
    if (nresp &gt; (UINT_MAX / sizeof(char*))) {
        printf("Input too large!\n");
        return 1;
    }

    response = (char**) malloc(nresp * sizeof(char*));

    if (response == NULL) {
        printf("Memory allocation failed!\n");
        return 1;
    }

    // ... rest of the code ...

    free(response);
    return 0;
}
</code></pre>
<ul>
<li>In this compliant code, we added a condition to check if multiplying nresp with sizeof(char*) will cause an overflow by dividing the maximum unsigned integer (UINT_MAX) by sizeof(char*) and comparing it against nresp. If nresp exceeds the result of this division, then the multiplication will result in an overflow, and the program will output an error message and exit.</li>
</ul>
<h4 id="heading-c-3"><strong>C</strong></h4>
<pre><code class="lang-plaintext">#include &lt;stdio.h&gt;
#include &lt;limits.h&gt;

int main() {
    unsigned int uint_max = UINT_MAX;
    unsigned int a = uint_max - 1;
    unsigned int b = 2;

    // Check for overflow before performing the addition
    if (a &gt; UINT_MAX - b) {
        printf("Error: unsigned int overflow detected\n");
    } else {
        unsigned int result = a + b;
        printf("Result of unsigned int addition: %u\n", result);
    }

    int int_max = INT_MAX;
    int c = int_max - 1;
    int d = 2;

    // Check for overflow before performing the addition
    if (c &gt; 0 &amp;&amp; d &gt; INT_MAX - c) {
        printf("Error: signed int overflow detected\n");
    } else {
        int result = c + d;
        printf("Result of signed int addition: %d\n", result);
    }

    return 0;
}
</code></pre>
<ul>
<li><p>Before adding two unsigned integers, we check if the first integer a is greater than UINT_MAX - b. If this is true, adding b to a would cause an overflow.</p>
</li>
<li><p>Before adding two signed integers, we check if c is positive and if d is greater than INT_MAX - c. If this is true, adding d to c would cause an overflow.</p>
</li>
</ul>
<h4 id="heading-rust-3"><strong>Rust</strong></h4>
<pre><code class="lang-plaintext">fn main() {
    let a: u32 = std::u32::MAX;
    let b: u32 = 1;

    // Use checked_add to prevent overflow
    match a.checked_add(b) {
        Some(result) =&gt; println!("Result of addition: {}", result),
        None =&gt; println!("Error: unsigned integer overflow detected"),
    }

    let c: i32 = std::i32::MAX;
    let d: i32 = 1;

    // Use checked_add to prevent overflow
    match c.checked_add(d) {
        Some(result) =&gt; println!("Result of addition: {}", result),
        None =&gt; println!("Error: signed integer overflow detected"),
    }
}
</code></pre>
<ul>
<li><p>checked_add is used to perform the addition. If the addition does not overflow, it returns Some(result), where result is the sum of a and b.</p>
</li>
<li><p>If the addition would cause an overflow, checked_add returns None, and the program prints an error message instead of panicking or wrapping around.</p>
</li>
</ul>
<h2 id="heading-3-pointer-initialization"><strong>3. Pointer initialization</strong></h2>
<h3 id="heading-noncompliant-code-vulnerable-to-dereferencing-uninitialized-pointer"><strong>Noncompliant Code (Vulnerable to Dereferencing Uninitialized Pointer):</strong></h3>
<h4 id="heading-cpp-4"><strong>CPP</strong></h4>
<pre><code class="lang-plaintext">#include &lt;stdio.h&gt;

void main() {
    int *ptr;  // uninitialized pointer

    if (nullptr != ptr) {  // incorrect check, can lead to undefined behavior
        *ptr = 5;
        printf("%d\n", *ptr);
    }
}
</code></pre>
<p>In the above code, the pointer ptr is uninitialized. Dereferencing an uninitialized pointer can result in undefined behavior. The check against nullptr is also incorrect since nullptr is a C++ keyword and not valid in C. The behavior is unpredictable since ptr might contain a garbage value.</p>
<h4 id="heading-c-4"><strong>C</strong></h4>
<pre><code class="lang-plaintext">#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;

int main() {
    int *initialized_pointer = malloc(sizeof(int)); // Allocate memory for an integer
    if (initialized_pointer == NULL) {
        fprintf(stderr, "Memory allocation failed\n");
        return 1;
    }

    *initialized_pointer = 42; // Dereference the initialized pointer safely

    printf("Value of the data pointed to by initialized_pointer: %d\n", *initialized_pointer);

    free(initialized_pointer); // Free the allocated memory

    return 0;
}
</code></pre>
<p>uninitialized_pointer is declared but not initialized; it points to some arbitrary memory location.</p>
<p>The program then attempts to write the value 42 to this location, which is unsafe because the pointer could be pointing anywhere.</p>
<p>Finally, the program attempts to print the value from the same location, which is also unsafe.</p>
<h4 id="heading-rust-4"><strong>Rust</strong></h4>
<pre><code class="lang-plaintext">fn main() {
    let uninitialized_pointer: *mut i32; // Declare a raw pointer but do not initialize it

    unsafe {
        // UNSAFE: Dereferencing an uninitialized pointer is undefined behavior
        *uninitialized_pointer = 42; // Attempt to write through the uninitialized pointer

        println!("Value of the data pointed to by uninitialized_pointer: {}", *uninitialized_pointer);
    }
}
</code></pre>
<p>data is a valid variable with an initial value.</p>
<p>initialized_pointer is a raw pointer that is initialized to the address of data.</p>
<p>The unsafe block is used to dereference the raw pointer, but this time it is safe because the pointer is initialized to a valid memory address.</p>
<h3 id="heading-compliant-code-proper-pointer-initialization"><strong>Compliant Code (Proper Pointer Initialization):</strong></h3>
<h4 id="heading-cpp-5"><strong>CPP</strong></h4>
<pre><code class="lang-plaintext">#include &lt;stdio.h&gt;

void main() {
    int *ptr = NULL;  // properly initialized pointer

    if (ptr != NULL) {  // correct check
        *ptr = 5;  // This code will not be executed because ptr is NULL
        printf("%d\n", *ptr);
    }
}
</code></pre>
<ul>
<li>In this compliant code, the pointer ptr is properly initialized to NULL. The check against NULL ensures that the pointer is not dereferenced when it is null, preventing any undefined behavior.</li>
</ul>
<h4 id="heading-c-5"><strong>C</strong></h4>
<pre><code class="lang-plaintext">#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;

int main() {
    int *initialized_pointer = malloc(sizeof(int)); // Allocate memory for an integer
    if (initialized_pointer == NULL) {
        fprintf(stderr, "Memory allocation failed\n");
        return 1;
    }

    *initialized_pointer = 42; // Dereference the initialized pointer safely

    printf("Value of the data pointed to by initialized_pointer: %d\n", *initialized_pointer);

    free(initialized_pointer); // Free the allocated memory

    return 0;
}
</code></pre>
<ul>
<li><p>Memory is allocated for an integer using malloc, and initialized_pointer is set to point to this memory.</p>
</li>
<li><p>Before dereferencing the pointer, the code checks if malloc returned NULL, which would indicate that the memory allocation failed.</p>
</li>
<li><p>After using the allocated memory, free is called to deallocate the memory, preventing a memory leak.</p>
</li>
</ul>
<h4 id="heading-rust-5"><strong>Rust</strong></h4>
<pre><code class="lang-plaintext">fn main() {
    let mut value = 0; // A mutable variable with an initial value
    let value_ptr = &amp;mut value as *mut i32; // Create a raw pointer to `value`

    unsafe {
        // SAFE: Dereferencing a pointer to memory we own is okay within an unsafe block
        *value_ptr = 42; // Dereference the pointer to write to `value`
        println!("Value: {}", *value_ptr); // Dereference the pointer to read `value`
    }
}
</code></pre>
<ul>
<li><p>value is a variable that is properly initialized.</p>
</li>
<li><p>value_ptr is a raw pointer that is created by taking the address of value.</p>
</li>
<li><p>An unsafe block is used to dereference value_ptr. This is necessary because all operations on raw pointers are considered unsafe in Rust. However, this is compliant with Rust's safety rules because we know that value_ptr points to valid memory.</p>
</li>
</ul>
<h2 id="heading-4-incorrect-type-conversion"><strong>4. Incorrect type conversion</strong></h2>
<h3 id="heading-noncompliant-code-vulnerable-to-incorrect-type-conversion">Noncompliant Code (Vulnerable to Incorrect Type Conversion):</h3>
<h4 id="heading-cpp-6">**CPP</h4>
<p>**</p>
<pre><code class="lang-plaintext">#include &lt;iostream&gt;
#include &lt;string&gt;
using namespace std;

int main()
{
    string str;
    cout &lt;&lt; "Please enter your string: \n";
    getline(cin, str);
    unsigned int len = str.length();
    if (len &gt; -1)
    {
        cout &lt;&lt; "string length is " &lt;&lt; len &lt;&lt; " which is bigger than -1 " &lt;&lt; std::endl;
    } 
    else 
    {
        cout &lt;&lt; "string length is " &lt;&lt; len &lt;&lt; " which is less than -1 " &lt;&lt;std::endl;
    }
    return 0;
}
</code></pre>
<p>As you've explained, due to the incorrect type conversion, comparing an unsigned int with -1 will always result in the else branch being executed.</p>
<h4 id="heading-c-6"><strong>C</strong></h4>
<pre><code class="lang-plaintext">#include &lt;stdio.h&gt;

int main() {
    long large_number = 9223372036854775807; // Maximum value for a signed long on a 64-bit system
    int truncated_number = (int)large_number; // Incorrectly casting to a smaller type

    printf("Original large number: %ld\n", large_number);
    printf("Truncated number: %d\n", truncated_number);

    // Incorrect pointer type conversion
    double pi = 3.141592653589793;
    int *pi_int_pointer = (int *)&amp;pi; // Cast a double pointer to an int pointer

    printf("Incorrectly interpreted value of pi: %d\n", *pi_int_pointer);

    return 0;
}
</code></pre>
<p>large_number is a long that contains the maximum value that can be stored in a signed long on a 64-bit system. Casting it to an int can truncate the value, leading to data loss and undefined behavior.</p>
<p>pi is a double, but its address is cast to an int*, and then dereferenced. This violates strict aliasing rules and leads to undefined behavior because the memory representation of a double is being incorrectly interpreted as an int.</p>
<h4 id="heading-rust-6"><strong>Rust</strong></h4>
<pre><code class="lang-plaintext">fn main() {
    let large_number: i64 = 9223372036854775807; // Maximum value for i64
    let truncated_number = large_number as i32; // Unsafe truncation

    println!("Original large number: {}", large_number);
    println!("Truncated number: {}", truncated_number);

    // Unsafe pointer type conversion
    let pi: f64 = 3.141592653589793;
    let pi_pointer = &amp;pi as *const f64 as *const i32; // Cast a f64 pointer to an i32 pointer

    unsafe {
        println!("Incorrectly interpreted value of pi: {}", *pi_pointer);
    }
}
</code></pre>
<p>large_number is cast to i32, which can lead to truncation and data loss because i64 can represent a wider range of values than i32.</p>
<p>pi is a f64, and its pointer is cast to a pointer to i32. Dereferencing this pointer is undefined behavior because f64 and i32 have different sizes and memory representations.</p>
<h3 id="heading-compliant-code-proper-type-conversion"><strong>Compliant Code (Proper Type Conversion):</strong></h3>
<h3 id="heading-cpp-7"><strong>CPP</strong></h3>
<pre><code class="lang-plaintext">#include &lt;iostream&gt;
#include &lt;string&gt;
using namespace std;

int main()
{
    string str;
    cout &lt;&lt; "Please enter your string: \n";
    getline(cin, str);
    size_t len = str.length(); // 'size_t' is an unsigned type representing the size of objects in bytes.
    if (len &gt; static_cast&lt;size_t&gt;(-1)) // Casting -1 to size_t for proper comparison.
    {
        cout &lt;&lt; "string length is " &lt;&lt; len &lt;&lt; " which is bigger than -1 " &lt;&lt; std::endl;
    } 
    else 
    {
        cout &lt;&lt; "string length is " &lt;&lt; len &lt;&lt; " which is less than -1 " &lt;&lt;std::endl;
    }
    return 0;
}
</code></pre>
<ul>
<li>In the compliant code, we utilize size_t which is the appropriate type for representing sizes. Additionally, instead of comparing directly with -1, we do a static_cast to ensure a correct type conversion and avoid issues related to signed/unsigned mismatch.</li>
</ul>
<h4 id="heading-c-7"><strong>C</strong></h4>
<pre><code class="lang-plaintext">#include &lt;stdio.h&gt;
#include &lt;limits.h&gt;

int main() {
    long large_number = 9223372036854775807; // Maximum value for a signed long on a 64-bit system

    // Check before casting
    if (large_number &gt; INT_MAX || large_number &lt; INT_MIN) {
        printf("Error: large_number is out of range for an int\n");
    } else {
        int safe_number = (int)large_number;
        printf("Safely casted number: %d\n", safe_number);
    }

    return 0;
}
</code></pre>
<ul>
<li>For the pointer conversion, you should avoid casting pointers to different types unless you are certain of the type of the object being pointed to and that the memory access will not violate alignment requirements or strict aliasing rules. If you need to interpret the bytes of a type as another type, you can use memcpy:</li>
</ul>
<pre><code class="lang-plaintext">#include &lt;stdio.h&gt;
#include &lt;string.h&gt;

int main() {
    double pi = 3.141592653589793;
    int pi_int;

    // Use memcpy to safely copy the bytes
    memcpy(&amp;pi_int, &amp;pi, sizeof(pi_int));

    printf("Value of pi copied into an int without type punning: %d\n", pi_int);

    return 0;
}
</code></pre>
<ul>
<li>In this compliant version, memcpy is used to copy the bytes of pi into pi_int without violating strict aliasing, although the resulting pi_int value will not make much sense as it's just a bit pattern copied from pi. It's important to note that this kind of byte-wise copy is rarely meaningful and should be used with caution.</li>
</ul>
<h4 id="heading-rust-7"><strong>Rust</strong></h4>
<pre><code class="lang-plaintext">fn main() {
    let large_number: i64 = 9223372036854775807;

    // Safe conversion using `try_into`
    match large_number.try_into() {
        Ok(truncated_number) =&gt; println!("Safely converted number: {}", truncated_number),
        Err(e) =&gt; println!("Conversion error: {:?}", e),
    }

    // Safe transmutation of `f64` to `i64` using `to_bits`, which is a safe operation
    let pi: f64 = 3.141592653589793;
    let pi_bits: u64 = pi.to_bits();

    // Now, if you really need to interpret these bits as i32 (which is unusual), you can do so safely:
    let pi_bits_high: i32 = (pi_bits &gt;&gt; 32) as i32; // High 32 bits
    let pi_bits_low: i32 = pi_bits as i32; // Low 32 bits

    println!("High 32 bits of pi: {}", pi_bits_high);
    println!("Low 32 bits of pi: {}", pi_bits_low);
}
</code></pre>
<ul>
<li><p>Instead of using as for casting (which can be unsafe), try_into() is used for the conversion, which safely converts types and returns a Result indicating success or failure of the conversion.</p>
</li>
<li><p><a target="_blank" href="http://pi.to">pi.to</a>_bits() is used to safely convert the f64 value into its bit pattern as a u64. This is a safe operation in Rust and does not involve any undefined behavior.</p>
</li>
<li><p>If you need to work with the bit pattern of pi as i32, you can safely split the u64 into two i32s. This is still a bit unusual and should be done with a clear understanding of why you're accessing the raw bits of a floating-point number.</p>
</li>
</ul>
<h2 id="heading-5-format-string-vulnerability"><strong>5. Format string vulnerability</strong></h2>
<p><strong>Noncompliant Code (Vulnerable to Format String Attacks):</strong></p>
<h4 id="heading-cpp-8"><strong>CPP</strong></h4>
<pre><code class="lang-plaintext">#include &lt;stdio.h&gt;

int main(int argc, char **argv) 
{
    // Unsafe usage of printf
    printf(argv[1]);
    return 0;
}
</code></pre>
<p>This code directly takes user input (argv[1]) and uses it as a format string, opening up the potential for format string attacks. An attacker could provide malicious format specifiers as arguments.</p>
<h4 id="heading-c-8"><strong>C</strong></h4>
<pre><code class="lang-plaintext">#include &lt;stdio.h&gt;

int main() {
    char user_input[100];

    // Assume user_input is filled with data from an untrusted source
    printf("Please enter your name: ");
    gets(user_input); // Unsafe use of gets(), which is also deprecated

    // Vulnerable to format string attack
    printf(user_input);

    return 0;
}
</code></pre>
<p>The gets function is used, which is unsafe because it does not check the length of the input and can lead to buffer overflows.</p>
<p>The printf function is directly passed user_input without format specifiers, which is a format string vulnerability.</p>
<h4 id="heading-rust-8"><strong>Rust</strong></h4>
<pre><code class="lang-plaintext">extern "C" {
    fn printf(format: *const i8, ...);
}

fn main() {
    let user_input = String::from("user input with %s format specifier");
    unsafe {
        // Unsafe and noncompliant: passing user-controlled input to a C-style printf
        printf(user_input.as_ptr() as *const i8);
    }
}
</code></pre>
<p>This example assumes you have a C printf function accessible from Rust, which is not normally the case. It's purely hypothetical and for illustrative purposes.</p>
<h3 id="heading-compliant-code-safe-against-format-string-attacks"><strong>Compliant Code (Safe against Format String Attacks):</strong></h3>
<h4 id="heading-cpp-9"><strong>CPP</strong></h4>
<pre><code class="lang-plaintext">#include &lt;stdio.h&gt;

int main(int argc, char **argv) 
{
    // Safe usage of printf
    printf("%s\n", argv[1]);
    return 0;
}
</code></pre>
<ul>
<li><p>In this version, we specify "%s\n" as the format string, ensuring that the user input is only interpreted as a string and not as additional format specifiers. This prevents format string attacks by displaying the string argument as is, without interpretation of any format specifiers that might be included in the input.</p>
</li>
<li><p>For those writing in modern C++, as mentioned, the C++20 std::format offers even better type-safety than the C-style format string functions.</p>
</li>
</ul>
<p><strong>C</strong></p>
<pre><code class="lang-plaintext">#include &lt;stdio.h&gt;

#define MAX_INPUT_LENGTH 100

int main() {
    char user_input[MAX_INPUT_LENGTH];

    // Safe way to read strings using fgets()
    printf("Please enter your name: ");
    if (fgets(user_input, MAX_INPUT_LENGTH, stdin) == NULL) {
        printf("Error reading input.\n");
        return 1;
    }

    // Secure way to use user input in printf
    printf("%s", user_input);

    return 0;
}
</code></pre>
<ul>
<li><p>fgets is used instead of gets to safely read user input, avoiding buffer overflow by specifying the maximum length of the input.</p>
</li>
<li><p>The printf function is used with a format specifier %s, which prevents format string vulnerabilities. The user input is treated as a string and not as a format string.</p>
</li>
</ul>
<h4 id="heading-rust-9"><strong>Rust</strong></h4>
<pre><code class="lang-plaintext">use std::io::{self, Write};

fn main() {
    let mut user_input = String::new();

    print!("Please enter your name: ");
    io::stdout().flush().unwrap(); // Ensure "Please enter your name: " is printed before input

    match io::stdin().read_line(&amp;mut user_input) {
        Ok(_) =&gt; {
            // Safe and compliant: Rust's macro `println!` requires format specifiers
            println!("Hello, {}", user_input.trim_end()); // trim_end removes the newline
        },
        Err(error) =&gt; println!("Error reading input: {}", error),
    }
}
</code></pre>
<ul>
<li><p>Rust's println! macro is used, which enforces the use of format specifiers ({}) for any inserted content.</p>
</li>
<li><p>User input is safely appended into the format string without the risk of it being interpreted as a format specifier.</p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[OWASP API Security Top 10 2023]]></title><description><![CDATA[API1:2023 - Broken Object Level Authorization 1 API2:2023 - Broken Authentication 5 API3:2023 - Broken Object Property Level Authorization 11 API4:2023…]]></description><link>https://devsecopsguides.hashnode.dev/owasp-api-security-top-10-2023-1</link><guid isPermaLink="true">https://devsecopsguides.hashnode.dev/owasp-api-security-top-10-2023-1</guid><category><![CDATA[DevSecOps]]></category><category><![CDATA[owasp]]></category><category><![CDATA[APIs]]></category><category><![CDATA[Application Security]]></category><category><![CDATA[secure coding]]></category><dc:creator><![CDATA[Reza Rashidi]]></dc:creator><pubDate>Mon, 30 Oct 2023 13:08:37 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1698671211869/200444ef-0372-4bbc-9aaa-e49a6b90ab30.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><a target="_blank" href="https://docs.google.com/document/d/1yyoFQSkfB8o2temhhxVuSvBktUcXX11X/edit#heading=h.8wyqowcmiy19"><strong>API1:2023 - Broken Object Level Authorization 1</strong></a></p>
<p><a target="_blank" href="https://docs.google.com/document/d/1yyoFQSkfB8o2temhhxVuSvBktUcXX11X/edit#heading=h.zciemajhq3uf"><strong>API2:2023 - Broken Authentication 5</strong></a></p>
<p><a target="_blank" href="https://docs.google.com/document/d/1yyoFQSkfB8o2temhhxVuSvBktUcXX11X/edit#heading=h.l3mkvtmxojtf"><strong>API3:2023 - Broken Object Property Level Authorization 11</strong></a></p>
<p><a target="_blank" href="https://docs.google.com/document/d/1yyoFQSkfB8o2temhhxVuSvBktUcXX11X/edit#heading=h.u9o6k3lpt9r9"><strong>API4:2023 - Unrestricted Resource Consumption 18</strong></a></p>
<p><a target="_blank" href="https://docs.google.com/document/d/1yyoFQSkfB8o2temhhxVuSvBktUcXX11X/edit#heading=h.sccq5vbf94mf"><strong>API5:2023 - Broken Function Level Authorization 23</strong></a></p>
<p><a target="_blank" href="https://docs.google.com/document/d/1yyoFQSkfB8o2temhhxVuSvBktUcXX11X/edit#heading=h.yeah1xj8t0oo"><strong>API6:2023 - Unrestricted Access to Sensitive Business Flows 29</strong></a></p>
<p><a target="_blank" href="https://docs.google.com/document/d/1yyoFQSkfB8o2temhhxVuSvBktUcXX11X/edit#heading=h.ofsc0epvf7ce"><strong>API7:2023 - Server Side Request Forgery 35</strong></a></p>
<p><a target="_blank" href="https://docs.google.com/document/d/1yyoFQSkfB8o2temhhxVuSvBktUcXX11X/edit#heading=h.7urajndkmbfx"><strong>API8:2023 - Security Misconfiguration 39</strong></a></p>
<p><a target="_blank" href="https://docs.google.com/document/d/1yyoFQSkfB8o2temhhxVuSvBktUcXX11X/edit#heading=h.5usbchwt7jew"><strong>API9:2023 - Improper Inventory Management 44</strong></a></p>
<p><a target="_blank" href="https://docs.google.com/document/d/1yyoFQSkfB8o2temhhxVuSvBktUcXX11X/edit#heading=h.xi6uyd81bpes"><strong>API10:2023 - Unsafe Consumption of APIs 49</strong></a></p>
<h2 id="heading-api12023-broken-object-level-authorization"><strong>API1:2023 - Broken Object Level Authorization</strong></h2>
<p>This vulnerability arises due to the lack of permission checks on resources and objects. An attacker can exploit this to gain access to resources and data of user groups and the system. Permission checks at the object level should be considered in any function that accesses a data resource using an identifier from the user.</p>
<p><strong>Example:</strong></p>
<p>GET request to retrieve the details of a product with the product ID:</p>
<p>GET /api/products/{product_id}</p>
<p><strong>Noncompliant Code(.NET):</strong></p>
<pre><code class="lang-plaintext">// Non-compliant code
public class UserController : ApiController
{
    [HttpGet]
    public User GetUser(int userId)
    {
        User user = UserRepository.GetUserById(userId);
        return user;
    }

    [HttpPut]
    public IHttpActionResult UpdateUser(User user)
    {
        UserRepository.UpdateUser(user);
        return Ok();
    }
}
</code></pre>
<p><strong>Compliant Code(.NET):</strong></p>
<pre><code class="lang-plaintext">// Compliant code
public class UserController : ApiController
{
    [HttpGet]
    [Authorize(Roles = "Admin")]
    public User GetUser(int userId)
    {
        User user = UserRepository.GetUserById(userId);
        return user;
    }
    [HttpPut]
    [Authorize(Roles = "Admin")]
    public IHttpActionResult UpdateUser(User user)
    {
        UserRepository.UpdateUser(user);
        return Ok();
    }
}
</code></pre>
<p><strong>Noncompliant Code(Java):</strong></p>
<pre><code class="lang-plaintext">// Non-compliant code
@RestController
public class UserController {

    @GetMapping("/users/{userId}")
    public User getUser(@PathVariable int userId) {
        User user = UserRepository.getUserById(userId);
        return user;
    }

    @PutMapping("/users/{userId}")
    public ResponseEntity&lt;?&gt; updateUser(@PathVariable int userId, @RequestBody User user) {
        UserRepository.updateUser(user);
        return ResponseEntity.ok().build();
    }
}
</code></pre>
<p><strong>Compliant Code(Java):</strong></p>
<pre><code class="lang-plaintext">// Compliant code
public class UserController : ApiController
{
    [HttpGet]
    [Authorize(Roles = "Admin")]
    public User GetUser(int userId)
    {
        User user = UserRepository.GetUserById(userId);
        return user;
    }

    [HttpPut]
    [Authorize(Roles = "Admin")]
    public IHttpActionResult UpdateUser(User user)
    {
        UserRepository.UpdateUser(user);
        return Ok();
    }
}
</code></pre>
<p><strong>General Prevention Suggestions:</strong></p>
<p>In any function that accesses a data resource using a user's identifier, consider the necessary checks for object-level permission. Ensure that the user is authorized to access this resource.</p>
<p>Validate identifiers and permissions in each request. Make sure that a user attempting to access a specific object is authorized to do so.</p>
<p>Protect the way the user's identifier is sent in requests. Use secure methods for transmitting and storing the identifier, such as using authentication tokens.</p>
<h2 id="heading-api22023-broken-authentication"><strong>API2:2023 - Broken Authentication</strong></h2>
<p>In this vulnerability, due to insufficient security mechanisms for user authentication to access resources, there's the possibility of disruption and unauthorized access to protected information by an attacker.</p>
<p><strong>Example:</strong></p>
<p>POST request for user login using login details:</p>
<p>POST /api/login</p>
<p>Body:</p>
<p>{</p>
<p>  "username": "exampleuser",</p>
<p>  "password": "secretpassword"</p>
<p>}</p>
<p><strong>Noncompliant Code(.NET):</strong></p>
<pre><code class="lang-plaintext">// Non-compliant code
[ApiController]
[Route("api/[controller]")]
public class UserController : ControllerBase
{
    [HttpPost]
    public IActionResult Login(string username, string password)
    {
        if (AuthenticateUser(username, password))
        {
            // Generate and return authentication token
            var token = GenerateAuthToken(username);
            return Ok(token);
        }
        else
        {
            return Unauthorized();
        }
    }

    [HttpGet]
    public IActionResult GetUserData(int userId)
    {
        // Retrieve user data from the database
        var userData = Database.GetUserById(userId);

        // Return user data
        return Ok(userData);
    }

    // Other methods...
}
</code></pre>
<p><strong>Compliant Code(.NET):</strong></p>
<pre><code class="lang-plaintext">// Compliant code
[ApiController]
[Route("api/[controller]")]
public class UserController : ControllerBase
{
    private readonly IUserService _userService;
    private readonly IAuthenticationService _authenticationService;

    public UserController(IUserService userService, IAuthenticationService authenticationService)
    {
        _userService = userService;
        _authenticationService = authenticationService;
    }

    [HttpPost]
    public IActionResult Login(LoginModel loginModel)
    {
        if (_authenticationService.AuthenticateUser(loginModel.Username, loginModel.Password))
        {
            // Generate and return authentication token
            var token = _authenticationService.GenerateAuthToken(loginModel.Username);
            return Ok(token);
        }
        else
        {
            return Unauthorized();
        }
    }

    [HttpGet]
    [Authorize]
    public IActionResult GetUserData(int userId)
    {
        // Retrieve the authenticated user's identity
        var identity = HttpContext.User.Identity as ClaimsIdentity;
        if (identity != null)
        {
            // Get the user ID from the authentication token
            var userIdFromToken = identity.FindFirst("UserId")?.Value;

            if (!string.IsNullOrEmpty(userIdFromToken) &amp;&amp; userIdFromToken == userId.ToString())
            {
                // Retrieve user data from the database
                var userData = _userService.GetUserData(userId);
                return Ok(userData);
            }
        }

        return Unauthorized();
    }

    // Other methods...
}
</code></pre>
<p><strong>Noncompliant Code(Java):</strong></p>
<pre><code class="lang-plaintext">@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public ResponseEntity&lt;String&gt; login(@RequestParam String username, @RequestParam String password) {
        if (userService.authenticateUser(username, password)) {
            // Generate and return authentication token
            String token = generateAuthToken(username);
            return ResponseEntity.ok(token);
        } else {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
    }

    @GetMapping("/{userId}")
    public ResponseEntity&lt;User&gt; getUserData(@PathVariable int userId) {
        // Retrieve user data from the database
        User user = userService.getUserById(userId);

        // Return user data
        return ResponseEntity.ok(user);
    }

    // Other methods...
}
</code></pre>
<p><strong>Compliant Code(Java):</strong></p>
<pre><code class="lang-plaintext">@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private AuthenticationService authenticationService;

    @PostMapping("/login")
    public ResponseEntity&lt;String&gt; login(@RequestParam String username, @RequestParam String password) {
        if (authenticationService.authenticateUser(username, password)) {
            // Generate and return authentication token
            String token = authenticationService.generateAuthToken(username);
            return ResponseEntity.ok(token);
        } else {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
    }

    @GetMapping("/{userId}")
    public ResponseEntity&lt;User&gt; getUserData(@PathVariable int userId, @RequestHeader("Authorization") String authToken) {
        if (authenticationService.validateAuthToken(authToken)) {
            // Retrieve user data from the database
            User user = userService.getUserById(userId);

            // Return user data
            return ResponseEntity.ok(user);
        } else {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
    }

    // Other methods...
}
</code></pre>
<p><strong>General Prevention Suggestions:</strong></p>
<p>Use strong and standard authentication mechanisms, such as JWT (JSON Web Tokens) or OAuth.</p>
<p>Use robust encryption methods for storing and transmitting sensitive information, like connection encryption (TLS/SSL).</p>
<p>Properly verify authentication information and ensure that every authenticated request comes from a legitimate user.</p>
<p>Carefully ensure that authentication details (like passwords) are securely encrypted during transmission or storage on the server.</p>
<p>Implement a limit on the number of unsuccessful login attempts and temporarily lock user accounts after a certain number of failed tries.</p>
<h2 id="heading-api32023-broken-object-property-level-authorization"><strong>API3:2023 - Broken Object Property Level Authorization</strong></h2>
<p>In this vulnerability, due to the lack of data model verification in the request and response, an attacker has the ability to extract or perform CRUD operations on the related methods. This issue arises due to the lack of proper validation of access permissions to object attributes, leading to information disclosure or disruption in requests.</p>
<p><strong>Example:</strong></p>
<p>PUT request to update a feature of an item:</p>
<p>PUT /api/items/{item_id}</p>
<p>Body:</p>
<p>{</p>
<p>  "name": "Updated Item Name",</p>
<p>  "price": 10.99,</p>
<p>  "is_available": true</p>
<p>}</p>
<p><strong>Noncompliant Code(.NET):</strong></p>
<pre><code class="lang-plaintext">[Route("api/items")]
public class ItemController : ControllerBase
{
    private readonly IItemService _itemService;

    public ItemController(IItemService itemService)
    {
        _itemService = itemService;
    }

    [HttpGet("{itemId}")]
    public IActionResult GetItem(int itemId)
    {
        // Retrieve the item from the database
        Item item = _itemService.GetItem(itemId);

        // Return the item without any authorization check
        return Ok(item);
    }

    [HttpPut("{itemId}")]
    public IActionResult UpdateItem(int itemId, [FromBody] Item updatedItem)
    {
        // Retrieve the existing item from the database
        Item existingItem = _itemService.GetItem(itemId);

        // Update only the allowed properties
        existingItem.Name = updatedItem.Name;
        existingItem.Price = updatedItem.Price;
        existingItem.IsAvailable = updatedItem.IsAvailable;

        // Save the changes to the database
        _itemService.UpdateItem(existingItem);

        // Return a success response
        return Ok();
    }

    // Other methods...
}
</code></pre>
<p><strong>Compliant Code(.NET):</strong></p>
<pre><code class="lang-plaintext">[Route("api/items")]
public class ItemController : ControllerBase
{
    private readonly IItemService _itemService;

    public ItemController(IItemService itemService)
    {
        _itemService = itemService;
    }

    [HttpGet("{itemId}")]
    public IActionResult GetItem(int itemId)
    {
        // Retrieve the item from the database
        Item item = _itemService.GetItem(itemId);

        // Check if the user is authorized to access the item
        if (!IsUserAuthorized(item))
        {
            return Forbid();
        }

        // Return the item
        return Ok(item);
    }

    [HttpPut("{itemId}")]
    public IActionResult UpdateItem(int itemId, [FromBody] Item updatedItem)
    {
        // Retrieve the existing item from the database
        Item existingItem = _itemService.GetItem(itemId);

        // Check if the user is authorized to update the item properties
        if (!IsUserAuthorized
</code></pre>
<p><strong>Noncompliant Code(Java):</strong></p>
<pre><code class="lang-plaintext">@RestController
@RequestMapping("/api/items")
public class ItemController {

    private final ItemService itemService;

    public ItemController(ItemService itemService) {
        this.itemService = itemService;
    }

    @GetMapping("/{itemId}")
    public Item getItem(@PathVariable int itemId) {
        // Retrieve the item from the database
        Item item = itemService.getItem(itemId);

        // Return the item without any authorization check
        return item;
    }

    @PutMapping("/{itemId}")
    public void updateItem(@PathVariable int itemId, @RequestBody Item updatedItem) {
        // Retrieve the existing item from the database
        Item existingItem = itemService.getItem(itemId);

        // Update only the allowed properties
        existingItem.setName(updatedItem.getName());
        existingItem.setPrice(updatedItem.getPrice());
        existingItem.setAvailable(updatedItem.isAvailable());

        // Save the changes to the database
        itemService.updateItem(existingItem);
    }

    // Other methods...
}
</code></pre>
<p><strong>Compliant Code(Java):</strong></p>
<pre><code class="lang-plaintext">@RestController
@RequestMapping("/api/items")
public class ItemController {

    private final ItemService itemService;

    public ItemController(ItemService itemService) {
        this.itemService = itemService;
    }

    @GetMapping("/{itemId}")
    public ResponseEntity&lt;Item&gt; getItem(@PathVariable int itemId) {
        // Retrieve the item from the database
        Item item = itemService.getItem(itemId);

        // Check if the user is authorized to access the item
        if (!isUserAuthorized(item)) {
            return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
        }

        // Return the item
        return ResponseEntity.ok(item);
    }

    @PutMapping("/{itemId}")
    public ResponseEntity&lt;Void&gt; updateItem(@PathVariable int itemId, @RequestBody Item updatedItem) {
        // Retrieve the existing item from the database
        Item existingItem = itemService.getItem(itemId);

        // Check if the user is authorized to update the item properties
        if (!isUserAuthorized(existingItem)) {
            return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
        }

        // Only update the allowed properties
        existingItem.setName(updatedItem.getName());
        existingItem.setPrice(updatedItem.getPrice());
        existingItem.setAvailable(updatedItem.isAvailable());

        // Save the changes to the database
        itemService.updateItem(existingItem);

        // Return a success response
        return ResponseEntity.ok().build();
    }

    private boolean isUserAuthorized(Item item) {
        // Implement your authorization logic here
        // Check if the user has the necessary permissions to access the item
        // Return true if authorized, false otherwise
    }

    // Other methods...
}
</code></pre>
<p>General Prevention Suggestions:</p>
<p>When creating or updating objects, ensure that access permissions for features are set at the correct level.</p>
<p>Validate user input data and only accept them if they have authorized access to the relevant features.</p>
<p>Use robust and secure mechanisms for defining and managing permissions and roles in the system, like RBAC (Role-Based Access Control).</p>
<p>Limit user access to object features based on business needs and the Principle of Least Privilege.</p>
<p>Conduct regular security tests on APIs and the system to ensure that all required permissions and validations have been correctly implemented.</p>
<h2 id="heading-api42023-unrestricted-resource-consumption"><strong>API4:2023 - Unrestricted Resource Consumption</strong></h2>
<p>Due to this vulnerability, the attacker can disrupt the API service delivery status due to the lack of limitations on requests, leading to errors resulting from insufficient resources for processing.</p>
<p><strong>Example:</strong></p>
<p>POST request to send an SMS to a specific mobile number:</p>
<p>POST /api/sms/send</p>
<p>Body:</p>
<p>{</p>
<p>  "phone_number": "1234567890",</p>
<p>  "message": "Hello, this is a test message."</p>
<p>}</p>
<p><strong>Noncompliant Code(.NET):</strong></p>
<pre><code class="lang-plaintext">[ApiController]
[Route("api/resource")]
public class ResourceController : ControllerBase
{
    private readonly ResourceService _resourceService;

    public ResourceController(ResourceService resourceService)
    {
        _resourceService = resourceService;
    }

    [HttpPost]
    public IActionResult ProcessResource(ResourceRequest request)
    {
        // Process the resource request
        string result = _resourceService.Process(request);

        // Return the result
        return Ok(result);
    }

    // Other methods...
}
</code></pre>
<p><strong>Compliant Code(.NET):</strong></p>
<pre><code class="lang-plaintext">   [ApiController]
[Route("api/resource")]
public class ResourceController : ControllerBase
{
    private readonly ResourceService _resourceService;

    public ResourceController(ResourceService resourceService)
    {
        _resourceService = resourceService;
    }

    [HttpPost]
    public IActionResult ProcessResource(ResourceRequest request)
    {
        // Validate the resource request
        if (!IsValidRequest(request))
        {
            return BadRequest();
        }

        // Process the resource request with resource consumption limits
        bool success = _resourceService.ProcessWithLimits(request);

        // Check if the resource consumption was successful
        if (!success)
        {
            return StatusCode((int)HttpStatusCode.TooManyRequests);
        }

        // Return the result
        return Ok("Resource processed successfully");
    }

    private bool IsValidRequest(ResourceRequest request)
    {
        // Implement your validation logic here
        // Check if the request is valid
        // Return true if valid, false otherwise
    }

    // Other methods...
}
</code></pre>
<p><strong>Noncompliant Code(Java):</strong></p>
<pre><code class="lang-plaintext">@RestController
@RequestMapping("/api")
public class ResourceController {

    private final ResourceService resourceService;

    public ResourceController(ResourceService resourceService) {
        this.resourceService = resourceService;
    }

    @PostMapping("/resource")
    public ResponseEntity&lt;String&gt; processResource(@RequestBody ResourceRequest request) {
        // Process the resource request
        String result = resourceService.process(request);

        // Return the result
        return ResponseEntity.ok(result);
    }

    // Other methods...
}
</code></pre>
<p><strong>Compliant Code(Java):</strong></p>
<pre><code class="lang-plaintext">@RestController
@RequestMapping("/api")
public class ResourceController {

    private final ResourceService resourceService;

    public ResourceController(ResourceService resourceService) {
        this.resourceService = resourceService;
    }

    @PostMapping("/resource")
    public ResponseEntity&lt;String&gt; processResource(@RequestBody ResourceRequest request) {
        // Validate the resource request
        if (!isValidRequest(request)) {
            return ResponseEntity.badRequest().build();
        }

        // Process the resource request with resource consumption limits
        boolean success = resourceService.processWithLimits(request);

        // Check if the resource consumption was successful
        if (!success) {
            return ResponseEntity.status(HttpStatus.TOO_MANY_REQUESTS).build();
        }

        // Return the result
        return ResponseEntity.ok("Resource processed successfully");
    }

    private boolean isValidRequest(ResourceRequest request) {
        // Implement your validation logic here
        // Check if the request is valid
        // Return true if valid, false otherwise
    }

    // Other methods...
}
</code></pre>
<p><strong>General Prevention Suggestions:</strong></p>
<p>Limit the resources consumed by each API request, such as bandwidth limitation, the number of requests in a specific time interval, and the maximum number of SMS messages or phone calls.</p>
<p>Review and validate API requests based on the allowable ceiling for resource consumption and apply necessary limitations.</p>
<p>Use traffic limiting and bandwidth control mechanisms like Advanced Network Limiting to manage the resources consumed by each user or service.</p>
<p>Monitor and log resource consumption to detect suspicious patterns and take more detailed validations when necessary.</p>
<p>Conduct Load Testing and evaluate the system's resource performance to detect and prevent issues from improper resource consumption.</p>
<h2 id="heading-api52023-broken-function-level-authorization"><strong>API5:2023 - Broken Function Level Authorization</strong></h2>
<p>Due to the lack of enforcing access control policies with hierarchical permissions, the attacker can invoke and execute unauthorized requests from the allowed Endpoint to access other users' resources and/or managerial functionalities.</p>
<p>Example:</p>
<p>DELETE request to delete a comment with the comment ID:</p>
<p>DELETE /api/comments/{comment_id}</p>
<p><strong>Noncompliant Code(.NET):</strong></p>
<pre><code class="lang-plaintext">[ApiController]
[Route("api/data")]
public class DataController : ControllerBase
{
    private readonly DataService _dataService;

    public DataController(DataService dataService)
    {
        _dataService = dataService;
    }

    [HttpGet]
    public IActionResult GetData()
    {
        // Get data from the service
        var data = _dataService.GetData();

        // Return the data
        return Ok(data);
    }

    [HttpPost]
    public IActionResult UpdateData(DataModel data)
    {
        // Update the data using the service
        _dataService.UpdateData(data);

        // Return success response
        return Ok("Data updated successfully");
    }

    // Other methods...
}
</code></pre>
<p><strong>Compliant Code(.NET):</strong></p>
<pre><code class="lang-plaintext">[ApiController]
[Route("api/data")]
[Authorize]
public class DataController : ControllerBase
{
    private readonly DataService _dataService;

    public DataController(DataService dataService)
    {
        _dataService = dataService;
    }

    [HttpGet]
    [Authorize(Roles = "ReadAccess")]
    public IActionResult GetData()
    {
        // Get the user's identity
        var identity = HttpContext.User.Identity as ClaimsIdentity;

        // Get the user's role
        var role = identity.FindFirst(ClaimTypes.Role)?.Value;

        // Check if the user has the required role for reading data
        if (role != "ReadAccess")
        {
            return Forbid(); // Return 403 Forbidden if the user is not authorized
        }

        // Get data from the service
        var data = _dataService.GetData();

        // Return the data
        return Ok(data);
    }

    [HttpPost]
    [Authorize(Roles = "WriteAccess")]
    public IActionResult UpdateData(DataModel data)
    {
        // Get the user's identity
        var identity = HttpContext.User.Identity as ClaimsIdentity;

        // Get the user's role
        var role = identity.FindFirst(ClaimTypes.Role)?.Value;

        // Check if the user has the required role for updating data
        if (role != "WriteAccess")
        {
            return Forbid(); // Return 403 Forbidden if the user is not authorized
        }

        // Update the data using the service
        _dataService.UpdateData(data);

        // Return success response
        return Ok("Data updated successfully");
    }

    // Other methods...
}
</code></pre>
<p><strong>Noncompliant Code(Java):</strong></p>
<pre><code class="lang-plaintext">@RestController
@RequestMapping("/api/data")
public class DataController {
    private final DataService dataService;

    public DataController(DataService dataService) {
        this.dataService = dataService;
    }

    @GetMapping
    public ResponseEntity&lt;List&lt;Data&gt;&gt; getData() {
        // Get data from the service
        List&lt;Data&gt; data = dataService.getData();

        // Return the data
        return ResponseEntity.ok(data);
    }

    @PostMapping
    public ResponseEntity&lt;String&gt; updateData(@RequestBody Data data) {
        // Update the data using the service
        dataService.updateData(data);

        // Return success response
        return ResponseEntity.ok("Data updated successfully");
    }

    // Other methods...
}
</code></pre>
<p><strong>Compliant Code(Java):</strong></p>
<pre><code class="lang-plaintext">@RestController
@RequestMapping("/api/data")
public class DataController {
    private final DataService dataService;

    public DataController(DataService dataService) {
        this.dataService = dataService;
    }

    @GetMapping
    @PreAuthorize("hasRole('ROLE_READ')")
    public ResponseEntity&lt;List&lt;Data&gt;&gt; getData() {
        // Get data from the service
        List&lt;Data&gt; data = dataService.getData();

        // Return the data
        return ResponseEntity.ok(data);
    }

    @PostMapping
    @PreAuthorize("hasRole('ROLE_WRITE')")
    public ResponseEntity&lt;String&gt; updateData(@RequestBody Data data) {
        // Update the data using the service
        dataService.updateData(data);

        // Return success response
        return ResponseEntity.ok("Data updated successfully");
    }

    // Other methods...
}
</code></pre>
<p><strong>General prevention suggestions:</strong></p>
<p>Complete validation in every API function based on access levels and user roles.</p>
<p>Use multi-level access permission systems and apply access levels to various resources.</p>
<p>Properly segregate between managerial and regular functionalities and enforce appropriate access policies for each.</p>
<p>Examine permissions in every function and validate user access at runtime.</p>
<p>Utilize frameworks and libraries for managing user access and implement more complex access policies like RBAC (Role-Based Access Control) or ABAC (Attribute-Based Access Control).</p>
<h2 id="heading-api62023-unrestricted-access-to-sensitive-business-flows"><strong>API6:2023 - Unrestricted Access to Sensitive Business Flows</strong></h2>
<p>Due to this vulnerability, an attacker has the ability to exploit the legitimate functions of the application for illicit purposes because of the app's capabilities.</p>
<p>Example:</p>
<p>POST request to purchase an airplane ticket by providing passenger details.</p>
<p>POST /api/tickets/buy</p>
<p>Body:</p>
<p>{</p>
<p>  "passenger_name": "John Doe",</p>
<p>  "flight_number": "AB123",</p>
<p>  "departure_date": "2023-07-01"</p>
<p>}</p>
<p><strong>Noncompliant Code(.NET):</strong></p>
<pre><code class="lang-plaintext">[Route("api/orders")]
public class OrderController : ApiController
{
    private readonly IOrderService _orderService;

    public OrderController(IOrderService orderService)
    {
        _orderService = orderService;
    }

    [HttpPost]
    public IHttpActionResult CreateOrder(OrderRequest request)
    {
        // Create a new order without proper validation
        Order order = _orderService.CreateOrder(request);

        // Return the created order
        return Ok(order);
    }

    [HttpGet]
    [Route("{orderId}")]
    public IHttpActionResult GetOrder(string orderId)
    {
        // Get the order by ID without proper authorization
        Order order = _orderService.GetOrder(orderId);

        // Return the order
        return Ok(order);
    }

    // Other methods...
}
</code></pre>
<p><strong>Compliant Code(.NET):</strong></p>
<pre><code class="lang-plaintext">[Route("api/orders")]
public class OrderController : ApiController
{
    private readonly IOrderService _orderService;

    public OrderController(IOrderService orderService)
    {
        _orderService = orderService;
    }

    [HttpPost]
    [Authorize(Roles = "Admin")]
    public IHttpActionResult CreateOrder(OrderRequest request)
    {
        // Validate the request and create a new order with proper authorization
        Order order = _orderService.CreateOrder(request);

        // Return the created order
        return Ok(order);
    }

    [HttpGet]
    [Route("{orderId}")]
    [Authorize(Roles = "User")]
    public IHttpActionResult GetOrder(string orderId)
    {
        // Authorize the user's access to the order
        // Only users with the "User" role can access the order
        Order order = _orderService.GetOrder(orderId);

        // Return the order
        return Ok(order);
    }

    // Other methods...
}
</code></pre>
<p><strong>Noncompliant Code(Java):</strong></p>
<pre><code class="lang-plaintext">@RestController
@RequestMapping("/api/orders")
public class OrderController {
    private final OrderService orderService;

    public OrderController(OrderService orderService) {
        this.orderService = orderService;
    }

    @PostMapping
    public ResponseEntity&lt;Order&gt; createOrder(@RequestBody OrderRequest request) {
        // Create a new order without proper validation
        Order order = orderService.createOrder(request);

        // Return the created order
        return ResponseEntity.ok(order);
    }

    @GetMapping("/{orderId}")
    public ResponseEntity&lt;Order&gt; getOrder(@PathVariable String orderId) {
        // Get the order by ID without proper authorization
        Order order = orderService.getOrder(orderId);

        // Return the order
        return ResponseEntity.ok(order);
    }

    // Other methods...
}
</code></pre>
<p><strong>Compliant Code(Java):</strong></p>
<pre><code class="lang-plaintext">@RestController
@RequestMapping("/api/orders")
public class OrderController {
    private final OrderService orderService;

    public OrderController(OrderService orderService) {
        this.orderService = orderService;
    }

    @PostMapping
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public ResponseEntity&lt;Order&gt; createOrder(@RequestBody OrderRequest request) {
        // Validate the request and create a new order with proper authorization
        Order order = orderService.createOrder(request);

        // Return the created order
        return ResponseEntity.ok(order);
    }

    @GetMapping("/{orderId}")
    @PreAuthorize("hasRole('ROLE_USER') or hasPermission(#orderId, 'READ')")
    public ResponseEntity&lt;Order&gt; getOrder(@PathVariable String orderId) {
        // Authorize the user's access to the order
        // Only users with ROLE_USER or permission to read the order can access it
        Order order = orderService.getOrder(orderId);

        // Return the order
        return ResponseEntity.ok(order);
    }

    // Other methods...
}
</code></pre>
<p><strong>General prevention recommendations:</strong></p>
<p>Implement authentication and user validation mechanisms before accessing sensitive business flows.</p>
<p>Carefully inspect and validate user data and inputs, including the validity of dates and input formats.</p>
<p>Apply limitations and logical rules for accessing sensitive business flows.</p>
<p>Use logging and monitoring systems to detect and track suspicious or inappropriate activities in business flows.</p>
<p>Provide and utilize interfaces (API Gateways) that facilitate control and management of access to business flows.</p>
<h2 id="heading-api72023-server-side-request-forgery"><strong>API7:2023 - Server Side Request Forgery</strong></h2>
<p>Through this vulnerability, the attacker has the ability to forge requests on the server side and send fraudulent requests to an authorized destination.</p>
<p>Example:</p>
<p>A GET request to retrieve an image from a specific URL:</p>
<p>GET /api/image?url=<a target="_blank" href="https://docs.google.com/document/d/1yyoFQSkfB8o2temhhxVuSvBktUcXX11X/edit#heading=h.8wyqowcmiy19">http://malicious-website.com/malware.jpg</a></p>
<p><strong>Noncompliant Code(.NET):</strong></p>
<pre><code class="lang-plaintext">[Route("api/images")]
public class ImageController : ApiController
{
    [HttpGet]
    public IHttpActionResult GetImage(string url)
    {
        // Fetch the image from the specified URL without proper validation
        using (WebClient client = new WebClient())
        {
            byte[] imageData = client.DownloadData(url);
            return File(imageData, "image/jpeg");
        }
    }

    // Other methods...
}
</code></pre>
<p><strong>Compliant Code(.NET):</strong></p>
<pre><code class="lang-plaintext">[Route("api/images")]
public class ImageController : ApiController
{
    [HttpGet]
    public IHttpActionResult GetImage(string url)
    {
        // Validate and sanitize the URL before fetching the image
        if (!IsValidUrl(url))
        {
            return BadRequest("Invalid URL");
        }

        using (WebClient client = new WebClient())
        {
            byte[] imageData = client.DownloadData(url);
            return File(imageData, "image/jpeg");
        }
    }

    private bool IsValidUrl(string url)
    {
        // Implement URL validation logic here (e.g., whitelist trusted domains)
        // Return true if the URL is valid, otherwise false
        // Example validation logic:
        return url.StartsWith("http://trusted-domain.com");
    }

    // Other methods...
}
</code></pre>
<p><strong>Noncompliant Code(Java):</strong></p>
<pre><code class="lang-plaintext">@RestController
@RequestMapping("/api/images")
public class ImageController {

    @GetMapping
    public ResponseEntity&lt;byte[]&gt; getImage(@RequestParam("url") String url) throws IOException {
        // Fetch the image from the specified URL without proper validation
        URL imageUrl = new URL(url);
        byte[] imageData = IOUtils.toByteArray(imageUrl);
        return ResponseEntity.ok().contentType(MediaType.IMAGE_JPEG).body(imageData);
    }

    // Other methods...
}
</code></pre>
<p><strong>Compliant Code(Java):</strong></p>
<pre><code class="lang-plaintext">@RestController
@RequestMapping("/api/images")
public class ImageController {

    @GetMapping
    public ResponseEntity&lt;byte[]&gt; getImage(@RequestParam("url") String url) throws IOException {
        // Validate and sanitize the URL before fetching the image
        if (!isValidUrl(url)) {
            return ResponseEntity.badRequest().build();
        }

        URL imageUrl = new URL(url);
        byte[] imageData = IOUtils.toByteArray(imageUrl);
        return ResponseEntity.ok().contentType(MediaType.IMAGE_JPEG).body(imageData);
    }

    private boolean isValidUrl(String url) {
        // Implement URL validation logic here (e.g., whitelist trusted domains)
        // Return true if the URL is valid, otherwise false
        // Example validation logic:
        return url.startsWith("http://trusted-domain.com");
    }

    // Other methods...
}
</code></pre>
<p><strong>General prevention suggestions:</strong></p>
<p>Before sending a request to a specific URL, thoroughly check and validate the URI and the target source.</p>
<p>Limit the capability to retrieve information from external sources and restrict access to remote URLs.</p>
<p>Use a Whitelist to only allow valid addresses and access to them.</p>
<p>Validate and filter user inputs and parameters related to the utilized URL before using them in the request.</p>
<p>Employ network restrictions, such as firewalls, to limit access to external resources.</p>
<p>Train the development team to properly evaluate and validate URIs before using them in requests.</p>
<h2 id="heading-api82023-security-misconfiguration"><strong>API8:2023 - Security Misconfiguration</strong></h2>
<p>Due to incorrect configurations or improper management of related settings, an attacker can exploit default or incorrect configurations.</p>
<p><strong>Example:</strong></p>
<p>GET request to retrieve system settings:</p>
<p>GET /api/configurations</p>
<p><strong>Noncompliant Code(.NET):</strong></p>
<pre><code class="lang-plaintext">using System.Web.Http;

namespace MyAPI.Controllers
{
    public class UserController : ApiController
    {
        // GET api/user/{id}
        public IHttpActionResult GetUser(int id)
        {
            // Fetch user data from the database without proper access control
            var user = Database.GetUser(id);
            return Ok(user);
        }

        // Other methods...
    }
}
</code></pre>
<p><strong>Compliant Code(.NET):</strong></p>
<pre><code class="lang-plaintext">using System.Web.Http;
using Microsoft.AspNetCore.Authorization;

namespace MyAPI.Controllers
{
    [Authorize] // Apply authorization to the controller
    public class UserController : ApiController
    {
        // GET api/user/{id}
        [Authorize(Roles = "Admin")] // Restrict access to authorized users with the "Admin" role
        public IHttpActionResult GetUser(int id)
        {
            // Fetch user data from the database only if the user has the "Admin" role
            var user = Database.GetUser(id);
            return Ok(user);
        }

        // Other methods...
    }
}
</code></pre>
<p><strong>Noncompliant Code(Java):</strong></p>
<pre><code class="lang-plaintext">@RestController
public class UserController {

    @Autowired
    private UserRepository userRepository;

    // GET /user/{id}
    @RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
    public User getUser(@PathVariable int id) {
        // Fetch user data from the database without proper access control
        User user = userRepository.findById(id);
        return user;
    }

    // Other methods...
}
</code></pre>
<p><strong>Compliant Code(Java):</strong></p>
<pre><code class="lang-plaintext">@RestController
public class UserController {

    @Autowired
    private UserRepository userRepository;

    // GET /user/{id}
    @PreAuthorize("hasRole('ADMIN')") // Restrict access to users with the "ADMIN" role
    @RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
    public User getUser(@PathVariable int id) {
        // Fetch user data from the database only if the user has the "ADMIN" role
        User user = userRepository.findById(id);
        return user;
    }

    // Other methods...
}
</code></pre>
<p><strong>General Prevention Recommendations:</strong></p>
<p>Before sending a request to a specific URL, thoroughly check and validate the URI and the destination source.</p>
<p>Limit the capability to retrieve information from external sources and restrict the list of allowed access to remote URLs.</p>
<p>Use a Whitelist to only allow access to valid addresses.</p>
<p>Validate and filter user inputs and parameters related to the URL in use before incorporating them into requests.</p>
<p>Use network restrictions, like firewalls, to limit access to external resources.</p>
<p>Train the development team to evaluate and validate the correct URI before using it in requests.</p>
<h2 id="heading-api92023-improper-inventory-management"><strong>API9:2023 - Improper Inventory Management</strong></h2>
<p>Due to the lack of management of API versions and also the list of capabilities and functionalities for specific use-case scenarios across all functions, an attacker has the possibility to exploit different functionalities in various versions of the application.</p>
<p>Example:</p>
<p>A GET request to retrieve the list of available API versions:</p>
<p>GET /api/versions</p>
<p><strong>Noncompliant Code(.NET):</strong></p>
<pre><code class="lang-plaintext">[ApiController]
[Route("api/inventory")]
public class InventoryController : ControllerBase
{
    private readonly IInventoryService _inventoryService;

    public InventoryController(IInventoryService inventoryService)
    {
        _inventoryService = inventoryService;
    }

    // GET api/inventory/{productId}
    [HttpGet("{productId}")]
    public IActionResult GetProductInventory(int productId)
    {
        // Fetch inventory data directly from the database
        var inventory = _inventoryService.GetInventoryByProductId(productId);
        return Ok(inventory);
    }

    // POST api/inventory
    [HttpPost]
    public IActionResult UpdateProductInventory(InventoryModel inventory)
    {
        // Update inventory directly in the database
        _inventoryService.UpdateInventory(inventory);
        return Ok();
    }

    // Other methods...
}
</code></pre>
<p><strong>Compliant Code(.NET):</strong></p>
<pre><code class="lang-plaintext">[ApiController]
[Route("api/inventory")]
public class InventoryController : ControllerBase
{
    private readonly IInventoryService _inventoryService;

    public InventoryController(IInventoryService inventoryService)
    {
        _inventoryService = inventoryService;
    }

    // GET api/inventory/{productId}
    [HttpGet("{productId}")]
    public IActionResult GetProductInventory(int productId)
    {
        // Fetch inventory data through the inventory service
        var inventory = _inventoryService.GetProductInventory(productId);

        if (inventory == null)
            return NotFound();

        return Ok(inventory);
    }

    // POST api/inventory
    [HttpPost]
    [Authorize(Roles = "Admin")] // Restrict access to authorized users with the "Admin" role
    public IActionResult UpdateProductInventory(InventoryModel inventory)
    {
        // Update inventory through the inventory service
        _inventoryService.UpdateProductInventory(inventory);
        return Ok();
    }

    // Other methods...
}
</code></pre>
<p><strong>Noncompliant Code(Java):</strong></p>
<pre><code class="lang-plaintext">@RestController
@RequestMapping("/api/inventory")
public class InventoryController {

    private final InventoryService inventoryService;

    public InventoryController(InventoryService inventoryService) {
        this.inventoryService = inventoryService;
    }

    // GET /api/inventory/{productId}
    @GetMapping("/{productId}")
    public ResponseEntity&lt;Inventory&gt; getProductInventory(@PathVariable int productId) {
        // Fetch inventory data directly from the database
        Inventory inventory = inventoryService.getInventoryByProductId(productId);
        return ResponseEntity.ok(inventory);
    }

    // POST /api/inventory
    @PostMapping
    public ResponseEntity&lt;?&gt; updateProductInventory(@RequestBody Inventory inventory) {
        // Update inventory directly in the database
        inventoryService.updateInventory(inventory);
        return ResponseEntity.ok().build();
    }

    // Other methods...
}
</code></pre>
<p><strong>Compliant Code(Java):</strong></p>
<pre><code class="lang-plaintext">@RestController
@RequestMapping("/api/inventory")
public class InventoryController {

    private final InventoryService inventoryService;

    public InventoryController(InventoryService inventoryService) {
        this.inventoryService = inventoryService;
    }

    // GET /api/inventory/{productId}
    @GetMapping("/{productId}")
    public ResponseEntity&lt;Inventory&gt; getProductInventory(@PathVariable int productId) {
        // Fetch inventory data through the inventory service
        Inventory inventory = inventoryService.getProductInventory(productId);

        if (inventory == null) {
            return ResponseEntity.notFound().build();
        }

        return ResponseEntity.ok(inventory);
    }

    // POST /api/inventory
    @PostMapping
    @PreAuthorize("hasRole('ADMIN')") // Restrict access to authorized users with the "ADMIN" role
    public ResponseEntity&lt;?&gt; updateProductInventory(@RequestBody Inventory inventory) {
        // Update inventory through the inventory service
        inventoryService.updateProductInventory(inventory);
        return ResponseEntity.ok().build();
    }

    // Other methods...
}
</code></pre>
<p><strong>General Prevention Recommendations:</strong></p>
<p>Comprehensive and precise documentation for the API, including current and previous versions.</p>
<p>Implementing a version management system that simplifies the updating and management of API versions.</p>
<p>Introducing a version release policy that includes the lifespan and support for outdated versions.</p>
<p>Using automated methods to check the API version used by clients and sending alerts if older versions are being used.</p>
<p>Continuous monitoring and auditing to detect and address issues like outdated API versions and faulty endpoints.</p>
<p>Employing automation techniques to examine and automatically update API versions and hosts.</p>
<p>Establishing update policies for outdated API versions and discontinuing support for them.</p>
<h2 id="heading-api102023-unsafe-consumption-of-apis"><strong>API10:2023 - Unsafe Consumption of APIs</strong></h2>
<p>Due to the aforementioned vulnerability, an attacker can execute their desired information or requests in a specific group by sending or receiving information from supply chain sources.</p>
<p><strong>Example:</strong></p>
<p>A GET request to retrieve weather information from a third-party service.</p>
<p>GET /api/weather?location=New+York</p>
<p><strong>Noncompliant Code(.NET):</strong></p>
<pre><code class="lang-plaintext">[ApiController]
[Route("api/weather")]
public class WeatherController : ControllerBase
{
    private readonly IWeatherService weatherService;

    public WeatherController(IWeatherService weatherService)
    {
        this.weatherService = weatherService;
    }

    // GET /api/weather
    [HttpGet]
    public IActionResult GetWeather(string location)
    {
        // Make a direct call to the third-party weather API
        WeatherData weatherData = weatherService.GetWeatherData(location);
        return Ok(weatherData);
    }

    // Other methods...
}
</code></pre>
<p><strong>Compliant Code(.NET):</strong></p>
<pre><code class="lang-plaintext">[ApiController]
[Route("api/weather")]
public class WeatherController : ControllerBase
{
    private readonly IWeatherService weatherService;

    public WeatherController(IWeatherService weatherService)
    {
        this.weatherService = weatherService;
    }

    // GET /api/weather
    [HttpGet]
    public IActionResult GetWeather(string location)
    {
        // Validate the location parameter and restrict access to trusted sources
        if (!IsValidLocation(location))
        {
            return BadRequest();
        }

        // Make a call to the third-party weather API through the weather service
        WeatherData weatherData = weatherService.GetWeatherData(location);

        if (weatherData == null)
        {
            return NotFound();
        }

        return Ok(weatherData);
    }

    private bool IsValidLocation(string location)
    {
        // Implement validation logic to ensure the location is safe and trusted
        // This could involve white-listing trusted sources or validating against a known set of safe locations
        // Return true if the location is valid, false otherwise
        // Example: return Regex.IsMatch(location, "^[a-zA-Z]+(,[a-zA-Z]+)*$");
        // Implement your validation logic here

        // For simplicity, assuming any location is valid
        return true;
    }

    // Other methods...
}
</code></pre>
<p><strong>Noncompliant Code(Java):</strong></p>
<pre><code class="lang-plaintext">@RestController
@RequestMapping("/api/weather")
public class WeatherController {

    private final ThirdPartyWeatherService weatherService;

    public WeatherController(ThirdPartyWeatherService weatherService) {
        this.weatherService = weatherService;
    }

    // GET /api/weather
    @GetMapping
    public ResponseEntity&lt;WeatherData&gt; getWeather(@RequestParam String location) {
        // Make a direct call to the third-party weather API
        WeatherData weatherData = weatherService.getWeatherData(location);
        return ResponseEntity.ok(weatherData);
    }

    // Other methods...
}
</code></pre>
<p><strong>Compliant Code(Java):</strong></p>
<pre><code class="lang-plaintext">@RestController
@RequestMapping("/api/weather")
public class WeatherController {

    private final ThirdPartyWeatherService weatherService;

    public WeatherController(ThirdPartyWeatherService weatherService) {
        this.weatherService = weatherService;
    }

    // GET /api/weather
    @GetMapping
    public ResponseEntity&lt;WeatherData&gt; getWeather(@RequestParam String location) {
        // Validate the location parameter and restrict access to trusted sources
        if (!isValidLocation(location)) {
            return ResponseEntity.badRequest().build();
        }

        // Make a call to the third-party weather API through the weather service
        WeatherData weatherData = weatherService.getWeatherData(location);

        if (weatherData == null) {
            return ResponseEntity.notFound().build();
        }

        return ResponseEntity.ok(weatherData);
    }

    private boolean isValidLocation(String location) {
        // Implement validation logic to ensure the location is safe and trusted
        // This could involve white-listing trusted sources or validating against a known set of safe locations
        // Return true if the location is valid, false otherwise
        // Example: return location.matches("^[a-zA-Z]+(,[a-zA-Z]+)*$");
        // Implement your validation logic here

        // For simplicity, assuming any location is valid
        return true;
    }

    // Other methods...
}
</code></pre>
<p><strong>General prevention recommendations:</strong></p>
<p>Approach data received from external APIs with caution and validate them thoroughly.</p>
<p>Investigate and ensure the security and security standards of the third-party service before connecting to it.</p>
<p>Use encryption when communicating with external services to prevent the transmission of sensitive information in plain text.</p>
<p>Limit access and set appropriate permissions for third-party services.</p>
<p>Implement protective mechanisms like sandboxing and generalization to ensure the security and reliability of data received from external services.</p>
<p>Continuously monitor and survey to detect and rectify any security flaws in external services.</p>
<p>Train developers on security principles and the proper use of external APIs.</p>
]]></content:encoded></item></channel></rss>