[Linux]file의 ownership 및 permission

공부기록·2023년 10월 20일
0
post-thumbnail

🔊 Users and Ownership


🖋️ Owner

  • 모든 file은 주로 file을 생성한 user가 소유권을 가지고있다.
  • user-id라는 uid 존재하는데 생성된 process가 이를 부여받는다.
  • 소유권의 전환 : superuser 혹은 file's owner가 가능하다.
login-id:password:uid:gid:user info:home-dir:shell
keith    : x     :35 :10 ::user    :keith    :bin/ksh
  • home-dir : 로그인할 디렉토리 경로
  • shell : 초기 쉘 프로그램 디폴트

🖋️ group

  • 유저는 하나 이상의 그룹에 속해있다.
  • /etc/group
	$ usermod -G group1,group2 user1
    $ id
    uid=509(user1) gid=509(group1) groups=509(group1),510(group2)

uid와 gid는 프로그램을 시작하는 유저의 것을 상속받는다.



🔊 Effective user and group ids


Real user-id (ruid)

  • 프로세스를 시작한 user의 uid이다.

Effective user-id (euid)

  • 특정 상황을 위하여 사용되는 uid이다.
  • file 접근 권한이 정해진다. -> euid = 0 : root권한으로 접근 불가한 것도 접근 가능



🔊 Permissions and file modes


Ownership

  • file의 접근권한을 바꿀 수 있다.
  • superuer(root,uid=0)은 그냥 바꾸기 가능

Permission

  • 접근 제어
Type of userType of file permission
userread
groupwrite
othersexecute
	ls -l /bin/vi
    -rwxr-xr-x     1    root    root    377404   Apr 2 2001  /bin/vi

- mode_t와 8진수 표현
OctalSymbol
00400S_IRUSR
00200S_IWUSR
00100S_IXUSR
00040S_IRGRP
00020S_IWGRP
00010S_IXGRP
00004S_IROTH
00002S_IWOTH
00001S_IXOTH

	S_IRUSER | S_IRGRP | S_IROTH = 0444 = r--r--r--

🔊 open과 file permission


  • 이미 존재하는 file을 open할 때
    • file을 열 때는 euid와 egid를 보고 파일에 접근이 가능한지 확인한다.
    • 만약 접근 안되면 -1을 반환하고 errono = EACCESS 이다.
    fd = open(pathname, O_RDONLY | O_CREAT | O_EXCL, 0600);
    /* 파일이 존재하면 errno = EEXIST 에러 발생으로 -1을 반환한다. */

권한 활용

	-r--r--rw- usr1 grp1 file1
    -r--rw---- usr2 grp1 file2
    -------r-- usr1 grp1 file3
    -rw-rw-rw- usr1 grp2 file4
    --w-rw---- usr2 grp2 file5
    
    -rwxrwxrwx usr1 grp1 a.out
    fd1 = open(“file1”, O_RDONLY); //usr1 read 권한 허용

    fd2 = open(“file2”, O_RDONLY); //grp1 read 권한 허용

    fd3 = open(“file3”, O_RDONLY); //usr와 grp의 read 권한 없음 -> 실패

    fd4 = open(“file4”, O_RDONLY); //usr1 read 권한 허용

    fd4 = open(“file5”, O_RDONLY); //usr와 grp이 다름 -> 실패

  • 파일 ACCESS 확인 흐름도

Extra permission for executable files

OctalSymbolMeaning
04000S_ISUIDset user-id on execution
02000S_ISGIDset group-id on execution
  • S_ISUID BIT가 설정되어있으면 권한이 없는 파일에 접근시 시스템은 그 USER에게 FILE OWNER의 USER-ID를 부여한다.


password 바꾸기

  • password 바꾸려면 /etc/shadow에 접근해야 하는데 직접적인 접근은 불가하다.
  • usr/bin/passwd를 통하여 /etc/shadow의 변경이 가능하다.
	$ ls -l /bin/passwd
    -rwsr-xr-x 1 root root 22984 날짜 /usr/bin/passwd
    $
    $ passwd
    (current) UNIX password:



