Можно ли сказать, что процессы (с подпроцессами или без них) полностью отражены в их (описательных) файлах?

379
JohnDoea

Можно ли сказать, что целая «серия» файлов в процессе (как представлено соответственно файловыми дескрипторами) напрямую отражает этот процесс и возможные его подпроцессы, так что при соответствующем взгляде на файлы, описанные файловыми дескрипторами, можно расскажите нам точную природу процесса и возможные подпроцессы?

Другими словами, если вы посмотрите на каждый файл (представленный файловыми дескрипторами в соответствующем порядке, например, 0-X), он скажет вам природу процесса или / и подпроцессов?

Я полагаю, что ответ был бы да, если действительно, весь процесс действительно сделан только из этих файлов.

2
Вы спрашиваете, можно ли написать статически связанную программу, которая закрывает все свои файловые дескрипторы и продолжает работать? Erik Bennett 6 лет назад 0
Хм, это не то, что я спрашиваю. JohnDoea 6 лет назад 0
ХОРОШО. Итак, если бы я написал такую ​​программу, в которой было мало открытых дескрипторов, если таковые вообще имеются, что бы вы ожидали от нее извлечь? То есть, если вы запустили на нем `lsof (8)` и не нашли открытых дескрипторов, что тогда? Другими словами, если бы я написал программу, которая просто для развлечения открыла каждую библиотеку в системе, что бы вы ожидали узнать из списка открытых дескрипторов? Erik Bennett 6 лет назад 0
Я не пытаюсь быть сложным (много), но мне не ясно, какие файлы открыты, говорит вам что-нибудь, кроме «этот процесс открывает эти файлы». Я нахожу вопрос интересным, но я упускаю суть? (Извините за комментарий из двух частей. Время истекло.) Erik Bennett 6 лет назад 0

5 ответов на вопрос

4
Eugen Rieck

Краткий ответ: нет

Длинный ответ: файловые дескрипторы, используемые процессом, недостаточно статичны, чтобы обеспечить надежный анализ процесса. Файлы могут быть открыты и закрыты, соответствующие структуры данных будут переработаны ядром.

Спасибо, Евгений. Не могли бы вы попытаться уточнить в скобках высказывание: «соответствующие структуры данных будут переработаны ядром»? JohnDoea 6 лет назад 0
Да, и, если вы посмотрите на файлы файловых дескрипторов в соответствующем порядке (0-X), я считаю, что это действительно надежно для анализа. JohnDoea 6 лет назад 0
@ Benia: Дело в том, _fd числа_ также переработаны. Если у вас открыто 10 файлов и вы вызываете close (4), то 11-й файл (если вы когда-нибудь откроете его в будущем) снова получит fd # 4, и исходный файл больше нигде не будет отражен. grawity 6 лет назад 0
2
dirkt

Counterexample: Write two programs that both sleep for, say, 100 seconds, and then write 1 resp. 2 to stderr. Start both from the same shell and put them in the background. You won't be able to distinguish them by looking at the file descriptors, which are identical for both.

Variant: Have them open the same file, so it doesn't even work if it's not restricted to the to the standard descriptors.

2
Attie

I don't think I fully understand what you are asking... Please add some explanation.

But from what I think I understand, No.

An analogy could be:

If I watch Person A and see who they talk to, can I determine the intent of Person A?

In this case, that answer is quite murky. You might be able to see that Person A talks to some important person in law enforcement, and perhaps some people associated with organised crime. But it is going to be extremely difficult (impossible?) to state for certain the motives of Person A. Are they an undercover cop, or a criminal with a judge under their thumb?

You can't reliably read anything into such knowledge alone.

If you managed to ascertain more information, such as the I/O that is being performed, then you would be on your way to understanding the situation more clearly.


In other words, if you look at each file (represented by file descriptors in a respective order like 0-X), will it tell you the nature of the process and or subprocesses?

I think you are somewhat confused about what a 'file descriptor' is. A file descriptor is identified by a simple number (int) - the return value of open()... but within the kernel a file descriptor has information associated with it. See struct file.


I believe the answer would be yes, if indeed, the whole process is really made out only of these files.

This also holds some evidence of mis-understanding. A process is not "made out of only these files", but instead is accessing these files right now. We can show this by running the following:

