600 likes | 803 Views
SDL and the CWE/SANS Top 25. MSSD-3 — третья по счету конференция, посвященная всестороннему обсуждению популярной и важной темы – минимизация уязвимостей программного обеспечения при его разработке. What is the CWE/SANS Top 25?.
E N D
SDL and the CWE/SANS Top 25 MSSD-3 — третья по счету конференция, посвященная всестороннему обсуждению популярной и важной темы – минимизация уязвимостей программного обеспечения при его разработке.
What is the CWE/SANS Top 25? The CWE/SANS Top 25 Most Dangerous Software Errors is a list of the most widespread and critical errors that can lead to serious vulnerabilities in software. They are often easy to find, and easy to exploit. They are dangerous because they will frequently allow attackers to completely take over the software, steal data, or prevent the software from working at all.
SDL memory corruption related tasks • Layout randomization • Stack cookies • NX • Safe exception handling • Many more… • Removing banned APIs • Code analysis • Using safe integer arithmetic • Fuzzing • Education
Removing banned APIs • SDL has banned over 100 C/C++ functions • Removing banned APIs removes potential security bugs with very little engineering effort
Banned API examples • strcpy and variants lstrcpy, wcscpy, _mbscpy, etc • strcat and variants • sprintf and variants • gets • lstrlen
Finding banned APIs • Use #include <banned.h> • VC++ deprecates many functions • Triage C4996 warnings
Removing banned APIs C++ std::string StrSafe Safe CRT #include <string>std::string dst;dst += src; #include <strsafe.h>if (StringCchCat(pszDest,cchDest,pszSrc) == S_OK){ … } if (strcat_s(pszDest,cchDest,pszSrc) == 0) { … }
Removing banned APIs automatically #define _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES 1 #define _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES_MEMORY 1 • ~25% of banned APIs removed automatically
Static analysis • Native static analysis tool ships with VC++ (/analyze) • Finds many common memory corruption bugs • As a general rule, any memory corruption bug should be treated as real
Integer overflow memory corruption • Math quiz: 65535 + 1 = ?
Integer overflow pattern size_t cb = num * sizeof(T); T *p = malloc(cb); size_t cb = 16384 * 4; T *p = malloc(0); size_t cb = 5 * 4; T *p = malloc(20);
Safe arithmetic libraries SafeInt class libraryfor C++ Windows IntSafe functions for C/C++ #include <safeint3.hpp>using namespace msl::utilities;SafeInt<size_t>cbFoo(sizeof(T));SafeInt<size_t>cb = cbFoo * num;T *p = malloc(cb) #include <intsafe.h>if (SUCCEEDED(SizeTMult(num,sizeof(T),&cb))) T *p = malloc(cb);
Additional memory corruption defenses • Address Space Layout Randomization (ASLR) • Stack cookies (/GS) • No eXecute (NX) a.k.a. Data Execution Prevention (DEP) • Exception handler protection (SafeSEH and SEHOP) • HeapSetInformation • Encoding long-lived pointers
ASLR • Randomizes memory locations • Introduced in Windows Vista and Server 2008 • Images must be linked with /DYNAMICBASE Boot 1 Boot 3 Boot 2 ssleay32.dll user32.dll app.exe app.exe user32.dll process address space ntdll.dll ntdll.dll ssleay32.dll app.exe user32.dll ntdll.dll ssleay32.dll
Exploit: Return address overwrite • Common stack-based buffer overflow • Return address is overwritten to get code execution Local Variables Saved EBP Return address Arguments Buffer overflow
Stack cookies (/GS) • Compiler change introduced in VS2002 • Cookie inserted into stack frame in function prologue • Cooke validated before function return in function epilogue • Mismatching cookie leads to process termination • Compile with /GS GS Cookie Local Variables Saved EBP Return address Arguments 0xa47c1039 0x0012ef04 0x7601148c 0x41414141 0x41414141 0x7843110b
SDL memory corruption related tasks • Layout randomization • Stack cookies • NX • Safe exception handling • Many more… • Removing banned APIs • Code analysis • Using safe integer arithmetic • Fuzzing • Education
SDL injection defense related tasks • Reduce privileges • HttpOnly • X-XSS-Protection • Encode or escape input • Validate input • Encode or escape output • Code analysis • Use anti-forgery tokens
SQL injection string Status = "No"; string sqlstring =""; try { SqlConnectionsql= new SqlConnection( @"data source=localhost;" + "user id=sa;password=…;"); sql.Open(); sqlstring="SELECT HasShipped" + " FROM Shipment WHERE ID='" + Id + "'"; SqlCommandcmd = new SqlCommand(sqlstring,sql); if ((int)cmd.ExecuteScalar() != 0) Status = "Yes"; } catch (SqlException se) { Status = sqlstring + " failed\n\r"; foreach (SqlError e in se.Errors) { Status += e.Message + "\n\r"; }
SQL injection string Status = "No"; string sqlstring =""; try { SqlConnectionsql= new SqlConnection( @"data source=localhost;" + "user id=sa;password=…;"); sql.Open(); sqlstring="SELECT HasShipped" + " FROM Shipment WHERE ID='" + Id + "'"; SqlCommandcmd = new SqlCommand(sqlstring,sql); if ((int)cmd.ExecuteScalar() != 0) Status = "Yes"; } catch (SqlException se) { Status = sqlstring + " failed\n\r"; foreach (SqlError e in se.Errors) { Status += e.Message + "\n\r"; } • Connecting as admin • SQL command built from concatenated strings • Detailed error messages returned to users
SQL injection sqlstring="SELECT HasShipped" + " FROM Shipment WHERE ID='" + Id + "'"; SqlCommandcmd = new SqlCommand(sqlstring,sql);
SQL injection sqlstring="SELECT HasShipped" + " FROM Shipment WHERE ID='" + Id + "'"; SqlCommandcmd = new SqlCommand(sqlstring,sql); sqlstring="SELECT HasShipped" + " FROM Shipment WHERE ID=@id"; SqlCommandcmd = new SqlCommand(sqlstring,sql); cmd.Parameters.Add("@id", SqlDbType.Int); cmd.Parameters["@id"].Value = Id;
SQL injection sqlstring="SELECT HasShipped" + " FROM Shipment WHERE ID='" + Id + "'"; SqlCommandcmd = new SqlCommand(sqlstring,sql); IQueryable<Shipment> shipmentQuery = from shipment in Shipment where id == Id select shipment;
SQL injection sqlstring="SELECT HasShipped" + " FROM Shipment WHERE ID='" + Id + "'"; SqlCommandcmd = new SqlCommand(sqlstring,sql); procName="FindShipment"; SqlCommandcmd = new SqlCommand(procName,sql); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@id", SqlDbType.Int); cmd.Parameters["@id"].Value = Id;
; deldeleteete from table Incorrect Filtering
Validate untrusted input • Use regular expressions for simple cases • Beware of ReDoS… • ValidateRequest for ASP.NET Web Forms
Cross-site scripting/HTML injection response.Write("Hello " + request["name"]);
Cross-site scripting/HTML injection response.Write("Hello " + request["name"]); • HTML response includes unsafe user-provided data
Cross-site scripting/HTML injection response.Write("Hello " + request["name"]); • HTML response includes unsafe user-provided data
Cross-site scripting/HTML injection response.Write("Hello " + request["name"]); • HTML response includes unsafe user-provided data
Escaping/encoding untrusted input response.Write("Hello " + HtmlEncode(request["name"])); • HTML response safely encodes untrusted input
Static analysis • FxCop (also integrated with Visual Studio) • Code Analysis Tool .NET
Reduce permissions • Permit only stored procedure execution rights
Browser defense-in-depth measures • HttpOnly cookies • IE X-XSS-Protection flag
Cross-site Request Forgery • Not a code injection vulnerability • Still a trust issue http://bank.com/transfer?acct=bryan&amt=1000 • SDL requires use of anti-forgery tokens such as ViewStateUserKey
SDL injection defense related tasks • Reduce privileges • HttpOnly • X-XSS-Protection • Encode or escape input • Validate input • Encode or escape output • Code analysis • Use anti-forgery tokens
Don’t use broken cryptography • Use known strong crypto • Use non-cryptographic algorithms such as CRC32 • Don’t design your own algorithms
Don’t use stream ciphers Plaintext 1 Key 1 Ciphertext 1 Plaintext 2 Key 1 Ciphertext 2 Ciphertext 2 Plaintext 1 xor Plaintext 2 Ciphertext 1
Threat modeling • “The cornerstone of the SDL” • Data flow diagrams (DFDs) • STRIDE per element • Mitigations • Assumptions • External dependencies Datastore Trustboundary Process
Threat modeling to find authentication/authorization issues • Spoofing; mitigated by authentication controls • Tampering; mitigated with integrity controls • Repudiation; mitigated by many of the other controls • Information Disclosure; mitigated by confidentiality controls • Denial of Service; mitigated by throttling and authorization controls • Elevation of Privilege; mitigated by authorization controls