🔊 The file creation mask


  • safeguarding
    • 파일 생성시 특정 bit는 자동으로 권한을 없앤다.
    • mask : 000 010 010 - group과 other의 write 권한을 제한한다.
    • 이는 mode(111 111 111)을 사용해도 자동으로 mask가 지정된 비트를 소거한다.

🔈 umask( )

  • process의 creation mask를 세팅한다.
	#include <sys/stat.h>
    mode_t umask(mode_t cmask);

  • 파일 소유자 이외의 사용자에게 쓰기 허가를 막는다.
    mode_t oldmast;
    ...
    oldmast = umask(022); 

    #include <fcntl.h>
    #include <sys/stat.h>

    int specialcreat (const char *pathname, mode_t mode){
      mode_t oldu;
      int filedes:

      /* file 생성 마스크를 0으로 설정 */
      if ( (oldu = umask(0)) ==1){
        perror ("saving old mask");
        return (-1);
      }

     /* file을 생성한다 */
     if((filedes=open(pathname, O_WRONLY|O_CREAT|O_EXCL, mode))== -1)
         perror ("opening file");

     /* 비록 개방에 실패하더라도, 과거의 file 모드를 복원한다. */
     if (umask (oldu) == -1) 
         perror ("restoring old mask");

     return filedes;
    }

🔈access( )

  • ruid와 rgid를 기반으로 접근이 가능한가의 여부를 확인한다.
	#include <unistd.h>

	int access(const char *pathname, int amode);

	/* 성공시 0, 실패시 -1을 반환한다. */
  • amode
    • R_OK, W_OK, X_OK, F_OK(존재하는 파일인지 확인한다.)
  • errno
    • EACCES : 접근 불가 오류
    • ENOENT : 파일 없음 오류
    #include <stdio.h>
    #include <stdlib.h>
    #include <unistd.h>

    main()
    {
      char *filename = "afile";

      if (access (filename, R_OK) == -1)
      {
        fprintf (stderr, "User cannot read file %s\n", filename);
        exit (1);
      }

     printf ("%s readable, proceeding\n", filename);

      /* 프로그램의 나머지 부분... */
    }

🔈 chmod( )

    #include <unistd.h>

    int chmod(const char *pathname, mode_t newmode);

    /* 성공시 0, 실패시 -1을 반환한다. */
    if( chmod(pathname, 0644) == -1 )
        perror(“call to chmod failed”);

🔈 chown( )

  • 내 file 혹은 root일 때, user-id와 group-id를 변경한다.
#include <unistd.h>

int chown(const char *pathname, uid_t owner_id, gid_t group_id);

/* 성공시 0, 실패시 -1을 반환한다. */
  • owner-id : new owner

  • group-id : new group

  • errno EPERM : 파일 소유자 변경시 일어날 수 있는 오류

  • set-user-id와 set-group-id 권한은 소유주가 바뀌면 비트세팅을 0으로 되돌린다.



🔊 File system

  • disk와 같은 저장소에 파일을 논리적으로 저장하는 소프트웨어이다.
  • root를 최상위로 둔 계층구조를 가지고 파일을 관리한다.

mount-on

  • 디렉토리는 mount file system에 속한다.
  • mount table & vfs list

UNIX file system

  • boot block : 부팅시 시작하는 code
  • super block : filesystem의 전체정보
    • number of blocks, inode free list속 inode갯수, free block 비트맵개수, block 사이즈, free block 개수, 사용중인 block 개수
  • i nodes : 디스크에 존재하는 모든 파일은 i-node와 연관되며 이는 파일에 고유하다.
  • data block : 저장된 file blocks에 대한 정보

