Sudo эффективный uid не равен 0 возможно usr bin sudo находится в файловой системе
Другой рабочий процесс - использовать драйвер «Generic PCL», поскольку принтеры eStudio не любят отправлять данные шрифта по постскриптум - драйверы PCL6XL даже будут делать цвет.
Как вы прочтете об этом ответе на SO, эта проблема не так сложна, как люди делают это. Я снова запустил команду sudo без переустановки, выполнив следующие простые шаги:
Выйти из текущего пользователя, а затем снова войти в систему с правами root. Выполнить chown root:root /usr/bin/sudo && chmod 4755 /usr/bin/sudo Выйти из системы root, а затем войти в систему как текущий пользователь.
Это делает трюк и намного быстрее и менее болезненно, чем «ядерный вариант», рекомендованный в других ответах.
В случае, если ваш пароль root не установлен. Вам нужно загрузить в Ubuntu этот ответ на SO для этого.
Конечно, это исправит sudo, но он не собирается исправлять десятки других вещей, которые были сломаны. – psusi 31 January 2015 в 00:57
Аналогичная проблема возникла в моем контейнере lxc: chown root:root /usr/lib/sudo/sudoers.so && chmod 4755 /usr/lib/sudo/sudoers.so; chown root:root /etc/sudoers; chown root:root /etc/sudoers; – infro 12 July 2016 в 08:40
используя su root вместо sudo su, а затем пароль root может сэкономить вам некоторую головную боль, если ваш ssh, или вместо того, чтобы собираться. – Brian Thomas 19 August 2016 в 04:03
в дополнение к тому, что @infro сказал, что мне также нужны chown для /etc/sudoers.d, /etc/sudoers.d/README и /var/lib/sudo – Roman Bekkiev 14 September 2016 в 11:59
перейдите в режим восстановления, продолжая нажимать Esc во время загрузки системы. выберите корневую опцию в длинном списке, который вы можете увидеть после ввода в режим восстановления (на самом деле root shell) команды типа - mount -o remount / (или в режиме восстановления вы можете нажать на параметр grub. Это помогло мне получить права на чтение и запись в файловой системе . Это в основном обновило режим чтения / записи в файловой системе, поскольку изначально команда не работала для меня). Он перемонтирует вашу файловую систему в режиме чтения и записи. command - chown -R root:root /usr эта команда изменит право собственности с «user» на root снова рекурсивно, но теперь у меня возникла проблема с командой sudo, поэтому я снова выполнил шаг 1,2,3 и выполнил chmod 4755 usr/bin/sudo
] Теперь я действительно думаю, что переустановка была бы действительно «ядерным вариантом»
Должен быть принятый ответ. Спасибо, сэр. Ты просто спаси мой день! – gvsrepins 24 November 2017 в 04:31
Была такая же проблема на моей капле в цифровом океане.
sudo: /usr/bin/sudo должен принадлежать uid 0 и установить бит setuid. Ниже приведена команда, в которой ive выполняет и перезагружается после.
Надеюсь, что это поможет.
Здесь вам не нужно -R. Как вам удалось получить разрешение на chown и chmod файлы? – Zanna 27 September 2016 в 08:02
без -R должен работать. Выполняйте команду на моей каплевой консоли. – Marvee Lou Manriquez Ventures 27 September 2016 в 10:27
К сожалению, если у вас нет полной резервной копии, возможно, самое лучшее, что вы можете сделать в этот момент, - это переустановить.
Считайте, что вы изменили все права собственности на одного пользователя, полностью запуская парадигму безопасности вашей системы .
Если вы просматриваете этот сайт, есть много подобных проблем с chmod, например, как я могу восстановить из chmod -R a-wrx / command?
Вышеуказанные методы не работали для меня, потому что я не мог «войти в систему как root» (неизвестный пароль). Но я получил корневую оболочку, отредактировав
После перезагрузки I наконец, смог запустить
Мне не удалось отредактировать файл lightdm.conf в текущей системе. Я исправил такие вещи:
boot Ubuntu live usb монтирует корневой раздел, чтобы получить доступ к /etc/lightdm/lightdm.conf при установке sudo -H gedit /mnt/etc/lightdm/lightdm.conf и добавить следующие строки из команды ответа от команды Anno2001 : [ f2] Измените обратно пользователя по умолчанию в /etc/lightdm/lightdm.conf (вы не хотите, чтобы каждый раз автолог был root, что было бы очень неуверенно и опасно), перезагрузка, и моя система снова работает отлично.
Note: When I had this issue, I had reinstalled the OS (Because at that time on-other answers exist and I can't wait more). So, Now new answers will be no longer supported from my side!
I wanted to answer this, its closed now, and IDK why. Its the oldest post I can find pertaining to this specific error message. Its important to note, that sometimes you can get this error message by adding 2 or more administrators to a single system. Another thing that can happen is that you could have change the permission of your binaries. In both of these situations, you could recieve this error message. Its important to note, that this error message comes the fundamental fsys, and not from distro specific software. From my understanding, this error is basically saying that
the sudo command is basically saying that sudo isn't owned by root anymore, which isn't the same as saying you are not the root user. In other words, many people that have answered this question misinterpret what it means. Every time I have encountered this issue its been realitivley easy to fix. Recently I changed an account name, but didn't want to delete my old account, so I just switched permissions for admin from the old account to the new account. I got really confused becuase I was getting this error, but quickly found out, its because I some how set both accounts as admin.
8 Answers 8
As you'll read on this answer on SO, this problem is not as hard as people are making it. You can get the sudo command working again without a reinstall by following these simple steps:
- Log out as the current user, then log back in as root.
- Execute chown root:root /usr/bin/sudo && chmod 4755 /usr/bin/sudo
- Log out as root, then log back in as the current user.
This does the trick and is much quicker and less painful than the "nuclear option" recommended in other answers.
If your root password is not set, you can boot in Recovery Mode to set it.
Note that this will resolve the titular error /usr/bin/sudo must be owned by uid 0 and have the setuid bit set but if like the OP you did more than mess up the permissions of the /usr/bin/sudo file, a more "nuclear" option may in fact make more sense.
If you do not have a root user, restart and press Esc to enter the grub menu. There select Advanced options for Ubuntu and select recovery mode. Then select root and you can find yourself in the root shell. If you get an error that the filesystem is in read only mode, do: mount -o remount,rw /
Had same problem in my lxc container, additionally had to do this: chown root:root /usr/lib/sudo/sudoers.so && chmod 4755 /usr/lib/sudo/sudoers.so; chown root:root /etc/sudoers; chown root:root /etc/sudoers;
using su root instead of sudo su , followed by the root password can save you some headache, if your ssh, or instead of going to grub.
in addition to what @infro said I also needed chown for /etc/sudoers.d , /etc/sudoers.d/README and /var/lib/sudo
Back up your data and reinstall.
This probably looks extreme but this isn't just sudo . You destroyed the permission structure of your entire filesystem. Some of the other answers can get sudo working, but ignoring the whole problem is inviting a later disaster.
You could try to mirror the owners off another install but there are cases ( /var/ for example) that are highly dependant on what you've actually got installed. If you want to get a scale of the problem, I've actually had a crack at helping somebody fix this sort of issue before. The fix is manual, long and could easily leave your system insecure or broken.
Picking through that mess is going to take considerably longer than a clean install.
This has had a couple of drive-bys from folks that don't understand the seriousness of the situation here. To them it looks like a big pile of unnecessary work, the sort of thing a rogue plumber or mechanic says to shake you down for a bigger job.
If you've only changed the permissions on /usr/bin/sudo , by all means, just fix that. But this question is about a total system change. Every file (save the runtime-only ones) are now owned by the user. Everything the user runs (eg browsers, browser exploits) could then overwrite system files, spy on you, extract any data. This needs to be corrected. Per above, this is difficult. The easiest way is a reinstall.
So please, don't be lazy about this. Filesystem permissions help keep you safe, fix them.
Last night I installed nodejs and did a sudo chown -R $(whoami) $(npm config get prefix)/ to allow for npm install -g without needing sudo . I was able to install the express, express-generator, and strongloop packages just fine.
This morning I went to do a pip install pdfx and got the usual message about not having permissions to /usr/local/lib/python2.7 so I tried to chown that directory and got the error:
sudo: /usr/bin/sudo must be owned by uid 0 and have the setuid bit set
sudo no longer works for any command and from what I can read there is no way to log into WSL as root to patch the sudoers file and make sure persmissions are properly set on /usr/bin/sudo.
The text was updated successfully, but these errors were encountered:
davetropeano commented Jul 5, 2016
Bingo - I found the problem.
sudo chown -R $(whoami) $(npm config get prefix)/
does not work here since the npm config is in /usr and NOT /usr/local when you install using apt-get . So. the ownership was extended to /usr/bin -- which of course impacts sudo.
ojengwa commented Mar 10, 2017
@benhillis Just ran into the same problem but on Azure (Ubuntu). Can't seems to fix it with the help I got online since the seems to depend on the sudo command.
Any helps?
PS: Sorry for calling you, sir. :)
Пользователь ch14-11
Вот мы и дошли до ещё одного распространённого совета, вместо vim использовать его ограниченную версию rvim и вот почему: Попробовав тот же способ, что использовался в самом начале для vim, получаем ошибку:
Но и тут есть лазейки… Просматривая список доступных команд, можно наткнуться на команды :python и :lua. Ограниченный от прямого исполнения команд rvim оказался не таким уж и безопасным.
Пользователь ch14-13
Тут тоже ничего сложного, поэтому просто запускаем и снова попадаем в «начало»:
garytube commented Dec 1, 2017 •
@lamirev
open cmd and set root as default
lxrun.exe /setdefaultuser root
open bash - you should be root - as root do:
chown root:root ~/usr/bin/sudo && chmod 4755 ~/usr/bin/sudo
login into your user - sudo should work now
Решение
Для этого зайдите в Rescue mode
Выберите оболочку root
Выполните команду смену пароля и введите его два раза:
Затем выполните перезагрузку системы:
Теперь зайдите в систему и переустановите sudo:
и затем снова установите
rahul-s20 commented Feb 26, 2020
First of all we will get an error which will show : “sudo /usr/bin/sudo must be owned by uid 0 and have the setuid bit set aws.
This means the sudo root permission has been over written, which creates restriction of using sudo and it leads you into problems like all the root access you lost and getting back from this situation is not a one way solution , so lets take a look and try to back track :
- Do not forget to create a back up using AMI or snapshot
- Create a totally new instance and detach the effected volume from the last instance attach it back to the newly created instance.
- Login to new instance and create a new folder in the root, and start operation as root.
- Now time to check the attached drive in new instance : “mount”…… “fdisk -l | grep Disk”.
- Create new folder in root directory : “mkdir /newfolder”
- Now mount the vol : “sudo mount /dev/xvdf1 /newfolder/”
- After mount if we check the permission we will see that the newfolder permission got changed after mounting because of the effected volume:
- Now we can change the permission of the mounted drive by default into root under root groups : “chown -R root:root newcopy/”, after the operation if we check the permision it will be root. After this permission we have to follow the same steps to change other’s permission inside the folder, newcopy/usr/bin/ : “chmod 4755 sudo”.
- After all the operation we have to detach the vol and attach that to the last volume
Пользователь ch14-1
После подключения по SSH мы попадаем на первого пользователя, и видим подсказку: «Всегда проверять sudo -l». Но для начала нужно обойти первую преграду, это rbash, который часто рекомендуют использовать для ограничения действий пользователя в командной оболочке. И действительно, с виду, он является хорошим решением, но не всегда!
Нас лишили возможности использовать ls, но мы можем отобразить содержимое любой директории используя echo:
Обычно, список бинарников разрешённых к запуску в rbash находится в так называемой домашней директории. В данном случае нам доступен vim, используя который мы можем выйти в нормальную оболочку. Запускаем vim и вводим команды:
Sudo разрешает нам запустить python, а учитывая его безграничные возможности это не совсем безопасно, и вот почему:
Вводим следующие команды:
lamirev commented Nov 23, 2017
@davetropeano Have you resolved the problem. I'm still stuck after reading the whole thread. Any other helpful information ?
benhillis commented Jul 5, 2016
In addition to the standard read / write / execute and type bits three additional bits that can be set in the files mode. The sticky bit, the set-user-id bit, and the set-group-id bit. When a file that has the set-user-id bit set is exec'ed it will inherit the uid of the file owner. For example, sudo is owned by root so it will be run as root instead of the uid of the current thread.
@davetropeano the chown -R /usr/lib/. command shouldn't have stripped this bit. Do you have an exact sequence of the commands you ran to get you into this state that I could try locally and see if we have a bug somewhere?
Пользователь ch14-5
Новый пользователь и новые ограничения:
GDB довольно мощный отладчик, и способов вызвать bash у него гораздо больше:
Первый это через встроенный Python:
Либо аналогично, как это делали с vim:
Пользователь ch14-12
script запускает новую сессию, и полностью логирует всё в указанный файл, так что просто запускаем:
vinayakmajagaonkar commented Nov 18, 2020
I had this problem on Win10 build 17763 with Ubuntu 18.04. On my Windows version there is no lxrun.exe so, adapting @garytube 's solution, I did the following:
1 - on an elevated CMD change default user to root:
ubuntu1804.exe config --default-user root2 - open bash (zsh in my case) and change ownership:
chown root:root /usr/bin/sudo && chmod 4755 /usr/bin/sudo3 - on an elevated CMD change default user back to my username
ubuntu1804.exe config --default-user [my_username]Then I could use sudo commands again! 🎉
Thanks! That worked perfectly fine. I've had ubuntu2004 as my exe.
thanos1983 commented Mar 2, 2021
I had this problem on Win10 build 17763 with Ubuntu 18.04. On my Windows version there is no lxrun.exe so, adapting @garytube 's solution, I did the following:
1 - on an elevated CMD change default user to root:
ubuntu1804.exe config --default-user root2 - open bash (zsh in my case) and change ownership:
chown root:root /usr/bin/sudo && chmod 4755 /usr/bin/sudo3 - on an elevated CMD change default user back to my username
ubuntu1804.exe config --default-user [my_username]Then I could use sudo commands again! 🎉
It might worth mentioning that on PowerShell you do not need to run it as admin, simply run it like this: ubuntu.exe config --default-user root
Once you fix the permissions on all files you can verify if the user can switch by simply run: su - . If no errors appear everything will work just fine, alternatively fix the permissions on any other dir that might appear and apply at the end: ubuntu.exe config --default-user
aseering commented Jul 5, 2016 •
"mode" is sometimes broadly defined to include "owning user". (I assume that's what @benhillis meant.)
Especially for binaries such as sudo which have the sticky bit set in their actual mode byte, which means that, regardless of which user executes them, they run as the user that owns the binary in the filesystem. (sudo is supposed to always run as root; it then checks the user who launched it and it checks what they asked to do, and it determines whether they're allowed to do it, whether they have to type a password first, etc.)
crcrewso commented Mar 15, 2017
@benhillis there is an ubuntu server in the Azure marketplace. I assume that means an Ubuntu VM running in the Azure infrastructure.
Пользователь ch14-3
Снова проверяем sudo:
На этот раз уже лучше, по умолчанию, zip только упаковывает файлы, для распаковки нужен unzip, который мы запустить не можем, или можем?
Заглянув в man по zip'у, находим там интересный параметр:
-TT cmd --unzip-command cmd
Use command cmd instead of 'unzip -tqq' to test an archive when the -T option is used. On Unix, to use a copy of unzip in the current directory instead of the standard system unzip, could use:
In cmd, <> is replaced by the name of the temporary archive, otherwise the name of the archive is appended to the end of the command. The return code is checked for success (0 on Unix)
Вот и ответ. Запускаем архивацию с последующим тестированием архива, а в качестве команды для проверки, указываем unzip, который распакует файл в текущую директорию, естественно с сохранением прав доступа:
Пользователь ch14-4
Смотрим, что ему доступно:
Ну тут всё просто, достаточно выполнить команду, описание которой можно легко найти в сети:
Пользователь ch14-14
На этот раз авторы учли ошибки, и убрали vim:
При выполнении команды, как можно догадаться появляется анимация локомотива и надпись
Но содержимое файла .passwd, требуемое по условию задания, мы так и не получили. Значит это ещё не конец.
Посмотрим список команд, которые доступны:
Не густо, однако есть несколько способов получить содержимое файла .passwd, здесь будет только 1 из них, остальные оставлю вам на самостоятельный поиск. И так, просматривая help по каждой доступной команде, находим одну из них довольно интересной:
После недолгих поисков в сети примеров её использования, находим статью, которая как раз описывает способ чтения произвольного файла в переменную окружения, используя эту команду.
Воспользовавшись советом, выполняем:
И получаем искомый пароль.
Теперь, добавляя возможность запуска какой-либо программы в файл sudoers, не поленитесь и ознакомьтесь с полным её описанием, ведь возможно именно она станет основной дырой в безопасности.
P.S. На самом деле для каждого из уровней есть своё определённое множество решений, и найти свой собственный путь будет гораздо интереснее.
Home / Linux / sudo: /usr/bin/sudo user должен принадлежать пользователю с uid 0 и иметь бит setuid.
davetropeano commented Jul 5, 2016
Thank you. It is odd though that a chown -R /usr/lib/. would modify the mode of sudo, no?
Пользователь ch14-2
И попадаем на следующего пользователя, которому доступен архиватор tar.
Казалось бы, что в этом опасного? Однако tar, как и многие другие архиваторы, позволяет упаковывать и распаковывать файл сохраняя права доступа к нему. Создадим файл shell.c следующего содержания:
Компилируем и добавляем SUID бит:
Теперь распаковываем с сохранением прав используя sudo:
В результате, после разархивирования, файл shell обретает нового владельца. В этом можно убедиться выполнив ls -ahl:
После запуска попадаем на следующий уровень:
Пользователь ch14-6
Если вы думаете: «Что можно сделать через такой простой редактор как pico», то вероятно вы не знаете про его проверку орфографии, о которой кстати написано в man'е. А сказано там следующее, что в качестве утилиты для проверки орфографии, мы можем указать всё что угодно. У нас уже есть отличный бинарник для запуска оболочки, нужно только придать ему соответствующие права. Для этого создадим файл spellbash.sh со следующим содержимым:
И запускаем pico, передав ему в качестве программы для проверки орфографии наш скрипт:
После успешной проверки орфографии и закрытия редактора, наш скрипт готов к запуску:
benhillis commented Mar 14, 2017
@ojengwa - Can you please clarify what you mean by Azure Ubuntu? Are you using Windows Subsystem for Linux?
Пользователь ch14-8
А вот это уже интересно. Однако и тут есть подводные камни. Так например, если запустить man, и в интерактивном режиме нажать "h", будет показана справка, в которой можно обнаружить вот такую запись:
Прямое исполнение команд оболочки. То что нам нужно, открываем man для любой команды, и вводим !/bin/bash:
Dutch77 commented Nov 5, 2020
Diogofgr's solution + this:
chmod 775 -R /etc/sudoers
chmod 775 -R /etc/sudoers.d/
fixed sudo for me
Пользователь ch14-10
Git так же предоставляет множество способов выполнить стороннюю команду, мы воспользуемся наиболее простым из них, который мы использовали с man:
Далее вводим !/bin/bash и попадаем на следующего пользователя:
hltdev8642 commented Jul 15, 2021
I had this problem on Win10 build 17763 with Ubuntu 18.04. On my Windows version there is no lxrun.exe so, adapting @garytube 's solution, I did the following:
1 - on an elevated CMD change default user to root:
ubuntu1804.exe config --default-user root
2 - open bash (zsh in my case) and change ownership:
chown root:root /usr/bin/sudo && chmod 4755 /usr/bin/sudo
3 - on an elevated CMD change default user back to my username
ubuntu1804.exe config --default-user [my_username]
Then I could use sudo commands again! 🎉
It might worth mentioning that on PowerShell you do not need to run it as admin, simply run it like this: ubuntu.exe config --default-user root
Once you fix the permissions on all files you can verify if the user can switch by simply run: su - . If no errors appear everything will work just fine, alternatively fix the permissions on any other dir that might appear and apply at the end: ubuntu.exe config --default-user
this worked for me so thank you :] , however I did have to change it a little:
on an elevated cmd prompt: wsl.exe -u root
chown root:root /usr/bin/sudo && chmod 4755 /usr/bin/sudo
This was nice because then you don't have to mess at all with the default user (and it seemed to work just the same)
Всем доброго времени суток, в этой статье постараюсь описать некоторые способы обхода ограничений на исполнение команд в ОС Linux, советы по использованию которых можно часто встретить на различных форумах. Демонстрация будет проведена на примере задания Restricted shells с сайта Root-Me. Итак, начнём.
robertqian-tech commented Dec 13, 2019
Diogofgr's solution works for me. Thank you so much
diogofgr commented Mar 7, 2019 •
I had this problem on Win10 build 17763 with Ubuntu 18.04. On my Windows version there is no lxrun.exe so, adapting @garytube 's solution, I did the following:
1 - on an elevated CMD change default user to root:
ubuntu1804.exe config --default-user root
2 - open bash (zsh in my case) and change ownership:
chown root:root /usr/bin/sudo && chmod 4755 /usr/bin/sudo
3 - on an elevated CMD change default user back to my username
ubuntu1804.exe config --default-user [my_username]
Then I could use sudo commands again! 🎉
Пользователь ch14-9
Так как прав выполнить подключение к внешнему серверу у нас нет, то нужен способ выполнить команду, ещё до установки соединения. И такая возможность есть, воспользуемся советом, описанным тут:
Пользователь ch14-7
Ну комментировать все последствия предоставления доступа к копированию файлов по сети не нужно, однако так как доступа в сеть у нас нет, то запустив man, узнаём следующее:
-S program — Name of program to use for the encrypted connection. The program must understand ssh(1) options.
Ок, действия аналогичны прошлому уровню:
Проблема
При запуске команды с привелигерованными правами судо, возникает ошибка:
benhillis commented Jul 5, 2016
@davetropeano Good catch, that definitely looks like what caused this.
Добавить комментарий Отменить ответ
Эта простая однострочная программа для Powershell выведет текущее время работы вашего компьютера. Вывод показан в несколько столбцов, но может быть выведен и в одну строку. PS C:\Users\Windows 11> (get-date) - (gcim Win32_OperatingSystem).LastBootUpTime Days : 0 Hours : 0 Minutes : 41 Seconds : 27 Milliseconds : 915 Ticks : 24879150105 TotalDays : 0.0287953126215278.
Ошибка 504 gateway time-out возникает тогда, когда Nginx не может получить ответ от службы достаточно долго. Например, от PHP-FPM. Nginx и PHP-FPM Наиболее распространенной причиной этой ошибки является совместная работа Nginx и PHP-FPM. В случае очень медленных PHP-скриптов Nginx выдает тайм-аут шлюза 504, когда не ожидает ответа в течение 30 секунд (по умолчанию). Чтобы избавиться.
17 сентября 2021 года произошло событие, всколыхнувшее кинематографический мир. На платформе Netflix появился корейский сериал “Игра в кальмара”. Всего пары недель ему хватило для того, чтобы выйти на первые позиции по популярности не только на Родине, но и в Соединенных Штатах, России. Оценить сюжет сериал можно не только просмотром, но и игрой squid game challenge скачать которую.
Читайте также: