Compilation of network sensitive programs
UNIX systems provide programmers with many subroutines, which can access various security properties.
Some information subroutines, return file properties, actual and valid UID, GID, etc. Some subroutines can
Change some file properties. UID, GID and other handling password files and group files, and some completion of encryption and decryption.
This article mainly discusses the security of the system, the standard C library subprogram, how to write secure C procedures
And from the root angle introduction program design (subroutine that can only be called by root).
System subscriber
(1) I / O subroutine
* Creat (): Create a new file or rewrite a temporary file.
Two parameters are required: file names and access license values (8 envelopes). Such as:
Creat ("/ usr / pat / read_write", 0666) / * Establish a file with 0666 to establish a license method * /
Calling this subroutine must have a write and execution license for the creation of the created file, set
The licensing mode variable for creat () will be modified by the files set by the Umask () setting, new
The owner and group of the file are determined by the effective UID and GID.
The return value is a file descriptor for the new file.
* fstat (): See Stat ().
* Open (): Opens the file inside the C program.
There are two parameters: file path name and open mode (i, o, i & o).
If the process called this subroutine does not have the correct access to the file to be opened (including the text
Search license for all directory components on the path path will cause execution failure.
If this subroutine is called to open the unssembling file, unless the O_CREAT flag is set, call
It will not be successful. At this point, the access license of the new file is the third parameter (can be repaired by the user.
change).
When the file is turned on, change the file or the access license of the file where the file is located, does not affect
The I / O operation of the file.
* Read (): Read information from the file that has been opened and used by Open ().
It doesn't care about the access license of the file. Once the file is opened as an input, you can read from this file.
Take information.
* WRITE (): Output information to files that have been opened and used as output in Open (). as with read ()
It also doesn't care about the access license of the document.
(2) Process control
* EXEC (): including Execl (), Execv (), Execle (), Execve (), Execlp () and Execvp ()
You can copy an executable model to the storage space occupied by the calling process.
The program executed by the process will not be present, and the new program replaces its position.
This is the only way to perform a program in the UNIX system: the original copy of the program will be executed
program.
Safety Precautions:
The actual and effective UID and GID passed to Exec () not have SUID and SGID
Program.
If the programs are transferred by Exec () include SUID and SGID licenses, the valid UID and GID will be
Place the owner or group of the program.
The file establishment shield value will be passed to the new program.
All open files are passed to the new program except for the except for the exec () shutdown flag.
Use the FCNTL () subroutine to set the shutdown flag of Exec ().
* for (): It is used to build a new process. The sub-process established is the process of calling fork () (parent process)
Exactly the same copy (except for processes)
Safety Precautions:
The child process will inherit the actual and effective UID and GID of the Parent process.
The sub-process inherits the file to establish a shield value.
All open files pass to the child process.
* Signal (): Allows an accident and interrupt that the process can occur.
Two parameters are required: the subroutines to be called when the signal number and the signal occur.
The signal number is defined in Signal.h.
The subroutine to be called when the signal occurs, can be written by the user, or the value given by the system, such as: SIG_IGN
The signal will be ignored, and the SIG_DFL signal will be processed by the default method of the system.
Such as many related programs prohibited from ending interrupt information (Break and Delete), so as to avoid oneself
The user terminal is terminated.
Some signals make the core dump of the process of generating the UNIX system (the process of receiving the signal when the signal is received
The contents, sometimes important information), which can be used to disable core dumps.
(3) File properties
* Access (): Detect whether the accessibility of the specified file meets the specified access type.
Two parameters are required: the file name and the access type (integer) to be detected.
The access type is defined as follows:
0: Check if the file exists
1: Check if the executive (search)
2: Check if you can write 3: Check if you can write and execute
4: Check if you read
5: Check if you readable and executed
6: Check if readable can be writable
The meaning of these numbers is the same meaning as the number of licensing methods in the chmod command.
This subroutine uses the actual UID and GID detection file access capabilities (generally valid UID and GID
Used to check file access capabilities).
Return Value: 0: License - 1: No license.
* chmod (): Change the access method of the specified file or directory to a new license method.
Two parameters are required: file names and new access licensing methods.
* Chown (): Change the UID and GID of the owner and group of the specified file at the same time. (With the chown command is not
with).
Since this subroutine changes the owner and group of the file at the same time, the SUID of the file must be canceled.
And SGID license to prevent users from establishing the SUID and SGID programs, then run Chown () to get
People's permissions.
* Stat (): Returns the status of the file (attribute).
Need two parameters: file path name and a structural pointer, pointing to status information
s position.
The structure is defined as follows:
ST_MODE: File Type and Access Licensing Method
ST_INO: i node number
ST_DEV: ID of the device where the file is located
ST_RDEV: ID of special file
ST_nLink: File Link Number
ST_UID: File owner's UID
ST_GID: GID of the file group
ST_SIZE: File size by byte count
ST_AATIME: Last Access Time (Reading)
ST_MTIME: The final modification time (write) and the final state change
ST_CTIME: The final state modification time
Return value: 0: Success 1: Failure
* umask (): Sets the file creation of the file and its sub-process to the specified access license.
Need a parameter: new file sets the screen value.
(4) UID and GID processing
* getuid (): Returns the actual UID of the process.
* getGID (): Returns the actual GID of the process.
The above two subroutines can be used to determine who is running the process.
* getEuid (): Returns the effective UID of the process.
* getGID (): Returns the effective GID of the process.
The above two subroutines can be determined in a program to determine if it is running a user rather than running
It is useful when the user's SUID program can be called to check that the program is indeed
The user's SUID license is running.
* SetUID (): Used to change the effective UID.
For general users, this subroutine is only for SUID programs to be converted between valid and actual UIDs.
Useful (from the original UID transformed into actual UID) to protect the process is not safe hazard. In fact,
The process is no longer a SUID mode.
* setgid (): Used to change the effective GID.
2. Standard C library
(1) Standard I / O
* FOPEN (): Open a file for reading or writing, security considerations are the same as Open ().
* Fread (), getc (), fgetc (), gets (), scanf () and fscanf (): From fopen ()
Read information in the files read. They don't care about the access license of the file. This
With read ().
* fwrite (), PUT (), FPUTC (), PUTS, FPUTS (), Printf (), fprintf (): Write information
The file has been opened by FOPEN (). They are also not concerned about the access license of the file.
With Write ().
* getpass (): Reads from the terminal to 8 characters long passwords, and does not return the characters entered by the user.
Need a parameter: prompt information.
The subroutine displays the prompt information on the terminal, disable character back display function, read from / dev / tty
Let, then restore the character backup function, return the pointer to the password just knocked.
* POPEN (): Introduction will be described in (5).
(2) / etc / passwd Processing There is a set of subroutines to make the / etc / passwd file for easy access, and read the file to the entry.
Items or new entry items or updates, etc.
* getPWUID (): Get the entry item of the specified UID from the / etc / passwd file.
* getPwnam (): For the specified login name, retrieve entry items in the / etc / passwd file.
The above two subroutines returns a pointer to the Passwd structure, which is defined in
/usr/include/pwd.h is defined as follows:
Struct passwd {
Char * pw_name; / * login name * / char * pw_passwd; / * Encrypted password * /
UID_T PW_UID; / * UID * /
GID_T PW_GID; / * GID * /
Char * pw_age; / * proxy information * /
Char * pw_comment; / * Note * /
Char * pw_gecos;
Char * pw_dir; / * Main directory * /
CHAR * PW_SHELL; / * Used shell * /
}
* getPwent (), setpwent (), endpwent (): Subsequent processing for password files.
First call getPwent (), open / etc / passwd and return to the first entry item in the file
The pointer keeps the file on the file on the open state of the file.
Then call the getPwent () to return to the entry items in the password file.
Call setPWent () Re-set the pointer of the password file as the beginning of the file.
Turn off the password file after using the full port file.
* Putpwent (): Modify or add the entry item in the / etc / passwd file.
This subroutine writes the entry entry into a specified file, usually a temporary file, directly written
The file is very dangerous. It is best to make a file blockade before execution, so that the two programs cannot be written at the same time.
Document. The algorithm is as follows:
Establish an independent temporary file, ie / etc / passnnn, NNN is the PID number.
Establish a new temporary document and standard temporary file / etc / PTMP chain, if the chain failed,
Then someone is using / etc / ptmp, waiting until / etc / ptmp available or exit.
Copy / etc / passwd to / etc / ptmp, you can make any modifications to this file.
Move / etc / passwd to backup file / etc / opasswd.
Establish / etc / ptmp and / etc / passwd chain.
Disconnect / etc / passnnn and / etc / ptmp chain.
Note: The temporary file should be built in the / etc directory to ensure that the file is in the same file system.
The chain can be successful, and the temporary file will not be unsafe. In addition, if the new file already exists, even if it is built
The chain is the root user, will also fail, so that once the temporary file is successfully built,
No one can plug in interference. Of course, the program with temporary files should ensure that all
Temporary files correctly capture the signal.
(3) / etc / group processing
There is a set of information similar to the previous subroutine handling / etc / group, you must use include Include
The statement adds the /usr/include/grp.h file into its own program. This file defines Group
The structure will return the Group structure pointer by getGRNAM (), getGRGID () and getGrent ().
Deputy:
This article discusses security issues from the perspective of system administrators. System administrator is a manager of management system: start
System, stop system operation, install new software, add new users, delete old users, and complete the system
Daily business work for exhibitions and running.
Safety management
Safety management is mainly divided into four aspects:
(1) Prevent unauthorized access: This is the most important issue of computer security: people who have not been used in the system
Universal awareness, good password management (with both system administrators and users), login activities
Periodic inspections of records, users and network activities, are all critical to prevent unauthorized access.
(2) Prevent leaks: This is an important issue for computer security. Prevent authorized or unauthorized users
Mutual access to mutual important information. File system check, Su Login and report, user awareness, encryption
It is the key to prevent leakage.
(3) Prevention of users from rejecting the system: This aspect should be done by the operating system. One system
Users who should not be intentionally tried to use too much resource. Unfortunately, UNIX can't be very good.
Restrict users' use of resources, one user can use the entire disk space of the file system,
UNIX can not prevent the user from doing so. System administrators should use PS commands, accounting programs DF and DU
Periodically check the system. Isors the process of occupying the CUP and a large number of files that take up the disk.
(4) Prevent the integrity of the loss system: this security aspect is actually working in a system administrator (example
Such as: periodically backup file system, system crash run FSCK check, repair file system, when there is new
When the user detects the software that the user may cause the system to crash) and maintain a reliable operating system.
Relevant (ie, users can't recallate the system often). The rest of this article mainly involves the first two issues, and the third issue is discussed in the "Safety Checking" section.
2. Super user
Some system management commands can only be run by superuser. Super users have special users
Right, super users can read, write any files, run any programs regardless of the file access licensing method.
System administrators usually use commands: / bin / su or to enter the system with root to become a super user.
In the following article, # indicate that the command that should be knocked by the superuser must be run by the superuser, and it should be knocked into all its
His user runs a command.
3. File system security
(1) Unix file system overview
The UNIX file system is the heart part of the UNIX system, providing a list of hierarchies and files.
The system divides the disk space into a group of 1024 bytes, called block (also available 512 bytes)
For a piece, such as: SCO Xenix. Number The maximum number of blocks from 0 to the entire disk.
All blocks can be divided into four parts, and block 0 is called boot block, and the file system does not need this block; block 1 is called special
With block, special blocks contain a lot of information, including the size of the disk size and the other two parts of the whole block. From
Block 2 begins with the i-node table, and the i node table contains I nodes, the number of blocks is variable, and discussion will be made later.
The I node table is an idle memory block (data storage block), which can be used to store file content.
The logical structure and physical structure of the file are very different, the logical structure is the user knocking in the CAT command
After the files you see, the user can get a character stream that represents the contents of the file. The physical structure is actually
How to store the storage format on the disk. Users think that their files are the character stream of the frontier, but actual
The file may not be stored on the disk in the side of the disk, which is usually dispersed.
Store on the disc. However, when the user accesss the file, UNIX file system will take each block in the correct order.
Provide the logical structure of the file to the user.
Of course, there will be a table at some point in the UNIX system, telling the file system how to generate the physical structure
Convert to logical structure. This involves i node .i node is a 64-byte long table, containing the relevant one
Information for files, where there is file size, file owner, file access method, and files
Ordinary files, directory files or special documents. The most important item in the i node is the disk address table.
There are 13 blocks in this table. The top 10 blocks are the storage address of 10 pieces of the previous file. These 10 blocks can be given
A logical structure of one up to 10 blocks, the file will appear in the order in the disk address table
Take the corresponding block in turn.
What happens when the file is longer than 10? The 11th item in the disk address table gives a block number, this
The block indicated by the block contains 256 block numbers, and this method satisfies the text of up to 266 blocks.
Parts (272,384 bytes). If the file is greater than 266 blocks, the twelfth item of the disk address table gives a block number.
The block indicated by this block contains 256 blocks, and each block of the 256 blocks indicates a piece.
The block contains 256 blocks, which are used to take the content of the file. Disk address and the thirteenth index
Addressing mode is similar to the twelfth item, just a multi-level indirect index.
In this way, in the UNIX system, the maximum length of the file is 16,842,762, namely 17, 246, 988, 288.
Byte, fortunately, is the maximum length of the UNIX system (generally 1 to 2M bytes) added more practical
Restrictions, users do not unintentionally create a file with all blocks with full disk.
The way the file system converts the file name to the i node is actually quite simple. A directory is actually
Is a file containing a directory table: For each file in the directory, there is an entry item in the catalog table.
The entry item contains the file name and the I node number corresponding to the file. When the user is knocked into CAT XXX, the file system
The entry entry named XXX is found in the current directory table to get the I node number corresponding to the file XXX,
After starting the block containing the contents of the file XXX.
(2) Equipment file
Communication between Unix systems and the various devices on the system, implemented by special documents,
For programs, disk is file, modem is file, or even memory is also a file. All connected to the system
The device is in the / dev directory with a file and it corresponds to it. When you execute I / O operations on these files,
The I / O operation is converted to the actual device of the actual device by the UNIX system. For example, files / dev / mem is within the system
Save, if the CAT is actually the memory of the system in the terminal. For security, this article
The piece is unreadable to ordinary users. Because at any given time, the memory area may contain the user login port.
Make or run the password of the program, the editing buffer of a part file, the buffer may contain the ed -x command
Decrypted text, as well as users who don't want others to access all kinds of information. The files in / dev are often referred to as device files, using the ls / dev command to look at one of the system.
Some equipment:
ACUO call automatic dialer
Console System Console
DSKNN block mode operation disk partition
KMEM core memory
MEM memory
LP printer
MTO block operation tape
RDSKNN flow mode operation disk partition
RMTO flow mode operated tape
SWAP exchange area
SYSCON system terminal
TTYNN terminal port
X25 network port
and many more
(3) / etc / mknod command
Used to establish a device file. Only root can use this command to establish a device file. The parameters are text
Parts, letters C, or B represent characters special files or block special files, main device number, secondary device number. Block
Special files are devices such as tapes, and some of the disks are available in blocks. Characters Special Files
It is like a terminal, printer, modem, or any other communication with the system, one character is transmitted.
The device, including the disk drive that mimics the manifestation of the disk. The main device number specifies the system.
Subprogram (device driver), when executing I / O on the device, the system will call this driver.
When using the device driver, the secondary device number will pass to the driver (the secondary device specifies the specific disk drive.
Motors, with drives, signal line numbers, or disk partitions). Each type of device generally has its own
Exquisite drive.
The file system stores the main device number and the secondary device number in the disk address table in the i node, so no
There is disk space allocated to device files (except for the disk area occupied by I node itself). When the program is trying to set up
When you execute I / O operations on a file, the system identifies that the file is a special file and calls the master device.
The specified device driver, the secondary device number as the parameter of the calling device driver.
(4) Safety consideration
Processing the device into files, making UNIX programs independently of the device, that is, the program does not have to know
Any feature of the device used, access device does not require recording length, block size, transmission speed, network
Such information such as the agreement, all annoying details are cared for by equipment drivers, to access
Prepare, the program only needs to open the device file and use it as a normal UNIX file.
From a secure point of view, this is good, because I / O operations on any device are only
A small number of channels (ie equipment files). Users cannot access devices directly. So if you correctly set it properly
The access license for disk partitions, users can only access disks through UNIX file system. The file system has
Internal security mechanism (file license). Unfortunately, if the disk partition device is incorrect, any user
Ability to write each file in the disk partition, the process is simple: read one I node, then be magnetic
The order in which the block number in the disk address table appears, and reads the blocks indicated by these blocks.
Outside ROOT, never make the disk partition to be written to anyone. Because of the owner, file access licensing method
Some information is stored in the i node, and anyone can set up anyone as long as it has a write license that has been installed.
Who's Suid license, regardless of the owner of the file, does not have to use the chmod () command, can also avoid
Safety checks for system establishment.
The above is the same as the memory file MEM, KMEM, and the switch SWAP. These files contain
User information, a "patience" program can extract user information.
To avoid disk partitions (and other devices) readable and writable, you should use it before establishing device files
The umask command sets the file to establish a shield value.
Under normal circumstances, the terminal port on the UNIX system is writable to anyone, so that the user can
Send a message with the Write command. Although the Write command is prone to security issues, most users
I feel that the information that uses Write gets other users is very convenient, so the system will set the terminal device access license.
Set to all users.
The / dev directory should be 755 access licensing method, and it is all all of ROOT.
There is an exception of any user to read or write any users outside ROOT, that is, some programs
(Usually the database system) requires direct access to disk partition, solving the disc partition area
This program should be dedicated (not installed), and the user who should use this program,
File security will be done by the programself rather than the UNIX file system.
(5) Find command
The Find command is used to search the directory tree and perform some action on all files on the directory tree, parameters
Is a catalog table (indicating which starting point start search), one or more options can also be given, specifying each
What operations do to perform.
Find. -print will list each file of the directory tree in the current working directory. Find / -user bob -print will list all the BOB users found in the system
file.
Find / usr / bob -perm 666 -print will list all the departments under the / usr / bob directory tree
Can be 666 files. If 666 is changed to -666, all containing 666 is included.
Access licensing files (such as 777).
Find / usr / bob --Type B -PRINT will list all blocks under the / usr / bob directory tree
Part (C is a character special file).
Find / -user root -perm -4000 -exec ls -l {} /; is a more complex one
Point command, -exec command /; allows you to run specified for each file found
Command Command. If the Command contains {}, {} will be replaced by the file name found by Find.