🔊 i-node

  • 각 파일들은 하나의 i-node를 이용하며 적어도 하나의 디렉토리와 link되어있다.
  • i node 0은 i-node가 없다, 1은 잘못된 disk에 저장되었단 뜻으로 사용하지 않는다.
  • i-node 2는 root에 할당되어있다.

  • file을 직접적으로 가르키는 포인터이다.
  • link count는 해당 i-node를 몇개의 디렉토리가 가르키는지에 대한 개수이다.
  • link count의 값이 0이되면 file은 삭제된다.
  • super user만 hard link를 생성할 수 있다.
  • filesystem 제한이 존재한다.
  • i-node는 같고 file이름은 다를 수 있다. file은 같은 file이다.
	$ ln  /dirA/name1  /dirB/name2
    $ ls -i /dirA/name1 /dirB/name2
    12345 /dirA/name1
    12345 /dirB/name2
  • file을 간접적으로 가르키는 포인터이다.
  • 바로가기의 개념과 유사하다.
  • link count의 증가는 없다.
  • 둘은 다른 i-node를 가지고 있으며 path를 가지고있다.
  • filesystem 제한이 없다.
	$ ln -s /dirA/name1  /dirB/name2
    lrwxrwxrwx  1  root  root  날짜   name -> dirA/name
	#include <unistd.h>

	int link(const char *orginal_path, const char *new_path);
	
    /* 성공시 0, 실패시 -1을 반환한다. */
  • 새로운 디렉토리를 생성하고 hard link를 생성하며 link count를 하나 증가시킨다.
  • 두 개의 pathname은 같은 file system 내에 존재해야한다.
	link(/usr/keith/chap.2,/usr/ben/2.chap”);
	#include <unistd.h>

	int unlink(const char *pathname);
	
    /* 성공시 0, 실패시 -1을 반환한다. */
  • 존재하는 디렉토리 entry를 제거한다.
  • 다른 link가 존재할 경우 그 link를 통하여 접근가능하다.
  • link count가 0이되면 dist가 free block list를 추가한다.
  • unlink permision ? dir(file)의 write permission이 필요하다.

  • 한 파일을 하나의 경로이름으로부터 다른 경로 이름으로 올린다.
    #include <stdlib.h>
    #include <stdio.h>
    #include <unistd.h>

    char *usage = "usage: move file1 file2\n";

    main (int argc, char **argv){
     if (argc != 3){
             fprintf (stderr, usage); exit (1);
     }

     if ( link (argv[1], argv[2]) == -1){
        perror ("link failed");
        exit (1);
     }

     if ( unlink(argv[1]) == -1){
        perror ("unlink failed");
        unlink (argv[2]);
        exit (1);
     }
     printf ("Succeeded\n");
    }

🔈 remove ( )

  • file의 unlink이다, file을 삭제한다.
	#include <stdio.h>

	int remove(const char *pathname);
	
    /* 성공시 0, 실패시 -1을 반환한다. */

🔈 rename( )

  • file과 directory의 이름을 재정의한다.
	#include <stdio.h>

	int rename(const char *oldname, const char *newname);
	
    /* 성공시 0, 실패시 -1을 반환한다. */
  • 뭐지 이부분 어디갔지, symbolic link 관련이었을 듯



🔊 File Information

🔈 stat( )

    #include <sys/stat.h>

    int stat(const char *pathname, struct stat *buf);

    int fstat(int filedes, struct stat *buf);

    int lstat(const char *pathname, struct stat *buf);

    /* 성공시 0, 실패시 -1을 반환한다. */
  • stat : namaed file
  • fstat : open file
  • lstat : sysmbolic link

- buf
    struct stat {
           mode_t    st_mode;    /* file type & mode (permissions) */
           ino_t     st_ino;     /* i-node number (serial number) */
           dev_t     st_dev;     /* device number (file system) */
           dev_t     st_rdev;    /* device number for special files */
           nlink_t   st_nlink;   /* number of links */
           uid_t     st_uid;     /* user ID of owner */
           gid_t     st_gid;     /* group ID of owner */
           off_t     st_size;    /* size in bytes, for regular files */
           time_t    st_atime;   /* time of last access */
           time_t    st_mtime;   /* time of last modification */
           time_t    st_ctime;   /* time of last file status change */
           blksize_t st_blksize; /* best I/O block size */
           blkcnt_t  st_blocks;  /* number of disk blocks allocated */
         };

0개의 댓글

관련 채용 정보