Secure Coding

  • Missing object level Access Control
    • Acts as an Authorization mechanism
    • Access is set up at the code level to determine which objects a user can or cannot access.
    • Failure to set up object level access control can leave records or other objects open to unauthorized access or modification.
    • Example
      • A listing page lists data for each business users
      • Now these are coming from an endpoint of service url.
      • If the service url is not Object level access controlled Any attacker can modify url and see Users in different businesses.
      • Moreover the attacker can also insert new users as admin and malicious Scripts in database.
    • To prevent missing object level access control, Developers should.
      • Ensure the authorization mechanism is set up based on the applications user policies and data level Access hierarchy.
      • Perform checks to see weather users have access to perform the requested actions for each function.
      • If possible use random values that are difficult to predict as globally unique identifier’s to ID records.
      • Ensure there are tests in place to evaluate the access control mechanism.
    • APIs tend to expose endpoints that handle object identifiers, creating a Wide attack surface Level  access control issue.Object level authorization checks should be considered in every function that accesses a data source using an input from the user.
  • Improper Authentication
    • Improper authentication occurs when an application improperly verifies the identity of a user.
    • As a result this can lead to the exposure of resources or functionality to unintended actors possibly providing attacks with sensitive information.
    • All multiuser applications that use different privilege levels are potentially affected by this vulnerability.
    • Example
      • An application uses encoded user objects as authentication cookies.
      • A malicious user Logs in as a normal user with this session cookie.
      • On decoding the cookie he gets the user object with user details.
      • Now this malicious user can create a admin cookie by encoding user details with admin role.
    • To avoid improper authentication
      • Beware of insufficient, incorrect or missing authentication checks that may allow a user to access functionality without supplying correct credentials.
      • Don’t expose session ID’s in the URL.
      • Implement multi factor authentication.
      • Don’t use user ID’s or predictable sequential values as session IDs.Instead use a secure server-side session manager that generates a session ID with high entropy.
    • Authentication mechanisms are often implemented incorrectly, allowing attackers to compromise authentication tokens or to exploit implementation flaws to assume other users identities Temporarily or permanently.
    • Compromising systems ability to identify the client/user, compromises API security overall.
  • Sensitive data exposure
    • Sensitive data exposure is a vulnerability where developers expose sensitive user data to unauthorized people like hackers all other third parties.
    • Following types of data are considered as sensitive user data
      • Personal identifiable information (PII)
      • Payment card industry (PCI)
      • Data subject to a privacy law such ass the general data protection regulation (GDPR)
    • Attention must be paid as to where and how data is being used in the system.
    • For example
      • While sending User information Addresses may not be sure do user but an adversary could inspect response and discover the address of the user.
    • To avoid sensitive data exposure
      • Identify where and how data is used and combined
      • Prevent sending unnecessary data to the users
      • Finally secured GDPR, PCI and PII data through encryption
    • Looking forward to generic implementation, Developers tend to expose all object properties without considering their individual sensitivity relying on clients to perform the data filtering before displaying it to the user.
  • Lack of resources and rate limiting
    • Affects APIs
    • All APIs have limited resources and are been called by multiple clients simultaneously.
    • The risk occurs When the APIs Is unable to effectively limit the number of requests all deliverables handled in a given time period.
    • This vulnerability Occurs when APIs Rate limits or resource limits are not set correctly, or not set at all.
    • API becomes unresponsive or unavailable when overloaded with unexpectedly high traffic Or a spike of calls.
    • This could happen if a company is experiencing a busy season.
    • Attackers can Also intentionally monopolize an API resources by using malicious Scripts.
    • To prevent ensure following limits are set properly
      • Execution timeouts
      • Maximum allocable memory
      • The number of processes permitted within a defined time frame.
      • Maximum number of file descriptors.
      • Maximum number of requests allowed per client.
      • The number of records per page, which can be returned per request.
      • Be sure To display a notification when these limits are met and include the time when the limit will be reset.
    • Try to use put method to create Records. The post method is unsafe and not Idempotent because it changes the state of the server which could be dangerous for the application as it allow to make too many requests in a short period.
    • Quite often, APIs do not impose any restrictions on the size or number of resources that can be requested by the client/user. Not only can this impact API Server performance leading to denial of service(DOS), But also leaves the door open two authenticate flows such ass brute force.
  • Missing function level access control
    • This occurs when users can perform Functions that they are not authorized for or when resources can be accessed by unauthorized users.
    • Functional Level access control is missing when access checks have not been implemented Or when a protection mechanism exists but is not properly configured.
    • Example
      • Attacker is authenticated user of the site and tries to gain elevated access to the application by either guessing or brute forcing URLs they are able to find an unprotected administrative page
        • The Attacker has now access to status page only meant for administrators.
        • Attacker is in authenticated user of the site which uses a popular framework. Knowing the firework the attacker crafts a request to create a new user with elevated permissions.
        • Since the “create user” Function is not properly protected by control checks, the request succeeds and a new user is created with admin privileges.
        • The attacker now has admin access to the site.
    • Impacts
      • Accounts could be taken over, including privileged ones,With stolen account, The attacker Could do anything the victim Could do.
      • Sensitive end-user or customer data could be stolen, leading to reputational damage and revenue loss.
      • An Employee from sales department could view information from finance department.
      • An attacker could forge request in order to access functionality without Proper authorization.
      • An attacker can also Gain access to The administrative panel of the application leading to disruption of the website, causing loss of customers and revenue.
    • Prevention 
      • Protect All business functions using a role-based authorization mechanism implemented on the service side.
      • Authorization should be applied using centralized routines either provided by the framework or easy to use external modules.
      • Always deny access by default as per Ji “least privilege” principle.
      • Implement Functional access control on the server never on the client.
    • Complex access control policies with different hierarchies, groups, and roles and an unclear separation between administrative and regular functions tend to lead to authorization flaws. By exploiting these issues, Attackers gain access to other users resources and/or administrative functions.
  • Mass Assignment
    • Mass assignment is a Vulnerability in which a API endpoints do not restrict which properties of their associated object can be modified by the user.
    • Mass assignment vulnerability can occur when the object represented within the HTTP request is bound directly to the data model used for storage, but fails to distinguish between fields that should be assignable and immutable.
    • This can happen automatically using the recommended defaults in some frameworks or as a conscious decision of the developer themselves For a particular situation.
    • Example
      • We are using same Endpoint to retrieve And update user details.
      • In the same object format they received from the endpoint they submit using put request updating the role.
      • The server Accepts And updates the rule
    • Prevention
      • Parse the request values Rather than Binding directly to an object.
      • Use a Reduced data transfer Object rather than binding directly to an object.
      • Ensure that sensitive properties are blacklisted Or only safe properties are whitelisted for direct object binding.
    • Binding client provided data (example JSON) to data models without proper properties Filtering based on a whitelist, usually leads to mass assignment.Either guessing object properties, exploring Other API and points, Reading The documentation, Or providing additional object properties in the request payloads allows attackers to modify object properties they are not supposed to.
  • Disabled security features
    • Disabled security features is a vulnerability where features that can help protect against hackers have been deactivated.
    • Security features may have been disabled four operational reasons or they may be simply Disabled by default.
    • For example
      • Our web app is storing session ID in cookie,Despite being securely generated the cookie is missing The flags that restrict it to secure HTTP requests and prevent it from being accessed by browsers Scripts.
      • A hacker manages To find a vulnerable field in a feedback form and injects malicious script to run in a browser.
      • The script is made to read session cookie transmitting it’s data to the hacker.
      • The hacker can now use the captured cookie data to pretend to be any of the users from the site stealing account details and performing actions as those users.
    • It’s recommended to verify that all Relevant restrictions are enabled.
    • Additionally Developers should ensure that, where features need to be disabled the data is Coupled with extra checks to help prevent manipulation by hackers.
    • Security misconfiguration is commonly a result of insecure default configuration, incomplete or ad-hoc configurations,Open cloud storage, misconfigured HTTP headers, unnecessary HTTP methods permissive Cross-Origin Resource Sharing (CORS), And verbose error messages containing Sensitive information.
  • Injection Flaws
    • SQL injections occur when an attacker is able to inject sql queries via the input data of an application.
    • Causes
      • User input is used to dynamically Build Queries, if this input is not first validated, the query  interpreter can be tricked into Running arbitrary SQL queries or commands.
    • To prevent SQL injection, developers should use parameterized queries.
    • Example
      • A user submits his credentials using POST parameters.
      • The parameters are appended to a Database Query String that is submitted to a database.
      • The credientials all valid and appropriate response is sent to the web server. Finally Seesion cookie is returned to the browser and user is now logged in.
      • This is normal Authentication but this can be bypassed using in SQL injection.
      • Attacker can input values that can take advantage of the query as follows.
        • Select*from users where username=‘admin’ and password=‘ABC’ or 1=1.
        • Here “abc or 1=1” condition is entered as input by attacker.
        • This changes the logic of the query and because of the always true condition, the password condition gets ignored.
      • The vulnerability is exploited in order to gain control to an account without providing a valid password.
      • The session cookie is returned to the Browser and the attacker is now logged in as in as an administrator.
    • Impacts
      • A Successful Injection could allow an attacker to update, insert or delete data.
      • All data could be exposed Or even deleted.Furthermore access to hosting system could be gained by an attacker, with proper authentication Process being bypassed as a result any altered data such as balance And transaction information could cause reputation issues.
      • Account And private data theft could damage reputation and credibility, leading to customer and revenue loss.
      • System unavailability could result in loss of revenue and reputation.
    • To prevent SQL injection it is important to use parameterized queries.
    • Developers should never concatenate User controllable input with application SQL sent to the database. Instead use parameterized queries.
    • All popular development frameworks Provide support for the secure construction of database queries.
    • In addition, developers Should use allow list Validation on all user input. This ensures all input is checked against an allowed list of input parameters, Before they are processed in the code.
    • Always apply The least privilege principle on all backend Database Users.
    • Consider GET & POST parameters, cookies and other HTTP headers.
  • OS command injections
    • An OS command injection is a vulnerability that Allows Arbitrary commands to be executed on the operating system of the application.
    • Causes
      • This vulnerability can happen when user controlled input, through parameters, Cookies, HTTP headers, etc. are passed to system shell without any prior validation.
    • Example
      • A GET parameter ‘File to delete’ Is passed To the system shell without prior validation.
      • This perimeter can be appended by attacker with malicious commands.
      • The application appends the GET parameter to the command string and the malicious command is executed.
      • If the url Is like “?fileToDelete=afile.txt;‘rm -rf /var/www’” All the web application file will be deleted.
      • The web application becomes unavailable.
    • Impacts
      • Injected commands will be run with the privileges of vulnerable application.
      • User passwords or other sensitive data could be displayed on the application output.
      • Customer data could get exposed leading to privacy issues and a damaged reputation.
      • Commands executed as the application owner could lead to reputation issues.
      • Files or database records could be manipulated or deleted and Services could even be started or stopped.
    • To prevent use Framework specific API calls instead of OS commands.
    • We should validate all user controlled output against an allow list before passing it to the shell.
      • This validation should include
        • Post and Get parameters
        • cookies
        • HTTP headers
    • Apply Principle of least privilege do the application 
    • Injection flaws,Such as SQL,No SQL, command injection etc. occur when untrusted data Is sent to an interpreter as part of a command or query.The attackers malicious data can trick the Interpreter into executing unintended commands or accessing data Without proper authorization.
  • Improper assets management
    • Improper assets management is a vulnerability In which attackers are able to Take advantage of outdated, incomplete or undocumented API behavior.
    • Improper assets Management vulnerabilities happen when an attacker is able to leverage undocumented or insecure functionality from outdated or development versions of API Endpoints.
    • This usually occurs when these versions remain Connected to the Data source used by the current API.
    • Example
      • A code compilation service provides an API which is rate-limited per user to ensure that all customers are able to access the functionality according to their access tier.
      • One of the development teams Posts a snippet of code To a popular debugging site, hoping to solve a tricky problem they are having.
      • This post leaks the address of the staging server used for testing new features against The production Database.
      • An Attacker finds that they can run tasks freely using the staging Server.
    • Prevention
      • Developers should ensure that production data and data stores are Kept Separate from development and staging environments.
      • Implement additional security controls such as Firewalls, to prevent intended access to Sensitive or weekend Environments.
      • Fully document the endpoints and error states That exist within API.
      • Ensure that legacy API versions all validated by any safety checks implemented in the latest version.
      • APIs tend to Expose more endpoints than Traditional Web applications, making proper and updated documentation highly important. Proper hosts and deployed API versions inventory also play an important role to mitigate issues such as deprecated API versions and exposed debug Endpoints.
  • Insufficient logging 
    • Insufficient Logging is the Lack of recording proper Historical information about events that happened inside an Application.
    • Causes
      • The application does not log auditable events, such as logins, failed login, and high-value transactions.
      • Warnings and errors Generate inadequate Unclear or no Log messages at all.
      • The application is unable to detect, escalate, or alert for active attacks in real time or, at least near real time.
      • Penetration testing and vulnerability scans do not trigger alerts.
    • Example
      • Attacker gains access to a list of valid usernames used on the website.
      • The website only logs failed attempts and alerts administrator whenever a certain account Receives Three subsequent failed login Attempts.
      • Attackers attacks via whole list of valid accounts he has on the list.
      • Thus There will be only one failed login per account And administrator will not be notified.
      • Attackers waits a day for the subsequently Failed login counter to reset.
    • Impact
      • If an attacker Gains access to the system through an application That has insufficient login He Will probably get away unnoticed.
      • Lack of an audit Trail will also make it hard to prove an attacker has committed a crime.
      • An application with insufficient Logging will Also be harder to debug Or perform Maintenance on, because the operations happening in the application cannot be followed up.
    • Prevention
      • Ensure all failures are properly logged With sufficient user context.
      • Log entries Should be held for a sufficient Time to allow through forensic analysis.
      • Ensure that Logs are generated in a Format that can be easily consumed by a centralized log management solution.
      • Ensure high-value transactions have an audit trail With integrity controls to prevent tempering or Deletion, such as append-Only Database tables or similar.
      • Ensure we have effective monitoring and alerting so that suspicious activities are detected And handled in a timely fashion.
    • Insufficient logging and monitoring, coupled with missing all ineffective integration with incident response,Allows attackers to further attack systems, maintain persistence, Pivot to more systems to Tamper with, extract, or destroy data.
    • Most breach studies demonstrate the time to detect a breach is over 200 days, typically detected by external parties rather than internal process or monitoring.

No comments:

Post a Comment

Recursion

Q What do you understand by a Recursive  Programme? Recursion Is the process of repeating items in a self similar way. In programming langua...