【问题标题】:How can I change Linux system time without root privileges?如何在没有 root 权限的情况下更改 Linux 系统时间?
【发布时间】:2018-11-23 17:56:55
【问题描述】:

我的场景如下:我有一个 C++ 应用程序,它访问无线电接收器以从中获取时间信号,然后根据无线电信号的时间更新系统时间。为安全起见,应用程序不得以 root 权限运行。在阅读了this advice from a forum thread 之后,我尝试了这样的代码 sn-p:

tm              current_time;
struct timeval *epoch         = new timeval;

// current_time is filled with time data from the radio tuner here.

epoch -> tv_sec  = mktime (&current_time);
epoch -> tv_usec = 0;

if (difftime (epoch -> tv_sec, mktime (&this -> last_system_time_update)) > (time_t) receiver::SYSTEM_TIME_UPDATE_INTERVAL) {
  retval += setgid       ((uid_t) 0);
  retval += setuid       ((uid_t) 0);
  retval += prctl        (PR_SET_KEEPCAPS, 1L, 0L, 0L, 0L);
  retval += setgid       (group_id);
  retval += setuid       (user_id);
  retval += settimeofday (epoch, NULL);
}

与建议相反,当我不以 root 身份运行它时,这个 sn-p 将不起作用。我总是得到 errno = 1。

这里有什么问题?并且:有解决方法吗?

【问题讨论】:

  • 您的进程是否设置了CAP_SYS_TIME 功能位?
  • 这是否意味着您已经遵循了为您的可执行文件提供 CAP_SYS_TIME 功能的建议?
  • 我什至没有达到可以设置系统时间上限的地步,因为第一个系统调用 (setgid) 返回 errno = 1。
  • 代码 sn-p 假定您是 root,可执行文件是 root 拥有的,设置了 SUID 位或设置了 CAP_SETUID。完全没有任何权限,您无法更改系统时间。它还保留了所有功能,而不仅仅是需要的功能。而不是在您的可执行文件上使用此代码集 CAP_SYS_TIME。

标签: c++ linux systemtime


【解决方案1】:

您仍在尝试获取 root 权限。如果你有 CAP_SYS_TIME 能力,你只需要 settimeofday()。

if (difftime (epoch -> tv_sec, mktime (&this -> last_system_time_update)) > 
(time_t) receiver::SYSTEM_TIME_UPDATE_INTERVAL) {
  retval += settimeofday (epoch, NULL);
}

【讨论】:

  • 我可以通过prctl()获得这个能力吗?
  • @Neppomuk 您使用 setcap 实用程序将程序的功能设置为 root。请参阅wiki.archlinux.org/index.php/capabilities 了解更多信息。
  • 所以我必须在执行我的应用程序之前发出以下命令:sudo setcap cap_sys_time+ep /home/jacek/autoradio 而且我只需要执行一次,因为上限存储在文件系统中。对吗?
  • 据我了解。我从来没有真正这样做过。
  • 无用:pi@autoradio:/import/valen/autoradio $ sudo setcap cap_sys_time+ep autoradio Failed to set capabilities on file autoradio'(无效参数)文件不允许使用功能参数的值。或者该文件不是常规(非符号链接)文件`
猜你喜欢
  • 2013-11-06
  • 1970-01-01
  • 2013-07-15
  • 2012-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多