-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathengine.ts
More file actions
4938 lines (4854 loc) · 186 KB
/
engine.ts
File metadata and controls
4938 lines (4854 loc) · 186 KB
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { defaultProvider } from '@aws-sdk/credential-provider-node';
import { getDefaultRoleAssumerWithWebIdentity } from '@aws-sdk/client-sts';
import { Client as ElkClient } from '@elastic/elasticsearch';
import { Client as OpenClient } from '@opensearch-project/opensearch';
import { AwsSigv4Signer } from '@opensearch-project/opensearch/aws';
import { Promise as BluePromise } from 'bluebird';
import * as R from 'ramda';
import semver from 'semver';
import { SEMATTRS_DB_NAME, SEMATTRS_DB_OPERATION, SEMATTRS_DB_STATEMENT } from '@opentelemetry/semantic-conventions';
import * as jsonpatch from 'fast-json-patch';
import {
buildPagination,
buildPaginationFromEdges,
cursorToOffset,
ES_INDEX_PREFIX,
getIndicesToQuery,
INDEX_DELETED_OBJECTS,
INDEX_DRAFT_OBJECTS,
INDEX_INTERNAL_OBJECTS,
inferIndexFromConceptType,
isDraftIndex,
isEmptyField,
isInferredIndex,
isNotEmptyField,
offsetToCursor,
pascalize,
READ_DATA_INDICES,
READ_DATA_INDICES_WITHOUT_INFERRED,
READ_DATA_INDICES_WITHOUT_INTERNAL_WITHOUT_INFERRED,
READ_ENTITIES_INDICES,
READ_ENTITIES_INDICES_WITHOUT_INFERRED,
READ_INDEX_INFERRED_ENTITIES,
READ_INDEX_INFERRED_RELATIONSHIPS,
READ_INDEX_INTERNAL_OBJECTS,
READ_INDEX_INTERNAL_RELATIONSHIPS,
READ_INDEX_STIX_CORE_RELATIONSHIPS,
READ_INDEX_STIX_CYBER_OBSERVABLE_RELATIONSHIPS,
READ_INDEX_STIX_CYBER_OBSERVABLES,
READ_INDEX_STIX_DOMAIN_OBJECTS,
READ_INDEX_STIX_META_OBJECTS,
READ_INDEX_STIX_META_RELATIONSHIPS,
READ_INDEX_STIX_SIGHTING_RELATIONSHIPS,
READ_PLATFORM_INDICES,
READ_RELATIONSHIPS_INDICES,
READ_RELATIONSHIPS_INDICES_WITHOUT_INFERRED,
UPDATE_OPERATION_ADD,
waitInSec,
WRITE_PLATFORM_INDICES,
} from './utils';
import conf, { booleanConf, extendedErrors, loadCert, logApp, logMigration } from '../config/conf';
import { ComplexSearchError, ConfigurationError, DatabaseError, EngineShardsError, FunctionalError, LockTimeoutError, TYPE_LOCK_ERROR, UnsupportedError } from '../config/errors';
import {
isStixRefRelationship,
isStixRefUnidirectionalRelationship,
RELATION_BORN_IN,
RELATION_CREATED_BY,
RELATION_ETHNICITY,
RELATION_GRANTED_TO,
RELATION_KILL_CHAIN_PHASE,
RELATION_OBJECT_ASSIGNEE,
RELATION_OBJECT_LABEL,
RELATION_OBJECT_MARKING,
RELATION_OBJECT_PARTICIPANT,
STIX_REF_RELATIONSHIP_TYPES,
} from '../schema/stixRefRelationship';
import {
ABSTRACT_BASIC_RELATIONSHIP,
ABSTRACT_STIX_REF_RELATIONSHIP,
BASE_TYPE_RELATION,
buildRefRelationKey,
buildRefRelationSearchKey,
ENTITY_TYPE_IDENTITY,
ID_INFERRED,
ID_INTERNAL,
ID_STANDARD,
IDS_STIX,
isAbstract,
REL_INDEX_PREFIX,
RULE_PREFIX,
} from '../schema/general';
import { isModifiedObject, isUpdatedAtObject } from '../schema/fieldDataAdapter';
import { generateInternalType, getParentTypes } from '../schema/schemaUtils';
import {
ATTRIBUTE_ABSTRACT,
ATTRIBUTE_DESCRIPTION,
ATTRIBUTE_DESCRIPTION_OPENCTI,
ATTRIBUTE_EXPLANATION,
ATTRIBUTE_NAME,
ENTITY_TYPE_LOCATION_CITY,
ENTITY_TYPE_LOCATION_COUNTRY,
ENTITY_TYPE_LOCATION_REGION,
isStixDomainObject,
STIX_ORGANIZATIONS_RESTRICTED,
STIX_ORGANIZATIONS_UNRESTRICTED,
} from '../schema/stixDomainObject';
import { isBasicObject, isStixCoreObject, isStixObject } from '../schema/stixCoreObject';
import { isBasicRelationship, isStixRelationship } from '../schema/stixRelationship';
import { isStixCoreRelationship, RELATION_INDICATES, RELATION_LOCATED_AT, RELATION_PUBLISHES, RELATION_RELATED_TO, STIX_CORE_RELATIONSHIPS } from '../schema/stixCoreRelationship';
import { generateInternalId, INTERNAL_FROM_FIELD, INTERNAL_TO_FIELD } from '../schema/identifier';
import {
BYPASS,
computeUserMemberAccessIds,
controlUserRestrictDeleteAgainstElement,
executionContext,
INTERNAL_USERS,
isBypassUser,
isServiceAccountUser,
isUserHasCapabilities,
MEMBER_ACCESS_ALL,
SYSTEM_USER,
userFilterStoreElements,
} from '../utils/access';
import { isSingleRelationsRef } from '../schema/stixEmbeddedRelationship';
import { now, runtimeFieldObservableValueScript } from '../utils/format';
import { ENTITY_TYPE_KILL_CHAIN_PHASE, ENTITY_TYPE_MARKING_DEFINITION, isStixMetaObject } from '../schema/stixMetaObject';
import { getEntitiesListFromCache, getEntityFromCache } from './cache';
import { refang } from '../utils/refang';
import { ENTITY_TYPE_MIGRATION_STATUS, ENTITY_TYPE_SETTINGS, ENTITY_TYPE_USER, isInternalObject } from '../schema/internalObject';
import { meterManager, telemetry } from '../config/tracing';
import {
isBooleanAttribute,
isDateAttribute,
isDateNumericOrBooleanAttribute,
isNumericAttribute,
isObjectFlatAttribute,
schemaAttributesDefinition,
validateDataBeforeIndexing,
} from '../schema/schema-attributes';
import { convertTypeToStixType } from './stix-2-1-converter';
import { extractEntityRepresentativeName, extractRepresentative } from './entity-representative';
import { checkAndConvertFilters, extractFiltersFromGroup, isFilterGroupNotEmpty } from '../utils/filtering/filtering-utils';
import {
ID_SUBFILTER,
IDS_FILTER,
INSTANCE_DYNAMIC_REGARDING_OF,
INSTANCE_REGARDING_OF,
INSTANCE_REGARDING_OF_DIRECTION_FORCED,
INSTANCE_REGARDING_OF_DIRECTION_REVERSE,
RELATION_INFERRED_SUBFILTER,
RELATION_TYPE_SUBFILTER,
TYPE_FILTER,
} from '../utils/filtering/filtering-constants';
import { type Filter, type FilterGroup, FilterMode, FilterOperator } from '../generated/graphql';
import {
type AttributeDefinition,
authorizedMembers,
baseType,
booleanMapping,
dateMapping,
entityType as entityTypeAttribute,
id as idAttribute,
internalId,
longStringFormats,
numericMapping,
shortMapping,
shortStringFormats,
standardId,
textMapping,
} from '../schema/attribute-definition';
import { connections as connectionsAttribute } from '../modules/attributes/basicRelationship-registrationAttributes';
import { schemaTypesDefinition } from '../schema/schema-types';
import { INTERNAL_RELATIONSHIPS, isInternalRelationship, RELATION_IN_PIR, RELATION_PARTICIPATE_TO } from '../schema/internalRelationship';
import { isStixSightingRelationship, STIX_SIGHTING_RELATIONSHIP } from '../schema/stixSightingRelationship';
import { rule_definitions } from '../rules/rules-definition';
import { buildElasticSortingForAttributeCriteria } from '../utils/sorting';
import { ENTITY_TYPE_DELETE_OPERATION } from '../modules/deleteOperation/deleteOperation-types';
import { buildEntityData } from './data-builder';
import { buildDraftFilter, type BuildDraftFilterOpts, isDraftSupportedEntity } from './draft-utils';
import { controlUserConfidenceAgainstElement } from '../utils/confidence-level';
import { getDraftContext } from '../utils/draftContext';
import { enrichWithRemoteCredentials } from '../config/credentials';
import { ENTITY_TYPE_DRAFT_WORKSPACE } from '../modules/draftWorkspace/draftWorkspace-types';
import { ENTITY_IPV4_ADDR, ENTITY_IPV6_ADDR, isStixCyberObservable } from '../schema/stixCyberObservable';
import { lockResources } from '../lock/master-lock';
import { DRAFT_OPERATION_CREATE, DRAFT_OPERATION_DELETE, DRAFT_OPERATION_DELETE_LINKED, DRAFT_OPERATION_UPDATE_LINKED } from '../modules/draftWorkspace/draftOperations';
import { RELATION_SAMPLE } from '../modules/malwareAnalysis/malwareAnalysis-types';
import { asyncMap } from '../utils/data-processing';
import { doYield } from '../utils/eventloop-utils';
import { RELATION_COVERED } from '../modules/securityCoverage/securityCoverage-types';
import type { AuthContext, AuthUser } from '../types/user';
import type {
BasicConnection,
BasicNodeEdge,
BasicStoreBase,
BasicStoreEntity,
BasicStoreEntityMarkingDefinition,
BasicStoreObject,
BasicStoreRelation,
StoreConnection,
StoreMarkingDefinition,
StoreObject,
StoreRelation,
} from '../types/store';
import type { BasicStoreSettings } from '../types/settings';
import { completeSpecialFilterKeys } from '../utils/filtering/filtering-completeSpecialFilterKeys';
import { IDS_ATTRIBUTES } from '../domain/attribute-utils';
import { schemaRelationsRefDefinition } from '../schema/schema-relationsRef';
import type { FiltersWithNested } from './middleware-loader';
import { pushAll, unshiftAll } from '../utils/arrayUtil';
const ELK_ENGINE = 'elk';
const OPENSEARCH_ENGINE = 'opensearch';
export const ES_MAX_CONCURRENCY: number = conf.get('elasticsearch:max_concurrency');
export const ES_DEFAULT_WILDCARD_PREFIX: boolean = booleanConf('elasticsearch:search_wildcard_prefix', false);
export const ES_DEFAULT_FUZZY: boolean = booleanConf('elasticsearch:search_fuzzy', false);
export const ES_INIT_MAPPING_MIGRATION: string = conf.get('elasticsearch:internal_init_mapping_migration') || 'off'; // off / old / standard
export const ES_IS_OLD_MAPPING: boolean = ES_INIT_MAPPING_MIGRATION === 'old';
export const ES_IS_INIT_MIGRATION: boolean = ES_INIT_MAPPING_MIGRATION === 'standard' || ES_IS_OLD_MAPPING;
export const ES_MINIMUM_FIXED_PAGINATION: number = 20; // When really low pagination is better by default
export const ES_DEFAULT_PAGINATION: number = conf.get('elasticsearch:default_pagination_result') || 500;
export const ES_MAX_PAGINATION: number = conf.get('elasticsearch:max_pagination_result') || 5000;
export const MAX_BULK_OPERATIONS: number = conf.get('elasticsearch:max_bulk_operations') || 5000;
export const MAX_RUNTIME_RESOLUTION_SIZE: number = conf.get('elasticsearch:max_runtime_resolutions') || 5000;
export const MAX_RELATED_CONTAINER_RESOLUTION: number = conf.get('elasticsearch:max_container_resolutions') || 1000;
export const MAX_RELATED_CONTAINER_OBJECT_RESOLUTION: number = conf.get('elasticsearch:max_container_object_resolutions') || 100000;
export const ES_INDEX_PATTERN_SUFFIX: string = conf.get('elasticsearch:index_creation_pattern');
const ES_MAX_RESULT_WINDOW: number = conf.get('elasticsearch:max_result_window') || 100000;
const ES_INDEX_SHARD_NUMBER: number = conf.get('elasticsearch:number_of_shards');
const ES_INDEX_REPLICA_NUMBER: number = conf.get('elasticsearch:number_of_replicas');
const ES_PRIMARY_SHARD_SIZE: string = conf.get('elasticsearch:max_primary_shard_size') || '50gb';
const ES_MAX_DOCS: number = conf.get('elasticsearch:max_docs') || 75000000;
const TOO_MANY_CLAUSES = 'too_many_nested_clauses';
const DOCUMENT_MISSING_EXCEPTION = 'document_missing_exception';
export const ES_RETRY_ON_CONFLICT = 30;
export const BULK_TIMEOUT = '1h';
const ES_MAX_MAPPINGS = 3000;
const MAX_AGGREGATION_SIZE = 100;
const INNER_HITS_WINDOWS_SIZE = 100;
export const ROLE_FROM = 'from';
export const ROLE_TO = 'to';
export const UNIMPACTED_ENTITIES_ROLE = [
`${RELATION_CREATED_BY}_${ROLE_TO}`,
`${RELATION_OBJECT_MARKING}_${ROLE_TO}`,
`${RELATION_OBJECT_ASSIGNEE}_${ROLE_TO}`,
`${RELATION_OBJECT_PARTICIPANT}_${ROLE_TO}`,
`${RELATION_GRANTED_TO}_${ROLE_TO}`,
`${RELATION_OBJECT_LABEL}_${ROLE_TO}`,
`${RELATION_KILL_CHAIN_PHASE}_${ROLE_TO}`,
`${RELATION_PUBLISHES}_${ROLE_FROM}`,
`${RELATION_IN_PIR}_${ROLE_TO}`,
// RELATION_OBJECT
// RELATION_EXTERNAL_REFERENCE
`${RELATION_INDICATES}_${ROLE_TO}`,
];
const LOCATED_AT_CLEANED = [ENTITY_TYPE_LOCATION_REGION, ENTITY_TYPE_LOCATION_COUNTRY];
const UNSUPPORTED_LOCATED_AT = [ENTITY_IPV4_ADDR, ENTITY_IPV6_ADDR, ENTITY_TYPE_LOCATION_CITY];
export const isSpecialNonImpactedCases = (relationshipType: string, fromType: string, toType: string, side: string | null | undefined): boolean => {
// The relationship is a related-to from an observable to "something" (generally, it is an intrusion set, a malware, etc.)
// This is to avoid for instance Emotet having 200K related-to.
// As a consequence, no entities view on the observable side.
if (side === ROLE_TO && relationshipType === RELATION_RELATED_TO && isStixCyberObservable(fromType)) {
return true;
}
// This relationship is a located-at from IPv4 / IPv6 / City to a country or a region
// This is to avoid having too big region entities
// As a consequence, no entities view in city / knowledge / regions,
if (side === ROLE_TO && relationshipType === RELATION_LOCATED_AT && UNSUPPORTED_LOCATED_AT.includes(fromType) && LOCATED_AT_CLEANED.includes(toType)) {
return true;
}
// Rel on the "to" side with targets from any threat to region / country / sector
// Adding March 2025: For the NLQ, we now re-index those relationships for "in regards of threat victimology"
// if (side === ROLE_TO && relationshipType === RELATION_TARGETS && [ENTITY_TYPE_LOCATION_REGION, ENTITY_TYPE_LOCATION_COUNTRY, ENTITY_TYPE_IDENTITY_SECTOR].includes(toType)) {
// return true;
// }
return false;
};
export const isImpactedTypeAndSide = (type: string, fromType: string, toType: string, side: string): boolean => {
if (isSpecialNonImpactedCases(type, fromType, toType, side)) {
return false;
}
return !UNIMPACTED_ENTITIES_ROLE.includes(`${type}_${side}`);
};
export const isImpactedRole = (type: string, fromType: string, toType: string, role: string): boolean => {
if (isSpecialNonImpactedCases(type, fromType, toType, role.split('_').at(1))) {
return false;
}
return !UNIMPACTED_ENTITIES_ROLE.includes(role);
};
let engine: ElkClient | OpenClient;
let isRuntimeSortingEnable = false;
let attachmentProcessorEnabled = false;
export const isAttachmentProcessorEnabled = () => {
return attachmentProcessorEnabled;
};
// The OpenSearch/ELK Body Parser (oebp)
// Starting ELK8+, response are no longer inside a body envelop
// Query wrapping is still accepted in ELK8
const oebp = (queryResult: any): any => {
if (engine instanceof ElkClient) {
return queryResult;
}
return queryResult.body;
};
export const elConfigureAttachmentProcessor = async (): Promise<boolean> => {
let success = true;
if (engine instanceof ElkClient) {
await engine.ingest.putPipeline({
id: 'attachment',
description: 'Extract attachment information',
processors: [
{
attachment: {
field: 'file_data',
remove_binary: true,
},
},
],
}).catch((e) => {
logApp.info('Engine attachment processor configuration fail', { cause: e });
success = false;
});
} else {
await engine.ingest.putPipeline({
id: 'attachment',
body: {
description: 'Extract attachment information',
processors: [
{
attachment: {
field: 'file_data',
},
},
{
remove: {
field: 'file_data',
},
},
],
},
}).catch((e) => {
logApp.info('Engine attachment processor configuration fail', { cause: e });
success = false;
});
}
return success;
};
// Look for the engine version with OpenSearch client
export const searchEngineVersion = async () => {
try {
const { version: { distribution, number }, tagline } = oebp(await (engine as OpenClient).info());
// Try to detect OpenSearch engine, based on https://github.com/opensearch-project/OpenSearch/blame/main/server/src/main/java/org/opensearch/action/main/MainResponse.java
const platform = (distribution === OPENSEARCH_ENGINE || tagline?.includes('OpenSearch')) ? OPENSEARCH_ENGINE : ELK_ENGINE;
return {
platform: platform,
version: number,
} as const;
} catch (e) {
throw ConfigurationError('Search engine seems down', { cause: e });
}
};
export const searchEngineInit = async (): Promise<boolean> => {
// Build the engine configuration
const ca = conf.get('elasticsearch:ssl:ca')
? loadCert(conf.get('elasticsearch:ssl:ca'))
: conf.get('elasticsearch:ssl:ca_plain') || null;
const region = conf.get('opensearch:region');
const elkSearchConfiguration = {
node: conf.get('elasticsearch:url'),
proxy: conf.get('elasticsearch:proxy') || null,
auth: {
username: conf.get('elasticsearch:username') || null,
password: conf.get('elasticsearch:password') || null,
apiKey: conf.get('elasticsearch:api_key') || null,
},
maxRetries: conf.get('elasticsearch:max_retries') || 3,
requestTimeout: conf.get('elasticsearch:request_timeout') || 3600000,
sniffOnStart: booleanConf('elasticsearch:sniff_on_start', false),
ssl: { // For Opensearch 2+ and Elastic 7
ca,
rejectUnauthorized: booleanConf('elasticsearch:ssl:reject_unauthorized', true),
},
tls: { // For Elastic 8+
ca,
rejectUnauthorized: booleanConf('elasticsearch:ssl:reject_unauthorized', true),
},
};
elkSearchConfiguration.auth = await enrichWithRemoteCredentials('elasticsearch', elkSearchConfiguration.auth);
const openSearchConfiguration = {
...elkSearchConfiguration,
...(region ? AwsSigv4Signer({
region,
service: conf.get('opensearch:service') || 'es',
getCredentials: () => {
const credentialsProvider = defaultProvider({
roleAssumerWithWebIdentity: getDefaultRoleAssumerWithWebIdentity({ region }),
});
return credentialsProvider();
},
}) : {}),
};
// Select the correct engine
let engineVersion;
let enginePlatform;
const engineSelector = conf.get('elasticsearch:engine_selector') || 'auto';
const engineCheck = booleanConf('elasticsearch:engine_check', true);
const elasticSearchClient = new ElkClient(elkSearchConfiguration);
const openSearchClient = new OpenClient(openSearchConfiguration);
if (engineSelector === ELK_ENGINE) {
logApp.info(`[SEARCH] Engine ${ELK_ENGINE} client selected by configuration`);
engine = elasticSearchClient;
const searchVersion = await searchEngineVersion();
if (engineCheck && searchVersion.platform !== ELK_ENGINE) {
throw ConfigurationError('Invalid Search engine selector', { configured: engineSelector, detected: searchVersion.platform });
}
enginePlatform = ELK_ENGINE;
engineVersion = searchVersion.version;
} else if (engineSelector === OPENSEARCH_ENGINE) {
logApp.info(`[SEARCH] Engine ${OPENSEARCH_ENGINE} client selected by configuration`);
engine = openSearchClient;
const searchVersion = await searchEngineVersion();
if (engineCheck && searchVersion.platform !== OPENSEARCH_ENGINE) {
throw ConfigurationError('Invalid Search engine selector', { configured: engineSelector, detected: searchVersion.platform });
}
enginePlatform = OPENSEARCH_ENGINE;
engineVersion = searchVersion.version;
} else {
logApp.info(`[SEARCH] Engine client not specified, trying to discover it with ${OPENSEARCH_ENGINE} client`);
engine = openSearchClient;
const searchVersion = await searchEngineVersion();
enginePlatform = searchVersion.platform;
logApp.info(`[SEARCH] Engine detected to ${enginePlatform}`);
engineVersion = searchVersion.version;
engine = enginePlatform === ELK_ENGINE ? elasticSearchClient : openSearchClient;
}
// Setup the platform runtime field option
isRuntimeSortingEnable = enginePlatform === ELK_ENGINE && semver.satisfies(engineVersion, '>=7.12.x');
const runtimeStatus = isRuntimeSortingEnable ? 'enabled' : 'disabled';
// configure attachment processor
attachmentProcessorEnabled = await elConfigureAttachmentProcessor();
logApp.info(`[SEARCH] ${enginePlatform} (${engineVersion}) client selected / runtime sorting ${runtimeStatus} / attachment processor ${attachmentProcessorEnabled ? 'enabled' : 'disabled'}`);
// Everything is fine, return true
return true;
};
export const isRuntimeSortEnable = (): boolean => isRuntimeSortingEnable;
export const elRawSearch = (context: AuthContext, user: AuthUser, types: string[] | string | null, query: any) => {
// Add signal to prevent unwanted warning
// Waiting for https://github.com/elastic/elastic-transport-js/issues/63
const searchOpts = { signal: new AbortController().signal };
const elRawSearchFn = async () => (engine instanceof ElkClient ? engine.search(query, searchOpts) : engine.search(query)).then((r: any) => {
const parsedSearch = oebp(r);
if (parsedSearch._shards.failed > 0) {
// We do not support response with shards failure.
// Result must be always accurate to prevent data duplication and unwanted behaviors
// If any shard fail during query, engine throw a shard exception with shards information
throw EngineShardsError({ shards: parsedSearch._shards });
}
// Return result of the search if everything goes well
return parsedSearch;
});
return telemetry(context, user, `SELECT ${Array.isArray(types) ? types.join(', ') : (types || 'None')}`, {
[SEMATTRS_DB_NAME]: 'search_engine',
[SEMATTRS_DB_OPERATION]: 'read',
[SEMATTRS_DB_STATEMENT]: JSON.stringify(query),
}, elRawSearchFn);
};
export const elRawGet = async (args: { id: string; index: string }) => {
if (engine instanceof ElkClient) {
const r = await engine.get(args);
return oebp(r);
}
const r_1 = await engine.get(args);
return oebp(r_1);
};
export const elRawIndex = async (args: any) => {
if (engine instanceof ElkClient) {
const r = await engine.index(args);
return oebp(r);
}
const r_1 = await engine.index(args);
return oebp(r_1);
};
export const elRawDelete = async (args: any) => {
if (engine instanceof ElkClient) {
const r = await engine.delete(args);
return oebp(r);
}
const r_1 = await engine.delete(args);
return oebp(r_1);
};
export const elRawDeleteByQuery = async (query: any) => {
if (engine instanceof ElkClient) {
const r = await engine.deleteByQuery(query);
return oebp(r);
}
const r_1 = await engine.deleteByQuery(query);
return oebp(r_1);
};
export const elRawBulk = async (args: any) => {
if (engine instanceof ElkClient) {
const r = await engine.bulk(args);
return oebp(r);
}
const r_1 = await engine.bulk(args);
return oebp(r_1);
};
export const elRawUpdateByQuery = async (query: any) => {
if (engine instanceof ElkClient) {
const r = await engine.updateByQuery(query);
return oebp(r);
}
const r_1 = await engine.updateByQuery(query);
return oebp(r_1);
};
export const elRawReindexByQuery = async (query: any) => {
if (engine instanceof ElkClient) {
const r = await engine.reindex(query);
return oebp(r);
}
const r_1 = await engine.reindex(query);
return oebp(r_1);
};
const elOperationForMigration = (operation: (query: any) => Promise<any>): (message: string, index: string, body: any) => Promise<any> => {
const elGetTask = async (taskId: string): Promise<any> => {
const taskArgs = { task_id: taskId };
if (engine instanceof ElkClient) {
const r = await engine.tasks.get(taskArgs);
return oebp(r);
}
const r_1 = await engine.tasks.get(taskArgs);
return oebp(r_1);
};
return async (message: string, index: string, body: any) => {
logMigration.info(`${message} > started`);
// Execute the update by query in async mode
const queryAsync = await operation({
...(index ? { index } : {}),
refresh: true,
wait_for_completion: false,
body,
}).catch((err) => {
throw DatabaseError('Async engine bulk migration fail', { migration: message, cause: err });
});
logMigration.info(`${message} > elastic running task ${queryAsync.task}`);
// Wait 10 seconds for task to initialize
await waitInSec(10);
// Monitor the task until completion
let taskStatus = await elGetTask(queryAsync.task);
while (!taskStatus.completed) {
const { total, updated } = taskStatus.task.status;
logMigration.info(`${message} > in progress - ${updated}/${total}`);
await waitInSec(5);
taskStatus = await elGetTask(queryAsync.task);
}
const timeSec = Math.round(taskStatus.task.running_time_in_nanos / 1e9);
logMigration.info(`${message} > done in ${timeSec} seconds`);
};
};
export const elUpdateByQueryForMigration = elOperationForMigration(elRawUpdateByQuery);
export const elDeleteByQueryForMigration = elOperationForMigration(elRawDeleteByQuery);
export const elReindexByQueryForMigration = elOperationForMigration(elRawReindexByQuery);
const buildUserMemberAccessFilter = (user: AuthUser, opts: { includeAuthorities?: boolean | null; excludeEmptyAuthorizedMembers?: boolean }) => {
const { includeAuthorities = false, excludeEmptyAuthorizedMembers = false } = opts;
const capabilities = user.capabilities.map((c) => c.name);
if (includeAuthorities && capabilities.includes(BYPASS)) {
return [];
}
const userAccessIds = computeUserMemberAccessIds(user);
// if access_users exists, it should have the user access ids
const emptyAuthorizedMembers = { bool: { must_not: { nested: { path: authorizedMembers.name, query: { match_all: {} } } } } };
// condition on authorizedMembers id
const authorizedMembersIdsTerms = { terms: { [`${authorizedMembers.name}.id.keyword`]: [MEMBER_ACCESS_ALL, ...userAccessIds] } };
// condition on group restriction ids
const userGroupsIds = user.groups.map((group) => group.internal_id);
const groupRestrictionCondition = {
bool: {
should: [
{ bool: { must_not: [{ exists: { field: `${authorizedMembers.name}.groups_restriction_ids` } }] } },
{
terms_set: {
[`${authorizedMembers.name}.groups_restriction_ids.keyword`]: {
terms: userGroupsIds,
minimum_should_match_script: {
source: `doc['${authorizedMembers.name}.groups_restriction_ids.keyword'].length`,
},
},
},
},
],
},
};
const authorizedFilters = [
{ bool: { must: [authorizedMembersIdsTerms, groupRestrictionCondition] } },
];
const shouldConditions = [];
if (includeAuthorities) {
const roleIds = user.roles.map((r) => r.id);
const owners = [...userAccessIds, ...capabilities, ...roleIds];
shouldConditions.push({ terms: { 'authorized_authorities.keyword': owners } });
}
if (!excludeEmptyAuthorizedMembers) {
shouldConditions.push(emptyAuthorizedMembers);
}
const bypassAuthorizedMembers = isServiceAccountUser(user);
const nestedQuery = {
nested: {
path: authorizedMembers.name,
query: {
// For service accounts, bypass authorized members restrictions
bool: { should: bypassAuthorizedMembers ? [] : authorizedFilters },
},
},
};
shouldConditions.push(nestedQuery);
return [{ bool: { should: shouldConditions } }];
};
const buildHistoryRestrictions = (user: AuthUser, historyFiltering?: boolean) => {
const restrictions = [];
if (historyFiltering) {
// Compute forbidden fields for the user
const forbiddenAttributes: string[] = [];
const registeredTypes = schemaAttributesDefinition.getRegisteredTypes();
const refTypes = schemaRelationsRefDefinition.getRegisteredTypes();
for (let i = 0; i < registeredTypes.length; i += 1) {
const registeredType = registeredTypes[i];
const attrs = schemaAttributesDefinition.getAttributes(registeredType);
const refs = refTypes.includes(registeredType) ? schemaRelationsRefDefinition.getRelationsRef(registeredType) : [];
const attributes = Array.from(attrs.values());
pushAll(attributes, refs);
const invalidAttrs = attributes.filter((a: AttributeDefinition) =>
!isUserHasCapabilities(user, a.requiredCapabilities));
pushAll(forbiddenAttributes, invalidAttrs.map((a) => registeredType + '--' + a.name));
}
restrictions.push({
bool: {
should: [
{
bool: {
must_not: [
{
nested: {
path: 'context_data.history_changes',
query: {
match_all: {},
},
},
},
],
},
},
{
nested: {
path: 'context_data.history_changes',
inner_hits: {
size: INNER_HITS_WINDOWS_SIZE, // Mandatory
},
query: {
bool: {
must_not: [
{
terms: {
'context_data.history_changes.field.keyword': forbiddenAttributes,
},
},
],
},
},
},
},
],
minimum_should_match: 1,
},
});
}
return restrictions;
};
export const buildDataRestrictions = async (
context: AuthContext,
user: AuthUser,
opts: { includeAuthorities?: boolean | null; historyFiltering?: boolean } | null | undefined = {},
): Promise<{ must: any[]; must_not: any[] }> => {
const must: any[] = [];
const must_not: any[] = [];
// If internal users of the system, we cancel rights checking
if (INTERNAL_USERS[user.id]) {
return { must, must_not };
}
// check user access
pushAll(must, buildUserMemberAccessFilter(user, { includeAuthorities: opts?.includeAuthorities }));
// If user have bypass, no need to check restrictions
if (!isBypassUser(user)) {
// region handle history protection
pushAll(must, buildHistoryRestrictions(user, opts?.historyFiltering));
// endregion
// region Handle marking restrictions
if (user.allowed_marking.length === 0) {
// If user have no marking, he can only access to data with no markings.
must_not.push({ exists: { field: buildRefRelationKey(RELATION_OBJECT_MARKING) } });
} else {
// Compute all markings that the user doesnt have access to
const allMarkings = await getEntitiesListFromCache<StoreMarkingDefinition>(context, SYSTEM_USER, ENTITY_TYPE_MARKING_DEFINITION);
const mustNotHaveOneOf = [];
const userMarkingsIds = new Set(user.allowed_marking.map((m) => m.internal_id));
for (let index = 0; index < allMarkings.length; index += 1) {
const marking = allMarkings[index];
const markingId = marking.internal_id;
if (!userMarkingsIds.has(markingId)) {
mustNotHaveOneOf.push(markingId);
}
}
// If use have marking, he can access to data with no marking && data with according marking
const mustNotMarkingTerms = [{
terms: {
[buildRefRelationSearchKey(RELATION_OBJECT_MARKING)]: mustNotHaveOneOf,
},
}];
const markingBool = {
bool: {
should: [
{
bool: {
must_not: [{ exists: { field: buildRefRelationSearchKey(RELATION_OBJECT_MARKING) } }],
},
},
{
bool: {
must_not: mustNotMarkingTerms,
},
},
],
minimum_should_match: 1,
},
};
must.push(markingBool);
}
// endregion
// region Handle organization restrictions
// If user have organization management role, he can bypass this restriction.
// If platform is for specific organization, only user from this organization can access empty defined
const settings = await getEntityFromCache<BasicStoreSettings>(context, user, ENTITY_TYPE_SETTINGS);
// We want to exclude a set of entities from organization restrictions while forcing restrictions for another set of entities
const excludedEntityMatches = {
bool: {
must: [
{
bool: { must_not: [{ terms: { 'entity_type.keyword': STIX_ORGANIZATIONS_RESTRICTED } }] },
},
{
bool: {
should: [
{ terms: { 'parent_types.keyword': STIX_ORGANIZATIONS_UNRESTRICTED } },
{ terms: { 'entity_type.keyword': STIX_ORGANIZATIONS_UNRESTRICTED } },
],
minimum_should_match: 1,
},
},
],
},
};
if (settings.platform_organization) {
if (context.user_inside_platform_organization) {
// Data are visible independently of the organizations
// Nothing to restrict.
} else {
// Data with Empty granted_refs are not visible
// Data with granted_refs users that participate to at least one
const should: any[] = [excludedEntityMatches];
const shouldOrgs = user.organizations
.map((m) => ({ match: { [buildRefRelationSearchKey(RELATION_GRANTED_TO)]: m.internal_id } }));
pushAll(should, shouldOrgs);
// User individual or data created by this individual must be accessible
if (user.individual_id) {
should.push({ match: { 'internal_id.keyword': user.individual_id } });
should.push({ match: { [buildRefRelationSearchKey(RELATION_CREATED_BY)]: user.individual_id } });
}
// For tasks
should.push({ match: { 'initiator_id.keyword': user.internal_id } });
// Access to authorized members
pushAll(should, buildUserMemberAccessFilter(user, { includeAuthorities: opts?.includeAuthorities, excludeEmptyAuthorizedMembers: true }));
// Finally build the bool should search
must.push({ bool: { should, minimum_should_match: 1 } });
}
}
// endregion
}
return { must, must_not };
};
export const elIndexExists = async (indexName: string): Promise<boolean> => {
const indexExistsArg = { index: indexName };
if (engine instanceof ElkClient) {
return engine.indices.exists(indexExistsArg);
}
const existOpenSearchResult = await engine.indices.exists(indexExistsArg);
return oebp(existOpenSearchResult) === true || existOpenSearchResult.body === true;
};
export const elIndexGetAlias = async (indexName: string): Promise<any> => {
const args = { index: indexName };
if (engine instanceof ElkClient) {
const r = await engine.indices.getAlias(args);
return oebp(r);
}
const r_1 = await engine.indices.getAlias(args);
return oebp(r_1);
};
export const elPlatformIndices = async (): Promise<any> => {
const args = { index: `${ES_INDEX_PREFIX}*`, format: 'JSON' };
if (engine instanceof ElkClient) {
const r = await engine.cat.indices(args);
return oebp(r);
}
const r_1 = await engine.cat.indices(args);
return oebp(r_1);
};
export const elPlatformMapping = async (index: any): Promise<Record<string, any>> => {
if (engine instanceof ElkClient) {
const r = await engine.indices.getMapping({ index });
return oebp(r)[index].mappings.properties;
}
const r_1 = await engine.indices.getMapping({ index });
return oebp(r_1)[index].mappings.properties;
};
export const elIndexSetting = async (index: any): Promise<{ settings: any; rollover_alias: string }> => {
let settings;
if (engine instanceof ElkClient) {
const r = await engine.indices.getSettings({ index });
settings = oebp(r)[index].settings;
} else {
const r_1 = await engine.indices.getSettings({ index });
settings = oebp(r_1)[index].settings;
}
const rollover_alias = engine instanceof ElkClient ? settings.index.lifecycle?.rollover_alias
: settings.index.plugins?.index_state_management?.rollover_alias;
return { settings, rollover_alias };
};
export const elPlatformTemplates = async (): Promise<any[]> => {
const args = { name: `${ES_INDEX_PREFIX}*`, format: 'JSON' };
if (engine instanceof ElkClient) {
const r = await engine.cat.templates(args);
return oebp(r);
}
const r_1 = await engine.cat.templates(args);
return oebp(r_1);
};
const elCreateLifecyclePolicy = async () => {
if (engine instanceof ElkClient) {
await engine.ilm.putLifecycle({
name: `${ES_INDEX_PREFIX}-ilm-policy`,
body: {
policy: {
phases: {
hot: {
min_age: '0ms',
actions: {
rollover: {
max_primary_shard_size: ES_PRIMARY_SHARD_SIZE,
max_docs: ES_MAX_DOCS,
},
set_priority: {
priority: 100,
},
},
},
},
},
},
}).catch((e) => {
throw DatabaseError('Creating lifecycle policy fail', { cause: e });
});
} else {
await engine.transport.request({
method: 'PUT',
path: `_plugins/_ism/policies/${ES_INDEX_PREFIX}-ism-policy`,
body: {
policy: {
description: 'OpenCTI ISM Policy',
default_state: 'hot',
states: [
{
name: 'hot',
actions: [
{
rollover: {
min_primary_shard_size: ES_PRIMARY_SHARD_SIZE,
min_doc_count: ES_MAX_DOCS,
},
}],
transitions: [],
}],
ism_template: {
index_patterns: [`${ES_INDEX_PREFIX}*`],
priority: 100,
},
},
},
}).catch((e) => {
throw DatabaseError('Creating lifecycle policy fail', { cause: e });
});
}
};
const updateCoreSettings = async (): Promise<void> => {
const putComponentTemplateArgs = {
name: `${ES_INDEX_PREFIX}-core-settings`,
create: false,
body: {
template: {
settings: {
index: {
max_result_window: ES_MAX_RESULT_WINDOW,
number_of_shards: ES_INDEX_SHARD_NUMBER,
number_of_replicas: ES_INDEX_REPLICA_NUMBER,
},
analysis: {
normalizer: {
string_normalizer: {
type: 'custom' as const,
filter: ['lowercase', 'asciifolding'],
},
},
},
},
},
},
};
if (engine instanceof ElkClient) {
await engine.cluster.putComponentTemplate(putComponentTemplateArgs).catch((e) => {
throw DatabaseError('Creating component template fail', { cause: e });
});
} else {
await engine.cluster.putComponentTemplate(putComponentTemplateArgs).catch((e) => {
throw DatabaseError('Creating component template fail', { cause: e });
});
}
};
// Engine mapping generation on attributes definition
const attributeMappingGenerator = (entityAttribute: AttributeDefinition): any => {
if (entityAttribute.type === 'string') {
if (shortStringFormats.includes(entityAttribute.format)) {
return shortMapping;
}
if (longStringFormats.includes(entityAttribute.format)) {
return textMapping;
}
throw UnsupportedError('Cant generated string mapping', { format: entityAttribute.format });
}
if (entityAttribute.type === 'date') {
return dateMapping;
}
if (entityAttribute.type === 'numeric') {
return numericMapping(entityAttribute.precision);
}
if (entityAttribute.type === 'boolean') {
return booleanMapping;
}
if (entityAttribute.type === 'object') {
// For flat object
if (entityAttribute.format === 'flat') {
return { type: engine instanceof ElkClient ? 'flattened' : 'flat_object' };
}
// For standard object
const properties: Record<string, any> = {};
for (let i = 0; i < entityAttribute.mappings.length; i += 1) {
const mapping = entityAttribute.mappings[i];
properties[mapping.name] = attributeMappingGenerator(mapping);
}
const config: { dynamic: string; properties: any; type?: string } = { dynamic: 'strict', properties };
// Add nested option if needed
if (entityAttribute.format === 'nested') {
config.type = 'nested';
}
return config;
}
throw UnsupportedError('Cant generated mapping', { type: entityAttribute.type });
};
const ruleMappingGenerator = (): Record<string, { dynamic: string; properties: any }> => {
const schemaProperties: Record<string, { dynamic: string; properties: any }> = {};
for (let attrIndex = 0; attrIndex < rule_definitions.length; attrIndex += 1) {
const rule = rule_definitions[attrIndex];
schemaProperties[`i_rule_${rule.id}`] = {
dynamic: 'strict',
properties: {
explanation: shortMapping,
dependencies: shortMapping,
hash: shortMapping,
data: { type: engine instanceof ElkClient ? 'flattened' : 'flat_object' },
},
};
}
return schemaProperties;
};
const denormalizeRelationsMappingGenerator = (): Record<string, { dynamic: string; properties: any }> => {