$ ls -l /proc/self/fd total 0 lrwx------ 1 attie attie 64 May 20 15:20 0 -> /dev/pts/3 lrwx------ 1 attie attie 64 May 20 15:20 1 -> /dev/pts/3 lrwx------ 1 attie attie 64 May 20 15:20 2 -> /dev/pts/3 lr-x------ 1 attie attie 64 May 20 15:20 3 -> /proc/13103/fd 

As @grawity has pointed out in a comment, open() will return the next free file descriptor, filling any gaps from zero. What you see above is a snapshot of files that are currently open, and will change over time.


You can't see the ls binary in the above list, or any of its immediate dependencies:

$ ldd $(which ls) linux-vdso.so.1 => (0x00007fff569ef000) libselinux.so.1 => /lib/x86_64-linux-gnu/libselinux.so.1 (0x00007feeb33df000) libacl.so.1 => /lib/x86_64-linux-gnu/libacl.so.1 (0x00007feeb31d7000) libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007feeb2e0e000) libpcre.so.3 => /lib/x86_64-linux-gnu/libpcre.so.3 (0x00007feeb2bd0000) libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007feeb29cc000) /lib64/ld-linux-x86-64.so.2 (0x00007feeb361a000) libattr.so.1 => /lib/x86_64-linux-gnu/libattr.so.1 (0x00007feeb27c6000) 

When you try to "execute ls" the linker is actually what reads the library files to collate and 'link' the full process image. By the time ls starts to execute, this data is already in memory and the files are not 'open' anymore.

Some applications may make use of 'plugins', or 'dynamically' load additional files that provide functionality (see dlopen()), but this is an edge case and is far from typical behaviour - none of the processes currently running on my machine have a Shared Object (*.so) file open.


In summary, and still in agreement with my original answer, No.

There is no definitive way to determine the behaviour of a process by looking at what files it has open.

As far as determining the nature of a subprocess, this is impossible - can you look at init and determine the full runtime configuration of a system? No.

Здравствуйте, Атти, чтобы убедиться, что вы меня правильно поняли, я попытался отредактировать свой вопрос. Если понадобятся какие-либо дополнительные разъяснения - я буду рад их добавить. Мы были в одном направлении с этим? JohnDoea 6 лет назад 0
@ Benia Я обновил свой ответ, чтобы добавить детали, и, надеюсь, устранить некоторые очевидные недоразумения Attie 6 лет назад 0
0
harrymc

Short answer: Yes, but in a very limited way.

In fact, watching what a process does is one of the main functions of an antivirus, as among the files that are opened are also those of DLLs (Windows) or shared libraries (Linux). An antivirus that judges the behavior of a process will raise the alarm when a process opens too many or too sensitive files, or try to access sensitive folders. Windows/Linux may ask for user permission in such cases.

It is possible to detect that a process is opening a DLL/shared-library, but to find out which APIs it calls requires the analysis of the system calls that it does, which an antivirus can find by examining the executable file itself of the process.

Do not forget that the executable itself is one of the opened files, so that its analysis can tell exactly which DLLs/shared-libraries it uses, which can give a very good understanding of what it does.

The OS will watch the behavior of the process and will classify it in a scheduling class as a CPU-bound or IO-bound or mixed, which will affect its execution priority and its allowed slices of system resources.

A sub-process will usually inherit all the opened file-descriptors of its parent, and therefore will start its life in the same classification in the eyes of the OS and antivirus, but may later on, through its actions, move to another classification.

0
styrofoam fly

No.

Most processes have very similar descriptor behavior. For example, nearly all daemons write their output to logs (files), which are often shared. For example, on my system /var/log/journal has entries from systemd, gnome-keyring-*, dbus-daemon and many programs more.

One pattern which is often used is redirecting descriptors to/from /dev/, or closing them.

Another example - cmp and diff do basically the same, but they deal with different type of data.

There are even programs in moreutils package (which is brilliant) that wrap some common descriptor patterns:

  • chronic - runs a command quietly unless it fails
  • sponge - soak up standard input and write to a file (the file is opened after the input is soaked, so that grep "mom" somefile | sponge somefile leaves only those lines in somefile which contain "mom" )
  • combine - combine sets of lines from two files using boolean operations (same descriptors as diff)

And imagine, how fast descriptors are changing for top or find programs. You would need to trace them during their whole execution time.

A take-home question: what is the difference in descriptors between LibreOffice Writer and GIMP, or better, sed and WannaCry?