1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
//! Contains the implementation logic for unrecognized custom STIX Objects.
use crate::{
base::{CommonPropertiesBuilder, Stix},
custom_objects::object::CustomObject,
error::{CheckContext, Outcome, StixError as Error},
types::{
DictionaryValue, ExtensionType, ExternalReference, Identifier, StixDictionary, Timestamp,
},
};
use serde_json::Value;
use std::{collections::BTreeMap, str::FromStr};
/// Builder struct for Custom Objects.
///
/// This follows the "Rust builder pattern," where we use a `new()` function to construct a Builder
/// with a minimum set of required fields, then set additional fields with their own setter functions.
/// Once all fields have been set, the `build()` function will take all of the fields in the Builder
/// struct and use them to create the final `CustomObject` struct.
#[derive(Clone, Debug)]
pub struct CustomObjectBuilder {
// The object type
object_type: String,
// Common STIX object properties
common_properties: CommonPropertiesBuilder,
// The map of custom properties
custom_properties: BTreeMap<String, Value>,
}
impl CustomObjectBuilder {
/// Creates a new STIX 2.1 `CustomObjectBuilder` for an SDO with a given name, map of custom properties, and extension definition id for the "new-sdo" extension
///
/// Automatically generates an `id`
/// Other fields are set to their Default (which is `None`` for optional fields)
pub fn new_sdo(
type_name: &str,
custom_properties: BTreeMap<String, Value>,
extension_definition: &str,
) -> Result<CustomObjectBuilder, Error> {
// Build the common properties with generated and default values
let default_common_properties = CommonPropertiesBuilder::new("sdo", type_name)?;
// Create a "new-sdo" extension
let mut object_extension = StixDictionary::new();
object_extension.insert(
"extension_type",
DictionaryValue::String("new-sdo".to_string()),
)?;
// Add that extension, with its extension definition id, to the common properties
let common_properties =
default_common_properties.add_extension(extension_definition, object_extension)?;
Ok(CustomObjectBuilder {
object_type: type_name.to_string(),
common_properties,
custom_properties,
})
}
/// Creates a new STIX 2.1 `CustomObjectBuilder` for an SRO with a given name, map of custom properties, and extension definition id for the "new-sro" extension
///
/// Automatically generates an `id`
/// Other fields are set to their Default (which is `None`` for optional fields)
pub fn new_sro(
type_name: &str,
custom_properties: BTreeMap<String, Value>,
extension_definition: &str,
) -> Result<CustomObjectBuilder, Error> {
// Build the common properties with generated and default values
let default_common_properties = CommonPropertiesBuilder::new("sro", type_name)?;
// Create a "new-sro" extension
let mut object_extension = StixDictionary::new();
object_extension.insert(
"extension_type",
DictionaryValue::String("new-sro".to_string()),
)?;
// Add that extension, with its extension definition id, to the common properties
let common_properties =
default_common_properties.add_extension(extension_definition, object_extension)?;
Ok(CustomObjectBuilder {
object_type: type_name.to_string(),
common_properties,
custom_properties,
})
}
/// Creates a new STIX 2.1 `CustomObjectBuilder` for an SCO with a given name, map of custom properties, and extension definition id for the "new-sco" extension
///
/// Automatically generates a UUIDv4-based `id`
/// Other fields are set to their Default (which is `None`` for optional fields)
pub fn new_sco(
type_name: &str,
custom_properties: BTreeMap<String, Value>,
extension_definition: &str,
) -> Result<CustomObjectBuilder, Error> {
// Build the common properties with generated and default values
let default_common_properties = CommonPropertiesBuilder::new("sco", type_name)?;
// Create a "new-sco" extension
let mut object_extension = StixDictionary::new();
object_extension.insert(
"extension_type",
DictionaryValue::String("new-sco".to_string()),
)?;
// Add that extension, with its extension definition id, to the common properties
let common_properties =
default_common_properties.add_extension(extension_definition, object_extension)?;
Ok(CustomObjectBuilder {
object_type: type_name.to_string(),
common_properties,
custom_properties,
})
}
/// Create a `CustomObjectBuilder` from an extension-less generic custom object.
///
/// The builder preserves the parsed object exactly; it does not add a
/// `new-sdo` / `new-sco` / `new-sro` extension.
pub fn from_generic(old: &CustomObject) -> Result<CustomObjectBuilder, Error> {
Ok(CustomObjectBuilder {
object_type: old.object_type.clone(),
common_properties: CommonPropertiesBuilder::from_existing(
"custom",
&old.common_properties,
)?,
custom_properties: old.custom_properties.clone(),
})
}
/// Create a new STIX 2.1 `CustomObjectBuilder` by cloning the fields from an already-parsed
/// `CustomObject`, preserving its `id`, `created`, `modified`, and `revoked` properties exactly.
/// Unlike `version()`, this does not treat the object as the basis for a new version.
pub fn from_parsed(old: &CustomObject) -> Result<CustomObjectBuilder, Error> {
let Some(object_type) = old.get_object_type() else {
return Self::from_generic(old);
};
let object_type_name = old.object_type.clone();
let custom_properties = old.custom_properties.clone();
// Find the extension-definition key that declares this as a custom object.
let ext_def_id = old
.common_properties
.extensions
.as_ref()
.and_then(|exts| {
for (key, ext) in exts.iter() {
if Identifier::from_str(key)
.map(|id| id.get_type() == "extension-definition")
.unwrap_or(false)
{
if let Some(DictionaryValue::String(val)) = ext.get("extension_type") {
if val != "property-extension" && val != "toplevel-property-extension" {
return Some(key.as_str());
}
}
}
}
None
})
.unwrap_or("extension-definition--00000000-0000-0000-0000-000000000000");
let mut builder = match object_type {
ExtensionType::NewSdo => {
CustomObjectBuilder::new_sdo(&object_type_name, custom_properties, ext_def_id)?
}
ExtensionType::NewSro => {
CustomObjectBuilder::new_sro(&object_type_name, custom_properties, ext_def_id)?
}
ExtensionType::NewSco => {
CustomObjectBuilder::new_sco(&object_type_name, custom_properties, ext_def_id)?
}
_ => unreachable!(),
};
let object_name = match object_type {
ExtensionType::NewSdo => "sdo",
ExtensionType::NewSro => "sro",
ExtensionType::NewSco => "sco",
_ => unreachable!(),
};
builder.common_properties =
CommonPropertiesBuilder::from_existing(object_name, &old.common_properties)?;
Ok(builder)
}
/// Create a new STIX 2.1 `CustomObjectBuilder` by cloning the fields from an existing `CustomObject`
/// When built, this will create `CustomObject` as a newer version of the original object.
///
/// Only custom SDOs and SROs can be versioned
pub fn version(old: &CustomObject) -> Result<CustomObjectBuilder, Error> {
if old.is_revoked() {
return Err(Error::UnableToVersion(format!(
"Custom object {} is revoked. Versioning a revoked object is prohibited.",
old.common_properties.id
)));
}
if old.get_object_type() == Some(ExtensionType::NewSco) {
return Err(Error::UnableToVersion(format!(
"Custom object {} is an SCO. SCOs cannot be versioned.",
old.common_properties.id
)));
}
let object_type = old.object_type.clone();
let old_properties = old.common_properties.clone();
let common_properties = CommonPropertiesBuilder::version("sdo", &old_properties)?;
let custom_properties = old.custom_properties.clone();
Ok(CustomObjectBuilder {
object_type,
common_properties,
custom_properties,
})
}
// Setter functions for optional common properties
/// Set the optional `created_by_ref` field for a custom object under construction.
/// This is only allowed when creating a new object, not when versioning an existing one,
/// as only the original creator of an object can version it.
pub fn created_by_ref(mut self, id: Identifier) -> Result<Self, Error> {
self.common_properties = self.common_properties.clone().created_by_ref(id)?;
Ok(self)
}
/// Set the optional `labels` field for a custom object under construction.
pub fn labels(mut self, labels: Vec<String>) -> Self {
self.common_properties = self.common_properties.clone().labels(labels);
self
}
/// Set the optional `confidence` field for a custom object under construction.
pub fn confidence(mut self, confidence: u8) -> Self {
self.common_properties = self.common_properties.clone().confidence(confidence);
self
}
/// Set the optional `lang` field for a custom object under construction.
/// If the language is English ("en"), this does not need to be set (but it can be if specificity is desired).
pub fn lang(mut self, language: String) -> Self {
self.common_properties = self.common_properties.clone().lang(language);
self
}
/// Set the `created` timestamp for a custom object under construction.
pub fn created(mut self, created: Timestamp) -> Self {
self.common_properties = self.common_properties.clone().created(created);
self
}
/// Set the `modified` timestamp for a custom object under construction.
pub fn modified(mut self, modified: Timestamp) -> Self {
self.common_properties = self.common_properties.clone().modified(modified);
self
}
/// Set the optional `external_references` field for a custom object under construction.
pub fn external_references(mut self, references: Vec<ExternalReference>) -> Self {
self.common_properties = self
.common_properties
.clone()
.external_references(references);
self
}
/// Set the optional `object_marking_refs` field for a custom object under construction.
pub fn object_marking_refs(mut self, references: Vec<Identifier>) -> Self {
self.common_properties = self
.common_properties
.clone()
.object_marking_refs(references);
self
}
/// Add an additional extension to the `extensions` field for a custom object under construction
pub fn add_extension(
mut self,
key: &str,
extension: StixDictionary<DictionaryValue>,
) -> Result<Self, Error> {
self.common_properties = self
.common_properties
.clone()
.add_extension(key, extension)?;
Ok(self)
}
/// Builds a new custom STIX object without running validation.
///
/// This assembles the final `CustomObject` from the builder, skipping the
/// object-specific validation. It is intended for callers that have already
/// validated the object and only need its typed representation
/// (e.g. serialization).
pub fn build_no_validate(self) -> Result<CustomObject, Error> {
let common_properties = self.common_properties.build();
let object = CustomObject {
object_type: self.object_type,
common_properties,
custom_properties: self.custom_properties,
};
Ok(object)
}
/// Builds a new custom STIX object, using the information found in the
/// `CustomObjectBuilder`.
///
/// This assembles the final `CustomObject` and runs validation on it.
pub fn build(self) -> Result<CustomObject, Error> {
let object = self.build_no_validate()?;
object.stix_check()?;
Ok(object)
}
/// Builds the object and returns its validation outcome, including warnings.
pub fn build_outcome(self) -> Outcome<CustomObject> {
let object = match self.build_no_validate() {
Ok(object) => object,
Err(error) => return Outcome::err(error, Vec::new()),
};
let mut ctx = CheckContext::new();
let result = object.check(&mut ctx).map(|()| object);
Outcome::from_result(result, ctx.into_warnings())
}
}