Follow
Publications: 0 | Followers: 1

5-1 Defensive Coding 2

Publish on Category: Birds 268

Defensive coding techniques
Engineering Secure Software
Part 2
Last Time…
Always code defensivelyPrinciplesWriting insecure code is easyMaintainability still countsKnow thy APIsComplexity is the enemy of securityDon’t be paranoidTree of KnowledgeValidating InputSanitizing InputException HandlingSubclassingImmutabilityConcurrencyDouble-free
Concept: Attack Surface
Most exploits enter in through the UIOften the same interface the users seeHence: input validation & sanitizationAttack surfaceThe number & nature of the inputs for a given systemCan be quantifiedUsually comparedAttack surfaceincreases with…More inputse.g. new input fields, new featuresLarger input space for a given inpute.g. allowing a markup language instead of plaintext
Let your GET mean GET
HTTP protocols have different actionsGET – for retrieving data (typical usage)POST, DELETE, etc. – modify stuffHTTP protocol specifies that GET actions should never have apersistenteffect(e.g. model)Even though you can encode parameters into URLsGreatly helps mitigate cross-site request forgery (CSRF)Rarely respectedThis is okay:This is not:
<ahref="index.jsp?navigation=home">Home</a>
<ahref="index.jsp?changeName=Bobby">Change Name</a>
Native Wrappers
If you use another language, you inherit all of the risks in that languagee.g. Java Native Interface (JNI) can executea C program with a buffer overflowAlso: treat native calls as external entitiesPerform input validation & sanitizationLoaded at runtime spoofing opportunity
Cloning is Insecure(and Medically Unethical!)
Every Java object has aclone()methodOften error-proneDoesn’t do what you think it doesMost people don’t abide by the contractEven the Java architects don’t like itThe Java Language Secure Coding Guidelines from Oracle recommend not usingjava.lang.Cloneableentirely.Use your own copy mechanism if needed
public static final
Global variables areevilMutable global variables are an abominationIncreases complexity unnecessarilyTampering concernin anuntrustedAPIConstants are the only acceptable use ofglobalsNice try, but still doesn’t count:
publicstaticfinalList<String>list=newArrayList<String>();
Serial Killer
Serialization is often unnecessary, difficult to get rightDeserializingis essentially constructing an object without executing the constructorIf your system uses it, don’t assume the constructor will be executedCan reverse-engineer to violate constructor post-conditionsComplex input!Also, serialized != encryptedConfidentiality disclosureUsetransientfor variables that don’t need serializatione.g. environment info, timestamps, keys
Memory Organization Assumptions
Don’t rely upon the memory organization of the compiler and OSE.g. C-code:char a=5;char b=3;*(&a+1)=0; /* b is now 0 *//* this works, but not advisable */Lots of problems with thisCompilers changeOS’s changeDev environment vs. Customer environmentReally difficult to debug
Dead Store Removal
Don’t leave sensitive data sitting in memory longer than neededHibernation features dump RAM to HDDSegfault core dump passwords!The following is usually a good idea...…BUT!!!C++ .NET andgcc3.x will optimize away that last call sincepwdis never used againSo watch out for zealous compiler optimizations
voidGetData(char *MFAddr) {charpwd[64];if (GetPasswordFromUser(pwd,sizeof(pwd))) {if (ConnectToMainframe(MFAddr,pwd)) {// Interact with mainframe}memset(pwd, 0,sizeof(pwd)); //clearpassword}}
Environment & File Confusion
In C/C++, theputenv()andgetenv()vary OS to OSChange depending on the compiler and platformSometimes case-sensitive, sometimes notAn attacker can add an environment variable that overrides yours (e.g. to his own JVM)Samewith file names in Windows and LinuxDo not rely on case sensitivity when interacting with the platform
putenv("TEST_ENV=foo“);putenv("Test_ENV=bar“);constchar*temp =getenv("TEST_ENV");if(temp == NULL) {   /* Handle error */ }printf("%s\n", temp); /*fooon Linux, bar on Windows*/
Watch Character Conversions
Most apps require I18N in some formYou will need to convert one character set to another for translationWhen apps “catch on”, I18N is usually an afterthoughtNot all character sets are the same size!Assume 4-bytes for a character? Buffer overrun on Chinese charsNot every byte maps to a characterSometimes multiple bytes map to a single characterRecommendationsUseunicode: UTF-8 or UTF-16Don’t roll your own convertersCheck: web servers, database systems, command inputs
DoSin Many forms
Denial of service occurs in many, many waysOverflow the hard driveOverflow memory page faultsPoorhashcodesconstant hash collisionsSlow database queriesPoor algorithmic complexityDeadlocks, race conditions, other concurrencyNetwork bandwidth issuesRecommendations:Black-box stress testingWhite-box, unit-level stress testingFocus less on user inputs, more on the logicLearn the art of profilinge.g.java –agentlib:hprof
Don’t ForgetConfigFiles!
Vulnerabilities can also exist in systemconfiguratione.g. log overflow, hardcoded credentials, authorization problemsMakefiles& Installation definitionsInsecure compiler optimizationse.g. dead store removal optimizationsUsing out-of-date, vulnerable dependenciesAlso:I18N configurationsGeneral configurationExample configurationsRecommendationBring these up in code inspectionsLook at thedefaults, andwhat is missing
Other Defensive Coding viaVotD
Resource exhaustionCheck the limits of your inputInteger overflowsBuffer overflowsError message information leakageSecure loggingLog overflowAvoid logging stuff that’s sensitive anywayLimit use of privileged features of the languageUse the Java Security ManagerClassloaderoverrideComplex file system interactionReflection AbuseMore serialization restrictions

0

Embed

Share

Upload

Make amazing presentation for free
5-1 Defensive Coding 2