TreeZ
TreeZ

Reputation: 147

File permissions in Linux assembly

I'm trying to get information about file permissions. I am using the sys_access system call. Here is my code snippet:

mov eax, 33 
mov ebx, fileName 
mov ecx, 1 
int 80h 

cmp eax, 0 
jl .error 

If eax is -1 there is an error, and I am not getting one, but I need to check all the permissions of the file (owner, group, others). How do I do that?

Upvotes: 1

Views: 1301

Answers (1)

rkhb
rkhb

Reputation: 14409

You can use the kernel function sys_newstat (No. 106 - look at this table) to get the file permissions. The structure stat is a never ending horror, but the following example works at least on my Debian Wheezy 64 bit (NASM, 32-bit and 64-bit modes):

SECTION .data

    filename        db '/root'          ; Just an example, can be replaced with any name
    filename_len    equ $ - filename    ; Length of filename
                    db 0                ; Terminator for `Int 80h / EAX = 106`
    perm_out        db 'Permissions: '
    perm            db 'drwxrwxrwx'
    perm_len        equ $ - perm        ; Index of last character in `perm`
    lf              db 10
    perm_out_len    equ $ - perm_out    ; Length of `Permissions: ...\n`

SECTION .bss
    stat resb 256               ; Way too much, but size is variable depending on OS

SECTION .text
global _start

_start:

    mov eax,4                   ; sys-out
    mov edx,filename_len        ; length of string to print
    mov ecx,filename            ; Pointer to string
    mov ebx,1                   ; StdOut
    int 0x80                    ; Call kernel

    mov eax,4                   ; sys-out
    mov edx,1                   ; Length of string to print
    mov ecx, lf                 ; Pointer to string
    mov ebx,1                   ; StdOut
    int 0x80                    ; Call kernel

    mov eax, 106                ; sys_newstat
    mov ebx, filename           ; Pointer to ASCIIZ file-name
    mov ecx, stat               ; Pointer to structure stat
    int 80h

    test eax, eax
    jz .noerr
    mov eax,1                   ; sys_exit
    mov ebx,1                   ; Exit code, 1=not normal
    int 0x80                    ; Call kernel
    .noerr:

    movzx eax, word [stat + 8]  ; st_mode (/usr/include/asm/stat.h)
    mov ebx, perm_len

    ; rwx bits
    mov ecx, 9
    .L1:
    sub ebx, 1
    shr eax, 1
    jc .J1
    mov byte [perm + ebx], '-'
    .J1:
    loop .L1

    ; directory bit
    sub ebx, 1
    shr eax, 6
    jc .J2
    mov byte [perm + ebx], '-'
    .J2:

    mov eax,4                   ; sys-out
    mov edx,perm_out_len        ; Length of string to print
    mov ecx,perm_out            ; Pointer to string
    mov ebx,1                   ; StdOut
    int 0x80                    ; Call kernel

    mov eax,1                   ; sys_exit
    mov ebx,0                   ; Exit code, 0=normal
    int 0x80                    ; Call kernel

Upvotes: 2

Related Questions