Как проверить сайт на уязвимости?
Сегодня поговорим о том, как проводить проверку сайтов на уязвимости с помощью сканера Nikto.
Как проходит проверка на уязвимости?
Перед тем как атаковать любой сайт, хакер или пентестер сначала составляет список целей. После проверки хакер найдет слабые места, затем ему понадобится инструмент сканирования веб-сервера, такой как Nikto, который поможет найти уязвимости.
Nikto – это открытый сканер веб-серверов, который проверяет веб-сайт и сообщает о найденных уязвимостях, которые могут быть использованы для эксплойта или взлома. Этот инструмент является очень популярным и широко используется для поиска уязвимостей.
Отличительная черта Nikto - сканер работает открыто. Любой сайт с системой обнаружения вторжений или иными мерами безопасности поймет, что его сканируют. Nikto был разработан для тестирования безопасности и о скрытности его работы никто не задумывался.
Как правильно использовать Nikto
Вначале разберем цели (target). Целью может быть почти любое место, куда может нанести свой удар хакер (например, веб-сервер). Для использования Nikto, нам нужно предоставить ему один из трех видов информации: IP-адрес для локальной службы, веб-домен для атаки или веб-сайт SSL/HTTPS.
Перед тем, как начать работу в Nikto, рекомендуем провести анализс помощью открытого инструмента Maltego. Скачать можно по ссылке:
https://null-byte.wonderhowto.com/collection/maltego/
Ресурс будет полезен для создания конкретного списка целей, которые мы будем проверять. После этого можно переходить к Nikto для поиска потенциальных уязвимостей в целях из вашего списка.
Шаг 1: Установка Nikto
Если вы используете Kali Linux, то Nikto будет предустановлен, поэтому вам ничего скачивать и устанавливать не нужно. Он находится в категории «Vulnerability Analysis». Если у вас его нет, скачать можно тут:
https://github.com/sullo/nikto
Или использовать в терминале командуapt install
.
Если вы работаете на Mac, то можете использовать Homebrew, чтобы установить Nikto:
https://null-byte.wonderhowto.com/how-to/mac-for-hackers-set-up-homebrew-install-update-open-source-tools-0174511/
brew install nikto
Шаг 2: Знакомство с Nikto
Перед сканированием веб-серверов с помощью Nikto, воспользуйтесь параметром -Help, чтобы увидеть все, что можно делать с этим инструментом:
nikto -Help
Options: -ask+ Whether to ask about submitting updates yes Ask about each (default) no Don't ask, don't send auto Don't ask, just send -Cgidirs+ Scan these CGI dirs: "none", "all", or values like "/cgi/ /cgi-a/" -config+ Use this config file -Display+ Turn on/off display outputs: 1 Show redirects 2 Show cookies received 3 Show all 200/OK responses 4 Show URLs which require authentication D Debug output E Display all HTTP errors P Print progress to STDOUT S Scrub output of IPs and hostnames V Verbose output -dbcheck Check database and other key files for syntax errors -evasion+ Encoding technique: 1 Random URI encoding (non-UTF8) 2 Directory self-reference (/./) 3 Premature URL ending 4 Prepend long random string 5 Fake parameter 6 TAB as request spacer 7 Change the case of the URL 8 Use Windows directory separator (\) A Use a carriage return (0x0d) as a request spacer B Use binary value 0x0b as a request spacer -Format+ Save file (-o) format: csv Comma-separated-value htm HTML Format nbe Nessus NBE format sql Generic SQL (see docs for schema) txt Plain text xml XML Format (if not specified the format will be taken from the file extension passed to -output) -Help Extended help information -host+ Target host -404code Ignore these HTTP codes as negative responses (always). Format is "302,301". -404string Ignore this string in response body content as negative response (always). Can be a regular expression. -id+ Host authentication to use, format is id:pass or id:pass:realm -key+ Client certificate key file -list-plugins List all available plugins, perform no testing -maxtime+ Maximum testing time per host (e.g., 1h, 60m, 3600s) -mutate+ Guess additional file names: 1 Test all files with all root directories 2 Guess for password file names 3 Enumerate user names via Apache (/~user type requests) 4 Enumerate user names via cgiwrap (/cgi-bin/cgiwrap/~user type requests) 5 Attempt to brute force sub-domain names, assume that the host name is the parent domain 6 Attempt to guess directory names from the supplied dictionary file -mutate-options Provide information for mutates -nointeractive Disables interactive features -nolookup Disables DNS lookups -nossl Disables the use of SSL -no404 Disables nikto attempting to guess a 404 page -Option Over-ride an option in nikto.conf, can be issued multiple times -output+ Write output to this file ('.' for auto-name) -Pause+ Pause between tests (seconds, integer or float) -Plugins+ List of plugins to run (default: ALL) -port+ Port to use (default 80) -RSAcert+ Client certificate file -root+ Prepend root value to all requests, format is /directory -Save Save positive responses to this directory ('.' for auto-name) -ssl Force ssl mode on port -Tuning+ Scan tuning: 1 Interesting File / Seen in logs 2 Misconfiguration / Default File 3 Information Disclosure 4 Injection (XSS/Script/HTML) 5 Remote File Retrieval - Inside Web Root 6 Denial of Service 7 Remote File Retrieval - Server Wide 8 Command Execution / Remote Shell 9 SQL Injection 0 File Upload a Authentication Bypass b Software Identification c Remote Source Inclusion d WebService e Administrative Console x Reverse Tuning Options (i.e., include all except specified) -timeout+ Timeout for requests (default 10 seconds) -Userdbs Load only user databases, not the standard databases all Disable standard dbs and load only user dbs tests Disable only db_tests and load udb_tests -useragent Over-rides the default useragent -until Run until the specified time or duration -update Update databases and plugins from CIRT.net -useproxy Use the proxy defined in nikto.conf, or argument http://server:port -Version Print plugin and database versions -vhost+ Virtual host (for Host header) + requires a value
Шаг 3: Базовый синтаксис
У Nikto множество вариантов использования, но мы будем пользоваться базовым синтаксисом <IP или hostname> с фактическим IP-адресом или именем хоста.
nikto -h <IP or hostname>
Также Nikto способен выполнять сканирование SSL и порта 443, который используют сайты HTTPS. А значит, мы не ограничиваемся одним сканированием старых сайтов, нам доступна оценка уязвимостей сайтов, использующих SSL. Это, кстати, является обязательным требованием для индексирования в поиске.
Если у целевого сайта есть SSL, мы можем указать это в Nikto, чтобы сэкономить время на сканировании, добавив -ssl в конец команды.
nikto -h <IP or hostname> -ssl
Шаг 4: Сканируйте сайты с SSL
Начнем со сканирования сайта pbs.org
и увидим типы информации, которые может выдать сканирование Nikto. После того, как он подключается к порту 443, выдается полезная информация о шифровании и др.:
nikto -h pbs.org -ssl
- Nikto v2.1.6 ------------------------------------------------------------------------------ - STATUS: Starting up! + Target IP: 54.225.198.196 + Target Hostname: pbs.org + Traget Port: 443 ------------------------------------------------------------------------------ + SSl Info: Subject: /CN=www.pbs.org Altnames: account.pbs.org, admin.pgs.org, dipsy-tc.pbs.org, docs.pbs.org, ga.video.cdn.pbs.org, git.pbs.org, heart.ops.pbs.org, hub-dev.pbs.org, image.pbs.org, jaws..pbs.org, kids.pbs.org, koth-qa.svp.pbs.org, login.pbs.org, ops.pbs.org, pbs.org, player.pbs.org, projects.pbs.org, sentry.pbs.org, teacherline.pbs.org, urs.pbs.org, video.pbs.org, weta-qa.svp.pbs.org, whut-qa.svp.pbs.org, wnet.video-qa.pbs.org, wnet.video-staging.pbs.org, www-cache.pbs.org, www.pbs.org Ciphers: ECDHE-RSA-AES128-GCM-SHA256 Issuer: /C-US/0=Let's Encrypt/CN=Let's Encrypt Authority X3 + Start Time: 2018-12-05 23:34:06 (GMT-8) ------------------------------------------------------------------------------ + Server: nginx + The anti-clickjacking X-Frame-Options header is not present. + The X-XSS-Protection header is not defined. This header can hint to the user agent to protect against some forms of XSS + Uncommon header 'x-pbs-fwsrvname' found, with contents: fwcacheproxy1 + The site uses SSL and the Strict-Transport-Security HTTP header is not defined. + The X-Content-Type-Options header is not set. This could allow the user agent to render the content of the site in a different fashion to the MIME type + Root page / redirects to: https://www.pbs.org/ + No CGI Directories found (use '-C all' to force check all possible dirs) + RC-1918 IP address found in the 'x-pbs-appsvrip' header: The IP is "10.137.181.52". + Uncommon header 'x-cache-fs-status' found, with contents: EXPIRED + Uncommon header 'x-pbs-appsvrname' found, with contents: fwcacheproxy1 + Uncommon header 'x-pbs-appsvrip' found, with contents: 10.137.181.52 + Server leaks inodes via ETags, header found with file /pbs.org.zip, fields: 0x5b96537e 0x1678 + 7446 requests: 0 error(s) and 10 item(s) reported on remote host + End Time: 2018-12-06 00:30:29 (GMT-8) (3383 seconds) ------------------------------------------------------------------------------ + 1 host(s) tested
Шаг 5: Сканирование IP-адреса
После того, как мы закончили сканировать веб-сайт, перейдем к анализу локальной сети и обнаружим embedded-сервера (страница логина роутера или HTTP-сервис на другой машине). Чтобы узнать IP-адрес мы будем использовать ifconfig
.
Нужный IP-адрес относится к «inet». Используемipcalc
, чтобы получить сетевой диапазон. Если у вас нет ipcalc, вы можете установить его с помощью команды apt install ipcalc
, а затем повторить попытку. Диапазон находится после «Network».
ifconfig
en0: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500 inet 192.168.0.48 netmask 0xffffff00 broadcast 192.168.0.255 inet6 XXXX::XXX:XXXX:XXXX:XXXX%en0 prefixlen 64 secured scopeid 0x8 ether XX:XX:XX:XX:XX:XX txqueuelen 1000 (Ethernet) inet6 XXXX::XXX:XXXX:XXXX:XXXX%en0 prefixlen 64 autoconf secured inet6 XXXX::XXX:XXXX:XXXX:XXXX%en0 prefixlen 64 autoconf temporary nd6 options=201<PERFORMNUD,DAD> media: autoselect status: active en2: flags=8863<UP,BROADCAST,SMART,RUNNING,PROMISC,SIMPLEX,MULTICAST> mtu 1500 options=60<TS04,TS06> ether XX:XX:XX:XX:XX:XX media: autoselect <full-duplex> status: inactive
https://null-byte.wonderhowto.com/collection/nmap/
и находим работающие службы в нужном диапазоне. Переходим к сканированию 80 порта с помощью команды -oG (grepable output), чтобы получить работающие хосты. А после сохраняем все в файл.
ipcalc 192.168.0.48
Address: 192.168.0.48 11000000.10101000.00000000. 00110000 Netmask: 255.255.255.0 = 24 11111111.11111111.11111111. 00000000 Wildcard: 0.0.0.255 00000000.00000000.00000000. 11111111 => Network: 192.168.0.0/24 11000000.10101000.00000000. 00000000 HostMin: 192.168.0.1 11000000.10101000.00000000. 00000001 HostMax: 192.168.0.254 11000000.10101000.00000000. 11111110 Broadcast: 192.168.0.255 11000000.10101000.00000000. 11111111 Hosts/Net: 254 Class C, Private Internet
Используем cat
для чтения входных данных, хранящихся в нашем документе _.txt
(или как вы его назвали самостоятельно), чтобы отправить все хосты прямо в Nikto для сканирования. Затем применяем awk – инструмент в Linux, который поможет найти шаблон, где Up означает, что хост поднят, а print $2 значит, что нужно вывести второе слово в каждой строке - IP-адрес. В итоге, наши данные перемещаем в файл, который называется targetIP.txt
.
cat nullbyte.txt | awk '/Up$/{print $2}' | cat >> targetIP.txt
Вот теперь нам видно содержимое нового файла с помощью команды cat, и мы можем прочесть все IP-адреса, у которых открыт 80 порт.
cat targetIP.txt
192.168.0.1 192.168.0.2 192.168.0.4 192.168.0.5 192.168.0.11 192.168.0.24 192.168.0.31 192.168.0.48 192.168.0.60
Этот вариант отлично подойдет Nikto - он может легко анализировать подобные файл. Отправляем вывод в Nikto с помощью команды:
nikto -h targetIP.txt
В результате мы получим то же, что и при сканировании с SSL.
Шаг 6: Сканирование HTTP-сайта
Переходим к сканированию сайта, чтобы найти незащищенный веб-домен с 80 портом. Для этого примера возьмем сайт afl.com.au, у которого нет SSL.
nikto -h www.afl.com.au
- Nikto v2.1.6 --------------------------------------------------------------------------- + Target IP: 159.180.84.10 + Target Hostname: www.afl.com.au + Target Port: 80 + Start Time: 2018-12-05 21:48:32 (GMT-8) --------------------------------------------------------------------------- + Server: instart/nginx + Retried via header: 1.1 varnish (Varnish/6.1), 1.1 e9ba0a9a729ff2960a04323bf1833df8.cloudfront.net (CloudFront) + The anti-clickjacking X-Frame-Options header is not present. + The X-XSS-Protection header is not defined. This header can hint to the user agent to protect against some forms of XSS + Uncommon header 'x-cache' found, with contents: Miss from cloudfront + Uncommon header 'x-instart-cache-id' found, with contents: 17:12768802731504004780::1544075250 + Uncommon header 'v-cache-hit' found, with contents: Hit + Uncommon header 'x-amz-cf-id' found, with contents: Dr-r6OwO5kk9ABt4ejzpc7R7AIF6SuH6kfJHQgP0v6xZoHwMLE55rQ== + Uncommon header 'x-instart-request-id' found, with contents: 12814413144077601501:BEQ01-CPVNPPRY18:1552504721:0 + Uncommon header 'x-oneagent-js-injection' found, with contents: true + Uncommon header 'grace' found, with contents: cache + The X-Content-Type-Options header is not set. This could allow the user agent to render the content of the site in a different fashion to the MIME type + Uncommon header 'x-ruxit-js-agent' found, with contents: true + Cookie dtCookie created without the httponly flag + Server banner has changed from 'instart/nginx' to 'nginx' which may suggest a WAF, load balancer or proxy is in place + No CGI Directories found (use '-C all' to force check all possible dirs) + Entry '/sites/' in robots.txt returned a non-forbidden or redirect HTTP code (200) + Entry '/search/' in robots.txt returned a non-forbidden or redirect HTTP code (200) + Entry '*.mobileapp' in robots.txt returned a non-forbidden or redirect HTTP code (400) + Entry '*.liveradio' in robots.txt returned a non-forbidden or redirect HTTP code (400) + Entry '*.smartmobile' in robots.txt returned a non-forbidden or redirect HTTP code (400) + Entry '*.responsive' in robots.txt returned a non-forbidden or redirect HTTP code (400) + Entry '/stats?*/' in robots.txt returned a non-forbidden or redirect HTTP code (200) + "robots.txt" contains 8 entries which should be manually viewed. + OSVDB-3092: /sitemap.xml: This gives a nice listing of the site content. + OSVDB-3092: /psql_history: This might be interesting... + OSVDB-3092: /global/: This might be interesting... + OSVDB-3092: /home/: This might be interesting... + OSVDB-3092: /news: This might be interesting... + OSVDB-3092: /search.vts: This might be interesting... + OSVDB-3092: /stats.htm: This might be interesting... + OSVDB-3092: /stats.txt: This might be interesting... + OSVDB-3092: /stats/: This might be interesting... + OSVDB-3092: /Stats/: This might be interesting... + OSVDB-3093: /.wwwacl: Contains authorization information + OSVDB-3093: /.www_acl: Contains authorization information + OSVDB-3093: /.htpasswd: Contains authorization information + OSVDB-3093: /.access: Contains authorization information + OSVDB-3093: /.addressbook: PINE addressbook, may store sensitive e-mail address contact information and notes + OSVDB-3093: /.bashrc: User home dir was found with a shell rc file. This may reveal file and path information. + OSVDB-3093: /.bash_history: A user's home directory may be set to the web root, the shell history was retrieved. This should not be accessible via the web. + OSVDB-3093: /.forward: User home dir was found with a mail forward file. May reveal where the user's mail is being forwarded to. + OSVDB-3093: /.history: A user's home directory may be set to the web root, the shell history was retrieved. This should not be accessible via the web. + OSVDB-3093: /.htaccess: Contains configuration and/or authorization information + OSVDB-3093: /.lynx_cookies: User home dir found with LYNX cookie file. May reveal cookies received from arbitrary web sites. + OSVDB-3093: /.mysql_history: Database SQL? + OSVDB-3093: /.passwd: Contains authorization information + OSVDB-3093: /.pinerc: User home dir found with a PINE rc file. May reveal system information, directories and more. + OSVDB-3093: /.plan: User home dir with a .plan, a now mostly outdated file for delivering information via the finger protocol + OSVDB-3093: /.proclog: User home dir with a Procmail rc file. May reveal mail traffic, directories and more. + OSVDB-3093: /.procmailrc: User home dir with a Procmail rc file. May reveal subdirectories, mail contacts and more. + OSVDB-3093: /.profile: User home dir with a shell profile was found. May reveal directory information and system configuration. + OSVDB-3093: /.rhosts: A user's home directory may be set to the web root, a .rhosts file was retrieved. This should not be accessible via the web. + OSVDB-3093: /.sh_history: A user's home directory may be set to the web root, the shell history was retrieved. This should not be accessible via the web. + OSVDB-3093: /.ssh: A user's home directory may be set to the web root, an ssh file was retrieved. This should not be accessible via the web. + OSVDB-5709: /.nsconfig: Contains authorization information + /portal/changelog: Vignette richtext HTML editor changelog found. + 7587 requests: 4 error(s) and 55 item(s) reported on remote host + End Time: 2018-12-05 22:42:41 (GMT-8) (3249 seconds) --------------------------------------------------------------------------- + 1 host(s) tested
Видно, что есть сервер Varnish и несколько заголовков, которые указывают на веб-сайт. Обнаруженные каталоги помогут найти конфигурационные файлы, с данными, которые были неправильно сконфигурированы и оказались доступными случайно.
Элементы с префиксом OSVDB – это уязвимости, о которых сообщается в базах данных уязвимостей, такие как SecurityFocus:
https://null-byte.wonderhowto.com/how-to/hack-like-pro-find-almost-every-known-vulnerability-exploit-out-there-0147820/
https://null-byte.wonderhowto.com/how-to/hack-like-pro-find-latest-exploits-and-vulnerabilities-directly-from-microsoft-0147354/
и National Vulnerability Database:
https://nvd.nist.gov/vuln/search
Cканирование не выявило критических уязвимостей, которые можно было бы эксплуатировать. Но мы можем использовать справочный инструмент CVE для перевода идентификатора OSVDB в запись CVE, чтобы можно было зайти на сайт.
CVE содержит информацию о том, как использовать уязвимость, насколько она серьезна и другие сведения, которые помогут с вектором атаки. Если обнаружится что-то стоящее, можно поискать с Metasploit. Там точно кто-то уже придумал, как эксплуатировать эту уязвимость.
Шаг 7: Сканирование с Metasploit
Крутая функция в Nikto - очень просто экспортировать информацию, полученную при сканировании, в формат для Metasploit. Для этого к командам сканирования добавьте в конце флаги -Format msf+.
nikto -h <IP or hostname> -Format msf+
Сегодня вы узнали, как пользоваться Nikto для сканирования и поиска уязвимостей. Только помните одну вещь - Nikto работает открыто, поэтому чтобы не скомпрометировать свой IP-адрес, используйте VPN или Tor.