在符号链接-C的情况下安全地更新文件



我想知道是否有人能帮我做这件事,我正试图弄清楚如何处理检查时间、使用时间问题以及在不需要时删除权限,例如,如果它是指向文件的符号链接,可以更改为影子文件。假设在调用进程以提升的权限运行时调用了下面的函数。

int
updatefile(char *file)
{
  int fd;
  if (access(file, R_OK|W_OK)) {
    perror("access()");
    return (-1);
  }
  fd = open(file, O_RDWR);
  /*
   * file is written to here.
   */
  printf("Updated %s on...n", file);
  system("date");
  /*
   * elevated privileges are required here...
   */
  return (0);
}

假设您的access函数检查文件类型并确定用户是否具有操作文件的适当权限,则您担心在对access的调用和对open的调用之间可能出现TOCTTOU错误。

避免这种情况的典型方法是:

int updatefile(char *file)
{
    int   fd = -1;
    if(-1 != (fd = open(file, R_OK | W_OK)))
    {
         struct stat buf;
         if(0 == fstat(fd, &buf))
         {
             /* perform any necessary check on the here */
             /* do what ever else you need to do */
             /* write to the file here */
             /* gain elevated permissions here */
             /* do privileged task */
             /* drop back to normal permissions here */
             close(fd);
         }
         else
         {
             /* handle error stating the file */
         }
    }
    else
    {
         /* handle error for not opening file */
    }
}

这样做的原因是,我们推迟对文件进行任何检查,直到我们获得文件的"句柄"之后。我们可以通过外部else块中errno的值来判断用户是否没有打开文件的权限;

如果我们能够获得文件的"句柄",那么我们就可以进行我们想要的任何检查。因为我们从打开文件到执行检查,再到使用文件,都要维护"句柄";恶意软件将无法在检查和使用之间修改文件系统。

希望这能有所帮助T.

最新更新