SetUID 란? 프로세스가 실행되는 동안 그 프로세스의 주인의 권한을 임시로 쥐
어주는 기능이다. 

SetGID 란? 프로세스가 실행되는 동안 그 프로세스를 실행 시킬 수 있는  그룹의 권한을 임시로 쥐어주는 기능이다. 

Sticky-bit 란? 공용 디렉터리로 쓰기 위한 기능이다.

 

이 것들이 필요한 이유는 프로세스가 현재 사용자가 가지고 있는 권한보다 높은 수준의 권한으로의 접근을 요구할 때 파일접근 제한 때문에 기능을 제공할 수 없기 때문에 이를 해결하기 위해서이다.

 

예를 들면 passwd명령을 이용하여 비밀번호를 변경하려고 할 때, 우리는 /etc/shadow파일을 변경하게 된다. 하지만 원래대로라면 우리는 /etc/shadow 파일을 변경할 수 없다. 하지만 passwd파일에는 root 권한의 SetUID가 걸려있다. 그러므로 passwd파일을 실행하게 되면 일시적으로 root의 권한을 가질 수 있게 되어 /etc/shadow파일을 변경할 수 있게 되는 것이다.

 

 

퍼미션

파일

디렉토리

  r(read)  파일 내용 읽기 가능  ls로 디렉토리 내용확인가능

  w(write)

  파일에 저장 가능

  파일을 삭제 가능

 디렉토리를 수정 가능

  x(execution)

  파일을 실행 가능

 디렉토리에 접근가능

  s(SetUID, SetGID)

  SetUID : 파일의 소유자 권한으로 실행

  SetGID : 파일의 그룹 권한으로 실행

  t(Sticky Bit)

  공유 디렉토리로 사용

 

 -

rwx

rwx

rwx 

파일 유형

소유자권한 

그룹권한

그외사용자 

 

파일유형

  • - : 일반파일
  • b : 블록형 특수 장치파일
  • c : 문자형 특수 장치파일
  • d : 디렉토리
  • l : 심볼릭 링크 파일
  • p : 파이프파일
  • s : 소켓파일

 

퍼미션 설정방법

  • SetUID 설정 : chmod 4000 파일명
  • SetGID 설정 : chmod 2000 파일명
  • Sticky Bit 설정 : chmod 1000 파일명

 

일반 퍼미션 설정방법

  • r(read) 설정: chmod 444 파일명
  • w(write) 설정 : chmod 222 파일명
  • x(execution) 설정 : chmod 111 파일명


    cnf[출처]
     SetUID, SetGID, Sticky-bit|작성자 각종수


출처 -  http://ljsk139.blog.me/30124955081 








1. 실제예(passwd명령어)로 SetUID, SetGID 이해하기

/etc/passwd 파일은 여러 가지로 보안의 문제점을 가지고 있습니다. 패스워드를 변경하기 위해 사용하는 명령어인 passwd라는 명령어는 /bin/passwd에 명령어 형태로 존재합니다. 물론 이 명령어는 계정을 가지 사용자이면 누구나 사용가능합니다. 다음의 퍼미션을 확인해 보도록 하겠습니다.

 

패스워드 보관파일

[root@host /root]# ls -l /etc/passwd

-rw-r--r--   1 root   root  1251 Nov 29 14:55 /etc/passwd

 

패스워드변경 명령어

[root@host /root]# ls -l /usr/bin/passwd

-r-s--x--x  1 root  root  10704 Apr 15  1999 /usr/bin/passwd

 

위의 예에서 알수 있듯이 계정사용자의 정보를 보관하고 있는 파일인 passwd파일은 거의 대부분 /etc/passwd에 존재하며, 이 파일의 퍼미션은 644입니다. 즉, 누구나 읽어 볼 수는 있습니다. 단 수정가능한 사용자는 이 파일의 소유자인 root만이 가능하지만, 흔히 계정을 가진 사용자라면 누구나 이파일에 있는 자신의 패스워드를 변경가능하지 않은가? 이상하지 않습니까?

