Performing Secure Code Review of R Code – A Beginner’s Guide

Background
R is a programming language primarily used for statistical computing and graphical presentation to analyze and visualize data. R is an interpreted language, meaning R programs are not pre-compiled but executed by the R interpreter at runtime. An R file is a script written in the R programming language and saved with the .R file extension.

R language - Ecosystem
Comprehensive R Archive Network (CRAN)
CRAN is R's central software repository, supported by the R Foundation. It is an archive of the latest and previous versions of the R distribution, documentation, and contributed R packages.

Posit – Shiny
Shiny is an R package used to build interactive web applications that execute R language code on the back-end. It enables users to host standalone applications on a webpage, embed interactive charts in R Markdown documents, and build dashboards.

OSS Index

OSS Index is a free catalogue of open source components and scanning tools developed by Sonatype. It helps developers identify open source dependencies, known publicly disclosed vulnerabilities, understand risk, and keep their software secure. The vulnerability data is derived from public sources and does not include human-curated intelligence or expert remediation guidance.

Shiny Applications
A typical web application built using the Shiny package runs the `shinyApp(ui, server)` object. The `ui.R` and `server.R` files contain the code for the client-side and server-side, respectively, which makes up the major logic and code for the application.


 

 

 

R Markdown Files
Another important file type used in applications developed using R is the `.Rmd` file, which is an R Markdown file. It is a specific type of file format designed to produce documents that include both code and text. These files are typically used to generate report files for the results in formats like DOCX, HTML, and PDF.

Secure code review guidelines 

Get background information

  • Obtain a brief overview of the application's purpose
  • Understand the feature list
  • Identify the targeted audience and deployment environment


Assess Potential Vulnerabilities
R is a statistical programming language primarily used for domain-specific application development. Based on the application details, try to gauge what security vulnerabilities the code may be susceptible to.

Understand Code Structure
Examine how the code handles user input, imports and exports data file, manages configurations, processes data, makes external/third-party calls, utilizes libraries/packages, and generates the user interface.

Check for Vulnerable Packages

  • \Packages are typically listed at the beginning of .R files
  • Package versions can be found in the package_list.csv file
  • If the package list file is not available, installed packages and versions can be found using the following command:
  • Vulnerabilities for R language-based packages can be found on the OSS Index
  • The `oysteR` package is an R interface to the OSS Index that allows users to scan their installed R packages


HTTP Requests
Look for HTTP requests from the code files. The `httr` package is commonly used to make HTTP requests from R language code. Check the sensitivity of the data sent in the HTTP request, if applicable.

User Input Sanitization
Trace the input data received from the user interface
Ensure that input data is validated, escaped, and sanitized using blacklisting or whitelisting approaches
For file imports, check that the file data is properly sanitized before consuming it in the program logic
Various functions can be used to search for specific characters and/or patterns in R, such as `gsub`, `grepl`, `str_replace`, and `str_replace_all` from the `stringr` package

Hardcoded Secrets
Check for hardcoded secrets like passwords, keys, or tokens in the code.

Built-in Security Features
R comes with a variety of built-in security features that can help protect your software. Here are a few key features:

  • Secure Password Storage: R provides the `bcrypt` package for secure password hashing
  • Secure Communication: The `openssl` package in R can be used to encrypt communication, ensuring data confidentiality and integrity
  • Data Anonymization: R's `sdcMicro` package provides methods for anonymizing data, a key aspect of privacy preservation

Common security vulnerabilities in R code
The most common security vulnerabilities in R code primarily revolve around the handling of data serialization and deserialization, particularly with RDS (R Data Serialization) files. Here are some of the common vulnerabilities observed:

Arbitrary Code Execution

Recent findings have highlighted a critical vulnerability, which allows for arbitrary code execution through the deserialization of untrusted RDS files. This vulnerability exploits R's lazy evaluation and promise objects, enabling attackers to craft malicious RDS files that execute arbitrary code when loaded. This poses a significant risk, especially in environments where R packages are shared among developers and data scientists.

