1 /*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "src/tracing/core/packet_stream_validator.h"
18
19 #include <stddef.h>
20
21 #include <cinttypes>
22
23 #include "perfetto/base/logging.h"
24 #include "perfetto/ext/base/utils.h"
25 #include "perfetto/protozero/proto_utils.h"
26
27 #include "protos/perfetto/trace/trace_packet.pbzero.h"
28
29 namespace perfetto {
30
31 namespace {
32
33 using protozero::proto_utils::ProtoWireType;
34
35 const uint32_t kReservedFieldIds[] = {
36 protos::pbzero::TracePacket::kTrustedUidFieldNumber,
37 protos::pbzero::TracePacket::kTrustedPacketSequenceIdFieldNumber,
38 protos::pbzero::TracePacket::kTraceConfigFieldNumber,
39 protos::pbzero::TracePacket::kTraceStatsFieldNumber,
40 protos::pbzero::TracePacket::kCompressedPacketsFieldNumber,
41 protos::pbzero::TracePacket::kSynchronizationMarkerFieldNumber,
42 protos::pbzero::TracePacket::kTrustedPidFieldNumber,
43 };
44
45 // This translation unit is quite subtle and perf-sensitive. Remember to check
46 // BM_PacketStreamValidator in perfetto_benchmarks when making changes.
47
48 // Checks that a packet, spread over several slices, is well-formed and doesn't
49 // contain reserved top-level fields.
50 // The checking logic is based on a state-machine that skips the fields' payload
51 // and operates as follows:
52 // +-------------------------------+ <-------------------------+
53 // +----------> | Read field preamble (varint) | <----------------------+ |
54 // | +-------------------------------+ | |
55 // | | | | | |
56 // | <Varint> <Fixed 32/64> <Length-delimited field> | |
57 // | V | V | |
58 // | +------------------+ | +--------------+ | |
59 // | | Read field value | | | Read length | | |
60 // | | (another varint) | | | (varint) | | |
61 // | +------------------+ | +--------------+ | |
62 // | | V V | |
63 // +-----------+ +----------------+ +-----------------+ | |
64 // | Skip 4/8 Bytes | | Skip $len Bytes |-------+ |
65 // +----------------+ +-----------------+ |
66 // | |
67 // +------------------------------------------+
68 class ProtoFieldParserFSM {
69 public:
70 // This method effectively continuously parses varints (either for the field
71 // preamble or the payload or the submessage length) and tells the caller
72 // (the Validate() method) how many bytes to skip until the next field.
Push(uint8_t octet)73 size_t Push(uint8_t octet) {
74 varint_ |= static_cast<uint64_t>(octet & 0x7F) << varint_shift_;
75 if (octet & 0x80) {
76 varint_shift_ += 7;
77 if (varint_shift_ >= 64) {
78 // Do not invoke UB on next call.
79 varint_shift_ = 0;
80 state_ = kInvalidVarInt;
81 }
82 return 0;
83 }
84 uint64_t varint = varint_;
85 varint_ = 0;
86 varint_shift_ = 0;
87
88 switch (state_) {
89 case kFieldPreamble: {
90 uint64_t field_type = varint & 7; // 7 = 0..0111
91 auto field_id = static_cast<uint32_t>(varint >> 3);
92 // Check if the field id is reserved, go into an error state if it is.
93 for (size_t i = 0; i < base::ArraySize(kReservedFieldIds); ++i) {
94 if (field_id == kReservedFieldIds[i]) {
95 state_ = kWroteReservedField;
96 return 0;
97 }
98 }
99 // The field type is legit, now check it's well formed and within
100 // boundaries.
101 if (field_type == static_cast<uint64_t>(ProtoWireType::kVarInt)) {
102 state_ = kVarIntValue;
103 } else if (field_type ==
104 static_cast<uint64_t>(ProtoWireType::kFixed32)) {
105 return 4;
106 } else if (field_type ==
107 static_cast<uint64_t>(ProtoWireType::kFixed64)) {
108 return 8;
109 } else if (field_type ==
110 static_cast<uint64_t>(ProtoWireType::kLengthDelimited)) {
111 state_ = kLenDelimitedLen;
112 } else {
113 state_ = kUnknownFieldType;
114 }
115 return 0;
116 }
117
118 case kVarIntValue: {
119 // Consume the int field payload and go back to the next field.
120 state_ = kFieldPreamble;
121 return 0;
122 }
123
124 case kLenDelimitedLen: {
125 if (varint > protozero::proto_utils::kMaxMessageLength) {
126 state_ = kMessageTooBig;
127 return 0;
128 }
129 state_ = kFieldPreamble;
130 return static_cast<size_t>(varint);
131 }
132
133 case kWroteReservedField:
134 case kUnknownFieldType:
135 case kMessageTooBig:
136 case kInvalidVarInt:
137 // Persistent error states.
138 return 0;
139
140 } // switch(state_)
141 return 0; // To keep GCC happy.
142 }
143
144 // Queried at the end of the all payload. A message is well-formed only
145 // if the FSM is back to the state where it should parse the next field and
146 // hasn't started parsing any preamble.
valid() const147 bool valid() const { return state_ == kFieldPreamble && varint_shift_ == 0; }
state() const148 int state() const { return static_cast<int>(state_); }
149
150 private:
151 enum State {
152 kFieldPreamble = 0, // Parsing the varint for the field preamble.
153 kVarIntValue, // Parsing the varint value for the field payload.
154 kLenDelimitedLen, // Parsing the length of the length-delimited field.
155
156 // Error states:
157 kWroteReservedField, // Tried to set a reserved field id.
158 kUnknownFieldType, // Encountered an invalid field type.
159 kMessageTooBig, // Size of the length delimited message was too big.
160 kInvalidVarInt, // VarInt larger than 64 bits.
161 };
162
163 State state_ = kFieldPreamble;
164 uint64_t varint_ = 0;
165 uint32_t varint_shift_ = 0;
166 };
167
168 } // namespace
169
170 // static
Validate(const Slices & slices)171 bool PacketStreamValidator::Validate(const Slices& slices) {
172 ProtoFieldParserFSM parser;
173 size_t skip_bytes = 0;
174 for (const Slice& slice : slices) {
175 for (size_t i = 0; i < slice.size;) {
176 const size_t skip_bytes_cur_slice = std::min(skip_bytes, slice.size - i);
177 if (skip_bytes_cur_slice > 0) {
178 i += skip_bytes_cur_slice;
179 skip_bytes -= skip_bytes_cur_slice;
180 } else {
181 uint8_t octet = *(reinterpret_cast<const uint8_t*>(slice.start) + i);
182 skip_bytes = parser.Push(octet);
183 i++;
184 }
185 }
186 }
187 if (skip_bytes == 0 && parser.valid())
188 return true;
189
190 PERFETTO_DLOG("Packet validation error (state %d, skip = %zu)",
191 parser.state(), skip_bytes);
192 return false;
193 }
194
195 } // namespace perfetto
196