pair will retrieve and return the already existing tufo if present. This allows a single atomic mechanism for the check-and- create primitive and provides a safe way to re-ingest data without worrying about creating duplicate representations of the same knowledge: tuf0= core.formTufoByProp('foo:bar','woot')Additional secondary properties may be specified as kwargs to formTufoByProp: tuf0= core.formTufoByProp('foo:bar','woot', baz=30)
Tufos may also be created for non-deconflicted forms which represent a unique occurrence or observation in time. Tufos which are not meant to be deconflicted are declared with a GUID as their primary property and may be formed using the the value None. tuf0 = core.addTufoEvent(‘hurr:durr’, blah=30, gronk=’lol’) The addTufoEvent API handles the generation of a GUID for the tufo’s primary property and is able to insert the tufo without incurring the overhead of deconfliction.
Retrieving TuFos By Property
A list of tufos which have a given property and optionally a specific value may be retrieved from a Cortex using the getTufosByProp API: tufs= core.getTufosByProp('foo:bar:baz', valu=30)
2.1. Cortex: Synapse Hypergraph 91 Synapse Documentation, Release 0.0.34
2.1.4 Cortex Datamodels
A Cortex may optionally store and enforce a data model which declares types, forms, and properties. The model’s knowledge of types will be used to ensure that properties are correctly normalized. This knowledge is also used by the getTufosByPropType API to allow the retrieval of tufos which contain a property type without knowing about the form in advance. The data model is stored as tufos within the Cortex which allows them to be inspected like any other tufos:
# gather all the forms with a property of type "inet:fqdn" and print the form name. for tufo in core.getTufosByProp('syn:prop:ptype', valu='inet:fqdn'): prop= tufo[1].get('syn:prop') form= tufo[1].get('syn:prop:form') print('tufo form: %s has prop: %s'% ( form, prop )) syn:type
The syn:type tufos are used to declare all types which the Cortex is aware of. Each type must either be implemented by an existing python class or extend an existing type. syn:form
The syn:form tufos are used to declare each form which the Cortex data model is aware of. A syn:form tufo will contain knowledge about the type for the primary property. syn:prop
Every declared property for a given tufo form is represented via a syn:prop tufo which contains knowledge of both the parent form as well as type information.
2.1.5 Cortex Rows
A row level API exists within the Cortex API to allow access to the underlying storage abstraction for individual properties. These APIs are detailed in Cortex Storage Details.
2.1.6 Calculating Statistics
INPROG
2.1.7 Cortex Storage Details
The Cortex can be back by one of several different storage layers. Detail information about storage layers which are available for Cortex can be found here Cortex Storage Types. Additional information about the Storage layer API itself can be found here Cortex Storage Details.
92 Chapter 2. Synapse DevOps Guide Synapse Documentation, Release 0.0.34
2.2 Cortex: Built-In Storage Layers
There are multiple different storage layers available for use with the Cortex hypgeraph. The choice of storage layer may affect performance characteristics of Cortex. XXX Notes about open_* handlers in cortex.py XXX Notes about cortex ctor helper in each storage definition.
2.2.1 ram://
The ram:// storage implementation is implemented in put python data structures resulting in a mind bending level of performance. However, this storage backing is only appropriate for data which does not cause the Cortex to exceed the available amount of memory on the system. With the addition of the savefile= URL parameter, a RAM cortex can persist to disk. However, for large or frequently changed data this savefile can grow very large due to storing all changes since the beginning and may take a long time to start up and apply all changes before the Cortex comes online.
2.2.2 sqlite://
The SQLite3 storage implementation uses a single SQLite3 db file to store a Cortex. They are reasonably fast for medium sized data sets and very simple to create and manage.
2.2.3 postgres://
The PostgreSQL storage backing implements storage for a Cortex as a single table within a PostgreSQL database. While slower than a ram:// Cortex, a PostgreSQL core has the advantage of being backed by PSQL and having asso- ciated PSQL management tools available for administrators to use.
2.2.4 lmdb://
A cortex backed by the Symas Lightning DB (lmdb).
2.2.5 Cortex Storage Compatibility Notes
Due to issues with Python serialization, the data stored and accessed from a Cortex is not guaranteed across Cortexes created in Python 2.7 and Python 3.x. In short, if a Cortex or savefile was created in Python 2.7; its use in a Python3 environment isn’t guaranteed. The inverse is also true; a Cortex created in 3.x may not work in Python2.7 as expected. This is known to affect the LMDB Cortex implementation, which heavily relies on using msgpack for doing key/value serialization, which has issues across python 2/3 with string handling. The Blob store APIs may also be affected by this, since the stored data is stored as a sgpack’d object. If there is a need for doing a data migration in order to ensure that your able to access a Cortex created on 2.7 with python 3.x, we have plans to provide a row level dump/backup tool in the near future that can be used to migrate data.
2.2. Cortex: Built-In Storage Layers 93 Synapse Documentation, Release 0.0.34
2.3 Cortex: Storage Layer Details
The storage layer for a Cortex is a standalone object which can be instantiated on its own. This allows the creation of empty Cortex’s, raw data manipulation or reuse of the Storage object for other purposes. In addition, the clean API separation between the Cortex and Storage classes allows for additional storage layer backings to be implemented.
2.3.1 What is a Storage Row
Most fundamentally, the Storage layer implements a way to store rows of data with simple prop/valu indexing. A row consists of four values: iden| prop| valu| time
These rows values are what we call a row from an API perspective. The field definitions are the following: • iden: This is a str value which acts as unique identifer for a given collection of related rows. A lift of all the rows with the same iden in a Storage layer is considered a join operation; and the resulting rows may be then converted into a tufo object by the Cortex or an external caller. By convention, the iden is typically a random, 16 byte guid value. An example is the following: “e2ac3afddab9394490d55f37a21f013d” (with lowercase characters). While it is possible to create and add rows with arbitrary iden values, tools and code made by the Vertex Project may not support them in all use cases. Suitable iden values can be made using the synapse.common.guid() function. • prop: This is a str value which represents a property. When rows are lifted together by a join operation and folder into a tufo, these become the keys of the tufo dictionary. • valu: This is either a str or int value which is associated with the prop. When rows are folded into a tufo, this valu becomes the value of the corresponding prop in the tufo dictionary. If the storage implementation allows for multiple values for the same prop the tufos may be inconsistent. The storage layer should enforce iden/prop/valu combination uniqueness. • time: This is a int containing the epoch timestamp in milliseconds. This should record when row was created. Suitable time values can be made using the synapse.common.time() function. Through synapse documentation, when row level API is referenced, it is referring to either adding or retrieving rows in this (iden, prop, valu, time) format. In many cases this is shortened to (i, p, v, t) in both documentation and code. It is possible for a storage implementation to store these rows across multiple columns, DBs or indices, as long as they adhere to the (i, p, v, t) format going in and coming out. For example the SQL based stores stores these rows in a five column table, with a separate columns for valus which are strings and valus which are integers.
2.3.2 Storage Layer APIs
The complete list of Storage layer APIs can be found at Cortex Storage API.
2.3.3 Implementing a Storage Layer
When implementing a new storage layer five things must be done. 1. The Storage class from synapse/cores/storage.py must be subclassed and multiple methods overridden. Some of these are private methods since they are wrapped by public APIs or called by other functions. 2. The StoreXact class from synapse/cores/xact.py must be subclassed and multiple methods overridden.
94 Chapter 2. Synapse DevOps Guide Synapse Documentation, Release 0.0.34
3. Additional Storage and StoreXact optional methods may be overridden to provided storage layer specific func- tionality for these objects which overrides default behaviors. This may be the case where a storage layer may have a more optimized way to do something, such as via a specific type of query or lift. 4. The Storage class should implement a helper function to allow creating a Cortex with the Storage implementa- tion as the backing store. 5. The Cortex should pass the basic Cortex tests provided in the test_cortex.py test suite. Each of these is actions is detailed below.
Overriding Required Storage APIs
The following APIs must be implemented:
Initializtion Type APIs
• _initCoreStor(self): • getStoreType(self):
Transaction APIs
These are used to provide transaction safety around a Storage object. • getStoreXact(self, size=None):
Blob Storage APIs
• _getBlobValu(self, key): • _setBlobValu(self, key, valu): • _hasBlobValu(self, key): • _delBlobValu(self, key): • _getBlobKeys(self):
Adding Data to the Store
• _addRows(self, rows):
Deleting Data from the Store
• _delRowsById(self, iden): • _delRowsByProp(self, prop, valu=None, mintime=None, maxtime=None): • _delRowsByIdProp(self, iden, prop, valu=None):
2.3. Cortex: Storage Layer Details 95 Synapse Documentation, Release 0.0.34
Getting Data From the Store
• getRowsById(self, iden): • getRowsByProp(self, prop, valu=None, mintime=None, maxtime=None, limit=None): • getRowsByIdProp(self, iden, prop, valu=None): • getSizeByProp(self, prop, valu=None, mintime=None, maxtime=None): • rowsByRange(self, prop, valu, limit=None): • rowsByGe(self, prop, valu, limit=None): • rowsByLe(self, prop, valu, limit=None): • sizeByGe(self, prop, valu, limit=None): • sizeByLe(self, prop, valu, limit=None): • sizeByRange(self, prop, valu, limit=None): • joinsByGe(self, prop, valu, limit=None): • joinsByLe(self, prop, valu, limit=None): • _genStoreRows(self, **kwargs):
Override the StoreXact APIs
The following APIs must be overridden: • _coreXactBegin(self): • _coreXactCommit(self):
Optional Storage APIs to Override
Some of the APIs provided in the Storage and StoreXact classes provide default implementations which will generi- cally work but may not be the best choice for a given storage layer.
Initializtion Type APIs
These allow for the the storage layer to close resources on teardown and allow it to do custom function/helper regis- tration when a Cortex class is registered with a Storage object. • _finiCoreStore(self): • _setSaveFd(self, fd, load=True, fini=False):
Row Level APIs
These are row level APIs which may be overridden. • _setRowsByIdProp(self, iden, prop, valu): • _delJoinByProp(self, prop, valu=None, mintime=None, maxtime=None): • getJoinByProp(self, prop, valu=None, mintime=None, maxtime=None, limit=None):
96 Chapter 2. Synapse DevOps Guide Synapse Documentation, Release 0.0.34
• rowsByLt(self, prop, valu, limit=None): • rowsByGt(self, prop, valu, limit=None):
Join Level APIs
These APIs return rows which can be turned into complete tufos. They are broken out so that the Storage layer can provide optimized methods which may be quicker than the default implementations. These are expected to return lists of rows which the Cortex can turn into tufos as needed. • getRowsById(self, iden): • getRowsByIdens(self, idens): The default implementations of these functions are just wrappers for joinsByLe / joinsByGt, respectively. • joinsByLt(self, prop, valu, limit=None): • joinsByGt(self, prop, valu, limit=None):
Optional StorXact APIs
These APIs may be used to acquire/release resources needed for the transaction: • _coreXactAcquire(self): • _coreXactRelease(self): These APIs may be used to perform work during __enter__ and __exit__ calls: • _coreXactInit(self): • _coreXactFini(self):
Implementing a helper function
A helper function for making a Cortex with your storage layer should be provided. It should match the following call signature and return a Cortex class which uses your storage layer for backing. A simple example is seen below: def initMyStorageCortex(link, conf=None, storconf=None): ''' Initialize a MyStore based Cortex from a link tufo.
Args: link ((str, dict)): Link tufo. conf (dict): Configable opts for the Cortex object. storconf (dict): Configable opts for the storage object.
Returns: s_cores_common.Cortex: Cortex created from the link tufo. ''' if not conf: conf={} if not storconf: storconf={}
store= MyStorage(link, **storconf) return s_cores_common.Cortex(link, store, **conf)
2.3. Cortex: Storage Layer Details 97 Synapse Documentation, Release 0.0.34
Then, in synapse/cortex.py, a few changes need to be made. We have to import the file containing the Storage object implementation and the helper function, as well as updating a pair of dictionaries to register URL handlers for making either raw Storage objects or making a Cortex backed by the new Storage implementation. The storectors dictionary should contain the path of your Storage class implementation, and the corctors should contain the path to the helper function. Assuming the storage object was implemented in synaspe/cores/mystorage.py, these would look like the following: import synapse.cores.ram import synapse.cores.lmdb import synapse.cores.sqlite import synapse.cores.postgres import synapse.cores.mystorage
... storectors={ 'lmdb': synapse.cores.lmdb.LmdbStorage, 'sqlite': synapse.cores.sqlite.SqliteStorage, 'ram': synapse.cores.ram.RamStorage, 'postgres': synapse.cores.postgres.PsqlStorage, 'mystorage': synapse.cores.mystorage.MyStorage, } corctors={ 'lmdb': synapse.cores.lmdb.initLmdbCortex, 'sqlite': synapse.cores.sqlite.initSqliteCortex, 'ram': synapse.cores.ram.initRamCortex, 'postgres': synapse.cores.postgres.initPsqlCortex, 'mystorage': synapse.cores.mystorage.initMyStorageCortex, }
With these registered, users can easily make raw storage objects or Cortexs using the openstorage() and openurl() functions provided in synapse/cortex.py. Examples of that are below: import synapse.cortex as s_cortex stor= s_cortex.openstore('mystorage:///./some/path') # Now you have a raw Storage object available. # This may be useful for various tests or direct storage layer activity. core= s_cortex.openurl('mystorage:///./some/other/path') # Now you have a Cortex available which has the Hypergraph data model loaded in it so
˓→you actually # store nodes using prop normalization, join a swarm instance, ask queries via storm,
˓→etc.
Basic Cortex Test Suite
Adding a new storage layer implementation to the test suite is fairly straightforward. In the synapse/tests/test_cortex.py file, add the following test to the CortexBaseTest class (this assumes you registered the handler as “mystore”): def test_cortex_mystore(self): with s_cortex.openurl('mystore:///./store/path') as core: self.basic_core_expectations(core,'mystoretype')
Then you can run the Cortex tests using the following command to ensure your Cortex works properly:
98 Chapter 2. Synapse DevOps Guide Synapse Documentation, Release 0.0.34
python-m unittest synapse.tests.test_cortex.CortexBaseTest.test_cortex_mystore
2.4 Ingest: Structured Data Import
API / Developer level details for the Ingest Subsystem.
2.4.1 Ingesting Data via API
Todo
2.4.2 Ingesting Data from the Web
Todo
2.4.3 Registering Format Helpers
Todo
2.4.4 Ingest Under the Hood
Todo
2.5 Axon: Synapse Blob Storage
2.6 Dmon: Synapse Deployment purpose / deployment arch as data
2.4. Ingest: Structured Data Import 99 Synapse Documentation, Release 0.0.34
2.6.1 Dmon Quick Start
2.6.2 Basic Dmon Configuration
2.6.3 Dmon Deployment
2.7 Eventbus: Synapse Event Distribution
2.7.1 EventBus Quick Start
2.7.2 EventBus Basics
2.7.3 Event Bus Linking
2.7.4 Async Event Bus Consumer
2.8 CoreModule: Model Definitions
2.8.1 Quick Start
This is intended as a reference for developers working on Synapse who are creating, or adding models to the base models or for developers who are looking to extend Synapse for their own use by the creation of new models. This is not intended as a ‘how-to’ guide for Synapse hypergraph modeling, rather a document for how models may be defined and loaded into a Cortex.
2.8.2 Models As Code
The the core models used in Synapse hypergraph implementations are a part of the codebase which makes up Synapse. This allows the model definitions to grow along with the codebase over time. One feature we have in Synapse is the ability to track model revisions over time. By using the Cortex extensions class, CoreModule, we can implement our modules, and specific handlers for them, and migration steps over time in a single place. By placing some conventions around how the CoreModule is used for modeling, we can ensure consistency across the Cortex, DataModel and TypeLib classes; as well as ensuring that consistent data migrations are available to Cortex users. An example of a simple model definition file is the following import synapse.lib.module as s_module class FooBarModule(s_module.CoreModule):
# getBaseModels is a method designed to be overridden in # CoreModules which implement Synapse models. It must return # an iterable of name, model tuples. @staticmethod def getBaseModels(): modl={ 'types':( ('foo:bar',{'subof':'str','doc':'A foo bar!'}), ), 'forms':( ('foo:bar',
100 Chapter 2. Synapse DevOps Guide Synapse Documentation, Release 0.0.34
{'ptype':'foo:bar'}, []) ) } name='foobar' return ((name, modl), )
This example module inherits from the the Synapse CoreModule. The initial model is defined as a tuple of (name, dict) pairs; which are returned by the getBaseModels() function. One @staticmethod, getBaseModels, is defined which returns a iterable of name, model tuples. This serves two purposes: 1. The @staticmethod nature of the getBaseModels function allows for the data model to directly available. This allows the path to be loaded as a dynamic Synapse module; which is used by the TypeLib and DataModel classes. This way, those classes may always have the latest versions of the model available. 2. Upon loading the the CoreModule implementation into a Cortex, each name & model pair is considered as the ‘revision 0’ for that named model. This allows new Cortexes to always be created with the latest base model. On existing Cortexes which do not have nodes storing the model revision, the revision 0 of the model will be created and the base model automatically loaded. When model updates need to be done, these updates are to be delivered as functions in the CoreModule sublcass. These functions must be decorated with the @s_module.modelrev function. This decorator takes two arguments: 1. The name of the model to be updated. 2. The timestamp of the model revision, in integer form. This is validated using the “%Y%m%d%H%M” format string. These decorated functions should implement any changes neccesary for the data model; and perform any neccesary data migrations. For performance reasons, these migrations should be performed using the storage layer APIs. The use of node (tufo) level APIs when doing data migrations may result in terrible performance, causing migrations to take a significant amount of time. Under the hood, when the model is loaded by the Cortex, the rev0 function and any @modelrev decorated functions are sorted by model version, and these functions are then executed when CoreModule initialization is completed. This has the following effects: • On new Cortexes, the rev0 function will be loaded (adding the complete data model). Then subsequent functions will be executed. These should perform any model changes and data migrations as needed. • On existing Cortexes which have already had the base model loaded; the rev0 function will be skipped and subsequent functions executed until the last function has been executed. These functions should perform a model addition of the basemodel contents, and perform any required migration actions using the storage layer APIs. The following is a second revision of the earlier FooBarModule - it add a property for the foo:bar type, and performs a storage layer migration of nodes to set a default value for the new property. The model revision for the foobar model will be updated to 201707210101 in the Cortex.: import synapse.lib.module as s_module class FooBarModule(s_module.CoreModule):
@staticmethod def getBaseModels(): modl={ 'types':( ('foo:bar',{'subof':'str','doc':'A foo bar!'}), ), 'forms':(
2.8. CoreModule: Model Definitions 101 Synapse Documentation, Release 0.0.34
('foo:bar', {'ptype':'foo:bar'}, [('duck',{'defval':'mallard','ptype':'str','doc':'Duck type.'}
˓→)] ), ), } name='foobar' return ((name, modl), )
@s_module.modelrev('foobar', 201707210101) def _testRev1(self): ''' This revision adds the 'duck' property to our foo:bar nodes with its default
˓→value. ''' self.core.addPropDef('foo:bar:duck', form='foo:bar', defval='mallard', ptype=
˓→'str', doc='Duck value!') # Now lets migrate existing nodes to accommodate model changes. rows=[] tick= s_common.now() for iden, p, v, t in self.core.getRowsByProp('foo:bar'): rows.append((iden,'foo:bar:duck','mallard', tick)) self.core.addRows(rows)
It is highly encouraged for model developers to write unit tests for any migrations which they do, in order to ensure that their migration functions are working correctly.
2.8.3 Advanced CoreModule Usage
The CoreModule class can also be used to extend the functionality of the Cortex beyond simply adding additional model definitions. The CoreModule has access to the Cortex is loaded with, for example, we can use it to add additional event handlers; type casts; or other functionality. The Cortex on method (from eventbus.py) can be used to quickly strap in additional actions, and the CoreModule class itself has specific event helpers as well (with more coming soon). An example of extending the previous example is shown below (minus migration functions). import logging import synpase.eventbus as s_eventbus import synapse.lib.module as s_module logger= logging.getLogger(__name__) class FooBarModule(s_module.CoreModule):
# Override the default initCoreModule function def initCoreModule(self):
# Define a function used for helping out during node creation. self.onFormNode('foo:knight', self.onTufoFormKnight)
# Calling self.revCoreModl() is required by classes which override # initCoreModule and define module revisions. self.revCoreModl()
def onTufoFormKnight(self, form, valu, props, mesg): if valu in ['erec','lancelot','blumenthal']:
102 Chapter 2. Synapse DevOps Guide Synapse Documentation, Release 0.0.34
props['foo:knight:court']='round table'
# Use an eventhandler to do an action during the property set. @s_eventbus.on('node:prop:set', prop='foo:bar:duck') def onTufoSetDuck(self, mesg): newv= mesg[1].get('newv') for tufo in self.core.getTufosByProp('foo:bar:duck', newv): msg='Already seen duck {} on {}'.format(newv, tufo[1].get('foo:bar')) logger.info(msg)
@staticmethod def getBaseModels(): modl={ 'types':( ('foo:bar',{'subof':'str','doc':'A foo bar!'}), ('foo:knight',{'subof':'str','doc':'A knight!'} ), 'forms':( ('foo:bar', {'ptype':'foo:bar'}, [('duck',{'defval':'mallard','ptype':'str','doc':'Duck type.'}
˓→)] ), ('foo:knight', {'ptype':'foo:knight'}, [('court',{'ptype':'str','doc':'Knight court'})] ), ), } name='foobar' return ((name, modl), )
This example shows the overriding of the initCoreModule() function, which registers a single function as a helper during node creation, and calls the revCoreModl() to cache the model revision functions for model initalization use by the Cortex. The helper is used to set a secondary property based on the primary property of the node. In addition, the @s_eventbus.on decorator is used to perform any action when an event is fired in the Cortex attached to the class. In the example, a message is logged; but other data could be retrieved, or looked up or modified; etc.
2.8.4 Core Synapse Model Conventions
The core Synapse modules are defined in the synapse/__init__.py file, in the BASE_MODELS list. This is a list of tuple values; containing the path to the CoreModule ctor, and the options. The base modules typically do not have options in them. New modules which contain new models should be added to the BASE_MODELs list. During the import process of Synapse, the python modules will be loaded and cached by the synapse.lib.modules.load_ctor() function. In addition, any ctors present in the environmental variable SYN_CORE_MODULES will also be loaded. The models contained in these ctors will be used to populate model information for instances of the TypeLib and DataModel classes, as well as serve as the CoreModules loaded into Cortexes upon creation. The convention for CoreModules which implement data models within the core Synapse codebase shall maintain a single CoreModule subclass per file, and this subclass will be responsible for maintaining a single named model.
2.8. CoreModule: Model Definitions 103 Synapse Documentation, Release 0.0.34
2.8.5 Gotchas
The following modeling gotchas exist: • The implementation of getBaseModels should be a @staticMethod, since it may be called directly by TypeLib or DataModel creation if the ctor has been loaded by synapse.lib.modules.load_ctor(). • It is possible for a single CoreModule to implement multiple named models, and revision them separately with @s_module.modelrev() decorators. The core Synapse modules will not be implemented in such a manner for the sake of simplicity in the codebase. • While it is possible for the model revision functions to simply add the base model data; it should really only do the changes neccesary to support the model changes. Currently, there are self.core.addTufoForm, self.core.addPropDef, and self.core.addType functions available for doing model additions. These functions may throw exceptions - see their docstrings for more information. We anticipate adding additional functions for doing removal of types, forms and props soon.
2.9 Storm: Synapse Query Language
Placeholder for future Storm documentation.
2.10 Telepath: Synapse Remote Method Invocation
2.10.1 Telepath Quick Start
2.10.2 Telepath Link URLs tcp:// ssl://
2.10.3 The Telepath Proxy
2.10.4 Telepath Protocol Modularity
2.10.5 Telepath Protocol Portability
2.11 Synapse Deployment Scenarios
2.11.1 Hardware
Currently Synapse may be run either natively or in a docker container. Both options will be covered. If performance is a consideration in testing please do not use a virtual machine and make sure the resources allocated are appropriate for the performance needed.
Experimental Hardware
For an experimental setup we recommend at least 8GB ram and several terabytes of disk space. Performance of the Synapse Hypergraph will drop considerably if the hardware resources are out paced by the data being loaded.
104 Chapter 2. Synapse DevOps Guide Synapse Documentation, Release 0.0.34
2.11.2 Install
Ubuntu 16.04 LTS is the recommended platform for installation. Installation via Docker is also supported. Synapse is available at the following places: 1. PyPi https://pypi.python.org/pypi/synapse 2. Github https://github.com/vertexproject/synapse 3. DockerHub https://hub.docker.com/r/vertexproject/synapse/
Ubuntu
Install the following prerequisites prior to using Synapse:
$ sudo apt update
$ sudo apt install -yq build-essential libffi-dev libssl-dev python3 python3-dev
˓→python3-pip python3-setuptools
$ sudo -H pip3 install --upgrade pip setuptools wheel
The following commands assume your Synapse checkout will be in ‘~/synapse’:
$ cd ~/ $ sudo apt install unzip wget $ wget https://github.com/vertexproject/synapse/archive/master.zip $ unzip master.zip $ mv synapse-master synapse $ cd synapse $ sudo python3 setup.py develop
An exemplar dmon configuration file is located at synapse/docker/cortex/sqlite_dmon.json:
$ python3 -m synapse.tools.dmon synapse/docker/cortex/sqlite_dmon.json
Docker
Synapse docker images are also based on Ubuntu 16.04 and install all relevant dependencies. Unless otherwise stated Synapse tracks the latest stable release of Docker engine for Ubuntu 16.04 LTS. General steps: 1. Create base Synapse image 2. Create a Postgresql backed Cortex image 3. Start Synapse
Synapse image
This image is intended to serve 2 functions 1. Provide a simple sandbox to get started with synapse 2. Base image to facilitate building other synapse ecosystem images
2.11. Synapse Deployment Scenarios 105 Synapse Documentation, Release 0.0.34
• build
$ docker build -t vertexproject/synapse -f /synapse/docker/
˓→synapse_dockerfile
• volumes – /syndata is exposed by default • ports – no ports are exposed by default
Cortex image - Postgresql
This image will provide a synapse daemon config driven cortex backed into a postgres(9.5) database by default. It is the general image used for experimentation as it can also be easily configured to start additional Cortexes with alternate storage backings as well. By default each Cortex image is configured to expose a Cortex object. • build
$ docker build -t vertexproject/core_pg -f /synapse/docker/
˓→cortex/postgres_9.5_dockerfile
• volumes – /syndata – /var/lib/postgresql/data for postgres data • ports – 47322 - listener in the default /syndata/dmon.json – 5432 - for postgres • use – /syndata/dmon.json is the synapse dmon conf file used by the image. This can be modified or mapped in at container startup:
$ docker run vertexproject/core_pg
Start Docker Cortex
Start a container using the Posgresql Cortex image just created:
$ docker run vertexproject/core_pg
General Cortex Use
Connecting to a Cortex will be a variant of: import synapse.telepath as s_telepath host='172.17.0.2' port= 47322
106 Chapter 2. Synapse DevOps Guide Synapse Documentation, Release 0.0.34
core= s_telepath.openurl('tcp:///core', host=host, port=port)
At this point ‘core’ is a proxy object to the Cortex being shared by the Synapse daemon running in the Docker container. The normal Cortex apis can now be called:
# make sure proxy is working normally... # this should return *something* forms= core.getTufosByProp('syn:core')
# create an fqdn and store it fqdn='woot.com' new_tufo= core.formTufoByProp('fqdn', fqdn)
# retrieve the shiny new fqdn ret_tufo= core.getTufosByProp('fqdn', fqdn)[0] print('formed, stored and retrieved a form: %r'% (new_tufo[0] == ret_tufo[0],))
2.11.3 Other Cortex Docker images
The other Docker images listed below are simpler examples of running a more basic Cortex without Postgresql. core_ram
Provides a synapse daemon config driven cortex backed into ram. • build
$ docker build -t vertexproject/core_ram -f /synapse/docker/
˓→cortex/ram_dockerfile
• volumes – /syndata • ports – 47322 - listener in the default /syndata/dmon.json • use – /syndata/dmon.json is the synapse dmon conf file used by the image. This can be modified or mapped in at container startup
$ docker run vertexproject/core_ram core_sqlite
Provides a synapse daemon config driven cortex backed into a sqlite database by default. • build
2.11. Synapse Deployment Scenarios 107 Synapse Documentation, Release 0.0.34
$ docker build -t vertexproject/core_sqlite -f /synapse/docker/
˓→cortex/sqlite_dockerfile
• volumes – /syndata • ports – 47322 - listener in the default /syndata/dmon.json • use – /syndata/dmon.json is the synapse dmon conf file used by the image. This can be modified or mapped in at container startup
$ docker run vertexproject/core_sqlite
The following sections are still under development: • Doc 1 • Doc 2
108 Chapter 2. Synapse DevOps Guide CHAPTER 3
Synapse Data Model
3.1 Types
3.1.1 file:base
A file or directory name (without a full path), such as system32 or foo.exe. Type Hierarchy: file:base
3.1.2 file:bytes
A unique file identifier Type Hierarchy: guid -> file:bytes
3.1.3 file:imgof
A file that contains an image of the specified node. Type Hierarchy: xref -> file:imgof
3.1.4 file:path
A file path that has been normalized by Synapse. Can consist of a directory path, a path and file name, or a file name. Type Hierarchy: file:path
109 Synapse Documentation, Release 0.0.34
3.1.5 file:rawpath
A raw file path in its default (non-normalized) form. Can consist of a directory path, a path and file name, or a file name. Type Hierarchy: file:rawpath
3.1.6 file:sub
A parent file that fully contains the specified child file. Type Hierarchy: sepr -> file:sub Sepr Fields: <file:bytes>/<file:bytes>
3.1.7 file:txtref
A file that contains a reference to the specified node. Type Hierarchy: xref -> file:txtref
3.1.8 geo:alias
An alias for the place GUID Type Hierarchy: str -> str:lwr -> geo:alias Examples: • repr mode: ‘foobar’ Type Constraints: • regex: ^[0-9a-z]+$ Type Transforms: • case: lower
3.1.9 geo:latlong
A Lat/Long string specifying a point Type Hierarchy: str -> geo:latlong Type Constraints: • regex: ^[-+]?([1-8]?d(.d+)?|90(.0+)?),s*[-+]?(180(.0+)?|((1[0-7]d)|([1-9]?d))(.d+)?)$ • null value: ??
3.1.10 geo:place
A GUID for a specific place Type Hierarchy: guid -> geo:place
110 Chapter 3. Synapse Data Model Synapse Documentation, Release 0.0.34
3.1.11 gov:cn:icp
A Chinese Internet Content Provider ID Type Hierarchy: int -> gov:cn:icp
3.1.12 gov:cn:mucd
A Chinese PLA MUCD Type Hierarchy: int -> gov:cn:mucd
3.1.13 gov:cn:orgicp
A multi-field composite type which uses separated repr values Type Hierarchy: sepr -> gov:cn:orgicp Sepr Fields: /
3.1.14 gov:intl:un:m49
UN M4 Numeric Country Code Type Hierarchy: int -> gov:intl:un:m49
3.1.15 gov:us:cage
A Commercial and Government Entity (CAGE) code Type Hierarchy: str -> gov:us:cage Type Transforms: • case: lower
3.1.16 gov:us:ssn
A US Social Security Number (SSN) Type Hierarchy: int -> gov:us:ssn
3.1.17 gov:us:zip
A US Zip Code Type Hierarchy: int -> gov:us:zip
3.1. Types 111 Synapse Documentation, Release 0.0.34
3.1.18 hash:md5
An MD5 hash Type Hierarchy: str -> hash:md5 Examples: • repr mode: ‘d41d8cd98f00b204e9800998ecf8427e’ Type Constraints: • regex: ^[0-9a-f]{32}$ Type Transforms: • case: lower
3.1.19 hash:sha1
A SHA1 hash Type Hierarchy: str -> hash:sha1 Examples: • repr mode: ‘da39a3ee5e6b4b0d3255bfef95601890afd80709’ Type Constraints: • regex: ^[0-9a-f]{40}$ Type Transforms: • case: lower
3.1.20 hash:sha256
A SHA256 hash Type Hierarchy: str -> hash:sha256 Examples: • repr mode: ‘ad9f4fe922b61e674a09530831759843b1880381de686a43460a76864ca0340c’ Type Constraints: • regex: ^[0-9a-f]{64}$ Type Transforms: • case: lower
3.1.21 hash:sha384
A SHA384 hash Type Hierarchy: str -> hash:sha384 Examples: • repr mode: ‘d425f1394e418ce01ed1579069a8bfaa1da8f32cf823982113ccbef531fa36bda9987f389c5af05b5e28035242efab6c’
112 Chapter 3. Synapse Data Model Synapse Documentation, Release 0.0.34
Type Constraints: • regex: ^[0-9a-f]{96}$ Type Transforms: • case: lower
3.1.22 hash:sha512
A SHA512 hash Type Hierarchy: str -> hash:sha512 Examples: • repr mode: ‘ca74fe2ff2d03b29339ad7d08ba21d192077fece1715291c7b43c20c9136cd132788239189f3441a87eb23ce2660aa243f334295902c904b5520f6e80ab91f11’ Type Constraints: • regex: ^[0-9a-f]{128}$ Type Transforms: • case: lower
3.1.23 inet:addr
An IPv4 or IPv6 address Type Hierarchy: inet:addr Examples: • repr mode: ‘1.2.3.4’
3.1.24 inet:asn
An Autonomous System Number (ASN). Type Hierarchy: int -> inet:asn
3.1.25 inet:asnet4
An Autonomous System Number (ASN) and its associated IPv4 address range. Type Hierarchy: sepr -> inet:asnet4 Examples: • repr mode: ‘54959/1.2.3.4-1.2.3.20’ Sepr Fields: /
3.1. Types 113 Synapse Documentation, Release 0.0.34
3.1.26 inet:cidr4
An IPv4 address block in Classless Inter-Domain Routing (CIDR) notation. Type Hierarchy: inet:cidr4 Examples: • repr mode: ‘1.2.3.0/24’
3.1.27 inet:dns:a
The result of a DNS A record lookup. Type Hierarchy: sepr -> inet:dns:a Examples: • repr mode: ‘vertex.link/1.2.3.4’ Sepr Fields: /
3.1.28 inet:dns:aaaa
The result of a DNS AAAA record lookup. Type Hierarchy: sepr -> inet:dns:aaaa Examples: • repr mode: ‘vertex.link/2607:f8b0:4004:809::200e’ Sepr Fields: /
3.1.29 inet:dns:cname
The result of a DNS CNAME record lookup. Type Hierarchy: sepr -> inet:dns:cname Examples: • repr mode: ‘foo.vertex.link/vertex.link’ Sepr Fields: /
3.1.30 inet:dns:look
The instance (point-in-time) result of a DNS record lookup. Type Hierarchy: guid -> inet:dns:look
114 Chapter 3. Synapse Data Model Synapse Documentation, Release 0.0.34
3.1.31 inet:dns:mx
The result of a DNS MX record lookup. Type Hierarchy: sepr -> inet:dns:mx Examples: • repr mode: ‘vertex.link/mail.vertex.link’ Sepr Fields: /
3.1.32 inet:dns:ns
The result of a DNS NS record lookup. Type Hierarchy: sepr -> inet:dns:ns Examples: • repr mode: ‘vertex.link/ns.dnshost.com’ Sepr Fields: /
3.1.33 inet:dns:req
A fused DNS request record Type Hierarchy: comp -> inet:dns:req
3.1.34 inet:dns:rev
The transformed result of a DNS PTR record lookup. Type Hierarchy: sepr -> inet:dns:rev Examples: • repr mode: ‘1.2.3.4/vertex.link’ Sepr Fields: /
3.1.35 inet:dns:rev6
The transformed result of a DNS PTR record for an IPv6 address. Type Hierarchy: sepr -> inet:dns:rev6 Examples: • repr mode: ‘2607:f8b0:4004:809::200e/vertex.link’ Sepr Fields: /
3.1.36 inet:dns:soa
The result of a DNS SOA record lookup. Type Hierarchy: comp -> inet:dns:soa
3.1. Types 115 Synapse Documentation, Release 0.0.34
3.1.37 inet:dns:txt
The result of a DNS TXT record lookup. Type Hierarchy: comp -> inet:dns:txt
3.1.38 inet:dns:type
A DNS request type enum Type Hierarchy: str -> inet:dns:type Type Transforms: • case: lower
3.1.39 inet:email
An email address. Type Hierarchy: inet:email Examples: • repr mode: ‘[email protected] ‘
3.1.40 inet:flow
An individual network connection between a given source and destination. Type Hierarchy: guid -> inet:flow
3.1.41 inet:fqdn
A fully qualified domain name (FQDN). Type Hierarchy: inet:fqdn Examples: • repr mode: ‘vertex.link’
3.1.42 inet:iface
A network interface with a set of associated protocol addresses. Type Hierarchy: guid -> inet:iface
3.1.43 inet:ipv4
An IPv4 address. Type Hierarchy: inet:ipv4 Examples:
116 Chapter 3. Synapse Data Model Synapse Documentation, Release 0.0.34
• repr mode: ‘1.2.3.4’
3.1.44 inet:ipv6
An IPv6 address. Type Hierarchy: inet:ipv6 Examples: • repr mode: ‘2607:f8b0:4004:809::200e’
3.1.45 inet:mac
A 48-bit Media Access Control (MAC) address. Type Hierarchy: str -> inet:mac Examples: • repr mode: ‘aa:bb:cc:dd:ee:ff’ Type Constraints: • regex: ^([0-9a-f]{2}[:]){5}([0-9a-f]{2})$ • null value: ?? Type Transforms: • case: lower
3.1.46 inet:net4
An IPv4 address range. Type Hierarchy: sepr -> inet:net4 Examples: • repr mode: ‘1.2.3.4-1.2.3.20’ Sepr Fields: -
3.1.47 inet:net6
An IPv6 address range. Type Hierarchy: sepr -> inet:net6 Examples: • repr mode: ‘ff::00-ff::30’ Sepr Fields: -
3.1. Types 117 Synapse Documentation, Release 0.0.34
3.1.48 inet:passwd
A password string. Type Hierarchy: str -> inet:passwd
3.1.49 inet:port
A network port. Type Hierarchy: int -> inet:port Examples: • repr mode: ‘80’ Type Constraints: • min value: 0 (0x0) • max value: 65535 (0xffff)
3.1.50 inet:srv4
An IPv4 address and port. Type Hierarchy: inet:srv4 Examples: • repr mode: ‘1.2.3.4:80’
3.1.51 inet:srv6
An IPv6 address and port. Type Hierarchy: inet:srv6 Examples: • repr mode: ‘[2607:f8b0:4004:809::200e]:80’
3.1.52 inet:ssl:tcp4cert
An SSL certificate file served by an IPv4 TCP server. Type Hierarchy: sepr -> inet:ssl:tcp4cert Sepr Fields: /<file:bytes>
3.1.53 inet:tcp4
A TCP server listening on an IPv4 address and port. Type Hierarchy: inet:srv4 -> inet:tcp4 Examples: • repr mode: ‘1.2.3.4:80’
118 Chapter 3. Synapse Data Model Synapse Documentation, Release 0.0.34
3.1.54 inet:tcp6
A TCP server listening on a specific IPv6 address and port. Type Hierarchy: inet:srv6 -> inet:tcp6 Examples: • repr mode: ‘[2607:f8b0:4004:809::200e]:80’
3.1.55 inet:udp4
A UDP server listening on an IPv4 address and port. Type Hierarchy: inet:srv4 -> inet:udp4 Examples: • repr mode: ‘1.2.3.4:80’
3.1.56 inet:udp6
A UDP server listening on a specific IPv6 address and port. Type Hierarchy: inet:srv6 -> inet:udp6 Examples: • repr mode: ‘[2607:f8b0:4004:809::200e]:80’
3.1.57 inet:url
A Universal Resource Locator (URL). Type Hierarchy: inet:url Examples: • repr mode: ‘http://www.woot.com/files/index.html‘
3.1.58 inet:urlfile
A file hosted at a specific Universal Resource Locator (URL). Type Hierarchy: comp -> inet:urlfile
3.1.59 inet:urlredir
A URL that redirects to another URL, such as via a URL shortening service or an HTTP 302 response. Type Hierarchy: comp -> inet:urlredir Examples: • repr mode: ‘(http://foo.com/,http://bar.com/)’
3.1. Types 119 Synapse Documentation, Release 0.0.34
3.1.60 inet:user
A username string. Type Hierarchy: str -> str:lwr -> inet:user Type Transforms: • case: lower
3.1.61 inet:web:acct
An account with a given Internet-based site or service. Type Hierarchy: sepr -> inet:web:acct Examples: • repr mode: ‘twitter.com/invisig0th’ Sepr Fields: /
3.1.62 inet:web:action
An instance of an account performing an action at an Internet-based site or service. Type Hierarchy: guid -> inet:web:action
3.1.63 inet:web:actref
A web action that references a given node. Type Hierarchy: xref -> inet:web:actref
3.1.64 inet:web:chprofile
A change to a web account. Used to capture historical properties associated with an account, as opposed to current data in the inet:web:acct node. Type Hierarchy: guid -> inet:web:chprofile
3.1.65 inet:web:file
A file posted by a web account. Type Hierarchy: comp -> inet:web:file
3.1.66 inet:web:follows
A web account follows or is connected to another web account. Type Hierarchy: comp -> inet:web:follows
120 Chapter 3. Synapse Data Model Synapse Documentation, Release 0.0.34
3.1.67 inet:web:group
A group hosted within or registered with a given Internet-based site or service. Type Hierarchy: sepr -> inet:web:group Examples: • repr mode: ‘somesite.com/mycoolgroup’ Sepr Fields: /
3.1.68 inet:web:logon
An instance of an account authenticating to an Internet-based site or service. Type Hierarchy: guid -> inet:web:logon
3.1.69 inet:web:memb
A web account that is a member of a web group. Type Hierarchy: comp -> inet:web:memb
3.1.70 inet:web:mesg
A message sent from one web account to another web account. Type Hierarchy: comp -> inet:web:mesg Examples: • repr mode: ‘twitter.com/invisig0th|twitter.com/gobbles|20041012130220’
3.1.71 inet:web:post
A post made by a web account. Type Hierarchy: comp -> inet:web:post
3.1.72 inet:web:postref
A web post that references a given node. Type Hierarchy: xref -> inet:web:postref
3.1.73 inet:whois:contact
An individual contact from a domain whois record. Type Hierarchy: comp -> inet:whois:contact
3.1. Types 121 Synapse Documentation, Release 0.0.34
3.1.74 inet:whois:rar
A domain registrar. Type Hierarchy: str -> str:lwr -> inet:whois:rar Examples: • repr mode: ‘godaddy, inc.’ Type Transforms: • case: lower
3.1.75 inet:whois:rec
A domain whois record Type Hierarchy: sepr -> inet:whois:rec Sepr Fields: @
3.1.76 inet:whois:recns
A nameserver associated with a domain whois record. Type Hierarchy: comp -> inet:whois:recns
3.1.77 inet:whois:reg
A domain registrant. Type Hierarchy: str -> str:lwr -> inet:whois:reg Examples: • repr mode: ‘woot hostmaster’ Type Transforms: • case: lower
3.1.78 inet:whois:regmail
An association between a domain and a registrant email address. Type Hierarchy: comp -> inet:whois:regmail
3.1.79 inet:wifi:ssid
A WiFi service set identifier (SSID) name. Type Hierarchy: str -> inet:wifi:ssid Examples: • repr mode: ‘The Vertex Project’
122 Chapter 3. Synapse Data Model Synapse Documentation, Release 0.0.34
3.1.80 it:av:filehit
A file that triggered an alert on a specific antivirus signature. Type Hierarchy: sepr -> it:av:filehit Sepr Fields: <file:bytes>/
3.1.81 it:av:sig
A vendor- or organization-specific antivirus signature name. Type Hierarchy: sepr -> it:av:sig Sepr Fields: /
3.1.82 it:dev:int
A developer-selected integer constant. Type Hierarchy: int -> it:dev:int
3.1.83 it:dev:mutex
A string representing a mutex. Type Hierarchy: str -> it:dev:str -> it:dev:mutex
3.1.84 it:dev:pipe
A string representing a named pipe. Type Hierarchy: str -> it:dev:str -> it:dev:pipe
3.1.85 it:dev:regkey
A Windows registry key. Type Hierarchy: str -> it:dev:str -> it:dev:regkey Examples: • repr mode: ‘HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run’
3.1.86 it:dev:regval
A Windows registry key/value pair. Type Hierarchy: comp -> it:dev:regval
3.1. Types 123 Synapse Documentation, Release 0.0.34
3.1.87 it:dev:str
A developer-selected string. Type Hierarchy: str -> it:dev:str
3.1.88 it:exec:proc
A process executing on a host. May be an actual (e.g., endpoint) or virtual (e.g., malware sandbox) host. Type Hierarchy: guid -> it:exec:proc
3.1.89 it:host
A GUID that represents a host or system. Type Hierarchy: guid -> it:host
3.1.90 it:hostname
The name of a host or system. Type Hierarchy: str -> str:lwr -> it:hostname Type Transforms: • case: lower
3.1.91 it:hostsoft
A version of a software product which is present on a given host. Type Hierarchy: comp -> it:hostsoft
3.1.92 it:hosturl
A URL hosted on or served by a host or system. Type Hierarchy: comp -> it:hosturl
3.1.93 it:prod:soft
A arbitrary, unversioned software product. Type Hierarchy: guid -> it:prod:soft
3.1.94 it:prod:softver
A version of a particular software product. Type Hierarchy: guid -> it:prod:softver
124 Chapter 3. Synapse Data Model Synapse Documentation, Release 0.0.34
3.1.95 it:sec:cve
A vulnerability as designated by a Common Vulnerabilities and Exposures (CVE) number. Type Hierarchy: str -> str:lwr -> it:sec:cve Examples: • repr mode: ‘CVE-2012-0158’ Type Constraints: • regex: (?i)^CVE-[0-9]{4}-[0-9]{4,}$ Type Transforms: • case: lower
3.1.96 it:semver
Semantic Version type. Type Hierarchy: it:semver
3.1.97 lang:idiom
A subcultural idiom Type Hierarchy: str -> str:txt -> lang:idiom
3.1.98 lang:trans
Raw text with a documented translation Type Hierarchy: str -> str:txt -> lang:trans
3.1.99 mat:item
A GUID assigned to a material object Type Hierarchy: guid -> mat:item
3.1.100 mat:itemimage
A multi-field composite type which uses separated repr values Type Hierarchy: sepr -> mat:itemimage Sepr Fields: /<file:bytes>
3.1.101 mat:spec
A GUID assigned to a material specification Type Hierarchy: guid -> mat:spec
3.1. Types 125 Synapse Documentation, Release 0.0.34
3.1.102 mat:specimage
A multi-field composite type which uses separated repr values Type Hierarchy: sepr -> mat:specimage Sepr Fields: /<file:bytes>
3.1.103 media:news
A GUID for a news article or report Type Hierarchy: guid -> media:news
3.1.104 ou:alias
An alias for the org GUID Type Hierarchy: str -> str:lwr -> ou:alias Examples: • repr mode: ‘vertexproj’ Type Constraints: • regex: ^[0-9a-z]+$ Type Transforms: • case: lower
3.1.105 ou:hasemail
A multi-field composite type which generates a stable guid from normalized fields Type Hierarchy: comp -> ou:hasemail
3.1.106 ou:hasfile
A multi-field composite type which generates a stable guid from normalized fields Type Hierarchy: comp -> ou:hasfile
3.1.107 ou:hasfqdn
A multi-field composite type which generates a stable guid from normalized fields Type Hierarchy: comp -> ou:hasfqdn
3.1.108 ou:hashost
A multi-field composite type which generates a stable guid from normalized fields Type Hierarchy: comp -> ou:hashost
126 Chapter 3. Synapse Data Model Synapse Documentation, Release 0.0.34
3.1.109 ou:hasipv4
A multi-field composite type which generates a stable guid from normalized fields Type Hierarchy: comp -> ou:hasipv4
3.1.110 ou:hasphone
A multi-field composite type which generates a stable guid from normalized fields Type Hierarchy: comp -> ou:hasphone
3.1.111 ou:haswebacct
A multi-field composite type which generates a stable guid from normalized fields Type Hierarchy: comp -> ou:haswebacct
3.1.112 ou:naics
North American Industry Classification System Type Hierarchy: int -> ou:naics
3.1.113 ou:name
The base string type Type Hierarchy: str -> str:lwr -> ou:name Type Transforms: • case: lower
3.1.114 ou:org
A GUID for a human organization such as a company or military unit Type Hierarchy: guid -> ou:org
3.1.115 ou:sic
Standard Industrial Classification Code Type Hierarchy: int -> ou:sic
3.1.116 ou:suborg
An org which owns a sub org Type Hierarchy: comp -> ou:suborg
3.1. Types 127 Synapse Documentation, Release 0.0.34
3.1.117 ou:user
A user name within an organization Type Hierarchy: sepr -> ou:user Sepr Fields: /
3.1.118 pol:country
A GUID for a country Type Hierarchy: guid -> pol:country
3.1.119 pol:iso2
The 2 digit ISO country code Type Hierarchy: str -> pol:iso2 Examples: • repr mode: ‘us’ Type Constraints: • regex: ^[a-z0-9]{2}$ • null value: ?? Type Transforms: • case: lower
3.1.120 pol:iso3
The 3 digit ISO country code Type Hierarchy: str -> pol:iso3 Examples: • repr mode: ‘usa’ Type Constraints: • regex: ^[a-z0-9]{3}$ • null value: ?? Type Transforms: • case: lower
3.1.121 pol:isonum
The ISO integer country code Type Hierarchy: int -> pol:isonum Examples:
128 Chapter 3. Synapse Data Model Synapse Documentation, Release 0.0.34
• repr mode: ‘840’
3.1.122 ps:contact
A GUID for a contact info record Type Hierarchy: guid -> ps:contact
3.1.123 ps:hasalias
A multi-field composite type which uses separated repr values Type Hierarchy: sepr -> ps:hasalias Sepr Fields: /
3.1.124 ps:hasemail
A multi-field composite type which uses separated repr values Type Hierarchy: sepr -> ps:hasemail Sepr Fields: /
3.1.125 ps:hashost
A multi-field composite type which uses separated repr values Type Hierarchy: sepr -> ps:hashost Sepr Fields: /
3.1.126 ps:hasphone
A multi-field composite type which uses separated repr values Type Hierarchy: sepr -> ps:hasphone Sepr Fields: /
3.1.127 ps:hasuser
A multi-field composite type which uses separated repr values Type Hierarchy: sepr -> ps:hasuser Sepr Fields: /
3.1.128 ps:haswebacct
A multi-field composite type which uses separated repr values Type Hierarchy: sepr -> ps:haswebacct Sepr Fields: /
3.1. Types 129 Synapse Documentation, Release 0.0.34
3.1.129 ps:image
A multi-field composite type which uses separated repr values Type Hierarchy: sepr -> ps:image Sepr Fields: /<file:bytes>
3.1.130 ps:name
A last,first person full name Type Hierarchy: ps:name Examples: • repr mode: ‘smith,bob’
3.1.131 ps:person
A GUID for a person or suspected person Type Hierarchy: guid -> ps:person
3.1.132 ps:tokn
A single name element (potentially given or sur) Type Hierarchy: str -> str:lwr -> ps:tokn Examples: • repr mode: ‘mike’ Type Transforms: • case: lower
3.1.133 rsa:key
An RSA keypair modulus and public exponent Type Hierarchy: sepr -> rsa:key Sepr Fields: /
3.1.134 syn:auth:role
The base string type Type Hierarchy: str -> syn:auth:role
3.1.135 syn:auth:user
The base string type Type Hierarchy: str -> syn:auth:user
130 Chapter 3. Synapse Data Model Synapse Documentation, Release 0.0.34
3.1.136 syn:auth:userrole
A multi-field composite type which generates a stable guid from normalized fields Type Hierarchy: comp -> syn:auth:userrole
3.1.137 syn:splice
A Globally Unique Identifier type Type Hierarchy: guid -> syn:splice
3.1.138 syn:tagform
A multi-field composite type which generates a stable guid from normalized fields Type Hierarchy: comp -> syn:tagform Examples: • repr mode: ‘(foo.bar,baz:faz)’
3.1.139 tel:mob:imei
An International Mobile Equipment Id Type Hierarchy: tel:mob:imei
3.1.140 tel:mob:imsi
An International Mobile Subscriber Id Type Hierarchy: tel:mob:imsi
3.1.141 tel:mob:tac
A mobile Type Allocation Code Type Hierarchy: int -> tel:mob:tac
3.1.142 tel:phone
Type Hierarchy: tel:phone
3.1.143 time:epoch
Timestamp in seconds since epoch (deprecated) Type Hierarchy: time:epoch Examples: • repr mode: ‘20161216084632’
3.1. Types 131 Synapse Documentation, Release 0.0.34
3.1.144 time:epoch:max
Maximum time in seconds (depricated) Type Hierarchy: time:epoch -> time:epoch:max Examples: • repr mode: ‘20161216084632’
3.1.145 time:epoch:min
Minimum time in seconds (depricated) Type Hierarchy: time:epoch -> time:epoch:min Examples: • repr mode: ‘20161216084632’
3.1.146 time:max
Maximum time in millis since epoch Type Hierarchy: time -> time:max Examples: • repr mode: ‘20161216084632’
3.1.147 time:min
Minimum time in millis since epoch Type Hierarchy: time -> time:min Examples: • repr mode: ‘20161216084632’
3.2 Forms
3.2.1 file:base = <file:base>
A file or directory name (without a full path), such as system32 or foo.exe. Properties: • file:base=<file:base> – A file or directory name (without a full path), such as system32 or foo.exe.
132 Chapter 3. Synapse Data Model Synapse Documentation, Release 0.0.34
3.2.2 file:bytes = <file:bytes>
A unique file identifier Properties: • file:bytes=<file:bytes> – A unique file identifier • file:bytes:md5 = – The md5 hash of the file. • file:bytes:mime = (default: ‘??’) – The MIME type of the file. • file:bytes:mime:* = – Namespace for high-value mime details • file:bytes:mime:pe:compiled = – The compile time of the file according to the PE header. • file:bytes:mime:pe:imphash = – The PE import hash of the file as calculated by Vivisect; this method excludes imports referenced as ordinals and may fail to calculate an import hash for files that use ordinals. • file:bytes:mime:pe:size = – The size of the executable file according to the file headers. • file:bytes:mime:x509:cn = – The Common Name (CN) attribute of the x509 Subject. • file:bytes:name=<file:base> – The name of the file. Because a given set of bytes can have any number of arbitrary names, this field is used for display purposes only. • file:bytes:sha1 = – The sha1 hash of the file. • file:bytes:sha256 = – The sha256 hash of the file. • file:bytes:sha512 = – The sha512 hash of the file. • file:bytes:size = – The size of the file in bytes.
3.2.3 file:imgof = <file:imgof>
A file that contains an image of the specified node. Properties: • file:imgof=<file:imgof>
3.2. Forms 133 Synapse Documentation, Release 0.0.34
– A file that contains an image of the specified node. • file:imgof:file=<file:bytes> – The guid of the file containing the image. • file:imgof:xref = – The form=valu of the object referenced in the image, e.g., geo:place=. • file:imgof:xref:intval = – The value of the property of the referenced object, as specified by the propvalu, if the value is an integer. • file:imgof:xref:prop = – The property (form) of the referenced object, as specified by the propvalu. • file:imgof:xref:strval = – The value of the property of the referenced object, as specified by the propvalu, if the value is a string.
3.2.4 file:path = <file:path>
A file path that has been normalized by Synapse. Can consist of a directory path, a path and file name, or a file name. Properties: • file:path=<file:path> – A file path that has been normalized by Synapse. Can consist of a directory path, a path and file name, or a file name. • file:path:base=<file:base> – The final component of the file path. Can be a file name (if present) or the final directory. • file:path:dir=<file:path> – The parent directory of the file path. • file:path:ext = – The file extension of the file name, (if present); for example: exe, bat, py, docx.
3.2.5 file:subfile = <file:sub>
A parent file that fully contains the specified child file. Properties: • file:subfile=<file:sub> – A parent file that fully contains the specified child file. • file:subfile:child=<file:bytes> – The guid of the child file. • file:subfile:name=<file:base> – The name of the child file. Because a given set of bytes can have any number of arbitrary names, this field is used for display purposes only. • file:subfile:parent=<file:bytes>
134 Chapter 3. Synapse Data Model Synapse Documentation, Release 0.0.34
– The guid of the parent file.
3.2.6 file:txtref = <file:txtref>
A file that contains a reference to the specified node. Properties: • file:txtref=<file:txtref> – A file that contains a reference to the specified node. • file:txtref:file=<file:bytes> – The guid of the file containing the reference. • file:txtref:xref = – The form=valu of the object referenced in the file, e.g., inet:fqdn=foo.com. • file:txtref:xref:intval = – The value of the property of the referenced object, as specified by the propvalu, if the value is an integer. • file:txtref:xref:prop = – The property (form) of the referenced object, as specified by the propvalu. • file:txtref:xref:strval = – The value of the property of the referenced object, as specified by the propvalu, if the value is a string.
3.2.7 geo:place =
A GUID for a specific place Properties: • geo:place = – A GUID for a specific place • geo:place:alias = – An alias for the place GUID • geo:place:latlong = (default: ‘??’) – The location of the place • geo:place:name = – The name of the place
3.2.8 gov:cn:icp =
A Chinese Internet Content Provider ID Properties: • gov:cn:icp = – A Chinese Internet Content Provider ID
3.2. Forms 135 Synapse Documentation, Release 0.0.34
3.2.9 gov:cn:mucd =
A Chinese PLA MUCD Properties: • gov:cn:mucd = – A Chinese PLA MUCD
3.2.10 gov:us:cage =
A Commercial and Government Entity (CAGE) code Properties: • gov:us:cage = – A Commercial and Government Entity (CAGE) code • gov:us:cage:cc = – The 2 digit ISO country code • gov:us:cage:city = – The base string type • gov:us:cage:country = – The base string type • gov:us:cage:name0 = – The name of the organization • gov:us:cage:name1 = – Name Part 1 • gov:us:cage:phone0 = • gov:us:cage:phone1 = • gov:us:cage:state = – The base string type • gov:us:cage:street = – The base string type • gov:us:cage:zip = – A US Zip Code
3.2.11 gov:us:ssn =
A US Social Security Number (SSN) Properties: • gov:us:ssn = – A US Social Security Number (SSN)
136 Chapter 3. Synapse Data Model Synapse Documentation, Release 0.0.34
3.2.12 gov:us:zip =
A US Zip Code Properties: • gov:us:zip = – A US Zip Code
3.2.13 hash:md5 =
An MD5 hash Properties: • hash:md5 = – An MD5 hash
3.2.14 hash:sha1 =
A SHA1 hash Properties: • hash:sha1 = – A SHA1 hash
3.2.15 hash:sha256 =
A SHA256 hash Properties: • hash:sha256 = – A SHA256 hash
3.2.16 hash:sha384 =
A SHA384 hash Properties: • hash:sha384 = – A SHA384 hash
3.2.17 hash:sha512 =
A SHA512 hash Properties: • hash:sha512 = – A SHA512 hash
3.2. Forms 137 Synapse Documentation, Release 0.0.34
3.2.18 inet:asn =
An Autonomous System Number (ASN). Properties: • inet:asn = – An Autonomous System Number (ASN). • inet:asn:name = (default: ‘??’) – The name of the organization currently responsible for the ASN. • inet:asn:owner = – The guid of the organization currently responsible for the ASN.
3.2.19 inet:asnet4 =
An Autonomous System Number (ASN) and its associated IPv4 address range. Properties: • inet:asnet4 = – An Autonomous System Number (ASN) and its associated IPv4 address range. • inet:asnet4:asn = – The Autonomous System Number (ASN) of the netblock. • inet:asnet4:net4 = – The IPv4 address range assigned to the ASN. • inet:asnet4:net4:max = – The last IPv4 in the range assigned to the ASN. • inet:asnet4:net4:min = – The first IPv4 in the range assigned to the ASN.
3.2.20 inet:cidr4 =
An IPv4 address block in Classless Inter-Domain Routing (CIDR) notation. Properties: • inet:cidr4 = – An IPv4 address block in Classless Inter-Domain Routing (CIDR) notation. • inet:cidr4:ipv4 = – The IP address from the CIDR notation. • inet:cidr4:mask = – The mask from the CIDR notation.
138 Chapter 3. Synapse Data Model Synapse Documentation, Release 0.0.34
3.2.21 inet:dns:a =
Fused knowledge of a DNS A record. Properties: • inet:dns:a = – Fused knowledge of a DNS A record. • inet:dns:a:fqdn = – The domain queried for its DNS A record. • inet:dns:a:ipv4 = – The IPv4 address returned in the A record. • inet:dns:a:seen:max = – The most recent observed time for the data in the A record. • inet:dns:a:seen:min = – The earliest observed time for the data in the A record.
3.2.22 inet:dns:aaaa =
Fused knowledge of a DNS AAAA record. Properties: • inet:dns:aaaa = – Fused knowledge of a DNS AAAA record. • inet:dns:aaaa:fqdn = – The domain queried for its DNS AAAA record. • inet:dns:aaaa:ipv6 = – The IPv6 address returned in the AAAA record. • inet:dns:aaaa:seen:max = – The most recent observed time for the data in the AAAA record. • inet:dns:aaaa:seen:min = – The earliest observed time for the data in the AAAA record.
3.2.23 inet:dns:cname =
Consolidated knowledge of a DNS CNAME record. Properties: • inet:dns:cname = – Consolidated knowledge of a DNS CNAME record. • inet:dns:cname:cname = – The domain returned in the CNAME record.
3.2. Forms 139 Synapse Documentation, Release 0.0.34
• inet:dns:cname:fqdn = – The domain queried for its CNAME record. • inet:dns:cname:seen:max = – The most recent observed time for the data in the CNAME record. • inet:dns:cname:seen:min = – The earliest observed time for the data in the CNAME record.
3.2.24 inet:dns:look =
Instance knowledge of a DNS record lookup. Properties: • inet:dns:look = – Instance knowledge of a DNS record lookup. • inet:dns:look:a = – The DNS A record returned by the lookup. • inet:dns:look:a:fqdn = – The domain queried for its A record. • inet:dns:look:a:ipv4 = – The IPv4 address returned in the A record. • inet:dns:look:aaaa = – The DNS AAAA record returned by the lookup. • inet:dns:look:aaaa:fqdn = – The domain queried for its AAAA record. • inet:dns:look:aaaa:ipv6 = – The IPv6 address returned in the AAAA record. • inet:dns:look:cname = – The DNS CNAME record returned by the lookup. • inet:dns:look:cname:cname = – The domain returned in the CNAME record. • inet:dns:look:cname:fqdn = – The domain queried for its CNAME record. • inet:dns:look:mx = – The DNS MX record returned by the lookup. • inet:dns:look:mx:fqdn = – The domain queried for its MX record. • inet:dns:look:mx:mx = – The domain returned in the MX record.
140 Chapter 3. Synapse Data Model Synapse Documentation, Release 0.0.34
• inet:dns:look:ns = – The DNS NS record returned by the lookup. • inet:dns:look:ns:ns = – The domain returned in the NS record. • inet:dns:look:ns:zone = – The domain queried for its NS record. • inet:dns:look:rev = – The DNS PTR record returned by the lookup. • inet:dns:look:rev:fqdn = – The domain returned in the PTR record. • inet:dns:look:rev:ipv4 = – The IPv4 address queried for its PTR record. • inet:dns:look:soa = – The DNS SOA record returned by the lookup. • inet:dns:look:soa:email = – The normalized email address (RNAME) returned in the SOA record. • inet:dns:look:soa:expire = – The EXPIRE value returned in the SOA record. • inet:dns:look:soa:fqdn = – The domain queried for its SOA record. • inet:dns:look:soa:min = – The MINIMUM value returned in the SOA record. • inet:dns:look:soa:ns = – The domain (MNAME) returned in the SOA record. • inet:dns:look:soa:refresh = – The REFRESH value returned in the SOA record. • inet:dns:look:soa:retry = – The RETRY value returned in the SOA record. • inet:dns:look:soa:serial = – The SERIAL value returned in the SOA record. • inet:dns:look:time = – The date and time that the lookup occurred. • inet:dns:look:txt = – The DNS TXT record returned by the lookup. • inet:dns:look:txt:fqdn = – The domain queried for its TXT record.
3.2. Forms 141 Synapse Documentation, Release 0.0.34
• inet:dns:look:txt:txt = – The string returned in the TXT record.
3.2.25 inet:dns:mx =
Consolidated knowledge of a DNS MX record. Properties: • inet:dns:mx = – Consolidated knowledge of a DNS MX record. • inet:dns:mx:fqdn = – The domain queried for its MX record. • inet:dns:mx:mx = – The domain returned in the MX record. • inet:dns:mx:seen:max = – The most recent observed time for the data in the MX record. • inet:dns:mx:seen:min = – The earliest observed time for the data in the MX record.
3.2.26 inet:dns:ns =
Fused knowledge of a DNS NS record. Properties: • inet:dns:ns = – Fused knowledge of a DNS NS record. • inet:dns:ns:ns = – The domain returned in the NS record. • inet:dns:ns:seen:max = – The most recent observed time for the data in the NS record. • inet:dns:ns:seen:min = – The earliest observed time for the data in the NS record. • inet:dns:ns:zone = – The domain queried for its DNS NS record.
3.2.27 inet:dns:req =
Fused knowledge of a DNS request origin Properties: • inet:dns:req =
142 Chapter 3. Synapse Data Model Synapse Documentation, Release 0.0.34
– Fused knowledge of a DNS request origin • inet:dns:req:addr = – The IPv4 address which requested the FQDN • inet:dns:req:addr:ipv4 = – The IPv4 address which requested the FQDN • inet:dns:req:fqdn = – The requested FQDN • inet:dns:req:type = – The type of DNS record requested
3.2.28 inet:dns:rev =
Fused knowledge of a DNS PTR record. Properties: • inet:dns:rev = – Fused knowledge of a DNS PTR record. • inet:dns:rev:fqdn = – The domain returned in the PTR record. • inet:dns:rev:ipv4 = – The IPv4 address queried for its DNS PTR record. • inet:dns:rev:seen:max = – The most recent observed time for the data in the PTR record. • inet:dns:rev:seen:min = – The earliest observed time for the data in the PTR record.
3.2.29 inet:dns:rev6 =
Fused knowledge of a DNS PTR record for IPv6. Properties: • inet:dns:rev6 = – Fused knowledge of a DNS PTR record for IPv6. • inet:dns:rev6:fqdn = – The domain returned in the PTR record. • inet:dns:rev6:ipv6 = – The IPv6 address queried for its DNS PTR record. • inet:dns:rev6:seen:max = – The most recent observed time for the data in the PTR record. • inet:dns:rev6:seen:min =
3.2. Forms 143 Synapse Documentation, Release 0.0.34
– The earliest observed time for the data in the PTR record.
3.2.30 inet:dns:soa =
Consolidated knowledge of a DNS SOA record. Properties: • inet:dns:soa = – Consolidated knowledge of a DNS SOA record. • inet:dns:soa:email = – The email address (RNAME) returned in the SOA record. • inet:dns:soa:fqdn = – The domain queried for its SOA record. • inet:dns:soa:ns = – The domain (MNAME) returned in the SOA record • inet:dns:soa:seen:max = – The most recent observed time for the data in the SOA record. • inet:dns:soa:seen:min = – The earliest observed time for the data in the SOA record.
3.2.31 inet:dns:txt =
Consolidated knowledge of a DNS TXT record. Properties: • inet:dns:txt = – Consolidated knowledge of a DNS TXT record. • inet:dns:txt:fqdn = – The domain queried for its TXT record. • inet:dns:txt:seen:max = – The most recent observed time for the data in the TXT record. • inet:dns:txt:seen:min = – The earliest observed time for the data in the TXT record. • inet:dns:txt:txt = – The string returned in the TXT record.
144 Chapter 3. Synapse Data Model Synapse Documentation, Release 0.0.34
3.2.32 inet:email =
An email address. Properties: • inet:email = – An email address. • inet:email:fqdn = – The domain of the email address. • inet:email:user = – The username of the email address.
3.2.33 inet:flow =
An individual network connection between a given source and destination. Properties: • inet:flow = – An individual network connection between a given source and destination. • inet:flow:dst:exe = <file:bytes> – The file (executable) that received the connection. • inet:flow:dst:host = – The guid of the destination host. • inet:flow:dst:proc = – The guid of the destination process. • inet:flow:dst:tcp4 = – The destination IPv4 address / port for an IPv4 TCP connection. • inet:flow:dst:tcp4:ipv4 = – The destination IPv4 address. • inet:flow:dst:tcp4:port = – The destination IPv4 port. • inet:flow:dst:tcp6 = – The destination IPv6 address / port for an IPv6 TCP connection. • inet:flow:dst:tcp6:ipv6 = – The destination IPv6 address. • inet:flow:dst:tcp6:port = – The destination IPv6 port. • inet:flow:dst:txbytes = – The number of bytes sent by the destination host / process / file.
3.2. Forms 145 Synapse Documentation, Release 0.0.34
• inet:flow:dst:udp4 = – The destination IPv4 address / port for an IPv4 UDP connection. • inet:flow:dst:udp4:ipv4 = – The destination IPv4 address. • inet:flow:dst:udp4:port = – The destination IPv4 port. • inet:flow:dst:udp6 = – The destination IPv6 address / port for an IPv6 UDP connection. • inet:flow:dst:udp6:ipv6 = – The destination IPv6 address. • inet:flow:dst:udp6:port = – The destination IPv6 port. • inet:flow:duration = – The duration of the flow in seconds. • inet:flow:from = – The ingest source file/iden. Used for reparsing. • inet:flow:src:exe = <file:bytes> – The file (executable) that created the connection. • inet:flow:src:host = – The guid of the source host. • inet:flow:src:proc = – The guid of the source process. • inet:flow:src:tcp4 = – The source IPv4 address / port for an IPv4 TCP connection. • inet:flow:src:tcp4:ipv4 = – The source IPv4 address. • inet:flow:src:tcp4:port = – The source IPv4 port. • inet:flow:src:tcp6 = – The source IPv6 address / port for an IPv6 TCP connection. • inet:flow:src:tcp6:ipv6 = – The source IPv6 address. • inet:flow:src:tcp6:port = – The source IPv6 port. • inet:flow:src:txbytes = – The number of bytes sent by the source host / process / file.
146 Chapter 3. Synapse Data Model Synapse Documentation, Release 0.0.34
• inet:flow:src:udp4 = – The source IPv4 address / port for an IPv4 UDP connection. • inet:flow:src:udp4:ipv4 = – The source IPv4 address. • inet:flow:src:udp4:port = – The source IPv4 port. • inet:flow:src:udp6 = – The source IPv6 address / port for an IPv6 UDP connection. • inet:flow:src:udp6:ipv6 = – The source IPv6 address. • inet:flow:src:udp6:port = – The source IPv6 port. • inet:flow:time = – The time the network connection was initiated.
3.2.34 inet:fqdn =
A fully qualified domain name (FQDN). Properties: • inet:fqdn = – A fully qualified domain name (FQDN). • inet:fqdn:created = – The earliest known registration (creation) date for the fqdn. • inet:fqdn:domain = – The parent fqdn of the fqdn. • inet:fqdn:expires = – The current expiration date for the fqdn. • inet:fqdn:host = – The host portion of the fqdn. • inet:fqdn:sfx = (default: 0) – Set to 1 if the fqdn is considered a “suffix”. • inet:fqdn:updated = – The last known updated date for the fqdn. • inet:fqdn:zone = (default: 0) – Set to 1 if the fqdn is a logical zone (under a suffix).
3.2. Forms 147 Synapse Documentation, Release 0.0.34
3.2.35 inet:iface =
A network interface with a set of associated protocol addresses. Properties: • inet:iface = – A network interface with a set of associated protocol addresses. • inet:iface:host = – The guid of the host the interface is associated with. • inet:iface:ipv4 = – The IPv4 address of the interface. • inet:iface:ipv6 = – The IPv6 address of the interface. • inet:iface:mac = – The ethernet (MAC) address of the interface. • inet:iface:mob:imei = – The IMEI of the interface. • inet:iface:mob:imsi = – The IMSI of the interface. • inet:iface:phone = – The telephone number of the interface. • inet:iface:wifi:bssid = – The wifi BSSID of the interface. • inet:iface:wifi:ssid = – The wifi SSID of the interface.
3.2.36 inet:ipv4 =
An IPv4 address. Properties: • inet:ipv4 = – An IPv4 address. • inet:ipv4:asn = (default: -1) – The ASN to which the IPv4 address is currently assigned. • inet:ipv4:cc = (default: ‘??’) – The country where the IPv4 address is currently located. • inet:ipv4:type = (default: ‘??’) – The type of IP address (e.g., private, multicast, etc.).
148 Chapter 3. Synapse Data Model Synapse Documentation, Release 0.0.34
3.2.37 inet:ipv6 =
An IPv6 address. Properties: • inet:ipv6 = – An IPv6 address. • inet:ipv6:asn = (default: -1) – The ASN to which the IPv6 address is currently assigned. • inet:ipv6:cc = (default: ‘??’) – The country where the IPv6 address is currently located.
3.2.38 inet:mac =
A 48-bit Media Access Control (MAC) address. Properties: • inet:mac = – A 48-bit Media Access Control (MAC) address. • inet:mac:vendor = (default: ‘??’) – The vendor associated with the 24-bit prefix of a MAC address.
3.2.39 inet:passwd =
A password string. Properties: • inet:passwd = – A password string. • inet:passwd:md5 = – The computed MD5 hash of the password. • inet:passwd:sha1 = – The computed SHA1 hash of the password. • inet:passwd:sha256 = – The computed SHA256 hash of the password.
3.2.40 inet:ssl:tcp4cert =
An SSL certificate file served by an IPv4 TCP server. Properties: • inet:ssl:tcp4cert = – An SSL certificate file served by an IPv4 TCP server.
3.2. Forms 149 Synapse Documentation, Release 0.0.34
• inet:ssl:tcp4cert:cert = <file:bytes> – The SSL certificate. • inet:ssl:tcp4cert:tcp4 = – The IPv4 TCP server where the certificate was observed. • inet:ssl:tcp4cert:tcp4:ipv4 = – The IPv4 address associated with the TCP server.
3.2.41 inet:tcp4 =
An IPv4 address and port. Properties: • inet:tcp4 = – An IPv4 address and port. • inet:tcp4:ipv4 = – The IPv4 address of the TCP server. • inet:tcp4:port = – The port of the IPv4 TCP server.
3.2.42 inet:tcp6 =
An IPv6 address and port. Properties: • inet:tcp6 = – An IPv6 address and port. • inet:tcp6:ipv6 = – The IPv6 address of the TCP server. • inet:tcp6:port = – The port of the IPv6 TCP server.
3.2.43 inet:udp4 =
An IPv4 address and port. Properties: • inet:udp4 = – An IPv4 address and port. • inet:udp4:ipv4 = – The IPv4 address of the UDP server. • inet:udp4:port =
150 Chapter 3. Synapse Data Model Synapse Documentation, Release 0.0.34
– The port of the IPv4 UDP server.
3.2.44 inet:udp6 =
An IPv6 address and port. Properties: • inet:udp6 = – An IPv6 address and port. • inet:udp6:ipv6 = – The IPv6 address of the UDP server. • inet:udp6:port = – The port of the IPv6 UDP server.
3.2.45 inet:url =
A Universal Resource Locator (URL). Properties: • inet:url = – A Universal Resource Locator (URL). • inet:url:fqdn = – The fqdn used in the URL (e.g., http://www.woot.com/page.html). • inet:url:ipv4 = – The IPv4 address used in the URL (e.g., http://1.2.3.4/page.html). • inet:url:ipv6 = – The IPv6 address used in the URL. • inet:url:passwd = – The optional password used to access the URL. • inet:url:port = – The port of the URL. URLs prefixed with http will be set to port 80 and URLs prefixed with https will be set to port 443 unless otherwise specified. • inet:url:user = – The optional username used to access the URL.
3.2.46 inet:urlfile =
A file hosted at a specific Universal Resource Locator (URL). Properties: • inet:urlfile = – A file hosted at a specific Universal Resource Locator (URL).
3.2. Forms 151 Synapse Documentation, Release 0.0.34
• inet:urlfile:file = <file:bytes> – The file that was hosted at the URL. • inet:urlfile:seen:max = – The most recent known time the file was hosted at the URL. • inet:urlfile:seen:min = – The earliest known time the file was hosted at the URL. • inet:urlfile:url = – The URL where the file was hosted.
3.2.47 inet:urlredir =
A URL that redirects to another URL, such as via a URL shortening service or an HTTP 302 response. Properties: • inet:urlredir = – A URL that redirects to another URL, such as via a URL shortening service or an HTTP 302 response. • inet:urlredir:dst = – The redirected/destination URL • inet:urlredir:dst:fqdn = – The FQDN within the dst URL (if present) • inet:urlredir:src = – The original/source URL before redirect • inet:urlredir:src:fqdn = – The FQDN within the src URL (if present)
3.2.48 inet:user =
A username string. Properties: • inet:user = – A username string.
3.2.49 inet:web:acct =
An account with a given Internet-based site or service. Properties: • inet:web:acct = – An account with a given Internet-based site or service. • inet:web:acct:avatar = <file:bytes>
152 Chapter 3. Synapse Data Model Synapse Documentation, Release 0.0.34
– The file representing the avatar (e.g., profile picture) for the account. • inet:web:acct:dob = – A self-declared date of birth for the account (if the account belongs to a person). • inet:web:acct:email = – The email address associated with the account. • inet:web:acct:loc = – A self-declared location for the account. • inet:web:acct:name = – The name associated with the account (may be different from the account identifier, e.g., a display name). • inet:web:acct:occupation = – A self-declared occupation for the account. • inet:web:acct:passwd = – The current password for the account. • inet:web:acct:phone = – The phone number associated with the account. • inet:web:acct:realname = – The real name of the account owner / registrant. • inet:web:acct:seen:max = – The most recent known date of activity for the account. • inet:web:acct:seen:min = – The earliest known date of activity for the account. • inet:web:acct:signup = – The date and time the account was registered. • inet:web:acct:signup:ipv4 = – The IPv4 address used to sign up for the account. • inet:web:acct:site = – The site or service associated with the account. • inet:web:acct:tagline = – The text of the account status or tag line. • inet:web:acct:url = – The service provider URL where the account is hosted. • inet:web:acct:user = – The unique identifier for the account (may be different from the common name or display name). • inet:web:acct:webpage = – A related URL specified by the account (e.g., a personal or company web page, blog, etc.).
3.2. Forms 153 Synapse Documentation, Release 0.0.34
3.2.50 inet:web:action =
An instance of an account performing an action at an Internet-based site or service. Properties: • inet:web:action = – An instance of an account performing an action at an Internet-based site or service. • inet:web:action:acct = – The web account associated with the action. • inet:web:action:acct:site = – The site or service associated with the account. • inet:web:action:acct:user = – The unique identifier for the account. • inet:web:action:act = – The action performed by the account. • inet:web:action:info = – Any other data associated with the action. • inet:web:action:ipv4 = – The source IPv4 address of the action. • inet:web:action:ipv6 = – The source IPv6 address of the action. • inet:web:action:time = – The date and time the account performed the action.
3.2.51 inet:web:actref =
A web action that references a given node. Properties: • inet:web:actref = – A web action that references a given node. • inet:web:actref:act = – The action that references the given node. • inet:web:actref:xref = – The prop=valu that is referenced as part of the action. • inet:web:actref:xref:intval = – The normed value of the form that was referenced, if the value is an integer. • inet:web:actref:xref:prop = – The property (form) of the referenced object, as specified by the propvalu.
154 Chapter 3. Synapse Data Model Synapse Documentation, Release 0.0.34
• inet:web:actref:xref:strval = – The normed value of the form that was referenced, if the value is a string.
3.2.52 inet:web:chprofile =
A change to a web account. Used to capture historical properties associated with an account, as opposed to current data in the inet:web:acct node. Properties: • inet:web:chprofile = – A change to a web account. Used to capture historical properties associated with an account, as opposed to current data in the inet:web:acct node. • inet:web:chprofile:acct = – The web account associated with the change. • inet:web:chprofile:acct:site = – The site or service associated with the account. • inet:web:chprofile:acct:user = – The unique identifier for the account. • inet:web:chprofile:ipv4 = – The source IPv4 address used to make the account change. • inet:web:chprofile:ipv6 = – The source IPv6 address used to make the account change. • inet:web:chprofile:pv = – The prop=valu of the account property that was changed. Valu should be the old / original value, while the new value should be updated on the inet:web:acct form. • inet:web:chprofile:pv:intval = – The normed value of the property (specified by pv), if the property is an integer. • inet:web:chprofile:pv:prop = – The property that was changed. • inet:web:chprofile:pv:strval = – The normed value of the property (specified by pv), if the property is a string. • inet:web:chprofile:time = – The date and time when the account change occurred.
3.2.53 inet:web:file =
A file posted by a web account. Properties: • inet:web:file = – A file posted by a web account.
3.2. Forms 155 Synapse Documentation, Release 0.0.34
• inet:web:file:acct = – The account that owns or is associated with the file. • inet:web:file:acct:site = – The site or service associated with the account. • inet:web:file:acct:user = – The unique identifier for the account. • inet:web:file:file = <file:bytes> – The file owned by or associated with the account. • inet:web:file:ipv4 = – The source IPv4 address used to post or submit the file. • inet:web:file:ipv6 = – The source IPv6 address used to post or submit the file. • inet:web:file:name = <file:base> – The name of the file owned by or associated with the account. • inet:web:file:posted = – The date and time the file was posted / submitted. • inet:web:file:seen:max = – The most recent known date the file was posted / submitted / associatedwith the account. • inet:web:file:seen:min = – The earliest known date the file was posted / submitted / associated with the account.
3.2.54 inet:web:follows =
A web account follows or is connected to another web account. Properties: • inet:web:follows = – A web account follows or is connected to another web account. • inet:web:follows:followee = – The account followed by an account. • inet:web:follows:follower = – The account following an account. • inet:web:follows:seen:max = – The most recent known date when the “follows” relationship existed. • inet:web:follows:seen:min = – The earliest known date when the “follows” relationship existed.
156 Chapter 3. Synapse Data Model Synapse Documentation, Release 0.0.34
3.2.55 inet:web:group =
A group hosted within or registered with a given Internet-based site or service. Properties: • inet:web:group = – A group hosted within or registered with a given Internet-based site or service. • inet:web:group:avatar = <file:bytes> – The file representing the avatar (e.g., profile picture) for the group. • inet:web:group:desc = – The text of the description of the group. • inet:web:group:name = – The base string type • inet:web:group:site = – The site or service associated with the group. • inet:web:group:url = – The service provider URL where the group is hosted. • inet:web:group:webpage = – A related URL specified by the group (e.g., primary web site, etc.).
3.2.56 inet:web:logon =
An instance of an account authenticating to an Internet-based site or service. Properties: • inet:web:logon = – An instance of an account authenticating to an Internet-based site or service. • inet:web:logon:acct = – The web account associated with the logon event. • inet:web:logon:acct:site = – The site or service associated with the account. • inet:web:logon:acct:user = – The unique identifier for the account. • inet:web:logon:ipv4 = – The source IPv4 address of the logon. • inet:web:logon:ipv6 = – The source IPv6 address of the logon. • inet:web:logon:logout = – The date and time the account logged out of the service.
3.2. Forms 157 Synapse Documentation, Release 0.0.34
• inet:web:logon:time = – The date and time the account logged into the service.
3.2.57 inet:web:memb =
A web account that is a member of a web group. Properties: • inet:web:memb = – A web account that is a member of a web group. • inet:web:memb:acct = – The account that is a member of the group. • inet:web:memb:group = – The group that the account is a member of. • inet:web:memb:joined = – The date / time the account joined the group. • inet:web:memb:seen:max = – The most recent known date when the account was a member of the group. • inet:web:memb:seen:min = – The earliest known date when the account was a member of the group. • inet:web:memb:title = – The title or status of the member (e.g., admin, new member, etc.).
3.2.58 inet:web:mesg =
A message sent from one web account to another web account. Properties: • inet:web:mesg = – A message sent from one web account to another web account. • inet:web:mesg:file = <file:bytes> – The file attached to or sent with the message. • inet:web:mesg:from = – The web account that sent the message. • inet:web:mesg:text = – The text of the message. • inet:web:mesg:time = – The date and time at which the message was sent. • inet:web:mesg:to = – The web account that received the message.
158 Chapter 3. Synapse Data Model Synapse Documentation, Release 0.0.34
• inet:web:mesg:url = – The URL where the message is posted / visible.
3.2.59 inet:web:post =
A post made by a web account. Properties: • inet:web:post = – A post made by a web account. • inet:web:post:acct = – The web account that made the post. • inet:web:post:acct:site = – The site or service associated with the account. • inet:web:post:acct:user = – The unique identifier for the account. • inet:web:post:file = <file:bytes> – The file that was attached to the post. • inet:web:post:replyto = – The post that this post is in reply to. • inet:web:post:repost = – The original post that this is a repost of. • inet:web:post:text = – The text of the post. • inet:web:post:time = – The date and time that the post was made. • inet:web:post:url = – The URL where the post is published / visible.
3.2.60 inet:web:postref =
A web post that references a given node. Properties: • inet:web:postref = – A web post that references a given node. • inet:web:postref:post = – The web post that references the given node. • inet:web:postref:xref = – The prop=valu that is referenced by the post.
3.2. Forms 159 Synapse Documentation, Release 0.0.34
• inet:web:postref:xref:intval = – The normed value of the form that was referenced, if the value is an integer. • inet:web:postref:xref:prop = – The property (form) of the referenced object, as specified by the propvalu. • inet:web:postref:xref:strval = – The normed value of the form that was referenced, if the value is a string.
3.2.61 inet:whois:contact =
An individual contact from a domain whois record. Properties: • inet:whois:contact = – An individual contact from a domain whois record. • inet:whois:contact:address = – The content of the street address field(s) of the contract. • inet:whois:contact:city = – The content of the city field of the contact. • inet:whois:contact:country = – The two-letter country code of the contact. • inet:whois:contact:email = – The email address of the contact. • inet:whois:contact:fax = – The content of the fax field of the contact. • inet:whois:contact:id = – The ID associated with the contact. • inet:whois:contact:name = – The name of the contact. • inet:whois:contact:orgname = – The name of the contact organization. • inet:whois:contact:phone = – The content of the phone field of the contact. • inet:whois:contact:rec = – The whois record containing the contact data. • inet:whois:contact:rec:asof = – The date of the whois record. • inet:whois:contact:rec:fqdn = – The domain associated with the whois record.
160 Chapter 3. Synapse Data Model Synapse Documentation, Release 0.0.34
• inet:whois:contact:state = – The content of the state field of the contact. • inet:whois:contact:type = – The contact type (e.g., registrar, registrant, admin, billing, tech, etc.).
3.2.62 inet:whois:rar =
A domain registrar. Properties: • inet:whois:rar = – A domain registrar.
3.2.63 inet:whois:rec =
A domain whois record Properties: • inet:whois:rec = – A domain whois record • inet:whois:rec:asof = – The date of the whois record. • inet:whois:rec:created = – The “created” time from the whois record. • inet:whois:rec:expires = – The “expires” time from the whois record. • inet:whois:rec:fqdn = – The domain associated with the whois record. • inet:whois:rec:registrant = (default: ‘??’) – The registrant name from the whois record. • inet:whois:rec:registrar = (default: ‘??’) – The registrar name from the whois record. • inet:whois:rec:text = – The full text of the whois record. • inet:whois:rec:updated = – The “last updated” time from the whois record.
3.2. Forms 161 Synapse Documentation, Release 0.0.34
3.2.64 inet:whois:recns =
A nameserver associated with a domain whois record. Properties: • inet:whois:recns = – A nameserver associated with a domain whois record. • inet:whois:recns:ns = – A nameserver for a domain as listed in the domain whois record. • inet:whois:recns:rec = – The whois record containing the nameserver data. • inet:whois:recns:rec:asof = – The date of the whois record. • inet:whois:recns:rec:fqdn = – The domain associated with the whois record.
3.2.65 inet:whois:reg =
A domain registrant. Properties: • inet:whois:reg = – A domain registrant.
3.2.66 inet:whois:regmail =
An association between a domain and a registrant email address. Properties: • inet:whois:regmail = – An association between a domain and a registrant email address. • inet:whois:regmail:email = – The registrant email address associated with the domain. • inet:whois:regmail:fqdn = – The domain associated with the registrant email address. • inet:whois:regmail:seen:max = – The most recent known date the registrant email was associated with the domain. • inet:whois:regmail:seen:min = – The earliest known date the registrant email was associated with the domain.
162 Chapter 3. Synapse Data Model Synapse Documentation, Release 0.0.34
3.2.67 inet:wifi:ssid =
A WiFi service set identifier (SSID) name. Properties: • inet:wifi:ssid = – A WiFi service set identifier (SSID) name.
3.2.68 it:av:filehit =
A file that triggered an alert on a specific antivirus signature. Properties: • it:av:filehit = – A file that triggered an alert on a specific antivirus signature. • it:av:filehit:file = <file:bytes> – The file that triggered the signature hit. • it:av:filehit:sig = – The signature that the file triggered on.
3.2.69 it:av:sig =
A vendor- or organization-specific antivirus signature name. Properties: • it:av:sig = – A vendor- or organization-specific antivirus signature name. • it:av:sig:desc = – A free-form description of the signature. • it:av:sig:org = – The organization responsible for the signature. • it:av:sig:sig = – The signature name. • it:av:sig:url = – A reference URL for information about the signature.
3.2.70 it:dev:int =
A developer-selected integer constant. Properties: • it:dev:int = – A developer-selected integer constant.
3.2. Forms 163 Synapse Documentation, Release 0.0.34
3.2.71 it:dev:mutex =
A string representing a mutex. Properties: • it:dev:mutex = – A string representing a mutex.
3.2.72 it:dev:pipe =
A string representing a named pipe. Properties: • it:dev:pipe = – A string representing a named pipe.
3.2.73 it:dev:regkey =
A Windows registry key. Properties: • it:dev:regkey = – A Windows registry key.
3.2.74 it:dev:regval =
A Windows registry key/value pair. Properties: • it:dev:regval = – A Windows registry key/value pair. • it:dev:regval:bytes = <file:bytes> – The file representing the value of the registry key, if the value is binary data. • it:dev:regval:int = – The value of the registry key, if the value is an integer. • it:dev:regval:key = – The Windows registry key. • it:dev:regval:str = – The value of the registry key, if the value is a string.
164 Chapter 3. Synapse Data Model Synapse Documentation, Release 0.0.34
3.2.75 it:dev:str =
A developer-selected string. Properties: • it:dev:str = – A developer-selected string. • it:dev:str:norm = – Lower case normalized version of it:dev:str
3.2.76 it:exec:bind:tcp =
A Globally Unique Identifier type Properties: • it:exec:bind:tcp = – A Globally Unique Identifier type • it:exec:bind:tcp:exe = <file:bytes> – The specific file containing code that bound the port. May or may not be the same :exe specified in :proc, if present. • it:exec:bind:tcp:host = – The host running the process that bound the port. Typically the same host referenced in :proc, if present. • it:exec:bind:tcp:ipv4 = – The IPv4 address specified to bind(). • it:exec:bind:tcp:ipv6 = – The IPv6 specified to bind(). • it:exec:bind:tcp:port = – The bound (listening) TCP port. • it:exec:bind:tcp:proc = – The main process executing code that bound the listening TCP port. • it:exec:bind:tcp:time = – The time the port was bound.
3.2.77 it:exec:bind:udp =
A Globally Unique Identifier type Properties: • it:exec:bind:udp = – A Globally Unique Identifier type • it:exec:bind:udp:exe = <file:bytes>
3.2. Forms 165 Synapse Documentation, Release 0.0.34
– The specific file containing code that bound the port. May or may not be the same :exe specified in :proc, if present. • it:exec:bind:udp:host = – The host running the process that bound the port. Typically the same host referenced in :proc, if present. • it:exec:bind:udp:ipv4 = – The IPv4 specified to bind(). • it:exec:bind:udp:ipv6 = – The IPv6 specified to bind(). • it:exec:bind:udp:port = – The bound (listening) UDP port. • it:exec:bind:udp:proc = – The main process executing code that bound the listening UDP port. • it:exec:bind:udp:time = – The time the port was bound.
3.2.78 it:exec:file:add =
A Globally Unique Identifier type Properties: • it:exec:file:add = – A Globally Unique Identifier type • it:exec:file:add:exe = <file:bytes> – The specific file containing code that created the new file. May or may not be the same :exe specified in :proc, if present. • it:exec:file:add:file = <file:bytes> – The file that was created. • it:exec:file:add:host = – The host running the process that created the new file. Typically the same host referenced in :proc, if present. • it:exec:file:add:path = <file:path> – The path where the file was created. • it:exec:file:add:path:base = <file:base> – The final component of the file path (parsed from :path). • it:exec:file:add:path:dir = <file:path> – The parent directory of the file path (parsed from :path). • it:exec:file:add:path:ext = – The file extension of the file name (parsed from :path).
166 Chapter 3. Synapse Data Model Synapse Documentation, Release 0.0.34
• it:exec:file:add:proc = – The main process executing code that created the new file. • it:exec:file:add:time = – The time the file was created.
3.2.79 it:exec:file:del =
A Globally Unique Identifier type Properties: • it:exec:file:del = – A Globally Unique Identifier type • it:exec:file:del:exe = <file:bytes> – The specific file containing code that deleted the file. May or may not be the same :exe specified in :proc if present. • it:exec:file:del:file = <file:bytes> – The file that was deleted. • it:exec:file:del:host = – The host running the process that deleted the file. Typically the same host referenced in :proc, if present. • it:exec:file:del:path = <file:path> – The path where the file was deleted. • it:exec:file:del:path:base = <file:base> – The final component of the file path (parsed from :path). • it:exec:file:del:path:dir = <file:path> – The parent directory of the file path (parsed from :path). • it:exec:file:del:path:ext = – The file extension of the file name (parsed from :path). • it:exec:file:del:proc = – The main process executing code that deleted the file. • it:exec:file:del:time = – The time the file was deleted.
3.2.80 it:exec:file:read =
A Globally Unique Identifier type Properties: • it:exec:file:read = – A Globally Unique Identifier type
3.2. Forms 167 Synapse Documentation, Release 0.0.34
• it:exec:file:read:exe = <file:bytes> – The specific file containing code that read the file. May or may not be the same :exe specified in :proc, if present. • it:exec:file:read:file = <file:bytes> – The file that was read. • it:exec:file:read:host = – The host running the process that read the file. Typically the same host referenced in :proc, if present. • it:exec:file:read:path = <file:path> – The path where the file was read. • it:exec:file:read:path:base = <file:base> – The final component of the file path (parsed from :path). • it:exec:file:read:path:dir = <file:path> – The parent directory of the file path (parsed from :path). • it:exec:file:read:path:ext = – The file extension of the file name (parsed from :path). • it:exec:file:read:proc = – The main process executing code that read the file. • it:exec:file:read:time = – The time the file was read.
3.2.81 it:exec:file:write =
A Globally Unique Identifier type Properties: • it:exec:file:write = – A Globally Unique Identifier type • it:exec:file:write:exe = <file:bytes> – The specific file containing code that wrote to the file. May or may not be the same :exe referenced in :proc, if present. • it:exec:file:write:file = <file:bytes> – The file that was modified. • it:exec:file:write:host = – The host running the process that wrote to the file. Typically the same host referenced in :proc, if present. • it:exec:file:write:path = <file:path> – The path where the file was modified. • it:exec:file:write:path:base = <file:base> – The final component of the file path (parsed from :path).
168 Chapter 3. Synapse Data Model Synapse Documentation, Release 0.0.34
• it:exec:file:write:path:dir = <file:path> – The parent directory of the file path (parsed from :path). • it:exec:file:write:path:ext = – The file extension of the file name (parsed from :path). • it:exec:file:write:proc = – The main process executing code that wrote to / modified the existing file. • it:exec:file:write:time = – The time the file was written to / modified.
3.2.82 it:exec:mutex =
A Globally Unique Identifier type Properties: • it:exec:mutex = – A Globally Unique Identifier type • it:exec:mutex:exe = <file:bytes> – The specific file containing code that created the mutex. May or may not be the same :exe specified in :proc, if present. • it:exec:mutex:host = – The host running the process that created the mutex. Typically the same host referenced in :proc, if present. • it:exec:mutex:name = – The mutex string. • it:exec:mutex:proc = – The main process executing code that created the mutex. • it:exec:mutex:time = – The time the mutex was created.
3.2.83 it:exec:pipe =
A Globally Unique Identifier type Properties: • it:exec:pipe = – A Globally Unique Identifier type • it:exec:pipe:exe = <file:bytes> – The specific file containing code that created the named pipe. May or may not be the same :exe specified in :proc, if present. • it:exec:pipe:host =
3.2. Forms 169 Synapse Documentation, Release 0.0.34
– The host running the process that created the named pipe. Typically the same host referenced in :proc, if present. • it:exec:pipe:name = – The named pipe string. • it:exec:pipe:proc = – The main process executing code that created the named pipe. • it:exec:pipe:time = – The time the named pipe was created.
3.2.84 it:exec:proc =
A Globally Unique Identifier type Properties: • it:exec:proc = – A Globally Unique Identifier type • it:exec:proc:cmd = – The command string used to launch the process, including any command line parameters. • it:exec:proc:exe = <file:bytes> – The file considered the “main” executable for the process. For example, rundll32.exe may be consid- ered the “main” executable for DLLs loaded by that program. • it:exec:proc:host = – The host that executed the process. May be an actual or a virtual / notional host. • it:exec:proc:path = <file:path> – The path to the executable of the process. • it:exec:proc:pid = – The process ID. • it:exec:proc:src:exe = <file:path> – The executable which created the process. • it:exec:proc:src:proc = – The process which created the process. • it:exec:proc:time = – The start time for the process. • it:exec:proc:user = – The user name of the process owner.
170 Chapter 3. Synapse Data Model Synapse Documentation, Release 0.0.34
3.2.85 it:exec:reg:del =
A Globally Unique Identifier type Properties: • it:exec:reg:del = – A Globally Unique Identifier type • it:exec:reg:del:exe = <file:bytes> – The specific file containing code that deleted data from the registry. May or may not be the same :exe referenced in :proc, if present. • it:exec:reg:del:host = – The host running the process that deleted data from the registry. Typically the same host referenced in :proc, if present. • it:exec:reg:del:proc = – The main process executing code that deleted data from the registry. • it:exec:reg:del:reg = – The registry key or value that was deleted. • it:exec:reg:del:reg:bytes = <file:bytes> – The binary data that was deleted (parsed from :reg). • it:exec:reg:del:reg:int = – The integer value that was deleted (parsed from :reg). • it:exec:reg:del:reg:key = – The registry key that was deleted (parsed from :reg). • it:exec:reg:del:reg:str = – The string value that was deleted (parsed from :reg). • it:exec:reg:del:time = – The time the data from the registry was deleted.
3.2.86 it:exec:reg:get =
A Globally Unique Identifier type Properties: • it:exec:reg:get = – A Globally Unique Identifier type • it:exec:reg:get:exe = <file:bytes> – The specific file containing code that read the registry. May or may not be the same :exe referenced in :proc, if present. • it:exec:reg:get:host = – The host running the process that read the registry. Typically the same host referenced in :proc, if present.
3.2. Forms 171 Synapse Documentation, Release 0.0.34
• it:exec:reg:get:proc = – The main process executing code that read the registry. • it:exec:reg:get:reg = – The registry key or value that was read. • it:exec:reg:get:reg:bytes = <file:bytes> – The binary data that was read (parsed from :reg). • it:exec:reg:get:reg:int = – The integer value that was read (parsed from :reg). • it:exec:reg:get:reg:key = – The registry key that was read (parsed from :reg). • it:exec:reg:get:reg:str = – The string value that was read (parsed from :reg). • it:exec:reg:get:time = – The time the registry was read.
3.2.87 it:exec:reg:set =
A Globally Unique Identifier type Properties: • it:exec:reg:set = – A Globally Unique Identifier type • it:exec:reg:set:exe = <file:bytes> – The specific file containing code that wrote to the registry. May or may not be the same :exe referenced in :proc, if present. • it:exec:reg:set:host = – The host running the process that wrote to the registry. Typically the same host referenced in :proc, if present. • it:exec:reg:set:proc = – The main process executing code that wrote to the registry. • it:exec:reg:set:reg = – The registry key or value that was written. • it:exec:reg:set:reg:bytes = <file:bytes> – The binary data that was written (parsed from :reg). • it:exec:reg:set:reg:int = – The integer value that was written (parsed from :reg). • it:exec:reg:set:reg:key = – The registry key that was written (parsed from :reg). • it:exec:reg:set:reg:str =
172 Chapter 3. Synapse Data Model Synapse Documentation, Release 0.0.34
– The string value that was written (parsed from :reg). • it:exec:reg:set:time = – The time the registry was written to.
3.2.88 it:exec:url =
A Globally Unique Identifier type Properties: • it:exec:url = – A Globally Unique Identifier type • it:exec:url:exe = <file:bytes> – The specific file containing code that requested the URL. May or may not be the same :exe specified in :proc, if present. • it:exec:url:host = – The host running the process that requested the URL. Typically the same host referenced in :proc, if present. • it:exec:url:ipv4 = – The IPv4 address of the host during URL retrieval. • it:exec:url:ipv6 = – The IPv6 address of the host during URL retrieval. • it:exec:url:proc = – The main process executing code that requested the URL. • it:exec:url:time = – The time the URL was requested. • it:exec:url:url = – The URL that was requested.
3.2.89 it:fs:file =
A Globally Unique Identifier type Properties: • it:fs:file = – A Globally Unique Identifier type • it:fs:file:atime = – The file access time. • it:fs:file:ctime = – The file creation time. • it:fs:file:file = <file:bytes>
3.2. Forms 173 Synapse Documentation, Release 0.0.34
– The file on the host. • it:fs:file:group = – The group owner of the file. • it:fs:file:host = – The host containing the file. • it:fs:file:mtime = – The file modification time. • it:fs:file:path = <file:path> – The path for the file. • it:fs:file:path:base = <file:base> – The final component of the file path (parsed from :path). • it:fs:file:path:dir = <file:path> – The parent directory of the file path (parsed from :path). • it:fs:file:path:ext = – The file extension of the file name (parsed from :path). • it:fs:file:user = – The owner of the file.
3.2.90 it:host =
A GUID that represents a host or system. Properties: • it:host = – A GUID that represents a host or system. • it:host:desc = – A free-form description of the host. • it:host:ipv4 = – The last known ipv4 address for the host. • it:host:name = – The name of the host or system.
3.2.91 it:hostname =
The name of a host or system. Properties: • it:hostname = – The name of a host or system.
174 Chapter 3. Synapse Data Model Synapse Documentation, Release 0.0.34
3.2.92 it:hostsoft =
A version of a software product which is present on a given host. Properties: • it:hostsoft = – A version of a software product which is present on a given host. • it:hostsoft:host = – Host with the software • it:hostsoft:seen:max = – Maximum time the software was seen on the host • it:hostsoft:seen:min = – Minimum time the software was seen on the host • it:hostsoft:softver = – Software on the host
3.2.93 it:prod:soft =
A arbitrary, unversioned software product. Properties: • it:prod:soft = – A arbitrary, unversioned software product. • it:prod:soft:author:acct = – Web user responsible for the software • it:prod:soft:author:org = – Organization responsible for the software • it:prod:soft:author:person = – Person responsible for the software • it:prod:soft:desc = – A description of the software • it:prod:soft:desc:short = – A short description of the software • it:prod:soft:name = – Name of the software • it:prod:soft:url = – URL relevant for the software
3.2. Forms 175 Synapse Documentation, Release 0.0.34
3.2.94 it:prod:softver =
A version of a particular software product. Properties: • it:prod:softver = – A version of a particular software product. • it:prod:softver:arch = – Software architecture. • it:prod:softver:semver = – System normalized semantic version number. • it:prod:softver:semver:build = – Semver build string. • it:prod:softver:semver:major = – Version major number • it:prod:softver:semver:minor = – Version minor number • it:prod:softver:semver:patch = – Version patch number • it:prod:softver:semver:pre = – Semver prerelease string. • it:prod:softver:software = – Software associated with this version instance. • it:prod:softver:software:name = – The name of the software at a particular version. • it:prod:softver:url = – URL where a specific version of the software is available from • it:prod:softver:vers = – A developer-selected string. • it:prod:softver:vers:norm = – Normalized version of the version string.
3.2.95 it:sec:cve =
A vulnerability as designated by a Common Vulnerabilities and Exposures (CVE) number. Properties: • it:sec:cve = – A vulnerability as designated by a Common Vulnerabilities and Exposures (CVE) number.
176 Chapter 3. Synapse Data Model Synapse Documentation, Release 0.0.34
• it:sec:cve:desc = – A free-form description of the CVE vulnerability.
3.2.96 lang:idiom =
A subcultural idiom Properties: • lang:idiom = – A subcultural idiom • lang:idiom:desc:en = – English description • lang:idiom:url = – Authoritative URL for the idiom
3.2.97 lang:trans =
Raw text with a documented translation Properties: • lang:trans = – Raw text with a documented translation • lang:trans:desc:en = – English description • lang:trans:text:en = – English translation
3.2.98 mat:item =
A GUID assigned to a material object Properties: • mat:item = – A GUID assigned to a material object • mat:item:name = – The human readable name of the material item
3.2.99 mat:itemimage =
A multi-field composite type which uses separated repr values Properties: • mat:itemimage =
3.2. Forms 177 Synapse Documentation, Release 0.0.34
– A multi-field composite type which uses separated repr values • mat:itemimage:file = <file:bytes> – The file containing an image of the item • mat:itemimage:item = – The item contained within the image file
3.2.100 mat:spec =
A GUID assigned to a material specification Properties: • mat:spec = – A GUID assigned to a material specification • mat:spec:name = – The human readable name of the material spec
3.2.101 mat:specimage =
A multi-field composite type which uses separated repr values Properties: • mat:specimage = – A multi-field composite type which uses separated repr values • mat:specimage:file = <file:bytes> – The file containing an image of the spec • mat:specimage:spec = – The spec contained within the image file
3.2.102 media:news =
A published news item, report, or article GUID Properties: • media:news = – A published news item, report, or article GUID • media:news:author = (default: ‘?,?’) – The free-form author of the news • media:news:file = <file:bytes> – The (optional) file blob containing or published as the news • media:news:org = (default: ‘??’) – The org alias which published the news
178 Chapter 3. Synapse Data Model Synapse Documentation, Release 0.0.34
• media:news:published = (default: 0) – The date the news item was published • media:news:summary = (default: ‘??’) – A brief summary of the news item • media:news:title = (default: ‘??’) – Title/Headline for the news • media:news:url = – The (optional) URL where the news was published • media:news:url:fqdn = – The FQDN within the news URL
3.2.103 ou:hasemail =
A multi-field composite type which generates a stable guid from normalized fields Properties: • ou:hasemail = – A multi-field composite type which generates a stable guid from normalized fields • ou:hasemail:email = – An email address. • ou:hasemail:org = – A GUID for a human organization such as a company or military unit • ou:hasemail:seen:max = – Maximum time in millis since epoch • ou:hasemail:seen:min = – Minimum time in millis since epoch
3.2.104 ou:hasfile =
A multi-field composite type which generates a stable guid from normalized fields Properties: • ou:hasfile = – A multi-field composite type which generates a stable guid from normalized fields • ou:hasfile:file = <file:bytes> – A unique file identifier • ou:hasfile:org = – A GUID for a human organization such as a company or military unit • ou:hasfile:seen:max = – Maximum time in millis since epoch
3.2. Forms 179 Synapse Documentation, Release 0.0.34
• ou:hasfile:seen:min = – Minimum time in millis since epoch
3.2.105 ou:hasfqdn =
A multi-field composite type which generates a stable guid from normalized fields Properties: • ou:hasfqdn = – A multi-field composite type which generates a stable guid from normalized fields • ou:hasfqdn:fqdn = – A fully qualified domain name (FQDN). • ou:hasfqdn:org = – A GUID for a human organization such as a company or military unit • ou:hasfqdn:seen:max = – Maximum time in millis since epoch • ou:hasfqdn:seen:min = – Minimum time in millis since epoch
3.2.106 ou:hashost =
A multi-field composite type which generates a stable guid from normalized fields Properties: • ou:hashost = – A multi-field composite type which generates a stable guid from normalized fields • ou:hashost:host = – A GUID that represents a host or system. • ou:hashost:org = – A GUID for a human organization such as a company or military unit • ou:hashost:seen:max = – Maximum time in millis since epoch • ou:hashost:seen:min = – Minimum time in millis since epoch
3.2.107 ou:hasipv4 =
A multi-field composite type which generates a stable guid from normalized fields Properties: • ou:hasipv4 =
180 Chapter 3. Synapse Data Model Synapse Documentation, Release 0.0.34
– A multi-field composite type which generates a stable guid from normalized fields • ou:hasipv4:ipv4 = – An IPv4 address. • ou:hasipv4:org = – A GUID for a human organization such as a company or military unit • ou:hasipv4:seen:max = – Maximum time in millis since epoch • ou:hasipv4:seen:min = – Minimum time in millis since epoch
3.2.108 ou:hasphone =
A multi-field composite type which generates a stable guid from normalized fields Properties: • ou:hasphone = – A multi-field composite type which generates a stable guid from normalized fields • ou:hasphone:org = – A GUID for a human organization such as a company or military unit • ou:hasphone:phone = • ou:hasphone:seen:max = – Maximum time in millis since epoch • ou:hasphone:seen:min = – Minimum time in millis since epoch
3.2.109 ou:haswebacct =
A multi-field composite type which generates a stable guid from normalized fields Properties: • ou:haswebacct = – A multi-field composite type which generates a stable guid from normalized fields • ou:haswebacct:org = – A GUID for a human organization such as a company or military unit • ou:haswebacct:seen:max = – Maximum time in millis since epoch • ou:haswebacct:seen:min = – Minimum time in millis since epoch • ou:haswebacct:web:acct = – An account with a given Internet-based site or service.
3.2. Forms 181 Synapse Documentation, Release 0.0.34
3.2.110 ou:member =
A multi-field composite type which uses separated repr values Properties: • ou:member = – A multi-field composite type which uses separated repr values • ou:member:start = – Minimum time in millis since epoch • ou:member:title = (default: ‘??’) – The base string type
3.2.111 ou:org =
A GUID for a human organization such as a company or military unit Properties: • ou:org = – A GUID for a human organization such as a company or military unit • ou:org:alias = – An alias for the org GUID • ou:org:cc = – The 2 digit ISO country code • ou:org:naics = – North American Industry Classification System • ou:org:name = – The base string type • ou:org:name:en = – The base string type • ou:org:phone = – The primary phone number for the organization • ou:org:sic = – Standard Industrial Classification Code • ou:org:url = – A Universal Resource Locator (URL). • ou:org:us:cage = – A Commercial and Government Entity (CAGE) code
182 Chapter 3. Synapse Data Model Synapse Documentation, Release 0.0.34
3.2.112 ou:owns =
A multi-field composite type which uses separated repr values Properties: • ou:owns = – A multi-field composite type which uses separated repr values
3.2.113 ou:suborg =
An org which owns a sub org Properties: • ou:suborg = – An org which owns a sub org • ou:suborg:current = (default: 1) – Is the suborg relationship still current • ou:suborg:org = – The org which owns sub • ou:suborg:perc = – The optional percentage of sub which is owned by org • ou:suborg:seen:max = – The optional time the suborg relationship ended • ou:suborg:seen:min = – The optional time the suborg relationship began • ou:suborg:sub = – The the sub which is owned by org
3.2.114 ou:user =
A user name within an organization Properties: • ou:user = – A user name within an organization • ou:user:org = – A GUID for a human organization such as a company or military unit • ou:user:user = – A username string.
3.2. Forms 183 Synapse Documentation, Release 0.0.34
3.2.115 pol:country =
A GUID for a country Properties: • pol:country = – A GUID for a country • pol:country:founded = (default: 0) – Timestamp in milliseconds since epoch • pol:country:iso2 = – The 2 digit ISO country code • pol:country:iso3 = – The 3 digit ISO country code • pol:country:isonum = – The ISO integer country code • pol:country:name = – The base string type • pol:country:pop = (default: 0) – The base integer type • pol:country:tld = – A fully qualified domain name (FQDN).
3.2.116 pol:flag = <file:bytes>
The flag image SHA256 Properties: • pol:flag = <file:bytes> – The flag image SHA256 • pol:flag:cc = – The (optional) ISO2 country code for the flag • pol:flag:orgalias = – The (optional) org alias for the flat
3.2.117 pol:hist =
A GUID for a country Properties: • pol:hist = – A GUID for a country
184 Chapter 3. Synapse Data Model Synapse Documentation, Release 0.0.34
3.2.118 ps:contact =
A collection of contact information in a single record Properties: • ps:contact = – A collection of contact information in a single record • ps:contact:address = – The free-form address listed for the contact • ps:contact:asof = – The time this contact was created or modified • ps:contact:dob = – The Date of Birth (DOB) for the contact • ps:contact:email = – The main email address for this contact • ps:contact:email:work = – The contact work email address • ps:contact:name = – The person name listed for the contact • ps:contact:org = – The ou:org GUID which owns this contact • ps:contact:orgname = – The listed org/company name for this contact • ps:contact:person = – The ps:person GUID which owns this contact • ps:contact:phone = – The “main” phone number for this contact • ps:contact:phone:fax = – The contact fax phone number • ps:contact:phone:work = – The contact work phone number • ps:contact:photo = <file:bytes> – The photo listed for this contact • ps:contact:title = – The job/org title listed for this contact • ps:contact:url = – The home/main site for this contact • ps:contact:user =
3.2. Forms 185 Synapse Documentation, Release 0.0.34
– The username or handle for the contact • ps:contact:web:acct = – The social media account for this contact
3.2.119 ps:hasalias =
A multi-field composite type which uses separated repr values Properties: • ps:hasalias = – A multi-field composite type which uses separated repr values • ps:hasalias:alias = – A last,first person full name • ps:hasalias:person = – A GUID for a person or suspected person
3.2.120 ps:hasemail =
A multi-field composite type which uses separated repr values Properties: • ps:hasemail = – A multi-field composite type which uses separated repr values • ps:hasemail:email = – An email address. • ps:hasemail:person = – A GUID for a person or suspected person
3.2.121 ps:hasphone =
A multi-field composite type which uses separated repr values Properties: • ps:hasphone = – A multi-field composite type which uses separated repr values • ps:hasphone:person = – A GUID for a person or suspected person • ps:hasphone:phone =
186 Chapter 3. Synapse Data Model Synapse Documentation, Release 0.0.34
3.2.122 ps:hasuser =
A multi-field composite type which uses separated repr values Properties: • ps:hasuser = – A multi-field composite type which uses separated repr values • ps:hasuser:person = – A GUID for a person or suspected person • ps:hasuser:user = – A username string.
3.2.123 ps:haswebacct =
A multi-field composite type which uses separated repr values Properties: • ps:haswebacct = – A multi-field composite type which uses separated repr values • ps:haswebacct:person = – A GUID for a person or suspected person • ps:haswebacct:web:acct = – An account with a given Internet-based site or service.
3.2.124 ps:image =
A multi-field composite type which uses separated repr values Properties: • ps:image = – A multi-field composite type which uses separated repr values • ps:image:file = <file:bytes> – A unique file identifier • ps:image:person = – A GUID for a person or suspected person
3.2.125 ps:name =
A last,first person full name Properties: • ps:name = – A last,first person full name
3.2. Forms 187 Synapse Documentation, Release 0.0.34
• ps:name:given = – The “given name” part of ps:name • ps:name:middle = – The “middle name” part of ps:name • ps:name:sur = – The “surname” part of ps:name
3.2.126 ps:person =
A GUID for a person or suspected person Properties: • ps:person = – A GUID for a person or suspected person • ps:person:dob = – The Date of Birth (DOB) if known • ps:person:guidname = – The GUID resolver alias for this person • ps:person:img = <file:bytes> – The “primary” image of a person • ps:person:name = – A last,first person full name • ps:person:name:given = – A single name element (potentially given or sur) • ps:person:name:sur = – A single name element (potentially given or sur) • ps:person:nick = – A username string.
3.2.127 ps:tokn =
A single name element (potentially given or sur) Properties: • ps:tokn = – A single name element (potentially given or sur)
188 Chapter 3. Synapse Data Model Synapse Documentation, Release 0.0.34
3.2.128 rsa:key =
An RSA keypair modulus and public exponent Properties: • rsa:key = – An RSA keypair modulus and public exponent • rsa:key:bits = – The length of the modulus in bits • rsa:key:mod = – The modulus • rsa:key:priv:exp = – The private exponent • rsa:key:priv:p = – One of the two private primes • rsa:key:priv:q = – One of the two private primes • rsa:key:pub:exp = – The public exponent
3.2.129 syn:auth:role =
The base string type Properties: • syn:auth:role = – The base string type • syn:auth:role:desc = – The base string type
3.2.130 syn:auth:user =
The base string type Properties: • syn:auth:user = – The base string type • syn:auth:user:storm:limit:lift = (default: 10000) – The storm query lift limit for the user • syn:auth:user:storm:limit:time = (default: 120) – The storm query time limit for the user
3.2. Forms 189 Synapse Documentation, Release 0.0.34
3.2.131 syn:auth:userrole =
A multi-field composite type which generates a stable guid from normalized fields Properties: • syn:auth:userrole = – A multi-field composite type which generates a stable guid from normalized fields • syn:auth:userrole:role = – The base string type • syn:auth:userrole:user = – The base string type
3.2.132 syn:core =
A node representing a unique Cortex Properties: • syn:core = – A node representing a unique Cortex
3.2.133 syn:fifo =
A Globally Unique Identifier type Properties: • syn:fifo = – A Globally Unique Identifier type • syn:fifo:desc = – The fifo description • syn:fifo:name = – The name of this fifo
3.2.134 syn:form =
The base form type. Properties: • syn:form = – The base form type. • syn:form:doc = – basic form definition • syn:form:local = (default: 0) – Flag used to determine if a form should not be included in splices
190 Chapter 3. Synapse Data Model Synapse Documentation, Release 0.0.34
• syn:form:model = – which model defines a given form • syn:form:ptype = – Synapse type for this form • syn:form:ver = – form version within the model
3.2.135 syn:model = prefix for all forms with in the model Properties: • syn:model = – prefix for all forms with in the model • syn:model:hash = – version hash for the current model • syn:model:prefix = – Prefix used by teh types/forms in the model
3.2.136 syn:prop =
The base property type. Properties: • syn:prop = – The base property type. • syn:prop:base = – Base name of the property • syn:prop:defval = – Set to the default value for this property • syn:prop:doc = – Description of the property definition. • syn:prop:form = – The form of the property. • syn:prop:glob = (default: 0) – Set to 1 if this property defines a glob • syn:prop:ptype = – Synapse type for this field • syn:prop:relname = – Relative name of the property
3.2. Forms 191 Synapse Documentation, Release 0.0.34
• syn:prop:req = – Set to 1 if this property is required to form teh node. • syn:prop:title = – A short description of the property definition. • syn:prop:univ = – Specifies if a prop is universal and has no form associated with it.
3.2.137 syn:seq =
A sequential id generation tracker Properties: • syn:seq = – A sequential id generation tracker • syn:seq:nextvalu = (default: 0) – The next sequential value • syn:seq:width = (default: 0) – How many digits to use to represent the number
3.2.138 syn:splice =
A Globally Unique Identifier type Properties: • syn:splice = – A Globally Unique Identifier type • syn:splice:act = – The base string type • syn:splice:form = – The base string type • syn:splice:node = – A Globally Unique Identifier type • syn:splice:tag = – The base string type • syn:splice:time = – Timestamp in milliseconds since epoch • syn:splice:user = – The base string type • syn:splice:valu = – The base string type
192 Chapter 3. Synapse Data Model Synapse Documentation, Release 0.0.34
3.2.139 syn:tag =
The base form for a synapse tag. Properties: • syn:tag = – The base form for a synapse tag. • syn:tag:base = • syn:tag:depth = (default: 0) – How deep the tag is in the hierarchy • syn:tag:doc = (default: ‘’) – The base string type • syn:tag:title = (default: ‘’) • syn:tag:up =
3.2.140 syn:tagform =
A node describing the meaning of a tag on a specific form Properties: • syn:tagform = – A node describing the meaning of a tag on a specific form • syn:tagform:doc = (default: ‘??’) – The long form description for what the tag means on the given node form • syn:tagform:form = – The form that the tag applies too • syn:tagform:tag = – The tag being documented • syn:tagform:title = (default: ‘??’) – The short name for what the tag means the given node form
3.2.141 syn:trigger =
A Globally Unique Identifier type Properties: • syn:trigger = – A Globally Unique Identifier type • syn:trigger:en = (default: 0) – Is the trigger currently enabled • syn:trigger:on =
3.2. Forms 193 Synapse Documentation, Release 0.0.34
– A synapse permission string • syn:trigger:run = – A synapse storm query string • syn:trigger:user = – The base string type
3.2.142 syn:type =
The base type type. Properties: • syn:type = – The base type type. • syn:type:* = • syn:type:ctor = – Python path to the class used to instantiate the type. • syn:type:subof = – Type which this inherits from.
3.2.143 tel:mob:imei =
An International Mobile Equipment Id Properties: • tel:mob:imei= – An International Mobile Equipment Id • tel:mob:imei:serial = – The serial number within the IMEI • tel:mob:imei:tac= – The Type Allocate Code within the IMEI
3.2.144 tel:mob:imsi =
An International Mobile Subscriber Id Properties: • tel:mob:imsi= – An International Mobile Subscriber Id • tel:mob:imsi:mcc = – The Mobile Country Code
194 Chapter 3. Synapse Data Model Synapse Documentation, Release 0.0.34
3.2.145 tel:mob:tac =
A mobile Type Allocation Code Properties: • tel:mob:tac= – A mobile Type Allocation Code • tel:mob:tac:internal = (default: ‘??’) – The TAC internal model name • tel:mob:tac:manu = (default: ‘??’) – The TAC manufacturer name • tel:mob:tac:model = (default: ‘??’) – The TAC model name • tel:mob:tac:org = – The org guid for the manufacturer
3.2.146 tel:phone =
Properties: • tel:phone= • tel:phone:cc = (default: ‘??’) – The 2 digit ISO country code
3.2.147 tel:prefix =
Properties: • tel:prefix= • tel:prefix:cc = (default: ‘??’) – The 2 digit ISO country code • tel:prefix:tag = – A synapse tag
3.3 Universal Props
Universal props are system level properties which are generally present on every node. These properties are not specific to a particular form and exist outside of a particular namespace.
3.3. Universal Props 195 Synapse Documentation, Release 0.0.34
3.3.1 node:created
• node:created = – The time the node was created
3.3.2 node:ndef
• node:ndef = – The unique guid representing the combination of the node form and primary property.
3.3.3 tufo:form
• tufo:form = – The form of the node
196 Chapter 3. Synapse Data Model CHAPTER 4
synapse package
4.1 Subpackages
4.1.1 synapse.cmds package
Submodules synapse.cmds.common module class synapse.cmds.common.GuidCmd(cli, **opts) Bases: synapse.lib.cli.Cmd Generate a new guid Examples: guid runCmdOpts(opts) class synapse.cmds.common.PyCmd(cli, **opts) Bases: synapse.lib.cli.Cmd Evaluate a line of python code with the cmd item. Examples: py item.getFooThingByBar(‘baz’) runCmdOpts(opts) synapse.cmds.cortex module class synapse.cmds.cortex.AskCmd(cli, **opts) Bases: synapse.lib.cli.Cmd
197 Synapse Documentation, Release 0.0.34
Execute a query. Examples: ask optional: –debug –[props|raw] ask –debug inet:ipv4=0 ask –props inet:ipv4=”0.0.0.0” ask –raw inet:ipv4=”0.0.0.0” ask –debug – props inet:ipv4=0x01020304 runCmdOpts(opts) class synapse.cmds.cortex.NextSeqCmd(cli, **opts) Bases: synapse.lib.cli.Cmd Generate and display the next id in the named sequence. Usage: nextseq runCmdOpts(opts)
Module contents
4.1.2 synapse.cores package
Submodules synapse.cores.common module class synapse.cores.common.Cortex(link, store, **conf ) Bases: synapse.eventbus.EventBus, synapse.datamodel.DataModel, synapse.lib. storm.Runtime, synapse.lib.ingest.IngestApi Top level Cortex key/valu storage object. ackCoreFifo(name, seqn) Acknowledge transmission of fifo items. Args: name (str): The syn:fifo:name of the fifo. nseq (int): The next expected sequence. addCoreMods(mods) Add a list of (name,conf) tuples to the cortex. addJsonItem(form, item, tstamp=None) Add and fully index a JSON compatible data structure ( not in text form ). Example: foo = { ‘bar’:10, ‘baz’:{ ‘faz’:’hehe’, ‘woot’:30 } } core.addJsonItem(‘foo’,foo) addJsonItems(form, items, tstamp=None) Add and fully index a list of JSON compatible data structures. Example: core.addJsonItems(‘foo’, foolist) addJsonText(form, text) Add and fully index a blob of JSON text. Example:
198 Chapter 4. synapse package Synapse Documentation, Release 0.0.34
addListRows(prop, *vals) Add rows by making a guid for each and using now(). Example: core.addListRows(‘foo:bar’,[ 1, 2, 3, 4]) addPermDefs(defs) Add a set of permission definitions for use with the cortex auth subsystem. A perm definition tuple consists of: (perm, info, fields) ex: (‘node:add’, {‘doc’: ‘The permission to add nodes’}, ( (‘form’, {‘doc’: ‘The form of the node being created’}), ) Args: defs (list): A list of permission defs Returns: (None) addRoleRule(role, rule, indx=None) Add a rule tuple for the given role (optionally at index). Args: role (str): The role name rule (tuple): The rule tuple indx (int): The index at which to insert the rule addRows(rows) Add (iden,prop,valu,time) rows to the Cortex. Example: import time tick = now() rows = [ (id1,’baz’,30,tick), (id1,’foo’,’bar’,tick), ] core.addRows(rows) addRuntNode(form, valu, props=None) Add a “runtime” node which does not persist. This is used for ephemeral node “look aside” registration. Args: form (str): The primary property for the node valu (obj): The primary value for the node props (dict): The node secondary properties ( if modeled, they will be indexed ) Returns: ((None,dict)): The ephemeral node addSaveLink(func) Add an event callback to receive save events for this cortex. Example: def savemesg(mesg): dostuff() core.addSaveLink(savemesg) addSeedCtor(name, func) Add a “seed constructor” to the cortex. This allows modules to register functions to construct nodes by a “seed name” which they transform into an existing node from the model. Example: def seedOrgName(name, valu,**props): orgn = core.getTufoByProp(‘org:iden:name’,valu) if orgn == None:
4.1. Subpackages 199 Synapse Documentation, Release 0.0.34
orgn = core.formTufoByProp(‘org:iden’,guid(),name=valu) return orgn core.addSeedCtor(‘org:iden:name’, seedOrgName) core.formTufoByProp(‘org:iden:name’,’The Vertex Project, LLC’) addSpliceFd(fd) Write all cortex splice events to the specified file-like object. Example: fd = open(‘audit.mpk’,’r+b’) core.addSpliceFd(fd) addStatFunc(name, func) Add a callback function to implement a statistic type. Example: def calcwoot(rows): sum([ r[2] for r in rows ]) + 99 ... core.addStatFunc(‘woot’, calcwoot) # later.. woot = core.getStatByProp(‘woot’,’haha’) addTufoDark(tufo, name, valu) Add a dark row to a tufo with a given name and value. Dark rows get their own index and can be used to quickly pull tufos. While similar to dsets, these are primarily intended for implementing features inside of Synapse directly. Args: tufo ((str, dict)): Tufo to add the dark row too. name (str): Dark row name. value (str): Value to set on the dark property. May be any data type which may stored in a cortex. Returns: None: Returns None. addTufoDset(tufo, name) Add the tufo to a named dataset. addTufoList(tufo, name, *vals) Add “list” rows to a tufo. Example: core.addTufoList(tufo, ‘counts’, 99, 300, 1773) Notes: • this creates the tufo:list: prop on the tufo to indicate that the list is present. addTufoTag(tufo, tag, times=()) Add a tag (and optionally time box) to a tufo. Args: tufo ((str,dict)): A node in tuple form. tag (str): A synapse tag string times ((int,)): A list of time stamps in milli epoch Examples: Form a node, and add the baz.faz tag to it:
node= core.formTufoByProp('foo','bar') node= core.addTufoTag(tufo,'baz.faz')
Add a timeboxed tag to a node:
200 Chapter 4. synapse package Synapse Documentation, Release 0.0.34
node= core.addTufoTag(tufo,'foo.bar@2012-2016')
Add a list of times sample times to a tag to create a timebox timeslist = (1513382400000, 1513468800000) node = core.addTufoTag(tufo,’hehe.haha’, times=timelist)
Returns: ((str,dict)): The node in tuple form (with updated props)
addTufoTags(tufo, tags) Add multiple tags to a tufo. Example: core.addTufoTags(tufo,[’foo.bar’,’baz.faz’]) addUserRule(user, rule, indx=None) Add a rule tuple for the given user (optionally at index). Args: user (str): The user name rule (tuple): The rule tuple indx (int): The index at which to insert the rule Returns: (None) NOTE: see synapse.lib.auth.Rules for rule tuple definition allowed(perm, user=None) Returns True if the user is allowed the given perms/info. Args: perm (str): The permission tufo user (str): The user name (or None for “current user”) Returns: (bool): True if the user is allowed delAddRows(iden, rows) Delete rows by iden and add rows as a single operation. Example: core.delAddRows( iden, rows ) Notes: This API is oriented toward “reparse” cases where iden will be the same for the new rows. delBlobValu(key) Remove and return a value from the blob store. Args: key (str): Key to remove. Returns: Content in the blob store for a given key. Raises: NoSuchName: If the key is not present in the store. delJoinByProp(prop, valu=None, mintime=None, maxtime=None) Delete a group of rows by selecting for property and joining on iden. Example: core.delJoinByProp(‘foo’,valu=10) delRoleRule(role, indx) Delete a rule at index for the given role. Args: role (str): The role name indx (int): The index of the rule to remove Returns: (None)
4.1. Subpackages 201 Synapse Documentation, Release 0.0.34
delRowsById(iden) Delete all the rows for a given iden. Example: core.delRowsById(iden) delRowsByIdProp(iden, prop, valu=None) Delete rows with the givin combination of iden and prop[=valu]. Example: core.delRowsByIdProp(id, ‘foo’) delRowsByProp(prop, valu=None, mintime=None, maxtime=None) Delete rows with a given prop[=valu]. Example: core.delRowsByProp(‘foo’,valu=10) delTufo(tufo) Delete a tufo and it’s associated props/lists/etc. Example: core.delTufo(foob) delTufoByProp(form, valu) Delete a tufo from the cortex by prop=valu. Example: core.delTufoByProp(‘foo’,’bar’) delTufoDark(tufo, name, valu=None) Remove dark rows from a tufo for a given name and optional value. Args: tufo ((str, dict)): Tufo to remove data dark rows from. name (str): Specific dark rows to remove. valu (str): Value to remove (optional). Returns: None: Returns None. delTufoDset(tufo, name) delTufoIval(tufo, name) Remove an iterval from a node. Args: tufo ((str,dict)): The node in tuple form name (str): The name of the interval Returns: ((str,dict)): The updated node in tuple form delTufoListValu(tufo, name, valu) delTufoProp(tufo, name) Delete a property from a node in tufo format. Args: tufo ((str,dict)): The node in tufo form name (str): The relative property name to delete Returns: ((str,dict)) The updated node in tufo form delTufoTag(tufo, tag) Delete a tag from a tufo. Args: tufo ((str,dict)): The node in tuple form. tag (str): The tag to remove Example: Remove the tag baz tag (and its subtags) from all tufos tagged baz.faz:
202 Chapter 4. synapse package Synapse Documentation, Release 0.0.34
for tufo in core.getTufosByTag('baz.faz'): core.delTufoTag(tufo,'baz')
Remove a tag from a tufo and then do something with the tufo:
tufo= core.delTufoTag(tufo,'hehe.haha') dostuff(tufo)
Returns: ((str,dict)): The node in tuple form (with updated props) delTufosByProp(prop, valu=None) Delete multiple tufos by a single property. Example: core.delTufosByProp(‘foo:bar’,valu=10) delUserRule(user, indx) Delete a rule at index for the given user. Args: user (str): The user name indx (int): The index of the rule to remove Returns: (None) NOTE: see synapse.lib.auth.Rules for rule tuple definition eatSpliceFd(fd) Consume all cortex splice events from the given file-like object. The file bytes are expected to be msgpack encoded (str,dict) splice tuples. Example: fd = open(‘saved.mpk’,’rb’) core.eatSyncFd(fd) finiSnap(snap) Cancel a tufo snapshot. formNodeByBytes(byts, stor=True, **props) Form a new file:bytes node by passing bytes and optional props. If stor=False is specified, the cortex will create the file:bytes node even if it is not configured with access to an axon to store the bytes. Args: byts (bytes): The bytes for a file:bytes node stor (bool): If True, attempt to store the bytes in an axon **props: Additional props for the file:bytes node Example: core.formNodeByBytes(byts,name=’foo.exe’) formNodeByFd(fd, stor=True, **props) Form a new file:bytes node by passing a file object and optional props. Args: fd (file): A file-like object to read file:bytes from. stor (bool): If True, attempt to store the bytes in an axon **props: Additional props for the file:bytes node formTufoByProp(prop, valu, **props) Form an (iden,info) tuple by atomically deconflicting the existence of prop=valu and creating it if not present. Args: prop (str): The primary property (or form) of the node valu (obj): The primary valu for the node **props: Additional secondary properties for the node
4.1. Subpackages 203 Synapse Documentation, Release 0.0.34
Example: Make a node for the FQDN woot.com:
tufo= core.formTufoByProp('inet:fqdn','woot.com')
Notes: When forming nodes whose primary property is derived from the GuidType, deconfliction can be skipped if the value is set to None. This allows for high-speed ingest of event type data which does note require deconfliction. This API will fire a node:form event prior to creating rows, allowing callbacks to populate any additional properties on the node. After node creation is finished, node:add events are fired on for the Cortex event bus, splices and triggers. Returns: ((str, dict)): The newly formed tufo, or the existing tufo if the node already exists. The ephemeral property ”.new” can be checked to see if the node was newly created or not.
formTufoByTufo(tufo) Form an (iden,info) tufo by extracting information from an existing one. Args: tufo ((str, dict)): An existing tufo to form a new tufo from. Examples: Create an IPv4 node from an existing node:
t0=( None,{'inet:ipv4':0x01020304,'inet:ipv4:asn': 1024}) new_tufo= core.formTufoByTufo(t0)
Notes: This API uses the formTufoByProp API to form the new tufo; after extracting the form, primary property and sub properties from the input tufo. In addition, this API does not utilize the iden value present in the first element of the tuple when making a new node. Returns: ((str, dict)): The new tufo, or an existing tufo if the tufo already existed. formTufosByProps(items) Forms tufos by prop, given a tuple of (form, valu, props) tuples. Args: items (tuple): A tuple of tuples of (form, valu, props) Returns: tuple: Tuple containing tufos, either with the node or error data Example: items = ( (‘foo:thing’, ‘hehe’, {‘a’: 1}), (‘bar:thing’, ‘haha’, {‘b’: 2}), ) results = core.formTufosByProps(items) getBlobKeys() Get a list of keys in the blob key/value store. Returns: list: List of keys in the store. getBlobValu(key, default=None) Get a value from the blob key/value (KV) store. This resides below the tufo storage layer and is Cortex implementation dependent. In purely memory backed cortexes, this KV store may not be persistent, even if the tufo-layer is persistent, through something such as the savefile mechanism. Notes: Data which is retrieved from the KV store is msgpacked, so caveats with that apply. Args: key (str): Value to retrieve default: Value returned if the key is not present in the blob store. Returns: The value from the KV store or the default valu (None).
204 Chapter 4. synapse package Synapse Documentation, Release 0.0.34
getCoreFifo(name) Return a Fifo object by name. Args: name (str): The :name of the syn:fifo node. Returns: (synapse.lib.fifo.Fifo): The Fifo object. getCorePath(*paths) Construct a path relative to the cortex metadata dir (or None). Args:* paths ([str,]): A set of path elements Returns: (str): The full path ( or None ). getCoreXact(size=1000) Get a Storage transaction context for use in a with block. This object allows bulk storage layer optimization and proper ordering of events. The context manager created through this function supports firing splice events. Args: size (int): Number of transactions to cache before starting to execute storage layer events. Examples: Get a context manager, use it to do stuff and fire splices:
with core.getCoreXact() as xact: result= dostuff() xact.spliced('some:slice:evt', **result)
Notes: This API does not work over a Telepath proxy object and it will raise an exception. Managing a transaction with from a remote caller is inherently difficult since the transaction can be opened, the caller then go away, unfortunately leaving the system in a weird state. Returns: s_xact.StoreXact: Transaction context manager. getJoinByProp(prop, valu=None, mintime=None, maxtime=None, limit=None) Similar to getRowsByProp but also lifts all other rows for iden. Example: for row in core.getRowsByProp(‘foo’,valu=20): stuff(row) Notes: • See getRowsByProp for options getJsonItems(prop, valu=None, mintime=None, maxtime=None, limit=None) Return a list of (iden,item) tuples (similar to tufos, but with hierarchical structure ) Example: x = { ‘bar’:10, } core.addJsonItem(‘foo’,x) # ... later ... for prim in core.getJsonsByProp(‘foo:bar’, 10): dostuff(tufo) getModlVers(name) Retrieve the model version for the given model name. Args: name (str): The name of the model
4.1. Subpackages 205 Synapse Documentation, Release 0.0.34
Returns: (int): The model version ( linear version number ) or -1 getPermDef(name) Return a permission definition tuple for the given perm name. Args: name (str): The permission name Returns: (tuple): A (name,info,fields) tuple for the perm. getPivotRows(prop, byprop, valu=None, mintime=None, maxtime=None, limit=None) Similar to getRowsByProp but pivots through “iden” to a different property. This can be a light way to return a single property from a tufo rather than lifting the whole. Example: # return rows for the foo:bar prop by lifting foo:baz=10 and pivoting through iden. for row in core.getPivotRows(‘foo:bar’, ‘foo:baz’, valu=10): dostuff() getRoleAuth(role) Return an auth dict for the given role. Args: role (str): The role name Returns: (dict): The role auth dict getRoleRules(role) Get a list of rule tuples for the given role. Args: role (str): The role name Returns: (list): A list of rule tuples getRoleUsers(role) Get a list of the users for the specified role. Args: role (str): The role name Returns: ([str,...]): The users for the role getRowsBy(name, prop, valu, limit=None) Retrieve rows by a specialized index within the cortex. Example: rows = core.getRowsBy(‘range’,’foo:bar’,(20,30))
Notes: • most commonly used to facilitate range searches
getRowsById(iden) Return all the rows for a given iden. Example: for row in core.getRowsById(iden): stuff() getRowsByIdProp(iden, prop, valu=None) Return rows with the given ,. Example: for row in core.getRowsByIdProp(iden,’foo:bar’): dostuff(row)
206 Chapter 4. synapse package Synapse Documentation, Release 0.0.34
getRowsByProp(prop, valu=None, mintime=None, maxtime=None, limit=None) Return a tuple of (iden,prop,valu,time) rows by prop[=valu]. Example: for row in core.getRowsByProp(‘foo’,valu=20): stuff(row) Notes: • Specify limit= to limit return size • Specify mintime= in epoch to filter rows • Specify maxtime= in epoch to filter rows getSeqNode(name) API helper/wrapper to form a syn:seq sequential id tracker getSizeBy(name, prop, valu, limit=None) Retrieve row count by a specialized index within the cortex. Example: size = core.getSizeBy(‘range’,’foo:bar’,(20,30)) print(‘there are %d rows where 20 <= foo < 30 ‘ % (size,)) getSizeByProp(prop, valu=None, mintime=None, maxtime=None) Return the count of matching rows by prop[=valu] Example: if core.getSizeByProp(‘foo’,valu=10) > 30: stuff() getSnapNext(snap) Get the next block of tufos for the given snapshot. getSplicePump(core) Return a splice pump for the remote cortex. #Example: with core.getSplicePump(prox): core.formTufoByProp(‘inet:fqdn’,’vertex.link’) getStatByProp(stat, prop, valu=None, mintime=None, maxtime=None, limit=None) Calculate and return a statistic for the specified rows. ( See getRowsByProp docs for most args ) Various statistics types are builtin. sum - total of all row values count - number of rows histo - histogram of values average - sum / count min - minimum value max - maximum value any - True if any value is true all - True if every value is true Example: minval = core.getStatByProp(‘min’,’foo:bar’) getStoreType() getTufoByIden(iden) Retrieve a tufo by id. Example: tufo = core.getTufoByIden(iden)
4.1. Subpackages 207 Synapse Documentation, Release 0.0.34
getTufoByProp(prop, valu=None) Return an (iden,info) tuple by joining rows based on a property. Example: tufo = core.getTufoByProp(‘fqdn’,’woot.com’) Notes: • This must be used only for rows added with formTufoByProp! getTufoDarkNames(tufo) Get a list of dark row names on a tufo. Args: tufo ((str, dict)): Tufo to look up. Returns: list: List of (name, time) tuples for a given tufos dark rows. getTufoDarkValus(tufo, name) Get a list of dark row values on a given tufo with a specific name. Args: tufo ((str, dict)): Tufo to look up. name (str): Specific dark rows to look up. Returns: list: List of (value, time) tuples for a given tufos dark rows. getTufoDsets(tufo) Return a list of (name,time) tuples for dset membership. getTufoList(tufo, name) Retrieve “list” values from a tufo. Example: for val in core.getTufoList(item,’foolist’): dostuff(val) getTufosBy(name, prop, valu, limit=None) Retrieve tufos by either a specialized method or the lower getRowsBy api Specialized methods will be dependant on the storage backing and the data indexed Example: tufos = core.getTufosBy(‘in’, ‘foo’, (47,3,8,22)) getTufosByDark(name, valu=None, mintime=None, maxtime=None, limit=None) Get a list of tufos with the named dark rows and optional values. Args: name (str): Dark row name to retrieve tufos by. valu (str): Value to retrieve. mintime (int): Mini- mum timevalue on tufos to return. maxtime (int): Maximum timevalue on tufos to return. limit (int): Maximum number of tufos to return. Examples: Get a list of tufos by a tag:
for tufo in getTufosByDark('tag','foo.bar.baz'): dostuff(tufo)
Returns: list: List of tufos getTufosByDset(name, mintime=None, maxtime=None, limit=None) Return a list of the tufos in the named dataset. Example: for tufo in getTufosByDset(‘woot’): dostuff(tufo)
208 Chapter 4. synapse package Synapse Documentation, Release 0.0.34
getTufosByIdens(idens) Return a list of tufos for the given iden GUIDs. Exmple: tufos = core.getTufosByIdens(idens) getTufosByProp(prop, valu=None, mintime=None, maxtime=None, limit=None) Return a list of tufos by property. Example: for tufo in core.getTufosByProp(‘foo:bar’, 10): dostuff(tufo) getTufosByPropType(name, valu=None, mintime=None, maxtime=None, limit=None) Return tufos by interrogating the data model to find fields of the given type. Example: # return all tufos with an inet:email type property with value [email protected] for tufo in core.getTufosByPropType(‘inet:email’, valu=’[email protected] ’): dostuff(tufo) getTufosByTag(tag, form=None, limit=None) Retrieve a list of tufos by tag and optionally form. Args: tag (str): A synapse tag name form (str): A synapse node form limit (int): A limit for the query Example: for node in core.getTufosByTag(‘foo.bar’): dostuff(tufo) getUserAuth(user) Return an auth dict for the given user. Args: user (str): The user name Returns: (dict): The user auth dict getUserRoles(user) Get a list of the roles for the specified user. Args: user (str): The user name Returns: ([str,...]): The roles for the user getUserRules(user) Get a list of rule tuples for the given user. Args: user (str): The user name Returns: (list): A list of rule tuples hasBlobValu(key) Check the blob store to see if a key is present. Args: key (str): Key to check Returns: bool: If the key is present, returns True, otherwise False. incTufoProp(tufo, prop, incval=1) Atomically increment/decrement the value of a given tufo property. Example: tufo = core.incTufoProp(tufo,prop)
4.1. Subpackages 209 Synapse Documentation, Release 0.0.34
initCoreModule(ctor, conf ) Load a cortex module with the given ctor and conf. Args: ctor (str): The python module class path conf (dict):Config dictionary for the module initTufosBy(name, meth) Initialize a “tufos by” handler for the Cortex. This is useful when the index or storage backing can optimize tufo creation from raw rows. Example: def getbyin(prop,valus,limit=None): ret = [] for valu in valus: res = self.getTufosByProp(prop, valu=valu, limit=limit) ret.extend(res) if limit != None: limit -= len(res) if limit <= 0: break return ret core.initTufos(‘in’,getbyin) Notes: • Used by Cortex implementers to facilitate getTufosBy(...) isOk() An API allowing Cortex to test for internal error states. isRuntForm(prop) Returns True if the given property name is a runtime node form. Args: prop (str): The property name Returns: (bool): True if the property is a runtime node form. isRuntProp(prop) Return True if the given property name is a runtime node prop. Args: prop (str): The property name Returns: (bool): True if the property is a runtime node property. isSetPropOk(prop, isadd=False) Check for enforcement and validity of a full prop name. This can be used to determine if a property name may be set on a node, given the data models currently loaded in a Cortex. Args: prop (str): Full property name to check. isadd (bool): Bool indicating that the property check is being done on a property which has not yet been set on a node. Examples: Check if a value is valid before calling a function.:
prop='foo:bar:baz' if core.isSetPropOk(prop): doSomething(...)
Returns: bool: True if the property can be set on the node; False if it cannot be set. nextSeqValu(name) Return the next sequence identifier for the given name. Example: name = core.nextSeqValu(‘foo’) # name is now foo0 or fooN from sequence
210 Chapter 4. synapse package Synapse Documentation, Release 0.0.34
popTufosByProp(prop, valu=None) Delete and return multiple tufos by a property. Example: items = core.popTufosByProp(‘foo:bar’,valu=10) putCoreFifo(name, item) Add an item to a cortex fifo. Args: name (str): The syn:fifo:name of the fifo. item (obj): The object to put in the fifo. reqCorePath(*paths) Use getCorePath and raise if dir is not set. Args: paths ([str,...]): A list of path elements to join. Returns: (str): The full path for the cortex directory. Raises: NoSuchOpt reqPermDef(name) Require (or raise) a permission definition tuple Args: name (str): The permission name Returns: (tuple): A (name,info,fields) tuple for the perm. Raises: (NoSuchPerm): The permission name was not found reqperm(perm, user=None) Require a given permission (or raise AuthDeny) Args: perm ((str,dict)): A perm tuple user (str): The user to check (or self) Raises: AuthDeny: The user is not allowed revModlVers(name, vers, func) Update and track a model version using a callback function. Args: name (str): The name of the model vers (int): The version int ( in YYYYMMDDHHMM int format ) func (function): The version update function Returns: (None) Each specified function is expected to update the cortex including data migration. setBlobValu(key, valu) Set a value from the blob key/value (KV) store. This resides below the tufo storage layer and is Cortex implementation dependent. In purely memory backed cortexes, this KV store may not be persistent, even if the tufo-layer is persistent, through something such as the savefile mechanism. Notes: Data which is stored in the KV store is msgpacked, so caveats with that apply. Args: key (str): Name of the value to store. valu: Value to store in the KV store. Returns: The input value, unchanged. setModlVers(name, vers) Set the version number for a specific model. Args: name (str): The name of the model vers (int): The new (linear) version number Returns: (None)
4.1. Subpackages 211 Synapse Documentation, Release 0.0.34
setRoleRules(role, rules) Set the rules for a given role. Rules are documented in synapse.lib.auth.Rules. Args: role (str): The role name rules (list): A list of rule tuples Returns: (None) Raises: (synapse.exc.BadRuleValu) setRowsByIdProp(iden, prop, valu) Update/insert the value of the row(s) with iden and prop to valu. Example: core.setRowsByIdProp(iden,’foo’,10) setSaveFd(fd, load=True, fini=False) Set a save fd for the cortex and optionally load. Args: fd (file): A file like object to save splice events to using msgpack load (bool): If True, load splice event from fd before starting to record fini (bool): If True, close() the fd automatically on cortex fini() Returns: (None) Example: core.setSaveFd(fd)
NOTE: This save file is allowed to be storage layer specific. If you want to store cortex splice events, use addSpliceFd().
setTufoIval(tufo, name, ival) Add an interval to a node. Args: tufo ((str,dict)): The node to add the interval to name (str): The name of the interval ival ((int,int)): The interval tuple Returns: ((str,dict)): The updated tufo setTufoProp(tufo, prop, valu) Set a single tufo property. Example: core.setTufoProp(tufo, ‘woot’, ‘hehe’) setTufoProps(tufo, **props) Set ( with de-duplication ) the given tufo props. Args: tufo ((str, dict)): The tufo to set properties on. **props: Properties to set on the tufo. Examples:
tufo= core.setTufoProps(tufo, woot='hehe', blah=10)
Returns: ((str, dict)): The source tufo, with any updated properties. setUserRules(user, rules) Set the rules for a given user. Args: user (str): The user name rules (list): The list of rule tuples Returns: (None)
212 Chapter 4. synapse package Synapse Documentation, Release 0.0.34
snapTufosByDark(name, valu=None, mintime=None, maxtime=None, limit=None) Create a snapshot of tufos by dark name/values. Args: name (str): Dark row name to snapshot tufos by. valu (str): Optional value to retrieve tufos by. mintime (int): Minimum timevalue on tufos to return. maxtime (int): Maximum timevalue on tufos to return. limit (int): Maximum number of tufos to return. Returns: dict: Snapshot generator for getting tufos. snapTufosByDset(name, mintime=None, maxtime=None, limit=None) snapTufosByProp(prop, valu=None, mintime=None, maxtime=None, limit=None) splice(mesg) Feed the cortex a splice event to make changes to the hypergraph. Args: mesg ((str,dict)): The (name,info) for the splice event. Returns: None Example: core.splice(mesg) splices(msgs) Process a list of splices in bulk (see splice()). Args: msgs (list): The list of splices. subCoreFifo(name, xmit=None) Provde an xmit function for a given core fifo. Args: name (str): The name of the fifo. xmit (func): A fifo xmit func. NOTE: if xmit is None, it is assumed that the caller is a remote telepath client and the socket.tx func- tion is used. synapse.cores.common.chunked(n, iterable) synapse.cores.common.reqiden(tufo) Raise an exception if the given tufo is ephemeral. synapse.cores.lmdb module class synapse.cores.lmdb.LmdbStorage(link, **conf ) Bases: synapse.cores.storage.Storage getRowsById(iden) getRowsByIdProp(iden, prop, valu=None) getRowsByProp(prop, valu=None, limit=None, mintime=None, maxtime=None, do_count_only=False) getSizeByProp(prop, valu=None, limit=None, mintime=None, maxtime=None) getStoreType() getStoreXact(size=None, core=None) rowsByGe(prop, valu, limit=None) rowsByLe(prop, valu, limit=None) rowsByRange(prop, valu, limit=None)
4.1. Subpackages 213 Synapse Documentation, Release 0.0.34
sizeByGe(prop, valu, limit=None) sizeByLe(prop, valu, limit=None) sizeByLt(prop, valu, limit=None) sizeByRange(prop, valu, limit=None) class synapse.cores.lmdb.LmdbXact(store, size=None, core=None) Bases: synapse.cores.xact.StoreXact synapse.cores.lmdb.initLmdbCortex(link, conf=None, storconf=None) Initialize a LMDB based Cortex from a link tufo. Args: link ((str, dict)): Link tufo. conf (dict): Configable opts for the Cortex object. storconf (dict): Configable opts for the storage object. Returns: s_cores_common.Cortex: Cortex created from the link tufo. synapse.cores.postgres module class synapse.cores.postgres.PsqlStorage(link, **conf ) Bases: synapse.cores.sqlite.SqliteStorage dblim = None getRowsByIdens(idens) getStoreType() synapse.cores.postgres.initPsqlCortex(link, conf=None, storconf=None) Initialize a Sqlite based Cortex from a link tufo. Args: link ((str, dict)): Link tufo. conf (dict): Configable opts for the Cortex object. storconf (dict): Configable opts for the storage object. Returns: s_cores_common.Cortex: Cortex created from the link tufo. synapse.cores.postgres.md5(x) synapse.cores.ram module class synapse.cores.ram.RamStorage(link, **conf ) Bases: synapse.cores.storage.Storage getRowsById(iden) getRowsByIdProp(iden, prop, valu=None) getRowsByIdens(idens) getRowsByProp(prop, valu=None, mintime=None, maxtime=None, limit=None) getSizeByProp(prop, valu=None, mintime=None, maxtime=None) getStoreType() getStoreXact(size=None, core=None) rowsByGe(prop, valu, limit=None) rowsByLe(prop, valu, limit=None) rowsByRange(prop, valu, limit=None)
214 Chapter 4. synapse package Synapse Documentation, Release 0.0.34
sizeByGe(prop, valu, limit=None) sizeByLe(prop, valu, limit=None) sizeByRange(prop, valu, limit=None) class synapse.cores.ram.RamXact(store, size=None, core=None) Bases: synapse.cores.xact.StoreXact synapse.cores.ram.initRamCortex(link, conf=None, storconf=None) Initialize a RAM based Cortex from a link tufo. The path element of the link tufo, if present, is used to cache the Cortex instance. Subsequent calls with the same path will return the existing Cortex instance. Args: link ((str, dict)): Link tufo. conf (dict): Configable opts for the Cortex object. storconf (dict): Configable opts for the storage object. Returns: s_cores_common.Cortex: Cortex created from the link tufo. synapse.cores.sqlite module class synapse.cores.sqlite.DbPool(size, ctor) Bases: object The DbPool allows generic db connection pooling using a factory/ctor method and a python queue. Example: def connectdb(): # do stuff return db pool = DbPool(3, connectdb) get() put(db) Add/Return a db connection to the pool. class synapse.cores.sqlite.SqlXact(store, size=None, core=None) Bases: synapse.cores.xact.StoreXact class synapse.cores.sqlite.SqliteStorage(link, **conf ) Bases: synapse.cores.storage.Storage dblim = -1 delete(q, **args) getJoinByProp(prop, valu=None, mintime=None, maxtime=None, limit=None) getRowsById(iden) getRowsByIdProp(iden, prop, valu=None) getRowsByProp(prop, valu=None, limit=None, mintime=None, maxtime=None) getSizeByProp(prop, valu=None, limit=None, mintime=None, maxtime=None) getStoreType() getStoreXact(size=None, core=None) rowsByGe(prop, valu, limit=None) rowsByLe(prop, valu, limit=None) rowsByRange(prop, valu, limit=None)
4.1. Subpackages 215 Synapse Documentation, Release 0.0.34
select(q, **args) sizeByGe(prop, valu, limit=None) sizeByLe(prop, valu, limit=None) sizeByRange(prop, valu, limit=None) update(q, **args) synapse.cores.sqlite.initSqliteCortex(link, conf=None, storconf=None) Initialize a Sqlite based Cortex from a link tufo. Args: link ((str, dict)): Link tufo. conf (dict): Configable opts for the Cortex object. storconf (dict): Configable opts for the storage object. Returns: s_cores_common.Cortex: Cortex created from the link tufo. synapse.cores.storage module synapse - storage.py Created on 7/19/17. Base storage layer implementation for Synapse Cortex class. See Storage class for more information. class synapse.cores.storage.Storage(link, **conf ) Bases: synapse.lib.config.Config Base class for Cortex storage layer backends. This implements functionality which is needed for a storage layer to operate, as well as providing stubs for the storage layer implementations to override. See the Synapse Documentation for more details. Args: link ((str, dict)): Link tufo containing information for creating the Storage object. This may include path information, authentication information, etc. **conf (dict): Additional configible options for the storage layer. addRows(rows) Add (iden, prop, valu, time) rows to the Storage object. Args: rows (list): List of rows containing (i, p, v, t) tuples. Examples: Adding a pair of rows to the storage object:
import time tick= now()
rows=[ (id1,'baz',30,tick), (id1,'foo','bar',tick), ]
store.addRows(rows)
Notes: The general convention for the iden value is a 16 byte hex string, such as “e190d108bdd30a035a15764313f4c397”. These can be made with the synapse.common.guid() function. While the storage layer is free to STORE these idens however it sees fit, some tools may expect that, at the public row level APIs, idens may conform to that shape. If other types of idens are put into the system, that could cause unintentional issues.
216 Chapter 4. synapse package Synapse Documentation, Release 0.0.34
This does fire a “core:save:add:rows” event on the savebus to save the raw rows which are being send to the storage layer. Returns: None addSaveLink(func) Add an event callback to receive save events for this Storage object. Args: func: Function to receive events from the Storage savebus. Examples: Register a function to receive events:
def savemesg(mesg): dostuff()
core.addSaveLink(savemesg)
Returns: None delBlobValu(key) Remove and return a value from the blob store. Args: key (str): Key to remove. Returns: Content in the blob store for a given key. Raises: NoSuchName: If the key is not present in the store. delRowsById(iden) Delete all the rows for a given iden. Args: iden (str): Iden to delete rows for. Examples: Delete the rows for a given iden:
store.delRowsById(iden)
Notes: This does fire a “core:save:del:rows:by:iden” event on the savebus to record which rows were deleted. Returns: None delRowsByIdProp(iden, prop, valu=None) Delete rows with the given combination of iden and prop[=valu]. Args: iden (str): Iden to delete rows for. prop (str): Prop to delete rows for. valu: Optional value to check. If present, only delete iden/prop rows with this value. Examples: Delete all ‘foo’ rows for a given iden:
store.delRowsByIdProp(iden,'foo')
Notes: This does fire a “core:save:del:rows:by:idprop” event on the savebus to record which rows were deleted. Returns: None delRowsByProp(prop, valu=None, mintime=None, maxtime=None) Delete rows with a given property (and optional valu) combination. Args: prop (str): Property to delete. valu: Optional value to constrain the property deletion by. mintime (int): Optional, minimum time in which to constrain the
4.1. Subpackages 217 Synapse Documentation, Release 0.0.34
deletion by.
maxtime (int): Optional, maximum time in which to constrain the deletion by.
Examples: Delete all ‘foo’ rows with the valu=10:
store.delRowsByProp('foo',valu=10)
Notes: This does fire a “core:save:del:rows:by:prop” event on the savebus to record which rows were deleted. Returns: None genJoinByProp(prop, valu=None, mintime=None, maxtime=None, limit=None) genStoreRows(**kwargs) A generator which yields raw rows from the storage layer. Args: **kwargs: Arguments which are passed to the storage layer implementation of _gen- StoreRows(). Notes: Since this is intended for use as a backup mechanism for a Storage object, it is not to be considered a performant API. Yields: list: List of rows. The number of rows and contents will vary by implementation. getBlobKeys() Get a list of keys in the blob key/value store. Returns: list: List of keys in the store. getBlobValu(key, default=None) Get a value from the blob key/value (KV) store. This resides below the tufo storage layer and is Cortex implementation dependent. In purely memory backed cortexes, this KV store may not be persistent, even if the tufo-layer is persistent, through something such as the savefile mechanism. Notes: Data which is retrieved from the KV store is msgpacked, so caveats with that apply. Args: key (str): Value to retrieve default: Value returned if the key is not present in the blob store. Returns: The value from the KV store or the default valu (None). getCoreXact(size=1000, core=None) Get a Storage transaction context for use in a with block. This object allows bulk storage layer optimization and proper ordering of events. Args: size (int): Number of transactions to cache before starting to execute storage layer events. core: Cortex to attach to the StoreXact. Required for splice event support. Examples: Get a StoreXact object and use it:
with store.getCoreXact() as xact: store.dostuff()
Returns: s_xact.StoreXact: A StoreXact object for the current thread. getJoinByProp(prop, valu=None, mintime=None, maxtime=None, limit=None)
218 Chapter 4. synapse package Synapse Documentation, Release 0.0.34
getJoinsBy(name, prop, valu, limit=None) Retrieve joined rows by either a sepecified method or by falling back to the rowsBy handlers. Specialized methods will be dependent on the storage backind and the data indexed. Args: name (str): Name of the method to look up. prop (str): Prop to filter by. valu: Value (or values) to pass to the helper method. limit (int): Limit on the join. Limit meaning may vary by implementation or named helper. Returns: getRowsById(iden) Return all the rows for a given iden. Args: iden (str): Iden to get rows from the storage object for. Examples: Getting rows by iden and doing stuff:
for row in store.getRowsById(iden): stuff()
Getting rows by iden and making a tufo out of them:
rows= store.getRowsById(iden) tufo= (iden, {p: v for (i, p, v, t) in rows})
Returns: list: List of rows for a given iden. getRowsByIdProp(iden, prop, valu=None) Return rows with the given ,. Args: iden (str): Iden to get rows from the storage object for. prop (str): Prop to constrain the lift by. valu: Optional, value to constrain the lift by. Examples: Getting rows by iden, prop and doing stuff:
for row in core.getRowsByIdProp(iden,'foo:bar'): dostuff(row)
Returns: list: List of rows for a given iden, prop, value comtination. getRowsByIdens(idens) Return all the rows for a given list of idens. Args: idens (list): Idens to get rows from the storage object for. Examples: Getting rows by idens and doing stuff:
for row in store.getRowsByIdens(idens): stuff(row)
Getting rows by idens and making a tufos out of them:
rows= store.getRowsById(iden) tufos= s_common.rowstotufos(rows)
Returns: list: List of rows for the given idens. getRowsByProp(prop, valu=None, mintime=None, maxtime=None, limit=None) Get rows from the Storage layer based on their property value and other, optional, constraints.
4.1. Subpackages 219 Synapse Documentation, Release 0.0.34
Args: prop (str): Property to retrieve rows based on. valu: Optional, str or integer value to constrain the retrieval by. mintime (int): Optional, minimum (inclusive) time to constrain the retrieval by. max- time (int): Optiona, maximum (exclusive) time to constrain the retrieval by. limit (int): Maximum number of rows to return. Returns: list: List of (i, p, v, t) rows. getSizeByProp(prop, valu=None, mintime=None, maxtime=None) getStoreType() Get the Store type. This may be used by the Cortex to determine what its backing store is. Returns: str: String indicating what the backing storage layer is. getStoreXact(size=None, core=None) Get a StoreXact object. This is normally called by the getCoreXact function. Args: size (int): Number of events to cache in the transaction before executing them. core: Cortex to attach to the transaction. Required for splice event support. Returns: s_xact.StoreXact: A storage layer specific StoreXact object. hasBlobValu(key) Check the blob store to see if a key is present. Args: key (str): Key to check Returns: bool: If the key is present, returns True, otherwise False. initJoinsBy(name, meth) Initialize a “joins by” handler for the Storage layer. These helpers are used by the Cortex to do special types of lifts. This allows different Storage layers to implement certain lifts in a optimized fashion. Args: name (str): Named handler to register. meth (func): Function to register. Examples: Registering a ‘woot’ handler:
def getbywoot(prop,valu,limit=None): return stuff() # list of rows
core.initJoinsBy('woot',getbywoot)
Returns: None initRowsBy(name, meth) Initialize a “rows by” handler for the Storage layer. These helpers are used by the Cortex to do special types of lifts. This allows different Storage layers to implement certain lifts in a optimized fashion. Args: name (str): Named handler to register. meth (func): Function to register. Examples: Registering a ‘woot’ handler:
220 Chapter 4. synapse package Synapse Documentation, Release 0.0.34
def getbywoot(prop,valu,limit=None): return stuff() # list of rows
core.initRowsBy('woot',getbywoot)
Returns: None initSizeBy(name, meth) Initialize a “size by” handler for the Storage layer. These helpers are used by the Cortex to do size by lifts. This allows different Storage layers to implement certain lifts in a optimized fashion. Args: name (str): Named handler to register. meth (func): Function to register. Examples: Registering a ‘woot’ handler:
def sizebywoot(prop,valu,limit=None): return stuff() # size of rows
core.initSizeBy('woot',meth)
Returns: None reqJoinByMeth(name) Get a handler for a JoinBy lift. Args: name (str): Name of the registered handler to retrieve. Returns: Function used to lift joined rows. Raises: NoSuchGetBy: If the named handler does not exist. reqRowsByMeth(name) Get a handler for a RowsBy lift. Args: name (str): Name of the registered handler to retrieve. Returns: Function used to lift by rows. Raises: NoSuchGetBy: If the named handler does not exist. reqSizeByMeth(name) Get a handler for a SizeBy lift. Args: name (str): Name of the registered handler to retrieve. Returns: Function used to lift by size. Raises: NoSuchGetBy: If the named handler does not exist. rowsByGe(prop, valu, limit=None) rowsByGt(prop, valu, limit=None) rowsByLe(prop, valu, limit=None) rowsByLt(prop, valu, limit=None) rowsByRange(prop, valu, limit=None) setBlobValu(key, valu) Set a value from the blob key/value (KV) store.
4.1. Subpackages 221 Synapse Documentation, Release 0.0.34
This resides below the tufo storage layer and is Cortex implementation dependent. In purely memory backed cortexes, this KV store may not be persistent, even if the tufo-layer is persistent, through something such as the savefile mechanism. Notes: Data which is stored in the KV store is msgpacked, so caveats with that apply. Args: key (str): Name of the value to store. valu: Value to store in the KV store. Returns: The input value, unchanged. setModlVers(name, vers) Set the version number for a specific model. Args: name (str): The name of the model vers (int): The new (linear) version number Returns: (None) setRowsByIdProp(iden, prop, valu) Update or insert the value of the row(s) with iden and prop to valu. Args: iden (str): Iden to update. prop (str): Property to update. valu: Value to set. Examples: Set the foo=10 value on a given iden: Notes: This does fire a “core:save:set:rows:by:idprop” event on the savebus to save the changes which are being sent to the storage layer. Returns: None setSaveFd(fd, load=True, fini=False) Set a save fd for the cortex and optionally load. Args: fd (file): A file like object to save splice events to using msgpack load (bool): If True, load splice event from fd before starting to record fini (bool): If True, close() the fd automatically on cortex fini() Returns: (None) Example: store.setSaveFd(fd)
NOTE: This save file is allowed to be storage layer specific. If you want to store cortex splice events, use addSpliceFd() from the Cortex class.
sizeByGe(prop, valu, limit=None) sizeByLe(prop, valu, limit=None) sizeByRange(prop, valu, limit=None) updateProperty(oldprop, newprop) Do a wholesale replacement of one property with another property. Args: oldprop (str): The orginal property which is removed. newprop (str): The property that is updated in place. Examples: Rename “inet:tcp4:port” to “inet:tcp4:foobar”:
nrows= store.updateProperty('inet:tcp4:port','inet:tcp4:foobar')
Notes: This API does fire syn:core:store:up:prop:pre and syn:core:store:up:prop:post events with the old and new property names in it, before and after the property update is done. This API is primarily designed for assisting with Cortex data migrations.
222 Chapter 4. synapse package Synapse Documentation, Release 0.0.34
Returns: int: Number of rows updated in place. updatePropertyValu(prop, oldval, newval) Do a wholesale update of one property=valu combination with a new valu. Args: prop (str): Property to select by for updating. oldval: Old valu to select rows by. newval: Valu to set the the prop=oldval rows to be. Examples: Rename “tufo:form”=”inet:tcp4” to instead be “tufo:form”=”inet:tcp4000”:
nrows= store.updatePropertyValu('tufo:form','inet:tcp4','inet:tcp4000
˓→')
Notes: This API does fire syn:core:store:up:propval:pre and syn:core:store:up:propval:post events with the property, old value and new values in it; before and after update is done. This API is primarily designed for assisting with Cortex data migrations. The oldval and newval must be of the same type. Returns: int: Number of rows updated in place. synapse.cores.xact module synapse - xact.py.py Created on 8/1/17. StoreXact implementation. This is designed to be subclassed by Storage layer implementors. class synapse.cores.xact.StoreXact(store, size=None, core=None) Bases: object A context manager for a storage “transaction”. acquire() begin() cedetime() commit() Commit the results thus far ( without closing / releasing ) fire(name, **props) Pend an event to fire when the transaction next commits. fireall() release() spliced(act, **info) Fire a splice event from the transaction. Args: act (str): Splice action. **info: Event values. Returns: None sync() Loop commiting and syncing events until there are no more events that need to fire. trigger(node, name, **info) Fire a trigger from the transaction Args: node ((str,dict)): The node for the trigger name (str): The trigger permission string info (dict): The trigger permission metadata
4.1. Subpackages 223 Synapse Documentation, Release 0.0.34
Module contents
4.1.3 synapse.data package
Module contents synapse.data.get(name, defval=None) Return an object from the embedded synapse data folder. Example: for tld in syanpse.data.get(‘iana.tlds’): dostuff(tld) NOTE: Files are named synapse/data/.mpk
4.1.4 synapse.docker package
Module contents
4.1.5 synapse.lib package
Subpackages synapse.lib.platforms package
Submodules synapse.lib.platforms.common module synapse.lib.platforms.common.daemonize() For unix platforms, form a new process group using fork(). synapse.lib.platforms.common.getLibC() Return a ctypes reference to libc synapse.lib.platforms.common.getVolInfo(*paths) Retrieve volume usage info for the given path. synapse.lib.platforms.common.inet_ntop(afam, byts) synapse.lib.platforms.common.inet_pton(afam, text) synapse.lib.platforms.common.initHostInfo() synapse.lib.platforms.common.setProcName(name) Set the process title/name for process listing. synapse.lib.platforms.darwin module synapse.lib.platforms.darwin.initHostInfo() synapse.lib.platforms.freebsd module synapse.lib.platforms.freebsd.initHostInfo()
224 Chapter 4. synapse package Synapse Documentation, Release 0.0.34
synapse.lib.platforms.linux module
synapse.lib.platforms.linux.initHostInfo()
synapse.lib.platforms.windows module
synapse.lib.platforms.windows.daemonize() synapse.lib.platforms.windows.getLibC() Override to account for python on windows not being able to find libc sometimes... synapse.lib.platforms.windows.initHostInfo() class synapse.lib.platforms.windows.sockaddr Bases: _ctypes.Structure ipv4 Structure/Union member ipv6 Structure/Union member sa_family Structure/Union member
Module contents
Home for platform specific code such as thishost info. all platform modules must be importable from any platform. ( guard any platform specific code with appropriate conditionals )
Submodules synapse.lib.atomfile module class synapse.lib.atomfile.AtomFile(fd, **opts) Bases: synapse.eventbus.EventBus Implement generic atomic “seek and read” behavior which some platforms override. flush() Request that all changes are flushed to disk. Example: atom.flush() readoff(off, size) Atomically read size bytes at the given offset. Example: byts = atom.readoff(off,size)
4.1. Subpackages 225 Synapse Documentation, Release 0.0.34
resize(size) Resize the underlying file (currently only supports growth). Example: atom.resize(newsize) writeoff(off, byts) Atomically write bytes at the given offset. class synapse.lib.atomfile.FastAtom(fd, **opts) Bases: synapse.lib.atomfile.AtomFile An AtomFile which uses pread/pwrite to avoid locking. class synapse.lib.atomfile.MemAtom(fd, **opts) Bases: synapse.lib.atomfile.AtomFile An AtomFile which uses a contiguous memory map for high-speed file IO. synapse.lib.atomfile.getAtomFile(fd, memok=True) Factory to construct the most optimal AtomFile for this platform. Example: atom = getAtomFile(fd) # provides thread safe routines for most optimal # offset based file I/O for this platform. # read 20 bytes at offset 300 byts = atom.readoff(300,20) # write byts at offset 400 atom.writeoff(400,byts) synapse.lib.atomfile.openAtomFile(path, memok=True) Open the given file path as an AtomFile. Args: path (str): A file path memok (bool): If True, allow use of mmap files. synapse.lib.atomic module class synapse.lib.atomic.CmpSet(valu) Bases: object The CmpSet class facilitates atomic compare and set. set(valu) Atomically set the valu and return change status. Args: valu (obj): The new value Returns: (bool): True if the value changed. synapse.lib.auth module class synapse.lib.auth.Rules(rules) Bases: object Rules provides an abstraction for metadata based filtration of events and tufos. Each “rule” is a tuple of: (allow, perm): (bool, (str, dict)) allow(perm) Returns True if the given perm/info is allowed by the rules.
226 Chapter 4. synapse package Synapse Documentation, Release 0.0.34
Args: perm ((str,dict)): The requested permission tuple Returns: (bool): True if the rules allow the perm/info synapse.lib.auth.runas(user) Construct and return a with-block object which runs as the given synapse user name. Example: import synapse.lib.auth as s_auth s_auth.runas(‘visi@localhost‘): # calls from here down may use check user/perms dostuff() synapse.lib.auth.whoami() Return the name of the current synapse user for this thread. Example: name = s_auth.whoami() synapse.lib.cache module class synapse.lib.cache.Cache(maxtime=None, onmiss=None) Bases: synapse.eventbus.EventBus A callback driven cache with options for timeout / maxsize. Example: cache = Cache(maxtime=60) cache.put(iden,thing) # ... some time later valu = cache.get(iden) Notes: The maxtime option is used to specify cache time based flushing. Cache accesses continue to bump a timestamp forward to facilite flushing the cache entries which were least recently requested. clear() Flush and clear the entire cache. flush(key) Flush a key:val within the cache. Example: cache.flush(‘woot’) Notes: • Mostly used to trigger “cache:flush” events get(key) Return a val from the cache. Example: val = cache.get(key) has(key) Checks if the given key is in the cache (mostly used for testing) Args: key (str): The key being checked in the cache Returns: (bool): True if the key is in the cache
4.1. Subpackages 227 Synapse Documentation, Release 0.0.34
keys() Return a list of the keys in the cache. Example: for key in cache.keys(): stuff(key) pop(key) Remove and return a val from the cache. Example: cache.pop(‘woot’) put(key, val) Put a key:val into the cache. Example: cache.put(‘woot’,10) setMaxTime(valu) setOnMiss(onmiss) Set a callback function to use on cache miss. Example: def onmiss(key): return stuff.get(key) cache.setOnMiss( onmiss ) values() class synapse.lib.cache.FixedCache(maxsize=10000, onmiss=None) Bases: synapse.eventbus.EventBus Implements a fixed-size cache. For implementation speed, the cache will flush oldest values first regardless of last cache hit. clear() Remove all entries from the FixedCache. get(key) Return the value from the cache. If onmiss is set, lookup entry on cache miss and add to cache. Example: valu = cache.get(‘foo’) if valu != None: dostuff(valu) class synapse.lib.cache.KeyCache(lookmeth) Bases: collections.defaultdict A fast key/val lookup cache. Example: cache = KeyCache( getFooThing ) valu = cache[x] get(key) pop(key) put(key, val)
228 Chapter 4. synapse package Synapse Documentation, Release 0.0.34 class synapse.lib.cache.MatchCache Bases: synapse.lib.cache.Cache The MatchCache allows caching fnmatch results for perf. match(valu, must) Check if a given value matches an fnmatch pattern Args: valu (str): The string being checked must (str): The fnmatch pattern to check against Returns: (bool): True if valu matches must class synapse.lib.cache.OnDem Bases: collections.defaultdict A dictionary based caching on-demand resolver. Example: class Woot(OnDem): @keymeth(‘foo’) def _getFooThing(self): # only called once return FooThing() woot = Woot() foo = woot.get(‘foo’) add(name, func, *args, **kwargs) Add a key lookup function callback to the OnDem dict. Example: def getfoo(): return FooThing() od = OnDem() od.add(‘foo’, getfoo) foo = od.get(‘foo’) get(name) Return the value for the given OnDem key. Example: woot = od.get(‘woot’) class synapse.lib.cache.RefDict Bases: synapse.eventbus.EventBus Allow reference counted ( and instance folded ) cache. bumpref(key, val=True) Increment and decrement the given ref to potentially trigger events. This API will be most commonly used by leaf references who only seek to trigger potential events. Args: key (str): The key to reference val (obj): The value for the key Returns: (None) clear() count(key) Returns the number of references to the specified key. Args: key (str): The key to check for references Returns: (int): The number of references
4.1. Subpackages 229 Synapse Documentation, Release 0.0.34
get(key) holdref(key, val=True) Provides with-block syntax for holding a reference increment. Args: key (str): The key to reference val (obj): The value for the key Returns: contextmanager Example: refd = RefDict() with refd.holdref(‘foo’,’bar’): dostuff() pop(key) pops(keys) put(key, val=True) puts(items) class synapse.lib.cache.TufoCache(core, maxtime=None) Bases: synapse.lib.cache.Cache class synapse.lib.cache.TufoPropCache(core, prop, maxtime=None) Bases: synapse.lib.cache.TufoCache getTufoByValu(valu) synapse.lib.cache.keymeth(name) Decorator for use with OnDem to add key callback methods. synapse.lib.certdir module class synapse.lib.certdir.CertDir(path=None) Bases: object genCaCert(name, signas=None, outp=None) genHostCert(name, signas=None, outp=None, pkey=None, sans=None) genHostCsr(name, outp=None) genUserCert(name, signas=None, outp=None, pkey=None) genUserCsr(name, outp=None) getCaCert(name) getCaCertPath(name) getCaKey(name) getCaKeyPath(name) getClientCert(name) Loads the PKCS12 object for a given client certificate. Example: mypkcs12 = cdir.getClientCert(‘mycert’) Args: name (str): The name of the client certificate. Returns: OpenSSL.crypto.PKCS12: The certificate if exists.
230 Chapter 4. synapse package Synapse Documentation, Release 0.0.34
getClientCertPath(name) Gets the path to a client certificate. Example: mypath = cdir.getClientCertPath(‘mycert’) Args: name (str): The name of the client certificate. Returns: str: The path if exists. getHostCaPath(name) getHostCert(name) getHostCertPath(name) getHostKey(name) getHostKeyPath(name) getPathJoin(*paths) getUserCaPath(name) getUserCert(name) getUserCertPath(name) getUserForHost(user, host) getUserKey(name) getUserKeyPath(name) isCaCert(name) isClientCert(name) Checks if a client certificate exists. Example: exists = cdir.isClientCert(‘mycert’) Args: name (str): The name of the client certificate. Returns: bool: True if the certificate is present, False otherwise. isHostCert(name) isUserCert(name) selfSignCert(cert, pkey) signCertAs(cert, signas) signHostCsr(xcsr, signas, outp=None, sans=None) signUserCsr(xcsr, signas, outp=None) synapse.lib.certdir.iterFqdnUp(fqdn) synapse.lib.cli module class synapse.lib.cli.Cli(item, outp=None, **locs) Bases: synapse.eventbus.EventBus A modular / event-driven CLI base object. addCmdClass(ctor, **opts) Add a Cmd subclass to this cli.
4.1. Subpackages 231 Synapse Documentation, Release 0.0.34
get(name, defval=None) getCmdByName(name) Return a Cmd instance by name. getCmdNames() Return a list of all the known command names for the CLI. printf(mesg, addnl=True) runCmdLine(line) Run a single command line. Example: cli.runCmdLine(‘woot –help’) runCmdLoop() Run commands from stdin until close or fini(). set(name, valu) exception synapse.lib.cli.CliFini Bases: Exception class synapse.lib.cli.Cmd(cli, **opts) Bases: object Base class for modular commands in the synapse CLI. FIXME: document the _cmd_syntax definitions. getCmdBrief() Return the single-line description for this command. getCmdDoc() Return the help/doc output for this command. getCmdItem() Get a reference to the object we are commanding. getCmdName() getCmdOpts(text) Use the _cmd_syntax def to split/parse/normalize the cmd line. NOTE: This is implemented indepedent of argparse (et.al) due to the need for syntax aware argu- ment splitting. ( also, allows different split per command type ) printf(mesg, addnl=True) runCmdLine(line) Run a line of command input for this command. Example: foo.runCmdLine(‘foo –opt baz woot.com’) class synapse.lib.cli.CmdHelp(cli, **opts) Bases: synapse.lib.cli.Cmd List commands and display help output. Example: help foocmd
232 Chapter 4. synapse package Synapse Documentation, Release 0.0.34
runCmdOpts(opts) class synapse.lib.cli.CmdQuit(cli, **opts) Bases: synapse.lib.cli.Cmd Quit the current command line interpreter. Example: quit runCmdOpts(opts) synapse.lib.cli.get_input(text) Get input from a user via stdin. Notes: This is just a wrapper for input() so mocking does not have to replace builtin functions for testing runCmdLoop. Args: text (str): Text displayed prior to the input prompt. Returns: str: String of text from the user. synapse.lib.cmdr module synapse.lib.cmdr.getItemCmdr(item, outp=None, **opts) Construct and return a cmdr for the given item. Example: cmdr = getItemCmdr(foo) synapse.lib.cmdr.runItemCmdr(item, outp=None, **opts) Create a cmdr for the given item and run the cmd loop. Example: runItemCmdr(foo) synapse.lib.config module
Tools for providing a central API for configurable objects within Synapse. class synapse.lib.config.Config(opts=None, defs=()) Bases: synapse.lib.config.Configable, synapse.eventbus.EventBus A EventBus classs which has the Configable mixin already added. class synapse.lib.config.Configable(opts=None, defs=()) Bases: object Config object base mixin to allow addition to objects which already inherit from the EventBus. addConfDef(name, **info) Add a configable option to the object. Args: name (str): Name of configuration option to set. **info: A list of options for the Configable option. The following options have specific meanings: • type: A Synapse type which is used to normalize the value. • doc: A docstring (used for doing automatic document generation within Synapse)
4.1. Subpackages 233 Synapse Documentation, Release 0.0.34
• defval: A default value for the option. This must be copyable using copy.deepcopy(). This is done to avoid mutable default values from being changed. • asloc: A string, if present, will set the a local object attribute to the name of the string which is equal to the valu of the configuration option. Examples: Add a definition for a option to a object with a local attribute:
item.addConfDef('cache:expiretime', type='int', doc='Time to expire data', defval=60, asloc='cache_expiretime')
Add a untype option definition to a object with a mutable defval. This sets the value to a copy of the defval, leaving the default object untouched:
item.addConfDef('foobars', defval=[], doc='A list of foobars we care
˓→about.')
Notes: This does not have to be explicitly called if the @confdef decorator is used to define the options for a class. Returns: None addConfDefs(defs) Add multiple configuration definitions for this object via addConfDef(). Args: defs ((str, dict),): A tuple containing multiple configuration definitions. Examples: Set a pair of options definitions related to caching on a object:
defs=( ('caching',{'type':'bool','doc':'Enable caching on this object'}
˓→), ('cache:expiretime',{'type':'int','doc':'Time to expire data',
˓→'defval': 60}) ) item.addConfDefs(defs)
Notes: This does not have to be explicitly called if the @confdef decorator is used to define the options for a class. Returns: None getConfDef(name) Get the defitition for a given Args: name (str): Name to get the definition of. Returns: dict: Dictionary containing the configuration definition for the given named option. Raises: NoSuchOpt: If the name is not a valid option. getConfDefs() Get the configuration definitions for this object. Returns: dict: Dictionary of option, values for the object. getConfNorm(name, valu) Return a normalized version of valu based on type knowledge for name. Args: name (str): The name of the config option valu (obj): The valu of the config option Returns: (obj): The normalized form for valu
234 Chapter 4. synapse package Synapse Documentation, Release 0.0.34
getConfOpt(name) Get the configured value for a given option. Args: name (str): Name of the option to retrieve. Returns: Value stored in the configuration dict, or None if the name is not present. getConfOpts() Get the current configuration for this object. Returns: dict: Dictionary of option and configured value for the object. onConfOptSet(name, func) Utility function for dynamically handling updates to config options. Args: name (str): Option name to respond too. func: Function to execute. This should take one parame- ter, the changed value. Examples: React to a (arbitrary) cache configuration option change:
def setCacheEnabled(self, en): dostuff() item.onConfOptSet('caching', setCacheEnabled)
Notes: The callback is fired using the syn:conf:set: event. Many places through Synapse (or third party applications which use Synapse) may set multiple opts at once using the setConfOpts() API, typically during a objects __init__ function. This sets values in a random order, due to dictionary iteration; and relying on other options being set during these callbacks can cause race conditions, leading to differences between expected and observed behaviors. In order to ensure that callbacks are free of such race conditions, do not write callback functions which rely on other Configable options being set to a particular value. Returns: None reqConfOk(opts) Check that that config values pass validation or raise. Args: opts (dict): Dictionary containing name, valu pairs to validate. Raises: NoSuchType: If the specified type of the option is non-existent. BadTypeValu: If a bad valu is encountered during type normalization. reqConfOpts() Check for the presense of required config options and raise if missing. Raises: ReqConfOpt setConfOpt(name, valu) Set a single config option for the object. This will perform type normalization if the configration option has a ‘type’ value set. Args: name (str): Configuration name valu: Value to set to the configuration option. Notes: This fires the following events, so that the EventBus can react to configuration changes. Each event includes the name, new valu and oldvalu. • syn:conf:set • syn:conf:set: Returns: None setConfOpts(opts) Use settings from the given dict to update the object config.
4.1. Subpackages 235 Synapse Documentation, Release 0.0.34
Args: opts (dict): Examples: Set a pair of keys on a object using a dictionary:
opts={ 'foo:enabled': True, 'foo:size': 1000 } item.setConfOpts(opts)
Returns: None synapse.lib.config.confdef(name) A decorator used to flag configable definition functions. The options returned by the decorated functions are automatically loaded into the class upon initialization of the Configable mixin. This decorator must be used AFTER a @staticmethod decorator for autodoc generation to work properly. Args: name (str): Identifier for a given function. This is used to prevent reloading configable options mul- tiple times in the case of multi-class inheritance or mixin use. Examples: Example class using the confdef decorator to define and (automatically load) a set of options into a Configable class:
class Foo(s_config.Config):
@staticmethod @s_config.confdef(name='foo') def foodefs(): defs=( ('fooval',{'type':'int','doc':'what is foo val?','defval':
˓→99}), ('enabled',{'type':'bool','doc':'is thing enabled?','defval
˓→':0}), ) return defs synapse.lib.dark module synapse.lib.dark.genDarkRows(iden, name, valus) Generate dark rows in bulk for a given set of values. This can be used generate rows in order to do bulk insertion of rows into a Cortex without the overhead of continually going through the addTufoDark() API. Args: iden (str): Iden to reverse. name (str): Dark row name. valus : Iterator to generate values to make in the rows. May be any data type which may stored in a Cortex. Example: Example use with a core:
rows= list(genDarkRows('1234','hidden',['garden','server','clown]) core.addRows(rows)
Yields: tuple: A cortex row, containing a iden, prop, value and timestamp.
236 Chapter 4. synapse package Synapse Documentation, Release 0.0.34
synapse.lib.datapath module
class synapse.lib.datapath.DataElem(item, name=None, parent=None) Bases: object iter(path) Iterate sub elements using the given path. Example: data = { ‘foo’:[ {‘bar’:’lol’}, {‘bar’:’heh’} ] } root = s_datapath.initelem(data) for elem in root.iter(‘foo/*/bar’): dostuff(elem) # elem is at value “lol” and “heh” name() step(path) Step to the given DataElem within the tree. vals(path) Iterate the given path elements and yield values. Example: data = { ‘foo’:[ {‘bar’:’lol’}, {‘bar’:’heh’} ] } root = s_datapath.initelem(data) for elem in root.iter(‘foo/*/bar’): dostuff(elem) # elem is at value “lol” and “heh” valu(path) Return the value of the element at the given path. class synapse.lib.datapath.XmlDataElem(item, name=None, parent=None) Bases: synapse.lib.datapath.DataElem synapse.lib.datapath.initelem(item, name=None, parent=None) Construct a new DataElem from the given item using which ever DataElem class is most correct for the type. Example: elem = initelem( synapse.lib.datfile module
Utilities for handling data files embedded within python packages. synapse.lib.datfile.openDatFile(datpath) Open a file-like object using a pkg relative path. Example: fd = openDatFile(‘foopkg.barpkg/wootwoot.bin’) synapse.lib.encoding module synapse.lib.encoding.decode(name, byts, **opts) Decode the given byts with the named decoder. If name is a comma separated list of decoders, loop through and do them all. Example:
4.1. Subpackages 237 Synapse Documentation, Release 0.0.34
byts = s_encoding.decode(‘base64’,byts)
Note: Decoder names may also be prefixed with + to encode for that name/layer. synapse.lib.encoding.encode(name, item, **opts) synapse.lib.fifo module class synapse.lib.fifo.Fifo(conf, xmit=None) Bases: synapse.lib.config.Config ack(seqn) Acknowledge (and cull) an item in the sequence. flush() Flush any file buffers associated with this Fifo. put(item) Put a new item into the Fifo. Args: item (obj): The object to serialize into the Fifo. resync(xmit=None) Re-synchronize this Fifo by sending all window entries. (optionally specify a new xmit callback) Args: xmit (func): The fifo xmit() callback. Example: def xmit(qent): seqn, nseq, item = qent dostuff() fifo.resync(xmit=xmit) class synapse.lib.fifo.Window(fdir, path, xmit=None) Bases: synapse.eventbus.EventBus A read window within a Fifo. ack(seqn) Ack a sequence from this Fifo. Args: seqn (int): The sequence number to acknowledge. fill() Possibly trigger filling the fifo window from bytes. flush() Flush the current AtomFile contents. resync(xmit=None) Re-synchronize this Fifo (assuming an xmit restart). ( see Fifo.resync ) synapse.lib.filepath module class synapse.lib.filepath.FpFile(pparts, idx, parent=None, fd=None) Bases: object close() Closes the file-like object if it has one isfile() Returns a boolean. If it returns False, it may be assumed to be a directory
238 Chapter 4. synapse package Synapse Documentation, Release 0.0.34
next() This is the workhorse method that can contain path specific processing of children. The object should consume as much as possible of the path before creating the child class NOTE: Override for container formats nexts() open(mode=’rb’) Returns a file-like object for this path This should return None if it doesn’t make sense to open, i.e. a directory path() class synapse.lib.filepath.FpOpener(fpobj) Bases: object close() read(*args) seek(*args) class synapse.lib.filepath.FpTar(pparts, idx, parent=None, fd=None) Bases: synapse.lib.filepath.FpFile close() Closes the file-like object if it has one innerLs(path) innrEnum() enumerate the files and directory paths in the container exactly once! creates a nested dict and a set of files and dirs... memory inefficient FIXME: consider abandoning sets innrExists(path) innrIsdir(path) innrIsfile(path) innrOpen(*parts) innrTmpExtract(path) Extract a file from within the container to a named temporary file next() This is the workhorse method for path specific processing of container children. The object should con- sume as much as possible of the path before instantiating a new object At a minimum, each container should override: innrOpen(path) innrEnum(path) nexts() open(mode=’rb’) Returns a file-like object for the path inside the container This should return None if it doesn’t make sense to open, i.e. a directory or if the container doesn’t contain the end of the path path() class synapse.lib.filepath.FpZip(pparts, idx, parent=None, fd=None) Bases: synapse.lib.filepath.FpTar innrEnum() enumerate the files and directory paths in the container exactly once!
4.1. Subpackages 239 Synapse Documentation, Release 0.0.34
innrOpen(*parts) synapse.lib.filepath.exists(*paths) Determines if the path exists even if the path terminates inside a container file. If a list of paths are provided, they are joined first. Returns a boolean. synapse.lib.filepath.getPathParts(path) Returns the elements of a path in order, w/o regard to their original separators synapse.lib.filepath.isdir(*paths) Determines if the path is a directory, even if the path terminates inside a container file. If a list of paths are provided, they are joined first. Returns a boolean. synapse.lib.filepath.isfile(*paths) Determines if the path is a file, even if the path terminates inside a container file. If a list of paths are provided, they are joined first. Returns a boolean. synapse.lib.filepath.max_temp_sz = 104857600 Provide a generic opener API for paths that cross into supported container files. For example: /dir0/dir1/foo.zip/d0/bar The above represents a file named bar located in the d0 directory inside the foo.zip zip archive located on the filesystem in the /dir0/dir1 directory. synapse.lib.filepath.normpath(*paths) Normalizes a path: 1. uses forward-slashes 2. removes leading slashes 3. removes trailing slashes This is useful for container path enumeration synapse.lib.filepath.openfile(*paths, **kwargs) Returns a read-only file-like object even if the path terminates inside a container file. If the path is a regular os accessible path mode may be passed through as a keyword argument. If the path terminates in a container file, mode is ignored. If req=True (Default) NoSuchPath will also be raised if the path exists, but is a directory Example: fd = openfile(‘/foo/bar/baz.egg/path/inside/zip/to/file’) if fd == None: return fbuf = fd.read() fd.close() synapse.lib.filepath.openfiles(*paths, **kwargs) Yields a read-only file-like object for each path even if the path terminates inside a container file. Paths may use python’s fnmatch glob matching If the path is a regular os accessible path mode may be passed through as a keyword argument. If the path terminates in a container file, mode is ignored. If req=True (Default) NoSuchPath will also be raised if ANY matching path exists, but is a directory Example: for fd in openfiles(‘/foo/bar/.egg/dir0/zz/nest.zip’): fbuf = fd.read() synapse.lib.filepath.parsePath(*paths) function to parse the incoming path. lists of paths are joined prior to parsing synapse.lib.filepath.parsePaths(*paths) function to parse the incoming path. lists of paths are joined prior to parsing The path supports python’s fnmatch glob matching synapse.lib.filepath.subpaths(path) Returns a list of subpaths in a path, one for each level in the path This is an internal function used for ONLY for
240 Chapter 4. synapse package Synapse Documentation, Release 0.0.34
iterating over paths in a container As such it should not be used for filesystem paths since separators will vary across platforms synapse.lib.hashitem module synapse.lib.hashitem.hashitem(item) Generate a uniq hash for the JSON compatible primitive data structure. synapse.lib.hashitem.normdict(item) synapse.lib.hashitem.normitem(item) synapse.lib.hashitem.normiter(item) synapse.lib.hashset module class synapse.lib.hashset.HashSet Bases: object digests() Return a list of (name,digest) tuples for the hashes in the set. eatfd(fd) Consume all the bytes from a file like object. Example: hset = HashSet() hset.eatfd(fd) guid() Use elements from this hash set to create a unique (re)identifier. update(byts) Update all the hashes in the set with the given bytes. synapse.lib.heap module class synapse.lib.heap.Heap(fd, **opts) Bases: synapse.eventbus.EventBus A persistant heap object. alloc(size) Allocate a block within the Heap and return the offset. Example: off = heap.alloc(len(foo)) readiter(off, size, itersize=10000000) Yield back byts chunks for the given off/size. Example: for byts in heap.readiter(off,size): dostuff() readoff(off, size) Read and return bytes from the heap at an offset. Example:
4.1. Subpackages 241 Synapse Documentation, Release 0.0.34
head = heap.readoff(off,headsize) size() sync(mesg) Consume a heap:sync event. syncs(msgs) Consume a list of heap:sync events. writeoff(off, byts) Write bytes at an offset within the heap. Example: off = heap.alloc(size) heap.writeoff(off,byts) synapse.lib.ingest module class synapse.lib.ingest.Ingest(info, axon=None) Bases: synapse.eventbus.EventBus An Ingest allows modular data acquisition and cortex loading. get(name, defval=None) Retrieve a value from self._i_info ingest(core, data=None) Ingest the data from this definition into the specified cortex. set(name, valu) Set a value in self._i_info class synapse.lib.ingest.IngestApi(core) Bases: object An API mixin which may be used to wrap a cortex and send along ingest data. addGestData(name, data) Ingest data according to a previously registered ingest format. Example: data = getDataFromThing() # use the foo:bar ingest iapi.addGestData(‘foo:bar’, data) setGestDef(name, idef ) Set an ingest definition by storing it in the cortex. Example: idef = {... ingest def json ... } iapi.setGestDef(‘foo:bar’, idef) setGestFunc(name, func) Set an ingest function to handle a custom data format. Args: name (str): The name of the ingest format func (func): The callback function to parse the data synapse.lib.ingest.addFormat(name, fn, opts) Add an additional ingest file format
242 Chapter 4. synapse package Synapse Documentation, Release 0.0.34 synapse.lib.ingest.iterdata(fd, close_fd=True, **opts) Iterate through the data provided by a file like object. Optional parameters may be used to control how the data is deserialized. Examples: The following example show use of the iterdata function.:
with open('foo.csv','rb') as fd: for row in iterdata(fd, format='csv', encoding='utf8'): dostuff(row)
Args: fd (file) : File like object to iterate over. close_fd (bool) : Default behavior is to close the fd object. If this is not true, the fd will not be closed.
**opts (dict): Ingest open directive. Causes the data in the fd to be parsed according to the ‘format’ key and any additional arguments.
Yields: An item to process. The type of the item is dependent on the format parameters. synapse.lib.ingest.loadfile(*paths) Load a json ingest def from file and construct an Ingest class. This routine is useful because it implements the convention for adding runtime info to the ingest json to facilitate path relative file opening etc... synapse.lib.ingest.register_ingest(core, gest, evtname, ret_func=False) Register an ingest class with a cortex eventbus with a given name. When events are fired, they are expected to have the argument “data” which is passed along to the Ingest.ingest() function. Parameters • core – Cortex to register the Ingest with • gest – Ingest to register • evtname – Event name to register the ingest with. • ret_func – Bool, if true, return the ingest function. synapse.lib.interval module
A few utilities for dealing with intervals. synapse.lib.interval.fold(*vals) Initialize a new (min,max) tuple interval from values. Args:* vals ([int,...]): A list of values (or Nones) Returns: ((int,int)): A (min,max) interval tuple or None synapse.lib.interval.overlap(ival0, ival1) Determine if two interval tuples have overlap. Args: iv0 ((int,int)): An interval tuple iv1 ((int,int)); An interval tuple Returns: (bool): True if the intervals overlap, otherwise False synapse.lib.interval.parsetime(text) Parse an interval time string and return a (min,max) tuple. Args: text (str): A time interval string Returns: ((int,int)): A epoch millis epoch time string
4.1. Subpackages 243 Synapse Documentation, Release 0.0.34 synapse.lib.iq module synapse - iq.py Created on 10/21/17. The IQ module contains the core test helper code used in Synapse. This gives the opportunity for third-party users of Synapse to test their code using some of the same of the same helpers used to test Synapse. The core class, synapse.lib.iq.SynTest is a subclass of unittest.TestCase, with several wrapper functions to allow for easier calls to assert* functions, with less typing. There are also Synapse specific helpers, to load both Ram and PSQL Cortexes. Since SynTest is built from unittest.TestCase, the use of SynTest is compatible with the unittest, nose and pytest frameworks. This does not lock users into a particular test framework; while at the same time allowing base use to be invoked via the built-in Unittest library. class synapse.lib.iq.SynTest(methodName=’runTest’) Bases: unittest.case.TestCase static addTstForms(core) Add test forms to the cortex. Args: core (s_cores_common.Cortex): Core to prep. Returns: None eq(x, y) Assert X is equal to Y false(x) Assert X is False ge(x, y) Assert that X is greater than or equal to Y getDmonCore() Context manager to make a ram:/// cortex which has test models loaded into it and shared via daemon. Yields: s_cores_common.Cortex: A proxy object to the Ram backed cortex with test models. getLoggerStream(logname) Get a logger and attach a io.StringIO object to the logger to capture log messages. Args: logname (str): Name of the logger to get. Examples: Do an action and get the stream of log messages to check against:
with self.getLoggerStream('synapse.foo.bar') as stream: # Do something that triggers a log message doSomthing() stream.seek(0) mesgs= stream.read() # Do something with messages
Yields: io.StringIO: A io.StringIO object getPgConn() Get a psycopg2 connection object. The PG database connected to is derived from the SYN_TEST_PG_DB environmental variable. Returns: psycopg2.connection: Raw psycopg2 connection object.
244 Chapter 4. synapse package Synapse Documentation, Release 0.0.34
getPgCore(table=’‘, persist=False, **opts) Get a Postgresql backed Cortex. This will grab the SYN_TEST_PG_DB environmental variable, and use it to construct a string to connect to a PSQL server and create a Cortex. By default, the Cortex DB tables will be dropped when onfini() is called on the Cortex. Some example values for this envar are shown below:
# From our .drone.yml file root@database:5432/syn_test # An example which may be used with a local docker image # after having created the syn_test database postgres:1234@localhost:5432/syn_test
Args: table (str): The PSQL table name to use. If the table name is not provided by URL or argu- ment; a random table name will be created. persist (bool): If set to True, keep the tables created by the Cortex creation. opts: Additional options passed to openlink call. Returns: s_cores_common.Cortex: A PSQL backed cortex. Raises: unittest.SkipTest: if there is no SYN_TEST_PG_DB envar set.
getRamCore() Context manager to make a ram:/// cortex which has test models loaded into it. Yields: s_cores_common.Cortex: Ram backed cortex with test models. getTestDir() Get a temporary directory for test purposes. This destroys the directory afterwards. Yields: str: The path to a temporary directory. getTestOutp() Get a Output instance with a expects() function. Returns: TstOutPut: A TstOutPut instance. getTestWait(bus, size, *evts) gt(x, y) Assert that X is greater than Y isin(member, container) Assert a member is inside of a container. isinstance(obj, cls) Assert a object is the instance of a given class or tuple of classes. le(x, y) Assert that X is less than or equal to Y len(x, obj) Assert that the length of an object is equal to X lt(x, y) Assert that X is less than Y ne(x, y) Assert X is not equal to Y
4.1. Subpackages 245 Synapse Documentation, Release 0.0.34
nn(x) Assert X is not None none(x) Assert X is None noprop(info, prop) Assert a property is not present in a dictionary. notin(member, container) Assert a member is not inside of a container. raises(*args, **kwargs) Assert a function raises an exception. setTstEnvars(**props) Set Environmental variables for the purposes of running a specific test. Args:** props: A kwarg list of envars to set. The values set are run through str() to ensure we’re setting strings. Examples: Run a test while a envar is set:
with self.setEnvars(magic='haha') as nop: ret= dostuff() self.true(ret)
Notes: This helper explicitly sets and unsets values in os.environ, as os.putenv does not automatically updates the os.environ object. Yields: None. This context manager yields None. Upon exiting, envars are either removed from os.environ or reset to their previous values. skipIfNoInternet() Allow skipping a test if SYN_TEST_SKIP_INTERNET envar is set. Raises: unittest.SkipTest if SYN_TEST_SKIP_INTERNET envar is set to a integer greater than 1. skipLongTest() Allow skipping a test if SYN_TEST_SKIP_LONG envar is set. Raises: unittest.SkipTest if SYN_TEST_SKIP_LONG envar is set to a integer greater than 1. sorteq(x, y) Assert two sorted sequences are the same. thisHostMust(**props) Requires a host having a specific property. Args:** props: Raises: unittest.SkipTest if the required property is missing. thisHostMustNot(**props) Requires a host to not have a specific property. Args:** props: Raises: unittest.SkipTest if the required property is missing. true(x) Assert X is True class synapse.lib.iq.TstEnv Bases: object
246 Chapter 4. synapse package Synapse Documentation, Release 0.0.34
add(name, item, fini=False) fini() class synapse.lib.iq.TstOutPut Bases: synapse.lib.output.OutPutStr expect(substr) synapse.lib.mixins module synapse.lib.mixins.addSynMixin(subsys, name, cname=None) Add a mixin class to the specified subsystem. Example: s_mixins.addSynMixin(‘foo’,’synapse.foo.FooMixin’) synapse.lib.mixins.getSynMixins(subsys, name) Return a list of mixin classes for the given subsystem class. Example: for clas in getSynMixins(‘telepath’,’foo.bar.Baz’): dostuff() synapse.lib.mixins.ldict() synapse.lib.module module class synapse.lib.module.CoreModule(core, conf ) Bases: synapse.eventbus.EventBus, synapse.lib.config.Configable The CoreModule base class from which cortex modules must extend. This module interface implements helper APIs to facilitate cortex extensions. To load a module within a cortex, add it to the list of modules in the cortex config ( mostly likely within your dmon config ) as shown: # example cortex config { “modules”:[ [”foopkg.barmod.modctor”, { “foo:opt”:10, “bar:opt”:”http://www.vertex.link” }] ] } Modules may extend the cortex in various ways such as: • Implement and enforce data model additions • Enrich properties during node creation / modification • Add “by” handlers and side-pocket indexes to extend queries • Add custom storm/swarm operators to the query language • etc etc etc...
NOTE: The cortex which loads the module plumbs all events into the CoreModule instance using Event- Bus.link().
4.1. Subpackages 247 Synapse Documentation, Release 0.0.34
form(form, valu, **props) A module shortcut for core.formTufoByProp() Args: form (str): The node form to retrieve/create valu (obj): The node value **props: Additional node properties static getBaseModels() Get a tuple containing name, model values associated with the CoreModule. Any models which are returned by this function are considered revision 0 models for the name, and will be automatically loaded into a Cortex if the model does not currently exist. Note: While this may return multiple tuples, internal Synapse convention is to define a single model in a single CoreModule subclass in a single file, for consistency. Returns: ((str, dict)): A tuple containing name, model pairs. getModName() Return the name of this module. Returns: (str): The module name. getModPath(*paths) Construct a path relative to this module’s working directory. Args: (*paths): A list of path strings Returns: (str): The full path getModlRevs() Generate a list of ( name, vers, func ) tuples for model revisions in this module. Returns: ([ (str, int, func), ... ]) Example: for name, vers, func in modu.getModlRevs(): core.revModlVers(name,revs) initCoreModule() Module implementers may over-ride this method to initialize the module during initial construction. Any exception raised within this method will be raised from the constructor and mark the module as failed. Args: Returns: (None) onFormNode(form, func) Register a callback to run during node formation. This callback will be able to set properties on the node prior to construction. Args: form (str): The name of the node creation func (function): A callback Returns: (None) Example: def myFormFunc(form, valu, props, mesg): props[’foo:bar:baz’] = 10 self.onFormNode(‘foo:bar’, myFormFunc) NOTE: This may not be used for a module loaded with a remote cortex. onNodeAdd(func, form=None) Register a callback to run when a node is added. Args: func (function): The callback form (str): The form of node to watch for (or all!)
248 Chapter 4. synapse package Synapse Documentation, Release 0.0.34
Returns: (None) Example: def callback(node): dostuff(node) self.onNodeAdd(callback, form=’inet:fqdn’) onNodeDel(func, form=None) Register a callback to run when a node is deleted. Args: func (function): The callback form (str): The form of node to watch for (or all!) Returns: (None) Example: def callback(node): dostuff(node) self.onNodeDel(callback, form=’inet:fqdn’) postCoreModule() Module implementers may over-ride this method to initialize the module after the configuration data has been loaded. Returns: (None) reqModPath(*paths) Require a path relative to this module’s working directory. Args: (*paths): A list of path strings Returns: (str): The full path synapse.lib.module.modelrev(name, vers) A decorator used to flag model revision functions. Args: name (str): Name of the model. vers (int): Revision of the model. It is validated using vali- date_revnumber. synapse.lib.module.validate_revnumber(revision) Validate a model revision number matches the time format ‘%Y%m%d%H%M’ Args: revision (int): Revision to validate. Raises: BadRevValu: If the integer does not match the time format. synapse.lib.modules module
Module which implements the synapse module API/convention. synapse.lib.modules.call(name, *args, **kwargs) Call the given function on all loaded synapse modules. Returns a list of name,ret,exc tuples where each module which implements the given function returns either ret on successful execution or exc in the event of an exception. Args: name (str): Name of the function to execute. *args (tuple): Additional positional args to use when executing the function. **kwargs (dict): Additional keyword args to use when executing the function. Example: Call getFooByBar with a single positional argument:
import synapse.lib.modules as s_modules for name,ret,exc in s_modules.call('getFooByBar',bar): dostuff()
4.1. Subpackages 249 Synapse Documentation, Release 0.0.34
Returns: list: List of name, returnval, exception information for each registered module. synapse.lib.modules.call_ctor(name, *args, **kwargs) Call the given function on all ctors loaded by load_ctor. Returns a list of name,ret,exc tuples where each ctor which implements the given function returns either ret on successful execution or exc in the event of an exception. Args: name (str): Name of the function to execute. *args (tuple): Additional positional args to use when executing the function. **kwargs (dict): Additional keyword args to use when executing the function. Example: Call getFooByBar on all loaded ctors.:
import synapse.lib.modules as s_modules for name,ret,exc in s_modules.call_ctor('getFooByBar'): dostuff()
Notes: This function does not create instances of the classes. It is best used when called against @staticmethod or @classmethod functions. Returns: list: List of name, returnval, exception information for each registered ctor. synapse.lib.modules.load(name) Load the given module path as a synapse module. Args: name (str): Python path to load. Example: Load the foopkg.barmod module.:
import synapse.lib.modules as s_modules s_modules.load('foopkg.barmod')
Notes: Users should be aware that the import process can perform arbitrary code execution by imported mod- ules. Returns: The loaded module is returned. synapse.lib.modules.load_ctor(name, opts) Load the given ctor path as a synapse CoreModule for extending the Cortex implementation. Args: name (str): Python path to a class ctor to load. opts (dict): Dictionary of configuration options. Example: Load the foopkg.barmod.Baz ctor:
import synapse.lib.modules as s_modules s_modules.load_ctor('foopkg.barmod.Baz', {})
Notes: This can only be used to dynamically load a subclass of the CoreModule class. Users should be aware that the import process can perform arbitrary code execution by imported modules. Returns: The loaded class is returned. Raises: NoSuchCtor: If the imported module does not have the listed ctor BadCtorType: If the ctor is not a subclass of the CoreModule class. synapse.lib.msgpack module class synapse.lib.msgpack.Unpk Bases: object
250 Chapter 4. synapse package Synapse Documentation, Release 0.0.34
An extension of the msgpack streaming Unpacker which reports sizes. feed(byts) Feed bytes to the unpacker and return completed objects. synapse.lib.msgpack.en(item) Use msgpack to serialize a compatible python object. Args: item (obj): The object to serialize Returns: bytes: The serialized bytes synapse.lib.msgpack.iterfd(fd) Generator which unpacks a file object of msgpacked content. Args: fd: File object to consume data from. Yields: Objects from a msgpack stream. synapse.lib.msgpack.un(byts) Use msgpack to de-serialize a python object. Args: byts (bytes): The bytes to de-serialize Returns: obj: The de-serialized object synapse.lib.openfile module
A single entry point for various protocol and open behaviors to allow all file open (for read) requests to support URLs and encapsulation. synapse.lib.openfile.openfd(*paths, **opts) Open and return a file like object for the given path/url. Example: with openfd(‘http://vertex.link/foo.csv‘) as fd: dostuff(fd) with openfd(‘foo/bar.txt’) as fd: fd.read() synapse.lib.output module
Tools for easily hookable output from cli-like tools. class synapse.lib.output.OutPut Bases: object printf(mesg, addnl=True) class synapse.lib.output.OutPutBytes Bases: synapse.lib.output.OutPutFd class synapse.lib.output.OutPutFd(fd, enc=’utf8’) Bases: synapse.lib.output.OutPut class synapse.lib.output.OutPutStr Bases: synapse.lib.output.OutPut
4.1. Subpackages 251 Synapse Documentation, Release 0.0.34 synapse.lib.persist module
Tools for persisting msgpack compatible objects. class synapse.lib.persist.Dir(path, **opts) Bases: synapse.eventbus.EventBus A persistence dir may be used similar to a Write-Ahead-Log to sync objects based on events ( and allow desync- catch-up ) add(item) Add an object to the persistant store. Returns (off,size) tuple within the persistance stream. Example: off,size = pers.add(item) getIdenOffset(iden) getPumpOffs() Return a dict of { iden:offset } info for the running pumps. Example: for iden,noff in pdir.getPumpOffs(): dostuff() items(off ) Yield (nextoff,item) tuples from the file backlog and real-time once caught up. NOTE: because this is a legitimate yield generator it may not be used across a telepath proxy. Example: for noff,item in pers.items(0): stuff(item) pump(iden, func) Fire a new pump thread to call the given function. Example: pdir.firePumpThread( iden, core.sync ) class synapse.lib.persist.File(fd=None, **opts) Bases: synapse.eventbus.EventBus A single fd based persistence stream. This is mostly a helper for Dir(). All consume/resume behavior should be facilitated by the Dir() object. add(item) Add an item to the persistance storage. readoff(off, size) Read size bytes form the given offset. class synapse.lib.persist.Offset(*paths) Bases: synapse.eventbus.EventBus A file backed persistant offset calculator. Example: poff = Offset(dirpath,’foo.off’): for off,item in pers.items(): dostuff(item) poff.set(off)
252 Chapter 4. synapse package Synapse Documentation, Release 0.0.34
get() Return the current offset. set(valu) Set (and save) the current offset. synapse.lib.persist.opendir(*paths, **opts) Open a persistance directory by path name with options. synapse.lib.queue module class synapse.lib.queue.Queue(items=()) Bases: synapse.eventbus.EventBus A simple custom queue to address python Queue() issues. done() Gracefully mark this Queue as done. This still allows a Queue consumer to finish consuming it. The Queue functions get(), slice() and slices() will not block when .done() has been called on a Queue. Returns: None get(timeout=None) Get the next item from the queue. Args: timeout (int): Duration, in seconds, to wait for items to be available to the queue before return- ing. Notes: This will block if the queue is empty and no timeout value is specified, or .done() has not been called on the Queue. Examples: Get an item and do stuff with it:
item=q.get(timeout=30) dostuff(item)
Returns: Item from the queue, or None if the queue is fini() or timeout occurs. put(item) Add an item to the queue and wake any consumers waiting on the queue. Args: item: Item to add to the queue. Examples: Put a string in a queue:
q.put('woot')
Returns: None slice(size, timeout=None) Get a slice of the next items from the queue. Args: size (int): Maximum number of items to get from the queue. timeout (int): Duration, in seconds, to wait for items to be available to the queue before returning. Examples: Return up to 3 items on a 30 second timeout from the queue:
4.1. Subpackages 253 Synapse Documentation, Release 0.0.34
items=q.slice(3, timeout=30)
Notes: This will block if the queue is empty and no timeout value is specified, or .done() has not been called on the Queue. Returns: list: A list of items from the queue. This will return None on fini() or timeout. slices(size, timeout=None) Yields slices of items from the queue. Args: size (int): Maximum number of items to yield at a time. timeout (int): Duration, in seconds, to wait for items to be added to the queue before exiting. Examples: Yield 2 items at a time with a 1 second time:
for items in q.slices(2, timeout=1): dostuff(items)
Notes: This will block if the queue is empty and no timeout value is specified, or .done() has not been called on the Queue. Yields: list: This generator yields a list of items. exception synapse.lib.queue.QueueShutdown Bases: Exception synapse.lib.ratelimit module class synapse.lib.ratelimit.RateLimit(rate, per) Bases: object A RateLimit class may be used to detect/enforce rate limits. Example: # allow 20 uses per 10 sec ( 2/sec ) rlimit = RateLimit(20,10) Notes: It is best ( even in a “calls per day” type config ) to specify a smaller “per” to force rate “smoothing”. allows() Returns True if the rate limit has not been reached. Example: if not rlimit.allows(): rasie RateExceeded() # ok to go... synapse.lib.reflect module synapse.lib.reflect.getClsNames(item) Return a list of “fully qualified” class names for an instance. Example: for name in getClsNames(foo): print(name)
254 Chapter 4. synapse package Synapse Documentation, Release 0.0.34 synapse.lib.reflect.getItemInfo(item) Get “reflection info” dict for the given object. Args: item: Item to inspect. Examples: Find out what classes a Telepath Proxy object inherits:
info= getItemInfo(prox) classes= info.get('inherits')
Notes: Classes may implement a def _syn_reflect(self): function in order to return explicit values. The Telepath Proxy object is one example of doing this, in order to allow a remote caller to identify what classes the Proxy object represents. Returns: dict: Dictionary of reflection information. synapse.lib.reflect.getItemLocals(item) Iterate the locals of an item and yield (name,valu) pairs. Example: for name,valu in getItemLocals(item): dostuff() synapse.lib.reflect.getMethName(meth) Return a fully qualified string for the .. name of a given method. synapse.lib.remcycle module
Remcycle provides a mechanism for kicking off asynchronous HTTP(S) requests via Tornado’s AsyncHTTPClient. A method for templating URL endpoints, providing default configuration values and user set configuration values, per request, is available. In addition, data can also be ingested into a cortex (provided, or a default ram cortex) for immediate consumption. These requests are handled by Hypnos objects, which can have a single or multiple definitions snapped into them in order to grab data on demand. Hypnos grabs these requests with a single IO thread, and offloads the consumption of the data to multiple worker threads. class synapse.lib.remcycle.Hypnos(core=None, opts=None, *args, **kwargs) Bases: synapse.lib.config.Config Object for grabbing a bunch of HTTP(S) data and consuming it via callbacks or ingest definitions. Users can register multiple namespaces, each with their own set of API endpoints configured with them. See the fire_api() function for details on retrieving data with Hypnos. The Hypnos object inherits from the Config object, and as such has both configable parameters and an EventBus available for message passing. Notes: The following items may be passed via kwargs to change the Hypnos object behavior: • ioloop: Tornado ioloop used by the IO thread. This would normally be left unset, and an ioloop will be created for the io thread. This is provided as a helper for testing. • content_type_skip: A list of content-type values which will not have any attempts to decode data done on them. The following values may be passed via configable opts: • web:worker:threads:min: Minimum number of worker threads to spawn. • web:worker:threads:max: Maximum number of worker threads to spawn.
4.1. Subpackages 255 Synapse Documentation, Release 0.0.34
• web:ingest:max_spool_size: Maximum spoolfile size, in bytes, to use for storing responses associ- ated withAPIs that have ingest definitions. • web:cache:enable: Enable caching of job results for a period of time, retrievable by jobid. • web:cache:timeout: Timeout value, in seconds, that the results will persist in the cache. • web:tornado:max_clients: Maximum number of concurrent requests which can be made at one time. Args: core (synapse.cores.common.Cortex): A cortex used to store ingest data. By default a ram cortex is used. opts (dict): Optional configuration data for the Config mixin. addWebConfig(config, reload_config=True) Register a configuration into a Hypnos object. The Hypnos object can accept a configuration object shaped like the following:
{ "apis":[ [ "geoloc", { "api_args":[ "someplace" ], "api_optargs":{ "domore":0 }, "doc":"api example", "http":{ "headers":{ "token-goodness":"sekrittoken" } }, "ingest":{ "definition":{ "ingest":{ "forms":[ [ "inet:ipv4", { "var":"ip" } ] ], "vars":[ [ "ip", { "path":"ip" } ] ] }, "open":{ "format":"json" } }, "name":"geolocv4" }, "url":"http://vertex.link/api/v4/geoloc/{{someplace}}/info?domore={
˓→{domore}}&apikey={APIKEY}",
256 Chapter 4. synapse package Synapse Documentation, Release 0.0.34
"vars":[ [ "APIKEY", "8675309" ] ] } ], [ "https", { "doc":"Get the vertex project landingpage.", "http":{ "validate_cert": false }, "url":"https://vertex.link/" } ] ], "doc":"GrabVertex.linkstuff", "http":{ "user_agent":"Totally Not a Python application." }, "namespace":"vertexproject" }
The following config keys are required: • namespace: String identifier for all APIs present in the configuration. Must be locally unique. • doc: Simple string describing the overall namespace. • apis: Sequence containing containing configuration values for API endpoints. See Nyx object for details of how this data should be shaped. The sequence should contain two value pairs of data. The first value should be the name of the API, while the second value is the actual API configuration. The name of the API, when joined with the namespace, forms the name the API can be called with for for later use. Given the example above, the following APIs would be registered: – vertexproject:geoloc – vertexproject:https The following config keys are optional: • http: Global HTTP Request arguments which will be the basis for creating HTTPRequest objects. These values should conform to the Tornado HTTPRequest constructor. An example of a generic configuration for getting arbitrary endpoints is shown below:
{ "apis":[ [ "fqdn", { "api_args":[ "fqdn" ], "api_optargs":{ "endpoint":"" },
4.1. Subpackages 257 Synapse Documentation, Release 0.0.34
"doc":"Get arbitrary domain name.", "http":{ "validate_cert": false }, "url":"https://{{fqdn}}/{{endpoint}}" } ] ], "doc":"Definition for getting an arbitrary domain.", "http":{ "user_agent":"Some.UserAgent" }, "namespace":"generic" }
Args: config (dict): Dictionary containing the configuration information. reload_config (bool): If true and the namespace is already registered, the existing namespace will be removed and the new config added. Otherwise a NameError will be thrown. Returns: None Raises: Other exceptions are possible, likely as a result of ducktyping. NameError: If the existing names- pace is registered or a invalid HTTP value is provided.
delWebConf(namespace) Safely remove a namespace. Removes a given namespace, APIs and any corresponding event handlers which have been snapped into the Hypnos object and its cortex via the addWebConfig API. Args: namespace (str): Namespace to remove. Returns: None Raises: NoSuchName: If the namespace requested does not exist. fireWebApi(name, *args, **kwargs) Fire a request to a registered API. The API response is serviced by a thread in the Hypnos thread pool, which will fire either an event on the Hypnos service bus or a caller provided callback function. The default action is to fire an event on the service bus with the same name as the API itself. A flattened version of the response, error information and the Boss job id will be stamped into the kwargs passed along to the the callbacks. If the API name has a ingest associated with it, the response data will be pushed into a generator created according to the ingest open directive. The flattened response is a dictionary, accessed from kwargs using the ‘resp’ key. It contains the following information: • request: A dictionary containing the requested URL and headers. This is guaranteed to exist. It has the following values: – url: URL requested by the remote server. – headers: Headers passed to the remote server.
258 Chapter 4. synapse package Synapse Documentation, Release 0.0.34
• code: HTTP Response code. This will only be present on a successfull request or if a HTTPError is encountered. • data: This may be one of three values: – A SpooledTemporaryFile containing the raw bytes of the response. This will be present if there is a ingest associated with the named response. A corresponding generator will be created and placed in the “ingdata” field and consumed by the ingest. Post-consumption, seek(0) will be called on the file-like object. If there are multiple post-ingest consumers of the job, each one may want to call seek(0) on the file object before consuming it. – The decoded data as a string or a decoded json blob. We will attempt to parse the data based on the Content-Type header. This is a best effort decoding. – In the event that the best effort decoding fails, the response will be available as raw bytes. • effective_url: The effective url returned by the server. By default, Tornado will follow redirects, so this URL may differ from the request URL. It will only be present on a successful request or if a HTTPError is encountered. • headers: The response headers. It will only be present on a successful request or if a HTTPError is encountered. The flattened error is a dictionary, accessed from kwargs using the ‘errinfo’ key. It mimics the synapse excinfo output, but without investigating a stack trace for performance reasons. It contains the following information: • err: The Exception class raised during the request. • errmsg: The str() representation of the exception. • errfile: Empty string. • errline: Empty string. The Hypnos boss job id is a str which can be accessed from kwargs using the ‘jid’ key. Notes: The following items may be used via kwargs to set request parameters: • api_args: This should be a dictionary containing any required or optional arguments the API rquires. The following items may be passed via kwargs to change the job execution parameters: • callback: A function which will be called by the servicing thread. By default, this will be wrapped to fire boss.err() if excinfo is present in the callback’s kwargs. • ondone: A function to be executed by the job:fini handler when the job has been com- pleted. If the api we’re firing has an ingest associated with it, the response data may not be available to be consumed by the ondone handler. • job_timeout: A timeout on how long the job can run from the perspective of the boss. This isn’t related to the request or connect timeouts. • wrap_callback: By default, the callback function is wrapped to perform error checking (and fast job failure) in the event of an error encountered during the request, and additional processing of the HTTP response data to perform decoding and content-type processing. If this value is set to false, the decorator will not be applied to a provided callback function, and the error handling and additional data procesing will be the responsibility of any event handlers or the provided callback function. The fast failure behavior is handled by boss.err() on the job associated with the API call.
4.1. Subpackages 259 Synapse Documentation, Release 0.0.34
A HTTP body can be provided to the request by passing its contents in by adding the “req_body” value to api_args argument. See the Nyx object documentation for more details. If caching is enabled, the caching will be performed as the first thing done by the worker thread handling the response data. This is done separately from the wrap_callback step mentioned above.
Args: name (str): Name of the API to send a request for. *args: Additional args passed to the callback functions. **kwargs: Additional args passed to the callback functions or for changing the job execution. Returns: str: String containing a Job ID which can be used to look up a job against the Hyp- nos.web_boss object. Raises: NoSuchName: If the requested API name does not exist.
getNyxApi(name) Get the Nyx object corresponding to a given API name. Args: name (str): Name of the API to get the object for. Returns: Nyx: A Nyx object. getWebDescription() Get a dictionary containing all namespaces, their docstrings, and registered api data. Returns: dict: Dictionary describing the regsistered namespace API data. webCacheClear() Clear all the contents of the web cache. webCacheGet(jid) Retrieve the cached web response for a given job id. Args: jid (str): Job ID to retrieve. Returns: dict: A dictionary containing the job response data. It will have the following keys: • web_api_name: Name of the API • resp: Dictionary containing response data. The raw data is not decoded or processed in any fashion, and is available in the ‘data’ key of this dictionary (if present). • api_args: Args used when crafting the HTTPRequest with Nyx • err (optional): Error type if a error is encountered. • errmsg (optional): Error message if a error is encountered. • errfile (optional): Empty string if a error is encountered. • errline (optional): Empty string if a error is encountered. webCachePop(jid) Retrieve the cached web response for a given job id and remove it from the cache. Args: jid (str): Job ID to retrieve.
Returns: dict: A dictionary containing the job response data. See the docs for webCacheGet for the dictionary details.
260 Chapter 4. synapse package Synapse Documentation, Release 0.0.34
webContentTypeSkipAdd(content_type) Add a content-type value to be skipped from any sort of decoding attempts. Args: content_type (str): Content-type value to skip. webContentTypeSkipDel(content_type) Removes a content-type value from the set of values to be skipped from any sort of decoding attempts. Args: content_type (str): Content-type value to remove. webJobWait(jid, timeout=None) Proxy function for the self.web_boss wait() call, in order to allow RMI callers to wait for a job to be completed if they wish. Args: jid (str): Job id to wait for. timeout: Time to wait for. Returns: bool: async.Boss.wait() result. class synapse.lib.remcycle.Nyx(config) Bases: object Configuration parser & request generator for a REST service. This class is responsible for doing the actual HTTPRequest generation in a parametrized fashion for a given input. The API configuration is expected to be a dictionary with the expected values: • doc: Human readable description of the current API endpoint. • url: This is the actual URL which will be used to connect to a service. This string will be run through format() twice - once during the construction of the Nyx object, and the second time during the construc- tion of the per-request url. As such, any values set by the api_args and api_optargs configuration methods noted below should be enclosed with double curly brackets. The following configuration values are optional for a Nyx configuration. • api_args: This is a list of values which must be provided by the user when they call buildHttpRequest. These would represent URL parameters which are required to be provided by the user each time a new HTTPRequest object is built. • api_optargs: This is a dictionary of URL parameters which are are optional for the user to provide when calling buildHttpRequest. This dictionary represents the parameter names and default values for them. A user may provide alternative values when calling buildHttpRequest, but sensible defaults should be provided here. • http: A dictionary of key/value items which can provide per-api specific arguements for the creation of HTTPRequest objects. These values should conform to the Tornado HTTPRequest constructor. • ingest: A dictionary containing a Synapse ingest definition which will be used to create an Ingest objects. During registration of a Nyx object with Hypnos, these will be registered into the Hypnos cortex. This dictionary should contain the key “name” which will be used to create a unique name for the ingest events, and the key “definition” which must contain the ingest definition. The ingest definition must contain a “open” directive which is used with the ingest iterdata() function to process the API data prior to ingest. • vars: This is a dictionary of items which are stamped into the url template during the construction of the Nyx object using format(). Some API endpoints (typically PUT/POST/PATCH) may require additional content which is provided via the HTTP body. The api_arg value “req_body” is reserved in order to support passing body data when making the HTTPRequest object. A consequence of pulling the body from the api_args is that the ‘body’ argument is not allowed to be present in the “http” kv dictionary used when constructing the non-URL portions of the
4.1. Subpackages 261 Synapse Documentation, Release 0.0.34
HTTPRequest For use cases where a caller needs to make body requests with a default set of content, they are responsible for provided that content in the req_body api_args value when calling buildHttpRequest. See a complete example below:
{ "api_args":[ "someplace" ], "api_optargs":{ "domore":0 }, "doc":"api example", "http":{ "headers":{ "token-goodness":"sekrit token" } }, "ingest":{ "definition":{ "ingest":{ "forms":[ [ "inet:ipv4", { "var":"ip" } ] ], "vars":[ [ "ip", { "path":"ip" } ] ] }, "open":{ "format":"json" } }, "name":"geolocv4" }, "url":"http://vertex.link/api/v4/geoloc/{{someplace}}/info?domore={{domore}}&
˓→apikey={APIKEY}", "vars":{ "APIKEY":"8675309" } }
This example should be interpreted as the following: 1. The APIKEY value in the ‘vars’ will be set in the URL, resulting in the following default url:
"http://vertex.link/api/v4/geoloc/{someplace}/info?domore={domore}&
˓→apikey=8675309"
2. The HTTP request will have the header “token-goodness” set to “sekrit token” for the request.
262 Chapter 4. synapse package Synapse Documentation, Release 0.0.34
3. The caller must provide the “someplace” value in the api_args when calling buildHttpRequest. The caller may provide the “domore” value if they want to override the default value of “0”. 4. An Ingest will be created for parsing the data from the API and made available to the Hypnos object.
Parameters config – API Endpoint configuration outlined above.
buildHttpRequest(api_args=None) Build the HTTPRequest object for a given configuration and arguments. Args: api_args (dict): Arguments support either required or optional URL values. Notes: A HTTP body can be provided to the request by passing its contents in by adding the “req_body” value to api_args argument. Returns: tornado.httpclient.HTTPRequest: HTTPRequest object with the configured url and attributes. Raises: NoSuchName: If the api_args is missing a required API value. description() Get a dictionary containing an objects docstring, required api_args and optional api args. Returns: dict: Dictionary containing data. synapse.lib.sched module class synapse.lib.sched.Sched(pool=None) Bases: synapse.eventbus.EventBus at(ts, func, *args, **kwargs) Schedule a function to run at a specific time. Example: # call foo(bar,baz=10) at ts sched.at(ts, foo, bar, baz=10) cancel(item) Cancel a previously scheduled call. Example: def woot(x,y): stuff() sched = Sched() item = sched.insec(10, woot, 10, 20) sched.cancel(item) insec(delay, func, *args, **kwargs) Schedule a callback to occur in delay seconds. Example: def woot(x,y): stuff() sched = Sched() e = sched.insec(10, woot, 10, 20) # woot will be called in 10 seconds.. loop(secs, func, *args, **kwargs) Call the given function in a delay loop.
4.1. Subpackages 263 Synapse Documentation, Release 0.0.34
Args: secs (int): Seconds between loop calls (can be float) func (function): The function to call args (list): The call arguments kwargs (dict): The call keyword arguments Examples: Scheduled a function to be called once every 10 seconds:
def tensec(x,y=None): blah()
sched= Sched() sched.loop(10, tensec, 10, y='woot')
Notes: If the function returns False, the loop will explicitly break. If the task object is isfini’d, the loop will explicitly break. In either of those scenarios, the task will not be scheduled for further execution. Returns: s_task.Task: A Task object representing the object’s execution. persec(count, func, *args, **kwargs) Schedule a callback to occur count times per second. Args: count: Number of times per second for this to occur. Either an int or a float. func: Function to execute. *args: Args passed to the function. **kwargs: Kwargs passed to the function. Examples: Scheduled a function to be called 10 times per second:
def tenpersec(x,y=None): blah()
sched= Sched() sched.persec(10, tenpersec, 10, y='woot')
Notes: This indefinitely calls the scheduled function until the function returns False or the Task is fini’d. See the Sched.loop function for more details. Returns: s_task.Task: A Task object representing the object’s execution. yieldTimeTasks() synapse.lib.scope module class synapse.lib.scope.Scope(*frames, **vals) Bases: object The Scope object assists in creating nested varible scopes. Example: with Scope() as scope: scope.set(‘foo’,10) with scope: scope.set(‘foo’,20) dostuff(scope) # ‘foo’ is 20... dostuff(scope) # ‘foo’ is 10 again... add(name, *vals) Add values as iter() compatible items in the current scope frame. ctor(name, func, *args, **kwargs) Add a constructor to be called when a specific property is not present. Example: scope.ctor(‘foo’,FooThing) ... foo = scope.get(‘foo’)
264 Chapter 4. synapse package Synapse Documentation, Release 0.0.34
enter(vals=None) Add an additional scope frame. get(name, defval=None) Retrieve a value from the closest scope frame. iter(name) Iterate through values added with add() from each scope frame. leave() Pop the current scope frame. set(name, valu) Set a value in the current scope frame. update(vals) Set multiple values in the current scope frame. synapse.lib.scope.ctor(name, func, *args, **kwargs) Add a ctor callback to the global scope. synapse.lib.scope.enter(vals=None) Return the thread’s local scope for use in a with block synapse.lib.scope.get(name, defval=None) Access this thread’s scope with default values from glob. synapse.lib.scope.set(name, valu) Set a value in the current frame of the local thread scope. synapse.lib.scope.update(vals) synapse.lib.scrape module synapse.lib.scrape.scrape(text) Scrape types from a blob of text and return an ingest compatible dict. synapse.lib.scrape.splices(text, tags=()) Return a list of splice events for the give scrape output. synapse.lib.service module class synapse.lib.service.IdenProxy(svcprox, svcfo) Bases: synapse.lib.service.SvcBase class synapse.lib.service.SvcBase(svcprox) Bases: object class synapse.lib.service.SvcBus Bases: synapse.eventbus.EventBus getSynSvcs() Retrieve a list of the services on the service bus. Example: for name,info in sbus.getSynSvcs(): dostuff(name,info) getSynSvcsByTag(tag) Return a list of synapse services by hierarchical tag. Example:
4.1. Subpackages 265 Synapse Documentation, Release 0.0.34
for name,props in sbus.getSynSvcsByTag(‘foo.bar’): dostuff(name,props) iAmAlive(iden) “heartbeat” API for services. Example: sbus.iAmAlive(iden) Notes: This API is generally called by a scheduled loop within the service object. iAmSynSvc(iden, props) API used by synapse service to register with the bus. Example: sbus.iAmSynSvc(‘syn.blah’, foo=’bar’, baz=10) class synapse.lib.service.SvcMeth(svcbase, name) Bases: object class synapse.lib.service.SvcNameMeth(nameprox, name) Bases: object class synapse.lib.service.SvcNameProxy(svcprox, name) Bases: object Constructed by SvcProxy for simplifying callByName use. class synapse.lib.service.SvcProxy(sbus, timeout=None) Bases: synapse.eventbus.EventBus A client-side helper for service dispatches. Mostly exists to wrap functionality for calling multiple services by tag. callByIden(iden, func, *args, **kwargs) Call a specific object on the service bus by iden. Example: ret = svcprox.callByIden(iden,’getFooByBar’,bar) callByName(name, dyntask, timeout=None) Call a specific object on the service bus by name. Example: # dyntask tuple is (name,args,kwargs) dyntask = gentask(‘getFooByBar’,bar) ret = svcprox.callByName(‘foo0’, dyntask) callByTag(tag, dyntask, timeout=None) Call a method on all services with the given tag. Yields (svcfo,job) tuples for the results. Example: dyntask = gentask(‘getFooThing’) for svcfo,retval in svcprox.callByTag(‘foo.bar’,dyntask): dostuff(svcfo,retval) getNameProxy(name) Construct and return a SvcNameProxy to simplify callByName use. Example:
266 Chapter 4. synapse package Synapse Documentation, Release 0.0.34
foosbars = svcprox.getNameProxy(‘foos_bars’) valu = foosbars.getBlahThing() dostuff(valu) getSynSvc(iden) Return the tufo for the specified svc iden ( or None ). Example: svcfo = svcprox.getSynSvc(iden) if svcfo != None: dostuff(svcfo) getSynSvcByName(name) getSynSvcs() Return the current list of known service tufos. Example: for svcfo in svcprox.getSynSvcs(): dostuff(svcfo) getSynSvcsByTag(tag) Return a list of service tufos by tag. Example: for svcfo in svcprox.getSynSvcsByTag(tag): dostuff(svcfo) getTagProxy(tag) Construct and return a SvcTagProxy to simplify callByTag use. Example: foosbars = svcprox.getTagProxy(‘foos.bars’) for valu in foosbars.getBlahThing(): dostuff(valu) runSynSvc(name, item, tags=(), **props) Publish an object to the service bus with the given tags. Example: foo = Foo() svcprox.runSynSvc(‘foo0’, foo, tags=(‘foos.foo0’,)) setSynSvcTimeout(timeout) class synapse.lib.service.SvcTagMeth(tagprox, name) Bases: object class synapse.lib.service.SvcTagProxy(svcprox, tag) Bases: object Constructed by SvcProxy for simplifying callByTag use. synapse.lib.service.openurl(url, **opts) Open a remote service bus and return a SvcProxy class. Example: svcprox = openbus(‘tcp://svcbus.com/mybus‘) synapse.lib.service.runSynSvc(name, item, sbus, tags=(), **props) Add an object as a synapse service. Example:
4.1. Subpackages 267 Synapse Documentation, Release 0.0.34
woot = Woot() sbus = s_telepath.openurl(‘tcp://1.2.3.4:90/syn.svcbus‘) runSynSvc(‘syn.woot’, woot, sbus)
synapse.lib.session module
class synapse.lib.session.Curator(conf=None) Bases: synapse.lib.config.Config The Curator class manages sessions. get(iden=None) Return a Session by iden. Args: iden (str): The guid (None creates a new sess). Returns: (Sess) class synapse.lib.session.Sess(iden, **props) Bases: synapse.eventbus.EventBus A synapse session to store prop/vals. get(prop) Retrieve a session property by name. Args: prop (str): The property name to retrieve. Returns: (obj): The property valu (or None) set(prop, valu) Set a session property to the given value. Args: prop (str): The name of the session property valu (obj): The property valu synapse.lib.socket module class synapse.lib.socket.Plex Bases: synapse.eventbus.EventBus Manage multiple Sockets using a multi-plexor IO thread. addPlexSock(sock) Add a Socket to the Plex() Args: sock (Socket): Socket to add. Example: plex.addPlexSock(sock) getPlexSocks() Return a list of the Socket()s managed by the Plex(). Returns: ([Socket(),...]): The list of Socket() instances. wake() class synapse.lib.socket.Socket(sock, **info) Bases: synapse.eventbus.EventBus Wrapper for the builtin socket.Socket class. Args: sock socket.socket: socket to wrap **info:
268 Chapter 4. synapse package Synapse Documentation, Release 0.0.34
accept() close() Hook the socket close() function to trigger fini() get(prop, defval=None) Retrieve a property from the socket’s info dict. Example: if sock.get(‘listen’): dostuff() recv(size) Slightly modified recv function which masks socket errors. ( makes them look like a simple close ) Additionally, any non-blocking recv’s with no available data will return None! recvall(size) Recieve the exact number of bytes requested. Returns None on if socket closes early. Example: byts = sock.recvall(300) if byts == None: return dostuff(byts)
Notes: • this API will trigger fini() on close
recvobj() runTxLoop() Run a pass through the non-blocking tx loop. Returns: (bool): True if there is still more work to do rx() Yield any completed mesg tufos (type,info) in the recv buffer. Example: for mesg in sock.rx(): dostuff(mesg) send(byts) set(prop, valu) Set a property on the Socket by name. Example: sock.set(‘woot’, 30) setblocking(valu) Set the socket’s blocking mode to True/False. Args: valu (bool): False to set socket non-blocking tx(mesg) Transmit a mesg tufo ( type, info ) via the socket using msgpack. If present this API is safe for use with a socket in a Plex(). txbytes(byts)
4.1. Subpackages 269 Synapse Documentation, Release 0.0.34 synapse.lib.socket.connect(sockaddr, **sockinfo) Simplified connected TCP socket constructor. synapse.lib.socket.hostaddr(dest=‘8.8.8.8’) Retrieve the ipv4 address for this host ( optionally as seen from dest ). Example: addr = s_socket.hostaddr() synapse.lib.socket.inet_ntop(afam, byts) Implements classic socket.inet_ntop regardless of platform. (aka windows) synapse.lib.socket.inet_pton(afam, text) Implements classic socket.inet_pton regardless of platform. (aka windows) synapse.lib.socket.listen(sockaddr, **sockinfo) Simplified listening socket contructor. synapse.lib.socket.socketpair() Standard sockepair() on posix systems, and pure shinanegans on windows. synapse.lib.socket.sockgzip(byts) synapse.lib.storm module class synapse.lib.storm.LimitHelp(limit) Bases: object dec(size=1) get() reached() class synapse.lib.storm.OperWith(query, oper) Bases: object class synapse.lib.storm.Query(data=(), maxtime=None) Bases: object add(tufo) Add a tufo to the current query result set. cancel() Cancel the current query ( occurs at next tick() call ). clear() data() load(name) log(**info) Log execution metadata for the current oper. opt(name) Return the current value of a query option. result() retn() Return the results data or raise exception. save(name, data)
270 Chapter 4. synapse package Synapse Documentation, Release 0.0.34
setOpt(name, valu) Set a query option to the given value. size() Get the number of tufos currently in the query. take() Return and clear the current result set. ( used by filtration operators ) tick(touch=1) withop(oper) exception synapse.lib.storm.QueryCancelled Bases: synapse.lib.storm.QueryKilled exception synapse.lib.storm.QueryKilled Bases: Exception exception synapse.lib.storm.QueryLimitTime Bases: synapse.lib.storm.QueryKilled exception synapse.lib.storm.QueryLimitTouch Bases: synapse.lib.storm.QueryKilled class synapse.lib.storm.Runtime(**opts) Bases: synapse.lib.config.Configable ask(text, data=(), timeout=None) Run a storm query and return the query result dict. user= stdin= eval(text, data=(), timeout=None) Run a storm query and return only the result data. Example: for tufo in runt.eval(‘foo:bar=10 +foo:baz<30’): dostuff(tufo) getCmprFunc(oper) Return a comparison function for the given operator. getLiftLimit(*limits) Return the lift() result limit for the current user/runtime. Args:* limits: Optional list of requested int limit values Returns: (int): The lift limit value or None getLiftLimitHelp(*limits) Return a LimitHelp object for the specified limits or defaults. Args: limits (list): A list of int/None limits Returns: (LimitHelp) getStormCore(name=None) Return the (optionally named) cortex for use in direct storm operators. parse(text) plan(opers) Review a list of opers and return a potentially optimized list. Args: opers ([(str,dict),]): List of opers in tufo form Returns: ([(str,dict),]): Optimized list
4.1. Subpackages 271 Synapse Documentation, Release 0.0.34
run(opers, data=(), timeout=None) Execute a pre-parsed set of opers. Example: opers = runt.parse(‘foo:bar=20 +foo:baz | foo:faz=30’) # ... some time later... res0 = runt.run(opers) setCmprCtor(name, func) Add a comparitor constructor function for use in the “filt” operator. Example: def substr(oper): prop = oper[1].get(‘prop’) valu = oper[1].get(‘valu’) def cmpr(tufo): tufo[1].get(prop).find(valu) != -1 return cmpr runt.setCmprCtor(‘substr’,substr) # storm syntax now suports # +foo:bar*substring=”baz” and -foo:bar*substring=”baz” setCmprFunc(name, func) Helper function for adding simple comparitors. Example: def substr(x,y): return x.find(y) != -1 runt.setCmprFunc(‘substr’, substr)
NOTE: Under the hood, this API dynamically generates a cmpr ctor add adds it using addCmprCtor.
setOperFunc(name, func) Add a handler function for a given operator. The function must implement the convention: def func(query,oper): args = oper[1].get(‘args’) opts = dict(oper[1].get(‘kwlist’)) dostuff() Where query is a synapse.lib.storm.Query instance and oper is a (,) tufo. stormTufosBy(by, prop, valu=None, limit=None) A STORM runtime specific version of the cortex function getTufosBy which allows sub-classes to over- ride the default behavior for operators like lift/join/pivot. class synapse.lib.storm.ShowHelp(core, show) Bases: object The ShowHelp class implements routines for formatting storm query output based on the embedded “show” directive within the query results. pad(rows) Pad a series of column values for aligned display. rows(nodes) Return a list of display columns for the given nodes. Args: nodes (((str,dict),...)): A list of nodes in tuple form. Returns: ( [(str,...), ...] ): A list of column lists containing strings synapse.lib.storm.eq(x, y) synapse.lib.storm.ge(x, y)
272 Chapter 4. synapse package Synapse Documentation, Release 0.0.34 synapse.lib.storm.gt(x, y) synapse.lib.storm.invert(func) synapse.lib.storm.le(x, y) synapse.lib.storm.lt(x, y) synapse.lib.storm.setkw(oper, name, valu) Set a keyword argument in a given operator. Args: oper ((str,dict)): A storm operator tufo name (str): A kwarg name valu (obj): A kwarg value Returns: (None) synapse.lib.syntax module synapse.lib.syntax.is_literal(text, off ) synapse.lib.syntax.isquote(text, off ) synapse.lib.syntax.meh(txt, off, cset) synapse.lib.syntax.nextchar(text, off, valu) synapse.lib.syntax.nextin(text, off, vals) synapse.lib.syntax.nextstr(text, off, valu) synapse.lib.syntax.nom(txt, off, cset, trim=True) Consume chars in set from the string and return (subtxt,offset). Example: text = “foo(bar)” chars = set(‘abcdefghijklmnopqrstuvwxyz’) name,off = nom(text,0,chars) synapse.lib.syntax.nom_whitespace(text, off ) synapse.lib.syntax.oper(name, *args, **kwargs) synapse.lib.syntax.parse(text, off=0) Parse and return a set of instruction tufos. synapse.lib.syntax.parse_cmd_kwarg(text, off=0) Parse a foo:bar= kwarg into (prop,valu),off synapse.lib.syntax.parse_cmd_kwlist(text, off=0) Parse a foo:bar=[,...] kwarg list into (prop,valu),off synapse.lib.syntax.parse_cmd_string(text, off, trim=True) Parse in a command line string which may be quoted. synapse.lib.syntax.parse_int(text, off, trim=True) synapse.lib.syntax.parse_list(text, off=0, trim=True) Parse a list (likely for comp type) coming from a command line input. The string elements within the list may optionally be quoted. synapse.lib.syntax.parse_literal(text, off, trim=True) synapse.lib.syntax.parse_macro_filt(text, off=0, trim=True, mode=’must’) synapse.lib.syntax.parse_macro_join(text, off=0) &foo:bar &foo:bar=baz:faz &hehe.haha/foo:bar=baz:faz
4.1. Subpackages 273 Synapse Documentation, Release 0.0.34 synapse.lib.syntax.parse_macro_lift(text, off=0, trim=True) Parse a “lift” macro and return an inst,off tuple. synapse.lib.syntax.parse_oper(text, off=0) Returns an inst,off tuple by parsing an operator expression. Example: inst,off = parse_oper(‘foo(“bar”,baz=20)’) synapse.lib.syntax.parse_opts(text, off=0) synapse.lib.syntax.parse_perm(text, off=0) Parse a permission string [=...] synapse.lib.syntax.parse_ques(text, off=0, trim=True) Parse “query” syntax: tag/prop[@][^][*][=valu] synapse.lib.syntax.parse_string(text, off, trim=True) synapse.lib.syntax.parse_time(text, off ) synapse.lib.syntax.parse_valu(text, off=0) Special syntax for the right side of equals in a macro synapse.lib.tags module class synapse.lib.tags.ByTag Bases: object A dictionary style put/get API using tags. get(tag) Retrieve items by a tag. Example: for item in btag.get(‘foo.bar’): dostuff(item) pop(item, dval=None) Remove an item previously added to the ByTag. put(item, tags) Add an item for ByTag lookup with tags. Example: btag.put( woot, (‘woots.woot0’, ‘foo’) ) synapse.lib.tags.getTufoSubs(tufo, tag) Return a list of tufo props for the given tag (and down). Args: tufo ((str,dict)): A node in tuple form tag (str): A tag name Returns: synapse.lib.tags.iterTagDown(tag, div=’.’) Yield tags from top to bottom. Example: iterTagDown(‘foo.bar.baz’) -> (‘foo’,’foo.bar’,’foo.bar.baz’)
274 Chapter 4. synapse package Synapse Documentation, Release 0.0.34 synapse.lib.tags.iterTagUp(tag, div=’.’) Yield tags from top to bottom. Example: iterTagUp(‘foo.bar.baz’) -> (‘foo.bar.baz’,’foo.bar’,’foo’) synapse.lib.tags.tufoHasTag(tufo, tag) Returns True if the tufo has the given tag. Example: if tufoHasTag(tufo,’woot’): dostuff() synapse.lib.task module class synapse.lib.task.CallTask(call) Bases: synapse.lib.task.Task An extension for a runnable task. Args: call ((func,[],{})): A tuple of call details. class synapse.lib.task.Task(iden=None) Bases: synapse.eventbus.EventBus A cancelable Task abstraction which operates much like a Future but with some additional features. err(info) Fire an error return value for the task. Args: info (dict): Exception info dict (see synapse.common.excinfo ) get(prop, defval=None) Get a value from the info dict for the task. Args: prop (str): The name of the info value. defval (obj): The default value to return if not found
Returns: (obj): The object from the info dict (or None)
onretn(func) Provide a function to receive return values. The specififed callback will be called with a retn tuple defined as (ok,valu). If ok is True, valu is a return valu, if ok is False, valu is an excinfo dictionary. Args: func (function): Callback for a retn tuple. retn(valu) Fire a result return value for the task. Args: valu (obj): The return value run() Execute the task. set(prop, valu) Set a value in the info dict for the task. Args: prop (str): The name of the info dict value valu (obj): The value to set in the info dict
4.1. Subpackages 275 Synapse Documentation, Release 0.0.34 synapse.lib.thishost module synapse.lib.thishost.get(prop) Retrieve a property from the hostinfo dictionary. Example: import synapse.lib.thishost as s_thishost if s_thishost.get(‘platform’) == ‘windows’: dostuff() synapse.lib.thisplat module synapse.lib.threads module class synapse.lib.threads.Pool(size=3, maxsize=None) Bases: synapse.eventbus.EventBus A thread pool for firing and cleaning up threads. The Pool() class can be used to keep persistant threads for work processing as well as optionally spin up new threads to handle “bursts” of activity. # fixed pool of 16 worker threads pool = Pool(size=16) # dynamic pool of 5-10 workers pool = Pool(size=5, maxsize=10) # dynamic pool of 8- workers pool = Pool(size=8, maxsize=-1) call(func, *args, **kwargs) Call the given func(*args,**kwargs) in the pool. task(func, *args, **kwargs) Call the given function in the pool with a task. NOTE: Callers must use with-block syntax. Example: def foo(x): dostuff() def onretn(valu): otherstuff() with pool.task(foo, 10) as task: task.onretn(onretn) # the task is queued for execution after we # leave the with block. wrap(func) Wrap a function to transparently dispatch via the pool. Example: # dispatch the message handler from a pool bus.on(‘foo’, pool.wrap( doFooThing ) ) class synapse.lib.threads.RWLock Bases: object A multi-reader/exclusive-writer lock. reader() Acquire a multi-reader lock. Example: lock = RWLock()
276 Chapter 4. synapse package Synapse Documentation, Release 0.0.34
with lock.reader(): # other readers can be here too... dowrites() release(holder) Used to release an RWWith holder ( you probably shouldn’t use this ) writer() Acquire an exclusive-write lock. Example: lock = RWLock() with lock.writer(): # no readers or other writers but us! dowrites() class synapse.lib.threads.RWWith(rwlock) Bases: object The RWWith class implements “with block” syntax for RWLock. class synapse.lib.threads.Thread(func, *args, **kwargs) Bases: threading.Thread, synapse.eventbus.EventBus A thread / EventBus to allow fini() etc. run() class synapse.lib.threads.cancelable(func, *args, **kwargs) Bases: object Use these to allow cancelation of blocking calls (where possible) to shutdown threads. Example: with cancelable(sock.close): byts = sock.recv(100) synapse.lib.threads.current() synapse.lib.threads.iCantWait(name=None) Mark the current thread as a no-wait thread. Any no-wait thread will raise MustNotWait on blocking calls within synapse APIs to prevent deadlock bugs. Example: iCantWait(name=’FooThread’) synapse.lib.threads.iMayWait() Function for no-wait aware APIs to use while handling no-wait threads. Example: def mayWaitThing(): if not iMayWait(): return False waitForThing() synapse.lib.threads.iWillWait() Check if the current thread is a marked no-wait thead and raise MustNotWait. Example: def doBlockingThing(): iWillWait() waitForThing() synapse.lib.threads.iden() synapse.lib.threads.isfini() synapse.lib.threads.newtask(func, *args, **kwargs) synapse.lib.threads.withlock(lock)
4.1. Subpackages 277 Synapse Documentation, Release 0.0.34 synapse.lib.threads.worker(func, *args, **kwargs) Fire a worker thread to run the given func(*args,**kwargs) synapse.lib.time module
Time related utilities for synapse “epoch millis” time values. synapse.lib.time.parse(text, base=None, chop=False) Parse a time string into an epoch millis value. synapse.lib.time.repr(tick, pack=False) Return a date string for an epoch-millis timestamp. Args: tick (int): The timestamp in milliseconds since the epoch. Returns: (str): A date time string synapse.lib.trees module
A simple implementation of an interval tree to lookup potentially overlapping intervals from a point. class synapse.lib.trees.IntervalTree(ivals) Bases: object Construct an interval tree from the inputs. https://en.wikipedia.org/wiki/Interval_tree Example: ivals = ( ((1,30),{}), ((18,33),{}), ... ) itree = IntervalTree(ivals) for ival in itree.get(12): dostuff(ival) get(valu) Return intervals which contain the specified value. Example: for ival in itree.get(valu): dostuff(ival) synapse.lib.trigger module class synapse.lib.trigger.Triggers Bases: object add(func, perm) Add a new callback to the triggers. Args: func (function): The function to call perm (str,dict): The permission tufo Returns: (None) clear() Clear all previously registered triggers trigger(perm, *args, **kwargs) Fire any matching trigger functions for the given perm.
278 Chapter 4. synapse package Synapse Documentation, Release 0.0.34
Args: perm ((str,dict)): The perm tufo to trigger *args (list): args list to use calling the trigger function **kwargs (dict): kwargs dict to use calling the trigger function Returns: (None) synapse.lib.tufo module
Some common utility functions for dealing with tufos. synapse.lib.tufo.ephem(form, fval, **props) synapse.lib.tufo.equal(tuf0, tuf1) Since dicts are not comparible, this implements equality comparison for a given tufo by comparing and orders list of (prop,valu) pairs. Example: import synapse.lib.tufo as s_tufo tuf0 = s_tufo.tufo(‘foo’,bar=10,baz=20) tuf1 = s_tufo.tufo(‘foo’,baz=20,bar=10) if s_tufo.equal(tuf0,tuf1): print(‘woot’)
NOTE: This API is not particularly fast and is mostly for implementing tests. synapse.lib.tufo.ival(tufo, name) Return a min,max interval tuple or None for the node. Args: tufo ((str,dict)): A node in tuple form name (str): The name of the interval to return Returns: (int,int) An interval value ( or None ) synapse.lib.tufo.ndef(tufo) Return a node definition (