renameat2函数RENAME_EXCHANGE参数使用

renameat(2)

NAME

rename, renameat- change the name of a file

SYNOPSIS

#include <stdio.h>
int rename(const char *old, const char *new);
int renameat(int fromfd, const char *old, int tofd, const char *new);
int renameat2(int olddir, const char *oldname, int newdir, const char *newname, unsigned int flags);

DESCRIPTION

rename()函数的作用是修改文件名。旧参数指向要重命名的文件的路径名。new参数指向文件的新路径名。

renameat2这个系统调用与renameat()的不同之处在于它有新的flags参数;如果flags为0,则renameat2()的行为与renameat()完全相同。反之,如果flags包含RENAME_EXCHANGE,则不会删除位于newname的现有文件,相反,它将被重命名为oldname。因此,有了这个标志,可以使用renameat2()原子地交换两个文件。renameat2()的主要用例是支持联合文件系统,通常希望用表示已删除的“whiteouts”自动替换文件或目录。我们也可以想象其他的可能性;Miklos建议用符号链接代替目录作为其中的一个。

举例:

[root@node115 ~]# vim exp.c
#define _GNU_SOURCE
#include <stdio.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/syscall.h>
#include <linux/fs.h>

// source https://github.com/sroettger/35c3ctf_chals/blob/master/logrotate/exploit/rename.c
int main(int argc, char *argv[]) {
  while (1) {
    syscall(SYS_renameat2, AT_FDCWD, argv[1], AT_FDCWD, argv[2], RENAME_EXCHANGE);
    sleep(5000);
  }
  return 0;
}
[root@node115 ~]# gcc exp.c -o exp
交换两个目录的软连接的inode:
执行exp将两个软连接交换之后,可以看到两个软连接的inode号对换了,指向的实际目录也对换了,但是软连接的名称没有变,其实也可以对目录进行交换,但是只能是本地目录,共享服务目录不能交换。
root@node115:~/inode_test# ls -li
total 32
148372 -rw-r--r-- 1 root root    5 Apr 27 09:02 aaaa
148373 -rw-r--r-- 1 root root    5 Apr 27 09:02 bbbb
148374 drwxr-xr-x 2 root root 4096 Apr 27 09:02 dir1
148380 lrwxrwxrwx 1 root root    4 Apr 27 09:06 dir1_link -> dir1
148376 drwxr-xr-x 2 root root 4096 Apr 27 09:02 dir2
148381 lrwxrwxrwx 1 root root    4 Apr 27 09:07 dir2_link -> dir2
148379 -rwxr-xr-x 1 root root 8496 Apr 27 09:02 exp
148378 -rw-r--r-- 1 root root  404 Apr 27 09:02 exp.c
root@node115:~/inode_test# ./exp dir1_link dir2_link
^C
root@node115:~/inode_test# ls -li
total 32
148372 -rw-r--r-- 1 root root    5 Apr 27 09:02 aaaa
148373 -rw-r--r-- 1 root root    5 Apr 27 09:02 bbbb
148374 drwxr-xr-x 2 root root 4096 Apr 27 09:02 dir1
148381 lrwxrwxrwx 1 root root    4 Apr 27 09:07 dir1_link -> dir2
148376 drwxr-xr-x 2 root root 4096 Apr 27 09:02 dir2
148380 lrwxrwxrwx 1 root root    4 Apr 27 09:06 dir2_link -> dir1
148379 -rwxr-xr-x 1 root root 8496 Apr 27 09:02 exp
148378 -rw-r--r-- 1 root root  404 Apr 27 09:02 exp.c

交换两个文件的inode:
root@node115:~/inode_test# cat aaaa
bbbb
root@node115:~/inode_test# cat bbbb
aaaa
root@node115:~/inode_test# ls -li aaaa bbbb
148372 -rw-r--r-- 1 root root 5 Apr 27 09:02 aaaa
148373 -rw-r--r-- 1 root root 5 Apr 27 09:02 bbbb
root@node115:~/inode_test# ./exp aaaa bbbb
^C
root@node115:~/inode_test# ls -li aaaa bbbb
148373 -rw-r--r-- 1 root root 5 Apr 27 09:02 aaaa
148372 -rw-r--r-- 1 root root 5 Apr 27 09:02 bbbb
root@node115:~/inode_test# cat aaaa
aaaa
root@node115:~/inode_test# cat bbbb
bbbb
posted @ 2022-04-28 10:13  xzy186  阅读(1057)  评论(0编辑  收藏  举报