Supply Chain Attacks
The nature of R's package management system, particularly with repositories like CRAN, makes it susceptible to supply chain attacks. An attacker can overwrite legitimate R packages with malicious versions containing harmful code. When users load these compromised packages, the malicious code is executed, potentially leading to system compromise.

Input Validation Issues
Like many programming languages, R is vulnerable to injection attacks if user inputs are not properly validated. This includes risks associated with SQL injection and command injection, especially when R is used to interact with databases or execute system commands.

Lack of Access Controls
R applications often lack robust access control mechanisms, which can lead to unauthorized access to sensitive data or functionalities. Ensuring that proper authentication and authorization checks are in place is essential to mitigate this vulnerability.

Insecure Data Handling

Improper handling of sensitive data, such as failing to encrypt data at rest or in transit, can expose applications to data breaches. It is crucial to implement strong encryption practices when dealing with sensitive information in R.

Article by Maunik Shah & Krishna Choksi

SSRF - Detection, Exploitation, and Mitigation Techniques [Part 3]

In the previous part 1 and part 2, we explored different techniques for detecting and exploitation of Server-Side Request Forgery (SSRF) based on the application's scenarios. Server-Side Request Forgery (SSRF) vulnerabilities pose a formidable threat to web applications, enabling malicious actors to exploit internal network assets, potentially leading to data breaches or unauthorized access to both the application and its underlying infrastructures. Within this discourse, we shall embark upon a profound exploration of potent SSRF mitigation techniques, designed to bolster the security of your applications across diverse scenarios – securing internal pages, and network URLs, handling external URL requests, and ensuring proper protocol/schema use. Additionally, we will offer specific advice for safeguarding cloud-hosted applications on platforms like AWS, Azure, and Google.

Constructing Resilient Applications: Scenarios and Strategies

In the realm of application development, consider these situations:

Securing Internal Pages Access Architecture:

  • Enlist a secure URL parsing library to meticulously extract schema, hostname, URL path, and query string.
  • Employ judicious input validation even though data are encoded or in different formats, as each parameter undergoes rigorous scrutiny to eliminate potential vulnerabilities.
  • In the case of dynamic generation of URL, only append the path associated with the specific page into the designated host configuration, while excluding extraneous parameters.
  • Unleash the power of map path functions to transform relative URLs into absolute URLs.
  • Validate input for URL formats, scrutinizing binary characters relevant to localhost URLs, employing techniques such as CIDR, dots, decimal/octal/hexadecimal, and domain parser confusion attacks.

Securing Internal URL Access Architecture:

  • Keep an updated list of internal IPs and domains, using it for whitelist/blacklist approaches to control access.
  • Enlist a secure URL parsing library to meticulously extract schema, hostname, URL path, and query string along with strict input validation on hostname and IPs.
  • Employ a local DNS resolver for converting DNS requests.
  • Validate destination IP against whitelist/blacklist IPs before granting access.
  • Handle encodings and null characters securely.
  • Avoid taking the internal application's IP address as user input; manage it from the backend.
  • Resolve DNS to A and AAAA IPs, validating them.
  • Make a single DNS call and use the IP for subsequent calls, preventing DNS rebinding attacks (time to check vs time to use).

Securing External URL Access: Few applications fetch or send data to an external domain through webhooks or external calls for image rendering, metadata processing, etc functionalities.

  • Permit access only to public IP ranges and limit access from private IP ranges.
  • Ensure that the backend web client does not reveal any sensitive information in the HTTP request’s headers such as user-agent, cookies, etc.
  • Do not throw any errors when IPs or URLs cannot be reached.
  • Follow guidelines for internal URL access architecture for validating input against IPs and domains.
  • Whitelisting of external URLs or domains would be a better approach.

