Download presentation
Presentation is loading. Please wait.
1
Designing and Writing Secure Application Code John Mitchell
2
General topics in this course uVulnerabilities How hackers break into systems –Circumvent security mechanisms (e.g., dictionary attack) –Use code for purpose it was not intended (buffer overflow) uDefensive programming Build all software with security in mind Make sure web server is not root shell uSecurity Mechanisms Authentication Access control Network protocols This lecture
3
Security vs Correctness uCorrectness Do all the things that are required, possibly more Good input Good output uSecurity Protect desired system properties against attack Bad input Bad output uWhat is a security component? Any portion of a system that has access to sensitive information, or that may effect the integrity of the system, must be secure
4
Silly (but illustrative) Example uKryptonite lock uSpecial Bic pen feature Much to our surprise, we were able to hack our Kryptonite Evolution 2000 U-Lock with a ballpoint pen
5
Building secure systems uSecure specification Intended functionality of the system must be secure uSecure system architecture Architect system to resist attack uSecure coding Each module should –do what is required for correctness –without doing things that compromise security Common problem: implementation does more than specification requires –E.g., handle large input buffers by running shell
6
Secure Specification: Example uWeak VPN system User authenticates using password Allows session hijacking, other problems uNext version Improve password system for better security Original functionality for backward compatibility uNet result? Version rollback attack: No better security than before!
7
Secure architecture and coding uRecall common problems from Lecture 2 Weak input checking Buffer overflow Inappropriate logging Unintended functionality Inappropriate privilege Race conditions Misconfigured systems Lack of diversity
8
Basic concepts [Wheeler] Design carefully Avoid buffer overflow, other coding problems Program Component Validate input Respond judiciously Call other code carefully See Wheeler’s book on web
9
Topics uGeneral principles Least privilege, defense in depth, minimize trust, … uExample Sendmail vs qmail vs Postfix uTools for secure coding Type-safe programming languages Purify Perl tainting Code analysis algorithms Run-time monitoring (save for another lecture)
10
General design advice uCompartmentalization Principle of least privilege Minimize trust relationships uDefense in depth Use more than one security mechanism Secure the weakest link Fail securely uPromote privacy uKeep it simple uConsult experts Don’t build what you can easily borrow/steal Open review is effective and informative
11
Compartmentalization uDivide system into modules Each module serves a specific purpose Assign different access rights to different modules –Read/write access to files, I/O –Execute privileged instructions (e.g., Unix root) Check module input and output carefully uPrinciple of least privilege Give each module only the rights it needs uMinimize trust relationships Clients, servers should not trust each other –Both can get hacked Trusted code should not call untrusted code
12
Example:.NET class NativeMethods { // This is a call to unmanaged code. Executing this method requires // the UnmanagedCode security permission. Without this permission, // an attempt to call this method will throw a SecurityException: [DllImport("msvcrt.dll")] public static extern int puts(string str); [DllImport("msvcrt.dll")] internal static extern int _flushall(); }
13
Code denies permission not needed [SecurityPermission(SecurityAction.Deny, Flags = SecurityPermissionFlag.UnmanagedCode)] private static void MethodToDoSomething() { try { Console.WriteLine(“ … "); SomeOtherClass.method(); } catch (SecurityException) { … }
14
Defense in Depth uFailure is unavoidable – plan for it uHave a series of defenses If an error or attack is not caught by one mechanism, it should be caught by another uExamples Firewall + network intrusion detection Code module illustration on next slide uFail securely Many, many vulnerabilities are related to error handling, debugging or testing features, error messages
15
Defense in Depth Check security Application.dll Application.exe Check security Secure resource with an ACL Application.dll [MSDN]
16
Secure the weakest link uThink about possible attacks How would someone try to attack this? What would they want to accomplish? uFind weakest link(s) Crypto library is probably pretty good Is there a way to work around crypto? –Data stored in encrypted form; where is key stored? uMain point Do security analysis of the whole system Spend your time where it matters
17
Keep It Simple uUse standard, tested components Don’t implement your own cryptography uDon’t add unnecessary features Extra functionality more ways to attack uUse simple algorithms that are easy to verify A trick that may save a few instructions may –Make it harder to get the code right –Make it harder to modify and maintain code
18
Promote Privacy uDiscard information when no longer needed No one can attack system to get information uExamples Don’t keep log of old session keys Delete firewall logs Don’t run unnecessary services (fingerd) uHiding sensitive information is hard Information in compiled binaries can be found Insider attacks are common
19
Example logging bug (PHP < 4.0.3) uError logging format string If error logging enabled, php_syslog function called with user-provided data Php_syslog called printf, using that data as the format string (!) uAttack Cause process to overwrite stack variables with arbitrary data Allows remote attacker to “take over” PHP process (usually with web server’s privileges)
20
Don’t reinvent the wheel uConsult experts uAllow public review uUse software, designs that other have used uExamples Bad use of crypto: 802.11b Protocols without expert review: early 802.11i Use standard url parser, crypto library, good random number generater, …
21
Security by Obscurity uSecurity by Obscurity is a BAD IDEA Do not hide security keys in files Do not rely on undocumented registry keys Assume an attacker knows everything you know uWhy? If attacker has 1-in-a-million chance, and there are a million attackers, you are out of luck uBetter approach Predictable code with unpredictable keys
22
Example: Mail Transport Agents uSendmail Complicated system Source of many vulnerabilities uQmail Simpler system designed with security in mind Gaining popularity Qmail was written by Dan Bernstein, starting 1995 $500 reward for successful attack; no one has collected
23
Stanford Sendmail Vulnerability Sent: Tuesday, March 04, 2003 1:12 PM To: unix-info@lists.Stanford.EDU Subject: Stanford ITSS Security Alert: sendmail Header Processing Vulnerability sendmail is the most popular Mail Transfer Agent (MTA) program in use on the Internet, … sendmail contains an error in one of the security checks it employs on addresses in its headers, which may allow an attacker to execute malicious code within the sendmail security context, usually root… All users of sendmail should patch immediately …
24
Amusing sendmail bug uSendmail debug flags: -dflag,value Sendmail –d8,100 sets flag #8 to value 100 Sendmail checked for max but not min flag numbers, since input format doesn’t allow negative numbers int >= 231 considered negative by C on 32-bit hosts uName of config file in data segment before flag array etc/sendmail.cf file gives /bin/mail path Sendmail –d4294967269,117 –d4294967270,110 – d4294967271,113 changed “etc” to “tmp” Attacker creates /tmp/sendmail.cf which claims local mailer is /bin/sh; debug call gives root shell to attacker [Wheeler]
25
Market share YearSendmailQmail 199680% 199776% 199863% 200055% 200147%9% 200242%17%
26
Simplified Mail Transactions mbox Mail User Agent Mail Delivery Agent Mail Transport Agent Mail User Agent uMessage composed using an MUA uMUA gives message to MTA for delivery If local, the MTA gives it to the local MDA If remote, transfer to another MTA
27
Qmail Security uLeast privilege Each module uses least privileges necessary Only one setuid program –setuid to one of the other qmail user IDs, not root –No setuid root binaries Only one run as root –Spawns the local delivery program under the UID and GID of the user being delivered to –No delivery to root –Always changes effective uid to recipient before running user-specified program uOther secure coding ideas
28
Structure of qmail qmail-smtpd qmail-localqmail-remote qmail-lspawnqmail-rspawn qmail-send qmail-inject qmail-queue Incoming SMTP mail Other incoming mail
29
Structure of qmail qmail-smtpd qmail-localqmail-remote qmail-lspawnqmail-rspawn qmail-send qmail-inject qmail-queue uSplits mail msg into 3 files Message contents 2 copies of header, etc. uSignals qmail-send
30
Structure of qmail qmail-smtpd qmail-localqmail-remote qmail-lspawnqmail-rspawn qmail-send qmail-inject qmail-queue uqmail-send signals qmail-lspawn if local qmail-remote if remote
31
Structure of qmail qmail-smtpd qmail-local qmail-lspawn qmail-send qmail-inject qmail-queue uqmail-lspawn Spawns qmail-local qmail-local runs with ID of user receiving local mail
32
Structure of qmail qmail-smtpd qmail-local qmail-lspawn qmail-send qmail-inject qmail-queue uqmail-local Handles alias expansion Delivers local mail Calls qmail-queue if needed
33
Structure of qmail qmail-smtpd qmail-remote qmail-rspawn qmail-send qmail-inject qmail-queue uqmail-remote Delivers message to remote MTA
34
Least privilege qmail-smtpd qmail-localqmail-remote qmail-lspawnqmail-rspawn qmail-send qmail-inject qmail-queue root setuid
35
UIDs qmail-smtpd qmail-localqmail-remote qmail-lspawnqmail-rspawn qmail-send qmail-inject qmail-queue root setuid qmailduser qmailq qmails qmailr root user setuid user qmailq – user who is allowed to read/write mail queue
36
Principles, sendmail vs qmail uDo as little as possible in setuid programs Of 20 recent sendmail security holes, 11 worked only because the entire sendmail system is setuid Only qmail-queue is setuid –Its only function is add a new message to the queue uDo as little as possible as root The entire sendmail system runs as root –Operating system protection has no effect Only qmail-start and qmail-lspawn run as root.
37
Principles, sendmail vs qmail uPrograms and files are not addresses sendmail treats programs and files as addresses –“sendmail goes through horrendous contortions trying to keep track of whether a local user was responsible for an address. This has proven to be an unmitigated disaster” (DJB) qmail programs and files are not addresses –“The local delivery agent, qmail-local, can run programs or write to files as directed by ~user/.qmail, but it's always running as that user. Security impact:.qmail, like.cshrc and.exrc and various other files, means that anyone who can write arbitrary files as a user can execute arbitrary programs as that user. That's it.” (DJB)
38
Keep it simple, qmail vs sendmail uParsing Limited parsing of strings –Minimizes risk of security holes from configuration errors uLibraries Avoid standard C library, stdio –“Write bug-free code” (DJB) uDon’t repeat functionality One simple mechanism handles forwarding, aliasing, and mailing lists (instead of 3) Single delivery mode instead of a selection
39
Comparison LinesWordsCharsFiles qmail-1.011602844331370123288 sendmail-8.8.852830179608121811653 zmailer-2.2e10575952055241423624227 smail-3.2623312461401701112151 exim-1.90677782720842092351127
40
Postfix uOrigin similar to qmail freeware by security specialist Wietse Venema uCharacteristics Very fast Several programs (but fewer than qmail) Monolithic configuration file Emphasis on security, but not to the extent of imposing unusual Unix management practices. a drop-in replacement for Sendmail
41
Postfix security uLeast privilege No component is set-uid. [A single component, postdrop is set-gid] uDefense in depth uses multiple layers of defense to protect the local system against intruders. Almost every Postfix daemon can run in a chroot jail with fixed low privileges. There is no direct path from the network to the security-sensitive local delivery programs - an intruder has to break through several other programs first. uMinimize trust Does not even trust the contents of its own queue files, or the contents of its own IPC messages. Filters sender-provided information before exporting it via environment variables.
42
Additional reading uContents Contemporary security –Need for secure systems, proactive security process Secure Coding Techniques –The buffer overrun –Determining appropriate access control –Running with least privilege –Protecting secret data –All input is evil – …. More Secure Coding techniques Special Topics –Testing, code review, secure installation, privacy
43
Methods for producing secure code uC vs type safe languages Buffer overflows are array bounds violations Java, C#, Caml, … check array bounds, uPerl tainting Language analysis to track use of untrusted input uAutomated analysis tools for C code Can catch many kinds of errors Can have many false alarms unless tool output is designed carefully
44
Example Software tools uCoverity Based on Dawson Engler’s research on source code analysis supports user-defined properties in the Metal language. uPolySpace French company co-founded by students of Patrick Cousot Customers in airline industry and the European space program. Does not support full ANSI-C language (e.g., restrictions on use of gotos). uPurify (Rational) Tool for detection of memory leaks uLint family, e.g. PC-Lint/FlexeLint (Gimpel), Lint Plus (Cleanscape) Generic source code analysis, value tracking, some types of array indexing errors. uPREfix and PREfast (Microsoft) PREfix developed by Jon Pincus, acquired by MS PREfast developed within Microsoft, faster alternative to PREfix uCCured, CQual Research variants of C with better type safety
45
Purify uGoal Instrument a program to detect run-time memory errors (out-of-bounds, use-before-init) and memory leaks uTechnique Works on relocatable object code –Link to modified malloc that provides tracking tables –Tracks heap locations only Memory access errors: insert instruction sequence before each load and store instruction Memory leaks: GC algorithm
46
Static Analysis Tools uVerify property for all possible executions (and then some) Complements run-time checking Static analyses exist for only a few properties uChoose at most one: Sound: analysis finds all instances of error Complete: analysis reports no false errors Can’t have both: halting prob Don’t need either: heuristics complete sound run timecompile time [Larus ASPLOS]
47
Perl tainting uRun-time checking of Perl code Perl used for CGI scripts, security sensitive Taint checking stops some potentially unsafe calls uTainted strings User input, Values derived from user input Except result of matching against untainted string uProhibited calls print $form_data{"email"}. "\n"; –OK since print is safe (???) system("mail ". $form_data{"email"}); –Flagged system call with user input as argument
48
Safe Perl mail command (?) uCheck email string against pattern and parse $email = $form_data{"email"}; if ( $email =~ /(\w{1}[\w-.]*)\@([\w-.]+)/) { $email = "$1\@$2"; } else { warn ("TAINTED DATA SENT BY …"); $email = ""; # successful match did not occur } uWhat does this accomplish? Only send email to address that “looks good” Programmer responsible for “good” pattern Perl cannot guarantee that email addr is OK
49
Microsoft Tools uPREfix detailed, path-by-path interprocedural analysis heuristic (unsound, incomplete) expensive (4 days on Windows) primarily language usage defects uPREfast simple plug-ins find defects by examining functions’ ASTs desktop use easily customized uWidely deployed in Microsoft 1/8 of defects fixed in Windows Server 2003 found by these tools [Larus ASPLOS]
50
Automated security analysis for C uExample tool Ken Ashcraft and Dawson Engler, Using Programmer-Written Compiler Extensions to Catch Security Holes, IEEE Security and Privacy 2002 Used modified compiler to find over 100 security holes in Linux and BSD http://www.stanford.edu/~engler/ uBenefit Capture recommended practices, known to experts, in tool available to all
51
Checking secure software uMany rules for writing secure code “sanitize user input before using it” “check permissions before doing operation X” uHow to find errors? Formal verification + rigorous – costly, expensive. *Very* rare to do for software Testing: + simple, few false positives – requires running code: doesn’t scale & can be impractical Manual inspection + flexible – erratic & doesn’t scale well. What to do??
52
Metacompilation (MC) uAnalyze compiler data structure to check code Extensions dynamically linked into GNU gcc compiler Applied down all paths in input program source E.g., extension to check user input copy_from_user(&frame) se401_newfram(…, frame) se401->frame[frame] =… return ret; Linux 2.4.5: drivers/ usb/ see401.c GNU compiler “unsafe use of frame!” checker Actual error in Linux: raid5 driver disables interrupts, and then if it fails to allocate buffer, returns with them disabled. This kernel deadlock is actually hidden by an immediate segmentation fault since the callers dereference the pointer without checking for NULL
53
Sanitize integers before use Linux: 125 errors, 24 false; BSD: 12 errors, 4 false array[v] while(i < v) … v.clean Use(v) v.tainted Syscall param Network packet copyin(&v, p, len) any<= v <= any memcpy(p, q, v) copyin(p,q,v) copyout(p,q,v) ERROR Warn when unchecked integers from untrusted sources reach trusting sinks
54
Example security holes /* 2.4.9/drivers/isdn/act2000/capi.c:actcapi_dispatch */ isdn_ctrl cmd;... while ((skb = skb_dequeue(&card->rcvq))) { msg = skb->data;... memcpy(cmd.parm.setup.phone, msg->msg.connect_ind.addr.num, msg->msg.connect_ind.addr.len - 1); uRemote exploit, no checks
55
Example security holes /* 2.4.5/drivers/char/drm/i810_dma.c */ if(copy_from_user(&d, arg, sizeof(arg))) return –EFAULT; if(d.idx > dma->buf_count) return –EINVAL; buf = dma->buflist[d.idx]; Copy_from_user(buf_priv->virtual, d.address, d.used); uMissed lower-bound check:
56
User-pointer inference uProblem: which are the user pointers? Hard to determine by dataflow analysis Easy to tell if kernel believes pointer is from user! uBelief inference “*p” implies safe kernel pointer “copyin(p)/copyout(p)” implies dangerous user ptr Error: pointer p has both beliefs. uImplementation: 2 pass checker inter-procedural: compute all tainted pointers local pass to check that they are not dereferenced
57
Results for BSD and Linux uAll bugs released to implementers; most serious fixed Gain control of system 18 15 3 3 Corrupt memory 43 17 2 2 Read arbitrary memory 19 14 7 7 Denial of service 17 5 0 0 Minor 28 1 0 0 Total 125 52 12 12 Linux BSD Violation Bug Fixed Bug Fixed
58
Local bugs 109 12 Global bugs 16 0 Bugs from inferred ints 12 0 False positives 24 4 Number of checks ~3500 594 Linux BSD
59
Conclusions uSecurity takes extra effort Know your security goals Design with security in mind –Compartmentalize, least privilege –Minimize setuid, root Implement carefully –Keep it simple –Think about attacks; secure the weakest link Use tools that detect common coding problems –There are also tools that can analyze designs, but that’s another story (harder to use, current research)
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.