简体   繁体   English

从Perl脚本中删除特权?

[英]Dropping privileges from perl script?

I have a perl script running as root, and from within it I want to execute a system command bar as a lesser priveleged user foo . 我有一个以root身份运行的perl脚本,并且我希望从中以较小的特权用户foo身份执行系统命令bar So I have my system call wrapped as follows: 所以我的system调用包装如下:

sub dosys
{
        system(@_) == 0
                or die "system @_ failed: $?";
}

And so I want to say: 所以我想说:

as user foo dosys("bar")

Is there a mechanism within perl or the underlying bash shell that I can use to do this? 我可以使用perl或底层bash shell中的机制来执行此操作吗? (I would prefer one that didn't require installing an additional cpan library if possible) (如果可能的话,我希望不需要安装额外的cpan库)

The POSIX module is a Perl core module, and it includes the functions: POSIX模块是Perl核心模块,它包含以下功能:

  • setuid()
  • setgid()

and related get*id() functions, though the values are also available through special variables: 和相关的get*id()函数,尽管这些值也可以通过特殊变量获得:

  • $) and $( (effective and real GID) $)$( (有效和实际GID)
  • $< and $> (effective and real UID) $<$> (有效和实际UID)

You can also try setting those directly (per $EGID and $UID ). 您也可以尝试直接设置它们(每个$ EGID$ UID )。

system('su www-data -c whoami')
> www-data

You have to change groups first, remember to quash supplementary groups, and then change user. 您必须先更改组,记住先取消补充组,然后再更改用户。 You'll want to do this in a separate process, so that the [UG]ID changing doesn't affect privs on your root process. 您将需要在一个单独的过程中执行此操作,以使[UG] ID更改不会影响根过程中的privs。

sub su_system {
  my $acct = shift;
  my $gid = getgrnam $acct; # XXX error checking!
  my $uid = getpwnam $acct;

  if (fork) {               # XXX error checking!
    wait;
    return $? >> 8;
  }

  # -- child
  $( = $) = "$gid $gid";    # No supp. groups; see perlvar $)
  $< = $> = $uid;

  exec @_;  # XXX not as safe as exec {prog} @argv
            #     oh, and what if $acct had [ug]id zero?  darn
}

Proceed with caution. 请谨慎操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM