The idea and implementation of session in CGI

Source: Internet
Author: User
Tags set cookie
For each client login, a session is generated on the server and stored as a file on the server, for example, under "/tmp.
The file starts with sess _, and a random string is added. This string is called session_id.
The content stored in the file includes:
1. User's last activity time. (To check whether the user has not performed the operation for a long time, it is deemed that the user has logged out ).
2. A random string. (Used to verify the identity of the client. This string is sent to the client as a cookie at the same time ).
3. Client IP address.
4. data to be stored. For example, the user ID and password. When a user logs in, this file is generated and the random string is sent to the client's cookie.
In the future, the hyperconnections of each page, or the session_id to be followed in FORM.
Starting from each page, you must:
1. Check for timeout.
2. verify the customer's identity by comparing the string in the cookie with the session file.
3. Compare the Client IP address and the IP address in the session file to verify the customer's identity.
4. Read data for the following programs. 5. Refresh the last activity time.
6. generate a new random string, refresh the corresponding part of the session, and send it as a cookie to the client. Because the project I am working on requires high security, I have considered more in this regard, but I know that I must
Not completely secure. If anyone finds any vulnerabilities, please let me know. Below is some of my implementation code:

Set_session () is called during login.
Start_session () is called before each page.
Kill_session () is called after logging out.
Clean_session () is used to delete expired session files. # Include <stdio. h>
# Include <stdlib. h>
# Include <time. h>
# Include <unistd. h>
# Include <sys/types. h>
# Include <sys/stat. h>
# Include <fcntl. h>
# Include <dirent. h> # define REMOTE_ADDR1 getenv ("REMOTE_ADDR ")
# Define HTTP_COOKIE getenv ("HTTP_COOKIE") char * sess_user_name;
Char * sess_user_pwd; static void print_session_error (char *);
Static void clean_session_file (); char * set_session (char * name, char * pwd)
{
Char str_now [11];
Char hash_key [17];
Char * session_id;
Time_t now; FILE * sf;
Char sfp [32]; int I, temp, r; time (& now );
/**
* Clean time out session file
*/
Clean_session_file ();

/**
* Get str_now
*/
Sprintf (str_now, "% 10d", now );/**
* Get random hash_key
*/
Srand (now );
R = rand ();
For (I = 0; I <16; I ++)
{
Srand (r );
R = rand ();
Hash_key [I] = r % 26 + 'a ';
}
Hash_key [16] = '/0 ';

/**
* Get more random session_id;
*/
Temp = rand ();
Srand (temp );
R = rand ();
Session_id = (char *) malloc (17 * sizeof (char ));
For (I = 0; I <16; I ++)
{
Srand (r );
R = rand ();
Session_id [I] = r % 26 + 'a ';
}
Session_id [16] = '/0 ';
/**
* Create session file
*/
Strcpy (sfp, "/tmp ");
Strcat (sfp, "/sess _");
Strcat (sfp, session_id); sf = fopen (sfp, "w ");
Chmod (sfp, 06777); if (sf = NULL)
{
Tc_error_page ("can't creat session file ");
}/**
* Fputs session file
*/
Fputs (str_now, SF );
Fputs ("/N", SF );
Fputs (hash_key, SF );
Fputs ("/N", SF );
Fputs (remote_addr1, SF );
Fputs ("/N", SF );
Fputs (name, SF); // sess_user_name
Fputs ("/N", SF );
Fputs (PWD, SF); // sess_user_pwd _
Fputs ("/N", SF );
Fclose (SF );/**
* Set cookie
*/
Printf ("Set-COOKIE: hash_key = % s/n", hash_key );
 
Return session_id;
} Void start_session ()
{
Int I, j, k; char * session_id;
File * SF;
Char SFP [32];
Time_t now;
Int R; char buffer [256];
Char temp [64];
Char str_time [16];
Char str_hash_key [20];
Char str_client_ip [20];
Char * str_array [6];
Sess_user_name = (char *) malloc (32 * sizeof (char ));
Sess_user_pwd = (char *) malloc (32 * sizeof (char); str_array [0] = str_time;
Str_array [1] = str_hash_key;
Str_array [2] = str_client_ip;
Str_array [3] = sess_user_name;
Str_array [4] = sess_user_pwd; session_id = cgi_val (entries, "session_id ");
/**
* Open session file
*/
Strcpy (sfp, "/tmp ");
Strcat (sfp, "/sess _");
Strcat (sfp, session_id );
Sf = fopen (sfp, "rb + ");
If (sf = NULL)
/** Can't open session file, maybe session has time out **/
{
Print_session_error ("1 ");
Exit (1 );
}
/**
* Read session var
*/
Bzero (buffer, 256 );
Fread (buffer, 1,256, sf );
For (I = 0, j = 0, k = 0; k <5 & I <strlen (buffer); I ++)
{
If (buffer [I] = '/N ')
{
Temp [j] = '/0 ';
Strcpy (str_array [k], temp );
J = 0;
K ++;
}
Else
{
Temp [j ++] = buffer [I];
}
}
/**
* Check active time
*/
Time (& now );
If (now-atoi (str_time)> atoi (parse_config_file ("session_live_time ")))
{
Print_session_error ("2 ");
Exit (1 );
}/**
* Compare client hash_key to session hash_key
*/
If (HTTP_COOKIE = "" strcmp (HTTP_COOKIE + 9, str_hash_key )! = 0)
{
Print_session_error ("3 ");
Exit (1 );
}/**
* Compare client ip to session ip
*/
If (strcmp (REMOTE_ADDR, str_client_ip )! = 0)
{
Print_session_error ("4 ");
Exit (1 );
}/**
* Refresh session active time
*/
Time (& now );
Sprintf (str_time, "% 10d/n", now );
Fseek (sf, 0, SEEK_SET );
Fputs (str_time, sf );/**
* Get new hash_key
*/
Srand (now );
R = rand ();
For (I = 0; I <16; I ++)
{
Srand (r );
R = rand ();
Str_hash_key [I] = r % 26 + 'a ';
}
Str_hash_key [16] = '/N ';
Str_hash_key [17] = '/0 ';
/**
* Refresh session hash_key
*/
Fseek (sf, 11, SEEK_SET );
Fputs (str_hash_key, sf); fclose (sf );/**
* Send cookie refresh client hash_key
*/
Printf ("Set-Cookie: hash_key = % s", str_hash_key );
} Void kill_session ()
{
Char * session_id;
Char * session_path;
Char sfp [128]; session_id = cgi_val (entries, "session_id"); strcpy (sfp, "/tmp ");
Strcat (sfp, "/sess _");
Strcat (sfp, session_id); remove (sfp );
} Void clean_session_file ()
{
DIR * pdir;
Struct dirent * ent;
Char * path;
Char * filename;
Char filepath [64];
Int fd;
Char str_time [11];
Time_t now; path = "/tmp ";
Pdir = opendir (path );
If (pdir! = NULL)
{
While (ENT = readdir (pdir ))
{
Filename = ent-> d_name;
If (strncmp (filename, "sess _", 5) = 0)
{
Strcpy (filepath, PATH );
Strcat (filepath ,"/");
Strcat (filepath, filename); FD = open (filepath, o_rdonly );
Read (FD, str_time, 10 );
Time (& now );
If (now-atoi (str_time)> atoi (parse_config_file ("session_live_time ")))
{
Remove (filepath );
}
Close (fd );
}
}
}
Closedir (pdir );
} Void print_session_error (char * n)
{
Printf ("Content-type: text/html/n ");
Printf ("Print_title ("Please log on again! ");
Printf ("Printf ("sorry, please log in again. <P>/N ");
Printf ("You have not performed the operation for a long time, and the login has timed out. Or a system error occurs. <P>/N ");
Printf ("if it is the latter, contact the administrator. /N ");
Printf ("<! -- % S --> ", N );
Printf ("</body> ");
Printf ("}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.