home *** CD-ROM | disk | FTP | other *** search
/ ftp.pasteur.org/FAQ/ / ftp-pasteur-org-FAQ.zip / FAQ / unix-faq / programmer / secure-programming < prev   
Encoding:
Internet Message Format  |  2001-11-13  |  85.7 KB

  1. Path: senator-bedfellow.mit.edu!dreaderd!not-for-mail
  2. Message-ID: <unix-faq/programmer/secure-programming_1005562532@rtfm.mit.edu>
  3. Supersedes: <unix-faq/programmer/secure-programming_1004179515@rtfm.mit.edu>
  4. Expires: 11 Dec 2001 10:55:32 GMT
  5. X-Last-Updated: 1999/05/17
  6. Organization: none
  7. From: shadows@whitefang.com (Thamer Al-Herbish)
  8. Newsgroups: comp.security.unix,comp.answers,news.answers
  9. Subject: Secure UNIX Programming FAQ
  10. Reply-To: shadows@whitefang.com
  11. Followup-To: poster
  12. Approved: news-answers-request@MIT.EDU
  13. Originator: faqserv@penguin-lust.MIT.EDU
  14. Date: 12 Nov 2001 10:57:20 GMT
  15. Lines: 1721
  16. NNTP-Posting-Host: penguin-lust.mit.edu
  17. X-Trace: 1005562640 senator-bedfellow.mit.edu 3931 18.181.0.29
  18. Xref: senator-bedfellow.mit.edu comp.security.unix:71603 comp.answers:47791 news.answers:218886
  19.  
  20. Archive-name: unix-faq/programmer/secure-programming
  21. Posting-Frequency: Every 15 days.
  22. URL: http://www.whitefang.com/sup/
  23.  
  24.                  Secure UNIX Programming FAQ 
  25.                  --------------------------- 
  26.  
  27.   Version 0.5 
  28.  
  29.   Sun May 16 21:31:40 PDT 1999 
  30.  
  31.   The master copy of this FAQ is currently kept at 
  32.  
  33.   http://www.whitefang.com/sup/ 
  34.  
  35.   The webpage has a more spiffy version of the FAQ in html. 
  36.  
  37.   This FAQ is also posted to comp.security.unix (c.s.u) , 
  38.   comp.answers , news.answers. 
  39.  
  40.   Please do not mirror this FAQ without prior permission. Due to the 
  41.   high volume of readers I'm worried that old versions of the FAQ are 
  42.   left to grow stale, consequently receive email based on fixed 
  43.   errors/omissions. 
  44.  
  45. Additional Resources 
  46. -------------------- 
  47.  
  48. After receiving many comments, and suggestions I decided to make some 
  49. more SUP FAQ related resources available. 
  50.  
  51.   A change log can be found at: 
  52.   http://www.whitefang.com/sup/sec-changes.txt 
  53.  
  54.   A moderated mailing list has been setup for the discussion of 
  55.   Secure UNIX programming. You can find a copy of the announcement 
  56.   at: 
  57.  
  58.   http://www.whitefang.com/sup/announcement.txt 
  59.  
  60.   I'm currently working on a terse reference guide. It will be made 
  61.   available Real Soon Now in PostScript format. The reference can be 
  62.   printed out and kept handy next to your can of cola. It contains, 
  63.   tables, diagrams, and step by step instructions for various 
  64.   operations mentioned in the FAQ. It will not be posted to Usenet, 
  65.   and downloadable from the FAQ's website. Its "Real Soon Now" status 
  66.   is very Real Soon Now. 
  67.  
  68. Copyright 
  69. --------- 
  70.  
  71. I, Thamer Al-Herbish reserve a collective copyright on this FAQ. 
  72. Individual contributions made to this FAQ are the intellectual 
  73. property of the contributor. 
  74.  
  75. I am responsible for the validity of all information found in this 
  76. FAQ. 
  77.  
  78. This FAQ may contain errors, or inaccurate material. Use it at your 
  79. own risk. Although an effort is made to keep all the material 
  80. presented here accurate, the contributors and maintainer of this FAQ 
  81. will not be held responsible for any damage -- direct or indirect -- 
  82. which may result from inaccuracies. 
  83.  
  84. You may redistribute this document as long as you keep it in its 
  85. current form, without any modifications. Read -- keep it up to date 
  86. please!! :-) 
  87.  
  88. Introduction 
  89. ------------ 
  90.  
  91. This FAQ answers questions about secure programming in the UNIX 
  92. environment. It is a guide for programmers and not administrators. 
  93. Keep this in mind because I do not tackle any administrative issues. 
  94. Try to read it as a guide if possible. I'm sorry it sounds like a bad 
  95. day on jeopardy. 
  96.  
  97. At the risk of sounding too philosophical, this FAQ is also a call to 
  98. arms. Over almost the last decade, a good six years, a movement took 
  99. place where security advisories would hit mailing lists and other 
  100. forums at astonishing speed. I think the veterans are all to familiar 
  101. with the repetitive nature of these security advisories, and the 
  102. small amount of literature that has been published to help avoid 
  103. insecure programming. This text is a condensation of this movement 
  104. and a contribution made to it, placed in a technical context to 
  105. better serve the UNIX security community. As the Usenet phrase goes: 
  106. "Hope this helps." 
  107.  
  108. Additions and Contributions 
  109. --------------------------- 
  110.  
  111. The current FAQ is not complete. I will continue to work on it as I 
  112. find time. Feel free to send in material for the Todo sections, and 
  113. for the small notes I've left around. Also, compatibility is an issue 
  114. I struggle with sometimes. The best I can do for some UNIX flavors is 
  115. read man pages. Corrections/addendums for compatibility notes is 
  116. greatly appreciated, and easily done as a collective effort. All 
  117. contributions, comments, and criticisms can be sent to: 
  118.  
  119. Secure UNIX Programming FAQ <sup@whitefang.com> 
  120.  
  121. Please don't send them to my personal mailbox, because I can keep 
  122. things organized better with the above e-mail address. Also please 
  123. try to be as concise as possible. Remember I will usually quote you 
  124. directly if you have something to add. 
  125.  
  126. Finally, although the contributors list is currently short, the 
  127. material in this FAQ did not pop out of my head in a pig-flying 
  128. fashion. Attribution is given where applicable. If you feel any of 
  129. this is unfair to something you have published, do let me know. The 
  130. bibliography is found at the end. 
  131.  
  132. Special thanks to John W. Temples, Darius Bacon, Brian Spilsbury, 
  133. Elias Levy, who had looked at some of the drafts of past material 
  134. that made it into this FAQ. As usual, all mistakes are mine and only 
  135. mine. 
  136.  
  137. Also kudos to the people at netspace.org for hosting Bugtraq all 
  138. these years. The archive is invaluable to my research. 
  139.  
  140. Table of Contents 
  141. ----------------- 
  142.  
  143.   1) General Questions: 
  144.     1.1) What is a secure program? 
  145.     1.2) What is a security hole? 
  146.     1.3) How do I find security holes? 
  147.     1.4) What types of attacks exist? 
  148.     1.5) How do I fix a security hole? 
  149.  
  150.   2) The Flow Of Information: 
  151.     2.1) What is the flow of information? 
  152.     2.2) What is trust? 
  153.     2.3) What is validation? 
  154.  
  155.   3) Privileges and Credentials 
  156.     3.1) What is a privilege and a credential? 
  157.     3.2) What is the least privilege principle? 
  158.     3.3) How do I apply the least privilege principle safely? 
  159.  
  160.   4) Local Process Interaction: 
  161.     4.1) What is process attribute inheritance? Or why should I not 
  162.     write SUID programs? 
  163.     4.2) How can I limit access to a SUID/SGID process-image safely? 
  164.     4.3) How do I authenticate a parent process? 
  165.     4.4) How do I authenticate a non-parent process? 
  166.  
  167.   5) Accessing The File System Securely: 
  168.     5.1) How do I avoid race condition attacks? 
  169.     5.2) How do I create/open files safely? 
  170.     5.3) How do I delete files safely? 
  171.     5.4) Is chroot() safe? 
  172.  
  173.   6) Handling Input: 
  174.     6.1) What is a "buffer overrun/overflow attack" and how do I 
  175.     avoid it? 
  176.     6.2) How do I hand integer values safely? 
  177.     6.3) How do I safely pass input to an external program? 
  178.  
  179.   7) Handling Resources Limits: [ Todo ] 
  180.   8) Bibliography 
  181.   9) List of Contributors 
  182.  
  183.     1) General Questions 
  184.     -------------------- 
  185.  
  186.       1.1) What is a secure program? 
  187.       ------------------------------ 
  188.  
  189.       The simplest definition would be : a program that is capable of 
  190.       performing its task withstanding any attempts to subvert it. 
  191.       This extends to the attribute of "robustness." Most importantly 
  192.       the program should be able to perform its task without 
  193.       jeopardizing the security policies of the system it is running 
  194.       on. This is done by making sure it adheres to local security 
  195.       policies at all times. To draw an analogy, a locksmith will 
  196.       install a lock, and the home owner will decide whether or not 
  197.       he will lock the door at any given time. It is the lock smith's 
  198.       responsibility to make sure the lock performs its function of 
  199.       keeping an intruder out. It is just as much the responsibility 
  200.       of the programmer to make sure the program adheres to the local 
  201.       security policies. Thus returning to the introduction, this FAQ 
  202.       is about the programmer's responsibilities and not the 
  203.       administrator. 
  204.  
  205.       The problem with that analogy is that when it is translated 
  206.       back into UNIX terms one thinks of an authentication program. 
  207.       By all means 'login' needs to be secure, but so do all the 
  208.       system components. To quote the U.S. Department of Defense 
  209.       Trusted Computer System Evaluation Criteria (a.k.a The Orange 
  210.       Book): 
  211.  
  212.       "No computer system can be considered truly secure if the basic 
  213.       hardware and software mechanisms that enforce the security 
  214.       policy are themselves subject to unauthorized modification or 
  215.       subversion." 
  216.  
  217.       Unfortunately this doesn't really help because we are sadly 
  218.       left thinking of firewalls, access control lists, persistent 
  219.       authentication systems etc. and we miss out on the other system 
  220.       components that must also be considered. So the quote can be 
  221.       re-written as such: 
  222.  
  223.       "No computer system can be considered truly secure if the basic 
  224.       hardware and software mechanisms that _can affect_ the security 
  225.       policies are themselves subject to unauthorized modification or 
  226.       subversion." 
  227.  
  228.       This gives us a much better view of what a secure program is, 
  229.       and places a distinction between a secure program and a 
  230.       security program. The security program enforces security 
  231.       policies; however, the secure program does not enforce any 
  232.       policies but must also co-exist with the security policies. 
  233.       This allows a much broader view of every program on the system. 
  234.       All the applications, and all the servers, and all the clients 
  235.       must be implemented securely. Granted that this approach is a 
  236.       bit extremist, it is actually quite reasonable. Programming 
  237.       securely should always be done as will be seen by some of the 
  238.       points brought up in this FAQ. 
  239.  
  240.       Finally, to finish this definition, consider a Mail User Agent 
  241.       (MUA), such a 'pine' or 'elm.' Both have to be written securely 
  242.       because they can affect the security policies if they were not. 
  243.       In light of an advisory posted to Bugtraq (Zalewski 1999), pine 
  244.       was reported to have a security hole. Even though it is not 
  245.       enforcing security policies it still failed to adhere to them. 
  246.  
  247.       1.2) What is a security hole? 
  248.       ----------------------------- 
  249.  
  250.       The term is somewhat colloquial but it has been used in 
  251.       technical context enough times to warrant common usage in 
  252.       security advisories. It just means the program has a flaw that 
  253.       allows an attacker to "exploit it." Thus comes the "exploit" 
  254.       that denotes a program, or technique to take advantage of the 
  255.       flaw, or "vulnerability." The terms mentioned here will be 
  256.       found in many advisories, and in this FAQ so familiarity with 
  257.       them is essential. 
  258.  
  259.       1.3) How do I find security holes? 
  260.       ---------------------------------- 
  261.  
  262.       Careful auditing of source code is usually the way. One way of 
  263.       doing it is going through this FAQ in its treatment toward 
  264.       specific security holes and attempt to find them throughout the 
  265.       code in question. I will attempt to give tips toward finding a 
  266.       said security hole where applicable. 
  267.  
  268.       However, if you really really need to find that security hole, 
  269.       disassemble the binary image of the program, grok the asm 
  270.       output into your head, run it slowly but carefully keeping 
  271.       track of registers, stacks etc -- and yes grasshopper, that is 
  272.       the One True Way. 
  273.  
  274.       1.4) What types of attacks exist? 
  275.       --------------------------------- 
  276.  
  277.       There are three main types of attacks (Saltzer 1975): 
  278.  
  279.           Unauthorized release of privileged information. 
  280.  
  281.           Unauthorized modification of privileged information. 
  282.  
  283.           Denial of service. 
  284.  
  285.       The word unauthorized speaks for itself. If information can be 
  286.       read, or modified when it should not have been, security has 
  287.       been breached. A denial of service attack is any attack that 
  288.       stops a program from performing its function. When considering 
  289.       whether a program is secure from its design, provisions for 
  290.       these three attacks need to be accounted for. 
  291.  
  292.       Obviously these attacks are aggregates of the more specific 
  293.       ones that exploit security holes. But that should give you an 
  294.       idea of what you're looking out for. 
  295.  
  296.       1.5) How do I fix a security hole? 
  297.       ---------------------------------- 
  298.  
  299.       Traditionally there are three approaches to fixing a security 
  300.       hole. At the risk of going slightly off topic, let us go back 
  301.       to the heyday of the SYN flood attack (daemon9 1997). 
  302.  
  303.       SYN flooding is when a host sends out a large number of TCP/IP 
  304.       packets with an unreachable source address, and a TCP flag of 
  305.       SYN. The receiving host responds and awaits for the SYN-ACK to 
  306.       complete the three-way handshake. Since the source address is 
  307.       unreachable the receiving host never receives a response to 
  308.       complete the handshake. Instead it is left in a "half open" 
  309.       state till it times out. The problem is that there is a finite 
  310.       number of "slots" per connection received on the listening 
  311.       socket. This is because the host needs to store information in 
  312.       order to recognize the last part of the TCP three-way 
  313.       handshake. This results in a denial of service where the 
  314.       receiving host would simply stop accepting new connections till 
  315.       the bogus half-open connections timed out. They are called 
  316.       half-open connections because the handshake is never completed. 
  317.  
  318.       Interestingly enough several different approaches were used to 
  319.       solve this problem: 
  320.  
  321.       Cisco Systems Inc., implemented a TCP Intercept feature on its 
  322.       routers. The router would act as a transparent TCP proxy 
  323.       between the real server, and the client. When a connection 
  324.       request was made from the client, the router would complete the 
  325.       handshake for the server, and open the real connection only 
  326.       after the handshake has completed. This allowed the router to 
  327.       impose a very aggressive strategy for accepting new 
  328.       connections. It would place a threshold on the amount of 
  329.       connection requests it would handle: If the amount of half-open 
  330.       connections exceeded the threshold it would lower the timeout 
  331.       period interval, thus dropping the half-open connections 
  332.       faster. The real servers were completely shielded while the 
  333.       routers took the brunt and handled it aggressively. 
  334.  
  335.       The OpenBSD developers implemented a work-around that caused 
  336.       old half-open TCP connections to be randomly dropped when new 
  337.       connection requests arrived on a full backlog. This allowed new 
  338.       connections to be established even with a constant SYN-flood 
  339.       taking place. The old bogus connections would be dropped at the 
  340.       behest of a new connection, legitimate or not. The randomness 
  341.       was implemented to be fair to all incoming connections. 
  342.       Although arguably with a large enough flood this technique may 
  343.       fail, it did have good results as tested by the developers. 
  344.  
  345.       Dan Bernstein (Bernstein 1996; Schenk 1996) proposed SYN 
  346.       cookies, which would eliminate the need to store information 
  347.       per half open connection. When a connection is initiated, the 
  348.       server generates a cookie with the initial TCP packet 
  349.       information. The server would then respond with the cookie. 
  350.       When the client responded with a SYN-ACK to complete the 
  351.       handshake, the server would redo the hash, this time with the 
  352.       information taken from the recent SYN-ACK packet. This would of 
  353.       course entail decrementing the sequence numbers since they have 
  354.       been incremented in the client response. If the new hash 
  355.       matched that of the returned sequence numbers, the server would 
  356.       have completed the three-way handshake. Only the secret was 
  357.       stored, the rest of the information is gathered from the 
  358.       incoming packets during the handshake. This meant only one 
  359.       datum for all incoming connections. Thus an infinite amount of 
  360.       half open connections could exist. 
  361.  
  362.       Three different methods were used. Cisco used a "wrapper." The 
  363.       actual UNIX system was completely unconcerned with what the 
  364.       router did and required no modification. This is good for a 
  365.       scalable solution, but does not remove the problem entirely. 
  366.       The wrapper just acts as a canvas. 
  367.  
  368.       The OpenBSD solution was to fix the problem in the 
  369.       implementation itself. This is usually the case with most 
  370.       security holes, especially the less complicated ones. 
  371.  
  372.       The solution presented by Dan Bernstein was more of a design 
  373.       change. The system's responses were changed, but remained 
  374.       reasonably well in conformance with the TCP standard. Some 
  375.       compromises were made however (see Schenk 1996). 
  376.  
  377.       There is no one True Way of fixing security holes. Approach the 
  378.       problem first in the code, then design, and finally by wrapping 
  379.       it if you really must. 
  380.  
  381.     2) The Flow Of Information 
  382.     -------------------------- 
  383.  
  384.   Although what is presented here is a bit cross platform and not 
  385.   UNIX dependent, it is so essential that I had to put it in its own 
  386.   section. 
  387.  
  388.       2.1) What is the flow of information? 
  389.       ------------------------------------- 
  390.  
  391.       Every program can be considered to follow a simple design: it 
  392.       accepts input, processes it, and produces output. Input may 
  393.       come from the keyboard, a file, or the network. As long as it 
  394.       is gained from an external source that is not part of the 
  395.       program, it is considered input. Output is not necessarily 
  396.       information printed on the screen, or in a log file, it may be 
  397.       an affect like the creation of a file. The processing may be 
  398.       any work from simple arithmetic, to parsing strings. 
  399.       Mathematically speaking, at least, your program should really 
  400.       be a function taking variables and producing results. This 
  401.       cycle may happen more than once during a program's lifetime. 
  402.  
  403.       Most programmers, for purposes of keeping things simple, will 
  404.       make assumptions about input. Particularly its format, and 
  405.       whether to apply sanity checks. There are probably entire books 
  406.       on doing this correctly: designing your program correctly, 
  407.       picking the right data formats and so on. This FAQ isn't 
  408.       interested in that aspect of processing information. Instead it 
  409.       is interested in three things: trust, validation, and acting on 
  410.       input. 
  411.  
  412.       2.2) What is trust? 
  413.       ------------------- 
  414.  
  415.       When trust is given to an external source of input, a program 
  416.       accepts information from it while considering the information 
  417.       valid. Secure programs need to be very untrusting and always 
  418.       validate information gained from external sources. Some 
  419.       programs, such as Dan Bernstein's 'qmail' distrust information 
  420.       gained from within. Usually trust is only given to an external 
  421.       source after it has been authenticated. Take the login program 
  422.       under UNIX. Once authenticated the user is trusted to do 
  423.       whatever he wishes to do under his own credentials. Although 
  424.       this example fails because the login program vanishes and is 
  425.       replaced by a shell, you get the idea. 
  426.  
  427.       As a general rule: any information than an attacker can 
  428.       manipulate cannot be given trust. For example: 
  429.  
  430.       In March 1994 Sun Microsystems released a security update for 
  431.       SunOS 4.1.x that fixed a security hole related to "/etc/utmp". 
  432.       The file acted as a database that keeps track of current users 
  433.       logged onto the system with additional information such as the 
  434.       terminal, and time of login. Certain daemons such as comsat, 
  435.       and talkd, would access the file to retrieve the terminal name 
  436.       associated with a user. The terminal name would consist of the 
  437.       path to the terminal device. The daemons would open the file 
  438.       specified by the path, and write to it. Users could modify the 
  439.       file, because it was world writable, and set arbitrary file 
  440.       names for the terminal. This resulted in potentially having the 
  441.       daemons open sensitive files while running with special 
  442.       privileges, and writing to them at the behest of the attacker. 
  443.       This is a good example of trusting information that can be 
  444.       manipulated by an attacker. 
  445.  
  446.       2.3) What is validation? 
  447.       ------------------------ 
  448.  
  449.       When information is received from an untrusted source it must 
  450.       be validated prior to processing it. In the case of the 
  451.       aforementioned talkd hole, the daemon should have made sure the 
  452.       path to the terminal file was indeed correct. This could have 
  453.       been done by simply checking the password database, making sure 
  454.       the ownership matched, and that the terminal path did indeed 
  455.       point to a terminal. Later in the FAQ, the concept of the least 
  456.       privilege principle is explained, and it would have worked 
  457.       wonders with the aforementioned security hole. 
  458.  
  459.       There are several ways you can validate information depending 
  460.       on what it is supposed to be. A good place to start is by 
  461.       defining its attributes. Is it supposed to hold a file name? 
  462.       Does the file exist? Is the user allowed access to that file? 
  463.       That as mentioned previously is what the talkd daemon should 
  464.       have done. In the "Handling Input" section a security hole 
  465.       found in SSH(van der Wijk 1997; Al-Herbish 1997)) will be 
  466.       brought up where privileged ports could be bound to by normal 
  467.       users. In that particular case the function binding to a port 
  468.       did not properly check to make sure the port number was not > 
  469.       1024, and as such the attacker could bind to privileged ports; 
  470.       however, the security hole entailed another error on the part 
  471.       of the program that is discussed in more detail in the coming 
  472.       section. 
  473.  
  474.       2.4) What do you mean by "acting on input"? 
  475.       --------------------------------------------- 
  476.  
  477.       [ I need a more formal term for it. Unfortunately I'm lost for 
  478.       words. ] 
  479.  
  480.       When you pass input directly to a system call, external 
  481.       program, memory copying routine etc. Basically you perform an 
  482.       operation with the aid of the information. In the 
  483.       aforementioned talkd hole the pathname read from the utmp 
  484.       database was passed to a file opening system call directly. The 
  485.       program assumed it was valid, and would not be malicious. This 
  486.       is a wrong assumption. 
  487.  
  488.       PERL supports "tainting" (Wall, Schwartz 1992). All input 
  489.       passed from an external source is tainted unless explicitly 
  490.       untainted. Any tainted input that is passed directly to a 
  491.       system call results in an error. This method of validation is 
  492.       quite ingenious. Regardless of whether or not you are using 
  493.       PERL, the methodology is a good one to follow. 
  494.  
  495.  
  496.     3) Privileges and Credentials 
  497.     ----------------------------- 
  498.  
  499.       3.1) What are privileges and credentials? 
  500.       ----------------------------------------- 
  501.  
  502.       Every process under UNIX has three sets of credentials: Real 
  503.       credentials, effective credentials, and saved credentials. The 
  504.       credentials are split into two groups, user and group 
  505.       credentials. Additionally the process has a list of 
  506.       supplemental group credentials. The different "set*id()" system 
  507.       calls allow a process to change the values in these sets. Only 
  508.       the root user can change them arbitrarily. Non-root users are 
  509.       limited to what they may change their credentials to. 
  510.  
  511.       It is essential to know how the system calls work on the 
  512.       credential sets (see Stevens 1992 for a more exhaustive 
  513.       reference). The following table lists each system call, what 
  514.       credential set it affects, and what credentials it will allow 
  515.       the process to change into. The credential sets are abbreviated 
  516.       with RUID standing for real user ID, EGID for effective group 
  517.       ID, SVUID for the saved user ID. ( Self explanatory really.) 
  518.  
  519.       System Call  Changes                  Can change to            
  520.  
  521.       setuid       RUID EUID SVUID          RUID EUID SVUID          
  522.  
  523.       setgid       RGID RGID SVGID          RGID RGID SVGID          
  524.  
  525.       setreuid     RUID EUID                RUID EUID                
  526.  
  527.       setregid     RGID EGID                RGID EGID                
  528.  
  529.       setruid      RUID                     RUID EUID                
  530.  
  531.       setrgid      GUID                     RGID EGID                
  532.  
  533.       seteuid      EUID                     RUID EUID                
  534.  
  535.       setegid      EGID                     RGID EGID                
  536.  
  537.       Make sure you've read the man pages, and just use the table for 
  538.       reference. When changing credentials make sure you change the 
  539.       right ones. 
  540.  
  541.       The credentials are checked by the kernel for access control. A 
  542.       process is considered privileged if its credentials give it 
  543.       access to privileged information, or privileged facilities. 
  544.       This FAQ will make use of three main privilege levels: 
  545.  
  546.           Special User -- The root user. 
  547.  
  548.           Normal User -- A local user without root privileges. 
  549.  
  550.           Anonymous User -- A user that has not been authenticated, 
  551.           or logged, into the local system. 
  552.  
  553.       The definitions above are a bit misleading without some 
  554.       elaboration. The root user is considered special because the 
  555.       kernel gives him special abilities; his access to files is not 
  556.       limited by file permissions; he can bind to privileged ports; 
  557.       he can change resource limits; he can arbitrarily change his 
  558.       own credentials lowering them to any other credential; he can 
  559.       send signals to any other process, and on some UNIX flavors 
  560.       trace any other process. Although there are some other special 
  561.       abilities the root user has, the list consisted of some of the 
  562.       more important abilities. However, on certain systems 
  563.       privileged information is accessible by non-root users. For 
  564.       example, on SCO 5.0.4 the passwd database is accessible by any 
  565.       user in group "auth." Thus non-root users in that group can 
  566.       still access privileged information. In the case of SCO 5.0.4 
  567.       it is also modifiable by users in that group. The astute reader 
  568.       will note that modifying the password database can effectively 
  569.       lead to modifying one's credentials. So keep in mind that the 
  570.       usage of special privileges in this FAQ is meant to encompass 
  571.       any user who has special abilities that are not conferred upon 
  572.       other local users. This may seem ambiguous but I hope the 
  573.       definition serves its purpose well. 
  574.  
  575.       The normal user has been authenticated, but is regarded as 
  576.       normal without any special privileges. The traditional UNIX 
  577.       kernel itself without any augmentation will not recognize any 
  578.       user except for the root user. The special user and the normal 
  579.       user have both been authenticated, but the special user is 
  580.       recognized to have higher privileges. 
  581.  
  582.       The anonymous user is one who has not been authenticated. It is 
  583.       very important to recognize this user when network applications 
  584.       are written. For example, consider an FTP server using the 
  585.       "anonymous" user open to everyone. In the same way consider the 
  586.       FTP client that connects to the FTP server. The client is run 
  587.       by a local "normal user," (or special user if the admin is 
  588.       nutty enough) but it is connecting to a completely anonymous 
  589.       entity. It must not give the server any special abilities on 
  590.       the local system, and allow only a set of abilities such as 
  591.       writing to a predefined file (downloading from the server). 
  592.       Indeed some advisories discussed the simplest of programs such 
  593.       as 'tar' (Tarreau 1998;Der Mouse 1998) where the tar archive 
  594.       itself could subvert the application into unauthorized 
  595.       modification of privileged information. 
  596.  
  597.       Depending on the privilege level, the application must take 
  598.       into account what the privilege allows the entity to do. 
  599.       Consider a web server that allows clients to browse the entire 
  600.       file system under a normal user ID (or the username 'www'). The 
  601.       web server should still not allow the client to browse just any 
  602.       file or it has given away part of the normal privileges to 
  603.       every user on the net. 
  604.  
  605.       3.2) What is the least privilege principle? 
  606.       ------------------------------------------- 
  607.  
  608.       When an application runs with higher privileges than the source 
  609.       of input, it can prevent the occurrence of security holes by 
  610.       only using the higher privileges for specific tasks. This is 
  611.       known as the least privilege principle (Saltzer 1975), because 
  612.       the lowest privileges are used during the program's execution. 
  613.       If the attacker is able to trick the program into accomplishing 
  614.       a specific task, it will do so with his privileges. 
  615.  
  616.       Most UNIX flavors come with a utility that allows the user to 
  617.       change his personal information. It is usually called chfn. The 
  618.       information is copied to a temporary file from the password 
  619.       database. The utility then forks a child process which executes 
  620.       an editor on the temporary copy. The user is subsequently given 
  621.       control of the editor and is free to modify the copy. Once the 
  622.       user completes modifying the copy and exits from the editor, 
  623.       the utility reads the temporary copy, performs any sanity 
  624.       checks on the input, and copies it back to the password 
  625.       database. The least privilege principle must be applied in this 
  626.       case. The child process running the editor cannot do so with 
  627.       special privileges. The editor may allow the user to run a 
  628.       shell, or open other files. chfn must revert the privilege to 
  629.       that of the user in the child process before executing the 
  630.       editor. 
  631.  
  632.       A security hole that was reported concerning XFree86 (plaguez 
  633.       1997) The server would run with root privileges and read any 
  634.       configuration file specified from a command line option. The 
  635.       advisory demonstrated how the shadowed password database could 
  636.       be read by pointing the server to it as its configuration file. 
  637.       Since the server ran with root privileges it could open the 
  638.       database, and would inadvertently output its contents as part 
  639.       of its error reporting. Thus an attacker could read files he 
  640.       would not normally be able to. Had the X server used the same 
  641.       privileges as the end user when attempting to read the 
  642.       configuration file, it would not have been able to. The 
  643.       attacker would only be able to access files readable by him. 
  644.       The file opening operation should have been done with the least 
  645.       privilege principle. 
  646.  
  647.       3.3) How do I apply the least privilege principle safely? 
  648.       --------------------------------------------------------- 
  649.  
  650.       The least privilege principle can be applied by either lowering 
  651.       privileges temporarily, or completely dropping privileges so 
  652.       that they will never be regained again. However, there are 
  653.       viable attacks that can occur from both operations. Also 
  654.       lowering privileges is not always enough without doing away 
  655.       with privileged information. 
  656.  
  657.       Note on saved credentials 
  658.       ------------------------- 
  659.  
  660.       Before discussing the details of lowering credentials properly, 
  661.       the saved credential set needs to be elaborated upon. The saved 
  662.       credential set is initialized to the effective credentials of 
  663.       the process at the time of its execution. So if the 
  664.       process-image has a set-id-on-execution (SUID) or 
  665.       set-group-id-on-execution (SGID) bit set, the saved credentials 
  666.       will match that credential. This is very useful if the program 
  667.       wishes to temporarily drop its effective credentials and then 
  668.       regain them. 
  669.  
  670.       Lowering privileges temporarily entails changing one of the 
  671.       credential sets, usually the effective credentials because they 
  672.       are most often checked by the kernel. The seteuid() and 
  673.       setegid() system calls allow a process to set its effective 
  674.       credentials to its real credentials or its saved credentials. 
  675.       This is where the switching between the two credential sets 
  676.       becomes very useful. A SUID or SGID process can change its 
  677.       effective credentials to its real credentials, which are 
  678.       inherited from the parent process, and then switch them back to 
  679.       its saved credentials which it inherits from the SUID or SGID 
  680.       file permission. In doing so the SUID or SGID program is 
  681.       toggling its privileges between its caller and the 
  682.       process-image owner. 
  683.  
  684.       Because a process cannot get its saved credentials via any 
  685.       system call, it is recommended to do a geteuid() and getegid() 
  686.       at the beginning of execution and store them internally. This 
  687.       works because the saved credentials are an exact copy of the 
  688.       effective credentials at the start of a process' execution. 
  689.       This will work: saved_uid = geteuid(); saved_gid = getegid(); 
  690.  
  691.       To change effective credentials to the saved credentials do a 
  692.       setegid(saved_gid); seteuid(saved_uid); Now to switch them back 
  693.       to match the real credentials do a setegid(getgid()); 
  694.       seteuid(getuid); Simple and straight forward. 
  695.  
  696.       The second method of applying the least privilege principle is 
  697.       to completely drop privileges and never regain them again. 
  698.       Recall the chfn example mentioned in question 3.2? It would 
  699.       have to drop the privileges in its child process completely 
  700.       because it gave the user control of the child process. This is 
  701.       done by calling setgid() and then setuid(). A common mistake is 
  702.       to drop the user ID first, and this will fail if the process is 
  703.       relying on the fact that it has root privileges! 
  704.  
  705.       There are, as mentioned earlier, viable attacks. The first is 
  706.       the signal attack. BSD derived operating systems allow a 
  707.       process to send a signal to another process if: 
  708.  
  709.           The real user ID of process A is that of the root user. 
  710.  
  711.           The real user ID of process A matches the real user ID of 
  712.           process B. 
  713.  
  714.           The effective user ID of process A matches the effective 
  715.           user ID of process B. 
  716.  
  717.           The real user ID of process A matches the effective user ID 
  718.           of process B. 
  719.  
  720.           The effective user ID of process A matches the real user ID 
  721.           of process B. 
  722.  
  723.           Both processes share the same session ID. 
  724.  
  725.       With those semantics it is obvious that if a process lowered 
  726.       its effective credentials to that of the user, he would be able 
  727.       to send it a signal. In the event that the process begins to 
  728.       run with the same real credentials as the user (all SUID or 
  729.       SGID processes start out this way), it should change its 
  730.       credentials if it expects to trust signals. Keep in mind that 
  731.       by lowering its effective credentials to that of the user's 
  732.       real credentials it _is_ susceptible. This access check on 
  733.       signals is quite a mishmash. Also, change the session ID via 
  734.       setsid(). 
  735.  
  736.       In April 1998, a Bugtraq posting discussed the circumvention of 
  737.       a protection scheme employed by implementations of the BSD ping 
  738.       utility (Sanfilippo 1998) The ping utility would use the alarm 
  739.       routine to synchronize the periodical sending of Internet 
  740.       Control Message Protocol (ICMP) echo requests to a remote host, 
  741.       and would not allow the normal user to send requests repeatedly 
  742.       in a flooding manner. The protection scheme was simply there to 
  743.       prevent abusive users from flooding other hosts with a large 
  744.       number of ICMP echo requests. The normal user, of course, 
  745.       cannot send an ICMP packet because performing this task 
  746.       requires the use of a raw socket. Only the root user can open a 
  747.       raw socket because of the security implications associated with 
  748.       raw network access -- receiving incoming packets rawly from the 
  749.       network, and sending raw packets into the network. Thus the 
  750.       ping utility is normally installed as SUID to root. The 
  751.       technique Sanfilippo used to get around ping's security 
  752.       mechanism was to constantly send the SIGALRM signal to it, 
  753.       subverting the protection scheme it attempted to implement. 
  754.       Since the alarm routine would schedule an occurrence of SIGALRM 
  755.       after a specified interval, the ping utility would have a 
  756.       signal handler for it, that sends the ICMP echo request. 
  757.       Obviously the process may not install handlers and act on them 
  758.       blindly if an attacker can trigger the signal handlers. 
  759.  
  760.       Some UNIX flavors support the SA_SIGINFO option that can set 
  761.       when setting the signal handler via 'sigaction'. This passes 
  762.       the handler additional information with regards to who sent the 
  763.       signal, and whether or not it is kernel generated. Another 
  764.       method is by using internal sanity checks. In the case of 
  765.       'ping' this could have been done by simply keeping track of the 
  766.       time that passed in between signals being generated and not 
  767.       honoring them unless a sufficient amount of time had passed. 
  768.  
  769.       However, a worse case would be a SIGTERM or SIGKILL that halts 
  770.       a process when it is in between a critical state. In the case 
  771.       of 'chfn' it would be downright despicable of a user to halt it 
  772.       just as it was writing out the new password file. If a process 
  773.       is in an "unclean state" it should not allow itself to be 
  774.       halted by an attacker and retain higher privileges untill the 
  775.       point whence it can afford to be halted. 
  776.  
  777.       A common mistake is to assume that a process with lowered 
  778.       credentials is no longer a security hazard. In fact it just 
  779.       might be, even with the previous attacks accounted for. 
  780.  
  781.       A well known, but ancient, technique of getting the password 
  782.       file from an old SunOS box was to cause its ftp daemon to dump 
  783.       core. Similar security holes were later reported (Temmingh 
  784.       1997). If a privileged process reads the password database into 
  785.       memory and is then caused to dump core because of a signal 
  786.       attack, the core image may hold a copy of the password file 
  787.       which is then easily readable by the attacker. But cleaning up 
  788.       internal memory may not be enough. A security hole was found on 
  789.       OpenBSD's chpass utility with file descriptor leakage (Network 
  790.       Associates Inc. 1998). The child process was passed a 
  791.       privileged file descriptor because the descriptor was never 
  792.       properly closed before giving the user control over the 
  793.       process. 
  794.  
  795.       Finally, process tracing attacks may take place. FreeBSD, and 
  796.       NetBSD both allow a process to trace any process with a 
  797.       matching real user ID. Tracing implies complete control over 
  798.       the process, including the file descriptors, memory, and 
  799.       executable instructions etc; however, a process may not be 
  800.       traced if it is SUID or SGID. 
  801.  
  802.       Here's a check list for lowering real and effective 
  803.       credentials: 
  804.  
  805.       Lowering Effective Credentials 
  806.       ------------------------------ 
  807.  
  808.           The process should not have any cleaning up to do. The 
  809.           state of external objects should be in a form that is 
  810.           suitable for reuse. This includes lock files, updates to 
  811.           databases, and even temporary files. 
  812.  
  813.           All signal handlers that may be triggered should not be 
  814.           trusted; they must be validated for authenticity. 
  815.  
  816.           All privileged information held in the process memory 
  817.           should be cleared so that a core dump will not contain them 
  818.           (don't just free up dynamic privileged memory, clean it out 
  819.           before freeing). 
  820.  
  821.       Lowering Real Credentials: 
  822.       -------------------------- 
  823.  
  824.       Previous steps must be followed as well. Additional steps take 
  825.       into account the process tracing attacks which are not viable 
  826.       on all systems. 
  827.  
  828.           Privileged information may not be held by the process. This 
  829.           includes file descriptors or sockets referencing privileged 
  830.           information. 
  831.  
  832.           The effective credentials should be dropped to the real 
  833.           credentials as well, since a process that is traced can be 
  834.           forced to execute arbitrary code under this effective 
  835.           credential. 
  836.  
  837.     4) Local Process Interaction: 
  838.     ----------------------------- 
  839.  
  840.       4.1) What is process attribute inheritance? Or why should I not 
  841.       write SUID/SGID programs? 
  842.       
  843.       ----------------------------------------------------------------
  844.       
  845.  
  846.       Process attribute inheritance (AFAIK a term I coined), is when 
  847.       a child process inherits attributes from the parent process' 
  848.       environment. I did see this referred to as "state variables", 
  849.       but I forgot by who and all searching has led nowhere. The 
  850.       problems with process attribute inheritance were fore shadowed 
  851.       by the 'ping' security hole mentioned in question 3.3, as well 
  852.       as the OpenBSD 'chpass' hole mentioned in that section. 
  853.  
  854.       A child process is an exact copy of its parent except for the 
  855.       process ID and the parent process ID. These change for obvious 
  856.       reasons. However, all other attributes are the copied with the 
  857.       exception of file descriptors. File descriptors, however, are 
  858.       shared. (For a more exhaustive explanation see Stevens 1992). 
  859.  
  860.       A process is executed after a call to execve() or one of the 
  861.       other routines in its family. This system call filters out many 
  862.       of the process attributes, but lets some through. This is 
  863.       considered a UNIX "feature" and is relied upon by daemons such 
  864.       as inetd. Keep in mind that a SUID process is a child that has 
  865.       been execve()'d, so it does inherit these attributes. Before I 
  866.       present a list of process attributes (albeit probably an 
  867.       incomplete list), some known security holes will be discussed 
  868.       to illustrate the types of attacks that can occur (Bishop 
  869.       1986). 
  870.  
  871.       A post was made to Bugtraq that discussed a weakness in a 
  872.       popular Mail User Agent package elm because it trusted an 
  873.       environment (Jensen 1994) variable. An autoreply utility was 
  874.       packaged with elm that would run with special privileges, and 
  875.       perform its own internal checks to prevent exploitation by the 
  876.       user. One of the checks included making sure a user did have 
  877.       read access to an arbitrary file before allowing him to read it 
  878.       (can you see what's wrong with this picture?). If the full path 
  879.       to the file was not specified, the utility simply prepended 
  880.       whatever was in the HOME environment variable, and opened the 
  881.       file for reading, without performing any checks. This allowed 
  882.       users to read files with the same privileges as the autoreply 
  883.       process. The mistake was to assume that environment variables 
  884.       can be trusted for valid information, and that the files in a 
  885.       user's home directory are his to read. Both these assumptions 
  886.       are false. Environment variables are inherited from a parent 
  887.       process, and thus can contain arbitrary information. The 
  888.       attacker can manipulate environment variables before forking 
  889.       the child process. It is also not true that the user would have 
  890.       access to the files in his home directory, necessarily. This 
  891.       was a tragic case of giving trust to information that can be 
  892.       manipulated by an attacker. 
  893.  
  894.       In December 1993, Sun Microsystems released a security 
  895.       bulletin, which among other subjects brought up a weakness in 
  896.       the modload and loadmod system utilities. The weakness was 
  897.       trusting the Internal Field Separator (IFS) environment 
  898.       variable. Since the shell would use the IFS to split the 
  899.       contents of variables after they are expanded, the attacker can 
  900.       specify how the contents are split. A path name such as 
  901.       "/bin/cat" , could indeed cause the file "bin" to be executed 
  902.       if the IFS is set to '/'. This is because the character '/' 
  903.       would be recognized as a field to separate the other strings in 
  904.       the variable. Since both these utilities would call upon a 
  905.       shell during their execution, the attacker could arbitrarily 
  906.       trick the utilities to run his process-images with their 
  907.       privileges by modifying the IFS variable. We might think that 
  908.       shells should not make use of the IFS variable if the shell is 
  909.       not run in interactive mode. This is not a solution, since this 
  910.       only canvases the problem of passing down harmful process 
  911.       attribute. The solution is not to pass the variable in the 
  912.       first place. If the aforementioned utility would not have 
  913.       called a shell, it may still have encountered problems with 
  914.       other child processes. For example the LD_PRELOAD environment 
  915.       variable is used by the run-time linker to load code from any 
  916.       shared library the variable specifies. Although the run-time 
  917.       linker will ignore such environment variables for SUID or SGID 
  918.       processes, the child process of a privileged process may 
  919.       inherit them nonetheless and not have such protection. Since 
  920.       the child process in turn inherits its parent's privileges, the 
  921.       parent is effectively compromised through the child process. So 
  922.       remember, the SUID process may have children that are passed 
  923.       down harmful environment variables that would not affect the 
  924.       SUID program necessarily but affect its children. 
  925.  
  926.       At this point I must concede that there may very well be 
  927.       implementations of run-time linkers (read: haven't done the 
  928.       research yet) that do not make the mistake of using the 
  929.       LD_PRELOAD variable even in the child process of a SUID or SGID 
  930.       process. Nonetheless, why risk it on an old box? 
  931.  
  932.       Finally a reminder of the OpenBSD chpass hole, and the 
  933.       descriptor leak. If you haven't read it in section 3.3, go and 
  934.       read it. 
  935.  
  936.       Thus four types of attacks are viable: 
  937.  
  938.           Child process trusts process attribute to contain valid 
  939.           information. (elm hole) 
  940.  
  941.           The process attribute affects the child process directly. 
  942.           (ping hole) 
  943.  
  944.           A process inherits an attribute and passes it down to a 
  945.           child process that is affected by it. This is the same as 
  946.           the second attack, but it is the child process of the 
  947.           secure process that is affected. (or the grandchild of the 
  948.           attacker). (LD_PRELOAD attack) 
  949.  
  950.           The child process of the secure process is passed an 
  951.           attribute containing privileged information. (chpass hole) 
  952.  
  953.       Now for the list of process attributes and how to go about 
  954.       avoiding any security holes. 
  955.  
  956.           Credentials: 
  957.  
  958.           Just a review of section 3. Processes running with the same 
  959.           credentials, or similar (see section 3!) can be attacked by 
  960.           process tracing, or sent signals that affect them. 
  961.  
  962.           File Descriptors: 
  963.  
  964.           The 'chpass' security hole had a file descriptor leak. A 
  965.           quick and easy way of avoiding file descriptor leaks is by 
  966.           setting the FD_CLOEXEC flag on the descriptor (again, see 
  967.           Stevens 1992 as he discusses this rather well). But that's 
  968.           not the end of it. In 1998 the OpenBSD team released a 
  969.           patch for OpenBSD which would not allow a SUID or SGID 
  970.           program from inheriting empty file descriptors in the first 
  971.           three slots. It would instead set them pointing to 
  972.           /dev/null. Theo deRaadt mentioned to me one of the problems 
  973.           that could occur: if the inherited descriptor would be 
  974.           opened as a raw socket, and error reporting by the standard 
  975.           C library (standard error) would be sent through it, bogus 
  976.           packets could be sent to the socket. Although he did 
  977.           mention for other reasons programs such as traceroute were 
  978.           not susceptible. As a workaround for systems without this 
  979.           security feature, doing a stat on the first three file 
  980.           descriptors to check their availability and opening them to 
  981.           "/dev/null" should do. It just adds bloat to your code, and 
  982.           should really be handled by the kernel. 
  983.  
  984.           Environment Variables: 
  985.  
  986.           Don't trust environment variables to contain valid 
  987.           information. In the case of the above mentioned 'elm' hole, 
  988.           it would have been wiser to look up the home directory in 
  989.           the password database. Another more subtle issue is not 
  990.           placing privileged information in an environment variable 
  991.           (Smith 1998). Specifically, a security hole related to 
  992.           FreeBSD's 'ps' utility. The utility would allow users to 
  993.           view another process' environment variables. Consequently 
  994.           applications like pppd that accepted passwords via 
  995.           environment variables became vulnerable to unauthorized 
  996.           release of privileged information attacks. In fact, the 
  997.           hole was not related to 'ps' if you think about it 
  998.           critically. The application that places privileged 
  999.           information in the environment variable is at fault. 
  1000.  
  1001.           Finally comes the security hole related to having an 
  1002.           environment variable affect an external program. IFS and 
  1003.           LD_PRELOAD, as discussed previously, are viable environment 
  1004.           variables, but a secure program should remove all 
  1005.           environment variables except the ones it chooses to use and 
  1006.           knows will not affect it. A good idea is to get rid of 
  1007.           every environment variable you don't need and keep the ones 
  1008.           you know are useful and actually have a use for. 
  1009.  
  1010.           File Mode Creation Mask: 
  1011.  
  1012.           Although it is very common for a robust program to reset 
  1013.           its file mode creation mask by calling umask(), it should 
  1014.           still be noted as a viable security concern. An attacker 
  1015.           can pass a mask that would affect the file permissions of 
  1016.           files created by open() and mkdir(). Resetting the mask to 
  1017.           0 suffices to prevent a file mode creation mask attack. 
  1018.  
  1019.           Working and Root Directories 
  1020.  
  1021.           Both the current working directory, and the root directory 
  1022.           are inherited from the parent process. The working 
  1023.           directory affects file system calls if they are not passed 
  1024.           a full path name. This can be made into an attack. Thus it 
  1025.           is advisable to both set the current working directory, and 
  1026.           use full paths when making file system calls. The root 
  1027.           directory should not be a concern. Only the root user can 
  1028.           change the root directory. 
  1029.  
  1030.           Resource Limits 
  1031.  
  1032.           The setrlimit() system call allows a process to set soft or 
  1033.           hard limits on its consumption of resources. When a process 
  1034.           reaches its soft limit a signal is sent depending on which 
  1035.           limit is reached. SIGSEV for the maximum stack size, 
  1036.           SIGXFSZ for an I/O operation that exceeded a file size 
  1037.           limit etc. The list is left till the section on resource 
  1038.           limits, but the signals if not handled will result in the 
  1039.           process being terminated. A careful attacker may trigger a 
  1040.           denial of service attack where the process is terminated in 
  1041.           the middle of performing a critical operation. When the 
  1042.           hard limit is reached, the process is prevented from 
  1043.           executing any further. The soft limits may be raised or 
  1044.           lowered at the process' own discretion. Thus by setting all 
  1045.           limits to infinity, the process can relieve itself of any 
  1046.           resource limit attacks. However, the hard limit can be 
  1047.           lowered by a normal user, but cannot be raised except by 
  1048.           root. A viable attack is to lower the hard resource limits, 
  1049.           and have the child process choke from underneath. The most 
  1050.           obvious solution is not to begin execution if the hard 
  1051.           limits are too low, and to heighten the soft limits to 
  1052.           infinity. Raising the soft limits over the hard limits will 
  1053.           not work. Thus the process will begin by specifying how 
  1054.           much of the individual resources it requires, and if the 
  1055.           setrlimit() system call returns an error it will not begin 
  1056.           execution as to avoid resource starvation. This is not very 
  1057.           helpful though, and better treatment of resource limits is 
  1058.           given in its own section below. 
  1059.  
  1060.           Scheduling Priority 
  1061.  
  1062.           The scheduling priority on a process can be modified by a 
  1063.           call to nice() or setpriority(). This is usually done to 
  1064.           tell the scheduler how important the process is. A very low 
  1065.           priority may cause the process to execute slower, which can 
  1066.           aid an attacker if he is attempting to exploit a race 
  1067.           condition.The semantics of setpriority() requires the user 
  1068.           to have an effective user ID matching the real or effective 
  1069.           user ID of the peer process. So this may not necessarily be 
  1070.           inherited. However, the priority of a process can only help 
  1071.           an attacker exploit a race condition more easily. It does 
  1072.           not really constitute a denial of resource attack unless 
  1073.           the process has time constraints. Regardless of the speed 
  1074.           of a process, a race condition can always be exploited. 
  1075.           Even with the element of luck, or by slowing down the 
  1076.           system as a whole. Race conditions need to be eliminated 
  1077.           and not made harder to exploit. Keep an eye out for this 
  1078.           scheduling priority in the rare case that it actually does 
  1079.           matter. 
  1080.  
  1081.           Interval Timers 
  1082.  
  1083.           Three interval timers that can be manipulated by the 
  1084.           setitimer() system call. The alarm facility is usually 
  1085.           wrapped around a call to setitimer(). Since the interval 
  1086.           timers are inherited, a parent process could set a timer to 
  1087.           send its child process SIGALRM, SIGVTALRM or the SIGPROF 
  1088.           signal. These could be used to either subvert a program if 
  1089.           it were to handle them, or terminate it. These signals 
  1090.           should be ignored at the beginning of the process' 
  1091.           execution or the timers should be reset. 
  1092.  
  1093.           Signal Handlers 
  1094.  
  1095.           Although all signal handlers are reset to their defaults, 
  1096.           blocked signals remain blocked and so do ignored signals. 
  1097.           This could be a problem if our program design is built 
  1098.           around receiving a signal before carrying on, and assumes 
  1099.           it is not blocked or ignored. Resetting the state of the 
  1100.           signal mask, and resetting signal handlers should also be 
  1101.           done without any preconceptions of default settings. 
  1102.  
  1103.       With all of this SUID/SGID programming is daunting at best. A 
  1104.       better technique (proposed by Thomas Ptacek on the newsgroup) 
  1105.       would be to use a server-client model where the server is 
  1106.       privileged but does not inherit the environment of its parent 
  1107.       process -- a would be attacker. That way the client runs with 
  1108.       no privileges, connects to the privileged server and passes the 
  1109.       relevant information through the IPC channel. 
  1110.  
  1111.       4.2) How can I limit access to a SUID/SGID process-image 
  1112.       safely? 
  1113.       
  1114.       ----------------------------------------------------------------
  1115.       
  1116.  
  1117.       The question may seem vague but sometimes it would seem 
  1118.       attractive to have a SUID process that is only executable by a 
  1119.       particular set of users. Some time ago I implemented a 
  1120.       distributed network monitoring package that had java clients 
  1121.       talk to it remotely, and sniffers running on different servers 
  1122.       (a very ambitious undertaking). The actual servers where run 
  1123.       under a special group called "sly" that would in turn have 
  1124.       access to a SUID process-image to do all the sniffing. The 
  1125.       child process ran as root, but could only be executed by users 
  1126.       in the group "sly." 
  1127.  
  1128.       At first this looks good. The actual server does not run with 
  1129.       special privileges, and it would seem that if it got exploited 
  1130.       the attacker would not gain root privileges. However, he would 
  1131.       gain privileges for the group "sly" that would let him sniff 
  1132.       the local network. If he was then able to exploit the sniffer, 
  1133.       he would gain root privileges. But he needs to exploit the 
  1134.       server to the point of executing arbitrary code on the machine. 
  1135.       Creating a file, or tricking it into sending privileged 
  1136.       information would not equate to gaining the privileges of group 
  1137.       "sly" necessarily. So this does not lessen the need for secure 
  1138.       code, but it _could_ in the long run lessen the chances of 
  1139.       complete compromise. I'm going to call this technique, at the 
  1140.       risk of coining yet another term, privilege segmentation. The 
  1141.       attacker may gain privileges to a specific group but has more 
  1142.       work to do in order to gain higher privileges. 
  1143.  
  1144.       Fair warning that security via "chance" or "hope" is not good. 
  1145.       I don't particularly like hearing about "risk management," and 
  1146.       the above technique is just that: risk management. 
  1147.  
  1148.       4.3) How do I authenticate a parent process? 
  1149.       -------------------------------------------- 
  1150.  
  1151.       Since the child process inherits the parent's real user ID, a 
  1152.       call to getuid() does the trick. Unfortunately due to a 
  1153.       misconception, some programmers are led to believe that 
  1154.       getuid() is not sufficient. This stems from the thinking that 
  1155.       if a user managed in exploiting a SUID process into running 
  1156.       another process, the child would have a real user ID matching 
  1157.       the parent process' effective user ID. This is not true, 
  1158.       because the real user ID keeps propagating from parent to child 
  1159.       regardless of the SUID feature. As mentioned in 2.1, the child 
  1160.       process inherits the credentials directly, a perfect copy with 
  1161.       the exception of the effective credentials if the SGID or SUID 
  1162.       feature. The saved credentials are also reset. But this 
  1163.       exception does not extend to the real credentials which are 
  1164.       directly inherited. 
  1165.  
  1166.       However, if the exploited SUID process was to change its real 
  1167.       user ID to match its effective user ID, which is easily done 
  1168.       with setuid(), then getuid() is not sufficient. There is a 
  1169.       logical fallacy here: if the parent process has already been 
  1170.       exploited to the point where the attacker can cause it to 
  1171.       switch credentials what's the point in faking it anymore? 
  1172.       Nonetheless, additional steps can be taken but not portably. On 
  1173.       systems where login information is stored in the kernel, and 
  1174.       not on the file system, by setlogin(), getlogin() will always 
  1175.       return the username associated with the session. [ FreeBSD 
  1176.       stores login information in kernel. ] 
  1177.  
  1178.       On OpenBSD, and FreeBSD the issetugid() system calls can be 
  1179.       used to find out if the current process is a SUID or GUID 
  1180.       process. This propagation continues unless a child process 
  1181.       clears all its privileges, to quote the OpenBSD man page "uid 
  1182.       != euid or gid != egid". So this system call may be used in 
  1183.       conjunction with getuid to be even more paranoid. 
  1184.  
  1185.       A good suggestion is to do a getuid(), check getlogin() if the 
  1186.       information is stored in the kernel, and finally do a 
  1187.       issetugid(). If all tests pass, you know you are talking to the 
  1188.       Real McCoy. In saying that, caution should not be thrown to the 
  1189.       wind. Using passwords, cookies, 
  1190.       insert-fancy-authentication-mechanism-here etc. is always 
  1191.       recommended, but the previous approach is the more light weight 
  1192.       kernel supported method. 
  1193.  
  1194.       4.4) How do I authenticate a non-parent process? 
  1195.       ------------------------------------------------ 
  1196.  
  1197.       [ I could use writing on SO_PEERCRED (Linux) doors (Solaris) 
  1198.       and LOCAL_CREDS (NetBSD). Also I have some example code for the 
  1199.       techniques discussed below. If you tackle the any of the issues 
  1200.       above, you would be a very nice contributor to provide example 
  1201.       source. Also this is advanced stuff so I'll elaborate more when 
  1202.       I fix it up] 
  1203.  
  1204.       It is possible to authenticate processes via IPC channels 
  1205.       (Bernstein 1999). However the methods differ on different UNIX 
  1206.       flavors making it a very non-portable mess to write. 
  1207.  
  1208.       BSD derived systems support the concept of access rights 
  1209.       (Stevens 1990). The facility allows a process to pass a file 
  1210.       descriptor through a UNIX domain socket, and with a small hack 
  1211.       it can be used to authenticate a local process. The term hack 
  1212.       is only used because the facility was not intended for 
  1213.       authentication. However, if the client sends a descriptor 
  1214.       referencing a file that has read permissions only for its 
  1215.       owner,the receiver knows the sender is the owner. Thus the file 
  1216.       acts as an identifier. However, on systems where a user may 
  1217.       give away files with chown() this method cannot be used. The 
  1218.       attacker can simply create a file with read permissions only 
  1219.       for himself, open it, and then chown it to another user. 
  1220.       Fortunately this is a System V "feature," and on many systems 
  1221.       can be turned off as a kernel configuration option. 
  1222.  
  1223.       A similar technique is found under System V derived systems. 
  1224.       This is done by receiving file descriptors via a STREAMS file. 
  1225.       Only the file descriptor is discarded because the UID is passed 
  1226.       along with it. This is done by using an ioctl call with the 
  1227.       I_SENDFD and I_RECVFD flags on a streams file used as an IPC 
  1228.       channel. This technique does not suffer from the chown attack 
  1229.       because the credentials are passed _along_ with the descriptor. 
  1230.  
  1231.       BSD/OS, FreeBSD and other BSD derived operating systems also 
  1232.       have SCM_CREDS that sends credential information through a UNIX 
  1233.       domain socket. [ Ok, someone point me to some standard that 
  1234.       documents the semantics. Every BSD camp is doing it differently 
  1235.       ":( ] 
  1236.  
  1237.     5) Using The File System Securely 
  1238.     --------------------------------- 
  1239.  
  1240.   [ The first contributor to find a better solution to 5.2 gets a 
  1241.   donut ] 
  1242.  
  1243.   Sadly too many past security holes show that the average programmer 
  1244.   fails to note that the file system is a database with links 
  1245.   pointing to resources, and that filenames act only as identifiers. 
  1246.   File names, which are stored in directories (considered special 
  1247.   files), point to inodes. Indeed that is how we get race condition 
  1248.   attacks, and symlink attacks. Both are given treatment below, but 
  1249.   keep in mind that the principles are open to other databases that 
  1250.   follow the same model as the file system. In particular race 
  1251.   conditions may occur in non-file-system related operations. 
  1252.  
  1253.       5.1) How do I avoid race condition attacks? 
  1254.       ------------------------------------------- 
  1255.  
  1256.       A race condition occurs when two or more operations occur in an 
  1257.       undefined manner (McKusick et al. 1996). Specifically in file 
  1258.       system races the attacker attempts to change the state of the 
  1259.       file system in between two file system operations on the part 
  1260.       of the program. Usually the program expects the two operations 
  1261.       to apply to the same file, or expects the information retrieved 
  1262.       to be the same. If the file operations are not atomic, or do 
  1263.       not reference the same file this cannot be guaranteed without 
  1264.       proper care. As an added note see Bishop 1996 for a more 
  1265.       exhaustive and but more theoretical discussion. 
  1266.  
  1267.       Solaris 2.x's 'ps' utility had a security hole that was caused 
  1268.       by a race condition (Chasin 1995). The utility would open a 
  1269.       temporary file, and then use the chown() system call with the 
  1270.       file's full path to change its ownership to root. This was 
  1271.       easily exploitable by slowing the system down, finding the file 
  1272.       created, deleting it, and then slipping in a new SUID word 
  1273.       writable file. After the file was created with that mode and 
  1274.       chowned to root by the insecure process, the attacker simply 
  1275.       copies a shell into the file. Viola, instant root shell. (The 
  1276.       exploit itself made use of symlinks to slip in the new file, 
  1277.       but I'm leaving the concept of symlinks untill the next 5.2) 
  1278.  
  1279.       At first glance, to the less perceptive reader, it may seem 
  1280.       that if the original file was not created world writable the 
  1281.       attacker could not delete it. Well it was not world writable 
  1282.       and he could. The file was created under the temporary 
  1283.       directory (usually "/var/tmp" or "/tmp") which had world 
  1284.       writable permissions. Global temporary directories are setup 
  1285.       this way or they aren't usable, hence the world global. It's a 
  1286.       completely different issue to argue whether having global 
  1287.       temporary directories is a good idea. [For a similar security 
  1288.       hole see Hull 1996] 
  1289.  
  1290.       The problem was that the second operation used the file name 
  1291.       and not the file descriptor. If a call to fchown() would have 
  1292.       been used on the file descriptor returned from the original 
  1293.       open() operation, the security hole would have been avoided. 
  1294.       File names are _not_ unique. The file name "/tmp/foo" is really 
  1295.       just an entry in the directory "/tmp". Directories are special 
  1296.       files. If an attacker can create, and delete files from a 
  1297.       directory the program cannot trust file names taken from it. Or 
  1298.       to look at it in a more critical way: because the directory is 
  1299.       modifiable by the attacker, a program cannot trust it as a 
  1300.       source of valid input. Instead it should use file descriptors 
  1301.       to perform its operations. 
  1302.  
  1303.       One solution is to use the sticky bit. This will prevent the 
  1304.       attacker from removing the file, but not prevent the attacker 
  1305.       from creating files in the directory. See below for a treatment 
  1306.       toward symbolic link attacks. 
  1307.  
  1308.       There are other race conditions that can occur. Using stat() 
  1309.       and instead of fstat(). Using access() and thinking that the 
  1310.       information will persist untill the next few lines of code. It 
  1311.       may not persist if the directory can be modified by an 
  1312.       attacker, so don't expect it to. The only way to make sure the 
  1313.       file permissions will not change, and that you have the file 
  1314.       you want is to fstat() after an open(). 
  1315.  
  1316.       5.2) How do I create/open files safely? 
  1317.       --------------------------------------- 
  1318.  
  1319.       Several attacks have made use of symbolic links to fool the 
  1320.       process into opening a different file. A symbolic link is a 
  1321.       convenient method of creating a file that references a 
  1322.       different file. It is not a hard link, because it does not 
  1323.       reference a particular inode. Instead it holds a path to 
  1324.       another file. This is convenient because the path could be 
  1325.       point to a non-existent file. 
  1326.  
  1327.       A process can be tricked into opening or creating a file it did 
  1328.       not intend to via a symbolic link attack. For example: 
  1329.  
  1330.       A security hole reported for SUN's license manager stemmed from 
  1331.       the creation of a file without checking for symbolic links (or 
  1332.       soft links) (Eriksson 1996). An open() call was made to either 
  1333.       create the file if it did not exist, or open it if it did 
  1334.       exist. The problem with a symbolic link is that an open call 
  1335.       will follow it and not consider the link to constitute a 
  1336.       created file. So if you had "/tmp/foo" symlinked to "/.rhosts" 
  1337.       (or "/root/.rhosts" depending on your cultural background), the 
  1338.       latter file would be transparently opened. The license manager 
  1339.       seemed to have used the O_CREAT flag with the open call making 
  1340.       it create the file if it did not exist. To make matters worse, 
  1341.       it created the file with world writable permissions. Since it 
  1342.       ran as root, the ".rhosts" file could be created, written to, 
  1343.       and root privileges attained. I'll leave it as an exercise to 
  1344.       the reader to work out how a world writable ".rhosts" file can 
  1345.       be used to get root privileges. (Back in those days a world 
  1346.       writable ".rhosts" was OK on the part of rlogind) 
  1347.  
  1348.       The problem is two fold, since it requires the following 
  1349.       conditions to solve it: "If file does not exist, and no 
  1350.       symbolic link exists in its place, then create file." And 
  1351.       remember: we can only use one system call to do this, in order 
  1352.       to avoid race conditions (see 5.1). At first glance it would 
  1353.       seem that using an O_EXCL should solve this problem. 
  1354.       Unfortunately it does not. Here's a quote from the FreeBSD man 
  1355.       page: 
  1356.  
  1357.       "If O_EXCL is set and the last component of the pathname is a 
  1358.       symbolic link, open() will fail even if the symbolic link 
  1359.       points to a non-existent name." 
  1360.  
  1361.       Because O_EXCL, on FreeBSD, only checks the last component, 
  1362.       symbolic links between directories are still viable attacks. 
  1363.       Consider the path "/usr/foo/bar/footest" to the file "footest" 
  1364.       now make a symbolic link with "/usr/foo2" pointing to 
  1365.       "/usr/foo/bar." Opening "/usr/foo2/footest" will translate to 
  1366.       opening "/usr/foo/bar/test." The only way to avoid this is to 
  1367.       make sure that the full path does not consist of symbolic 
  1368.       links. One method to is chdir() down the path to the current 
  1369.       directory. Once the directory is reached, check to make sure it 
  1370.       matches the path specified previously. If it does, create the 
  1371.       file, knowing that you are using O_EXCL and relying on the last 
  1372.       component to be checked by the system call. 
  1373.  
  1374.       The semantics of O_EXCL as mentioned in the FreeBSD man page is 
  1375.       not found in the UNIX98 standard. This means some systems are 
  1376.       broken inherently. We'll proceed without taking these semantics 
  1377.       into consideration, and look for other work arounds. 
  1378.  
  1379.       One of the other work arounds is to create a file with write 
  1380.       only permissions for the program's real user ID. Then an 
  1381.       fstat() can be made and the program will know the full path to 
  1382.       the file it has opened. If it is the correct file, go about 
  1383.       business as usual, fchmod() if you want as well. However, if it 
  1384.       is the wrong file it needs to be deleted. See below for 
  1385.       treatment toward deleting files safely. Again, we find the 
  1386.       safest method to avoid attacks while accessing the file system 
  1387.       is to do it in a directory that is only accessible by the 
  1388.       program. If the directory can be modified by an attacker, or 
  1389.       any of its parent directories for that matter, the program may 
  1390.       be tricked into creating the wrong file. 
  1391.  
  1392.       A final note: when applying the aforementioned work around of 
  1393.       creating, checking, and deleting files, _do not_ use O_TRUNC or 
  1394.       you may wind up truncating the password database among other 
  1395.       things. 
  1396.  
  1397.       5.3) How do I delete files safely? 
  1398.       ---------------------------------- 
  1399.  
  1400.       You cannot delete files from a directory safely unless the 
  1401.       directory is writable only by the secure process. The problem 
  1402.       relates to the discussion in 5.1 regarding race conditions. 
  1403.       Since the unlink() system call requires a file name, and does 
  1404.       not accept a file descriptor, there is no way to atomically 
  1405.       delete files from the file system. 
  1406.  
  1407.       Also as mentioned in 5.2, make sure that the secure directory 
  1408.       (writable only by the secure process) is accessed from a path 
  1409.       that does not contain any symbolic links. 
  1410.  
  1411.       5.4) Is chroot() safe? 
  1412.       ---------------------- 
  1413.  
  1414.       chroot() only limits the file system scope and nothing else. 
  1415.       This means that the process will not have access to files 
  1416.       outside of its root file system; however, it does have access 
  1417.       to the kernel, and all the system calls any other process has 
  1418.       access to. 
  1419.  
  1420.       This can lead to complications. Consider the attacks mentioned 
  1421.       in the "Process Interaction" section. If a process has the same 
  1422.       real user ID as another process it can hijack it via ptrace() 
  1423.       on certain BSD derived operating systems that allow ptrace() 
  1424.       without consent from the targeted process. Same goes for 
  1425.       kill(), setpriority(). Thus the process, even if not privileged 
  1426.       may still break out of the chroot() environment. Other attacks 
  1427.       include mknod(), but need root privileges. The aforementioned 
  1428.       attacks do not. What this boils down to is that the root 
  1429.       directory is only checked by the file system calls, and not 
  1430.       other system calls. 
  1431.  
  1432.       The chroot() call itself will only change the root file system 
  1433.       in the process' context. A chroot() call must be followed by a 
  1434.       chdir("/") call in order to reset the current working 
  1435.       directory. 
  1436.  
  1437.       Here are a list of recommended guidelines to make sure the 
  1438.       chroot() environment is indeed a "jail". I may have missed some 
  1439.       items, especially those that may pertain to more exotic UNIX 
  1440.       flavors. 
  1441.  
  1442.           Credentials and Privileges 
  1443.           -------------------------- 
  1444.  
  1445.           The chrooted process should not run with root credentials, 
  1446.           or have any special privileges. It should also not share 
  1447.           credentials with any other process outside of the chrooted 
  1448.           environment. If it does share credentials it will be able 
  1449.           to send signals and possibly even ptrace() other processes. 
  1450.           Other attacks may exist such as setpriority() etc. By 
  1451.           segregating the credentials, the process will not be able 
  1452.           to pass credential checks when making use of process 
  1453.           interacting system calls. 
  1454.  
  1455.           If there exists no SUID to root process-image in the 
  1456.           chrooted environment, after calling chroot() and dropping 
  1457.           privileges, the process cannot gain root privileges without 
  1458.           breaking out of the chroot environment. It is a highly 
  1459.           recommended to do away with SUID process images completely 
  1460.           in a chroot jail. 
  1461.  
  1462.           Privileged Information 
  1463.           ---------------------- 
  1464.  
  1465.           The chrooted environment should not contain privileged 
  1466.           information. Password databases, confidential data etc. 
  1467.           should not be placed within the chrooted environment. In 
  1468.           the case of passwords, this can lead to the system being 
  1469.           compromised as a whole. 
  1470.  
  1471.           No devices should be present in the chrooted environment. 
  1472.           Especially devices that can be mounted as a file system, or 
  1473.           a Berkeley Packet Filter (BPF) device etc. 
  1474.  
  1475.         [ Send in more if I missed any. ] 
  1476.  
  1477.     6) Handling Input 
  1478.     ----------------- 
  1479.  
  1480.   This section should be read with section 2 "The Flow Of 
  1481.   Information" 
  1482.  
  1483.       6.1) What is a "buffer overrun/overflow attack" and how do I 
  1484.       avoid it? 
  1485.       
  1486.       ----------------------------------------------------------------
  1487.       
  1488.  
  1489.     The term can be misleading if one thinks about buffers filling up 
  1490.     in a modem. The problem is not lossage of data, but the ability 
  1491.     for the attacker to point the process to execute arbitrary code. 
  1492.     This FAQ will not cover the various ways of exploiting this 
  1493.     security hole, since it has become an art form in itself; 
  1494.     however, understanding how the security hole can be exploited 
  1495.     will help avoid some of the common myths circulating about work 
  1496.     arounds for it. 
  1497.  
  1498.     The traditional method is to pass a memory copying routine 
  1499.     (string copying included) data larger than the targeted memory, 
  1500.     which is usually holding data for an automatic variable (local 
  1501.     variable in a C function), and thus spilling the excess data on 
  1502.     the other local variables and eventually onto the instruction 
  1503.     stack itself. The end spillage would ideally cause a pointer on 
  1504.     the stack to point to arbitrary code, possibly held within an 
  1505.     environment variable. When the function returns, the process 
  1506.     executes the code pointed to by instruction stack. (Aleph One 
  1507.     1996). This is not the only method, among the others include 
  1508.     writing to heap memory (dynamic memory) and overwriting 
  1509.     structures such as stdio's FILE (Conover 1999). Like I said, it 
  1510.     has become an art form. 
  1511.  
  1512.     The previous paragraph was a gross over simplification, but that 
  1513.     is really the best that can be done within the scope of this FAQ. 
  1514.     The point that needs to be made is that bounds checking _must_ be 
  1515.     performed on input. Bounds checking basically means keeping track 
  1516.     of sizes and not overrunning any particular memory location with 
  1517.     more than it should hold. If the concept of bounds checking is 
  1518.     alien to you, I strongly urge you to pick up a C book. Even 
  1519.     though, by all means, the concept is not native to C alone. 
  1520.  
  1521.     Programs that do not perform bounds checking on internal data are 
  1522.     bugged. Programs that do not perform bounds checking on input are 
  1523.     insecure. Bugs cause programs to be insecure. So you want to 
  1524.     perform bounds checking always. 
  1525.  
  1526.     Obligatory warnings include: "Don't use strcpy() use strncpy()", 
  1527.     "Don't use the stdio library when receiving input that may be 
  1528.     malicious, it may be implemented without proper bounds checking." 
  1529.     Indeed, I could recite a plethora of security holes that came 
  1530.     from just this, but I'll leave the research this time as an 
  1531.     exercise for the reader. The actual principle was brought up in 
  1532.     the previous paragraphs and should be come easily to a 
  1533.     programmer. 
  1534.  
  1535.     Some myths need to be dispelled now. Not returning from a 
  1536.     function and calling exit() will not act as a work around. Heap 
  1537.     attacks can still be made, local variables can still be 
  1538.     overwritten, and most importantly your program could easily be 
  1539.     crashed by a segmentation fault signal (please don't mail in with 
  1540.     "but I can catch that signal"). Using huge buffers to copy data 
  1541.     about and expect things to magically work will not do. If you 
  1542.     find a fellow programmer using these work arounds, please lock 
  1543.     them up in a padded room till they get better. 
  1544.  
  1545.     Certain languages provide bounds checking inherently. This is a 
  1546.     good thing; however, some will argue that bounds checking at run 
  1547.     time is too costly. This is also a good thing. If you want to 
  1548.     use, and can use a language that supports bounds checking, go 
  1549.     right ahead. 
  1550.  
  1551.     In C you won't have any bounds checking unless you have a 
  1552.     compiler that is patched to support it. Oddly enough there 
  1553.     doesn't seem to be any mention in any standard that would 
  1554.     outright forbid the usage of run time bounds checking, and as 
  1555.     such there exist a patch for GCC to do just this. Richard Jones 
  1556.     and Paul Kelley, who have done just this, have a page at: 
  1557.  
  1558.     http://www-ala.doc.ic.ac.uk/~phjk/BoundsChecking.html 
  1559.  
  1560.     Other work arounds include patching the kernel to _not_ execute 
  1561.     code on the stack, which prevents some exploits but not all (heap 
  1562.     attacks etc.). Several vendors and individuals have already taken 
  1563.     this initiative. A quick search on Dejanews and even the Bugtraq 
  1564.     archives should point you in the right direction. [ If I receive 
  1565.     any submissions of URLs for patches, I will be happy to add 
  1566.     them.] 
  1567.  
  1568.     Unfortunately, this question could not be answered completely and 
  1569.     thoroughly. It is too big of an exploit, and too simple of a 
  1570.     problem, but yet so wide spread it requires awareness more than 
  1571.     anything else. See Aleph One 1997 for a similar discussion on the 
  1572.     prevention on bounds checking. 
  1573.  
  1574.     6.2) How do I hand integer values safely? 
  1575.     ----------------------------------------- 
  1576.  
  1577.   A problem reported in sshd 1.2.7 (van der Wijk 1997) allowed a 
  1578.   normal user to bind to privileged ports. The daemon read the port 
  1579.   number into a 32 bit value, and did the port privilege checks on 
  1580.   the 32-bit integer. After it was satisfied that the value is not 
  1581.   under 1024 (IPPORT_RESERVED), the daemon would then place the 
  1582.   integer into a 16-bit unsigned integer ("short" on most systems). 
  1583.   The value if over 65535 could wrap under 1024. This effectively 
  1584.   allowed a user to bind to a privileged port. The fix is to check 
  1585.   the value in its 16-bit form. Thus in sshd's case, check it in the 
  1586.   sin_port member of the struct sockaddr_in. Any checks prior to that 
  1587.   should be done with the assumption that 65535 (or negative values) 
  1588.   can overflow in the 16-bit integer and not be valid. If you don't 
  1589.   quite see why, pick up a C book and go over the way casting is done 
  1590.   between different types of varying length. 
  1591.  
  1592.   Similar problems were reported in the Linux kernel's system call 
  1593.   interface (Solar Designer 1997). 
  1594.  
  1595.   The fix, as mentioned previously, is to double check that the 
  1596.   values are the same after any conversion between types. Luckily 
  1597.   this is one of the more arcane security holes that don't pop up too 
  1598.   often. 
  1599.  
  1600.   6.3) How do I safely pass input to an external program? 
  1601.   ------------------------------------------------------- 
  1602.  
  1603. One of the biggest mistakes is to use a shell. Indeed the famous 
  1604. 'phf' security hole, a cgi program that came packaged with the NCSA 
  1605. httpd distribution, had a problem involving the use of a shell to 
  1606. execute an external program (CERT 1997). The security hole stemmed 
  1607. from a library routine it used, that was packaged with the NCSA cgi 
  1608. example distribution, called escape_shell(). The routine would take a 
  1609. command line, search for characters that would be interpreted by the 
  1610. shell, and remove them so the attacker can not invoke additional 
  1611. commands to the shell. 
  1612.  
  1613. At first glance it seems like a completely correct way to go about 
  1614. executing an external program. Escape the shell characters, and let 
  1615. the shell do the calling. It is completely and utterly wrong. In the 
  1616. rare case where you need to use a shell, a very rare and dangerous 
  1617. case, go ahead and do just that. But by removing characters you open 
  1618. yourself to a slew of mistakes. Indeed, escape_shell() forgot to 
  1619. strip certain characters that the shell would interpret. This allowed 
  1620. the attacker to send arbitrary commands to the shell. 
  1621.  
  1622. Instead of checking input for shell characters, don't use the shell 
  1623.  
  1624. Library routines such as system() and popen() invoke a shell. It is 
  1625. more secure, from the input handling perspective, to use execve() or 
  1626. one of its wrapper routines to call the process-image directly. The 
  1627. logic is that you can't mess up checking for special shell characters 
  1628. because you are not doing that. 
  1629.  
  1630. Also make sure you've read the section on process attribute 
  1631. inheritance. You may leak file descriptors as per the above mentioned 
  1632. chpass hole. 
  1633.  
  1634.  
  1635. 8) Bibliography 
  1636. --------------- 
  1637.  
  1638.   Aleph One, "Smashing the Stack For Fun And Profit" Phrack, Vol.7, 
  1639.   No. 49, Nov 1996, [ File 14 of 16 ] 
  1640.  
  1641.   Al-Herbish, Thamer "Re: More ssh fun (sshd this time)" Online 
  1642.   posting. 23 Aug. 1997. Bugtraq. 
  1643.  
  1644.   Bernstein, Dan "Secure Interprocess Communication" 1998. <URL: 
  1645.   //koobera.math.uic.edu/www/docs/secureipc.html> 
  1646.  
  1647.   Bernstein, Dan "Re: A thought on TCP SYN attacks" Online posting. 
  1648.   26 Sept. 1996. SYN-Cookies Mailing List. 
  1649.  
  1650.   Bishop, Matt "How to write a setuid program" login 12(1) Jan/Feb 
  1651.   1986. 
  1652.  
  1653.   Bishop Matt, and M. Dilger "Checking for Race Conditions in File 
  1654.   Accesses," Computing Systems 9(2) (Spring 1996) pp. 131-152. 
  1655.  
  1656.   CERT (Computer Emergency Response Team) "CERT(*) Advisory CA-96.06" 
  1657.   20 March 1996. <URL: 
  1658.   http://www.cert.org/ftp/cert_advisories/CA-96.06.cgi_example_code> 
  1659.  
  1660.   Chasin, Scott "BUGTRAQ ALERT: Solaris 2.x vulnerability" Online 
  1661.   posting. 14 Aug. 1995. Bugtraq. 
  1662.  
  1663.   Conover, Matt "w00w00 on Heap overflows" Online posting. 27 Jan. 
  1664.   Bugtraq. 
  1665.  
  1666.   daemon9, route, infinity "Project Neptune "Phrack, Vol.7, No. 48, 
  1667.   July 1996, [ File 13 of 18 ] 
  1668.  
  1669.   Der Mouse "Re: Tar "features"" Online posting. 25 Sept. 1998. 
  1670.   Bugtraq. 
  1671.  
  1672.   Eriksson, Joel "License Manager's lockfiles (Solaris 2.5.1)" Online 
  1673.   posting. 12 Oct. 1998. Bugtraq. 
  1674.  
  1675.   Hull, Gregory "r00t advisory -- sol2.5 su(1M) vulnerability" Online 
  1676.   posting. 26 Aug. 1996. 
  1677.  
  1678.   Harrison, Roger "License Manager's lockfiles (Solaris 2.5.1)" 
  1679.   Online posting. 23 Oct. 1998. Bugtraq 
  1680.  
  1681.   Jensen, Geir Inge "Another autoreply security hole" Online posting, 
  1682.   12 Mar. 1994. Bugtraq. 
  1683.  
  1684.   Network Associates Inc. "Network Associates Inc. Advisory 
  1685.   (OpenBSD)" Online posting. 10 Aug. 1998. Bugtraq. 
  1686.  
  1687.   plaguez shegget "XFree86 insecurity" Online posting. 21 Nov. 1997. 
  1688.   Bugtraq. 
  1689.  
  1690.   Saltzer, J.H., and M.D. Schroeder, "The Protection of Information 
  1691.   in Computer Systems," Proc. IEEE, Vol. 63, No. 9, Sept. 1975, pp. 
  1692.   1278-1308. 
  1693.  
  1694.   Sanfilippo, Salvatore "pingflood.c" Online posting. 9 Apr. 1998. 
  1695.   Bugtraq. 
  1696.  
  1697.   Schenk, Eric "A thought on TCP SYN attacks" Online posting. 25 
  1698.   Sept. 1996. SYN-Cookies Mailing List. 
  1699.  
  1700.   Solar Designer "Integer Overflows" Online posting. 28 Aug. 1997. 
  1701.   Bugtraq. 
  1702.  
  1703.   Stevens, Richard W. "UNIX Network Programming" New Jersey, Prentice 
  1704.   Hall, 1990. 
  1705.  
  1706.     Stevens, Richard W. "Advanced Programming In The UNIX 
  1707.     Environment" Reading, Massachusetts, Addison-Wesley, 1992. 
  1708.  
  1709.     Smith, Ben "ps(1) for freebsd." Online posting. 12 Aug. 1998. 
  1710.     Bugtraq. 
  1711.  
  1712.     Tarreau, William "Tar "features"" Online posting. 22 Sept. 1998. 
  1713.     Bugtraq. 
  1714.  
  1715.     Temmingh, Roelof W "FreeBSD rlogin and coredumps" Online posting. 
  1716.     17 Feb. 1997. Bugtraq 
  1717.  
  1718.     Wall, Larry and Schwartz, Randal L. "Programming Perl" : 
  1719.     Sebastopol, California : O'Reilly And Associates, 1992. 
  1720.  
  1721.     van der Wijk, Ivo "More ssh fun (sshd this time)" Online posting. 
  1722.     19 Aug. 1997. Bugtraq. 
  1723.  
  1724.     Zalewski, Michal "ipop3d (x2) / pine (x2) / Linux kernel (x2) / 
  1725.     Midnight Commander (x2)" Online posting. 7, March 1999. Bugtraq. 
  1726.  
  1727.   9) List of Contributors 
  1728.   ----------------------- 
  1729.  
  1730.     Thamer Al-Herbish <shadows@whitefang.com> 
  1731.  
  1732.     Peter Roozemaal <mathfox@xs4all.nl> 
  1733.  
  1734. "Youth, Nature, and relenting Jove, 
  1735. To keep my lamp _in_ strongly strove,
  1736. But Romanelli was so stout, 
  1737. He beat all three -- _and blew it out_."
  1738.  
  1739. -- George Gordon Byron "My Epitaph" From "Occasional Pieces"
  1740.  
  1741.