이것의 비밀은 setuid라는 것에 있습니다.

setuid를 설명하기 전에 유닉스시스템에서 명령어가 실행되는 절차를 확인해 보겠습니다.

 

2. 명령어 실행절차

일반적으로 시스템사용자가 명령어를 실행시켰을 때 명령어를 찾아서 실행시키는 경로와 절차는 다음과 같습니다.

  1. 현재 작업디렉토리에서 찾음.
  2. $PATH에서 찾음
  3. 찾은후에 실행권한 체크
  4. 권한이 있다면 실행시킨 사용자의 UID로 실행
  5. 권한이없다면 이 파일이 Setuid bit가 있는가를 확인
  6. Setuid bit가 있다면 명령어 소유주의 UID(Effective UID)로 실행

 

3. SetUID 파일 찾기

일반적으로 시스템에서 SetUID로 실행가능한 명령어는 몇 개로 제한이 되어있습니다. 이미 설정되어있는 명령어외에 새롭게 생성된 SetUID파일(명령어)가 있나를 정기적으로 체크해보셔야합니다.

다음과 같은 find 명령어로 SetUID파일을 찾아보시기 바랍니다.

[root@host /root]# find / -user root -perm -4000 -print -xdev

/bin/login
/bin/su
/bin/mount
/bin/umount
/bin/ping
/sbin/pwdb_chkpwd
/sbin/dump
/sbin/restore

그리고 /usr/bin/passwd라는 명령어의 퍼미션정보를 보면 s라는 것이 있습니다. 이것이 setuid bit입니다.

일반사용자가 자기의 패스워드를 변경하기 위해 "passwd"라는 명령어를 사용했을 때는 s라는 퍼미션(SetUID 퍼미션) 때문에 root권한으로 실행이 되는 것입니다. 따라서 /etc/passwd파일이 root소유임에도 불구하고 일반사용자가 변경이 가능하게 되는 것입니다.

그런데, 해커들은 바로 이런 SetUID퍼미션이 설정되어 있으면서 root소유로 되어있는 명령어들을 해킹에 이용하게되며 가장 대표적인 명령어가 passwd라는 명령어입니다.

즉, 다시말씀드려서 passwd라는 명령어가 실행이 될 때 root 권한으로 /etc/passwd내용을 변경하게되는데 바로 이싯점에 즉 root권한으로 실행이 되고 있을 때에 정규적인 작업만을 하게하는 것이 아니라 자기가 목적하는 악의적인 작업까지 하게 만드는 것입니다.

 

4. SetUID 파일 설정하기

일반적으로 파일퍼미션은 "chmod 777 파일이름"등과 같이 숫자로 지정하는 것이 일반적입니다.

하지만 SetUID를 지정할 때에는 이 3자리숫자앞에 SetUID퍼미션을 하나더 사용하면 됩니다.

[root@hlxsvr /imsi]# ls -l
-rw-r--r--  1 root   root        0 Oct 27 14:06 testfile

[root@hlxsvr /imsi]# chmod 4755 testfile
[root@hlxsvr /imsi]# ls -l
-rwsr-xr-x    1 root     root            0 Oct 27 14:06 testfile*

 

5. SetUID, SetGID, Sticky-bit

SetUID설정을 할 때와 마찬가지로 퍼미션의 3자리숫자앞에 2또는 1을 함께입력하면 SetGID와 Sticky-bit을 설정할 수 있습니다.

4000 : SetUID설정

2000 : SetGID설정

1000 : Sticky-bit설정

참고로 Sticky-bit설정은 대부분 /tmp 디렉토리에 설정되어 있는데, 가장 흔한 용도는 공용디렉토리로 사용하기 위한 것입니다.  즉, Sticky-bit로 설정된 디렉토리는 모든 사용자가 write가능하며 write된 파일은 그 사용자의 소유되 됩니다. Sticky-bit 때문에 가능한 것이지요. 물론 삭제할 수 있는 권한또한 root와 해당사용자만이 가능합니다.

따라서 사용자들에게 공용으로 사용될 디렉토리를 Sticky-bit로 설정해두면 이런 것들이 가능하게 됩니다.



출처 - https://www.linux.co.kr/home/lecture/?leccode=476







setuid


setuid and setgid (short for "set user ID upon execution" and "set group ID upon execution", respectively)[1] are Unix access rights flags that allow users to run an executable with the permissions of the executable's owner or group respectively and to change behaviour in directories. They are often used to allow users on a computer system to run programs with temporarily elevated privileges in order to perform a specific task. While the assumed user id or group id privileges provided are not always elevated, at a minimum they are specific.

setuid and setgid are needed for tasks that require higher privileges than those which common users have, such as changing their login password.[2] Some of the tasks that require elevated privileges may not immediately be obvious, though — such as the ping command, which must send and listen for control packets on a network interface.

setuid and setgid on executables[edit]

When an executable file has been given the setuid attribute, normal users on the system who have permission to execute this file gain the privileges of the user who owns the file (commonly root) within the created process.[2] When root privileges have been gained within the process, the application can then perform tasks on the system that regular users normally would be restricted from doing. The invoking user will be prohibited by the system from altering the new process in any way, such as by using ptraceLD_LIBRARY_PATH or sending signals to it (signals from the terminal will still be accepted, however).

While the setuid feature is very useful in many cases, its improper use can pose a security risk[2] if the setuid attribute is assigned to executable programs that are not carefully designed. Due to potential security issues,[3] many operating systems ignore the setuid attribute when applied to executable shell scripts.

The setgid attribute will allow for changing the group-based privileges within a process, like the setuid flag does for user-based privileges.

The presence of setuid executables explains why the chroot system call is not available to non-root users on Unix. See limitations of chroot for more details.

The setuid and setgid bits are normally set with the command chmod by setting the high-order octal digit to 4 for setuid or 2 for setgid. "chmod 6711 file" will set both the setuid andsetgid bits (2+4=6), making the file read/write/executable for the owner (7), and executable by the group (first 1) and others (second 1). When a user other than the owner executes the file, the process will run with user and group permissions set upon it by its owner. For example, if the file is owned by user root and group wheel, it will run as root:wheel no matter who executes the file.

Most implementations of the chmod command also support finer-grained, symbolic arguments to set these bits. This is shown in the demonstration below as the "chmod ug+s"

setuid and setgid on directories[edit]

The setuid and setgid flags, when set on a directory, have an entirely different meaning.

Setting the setgid permission on a directory ("chmod g+s") causes new files and subdirectories created within it to inherit its group ID, rather than the primary group ID of the user who created the file (the owner ID is never affected, only the group ID). Newly created subdirectories inherit the setgid bit. Thus, this enables a shared workspace for a group without the inconvenience of requiring group members to explicitly change their current group before creating new files or directories. Note that setting the setgid permission on a directory only affects the group ID of new files and subdirectories created after the setgid bit is set, and is not applied to existing entities. Setting the setgid bit on existing subdirectories must be done manually, with a command such as the following:

[root@foo]# find /path/to/directory -type d -exec chmod g+s '{}' \;

The setuid permission set on a directory is ignored on UNIX and Linux systems.[4] FreeBSD can be configured to interpret it analogously to setgid, namely, to force all files and sub-directories to be owned by the top directory owner.[5]

On systems derived from BSD, directories behave as if their setgid bit was always set, regardless of its actual value. As is stated in open(2), "When a new file is created it is given the group of the directory which contains it."

Common use examples[edit]

4700 - SUID on an executable file owned by "root"

A user named "tails" attempts to execute the file. The file owner is "root," and the permissions of the owner are executable -- so the file is executed as root.

Without SUID the user "tails" would not have been able to execute the file, as no permissions are allowed for group or others on the file. A default use of this can be seen with the /usr/bin/passwdbinary file.

-

2070 - GUID on a directory named "planets" owned by the group "doctors" and the user "root"

A user named "tails" who belongs primarily to the group "tails" but secondarily to the group "doctors" makes a new file or directory named "neptune" under the directory named "planets." The group ownership of the new file or directory named "neptune" inherits "doctors."

Without GUID the group ownership would have been "tails."

-

1077 - sticky bit on a directory named "planets" owned by the group "doctors" and the user "root"

A user named "tails" creates a file named "neptune" under the directory named "planets." A user named "knuckles" attempts to delete the file named "neptune" but he cannot, since he is not the owner.

Without sticky bit "knuckles" could have deleted the file, because the directory named "planets" allows read and write by others. A default use of this can be seen with the /tmp folder.

-

3077 - sticky bit with GUID on a directory named "planets" owned by the group "doctors" and the user "root"

A user named "tails" who belongs to the group "doctors" creates a file or directory named "neptune" inside the directory named "planets." A user named "knuckles" who also belongs to the group "doctors" cannot delete, rename, or move the file or directory named "neptune," because he is not the owner. However, if "neptune" is a file, then "knuckles" can edit it.

If sticky bit and GUID had not been set, the user "knuckles" could rename, move, or delete the file named "neptune" because the directory named "planets" allows read and write by others. Sticky bit and GUID could be combined with something such as a read-only umask or an append only attribute

Security[edit]

Developers should design and implement programs that use this bit on executables carefully in order to avoid security vulnerabilities including buffer overruns and path injection. Successful buffer-overrun attacks on vulnerable applications allow the attacker to execute arbitrary code under the rights of the process exploited. In the event that a vulnerable process uses the setuid bit to run asroot, the code will execute with root privileges, in effect giving the attacker root access to the system on which the vulnerable process is running.

Of particular importance in the case of a setuid process is the environment of the process. If the environment is not properly sanitized by a privileged process, its behavior can be changed by the unprivileged process that started it.[6] For example, GNU libc was at one point vulnerable to an exploit using setuid and an environment variable that allowed executing code from untrusted shared libraries.[7]

History[edit]

The setuid bit was invented by Dennis Ritchie[8] and included in su.[8] His employer, then Bell Telephone Laboratories, applied for a patent in 1972; the patent was granted in 1979 as patent numberUS 4135240 "Protection of data file contents". The patent was later placed in the public domain.[9]

See also[edit]



source - https://en.wikipedia.org/wiki/Setuid








Sticky bit


In computing, the sticky bit is a user ownership access right flag that can be assigned to files and directories on Unix-like systems.

When a directory's sticky bit is set, the filesystem treats the files in such directories in a special way so only the file's owner, the directory's owner, or root user can rename or delete the file. Without the sticky bit set, any user with write and execute permissions for the directory can rename or delete contained files, regardless of the file's owner. Typically this is set on the /tmp directory to prevent ordinary users from deleting or moving other users' files.

Sticky bit, as a feature, was introduced in 4.3BSD in 1986 and today it is found in most modern Unix-like systems.

History[edit]

The sticky bit was introduced in the Fifth Edition of Unix (in 1974) for use with pure executable files. When set, it instructed the operating system to retain the text segment of the program in swap space after the process exited. This speeds up subsequent executions by allowing the kernel to make a single operation of moving the program from swap to real memory. Thus, frequently-used programs like editors would load noticeably faster. One notable problem with "sticked" programs was replacing the executable (for instance, during patching); to do so required removing the sticky bit from the executable, executing the program and exiting to flush the cache, replacing the binary executable, and then restoring the sticky bit.

Currently, this behavior is only operative in HP-UX and UnixWareSolaris appears to have abandoned this in 2005.[citation needed] The 4.4-Lite release of BSD retained the old sticky bit behavior, but it has been subsequently dropped from OpenBSD (as of release 3.7) and FreeBSD (as of release 2.2.1). No version of Linux has ever supported this traditional behavior.

