From 8a06e3469002f27b42271746da23ceb91788ed65 Mon Sep 17 00:00:00 2001 From: "Victor M. Alvarez" Date: Tue, 11 Jan 2022 13:59:39 +0100 Subject: [PATCH] Fix issue while serializing unary operators to protobuf. --- serialize.go | 20 ++++++++++++++++++++ tests/grammar_test.go | 10 ++++++++++ 2 files changed, 30 insertions(+) diff --git a/serialize.go b/serialize.go index c32a4bf..e4949fe 100644 --- a/serialize.go +++ b/serialize.go @@ -54,6 +54,11 @@ var stringSetKeywords = map[pb.StringSetKeyword]string{ pb.StringSetKeyword_THEM: "them", } +var unaryOperators = map[pb.UnaryExpression_Operator]string{ + pb.UnaryExpression_BITWISE_NOT: "~", + pb.UnaryExpression_UNARY_MINUS: "-", +} + var operators = map[pb.BinaryExpression_Operator]string{ pb.BinaryExpression_MATCHES: "matches", pb.BinaryExpression_CONTAINS: "contains", @@ -566,6 +571,8 @@ func (ys *YaraSerializer) SerializeExpression(e *pb.Expression) error { return ys.serializeForOfExpression(e.GetForOfExpression()) case *pb.Expression_BinaryExpression: return ys.serializeBinaryExpression(e.GetBinaryExpression()) + case *pb.Expression_UnaryExpression: + return ys.serializeUnaryExpression(e.GetUnaryExpression()) case *pb.Expression_Text: if err := ys.writeString(`"`); err != nil { return err @@ -886,6 +893,19 @@ func (ys *YaraSerializer) serializeStringSetKeyword(e pb.StringSetKeyword) error return ys.writeString(kw) } +func (ys *YaraSerializer) serializeUnaryExpression(e *pb.UnaryExpression) error { + op, ok := unaryOperators[e.GetOperator()] + if !ok { + return fmt.Errorf(`Unknown unary operator "%v"`, e.GetOperator()) + } + + if err := ys.writeString(op); err != nil { + return err + } + + return ys.SerializeExpression(e.GetExpression()) +} + // Serializes a BinaryExpression. func (ys *YaraSerializer) serializeBinaryExpression(e *pb.BinaryExpression) error { if getExpressionPrecedence(e.Left) < getBinaryExpressionPrecedence(e) { diff --git a/tests/grammar_test.go b/tests/grammar_test.go index 8a9b606..97e3bd5 100644 --- a/tests/grammar_test.go +++ b/tests/grammar_test.go @@ -20,6 +20,16 @@ rule BASIC_BOOL2 { false } +rule OPERATORS1 { + condition: + (1 + 1 - 1) * 2 == 4 % 2 +} + +rule OPERATORS2 { + condition: + -1 != 0 +} + rule HEX_STRING1 { strings: $h1 = { 01 23 45 67 89 AB }