- Finding setuid binaries on Linux and BSD
- Finding setuid binaries
- Why setuid?
- Finding files with setuid bit
- Exact match
- Exclude other devices/mounts
- Specific user
- Setgid bit as well
- What to do with the results?
- Remove the package
- Remove the bit
- Linux: Monitor usage with audit
- Continue reading
- How to secure a Linux system
- The Difference Between Auditing and Vulnerability Scanning
- Find Differences Between Two Daily Lynis Audits
- Logging root actions by capturing execve system calls
- Leave a Reply Cancel reply
- About Linux Audit
- Linux and UNIX security automation
- Recent Posts
- Contact
- Команда find в Linux – мощный инструмент сисадмина
- Поиск по имени
- Поиск по типу файла
- Поиск по размеру файла
- Единицы измерения файлов:
- Поиск пустых файлов и каталогов
- Поиск времени изменения
- Поиск по времени доступа
- Поиск по имени пользователя
- Поиск по набору разрешений
- Операторы
- Действия
- -delete
- Заключение
- 35 Practical Examples of Linux Find Command
- 1. Find Files Using Name in Current Directory
- 2. Find Files Under Home Directory
- 3. Find Files Using Name and Ignoring Case
- 4. Find Directories Using Name
- 5. Find PHP Files Using Name
- 6. Find all PHP Files in the Directory
- 7. Find Files With 777 Permissions
- 8. Find Files Without 777 Permissions
- 9. Find SGID Files with 644 Permissions
- 10. Find Sticky Bit Files with 551 Permissions
- 11. Find SUID Files
- 12. Find SGID Files
- 13. Find Read-Only Files
- 14. Find Executable Files
- 15. Find Files with 777 Permissions and Chmod to 644
- 16. Find Directories with 777 Permissions and Chmod to 755
- 17. Find and remove single File
- 18. Find and remove Multiple File
- 19. Find all Empty Files
- 20. Find all Empty Directories
- 21. File all Hidden Files
- 22. Find Single File Based on User
- 23. Find all Files Based on User
- 24. Find all Files Based on Group
- 25. Find Particular Files of User
- 26. Find Last 50 Days Modified Files
- 27. Find Last 50 Days Accessed Files
- 28. Find Last 50-100 Days Modified Files
- 29. Find Changed Files in Last 1 Hour
- 30. Find Modified Files in Last 1 Hour
- 31. Find Accessed Files in Last 1 Hour
- 32. Find 50MB Files
- 33. Find Size between 50MB – 100MB
- 34. Find and Delete 100MB Files
- 35. Find Specific Files and Delete
- If You Appreciate What We Do Here On TecMint, You Should Consider:
Finding setuid binaries on Linux and BSD
Finding setuid binaries
for Linux and BSD systems
Why setuid?
Binaries with the setuid bit enabled, are being executed as if they were running under the context of the root user. This enables normal (non-privileged) users to use special privileges, like opening sockets. While this seems unnecessary for a normal user, it is actually needed for simple commands like ping.
Finding files with setuid bit
To discover all files with the setuid bit, we can use the find command. Depending on the distribution, you can use some specific parameters and special options. For example on Linux you can use -perm with slash notation (e.g. /4000). This means that if any of the file permission bits match, the result will be displayed. However, this option does not work for BSD systems, like NetBSD.
Exact match
One of the best alternatives we discovered is using the -perm parameter with the octal value. However, just providing the value, would mean we have to search for the specific mode (like 4555 in the example below).
Finding setuid binaries with find command
This exact match can be useful to fix files which got incorrect permissions and are very specific. In our case this is not the case. We want all files with the setuid bit set, which means effectively “4***”. To get this type of search, we can add a dash before the octal mode. This will also match the file if the first bit is found.
As can be seen in the example, the file rcmd will match. However, instead of using -4555, we can simplify the search to -4000. The zeros tell the find command that any of the values are fine for the other permission bits. So it will also include files which have normally 755 (or 4755).
Exclude other devices/mounts
Another useful addition to discovering the right binaries, is searching from the root. We are interested in directories like /bin, /sbin and /usr/(s)bin. Since we are not interested in files from other file systems mounted below /, we can exclude those first. This is done with the -xdev parameter.
Specific user
Now we want just the files owned by the root user. Files with root as owner in combination with setuid, are executed with root privileges. All other files are not interesting. So for to be true, we add the -user root parameter.
Setgid bit as well
To complete our search, we also want to discover files which have the similar setgid bit set. This would execute files with the permission of the group. We can do this with a logical “or” statement. So we want files with the first bit to be 4 or 2.
This is one of the quickest ways to search through the file system, skipping any files which are not owned by the root user and skipping device files.
What to do with the results?
Most systems will reveal a few files with the setuid or setgid bit set. So having a few on your system is not an issue, but still room for improvement. Let’s have a look at the options:
Remove the package
Sometimes we come across files which we simply don’t need on our system.
Debian / Ubuntu: dpkg -s /path/to/binary or dpkg-query -S /path/to/binary
Red Hat based systems: rpm -qf /path/to/binary
For Debian based systems with the dpkg utility, the output looks like this:
Remove the bit
Another logical option is removing the bit from the system. For example when the system has no normal users, why allow any software to use special rights? With chmod u-s we can strip the setuid bit off the file permissions. Similarly chmod g-s will remove the setgid bit.
Linux: Monitor usage with audit
If you don’t want to alter your system yet, another option would be to add the system to a Linux audit rule. This way we can track the the usage of the file.
An example to monitor the execution of binaries is with the follow Linux audit rule:
This rule will monitor files /bin/ps and /bin/ls and trigger an event when being executed (perm=x), with the tag binaries (k=binaries). For more information about auditing with the Audit framework, have a look at our previous post:
Keep learning
So you are interested in Linux security? Join the Linux Security Expert training program, a practical and lab-based training ground. For those who want to become (or stay) a Linux security expert.
Run automated security scans and increase your defenses. Lynis is an open source security tool to perform in-depth audits. It helps with system hardening, vulnerability discovery, and compliance.
Continue reading
How to secure a Linux system
The Difference Between Auditing and Vulnerability Scanning
Find Differences Between Two Daily Lynis Audits
Logging root actions by capturing execve system calls
Leave a Reply Cancel reply
This site uses Akismet to reduce spam. Learn how your comment data is processed.
About Linux Audit
This blog is part of our mission: help individuals and companies, to scan and secure their systems. We simply love Linux security, system hardening, and questions regarding compliance.
Besides the blog, we have our security auditing tool Lynis. Open source, GPL, and free to use.
For those with enterprise needs, or want to audit multiple systems, there is an Enterprise version.
«One security solution to audit, harden, and secure your Linux/UNIX systems.»
Benefits:
- Perform audits within a few minutes
- Central management
- Powerful reporting
- Compliance checks (e.g. PCI DSS)
- Additional plugins and more tests
Enjoy the articles!
Linux and UNIX security automation
Lynis is a free and open source security scanner. It helps with testing the defenses of your Linux, macOS, and Unix systems. Typical use-cases for this software include system hardening, vulnerability scanning, and checking compliance with security standards (PCI-DSS, ISO27001, etc).
Recent Posts
Contact
This blog is part of our mission to share valuable tips about Linux security. We are reachable via @linuxaudit
Company details
CISOfy
De Klok 28,
5251 DN, Vlijmen, The Netherlands
+31-20-2260055
Источник
Команда find в Linux – мощный инструмент сисадмина
Иногда критически важно быстро найти нужный файл или информацию в системе. Порой можно ограничиться стандартами функциями поиска, которыми сейчас обладает любой файловый менеджер, но с возможностями терминала им не сравниться.
Команда find – это невероятно мощный инструмент, позволяющий искать файлы не только по названию, но и по:
- Дате добавления.
- Содержимому.
- Регулярным выражениям.
Данная команда будет очень полезна системным администраторам для:
- Управления дисковым пространством.
- Бэкапа.
- Различных операций с файлами.
Команда find в Linux производит поиск файлов и папок на основе заданных вами критериев и позволяет выполнять действия с результатами поиска.
Синтаксис команды find:
- directory-to-search (каталог поиска) – это отправной каталог, с которой find начинает поиск файлов по всем подкаталогам, которые находятся внутри. Если не указать путь, тогда поиск начнется в текущем каталоге;
- criteria (критерий) – критерий, по которым нужно искать файлы;
- action (действие) – что делать с каждым найденным файлом, соответствующим критериям.
Поиск по имени
Следующая команда ищет файл s.txt в текущем каталоге:
- . (точка) – файл относится к нынешнему каталогу
- -name – критерии по которым осуществляется поиск. В данном случае поиск по названию файла.
В данном случае критерий -name учитывает только символы нижнего регистра и файл S.txt не появиться в результатах поиска. Чтобы убрать чувствительность к регистру необходимо использовать –iname.
Для поиска всех изображений c расширением .png нужно использовать шаблон подстановки *.png:
Можно использовать название каталога для поиска. Например, чтобы с помощью команды find найти все png изображения в каталоге home:
Если выдает слишком много ошибок в отказе разрешения, тогда можно добавить в конец команды – 2> /dev/null. Таким образом сообщения об ошибках будут перенаправляться по пути dev/null, что обеспечит более чистую выдачу.
Поиск по типу файла
Критерий -type позволяет искать файлы по типу, которые бывают следующих видов:
- f – простые файлы;
- d – каталоги;
- l – символические ссылки;
- b – блочные устройства (dev);
- c – символьные устройства (dev);
- p – именованные каналы;
- s – сокеты;
Например, указав критерий -type d будут перечислены только каталоги:
Поиск по размеру файла
Допустим, что вам необходимо найти все большие файлы. Для таких ситуаций подойдет критерий -size.
- «+» — Поиск файлов больше заданного размера
- «-» — Поиск файлов меньше заданного размера
- Отсутствие знака означает, что размер файлов в поиске должен полностью совпадать.
В данном случае поиск выведет все файлы более 1 Гб (+1G).
Единицы измерения файлов:
Поиск пустых файлов и каталогов
Критерий -empty позволяет найти пустые файлы и каталоги.
Поиск времени изменения
Критерий -cmin позволяет искать файлы и каталоги по времени изменения. Для поиска всех файлов, измененных за последний час (менее 60 мин), нужно использовать -60:
Таким образом можно найти все файлы в текущем каталоге, которые были созданы или изменены в течение часа (менее 60 минут).
Для поиска файлов, которые наоборот были изменены в любое время кроме последнего часа необходимо использовать +60.
Поиск по времени доступа
Критерий -atime позволяет искать файлы по времени последнего доступа.
Таким образом можно найти файлы, к которым не обращались последние полгода (180 дней).
Поиск по имени пользователя
Опция –user username дает возможность поиска всех файлов и каталогов, принадлежащих конкретному пользователю:
Таким образом можно найти все файлы пользователя tisha в каталоге home, а 2>/dev/null сделает выдачу чистой без ошибок в отказе доступа.
Поиск по набору разрешений
Критерий -perm – ищет файлы по определенному набору разрешений.
Поиск файлов с разрешениями 777.
Операторы
Для объединения нескольких критериев в одну команду поиска можно применять операторы:
Например, чтобы найти файлы размером более 1 Гбайта пользователя tisha необходимо ввести следующую команду:
Если файлы могут принадлежать не только пользователю tisha, но и пользователю pokeristo, а также быть размером более 1 Гбайта.
Перед скобками нужно поставить обратный слеш «\».
Действия
К команде find можно добавить действия, которые будут произведены с результатами поиска.
- -delete — Удаляет соответствующие результатам поиска файлы
- -ls — Вывод более подробных результатов поиска с:
- Размерами файлов.
- Количеством inode.
- -print Стоит по умолчанию, если не указать другое действие. Показывает полный путь к найденным файлам.
- -exec Выполняет указанную команду в каждой строке результатов поиска.
-delete
Полезен, когда необходимо найти и удалить все пустые файлы, например:
Перед удалением лучше лишний раз себя подстраховать. Для этого можно запустить команду с действием по умолчанию -print.
Данное действие является особенным и позволяет выполнить команду по вашему усмотрению в результатах поиска.
- command – это команда, которую вы желаете выполнить для результатов поиска. Например:
- rm
- mv
- cp
- <> – является результатами поиска.
- \; — Команда заканчивается точкой с запятой после обратного слеша.
С помощью –exec можно написать альтернативу команде –delete и применить ее к результатам поиска:
Другой пример использования действия -exec:
Таким образом можно скопировать все .jpg изображения в каталог backups/fotos
Заключение
Команду find можно использовать для поиска:
- Файлов по имени.
- Дате последнего доступа.
- Дате последнего изменения.
- Имени пользователя (владельца файла).
- Имени группы.
- Размеру.
- Разрешению.
- Другим критериям.
С полученными результатами можно сразу выполнять различные действия, такие как:
- Удаление.
- Копирование.
- Перемещение в другой каталог.
Команда find может сильно облегчить жизнь системному администратору, а лучший способ овладеть ей – больше практиковаться.
Источник
35 Practical Examples of Linux Find Command
The Linux find command is one of the most important and frequently used command command-line utility in Unix-like operating systems. The find command is used to search and locate the list of files and directories based on conditions you specify for files that match the arguments.
find command can be used in a variety of conditions like you can find files by permissions, users, groups, file types, date, size, and other possible criteria.
Through this article, we are sharing our day-to-day Linux find command experience and its usage in the form of examples.
In this article, we will show you the most used 35 Find Commands Examples in Linux. We have divided the section into Five parts from basic to advance usage of the find command.
- Part I: Basic Find Commands for Finding Files with Names
- Part II: Find Files Based on their Permissions
- Part III: Search Files Based On Owners and Groups
- Part IV: Find Files and Directories Based on Date and Time
- Part V: Find Files and Directories Based on Size
- Part VI: Find Multiple Filenames in Linux
1. Find Files Using Name in Current Directory
Find all the files whose name is tecmint.txt in a current working directory.
2. Find Files Under Home Directory
Find all the files under /home directory with the name tecmint.txt.
3. Find Files Using Name and Ignoring Case
Find all the files whose name is tecmint.txt and contains both capital and small letters in /home directory.
4. Find Directories Using Name
Find all directories whose name is Tecmint in / directory.
5. Find PHP Files Using Name
Find all php files whose name is tecmint.php in a current working directory.
6. Find all PHP Files in the Directory
Find all php files in a directory.
7. Find Files With 777 Permissions
Find all the files whose permissions are 777.
8. Find Files Without 777 Permissions
Find all the files without permission 777.
9. Find SGID Files with 644 Permissions
Find all the SGID bit files whose permissions are set to 644.
10. Find Sticky Bit Files with 551 Permissions
Find all the Sticky Bit set files whose permission is 551.
11. Find SUID Files
Find all SUID set files.
12. Find SGID Files
Find all SGID set files.
13. Find Read-Only Files
Find all Read-Only files.
14. Find Executable Files
Find all Executable files.
15. Find Files with 777 Permissions and Chmod to 644
Find all 777 permission files and use the chmod command to set permissions to 644.
16. Find Directories with 777 Permissions and Chmod to 755
Find all 777 permission directories and use the chmod command to set permissions to 755.
17. Find and remove single File
To find a single file called tecmint.txt and remove it.
18. Find and remove Multiple File
To find and remove multiple files such as .mp3 or .txt, then use.
19. Find all Empty Files
To find all empty files under a certain path.
20. Find all Empty Directories
To file all empty directories under a certain path.
21. File all Hidden Files
To find all hidden files, use the below command.
22. Find Single File Based on User
To find all or single files called tecmint.txt under / root directory of owner root.
23. Find all Files Based on User
To find all files that belong to user Tecmint under /home directory.
24. Find all Files Based on Group
To find all files that belong to the group Developer under /home directory.
25. Find Particular Files of User
To find all .txt files of user Tecmint under /home directory.
26. Find Last 50 Days Modified Files
To find all the files which are modified 50 days back.
27. Find Last 50 Days Accessed Files
To find all the files which are accessed 50 days back.
28. Find Last 50-100 Days Modified Files
To find all the files which are modified more than 50 days back and less than 100 days.
29. Find Changed Files in Last 1 Hour
To find all the files which are changed in the last 1 hour.
30. Find Modified Files in Last 1 Hour
To find all the files which are modified in the last 1 hour.
31. Find Accessed Files in Last 1 Hour
To find all the files which are accessed in the last 1 hour.
32. Find 50MB Files
To find all 50MB files, use.
33. Find Size between 50MB – 100MB
To find all the files which are greater than 50MB and less than 100MB.
34. Find and Delete 100MB Files
To find all 100MB files and delete them using one single command.
35. Find Specific Files and Delete
Find all .mp3 files with more than 10MB and delete them using one single command.
That’s it, We are ending this post here, In our next article, we will discuss more other Linux commands in-depth with practical examples. Let us know your opinions on this article using our comment section.
If You Appreciate What We Do Here On TecMint, You Should Consider:
TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
We are thankful for your never ending support.
Источник