규칙 파일이 있습니다. 각 줄에는 sid:number 및 rev:number가 있습니다.
이 파일을 업데이트된 파일과 비교하고 싶지만 모든 행이 업데이트되지는 않습니다.
동일한 sid:number를 가진 행 중 하나의 rev:number가 더 높으면 이를 더 높은 rev:number로 바꿔야 합니다.
이게 내가 현재 처한 상황이야
grep -oP "sid:[0-9]{0,11}; rev:[0-9]{0,3}" all_rules.rules |
while read line; do
if grep -q "$line" /home/path/update_rules.rules; then
echo updated;
else
echo > /dev/null;
fi
done
다음은 all.rules 파일의 예입니다.
alert udp $HOME_NET any -> any 53 (msg:"ET
TROJAN CopyKittens? Matryoshka DNS Lookup 1 (winupdate64 . com)";
content:"|01 00 00 01 00 00 00 00 00 00|"; depth:10; offset:2;
content:"|0b|winupdate64|03|com|00|"; nocase; distance:0; fast_pattern;
reference:url,www.clearskysec.com/wp-
content/uploads/2017/07/Operation_Wilted_Tulip.pdf; classtype:trojan-
activity; sid:2024495; rev:1;)
alert udp $HOME_NET any -> any 53 (msg:"ET
TROJAN CopyKittens? Matryoshka DNS Lookup 2 (twiter-statics . info)";
content:"|01 00 00 01 00 00 00 00 00 00|"; depth:10; offset:2;
content:"|0e|twiter|2d|statics|04|info|00|"; nocase; distance:0;
fast_pattern; reference:url,www.clearskysec.com/wp-
content/uploads/2017/07/Operation_Wilted_Tulip.pdf;
reference:md5,752240cddda5acb5e8d026cef82e2b54; classtype:trojan-
activity; sid:2024496; rev:1;)
alert udp $HOME_NET any -> any 53 (msg:"ET TROJAN CopyKittens? Cobalt
Strike DNS Lookup (cloudflare-analyse . com)"; content:"|01 00 00 01 00
00 00 00 00 00|"; depth:10; offset:2;
content:"|12|cloudflare|2d|analyse|03|com|00|"; nocase; distance:0;
fast_pattern; threshold:type limit, track by_src, count 1, seconds 60;
reference:url,www.clearskysec.com/wp-
content/uploads/2017/07/Operation_Wilted_Tulip.pdf;
reference:md5,752240cddda5acb5e8d026cef82e2b54; classtype:trojan-
activity; sid:2024497; rev:1;)
다음은 update.rules의 예입니다.
alert tcp $HOME_NET any -> $EXTERNAL_NET $HTTP_PORTS (msg:"ET TROJAN Revcode
RAT CnC"; flow:established,to_server; content:"POST"; http_method;
content:".php"; http_uri; content:"keyauth="; http_client_body;
fast_pattern; depth:8; content:"&key="; http_client_body; distance:0;
content:"&uid="; http_client_body; distance:0; content:!"Referer|3a|";
http_header; content:"WinHttpRequest"; http_header; metadata:
former_category TROJAN; reference:md5,3f652d9bc17a4be3c0e497ea19848344;
classtype:trojan-activity; sid:2024500; rev:1; metadata:affected_product
Windows_XP_Vista_7_8_10_Server_32_64_Bit, attack_target Client_Endpoint,
deployment Perimeter, signature_severity Major, created_at 2017_07_27,
performance_impact Moderate, updated_at 2017_07_27;)
alert udp $HOME_NET any -> any 53 (msg:"ET TROJAN CopyKittens? Matryoshka
DNS Lookup 1 (winupdate64 . com)"; content:"|01 00 00 01 00 00 00 00 00
00|"; depth:10; offset:2; content:"|0b|winupdate64|03|com|00|"; nocase;
distance:0; fast_pattern; reference:url,www.clearskysec.com/wp-
content/uploads/2017/07/Operation_Wilted_Tulip.pdf; classtype:trojan-
activity; sid:2024495; rev:2;)
alert udp $HOME_NET any -> any 53 (msg:"ET TROJAN CopyKittens Matryoshka DNS
Lookup 2 (twiter-statics . info)"; content:"|01 00 00 01 00 00 00 00 00
00|"; depth:10; offset:2; content:"|0e|twiter|2d|statics|04|info|00|";
nocase; distance:0; fast_pattern; metadata: former_category TROJAN;
reference:url,www.clearskysec.com/wp-
content/uploads/2017/07/Operation_Wilted_Tulip.pdf;
reference:md5,752240cddda5acb5e8d026cef82e2b54; classtype:trojan-activity;
sid:2024496; rev:2; metadata:affected_product
Windows_XP_Vista_7_8_10_Server_32_64_Bit, attack_target Client_Endpoint,
deployment Perimeter, signature_severity Major, created_at 2017_07_25,
malware_family Matryoshka, performance_impact Moderate, updated_at
2017_07_25;)
alert udp $HOME_NET any -> any 53 (msg:"ET TROJAN CopyKittens Cobalt Strike
DNS Lookup (cloudflare-analyse . com)"; content:"|01 00 00 01 00 00 00 00 00
00|"; depth:10; offset:2; content:"|12|cloudflare|2d|analyse|03|com|00|";
nocase; distance:0; fast_pattern; threshold:type limit, track by_src, count
1, seconds 60; metadata: former_category TROJAN;
reference:url,www.clearskysec.com/wp-
content/uploads/2017/07/Operation_Wilted_Tulip.pdf;
reference:md5,752240cddda5acb5e8d026cef82e2b54; classtype:trojan-activity;
sid:2024497; rev:2; metadata:affected_product
Windows_XP_Vista_7_8_10_Server_32_64_Bit, attack_target Client_Endpoint,
deployment Perimeter, signature_severity Major, created_at 2017_07_25,
malware_family CobaltStrike, performance_impact Moderate, updated_at
2017_07_26;)
alert tcp $HOME_NET any -> $EXTERNAL_NET $HTTP_PORTS (msg:"ET TROJAN
Win32/BanloadDownloader.XZY Retrieving Payload"; flow:to_server,established;
content:"GET"; http_method; content:"/sosdoudou_V3/"; http_uri;
fast_pattern; content:"WinHttp.WinHttpRequest"; http_header;
content:!"Accept-"; http_header; content:!"Referer|3a 20|"; http_header;
metadata: former_category TROJAN;
reference:md5,98376de10118892f0773617da137c2be
md5,599ea45f5420f948e0836239eb3ce772; classtype:trojan-activity;
sid:2024499; rev:2; metadata:affected_product
Windows_XP_Vista_7_8_10_Server_32_64_Bit, attack_target Client_Endpoint,
deployment Perimeter, signature_severity Major, created_at 2017_07_26,
malware_family Banload, performance_impact Moderate, updated_at 2017_07_26;)
세 가지 동일한 규칙 이 있지만 update.rules sid:2024497
에는 업데이트 개정이 포함되어 있습니다. all.rules 파일의 이전 버전을 update.rules의 최신 버전 규칙으로 바꾸고 싶습니다.sid:2024496
sid:2024495
답변1
이것은 최소한의 테스트로 나에게 효과적입니다.
#!/bin/zsh
typeset -A rule sidrev
while read -r line; do
sid=${${line/*sid:/}/;*/}
rev=${${line/*rev:/}/;*/}
if [[ "$rev" -gt "$sidrev[$sid]" ]]; then
sidrev[$sid]="$rev"
rule[$sid]="$line"
fi
done
echo -E ${(F)rule}
스크립트는 stdin에서 snort 규칙을 읽고 읽은 모든 규칙의 최신 버전을 stdout에 인쇄합니다.
답변2
어떤 종류의 답을 얻으려면 몇 가지 가정을 하십시오. 이러한 가정은 다음과 같습니다.
- 단방향 업데이트: update_rules(또는 입력 파일 2)는 최신 콘텐츠가 포함된 참조 파일입니다.
- 참조 파일에는 최신 버전만 포함되거나 업데이트되는 파일(입력 파일 1)과 최소한 동일한 버전이 포함됩니다.이는 rev(IF2)를 확인하는 대신 실제로 >= rev IF1 자체임을 의미합니다. 아헤동!
- 나는 IF1과 IF2의 차이점에 의존합니다. (행 측면에서) 차이가 얼마나 큰지 잘 모르겠습니다. 이것이 영향을 미칠 수 있습니다.
어쨌든 블라블라는 이제 그만, 고기 부분까지
#!/bin/bash
cp "$1" "copy_$1" #backup file we're going to change
#then only extract sid + rev (cut -f cols) + sort
#do that for both file and diff them with RCS format > see output of script for example
#and filter to keep only the sid (prob worth testing without grep to see output)
var=($(diff -n <(egrep -oe "sid:[0-9]{0,11}; rev:[0-9]{0,3}" $1|sort -k2) <(egrep -oe "sid:[0-9]{0,11}; rev:[0-9]{0,3}" $2|sort -k 2) | egrep -oe "sid:[0-9]{0,11};" ))
#Now loop over each SID
for i in ${var[@]}; do
#Extract line number in IF1
oldline=$(grep -n $i $1|cut -f1 -d:)
#Extract replacement line in IF2
newline=$(grep $i $2.txt)
#awk magic see (note sed was a pain, couldn't get it to work :/) >> https://askubuntu.com/questions/434051/how-to-replace-a-string-on-the-5th-line-of-multiple-text-files
awk -v nline="$oldline" -v repl="$newline" '(NR==nline){$0=repl}1;' "copy_$1" > "f.tmp" && mv "f.tmp" "copy_$1"
done
#then highlight diff between copy and original // you'll still need to mv "copy_$1" "$1" for it to be applied
diff -n "copy_$1" "$1"
이 모든 것을 스크립트로 감싸서 호출하세요.
./my_script.sh all_rules.rules /home/path/update_rules.rules
답변3
당신은 그것에 대해 언급하지 않았지만 , 당신이 언급 한 이후로 그것은 효과가 있다고 perl
생각합니다 . 대신 다중 레벨 연관 배열( 용어에서는 "Hash-of-Hashes" 또는 "HoH")을 사용하는 것이 .awk
sed
grep
perl
awk
perl
awk
#!/usr/bin/perl
use strict;
# array used to keep track of the order each sid was first seen,
# so that they can be printed out in the same order.
# Necessary because perl hashes are inherently un-ordered.
my @order=();
# hashed array to contain the highest rev seen of each sid.
my %S = ();
# count of the number of files we've read completely so far.
my $filenum=0;
while(<>) {
s/^\s*|\s*$//g; # strip leading and trailing spaces
if (m/^$/) { $filenum++ if eof; next }; # skip empty lines
# extract the sid and the rev
my ($sid, $rev) = $_ =~ (m/^.*; sid:(\d+); rev:(\d+)/) ;
# store or update an anonymous hash containing the rev and the entire
# line in the hash, keyed by the sid.
if (defined($S{$sid})) {
$S{$sid} = { rev => $rev, line => $_ } if ( ($rev > $S{$sid}->{rev}) );
} else {
next if ($filenum); # only store sid if we're still reading the 1st file.
push @order, $sid;
$S{$sid} = { rev => $rev, line => $_ };
};
$filenum++ if eof;
};
# if you want output sorted by the sid, comment the first of the next
# two lines and uncomment the second
for my $sid (@order) {
#for my $sid (sort keys %S) {
print $S{$sid}->{line}, "\n";
};
예를 들어 다른 이름으로 저장 ./apply-update.pl
하고 다음과 같이 실행하십시오../apply-update.pl all.rules update.rules > out.rules
새 예제 입력 파일의 출력에는 세 줄만 있습니다(에 표시된 SID가 all.rules
업데이트되었습니다 update.rules
. 즉, "rev:1" 버전 대신 "rev:2").
alert udp $home_net any -> any 53 (msg:"et trojan copykittens? matryoshka dns lookup 1 (winupdate64 . com)"; content:"|01 00 00 01 00 00 00 00 00 00|"; depth:10; offset:2; content:"|0b|winupdate64|03|com|00|"; nocase; distance:0; fast_pattern; reference:url,www.clearskysec.com/wp- content/uploads/2017/07/operation_wilted_tulip.pdf; classtype:trojan- activity; sid:2024495; rev:2;)
alert udp $home_net any -> any 53 (msg:"et trojan copykittens matryoshka dns lookup 2 (twiter-statics . info)"; content:"|01 00 00 01 00 00 00 00 00 00|"; depth:10; offset:2; content:"|0e|twiter|2d|statics|04|info|00|"; nocase; distance:0; fast_pattern; metadata: former_category trojan; reference:url,www.clearskysec.com/wp- content/uploads/2017/07/operation_wilted_tulip.pdf; reference:md5,752240cddda5acb5e8d026cef82e2b54; classtype:trojan-activity; sid:2024496; rev:2; metadata:affected_product windows_xp_vista_7_8_10_server_32_64_bit, attack_target client_endpoint, deployment perimeter, signature_severity major, created_at 2017_07_25, malware_family matryoshka, performance_impact moderate, updated_at 2017_07_25;)
alert udp $home_net any -> any 53 (msg:"et trojan copykittens cobalt strike dns lookup (cloudflare-analyse . com)"; content:"|01 00 00 01 00 00 00 00 00 00|"; depth:10; offset:2; content:"|12|cloudflare|2d|analyse|03|com|00|"; nocase; distance:0; fast_pattern; threshold:type limit, track by_src, count 1, seconds 60; metadata: former_category trojan; reference:url,www.clearskysec.com/wp- content/uploads/2017/07/operation_wilted_tulip.pdf; reference:md5,752240cddda5acb5e8d026cef82e2b54; classtype:trojan-activity; sid:2024497; rev:2; metadata:affected_product windows_xp_vista_7_8_10_server_32_64_bit, attack_target client_endpoint, deployment perimeter, signature_severity major, created_at 2017_07_25, malware_family cobaltstrike, performance_impact moderate, updated_at 2017_07_26;)
이것은 ~이 될 것이다많은기반 버전보다 몇 배 더 빠릅니다. bash
- 쉘 인터프리터의 텍스트 처리 는 perl
또는 . 이와 같은 컴파일된 언어 는 더 빠르겠지만, C에서 이와 같은 것을 작성하려면 아마도 15줄의 Perl(주석이나 빈 줄 제외) 대신 적어도 50~60줄, 어쩌면 수백 줄의 C 코드가 필요할 것입니다.awk
python
C