Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/suricata update #148

Open
wants to merge 222 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
222 commits
Select commit Hold shift + click to select a range
4d33ca1
- Abstracted YAMLConfig class
JaminB Jan 27, 2021
b0725bf
Added typing to process modules;
JaminB Feb 1, 2021
2a428b6
Added some additional comments;
JaminB Feb 2, 2021
ce19e8c
moved scripts/signatures/definitions to common module
JaminB Feb 5, 2021
a9d6aa7
Updated generic objects; first-pass at zeek script ConfigManager rewr…
JaminB Feb 8, 2021
d3faf5b
updated __str__ methods in several service_objects; first pass at bpf…
JaminB Feb 9, 2021
f77aadc
added GenericItem and GenericItemGroup as an additional layer of abst…
JaminB Feb 9, 2021
154ddcd
added local_network module; fixes to bpf_filter inheritance
JaminB Feb 9, 2021
ee89ed1
greatly simplified zeek installation
JaminB Feb 11, 2021
07c49d7
fixed a few issues that were preventing Zeek from starting with new c…
JaminB Feb 12, 2021
48788f6
removed a lot of exception handling from zeek and suricata installers;
JaminB Feb 12, 2021
21f8d2d
Added typing to several agent related services;
JaminB Feb 15, 2021
6d6bf79
removed redundant exception handling; moved some specific exceptions …
JaminB Feb 16, 2021
9ca25a1
padded unittests for node.cfg
JaminB Feb 17, 2021
b5def1d
a few configuration updates
JaminB Feb 18, 2021
04d2cc9
greatly simplify elasticsearch installation; and switched install to …
JaminB Feb 23, 2021
aa0316a
removed several unneeded installers; added new java and logstash inst…
JaminB Feb 24, 2021
2e60400
added kibana config/installer
JaminB Feb 25, 2021
7dffed2
updated ES bootstrapping process!!
JaminB Feb 27, 2021
0c910c9
fixed a few issues with ES bootstrapping
JaminB Mar 5, 2021
1e8e71d
removed uneeded exception modules; adding logging to install; added v…
JaminB Mar 9, 2021
04d88ae
Refactored zeek installer; updated the name of the mirror directory i…
JaminB Mar 10, 2021
8d29dd0
Addressed some issues with AFPacketNetworkInterface defaults; refacto…
JaminB Mar 10, 2021
ce3fd3c
Removed cumbersome components framework; replacing with more intuitiv…
JaminB Mar 12, 2021
2205c95
fixed some comments
JaminB Mar 12, 2021
cddc73c
stripped out old component framework; added some utility examples
JaminB Mar 12, 2021
e2a49f4
Added more shell endpoints
JaminB Mar 13, 2021
b64d0fa
added several more logs
JaminB Mar 15, 2021
acb669b
added filebeat and suricata loggers
JaminB Mar 16, 2021
fcbdac0
renamed directory; refactored
JaminB Mar 16, 2021
1af7fb3
added uninstallers
JaminB Mar 16, 2021
b8e5d64
added more config managers; updated docs; updated interface exporting
JaminB Mar 17, 2021
c0e6711
updated install readme for kibana; moved __init__ logic in root under…
JaminB Mar 17, 2021
0b9c5b6
Merge branch 'master' into release/dynamite-nsm-1.0
JaminB Mar 17, 2021
c5baa3c
Added two new commandline descriptions; updated const
JaminB Mar 17, 2021
4c66a0e
removed new restricted keywords
JaminB Mar 18, 2021
a36ea96
refactoring the way component/interface/subcomponent is selected
JaminB Mar 18, 2021
142db1a
made updater.py commandline invokable
JaminB Mar 18, 2021
8ca9955
cmd __main__.py interfaces now aligned to the same pattern
JaminB Mar 18, 2021
ede709e
removed some uneeded parameters
JaminB Mar 19, 2021
f4fd224
fixed issues with config loading
JaminB Mar 21, 2021
9f7d3c3
defaulted filebeat config to send direct to elasticsearch
JaminB Mar 21, 2021
1d4b246
- Added ES/Kibana post_installation_tasks as separate modules;
JaminB Mar 23, 2021
0871072
moved updater into a service module
JaminB Mar 23, 2021
35baaae
split up service_to_commandline.py into several modules within cmd pa…
JaminB Mar 24, 2021
3db74ff
More refactoring; added BaseInterface class for easier instance check…
JaminB Mar 24, 2021
016069e
Fixed several minor issues with parent parsers that were calling zeek…
JaminB Mar 25, 2021
6dfb4be
added suricata config parser; added usage instructions
JaminB Mar 25, 2021
0d08ffd
added more examples to README.md
JaminB Mar 25, 2021
4f746e1
[WIP] Tool for enumerating, installing and removing kibana saved obje…
louism-dynamiteai Mar 26, 2021
ee351ea
Feature/commandline modules (#99)
JaminB Mar 26, 2021
e9acc8d
started work on targets base class interface
JaminB Mar 26, 2021
e874170
small fix to get the MultipleRespInterface working
JaminB Mar 26, 2021
eb1858c
added stdout param to `services.kibana.package.SavedObjectsManager` (…
JaminB Mar 26, 2021
7b0b8c2
moved RESERVED_VARIABLES to more accessible location; added filebeat …
JaminB Mar 29, 2021
5ed5a17
add support for installing multiple ndjson files from an archive
louism-dynamiteai Mar 30, 2021
c052aba
add script, rename package add/remove to install/uninstall
louism-dynamiteai Mar 31, 2021
f6b8529
added dynamite commandline utility!
JaminB Mar 31, 2021
84e523e
Merge branch 'feature/kibana-packages-cmd' into feature/commandline-m…
JaminB Mar 31, 2021
78f287a
Some refactoring of the kibana package installer; added method explic…
JaminB Mar 31, 2021
ed02a92
removed TUIs
JaminB Apr 1, 2021
a510825
Add PackageManifest, use file list from validated manifest when impor…
louism-dynamiteai Apr 1, 2021
9af4748
Merge branch 'feature/kibana-packages-cmd' into feature/commandline-m…
JaminB Apr 2, 2021
401314e
Add InstalledPackages/InstalledPackagesSchema, handle error and succe…
louism-dynamiteai Apr 3, 2021
f806985
add pytest to setup and freeze deps
louism-dynamiteai Apr 3, 2021
ae8207e
passed through environ to base install class; added the ability to up…
JaminB Apr 3, 2021
4951661
Adding SDK documentation
JaminB Apr 6, 2021
24b018b
add class schemas and index mappings for managing installed package m…
louism-dynamiteai Apr 6, 2021
567b6e4
added remaining zeek service documentation; as well as starting suricata
JaminB Apr 6, 2021
2de6683
Added some documentation sections
JaminB Apr 7, 2021
2fa59d6
added tons of contextual documentation
JaminB Apr 7, 2021
8085ad6
added more documentation; and converted several more module docstring…
JaminB Apr 8, 2021
e489944
Process resp from kibana object install to InstalledObject instance a…
louism-dynamiteai Apr 8, 2021
bceeee8
remove whitespace
louism-dynamiteai Apr 8, 2021
3b2f6c7
Added several new SDK endpoints and a ton of new documentation
JaminB Apr 9, 2021
e61abf6
List packages and number of objects by type on command, make some pac…
louism-dynamiteai Apr 9, 2021
8d264dd
Merge branch 'feature/commandline-modules' into release/dynamite-nsm-1.0
JaminB Apr 13, 2021
47557b4
Merge branch 'feature/SDK-docs' into release/dynamite-nsm-1.0
JaminB Apr 13, 2021
f6ae396
Alter mapping for installed packages data, Store more package metadat…
louism-dynamiteai Apr 13, 2021
fa7ebf4
added very basic node stub
JaminB Apr 14, 2021
6e5e9ec
Merge branch 'feature/kibana-packages-cmd' into release/dynamite-nsm-1.0
JaminB Apr 14, 2021
66fe16f
fix zeek network config comment/blank line parsing issue, use __getit…
louism-dynamiteai May 4, 2021
b9ae6bf
reintroduce filebeat install manager validate_targets function
louism-dynamiteai May 6, 2021
0e8325c
update to properly handle subdirectories in dynamite_nsm.utilities.la…
louism-dynamiteai May 10, 2021
38bc864
[WIP] ConfigManager tests for services (#104)
louism-dynamiteai May 11, 2021
3260b33
Kibana Package Manager + Commandline Modules (#100)
JaminB May 11, 2021
65b6e3e
Feature/remote node service (#107)
JaminB May 11, 2021
f422cde
added some additional documentation; minor formatting to some tests
DynamiteDocker May 11, 2021
583bd67
Merge remote-tracking branch 'origin/release/dynamite-nsm-1.0' into r…
DynamiteDocker May 11, 2021
96e9dde
added some missing doc files
JaminB May 11, 2021
35aa0f3
Merge remote-tracking branch 'origin/release/dynamite-nsm-1.0' into r…
JaminB May 11, 2021
ea98c64
Merge branch 'release/dynamite-nsm-1.0' of https://github.com/Dynamit…
DynamiteDocker May 11, 2021
5912b12
added submodule
DynamiteDocker May 12, 2021
d54c727
added configurations dir
DynamiteDocker May 12, 2021
032e3d2
added configurations submodule
DynamiteDocker May 12, 2021
623ec00
updated README.md
DynamiteDocker May 12, 2021
8586006
README update
DynamiteDocker May 12, 2021
264a9e9
README update
DynamiteDocker May 12, 2021
3fd1ec9
Update README.md
JaminB May 12, 2021
6a8f052
added new submodule
DynamiteDocker May 12, 2021
11b925e
Update README.md
JaminB May 12, 2021
999ec4b
Update README.md
JaminB May 12, 2021
53ab9d4
added utilities submodule
DynamiteDocker May 12, 2021
1e32986
added utilities submodule
DynamiteDocker May 12, 2021
4d4bac5
Merge branch 'docs/dynamite-1.0-docs' of https://github.com/DynamiteA…
DynamiteDocker May 12, 2021
782fbe6
added extras
DynamiteDocker May 12, 2021
2179fdc
add from_raw_text where missing and alter existing to work with hardc…
louism-dynamiteai May 12, 2021
06367d9
refactored kibana package manager
DynamiteDocker May 13, 2021
4cd7706
fixed several issues discovered during testing; improved uninstall ex…
DynamiteDocker May 14, 2021
e6ac638
fixed issue when invoking multresp interfaces from main commandline;
DynamiteDocker May 14, 2021
749966c
some minor changes to username, passwrod are passed in
DynamiteDocker May 14, 2021
26de1b6
added diagram
DynamiteDocker May 14, 2021
d4311db
Update README.md
JaminB May 14, 2021
9c6c4c1
Update README.md
JaminB May 14, 2021
f52cc7d
Update README.md
JaminB May 14, 2021
466abd6
comment updates
DynamiteDocker May 14, 2021
1f5f997
Merge remote-tracking branch 'origin/feature/kibana-package-manager-r…
DynamiteDocker May 14, 2021
586e8e6
updated README.md
DynamiteDocker May 14, 2021
10541b2
Update README.md
JaminB May 14, 2021
c2bf4fe
Update README.md
JaminB May 14, 2021
7f41ae5
refactored kibana package manager (#109)
JaminB May 14, 2021
c3a86c8
add list-spaces command
louism-dynamiteai May 14, 2021
fde7a7a
Merge branch 'feature/kibana-package-manager-refactor' of github.com:…
louism-dynamiteai May 14, 2021
452894b
Added some more README text
DynamiteDocker May 17, 2021
e56cc00
Merge remote-tracking branch 'origin/docs/dynamite-1.0-docs' into doc…
DynamiteDocker May 17, 2021
f11296a
Update README.md
JaminB May 17, 2021
e73777f
Update README.md
JaminB May 17, 2021
7f488f1
Create README.md
JaminB May 17, 2021
347ef8d
Update README.md
JaminB May 17, 2021
9dbd2bb
Ability to install package to a specific tenant, rename space/spaces …
louism-dynamiteai May 18, 2021
610e352
added an agent service; deleted lab service; added some docstrings
DynamiteDocker May 18, 2021
4c2314a
fix broken kibanau in post package install to different tenant, tenan…
louism-dynamiteai May 18, 2021
21a9320
added optimize logic for negotiating threading between Zeek/Suricata
DynamiteDocker May 19, 2021
eecb315
added job logic and agent process module
DynamiteDocker May 19, 2021
2a6deca
fix bug in list command; fix bug where similarly named packages may b…
louism-dynamiteai May 19, 2021
c8b2d03
show tenant for packages on uninstall list
louism-dynamiteai May 19, 2021
b8f983a
check tenant validity before proceeding if tenant is provided
louism-dynamiteai May 19, 2021
63692a4
improved error handling when a security exception/403 occurs.
louism-dynamiteai May 19, 2021
04ffec7
Merge remote-tracking branch 'origin/feature/kibana-package-install-t…
DynamiteDocker May 20, 2021
d457dbf
Fix uninstall by id, improve assisted uninstall query by package name…
louism-dynamiteai May 20, 2021
4ca4ec5
Added monitor installation/process management logic
DynamiteDocker May 20, 2021
1865ab7
Merge remote-tracking branch 'origin/feature/kibana-package-install-t…
DynamiteDocker May 20, 2021
6fa4720
Added task base classes and incorporated them into installers
DynamiteDocker May 21, 2021
0313d3a
Added monitor compatibility and better representation of various results
DynamiteDocker May 21, 2021
04a4fcd
process formatting for agent; added uninstall logic for crontab
DynamiteDocker May 21, 2021
bdb1de6
Added a basic quickstart guide
DynamiteDocker May 25, 2021
835190e
Delete .DS_Store
JaminB May 26, 2021
b594d6c
updated the config_object_interfaces.py for Zeek scripts/rules to han…
DynamiteDocker May 26, 2021
b499734
Merge branch 'docs/dynamite-1.0-docs' of https://github.com/DynamiteA…
DynamiteDocker May 27, 2021
0c52773
More SDK documentation; re-oriented guides around more traditional fo…
DynamiteDocker Jun 2, 2021
cbb5edc
More SDK documentation; moved some guides out into more appropiate se…
DynamiteDocker Jun 2, 2021
a959a6e
Add warning about the importance of the order that files appear in th…
louism-dynamiteai Jun 2, 2021
4d96686
added some more tutorials; fixed some file names
DynamiteDocker Jun 2, 2021
9f57900
Merge remote-tracking branch 'origin/docs/dynamite-1.0-docs' into doc…
DynamiteDocker Jun 2, 2021
e7d66f0
fill out the 'working with kibana package manager' guide
louism-dynamiteai Jun 2, 2021
4603607
Merge branch 'docs/dynamite-1.0-docs' of github.com:DynamiteAI/dynami…
louism-dynamiteai Jun 2, 2021
d5352a4
add more detail to installation usage guide
louism-dynamiteai Jun 2, 2021
95f0698
formatting and styling
louism-dynamiteai Jun 2, 2021
76e44b7
more docs; added contributing guide
DynamiteDocker Jun 3, 2021
1f7134a
added missing visualisations. Updated index contributing section
DynamiteDocker Jun 3, 2021
9a968fb
Updated documentation; Fixed some duplicate code in cmd *interfaces. …
DynamiteDocker Jun 7, 2021
38a49d2
added more service documentation and some place holder files
DynamiteDocker Jun 8, 2021
c710bce
added more docs
DynamiteDocker Jun 15, 2021
a986146
updated config version
DynamiteDocker Jun 16, 2021
b145626
removed old configurations file bumped version in setup.py
DynamiteDocker Jun 16, 2021
cd19ef4
added centos 7 specific setup guide
DynamiteDocker Jun 16, 2021
c83669b
added logic to handle update checking; corrected bug where the url va…
DynamiteDocker Jun 16, 2021
2ca2280
slight change to cluster settings
DynamiteDocker Jun 16, 2021
2af47ee
reduced log name padding
DynamiteDocker Jun 16, 2021
cdef40d
simplified downloader
DynamiteDocker Jun 16, 2021
c2e83c3
fixed char spacing
DynamiteDocker Jun 16, 2021
c34bda6
IndexTemplateSettings did not include enable and overwrite fields
DynamiteDocker Jun 16, 2021
1055d42
added ubuntu guide
DynamiteDocker Jun 17, 2021
0422943
Merge remote-tracking branch 'origin/bug/fix-zeeknetwork-parsing' int…
DynamiteDocker Jun 17, 2021
0bcae6a
Bug/fix zeeknetwork parsing (#110)
JaminB Jun 17, 2021
0c16b6b
added configure_cluster tasks to replace post_installation_tasks; add…
DynamiteDocker Jun 18, 2021
c7e4949
Updated operating system guides
DynamiteDocker Jun 18, 2021
f25883d
Updated operating system guides
DynamiteDocker Jun 23, 2021
1bac849
Moved image out of docs dir
DynamiteDocker Jun 23, 2021
c0535e2
or not and when displaying results (#112)
louism-dynamiteai Jun 23, 2021
9be5509
Multitenancy support, improved error handling, addition of list-tenan…
louism-dynamiteai Jun 23, 2021
070bf52
Update overview page.
pmphry Jun 23, 2021
07ff3b2
Add documentation for modules and views.
apdynai Jun 23, 2021
4345e4d
updated doc strings; added docs
DynamiteDocker Jun 24, 2021
fff3e58
Update README.md
JaminB Jun 24, 2021
5bc9f0f
updated submodule
DynamiteDocker Jun 24, 2021
815ff4e
added mkdocstrings
DynamiteDocker Jun 24, 2021
ceac85e
added more SDK documentation; create_dynamite_user now passes in `sys…
DynamiteDocker Jun 24, 2021
b6e4c95
Merge remote-tracking branch 'origin/release/dynamite-nsm-1.0' into r…
DynamiteDocker Jun 24, 2021
6cb8c6c
Update README.md
JaminB Jun 24, 2021
cf7ef9d
Update README.md
JaminB Jun 24, 2021
b33cb21
Update README.md
JaminB Jun 24, 2021
67a7301
Update README.md
JaminB Jun 24, 2021
9297349
Update README.md
JaminB Jun 24, 2021
c60f036
Updated tasks to pull down base views package
DynamiteDocker Jun 24, 2021
22eadca
Merge remote-tracking branch 'origin/release/dynamite-nsm-1.0' into r…
DynamiteDocker Jun 24, 2021
21aadbf
Update README.md
JaminB Jun 24, 2021
f53ea01
Update README.md
JaminB Jun 24, 2021
00c8ba1
dynamite user now properly created
DynamiteDocker Jun 24, 2021
caf666c
Added --with-latest-kernel flag to AF_PACKET setup
DynamiteDocker Jun 24, 2021
83a2485
added some additional classifiers in setup.py
DynamiteDocker Jun 24, 2021
3fa9658
Merge branch 'release/dynamite-nsm-1.0'
DynamiteDocker Jun 24, 2021
05191f2
Merge branch 'master' of https://github.com/DynamiteAI/dynamite-nsm
DynamiteDocker Jul 8, 2021
e4e4bf5
Merge branch 'master' of https://github.com/DynamiteAI/dynamite-nsm
DynamiteDocker Aug 17, 2021
9bb814f
Merge branch 'master' of https://github.com/DynamiteAI/dynamite-nsm
DynamiteDocker Sep 2, 2021
e2cf677
Merge branch 'master' of https://github.com/DynamiteAI/dynamite-nsm
DynamiteDocker Sep 28, 2021
0c80ead
Merge branch 'master' of https://github.com/DynamiteAI/dynamite-nsm
DynamiteDocker Nov 10, 2021
a9a463a
Merge branch 'master' of https://github.com/DynamiteAI/dynamite-nsm
DynamiteDocker Dec 20, 2021
8207765
Merge branch 'master' of https://github.com/DynamiteAI/dynamite-nsm
DynamiteDocker Feb 10, 2022
2458a0e
Merge branch 'master' of https://github.com/DynamiteAI/dynamite-nsm
DynamiteDocker Feb 10, 2022
33f6575
Merge branch 'master' of https://github.com/DynamiteAI/dynamite-nsm
DynamiteDocker Feb 15, 2022
c992858
added suricata-update related configuration wrappers
DynamiteDocker Feb 18, 2022
1a21307
added logic to handle updating of suricata rules
DynamiteDocker Feb 18, 2022
da70242
Stubbed out basic funcionality for a suricata rules interface, backed…
DynamiteDocker Feb 21, 2022
f78f1a0
added some additional logic for rule editing and cache management
DynamiteDocker Feb 22, 2022
66d2eb9
fixed several more issues with literal string parsing
DynamiteDocker Feb 25, 2022
58e6c3f
incorporated database logic into RuleFile rather so local caches buil…
DynamiteDocker Mar 1, 2022
d4fc24a
removed old database module which has been integrated directly into t…
DynamiteDocker Mar 3, 2022
557e83a
we weren't building the cache before merging in
DynamiteDocker Mar 3, 2022
7b32c61
fixed parsing issue where spaces were included in source/port dest/po…
DynamiteDocker Mar 4, 2022
6e0206e
fixed several issues with merge function; added prune method to preve…
DynamiteDocker Mar 8, 2022
1269422
added bulk enable/disable rule by classtype methods
DynamiteDocker Mar 8, 2022
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 24 additions & 9 deletions dynamite_nsm/services/base/tasks.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,30 @@
import os
import sys
import logging
import requests
import subprocess
from time import sleep
import crontab

from typing import List, Optional, Tuple

from dynamite_nsm import const
from dynamite_nsm import utilities
from typing import List, Optional, Tuple
from dynamite_nsm.logger import get_logger


class BaseTask:
def __init__(self, name: str, package_link: Optional[str] = None, description: Optional[str] = None):
def __init__(self, name: str, package_link: Optional[str] = None, description: Optional[str] = None,
verbose: Optional[bool] = False, stdout: Optional[bool] = True):
self.name = name
self.package_link = package_link
self.description = description
log_level = logging.INFO
if verbose:
log_level = logging.DEBUG
self.stdout = stdout
self.verbose = verbose
self.logger = get_logger(str(name), level=log_level, stdout=stdout)

def download_and_install(self):
raise NotImplemented()
Expand All @@ -24,11 +35,13 @@ def invoke(self):

class BaseShellCommandsTask(BaseTask):

def __init__(self, name: str, package_link: str, commands: List[List[str]], description: Optional[str] = None):
super().__init__(name, package_link, description)
def __init__(self, name: str, package_link: str, commands: List[List[str]], description: Optional[str] = None,
verbose: Optional[bool] = False, stdout: Optional[bool] = True):
super().__init__(name, package_link, description, stdout=stdout, verbose=verbose)
self.commands = commands

def invoke(self, shell: Optional[bool] = False, cwd: Optional[str] = os.getcwd()) -> List[Tuple[List, bytes, bytes]]:
def invoke(self, shell: Optional[bool] = False, cwd: Optional[str] = os.getcwd()) -> List[
Tuple[List, bytes, bytes]]:
results = []
for command in self.commands:
if not shell:
Expand Down Expand Up @@ -62,13 +75,15 @@ def remove_cronjob(self):

class BaseShellCommandTask(BaseShellCommandsTask):

def __init__(self, name: str, package_link: str, command: str, args: List[str], description: Optional[str] = None):
def __init__(self, name: str, package_link: str, command: str, args: List[str], description: Optional[str] = None,
verbose: Optional[bool] = False, stdout: Optional[bool] = True):
command = [
command
]
command.extend(args)

super().__init__(name, commands=[command], package_link=package_link, description=description)
super().__init__(name, commands=[command], package_link=package_link, description=description, verbose=verbose,
stdout=stdout)
self.command = command
self.args = args

Expand All @@ -92,8 +107,8 @@ def __init__(self, name: str, kibana_package_link: Optional[str] = None, usernam
password: Optional[str] = 'admin',
target: Optional[str] = f'http://{utilities.get_primary_ip_address()}:5601',
tenant: Optional[str] = '',
description: Optional[str] = ''):
super().__init__(name, kibana_package_link, description)
description: Optional[str] = '', verbose: Optional[bool] = False, stdout: Optional[bool] = True):
super().__init__(name, kibana_package_link, description, verbose=verbose, stdout=stdout)
self.username = username
self.password = password
self.target = target
Expand Down
192 changes: 190 additions & 2 deletions dynamite_nsm/services/suricata/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,36 @@

from yaml import Loader
from yaml import load
from suricata.update import config
from suricata.update import sources
from suricata.update.commands.enablesource import write_source_config

from dynamite_nsm import exceptions as general_exceptions

from dynamite_nsm import const, utilities
from dynamite_nsm.services.base import install
from dynamite_nsm.services.base.config import YamlConfigManager
from dynamite_nsm import exceptions as general_exceptions
from dynamite_nsm.services.base.config import YamlConfigManager, GenericConfigManager
from dynamite_nsm.services.base.config_objects.suricata import misc, rules


class SourceAlreadyExists(Exception):
def __init__(self, name):
msg = f"This source ({name}) already exists. You must first remove it before it can be added again."
super(SourceAlreadyExists, self).__init__(msg)


class SourceUrlMissing(Exception):
def __init__(self, name):
msg = f"You must specify a URL for this source ({name})."
super(SourceUrlMissing, self).__init__(msg)


class SourceSecretMissing(Exception):
def __init__(self, name):
msg = f"You must specify a secret for this source ({name})."
super(SourceSecretMissing, self).__init__(msg)


def lookup_rule_definition(rule_id: str) -> Dict:
"""Return the definition, categories, and friendly_name of a given script
Args:
Expand Down Expand Up @@ -280,3 +301,170 @@ def commit(self, out_file_path: Optional[str] = None, backup_directory: Optional
self._af_packet_interfaces_raw = self.af_packet_interfaces.get_raw()
self._threading_raw = self.threading.get_raw()
super(ConfigManager, self).commit(out_file_path, backup_directory, top_text=top_text)


class UpdateConfigManager(YamlConfigManager):

def __init__(self, configuration_directory: str, verbose: Optional[bool] = False, stdout: Optional[bool] = True):
extract_tokens = {
'disable_conf': ('disable-conf',),
'enable_conf': ('enable-conf',),
'modify_conf': ('modify-conf',),
'ignore': ('ignore',),
'sources': ('sources',),
'local': ('local',)
}
self.disable_conf = None
self.enable_conf = None
self.modify_conf = None
self.ignore = None
self.sources = None
self.local = None

self.configuration_directory = configuration_directory
self.suricata_config_file = os.path.join(self.configuration_directory, 'update.yaml')
try:
with open(self.suricata_config_file, 'r') as configyaml:
self.config_data_raw = load(configyaml, Loader=Loader)
except (IOError, ValueError):
raise general_exceptions.ReadConfigError(f'Failed to read or parse {self.suricata_config_file}.')

super().__init__(self.config_data_raw, name='suricata.update.config', verbose=verbose, stdout=stdout,
**extract_tokens)

self.parse_yaml_file()

def commit(self, out_file_path: Optional[str] = None, backup_directory: Optional[str] = None,
top_text: Optional[str] = None) -> None:
if not out_file_path:
out_file_path = f'{self.configuration_directory}/update.yaml'
super(UpdateConfigManager, self).commit(out_file_path, backup_directory, top_text=top_text)


class SourcesConfigManager(GenericConfigManager):

DEFAULT_SOURCE = 'et/open'

def __init__(self, configuration_directory: str, verbose: Optional[bool] = False,
stdout: Optional[bool] = True):
self.configuration_directory = configuration_directory
config.DEFAULT_DATA_DIRECTORY = f'{self.configuration_directory}/data/'
config.DEFAULT_UPDATE_YAML_PATH = f'{self.configuration_directory}/update.yaml'
config.DEFAULT_SURICATA_YAML_PATH = [f'{self.configuration_directory}/suricata.yaml']
self.config = config
self.source_index = sources.load_source_index(config)
super().__init__({}, 'suricata.update.sources', verbose, stdout)

@staticmethod
def _format_sources_as_list(raw_sources: Dict) -> List[Dict]:
new_sources = []
for k, v in raw_sources.items():
v.update({'name': k})
if v.get('min-version'):
v['min_version'] = v.pop('min-version')
if v.get('support-url'):
v['support-url'] = v.pop('support-url')
new_sources.append(v)
return new_sources

def _enable_index_source(self, name: str, secret: Optional[str] = None):
source_directory = sources.get_source_directory()
source = self.source_index.get_sources()[name]
source_parameters = source.get('parameters', {})
if 'secret-code' in source_parameters:
if not secret:
raise SourceSecretMissing(name)
source_parameters['secret-code'] = secret
if 'checksum' in source:
checksum = source["checksum"]
else:
checksum = source.get("checksum", True)
new_source = sources.SourceConfiguration(
name, params=source_parameters, checksum=checksum)
if not os.path.exists(source_directory):
utilities.makedirs(source_directory)
if "replaces" in source and self.DEFAULT_SOURCE in source["replaces"]:
self.logger.debug("Not enabling default source as selected source replaces it")
elif new_source.name == self.DEFAULT_SOURCE:
self.logger.debug(
"Not enabling default source as selected source is the default")
else:
self.logger.info(f"Enabling default source {self.DEFAULT_SOURCE}")
if not self.source_index.get_source_by_name(self.DEFAULT_SOURCE):
self.logger.error(f"Default source {self.DEFAULT_SOURCE} not in index")
else:
default_source_config = sources.SourceConfiguration(self.DEFAULT_SOURCE)
write_source_config(default_source_config, True)
write_source_config(new_source, True)
self.logger.info(f'Source {str(new_source)} enabled.')
if "replaces" in source:
for replaces in source["replaces"]:
filename = sources.get_enabled_source_filename(replaces)
if os.path.exists(filename):
os.unlink(filename)

def add_source(self, name: str, url: Optional[str] = None, secret: Optional[str] = None,
header: Optional[str] = None) -> None:
"""Add a source from an index of known public sources, or add a source from a custom URL
Args:
name: The name of the source to add, if not found within the index a new one will be created
url: The url where the rules can be downloaded
secret: A secret key required to retrieve some commercial rule-sets
header: An http header sometimes required when basic HTTP authentication is used

Returns:
None
"""
enabled_source_filename = sources.get_enabled_source_filename(name)
if os.path.exists(enabled_source_filename):
raise SourceAlreadyExists(name)

if name not in self.source_index.get_sources():
if not url:
raise SourceUrlMissing(name)
checksum = None
if sources.source_name_exists(name):
raise SourceAlreadyExists(name)
source_config = sources.SourceConfiguration(
name, header=header, url=url, checksum=checksum)
sources.save_source_config(source_config)
else:
self._enable_index_source(name, secret)

def list_enabled_sources(self) -> List[Dict]:
"""Get enabled sources
Returns:
A list of enabled sources
"""
self.logger.debug(f'Fetching enabled sources from {sources.get_source_directory()}')
return self._format_sources_as_list(sources.get_enabled_sources())

def list_available_sources(self) -> List[Dict]:
"""Get all available sources
Returns:
A list of available sources
"""
return self._format_sources_as_list(sources.load_source_index(self.config).get_sources())

def remove_source(self, name: str) -> None:
"""Remove a source
Args:
name: The name of the source
Returns:
None
"""
enabled_source_filename = sources.get_enabled_source_filename(name)
if os.path.exists(enabled_source_filename):
self.logger.debug(f"Deleting file {enabled_source_filename}.")
os.remove(enabled_source_filename)
self.logger.info(f"Source {name} removed, previously enabled.")
disabled_source_filename = sources.get_disabled_source_filename(name)
if os.path.exists(disabled_source_filename):
self.logger.debug(f"Deleting file {disabled_source_filename}.", )
os.remove(disabled_source_filename)
self.logger.info(f"Source {name} removed, previously disabled.")


if __name__ == '__main__':
s = SourcesConfigManager('/etc/dynamite/suricata/')
s.remove_source('et/open')
8 changes: 8 additions & 0 deletions dynamite_nsm/services/suricata/install.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,8 @@ def setup(self, inspect_interfaces: List[str]):
self.create_update_suricata_environment_variables()
self.logger.debug(f'Creating directory: {self.configuration_directory}')
utilities.makedirs(self.configuration_directory)
self.logger.debug(f'Creating directory: {self.configuration_directory}/data')
utilities.makedirs(f'{self.configuration_directory}/data')
self.logger.debug(f'Creating directory: {self.install_directory}')
utilities.makedirs(self.install_directory)
self.logger.debug(f'Creating directory: {self.log_directory}')
Expand All @@ -181,6 +183,10 @@ def setup(self, inspect_interfaces: List[str]):
f'{const.DEFAULT_CONFIGS}/suricata/suricata.yaml',
self.configuration_directory
)
self.copy_file_or_directory_to_destination(
f'{const.DEFAULT_CONFIGS}/suricata/update.yaml',
self.configuration_directory
)

suricata_config = config.ConfigManager(self.configuration_directory, stdout=self.stdout, verbose=self.verbose)
suricata_config.default_log_directory = self.log_directory
Expand Down Expand Up @@ -212,6 +218,8 @@ def setup(self, inspect_interfaces: List[str]):
utilities.set_ownership_of_file(self.install_directory, user='dynamite', group='dynamite')
utilities.set_ownership_of_file(self.log_directory, user='dynamite', group='dynamite')
utilities.set_permissions_of_file(f'{self.configuration_directory}/suricata.yaml', 660)
utilities.set_permissions_of_file(f'{self.configuration_directory}/update.yaml', 660)
utilities.set_permissions_of_file(f'{self.configuration_directory}/data', 770)
post_install_bootstrap_updater(self.install_directory, stdout=self.stdout, verbose=self.verbose)

self.logger.info('Setting up Suricata capture rules for dynamite user.')
Expand Down
4 changes: 4 additions & 0 deletions dynamite_nsm/services/suricata/rules/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@




Loading