Securing Protocol/Schema Usage in the Application:

  • Allow only HTTPS access.
  • Explicitly disable undesired URL schemas like gopher, sftp, file, dict, ftp, etc.
  • Ensure your URL parsing tool disables these schemas as well.

Securing Metadata of the Cloud hosted application:

  • AWS - Disable IMDSv1. Only enable IMDSv2 if required.
  • IMDSv2 - Token is being used as an authorization header. The value of the token is collected from the PUT request and the same token value is passed in the next request used as an authorization header to get the metadata details.
    • TOKEN=`curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"`
    • curl http://169.254.169.254/latest/meta-data/profile -H "X-aws-ec2-metadata-token: $TOKEN"
  • Azure – By default “Metadata"="true" header is passed as a request header in the HTTP request to get the metadata details. (ref: - https://learn.microsoft.com/en-us/azure/virtual-machines/instance-metadata-service?tabs=windows)
  •  Google – By default “Metadata-Flavor: Google” header is passed as a request header in the metadata HTTP request to get the metadata details. (ref: https://cloud.google.com/compute/docs/metadata/querying-metadata)

Strengthening Defences: Extra Layers of Security

Along with the above techniques, network layer and host-based firewalls can be utilized as an additional layer of protection that complements application layer protection. Also, enable authentication/access control for internal applications to thwart unauthorized access.
By implementing these Server-Side Request Forgery (SSRF) mitigation techniques, you can significantly reduce the risk of SSRF attacks and protect your applications from potential vulnerabilities. It is crucial to adopt a layered approach to security, combining proper input validation, access controls, and secure configurations to ensure the integrity and confidentiality of your application’s resources.

Article by Amish Shah

Unveiling the Vulnerabilities: Hacking Cloud Native Apps and Discovering the Silver Lining

 

The security of cloud storage services, such as S3/GCP Buckets, the implementation of Cognito/SSO OAuth, and the protection of API endpoints have become paramount for web applications. As cloud integration becomes more accessible, comprehensive assessments of these components before deployment are crucial. Cloud infrastructure offers technological advancements, resource availability, and cost savings compared to traditional setups. However, cloud-native applications bring unique challenges. This talk addresses risks associated with user authentication using OAuth providers like Google, Slack, or AWS Cognito, where insecure implementations can lead to complete user account takeovers. It delves into security concerns regarding cloud storage services like AWS S3/GCP Buckets, which expose sensitive user data to unauthorized access. Additionally, vulnerabilities introduced by API-based micro-services employing Serverless lambda functions are explored. Attendees will gain insights into identifying, exploiting, and mitigating these cloud-native vulnerabilities through manual penetration testing and automated tools, as well as practical mitigation techniques.

Here for more detail on this talk.

Speakers

avatar for Amish Shah

Amish Shah

Co-CEO and Director, Blueinfy Solutions Pvt. Ltd
Amish Shah, Co-CEO and Director at Blueinfy, an esteemed technical expert in the field. With a wealth of experience spanning over 20 years, Amish brings a unique blend of skills in secure product development, application security assessment, and red team exploitation. As the technical... Read More →


[Case Study] Case Study: Securing App Directory Applications with Targeted Security Reviews

Background
ACME has emerged as a leading messaging platform company that specializes in providing real-time communication solutions. With a robust suite of features designed for managing notifications from users and groups, ACME has positioned itself as an essential tool for businesses and individuals seeking efficient communication.

One of the standout features of ACME's platform is its ability to allow users and vendors to develop applications that integrate seamlessly with third-party API/SaaS solutions. This capability enables users to receive notifications and updates in real-time, consolidating various operational outcomes into a single interface. By eliminating the need for users to switch between multiple applications, ACME enhances user experience and operational efficiency.

However, as the App Directory applications have full privileges to the platform, poorly written applications can compromise the security of the ACME’s platform along with the ACME’s users’ data. Thus, it becomes extremely important for the companies to protect their platform itself as well as the data of users whenever users use the App Directory apps developed by a third party. Hence, the rapid expansion of the App Directory has introduced significant security challenges. As more applications are added, the risk of vulnerabilities and security breaches increases, necessitating a comprehensive approach to security reviews.

Challenges
The integration of third-party applications into ACME's platform presents several challenges:
Security Risks: The extensive App Directory poses significant security risks if comprehensive reviews are not performed. Each application may introduce vulnerabilities that could compromise user data and the integrity of the platform.

Complexity of Integrations:
Automated security scanners often struggle to conduct thorough reviews due to the intricate nature of these integrations. The diverse functionalities and varying levels of security compliance among third-party applications complicate the review process.

Time-Consuming Manual Testing: While manual black-box testing can provide in-depth security insights, it is often time-consuming and resource-intensive. This approach can delay the onboarding of new applications, impacting ACME's growth and responsiveness to market demands.

Need for a Systematic Approach: Without a structured methodology for security reviews, ACME risks overlooking critical vulnerabilities, which could lead to data breaches and loss of user trust.

Solutions
To address these challenges, ACME partnered with Blueinfy. Blueinfy undertook a comprehensive analysis of ACME's application development process and architecture in order to build a efficient security review methodology. The following solutions were implemented:

Development of a Security Review Methodology: Blueinfy created a tailored methodology to define the scope of security reviews based on integrated application domains and related functionalities. This systematic approach ensures that all relevant aspects of an application are considered during the review process.

Identify Scoped Entities: The methodology specifies the domains and users interacting with the platform application, whether directly or indirectly, through data communication. By clearly defining these interactions, the focus of the security reviews would be on
the most critical areas, ensuring thorough examination of potential vulnerabilities.

Time-Bound Black-Box Security Reviews: Blueinfy conducted time-bound black-box application security reviews on the specified scoped domains/entities. This focused approach allowed for efficient testing while maintaining high standards of security assessment. Remarkably, this process achieved zero false positives and negatives, ensuring that all identified vulnerabilities were genuine and actionable.

Outcome
The partnership between ACME and Blueinfy yielded significant positive outcomes:

Secure Expansion of App Directory: ACME can now securely expand its App Directory, incorporating hundreds of applications within a minimal timeframe. The targeted security reviews have instilled confidence in the integrity of the applications being added.

Effective Vulnerability Mitigation: The targeted security reviews ensure that vulnerabilities associated with third-party integrations are effectively mitigated. This proactive approach minimizes the risk of security breaches and enhances user trust in the platform.

Operational Efficiency: By streamlining the security review process, ACME can onboard new applications more quickly, maintaining its competitive edge in the messaging platform market.

Conclusion
The collaboration between ACME and Blueinfy serves as a compelling case study in the importance of targeted security reviews for application platforms. As the digital landscape continues to evolve, the need for robust security measures becomes increasingly critical. By implementing a systematic approach to security reviews, ACME has not only enhanced the security of its App Directory but also ensured operational efficiency and user trust.

Article by Amish Shah

The Fading Line Between Data and Instruction in LLM-Driven Applications

Overview

In the ever-advancing landscape of technology, the once distinct boundary between data and instruction is steadily dissolving, particularly in the realm of Language Model (LM) driven applications. These applications, powered by impressive language models like GPT-3.5, built upon the foundation of Large Language Model (LLM) architecture, possess the extraordinary capability to process and generate vast volumes of text. This remarkable feat allows them to undertake tasks that were previously exclusive to human intelligence, marking a significant paradigm shift.

Over time, language models have undergone remarkable transformations, and LLMs have propelled this evolution to unprecedented heights. Traditional programming paradigms relied on explicit instructions to manipulate data. However, LLMs have revolutionized this approach by harnessing the power of large datasets, extracting intricate patterns, and leveraging their knowledge to generate text. This transformative capability empowers LLMs to undertake a diverse range of tasks, including natural language understanding, text completion, and even creative writing.

Root cause:

The diminishing line between data and instruction in LLM-driven applications can be attributed, in large part, to the dynamic interpretation of input. LLMs possess the remarkable ability to comprehend and interpret the contextual intricacies of the provided data, enabling them to discern the underlying task or instruction at hand. This dynamic interpretation empowers LLMs to generate responses or outputs that align seamlessly with the intended objective, even when the instructions are not explicitly specified.

LLMs shine in their aptitude for contextual understanding, a trait previously reserved for human cognition. By meticulously analyzing the surrounding text, LLMs can discern the desired instructions or tasks implicitly embedded within the data. This context-driven approach equips them to generate outputs that are remarkably accurate and relevant, even when the inputs are incomplete or ambiguous.

Security implication:

While the blurring line between data and instruction in LLM-driven applications opens up new horizons and offers unparalleled convenience, it also raises crucial considerations regarding security. On one hand, this convergence facilitates more seamless and intuitive interactions with technology, as users can input data in a natural and flexible manner. On the other hand, concerns arise regarding the potential for misinterpretation or bias in the outputs generated by these models.

Prompt Leakage

The inadvertent exposure of initial prompts in language models, known as prompt leakage, has sparked concerns regarding the disclosure of sensitive information, biases, and limitations embedded within them. This phenomenon poses potential risks to privacy and security.

Language models, including the powerful LLM (Large Language Model), often come preconfigured with specific prompts to initiate the generation of responses and guide the model's behavior. These prompts may contain sensitive information, limitations, or inherent biases that should be treated with utmost confidentiality. However, prompt leakage occurs when a language model unintentionally reveals its initial prompt configurations, undermining the safeguarding of such sensitive content.

The following link provides a compilation of examples showcasing leaked system prompts: [Link: https://matt-rickard.com/a-list-of-leaked-system-prompts].

Prompt Injection

A Large Language Model (LLM) stands as a formidable and intricate form of language model, distinguished by its immense size and parameter count. LLMs, often based on architectures like Transformers, undergo training on vast datasets, equipping them with the ability to learn patterns, grammar, and semantics from extensive textual sources. These models boast billions of parameters, granting them the capacity to generate coherent and contextually relevant text across a wide array of tasks and applications.

Within the realm of machine learning, particularly in the context of LLMs, the role of a prompt is of paramount importance. A prompt serves as the initial input or instruction provided to the model, shaping its behavior and influencing the output it produces. It acts as a starting point or contextual framework for the model's responses or task execution. Prompts can assume various forms, ranging from a few words to a sentence, a paragraph, or even a dialogue, tailored to the specific requirements of the model and the task at hand. The primary purpose of a prompt is to furnish the necessary context, constraints, or explicit instructions that guide the model's decision-making process and shape the content it generates.

Prompt injection, conversely, entails purposefully embedding a targeted instruction, query, question, or context into the model's prompt to manipulate or influence its subsequent output. Through skillful construction of the prompt, users can steer the model's responses in their desired direction or elicit specific types of answers. Prompt injection grants users greater control over the generated text, enabling them to tailor the model's output to meet specific criteria or objectives.

The concept of prompt injection proves especially valuable when fine-tuning the model's responses to attain desired outcomes or generate content that aligns with specific requirements. It empowers users to guide the model's creative output and shape the conversation in accordance with their needs. Prompt injection finds applications in various domains, including generating creative writing, providing customized responses in chatbots, or facilitating specific tasks such as code generation or translation.

Nevertheless, it is crucial to acknowledge that prompt injection can introduce vulnerabilities and raise ethical concerns. There is a potential for malicious actors to manipulate the model to generate harmful or biased content. Hence, it is of utmost importance to implement safeguards, robust validation mechanisms, and regular model updates to mitigate potential risks.

Here is the link with examples and possbilities - https://simonwillison.net/2023/Apr/14/worst-that-can-happen/