程序代写案例-FIT5003

  • February 8, 2021

FIT5003 Software Security Software Security In a Nutshell Apostolos Fournaris 1 2Software Security Renewed interest  “idea of engineering software so that it continues to function correctly under malicious attack”  Existing software is riddled with design flaws and implementation bugs  “any program, no matter how innocuous it seems, can harbor security holes” Threat Modelling (Architectural Risk Analysis) • Spoofing, Tampering, Repudiation, Information Disclosure, Denial of Service, and Elevation of Privilege • To follow STRIDE, you decompose your system into relevant components, analyse each component for susceptibility to threats, and mitigate them 4 STRIDE Approach 5Threat Modelling Process 6Level 1 Diagram 7Standard Mitigations Attacks and Defenses 9Attack Methodology STRIDE Threat Model Threat Property we want Spoofing Authentication Tampering Integrity Repudiation Nonrepudiation Information Disclosure Confidentiality Denial of Service Availability Elevation of Privilege Authorization 10 Attack Methodology (STRIDE) Spoofing Impersonating another person/process Cookie Replay / Session Hijacking CSRF (Cross-site request forgery) 11 Attack Methodology (STRIDE) Tampering Unauthorized alternations XSS SQL Injection 12 Attack Methodology (STRIDE) Repudiation Denying claims/unproven actions Audit Log Deletion Insecure Backup 13 Attack Methodology (STRIDE) Information Disclosure Exposure to unauthorized person/process Eavesdropping Verbose Exception 14 Attack Methodology (STRIDE) Denial of Service (DOS) Service unavailability Website defacement 15 Attack Methodology (STRIDE) Elevation of Privilege Increasing person/process access level Logic Flow Attacks 16 Buffer Overflow Attack stack grows overwrite new address overwrite buffer[11] … … buffer[0] foo()’s stack overwritemain()’sstack buffer copy malicious code Trigger the execution of malicious payloads Developer approaches: • Use of safer functions like strncpy(), strncat() etc, safer dynamic link libraries that check the length of the data before copying. OS approaches: • ASLR (Address Space Layout Randomization) Compiler approaches: • Stack-Guard-> Stack Canaries Hardware approaches: • Non-Executable bit (NX bit) Stack Countermeasures 18 Obfuscation int main() { … … … … } } Abstraction Transformation Destroy module structure, classes, functions, etc.! Data Transformation Replace data structures with new representations! Control Transformation Destroy if-, while-, repeat-, etc.! Dynamic Transformation Make the program change at runtime! Secure Software Design Good Practises 1.Model threats. Use threat modeling to anticipate the threats to which the software will be subjected. Threat modeling involves identifying key assets, decomposing the application, identifying and categorizing the threats to each asset or component, rating the threats based on a risk ranking, and then developing threat mitigation strategies that are implemented in designs, code, and test cases 2.Define security requirements. Identify and document security requirements early in the development life cycle and make sure that subsequent development artifacts are evaluated for compliance with those requirements. When security requirements are not defined, the security of the resulting system cannot be effectively evaluated. Define security requirements. • Identify and document security requirements early in the development life cycle • Make sure that subsequent development artifacts are evaluated for compliance with those requirements. • When security requirements are not defined, the security of the resulting system cannot be effectively evaluated. • OWASP: “A security requirement is a statement of needed security functionality that ensures one of many different security properties of software is being satisfied. Security requirements are derived from industry standards, applicable laws, and a history of past vulnerabilities” • Some standards with requirements: • ISO/IEC 27034; https://www.iso.org/obp/ui/#iso:std:iso-iec:27034:-1:ed-1:v1:en • OWASP Application Security Verification Standard; https://owasp.org/www-project-application-security-verification-standard/ • SAFECode “Fundamental Practices”; https://safecode.org/wp- content/uploads/2018/03/SAFECode_Fundamental_Practices_for_Secure_Software_Development_March_2018.pdf • SAFECode “Tactical Threat Modeling”; • SAMM; BSIMM; CWSS; CAPEC; • OWASP Threat Modeling Cheat Sheet Secure Design Principles Economy of mechanism: keep the design of the system as simple and small as possible. Fail-safe defaults: base access decisions on permission (a user is explicitly allowed access to a resource) rather than exclusion (a user is explicitly denied access to a resource). Complete mediation: every access to every object must be checked for authorization. Least privilege: every program and every user of the system should operate using the least set of privileges necessary to complete the job. Least common mechanism: minimize the amount of mechanism common to more than one user and depended on by all users. Psychological acceptability: it is essential that the human interface be designed for ease of use, so that users routinely and automatically apply the protection mechanisms correctly. Compromise recording: it is sometimes suggested that mechanisms that reliably record that a compromise of information has occurred can be used in place of more elaborate mechanisms that completely prevent loss. Defense in depth: design the system so that it can resist attack even if a single security vulnerability is discovered or a single security feature is bypassed. Defense in depth may involve including multiple levels of security mechanisms or designing a system so that it crashes rather than allowing an attacker to gain complete control. Fail securely: a counterpoint to defense in depth is that a system should be designed to remain secure even if it encounters an error or crashes. Design for updating: no system is likely to remain free from security vulnerabilities forever, so developers should plan for the safe and reliable installation of security updates Secure Design Principles: Develop an Encryption Strategy • Definitions of what to protect: • Data in transition • Data in storage • Designation of mechanisms to use for encryption: There exist many algorithms and ways to used them (mode of encryption etc.) • Decide on a key and certificate management solution: Encrypting data is only one half of an encryption strategy. The other half is the solution to manage encryption keys and certificates. • Implement with cryptographic agility in mind: An encryption strategy should specify how applications and services should implement their encryption to enable transition to new cryptographic mechanisms, libraries and keys when the need arises. Example: Hard-coding encryption keys (or other secrets) within source code leaves them very vulnerable and must be avoided Secure Design Principles: Standardize Identity and Access Management • This provides consistency between components as well as clear guidance on how to verify the presence of the controls. • What to include/consider? • The mechanism by which users (both end-users and organization administrators) authenticate their identities. • The mechanism(s) by which one service or logical component authenticates to another, how the credentials are stored, and how they are rotated in a timely fashion • The mechanism(s) that authorizes the actions of each principal.  Complete mediation • Authorization/authentication is linked: • The lease privilege policy.. • economy of mechanism, and • complete mediation Lease Privilege policy • Adhere to the principle of least privilege. Every process should execute with the least set of privileges necessary to complete the job. Any elevated permission should be held for a minimum time. This approach reduces the opportunities an attacker has to execute arbitrary code with elevated privileges. • Default deny. Base access decisions on permission rather than exclusion. This means that, by default, access is denied and the protection scheme identifies conditions under which access is permitted economy of mechanism • Keep it simple. Keep the design as simple and small as possible. Complex designs increase the likelihood that errors will be made in their implementation, configuration, and use. Additionally, the effort required to achieve an appropriate level of assurance increases dramatically as security mechanisms become more complex. Secure Design Principles: Establish Log Requirements and Audit Practices • Use the operating system logging mechanism to capture the status changes of the software and record software critical events • What is a security critical event? • The content of the log files should always be determined by the group or groups that will need to consume the log file contents. • It is important not only to capture the critical information but to restrict information capture to only the needed data. • It is equally important to carefully identify what security information is relevant and needs to be logged, where the logs will be stored, for how long the logs will be retained and how the logs will be protected Why loging and auditing is needed? • In the event of a security-related incident, it is important to be able to piece together relevant details to determine what happened. • Well-designed application, system and security log files provide the ability to understand an application’s behavior and how it has been used at any moment in time. • They are the fundamental data sources that inform automated Security Information and Event Management (SIEM) systems alerting. • Example: Linux logging • /var/log/syslog or /var/log/messages: Generic log mechanism • /var/log/auth.log or /var/log/secure: store authentication logs, including both successful and failed logins and authentication methods. • /var/log/boot.log: a repository of all information related to booting and any messages logged during startup. • /var/log/kern: stores Kernel logs and warning data. This log is valuable for troubleshooting custom kernels as well. • /var/log/dmesg: messages relating to device drivers. The command dmesg can be used to view messages in this file. • /var/log/faillog: contains information all failed login attempts, which is useful for gaining insights on attempted security breaches, such as those attempting to hack login credentials as well as brute-force attacks. • /var/log/mysqld.log or /var/log/mysql.log Secure Coding Practices Establish Coding Standards and Conventions: • use built-in security features in the frameworks and tools selected and ensure that these are on by default • Create a secure code writing policy and enforce it to the software development team. In principle there will be mostly the same for various programming language. It might need some fine tuning fro each programming language. • Architect and design for security policies. Create a software architecture and design your software to implement and enforce security policies. For example, if your system requires different privileges at different times, consider dividing the system into distinct intercommunicating subsystems, each with an appropriate privilege set. • There are secure coding standards to help • Eg.: https://wiki.sei.cmu.edu/confluence/display/seccode/SEI+CERT+Coding+Standards Secure Coding Practices Handle Data securely, Input Validation • All user-originated input should be treated as untrusted • Validate input. Validate input from all untrusted data sources. Proper input validation can eliminate the vast majority of software vulnerabilities. Be suspicious of most external data sources, including command line arguments, network interfaces, environmental variables, and user controlled files • Ensure that each area in the application stack defends itself against the malicious input it may be vulnerable to. • Even with input validation, vulnerabilities remain as a result of processing data in unsafe ways, and therefore input validation should only be considered as a defense in depth approach. • Additional steps: • Encoding, which ensures the data is transformed so that it will be interpreted purely as data in the context where it is being used • Data binding, which prevents data from being interpreted as control logic by binding it to a specific data type Secure Coding Practices Input Validation • Validation can be broken down into checking origin, data size, lexical content, syntactic format, and semantics. • Origin checks can be done by checking the origin IP or requiring an access key to counteract DDoS attacks. • Data size checks can be done both at the system border and at object creation. • Lexical content checks can be done with a simple regular expression (regexp). • Syntax format checks might require a parser, which is more expensive in terms of CPU and memory. • Semantic checks often require looking at the data in the database, such as searching for an entity with a specific ID. • Earlier steps in the validation order are more economical to perform and protect the later, more expensive steps. If early checks fail, later steps can be skipped Secure Coding Practices Input validation After initial input validation and filtering ….still attacks are possible: Attackers use alternativ formulation of data input that can by pass the validation process. Thus, we need: • Canonicalization: is the process for converting data that establishes how these various equivalent forms of data are resolved into a “standard,” “normal” or canonical form. Canonical representation ensures that the various forms of an expression do not bypass any security or filter mechanisms • Input validation should be done AFTER canonicalization should be validated and either accepted or rejected. Only after canonicalization can a decision be made. • Sanitization can involve removing, replacing or encoding unwanted characters or escaping characters. Input from untrusted sources should always be sanitized • Sanitize data sent to other systems. Sanitize all data passed to complex subsystems such as command shells, relational databases, and commercial off-the-shelf (COTS) components. • Attackers may be able to invoke unused functionality in these components through the use of SQL, command, or other injection attacks.. Secure Coding Practices Use Safe Functions Only • Many programming languages have functions and APIs whose security implications were not appreciated when initially introduced but are now widely regarded as dangerous. • Eg. Strcpy, strcat in C is vulnerable to buffer overflow • Java serializable objects • Javascript functions generate new code at runtime (eval, seTtimeout, etc.) and are a frequent source of code execution vulnerabilities. • The developers should counsel a security standard so that they avoid vulnerable functions Secure Coding Practices Handle Errors • Generated Errors can be exploited by attackers: • Information about the program • Data input manipulation • Even secret information disclosure • It’s better to fail fast in a controlled manner than to risk uncontrolled failures later. Fail fast by checking preconditions early in each method. • When notifying the user of an error, the technical details of the problem should not be revealed. • Details such as a stack trace or exception message provide little utility to most users, and thus degrade their user experience, but they provide insight to the attacker about the inner workings of the application • Error messages to users should be generic, and ideally from a usability perspective should direct users to perform an action helpful to them Secure Coding Practices Latest Compiler and Secure Compilers 1.Using the latest versions of compilers, linkers, interpreters and runtime environments: Commonly, as languages evolve over time they incorporate security features, and developers using previous compiler and toolchain versions cannot make use of these security improvements in their software 2.Secure complier options: Enable secure compiler options and do not disable secure defaults for the sake of performance or backwards compatibility. 3.Heed compiler warnings. Compile code using the highest warning level available for your compiler and eliminate warnings by modifying the code [C MSC00-A, C++ MSC00-A]. Use static and dynamic analysis tools to detect and eliminate additional security flaws. Defense in depth • Practice defense in depth. Manage risk with multiple defensive strategies, so that if one layer of defense turns out to be inadequate, another layer of defense can prevent a security flaw from becoming an exploitable vulnerability and/or limit the consequences of a successful exploit. • For example, combining secure programming techniques with secure runtime environments should reduce the likelihood that vulnerabilities remaining in the code at deployment time can be exploited in the operational environment. Beyond Secure Designing and Coding: Testing and Quality assurance • Use effective quality assurance techniques. Good quality assurance techniques can be effective in identifying and eliminating vulnerabilities. • Fuzz testing, penetration testing, and source code audits should all be incorporated as part of an effective quality assurance program. • Independent security reviews can lead to more secure systems. • External reviewers bring an independent perspective; for example, in identifying and correcting invalid assumptions Security Testing • Static Analysis Security Testing (SAST) • Dynamic Analysis Security Testing (DAST) • Audits • Penetration Testing (red team) • Run Time Monitoring 38 Java Security (Now) Bootstrap class files System class files User class files Bytecode Verifier Bootstrap ClassLoader System ClassLoader ClassLoader Security Manager Protection Domains AccessController Operating System Hardware Permissions Keystore CodeSource(URL, Certificates) Policy Database 39 Java Security  The class java.lang.SecurityManager is the focal point of authorization.  SecurityManager is concrete, with a public constructor and appropriate checks in place to ensure that it can be invoked in an authorized manner.  It consists of a number of check methods, e.g,: CheckPermission method is used to check to see if the requested access has the given permission based on policy. Security Manager 40 Java Security The bootstrap classloader is platform specific machine instructions that kick off the whole classloading process. Bootstrap classes – Classes that comprise the Java platform, including the classes in rt.jar and several other important jar files. The bootstrap classloader also takes care of loading all of the code needed to support the basic Java Runtime Environment (JRE), including classes in the java.util and the java.lang packages. Bootstrap Class Loader 41 Java Security classes from the system class path, which are set by the CLASSPATH environment variable System Class Loader java -Djava.system.class.loader=com.test.MyClassLoader MyApplication 42 Java Security  Customized ClassLoader or a subclass from java.security.SecureClassLoader provides security features beyond the standard Java2 security model.  ClassLoader loads classes into VM and is responsible for the namespaces at runtime. Namespaces as identically named identifiers can reference different objects.  Primordial class loader loads bootstrap classes in a platform-dependent manner.  System classes, some classes in java.* package are essential to the JVM and the runtime system are loaded by System ClassLoader. Class Loader when are classes loaded? 1. when the new bytecode is executed (for example, FooClass f = new FooClass();) 2. when the bytecodes make a static reference to a class (for example, System.out). 43 Java Security  Checks a classfile for validity:  Code should have only valid instructions and register use.  Code does not overflow/underflow stack.  Does not convert data types illegally.  Accesses objects correct types.  Method calls use correct number and types of parameters.  References to other classes use legal names. Byte Code Verifier 44 Java Security CodeSource  Java Code is downloaded over a network, so the code’s signature and author are critical to maintain a secure environment.  The object java.security.CodeSource describes a piece of code.  CodeSource encapsulates the code’s origin, which is specified as an URL.  Set of digital certificates containing public keys corresponding to the set of private keys are used to sign the code 45 Java Security  Keystore is a password-protected database that holds private keys and certificates.  The password is selected at the time of creation.  Each database entry can be guarded by its own password for extra security.  Certificates accepted into the keystore are considered to be trusted. Keystore 46 Access Policy The policy file(s) specify what permissions are allowed for code from a specified code source, and executed by a specified principal. $JAVA_HOME/jre/lib/security/java.security $JAVA_HOME/jre/lib/security/java.policy $ /usr/libexec/java_home /Library/Java/JavaVirtualMachines/ jdk1.8.0_152.jdk/Contents/Home 47 Access Policy $JAVA_HOME/jre/lib/security/java.policy grant codeBase “file:${{java.ext.dirs}}/*” { permission java.security.AllPermission; }; grant { permission java.util.PropertyPermission “java.version”, “read”; }; policy.url.1=file:${java.home}/lib/security/java.policy policy.url.2=file:${user.home}/.java.policy $JAVA_HOME/jre/lib/security/java.security 48 Access Controller static boolean unaligned() { if (unalignedKnown) return unaligned; String arch = AccessController.doPrivileged( new sun.security.action.GetPropertyAction(“os.arch”)); unaligned = arch.equals(“i386”) || arch.equals(“x86”) || arch.equals(“amd64”) || arch.equals(“x86_64”); unalignedKnown = true; return unaligned; } get_property permission 49 Access Controller static boolean unaligned() { if (unalignedKnown) return unaligned; String arch = AccessController.doPrivileged( new sun.security.action.GetPropertyAction(“os.arch”)); unaligned = arch.equals(“i386”) || arch.equals(“x86”) || arch.equals(“amd64”) || arch.equals(“x86_64”); unalignedKnown = true; return unaligned; } get_property permission Class Method Constructor Field Modifier Others Reflection Reflection Method[] methods = MyObject.class.getMethods(); for(Method method : methods){ System.out.println(“method = ” + method.getName()); } This example obtains the Class object from the class called MyObject. Using the class object the example gets a list of the methods in that class, iterates the methods and print out their names. Reflection How to get Metadata of Class? 1 cls.getName(); 2  cls.getModifiers(); 3  cls.getInterfaces(); 4  cls.getSuperclass().getName(); import java.io.Serializable; public abstract class fit5003base implements Serializable,Cloneable { } 12 3 4 Reflection How to get Metadata of Variable? from the specified class as well as from its super class Field[] field1 = cls.getFields(); //from the specified class only Field[] fiel2 = cls.getDeclaredFields(); Java Deserialization in a Nutshell Serializable creates: •a public hidden constructor •a public interface to all fields of that class Deserialization is Object Creation and Initialization •Without invoking the actual class’s constructor Any available class can be deserialized •Calling ObjectInputStream.readObject() using untrusted data can result in malicious behavior 55 Public Key Encryption Generating Key KeyPairGenerator keyGen = KeyPairGenerator.getInstance(“RSA”); keyGen.initialize(512); KeyPair pair = keyGen.generateKeyPair(); PublicKey publicKey = pair.getPublic(); PrivateKey privateKey = pair.getPrivate(); Cipher cipher = Cipher.getInstance(“RSA”); cipher.init(Cipher.ENCRYPT_MODE, publickey); byte[] buf = cipher.doFinal(“xyz”.getBytes()); System.out.println(new String(buf)); Encrypt Decrypt Cipher cipher2 = Cipher.getInstance(“RSA”); cipher2.init(Cipher.DECRYPT_MODE, privatekey); byte[] buf2 = cipher2.doFinal(buf); System.out.println(new String(buf2)); publicKey privateKey 56 Android Basics Activity Service Content Provider Broadcast Receiver Component – Explicit – The intent “explicitly” specifies which component it wants to talk to – It specifies the target’s full package name / component – Implicit – The intent just describes the type of action to perform (and, optionally, some data) – Good source of info / tutorial: link 57 Explicit vs. Implicit Intents 58 Activity1 Activity2 ICC methods: e.g., startActivity(Intent) Action: test.ACTION Category: test.CATEGORY Activity3 Implicit Intent (example) 59 Activity1 Activity2 ICC methods: e.g., startActivity(Intent) destComp: Activity2 Activity3 Explicit Intent (example) 60 ICC Issues Activity1 Activity2 MaliciousActivity Want to Send SMS but does not declare SEND_SMS permission Declared SEND_SMS permission Exploit SEND_SMS 61 ICC Issues Component1 Component2 Activity Hijacking Service Hijacking Broadcast Theft Activity Launch Service Launch Broadcast Injection Malicious Components Malicious Components Hijacking Launch 62 Android Permission System  activity  restricts access to the activity  checked when starting activity  throw SecurityException if caller does not have required permission  service  restricts who can start, stop or bind to the service  receiver  restricts who can send broadcasts to the BroadcastReceiver  checked at delivery, after broadcast was sent  does not throw exception in case of permission failure  provider  restrict who can access the data  read and write permissions  checked when performing operations(e.g. query, insert) package=”com.example.awesomeapp”> … 63 Permission Request 64 Clone Detection Piggybacked App Original App Malicious Payload Carrier Rider Hook Wu Zhou, Yajin Zhou, Michael Grace, Xuxian Jiang, and Shihong Zou. Fast, scalable detection of “piggybacked” mobile applications. In CODASPY ’13, pages 185–196, New York, NY, USA, 2013 65 Clone Detection  Similarity Comparison  Symptom Discovery  (Un)Supervised Learning  Runtime Monitoring 66 Privacy Leak source sink Taint Analysis public class Activity_A { void onCreate(Bundle b) { String id = telManager.getDeviceId(); //… String alias = id; String number = “+3524666445556”; sms.sendTextMessage(number, null, alias, null, null); } } 67 source sink Privacy Leak White Box: Static Code Analysis Black Box Fuzzing 68 Security Testing (Methodology) Goals: Find common bugs quickly Allow humans to focus on parts of code likely to be risky Limitations Cannot find design level vulnerabilities Cannot make a judgement of importance of a found vulnerability Only detect vulnerabilities in tool’s “rule database” Suffer from errors: False positive: reported bugs are not really bugs False negative: missed reporting a real bug 69 Static Code Analysis 70 Control-Flow Graph (CFG) read(x); while (X<10){ X←X-1; A[X]←10; if (X=4) X←X-2; }; Y←X+5; Exercise! ENTRYB0: read(x); if (x>=10) goto B4B1: X=X-1 A[X]=10; If (X=4)goto B3; B2: EXITB5: Y=x+5B4: X=x-2B3: Simple (usually free) search-based tools Examples: FlawFinder, RATS, ITS4, … Search source file for “dangerous functions” known to cause common vulnerabilities e.g. strcpy(), gets() for buffer overflows Produces list of “hits” and ranks them by risk Better than just pure search Ignores commented code Ignores strings Some risk ranking But little attempt to analyze relationships within code 71 Static Code Analysis 72 Fuzz Testing  Automaticaly generate test cases  Many slightly anomalous test cases are input into a target interface  Application is monitored for errors  Inputs are generally either file based (.pdf, .png, .wav, .mpg)  Or network based…  http, SNMP, SOAP  Or other…  e.g. crashme() 73 Fuzz Testing (Mutation) Strengths Super easy to setup and automate Little to no protocol knowledge required Weaknesses Limited by initial corpus May fail for protocols with checksums, those which depend on challenge response, etc. 74 Fuzz Testing (Generation-based) Strengths Completeness Can deal with complex dependencies e.g. checksums Weaknesses Have to have spec of protocol Often can find good tools for existing protocols e.g. http, SNMP Writing generator can be labor intensive for complex protocols The spec is not the code Web Technologies 75 3-Tier Web Architecture: Client-Server-Database Interface tier Logic tier Storage tier Client Web Browser (IE, Chrome, Firefox,… ) Web Server (IIS, Apache, …) Database / Backend server (MySQL, MS-SQL, Oracle, …) HTTP / HTTPS Browser script (HTML / HTML5, CSS, Javascript, VBScript, DOM/Ajax/ JSON/XML, browser extensions: Java applets, ActiveX,Flash,Silverlight, … ) SQL, SOAP /XML,…Server Script (PHP, Java, ASP.NET, Python, Perl, …) Database language (MySQL, MS-SQL, Oracle, …) Web Security Overview Server Side: Database Query Languages • Structured Query Language (SQL) • Variants: Oracle, MS-SQL, MySQL • SQL manages relational databases: • Database consists of tables • Each table has a number of rows (database records) , e.g. a row per user • Each row has a number of columns (data fields), e.g. “email address”, “name”, “age”,… • SQL language queries: read, update, add, or delete data • E.g. SELECT email FROM users WHERE name = ‘Li’ • Returns email column value for rows in users table where the name column value = ‘Li’. 76 Web Security (Server Side) Client Side: Browser Security Policy •Browser security goals: • User can safely visit any web site • Even malicious web sites cannot access / modify client’s local disk / memory information without user’s permission • Browser runs Javascript in a sandbox – access OS / file system via API enforcing access control • E.g. Upload authorization via file picker dialog. • However, a web site can still track users (e.g. cookies,…)! • User can safely visit multiple web sites in same browser: • Open page from site X cannot interfere (read/write) with open page from site Y • E.g. banking site window should not be read by script in social networking window • Enforced via the browser Same Origin Policy 77 Web Security (Browser Side) • Another method to bypass escaping: second-order SQLi • Suppose ‘ character in user input string was escaped (replaced by ’’) by web application A second-order vulnerability for string inputs may still be exploitable: • Consider app registering users in database and then retrieving • Attack first phase: attacker registers escaped input into database • Attacker registers into database user name such as • bob ‘ OR 5=5 — • Due to escaping of ‘ character, this user name is processed correctly, and inserted into database • No injected code execution in phase 1. But now the stored username string is bob‘ OR 5=5 — without escaping… 78 SQL Injection Vulnerabilities • How to defend effectively against SQLi? • Filtering / escaping is tricky / can often be bypassed • Preferred robust solution: parameterized queries • A.k.a prepared statements • Fix root cause of injection problem: SQL database treating user data as code • Idea: Application passes the SQL statement to SQL server in two distinct phases: • Phase 1 (pass code): Pass desired SQL statement with placeholders (? Symbol) for data values, e.g. $stmt = $mysqli->prepare(“SELECT District FROM City WHERE name=?”); • Phase 2 (pass data): Pass the data values for placeholders, e.g.: $stmt->bind_param(“s”, $name); • Finally, execute and get result, e.g.: •$stmt->execute(); /* This executes the prepared statement $stmt */ •$result = $stmt->get_result(); /* Get result into $result */ •$stmt->close(); /* This completes the prepared statement */ • Any malicious user data passed in Phase 2 will be interpreted as data, not code. 79 SQL Injection Vulnerabilities 6REFLECTED XSS Another Practical example 1. The attacker crafts a URL containing a malicious string and sends it to the victim. 2. The victim is tricked by the attacker into requesting the URL from the website. 3. The website includes the malicious string from the URL in the response. 4. The victim’s browser executes the malicious script inside the response, sending the victim’s cookies to the attacker’s server. https://excess-xss.com/ ATTACK SCENARIO The steps involved in a stored XSS attack A Practical Example 1. The attacker uses one of the website’s forms to insert a malicious string into the website’s database. 2. The victim requests a page from the website. 3. The website includes the malicious string from the database in the response and sends it to the victim. 4. The victim’s browser executes the malicious script inside the response, sending the victim’s cookies to the attacker’s server. https://excess-xss.com/ Attacker can craft a URL containing JavaScript code as the value of the message parameter This code will be dynamically written into the page and executed in the same way as if the server had returned it E.g. http://domain- a.net/error/18/Error.ashx?message= 28 DOM-BASED XSS Another Practical example 1. The attacker crafts a URL containing a malicious string and sends it to the victim. 2. The victim is tricked by the attacker into requesting the URL from the website. 3. The website receives the request, but does not include the malicious string in the response. 4. The victim’s browser executes the legitimate script inside the response, causing the malicious script to be inserted into the page. 5. The victim’s browser executes the malicious script inserted into the page, sending the victim’s cookies to the attacker’s server. https://excess-xss.com/ Cross-Site Request Forgeries (CSRF) • Recall: Cross-Site Scripting (XSS) vulnerabilities need attacker script to be reflected back from application (step 4): • XSS prevented if application output is filtered/encoded to avoid reflecting attacker script – step 4 is blocked. • BUT, steps 2 and 3 still possible! Can this still be exploited? • Sometimes, YES, via OSRF/CSRF vulnerabilities 86 Cross-Site Request Forgeries (CSRF) 87 • Session Fixation Vulnerabilities • Suppose: • same session token used for all requests • session token = URL parameter in user request • Attack: 1. Attacker logs in anonymously to http://amazon.com • Obtains session token: SESS=2as435sdf34251sdg 2. Attacker sends user john a URL with attacker’s session token • E.g. user gets email with URL http://amazon.com/login.php?SESS=2as435sdf34251sdg 3. User clicks attacker’s URL and logs in to Amazon: • Amazon associates attacker’s token with logged in user john 4. Attacker uses token to hijack user’s session: • Attacker requests http://amazon.com/browse.php?SESS=2as435sdf34251sdg • Gets access to john’s amazon session • Defense: John gets new session token from Amazon at step 3, attacker’s session id not accepted in step 4. 88 Session Management 89 Blockchain 90 Smart Contract Tx-nTx-1 Block Mining Miners Tx-2 Block A set of TXs Previous block New State Root Receipt Root Nonce SHA3(Block) < D Broadcast Block Verify transactions & execute all code to update the state 91 Smart Contract Code execution • Every (full) node on the blockchain processes every transaction and stores the entire state P6 P5 P4 P3 P2 P1 This is a new block! I’m a leader This is a new block! This is a new block! This is a new block! This is a new block! This is a new block! 92 Smart Contract • Halting problem • Cannot tell whether or not a program will run infinitely • A malicious miner can DoS attack full nodes by including lots of computation in their txs • Full nodes attacked when verifying the block uint i = 1; while (i++ > 0) { donothing(); } 93 Smart Contract Solution: Gas Charge fee per computational step (“gas”). Special gas fees for operations that take up storage Sender has to pay for the gas 94 The DAO Attack A DAO is a Decentralized Autonomous Organization. Its goal is to codify the rules and decision making apparatus of an organization, eliminating the need for documents and people in governing, creating a structure with decentralized control. 95 Unchecked CALL Return Values The return value of send() is not checked 96 eEXAMs eAssessment Platform on 25th of November (a 2h 10min exam) Sample eExam next week Consultations will be announced on the Ed platform 20 MCQs and 6-8 Short Essay Questions Related to lectures AND the tutorials/labs The answers can be derived from the slides/labs but you will also have to make some critical reflection on the existing resources. Thank you! Hope you enjoyed the Unit 97 欢迎咨询51作业君