Usage[edit]

The most common use of the sticky bit is on directories residing within filesystems for Unix-like operating systems. When a directory's sticky bit is set, the filesystem treats the files in such directories in a special way so only the file's owner, the directory's owner, or root can rename or delete the file. Without the sticky bit set, any user with write and execute permissions for the directory can rename or delete contained files, regardless of the file's owner. Typically, this is set on the /tmp directory to prevent ordinary users from deleting or moving other users' files. This feature was introduced in 4.3BSD in 1986, and today it is found in most modern Unix-like systems.

In addition, Solaris (as of Solaris 2.5) defines special behavior when the sticky bit is set on non-executable files: those files, when accessed, will not be cached by the kernel. This is usually set on swap files to prevent access on the file from flushing more important data from the system cache. It is also used occasionally for benchmarking tests.[citation needed]

The sticky bit is also set by the automounter to indicate that a file has not been mounted yet. This allows programs like ls to ignore unmounted remote files.

Operating SystemExcerpt from man pages regarding the sticky bit's effect on files
AIX 5.2For directories, indicates that only file owners can link or unlink files in the specified directory. For files, sets the save-text attribute.[1]
Solaris 11If a regular file is not executable and has S_ISVTX set, the file is assumed to be a swap file. In this case, the system's page cache will not be used to hold the file's data. If the S_ISVTX bit is set on any other file, the results are unspecified. If a directory is writable and has S_ISVTX (the sticky bit) set, files within that directory can be removed or renamed only if one or more of the following is true (see unlink(2) and rename(2)): the user owns the file, the user owns the directory, the file is writable by the user, the user is a privileged user.[2]
HP-UX[...] prevents the system from abandoning the swap-space image of the program-text portion of the file when its last user terminates. Then, when the next user of the file executes it, the text need not be read from the file system but can simply be swapped in, thus saving time.[3]
Linux[...] the Linux kernel ignores the sticky bit on files. [...] When the sticky bit is set on a directory, files in that directory may only be unlinked or renamed by root or the directory owner or the file owner.[4]
FreeBSDThe FreeBSD VM system totally ignores the sticky bit (ISVTX) for executables. If mode ISVTX (the `sticky bit') is set on a directory, an unprivileged user may not delete or rename files of other users in that directory.[5]
IRIXIf the sticky bit, S_ISVTX, is set on a file that is a dynamic loader for an ELF executable, then when the executable is execed the old process's read only address spaces will be made available to the dynamic loader in the new process. This can improve program start up time considerably. The setting of the sticky bit on any other file has no effect.[6]
Mac OS X (Leopard)The ISVTX (the sticky bit) has no effect on executable files. All optimization on whether text images remain resident in memory is handled by the kernel's virtual memory system. A directory whose 'sticky bit' is set becomes an append-only directory, or, more accurately, a directory in which the deletion of files is restricted. A file in a sticky directory may only be removed or renamed by a user if the user has write permission for the directory and the user is the owner of the file, the owner of the directory, or the super-user. This feature is usefully applied to directories such as /tmp which must be publicly writable but should deny users the license to arbitrarily delete or rename each other's files. Any user may create a sticky directory.[7]
NetBSDThe sticky bit can be set on files, but without any effect. It is reserved for future use.[8]
OpenBSDSTICKY FILES

Historically, an executable shareable file which had the sticky bit set was not immediately discarded from swap space after execution. The kernel hoarded the text segment of the file for future reuse, thus avoiding having to reload the program. This is no longer true on modern systems; the current virtual memory system keeps track of recently used executables, making the sticky bit for files redundant. The sticky bit can still be set on files, but without any effect.

Only the superuser can set the sticky bit on a file, though the owner of the file may clear the sticky bit.

STICKY DIRECTORIES

A directory with the `sticky bit' set places restrictions on file deletion: a file in a sticky directory may only be removed or renamed by a user if the user has write permission for the directory and the user is the owner of the file, the owner of the directory, or the superuser. This feature is usefully applied to directories such as /tmp which must be publicly writable but should deny users the license to arbitrarily delete or rename each other's files.

Any user may create a sticky directory. See chmod(1) for details about modifying file modes.[9]

SCO UnixWareIf a 0410 a.out executable file has the sticky bit (mode bit 01000) set, the operating system will not delete the program text from the swap area when the last user process terminates. If a 0413 a.out or ELF executable file has the sticky bit set, the operating system will not delete the program text from memory when the last user process terminates. In either case, if the sticky bit is set the text will already be available (either in a swap area or in memory) when the next user of the file executes it, thus making execution faster.[10]

Examples[edit]

The sticky bit can be set using the chmod command and can be set using its octal mode 1000 or by its symbol t (s is already used by the setuid bit). For example, to add the bit on the directory/usr/local/tmp, one would type chmod +t /usr/local/tmp. Or, to make sure that directory has standard tmp permissions, one could also type chmod 1777 /usr/local/tmp.

To clear it, use chmod -t /usr/local/tmp or chmod 0777 /usr/local/tmp (the latter will also reset the tmp directory to standard permissions).

In Unix symbolic file system permission notation, the sticky bit is represented by the letter t in the final character-place. For instance, on Solaris 8, the /tmp directory, which by default has the sticky-bit set, shows up as:

  $ ls -ld /tmp
  drwxrwxrwt   4 root     sys          485 Nov 10 06:01 /tmp

If the sticky-bit is set on a file or directory without the execution bit set for the others category (non-user-owner and non-group-owner), it is indicated with a capital T:

  # ls -l test
  -rw-r--r--   1 root     other          0 Nov 10 12:57 test
  # chmod +t test; ls -l test
  -rw-r--r-T   1 root     other          0 Nov 10 12:57 test

See also[edit]



source - https://en.wikipedia.org/wiki/Sticky_bit









chmod


In Unix-like operating systemschmod is the command and system call which may change the access permissions to file system objects (files and directories). It may also alter special mode flags. The request is filtered by the umask. The name is an abbreviation of change mode.[1]

History[edit]

chmod command first appeared in AT&T Unix version 1.

As systems grew in number and types of users access_control_lists were added to many file systems in addition to these most basic modes to increase flexibility.

Command syntax[edit]

chmod [options] mode[,mode] file1 [file2 ...]

[2]

Usual implemented options include:

  • -R recursive, i.e. include objects in subdirectories
  • -f force, forge ahead with all objects even if errors occur
  • -v verbose, show objects processed

If a symbolic link is specified, the target object is affected. File modes directly associated with symbolic links themselves are typically never used.

To view the file mode, the ls or stat commands may be used:

$ ls -l findPhoneNumbers.sh
-rwxr-xr--  1 dgerman  staff  823 Dec 16 15:03 findPhoneNumbers.sh
$ stat -c %a findPhoneNumbers.sh
754

The rw, and x specify the read, write, and execute access, respectively. The first character of the ls display denotes the object type; a hyphen represents a plain file. This script can be read, written to, and executed by the user, read and executed by other members of the staff group and can also be read by others.

Octal modes[edit]

The chmod numerical format accepts up to four octal digits. The three rightmost digits refer to permissions for the file owner, the group, and other users. The optional leading digit (when 4 digits are given) specifies the special setuidsetgid, and sticky flags.

Numerical permissions

#Permissionrwx
7read, write and executerwx
6read and writerw-
5read and executer-x
4read onlyr--
3write and execute-wx
2write only-w-
1execute only--x
0none---

Numeric example[edit]

In order to permit all users who are members of the programmers group to update a file

$ ls -l sharedFile
-rw-r--r--  1 jsmith programmers 57 Jul  3 10:13  sharedFile
$ chmod 664 sharedFile
$ ls -l sharedFile
-rw-rw-r--  1 jsmith programmers 57 Jul  3 10:13  sharedFile

Since the setuidsetgid and sticky bits are not specified, this is equivalent to:

$ chmod 0664 sharedFile

Symbolic modes[edit]

The chmod command also accepts a finer-grained symbolic notation, which allows modifying specific modes while leaving other modes untouched. The symbolic mode is composed of three components, which are combined to form a single string of text:

$ chmod [references][operator][modes] file ...

The references (or classes) are used to distinguish the users to whom the permissions apply. If no references are specified it defaults to “all” but modifies only the permissions allowed by the umask. The references are represented by one or more of the following letters:

ReferenceClassDescription
uuserthe owner of the file
ggroupusers who are members of the file's group
oothersusers who are neither the owner of the file nor members of the file's group
aallall three of the above, same as ugo

The chmod program uses an operator to specify how the modes of a file should be adjusted. The following operators are accepted:

OperatorDescription
+adds the specified modes to the specified classes
-removes the specified modes from the specified classes
=the modes specified are to be made the exact modes for the specified classes

The modes indicate which permissions are to be granted or removed from the specified classes. There are three basic modes which correspond to the basic permissions:

ModeNameDescription
rreadread a file or list a directory's contents
wwritewrite to a file or directory
xexecuteexecute a file or recurse a directory tree
Xspecial executewhich is not a permission in itself but rather can be used instead of x. It applies execute permissions to directories regardless of their current permissions and applies execute permissions to a file which already has at least one execute permission bit already set (either user, group or other). It is only really useful when used with '+' and usually in combination with the -R option for giving group or other access to a big directory tree without setting execute permission on normal files (such as text files), which would normally happen if you just used "chmod -R a+rx .", whereas with 'X' you can do "chmod -R a+rX ." instead
ssetuid/giddetails in Special modes section
tstickydetails in Special modes section

Multiple changes can be specified by separating multiple symbolic modes with commas (without spaces).

Symbolic examples[edit]

Add write permission (w) to the group's(g) access modes of a directory,
allowing users in the same group to add files:

$ ls -ld shared_dir # show access modes before chmod
drwxr-xr-x   2 teamleader  usguys 96 Apr 8 12:53 shared_dir
$ chmod  g+w shared_dir
$ ls -ld shared_dir  # show access modes after chmod
drwxrwxr-x   2 teamleader  usguys 96 Apr 8 12:53 shared_dir

Remove write permissions (w) for all classes (a),
preventing anyone from writing to the file:

$ ls -l ourBestReferenceFile
-rw-rw-r--   2 teamleader  usguys 96 Apr 8 12:53 ourBestReferenceFile
$ chmod a-w ourBestReferenceFile
$ ls -l ourBestReferenceFile
-r--r--r--   2 teamleader  usguys 96 Apr 8 12:53 ourBestReferenceFile

Set the permissions for the user and the group (ug) to read and execute (rx) only (no write permission) on referenceLib,
preventing anyone other than the owner to add files.

$ ls -ld referenceLib
drwxr-----   2 teamleader  usguys 96 Apr 8 12:53 referenceLib
$ chmod ug=rx referenceLib
$ ls -ld referenceLib
dr-xr-x---   2 teamleader  usguys 96 Apr 8 12:53 referenceLib

Special modes[edit]

The chmod command is also capable of changing the additional permissions or special modes of a file or directory. The symbolic modes use s to represent the setuid and setgid modes, and t to represent the sticky mode. The modes are only applied to the appropriate classes, regardless of whether or not other classes are specified.

Most operating systems support the specification of special modes using octal modes, but some do not. On these systems, only the symbolic modes can be used.

Command line examples[edit]

commandexplanation
chmod a+r publicComments.txtread is added for all classes (i.e. User, Group and Others).
chmod +r publicComments.txtomitting the class defaults to all classes, but the resultant permissions are dependent on umask
chmod a-x publicComments.txtexecute permission is removed for all classes.
chmod a+rx viewer.shadd read and execute for all classes.
chmod u=rw,g=r,o= internalPlan.txtuser(i.e. owner) can read and write, group can read, Others cannot access.
chmod -R u+w,go-w docsadd write permissions to the directory docs and all its contents (i.e. Recursively) for user and deny write access for everybody else.
chmod ug=rw groupAgreements.txtUser and Group members can read and write (update the file).
chmod 664 global.txtsets read and write and no execution access for the user and group, and read, no write, no execute for all others.
chmod 0744 myCV.txtequivalent to u=rwx (400+200+100),go=r (40+ 4). The 0 specifies no special modes.
chmod 1755 findReslts.shthe 1000 specifies set sticky bit and the rest is equivalent to u=rwx (400+200+100),go=rx (40+10 + 4+1) This suggests that the script be retained in memory.
chmod 4755 SetCtrls.shthe 4 specifies set user ID and the rest is equivalent to u=rwx (400+200+100),go=rx (40+10 + 4+1).
chmod 2755 SetCtrls.shthe 2 specifies set group ID and the rest is equivalent to u=rwx (400+200+100),go=rx (40+10 + 4+1).
chmod -R u+rwX,g-rwx,o-rx PersonalStuffRecursively set a directory tree to rwx for owner directories, rw for owner files, --- (i.e. no access) for group and others.
chmod -R a-x+X publicDocsremove the execute permission on all files in a directory tree (i.e. Recursively), while allowing for directory browsing.

System call[edit]

The POSIX standard defines the following function prototype:

int chmod(const char *path, mode_t mode);

The mode parameter is a bitfield composed of various flags:

FlagOctal valuePurpose
S_ISUID04000Set user ID on execution
S_ISGID02000Set group ID on execution
S_ISVTX01000Sticky bit
S_IRUSR, S_IREAD00400Read by owner
S_IWUSR, S_IWRITE00200Write by owner
S_IXUSR, S_IEXEC00100Execute/search by owner
S_IRGRP00040Read by group
S_IWGRP00020Write by group
S_IXGRP00010Execute/search by group
S_IROTH00004Read by others
S_IWOTH00002Write by others
S_IXOTH00001Execute/search by others

Where alternate flag names are given, one of the pair of names might not be supported on some OSs. The octal values of the flags are summed or combined in a bitwise OR operation to give the desired permission mode.

The function returns an error code.

Common Errors[edit]

When you type in 'ls -l' and see bunch of question marks such as this:

ls: cannot access example/authorized_keys: Permission denied
ls: cannot access example/id_dsa: Permission denied
ls: cannot access example/id_dsa.pub: Permission denied
ls: cannot access example/id_rsa.pub: Permission denied
ls: cannot access example/id_rsa: Permission denied
ls: cannot access example/known_hosts: Permission denied
ls: cannot access example/config: Permission denied
total 0
?????????? ? ? ? ?            ? authorized_keys
?????????? ? ? ? ?            ? config
?????????? ? ? ? ?            ? id_dsa
?????????? ? ? ? ?            ? id_dsa.pub
?????????? ? ? ? ?            ? id_rsa
?????????? ? ? ? ?            ? id_rsa.pub
?????????? ? ? ? ?            ? known_hosts

this usually means that one of the parent folders does not have proper permissions set.

Unless you fix the permissions of the parent folder, commands like:

sudo chown -R me:me example
sudo chmod -R 775 example

won't work.

See also[edit]

References[edit]



source - https://en.wikipedia.org/wiki/Chmod



'System > Common' 카테고리의 다른 글

Sun Fire  (0) 2012.01.13
IBM System X  (0) 2012.01.11
디바이스 파일  (0) 2011.12.15
i-node & Directory  (0) 2011.12.15
linux - File Descriptor  (0) 2011.12.12
Posted by linuxism
,