1 / 58

Language-based security

CS 242. Language-based security. John Mitchell. Security goals. Confidentiality Information accessible only as intended Integrity Data and system operation are not corrupted Availability System remains operable and performs when needed Assurance

gusty
Download Presentation

Language-based security

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CS 242 Language-based security John Mitchell

  2. Security goals • Confidentiality • Information accessible only as intended • Integrity • Data and system operation are not corrupted • Availability • System remains operable and performs when needed • Assurance • We have some way of knowing which of these properties we have, with some degree of confidence

  3. Solution concepts • Isolation • Separate program modules have separate local memory • Modules communicate only through specified interfaces • Access control • Specify rights for each program module • Only allow behavior that is given by these rights • Create or access a file? • Create or read/write to socket? • Make a specific system call? • Principle of least privilege • Give each module only the rights it needs

  4. Least Privilege: Mail Transport Agents • Sendmail • Complicated system • Source of many vulnerabilities • Qmail • 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

  5. Simplified Mail Transactions Mail User Agent Mail Transport Agent Mail Transport Agent Mail User Agent Mail Delivery Agent Mail Delivery Agent mbox mbox • Message composed using an MUA • MUA gives message to MTA for delivery • If local, the MTA gives it to the local MDA • If remote, transfer to another MTA

  6. Qmail Security • Least 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 • Other secure coding ideas

  7. qmailq – user who is allowed to read/write mail queue Least Privilege and UIDs qmaild user qmail-smtpd qmail-inject qmailq qmail-queue setuid Other incoming mail Incoming SMTP mail qmail-send qmailr qmails root qmail-rspawn qmail-lspawn root setuid user qmailr user qmail-remote qmail-local

  8. Two access control concepts • Access control list (ACL) • Store column of matrix with the resource • Capability • User holds a “ticket” for each resource • Two variations • store row of matrix with user, under OS or runtime sys control • unforgeable ticket in user space Access control lists are widely used in OS, often with groups Some aspects of capability concept are used in Kerberos, …

  9. ACL vs Capabilities Process P User U Process P Capabilty c,d Process Q User U Process Q Capabilty c Process R User U Process R Capabilty c

  10. ACL vs Capabilities • Delegation • Cap: Process can pass capability at run time • ACL: Try to get owner to add permission to list • Revocation • ACL: Remove user or group from list • Cap: Try to get capability back from process? • Possible in some systems if appropriate bookkeeping • OS knows what data is capability • If capability is used for multiple resources, have to revoke all or none … • Other details …

  11. Programming language security • Meaningful trust distinctions • Confused deputy problem – trusted code does work for untrusted malicious agent (examples next slide) • Finer-grained policies • Program reads/writes files A and B, but does not write confidential information from A to B • Extensible operating systems • Enforce application-level security in applications • Don’t run dangerous applet instructions in browser • Don’t run dangerous Word macro in downloaded file

  12. Confused Deputy • KeyKOS story • Compiler writes errors into user-designated log file • User can’t change accounting file, but compiler can • User designates accounting file as compiler log file • Reference: Norm Hardy , The Confused Deputy (…) • Early Netscape problem • Applet asks font manager for “password file” font • Font manager can’t find it so asks system registry • System registry trusts font manager, so turns it over • Font manager gives password file to applet

  13. Buffer Overflow Attack • Most prevalent security problem today • Approximately 80% of CERT advisories are related to buffer overflow vulnerabilities in OS, other code • General network-based attack • Attacker sends carefully designed network msgs • Input causes privileged program (e.g., Sendmail) to do something it was not designed to do • Does not work in Java • Illustrates what Java was designed to prevent

  14. void f (char *str) { char buffer[16]; … strcpy(buffer,str); } void main() { char large_string[256]; int i; for( i = 0; i < 255; i++) large_string[i] = 'A'; f(large_string); } Function Copies str into buffer until null character found Could write past end of buffer, over function retun addr Calling program Writes 'A' over f activation record Function f “returns” to location 0x4141414141 This causes segmentation fault Variations Put meaningful address in string Put code in string and jump to it !! Sample C code to illustrate attack See: Smashing the stack for fun and profit

  15. Language-based security • Topics • Java sandbox model • E language • capability model in Java (see Hawblitzel et al) • CLR methods • Code analysis and monitoring • Typed assembly language, PCC • Static tools • SFI, code rewriting • Information flow properties - JIF

  16. Java Security Mechanisms • Sandboxing • Run program in restricted environment • Analogy: child’s sandbox with only safe toys • This term refers to • Features of loader, verifier, interpreter that restrict program • Java Security Manager, a special object that acts as access control “gatekeeper” • Code signing • Use cryptography to establish origin of class file • This info can be used by security manager

  17. JVM sandbox local code remote code (applets) resources The Java 1.0 sandbox • Local code subject to Java language restrictions only • Downloaded code (applet) further restricted to sandbox • cannot access the local file system • cannot access system resources, • can establish network connection only to originating web server

  18. JVM local code sandbox signed and trusted remote code (applets) unsigned, or signed and untrusted resources Java 1.1 trusted code • Trust code from trusted sources • Local file system • Signed by trusted principal

  19. class loaders Java 2 Finer grained access control • All access to system resources based on policy file • Protection domain: code source and permissions granted • Code source consists of a URL and an optional signature • Permissions granted in policy file grant CodeBase “http://java.sun.com”, SignedBy “Sun” { permission java.io.FilePermission “${user.home}${/}*”, “read, write”; permission java.net.SocketPermission “localhost:1024-”, “listen”;}; JVM local or remote code (signed or unsigned) policy file resources

  20. Java security mechanisms • Four complementary mechanisms • Class loader • Separate namespaces for separate class loaders • Associates protection domain with each class • Verifier and JVM run-time tests • NO unchecked casts or other type errors, NO array overflow • Preserves private, protected visibility levels • Security Manager • Called by library functions to decide if request is allowed • Uses protection domain associated with code, user policy

  21. Security Manager • Java library functions call security manager when they are invoked at runtime • For example, checkRead(String filename) • checkRead method is defined by SecurityManager class • Method throws exception if operation is not allowed • Security manager uses the system policy to decide whether calling code is allowed to do operation • Examines protection domain of calling class • Signer: organization that signed code before loading • Location: URL where the calling class came from

  22. Sample SecurityManager Methods

  23. Creating a Security Policy • Create your own subclass of SecurityManager and instantiate • Redefine checkRead, checkWrite, etc. methods to enforce your policy • Install using System.setSecurityManager • setSecurityManager cannot be revoked or replaced • If no SecurityManager installed, all privileges are granted to any applet

  24. Sample Security Policy CodeSource Permissions Base URL Signature http://www.schwab.com/ Read/write file · Schwab’s signature /home/ jcm/stocks classes/ stockeditor.jar Connect/accept · http://*.schwab.com/ (not required) bankofamerica.com ports 1-1023 Read file · /home/ jcm/ logo.png

  25. Installing Security Manager • JVM allows only one SM to be active at a time • Default SM provided by the JDK • Java programs can replace the default SM if they have permission • Two permissions are needed • create an instance of SecurityManager • set an SM instance as active • Example grant CodeBase “…”, SignedBy “…” { permission java.lang.RuntimePermission “createSecurityManager”; permission java.lang.RuntimePermission “setSecurityManager”;};

  26. Recall: typing as a security foundation • Sandbox mechanisms all rely on type safety • Example • Unchecked C cast lets code make any system call int (*fp)() /* variable "fp" is a function pointer */ ... fp = addr; /* assign address stored in an integer var */ (*fp)(n); /* call the function at this address */ Other examples involving type confusion in book

  27. Stack Inspection • Permission depends on • Permission of calling method • Permission of all methods above it on stack • Up to method that is trusted and asserts this trust Many details omitted here method f method g method h java.io.FileInputStream • Stories: Netscape font / passwd bug; Shockwave plug-in

  28. Beyond JVM security • JVM does not prevent • Denial of service attacks • Applet creates large windows and ignores mouse • Certain network behavior • Applet can connect to port 25 on client machine, forge email (on some implementations) • URL spoofing • Applet can write false URL on browser status line • Annoying behavior • Applet can play loud sound • Applet can reload pages in new windows

  29. E: Electric Communities • Electronic communities • Planned network of interacting virtual realities • Example: automated garden (in Netherlands?) with watering can • E programming language • Distributed communication • An object may send messages directly to objects that exist in other machines • Capability system • Goal: detailed control over sensitive functions within a single machine or across a network • Optimistic computation • Reduces the effect of communications latency in distributed systems

  30. Java capability example • Give untrusted object read access to a file • Pass the name of the file • Pass the File object • Pass a ReadStream on the File object • Problem • Given Java ReadStream, can request the File object of the ReadStream, then access file, directory structure, etc. • E approach • Capabilities are granted to E objects at load time. • A cryptographic signature and a set of capability requirements are attached to every E object See Amoeba OS papers for good description of capability system

  31. .NET Code Access Security • Default Security Policy is part of the .NET Framework • Default permission for code access to protected resources • Permissions can limit access to system resources. • Use EnvironmentPermission class for environment variables access permission. • The constructor defines the level of permission (read, write,…) • Deny and Revert • The Deny method of the permission class denies access to the associated resource • The RevertDeny method will cause the effects of any previous Deny to be cancelled

  32. DBDataPermission PrintingPermission DnsPermission SocketPermission WebPermission UIPermission SecurityPermission RegistryPermission FileIOPermission PrincipalPermission MessageQueuePermission EnvironmentPermission FileDialogPermission IsolatedStoragePermission ReflectionPermission PublisherIdentityPermission StrongNameIdentityPermission ZoneIdentityPermission SiteIdentityPermission UrlIdentityPermission Built-in Permission Classes

  33. Example: code requires permission 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(); }

  34. Example: Code denies permission not needed [SecurityPermission(SecurityAction.Deny, Flags = SecurityPermissionFlag.UnmanagedCode)] private static void MethodToDoSomething() { try { Console.WriteLine(“ … "); SomeOtherClass.method(); } catch (SecurityException) { … } }

  35. calls calls .NET Stackwalk • Demand must be satisfied by all callers • Ensures all code in causal chain is authorized • Cannot exploit other code with more privilege A has P? Code A B has P? Code B Code C Demand P

  36. Stackwalk: Assert • The Assert method can be used to limit the scope of the stack walk • Processing overhead decreased • May inadvertently result in weakened security CAUTION   Use assertions carefully because they can open security holes and undermine the runtime's mechanism for enforcing security restrictions.

  37. Methods for producing secure code • C vs type safe languages • Buffer overflows are array bounds violations • Java, C#, Caml, … check array bounds, • Perl tainting • Language analysis to track use of untrusted input • Automated analysis tools for C code • Can catch many kinds of errors • Can have many false alarms unless tool output is designed carefully

  38. Example Software tools • Coverity • Based on Dawson Engler’s research on source code analysis • supports user-defined properties in the Metal language. • PolySpace • 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). • Purify (Rational) • Tool for detection of memory leaks • Lint family, e.g. PC-Lint/FlexeLint (Gimpel), Lint Plus (Cleanscape) • Generic source code analysis, value tracking, some types of array indexing errors. • PREfix and PREfast (Microsoft) • PREfix developed by Jon Pincus, acquired by MS • PREfast developed within Microsoft, faster alternative to PREfix • CCured, CQual • Research variants of C with better type safety

  39. Purify • Goal • Instrument a program to detect run-time memory errors (out-of-bounds, use-before-init) and memory leaks • Technique • 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

  40. Static Analysis Tools • Verify property for all possible executions (and then some) • Complements run-time checking • Static analyses exist for only a few properties • Choose 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 sound run time compile time complete [Larus ASPLOS]

  41. Perl tainting • Run-time checking of Perl code • Perl used for CGI scripts, security sensitive • Taint checking stops some potentially unsafe calls • Tainted strings • User input, Values derived from user input • Except result of matching against untainted string • Prohibited calls • print $form_data{"email"} . "\n"; • OK since print is safe (???) • system("mail " . $form_data{"email"}); • Flagged system call with user input as argument

  42. Safe Perl mail command (?) • Check 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 } • What does this accomplish? • Only send email to address that “looks good” • Programmer responsible for “good” pattern • Perl cannot guarantee that email addr is OK

  43. Microsoft Tools • PREfix • detailed, path-by-path interprocedural analysis • heuristic (unsound, incomplete) • expensive (4 days on Windows) • primarily language usage defects • PREfast • simple plug-ins find defects by examining functions’ ASTs • desktop use • easily customized • Widely deployed in Microsoft • 1/8 of defects fixed in Windows Server 2003 found by these tools [Larus ASPLOS]

  44. Automated security analysis for C • Example 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/ • Benefit • Capture recommended practices, known to experts, in tool available to all

  45. Checking secure software • Many rules for writing secure code • “sanitize user input before using it” • “check permissions before doing operation X” • How 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??

  46. Metacompilation (MC) • Analyze 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 GNU compiler Linux 2.4.5: drivers/ usb/ see401.c copy_from_user(&frame) se401_newfram(…, frame) se401->frame[frame] =… return ret; “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

  47. Sanitize integers before use Warn when unchecked integers from untrusted sources reach trusting sinks Linux: 125 errors, 24 false; BSD: 12 errors, 4 false Network packet copyin(&v, p, len) Syscall param any<= v <= any v.tainted v.clean Use(v) memcpy(p, q, v) copyin(p,q,v) copyout(p,q,v) array[v] while(i < v) … ERROR

  48. Example security holes • Remote exploit, no checks /* 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);

  49. Example security holes • Missed lower-bound check: /* 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);

  50. User-pointer inference • Problem: which are the user pointers? • Hard to determine by dataflow analysis • Easy to tell if kernel believes pointer is from user! • Belief inference • “*p” implies safe kernel pointer • “copyin(p)/copyout(p)” implies dangerous user ptr • Error: pointer p has both beliefs. • Implementation: 2 pass checker inter-procedural: compute all tainted pointers local pass to check that they are not dereferenced

More Related