mirror of
https://github.com/bol-van/zapret2.git
synced 2026-10-29 14:09:23 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d214ebf2de | ||
|
|
fe8b8df2ae | ||
|
|
441d2e3cfc | ||
|
|
b37f17e623 | ||
|
|
7b82744d4d | ||
|
|
211867eca5 | ||
|
|
c90e0e9a7f | ||
|
|
fd4716da54 | ||
|
|
5dcb6c1163 | ||
|
|
fe112c1f22 | ||
|
|
850a9920f6 | ||
|
|
dc99547ff0 | ||
|
|
8d08b4f9a4 | ||
|
|
860b13c86e | ||
|
|
a154c223f4 |
No files matched your search
@@ -288,3 +288,13 @@ v0.9.4.3
|
||||
0.9.5.1
|
||||
|
||||
* nfqws2: timer_info, timer_enum
|
||||
|
||||
0.9.5.2
|
||||
|
||||
* nfqws2: rewrite time counting algorithm, remove --timer-res
|
||||
|
||||
1.0
|
||||
|
||||
* zapret-lib,zapret-antidpi: delay parameter in "send" desync function
|
||||
* zapret-lib: fix oob urp=b case in rawsend_dissect_segmented
|
||||
* nfqws2, zapret-lib: (LUA_COMPAT_VER=6) fix wrong spelling : WRITEABLE -> WRITABLE
|
||||
+30
-7
@@ -162,6 +162,7 @@
|
||||
- [rawsend_payload_segmented](#rawsend_payload_segmented)
|
||||
- [Standard direction and payload filters](#standard-direction-and-payload-filters)
|
||||
- [Working with multi-packet payloads](#working-with-multi-packet-payloads)
|
||||
- [Timer helpers](#timer-helpers)
|
||||
- [Orchestration](#orchestration)
|
||||
- [instance_cutoff_shim](#instance_cutoff_shim)
|
||||
- [cutoff_shim_check](#cutoff_shim_check)
|
||||
@@ -655,7 +656,7 @@ General parameters for all versions - nfqws2, dvtws2, winws2.
|
||||
--reasm-disable=[type[,type]] ; disable fragment reassembly for a list of payloads: tls_client_hello quic_initial. without arguments - disable reasm for everything.
|
||||
|
||||
DESYNC ENGINE INIT:
|
||||
--writeable[=<dir_name>] ; create a directory for Lua with write permissions and store its path in the "WRITEABLE" env variable (only one directory)
|
||||
--writable[=<dir_name>] ; create a directory for Lua with write permissions and store its path in the "WRITABLE" env variable (only one directory)
|
||||
--blob=<item_name>:[+ofs]@<filename>|0xHEX ; load a binary file or hex string into the Lua variable <item_name>. +ofs specifies the offset from the start of the file
|
||||
--lua-init=@<filename>|<lua_text> ; execute Lua code from a string or file once at startup. supports gzipped files. automatically checks for "<filename>.gz"
|
||||
--lua-gc=<int> ; Lua garbage collector invocation interval in seconds. 0 disables periodic calls.
|
||||
@@ -1017,7 +1018,7 @@ Windows:
|
||||
- All `Se*` privileges are irrevocably removed from the token, except for `SeChangeNotifyPrivilege`.
|
||||
- A Job object is used to prohibit the creation of child processes and restrict desktop interaction - clipboard access, changing desktop settings, changing display settings, etc.
|
||||
|
||||
There is a simple way to pass a writable directory to the Lua code using the `--writeable[=<dirname>]` parameter. `nfqws2` creates the directory and assigns permissions so that the Lua code can write files there, then passes the directory name in the `WRITEABLE` environment variable. If `dirname` is not specified, a directory is created within `%USERPROFILE%/AppData/LocalLow` on Windows.
|
||||
There is a simple way to pass a writable directory to the Lua code using the `--writable[=<dirname>]` parameter. `nfqws2` creates the directory and assigns permissions so that the Lua code can write files there, then passes the directory name in the `WRITABLE` environment variable. If `dirname` is not specified, a directory is created within `%USERPROFILE%/AppData/LocalLow` on Windows.
|
||||
|
||||
On the Lua side, dangerous functions are removed: `os.execute`, `io.popen`, `package.loadlib`, and the `debug` module. On GitHub, `nfqws2` executables are built with a version of LuaJIT that excludes FFI.
|
||||
|
||||
@@ -1696,8 +1697,8 @@ Before executing `--lua-init`, the C code sets up base constants, blobs, and C f
|
||||
|
||||
| env | Purpose |
|
||||
| :-------- |:---------- |
|
||||
| WRITEABLE | A directory writable by Lua. Corresponds to the `--writeable` option. |
|
||||
| APPDATALOW | (Windows only) The AppData location for the low mandatory level. This is also writable, but using `--writeable` is preferred for cross-platform compatibility. |
|
||||
| WRITABLE | A directory writable by Lua. Corresponds to the `--writable` option. |
|
||||
| APPDATALOW | (Windows only) The AppData location for the low mandatory level. This is also writable, but using `--writable` is preferred for cross-platform compatibility. |
|
||||
|
||||
## C functions
|
||||
|
||||
@@ -2441,7 +2442,7 @@ function timer_del(name)
|
||||
Get information about the timer identified by name.
|
||||
|
||||
```
|
||||
function timer_del(name)
|
||||
function timer_info(name)
|
||||
```
|
||||
|
||||
Returns table in case of success, nil otherwise.
|
||||
@@ -3294,12 +3295,12 @@ function host_or_ip(desync)
|
||||
```
|
||||
function is_absolute_path(path)
|
||||
function append_path(path, file)
|
||||
function writeable_file_name(filename)
|
||||
function writeble_file_name(filename)
|
||||
```
|
||||
|
||||
- `is_absolute_path` returns true if the path starts from the root. It accounts for CYGWIN path specifics.
|
||||
- `append_path` appends a file or directory name `file` to `path`, using '/' as a separator.
|
||||
- `writeable_file_name` returns `filename` if it contains an absolute path or if the `WRITEABLE` environment variable is not set. Otherwise, it retrieves the path from the `WRITEABLE` environment variable and appends the `filename` using `append_path`.
|
||||
- `writeble_file_name` returns `filename` if it contains an absolute path or if the `WRITABLE` environment variable is not set. Otherwise, it retrieves the path from the `WRITABLE` environment variable and appends the `filename` using `append_path`.
|
||||
|
||||
## Reading and writing Files
|
||||
|
||||
@@ -3603,6 +3604,23 @@ function replay_drop(desync)
|
||||
|
||||
These functions work correctly with both [replays](#handling-multi-packet-payloads) and regular dissects. For regular dissects, `replay_first` is always true, `replay_drop_set` does not change the flag, and `replay_drop` is always false.
|
||||
|
||||
## Timer helpers
|
||||
|
||||
```
|
||||
function dis_timer_name(dis)
|
||||
```
|
||||
|
||||
Construct timer name based on ip src and dst addresses, l4 protocol name, port numbers or icmp codes.
|
||||
May not be unique.
|
||||
|
||||
```
|
||||
function desync_timer_name(desync)
|
||||
```
|
||||
|
||||
Construct timer name that includes dis_timer_name result + conntrack packet number.
|
||||
If track is absent random characters are added to the end.
|
||||
This name can be considered unique per desync and can be used as an oneshot timer name.
|
||||
|
||||
## Orchestration
|
||||
|
||||
This group includes functions that support the orchestration and shimming processes.
|
||||
@@ -3767,9 +3785,14 @@ function send(ctx, desync)
|
||||
- arg: [standard ipfrag](#standard-ipfrag)
|
||||
- arg: [standard reconstruct](#standard-reconstruct)
|
||||
- arg: [standard rawsend](#standard-rawsend)
|
||||
- arg: delay - packet send delay in msec
|
||||
- Default `ip_id` mode is `none`.
|
||||
|
||||
Sends the current dissect with optional modifications applied.
|
||||
If delay is specified packet data and send options are remembered. After specified time packet is sent out.
|
||||
|
||||
The function returns VERDICT_PASS - the sending of the current dissect is not canceled. If you want to cancel, use the [drop](#drop) instance.
|
||||
|
||||
|
||||
### pktmod
|
||||
|
||||
|
||||
+37
-9
@@ -159,6 +159,7 @@
|
||||
- [rawsend_payload_segmented](#rawsend_payload_segmented)
|
||||
- [Стандартные фильтры direction и payload](#стандартные-фильтры-direction-и-payload)
|
||||
- [Работа с многопакетными пейлоадам](#работа-с-многопакетными-пейлоадам)
|
||||
- [Помощь с таймерами](#помощь-с-таймерами)
|
||||
- [Оркестрация](#оркестрация)
|
||||
- [instance_cutoff_shim](#instance_cutoff_shim)
|
||||
- [cutoff_shim_check](#cutoff_shim_check)
|
||||
@@ -714,7 +715,7 @@ nfqws2 использует стандартный парсер getopt_long_only
|
||||
--reasm-disable=[type[,type]] ; отключить сборку фрагментов для списка пейлоадов : tls_client_hello quic_initial . без аргумента - отключить reasm для всего.
|
||||
|
||||
DESYNC ENGINE INIT:
|
||||
--writeable[=<dir_name>] ; создать директорию для Lua с разрешением записи и поместить путь к ней в переменную env "WRITEABLE" (только одна директория)
|
||||
--writable[=<dir_name>] ; создать директорию для Lua с разрешением записи и поместить путь к ней в переменную env "WRITABLE" (только одна директория)
|
||||
--blob=<item_name>:[+ofs]@<filename>|0xHEX ; загрузить бинарный файл или hex строку в переменную Lua <item_name>. +ofs задает смещение от начала файла
|
||||
--lua-init=@<filename>|<lua_text> ; однократно при старте выполнить Lua код из строки или из файла. поддерживаются сжатые gzip файлы. автоматически проверяется "<filename>.gz"
|
||||
--lua-gc=<int> ; интервал вызова сборщика мусора Lua в секундах. 0 отключает периодический вызов.
|
||||
@@ -1138,8 +1139,8 @@ Windows :
|
||||
- Безвозвратно убираются все Se* привилегии из токена, кроме SeChangeNotifyPrivilege.
|
||||
- С помощью Job запрещается создание дочерних процессов и ограничивается взаимодействие с десктопом - clipboard, change desktop, change display settings и тд
|
||||
|
||||
Есть простой способ передать Lua коду каталог, доступный на запись - параметр `--writeable[=<dirname>]`.
|
||||
nfqws2 создает каталог, назначает на него такие права, чтобы Lua код смог писать туда файлы, передает имя директории в переменной env `WRITEABLE`.
|
||||
Есть простой способ передать Lua коду каталог, доступный на запись - параметр `--writable[=<dirname>]`.
|
||||
nfqws2 создает каталог, назначает на него такие права, чтобы Lua код смог писать туда файлы, передает имя директории в переменной env `WRITABLE`.
|
||||
Если dirname не задан, на Windows создается каталог внутри `%USERPROFILE%/AppData/LocalLow`
|
||||
|
||||
Со стороны Lua убираются опасные функции - os.execute, io.popen, package.loadlib и модуль debug.
|
||||
@@ -1843,8 +1844,8 @@ data задается при запуске таймера через [timer_set
|
||||
|
||||
| env | Назначение |
|
||||
| :-------- |:---------- |
|
||||
| WRITEABLE | Директория, доступная на запись Lua. Результат опции `--writeable` |
|
||||
| APPDATALOW | (только Windows) Расположение AppData для low mandatory level. Сюда тоже можно записывать, но предпочтительно использовать `--writeable` для кросс-платформенности. |
|
||||
| WRITABLE | Директория, доступная на запись Lua. Результат опции `--writable` |
|
||||
| APPDATALOW | (только Windows) Расположение AppData для low mandatory level. Сюда тоже можно записывать, но предпочтительно использовать `--writable` для кросс-платформенности. |
|
||||
|
||||
## C функции
|
||||
|
||||
@@ -2601,7 +2602,7 @@ function timer_del(name)
|
||||
Получить информацию о таймере.
|
||||
|
||||
```
|
||||
function timer_del(name)
|
||||
function timer_info(name)
|
||||
```
|
||||
|
||||
В случае успеха возвращается таблица, в случае неудачи - nil.
|
||||
@@ -3467,13 +3468,13 @@ function host_or_ip(desync)
|
||||
```
|
||||
function is_absolute_path(path)
|
||||
function append_path(path,file)
|
||||
function writeable_file_name(filename)
|
||||
function writable_file_name(filename)
|
||||
```
|
||||
|
||||
- is_absolute_path возвращает true, если путь path начинается с корня. Учитываются особенности путей CYGWIN.
|
||||
- append_path дописывает имя файла или каталога file к пути path, разделяя их знаком '/'
|
||||
- writeable_file_name возвращает filename, если filename содержит абсолютный путь или env `WRITEABLE` отсутствует.
|
||||
Иначе берется путь из env `WRITEABLE` и к нему дописывается имя файла filename через append_path.
|
||||
- writable_file_name возвращает filename, если filename содержит абсолютный путь или env `WRITABLE` отсутствует.
|
||||
Иначе берется путь из env `WRITABLE` и к нему дописывается имя файла filename через append_path.
|
||||
|
||||
## Чтение и запись файлов
|
||||
|
||||
@@ -3782,6 +3783,24 @@ function replay_drop(desync)
|
||||
|
||||
Функции работают корректно как с [реплеем](#особенности-приема-многопакетных-пейлоадов), так и обычными диссектами. Для обычных диссектов replay_first всегда true, replay_drop_set не меняет признак, replay_drop всегда false.
|
||||
|
||||
## Помощь с таймерами
|
||||
|
||||
```
|
||||
function dis_timer_name(dis)
|
||||
```
|
||||
|
||||
Конструирует имя таймера, включающее в себя ip адреса src,dst, имя протокола l4, номера портов или icmp коды.
|
||||
Имя таймера может не быть уникальным.
|
||||
|
||||
```
|
||||
function desync_timer_name(desync)
|
||||
```
|
||||
|
||||
Конструирует имя таймера, включающее в себя результат dis_timer_name + номер пакета в conntrack по прямому направлению.
|
||||
Если track отсутствует, добавляются случайные символы.
|
||||
Имя таймера можно считать уникальным на desync, его можно использовать как oneshot timer name.
|
||||
|
||||
|
||||
## Оркестрация
|
||||
|
||||
В эту группу функций входят функции поддержки процесса оркестрации и прокладки.
|
||||
@@ -3951,10 +3970,19 @@ function send(ctx, desync)
|
||||
- arg: [standard ipfrag](#standard-ipfrag)
|
||||
- arg: [standard reconstruct](#standard-reconstruct)
|
||||
- arg: [standard rawsend](#standard-rawsend)
|
||||
- arg: delay - задержка отправки в мсек
|
||||
- режим ip_id по умолчанию - none
|
||||
|
||||
Отсылает текущий диссект c опциональным применением модификаций.
|
||||
|
||||
При наличии параметра delay данные пакета и опции отправки запоминаются. Спустя указанное время происходит отправка.
|
||||
Функция отсылки с delay реализована тривиальным образом через таймер с именем, уникальным для диссекта.
|
||||
Множественные send с delay не вызывают дополнительную отправку, вместо этого замещается предыдущая отправка.
|
||||
Если вам нужно задерживать несколько вариаций (например, результат tcp сегментации) и нужна очередь для отправки в строгом порядке,
|
||||
то вам нужно писать свою функцию - send не подойдет.
|
||||
|
||||
Функция выносит VERDICT_PASS - отсылка текущего диссекта не отменяется. Если нужно отменить - используйте инстанс [drop](#drop).
|
||||
|
||||
### pktmod
|
||||
|
||||
```
|
||||
|
||||
+9
-9
@@ -102,7 +102,7 @@ windivert вообще не отслеживает соединения. Поэ
|
||||
Дальше под рутом нужно запустить *nfqws2* с параметрами командной строки. Они строятся примерно следующим образом :
|
||||
|
||||
```
|
||||
nfqws2 --qnum 200 --debug --lua-init=@zapret-lib.lua --lua-init=@zapret-antidpi.lua \
|
||||
nfqws2 --qnum=200 --debug --lua-init=@zapret-lib.lua --lua-init=@zapret-antidpi.lua \
|
||||
--filter-tcp=80,443 --filter-l7=tls,http \
|
||||
--payload=tls_client_hello --lua-desync=fake:blob=fake_default_tls:tcp_md5:tls_mod=rnd,rndsni,dupsid \
|
||||
--payload=http_req --lua-desync=fake:blob=fake_default_http:tcp_md5 \
|
||||
@@ -117,7 +117,7 @@ nfqws2 --qnum 200 --debug --lua-init=@zapret-lib.lua --lua-init=@zapret-antidpi.
|
||||
После двоеточия и через двоеточия следуют параметры для данной функции в формате `param[=value]`. В примере реализована стратегия
|
||||
|
||||
```
|
||||
nfqws --qnum 200 --debug \
|
||||
nfqws --qnum=200 --debug \
|
||||
--filter-tcp=80,443 --filter-l7=tls,http \
|
||||
--dpi-desync=fake,multisplit --dpi-desync-fooling=md5sig --dpi-desync-split-pos=1,midsld \
|
||||
--dpi-desync-split-seqovl=5 --dpi-desync-split-seqovl-pattern=0x1603030000 \
|
||||
@@ -150,7 +150,7 @@ nfqws --qnum 200 --debug \
|
||||
В *nfqws1* они падали на профиль с автолистом.
|
||||
|
||||
```
|
||||
nfqws2 --qnum 200 --debug --lua-init=@zapret-lib.lua --lua-init=@zapret-antidpi.lua \
|
||||
nfqws2 --qnum=200 --debug --lua-init=@zapret-lib.lua --lua-init=@zapret-antidpi.lua \
|
||||
--filter-tcp=80 --filter-l7=http --hostlist=mylist1.txt --lua-desync=multisplit --new \
|
||||
--filter-tcp=80 --filter-l7=http --hostlist-exclude=mylist2.txt --lua-desync=fake:blob=0x00000000:ip_ttl=5:ip6_ttl=3 --lua-desync=multidisorder:pos=5,endhost-1 --new \
|
||||
--filter-tcp=443 --filter-l7=tls --hostlist=mylist1.txt --lua-desync=multidisorder
|
||||
@@ -167,7 +167,7 @@ range задается как `mX-mY`, `mX<mY`, `-mY`, `<mY`, `mX-`.
|
||||
Есть и режимы, не требущие числа - `a` - всегда, `x` - никогда.
|
||||
Если разделителем указан знак '-' - конечная позиция включительна, а если '<' - не включительна.
|
||||
|
||||
Установка по умолчанию `--in-range=x --out-range=a --payload all`. То есть отсекаются все входящие пакеты и берутся все исходящие.
|
||||
Установка по умолчанию `--in-range=x --out-range=a --payload=all`. То есть отсекаются все входящие пакеты и берутся все исходящие.
|
||||
|
||||
`--in-range`, `--out-range` и `--payload` фильтры могут присутствовать множественно в одном профиле.
|
||||
Их действие распространяется на все последующие `--lua-desync` функции до следующего фильтра того же типа или до конца профиля.
|
||||
@@ -248,7 +248,7 @@ nfqws \
|
||||
nfqws2 \
|
||||
--blob=tls_google:@tls_clienthello_google_com.bin \
|
||||
--filter-l7=tls \
|
||||
--payload tls_client_hello,http_req \
|
||||
--payload=tls_client_hello,http_req \
|
||||
--lua-desync=fakedsplit:pattern=tls_google:pos=method+2:nofake1:ip_ttl=1:ip6_ttl=1:ip_autottl=-1,3-20:ip6_autottl=-1,3-20
|
||||
```
|
||||
|
||||
@@ -269,19 +269,19 @@ nfqws2 --lua-desync=wssize:wsize=1:scale=6 --lua-desync=syndata --lua-desync=mul
|
||||
|
||||
```
|
||||
nfqws1 \
|
||||
--filter-l7 tls \
|
||||
--filter-l7=tls \
|
||||
--dpi-desync=fake --dpi-desync-fooling=datanoack --dpi-desync-fake-tls=! \
|
||||
--dpi-desync-fake-tls-mod=rnd,rndsni,dupsid
|
||||
|
||||
nfqws2
|
||||
--filter-l7 tls \
|
||||
--filter-l7=tls \
|
||||
--payload=tls_client_hello --lua-desync=fake:blob=fake_default_tls:tcp_flags_unset=ack:tls_mod=rnd,rndsni,dupsid,padencap \
|
||||
--payload=empty --out-range="s1<d1" --lua-desync=pktmod:ip_ttl=1:ip6_ttl=1
|
||||
|
||||
|
||||
nfqws2 \
|
||||
--lua-init="fake_default_tls=tls_mod(fake_default_tls,'rnd,rndsni')" \
|
||||
--filter-l7 tls \
|
||||
--filter-l7=tls \
|
||||
--payload=tls_client_hello --lua-desync=fake:blob=fake_default_tls:tcp_flags_unset=ack:tls_mod=dupsid,padencap \
|
||||
--payload=empty --out-range="s1<d1" --lua-desync=pktmod:ip_ttl=1:ip6_ttl=1
|
||||
```
|
||||
@@ -468,7 +468,7 @@ table ip ztest {
|
||||
```
|
||||
|
||||
```
|
||||
nfqws2 --qnum 200 --server
|
||||
nfqws2 --qnum=200 --server
|
||||
--lua-init=@/opt/zapret2/lua/zapret-lib.lua
|
||||
--lua-init=@/opt/zapret2/lua/zapret-obfs.lua
|
||||
--in-range=a
|
||||
|
||||
+12
-2
@@ -86,6 +86,7 @@ end
|
||||
|
||||
-- nfqws1 : "--dup"
|
||||
-- standard args : direction, fooling, ip_id, ipfrag, rawsend, reconstruct
|
||||
-- arg : delay=<msec> - drop and send delayed
|
||||
function send(ctx, desync)
|
||||
direction_cutoff_opposite(ctx, desync, "any")
|
||||
if direction_check(desync, "any") then
|
||||
@@ -93,10 +94,19 @@ function send(ctx, desync)
|
||||
local dis = deepcopy(desync.dis)
|
||||
apply_fooling(desync, dis)
|
||||
apply_ip_id(desync, dis, nil, "none")
|
||||
-- it uses rawsend, reconstruct and ipfrag options
|
||||
rawsend_dissect_ipfrag(dis, desync_opts(desync))
|
||||
if desync.arg.delay then
|
||||
local tname = "send_"..desync_timer_name(desync)
|
||||
timer_set(tname, "send_timer_delayed", tonumber(desync.arg.delay), true, {dis = dis, opts = desync_opts(desync)})
|
||||
else
|
||||
-- it uses rawsend, reconstruct and ipfrag options
|
||||
rawsend_dissect_ipfrag(dis, desync_opts(desync))
|
||||
end
|
||||
end
|
||||
end
|
||||
function send_timer_delayed(name, data)
|
||||
-- oneshot timer, auto deletes
|
||||
rawsend_dissect_ipfrag(data.dis, data.opts)
|
||||
end
|
||||
|
||||
-- nfqws1 : "--orig"
|
||||
-- apply modification to current packet
|
||||
|
||||
+64
-4
@@ -1,4 +1,4 @@
|
||||
NFQWS2_COMPAT_VER_REQUIRED=5
|
||||
NFQWS2_COMPAT_VER_REQUIRED=6
|
||||
|
||||
if NFQWS2_COMPAT_VER~=NFQWS2_COMPAT_VER_REQUIRED then
|
||||
error("Incompatible NFQWS2_COMPAT_VER. Use pktws and lua scripts from the same release !")
|
||||
@@ -761,6 +761,63 @@ function fix_ip6_next(ip6, last_proto)
|
||||
end
|
||||
end
|
||||
|
||||
function dis_ipsrc(dis)
|
||||
if dis.ip then
|
||||
return dis.ip.ip_src
|
||||
elseif dis.ip6 then
|
||||
return dis.ip6.ip6_src
|
||||
end
|
||||
end
|
||||
function dis_ipdst(dis)
|
||||
if dis.ip then
|
||||
return dis.ip.ip_dst
|
||||
elseif dis.ip6 then
|
||||
return dis.ip6.ip6_dst
|
||||
end
|
||||
end
|
||||
|
||||
function dis_l4_name(dis)
|
||||
local l4
|
||||
if dis.tcp then
|
||||
l4="tcp"
|
||||
elseif dis.udp then
|
||||
l4="udp"
|
||||
elseif dis.icmp then
|
||||
l4="icmp"
|
||||
else
|
||||
l4="raw"..ip_proto_l3(dis)
|
||||
end
|
||||
return l4
|
||||
end
|
||||
function dis_l4_ports(dis)
|
||||
local p1,p2
|
||||
if dis.tcp then
|
||||
p1=dis.tcp.th_sport
|
||||
p2=dis.tcp.th_dport
|
||||
elseif dis.udp then
|
||||
p1=dis.udp.uh_sport
|
||||
p2=dis.udp.uh_dport
|
||||
elseif dis.icmp then
|
||||
p1=dis.icmp.icmp_type
|
||||
p2=dis.icmp.icmp_code
|
||||
end
|
||||
return p1 and (p1..":"..p2) or "?"
|
||||
end
|
||||
|
||||
function dis_timer_name(dis)
|
||||
return table.concat({ntop(dis_ipsrc(dis)),"->",ntop(dis_ipdst(dis)),"_",dis_l4_name(dis),"_",dis_l4_ports(dis)})
|
||||
end
|
||||
function desync_timer_name(desync)
|
||||
local name = dis_timer_name(desync.dis)
|
||||
if desync.track then
|
||||
name = name.."_n"..desync.track.pos.direct.pcounter
|
||||
else
|
||||
name = name.."_"..brandom_az09(10)
|
||||
end
|
||||
return name
|
||||
end
|
||||
|
||||
|
||||
-- reverses ip addresses, ports and seq/ack
|
||||
function dis_reverse(dis)
|
||||
if dis.ip then
|
||||
@@ -1193,7 +1250,9 @@ function rawsend_dissect_segmented(desync, dis, mss, options)
|
||||
len = #payload - pos + 1
|
||||
if len > max_data then len = max_data end
|
||||
if oob then
|
||||
if urp>=pos and urp<(pos+len)then
|
||||
if urp==0 and pos==1 then
|
||||
discopy.tcp.th_flags = bitor(discopy.tcp.th_flags, TH_URG)
|
||||
elseif urp>=pos and urp<(pos+len) then
|
||||
discopy.tcp.th_flags = bitor(discopy.tcp.th_flags, TH_URG)
|
||||
discopy.tcp.th_urp = urp-pos+1
|
||||
else
|
||||
@@ -1376,9 +1435,9 @@ end
|
||||
function append_path(path,file)
|
||||
return string.sub(path,#path,#path)=='/' and path..file or path.."/"..file
|
||||
end
|
||||
function writeable_file_name(filename)
|
||||
function writable_file_name(filename)
|
||||
if is_absolute_path(filename) then return filename end
|
||||
local writedir = os.getenv("WRITEABLE")
|
||||
local writedir = os.getenv("WRITABLE")
|
||||
if not writedir then return filename end
|
||||
return append_path(writedir, filename)
|
||||
end
|
||||
@@ -1690,6 +1749,7 @@ function writefile(filename, data)
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
-- DISSECTORS
|
||||
|
||||
function http_dissect_header(header)
|
||||
|
||||
+3
-3
@@ -15,8 +15,8 @@ function pcap_write(file, raw)
|
||||
pcap_write_packet(file, raw)
|
||||
end
|
||||
|
||||
-- test case : --writeable=zdir --in-range=a --lua-desync=pcap:file=test.pcap
|
||||
-- arg : file=<filename> - file for storing pcap data. if --writeable is specified and filename is relative - append filename to writeable path
|
||||
-- test case : --writable=zdir --in-range=a --lua-desync=pcap:file=test.pcap
|
||||
-- arg : file=<filename> - file for storing pcap data. if --writable is specified and filename is relative - append filename to writable path
|
||||
-- arg : keep - do not overwrite file, append packets to existing
|
||||
function pcap(ctx, desync)
|
||||
if not desync.arg.file or #desync.arg.file==0 then
|
||||
@@ -24,7 +24,7 @@ function pcap(ctx, desync)
|
||||
end
|
||||
local fn_cache_name = desync.func_instance.."_fn"
|
||||
if not _G[fn_cache_name] then
|
||||
_G[fn_cache_name] = writeable_file_name(desync.arg.file)
|
||||
_G[fn_cache_name] = writable_file_name(desync.arg.file)
|
||||
if not desync.arg.keep then
|
||||
-- overwrite file
|
||||
os.remove(_G[fn_cache_name])
|
||||
|
||||
+4
-4
@@ -2478,11 +2478,11 @@ bool set_socket_buffers(int fd, int rcvbuf, int sndbuf)
|
||||
return true;
|
||||
}
|
||||
|
||||
bool make_writeable_dir()
|
||||
bool make_writable_dir()
|
||||
{
|
||||
char wdir[PATH_MAX], *wrdir;
|
||||
if (*params.writeable_dir)
|
||||
wrdir = params.writeable_dir;
|
||||
if (*params.writable_dir)
|
||||
wrdir = params.writable_dir;
|
||||
else
|
||||
{
|
||||
#ifdef __CYGWIN__
|
||||
@@ -2516,6 +2516,6 @@ bool make_writeable_dir()
|
||||
}
|
||||
}
|
||||
#endif
|
||||
if (b) setenv("WRITEABLE",wrdir,1);
|
||||
if (b) setenv("WRITABLE",wrdir,1);
|
||||
return b;
|
||||
}
|
||||
+1
-1
@@ -121,7 +121,7 @@ bool tcp_synack_segment(const struct tcphdr *tcphdr);
|
||||
bool tcp_syn_segment(const struct tcphdr *tcphdr);
|
||||
|
||||
|
||||
bool make_writeable_dir();
|
||||
bool make_writable_dir();
|
||||
bool ensure_file_access(const char *filename);
|
||||
#ifdef __CYGWIN__
|
||||
extern uint32_t w_win32_error;
|
||||
|
||||
+12
-12
@@ -605,10 +605,10 @@ exok:
|
||||
res=0;
|
||||
ex:
|
||||
if (Fpid) fclose(Fpid);
|
||||
if (cbdata.sock>=0) close(cbdata.sock);
|
||||
free(cbdata.mod);
|
||||
free(buf);
|
||||
nfq_deinit(&h, &qh);
|
||||
if (cbdata.sock>=0) close(cbdata.sock);
|
||||
lua_shutdown();
|
||||
#ifdef HAS_FILTER_SSID
|
||||
wlan_info_deinit();
|
||||
@@ -1866,7 +1866,7 @@ static void exithelp(void)
|
||||
" --nlm-list[=all]\t\t\t\t\t; list Network List Manager (NLM) networks. connected only or all.\n"
|
||||
#endif
|
||||
"\nDESYNC ENGINE INIT:\n"
|
||||
" --writeable[=<dir_name>]\t\t\t\t; create writeable dir for LUA scripts and pass it in WRITEABLE env variable (only one dir possible)\n"
|
||||
" --writable[=<dir_name>]\t\t\t\t; create writable dir for LUA scripts and pass it in WRITABLE env variable (only one dir possible)\n"
|
||||
" --blob=<item_name>:[+ofs]@<filename>|0xHEX\t\t; load blob to LUA var <item_name>\n"
|
||||
" --lua-init=@<filename>|<lua_text>\t\t\t; load LUA program from a file or string. if multiple parameters present order of execution is preserved. gzipped files are supported.\n"
|
||||
" --lua-gc=<int>\t\t\t\t\t\t; forced garbage collection every N sec. default %u sec. triggers only when a packet arrives. 0 = disable.\n"
|
||||
@@ -2003,7 +2003,7 @@ enum opt_indices {
|
||||
IDX_SOCKARG,
|
||||
#endif
|
||||
|
||||
IDX_WRITEABLE,
|
||||
IDX_WRITABLE,
|
||||
|
||||
IDX_BLOB,
|
||||
IDX_LUA_INIT,
|
||||
@@ -2107,7 +2107,7 @@ static const struct option long_options[] = {
|
||||
#elif defined(SO_USER_COOKIE)
|
||||
[IDX_SOCKARG] = {"sockarg", required_argument, 0, 0},
|
||||
#endif
|
||||
[IDX_WRITEABLE] = {"writeable", optional_argument, 0, 0},
|
||||
[IDX_WRITABLE] = {"writable", optional_argument, 0, 0},
|
||||
[IDX_BLOB] = {"blob", required_argument, 0, 0},
|
||||
[IDX_LUA_INIT] = {"lua-init", required_argument, 0, 0},
|
||||
[IDX_LUA_GC] = {"lua-gc", required_argument, 0, 0},
|
||||
@@ -2519,18 +2519,18 @@ int main(int argc, char **argv)
|
||||
}
|
||||
break;
|
||||
#endif
|
||||
case IDX_WRITEABLE:
|
||||
params.writeable_dir_enable = true;
|
||||
case IDX_WRITABLE:
|
||||
params.writable_dir_enable = true;
|
||||
if (optarg)
|
||||
{
|
||||
if (!realpath_any(optarg, params.writeable_dir))
|
||||
if (!realpath_any(optarg, params.writable_dir))
|
||||
{
|
||||
DLOG_ERR("bad file '%s'\n",optarg);
|
||||
exit_clean(1);
|
||||
}
|
||||
}
|
||||
else
|
||||
*params.writeable_dir = 0;
|
||||
*params.writable_dir = 0;
|
||||
break;
|
||||
|
||||
case IDX_BLOB:
|
||||
@@ -3148,14 +3148,14 @@ int main(int argc, char **argv)
|
||||
DLOG_CONDUP("we have %u user defined desync profile(s) and default low priority profile 0\n", desync_profile_count);
|
||||
DLOG_CONDUP("we have %u user defined desync template(s)\n", desync_template_count);
|
||||
|
||||
if (params.writeable_dir_enable)
|
||||
if (params.writable_dir_enable)
|
||||
{
|
||||
if (!make_writeable_dir())
|
||||
if (!make_writable_dir())
|
||||
{
|
||||
DLOG_ERR("could not make writeable dir for LUA\n");
|
||||
DLOG_ERR("could not make writable dir for LUA\n");
|
||||
exit_clean(1);
|
||||
}
|
||||
DLOG("LUA writeable dir : %s\n", getenv("WRITEABLE"));
|
||||
DLOG("LUA writable dir : %s\n", getenv("WRITABLE"));
|
||||
}
|
||||
#ifndef __CYGWIN__
|
||||
if (params.droproot)
|
||||
|
||||
+1
-1
@@ -10,4 +10,4 @@ extern volatile sig_atomic_t bQuit;
|
||||
int main(int argc, char *argv[]);
|
||||
|
||||
// when something changes that can break LUA compatibility this version should be increased
|
||||
#define LUA_COMPAT_VER 5
|
||||
#define LUA_COMPAT_VER 6
|
||||
+2
-2
@@ -190,8 +190,8 @@ struct params_s
|
||||
uint64_t payload_disable;
|
||||
|
||||
struct str_list_head lua_init_scripts;
|
||||
bool writeable_dir_enable;
|
||||
char writeable_dir[PATH_MAX];
|
||||
bool writable_dir_enable;
|
||||
char writable_dir[PATH_MAX];
|
||||
|
||||
timer_pool *timers;
|
||||
bool timers_dirty; // changed something in timers
|
||||
|
||||
+11
-11
@@ -42,6 +42,7 @@ struct timer_pool *TimerPoolSearch(timer_pool *p, const char *str)
|
||||
struct timer_pool *TimerPoolAdd(timer_pool **pp, const char *str, const char *func, uint64_t period, bool oneshot)
|
||||
{
|
||||
ADD_STR_POOL(timer_pool, pp, str, strlen(str))
|
||||
elem->lua_ref = LUA_NOREF;
|
||||
if (!(elem->func = strdup(func)))
|
||||
{
|
||||
TimerPoolDel(pp,elem);
|
||||
@@ -49,8 +50,7 @@ struct timer_pool *TimerPoolAdd(timer_pool **pp, const char *str, const char *fu
|
||||
}
|
||||
elem->period = period;
|
||||
elem->oneshot = oneshot;
|
||||
elem->lua_ref = LUA_NOREF;
|
||||
elem->bt_prev = boottime_ms();
|
||||
elem->bt_next = boottime_ms() + elem->period;
|
||||
elem->n = ++timer_n;
|
||||
elem->fires = 0;
|
||||
return elem;
|
||||
@@ -80,14 +80,13 @@ static bool TimerPoolRunTimer(timer_pool *p)
|
||||
uint64_t TimerPoolNext(const timer_pool *p, bool *dirty)
|
||||
{
|
||||
const timer_pool *elem, *tmp;
|
||||
uint64_t nexttime, mintime=0x7FFFFFFFFFFFFFFF;
|
||||
uint64_t mintime=0x7FFFFFFFFFFFFFFF;
|
||||
|
||||
if (!p) return 0;
|
||||
|
||||
HASH_ITER(hh, p, elem, tmp)
|
||||
{
|
||||
nexttime = elem->bt_prev + elem->period;
|
||||
if (nexttime<mintime) mintime = nexttime;
|
||||
if (elem->bt_next < mintime) mintime = elem->bt_next;
|
||||
}
|
||||
*dirty = false;
|
||||
return mintime;
|
||||
@@ -101,13 +100,12 @@ uint64_t TimerPoolRun(timer_pool **pp, bool *dirty, uint64_t bt)
|
||||
char *name;
|
||||
const char *del;
|
||||
unsigned int n;
|
||||
uint64_t nexttime, mintime=0x7FFFFFFFFFFFFFFF;
|
||||
uint64_t mintime=0x7FFFFFFFFFFFFFFF;
|
||||
|
||||
if (!bt) bt = boottime_ms();
|
||||
HASH_ITER(hh, *pp, elem, tmp)
|
||||
{
|
||||
nexttime = elem->bt_prev + elem->period;
|
||||
if (bt >= nexttime)
|
||||
if (bt >= elem->bt_next)
|
||||
{
|
||||
if (!(name = strdup(elem->str)))
|
||||
return 0;
|
||||
@@ -132,8 +130,10 @@ uint64_t TimerPoolRun(timer_pool **pp, bool *dirty, uint64_t bt)
|
||||
}
|
||||
else
|
||||
{
|
||||
elem->bt_prev = bt;
|
||||
nexttime = elem->bt_prev + elem->period;
|
||||
// in case process was freezed (--ssid-filter/nlm-filter stop in winws for example)
|
||||
// do not use previous activation time or timer can hit multiple times
|
||||
// use current time instead to prevent bulk activation
|
||||
elem->bt_next = bt + elem->period;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -141,7 +141,7 @@ uint64_t TimerPoolRun(timer_pool **pp, bool *dirty, uint64_t bt)
|
||||
}
|
||||
if (elem)
|
||||
{
|
||||
if (nexttime<mintime) mintime = nexttime;
|
||||
if (elem->bt_next < mintime) mintime = elem->bt_next;
|
||||
}
|
||||
}
|
||||
if (!*pp) return 0; // no timers
|
||||
|
||||
+1
-1
@@ -11,7 +11,7 @@ typedef struct timer_pool {
|
||||
uint64_t period;
|
||||
bool oneshot;
|
||||
int lua_ref;
|
||||
uint64_t bt_prev;
|
||||
uint64_t bt_next; /* next activation time */
|
||||
unsigned int n, fires;
|
||||
UT_hash_handle hh; /* makes this structure hashable */
|
||||
} timer_pool;
|
||||
|
||||
Reference in new issue
Block a user