1728 Commits

Author SHA1 Message Date
Christopher McCarthy
2b93941a6b Merged PR 478: merged 3.0.0 into main for git history alignment
merged 3.0.0 into main for git history alignment

Related work items: #2457, #2472, #2536, #2552, #2560, #2561, #2563, #2570, #2588, #2606, #2626, #2628, #2637, #2639
2024-07-22 13:24:33 +00:00
Defence Science and Technology Laboratory UK
7f9acc4329 Automated benchmark output commit for version 3.0.0 [skip ci] 2024-07-20 16:11:46 +00:00
Chris McCarthy
213e301e58 retrospectively benchmarked 3.0.0 using the new benchmark process 2024-07-20 15:05:56 +01:00
Archer Bowen
3eacad200e Merged PR 408: User Guide & Notebook changes to align with 3.0.0+internal
## Summary

They are a few changes made in 3.0.0-internal that cannot be synced up.
For example, some of the RLIB Notebooks were changed around to use uc6 or tap003 which don't exist in 3.0.0:
![image (2).png](https://dev.azure.com/ma-dev-uk/b50a61ee-86c4-48bc-9a0b-a67645ba12ee/_apis/git/repositories/2825053e-bd3b-45b2-8680-1281809eefa2/pullRequests/408/attachments/image%20%282%29.png)

Additionally, as my python env is different to that of the pipeline there is some meta-data differences such as:
![image.png](https://dev.azure.com/ma-dev-uk/b50a61ee-86c4-48bc-9a0b-a67645ba12ee/_apis/git/repositories/2825053e-bd3b-45b2-8680-1281809eefa2/pullRequests/408/attachments/image.png)

Which I'm pretty certain will sort it self out after the pipeline is finished.
2024-06-10 14:47:47 +00:00
Marek Wolan
d1bbab71b7 Updated session_output_writer.py 2024-06-10 14:46:06 +00:00
Marek Wolan
2d54d482a0 Updated session_output_reader.py 2024-06-10 14:45:56 +00:00
Marek Wolan
c538aee022 Rename benchmark variables and add h1 to notebooks 2024-06-10 12:58:07 +01:00
Chris McCarthy
05a6a4f7bd added manual benchmark pdf report and graphs 2024-06-10 11:12:41 +01:00
Archer.Bowen
2a6a16b222 Space inbetween title to prevent merge conflicts. 2024-06-10 10:50:58 +01:00
Archer.Bowen
af0e67a61a User-Guide update: Very minor changes to notebook code cells to match release version identically. 2024-06-10 10:41:05 +01:00
Archer.Bowen
1ad3adbec2 Merge remote-tracking branch 'origin/release/3.0.0' into user-guide-feedback-core-fixes 2024-06-10 09:54:02 +01:00
Chris McCarthy
4068231547 Refactored the benchmarking process 2024-06-07 19:59:55 +01:00
Archer.Bowen
ae242694f3 Minor change to title to prevent merge conflicts. 2024-06-07 17:13:21 +01:00
Archer.Bowen
146afea44f Updated copyright clause on .rst 2024-06-07 16:44:33 +01:00
Archer.Bowen
2954ca966f Updated core user guide to match exactly that of 3.0.0/internal. 2024-06-07 16:35:33 +01:00
Archer.Bowen
29d42a88dc Core user guide updated to reflect changes made down stream. 2024-06-07 14:48:22 +01:00
Archer.Bowen
71e0c4179e Merge branch 'user-guide-feedback-core-fixes' of https://dev.azure.com/ma-dev-uk/PrimAITE/_git/PrimAITE into user-guide-feedback-core-fixes 2024-06-03 15:51:55 +01:00
Archer.Bowen
18e6886381 User guide updates 2024-06-03 15:51:14 +01:00
Czar Echavez
3bad9aa51e #2628: committing to be reviewed 2024-06-01 13:23:27 +01:00
Czar Echavez
472040aa70 Merge remote-tracking branch 'origin/dev' into feature/2628-update-benchmarking-script-branched 2024-06-01 00:20:21 +01:00
Archer Bowen
c705a15d00 Merged PR 397: User Guide Feed Back Core Changes
Further changes to be made post sync.
2024-05-31 17:55:27 +00:00
Marek Wolan
2406579c78 format using precommit 2024-05-31 18:50:56 +01:00
Archer.Bowen
9f0c6ddbb4 Fix primaite dependencies formatting issue 2024-05-31 18:18:40 +01:00
Archer.Bowen
4a9b92eab1 Removing data-manp notebook outputs 2024-05-31 17:17:07 +01:00
Archer.Bowen
93a729029c Merge remote-tracking branch 'origin/dev' into user-guide-feedback-core-fixes 2024-05-31 17:13:27 +01:00
Archer.Bowen
0ac57147cd Updated index following new primAITE 2 Pager 2024-05-31 17:05:30 +01:00
Marek Wolan
262390b74d Merged PR 396: Merge fixes for bugs found during testing and updates to docs
- Merge branch 'feature/2588-minimal-deps' into bugfix/2626-too-many-open-files
- #2626 fix too many open files bug
- Merge remote-tracking branch 'origin/dev' into bugfix/reward-logging
- fix reward logging
- Merge remote-tracking branch 'origin/dev' into bugfix/reward-logging
- get ray to stop crashing
- Merged PR 394: Fix 'too many open files'
- Merged PR 395: Fix reward logging and get ray to stop complaining
- Fix firewall diagram

Related work items: #2588, #2626
2024-05-31 15:47:41 +00:00
Marek Wolan
f9cff42856 glossary fact check 2024-05-31 16:03:47 +01:00
Marek Wolan
97d4c38298 remove tests from api docs 2024-05-31 15:56:27 +01:00
Chris McCarthy
4d61e857df dropped the automatic creation of primaite-dependencies.rst and made it manual as we now only need immediate dependencies 2024-05-31 15:42:41 +01:00
Marek Wolan
4ee29d129d Fix firewall diagram 2024-05-31 15:41:40 +01:00
Marek Wolan
53f01ca1e1 Merged PR 395: Fix reward logging and get ray to stop complaining
## Summary
Change the agent history log to also spit out rewards correctly.
Make ray adhere to new ray API

## Test process
Unit test pass
All notebooks run without crash

## Checklist
- [ ] PR is linked to a **work item**
- [ ] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [x] attended to any **TO-DOs** left in the code
2024-05-31 14:38:05 +00:00
Marek Wolan
f7cb5bd370 Merged PR 394: Fix 'too many open files'
## Summary
Add a method to PCAP to clear file handlers. Invoke this method while resetting environment.

## Test process
no longer crashes on windows when i run too many episodes

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [n] written **tests** for any new functionality added with this PR
- [n] updated the **documentation** if this PR changes or adds functionality
- [n] written/updated **design docs** if this PR implements new functionality
- [n] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [x] attended to any **TO-DOs** left in the code

Related work items: #2588, #2626
2024-05-31 14:31:25 +00:00
Marek Wolan
e48b71ea1a get ray to stop crashing 2024-05-31 15:25:08 +01:00
Czar Echavez
5f02846879 #2628: commit changes to combined av per episode 2024-05-31 15:20:10 +01:00
Marek Wolan
46ef3b8041 Merge remote-tracking branch 'origin/dev' into bugfix/reward-logging 2024-05-31 15:00:25 +01:00
Marek Wolan
c5f131ece5 fix reward logging 2024-05-31 15:00:18 +01:00
Marek Wolan
acfe49fd9f Merged PR 389: #2588 optional RL deps
## Summary
Make it optional to install ray, sb3, and their dependencies.

## Test process
pytest and notebooks

## Checklist
- [ ] PR is linked to a **work item**
- [ ] **acceptance criteria** of linked ticket are met
- [ ] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [ ] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

#2588 optional RL deps

Related work items: #2588
2024-05-31 13:17:27 +00:00
Archer.Bowen
71190a41c2 Fix to red agent image not loading 2024-05-31 14:10:01 +01:00
Marek Wolan
04dc486708 Merge remote-tracking branch 'origin/dev' into bugfix/reward-logging 2024-05-31 14:01:34 +01:00
Archer.Bowen
efc4e3e9b0 Core User Guide Feeedback Implemented.
Feedback Issues left:

1.Issues with red-agent image not embeded correctly in data_manipulation_e2e notebook

2._autosummary/tests.unit_tests.html is still completely blank.

3. _index.html is not updated with new 2-pager

4. _dependencies is not updated to just include tier-1 and primary for v3.

5. definiton of user_app_home is not confirmed
2024-05-31 13:55:20 +01:00
Czar Echavez
add8cc0ab1 #2628: temp commit 2024-05-31 13:47:02 +01:00
Marek Wolan
10ff2e008e Merge remote-tracking branch 'origin/dev' into feature/2588-minimal-deps 2024-05-31 13:31:22 +01:00
Marek Wolan
f8336d07bd #2626 fix too many open files bug 2024-05-31 13:28:56 +01:00
Marek Wolan
a96cd0064d Merged PR 393: drop python 3.8 builds 2024-05-31 12:00:53 +00:00
Marek Wolan
ac9184b7d8 Merge branch 'feature/2588-minimal-deps' into bugfix/2626-too-many-open-files 2024-05-31 12:42:52 +01:00
Marek Wolan
ae8b726beb drop python 3.8 builds 2024-05-31 11:27:27 +00:00
Marek Wolan
1c86948d61 #2588 fix import in notebook 2024-05-31 12:12:35 +01:00
Marek Wolan
c7b2ed7f86 Merge branch 'dev' into feature/2588-minimal-deps 2024-05-31 12:11:16 +01:00
Marek Wolan
a5cd902175 Merged PR 390: Updated pyproject.toml
ADD deepdiff to dependency list

Related work items: #2637
2024-05-31 10:30:47 +00:00
Marek Wolan
4c9b2334da Merged PR 391: #2639 Fix reset signature
I don't want to write a description for this.

Related work items: #2639
2024-05-31 09:01:16 +00:00
Czar Echavez
40b4c9dac3 Merged PR 384: #2563: notebook explaining how to get simulation information from PrimAITE
## Summary
*Replace this text with an explanation of what the changes are and how you implemented them. Can this impact any other parts of the codebase that we should keep in mind?*

## Test process
*How have you tested this (if applicable)?*

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

#2563: notebook explaining how to get simulation information from PrimAITE

Related work items: #2563
2024-05-30 15:10:04 +00:00
Marek Wolan
a161a3a5ec #2639 Fix reset signature 2024-05-30 15:34:46 +01:00
Marek Wolan
d2f82a1535 Updated pyproject.toml 2024-05-30 12:31:35 +00:00
Marek Wolan
0c19546322 #2588 optional RL deps 2024-05-29 14:54:45 +01:00
Czar Echavez
d62ce7f86b #2563: apply PR suggestions 2024-05-29 12:01:14 +01:00
Czar Echavez
69aa12f49b #2563: notebook explaining how to get simulation information from PrimAITE 2024-05-23 17:12:48 +01:00
Charlie Crane
85f03570f7 Merged PR 376: 2457 - Remove Hardcoding from Links
## Summary
This PR removes the hardcoding of Link bandwidth, and makes it possible to be configured via the network yaml definitions.
Link bandwidth will still default to 100 if this is not present, to prevent breaking all previous defined networks.

## Test process
All tests continue to pass.
`basic_network_config.yaml` now provides a non-default link bandwidth which is confirmed within unit tests.

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [X] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [X] attended to any **TO-DOs** left in the code

Related work items: #2457
2024-05-22 11:35:48 +00:00
Charlie Crane
a676982dc5 Apply suggestions from code review 2024-05-22 10:50:59 +00:00
Charlie Crane
20d7f589d7 #2457 - Removing the ci-pipeline changes. These were explorative to entertain a possible fix to some flaky pipeline behaviour 2024-05-22 09:17:48 +01:00
Charlie Crane
417c02eaaa Merged PR 379: #2560 - Network_simulator_demo.ipynb cell fixes
## Summary
Some minor changes to the network_simulator_demo jupyter notebook so that all cells run.
I've updated the notebook to use a **very lightly** modified version of the ARCD UC2 network that it has been using.
_I've added a single route into the router_1 route table so that `network.get_node_by_hostname("router_1").route_table.show()` returns something visible. I didn't want to have this within the 'normal' uc2 network. Don't @ me._

![image.png](https://dev.azure.com/ma-dev-uk/b50a61ee-86c4-48bc-9a0b-a67645ba12ee/_apis/git/repositories/2825053e-bd3b-45b2-8680-1281809eefa2/pullRequests/379/attachments/image.png)

Corrected a path typo in `basic_lan_network_example()` so it correctly loads that network config.

## Test process
I've not broken any existing tests, and the notebook now runs with fully populated cells.

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [X] updated the **documentation** if this PR changes or adds functionality
- [X] written/updated **design docs** if this PR implements new functionality
- [X] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [X] attended to any **TO-DOs** left in the code

Related work items: #2560
2024-05-21 16:11:12 +00:00
Czar Echavez
af71fe52be Merged PR 378: Add create file/folder and file access requests
## Summary
Added requests in file system that allows:
- file to be created
- folder to be created
- file to be "accessed"

## Test process
https://dev.azure.com/ma-dev-uk/PrimAITE/_git/PrimAITE/pullrequest/378?_a=files&path=/tests/integration_tests/test_simulation/test_request_response.py

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

Related work items: #2606
2024-05-21 10:35:49 +00:00
Christopher McCarthy
be0cf10847 Merged PR 380: #2561 - Set the DatabaseServer service to automatically install the FTPClient
## Summary
- Set the DatabaseServer service to automatically install the upon install to enable backup. Added some defensive statements that gracefully handle backup/restore requests when FTPClient is not installed.

## Test process
Added test that installs `DatabaseServer` on a new node then checks for an installed `FTPClient`.

## Checklist
- [ ] PR is linked to a **work item**
- [ ] **acceptance criteria** of linked ticket are met
- [ ] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [ ] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

#2561 - Set the DatabaseServer service to automatically install the  upon install to enable backup. Added some defensive statements that gracefully handle backup/restore requests when FTPClient is not

Related work items: #2561, #2570
2024-05-21 08:56:50 +00:00
Czar Echavez
b7b87996d8 #2606: add metadata to file access 2024-05-20 17:21:20 +01:00
Charlie Crane
a759a6f5c3 #2457 - Addressing review comments 2024-05-20 16:52:17 +01:00
Czar Echavez
582cdb1f9a Merged PR 372: Integrate executed notebooks into primaite docs
## Summary
Integrating the notebooks into the primaite sphinx socumentation

## Test process
*How have you tested this (if applicable)?*

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [X] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

Related work items: #2472
2024-05-20 15:46:27 +00:00
Chris McCarthy
3be72ab6be Merge remote-tracking branch 'devops/feature/2561_Training-fails-because-database-service-can't-access-ftp-client-on-own-node' into feature/2561_Training-fails-because-database-service-can't-access-ftp-client-on-own-node 2024-05-20 16:27:09 +01:00
Chris McCarthy
18c837ff0e #2561 - Fixed issue relating to no access to software manager from inside service during install 2024-05-20 16:16:19 +01:00
Charlie Crane
7584271ad0 #2560 - Addressing review comments 2024-05-20 15:24:21 +01:00
Czar Echavez
f45df780c9 #2606: correcting the access verb 2024-05-20 15:02:05 +01:00
Christopher McCarthy
2170f6bc90 Apply suggestions from code review 2024-05-20 12:51:06 +00:00
Czar Echavez
80b1988ab9 #2606: add agent actions + test 2024-05-20 13:10:21 +01:00
Chris McCarthy
7a404773ac #2561 - Ran pre-commit hook 2024-05-20 12:44:58 +01:00
Charlie Crane
e9f3cef805 #2560 - Removing a sys_log.show() call in create-simulation_demo notebook that was used for debugging. 2024-05-20 12:32:03 +01:00
Charlie Crane
103c7f8d39 #2560 - Addressing the sys_log bug that could occur when scripts run across two time intervals. Additional updates to network_simulator notebook so that sys_log works in production mode 2024-05-20 12:28:02 +01:00
Czar Echavez
406d4e889b #2606: pre-commit check 2024-05-17 17:05:14 +01:00
Czar Echavez
e98ae0bd09 #2606: altered so that the request is done in file system + also completing access request 2024-05-17 16:59:24 +01:00
Charlie Crane
dc8105e8d6 2560 - Some minor tweaks to network_simulator_demo.ipynb and networks.py after looking through some bugs. Sys_log should print 2024-05-17 16:55:41 +01:00
Czar Echavez
8e17151696 #2472: apply PR suggestions 2024-05-17 11:17:00 +01:00
Archer Bowen
13fcda7a26 #2606 - Added initial attempts and created for visibility 2024-05-17 09:28:03 +01:00
Czar Echavez
7530b5b7a6 #2472: prevent notebook outputs when building documentation 2024-05-16 15:36:40 +01:00
Czar Echavez
fb7571ceae #2472: apply PR suggestions + minor fixes to make the notebooks output beautifuller 2024-05-16 14:06:43 +01:00
Czar Echavez
82953b4b0a #2472: add install pandoc to docs build pipeline + fix RLlib running for a long time 2024-05-16 10:55:17 +01:00
Czar Echavez
cb90c63c18 Merge remote-tracking branch 'origin/dev' into feature/2472-add-executed-notebook-to-html-documentation 2024-05-16 09:12:03 +01:00
Czar Echavez
d2cf0f2d22 #2472: revert make.bat changes 2024-05-15 14:03:17 +01:00
Czar Echavez
f7de3e6425 #2472: clean up 2024-05-15 14:00:14 +01:00
Charlie Crane
c1f4cb050e #2457 - Retesting the use of --no-cache-dir to see if that prevents hash issue 2024-05-15 09:00:54 +01:00
Charlie Crane
dc0f46270f #2457 - Adding a line to build pipeline to purge pip cache. Seeing if this could resolve hash error seen on some pipeline failures 2024-05-14 14:50:06 +01:00
Charlie Crane
f66d9d5817 Merge branch 'dev' into feature/2457-Set_link_bandwidth_via_config 2024-05-14 14:44:20 +01:00
Charlie Crane
084f48c721 #2457 - Updating changelog and testing a minor change in pipeline config to see if it resolves package hash errors 2024-05-14 11:11:42 +01:00
Charlie Crane
74514e977d #2457 - Syncing changes made. Updates to documentation and tests 2024-05-14 11:05:37 +01:00
Christopher McCarthy
7367fc67cf Merged PR 373: 2536 - Removed 'real files' from FileSystem and FTP
## Summary
Removed 'real files' from FileSystem and FTP

## Test process
- Dropped any tests that contain 'real files'
- Ran remaining tests to check that everything still works

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

2536 - Removed 'real files' from FileSystem and FTP

Related work items: #2536
2024-05-14 08:05:56 +00:00
Czar Echavez
2774623fba #2472: switch to using nbsphinx + added readme steps to setup pandoc + revert changes 2024-05-14 07:36:29 +01:00
Charlie Crane
71684dc5f0 #2457 - Initial commit removing the hardcoding of bandwidth values within links. Now pull it from configuration files, defaulting to 100 if not implemented 2024-05-13 14:42:15 +01:00
Chris McCarthy
e2f061fde0 #2561 - Set the DatabaseServer service to automatically install the upon install to enable backup. Added some defensive statements that gracefully handle backup/restore requests when FTPClient is not installed. 2024-05-13 07:58:43 +01:00
Chris McCarthy
ebbdea517e 2536 - Removed 'real files' from FileSystem and FTP 2024-05-13 07:30:33 +01:00
Marek Wolan
22e4b04a21 Merged PR 370: Merge back release
bump version basically.

Related work items: #2552
2024-05-10 14:48:08 +00:00
Czar Echavez
795004be5b #2472: copy image assets + applying change to makefile 2024-05-09 14:16:29 +01:00
Czar Echavez
81c523dc67 #2472: integrating jupyter notebooks into documentation 2024-05-09 13:43:55 +01:00
Nick Todd
d80eb15fa2 #2560: Fix typos and punctuation. 2024-05-08 14:56:44 +01:00
Marek Wolan
c6b6753aeb Updated VERSION 2024-05-08 11:13:32 +00:00
Marek Wolan
d02b7744ae Merged PR 368: #2550 Backport changes into core
## Summary
Backport changes from sensitive into core.

Mainly the application install and a couple of test changes.

## Test process
pytest

## Checklist
- [ ] PR is linked to a **work item**
- [ ] **acceptance criteria** of linked ticket are met
- [ ] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [ ] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

#2550 Backport changes into core

Related work items: #2549, #2550
2024-05-08 08:38:44 +00:00
Marek Wolan
4d3c85bc14 #2550 Backport changes into core 2024-05-07 15:35:02 +01:00
Charlie Crane
75fd6b923a Merged PR 361: #2464 - v3b7 install errors when using Python 3.11
## Summary
This is a two line change to `README.md` to correct the Python versions listed as a pre-requisite for PrimAITE, contradicting what is in `pyproject.toml`
We do not currently support Python3.11, which the README suggests we do.

## Test process
Not Applicable - Although I have installed v3b7 using Python3.11 as part of the bugfix investigation on a blank Ubuntu VM, and the install looks to of ran smoothly.
`Data-Manipulation-E2E-Demonstration` & `Training-an-SB3-Agent` both ran fine.

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [X] updated the **documentation** if this PR changes or adds functionality
- [X] written/updated **design docs** if this PR implements new functionality
- [X] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [X] attended to any **TO-DOs** left in the code

#2464 - Correcting Python versioning pre-req range on README.md as we do not currently support Python3.11

Related work items: #2464
2024-05-07 13:23:35 +00:00
Nick Todd
bfb8fbd1bf Merged PR 365: Run SB3 training in SubprocVecEnv
## Summary
Demonstration notebook show how to use SB3 SubprocVecEnv to vectorise environments to speed up training.
## Test process
Successfully run notebook on Windows and Linux.

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [X] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

Related work items: #2442
2024-05-03 16:02:34 +00:00
Nick Todd
e510c3ceff #2442: Removed 'primaite setup' call 2024-05-03 15:10:24 +01:00
Marek Wolan
727a05f291 Merged PR 363: Make ftp client only default on computers, not servers
## Summary
REMOVE ftp client from host node default software and add it to computer default software, effectively removing it from servers.

Ensure tests are using the uc2 yaml file instead of outdated network generator function.

Fix some tests to make sure it all passing

## Test process
I have tested it.

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [X] attended to any **TO-DOs** left in the code

Make ftp client only default on computers, not servers

Related work items: #2546
2024-05-03 12:40:17 +00:00
Marek Wolan
535e064af5 unflake test 2024-05-03 11:05:33 +01:00
Marek Wolan
4f38184959 remove redundant comment 2024-05-03 09:08:26 +01:00
Charlie Crane
4cd15a39aa #2457 - Commit before switching branches to review 2024-05-03 08:35:24 +01:00
Nick Todd
689400e95c Merge branch 'dev' into bugfix/2442-add_SubprocVecEnv_support 2024-05-02 17:04:43 +01:00
Marek Wolan
4a02d1d8e5 Readd import statement 2024-05-02 17:00:29 +01:00
Nick Todd
3c5e107f81 Merge branch 'dev' into bugfix/2442-add_SubprocVecEnv_support 2024-05-02 16:59:08 +01:00
Nick Todd
5a3b6ade2f #2442: Updated changelog. 2024-05-02 16:52:35 +01:00
Marek Wolan
6ef6a5cd18 Merge remote-tracking branch 'origin/dev' into feature/remove-ftp-client-default-app 2024-05-02 16:52:24 +01:00
Nick Todd
7c689a0d35 #2442: Markdown changes. 2024-05-02 16:32:54 +01:00
Nick Todd
a37ed4e487 #2442: Fix config file path to be OS independent. 2024-05-02 16:16:36 +01:00
Marek Wolan
b9b922e776 Make ftp client only default on computers, not servers 2024-05-02 15:51:06 +01:00
Nick Todd
2774442561 Merge branch 'bugfix/2442-add_SubprocVecEnv_support' of ssh.dev.azure.com:v3/ma-dev-uk/PrimAITE/PrimAITE into bugfix/2442-add_SubprocVecEnv_support 2024-05-02 15:48:30 +01:00
Nick Todd
db29d33629 #2442: Add multi-processing notebook example. 2024-05-02 15:44:18 +01:00
Czar Echavez
a5794e5df1 Merged PR 359: Improved Dev CLI tools
## Summary
Improved dev tools:
- can configure what the dev mode can override
  - sys log level
  - outputting sys log
  - outputting pcap logs
  - outputting to terminal
  - the location where to output session (by default will print to the primaite repo root)

## Test process
https://dev.azure.com/ma-dev-uk/PrimAITE/_git/PrimAITE/pullrequest/359?_a=files&path=/tests/integration_tests/cli/test_dev_cli.py

and a lot of manually checking if the thing outputs to the correct directories

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [X] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [X] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

Related work items: #2447, #2533
2024-05-02 13:37:16 +00:00
Czar Echavez
e599e03c10 #2533: cleaner output text for dev-mode show + consistent colors 2024-05-02 12:21:24 +01:00
Charlie Crane
5cfa9c7fa2 #2464 - Version typo in README.md 2024-05-02 08:54:37 +01:00
Charlie Crane
ec582c0002 #2464 - Reverting flake8 change 2024-05-01 17:08:08 +01:00
Charlie Crane
d25a8aa0ef #2464 - Reverting changes from Python3.12 investigations, updating README and prproject.toml so that python 3.11 is allowed 2024-05-01 17:06:58 +01:00
Czar Echavez
ec6d2bf640 #2533: fix missing implementation of output_dir override in io.py + moving the dev mode override in SIM_OUTPUT to prevent the override from being overridden 2024-05-01 16:53:37 +01:00
Charlie Crane
0fd85722ae #2464 I missed a linting error 2024-05-01 16:37:16 +01:00
Czar Echavez
952f6ee225 #2533: fix is_dev_mode for missing or outdated configs 2024-05-01 16:23:44 +01:00
Charlie Crane
a2482dc744 #2464 - Forgot to save and add a file that would cause flake8 failure 2024-05-01 16:22:26 +01:00
Charlie Crane
c2cc5228ae #2464 - Linting changes to see if the python 3.12 pipeline will pass 2024-05-01 16:20:01 +01:00
Czar Echavez
25807653f4 Merge remote-tracking branch 'origin/dev' into feature/2533-improve-dev-tools-in-primaite-cli 2024-05-01 16:11:52 +01:00
Czar Echavez
d7572dc18b #2533: changelog 2024-05-01 16:10:27 +01:00
Czar Echavez
61e7a4e439 #2533: documentation on use of dev-mode 2024-05-01 16:04:18 +01:00
Charlie Crane
57cff8d4e3 #2464 - Seeing if python 3.12 will also run... 2024-05-01 16:01:08 +01:00
Czar Echavez
5516fbc6fc #2533: output directory for sessions 2024-05-01 14:48:10 +01:00
Charlie Crane
392b83fc64 #2464 - Correcting use of spaces in pipeline job names 2024-05-01 14:34:38 +01:00
Charlie Crane
efdc979495 #2464 Changing pyproject.toml to allow the use of python 3.11 and tweaking the pipeline to use python 3.11. Seeing what happens... 2024-05-01 14:33:38 +01:00
Czar Echavez
b6b5ce91c2 #2533: clean up temp items in tests + fixing the CLI tests 2024-05-01 14:33:33 +01:00
Czar Echavez
a2fb04e6f6 #2533: set default dev output path + clean up 2024-05-01 14:02:40 +01:00
Charlie Crane
8d9ffab514 #2464 - Correcting Python versioning pre-req range on README.md as we do not currently support Python3.11 2024-05-01 12:04:11 +01:00
Nick Todd
831f80f617 Merge branch 'bugfix/2442-add_SubprocVecEnv_support' of ssh.dev.azure.com:v3/ma-dev-uk/PrimAITE/PrimAITE into bugfix/2442-add_SubprocVecEnv_support 2024-05-01 11:22:08 +01:00
Nick Todd
b7fa826d95 #2442: Initial commit of MP test script 2024-05-01 11:16:45 +01:00
Christopher McCarthy
4763344835 Merged PR 358: #2519 - refactored all air-space usage to that a new instance of AirSpace is...
## Summary
- Refactored all air-space usage to that a new instance of `AirSpace` is created for each instance of Network. This 1:1 relationship between network and airspace will allow parallelization.

## Test process
- Original test remains the same. TDD, init.
- Added additional `WirelessRouter` test that tests wireless connectivity from config file too.
``` text
C:\Users\ChristopherMcCarthy\source\azure_devops\ma-dev-uk\PrimAITE\venv\Scripts\python.exe "C:/Program Files/JetBrains/PyCharm 2023.3.5/plugins/python/helpers/pycharm/_jb_pytest_runner.py" --path C:\Users\ChristopherMcCarthy\source\azure_devops\ma-dev-uk\PrimAITE\tests\integration_tests\network\test_wireless_router.py
Testing started at 15:33 ...
Launching pytest with arguments C:\Users\ChristopherMcCarthy\source\azure_devops\ma-dev-uk\PrimAITE\tests\integration_tests\network\test_wireless_router.py --no-header --no-summary -q in C:\Users\ChristopherMcCarthy\source\azure_devops\ma-dev-uk\PrimAITE\tests\integration_tests\network

============================= test session starts =============================
collecting ... collected 2 items

test_wireless_router.py::test_cross_wireless_wan_connectivity
test_wireless_router.py::test_cross_wireless_wan_connectivity_from_yaml

======================== 2 passed, 1 warning in 0.14s =========================
+----------------+-------------------+-------------+---------------+--------------+---------+
| Connected Node |    MAC Address    |  IP Address |  Subnet Mask  |  Frequency   |  Status |
+----------------+-------------------+-------------+---------------+--------------+---------+
|    router_1    | da:9a:08:17:80:a4 | 192.168.1.1 | 255.255.255.0 | WiFi 2.4 GHz | Enabled |
|    router_2    | 0d:67:76:5e:c2:fb | 192.168.1.2 | 255.255.255.0 | WiFi 2.4 GHz | Enabled |
+----------------+-------------------+-------------+---------------+--------------+---------+
PASSED     [ 50%]+----------------+-------------------+-------------+---------------+--------------+---------+
| Connected Node |    MAC Address    |  IP Address |  Subnet Mask  |  Frequency   |  Status |
+----------------+-------------------+-------------+---------------+--------------+---------+
|    router_1    | 1a:46:f6:cb:8c:15 | 192.168.1.1 | 255.255.255.0 | WiFi 2.4 GHz | Enabled |
|    router_2    | 7a:9f:d8:2b:4b:90 | 192.168.1.2 | 255.255.255.0 | WiFi 2.4 GHz | Enabled |
+----------------+-------------------+-------------+---------------+--------------+---------+
PASSED [100%]
Process finished with exit code 0
```

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [X] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [X] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [ ] atte...
2024-05-01 10:12:28 +00:00
Chris McCarthy
7552872430 #2519 - Fixed the broked multi-lan network topology diagrams while I was in doing a PR too 2024-05-01 10:28:54 +01:00
Chris McCarthy
d72622f3f7 Merge branch 'dev' into feature/2519_Make-airspace-an-attribute-of-Simulation
# Conflicts:
#	CHANGELOG.md
2024-05-01 10:22:44 +01:00
Czar Echavez
95643d3255 #2533: optimise so we are not reading from file all the time 2024-04-30 19:36:22 +01:00
Czar Echavez
729f9c5064 #2533: fix primaite config recreated when running setup 2024-04-30 19:15:54 +01:00
Czar Echavez
73f64cd89c Merge remote-tracking branch 'origin/dev' into feature/2533-improve-dev-tools-in-primaite-cli 2024-04-30 18:27:05 +01:00
Charlie Crane
13cabf8e21 Merged PR 360: 2523 - Logging Rewards updates.
## Summary
This PR updates `PrimaiteGymEnv` and `PrimaiteRayMARLEnv` within `environment.py` to log reward values per step and per episode.
Corrects an import statement within `io.py` - removing the use of `src`.
Fixes an error within notebooks that saw them failing following a rename of `game_config` to `env_config`.

## Test process
 - Tests all continue to pass, and notebooks now run without error. This PR does not change any functionality, just adds some logging.
 - Searched for the catch-22 that would trip me up as part of this ticket. A 3 line change felt like too simple an implementation...

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [X] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [X] attended to any **TO-DOs** left in the code

Related work items: #2523
2024-04-30 17:13:50 +00:00
Charlie Crane
9c89fe4143 #2523 - Typo corrections within notebooks that stopped them from running 2024-04-30 16:14:34 +01:00
Chris McCarthy
04eb33e28a #2519 - Dropped failed unit test in test_wireless_router.py as it didn't actually test any functionality and simply just tested the config parser, which we now do in the integration test. 2024-04-30 16:07:38 +01:00
Charlie Crane
bb99e46651 #2523 - Updating CHANGELOG.md 2024-04-30 16:03:31 +01:00
Czar Echavez
ab3d23785d #2533: precommit 2024-04-30 15:50:53 +01:00
Chris McCarthy
bc573dfed0 #2519 - refactored all air-space usage to that a new instance of AirSpace is created for each instance of Network. This 1:1 relationship between network and airspace will allow parallelization. Added additional WirelessRouter test that tests wireless connectivity from config file too. 2024-04-30 15:46:16 +01:00
Czar Echavez
59990813f5 #2533: added tests + log level for output 2024-04-30 15:43:25 +01:00
Charlie Crane
9b3699389a #2523 - Adding in some additional logging for other agent classes. This currently prints total_reward instead of average reward 2024-04-30 15:36:59 +01:00
Christopher McCarthy
a82ee2b8e1 Merged PR 354: Network focussed dev config documentation
## Summary
Built three networks, one is the minimal network, one is a basic LAN, and another is a nice beefy multi-LAN setup with ISP and DNS along with applications, services. Documented the process when building the config files. Included the config files as example configs for use.

## Test process
Tested the shit out of the big multi-lan network.

## Checklist
- [ ] PR is linked to a **work item**
- [ ] **acceptance criteria** of linked ticket are met
- [ ] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [ ] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

Related work items: #2266
2024-04-30 13:53:28 +00:00
Charlie Crane
b8c46a92e9 #2523 - Minor typos/corrections to make things run locally. Added one logging line to record Blue agent reward per step in environment.py 2024-04-30 14:16:29 +01:00
Chris McCarthy
a141c8d212 #2266 - fixed typos from PR suggestions 2024-04-30 14:08:12 +01:00
Nick Todd
137f2a9648 Merged PR 306: Fix issues with check_hash function.
## Summary
The current implementation of check_hash() as triggered by NODE_FILE_CHECKHASH and NODE_FOLDER_CHECKHASH is incorrect. However, a correct implementation is a future task so the code is disabled and a deprecation warning has been added.

## Test process
Disabled tests that exercise check_hash() functionality. Added tests to show that deprecation warning is present.

## Checklist
- [X ] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [X] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [X] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

2299: Remove calls to corrupt.

Related work items: #2299
2024-04-30 12:08:19 +00:00
Nick Todd
3d0ebe1aba #2299: Correct possible mis-merge. 2024-04-30 10:39:33 +01:00
Nick Todd
9906ba20ae Merge branch 'dev' into bugfix/2299-check_hash_function_corrupts_files_and_folders 2024-04-30 09:17:40 +01:00
Marek Wolan
8a97d197b9 Merged PR 355: Document request success
## Summary
Add a doc page and a notebook to go over the request manager.

## Test process
Notebook runs.

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [na] written **tests** for any new functionality added with this PR
- [x] updated the **documentation** if this PR changes or adds functionality
- [x] written/updated **design docs** if this PR implements new functionality
- [na] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [x] attended to any **TO-DOs** left in the code

Related work items: #2514
2024-04-29 17:36:29 +00:00
Czar Echavez
c94fa653f7 Merge remote-tracking branch 'origin/dev' into feature/2533-improve-dev-tools-in-primaite-cli 2024-04-29 16:24:19 +01:00
Nick Todd
5b03013e3f Merge branch 'dev' into bugfix/2299-check_hash_function_corrupts_files_and_folders 2024-04-29 15:44:06 +01:00
Nick Todd
e667223a98 #2299: Remove debug cell from notebook. 2024-04-29 15:34:23 +01:00
Nick Todd
e7db5c7f58 #2299: Review comments 2024-04-29 15:30:24 +01:00
Czar Echavez
a7492ba39f #2447: cli commands for dev mode 2024-04-29 13:45:10 +01:00
Marek Wolan
68d4751f73 Apply suggestions from code review 2024-04-29 11:56:40 +00:00
Marek Wolan
27d1cd460b #2514 Provide more friendly messages on validation failure 2024-04-29 11:13:32 +01:00
Marek Wolan
3c046b838b #2514 Document request response. 2024-04-29 11:11:51 +01:00
Nick Todd
75f404416c #2299: Update CHANGELOG.md 2024-04-29 10:30:47 +01:00
Marek Wolan
32a0542b73 Merged PR 353: Episode Schedule
## Summary
* Made It Possible™ to vary the layout and agents between episodes.
* Standardised the environments to all use `env_config` as the __init__ parameter name, previously PrimaiteGymEnv was using `game_config`
* Added a notebook that demonstrates how to use the variable episodes.

## Test process
Checked that existing pytests run. Added more tests. Checked that notebooks run.

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [x] written **tests** for any new functionality added with this PR
- [x] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [x] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [x] attended to any **TO-DOs** left in the code

Related work items: #2269, #2334, #2336, #2475, #2476
2024-04-29 09:08:37 +00:00
Chris McCarthy
81d4006240 #2266 - Finalised the tests and fleshed out the documentation more. 2024-04-26 23:18:09 +01:00
Marek Wolan
394e76048f Merge remote-tracking branch 'origin/dev' into feature/2476-training-schedules-mockup 2024-04-26 16:23:41 +01:00
Marek Wolan
30cc04411d #2476 apply pr comments 2024-04-26 16:23:02 +01:00
Chris McCarthy
0ccd53e907 Merge branch 'dev' into feature/2266_network-focussed-dev-documentation 2024-04-26 16:19:33 +01:00
Charlie Crane
5ee23dcb17 Merged PR 348: #2462 - Refactor of DatabaseClient and DatabaseServer
## Summary
Refactor of `DatabaseClient` and `DatabaseService` to update how connection IDs are generated. These are now provided by DatabaseService when establishing a connection.
Creation of `DatabaseClientConnection` class. This is used by `DatabaseClient` to hold a dictionary of active db connections.

## Test process
Tests have been updated to reflect the changes and all pass

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [X] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [X] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [X] attended to any **TO-DOs** left in the code

Related work items: #2462
2024-04-26 14:52:21 +00:00
Chris McCarthy
058ca3987f #2266 - Added more docs. Now need to test 2024-04-26 14:32:54 +01:00
Nick Todd
ec8b46f3bc #2299: Add tests to check for 'not implemented' warning message. 2024-04-25 17:56:55 +01:00
Nick Todd
0c375ebe4d #2299: Disable tests using CHECKHASH functionality 2024-04-25 17:08:03 +01:00
Nick Todd
0fa9fa32bc #2299: Add not implemented warning message. 2024-04-25 16:20:57 +01:00
Marek Wolan
be5cf0b877 Merge remote-tracking branch 'origin/dev' into feature/2476-training-schedules-mockup 2024-04-25 15:17:08 +01:00
Chris McCarthy
0fff7d2240 Merge branch 'dev' into feature/2266_network-focussed-dev-documentation 2024-04-25 15:16:28 +01:00
Marek Wolan
37945c0065 #2476 Remove temporary testing file 2024-04-25 15:16:20 +01:00
Chris McCarthy
c93c432bf1 #2266 - Added final complex network to the examples. Just need to finalise the building the config section 2024-04-25 15:14:40 +01:00
Czar Echavez
e1ac6255ad Merged PR 352: #2447: added mode to primaite cli + printing session to current working direc...
## Summary
- Added the mode command in PrimAITE CLI
- command allows users to switch between developer mode and production mode
- developer mode changes where the simulation_output is written
  - dev mode writes simulation output where the current working directory is

## Test process
CLI:
![primaite mode.gif](https://dev.azure.com/ma-dev-uk/b50a61ee-86c4-48bc-9a0b-a67645ba12ee/_apis/git/repositories/2825053e-bd3b-45b2-8680-1281809eefa2/pullRequests/352/attachments/primaite%20mode.gif)

Running prod mode:
![primaite mode prod.gif](https://dev.azure.com/ma-dev-uk/b50a61ee-86c4-48bc-9a0b-a67645ba12ee/_apis/git/repositories/2825053e-bd3b-45b2-8680-1281809eefa2/pullRequests/352/attachments/primaite%20mode%20prod.gif)

Running dev mode:
![primaite mode dev.gif](https://dev.azure.com/ma-dev-uk/b50a61ee-86c4-48bc-9a0b-a67645ba12ee/_apis/git/repositories/2825053e-bd3b-45b2-8680-1281809eefa2/pullRequests/352/attachments/primaite%20mode%20dev.gif)

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [X] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [X] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

#2447: added mode to primaite cli + printing session to current working directory if in dev mode

Related work items: #2447
2024-04-25 14:13:55 +00:00
Marek Wolan
736408f8b4 Reference the episode schedule notebook in docs 2024-04-25 15:12:46 +01:00
Marek Wolan
66f31e8ed1 #2476 Add test for episode scheduler 2024-04-25 15:09:46 +01:00
Marek Wolan
42ce264e73 #2476 Fix string formatting 2024-04-25 13:54:05 +01:00
Czar Echavez
0fff29ef27 #2447: changelog + documentation 2024-04-25 13:50:41 +01:00
Marek Wolan
e3f9162a77 Merge remote-tracking branch 'origin/dev' into feature/2476-training-schedules-mockup 2024-04-25 13:50:11 +01:00
Czar Echavez
96b6fb81da #2447: added mode to primaite cli + printing session to current working directory if in dev mode 2024-04-25 13:32:57 +01:00
Marek Wolan
a92898d001 #2476 Finalise explanation notebook for episode schedule 2024-04-25 13:25:26 +01:00
Nick Todd
228a8099a3 #2299: Revert changes to disable check_hash() 2024-04-24 17:27:27 +01:00
Chris McCarthy
081ff0647f Merge branch 'dev' into feature/2266_network-focussed-dev-documentation
# Conflicts:
#	src/primaite/game/agent/observations/observations.py
2024-04-24 16:04:46 +01:00
Czar Echavez
f01c30864d Merged PR 347: Implementing log levels
## Summary
- Implementation of log levels
- log levels can be set via io_settings.log_level in the yaml config file

## Test process
https://dev.azure.com/ma-dev-uk/PrimAITE/_git/PrimAITE/pullrequest/347?_a=files&path=/tests/unit_tests/_primaite/_simulator/_system/core/test_sys_log.py

set up a test where the test checks the contents of the terminal so make sure that specific log level messages appear (or not) depending on the log level

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [X] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [X] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [X] attended to any **TO-DOs** left in the code

Related work items: #2470
2024-04-24 11:09:48 +00:00
Czar Echavez
d4aaeda4b6 #2470: update doc to reflect the default log level 2024-04-24 10:11:23 +01:00
Czar Echavez
23231e432e Merge remote-tracking branch 'origin/dev' into feature/2470-refactor-syslog-to-be-able-to-leverage-a-configured-log-level 2024-04-24 09:17:28 +01:00
Czar Echavez
16fc6f4fd0 Merge remote-tracking branch 'origin/dev' into feature/2470-refactor-syslog-to-be-able-to-leverage-a-configured-log-level 2024-04-23 16:54:03 +01:00
Czar Echavez
32cd7dba04 Merged PR 350: #2510: cleaning up logs and add logging handler clearing to prevent duplicate...
## Summary
- Cleaning up multiple logs that say the same thing
- Added Nick's suggestion to clear log handlers before adding a handler on SysLog initialisation

## Test process
*How have you tested this (if applicable)?*

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [ ] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [ ] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

#2510: cleaning up logs and add logging handler clearing to prevent duplicate logs

Related work items: #2510
2024-04-23 15:53:58 +00:00
Czar Echavez
90343bd5ec #2470: apply PR suggestions 2024-04-23 16:52:53 +01:00
Nick Todd
3eea70f7d8 Merge branch 'dev' into bugfix/2299-check_hash_function_corrupts_files_and_folders 2024-04-23 16:40:02 +01:00
Christopher McCarthy
a60e8b2203 Merged PR 349: #2511 - Upgraded pydantic to version 2.7.0
## Summary
- Upgraded pydantic to version 2.7.0.
- Added ipywidgets to the dependencies (for #2300)

## Test process
N/A

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [X] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

#2511 - Upgraded pydantic to version 2.7.0. Added ipywidgets to the dependencies (for #2300)

Related work items: #2300, #2511
2024-04-23 13:43:44 +00:00
Marek Wolan
8e008b6d24 #2511 Appease isort pre commit hook 2024-04-23 13:54:56 +01:00
Czar Echavez
c13b7d7c81 #2510: cleaning up logs and add logging handler clearing to prevent duplicate logs 2024-04-23 11:54:34 +01:00
Marek Wolan
28c8b7c9d9 #2476 Get episode schedule working 2024-04-23 11:51:50 +01:00
Marek Wolan
1eca20157b Updated CHANGELOG.md 2024-04-23 09:04:49 +00:00
Marek Wolan
2b19c8c91d #2551 upgrade ray to >2.9 and resolve logging error in db client 2024-04-23 09:51:56 +01:00
Marek Wolan
2b3664ce36 #2476 Add proof of concept yaml combining notebook 2024-04-23 09:29:59 +01:00
Chris McCarthy
6060cbbc5b #2511 - Put the ray rlllib dep back to "ray[rllib] == 2.8.0, < 3" 2024-04-23 09:04:17 +01:00
Nick Todd
779a9587bc Merged PR 338: #2455: Fix typo in config file and notebook
## Summary
Fixed small typo in data_manipulation_marl.yaml. Correct database key in Data-Manipulation-Customising-Red-Agent notebook.

## Test process
Successfully re-ran all notebooks in src/primaite/notebooks on Windows and Linux (WSL).
Successfully re-ran all tests in primaite/tests.
Also checked that Ransomware-Kill-Chain-E2E and UC6-E2E-Demo ran correctly in PrimAITE Sensitive repo.

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

#2455: Fix typo in config file and notebook

Related work items: #2455
2024-04-22 15:35:51 +00:00
Nick Todd
6726a2da37 #2245: Add comment 2024-04-22 14:09:12 +01:00
Chris McCarthy
a7dae6e373 #2511 - Upgraded pydantic to version 2.7.0. Added ipywidgets to the dependencies (for #2300) 2024-04-22 08:49:08 +01:00
Chris McCarthy
9a55b7b864 #2266 - Fixed some minor bugs that prevented basic networks without a default gateway from being parsed. Completed the basic client-server P2P network documentation, file and retrieval method. 2024-04-19 15:58:50 +01:00
Chris McCarthy
455c8cdcd5 Merge branch 'dev' into feature/2266_network-focussed-dev-documentation 2024-04-19 14:57:40 +01:00
Chris McCarthy
cbb8da61c8 #2266 - Finally started to add some user documentation around how to properly create networks 2024-04-19 14:56:56 +01:00
Czar Echavez
57e6f8bca7 #2470: update documentation 2024-04-19 11:55:38 +01:00
Nick Todd
873b70c2c9 Merge branch 'dev' into bugfix/2455-notebook_updates 2024-04-19 11:52:09 +01:00
Czar Echavez
b8d4a8cc8d #2470: changed default log level to warning + changed sys logging in code to be more aligned with severity of messages 2024-04-19 11:37:52 +01:00
Nick Todd
9334b1e79b #2455: Add NICObservation.ConfigSchema to NIC list. 2024-04-19 11:07:32 +01:00
Czar Echavez
833fd18936 #2470: add write_sys_log_to_terminal to documentation 2024-04-18 16:44:18 +01:00
Czar Echavez
cbea0fd595 #2470: fix documentation 2024-04-18 16:40:05 +01:00
Czar Echavez
34773ed225 #2470: implement PR suggestions 2024-04-18 16:38:42 +01:00
Czar Echavez
2a1203675d #2470: changelog + documentation 2024-04-18 15:57:02 +01:00
Czar Echavez
94ca13c0f9 #2470: add log level via config + test 2024-04-18 15:14:40 +01:00
Charlie Crane
56d03aaf7b Merged PR 339: #2453 - Example Notebooks Refactor
## Summary
Updates to `create-simulation_demo.ipynb` and `network_simulator_demo.ipynb` to reflect changes within repo.
 - Corrected import paths
 - Corrected typo in create-simulation_demo: my_swtich -> my_switch and switch.sys_log.show -> computer.sys_log.show()
 - Changes to ARP implementation within nodes. Now defined as a property within HostNode and NetworkNode, allowing router.arp.show() to work as intended within the notebook.

## Test process
 - Both notebooks now run without issue when ran.
 - All tests pass

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [X] attended to any **TO-DOs** left in the code

Related work items: #2453, #2477, #2478
2024-04-18 13:36:23 +00:00
Charlie Crane
abf94fc4bb #2453 - Committing additional explanations to notebook 2024-04-18 13:52:43 +01:00
Charlie Crane
bb88d43b90 #2453 - Updating with some explanation to improve the readability of the notebook 2024-04-18 13:50:47 +01:00
Charlie Crane
49be3b3639 #2453 - Updates to Training-an-SB3-agent.ipynb following review 2024-04-18 10:23:26 +01:00
Charlie Crane
d05ded0dc2 Merge branch 'dev' into bugfix/2453-Example_Notebooks_require_refactor 2024-04-18 09:30:12 +01:00
Czar Echavez
b57deaf9e1 #2470: implementing log levels into sys log 2024-04-17 18:13:00 +01:00
Charlie Crane
999044a444 2453 - removal of notebook metadata 2024-04-17 10:44:44 +01:00
Marek Wolan
137a203acc Merged PR 346: Deprecate PrimaiteSession
## Summary
A while ago we have added several notebooks to get users started training their own agents. These notebooks overlap in functionality with PrimAITE session but they are more suitable.

* removed primaite session
* removed any tests relying on primaite session (except some tests were converted into environment tests.
* removed any CLI commands that rely on `PrimaiteSession`
* Added deprecation warnings to any benchmarking code that will break now because they rely on the old Primaite 2 session. (I left the code in because when we update benchmarking to v3, this will be a useful starting point)
* added similar deprecation warnings to Session metadata writer, reader and transaction stuff, for the same reason.
* removed parts of the documentation that are no longer relevant (session, training config, policy)
* went through all existing yaml config files and removed training options (as they were for session only)

## Test process
Checked that existing pytests all pass, and updated some pytests to use environment instead of session.

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [x] written **tests** for any new functionality added with this PR
- [x] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [x] attended to any **TO-DOs** left in the code

Related work items: #2374
2024-04-17 08:25:43 +00:00
Nick Todd
796c0553a4 Merge branch 'dev' into bugfix/2455-notebook_updates 2024-04-17 09:15:29 +01:00
Charlie Crane
750cc98703 #2453 - Actioning review comments 2024-04-16 16:52:36 +01:00
Charlie Crane
dcfcfc0c54 #2453 - Merging in updates on dev branch 2024-04-16 16:51:29 +01:00
Nick Todd
4903c77f65 #2455: Add missing source_wildcard_id and dest_wildcard_id data. 2024-04-16 14:17:58 +01:00
Marek Wolan
db56eea4ce #2374 Update readme and minor fix to yaml 2024-04-16 13:20:07 +01:00
Marek Wolan
e12fd8f1a2 Merged PR 344: Bump version and reenable multi-platform builds
Yes

Related work items: #2471
2024-04-16 11:19:20 +00:00
Marek Wolan
7c0a7702c4 #2374 update changelog 2024-04-16 11:39:13 +01:00
Marek Wolan
9679b898fe Merge remote-tracking branch 'origin/dev' into feature/2471-bump-version 2024-04-16 11:28:30 +01:00
Marek Wolan
8d0d323e0b #2374 Remove primaite session 2024-04-16 11:26:17 +01:00
Nick Todd
8fac8be6c2 Merge branch 'dev' into bugfix/2455-notebook_updates 2024-04-16 11:03:48 +01:00
Christopher McCarthy
2410d5ab37 Merged PR 345: PrimAITE v3.0.0b8 release
Merge the PrimAITE v3.0.0b3 release back into dev

gitflow, init
2024-04-16 09:45:43 +00:00
Marek Wolan
2d444f71c9 Updated VERSION 2024-04-16 08:53:55 +00:00
Marek Wolan
f0ed9d2240 re-enable multi platform builds 2024-04-15 14:16:09 +01:00
Marek Wolan
b797662b1d bump version 2024-04-15 14:15:58 +01:00
Marek Wolan
72dd84886b Merged PR 343: #2459 back-sync b8 changes into core
Copy pasta job

Related work items: #2459
2024-04-15 12:56:26 +00:00
Marek Wolan
39ec55c7b6 #2459 strip notebook outputs to appease pre-commit 2024-04-15 13:12:51 +01:00
Marek Wolan
72283e6184 #2459 Align whitespace and typing 2024-04-15 12:40:50 +01:00
Marek Wolan
e876bb5d41 #2459 update doc page 2024-04-15 11:59:17 +01:00
Marek Wolan
0828f70b4c #2459 back-sync b8 changes into core 2024-04-15 11:50:08 +01:00
Charlie Crane
9496441169 #2453 - Ignore this commit. Removing saved output in Training-an-SB3-Agent Notebook 2024-04-09 15:19:45 +01:00
Charlie Crane
3245c7e81e #2453 - Renaming Server hostname in create-simulation_demo and removing saved output 2024-04-09 14:48:49 +01:00
Nick Todd
89de5a298d #2455: Fix typo in config file and notebook 2024-04-09 14:47:31 +01:00
Charlie Crane
265f25b442 #2453 - One final typo correction found in network_simulator_demo.ipynb. Correcting switch.sys_log.show() to computer.sys_log.show() in Computer/Server Nodes section 2024-04-09 14:15:51 +01:00
Charlie Crane
8e6689d881 #2453 - Corrected flake8 linting errors ahead of creating PR, after finally managing to get it to run locally. This should now be ready for review 2024-04-09 13:56:21 +01:00
Charlie Crane
d02b12d1e5 #2453 Addressing some flake8 corrections 2024-04-09 13:45:27 +01:00
Charlie Crane
c13d3f191f #2453 - Correcting errors found from pipeline pre-commit checks 2024-04-09 13:34:57 +01:00
Charlie Crane
f8432bf53b #2453 - Example Notebooks Require Refactor
- create_simulation_demo and network_simulator_demo notebooks have been updated with correct import paths to reflect refactoring within condebase.
 - Corrected typo within create-simulation_demo: my_swtich -> my_switch
 - updates to ARP implementation. This is now a property in HostNode and NetworkNode, meaning router.arp.show() now works in network_simulator_demo notebook as intended.
2024-04-09 13:26:35 +01:00
Czar Echavez
bce32fb376 Merged PR 330: #2448: store last query response for db client
## Summary
Required to complete #2448
DB Client will store last query response - Data Fusion Service will use this to know the difference between no response and invalid response

## Test process
*How have you tested this (if applicable)?*

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

#2448: store last query response for db client

Related work items: #2448
2024-04-04 13:30:55 +00:00
Czar Echavez
383cf051df #2448: store last query response for db client 2024-04-04 14:17:34 +01:00
Marek Wolan
5408611c73 Merged PR 329: Remove link refs and put nice naming convention instead
instead of UUID for link primary key in describe state, we are using something more like

router_1:eth-3<->switch_1:eth-8
**all configs need to change the observation space link schema as a result of this change**

It looks like there are a lot of changed files, but it's mostly just removing the `game` parameter from observations and removing 'ref' from config files.

:)

also we no longer need to specify `ref` for nodes, services, or applications. (**but existing configs will not break based on this change!**)

Related work items: #2450
2024-04-04 09:11:23 +00:00
Marek Wolan
3b4962830a #2450 remove unused ref maps in PrimaiteGame 2024-04-03 22:52:06 +01:00
Marek Wolan
698cb83e41 #2450 change link definition schema 2024-04-03 22:20:33 +01:00
Marek Wolan
526dcc7ffe #2450 remove the need to pass Game to observation objects 2024-04-03 22:16:54 +01:00
Marek Wolan
53de4bf7dd Update test assets to new link naming convention 2024-04-03 21:46:42 +01:00
Marek Wolan
e99d238568 #2450 remove link refs and put nice naming convention instead 2024-04-03 21:39:13 +01:00
Marek Wolan
c9a552b836 Merged PR 328: #2449 fix observation integration
small fix

Related work items: #2449
2024-04-03 20:32:32 +00:00
Marek Wolan
2cd9e58994 temp disable extra platforms for build pipeline 2024-04-03 20:18:23 +00:00
Marek Wolan
5f9af03cd9 Merge remote-tracking branch 'origin/dev' into bugfix/2449-observation-where 2024-04-03 20:00:19 +01:00
Marek Wolan
06fd15abaa Merged PR 325: #2446 Fix io config parsing order
Tiny small bugfix.

make sure IO settings are read before the game config in the environments. This is so that SIM_OUTPUT global variable is set before constructing game objects.

Related work items: #2446
2024-04-03 16:33:51 +00:00
Marek Wolan
a4caa3dfe4 #2449 fix observation integration 2024-04-03 15:58:01 +01:00
Czar Echavez
985628f2da Merged PR 324: #2437: fix the visible health status not being carried on after restoring bac...
## Summary
The file being backed up by the database service does not restore the last visible health status of the db file before being restored

## Test process
- Tests that the visible health status is carried forward when the file is corrupted and then restored
- Tests that the visible health status is carried forward when the file is corrupted, deleted and then restored

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

#2437: fix the visible health status not being carried on after restoring backup file

Related work items: #2437
2024-04-02 15:37:01 +00:00
Czar Echavez
989e7481f3 #2437: fix the visible health status not being carried on after restoring backup file 2024-04-02 15:10:48 +01:00
Marek Wolan
e3d3a94da2 Merged PR 321: CAOS 0.8 observations
## Summary
* Remove the usecase-specific and agent-specific observation classes, replacing with a more flexible system
* Add configuration schemas to every observation class
* Add router, firewall, port, and application observation
* Re-shape the dict structure of observations to make it adhere to CAOS 0.8
* Change existing configs to use the new structure
* make host observation separate

## Test process
existing and new unit tests as well as ad hoc notebooks

## Checklist
- [ ] PR is linked to a **work item**
- [ ] **acceptance criteria** of linked ticket are met
- [ ] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [ ] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

Related work items: #2417
2024-04-02 14:00:27 +00:00
Christopher McCarthy
742f1be81b Merged PR 320: #2419- Created a Router-specific version of SessionManager
## Summary
Created a Router-specific version of `SessionManager` that looks at route table rather than default gateway when dst ip address isn't for a locally attached network. Carried these changes through to arp. Added test for this. Made some minor improvements to show functions in container and node that assist debugging.

## Test process
TDD approach: wrote the test, ran it and watched it fail. The implemented the fix and re-ran the test; it passes.

**Before fix:**
![image (2).png](https://dev.azure.com/ma-dev-uk/b50a61ee-86c4-48bc-9a0b-a67645ba12ee/_apis/git/repositories/2825053e-bd3b-45b2-8680-1281809eefa2/pullRequests/320/attachments/image%20%282%29.png)

**After fix:**
![image.png](https://dev.azure.com/ma-dev-uk/b50a61ee-86c4-48bc-9a0b-a67645ba12ee/_apis/git/repositories/2825053e-bd3b-45b2-8680-1281809eefa2/pullRequests/320/attachments/image.png)

## Checklist
- [ ] PR is linked to a **work item**
- [ ] **acceptance criteria** of linked ticket are met
- [ ] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [ ] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

#2419

Related work items: #2419
2024-04-02 12:58:21 +00:00
Chris McCarthy
bb937c1092 #2149 - docstring changes following PR suggestions. 2024-04-02 12:56:15 +01:00
Marek Wolan
82143a2a2e #2446 Fix io config parsing order 2024-04-02 00:31:06 +01:00
Marek Wolan
d2c7ae481c #2417 Add categorisation and updated new configs from merge 2024-04-01 22:03:28 +01:00
Marek Wolan
e4300faa1c Merge remote-tracking branch 'origin/dev' into feature/2417-observation-refactor 2024-04-01 19:21:40 +01:00
Marek Wolan
2513646205 #2417 fix last observation tests 2024-04-01 16:50:59 +01:00
Cristian Genes
1dd911b417 Merged PR 322: #2402 Add ACL actions for routers and firewalls
## Summary
Added ACL addrule and removerule for routers and firewalls

## Test process
New test created to cover all possibilities

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [x] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [x] attended to any **TO-DOs** left in the code

Related work items: #2402, #2415
2024-04-01 15:34:26 +00:00
Marek Wolan
709486d739 #2417 test firewall and router obs 2024-04-01 16:06:12 +01:00
Cristian-VM2
80c13adfdf #2402 add action maps on all yaml scenarios used for testing 2024-04-01 14:28:41 +00:00
Cristian-VM2
2096b619ec #2402 raise error if action map is not specified. update comment in firewall.py 2024-04-01 12:32:44 +00:00
Marek Wolan
0ba767d2a0 #2417 update observation tests and make old tests pass 2024-04-01 00:54:55 +01:00
Marek Wolan
0e0df1012f #2417 update observations init to autoimport all obs types 2024-03-31 23:39:24 +01:00
Marek Wolan
8da53db822 #2417 Finalise parsing of observation space 2024-03-31 23:20:48 +01:00
Marek Wolan
62ebca8c08 #2417 Remove references to old obs names and add link obs 2024-03-31 21:39:24 +01:00
Marek Wolan
15cb2e6970 #2417 Add NestedObservation 2024-03-31 17:31:10 +01:00
Cristian-VM2
2546f268eb #2402 refactor port actions to take same input params (hostname) as new acl actions for routers and firewalls 2024-03-31 11:59:31 +00:00
Cristian-VM2
2d1f38bcb7 #2402 fix test 2024-03-29 17:28:40 +00:00
Cristian-VM2
d1301002d3 #2402 run pre-commits 2024-03-29 17:07:08 +00:00
Cristian-VM2
8763a27cca Merge remote-tracking branch 'origin/dev' into feature/2402-add-acl-actions-for-routers-and-firewalls 2024-03-29 16:37:37 +00:00
Cristian-VM2
7299a12c64 #2402 add firewall acl actions 2024-03-29 16:30:39 +00:00
Marek Wolan
22e1dfea2f #2417 Move classes to correct files 2024-03-29 14:14:03 +00:00
Marek Wolan
9123aff592 #2417 Add hella docstrings 2024-03-29 13:15:31 +00:00
Marek Wolan
1751714d3d Tidy up node observation file 2024-03-29 12:21:52 +00:00
Marek Wolan
d8a66104f5 Fixed observations 2024-03-29 11:55:22 +00:00
Cristian-VM2
2eb900746b #2402 rename network_acl actions to router_acl and refactor how router_name is given 2024-03-29 11:34:43 +00:00
Marek Wolan
f88b4c0f97 #2417 more observations 2024-03-28 17:40:27 +00:00
Cristian Genes
d415ef9c3e Merged PR 319: Add application install and remove actions
## Summary
Add application install and remove (uninstall) actions

## Test process
Both actions are tested in the same (new) test

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [x] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

Related work items: #2405
2024-03-28 16:37:01 +00:00
Cristian-VM2
2a5432fb0a Merge branch 'feature/2402-add-acl-actions-for-routers-and-firewalls' of ssh.dev.azure.com:v3/ma-dev-uk/PrimAITE/PrimAITE into feature/2402-add-acl-actions-for-routers-and-firewalls 2024-03-28 16:09:55 +00:00
Chris McCarthy
1ac3e1c6b4 #2149 - Created a Router-specific version of SessionManager that looks at route table rather than default gateway when dst ip address isn't for a locally attached network. Carried these changes through to arp. Added test for this. Made some minor improvements to show functions in container and node that assist debugging. 2024-03-28 15:52:08 +00:00
Cristian-VM2
cfea38c5a7 #2405 refactor e2e test, fix uninstalled apps not being removed from the request manager 2024-03-28 15:34:47 +00:00
Cristian-VM2
1e1eea47f1 #2405 add e2e test for application install and uninstall, refactor input params 2024-03-28 14:08:08 +00:00
Cristian-VM2
f83d9cb1b0 #2405 refactor application_uninstall_action to re-use existing code in uninstall_application 2024-03-28 12:14:05 +00:00
Cristian-VM2
8612842b74 #2405 remove .lower from _read_application_type, rename _software_manager to _software_request_manager in base.py 2024-03-28 12:01:36 +00:00
Marek Wolan
350b988318 #2418 Fix broken property 2024-03-28 11:29:22 +00:00
Marek Wolan
09caa55c65 #2418 - Add printer and wireless router as node types in network show 2024-03-28 11:29:22 +00:00
Marek Wolan
c29c3971fa #2418 - add wildcard masks and from_config tests to routers 2024-03-28 11:29:22 +00:00
Marek Wolan
e21c59dff1 #2418 - Change test config 2024-03-28 11:29:22 +00:00
Marek Wolan
b12dee73ba #2418 Fix wireless router from config 2024-03-28 11:29:22 +00:00
Marek Wolan
4301f3fdba #2418 Add Printer and Wireless router to config parser 2024-03-28 11:29:22 +00:00
Cristian-VM2
9b6135524e #2504 update application_install_action docstring 2024-03-28 11:08:30 +00:00
Cristian-VM2
d5b5c7d47a #2405 simplify implementation 2024-03-28 11:02:26 +00:00
Cristian-VM2
cddb39e8e9 #2405 update docstrings 2024-03-28 10:43:57 +00:00
Marek Wolan
0d0b5bc7d9 fix previous commit 2024-03-27 22:11:37 +00:00
Marek Wolan
cae9f64b93 New observations 2024-03-27 22:11:02 +00:00
Cristian-VM2
8bb7f8a177 #2405 add application install and remove actions 2024-03-27 17:07:12 +00:00
Marek Wolan
3d996f05bd Merged PR 318: #2418 Add Printer and Wireless router to config parser
## Summary
Add ability to parse printers and wireless routers from yaml config.

## Test process
Existing unit tests pass. Added a printer to one of the test yamls. Adding a wireless router as well now.

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [x] attended to any **TO-DOs** left in the code

Related work items: #2418
2024-03-27 13:35:33 +00:00
Cristian Genes
de2e5d0b7d Merged PR 317: Add actions for application close, scan and fix. Rename software patch to fix
## Summary
Added actions for application close, scan and fix
Renamed software patch to software fix
Fixed and enabled `test_node_service_scan_integration`

## Test process
All tests passed locally

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [x] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [x] attended to any **TO-DOs** left in the code

Related work items: #2404
2024-03-27 09:21:12 +00:00
Marek Wolan
fbb4eba6b7 Draft new observation space config 2024-03-27 03:27:44 +00:00
Marek Wolan
27bee58bf7 #2418 Fix broken property 2024-03-27 00:00:06 +00:00
Marek Wolan
368542df03 #2418 - Add printer and wireless router as node types in network show 2024-03-26 21:51:27 +00:00
Marek Wolan
9a8a42f3ec #2418 - add wildcard masks and from_config tests to routers 2024-03-26 21:48:17 +00:00
Cristian-VM2
94e637375d #2404 update software state to fixing in UC2 e2e notebook [skip ci] 2024-03-26 17:02:51 +00:00
Cristian-VM2
5860c74ef9 #2404 change software state from patching to fixing to align with CAOS v0.8 2024-03-26 16:41:11 +00:00
Marek Wolan
0e90e6a262 #2418 - Change test config 2024-03-26 16:23:39 +00:00
Marek Wolan
dca26b832d #2418 Fix wireless router from config 2024-03-26 13:21:22 +00:00
Cristian-VM2
b3c1b6b7a5 #2404 quick fix for failing test_query_fail_to_connect 2024-03-26 12:52:16 +00:00
Cristian-VM2
53126e79df #2404 remove extra code in test_query_when_client_is_closed 2024-03-26 12:43:45 +00:00
Cristian-VM2
128e2227d6 #2404 add missing test and revert some name changes 2024-03-26 12:39:11 +00:00
Marek Wolan
e560529639 #2418 Add Printer and Wireless router to config parser 2024-03-26 12:06:23 +00:00
Cristian-VM2
944b248300 #2404 rename software patch to fix 2024-03-26 10:51:33 +00:00
Cristian-VM2
600dc3f016 #2404 add application scan, close, and fix actions, fix and enable service scan test 2024-03-25 16:58:27 +00:00
Cristian Genes
8b8940f465 Merged PR 314: Add actions to enable/disable ports in routers/firewalls
## Summary
Added actions to enable/disable ports for routers/firewalls
Added tests for routers and added ticket in the backlog to test on firewalls (it's not possible to test at the moment because the game_and_agent fixture cannot build from a yaml file)

Improved the notebook for training sb3 agents on UC2 to include validated value for learning rate and fix for loading sb3 PPO from IY as well as code to evaluate agents

## Test process
Run new tests locally

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [x] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [x] attended to any **TO-DOs** left in the code

Related work items: #2403
2024-03-25 12:34:21 +00:00
Cristian-VM2
78b966ace4 fix port/nic enable/disable actions returning failure when they succeed 2024-03-25 11:41:07 +00:00
Cristian-VM2
4a5dd9ba0f fix typo 2024-03-25 11:08:36 +00:00
Cristian-VM2
bef2bd8084 add actions to enable/disable ports in routers/firewalls, improve notebook for training PPO agents 2024-03-22 16:35:53 +00:00
Marek Wolan
cb9c14c87e Merged PR 310: Pull last-minute beta 7 changes into dev
## Summary
the step label for actions was off by one from the step label in the step metadata log. Also the last episode was not outputting an action log because the reset method wasn't being called (there's a close method for this instead).

## Test process
Notebooks, pytests

## Checklist
- [~] PR is linked to a **work item**
- [~] **acceptance criteria** of linked ticket are met
- [y] performed **self-review** of the code
- [n] written **tests** for any new functionality added with this PR
- [n] updated the **documentation** if this PR changes or adds functionality
- [n] written/updated **design docs** if this PR implements new functionality
- [n] updated the **change log**
- [y] ran **pre-commit** checks for code style
- [y] attended to any **TO-DOs** left in the code

Related work items: #2230
2024-03-18 10:39:01 +00:00
Marek Wolan
bb01619918 Bump version 2024-03-15 16:17:45 +00:00
Marek Wolan
b4d310eda2 Align step counts in logging 2024-03-15 16:17:38 +00:00
Marek Wolan
a8c98c28f1 Merge remote-tracking branch 'origin/dev' into release/3.0.0b7 2024-03-15 16:13:50 +00:00
Czar Echavez
d5fb2f2309 Merged PR 307: #2369: commiting work done so far
## Summary
Added a page to explain how to use the Jupyter notebooks via jupyter command and VSCode

Also added Nick's suggestion to fix #2226

Going to be honest - not my finest pull request

## Test process
*How have you tested this (if applicable)?*

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [X] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

#2369: commiting work done so far

Related work items: #2369
2024-03-15 15:59:42 +00:00
Nick Todd
d8b75a33e4 Merged PR 309: 2384: Updates for 3.0.0b7 release.
## Summary
Updated CHANGELOG.md, lightly edited and corrected.

## Test process
N/A

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [X] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [X] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

2384: Updates for 3.0.0b7 release.

Related work items: #2384
2024-03-15 15:06:22 +00:00
Marek Wolan
b217869dd1 Improve clarity in docs 2024-03-15 15:03:27 +00:00
Marek Wolan
fc67fc4833 Fix notebook parsing data 2024-03-15 14:37:28 +00:00
Marek Wolan
9a38fcdae2 Fix broken config 2024-03-15 14:19:30 +00:00
Marek Wolan
8a9d8fb17c Calm logging again 2024-03-15 14:10:34 +00:00
Marek Wolan
7f4f3e9bfe Calm logging 2024-03-15 14:09:02 +00:00
Marek Wolan
c8beb39fac clear notebook output 2024-03-15 14:03:49 +00:00
Marek Wolan
33dd6e4dcd Make sure notebook is using correct dict key 2024-03-15 14:03:37 +00:00
Nick Todd
6f780f20d7 2384: Updates for 3.0.0b7 release. 2024-03-15 13:55:00 +00:00
Marek Wolan
d9b6506572 Mention python version in getting started guide. 2024-03-15 13:42:59 +00:00
Marek Wolan
6ce96f00fe Merge branch 'feature/2369-document-how-to-use-primaite-notebooks' of https://dev.azure.com/ma-dev-uk/PrimAITE/_git/PrimAITE into feature/2369-document-how-to-use-primaite-notebooks 2024-03-15 13:25:54 +00:00
Marek Wolan
2fde071789 Update docs on example notebooks 2024-03-15 13:25:50 +00:00
Marek Wolan
505f9dfb09 Merge remote-tracking branch 'origin/dev' into feature/2369-document-how-to-use-primaite-notebooks 2024-03-15 13:25:30 +00:00
Marek Wolan
40ba8c5ac0 Merged PR 308: Fix stubborn logs and default config values
## Summary
Ensure that the logging options are being read correctly from the config. Makes logs actually optional.

Also temporarily disable checkhash and replace it with file scan because checkhash is buggy.

## Test process
By inspection

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [x] attended to any **TO-DOs** left in the code

Fix some stuff

Related work items: #2382
2024-03-15 13:20:26 +00:00
Czar Echavez
e580fa0464 Merge remote-tracking branch 'origin/dev' into feature/2369-document-how-to-use-primaite-notebooks 2024-03-15 13:14:31 +00:00
Czar Echavez
1ed2f48f54 #2369: missed items 2024-03-15 13:13:54 +00:00
Marek Wolan
e0eef8e56e Fix tests 2024-03-15 12:19:56 +00:00
Marek Wolan
04c86e30c9 Fix some stuff 2024-03-15 11:15:02 +00:00
Marek Wolan
d257501703 Merged PR 304: Reward sharing
## Summary
* add ability for agents to share rewards - the calculated reward value for one agent can be used as a component of another agent's reward.
* Update UC2 configs to use the reward sharing functionality - green agents have a reward based on their two actions. Blue agent reward adds green agent rewards to itself.
* Add agent action history - This allows the rewards to react to agent actions.
* Make action logging use the new agent history.
* Make the webpage and database reward components treat failed requests the same as if the webpage was unavailable / database was unreachable.
* reorder the PrimaiteGame step to be the same as the Gymnasium env step
* update uc2 notebook accordingly.

## Test process
Tested with ad-hoc notebooks and debugging tool to verify correct data is being used. Tested notebooks run properly and pytests pass. Added unit and integration tests.

## Checklist
- [ ] PR is linked to a **work item**
- [ ] **acceptance criteria** of linked ticket are met
- [ ] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [ ] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

Related work items: #2372
2024-03-15 10:42:12 +00:00
Nick Todd
90224960e5 2299: Backup Jupyter notebook changes. 2024-03-15 10:33:58 +00:00
Marek Wolan
a9bf0981e6 Doc fixes 2024-03-15 09:22:55 +00:00
Czar Echavez
1d09f0791a #2369: Reduce dependency on manually replacing primaite version across documentation 2024-03-14 23:17:34 +00:00
Czar Echavez
88a3c42f2f #2369: commiting work done so far 2024-03-14 22:15:27 +00:00
Marek Wolan
d33c80d0d6 Minor fixes 2024-03-14 14:33:04 +00:00
Nick Todd
c5e142a500 2299: Remove calls to corrupt. 2024-03-13 17:43:56 +00:00
Marek Wolan
f438acf745 Add shared reward test 2024-03-13 14:01:17 +00:00
Marek Wolan
ee26554ef0 merge origin/dev into feature branch 2024-03-13 12:11:50 +00:00
Marek Wolan
10ee9b300f Update docs on rewards 2024-03-13 12:08:20 +00:00
Czar Echavez
c7c34e1fb6 Merged PR 301: #2350: Confirm action / observation space conforms to CAOS v0.7
## Summary
### **work related to v0.7 CAOS**
- Split observations.py into:
  - agent_observations.py
  - file_system_observations.py
  - node_observations.py
  - nic_observations.py
  - observation_manager.py
  - observations.py
  - software_observations.py
- added tests to ensure that the observations align with [QTSL-820-2450 - ARCD Track 2 Common Action Observation Space Definition v0.7](https://nscuk.sharepoint.com//r/sites/SSE32ARCDIDT/Shared%20Documents/General/ARCD/Architecture%20%26%20Design%20Documentation/Common/CAOS%20Related%20Documents/QTSL-820-2450%20-%20ARCD%20Track%202%20Common%20Action%20Observation%20Space%20Definition%20v0.7.xlsx?d=wee5713d8640b4b5bb3cb5624936e417e&csf=1&web=1&e=lByVQ5)

### preparation for v0.8 CAOS
WILL NOT AFFECT OBSERVATION SPACE FOR V0.7

**DO NOT PANIC**

these features are needed for v0.8

- integrated `num_access` to file (not used yet in file observations)
- integrated `num_file_deletions` and `num_file_creations` to file_system (not used yet in node observations)

## Test process
*How have you tested this (if applicable)?*

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

Related work items: #2350
2024-03-13 09:20:23 +00:00
Marek Wolan
6dedb91099 Remove redundant TODOs 2024-03-13 09:17:29 +00:00
Czar Echavez
f2c6f10c21 #2350: apply PR suggestions 2024-03-12 12:20:02 +00:00
Marek Wolan
045f467407 Update marl config 2024-03-12 11:51:17 +00:00
Marek Wolan
24fdb8dc17 Fix minor reward sharing bugs 2024-03-12 11:40:26 +00:00
Marek Wolan
03ee976a2d remove extra print statement 2024-03-12 11:00:55 +00:00
Marek Wolan
a76f5b0efb Merge remote-tracking branch 'origin/dev' into feature/2327-green-action-failure-part-II 2024-03-12 10:59:41 +00:00
Czar Echavez
ec4818e4d3 Merge remote-tracking branch 'origin/dev' into feature/2350-confirm-action-observation-space-conforms-to-CAOS-0.7 2024-03-12 09:11:30 +00:00
Marek Wolan
c3f1cfb33d Add shared reward 2024-03-11 22:53:39 +00:00
Marek Wolan
7599655879 Add agent action history 2024-03-11 20:10:08 +00:00
Marek Wolan
f46980b5f5 Merged PR 302: Make simulator requests able to provide a response
this PR is a pre-requisite to the work im doing today where green agents actions that fail to reach their target still incur a negative reward.

## Summary
- Requests now return a response.
- Added the request response to the agent logging and info output of env step.
- Changed all request types in the simulator to return a response
- Added a new 'validator' that allows nodes to execute actions only if the node is on (this check happens at the request level rather than in every single function)
- Fixed NMNE - made nic observation responsible for converting total NMNE this episode to NMNE last step because apply_timestep is applied after actions but before observations in the step method.
- Fixed arcd_uc2_network to configure the db clients and web browsers correctly
- Added tests for request responses

## Test process
New tests, existing tests pass.

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [x] written **tests** for any new functionality added with this PR
- [X] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [x] attended to any **TO-DOs** left in the code

Related work items: #2372
2024-03-11 19:48:18 +00:00
Czar Echavez
cd6d6325db #2350: add tests to check spaces + acl obs test + nmne space changes 2024-03-11 17:47:33 +00:00
Marek Wolan
1faefbccac Add docstring for init request manager 2024-03-11 10:20:47 +00:00
Marek Wolan
66ab5ec980 Fix last tests 2024-03-11 09:18:31 +00:00
Czar Echavez
a228a09917 #2350: documentation 2024-03-10 15:13:37 +00:00
Marek Wolan
d2afcaa939 Update changelog 2024-03-10 13:06:45 +00:00
Marek Wolan
e5c5a85003 Add docs on request response 2024-03-10 13:05:57 +00:00
Marek Wolan
f4684b0349 Fix how nmnes are getting put into obs space. 2024-03-09 23:32:00 +00:00
Marek Wolan
359777f4f8 Add tests for request success/fail 2024-03-09 23:06:53 +00:00
Marek Wolan
31ae4672ac Make nodes only accept requests when they're on 2024-03-09 20:47:57 +00:00
Czar Echavez
cc721056d8 #2350: configurable NMNE category thresholds 2024-03-08 19:32:07 +00:00
Marek Wolan
289b5c548a Make a type alias for request & fix typo 2024-03-08 17:14:41 +00:00
Marek Wolan
0447a05084 Add call validation 2024-03-08 15:57:43 +00:00
Marek Wolan
beb51834f9 Make all requests return a RequestResponse 2024-03-08 14:58:34 +00:00
Czar Echavez
61aa242128 #2350: tests + application 2024-03-08 14:48:31 +00:00
Czar Echavez
ba58204542 #2350: split observations into smaller files 2024-03-08 14:08:35 +00:00
Czar Echavez
b13725721d #2350: splitting observations into separate files 2024-03-08 13:49:00 +00:00
Marek Wolan
d331224b45 Start introducing RequestResponse 2024-03-08 12:42:22 +00:00
Czar Echavez
e9eef2b4c0 #2350: add num_access, num_file_deletions and num_creations to file system 2024-03-08 11:16:27 +00:00
Marek Wolan
59bbc0e733 Merged PR 299: Match default reward configs to Imaginary Yak.
## Summary
Change the default rewards for the data manipulation configs
Also I renamed the config files to make their names more descriptive.

## Test process
Pytests and all notebooks run without fail.

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [x] attended to any **TO-DOs** left in the code

Related work items: #2365
2024-03-07 21:52:55 +00:00
Marek Wolan
81a375d6c4 Merged PR 298: Update NMNE to only count MNEs in the last step.
## Summary
The NMNE counts MNEs since last step rather than since last episode.

## Test process
Updated unit tests to check for the new behaviour and added new test.

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [x] written **tests** for any new functionality added with this PR
- [x] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [x] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [x] attended to any **TO-DOs** left in the code

There's no update necessary to the docs or change log because it NMNE is already documented, and the text is still correct given this minor change.

Related work items: #2348
2024-03-07 16:20:39 +00:00
Marek Wolan
618da8abe9 Rename notebooks 2024-03-07 15:25:11 +00:00
Marek Wolan
76752fd9af Change the nmne clear to happen at apply_timestep instead of within describe_state 2024-03-07 14:44:44 +00:00
Marek Wolan
17d4807660 Rename configs 2024-03-07 14:33:21 +00:00
Marek Wolan
2547361daf Change default reward weights 2024-03-07 13:52:26 +00:00
Marek Wolan
a900d59f7b Update NMNE to only count MNEs in the last step. 2024-03-07 12:15:30 +00:00
Marek Wolan
8589ce449a Merged PR 295: Agent action logging
## Summary
Added a new optional capability to create a JSON log each episode with a list of action each agent took each step (including scripted, RL, and red agents).

Also I had to slightly refactor the IO system to not rely on PrimaiteSession, as it's gonna be deprecated soon. Therefore the IO module is now linked to the gym environment. Each time you init a gym environment, it creates a session directory.

## Test process
Tried the SB3, Ray SARL and Ray MARL notebooks to see that the outputs get generated.

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [x] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [x] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [x] attended to any **TO-DOs** left in the code

Move IO to environments from session and add agent logging

Related work items: #2278
2024-03-05 16:39:44 +00:00
Marek Wolan
e117f94f43 Minor doc fix 2024-03-05 15:46:30 +00:00
Marek Wolan
72e0c3b402 Merged PR 296: Add a notebook to customise red agent behaviour
## Summary
just run the notebook and see if the explanation makes sense.

I also renamed some stuff to make it more user friendly

Related work items: #2343
2024-03-05 12:02:19 +00:00
Marek Wolan
a7bfc56b98 Apply documentation changes based on PR review. 2024-03-05 11:21:49 +00:00
Marek Wolan
3e495c4622 Cosmetic changes to notebook 2024-03-05 09:28:22 +00:00
Marek Wolan
758f892b74 Make notebook for varying red agent behaviour in uc2 2024-03-04 21:04:27 +00:00
Marek Wolan
a222a8c58f Give the UC2 config load function a meaningful name 2024-03-04 19:43:51 +00:00
Marek Wolan
1e8dfa40cf Give uc2 notebook a meaningful name 2024-03-04 19:36:54 +00:00
Marek Wolan
d0225bf3e1 Merge remote-tracking branch 'origin/dev' into feature/2278-log-agent-actions 2024-03-04 19:00:03 +00:00
Marek Wolan
c3010ff816 Update changelog and docs 2024-03-04 18:59:03 +00:00
Marek Wolan
2f456e7ae0 Move IO to environments from session and add agent logging 2024-03-04 18:47:50 +00:00
Marek Wolan
84f5d45540 Merged PR 294: Update actions set in uc2 to match Yak
## Summary
Expand the available actions.

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [x] written **tests** for any new functionality added with this PR
- [x] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [x] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [x] attended to any **TO-DOs** left in the code

Related work items: #2243
2024-03-04 14:39:07 +00:00
Marek Wolan
bc830e6458 Merge remote-tracking branch 'origin/dev' into feature/2243-sync-uc2-action-to-iy 2024-03-04 13:39:22 +00:00
Marek Wolan
c32bd3f941 Merged PR 285: Green agent that sometimes performs database connections
## Summary
* removed `GreenWebBrowsingAgent` because it was replaced by probabilistic agent
* created new 'probabilistic agent' which selects actions randomly from its action map, with configurable probabilities
* slightly refactored action manager to decouple it from `PrimaiteGame` (as a consequence, agents should be given the current timestep if their `get_action()` method is time-dependent)
* refactored `data_manipulation_bot` to use an existing db client on the host rather than inheriting from it
* added new type of SQL query to databases: `"SELECT * FROM pg_stat_activity"` to model checking connection status
* added new execution definition on the `DatabaseClient` app which just performs that new SQL query
* added reward for the green admin being able to connect to the db
* updated uc2 notebook to reflect new changes.
* updated documentation for data manipulation bot
* added new test for probabilistic agent
* added test for new reward

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [x] written **tests** for any new functionality added with this PR
- [x] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [x] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [x] attended to any **TO-DOs** left in the code

Related work items: #2319
2024-03-04 12:06:55 +00:00
Marek Wolan
2c3652979b Add helpful error messages to action index errors 2024-03-04 11:17:54 +00:00
Marek Wolan
ac9d550e9b Change get_action signature for agents 2024-03-04 10:43:38 +00:00
Marek Wolan
d1480e4477 Apply suggestions from PR review. 2024-03-04 09:58:57 +00:00
Marek Wolan
0d490d618c Update MARL config 2024-03-03 16:59:14 +00:00
Marek Wolan
a4c723858b Update action map in second 2024-03-03 16:57:53 +00:00
Marek Wolan
afc3635bfe Update changelog 2024-03-03 16:56:52 +00:00
Marek Wolan
ea1d016bc2 Merge remote-tracking branch 'origin/feature/2319-database-admin' into feature/2243-sync-uc2-action-to-iy 2024-03-03 16:55:42 +00:00
Marek Wolan
0e8c60df4c Update actions 2024-03-03 16:53:18 +00:00
Marek Wolan
a6031d568d Remove unused import 2024-03-03 16:36:08 +00:00
Marek Wolan
ef1a2dc3f4 clear uc2 notebook outputs 2024-03-03 16:00:10 +00:00
Marek Wolan
afa775baff Add test for new reward 2024-03-03 15:52:34 +00:00
Marek Wolan
4d51b1a414 Update configs to new db manipulation bot approach 2024-03-03 14:57:28 +00:00
Marek Wolan
070655cfce Update data manipulation bot documentation 2024-03-03 11:47:50 +00:00
Marek Wolan
9762927289 Update notebook with new changes 2024-03-03 11:43:24 +00:00
Marek Wolan
fe13583d2a Merge remote-tracking branch 'origin/dev' into feature/2319-database-admin 2024-03-03 11:24:09 +00:00
Marek Wolan
4a292a6239 Fix checking connection in db client 2024-03-03 11:23:24 +00:00
Marek Wolan
80158fd9b4 Make db manipulation bot work with db client 2024-03-03 11:18:06 +00:00
Christopher McCarthy
e8b1177c18 Merged PR 291: #2357 - Allow empty nodes, links, and agents arrays in config file
## Summary
Allowed the config to not have nodes, links and agents and still be parsed

## Test process
Tested with config file that doesn't have any simulation key/value pair

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

#2357 - Allowed the config to not have nodes, links and agents and still be parsed

Related work items: #2357
2024-03-02 19:30:22 +00:00
Christopher McCarthy
e5ebf6a745 Merged PR 292: #2358 - Use class name for node type properties in network container
## Summary
The node-specific properties in Network class now simply use node.__class__.__name__ to check their type for filtering by type

## Test process
Tests updated to use the new property function names

## Checklist
- [ ] PR is linked to a **work item**
- [ ] **acceptance criteria** of linked ticket are met
- [ ] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [ ] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

#2358 - the node-specific properties in Network class now simply use node.__class__.__name__ to check their type for filtering by type. Tests updated to use the new property function names

Related work items: #2358
2024-03-02 18:34:51 +00:00
Chris McCarthy
81fd43035d #2358 - the node-specific properties in Network class now simply use node.__class__.__name__ to check their type for filtering by type. Tests updated to use the new property function names 2024-03-01 22:51:01 +00:00
Chris McCarthy
af036f63f1 #2357 - Allowed the config to not have nodes, links and agents and still be parsed 2024-03-01 22:37:51 +00:00
Czar Echavez
ac304c85a3 Merged PR 290: #2356: optional dmz port + optional external acl rules
## Summary
Bug fix to allow firewall dmz port to be optional as well as external acl rules to be optional

## Test process
See https://dev.azure.com/ma-dev-uk/PrimAITE/_git/PrimAITE/pullrequest/290?_a=files&path=/tests/integration_tests/configuration_file_parsing/nodes/network/test_firewall_config.py

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

#2356: optional dmz port + optional external acl rules

Related work items: #2356
2024-03-01 17:49:37 +00:00
Czar Echavez
78ff658e30 #2356: optional dmz port + optional external acl rules 2024-03-01 16:48:05 +00:00
Marek Wolan
2a1d99ccce Fix problem with checking connection for db admin 2024-03-01 16:36:41 +00:00
Marek Wolan
ed01293b86 Make db admin reward persistent 2024-03-01 16:02:27 +00:00
Marek Wolan
10a4053887 Fix tests 2024-03-01 15:14:00 +00:00
Marek Wolan
9ff8adab1a Merge remote-tracking branch 'origin/dev' into feature/2319-database-admin 2024-03-01 09:23:00 +00:00
Czar Echavez
b849bfd6e2 Merged PR 280: Router Routes and Configuration documentation updates
## Summary

- Updated Sphinx 6.1.3 => 7.1.2
- Updated furo 2023.3.27 => 2024.01.29
- Added tests to check that firewall, routers and nodes are properly added via config (config parser tests)
- Added some reference points in code comments for Sphinx documentation to reference
- Created a list of System Software so it can be referenced in docs and by code
- Added default values to config within game.py (The defaults are pulled from example_config.yaml)
- Created a section for creating a session via config files:
    - set up a lot of stuff so documentation is easier to maintain
    - Template for things that are repeated in places
    - added how to create nodes via config
    - added how to install applications and services via config
- diagrams to make it easier to understand some stuff e.g. ACL rules for firewall

see https://dev.azure.com/ma-dev-uk/PrimAITE/_git/PrimAITE/pullrequest/280?_a=files&path=/CHANGELOG.md

## Test process
- Firewall:
  - Created a DMZ Network example config
  - Tested the creation of Firewall
  - Tested the ACL Rules of Firewall

https://dev.azure.com/ma-dev-uk/PrimAITE/_git/PrimAITE/pullrequest/280?_a=files&path=/tests/integration_tests/configuration_file_parsing/nodes/network/test_firewall_config.py

https://dev.azure.com/ma-dev-uk/PrimAITE/_git/PrimAITE/pullrequest/280?_a=files&path=/tests/integration_tests/configuration_file_parsing/nodes/network/test_router_config.py

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [X] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [X] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [X] attended to any **TO-DOs** left in the code

Related work items: #2257
2024-02-29 16:22:55 +00:00
Czar Echavez
69b7ca1703 Merge remote-tracking branch 'origin/dev' into feature/2257-router-routes-cannot-be-represented-in-config-file 2024-02-29 15:21:20 +00:00
Czar Echavez
49a4e1fb56 #2257: added common node attributes page + ability to set node operating state via config + tests 2024-02-29 15:20:54 +00:00
Christopher McCarthy
90d51c071c Merged PR 288: #2326 - Network Interface port name/num fixed so that it carries through to s...
## Summary
This pull request fixes the issue o network interface port name and number not being pulled through into sys log and PCAP output files.

## Test process
Manually checked:
![image (4).png](https://dev.azure.com/ma-dev-uk/b50a61ee-86c4-48bc-9a0b-a67645ba12ee/_apis/git/repositories/2825053e-bd3b-45b2-8680-1281809eefa2/pullRequests/288/attachments/image%20%284%29.png)
![image (2).png](https://dev.azure.com/ma-dev-uk/b50a61ee-86c4-48bc-9a0b-a67645ba12ee/_apis/git/repositories/2825053e-bd3b-45b2-8680-1281809eefa2/pullRequests/288/attachments/image%20%282%29.png)
![image (3).png](https://dev.azure.com/ma-dev-uk/b50a61ee-86c4-48bc-9a0b-a67645ba12ee/_apis/git/repositories/2825053e-bd3b-45b2-8680-1281809eefa2/pullRequests/288/attachments/image%20%283%29.png)

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [X] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

#2326 - Network Interface port name/num fixed so that it carries through to sys log and PCAP outputs.

Related work items: #2326
2024-02-29 15:14:08 +00:00
Chris McCarthy
8f0de8521e #2326 - removed port_name print statement 2024-02-29 14:08:42 +00:00
Marek Wolan
bd0b2e0033 Remove redundant notebook cells 2024-02-29 13:22:41 +00:00
Marek Wolan
2f3e40fb6b Fix issue around reset 2024-02-29 13:22:05 +00:00
Marek Wolan
f7c535b557 Merge 'origin/dev' into feature/2319-database-admin 2024-02-29 13:21:44 +00:00
Chris McCarthy
cf0674ce22 #2326 - Network Interface port name/num fixed so that it carries through to sys log and PCAP outputs. 2024-02-29 13:00:27 +00:00
Czar Echavez
eefc2739c8 Merge remote-tracking branch 'origin/dev' into feature/2257-router-routes-cannot-be-represented-in-config-file 2024-02-29 11:34:56 +00:00
Marek Wolan
312b5c35bd Merged PR 283: Refactor episode reset
## Summary
Instead of setting all attributes back to a snapshot, simply recreate the entire game and all agents from a cached copy of the config.

This removes the need for `set_original_state` and `reset_component_for_episode` methods on SimComponents.

## Test process
* Unit tests passing
* I've also tried adding a `__del__` method to simcomponent and agent and press env.reset() to verify that the ref count reaches 0, and nothing is secretly keeping using an old part of the simulation.

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [X] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [X] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

Related work items: #2317
2024-02-29 11:11:03 +00:00
Czar Echavez
9a4587155b #2257: specifically stating that enpoint refs are node hostnames + remove TODO 2024-02-29 11:07:21 +00:00
Marek Wolan
ce39387f92 Merge 'origin/dev' into feature/2317-refactor-reset 2024-02-29 10:16:42 +00:00
Marek Wolan
8730330f73 Apply PR suggestions 2024-02-29 10:14:31 +00:00
Czar Echavez
13db07dc11 Merge remote-tracking branch 'origin/dev' into feature/2257-router-routes-cannot-be-represented-in-config-file 2024-02-28 15:09:23 +00:00
Czar Echavez
6d43c61058 #2257: apply PR suggestions 2024-02-28 15:08:00 +00:00
Christopher McCarthy
98427b0e73 Merged PR 279: #2238 - Implement NMNE detection and capture
## Summary

This pull request introduces new features for capturing Malicious Network Events (NMNE) within the `NetworkInterface` class and extends the functionality to the `NicObservation` class .Additionally, it updates the simulation configuration to allow customizable NMNE capturing settings.

### Changes
- `NetworkInterface` Enhancements: Added NMNE capturing capabilities to detect and log specified malicious activities.
- `NicObservation` Integration: Updated to support detailed monitoring and analysis based on NMNE capturing results.
- Simulation Configuration: Introduced nmne_config options allowing users to enable NMNE capturing and define specific keywords, enhancing the adaptability of network security measures.

### New Configuration Options
Added to simulation.yml:
``` yaml
simulation:
  network:
    nmne_config:
      capture_nmne: true
      nmne_capture_keywords:
        - DELETE
```

Tests

Documentation
Updated README and related documentation to guide users on how to utilize the new NMNE capturing features and configure them in their simulations.

## Test process
- **NMNE Capture Testing**: Implemented tests using the UC2 network setup, where DELETE SQL queries are initiated by the database client residing on the web server and targeted towards the database service on the database server. Post-query, the network interface cards (NICs) on both servers are examined to verify accurate counting and logging of NMNE (Malicious Network Events) as expected per configuration.

- **NicObservation Testing**: Introduced additional tests to ensure proper integration of the `NicObservation `class, focusing on its ability to accurately observe and report NMNE occurrences.

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [X] updated the **documentation** if this PR changes or adds functionality
- [X] written/updated **design docs** if this PR implements new functionality
- [X] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [X] attended to any **TO-DOs** left in the code

#2238

Related work items: #2238
2024-02-28 14:57:46 +00:00
Chris McCarthy
63ea5478ab #2238 - Updated uc2_demo.ipynb to explain the NMNE in observation space 2024-02-28 13:56:19 +00:00
Chris McCarthy
d55b6a5b48 #2238 - Fixed the observations issue causing tests to fail 2024-02-28 12:03:58 +00:00
Marek Wolan
af8ca82fcb Get the db admin green agent working 2024-02-27 13:30:16 +00:00
Marek Wolan
c54f82fb1b Start implementing green agent logic for UC2 2024-02-26 20:08:13 +00:00
Marek Wolan
922298eaf0 Make database admin action possible 2024-02-26 20:07:02 +00:00
Marek Wolan
33d2ecc26a Apply suggestions from code review. 2024-02-26 16:58:43 +00:00
Marek Wolan
f9cc5af7aa Not sure how this test was passing before 2024-02-26 16:06:58 +00:00
Czar Echavez
f2d7a2fc16 #2257: added way to ensure nodes are on at start + more test to make sure nodes are on when added via config 2024-02-26 14:34:34 +00:00
Marek Wolan
2076b011ba Put back default router rules 2024-02-26 14:26:47 +00:00
Marek Wolan
a5043a8fbe Modify tests based on refactoring 2024-02-26 12:15:53 +00:00
Czar Echavez
d738a23709 #2257: list of db payloads 2024-02-26 11:35:17 +00:00
Marek Wolan
ccb10f1160 Update docs based on reset refactor 2024-02-26 11:02:37 +00:00
Marek Wolan
e5982c4599 Change agents list in game object to dictionary 2024-02-26 10:26:28 +00:00
Czar Echavez
634f634097 #2257: fix text and make examples in node configs more specific 2024-02-26 09:47:12 +00:00
Czar Echavez
e964b8a3ea #2257: more in depth changelog 2024-02-26 08:58:03 +00:00
Czar Echavez
1d5c153752 #2257: changelog update 2024-02-26 08:49:11 +00:00
Czar Echavez
07373d941e #2257: Downgrade version of sphinx - 7.2.0 drops support for Python 3.8 2024-02-26 08:44:08 +00:00
Marek Wolan
63c9a36c30 Fix typos 2024-02-25 18:36:20 +00:00
Marek Wolan
994dbc3501 Finalise the refactor. It works well now. 2024-02-25 17:44:41 +00:00
Marek Wolan
a34cf08209 Merge remote-tracking branch 'origin/dev' into feature/2317-refactor-reset 2024-02-25 16:41:40 +00:00
Marek Wolan
c115095157 Fix router from config using wrong method 2024-02-25 16:17:12 +00:00
Czar Echavez
fb148dc4fb #2257: applications and services docs 2024-02-23 16:49:01 +00:00
Chris McCarthy
52677538a8 #2238 - Tidied up code, added more docstrings, and implemented suggestions from PR. 2024-02-23 15:12:46 +00:00
Marek Wolan
f933341df5 eod commit 2024-02-23 10:06:48 +00:00
Czar Echavez
ef61fe219c Merge remote-tracking branch 'origin/dev' into feature/2257-router-routes-cannot-be-represented-in-config-file 2024-02-23 08:56:35 +00:00
Czar Echavez
5836ea68e3 #2257: rearrange software pages + creating a list of applications and services which is hopefully a single point that should be referred to 2024-02-23 08:55:32 +00:00
Chris McCarthy
771a68dccb #2238 - Implement NMNE detection and logging in NetworkInterface.
- Enhance NicObservation for detailed NMNE event monitoring.
- Add nmne_config options to simulation settings for customizable NMNE capturing.
- Update documentation and tests for new NMNE features and simulation config.
2024-02-22 22:43:14 +00:00
Czar Echavez
98fb28cbbc #2257: setting up application and service docs 2024-02-21 18:19:16 +00:00
Czar Echavez
deb7a3aa9d #2257: massive docs addition for config file 2024-02-21 14:49:59 +00:00
Marek Wolan
8f85555709 Merged PR 278: Enable the red agent to vary its start node
## Summary
- Made the data manipulation red agent be able to choose between the two clients to start operating on
- changed the attacker name in the config to 'data_manipulation_attacker' to because it is no longer tied to any client
- Updated the documentation notebook accordingly.
- Fixed a bug where the database client made a new connection every time it sent a SQL query (it tries to reuse its most recent one instead)
- Fixed a bug where link loads were not being cleared between episodes (?)

**warning** - the green agents are not working properly after reset right now, but I'm gonna fix this in the next ticket where I refactor episode reset.

## Test process
- unit tests pass
- UC2 notebook passes with both clients. (currently this doesn't work after an episode reset, but the very next thing I'm gonna work on is refactoring the reset, so I don't want to waste time fixing this.)

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [x] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [x] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [n] attended to any **TO-DOs** left in the code

Related work items: #2232
2024-02-20 20:22:20 +00:00
Marek Wolan
72f4cc0a50 Remove reset methods from most classes 2024-02-20 16:56:25 +00:00
Marek Wolan
f82506023b Delete set_original_state method definitions 2024-02-20 16:29:27 +00:00
Marek Wolan
64b9ba3ecf Make environment reset reinstantiate the game 2024-02-20 16:21:03 +00:00
Marek Wolan
88f8e9cb42 Add todo comment. 2024-02-20 12:09:32 +00:00
Marek Wolan
f7c1da3118 Update MARL config. 2024-02-20 12:06:30 +00:00
Marek Wolan
76db5dbaa2 Update changelog 2024-02-20 12:05:02 +00:00
Marek Wolan
4a3c66bdc6 Clear notebook code cells. 2024-02-20 12:04:07 +00:00
Marek Wolan
701781b23e Clear link load in new timestep 2024-02-20 11:05:09 +00:00
Marek Wolan
945db1341b Make database client try to use most recent connection instead of generating new one 2024-02-20 11:04:53 +00:00
Czar Echavez
2e2d83c3e9 #2257: update sphinx version + cleaning up some errors + splitting configuration page into multiple pages 2024-02-16 16:14:36 +00:00
Nick Todd
317fbdbb9c 2230: Version bump 2024-02-16 12:46:36 +00:00
Czar Echavez
e390d8385c #2257: acl tests 2024-02-15 16:29:36 +00:00
Czar Echavez
48d7f9f85a Merge remote-tracking branch 'origin/dev' into feature/2257-router-routes-cannot-be-represented-in-config-file 2024-02-15 15:45:44 +00:00
Czar Echavez
b739823318 #2257: add firewall via config + fix router hop ip address + shuffling around tests 2024-02-15 15:45:18 +00:00
Czar Echavez
23a56ca59f Merged PR 270: #2258: DoSBot cannot be added via configuration file
## Summary
- Added ability to set DoSBot in nodes via config file
- Fixed missing configuration items in other services/applications
- Created a variable which contains the list of applications and services
- Moved `DatabaseClient` from list of services to list of applications

## Test process
Created a configuration file where a node has all services and applications installed, this is then used by an integration test which loads the configuration file. The test checks to make sure that the configuration file is correctly read and the Service and Application objects are properly created

## Checklist
- [X] PR is linked to a **work item**
- [ ] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [ ] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

Related work items: #2258
2024-02-15 09:36:08 +00:00
Nick Todd
0af2eef89c Merged PR 274: Add INSERT query functionality into database service.
## Summary
Add support for SQL INSERT query in database_service.py.

## Test process
Updated test_database_on_node.py to test for database INSERTions.

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [X] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [X] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

Related work items: #2306
2024-02-14 16:51:25 +00:00
Nick Todd
8520f22e22 2306: Updated documentation 2024-02-14 13:35:08 +00:00
Nick Todd
4a38672fea 2306: Handle INSERT query 2024-02-14 13:18:20 +00:00
Nick Todd
07a934ab66 2306: Update tests to verify INSERT query. 2024-02-14 12:00:08 +00:00
Czar Echavez
ab7c7b9c06 Merge remote-tracking branch 'origin/dev' into feature/2257-router-routes-cannot-be-represented-in-config-file 2024-02-13 17:37:34 +00:00
Czar Echavez
98a4fbecb5 Merge remote-tracking branch 'origin/dev' into feature/2258-dosbot-cannot-be-added-via-configuration-file 2024-02-13 16:04:02 +00:00
Christopher McCarthy
9835b31dc5 Merged PR 272: #2205 - Firewall Node
## Description:

This pull request introduces the Firewall class and extends the ACLRule functionality within PrimAITE to provide comprehensive network traffic management and security capabilities. These enhancements enable detailed control over data flow through network simulations, mimicking real-world firewall operations and ACL configurations. The updates focus on the addition of a Firewall node that extends the Router class functionalities and the enhancement of ACLRule to support IP ranges through wildcard masking, thus offering granular traffic filtering based on IP addresses, protocols, ports, and more.

## Key Features:

**Firewall Class:** A new class that extends the Router class, incorporating firewall-specific logic for inspecting, directing, and filtering traffic between the internal, external, and DMZ (De-Militarized Zone) network interfaces. The Firewall class supports configuring network interfaces and applying Access Control Lists (ACLs) for inbound and outbound traffic control.

**Enhanced ACLRule:** The ACLRule class has been updated to support IP ranges using wildcard masking. This allows for more flexible rule definitions, enabling users to specify broad network ranges or individual IP addresses in ACL rules.

**Comprehensive ACL Configuration:** Six distinct ACLs (internal inbound, internal outbound, DMZ inbound, DMZ outbound, external inbound, and external outbound) provide meticulous control over traffic flow, ensuring robust network security. Examples included in the documentation illustrate how to configure ACLs for common scenarios, such as blocking external threats, permitting specific services, and restricting access to sensitive internal resources.

**Intuitive Interface and ACL Management:** Simplified methods for configuring firewall interfaces and ACL rules enhance usability. The Firewall class offers intuitive functions for rule management, including adding, removing, and listing ACL rules.

**Detailed Documentation and Examples:** Accompanying the code updates, comprehensive documentation and example configurations are provided, detailing the use and configuration of the Firewall node and ACL rules within PrimAITE simulations.

## Impact:

The introduction of the Firewall class and the enhancement of ACLRule significantly broaden PrimAITE's capabilities for simulating realistic network security scenarios. Users can now accurately model the behavior of firewalls in their network simulations, applying complex ACLs to control traffic flow and enforce security policies. This update enables more detailed network security analyses, teaching, and experimentation within the PrimAITE environment.

## Test process
Extensive unit tests have been added to cover the new functionality, ensuring reliability and correctness. Tests include scenarios for firewall configuration, ACL rule application, traffic filtering based on various criteria, and interaction between different network zones.

## Checklist
- [X] PR is linked to ...
2024-02-13 13:56:56 +00:00
Czar Echavez
b277034e8b #2257: temporarily commit changes - added startup and shut down durations to node config + adding routes 2024-02-13 13:02:24 +00:00
Chris McCarthy
7b64d99a63 #2205 - Final suggestions from PR 2024-02-13 12:56:41 +00:00
Czar Echavez
f4369a4fff Merge remote-tracking branch 'origin/dev' into feature/2257-router-routes-cannot-be-represented-in-config-file 2024-02-13 10:50:45 +00:00
Chris McCarthy
426c0a6682 2205 - Slimmed down the capability of the wireless router for now 2024-02-13 10:18:06 +00:00
Nick Todd
a6f3c458d5 Merged PR 273: 2297: Convert NTP Client and Server to UDP
## Summary
Replaced references to TCP with UDP in NTP client and server code. Updated docs.

## Test process
Re-ran and passed existing tests.

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [X] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

2297: Convert NTP Client and Server to UDP

Related work items: #2297
2024-02-13 09:43:09 +00:00
Czar Echavez
2c743005cd #2257: moved config tests into its own directory + added dmz_network.yaml to use in tests 2024-02-12 18:58:10 +00:00
Nick Todd
4c66d2b252 2297: Change missed reference TCP to UDP. 2024-02-12 17:24:28 +00:00
Nick Todd
697e53def8 2297: Doc update. 2024-02-12 17:12:59 +00:00
Nick Todd
fa08e53b15 2297: Convert NTP Client and Server to UDP 2024-02-12 17:01:53 +00:00
Chris McCarthy
add09a0280 #2205 - Tidied up interface creation and applied some suggestions from PR 2024-02-12 14:08:55 +00:00
Chris McCarthy
cfd64333e2 #2205 - Added wireless router tests and documentation. Refactored some code based on PR suggestions. 2024-02-12 12:31:08 +00:00
Czar Echavez
7beacfd95f #2258: missing some configuration items + added more tests 2024-02-12 11:41:55 +00:00
Czar Echavez
da92d74236 #2258: remove unnecessary ntp server check 2024-02-12 09:01:30 +00:00
Czar Echavez
66a3e8d02c Merge remote-tracking branch 'origin/dev' into feature/2258-dosbot-cannot-be-added-via-configuration-file 2024-02-12 08:57:47 +00:00
Chris McCarthy
9df7ceed3d #2205 - feat: Implement AirSpace and WirelessRouter for Enhanced Network Simulations
This commit introduces the AirSpace and WirelessRouter classes, expanding the PrimAITE's capabilities to simulate wireless networking environments. The AirSpace class manages wireless communications, ensuring seamless transmission across different frequencies. Meanwhile, the WirelessRouter class integrates both wired and wireless networking functionalities.
2024-02-10 23:44:08 +00:00
Chris McCarthy
a8c1e2b9d9 #2205 - Fixed ACLRule.is_permitted function by returning a bool that indicates whether the rule was matched or not to allow the AccessControlList to know whether to pay attention to the rule or not when it's iterating over them. 2024-02-10 21:32:13 +00:00
Chris McCarthy
58af58810d #2205 - Introduced a Firewall class for enhanced network security and control, extending Router functionalities. Updated ACLRule to support IP ranges via wildcard masking for refined traffic filtering. Includes documentation updates. 2024-02-09 23:29:06 +00:00
Christopher McCarthy
a960741f66 Merged PR 269: Refactor Network Infrastructure: Introduce ARP & ICMP Services and Network Interface Hierarchy
## Summary

This pull request encompasses a series of significant refactoring and enhancements aimed at improving the network simulation framework's architecture and functionality. Central to these changes is the introduction of ARP and ICMP as standalone services, the creation of a structured hierarchy for network interfaces, and a comprehensive overhaul of the testing suite to align with these new developments.

### Key Changes:

ARP and ICMP as Services: Transitioned ARP into a dedicated service, laying the groundwork for more sophisticated network interaction simulations. This shift involved substantial refactoring but has resulted in the successful integration of ARP requests within the network service architecture. Following this, ICMP was also encapsulated as a service, utilizing the session manager for packet transmission, thereby enhancing modularity and interaction within the network.

Network Interface Hierarchy: Introduced a hierarchy for network interfaces, differentiating between wired (NIC, SwitchPort) and wireless (WirelessNIC, WirelessAccessPoint) interfaces. This structure is further enriched with the Layer3Interface abstract base class, facilitating IP-based communications across both wired and wireless mediums.

PCAPs (Packet Capture) are now logged separately for inbound and outbound frames.

Test Suite Overhaul: Undertook a significant refactor of the testing suite, shifting to utilize the newly introduced Node subclasses (Computer, Server, Router, Switch) and the Network() class for node management and connection setup. This effort ensures that tests more accurately reflect the intended usage patterns and configurations within the simulation framework.

IPV4Address Validation and Conversion: Added a new IPV4Address type with pre-validation and auto-conversion capabilities, streamlining the handling of IPv4 addresses throughout the framework.

### Commit Highlights:

1. Commenced by integrating ARP as a service, facing initial challenges but achieving a functional ARP request capability as a milestone (Initial crack at getting ARP into a Service).
1. Progressed to fully integrate ARP service and link it with ICMP operations, marking a significant advancement in service-based network interactions (Lots more progress).
1. Began the process of encapsulating ICMP within the service model, necessitating further adjustments and test fixes (Initial work has been done on moving ICMP into services).
1. Completed the ICMP service integration, enhancing PCAP logging for inbound and outbound frames, and began addressing test suite discrepancies (ICMP now working as a service).
1. Implemented a broad refactor of the base network model to introduce a clear network interface hierarchy and started troubleshooting routing tests affected by ARP integration issues (Big refactor of base).

### Conclusion:

These changes collectively represent a leap forward in the framework's architecture, laying a robust foundation for future enhancements and ...
2024-02-09 12:50:58 +00:00
Czar Echavez
d1c3f891bf #2258: moving applications to application types - more tests 2024-02-09 11:41:06 +00:00
Chris McCarthy
6b3829dc48 #2248 - Removed redundant Union from single type params 2024-02-09 11:37:47 +00:00
Chris McCarthy
cceb6208e0 #2248 - Reset the auto save pcap and syslog to False 2024-02-09 11:09:44 +00:00
Chris McCarthy
2518a42604 #2248 - Dropped old router_arp.py module. Fixed the ICMP codes as per IANA (https://www.iana.org/assignments/icmp-parameters/icmp-parameters.xhtml) 2024-02-09 11:03:48 +00:00
Chris McCarthy
bebfbd53be #2248 - MAde tests use new way of accessing network interfaces by their port number 2024-02-09 10:30:39 +00:00
Chris McCarthy
0acd9a2938 #2248 - Removed redundant code and added more documentation from PR suggestions 2024-02-09 10:27:22 +00:00
Chris McCarthy
a036160515 #2248 - Enhances the PrimAITE documentation, covering the Node, network interfaces, Session Manager, Software Manager, PCAP service, SysLog functionality, and network devices like Routers, Switches, Computers, and Switch Nodes. It details their roles, workflows, and integration within the simulation, focusing on frame processing, software management, and logging. The documentation also clarifies the frame reception process, including port checks and application-level dispatching, ensuring a thorough understanding of network operations within the simulation 2024-02-08 22:37:21 +00:00
Czar Echavez
0590f956e3 #2258: ntp client should not request if ntp server is not set 2024-02-08 16:21:08 +00:00
Chris McCarthy
5eed467271 #2248 - synced wth dev 2024-02-08 16:15:57 +00:00
Czar Echavez
e1237625a5 Merge remote-tracking branch 'origin/dev' into feature/2258-dosbot-cannot-be-added-via-configuration-file 2024-02-08 16:03:41 +00:00
Czar Echavez
b31a9943d7 #2258: testing individual application install 2024-02-08 16:02:37 +00:00
Chris McCarthy
114fb8c077 #2248 - synced wth dev 2024-02-08 15:27:02 +00:00
Marek Wolan
c3ea06aeec Merged PR 268: Make build fail if tests fail 2024-02-08 15:21:19 +00:00
Marek Wolan
1a2298ebfb Merged PR 267: Make web status rewards based on web browser instead of web server.
## Summary
- added a second green agent on client 1
- added browser history
- added a reward component based on the most recent return code in browser history
- modified the UC2 notebook to adhere to new reward.
- (also there were some issues in example_config from a previous merge that I failed to notice prior)

## Test process
New unit tests. Ran uc2 notebook to check that it produces results aligning with what is described in the markdown cells.

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [x] written **tests** for any new functionality added with this PR
- [x] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [x] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [x] attended to any **TO-DOs** left in the code

Add second green agent and make rewards based on webbrowser

Related work items: #2247
2024-02-08 15:19:24 +00:00
Marek Wolan
9b350ddd6f Apply suggestions from code review. 2024-02-08 13:20:32 +00:00
Czar Echavez
1dcb9214af #2258: Added DoSBot to list of applications 2024-02-08 12:04:49 +00:00
Chris McCarthy
411f0a320f #2248 - Final run over all the docstrings after running pre-commit. All tests now working. Updated CHANGELOG.md. 2024-02-08 10:53:30 +00:00
Czar Echavez
a4b7878604 #2258: added NTPClient to system software + testing all installable software on client1 in config 2024-02-08 10:36:07 +00:00
Marek Wolan
ff17062e1c Vary start node of red agent. 2024-02-08 09:19:18 +00:00
Chris McCarthy
0c96fef3ec #2248 - All tests (bar the one config file test) now working. Still need to tidy up docstrings and some docs. Almost there 2024-02-07 23:05:34 +00:00
Chris McCarthy
5e25fefa14 #2248 - Further fixes. All router integration tests now passing. 2024-02-07 19:44:40 +00:00
Czar Echavez
f21ee857a7 #2258: setting up test that verifies game config parsing 2024-02-07 18:09:54 +00:00
Marek Wolan
b7ff520d55 make task fail if tests fail 2024-02-06 18:58:50 +00:00
Marek Wolan
c35c060448 Cosmetic changes based on PR feedback 2024-02-06 17:32:15 +00:00
Marek Wolan
e500eccaf7 Finish upgrading folder actions to work with names instead of uuids & get tests fixed 2024-02-06 16:58:08 +00:00
Marek Wolan
41bc932f52 Add reward test. 2024-02-06 15:05:44 +00:00
Marek Wolan
5b5b750d4d Add second green agent and make rewards based on webbrowser 2024-02-06 14:42:59 +00:00
Chris McCarthy
7bbfd564fb #2248 - Big refactor of base with all Network Interface subclasses created to allow for proper management of ports on devices as it was starting to get messy with the Router. Some routing tests still need fixing as ARP doesn't seem to be working properly 2024-02-05 08:44:10 +00:00
Chris McCarthy
a0253ce6c4 #2248 - TSome further fixess to ARP. Also refactored PCAP to log inbound and outbound frames separately 2024-02-02 17:14:34 +00:00
Chris McCarthy
cb002d644f #2248 - Tidying up the tests so that they use updated networks 2024-02-02 16:55:43 +00:00
Chris McCarthy
dc5aeede33 #2248 - ICMP now working as a service using the session manager for transmission. Now started to comb through the tests to fix anything up. 2024-02-02 16:20:15 +00:00
Marek Wolan
cfc254753f Merged PR 265: Make requests work with names instead of uuids
## Summary
Make actions work with object names instead of UUIDs. This makes it possible to define action spaces which can act on network elements that don't exist yet (as long as you can anticipate what they will be called).

## Test process
Many new tests. Old tests pass. Notebooks run.

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [x] written **tests** for any new functionality added with this PR
- [x] updated the **documentation** if this PR changes or adds functionality
- [no time] written/updated **design docs** if this PR implements new functionality
- [x] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [x] attended to any **TO-DOs** left in the code

Related work items: #2137
2024-02-02 15:39:38 +00:00
Chris McCarthy
87d9d6da04 #2248 - Initial work has been done on moving ICMP into services. still tidying up to be done. Need to fix tests too. 2024-02-02 15:35:02 +00:00
Marek Wolan
4c6ae135cd Fix typos 2024-02-02 14:48:49 +00:00
Chris McCarthy
1964ab4635 #2248 - Lots more progress. Can now use ARP as a service properly. Also integrated the new ARP into the old ICMP which works. Next step is to more ICMP into services. 2024-02-01 23:05:14 +00:00
Chris McCarthy
9577f212f8 #2248 - Initial crack at getting ARP into a Service. Lots of refactoring has been done. It's a mess at the minute, but I can successfully send an ARP request so committing as a successful point in time 2024-02-01 22:19:55 +00:00
Marek Wolan
c163fb37ea Update request system docs. 2024-02-01 11:19:42 +00:00
Marek Wolan
261423bc78 Update changelog 2024-01-31 13:54:15 +00:00
Marek Wolan
83db5b1eb5 Fix node file delete action 2024-01-31 13:50:20 +00:00
Marek Wolan
41a7f83887 Add file scan test 2024-01-31 13:29:46 +00:00
Marek Wolan
d6a83fd1fb Update action tests to use name, not uuid 2024-01-31 11:55:38 +00:00
Marek Wolan
6aa6383fb7 Fix broken test configs 2024-01-31 11:44:56 +00:00
Marek Wolan
9f993dda57 Fix test config discrepancies 2024-01-31 10:48:40 +00:00
Marek Wolan
0dbaa66aa3 Merge remote-tracking branch 'origin/dev' into feature/2137-refactor-request-api 2024-01-31 10:05:09 +00:00
Marek Wolan
0c3304b1fd Merged PR 263: Several hotfixes
## Summary
Hotfixes from 3.0.0b4, b5, b6. These have all gone thru the PR process already we just need to sync dev back.

## Test process
Merge conflicts resolved and all automated tests pass.

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [x] written **tests** for any new functionality added with this PR
- [~] updated the **documentation** if this PR changes or adds functionality
- [~] written/updated **design docs** if this PR implements new functionality
- [~] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [x] attended to any **TO-DOs** left in the code

Related work items: #2161, #2173, #2174, #2175, #2176, #2179, #2208, #2218, #2219, #2220
2024-01-30 15:18:21 +00:00
Marek Wolan
def52f94e3 Add docstrings and update typos 2024-01-30 09:56:16 +00:00
Marek Wolan
bea72aa6a9 Fix ftp client connection list 2024-01-29 12:28:44 +00:00
Marek Wolan
555802baaa Merge remote-tracking branch 'origin/dev' into dev-v3.0.0b6 2024-01-29 10:26:28 +00:00
Marek Wolan
2ba05e7348 Fixed being unable to specify all addresses in acl rule 2024-01-25 15:17:09 +00:00
Marek Wolan
0056bfddee Bump version to 3.0.0b6 2024-01-25 14:59:24 +00:00
Marek Wolan
5a9eaeb185 Update the readme 2024-01-25 14:59:00 +00:00
Marek Wolan
a3a7d11ff7 Merged PR 261: Make sure notebook images get copied
Just made sure that notebook images get copied to user notebook directory.
2024-01-25 15:24:38 +00:00
Marek Wolan
51be271928 Merged PR 260: Beta 6 Fixes
Please run some of these changes locally. Read the notebook, check that it makes sense, and run the code cells to see if they produce the result you expect.

## Summary
Apologies that all these fixes are part of 1 massive PR instead of individual PRs. I thought it was going to be a quick job and it spiralled out of control.

Changes:
- Fixed a bug where ACL rules were not resetting on episode reset.
- Fixed a bug where blue agent's ACL actions were being applied against the wrong IP addresses
- Fixed a bug where deleted files and folders did not reset correctly on episode reset.
- Fixed a bug where service health status was using the actual health state instead of the visible health state
- Fixed a bug where the database file health status was using the incorrect value for negative rewards
- Fixed a bug preventing file actions from reaching their intended file
- Made database patch correctly take 2 timesteps instead of being immediate
- Made database patch only possible when the software is compromised or good, it's no longer possible when the software is OFF or RESETTING
- Temporarily disable the blue agent file delete action due to crashes. This issue is resolved in another branch that will be merged into dev soon.
- Fix a bug where ACLs were not showing up correctly in the observation space.
- Added a recap of agent actions to the `info` output of `step()`
- Added a notebook which explains UC2, demonstrates the attack, and shows off blue agent's action space, observation space, and reward function.

## Test process
New notebook verifies end-to-end UC2 functionality.

## Checklist
- [y] PR is linked to a **work item**
- [y] **acceptance criteria** of linked ticket are met
- [y] performed **self-review** of the code
- [~] written **tests** for any new functionality added with this PR
- [y] updated the **documentation** if this PR changes or adds functionality
- [n] written/updated **design docs** if this PR implements new functionality
- [y] updated the **change log**
- [y] ran **pre-commit** checks for code style
- [y] attended to any **TO-DOs** left in the code

Related work items: #2208, #2218, #2219, #2220
2024-01-25 15:15:48 +00:00
Marek Wolan
7f996ca16a Make sure notebook images get copied 2024-01-25 14:52:48 +00:00
Marek Wolan
4b98c1f630 Update uc2 notebook 2024-01-25 14:43:49 +00:00
Marek Wolan
73a75c497b Fix test 2024-01-25 13:13:50 +00:00
Marek Wolan
e7aac754a0 Update the changelog 2024-01-25 12:38:28 +00:00
Marek Wolan
99723b6578 Update notebook with more images. 2024-01-25 12:33:18 +00:00
Marek Wolan
28acb5dcae Populate step info in environment, and finish notebook 2024-01-25 12:04:09 +00:00
Marek Wolan
0a65f32adf Fix ACL observations 2024-01-25 09:27:08 +00:00
Marek Wolan
88c1d16f11 Fix Router acl not clearing 2024-01-23 14:34:05 +00:00
Marek Wolan
8e19e05f57 Fix acl actions for blue agent. 2024-01-21 17:29:19 +00:00
Marek Wolan
42d00e0440 Fix issue where file deleted flag wouldn't be reset 2024-01-21 16:33:51 +00:00
Marek Wolan
7d218c5201 bump version 2024-01-15 10:31:13 +00:00
Marek Wolan
edc9772d0a Fix typo in database restore 2024-01-15 10:10:30 +00:00
Marek Wolan
728f80cc21 Temporarily disable file delete action 2024-01-15 09:48:14 +00:00
Marek Wolan
e0033de7b6 Fix folder reset 2024-01-12 14:54:55 +00:00
Marek Wolan
842e59f596 Database patch 2024-01-11 15:40:37 +00:00
Marek Wolan
ed5591caf8 Minor fix 2024-01-11 14:49:36 +00:00
Marek Wolan
63b9bc5bc6 3.0.0b5 2024-01-11 11:13:43 +00:00
Marek Wolan
40ad446ff2 Merged PR 257: Fix reward data type
Related work items: #2179
2024-01-11 11:07:01 +00:00
Marek Wolan
4d1c0d268e Fix reward data type 2024-01-11 11:05:55 +00:00
Marek Wolan
b11e4c8ccd update changelog 2024-01-11 11:05:00 +00:00
Marek Wolan
f283afc04a Merged PR 256: Align the database backup and corruption processes with IYak
## Summary
**Changed:**
- Copying a file via FTP also copies its health status
- The database automatically attempts to make a backup on step 1
- make the db file a property that is fetched by name from the file system instead of a handle to a file (bruh)
- fixed ftp server re-sending requests back to the client
- fix issue where links with >100% bandwidth cause the observation space to crash
- fix issue where starting a node didn't start services. (not sure how that one passed tests previously)

**To align with Yak:**
- database service removed from uc2 observation space
- sql attack affects the file health status instead of the service
- when the web server fails to fetch data, it goes into compromised state until a successful data fetch

## Test process
Notebooks

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [x] attended to any **TO-DOs** left in the code

Related work items: #2176
2024-01-11 10:54:25 +00:00
Marek Wolan
d2a2472e5f Apply bugfix 2151 2024-01-11 10:49:32 +00:00
Marek Wolan
e57c240b9b Apply cosmetic changes based on review. 2024-01-11 09:55:09 +00:00
Marek Wolan
2d1041e7b3 Fix final bugs 2024-01-10 18:38:37 +00:00
Marek Wolan
1505d08721 Fix backup issues and align with Yak 2024-01-10 18:04:48 +00:00
Marek Wolan
b34f2a5c8c Merged PR 253: Make observations use software health state visible instead of actual.
We already merged this change into dev, I just replicated it for b5.

Related work items: #2161, #2174
2024-01-10 13:53:05 +00:00
Marek Wolan
3486347566 Merged PR 252: Align Software health state enum with CAOS
Related work items: #2175
2024-01-10 13:52:46 +00:00
Marek Wolan
9fce9ceea4 Merged PR 255: Fix issue where red agent acted too early
## Fixed:
- data manipulation red agent now considers episode reset when calculating next action time
- Moved attack logic out of data manipulation bot `run` method into dedicated `attack` method, because `run` is triggered by episode reset logic. This means the attack no longer always happens at step 1 of every episode.

## Test process
*How have you tested this (if applicable)?*

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [na] updated the **documentation** if this PR changes or adds functionality
- [na] written/updated **design docs** if this PR implements new functionality
- [x] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [x] attended to any **TO-DOs** left in the code

Related work items: #2173
2024-01-10 13:52:33 +00:00
Czar Echavez
62197fe72b Merged PR 254: #2151: remove changing of health_state_actual in actions and tests
## Summary
Removed the changing of health_state_actual from the actions - only few places where the health_state_actual is changed:
- compromised in specific scripted events
- set to good when started (if the state is still at UNUSED
- set to good after patching

## Test process
unit tests
https://dev.azure.com/ma-dev-uk/PrimAITE/_git/PrimAITE/pullrequest/254?_a=files&path=/tests/unit_tests/_primaite/_simulator/_system/_services/test_services.py

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

#2151: remove changing of health_state_actual in actions and tests

Related work items: #2151, #2166
2024-01-10 13:35:51 +00:00
Marek Wolan
9d06284edb Merge remote-tracking branch 'origin/dev-v3.0.0b5' into bugfix/2176-attack-observation-symptoms 2024-01-10 13:07:23 +00:00
Marek Wolan
66a42ebc69 Make database failure based on file status not service status 2024-01-10 13:06:48 +00:00
Czar Echavez
c985b8793d #2151 and #2166: added tests for application being unused + even more tests 2024-01-10 11:58:36 +00:00
Marek Wolan
b6e414bd70 Update changelog 2024-01-10 09:14:07 +00:00
Marek Wolan
b7cc940e9d Remove temporary print statements 2024-01-10 09:07:51 +00:00
Marek Wolan
e73783f6fa Fixed issue where data manipulation was always executing 2024-01-09 17:10:12 +00:00
Czar Echavez
a4d372d3eb #2151: utilise set_health_state method instead of directly changing software states 2024-01-09 16:29:40 +00:00
Czar Echavez
9eb0102069 Merge remote-tracking branch 'origin/dev' into bugfix/2151-service-status-set-to-overwhelmed-at-incorrect-actions 2024-01-09 15:29:49 +00:00
Czar Echavez
6fc4e15660 #2151: remove changing of health_state_actual in actions and tests 2024-01-09 15:18:31 +00:00
Marek Wolan
daa34385e5 Add agent reset for episodes 2024-01-09 14:53:15 +00:00
Marek Wolan
f2a496893c Bump VERSION 2024-01-09 14:33:24 +00:00
Marek Wolan
716bd626a5 Hide software health state until scan. 2024-01-09 14:29:23 +00:00
Marek Wolan
91addee09d Merged PR 248: Make observation flattening optional for agents.
## Summary
Same as other PR but this time we are merging into DEV.

The Proxy agent has a new config option, `flatten_obs`. If true, we use gymnasium flatten.

## Test process
Unit tests and inspection.

Related work items: #2143, #2154, #2161
2024-01-09 14:28:36 +00:00
Marek Wolan
82cd8780f9 Align Software health state enum with CAOS 2024-01-09 14:03:10 +00:00
Marek Wolan
5d89820a15 Apply PR review suggestions 2024-01-09 12:38:01 +00:00
Marek Wolan
7c0ff8e3f0 Add acl remove rule integration test. 2024-01-08 16:24:09 +00:00
Marek Wolan
534f84ccd1 Add action tests. 2024-01-08 13:29:17 +00:00
Marek Wolan
294c8b982f Add convenience method for router acl 2024-01-08 13:28:55 +00:00
Marek Wolan
27f70204ed Fix minor issues in actions 2024-01-08 13:28:34 +00:00
Christopher McCarthy
7c0ab1a19e Merged PR 243: #2139 - Implemented routing
## Summary
- Integrated the RouteTable into the Routers frame processing.
- Frames are now dropped when their TTL reaches 0

## Test process
Added five tests that check routing passes and fails with correct/incorrect route tables.

## Checklist
- [ ] PR is linked to a **work item**
- [ ] **acceptance criteria** of linked ticket are met
- [ ] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [ ] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

#2139 - Implemented routing

Related work items: #2139
2024-01-08 11:17:16 +00:00
Marek Wolan
2f97dcb6f9 Merge remote-tracking branch 'origin/dev' into feature/2137-refactor-request-api 2024-01-08 10:39:24 +00:00
Chris McCarthy
8b43f6abe3 #2139 - updated docstring in send_arp_request function in base.py 2024-01-08 10:30:38 +00:00
Chris McCarthy
59d1a6668e #2139 - Updated the CHANGELOG.md with broadcast entry 2024-01-05 22:19:54 +00:00
Chris McCarthy
d2d628b676 #2139 - Fixed unicast and broadcast functionality properly 2024-01-05 22:11:37 +00:00
Chris McCarthy
ddf7fbf88b #2139 - Included a test that tests services over multi-hop routing. Added some PR suggestions around logging. 2024-01-05 15:27:10 +00:00
Marek Wolan
33f72db1cb Updated VERSION 2024-01-05 14:03:06 +00:00
Marek Wolan
0d07364669 Merged PR 246: Make flattening observation spaces optional.
## Summary
Simple change that gives the user an option to turn on/off observation space flattening.

## Test process
Confirmed that if the new setting is set to 'false', SB3 complains about composite spaces, but RL agents notebook works fine.

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [x] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [x] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [x] attended to any **TO-DOs** left in the code

Make flattening observation spaces optional.

Related work items: #2161
2024-01-05 13:50:22 +00:00
Marek Wolan
d038f63fda Clear notebook output 2024-01-05 13:11:47 +00:00
Marek Wolan
f75c10aafb Make flattening observation spaces optional. 2024-01-05 13:10:49 +00:00
Marek Wolan
b8312b8a2b Merged PR 244: Make pcap and sys logging optional (beta 4)
## Summary
Very straightforward change. Just added some config parameters to make pcap and sys logs optional. These options default to false.

## Test process
Verified that both options produce the desired result by running a primaite session with logs enabled and disabled in the config. Unit tests still pass.

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [x] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [x] attended to any **TO-DOs** left in the code

Related work items: #2143, #2154
2024-01-05 12:40:13 +00:00
Marek Wolan
4266618ba5 Make pcap logs and sys logs optional 2024-01-05 11:25:57 +00:00
Marek Wolan
81734e7ad3 Merged PR 241: Add service patch and fix apply timestep issues.
## Summary
Replaces Action ID 13 in UC2 with SERVICE.PATCH.
Fixes issue where apply_timestep was not happening at all
Fixes issue where file actions were not correctly being forwarded

## Test process
All pytests passing including a new one for service patch.

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [x] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [x] attended to any **TO-DOs** left in the code

Related work items: #2143
2024-01-05 09:58:16 +00:00
Marek Wolan
bc08db6b7e Merged PR 240: Add service patch action and fix some clangers.
## Summary
- Replaces Action ID 13 in UC2 with SERVICE.PATCH.
- Fixes issue where `apply_timestep` was not happening at all
- Fixes issue where file actions were not correctly being forwarded

## Test process
Unit tests passing
Running primaite session works without errors
Ran primaite session on UC2 in debug mode and inspected that correct changes are being reflected after actions are applied.

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [ ] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

Related work items: #2143
2024-01-05 09:56:33 +00:00
Marek Wolan
7d81b1cb07 Merged PR 242: Change software describe state keys
## Summary
Tiny change to change the names of the keys in `software.describe_state()`
Also fixed the observation to use the visible health state instead of the actual health state (and therefore the blue agent will actually have to scan to learn the health state)

## Test process
Unit tests pass

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [x] attended to any **TO-DOs** left in the code

Change software describe state keys

Related work items: #2160
2024-01-04 14:50:37 +00:00
Marek Wolan
ec7723732b Merge remote-tracking branch 'origin/dev' into feature/2137-refactor-request-api 2024-01-04 14:40:20 +00:00
Marek Wolan
bc367222a8 Change software describe state keys 2024-01-04 12:55:46 +00:00
Marek Wolan
528e3b22a9 Add integration tests 2024-01-04 12:47:35 +00:00
Marek Wolan
25c8ec2ec9 Add skeleton for action integration and unit tests 2024-01-03 18:19:10 +00:00
Marek Wolan
48f1d13fd8 Minor refactor and add comment 2024-01-03 16:23:44 +00:00
Marek Wolan
3adf1f9f6a bump version 2024-01-03 14:49:40 +00:00
Marek Wolan
2aa7c18ad3 Merge remote-tracking branch 'origin/dev' into bugfix/2143-node-service-patch-main 2024-01-03 14:43:46 +00:00
Chris McCarthy
ade5f133d0 #2139 - Implemented routing 2023-12-22 10:31:11 +00:00
Marek Wolan
2135bdcd10 Add unit test 2023-12-21 16:08:09 +00:00
Marek Wolan
fa585168de update marl config with service patch bugfix 2023-12-21 15:10:23 +00:00
Marek Wolan
96f8435c5e Add service patch and fix other bugs 2023-12-21 15:07:41 +00:00
Marek Wolan
e33f74e3f2 bump version to 3.0.0b3dev 2023-12-21 09:28:14 +00:00
Marek Wolan
a1dcfa291b Update test configs with new action spec 2023-12-21 09:25:54 +00:00
Marek Wolan
a798d262b8 use names instead of uuids for requests 2023-12-18 14:03:47 +00:00
Marek Wolan
ffeb04d6ed Merged PR 235: Refactor describe_state to use name/hostname instead of UUID as primary key
## Summary
- Refactor Simulator state to use service/application name instead of UUID, and node hostname instead of UUID.
- Refactor observations to read the hostname/name instead of UUID.
- Refactor rewards as well.
- Refactor configs to specify name instead of reference that will be translated to UUID.

## Test process
Existing unit tests pass. Inspected the printout from running 'describe_state' on arcd_uc2_network' to verify that names are used to report state.

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [na] written **tests** for any new functionality added with this PR
- [na] updated the **documentation** if this PR changes or adds functionality
- [x] written/updated **design docs** if this PR implements new functionality
- [na] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [x] attended to any **TO-DOs** left in the code

Related work items: #2131
2023-12-15 16:02:29 +00:00
Nick Todd
360a86188c Merged PR 233: NTP server and client
## Summary
The NTP Server and Client are created as two separate classes NTPServer and NTPClient which define the methods used to send and receive time data. A set of classes used in the sending and receiving of requests and data is in ntp.py. A single file, test_ntp_client_server.py is used to run the unit tests.
The changes have no impact on other parts of the codebase.

## Test process
Created simple two node network representing NTP server and client. Created NTP server and client objects and client requests and receives date/time from server.

## Checklist
- [Y] PR is linked to a **work item**
- [Y] **acceptance criteria** of linked ticket are met
- [Y] performed **self-review** of the code
- [Y] written **tests** for any new functionality added with this PR
- [Y] updated the **documentation** if this PR changes or adds functionality
- [N] written/updated **design docs** if this PR implements new functionality
- [Y] updated the **change log**
- [Y] ran **pre-commit** checks for code style
- [N] attended to any **TO-DOs** left in the code

Related work items: #2041, #2042
2023-12-15 14:26:17 +00:00
Marek Wolan
7a1abb1ef8 Minor fixes based on code review 2023-12-15 13:09:50 +00:00
Marek Wolan
495d847a71 Use service and app name for node software requests 2023-12-15 13:04:18 +00:00
Nick Todd
2d892d4a5a 2041: Tidy up test comments 2023-12-15 10:52:46 +00:00
Nick Todd
0cfd525ab8 2041: change comparison operator in test 2023-12-15 10:14:35 +00:00
Marek Wolan
a16028d10c Merge remote-tracking branch 'origin/feature/2131-refactor-describe-state' into feature/2137-refactor-request-api 2023-12-15 10:10:39 +00:00
Nick Todd
fab39b1506 Merge branch 'dev' into feature/2041_2042-Add-NTP-Services 2023-12-15 09:50:19 +00:00
Marek Wolan
6a80f4cc77 Make game layer work with new state api 2023-12-14 14:04:43 +00:00
Marek Wolan
1ec7df1170 Change describe_state to use names instead of uuids 2023-12-14 11:19:32 +00:00
Czar Echavez
0aeaeaa60f Merged PR 234: #2059: Denial of Service Bot
## Summary
- Moved DataManipulationBot into red applications - these are applications, not services
- moved the connection handling from Service base class to the IOSoftware base class
  - Applications and Services can track the connections they make
  - increased default max sessions to 100
  - made sure the services/applications that are dependent on connections use the IOSoftware connections
- DoSBot follows some sort of kill chain, although at the moment it just:
  - runs a port scan with a 10% success chance (by default)
  - runs a DoS attack that fills a service's max sessions

## Test process
unit test in https://dev.azure.com/ma-dev-uk/PrimAITE/_git/PrimAITE/pullrequest/234?path=/tests/unit_tests/_primaite/_simulator/_system/_applications/_red_applications/test_dos_bot.py&_a=files

integration test in https://dev.azure.com/ma-dev-uk/PrimAITE/_git/PrimAITE/pullrequest/234?path=/tests/integration_tests/system/red_applications/test_dos_bot_and_server.py&_a=files

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

Related work items: #2059
2023-12-14 10:16:34 +00:00
Czar Echavez
592e1a3610 #2059: apply suggestions from PR + adding another test that checks for dos affecting green agent 2023-12-13 11:56:25 +00:00
Nick Todd
f7b5c8ae2f 2041: Remove NTPRequest class (review comment) 2023-12-13 10:34:52 +00:00
Czar Echavez
f0be77c79b #2059: configure missing configurable items 2023-12-12 17:20:31 +00:00
Nick Todd
e620771c8d 2041: Remove IP address from NTP client (review comment) 2023-12-12 17:08:11 +00:00
Czar Echavez
4f79d2ad36 #2059: moved connection handling from Service to IOSoftware + changes that now utilise connections from IOSoftware + dos bot attacking now works + tests 2023-12-12 17:01:03 +00:00
Czar Echavez
1b124035a1 Merge remote-tracking branch 'origin/dev' into feature/2059-denial-of-service-bot-post-beta-2 2023-12-11 08:57:59 +00:00
Czar Echavez
cd5ed48b00 #2059: implementing the service connections limit 2023-12-08 17:07:57 +00:00
Czar Echavez
094e89fff1 #2059: Renamed Red service to red application and moved the datamanipulation bot to the red application folder 2023-12-08 14:54:29 +00:00
Nick Todd
c3015b7f0e Merge branch 'dev' into feature/2041_2042-Add-NTP-Services 2023-12-07 14:55:01 +00:00
Nick Todd
44ada941e6 2041: Reinstate test for ntp_server failure 2023-12-07 14:22:27 +00:00
Marek Wolan
e93fb85672 Merged PR 232: Allow cancelling jobs
## Summary
Fix the azure build pipeline job conditions to correctly stop the job if we cancel the build.

Related work items: #2103
2023-12-07 13:49:08 +00:00
Marek Wolan
385a4997ce New parameter for publishing code coverage 2023-12-07 10:35:50 +00:00
Nick Todd
50a6e17fab 2041: Make NTP work with TCP transport layer 2023-12-06 16:42:28 +00:00
Nick Todd
12ede2329b 2041: Add network config and pytest fixture 2023-12-06 16:41:10 +00:00
Marek Wolan
75f732dacf bump version to 3.0.0b2 2023-12-04 13:08:13 +00:00
Marek Wolan
30b0f12a8d Allow cancelling jobs 2023-12-04 11:34:17 +00:00
Nick Todd
39694fcec2 Merge branch 'dev' into feature/2041_2042-Add-NTP-Services 2023-12-04 11:23:35 +00:00
Christopher McCarthy
4cc2674745 Merged PR 229: Step metadata json output
## Summary
- Added step metadata json file dumps to the environments. Fixed serialization issues in the Switch and ACLRule classes.

## Test process
Nothing outside of a manual inspection for now.

## Checklist
- [ ] PR is linked to a **work item**
- [ ] **acceptance criteria** of linked ticket are met
- [ ] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [ ] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

Related work items: #2085
2023-12-04 10:47:09 +00:00
Marek Wolan
01b9e661ce Clean up print statements. 2023-12-04 10:45:33 +00:00
Marek Wolan
a5c4f7797d Make saving step metadata optional 2023-12-04 10:42:20 +00:00
Marek Wolan
8ea9db2d34 Merge remote-tracking branch 'origin/dev' into feature/2085-dump_describe_state 2023-12-04 10:38:41 +00:00
Marek Wolan
2203877302 Merged PR 231: Add docpage for config
## Summary
*Replace this text with an explanation of what the changes are and how you implemented them. Can this impact any other parts of the codebase that we should keep in mind?*

## Test process
*How have you tested this (if applicable)?*

## Checklist
- [ ] PR is linked to a **work item**
- [ ] **acceptance criteria** of linked ticket are met
- [ ] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [ ] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

Add docpage for config

Related work items: #2088
2023-12-04 10:17:56 +00:00
Marek Wolan
9fa6f0b7ab Formatting improvements in cfg doc page 2023-12-04 10:16:29 +00:00
Marek Wolan
ec8e6b5ff7 Merged PR 228: Fix annoying Ray issues
## Summary
Fix ray episode issues. Allow ray to manage its environment fully - this fixes the perma-zero reward.

## Test process
Running notebooks and primaite sessions.

## Checklist
- [ ] PR is linked to a **work item**
- [ ] **acceptance criteria** of linked ticket are met
- [ ] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [ ] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

Related work items: #2095
2023-12-04 10:10:10 +00:00
Czar Echavez
6ca28f5d17 Merged PR 230: #2084: add coverage fail condition
## Summary
Added a fail condition for coverage

## Test process
n/a

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

#2084: add coverage fail condition

Related work items: #2084
2023-12-04 10:02:24 +00:00
Marek Wolan
ba3d37316b Apply suggestions from review 2023-12-04 09:21:47 +00:00
Marek Wolan
de5fead9a4 Add docpage for config 2023-12-04 09:14:20 +00:00
Czar Echavez
8f063aa339 #2084: apply previous PR suggestions 2023-12-04 09:07:42 +00:00
Czar Echavez
534d4f96f3 #2084: add coverage fail condition 2023-12-04 08:58:03 +00:00
Czar Echavez
f55e18c4c8 Merged PR 225: #2084: Adding more tests
## Summary
Added tests and integrating code coverage checks - current target set to 80% of code to be covered by tests

## Test process
The pull request is literally to add more tests (lol)

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

#2084: beginning the introduction of code coverage + adding tests to try to meet the 80% code coverage target

Related work items: #2084
2023-12-03 14:55:20 +00:00
Marek Wolan
105763971d Merge 'origin/dev' into bugfix/episode-length-and-rewards 2023-12-03 14:49:34 +00:00
Czar Echavez
1d5337153b #2084: fix pr autocancel 2023-12-02 19:46:04 +00:00
Czar Echavez
1cc0020381 #2084: only upload copy of html report once 2023-12-02 19:38:45 +00:00
Czar Echavez
53f43dde0d #2084: cleaning up 2023-12-02 19:07:10 +00:00
Czar Echavez
060a46e251 #2084: more debugging 2023-12-02 18:44:27 +00:00
Czar Echavez
7b21f390c0 #2084: more debugging 2023-12-02 15:31:36 +00:00
Czar Echavez
e48f0a6d68 #2084: more debugging 2023-12-02 14:41:45 +00:00
Czar Echavez
2123fbb8f4 #2084: more debugging 2023-12-02 14:17:34 +00:00
Czar Echavez
47287ad1eb #2084: fixing 0% coverage 2023-12-02 13:44:39 +00:00
Czar Echavez
6ecb47f5ae #2084: debug coverage file 2023-12-02 01:19:38 +00:00
Czar Echavez
31c4287f46 #2084: applying github example fix to pipeline 2023-12-02 01:05:13 +00:00
Chris McCarthy
cc04efb31d #2085 - Added step metadata json file dumps to the environments. Fixed serialization issues in the Switch and ACLRule classes. 2023-12-01 16:37:58 +00:00
Czar Echavez
af8401440d #2084: using v2 publish codecov 2023-12-01 16:29:05 +00:00
Czar Echavez
88f74d9eec #2084: remove debugs and comment out the uploading of report 2023-12-01 16:08:02 +00:00
Czar Echavez
8a4978cf96 #2084: remove 80% requirement - causes tests to fail 2023-12-01 15:59:34 +00:00
Chris McCarthy
32c13e06f6 Merge remote-tracking branch 'devops/bugfix/episode-length-and-rewards' into feature/2085-dump_describe_state 2023-12-01 15:58:32 +00:00
Chris McCarthy
008efa1e9d Merge remote-tracking branch 'devops/bugfix/episode-length-and-rewards' into feature/2085-dump_describe_state 2023-12-01 15:55:22 +00:00
Czar Echavez
9a8350fd8f #2084: artifact the report 2023-12-01 15:49:20 +00:00
Marek Wolan
3e3fd89618 Minor string fix 2023-12-01 15:41:10 +00:00
Marek Wolan
eeedea2eff Make more friendly user outputs when training SB3 2023-12-01 15:36:07 +00:00
Czar Echavez
f0327da9b6 #2084: remove 80% requirement - causes tests to fail 2023-12-01 15:33:43 +00:00
Czar Echavez
6598c66da1 #2084: i hope no one is keeping an eye on these atrocious commit messages 2023-12-01 15:18:38 +00:00
Czar Echavez
294f57c292 #2084: find paths with wildcard 2023-12-01 15:08:42 +00:00
Marek Wolan
321d1f7219 Fix rllib marl problems 2023-12-01 14:58:34 +00:00
Czar Echavez
d6fedf0079 #2084: maybe pointing to different source might help 2023-12-01 14:58:22 +00:00
Czar Echavez
656cb03b16 #2084: print content of coverage.xml 2023-12-01 14:34:42 +00:00
Czar Echavez
4f57403751 #2084: debug pipeline 2023-12-01 13:52:06 +00:00
Czar Echavez
c21a52d3f7 #2084: debug pipeline 2023-12-01 13:26:27 +00:00
Czar Echavez
1dbea3041a #2084: add files + remove extra slash 2023-12-01 12:46:12 +00:00
Czar Echavez
738aeed0a5 #2084: debug pipeline 2023-12-01 12:05:12 +00:00
Czar Echavez
6430a7588d #2084: debug pipeline 2023-12-01 11:38:34 +00:00
Czar Echavez
74b8f58b36 #2084: debug pipeline 2023-12-01 11:22:30 +00:00
Marek Wolan
3642e87eda Remove distracting debug print statements 2023-12-01 11:07:57 +00:00
Czar Echavez
4ad93b0961 #2084: publish coverage report + more verbose test output 2023-12-01 10:32:48 +00:00
Czar Echavez
f1c706631f #2084: publish coverage report 2023-12-01 10:02:12 +00:00
Nick Todd
a073038ec0 #2085: Get enum value data 2023-12-01 09:52:31 +00:00
Czar Echavez
3eb9a5ef1c #2084: publish coverage report 2023-12-01 09:13:17 +00:00
Czar Echavez
c2f7d737f7 #2084: missed change to logger 2023-11-30 21:11:35 +00:00
Czar Echavez
5b50213626 #2084: upload reports - debug 2023-11-30 19:58:35 +00:00
Czar Echavez
4c1bb7d786 #2084: upload reports - debug 2023-11-30 19:43:23 +00:00
Czar Echavez
4572afac69 #2084: upload reports - debug 2023-11-30 19:34:18 +00:00
Czar Echavez
d60250e1b8 #2084: upload reports - azure cannot find things 2023-11-30 19:21:11 +00:00
Czar Echavez
bfb631f88c #2084: upload reports - use default htmlcov location 2023-11-30 18:45:27 +00:00
Czar Echavez
9d4e564e0e #2084: upload reports 2023-11-30 18:32:03 +00:00
Czar Echavez
423436c3ad #2084: testing webbrowser requesting database service user data via web server 2023-11-30 16:32:31 +00:00
Nick Todd
10d4b61c73 Merge branch 'feature/2087_Full-reset-functionality' into feature/2085-dump_describe_state 2023-11-30 16:16:44 +00:00
Nick Todd
5cd69f343f #2085: generate time based log files 2023-11-30 16:11:44 +00:00
Czar Echavez
d9de57757f #2084: more tests + remove concurrency in test to make sure coverage works 2023-11-30 15:47:31 +00:00
Czar Echavez
3cf21e4015 #2084: change all instances of retrieving software from software['software_name'] to software.get() + adding some tests for describe state 2023-11-30 13:49:37 +00:00
Czar Echavez
7c1ffb5ba1 #2084: change all instances of retrieving software from software['software_name'] to software.get() + adding some tests for describe state 2023-11-30 13:48:57 +00:00
Czar Echavez
349f9dee38 Merge remote-tracking branch 'origin/dev' into feature/2084-add-more-tests-to-make-primaite-more-robust 2023-11-30 09:29:34 +00:00
Marek Wolan
deea09f88d Merged PR 226: Episode Reset
## Summary
After initial setup, get sim components to save their state. Then, during episode reset, set attributes to original values.

## Test process
Test script that checks for web client ability to resolve requests after a reset. Formal tests don't exist.

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

Related work items: #1859, #2087
2023-11-30 09:10:06 +00:00
Marek Wolan
9d39458ef3 Deleted sandbox.py 2023-11-29 22:30:12 +00:00
Czar Echavez
b2a52b2ec0 #2084: created a fixture that we can use to test things at a non end to end level 2023-11-29 16:31:21 +00:00
Marek Wolan
ac2f7ba757 Fix web browser tests. 2023-11-29 14:33:52 +00:00
Marek Wolan
a16116a688 Fix file system reset error 2023-11-29 13:22:15 +00:00
Marek Wolan
05d62a956d Fix software reset issues 2023-11-29 13:18:38 +00:00
Chris McCarthy
bf73cc2eb7 #1859 - Re-ordered the node reset function again 2023-11-29 13:45:34 +00:00
Nick Todd
3ab911f6af #2085: Change output file type 2023-11-29 11:41:02 +00:00
Nick Todd
957702fa5d #2085: Remove JSON file handling 2023-11-29 10:10:23 +00:00
Czar Echavez
19d534395b #2084: beginning the introduction of code coverage + adding tests to try to meet the 80% code coverage target 2023-11-29 01:28:40 +00:00
Nick Todd
28da7bb648 #2085: Merge branch 'feature/2087_Full-reset-functionality' into feature/2085-dump_describe_state 2023-11-28 16:19:16 +00:00
Chris McCarthy
94f8a45a4d #1859 - Re-ordered the node reset function 2023-11-28 15:29:13 +00:00
Nick Todd
e63727fa3a #2058 - Fix up log file path 2023-11-28 14:12:01 +00:00
Nick Todd
2eeb896099 #2085 - Dump describe_state output to JSON file. 2023-11-28 12:16:04 +00:00
Chris McCarthy
9a4855e7bd #1859 - Added the call to file system reset 2023-11-28 11:58:09 +00:00
Marek Wolan
da955038f5 Merged PR 224: Enhanced probabilistic red agent.
## Summary
This is @<Jake Walker> 's and @<Christopher McCarthy> 's PR.

- The red agent now performs attacks in stages.
- There is now a random probability of each stage being successfully run.
- There are start settings for the red agent which set the start time, frequency and variance for both.

## Test process
Additional unit tests have been added to test new functionality.

## Checklist
- [ ] PR is linked to a **work item**
- [ ] **acceptance criteria** of linked ticket are met
- [ ] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [ ] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

Related work items: #1859
2023-11-28 10:47:39 +00:00
Marek Wolan
2de1d02c48 Fix app install logic 2023-11-27 22:55:00 +00:00
Marek Wolan
3df3e113d1 Change data manipulation test to use the right func 2023-11-27 22:24:30 +00:00
Marek Wolan
b0399195bb Fix software manager usage in uc2 network func 2023-11-27 22:20:44 +00:00
Marek Wolan
21b865d8a8 Merge origin/dev into feature/1859 2023-11-27 22:13:42 +00:00
Chris McCarthy
517f99b04b #1859 - Added the call to file system reset 2023-11-28 09:45:45 +00:00
Chris McCarthy
37663c941d #1859 - Added route table reset, still not working 2023-11-28 00:51:48 +00:00
Chris McCarthy
39dfbb741f #1859 - Made some fixes to resets. Still an issue with the Router reset. 2023-11-28 00:21:41 +00:00
Chris McCarthy
58e9033a4c #1859 - First pass at an implementation of the full reset method. Will now start testing... 2023-11-27 23:01:56 +00:00
Nick Todd
95f6cf6691 Merged PR 221: Version 3 beta 2 doc changes
## Summary
*Replace this text with an explanation of what the changes are and how you implemented them. Can this impact any other parts of the codebase that we should keep in mind?*

## Test process
*How have you tested this (if applicable)?*

## Checklist
- [Y] PR is linked to a **work item**
- [Y] **acceptance criteria** of linked ticket are met
- [Y ] performed **self-review** of the code
- [N] written **tests** for any new functionality added with this PR
- [Y] updated the **documentation** if this PR changes or adds functionality
- [N] written/updated **design docs** if this PR implements new functionality
- [N] updated the **change log**
- [Y] ran **pre-commit** checks for code style
- [N] attended to any **TO-DOs** left in the code

Related work items: #2068
2023-11-27 21:35:37 +00:00
Czar Echavez
58a84da7af Merged PR 217: #2064: fix for services still running after node is turned off
## Summary
- Added a check for services so that they should not do anything unless the node it is installed in is turned on

## Test process
- Added tests everywhere

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [X] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [X] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [X] attended to any **TO-DOs** left in the code

Related work items: #2064
2023-11-27 20:23:37 +00:00
Chris McCarthy
ae5046b8fb #1859 - As disccused 2023-11-27 17:05:12 +00:00
Nick Todd
40d596c373 Merge branch 'dev' into feature/2041_2042-Add-NTP-Services 2023-11-27 15:07:06 +00:00
Nick Todd
6fd37a609a #2068: code review comments. 2023-11-27 14:38:59 +00:00
Chris McCarthy
c3bb78c5a3 Merge remote-tracking branch 'devops/feature/1859-red-agent-marek' into feature/1859-red-agent-marek 2023-11-27 13:50:41 +00:00
Chris McCarthy
4d4a578555 #1859 - Integrated the runtime execution for web client. Added in the webclient application execution action. Now fixing http status code issues. 2023-11-27 13:47:59 +00:00
Marek Wolan
89cbc08352 Apply suggestions from code review 2023-11-27 13:28:11 +00:00
Marek Wolan
43fee23600 Fix incorrect order in session from config 2023-11-27 11:55:58 +00:00
Czar Echavez
299729d5b4 #2064: documentation EVERYWHERE 2023-11-27 11:38:03 +00:00
Marek Wolan
84bd9b1bff Merge remote-tracking branch 'origin/dev' into feature/1859-red-agent-marek 2023-11-26 23:45:10 +00:00
Marek Wolan
ece9b14d63 Resolve merge conflicts 2023-11-26 23:29:14 +00:00
Czar Echavez
cd49f1eb85 #2064: Apply PR suggestions 2023-11-25 13:19:32 +00:00
Jake Walker
cbdaa6c444 Move data manipulation agent into individual file 2023-11-24 16:32:04 +00:00
Jake Walker
afce6ca515 Update changelog for data manipulator bot & agent 2023-11-24 16:04:11 +00:00
Jake Walker
08c1b3cfb9 Fix code style issues 2023-11-24 15:56:04 +00:00
Jake Walker
e62ca22cb7 Fix data manipulation bot tests 2023-11-24 15:53:07 +00:00
Nick Todd
2ce27080a6 #2068: Remove reference to ARCD GATE 2023-11-24 15:48:13 +00:00
Nick Todd
76b3a5ab6f #2068: Updated version 2023-11-24 15:43:52 +00:00
Nick Todd
a2a27697a3 Merge branch 'dev' into feature/2068-Validate_documentation 2023-11-24 15:27:33 +00:00
Nick Todd
355cbedbae #2068: Further typo and formatting changes. 2023-11-24 15:17:08 +00:00
Czar Echavez
330e87698e Merge remote-tracking branch 'origin/dev' into bugfix/2064-software-continues-running-after-node-is-turned-off 2023-11-24 15:16:25 +00:00
Czar Echavez
b7b718f25d #2064: added a method that checks if the class can perform actions and added it where necessary + tests everywhere 2023-11-24 15:15:56 +00:00
Jake Walker
c5cfbb825a Fix database client connect method 2023-11-24 15:15:45 +00:00
Jake Walker
e6f75f8b32 Improve data manipulation bot documentation 2023-11-24 15:15:24 +00:00
Marek Wolan
5a03db9ff3 Merged PR 219: Skip slow tests for now.
Related work items: #1971
2023-11-24 14:58:00 +00:00
Marek Wolan
e609f8eb50 Fix misconfiguration in uc2 config and session 2023-11-24 14:56:17 +00:00
Marek Wolan
82116e6c92 Merged PR 218: Get Ray agents working
## Summary
- PrimaiteSession class was separated into 'game' and 'session' classes. Game manages the interfacing of agents and the simulator. Session manages the environment, IO, and RL algorithms, as well as the game.
- Add ray single and multi agent support
- Add environments that can be interacted with directly so that users who want to manually configure RL policies can do so.
- Add notebooks demonstrating manual environment interfacing.

## Test process
Unit tests added, all pass. Example notebooks run to demonstrate compatibility with SB3 and Ray.

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [x] written **tests** for any new functionality added with this PR
- [x] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

![PrimAITE High Level Design - Page 1 (4).png](https://dev.azure.com/ma-dev-uk/b50a61ee-86c4-48bc-9a0b-a67645ba12ee/_apis/git/repositories/2825053e-bd3b-45b2-8680-1281809eefa2/pullRequests/218/attachments/PrimAITE%20High%20Level%20Design%20-%20Page%201%20%284%29.png)

Related work items: #1970, #1971
2023-11-24 13:57:54 +00:00
Marek Wolan
64c7dd3c84 Skip slow tests for now. 2023-11-24 12:03:46 +00:00
Chris McCarthy
dfb08b8cf3 #1859 - DB query now returns false if the query isn't ran due to the node being off 2023-11-24 11:52:33 +00:00
Nick Todd
dd351f8143 #2068: Remove duplicated index entries. 2023-11-24 11:21:25 +00:00
Jake Walker
ff8b773c10 Database Manipulation Bot bug fixes 2023-11-24 11:10:34 +00:00
Marek Wolan
d8975078b3 Fix game reset test. 2023-11-24 10:50:10 +00:00
Jake Walker
4e104a4d99 Update data manipulation bot 2023-11-24 10:33:19 +00:00
Jake Walker
178d911be0 Update data manipulation bot 2023-11-24 10:05:36 +00:00
Jake Walker
92dabe59f7 Fix data manipulation bot configuration 2023-11-24 10:04:19 +00:00
Marek Wolan
bfd5f054dc Merge 'origin/dev' into feature/1971-ray-agents-2 2023-11-24 09:50:37 +00:00
Marek Wolan
abba1ef86b Remove hardcoded checkpoint frequency in rllib 2023-11-24 09:37:26 +00:00
Marek Wolan
6754dbf541 Remove GATE and fix a few spelling mistakes. 2023-11-24 09:28:50 +00:00
Jake Walker
b13a9d3daf Add application execution action for data manipulation bot 2023-11-24 09:25:55 +00:00
Marek Wolan
50c9ef16cb Move policy module into session 2023-11-24 09:18:18 +00:00
Marek Wolan
bd109a7cfc Complete session->game rename refactor 2023-11-24 09:14:55 +00:00
Christopher McCarthy
0caeb60e01 Merged PR 216: #2034 - Implemented the Simulation reset functionality
## Summary
Implemented the Simulation reset functionality by doing a deepcopy of the Simulation object inside the PrimaiteSession upon instantiation and assigning it to a `_simulation_initial_state` variable. Then when reset called, the sessions `simulation` variable is assigned the value of the `_simulation_initial_state` variable.

## Test process
Added a test that uninstalls a service before performing a reset then checks that the service reappears.

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [X] attended to any **TO-DOs** left in the code

#2034 - Implemented the Simulation reset functionality by doing a deepcopy of the Simulation object inside the PrimaiteSession upon instantiation. Added a test that uninstalls a service before performing a reset then checks that the service reappears.

Related work items: #2034
2023-11-23 22:33:12 +00:00
Czar Echavez
8aa743188f #2064: fix layout of test so it passes in pipeline 2023-11-23 22:28:08 +00:00
Czar Echavez
2ce03e0262 #2064: turn on everything when node is turned on 2023-11-23 22:10:53 +00:00
Czar Echavez
f0fc6518a0 #2064: add handling of offline service to dns, ftp and database 2023-11-23 21:48:11 +00:00
Chris McCarthy
dfe07ad926 #2034 - Fixed deepcopy reference issue 2023-11-23 21:25:52 +00:00
Czar Echavez
bd6c27244c #2064: Edited services and applications to handle when they are shut down 2023-11-23 19:49:03 +00:00
Nick Todd
3dfd7a2e14 #2068: Fix malformed Windows path 2023-11-23 17:57:51 +00:00
Nick Todd
3894a9615d #2068: Replace refs to OpenAI Gym with Gymnasium 2023-11-23 17:42:26 +00:00
Nick Todd
47112aafcf #2068: Removed references to ARCD GATE 2023-11-23 16:19:39 +00:00
Jake Walker
5f1a5af1b4 Add data manipulation bot action manager 2023-11-23 16:06:19 +00:00
Nick Todd
87dde6ee0b #2042: Test tidying changes. 2023-11-23 15:55:58 +00:00
Jake Walker
c93705867f Move configuration from agent to data manipulation bot 2023-11-23 15:53:47 +00:00
Christopher McCarthy
76939fb8e8 Apply suggestions from code review 2023-11-23 15:45:22 +00:00
Chris McCarthy
efeaa4c1cc #2034 - Implemented the Simulation reset functionality by doing a deepcopy of the Simulation object inside the PrimaiteSession upon instantiation. Added a test that uninstalls a service before performing a reset then checks that the service reappears. 2023-11-23 15:31:06 +00:00
Marek Wolan
4ee29efd1f Merged PR 213: Replace SQLite database implementation with a simulation
## Summary
Remove SQLLite and real sql queries and replace them with `SELECT` and `DELETE` queries that interact with the node's file system and service operating status.

## Test process
Existing unit tests pass after logic was changed.

## Checklist
- [x] PR is linked to a **work item**
- [ ] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [x] written **tests** for any new functionality added with this PR
- [x] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [x] attended to any **TO-DOs** left in the code

Related work items: #1971
2023-11-23 10:18:06 +00:00
Nick Todd
8584fa8f51 # 2041: Minor test changes 2023-11-23 10:04:52 +00:00
Marek Wolan
dd63563ba1 Update doc page on primaite session. 2023-11-23 03:07:39 +00:00
Marek Wolan
f1f516c51a Add multi agent session test 2023-11-23 02:51:31 +00:00
Marek Wolan
8a2279c6cb Update end to end tests after session changes 2023-11-23 01:40:27 +00:00
Marek Wolan
14ae8be5e2 Update session after it was split from game 2023-11-23 00:54:19 +00:00
Marek Wolan
1fd5298fc5 Fix multi agent system 2023-11-22 20:22:34 +00:00
Jake Walker
061e508187 Add repeat option to data manipulation bot 2023-11-22 16:24:17 +00:00
Nick Todd
006a37d268 #2042: extract code into request_time() method. 2023-11-22 14:40:44 +00:00
Nick Todd
3f76e09521 #2042: remove apply_timestep() return value 2023-11-22 14:13:50 +00:00
Marek Wolan
9070fb44d4 Check that ray single agent training works 2023-11-22 13:26:29 +00:00
Marek Wolan
b81dd26b71 Add Ray env class 2023-11-22 13:12:08 +00:00
Marek Wolan
1138644a4b Update to make things work with new layout 2023-11-22 12:59:33 +00:00
Marek Wolan
afd64e4674 Separate game, environment, and session 2023-11-22 11:59:25 +00:00
Nick Todd
dd7c2b05f8 #2041: Add RST doc 2023-11-22 08:54:39 +00:00
Nick Todd
984d165364 #2041: Fix long line 2023-11-21 17:24:50 +00:00
Nick Todd
eb2e37429a #2042: Add time attribute 2023-11-21 17:24:24 +00:00
Jake Walker
aa65c53a95 Pass probability of success through to functions 2023-11-21 15:09:51 +00:00
Jake Walker
48af022963 Run agent at configured timesteps 2023-11-21 13:41:38 +00:00
Nick Todd
243f2dd938 #2041: Update CHANGELOG 2023-11-21 12:11:30 +00:00
Jake Walker
d8154bbebd Add tests for data manipulation bot attack stages 2023-11-21 11:43:47 +00:00
Jake Walker
2975aa8827 Execute data manipulation bots from agent 2023-11-21 11:42:01 +00:00
Nick Todd
9ab33a4aa4 Merge branch 'dev' into feature/2041_2042-Add-NTP-Services 2023-11-21 11:28:50 +00:00
Nick Todd
60d94bf4b5 #2041: Remove test 2023-11-21 11:17:38 +00:00
Nick Todd
4f0f758ce9 #2041: Correct return value from receive() 2023-11-21 11:16:34 +00:00
Nick Todd
813a1f356e #2042: Remove debug statement 2023-11-21 11:15:07 +00:00
Marek Wolan
e9d2437db8 Merged PR 212: GATE-less agents
## Summary
Remove gate and integrate SB3 agent natively.
This includes:
- agent saving
- checkpoints
- session output directory
- simulation output (such as syslogs) are now in the session output directory
- agent loading
- training progress bar (with `enlighten`)

## Test process
End to end tests that verify that a session is being created correctly with a network
They also check the outputs exist.

## Checklist
- [y] PR is linked to a **work item**
- [upcoming PR] **acceptance criteria** of linked ticket are met
- [y] performed **self-review** of the code
- [loading not tested but need to move onto Ray now] written **tests** for any new functionality added with this PR
- [n] updated the **documentation** if this PR changes or adds functionality
- [n] written/updated **design docs** if this PR implements new functionality
- [n] updated the **change log**
- [y] ran **pre-commit** checks for code style
- [n] attended to any **TO-DOs** left in the code

Related work items: #1971
2023-11-21 09:33:29 +00:00
Nick Todd
f7215847d4 #2041: ntp_server test fixes. 2023-11-20 18:08:55 +00:00
Nick Todd
b0b37f9da5 #2042: ntp_client test fixes. 2023-11-20 18:06:50 +00:00
Nick Todd
95ad55a783 #2041: change deprecated logger levels. 2023-11-20 18:04:49 +00:00
Jake Walker
7e0e8a4768 Pass agent settings from config to agent 2023-11-20 10:38:01 +00:00
Marek Wolan
66d5612e92 Merge remote-tracking branch 'origin/feature/1972-remove-sqlite' into feature/1971-ray-agents-2 2023-11-18 04:54:17 +00:00
Marek Wolan
fdb48c0ded Update docs for Database 2023-11-18 03:46:24 +00:00
Marek Wolan
7d800cbbc9 Merge remote-tracking branch 'origin/dev' into feature/1972-remove-sqlite 2023-11-18 03:41:22 +00:00
Marek Wolan
77f3806ba7 Remove real database in favour of simulated 2023-11-18 03:40:08 +00:00
Marek Wolan
9d0a98b221 Apply suggestions from code review 2023-11-17 20:30:07 +00:00
Marek Wolan
5d9d8fe92c merge PR updates from parent branch 2023-11-17 17:59:45 +00:00
Marek Wolan
3fb7bce3ce Get RLLib to stop crashing. 2023-11-17 17:57:57 +00:00
Nick Todd
d28bd0d1c3 #2041: Fix names 2023-11-17 14:19:36 +00:00
Nick Todd
dbecc681dc #2041: Install NTPServer and NTPClient. 2023-11-17 12:59:06 +00:00
Nick Todd
6081f02caa #2041: Add missing return statement 2023-11-17 12:41:53 +00:00
Nick Todd
622c6931d8 #2041: Create test network + extra test 2023-11-17 12:07:46 +00:00
Jake Walker
227e73602f Pass execution definition from config to agent 2023-11-17 11:51:19 +00:00
Marek Wolan
c5b4ae45be Remove problematic progress bars 2023-11-17 11:40:36 +00:00
Marek Wolan
6e5e1e6456 Begin rllib 2023-11-17 11:38:29 +00:00
Marek Wolan
5bda952ead Fix sim output 2023-11-17 10:20:26 +00:00
Marek Wolan
ba580b00b4 Improve config validation and fix tests 2023-11-16 16:14:50 +00:00
Marek Wolan
0861663cc1 Add agent loading 2023-11-16 15:40:49 +00:00
Marek Wolan
e52d1fbd45 Add enlighten dependency 2023-11-16 15:29:48 +00:00
Marek Wolan
0b9bdedebd Fix typehints 2023-11-16 15:28:38 +00:00
Marek Wolan
13c49bf3ea Fix session path monkeypatch 2023-11-16 15:19:14 +00:00
Marek Wolan
7545c25a46 Make pytest patch with temporary session dir 2023-11-16 15:11:03 +00:00
Nick Todd
7ee2c4220a #2042: ntp_client test 2023-11-16 15:04:01 +00:00
Marek Wolan
829500a60f Get sb3 checkpoints saving during training 2023-11-16 14:37:37 +00:00
Jake Walker
1c5ff66d26 Pass execution definition from config to agent 2023-11-16 13:26:30 +00:00
Marek Wolan
4cc7ba1522 Add ability to save sb3 final model 2023-11-15 16:59:56 +00:00
Marek Wolan
64e8b3bcea Add basic primaite session e2e tests 2023-11-15 16:04:16 +00:00
Nick Todd
0c544a9a26 #2042: Add support for apply_timestep() 2023-11-15 15:58:10 +00:00
Marek Wolan
6182b53bfd Fix incorrect number of steps per episode 2023-11-15 14:49:44 +00:00
Marek Wolan
c8f2f193bd Implement agent training with sb3 2023-11-15 12:52:18 +00:00
Nick Todd
9deb130d10 #2042: pre-commit changes 2023-11-15 10:58:24 +00:00
Nick Todd
d31fce202c #2041: pre-commit changes. 2023-11-15 10:57:56 +00:00
Nick Todd
195e8a4e84 #2042: Implement NTP protocol for client 2023-11-14 15:13:28 +00:00
Nick Todd
f320487128 #2041: Implement NTP protocol for server 2023-11-14 15:13:05 +00:00
Marek Wolan
e6ead6e532 Update agent interface to work better with envs 2023-11-14 15:10:07 +00:00
Nick Todd
764d9561bd #2042: NTP client initial commit 2023-11-13 17:40:25 +00:00
Nick Todd
2ee8203397 #2041: NTP server initial commits 2023-11-13 17:39:27 +00:00
Marek Wolan
1cb54da2dd Remove more GATE stuff 2023-11-13 17:12:50 +00:00
Marek Wolan
08e88e52b0 Begin implementing training loop in session 2023-11-13 16:35:35 +00:00
Marek Wolan
707f2b59af Add SB3 RL agent 2023-11-13 16:08:39 +00:00
Marek Wolan
21c06dbea1 Remove GATE-related code. 2023-11-13 16:04:25 +00:00
Chris McCarthy
23fd9c3839 #1859 - Started giving the red agent some 'intelligence' and a sense of a state. Changed Application.run to .execute. 2023-11-13 15:55:14 +00:00
Czar Echavez
815bdfe603 Merged PR 206: 1962-Folder and File restore
## Summary
- Implement the folder/file restore
- Split the FileSystem and its classes into their own files so that it is easier to maintain.
- Reimplement how deleted folders and files are stored in a deleted list, so that it is possible to restore later

## Test process
See https://dev.azure.com/ma-dev-uk/PrimAITE/_git/PrimAITE/pullrequest/206?_a=files&path=/tests/unit_tests/_primaite/_simulator/_file_system
- Unit tests written to make sure methods work as intended
- Integration tests with the apply_request method which tests that the agents can send the request to the simulation to affect it

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

Related work items: #1962
2023-11-09 11:55:53 +00:00
Czar.Echavez
6e1f9bd63d #1962: add gate installation for docs build pipeline 2023-11-08 13:00:07 +00:00
Czar.Echavez
be4a467877 #1962: revert pulling from src 2023-11-08 10:48:41 +00:00
Czar.Echavez
f5df1366a7 #1962: merge dev into branch + fix minor diffs + ensure that imports pull from src 2023-11-08 10:36:47 +00:00
Marek Wolan
c060991084 Merged PR 207: Game layer
## Summary
- Remove v2-specific code, documentation, and tests
- Reconnect CLI, to new v3 classes and functions
- Add Game layer
- Minor changes to simulation layer to ensure compatibility with game layer actions and observations

### Game layer
- Add a primaite session, which is the main entry point to running a session. This encompasses agents, the simulation, and a connection with GATE.
- Add an agent interface, random agents, and RL agents.
- Add new observation space management
- Add new action space management
- Add new reward function management

## Test process
Ran primaite session without crash. Majority of integration and unit tests have not been written yet. (sorry)

I know it's not ideal to merge in this not-tested-state, but it doesn't make sense to continue diverging `dev` and `dev-game-layer`.

Instead of reviewing the diff, I would recommend downloading this code and getting familiarised with the new `game` module by reading the code and playing around with it.

Related work items: #1622, #1759, #1760, #1761, #1764, #1765, #1766, #1767, #1768, #1879, #1924, #1986, #1987, #1988, #1989, #1990, #1998
2023-11-07 16:03:43 +00:00
Czar Echavez
729ef2ebac Merged PR 208: #2025: added GATE installation as part of pipeline
## Summary
Installing GATE before running the primaite setup command so that the pipeline passes

## Test process
*How have you tested this (if applicable)?*

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [X] attended to any **TO-DOs** left in the code

#2025: added GATE installation as part of pipeline

Related work items: #2025
2023-11-07 15:03:00 +00:00
Czar.Echavez
d4679bb0e3 #2025: Missing character for GATE path 2023-11-07 14:09:22 +00:00
Czar.Echavez
e0d694a736 #2025: added GATE installation as part of pipeline 2023-11-07 14:00:08 +00:00
Marek Wolan
0ea282166d Merge remote-tracking branch 'origin/dev' into dev-game-layer 2023-11-06 16:23:29 +00:00
Czar.Echavez
eba10ae5ef #1962: clean up tests + improve the show command which shows the folders and files in file system 2023-11-06 11:56:44 +00:00
Czar.Echavez
535c1b19ab #1962: attempt to make the timestep actions look neater + adding logic that allows restoring a folder take multiple timesteps 2023-11-06 11:12:06 +00:00
Czar.Echavez
e70ceec716 #1962: folder/file restore logic 2023-11-06 10:22:08 +00:00
Czar.Echavez
51713bad74 #1962: split tests into managable files + implement deletion of folders and files + tests 2023-11-03 15:15:18 +00:00
Czar.Echavez
b2c3e273b7 #1962: separating file system into more managable files 2023-11-02 15:10:51 +00:00
Czar.Echavez
b67eb1bb34 #1962: separating file system into more managable files 2023-11-02 13:14:08 +00:00
Czar.Echavez
11848aa180 #1962: keeping track of deleted files 2023-10-31 15:52:44 +00:00
Czar Echavez
870707f86b Merged PR 200: Implement node scan and reset
## Summary
Implementing the ability for the simulation to scan all node components as well as the ability for the red agent to reveal the node and its components.

Implementing the ability for the simulation to reset a node

## Test process
Unit tests added

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

Related work items: #1961
2023-10-30 16:47:28 +00:00
Czar.Echavez
98ca33e994 #1961: scanning no longer happens every timestep - the scan is all done in one timestep after the required timestep countdown is complete 2023-10-30 15:34:13 +00:00
Czar.Echavez
1ddf400d6f #1961: node resetting 2023-10-27 18:28:34 +01:00
Czar.Echavez
68b22b6444 #1961: node scanning + applying timestep to all components within node + node revealing to red 2023-10-27 17:50:41 +01:00
Marek Wolan
2923921559 Merged PR 199: Fix setup and session commands
## Summary
Make PrimAITE work with the new:
- configs
- CLI commands

## Test process
I ran primaite setup and primaite session to check that they work

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

Related work items: #1987, #1998
2023-10-27 15:14:06 +00:00
Marek Wolan
a37ce051c5 Add ARCD GATE setup to primaite setup 2023-10-27 14:50:31 +01:00
Marek Wolan
75d1fd20c3 Remove temporary files 2023-10-27 14:41:53 +01:00
Marek Wolan
b81c1739f8 Fix CLI and Session to work with new classes 2023-10-27 14:26:52 +01:00
Marek Wolan
6378ff3087 Merged PR 198: Updates to documentation
* STILL IN PROGRESS *

## Summary
Delete old documentation, write some more up-to-date documentation.

## Test process

## Checklist
- [ ] PR is linked to a **work item**
- [ ] **acceptance criteria** of linked ticket are met
- [ ] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [ ] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

Updates to documentation

Related work items: #1988, #1990
2023-10-27 11:33:09 +00:00
Marek Wolan
1ec1b319e5 Fix formatting in docs 2023-10-27 12:24:22 +01:00
Marek Wolan
d4eb499729 Start fixing up cli and setup 2023-10-27 12:20:23 +01:00
Marek Wolan
a06629ed0b Bump version 2023-10-27 11:48:54 +01:00
Marek Wolan
6ac7dcf9ac Update README.md 2023-10-27 11:48:22 +01:00
Marek Wolan
318c9f8c5a Fix formatting issues 2023-10-27 11:43:11 +01:00
Czar.Echavez
8783574442 #1961: os scan set up 2023-10-27 10:17:59 +01:00
Marek Wolan
11fad5084e Merged PR 197: Remove deprecated functionality
## Summary
* Delete many files which are not used with the new V3 approach. Including all the previous simulation files, as well as the old config, old session, etc.
* Delete tests for the removed functionality
* Note: this PR can only be merged after !195

## Test process
This PR Changes our Unit Test suite to only keep tests related to V3 code. All tests pass as of my recent attempt.

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [~] written **tests** for any new functionality added with this PR
- [~] updated the **documentation** if this PR changes or adds functionality
- [n] written/updated **design docs** if this PR implements new functionality
- [x] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [n] attended to any **TO-DOs** left in the code

Related work items: #1989, #1986
2023-10-26 14:33:31 +00:00
Marek Wolan
4f387cf092 Merged PR 195: Initial game layer functionality
## Summary
* add a new module `game` to PrimAITE
* this includes a new PrimaiteSession which creates a simulation, and multiple agents, and talks to GATE
* agent interface
* agent actions to work with Simulator requests
* agent observations that work with Simulator State
* agent rewards also with Simulator state

**note** that this branch is currently still in a broken state. Still need to do things like updating readme, install instructions, refactoring some poorly designed classes, and removing legacy code. These will be done in subsequent PRs to avoid making this PR even bigger than it needs to be. Still, please review this to familiarise yourself.

## Test process
Some unit tests exist but their coverage will be expanded.
I performed some test runs with to train a SB3 agent in GATE with a primaite simulation.

## Checklist
- [y] PR is linked to a **work item**
- [y] **acceptance criteria** of linked ticket are met
- [~] performed **self-review** of the code
- [n] written **tests** for any new functionality added with this PR
- [~] updated the **documentation** if this PR changes or adds functionality
- [~] written/updated **design docs** if this PR implements new functionality
- [~] updated the **change log**
- [y] ran **pre-commit** checks for code style
- [n] attended to any **TO-DOs** left in the code

Related work items: #1622, #1759, #1760, #1761, #1764, #1765, #1766, #1767, #1768, #1879, #1924
2023-10-26 12:49:11 +00:00
Marek Wolan
afa7916db0 Updates to documentation 2023-10-25 23:32:52 +01:00
Marek Wolan
450aa150ae Merge remote-tracking branch 'origin/dev-game-layer' into feature/1989-remove-v2-modules 2023-10-25 19:19:34 +01:00
Marek Wolan
02901a7c99 Apply suggestions from code review. 2023-10-25 19:07:45 +01:00
Marek Wolan
38b71c0c8e Update CHANGELOG 2023-10-25 18:06:33 +01:00
Marek Wolan
78a8d2be3e Fix File observation test 2023-10-25 17:57:19 +01:00
Marek Wolan
59e2c23c04 Merge remote-tracking branch 'origin/feature/1924-Agent-Interface' into feature/1989-remove-v2-modules 2023-10-25 17:56:21 +01:00
Marek Wolan
4872c939ff Apply suggestions from code review 2023-10-25 17:19:24 +01:00
Marek Wolan
c57b5152c0 Remove broken tests 2023-10-25 17:08:01 +01:00
Marek Wolan
1e811148ed Fix dependency versions to align with GATE 2023-10-25 17:04:30 +01:00
Marek Wolan
2b8462d38d Fix link import in v3 code 2023-10-25 17:04:04 +01:00
Marek Wolan
e8e14ae68a Comment out tests for primaite v2 2023-10-25 13:56:02 +01:00
Marek Wolan
f861b1897a Remove deprecated code from v2 2023-10-25 13:36:55 +01:00
Marek Wolan
ffe80f215e Merge 'origin/dev-game-layer' into feature/1924-Agent-Interface 2023-10-25 09:58:04 +01:00
Czar Echavez
091920c6f7 Merged PR 192: Implement missing actions
## Summary

#1947
Implementation of actions from the QTSL-820-2450 - ARCD Track 2 Common Interface Definition for Environments UC2 document

Covers:
- [X] BAS-12 NODE  SERVICE SCAN
- [X] BAS-15 NODE  SERVICE STOP
- [X] BAS-16 NODE  SERVICE START
- [X] BAS-17 NODE  SERVICE PAUSE
- [X] BAS-18 NODE  SERVICE RESUME
- [X] BAS-19 NODE  SERVICE RESTART
- [X] BAS-20 NODE  SERVICE DISABLE
- [X] BAS-21 NODE  SERVICE ENABLE

- [X] BAS-29 NODE  FILE SCAN
- [X] BAS-30 NODE  FILE CHECKHASH
- [X] BAS-33 NODE  FILE DELETE
- [X] BAS-34 NODE  FILE REPAIR

- [X] BAS-38 NODE  FOLDER SCAN
- [X] BAS-39 NODE  FOLDER CHECKHASH
- [X] BAS-41 NODE  FOLDER REPAIR

- [X] BAS-44 NODE SHUTDOWN
- [X] BAS-45 NODE STARTUP

- [X] RAS-30 NODE FILE DELETE
- [X] RAS-31 NODE FILE CORRUPT
- [X] RAS-36 NODE FOLDER DELETE
- [X] RAS-37 NODE FOLDER CORRUPT

## Test process

### node actions test
https://dev.azure.com/ma-dev-uk/PrimAITE/_git/PrimAITE/pullrequest/192?_a=files&path=/tests/unit_tests/_primaite/_simulator/_network/_hardware/test_node_actions.py

### service actions
https://dev.azure.com/ma-dev-uk/PrimAITE/_git/PrimAITE/pullrequest/192?_a=files&path=/tests/unit_tests/_primaite/_simulator/_system/_services/test_service_actions.py

### file/folder actions
https://dev.azure.com/ma-dev-uk/PrimAITE/_git/PrimAITE/pullrequest/192?_a=files&path=/tests/unit_tests/_primaite/_simulator/_file_system/test_file_system_actions.py

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [X] attended to any **TO-DOs** left in the code

Related work items: #1947
2023-10-25 08:35:59 +00:00
Marek Wolan
c9b06e1bfb Delete sandbox file 2023-10-24 17:06:58 +01:00
Marek Wolan
cb60b6f785 Update text in docs 2023-10-24 17:02:29 +01:00
Marek Wolan
d49d5b292d Add a bit of documentation 2023-10-24 15:51:29 +01:00
Czar.Echavez
ac23633d82 #1947: Added documentation on how the node initialisation works 2023-10-24 15:41:39 +01:00
Czar.Echavez
c4b43c479e #1947: remove storing deleted files in a list and banish them to the shadow realm instead 2023-10-24 11:53:21 +01:00
Marek Wolan
174de013fb Align blue actions with common env 2023-10-24 11:43:25 +01:00
Marek Wolan
6b7c483a67 Align observations to Common approach 2023-10-24 11:07:25 +01:00
Czar.Echavez
1e66795aff #1947: remove scan from components that cannot be scanned 2023-10-24 10:43:00 +01:00
Czar.Echavez
8b85d5d55b #1947: node startup/shutdown now take multiple timesteps to complete 2023-10-24 10:11:50 +01:00
Marek Wolan
d4eee36b7b Fix software registration for game layer and simulator interface 2023-10-23 17:23:14 +01:00
Marek Wolan
975aa9ffc2 Minor changes to rewards and services. 2023-10-23 16:26:34 +01:00
Czar.Echavez
724beb1a29 #1947: folder/file scan now take multiple time steps to complete 2023-10-23 15:58:37 +01:00
Czar.Echavez
ffc4711afb #1947: added test for agent actions + clearing up the implementation of the request managers for filesystem 2023-10-20 12:58:58 +01:00
Marek Wolan
0f24b4a646 Remove broken import 2023-10-19 15:34:46 +01:00
Marek Wolan
49e78d5291 Add docstrings and fix formatting on many things 2023-10-19 09:36:23 +01:00
Marek Wolan
e0f8c3c5ea Add documentation 2023-10-19 01:56:40 +01:00
Czar.Echavez
0edb9b46a7 #1947: clean up existing work and clear up some itesm left in TODO 2023-10-18 13:21:05 +01:00
Czar.Echavez
4ee2235dd1 #1947: temp commit what is done so far 2023-10-16 11:42:56 +01:00
Czar.Echavez
9b5d95cbb9 #1947: refactor am->rm to align with refactor of ActionManager->RequestManager 2023-10-13 10:41:27 +01:00
Czar.Echavez
5e419455f1 Merge branch 'dev' into feature/1947-implement-missing-node-actions 2023-10-12 13:17:04 +01:00
Czar.Echavez
c9e4ba3c7d #1947: File and Folder hash checks 2023-10-12 11:16:25 +01:00
Marek Wolan
027addc485 Merge remote-tracking branch 'origin/dev' into feature/1924-Agent-Interface 2023-10-12 10:00:46 +01:00
Marek Wolan
1c5eb392d0 Merged PR 184: Connect up actions in the simulator
## Summary
Finishes (?) the action system.
- Defines all UC2 common action space actions on SimComponents
- Links up SimComponents and their children, so actions can be passed from parent to child
- Add a function for enumerating all possible actions that exist on a SimComponent. (will be used for generating action space)
- add documentation for action management

note: I know that the way I approached this is a bit convoluted but It's just what I came up with to allow the actions to be as flexible and modular as the SimComponents themselves.

## Test process
Tested that the functionality works in scratch notebook. But also in the process of adding unit/integration tests now.

## Checklist
- [x] PR is linked to a **work item**
- [ ] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [x] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

Related work items: #1923
2023-10-12 09:00:30 +00:00
Marek Wolan
565af11dba Minor fixes to rewards 2023-10-12 09:59:45 +01:00
Marek Wolan
70c1857bbc Implement rewards for UC2 (draft) 2023-10-11 15:49:41 +01:00
Marek Wolan
b84ab84385 Fix GATE Client to work successfully with GATE Server 2023-10-11 14:08:55 +01:00
Marek Wolan
def2c3699b Add empty obs placeholders 2023-10-10 21:01:09 +01:00
Czar.Echavez
060bbf0506 #1947: added ability for files and folders to be scanned, corrupted and repaired 2023-10-10 15:14:47 +01:00
Czar.Echavez
a1b4d3d5e0 Merge branch 'feature/1812-traverse-actions-dict' into feature/1947-implement-missing-node-actions 2023-10-10 09:59:34 +01:00
Czar.Echavez
56eda38a6e #1947: git merge did not change add_action -> add_request 2023-10-10 09:52:40 +01:00
Marek Wolan
f3451b2fbb Replace request overwrite error with warning 2023-10-10 09:50:39 +01:00
Marek Wolan
b53c3856dd Add GATE wheel temporarily 2023-10-10 09:48:04 +01:00
Czar.Echavez
80d371c238 Merge branch 'feature/1812-traverse-actions-dict' into feature/1947-implement-missing-node-actions 2023-10-10 08:58:58 +01:00
Marek Wolan
91f06c15f6 Fix formatting with precommit 2023-10-09 18:35:30 +01:00
Marek Wolan
c9bc8fbf3d Fix file observation test 2023-10-09 18:33:30 +01:00
Marek Wolan
37c851b5c5 Merge remote-tracking branch 'origin/dev' into feature/1924-Agent-Interface 2023-10-09 18:29:48 +01:00
Marek Wolan
18706be4ff Merge branch 'origin/dev' into feature/1812-traverse-actions-dict 2023-10-09 18:26:25 +01:00
Marek Wolan
560e416eda Merge 'origin/feature/1812' into feature/1924 2023-10-09 18:25:46 +01:00
Marek Wolan
e85c5977d0 remove redundant code from sandbox notebook 2023-10-09 18:22:30 +01:00
Marek Wolan
f68886d5df Fix bugged actions 2023-10-09 17:29:50 +01:00
Czar.Echavez
bbf2b09f96 #1947: Add ability for all simcomponents to be scanned - sets up ability for service, files, folders and nodes to be scanned 2023-10-09 16:47:36 +01:00
Czar Echavez
e06c51e5d6 Merged PR 191: Web Service and Client
## Summary
Added a WebServer service and a Web Browser (client) so that the simulation can emulate HTTP requests across the network via HTTPPacket transfer

## Test process
Written an integration test that tests Web Server and Web Browser sending and returning requests

## Checklist
- [X] PR is linked to a **work item**
- [X] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [X] written **tests** for any new functionality added with this PR
- [X] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [X] updated the **change log**
- [X] ran **pre-commit** checks for code style
- [X] attended to any **TO-DOs** left in the code

Related work items: #1752, #1816, #1866, #1916, #1943
2023-10-09 13:21:17 +00:00
Czar.Echavez
318539fd8f #1943: apply suggestions from PR + fixing FTP bug + elaborating 2023-10-09 13:25:12 +01:00
Marek Wolan
5a5710c6ae Rename Sim Actions to request 2023-10-09 13:24:08 +01:00
Marek Wolan
2722abe428 Fix typos and formattig (based on PR Review) 2023-10-09 11:49:38 +01:00
Marek Wolan
df22d0de0b Merge remote-tracking branch 'origin/dev' into feature/1812-traverse-actions-dict 2023-10-09 11:39:31 +01:00
Marek Wolan
081a3e519a Fix certain observation bugs 2023-10-08 17:57:45 +01:00
Marek Wolan
ccb36f8400 Change observations to make loading from config better 2023-10-08 17:02:54 +01:00
Marek Wolan
3dea9743c3 Get primaite session step working 2023-10-06 20:32:52 +01:00
Czar.Echavez
853bb9eecc #1943: unit tests + refactoring HTTP -> Http 2023-10-06 12:10:57 +01:00
Marek Wolan
2a8df074b9 Add network action 2023-10-06 10:36:29 +01:00
Czar.Echavez
be6b904db9 - Fixed FTP client server infinite recursion - ftp server and clients can be installed on the same node, this could cause a loop of requests
- fixed tests broken by merged with dev
2023-10-05 16:24:48 +01:00
Czar.Echavez
4699e87ea8 Merge branch 'dev' into feature/1943-service-web-server 2023-10-04 16:35:23 +01:00
Czar Echavez
c71e989ac6 Merged PR 187: Database Service backup using FTP
## Summary
- Used FTP changes to allow the database service to create a copy of the database.db file in the backup server
- Used FTP changes to allow the database service to restore the database.db file from a copy made in the backup server

## Test process
*How have you tested this (if applicable)?*

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [X] performed **self-review** of the code
- [x] written **tests** for any new functionality added with this PR
- [X] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [X] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [x] attended to any **TO-DOs** left in the code

Related work items: #1752, #1796, #1816, #1866, #1916
2023-10-04 14:06:32 +00:00
Czar.Echavez
97f0267539 #1796: apply PR suggestions + fix tests 2023-10-04 11:33:18 +01:00
Marek Wolan
fabd4fd5dd Add ACL Action to game layer 2023-10-04 09:07:04 +01:00
Czar.Echavez
82da21b073 \#1943:
- changelog added
- added documentation + example of using web server + web browser
- extended web server so that it also accepts ip addresses
- web server can differentiate between a normal page request and one that propagates into a DB request
- rename WebServerService -> WebServer
2023-10-03 16:56:35 +01:00
Czar.Echavez
4b5a73bd32 #1943: web server + client + tests + a few improvements to syslogging 2023-10-03 14:59:48 +01:00
Marek Wolan
2b617e01a3 Finalise actions interface 2023-10-02 17:21:43 +01:00
Czar.Echavez
fdebfce406 #1796: Fix test + making the restore test better 2023-10-02 12:14:59 +01:00
Chris McCarthy
84405d7ed3 #1796 - Added docstring to the test_uc2_data_manipulation_scenario.py 2023-09-29 20:19:26 +01:00
Chris McCarthy
3dc8a0f222 #1796 - Made the FTP copy real files. Hardcoded the DatabaseService backup folder and filename. Added db restore and final query check to the data manipulation e2e test. 2023-09-29 20:14:42 +01:00
Czar.Echavez
bca3e6344e #1796: documentation 2023-09-28 14:09:32 +01:00
Czar.Echavez
6202d320a6 #1796: Add ability to create and restore database backups + add more sys log messages + remove the link size checks temporarily 2023-09-28 12:23:49 +01:00
Czar.Echavez
c096d06bcd #1796: pre installing system software 2023-09-26 15:14:24 +01:00
Czar Echavez
161d441ad6 Merged PR 185: FTP - client/server
## Summary
Initial implementation of an FTP Client/Server service used to emulate a transfer of files across nodes

## Test process
Added an integration and unit test

## Checklist
- [x] PR is linked to a **work item**
- [x] **acceptance criteria** of linked ticket are met
- [x] performed **self-review** of the code
- [x] written **tests** for any new functionality added with this PR
- [X] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [X] updated the **change log**
- [x] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

Related work items: #1752, #1816, #1916
2023-09-26 13:38:42 +00:00
Marek Wolan
f1346ae278 put in agent parsing skeleton 2023-09-26 12:54:56 +01:00
Czar.Echavez
79615243e4 #1916: Added example usage for FTP 2023-09-26 12:09:41 +01:00
Marek Wolan
92e0110e73 yaml parse and connect links 2023-09-26 11:48:22 +01:00
Marek Wolan
fdf66ba3de Make yaml parser work with services 2023-09-26 10:52:14 +01:00
Marek Wolan
f79ed99bd2 end of day 2023-09-25 19:17:57 +01:00
Marek Wolan
493014ca19 draft yaml parser 2023-09-25 17:57:47 +01:00
Marek Wolan
9d4e41435d End-of-day commit 2023-09-25 16:04:04 +01:00
Czar.Echavez
0140fe7c48 #1916: fix a problem with process_ftp_command method 2023-09-25 15:59:31 +01:00
Czar.Echavez
2520b67889 #1916:
- Added FTP to changelog
- Added FTP to documentation
- Added documentation in code
- Clean up of methods - prevent repeats of the same code
2023-09-25 14:31:57 +01:00
Czar.Echavez
98ca71aaba Merge branch 'dev' into feature/1916-ftp-client-server 2023-09-25 10:40:51 +01:00
Czar.Echavez
2c234ab67a #1916: Setting up a connected states + added tests + error states for if service is interacted with when not running 2023-09-22 15:38:01 +01:00
Czar.Echavez
58edb6d3e4 #1916: Created FTP superclass + working retrieve file method for FTP 2023-09-21 15:13:30 +01:00
Marek Wolan
53fd4ed828 Finish File Observation 2023-09-21 10:42:26 +01:00
Marek Wolan
d98d303dda Merge remote-tracking branch 'origin/feature/1812-traverse-actions-dict' into feature/1924-Agent-Interface 2023-09-21 10:13:31 +01:00
Marek Wolan
f54f278fca Initialise observations in agent interface 2023-09-21 10:13:01 +01:00
Czar.Echavez
2e76b3f162 #1916: FTP client STOR request to FTP server 2023-09-20 16:23:35 +01:00
Marek Wolan
860b3fb801 Add test to new action functionliaty 2023-09-19 16:11:42 +01:00
Marek Wolan
682091b4ba Remove redundant method 2023-09-19 15:30:02 +01:00
Marek Wolan
93476554a9 Undo experimental changes to request format 2023-09-19 15:17:13 +01:00
Marek Wolan
68f67f13da Fix formatting on docs for actions. 2023-09-19 15:13:51 +01:00
Marek Wolan
d523ccc3cb Improve docs on action system 2023-09-19 14:23:14 +01:00
Marek Wolan
fd1a4403f4 Merged PR 179: Updated pull_request_template.md
## Summary
*Replace this text with an explanation of what the changes are and how you implemented them. Can this impact any other parts of the codebase that we should keep in mind?*

## Test process
*How have you tested this (if applicable)?*

## Checklist
- [ ] This PR is linked to a **work item**
- [ ] I have performed **self-review** of the code
- [ ] I have written **tests** for any new functionality added with this PR
- [ ] I have updated the **documentation** if this PR changes or adds functionality
- [ ] I have written/updated **design docs** if this PR implements new functionality
- [ ] I have update the **change log**
- [ ] I have run **pre-commit** checks for code style

Updated pull_request_template.md

Related work items: #1866
2023-09-19 12:43:17 +00:00
Marek Wolan
3ee5e22b24 Add router action 2023-09-19 12:48:55 +01:00
Marek Wolan
898123cb10 Stub out more actions 2023-09-19 11:46:02 +01:00
Marek Wolan
aa6834ad08 Check service actions work. 2023-09-19 11:41:02 +01:00
Marek Wolan
610517d817 Underscore 'parent' refs to make pydantic happy.
Rename attributes like connected_link and connected_node to start with
an underscore.

This will prevent circular dependency and stack recursion depth error.
2023-09-19 11:28:13 +01:00
Marek Wolan
a719389e05 Add placeholder actions 2023-09-19 11:24:42 +01:00
Marek Wolan
77108634e8 Merge remote-tracking branch 'origin/dev' into feature/1812-traverse-actions-dict 2023-09-19 10:12:47 +01:00
Czar.Echavez
f913294058 #1916: moved services into their own subdirectories 2023-09-18 14:20:19 +01:00
Czar Echavez
f180c6f680 Merged PR 177: DNS Server and Client
## Summary
Carrying on where Sunil left the task. Added more functionality to the DNS.
- DNS Server can keep a list of domain names that the DNS Client can request
- DNS Client has a cache of domain names that are valid from the DNS Server

## Test process
https://dev.azure.com/ma-dev-uk/PrimAITE/_git/PrimAITE/pullrequest/177?_a=files&path=/tests/unit_tests/_primaite/_simulator/_system/_services/test_dns.py

## Checklist
- [x] This PR is linked to a **work item**
- [x] I have performed **self-review** of the code
- [x] I have written **tests** for any new functionality added with this PR
- [X] I have updated the **documentation** if this PR changes or adds functionality
- [ ] I have written/updated **design docs** if this PR implements new functionality
- [X] I have update the **change log**
- [x] I have run **pre-commit** checks for code style

Related work items: #1752
2023-09-18 10:31:16 +00:00
Chris McCarthy
939de40f1e #1752 - Moved dns_server ip address from the NIC to the Node. Updated the arcd_uc2_network so that clients and servers have a dns server. Added sys_log entries for DNSServer and DNSClient. MAde the DNSServer always rend a reply, but for the resolved IP address to be empty if it cannot be resolved. 2023-09-18 10:25:26 +01:00
Czar.Echavez
b1e46b4f9e #1752: Apply suggestions from PR review 2023-09-14 20:08:06 +01:00
Czar Echavez
98e103a984 #1752: added documentation for DNS Client and Server 2023-09-13 09:48:38 +01:00
Czar Echavez
b0478f4e88 #1752: added positions to ACL rules for UC2 network to prevent rules being overwritten 2023-09-13 08:46:22 +01:00
Czar Echavez
f29477a50a Merge branch 'dev' into feature/1752-dns-server-and-client 2023-09-12 14:34:15 +01:00
Christopher McCarthy
69c3f97cd9 Merged PR 178: Database Client/Server Simulation
## Summary
This pull request focuses on implementing key functionalities needed for network frame processing and database interactions. The primary changes are:

1. **Internal Frame Processing:** The logic has been implemented in various components like `NIC`, `Node`, `SessionManager`, and `SoftwareManager`. These changes enable the system to process incoming and outgoing network frames in a structured manner.
2. **Database Service and Client:** The `DatabaseService` simulates a SQL database server, while the `DatabaseClient` provides a client interface for connecting to this service. These functionalities have been built and integrated into the existing architecture.
3. **Networking and Communication:** Tests have been added to confirm that database queries can be sent over the network, demonstrating end-to-end functionality.

## Commits

- #1816 Simplified a bunch of stuff in the file system in prep for services and applications. Started adding the database logic. Waiting for the software manager/session manager work from another tick. Merge branch 'dev' into feature/1816_Database-Service-(Network-and-User-Interaction)
- #1816 Added the final pieces of the puzzle to get data up from NIC → session manager → software manager → service.
- #1816 DatabaseService now uses the send function when responding.
- #1816 Added database client. Installed the database client on the Web Server node in the UC2 network. Updated the integration test to query the DB server using the DB client.
- #1816 Added full documentation on the database client/server, and the internal frame processing process
- #1816 Fixed tests. Used node and link added number (id) in observation space.

## Test process
For testing these functionalities, the following steps were taken:

1. **Unit Tests:** Tests have been written to confirm that database queries can be sent over the network successfully.
2. **Integration Tests:** Manually tested the frame processing flow from NIC to Service/Application, ensuring the functionality behaves as expected.
3. **Database Queries** Executed sample SQL queries using the `DatabaseClient` to make sure it interacts correctly with the `DatabaseService`.

## Checklist
- [ ] This PR is linked to a **work item**
- [ ] I have performed **self-review** of the code
- [ ] I have written **tests** for any new functionality added with this PR
- [ ] I have updated the **documentation** if this PR changes or adds functionality
- [ ] I have written/updated **design docs** if this PR implements new functionality
- [ ] I have update the **change log**
- [ ] I have run **pre-commit** checks for code style

Related work items: #1816
2023-09-12 13:31:08 +00:00
Czar Echavez
8b6bc84321 #1752: simplifying the DNS implementation - switch to TCP + fixing the DNS integration test 2023-09-12 13:37:11 +01:00
Marek Wolan
275115f4dd Updated pull_request_template.md 2023-09-12 12:12:38 +00:00
Czar Echavez
fb96ef18c0 #1752: remove unnecessary changes 2023-09-12 09:32:28 +01:00
Czar Echavez
1a81285b76 #1752: Added send+receive functionality for DNS client and server + tests + added simulation_output to gitignore 2023-09-12 08:46:07 +01:00
Czar Echavez
ee730d4ab0 Merge branch 'feature/1816_Database-Service-(Network-and-User-Interaction)' into feature/1752-dns-server-and-client 2023-09-11 16:22:18 +01:00
Chris McCarthy
695b3ceab4 #1816 - Updated the DataManipulationBot to subclass DatabaseClient. Extended logging. Dropped the Link loading logging as it was clogging up the terminal output. 2023-09-11 16:15:03 +01:00
Czar Echavez
4c67365d4f Merge branch 'feature/1816_Database-Service-(Network-and-User-Interaction)' into feature/1752-dns-server-and-client 2023-09-11 15:23:39 +01:00
Chris McCarthy
f19dc9892b #1816 - Fixed tests. Used node and link added number (id) in observation space. 2023-09-11 11:31:03 +01:00
Czar Echavez
5a101d5426 Merge branch 'feature/1816_Database-Service-(Network-and-User-Interaction)' into feature/1752-dns-server-and-client 2023-09-11 09:50:16 +01:00
Chris McCarthy
388176b8bd #1816 - Added full documentation on the database client/server, and the internal frame processing process 2023-09-11 09:30:40 +01:00
Czar Echavez
5cd1e2edf0 Merge branch 'feature/1816_Database-Service-(Network-and-User-Interaction)' into feature/1752-dns-server-and-client 2023-09-11 08:58:13 +01:00
Chris McCarthy
b1d8666c16 #1816 - Added database client. Installed the database client on the Web Server node in the UC2 network. Updated the integration test to query the DB server using the DB client. 2023-09-08 16:50:49 +01:00
Czar Echavez
97a38efc27 Merge branch 'feature/1816_Database-Service-(Network-and-User-Interaction)' into feature/1752-dns-server-and-client 2023-09-08 10:41:03 +01:00
Chris McCarthy
ceac89e778 #1816 - DatabaseService now uses the send function when responding. 2023-09-08 10:15:26 +01:00
Czar Echavez
6f2f23e04f #1752: update changelog 2023-09-07 15:59:46 +01:00
Czar Echavez
47dd23311b #1752: added more functionality to DNS client and server + tests 2023-09-07 15:45:37 +01:00
Chris McCarthy
2f744af34e #1816 - Added the final pieces of the puzzle to get data up from NIC → session manager → software manager → service.
- Implemented a basic sim DB that matches UC2 data manipulation DB in IY.
- Added a test that confirms DB queries can be sent over the network.
2023-09-06 22:26:23 +01:00
Chris McCarthy
6b41bec32a #1816 - Added the final pieces of the puzzle to get data up from NIC → session manager → software manager → service.
- Implemented a basic sim DB that matches UC2 data manipulation DB in IY.
- Added a test that confirms DB queries can be sent over the network.
2023-09-06 22:01:51 +01:00
Czar Echavez
2cb0c238c9 Merge branch 'dev' into feature/1752-dns-server-and-client 2023-09-06 13:42:07 +01:00
Chris McCarthy
65b027bc06 Merge branch 'dev' into feature/1816_Database-Service-(Network-and-User-Interaction) 2023-09-06 13:37:06 +01:00
Marek Wolan
4f89adb19a Start changing to dict instead of string actions. 2023-09-06 12:51:47 +01:00
Czar Echavez
6b9928c9b9 Merged PR 175: Red Service Data Manipulator Bot
## Summary
Implementation of the Data Manipulation Bot. This service sends a SQL query payload to the database server (or a given machine IP and port)

## Test process
Added a test
https://dev.azure.com/ma-dev-uk/PrimAITE/_git/PrimAITE/pullrequest/175?_a=files&path=/tests/unit_tests/_primaite/_simulator/_system/_services/_red_services/test_data_manipulator_service.py

## Checklist
- [x] This PR is linked to a **work item**
- [x] I have performed **self-review** of the code
- [x] I have written **tests** for any new functionality added with this PR
- [ ] I have updated the **documentation** if this PR changes or adds functionality
- [ ] I have written/updated **design docs** if this PR implements new functionality
- [X] I have update the **change log**
- [x] I have run **pre-commit** checks for code style

Related work items: #1814
2023-09-06 11:40:29 +00:00
Chris McCarthy
7c157d27d7 #1800 - Simplified a bunch of stuff in the file system in prep for services and applications. Started adding the database logic. Waiting for the software manager/session manager work from another ticket. 2023-09-06 11:35:41 +01:00
Czar Echavez
597c7664bc #1814: update changelog 2023-09-06 11:19:30 +01:00
Czar Echavez
d503e51c2d #1814: Remove hardcoded values + added test + remove unnecessary private parent attribute 2023-09-06 11:12:03 +01:00
Czar Echavez
c349bb4484 #1814: initial implementation of data manipulator service 2023-09-05 17:14:47 +01:00
Marek Wolan
1dccceaf56 Verify that action tree is starting to work! 2023-09-05 15:53:22 +01:00
Marek Wolan
ffe1e92664 Make actions more recursive 2023-09-05 14:51:25 +01:00
Marek Wolan
2b68ed813c Make actions more recursive 2023-09-05 14:51:04 +01:00
Marek Wolan
0c362da789 Merge remote-tracking branch 'origin/dev' into feature/1812-traverse-actions 2023-09-05 13:20:20 +01:00
Marek Wolan
0493c2062c Merged PR 173: Database service (without networking)
## Summary
- add a database service
- change how `SimComponent` adds actions to allow inheritance of actions
- add service-based actions, like start, stop, pause, and compromise

## Test process
New test cases were added.

## Checklist
- [x] This PR is linked to a **work item**
- [x] I have performed **self-review** of the code
- [x] I have written **tests** for any new functionality added with this PR
- [ ] I have updated the **documentation** if this PR changes or adds functionality
- [ ] I have written/updated **design docs** if this PR implements new functionality
- [ ] I have update the **change log**
- [x] I have run **pre-commit** checks for code style

Related work items: #1801
2023-09-04 19:41:17 +00:00
Chris McCarthy
1385adf3fe Merge remote-tracking branch 'devops/dev' into feature/1801-Database
# Conflicts:
#	src/primaite/simulator/network/container.py
#	src/primaite/simulator/network/hardware/base.py
2023-09-04 19:45:29 +01:00
Christopher McCarthy
0892a976fd Apply suggestions from code review 2023-09-04 18:37:05 +00:00
Christopher McCarthy
c547f12f4e Merged PR 158: Sync with the downstream GitHub repo
DSTL requested some changes to docs.

Related work items: #1711
2023-09-04 18:21:19 +00:00
Christopher McCarthy
482a5fc5e9 Merged PR 174: Router Node
**_*Disclaimer, I used AI to write this PR description for me, you know, for efficiency._**

## Summary
In this pull request, we've made several key enhancements and fixes to improve the routing and network simulation functionalities of our codebase. At the heart of this PR is the introduction of a `Router` class, complete with `ACLRule` and `RouteTableEntry` classes to facilitate easier management of routes and permissions. We've also fixed a lingering issue with the `.ping` functionality, ensuring that it properly checks for replies before returning a boolean value.

To make our `Router` class more inspectable, `.show()` methods have been added which can output information in both plain text and markdown formats. Additionally, we've removed the `gateway` field from the `NIC` class and relocated it to the `Node` class. This move allows each `Node` to have a single default gateway. To further refine the system, we've added `Computer` and `Server` classes, and updated our restructured text formatted docstrings and documentation. Finally, a UC2 network has been added.

Changes have been fully tested to ensure that the existing functionalities remain intact, and new unit tests have been added to verify routing between different subnets. The code has been synced with the dev branch.

## Test process
We've added new unit tests and integration tests to check the routing capabilities when a router is placed between different subnets. These tests specifically focus on the ping functionality to verify that it works as expected after the changes. Existing tests were also run to make sure no existing functionality was broken.

## Checklist
- [X] This PR is linked to a **work item**
- [X] I have performed **self-review** of the code
- [X] I have written **tests** for any new functionality added with this PR
- [X] I have updated the **documentation** if this PR changes or adds functionality
- [X] I have written/updated **design docs** if this PR implements new functionality
- [ ] I have update the **change log**
- [X] I have run **pre-commit** checks for code style

Related work items: #1800
2023-09-04 16:56:41 +00:00
Marek Wolan
289f818266 Apply suggestions from code review 2023-09-04 16:11:47 +00:00
Chris McCarthy
dc9601bf30 Merge remote-tracking branch 'devops/dev' into downstream_github_sync 2023-09-04 16:46:14 +01:00
Chris McCarthy
f3f8d02fcb Merge remote-tracking branch 'github/dev' into downstream_github_sync 2023-09-04 16:45:23 +01:00
Chris McCarthy
596ad20cc6 #1800 - Added better logging and error messages to AccessControlList class. Updated usage of extra following pydantic deprecated warning "pydantic.config.Extra is deprecated, use literal values instead (e.g. extra='allow')" 2023-09-04 16:44:29 +01:00
Chris McCarthy
ccad5ba8a3 #1800 - Ran pre-commit 2023-09-04 16:34:55 +01:00
Chris McCarthy
5981bc7255 Merge remote-tracking branch 'devops/feature/1800_model-a-basic-router-subclass-of-node' into feature/1800_model-a-basic-router-subclass-of-node 2023-09-04 14:58:52 +01:00
Chris McCarthy
3075d1985b #1800 - Renamed all ip fields so that they're post-fixed with ip_address 2023-09-04 14:58:34 +01:00
Christopher McCarthy
d9feb67e02 Apply suggestions from code review 2023-09-04 11:20:40 +00:00
Chris McCarthy
05959e5408 #1800 - Moved the Switch code to a dedicated switch.py module.
- Added more switch tests.
- Updated ACL tests to use router acl.
- Updated more docs.
- Moved the Jupyter notebooks to _package_data and fixed up the setup to move all notebooks to ~/primaite/notebooks/example_notebooks.
2023-09-04 12:14:24 +01:00
Marek Wolan
33b4911cb1 Move actions to pydantic 2023-09-04 10:20:06 +01:00
Chris McCarthy
5111affeeb #1800 - Added more docstrings and rst docs.
- Extended the .show functionality to enable markdown format too.
2023-09-01 16:58:21 +01:00
Marek Wolan
d55fd835c7 Merge remote-tracking branch 'origin/dev' into feature/1801-Database 2023-08-31 14:56:31 +01:00
Marek Wolan
61fa83a00d Fix failing test 2023-08-31 14:55:14 +01:00
Chris McCarthy
89ad22aceb #1800 - Synced with dev.
- Added the UC2 network.
- Added a Computer class.
2023-08-31 13:35:56 +01:00
Chris McCarthy
415ee3b3a7 Merge branch 'dev' into feature/1800_model-a-basic-router-subclass-of-node 2023-08-31 11:39:21 +01:00
Marek Wolan
bd5aacaf0c Remove todo comments 2023-08-31 11:32:11 +01:00
Marek Wolan
f60f775f03 Improve logging 2023-08-31 11:27:52 +01:00
Marek Wolan
7759c178bb Add logging and service restarting 2023-08-31 11:20:16 +01:00
Marek Wolan
3368376596 Merged PR 172: Methods for adding, removing, connecting and disconnecting nodes in the network.
## Summary
- Add public API for adding, removing, connecting and disconnecting nodes in the network.
- Introduce parent of simcomponent to keep track of parent as per this diagram ![Component ownership tree - Page 1 (2).png](https://dev.azure.com/ma-dev-uk/b50a61ee-86c4-48bc-9a0b-a67645ba12ee/_apis/git/repositories/2825053e-bd3b-45b2-8680-1281809eefa2/pullRequests/172/attachments/Component%20ownership%20tree%20-%20Page%201%20%282%29.png)
- Update tutorial notebook with new way of doing things.

## Test process
Unit and integration tests written and passing.

## Checklist
- [x] This PR is linked to a **work item**
- [x] I have performed **self-review** of the code
- [x] I have written **tests** for any new functionality added with this PR
- [x] I have updated the **documentation** if this PR changes or adds functionality
- [ ] I have written/updated **design docs** if this PR implements new functionality
- [ ] I have update the **change log**
- [x] I have run **pre-commit** checks for code style

Related work items: #1798
2023-08-31 10:04:11 +00:00
Chris McCarthy
e73d7f49d6 #1800 - Fixed routing and processing of ICMP packets in the Router class 2023-08-31 11:03:38 +01:00
Marek Wolan
62be66205c Fix unit tests 2023-08-31 10:57:45 +01:00
Chris McCarthy
1bf51c7741 #1800 - Added ACL and routing classes.
- Added .show() methods to new router classes to enable inspection of the components as you would a real router.
- Removed gateway from the NIC and added default_gateway to Node so that Node has a single default gateway.
- Added some routing tests to check that ping can be performed when router between subnets.
2023-08-30 21:38:55 +01:00
Marek Wolan
40d3e04e64 Move init action manager function to the top 2023-08-29 14:33:28 +01:00
Marek Wolan
f0b82cbdfb Add ability to uninstall service 2023-08-29 14:15:49 +01:00
Marek Wolan
9c8b7a7b7a Merge remote-tracking branch 'origin/feature/1789-add-convenience-methods-to-network-object' into feature/1801-Database 2023-08-29 13:22:14 +01:00
Marek Wolan
94325d1fde Add Install method to software. 2023-08-29 13:21:34 +01:00
Marek Wolan
7b61322e70 Add service actions 2023-08-29 12:34:41 +01:00
Marek Wolan
1eff41c786 Update docs based on new action options 2023-08-29 11:10:29 +01:00
Marek Wolan
319e87d200 Make changes to the way actions work 2023-08-28 22:34:20 +01:00
Marek Wolan
6e602aa151 Fix unit tests by removing warning checks 2023-08-25 17:56:05 +01:00
Marek Wolan
ae6e835955 Apply suggestions from code review. 2023-08-25 15:58:07 +01:00
Marek Wolan
a9e969aa13 init work on database 2023-08-25 15:29:53 +01:00
Chris McCarthy
c6f71600fc #1800 - Fixed the ping functionality so that it actually checks for replies and returns True if the right number of replies have been received.
- Added the foundations of a Router class along with ACLRule and RouteTableEntry classes.
2023-08-25 09:07:32 +01:00
Marek Wolan
2dd191bf32 Merge branch 'feature/1789-add-convenience-methods-to-network-object' into feature/1801-Database 2023-08-24 14:41:09 +01:00
Marek Wolan
05bb0f295b Update notebook tutorial on creating a simulation 2023-08-24 13:06:45 +01:00
Marek Wolan
fec44aef53 Rename connect_nodes to connect and fix minor bug 2023-08-24 13:03:16 +01:00
Marek Wolan
78008e3c6e Fix container test 2023-08-24 12:52:38 +01:00
Marek Wolan
7058c7e9a8 Rename networkcontainer to network 2023-08-24 12:41:46 +01:00
Marek Wolan
a818de8f01 Add ability to connect nodes via the network. 2023-08-24 12:40:00 +01:00
Marek Wolan
f38b423886 Update comment 2023-08-24 10:27:30 +01:00
Marek Wolan
4077eb3a5c Add tests for network node adding/removal 2023-08-24 10:26:17 +01:00
Marek Wolan
01e8501bc1 Merged PR 169: Connect all components and add describe_state() methods
## Summary
- Add an object that holds the entire simulation, and a container for the network that keeps track of a list of nodes and links.
- Implement `describe_state()` for all existing sim components and take advantage of the inheritance relationships to avoid repetition.
- Fix some minor mistakes like typehints and indentation errors.
- Write a jupyter notebook which uses the python API to create a simulation and verify that it's `describe_state()` method outputs a correct value.
- Currently the notebook creates the simulation in a janky way, because the API for simulation creation is not fleshed out yet. Further tickets have been added to the backlog to address some of these shortcomings. They are:
  - #1790

## Test process
I have tested that the notebook runs and that after populating a simulation, the describe_state function returns a dictionary full of only serialisable data types.

## Checklist
- [y] This PR is linked to a **work item**
- [y] I have performed **self-review** of the code
- [~] I have written **tests** for any new functionality added with this PR
- [n] I have updated the **documentation** if this PR changes or adds functionality
- [na] I have written/updated **design docs** if this PR implements new functionality
- [y] I have update the **change log**
- [y] I have run **pre-commit** checks for code style

Note:
This ticket also makes a small amount of progress against: #1705, it adds a shell of a network class, but only by creating the class, not implementing any functionality.

Related work items: #1787
2023-08-23 15:24:17 +00:00
Marek Wolan
a82ffb9747 Add notebook outputs back into src control 2023-08-23 15:44:23 +01:00
Marek Wolan
72b019287a Add scratch notebook to gitignore. 2023-08-23 14:41:59 +01:00
Marek Wolan
1613bbe27a Add methods for adding/removing nodes form network 2023-08-23 14:41:30 +01:00
SunilSamra
c1ba3b0850 #1752 - Added comments to ticket 2023-08-22 21:43:57 +01:00
SunilSamra
550b62f75d #1752 - Removed unnecessary print statement
- Changed docstring on function check_domain_in_cache
2023-08-21 16:09:17 +01:00
SunilSamra
1a13af2f5e #1752 - Changed DNSReply and DNSResponse to have 1 parameter only 2023-08-21 14:11:53 +01:00
Marek Wolan
7e64acd368 Update container docstrings 2023-08-21 10:04:23 +01:00
Marek Wolan
07b740a81e Update docs and changelog. 2023-08-21 09:49:31 +01:00
SunilSamra
a0b258a597 #1752 - Added a dns_lookup function to dns_server.py 2023-08-21 09:02:04 +01:00
Marek Wolan
7c16a9cdde Update notebook 2023-08-20 18:43:21 +01:00
Marek Wolan
3911010777 update notebook 2023-08-20 18:42:58 +01:00
Marek Wolan
01c912c094 fix type hints and describe state functions 2023-08-20 18:38:02 +01:00
Marek Wolan
6ca53803cd Describe state 2023-08-17 15:32:12 +01:00
SunilSamra
2919be3796 #1752 - Added web_browser.py application for DNS modelling 2023-08-17 14:20:09 +01:00
Marek Wolan
ced45d4275 Connect actions of top-level sim components 2023-08-16 16:45:52 +01:00
SunilSamra
72cd9fd8e2 #1752 - Created dns.py protocol file with DNSPacket and DNSRequest and DNSReply packets
- Added reset_component logic for dns_server.py and dns_client.py
2023-08-16 13:00:16 +01:00
SunilSamra
76d404dc2f #1752 - Added dns_client.py and dns_server.py service files
- Added new get_install method to software.py
2023-08-15 13:56:38 +01:00
Chris McCarthy
18f57d6418 Added PrimAITE_logo_transparent.png file 2023-08-15 13:56:06 +01:00
Chris McCarthy
58048cd0e1 Dropped sphinx-pipeline 2023-08-15 13:28:02 +01:00
ARCD
eb70acf0c6 Create spinx-pipeline 2023-08-15 13:23:25 +01:00
Chris McCarthy
1a1c3c9344 Added sphinx docs build pipeline for GitHub pages on release 2023-08-15 11:26:15 +01:00
Chris McCarthy
01fb9e65fe Added the DSTL MIT license and updated the license in pyproject.toml 2023-08-15 11:14:23 +01:00
Czar Echavez
d972fcc07e Merged PR 164: File System Class setup fixing tests
## Summary
Attempting to fix a test which seems to be broken when integrated with https://dev.azure.com/ma-dev-uk/PrimAITE/_git/PrimAITE/pullrequest/160

## Test process
*How have you tested this (if applicable)?*

## Checklist
- [x] This PR is linked to a **work item**
- [x] I have performed **self-review** of the code
- [x] I have written **tests** for any new functionality added with this PR
- [ ] I have updated the **documentation** if this PR changes or adds functionality
- [ ] I have written/updated **design docs** if this PR implements new functionality.
- [x] I have run **pre-commit** checks for code style

#1714: fixing minor error in test + adding a check for existing uuid when adding file

Related work items: #1714
2023-08-14 08:27:09 +00:00
Czar Echavez
c4aacb8c69 #1714: Change file and folder uuid checking to check for file or folder names already existing 2023-08-11 15:33:07 +01:00
Christopher McCarthy
1b84d28c48 Merged PR 161: Working base Node class
## Summary
- Network Hardware - Added base hardware module with NIC, SwitchPort, Node, Switch, and Link. Nodes and Switches have
fundamental services like ARP, ICMP, and PCAP running them by default.
- Network Transmission - Modelled OSI Model layers 1 through to 5 with various classes for creating network frames and
transmitting them from a Service/Application, down through the layers, over the wire, and back up through the layers to
a Service/Application another machine.
- system - Added the core structure of Application, Services, and Components. Also added a SoftwareManager and
SessionManager.

- #1706 - Got the core Node class build and working with ARP and the ability to ping another node. Added some basic tests in. Next job is to create the Node subclasses. Then move ARP and ICMP into a ser
- #1706 - Added some extra logging
- #1706 - Started adding the core node software required by all nodes. Made some tweaks to the Frame to have send and receive timestamp.
- #1706 - Got the code services, application, and process base classes stubbed out. Need them now so that I can leverage them for core node services required.
- #1706 - Tidied up the SysLog ARPCache, and ICMP classes and integrated them into the Node. Tidied up the base implementation of SoftwareManager and SessionManager. Tidies up the public API for Service

## Test process
Tests really asses how components fit together and that it all does work. They tests don't yet check that things like ICMP work, as in the ping is received and responded to.

## Checklist
- [X] This PR is linked to a **work item**
- [X] I have performed **self-review** of the code
- [X] I have written **tests** for any new functionality added with this PR
- [X] I have updated the **documentation** if this PR changes or adds functionality
- [X] I have written/updated **design docs** if this PR implements new functionality.
- [X] I have run **pre-commit** checks for code style

Related work items: #1706
2023-08-10 14:30:04 +00:00
Chris McCarthy
49f855c320 #1706 - Synced with Dev 2023-08-10 13:33:32 +01:00
Chris McCarthy
b902d945ee Merge remote-tracking branch 'devops/dev' into feature/1706_node_class_and_node_type_subclasses
# Conflicts:
#	CHANGELOG.md
#	src/primaite/simulator/core.py
2023-08-10 13:29:14 +01:00
Chris McCarthy
9ee0ef2fd6 #1706 - Applied some final changes from PR. Fixed the PCAP log name on SwitchPort so that a pcap file is generated for each port. 2023-08-10 13:26:51 +01:00
Marek Wolan
586f210402 Merged PR 160: Permission system, account skeleton, and group skeleton
## Summary
This PR implements an outline of accounts and domain controller. However, the main contribution is the permissions system and the changes to `SimComponent`. The domain skeleton will probably change after the node/folder/file/app/service classes exist.

The big idea of the permissions is that the simulator itself is built in a way that permits everything, i.e. the methods of each component that make something happen don't have any permissions checking. Therefore, if you can use primaite without any agents and you will essentially have superadmin, any action you perform will go through. The permissions come into play when you try to interact with the components via the actions. Every action has a configurable permission validator attached to it that will either allow or block the action.

For this reason, I've had to modify the way actions work. To keep everything neatly contained, there is a new Action class that holds a reference to both the action function itself but also to a permission validation function.

## Test process
Unit tests and integration tests.
I will write the design documentation for permissions and update the design for SimComponent once others are happy that the design makes sense.

## Checklist
- [x] This PR is linked to a **work item**
- [x] I have performed **self-review** of the code
- [x] I have written **tests** for any new functionality added with this PR
- [x] I have updated the **documentation** if this PR changes or adds functionality
- [x] I have updated the **changelog**
- [ ] I have written/updated **design docs** if this PR implements new functionality
- [x] I have run **pre-commit** checks for code style

Related work items: #1716
2023-08-10 12:07:38 +00:00
Marek Wolan
e24d4b8890 Fix typo in test 2023-08-10 09:14:45 +01:00
Chris McCarthy
ad81a81949 #1706 - Applied some code suggestions from the PR 2023-08-09 20:38:45 +01:00
Chris McCarthy
b46057841d #1706 - Refactored a bunch of if statements in base.py to improve readability 2023-08-09 20:31:42 +01:00
Marek Wolan
34ff9abd7a Apply changes from code review. 2023-08-09 15:55:28 +01:00
Czar Echavez
cf241366dc #1714: apply suggestions for preventing addition of objects with similar uuid 2023-08-09 15:15:45 +01:00
Marek Wolan
f198a8b94d Fix bad merge 2023-08-09 12:36:09 +01:00
Marek Wolan
51baabb35b Update enums to uppercase in docs 2023-08-09 12:34:56 +01:00
Marek Wolan
596bbaacde Change enum strings to uppercase 2023-08-09 12:06:06 +01:00
Czar Echavez
572f457231 #1714: fixing minor error in test + adding a check for existing uuid when adding file 2023-08-09 11:19:58 +01:00
Marek Wolan
be8c2955ce Change Accountstatus to a bool 2023-08-09 10:26:52 +01:00
Marek Wolan
1de8e0a058 Update tests 2023-08-09 09:19:11 +01:00
Marek Wolan
a3c2ae6c7d Merge dev into feature/1716-accounts-and-groups 2023-08-09 09:18:06 +01:00
Chris McCarthy
a840159460 #1706 - Fixed the "smart" merging of SimComponent that PyCharm performed. Integrated the Filesystem class into the Node. Added prettytable to deps in pyproject.toml 2023-08-08 20:30:37 +01:00
Chris McCarthy
9fbc3c91f7 #1706 - Finished up the Node and Switch MVP. Added full extensive documentation on what's happening at each step. 2023-08-08 20:22:18 +01:00
Chris McCarthy
4e4c2b501a Merge remote-tracking branch 'devops/dev' into feature/1706_node_class_and_node_type_subclasses
# Conflicts:
#	tests/unit_tests/_primaite/_simulator/test_core.py
2023-08-08 20:05:11 +01:00
Czar Echavez
5f097b7c1b Merged PR 157: File System Class setup
## Summary
Skeleton of the FileSystem for the simulation. Does not have all the requirements for the FileSystem yet, since we need to start somewhere

## Test process
Created unit tests for:
- [FileSystem](https://dev.azure.com/ma-dev-uk/PrimAITE/_git/PrimAITE/pullrequest/157?_a=files&path=/tests/unit_tests/_primaite/_simulator/_file_system/test_file_system.py)
- [FileSystemFolder](https://dev.azure.com/ma-dev-uk/PrimAITE/_git/PrimAITE/pullrequest/157?_a=files&path=/tests/unit_tests/_primaite/_simulator/_file_system/test_file_system_folder.py)
- [FileSystemFile](https://dev.azure.com/ma-dev-uk/PrimAITE/_git/PrimAITE/pullrequest/157?_a=files&path=/tests/unit_tests/_primaite/_simulator/_file_system/test_file_system_file.py)

## Design document
https://dev.azure.com/ma-dev-uk/PrimAITE/_wiki/wikis/PrimAITE.wiki/151/FileSystem

## Checklist
- [x] This PR is linked to a **work item**
- [x] I have performed **self-review** of the code
- [x] I have written **tests** for any new functionality added with this PR
- [ ] I have updated the **documentation** if this PR changes or adds functionality
- [x] I have written/updated **design docs** if this PR implements new functionality.
- [x] I have run **pre-commit** checks for code style

Related work items: #1714
2023-08-08 09:29:46 +00:00
Czar Echavez
2f27e02877 #1714: fix precommit 2023-08-08 09:53:32 +01:00
Czar Echavez
c2b783c858 Apply suggestions from code review 2023-08-08 08:17:40 +00:00
Czar Echavez
f854404ba0 #1714: added file system to changelog 2023-08-08 08:41:50 +01:00
Czar Echavez
c8ee409b3b #1714: run precommit 2023-08-08 08:29:51 +01:00
Chris McCarthy
139d739732 #1706 - Tidies up the sysLog ARPCache, and ICMP classes and integrated them into the Node. Tidied up the base implementation of SoftwareManager and SessionManager. Tidies up the public API for Services and Applications. Added the SwitchPort and Switch classes. Added a basic test in test_frame_transmission.py that tests sending a frame from one node to another across a multi-switch network. 2023-08-07 19:33:52 +01:00
Marek Wolan
7eb0bb428f Update code based on PR comments. 2023-08-07 17:24:14 +01:00
Czar Echavez
700950b856 Apply suggestions from code review 2023-08-07 15:38:15 +00:00
Czar Echavez
a4c193cd34 #1714: apply recommended changes with removing get methods and using the properties directly 2023-08-07 16:20:55 +01:00
Czar Echavez
554619e4b4 #1714: conver file and folder lists to dicts + fixing and adding a few more tests 2023-08-07 14:49:59 +01:00
Czar Echavez
b58a3a3e24 #1714: FileSystemItem is no longer an abstract base class + Added enums and enum sizes + stream lined FileSystemFile init 2023-08-07 11:52:54 +01:00
Marek Wolan
22afdc9134 Updated pull_request_template.md 2023-08-07 10:19:06 +00:00
Marek Wolan
84b6e2206e Updated CHANGELOG.md 2023-08-07 10:18:27 +00:00
Marek Wolan
f0d7e03fd7 Add docs and tests 2023-08-07 10:55:29 +01:00
Czar Echavez
d57c2a936e #1714: remove duplicate method 2023-08-07 10:10:05 +01:00
Czar Echavez
028211d288 #1714: update to use objects instead of uuids + tests 2023-08-07 09:34:59 +01:00
Marek Wolan
ac9b83cc42 Merge remote-tracking branch 'origin/dev' into feature/1716-accounts-and-groups 2023-08-07 09:15:35 +01:00
Czar Echavez
46c70ac084 #1714: refactor private attributes and made them public + serialisation tests 2023-08-03 22:20:14 +01:00
Chris McCarthy
04f1cb0dc6 #1706 - Got the code services, application, and process base classes stubbed out. Need them now so that I can leverage them for core node services required. 2023-08-03 21:30:13 +01:00
Marek Wolan
2a680c1e48 Test my validators 2023-08-03 16:26:33 +01:00
Chris McCarthy
e7e39a8c1d Merge branch 'github_dev' into downstream_github_sync
# Conflicts:
#	docs/index.rst
#	docs/source/primaite_session.rst
2023-08-03 16:07:15 +01:00
Chris McCarthy
fed65db7fc Updated the What is PrimAITE? section in index.rst. Dropped the use of sphinx-code-tabs in the docs as building the docs in pdf (make latexpdf) is suddenly complaining about the tab buttons. 2023-08-03 16:04:23 +01:00
Chris McCarthy
cac4779244 #1706 - Started adding the core node software required by all nodes. Made some tweaks to the Frame to have send and receive timestamp. 2023-08-03 14:37:55 +01:00
Marek Wolan
94617c57a4 Make register and deregister acct private 2023-08-03 13:24:27 +01:00
Marek Wolan
3a2840bed8 Overhaul sim component for permission management. 2023-08-03 13:09:04 +01:00
Czar Echavez
b08683fcd3 #1714: fix tests 2023-08-03 12:42:16 +01:00
Czar Echavez
483fa7d841 Merge branch 'dev' into feature/1714-file-system-file-system-folder-and-file-system-file-class-skeletons 2023-08-03 12:15:08 +01:00
Czar Echavez
a0356a7fbc #1714: updated file system classes 2023-08-03 12:14:11 +01:00
Chris McCarthy
209f934abd #1706 - Added some extra logging 2023-08-02 22:01:15 +01:00
Chris McCarthy
897dbdf10c #1706 - Got the core Node class build and working with ARP and the ability to ping another node. Added some basic tests in. Next job is to create the Node subclasses. Then move ARP and ICMP into a service that is used by all nodes. 2023-08-02 21:54:21 +01:00
Christopher McCarthy
3660e27c15 Merged PR 156: Model a minimal implementation of a network Frame
## Summary
- Added the primaite/simulator/network/transmission sub-package with modules for each layer. They come together to build a minimal but fairly realistic network Frame.
- A custom PrimaiteHeader has been included to hold primaite specific metadata required in transmission for reward function and RL agent downstream.
- Added some basic tests that check the proper configuration of Frames with matching headers for protocols.
- Updated the frame typehints in NIC and Link classes.
- Added documentation for the transport layer down to data link layer

## Test process
Unit tests check the frame has been configured correctly with the right headers for the right protocol.

## Checklist
- [X] This PR is linked to a **work item**
- [X] I have performed **self-review** of the code
- [X] I have written **tests** for any new functionality added with this PR
- [X] I have updated the **documentation** if this PR changes or adds functionality
- [X] I have written/updated **design docs** if this PR implements new functionality.
- [X] I have run **pre-commit** checks for code style

Related work items: #1724
2023-08-02 14:25:58 +00:00
Marek Wolan
091b4a801d Make some progress on accounts 2023-08-02 13:43:31 +01:00
Chris McCarthy
95f5515d69 #1724 - Added documentation for the transport layer down to data link layer 2023-08-02 12:12:08 +01:00
Chris McCarthy
9d17a9b0d3 #1724 - Added the primaite/simulator/network/transmission sub-package with modules for each layer. They come together to build a minimal but fairly realistic network Frame. A custom PrimaiteHeader has been included to hold primaite specific metadata required in transmission for reward function and RL agent downstream. Added some basic tests that check the proper configuration of Frames with matching headers for protocols. Updated the frame typehints in NIC and Link classes. 2023-08-01 22:25:00 +01:00
Czar Echavez
841aafd259 Merge branch 'dev' into feature/1714-file-system-file-system-folder-and-file-system-file-class-skeletons 2023-08-01 16:20:08 +01:00
Czar Echavez
ea8c65a17e #1714: set up files 2023-08-01 16:18:49 +01:00
Christopher McCarthy
f41fc241b7 Merged PR 152: Model Link and NIC
## Summary
- #1715 #1715 - Added Link class in physical_layer.py.- Also added NIC class in physical_layer.py for
#1672. Added attributes and public API functions.
- Added test_physical_layer.py with some basic tests ready to house the tests once logic has been implemented.
- Made use of the pydantic model_post_init function for proper ipv4 configuration checking.
- Added NetworkError to exceptions.py.
- Added timestep int as a param to the apply_timestep function in core.py. Also added a reset_component_for_episode function.
- Updated docs with details of Link and NIC.

## Test process
- Added basic unit tests for instantiation that look at proper config and error raising.
- Added an integration test for linking NICs to Link.

## Checklist
- [ ] This PR is linked to a **work item**
- [ ] I have performed **self-review** of the code
- [ ] I have written **tests** for any new functionality added with this PR
- [ ] I have updated the **documentation** if this PR changes or adds functionality
- [ ] I have run **pre-commit** checks for code style

Related work items: #1672, #1715
2023-08-01 12:31:42 +00:00
Marek Wolan
dda986fc56 Merge remote-tracking branch 'origin/dev' into feature/1716-accounts-and-groups 2023-08-01 12:52:17 +01:00
Chris McCarthy
0f33b837aa #1715 - Fixed up pr code suggestion flake8 issues 2023-08-01 12:45:36 +01:00
Christopher McCarthy
5ee3eff0e9 Apply suggestions from code review 2023-08-01 11:14:36 +00:00
Christopher McCarthy
2769b1bfb1 Apply suggestions from code review 2023-08-01 11:04:16 +00:00
Chris McCarthy
8785089a1c #1715 - Moved IPv4Address conversions to the NIC init. Mak wake_on_lan not optional. Ignored ANN002 and ANN003 in .flake8 so we don't get silly 'ANN002 Missing type annotation for *args' and 'ANN003 Missing type annotation for **kwargs' flake8 failures 2023-08-01 10:32:16 +01:00
Marek Wolan
5ebbfab0ff Create some files for domain sim 2023-08-01 10:02:13 +01:00
Chris McCarthy
557caeaac4 #1715 - Added suppress-none-returning and suppress-dummy-args to .flake8 as flake8-annotations can get very annoying 2023-08-01 08:19:28 +01:00
Chris McCarthy
c05cb62aa9 Merge branch 'dev' into feature/1715_model_link 2023-08-01 08:12:39 +01:00
Marek Wolan
0f0c61642c Merged PR 151: Check type hints with pre-commit
## Summary
Added `flake8-annotations` to the pre-commit hooks. This ensures that we all write type hints for all new code.

There's also a minor unrelated addition to the pre-commit template.

## Test process
I tried adding a function with a parameter but no typehint. Git did not allow me to commit this.

## Checklist
- [x] This PR is linked to a **work item**
- [x] I have performed **self-review** of the code
- [x] I have written **tests** for any new functionality added with this PR
- [x] I have updated the **documentation** if this PR changes or adds functionality
- [x] I have run **pre-commit** checks for code style

Related work items: #1721
2023-07-31 19:34:48 +00:00
Chris McCarthy
e4b6f266e8 #1715 - Added timestep int as a param to the apply_timestep function in core.py. Also added a reset_component_for_episode function. Updated docs with details of Link and NIC. 2023-07-31 20:05:36 +01:00
Marek Wolan
3324a8caae Apply suggestions from code review 2023-07-31 18:54:29 +00:00
Marek Wolan
c1bb6d8b7f Update the PR template 2023-07-31 17:09:38 +01:00
Marek Wolan
9cf5bfa1b2 Fix typehint issues 2023-07-31 17:07:56 +01:00
Marek Wolan
0a079832e9 Add self,cls to flake8-ann ignore list 2023-07-31 17:00:28 +01:00
Chris McCarthy
0532db960a #1715 - Added more tests. MAde use of the pydantic model_post_init function for proper ipv4 cofiguration checking. Added NetworkError to exceptions.py. 2023-07-31 16:55:45 +01:00
Marek Wolan
c4adc2f543 add flake8-annotations to pre-commits 2023-07-31 16:47:13 +01:00
Chris McCarthy
59394c3642 #1715 - Added Link class in physical_layer.py. Also added NIC class in physical_layer.py for #1672. Added attributes and public API functions. test_physical_layer.py ready to house the tests once logic has been implemented. 2023-07-31 15:55:22 +01:00
Marek Wolan
020682f546 Merged PR 149: Base class for Simulation Components
## Summary
This introduces a base class for all simulation components. The idea behind this is to formalise the way in which data is extracted from the simulator and the way actions are applied to the different aspects of the simulator.

The intention is that any class that simulates something will inherit from SimComponent (which inherits from pydantic BaseModel).

Actions enter the simulator as a list of strings that is intended to be peeled back as you go down the layers of the simulation. For example we could have an action of `["network", "nodes", "node3", "network_interface_card", "disable"]` This list is passed to the `apply_action()` function of the overall simulation controller. The simulation controller looks at the first word on the list, `network` and uses this to select a method that can apply the function. It passes the remainder of the list as an argument to that function. In this case it will be `["nodes", "node3", "network_interface_card", "disable"]`.

To the reviewers, please validate that you're happy with the implicit design choices I've made while implementing this. Especially the contract passing actions down the components tree.

(also I changed some mentions of agent to agent_abc in the docs as it was complaining and refusing to build.)

## Test process
I have written basic unit tests to check that the custom functionality added to SimComponent doesn't interfere with basic pydantic functionality.
I also started doc pages that explains these concepts to potential developers, although once there are subclasses of this core class, it will be easier to populate the docs with concrete examples.

## Checklist
- [x] This PR is linked to a **work item**
- [x] I have performed **self-review** of the code
- [x] I have written **tests** for any new functionality added with this PR
- [x] I have updated the **documentation** if this PR changes or adds functionality
- [x] I have run **pre-commit** checks for code style
- [x] I have **type hinted** all the code I changed.

Related work items: #1709
2023-07-31 12:43:07 +00:00
Marek Wolan
954026d3e0 Comment out RLLib support 2023-07-31 12:13:52 +01:00
Marek Wolan
a486780fba Add timestep function 2023-07-31 11:39:33 +01:00
Marek Wolan
fa2cdf853c Drop Ray 2023-07-31 11:27:16 +01:00
Marek Wolan
8e2ef1b695 Apply suggestions from code review 2023-07-31 10:25:29 +00:00
jamesshort1
80ddf511dc Update README.md 2023-07-31 09:17:48 +01:00
jamesshort1
61fe8c2031 Update README.md 2023-07-31 09:16:24 +01:00
Christopher McCarthy
fd28475e83 Merged PR 148: 1711 Fix legacy config loading issues
## Summary
Added the ability to load legacy lay down config files. Added extensive unit testing and end-to-end testing. Also added the ability to set exactly how many num_train_steps, num_eval_steps, num_train_episodes, and num_eval_episode and used when converting a legacy training config.

## Test process
Full unit test and end-to-end test

## Checklist
- [X] This PR is linked to a **work item**
- [X] I have performed **self-review** of the code
- [X] I have written **tests** for any new functionality added with this PR
- [ ] I have updated the **documentation** if this PR changes or adds functionality
- [X] I have run **pre-commit** checks for code style

Related work items: #1711
2023-07-28 14:45:58 +00:00
Marek Wolan
3b4a01760b Rework apply_actions to make it more standard 2023-07-28 15:14:43 +01:00
Marek Wolan
c1bcc372b1 Merge remote-tracking branch 'origin/dev' into feature/1709-base-simulation-class 2023-07-28 14:49:56 +01:00
Marek Wolan
b129c4fc97 Add SimComponent core class 2023-07-28 14:49:21 +01:00
Chris McCarthy
0f8d31c72c #1711 - Last minute docs changes 2023-07-28 14:41:39 +01:00
Chris McCarthy
77e7941510 #1711 - Last minute docs changes 2023-07-28 14:39:01 +01:00
Chris McCarthy
e8349a8ca3 Merge branch 'github_dev' into bugfix/1711_Fix_legacy_config_loading_issues 2023-07-28 14:13:37 +01:00
Chris McCarthy
bb8b41a5ec #1711 - Removed the legacy bools from the RLlibAgent constructor in primaite_session.py 2023-07-28 14:02:17 +01:00
Chris McCarthy
0fb9268f44 #1711 - Fully Integrated the legacy training config and lay down config options into the CLI, run PrimaiteSession, and Agent classes. Made the ese test in test_full_legacy_config_session.py use this new integrated option to read the legacy file. 2023-07-28 13:49:26 +01:00
Chris McCarthy
c276281a64 Merge branch 'github_dev' into bugfix/1711_Fix_legacy_config_loading_issues 2023-07-28 12:55:58 +01:00
Chris McCarthy
baed7445c9 Merge remote-tracking branch 'github/dev' into github_dev 2023-07-28 12:54:58 +01:00
Chris McCarthy
7c843d3caa #1711 - Added the ability to load legacy lay down config files. Added extensive unit testing and end-to-end testing. Also added the ability to set exactly how many num_train_steps, num_eval_steps, num_train_episodes, and num_eval_episode and used when converting a legacy training config. 2023-07-28 12:53:49 +01:00
jamesshort1
e62846255f Update README.md 2023-07-28 09:41:29 +01:00
jamesshort1
546c66c542 Update README.md 2023-07-28 09:40:05 +01:00
jamesshort1
74e3dabae9 Update README.md 2023-07-28 09:39:05 +01:00
Christopher McCarthy
2642cc97de Merged PR 146: Final sync with github v2.0.0 release 2023-07-27 16:24:17 +00:00
Chris McCarthy
3f34c76b3c Merge branch 'github_dev' into release/2.0.0 2023-07-27 17:22:17 +01:00
jamesshort1
378001ff68 Update README.md 2023-07-27 14:57:08 +01:00
Chris McCarthy
92671796a1 Added GFX license conditions. Included LICENSE file in build. Fixed a few character issues in README.md 2023-07-27 11:40:29 +01:00
Chris McCarthy
858396f3d6 Dropped MIT license until public release 2023-07-27 11:03:25 +01:00
jamesshort1
fde033b387 Update README.md 2023-07-27 08:59:43 +01:00
jamesshort1
bd30bab096 Update README.md 2023-07-27 08:59:24 +01:00
Christopher McCarthy
4baff171af Merged PR 144: v2.0.0 GitHub release sync
v2.0.0 GitHub release sync

Related work items: #901, #1523, #1574, #1594, #1595, #1597, #1623, #1626, #1629, #1631, #1632, #1635, #1637, #1638, #1639, #1640, #1641, #1647, #1648, #1650
2023-07-27 07:46:59 +00:00
Chris McCarthy
31e2af6db1 Merge branch 'github_dev' into release/2.0.0 2023-07-27 08:43:33 +01:00
Chris McCarthy
c5a23fa035 Added run section with primaite session command in the README.md 2023-07-26 22:10:59 +01:00
Chris McCarthy
6cf18e7808 Merge branch 'github_dev' into release/2.0.0 2023-07-26 22:08:19 +01:00
Chris McCarthy
472e85cffb Added additional install instructions to the README.md 2023-07-26 21:49:36 +01:00
Chris McCarthy
fce4e78933 Synced with the github repo release 2023-07-26 21:40:30 +01:00
Chris McCarthy
499219eb40 Added project urls to pyproject.toml and a setup.cfg file for PyPi to pickup author and url 2023-07-26 21:11:15 +01:00
Chris McCarthy
efbb6ef8df Added a CONTRIBUTING.md and added a URL to the Yawning-Titan reference in index.rst 2023-07-26 20:17:29 +01:00
Chris McCarthy
1c4695d391 Dropped the ADF build files and updated the package name install step in python-package.yml. Added bug_report.md and feature_request.md files for GitHub 2023-07-26 20:05:44 +01:00
Chris McCarthy
5c5528bb94 Updated the README.md with developer install specific instructions 2023-07-26 19:49:24 +01:00
Chris McCarthy
1c35b109b1 Merge remote-tracking branch 'devops/main' into github_dev 2023-07-26 19:43:46 +01:00
Chris McCarthy
c6cbb5ae8d Create python-package.yml CI pipeline 2023-07-26 19:38:28 +01:00
Christopher McCarthy
1f7677270b Merged PR 143: v2.0.0
v2.0.0
2023-07-26 18:21:18 +00:00
Christopher McCarthy
db9aa3cdf0 Merged PR 142: v2.0.0
v2.0.0

Related work items: #901, #1523, #1574, #1594, #1595, #1597, #1623, #1626, #1629, #1631, #1632, #1635, #1637, #1638, #1639, #1640, #1641, #1647, #1648, #1650
2023-07-26 18:20:28 +00:00
Chris McCarthy
46b3ab0959 Ran final v2.0.0 benchmark and dropped the release candidate benchmarks 2023-07-26 18:19:11 +01:00
Chris McCarthy
38f851ab66 Bumped version to 2.0.0 2023-07-26 14:38:57 +01:00
Christopher McCarthy
9377553a22 Merged PR 139: Re-run the benchmarks for v2.0.0rc1 and v2.0.0rc2 using the same config file....
## Summary
Re-run the benchmarks for v2.0.0rc1 and v2.0.0rc2 using the same config file. As expected, the versions perform almost identically as there's no real logic changes that would affect the agent between the two release candidates

## Checklist
- [X] This PR is linked to a **work item**
- [X] I have performed **self-review** of the code
- [ ] I have written **tests** for any new functionality added with this PR
- [ ] I have updated the **documentation** if this PR changes or adds functionality
- [X] I have run **pre-commit** checks for code style

Related work items: #1574
2023-07-25 09:33:32 +00:00
Chris McCarthy
e5983d7d0e Merge remote-tracking branch 'origin/dev' into release/2.0.0rc1
# Conflicts:
#	.gitignore
#	benchmark/results/PrimAITE Versions Learning Benchmark.png
#	benchmark/results/v2.0.0rc1/PrimAITE v2.0.0rc1 Learning Benchmark.pdf
#	benchmark/results/v2.0.0rc1/PrimAITE v2.0.0rc1 Learning Benchmark.png
#	benchmark/results/v2.0.0rc1/v2.0.0rc1_benchmark_metadata.json
2023-07-24 22:50:34 +01:00
Chris McCarthy
b6c2120f22 RE-ran the benchmarks for v2.0.0rc1 and v2.0.0rc2 using the same config file. As expected, the versions perform almost identically as there's no real logic changes that would affect the agent between the two release candidates 2023-07-24 22:43:22 +01:00
Christopher McCarthy
19643287af Merged PR 137: #1650 - Turned on the test. Also updated some references to the old primaite...
## Summary
- Turned on the test. Also updated some references to the old primaite paths. Finally, pushed the deployment status classifier to Development Status :: 5 - Production/Stable

## Test process
Yes, turned on the test.

## Checklist
- [ ] This PR is linked to a **work item**
- [ ] I have performed **self-review** of the code
- [ ] I have written **tests** for any new functionality added with this PR
- [ ] I have updated the **documentation** if this PR changes or adds functionality
- [ ] I have run **pre-commit** checks for code style

#1650 - Turned on the test. Also updated some references to the old primaite paths. Finally, pushed the deployment status classifier to Development Status :: 5 - Production/Stable

Related work items: #1650
2023-07-24 11:11:17 +00:00
Chris McCarthy
1131663cde #1650 - Removed the commented out pytest.mark.skip statement now that the test does work. 2023-07-24 09:20:36 +01:00
Chris McCarthy
66d367aa94 #1650 - Turned on the test. Also updated some references to the old primaite paths. Finally, pushed the deployment status classifier to Development Status :: 5 - Production/Stable 2023-07-21 16:49:17 +01:00
Christopher McCarthy
b92145cfc7 Merged PR 135: #1648 - Updated file headers
## Summary
 - Updated file header from 'Crown Owned Copyright (C) Dstl 2023. DEFCON 703. Shared in confidence.' to '© Crown-owned copyright 2023, Defence Science and Technology Laboratory UK'

## Checklist
- [ ] This PR is linked to a **work item**
- [ ] I have performed **self-review** of the code
- [ ] I have written **tests** for any new functionality added with this PR
- [ ] I have updated the **documentation** if this PR changes or adds functionality
- [ ] I have run **pre-commit** checks for code style

#1648 - Updated file header from 'Crown Owned Copyright (C) Dstl 2023. DEFCON 703. Shared in confidence.' to '© Crown-owned copyright 2023, Defence Science and Technology Laboratory UK'

Related work items: #1648
2023-07-21 14:08:09 +00:00
Chris McCarthy
1c6ceaa95b #1648 - Reverted benchmark sessions and episodes numbers 2023-07-21 15:07:21 +01:00
Chris McCarthy
4bb4850681 #1648 - Added header to benchmark files 2023-07-21 15:06:05 +01:00
Chris McCarthy
b9ae82310c #1648 - Reverted the benchmark files 2023-07-21 15:01:51 +01:00
Chris McCarthy
1dc23e11f2 #1648 - Updated file header from 'Crown Owned Copyright (C) Dstl 2023. DEFCON 703. Shared in confidence.' to '© Crown-owned copyright 2023, Defence Science and Technology Laboratory UK' 2023-07-21 14:54:09 +01:00
Christopher McCarthy
2bccfc8df8 Merged PR 134: PrimAITE app and user dirs are version specific
## Summary
- Added _PrimaitePaths class that manages all the primaite locations using PlayformDirs. This class now creates new primaite locations for each version of primaite.
- Rolled the _PrimaitePaths class out throughout the code base.
- Updated the docs to reference the new version paths.
- Updated the author from qinetiq to dstl
- Bumped version number to 2.0.0rc2

## Test process
- Manual checks. Tough to test the install paths.

## Checklist
- [ ] This PR is linked to a **work item**
- [ ] I have performed **self-review** of the code
- [ ] I have written **tests** for any new functionality added with this PR
- [ ] I have updated the **documentation** if this PR changes or adds functionality
- [ ] I have run **pre-commit** checks for code style

Related work items: #1647
2023-07-21 13:50:56 +00:00
Chris McCarthy
92eae6c7d7 Merge branch 'dev' into feature/1647_Append_version_number_to_the_primaite_root_dir 2023-07-21 14:01:45 +01:00
Chris McCarthy
534c066170 #1647 - Added _PrimaitePaths class that manages all the primaite locations using PlayformDirs. This class now creates new primaite locations for each version of primaite.
- Rolled the _PrimaitePaths class out throughout the code base.
- Updated the docs to reference the new version paths.
- Updated the author from qinetiq to dstl
- Bumped version number to 2.0.0rc2
2023-07-21 14:00:50 +01:00
Czar Echavez
034ea831c3 Merged PR 130: #1595: load session double run
## Summary
- Fixed the bug where session gets run twice when loading a session via CLI
- Added a test for the CLI run - xskipped while the bugfix for load session acting odd is tbd
- Fixed a minor bug in PrimAITE session where session_path is overwritten

## Test process
Added a new test for CLI, but xskipped while a different bug is tbd

Ran it locally and no longer runs another session after the loaded session
```
(venv) PS D:\Projects\ARCD\PrimAITE\PrimAITE> primaite session --load [REDACTED for security]\primaite\sessions\2023-07-20\2023-07-20_15-01-11
2023-07-20 15:04:21,320: Using: AgentFramework.SB3, AgentIdentifier.PPO, ActionType.NODE, observation_space=NODE_LINK_TABLE, Training: 5 episodes @ 256 stepsEvaluation: 5 episodes @ 256 steps
2023-07-20 15:04:21,335: Environment configuration loaded
Environment configuration loaded
2023-07-20 15:04:21,775: Welcome to the Primary-level AI Training Environment (PrimAITE) (version: 2.0.0rc1)
2023-07-20 15:04:21,775: The output directory for this session is: C:\Users\czar.echavez\primaite\sessions\2023-07-20\2023-07-20_15-04-21
2023-07-20 15:04:21,779: Beginning learning for 10 episodes @ 256 time steps...
2023-07-20 15:04:22,379: Episode: 1, Average Reward: -0.0020839843750000003
2023-07-20 15:04:23,137: Episode: 2, Average Reward: -0.0021933593750000004
2023-07-20 15:04:23,831: Episode: 3, Average Reward: -0.0022617187500000003
2023-07-20 15:04:24,486: Episode: 4, Average Reward: -0.002373046874999999
2023-07-20 15:04:25,125: Episode: 5, Average Reward: -0.0018066406250000014
2023-07-20 15:04:25,791: Episode: 6, Average Reward: -0.0017597656250000013
2023-07-20 15:04:26,415: Episode: 7, Average Reward: -0.0018437500000000014
2023-07-20 15:04:27,053: Episode: 8, Average Reward: -0.0019101562500000015
2023-07-20 15:04:27,715: Episode: 9, Average Reward: -0.0016777343750000013
2023-07-20 15:04:28,359: Episode: 10, Average Reward: -0.0015976562500000012
2023-07-20 15:04:28,550: Finished learning
2023-07-20 15:04:30,851: Beginning deterministic evaluation for 5 episodes @ 256 time steps...
2023-07-20 15:04:31,243: Episode: 1, Average Reward: -0.0018515625000000014
2023-07-20 15:04:31,663: Episode: 2, Average Reward: -0.0018515625000000014
2023-07-20 15:04:32,112: Episode: 3, Average Reward: -0.0018515625000000014
2023-07-20 15:04:32,505: Episode: 4, Average Reward: -0.0018515625000000014
2023-07-20 15:04:32,904: Episode: 5, Average Reward: -0.0018515625000000014
2023-07-20 15:04:32,998: Finished evaluation

```

Also fixed the xskipped tests, since the double running seems to have caused the issue of rewards not matching.

Added a test that runs the PrimAITE in CLI

## Checklist
- [x] This PR is linked to a **work item**
- [x] I have performed **self-review** of the code
- [x] I have written **tests** for any new functionality added with this PR
- [x] I have updated the **documentation** if this PR changes or adds functionality
- [x] I have run **pre-commit** checks for code style

#1595:
- Fixed the...
2023-07-21 11:32:32 +00:00
Christopher McCarthy
de8f847afd Merged PR 132: #1594 - Managed to get the evaluation of rllib agents working. A test has bee...
## Summary
Managed to get the evaluation of rllib agents working. A test has been added to test_primaite_session.py that now tests the full RLlib agent from end-to-end. I've also updated the tests in here to check that the mean reward per episode plot is created for both too. This will need a bit of a re-design further down the line, but for now, it works. Added a custom exception for RLlib eval only error.

Is this a hack? Yes. Does it work? Yes. we'll make this better later.

## Test process
Both a SB3 and Ray RLlib agent is tested now in the test_primaite_session.py module.

## Checklist
- [X] This PR is linked to a **work item**
- [X] I have performed **self-review** of the code
- [X] I have written **tests** for any new functionality added with this PR
- [X] I have updated the **documentation** if this PR changes or adds functionality
- [X] I have run **pre-commit** checks for code style

Related work items: #1594
2023-07-21 10:26:31 +00:00
Chris McCarthy
e9b90760dd #1594 - Added docstrings and fixed training type. Added a clean-up of the unpacked agent in eval dir. 2023-07-21 10:33:22 +01:00
Christopher McCarthy
b4d05e7b3e Merged PR 131: #1639 - Added CHANGELOG.md and backfilled it with v1.1.0 and v1.1.1 release n...
## Summary
Added changelog and backfilled with v1.1.0 and v1.1.0 release notes.

Check what's written against notes in: https://nscuk.sharepoint.com/:f:/r/sites/SSE32-ARCDTrainingEnvironments/Shared%20Documents/General/01%20PrimAITE/01.01%20Releases/Release%20Notes?csf=1&web=1&e=uwPsyM

## Test process
N/A

## Checklist
- [ ] This PR is linked to a **work item**
- [ ] I have performed **self-review** of the code
- [ ] I have written **tests** for any new functionality added with this PR
- [ ] I have updated the **documentation** if this PR changes or adds functionality
- [ ] I have run **pre-commit** checks for code style

#1639 - Added CHANGELOG.md and backfilled it with v1.1.0 and v1.1.1 release notes.

Related work items: #1639
2023-07-21 09:28:28 +00:00
Czar Echavez
720a326537 #1595: refactor variable name 2023-07-21 09:31:37 +01:00
Czar Echavez
f313709f47 #1595: possibly fixed the tests by fixing the bug 2023-07-21 09:17:38 +01:00
Chris McCarthy
90d825736b #1594 - Managed to get the evaluation of rllib agents working. A test has been added to test_primaite_session.py that now tests the full RLlib agent from end-to-end. I;ve also updated the tests in here to check that the mean reward per episode plot is created for both too. This will need a bit of a re-design further down the line, but for now, it works. Added a custom exception for RLlib eval only error. 2023-07-20 19:58:48 +01:00
Chris McCarthy
60d6e7b9ab #1639 - Reinstalled pre-commit hook 2023-07-20 18:45:02 +01:00
Chris McCarthy
940d6f85a8 #1639 - Added CHANGELOG.md and backfilled it with v1.1.0 and v1.1.1 release notes. 2023-07-20 17:24:55 +01:00
Brian Kanyora
6b11095d71 Merged PR 129: feature/1641:Update config.rst
## Summary
Changed environment config to training config in config.rst as Chris requested.

## Checklist
- [X] This PR is linked to a **work item**
- [X] I have performed **self-review** of the code
- [X] I have written **tests** for any new functionality added with this PR
- [X] I have updated the **documentation** if this PR changes or adds functionality
- [X] I have run **pre-commit** checks for code style

feature/1641:
Changed environment config to training config

Related work items: #1641
2023-07-20 15:50:13 +00:00
Czar Echavez
6930c8ba7b #1595:
- Fixed the bug where session gets run twice when loading a session via CLI
- Added a test for the CLI run - xskipped while the bugfix for load session acting odd is tbd
- Fixed a minor bug in PrimAITE session where session_path is overwritten
2023-07-20 16:21:30 +01:00
Brian Kanyora
26ed3e8ec6 feature/1641:
Changed environment config to training config
2023-07-20 16:09:57 +01:00
Sunil Samra
d81b8af7ec Merged PR 128: #1640 - Update Sphinx Docs for 2.0.0 Release
## Summary
Added to docs as per @<Christopher McCarthy> changes - added prefixes to command line primaite session and explained primate session default no arguments command.

## Test process
*NA*

## Checklist
- [X] This PR is linked to a **work item**
- [X] I have performed **self-review** of the code
- [X] I have written **tests** for any new functionality added with this PR
- [X] I have updated the **documentation** if this PR changes or adds functionality
- [X] I have run **pre-commit** checks for code style

#1640 - Added --ldc and --tc prefixes and added small note about primaite session default run command

Related work items: #1640
2023-07-20 14:31:05 +00:00
SunilSamra
2fba54bfff #1640 - Added --ldc and --tc prefixes and added small note about primaite session default run command 2023-07-20 14:45:55 +01:00
Brian Kanyora
8d31afe139 Merged PR 125: feature/1637:Updating-UML-Diagram
## Summary
Updated the UML diagram using puml to help render a better output of the diagram.

## Checklist
- [x] This PR is linked to a **work item**
- [x] I have performed **self-review** of the code
- [na] I have written **tests** for any new functionality added with this PR
- [na] I have updated the **documentation** if this PR changes or adds functionality
- [x] I have run **pre-commit** checks for code style

feature/1637:
Updating the UML diagram using puml instead of mmd.

Related work items: #1637
2023-07-20 13:34:26 +00:00
Christopher McCarthy
e0da34765c Merged PR 126: PrimAITE Benchmarking
## Summary
 - Added full benchmarking script that included plots and a LaTeX report. Ran the v2.0.0rc1 benchmark. Tidied a few other things up.

The code is a bit scrappy. But it's not released code. I will endeavour to tidy it up at a later date.

## Test process
Manually ran the script. This is the final report -> [PrimAITE v2.0.0rc1 Learning Benchmark.pdf](https://dev.azure.com/ma-dev-uk/b50a61ee-86c4-48bc-9a0b-a67645ba12ee/_apis/git/repositories/2825053e-bd3b-45b2-8680-1281809eefa2/pullRequests/126/attachments/PrimAITE%20v2.0.0rc1%20Learning%20Benchmark.pdf)

## Checklist
- [X] This PR is linked to a **work item**
- [X] I have performed **self-review** of the code
- [ ] I have written **tests** for any new functionality added with this PR
- [ ] I have updated the **documentation** if this PR changes or adds functionality
- [X] I have run **pre-commit** checks for code style

Related work items: #1632
2023-07-20 12:58:54 +00:00
Marek Wolan
93d9cfb224 Merged PR 127: Add license
## Summary
Add license file and reference it in the pyproject.toml

## Test process
Running `pip-licenses` shows:
```
 pre-commit                     2.20.0       MIT License
 primaite                       2.0.0rc1     MIT
 primaite                       2.0.0rc1     MIT
 prometheus-client              0.17.1       Apache Software License
 prompt-toolkit                 3.0.39       BSD License
```
## Checklist
- [x This PR is linked to a **work item**
- [x] I have performed **self-review** of the code
- [ ] I have written **tests** for any new functionality added with this PR
- [ ] I have updated the **documentation** if this PR changes or adds functionality
- [x] I have run **pre-commit** checks for code style

Related work items: #1638
2023-07-20 11:16:05 +00:00
Chris McCarthy
7f8666b3d1 Create README.md 2023-07-20 10:55:59 +01:00
Brian Kanyora
450342579b feature/1637:
Fixed the relationship between PrimIATE and Transaction.
2023-07-20 10:54:42 +01:00
Chris McCarthy
1f3ac50849 #1632 - Fixed output directory clear bug. Added gputil to dev deps. 2023-07-20 10:28:19 +01:00
Marek Wolan
c543c6c147 Apply suggestions from code review 2023-07-20 09:21:35 +00:00
Chris McCarthy
26aea67cd3 #1632 - Added Python version to the System Information section in the report 2023-07-20 10:16:29 +01:00
Chris McCarthy
2aeb11771f #1632 - Increased rolling window from 5 to 25 2023-07-20 10:06:44 +01:00
Marek Wolan
1e2244583a Add license 2023-07-20 10:03:05 +01:00
Chris McCarthy
aaf1066d29 #1632 - Added full benchmarking script that included plots and a LaTeX report. Ran the v2.0.0rc1 benchmark. Tidied a few other things up. 2023-07-20 08:48:18 +01:00
Brian Kanyora
4ef63bb29e feature/1637:
Updating the UML diagram using puml instead of mmd.
2023-07-19 17:03:10 +01:00
Chris McCarthy
beb8451a80 Merge branch 'dev' into feature/1632_Add_benchmarking_scripts 2023-07-18 13:24:15 +01:00
Christopher McCarthy
6eb123680f Merged PR 124: #1635 - Updated the session outputs details in primaite_session.rst
## Summary
- Updated the session outputs details in primaite_session.rst
- Fixed Logger typehint bugs
- Fixed typing issues in access_control_list.py

## Test process
Build the docs

![image.png](https://dev.azure.com/ma-dev-uk/b50a61ee-86c4-48bc-9a0b-a67645ba12ee/_apis/git/repositories/2825053e-bd3b-45b2-8680-1281809eefa2/pullRequests/124/attachments/image.png)

## Checklist
- [ ] This PR is linked to a **work item**
- [ ] I have performed **self-review** of the code
- [ ] I have written **tests** for any new functionality added with this PR
- [ ] I have updated the **documentation** if this PR changes or adds functionality
- [ ] I have run **pre-commit** checks for code style

#1635 - Updated the session outputs details in primaite_session.rst

Related work items: #1635
2023-07-18 10:44:17 +00:00
Chris McCarthy
b31522bd9b #1635 - Fixed typing issues in access_control_list.py 2023-07-18 11:38:28 +01:00
Chris McCarthy
6ac6b79b35 Merge branch 'dev' into feature/1635_Update_Primaite_Session_page_in_Docs
# Conflicts:
#	src/primaite/setup/old_installation_clean_up.py
#	src/primaite/setup/reset_example_configs.py
2023-07-18 11:36:31 +01:00
Chris McCarthy
0af6d6c44f #1635 - Updated the session outputs details in primaite_session.rst
- Fixed Logger typehint bugs
2023-07-18 11:34:41 +01:00
Sunil Samra
693c9489e1 Merged PR 120: Change Functionality of ACL Rules
## Summary
### ACL List
First change was I changed `access_control_list.py` from a `dict` to a `list` so it is now an ordered structure. This was done so I could implement the positions inside the `ACL` and `ANY` action spaces.

From this, some functions have changed such as `add_rule` and `remove_rule`, `is_blocked` and `get_relevant_rules`.

The ACL list is now a fixed size and on initialisation it is filled with `None` types. When a function calls `self.acl` the `implicit rule` (if there is one) is added after the last `ACLRule` object in the list. The remainder of the list (if there is left over space) is padded out with `None`.

As the agent adds rules, the `None` are replaced by `ACLRule` objects and the agent cannot overwrite an existing `ACLRule` with another, it can only write over `None` types.

### ACL Training Config Changes
Changes have been made to the `training_config_main.yaml`. There are 2 new items:

`implicit_acl_rule:` - Implicit ACL firewall rule at end of list to be default action (ALLOW or DENY)
`max_number_acl_rules:` - Total number of ACL rules allowed in the environment

In the `OBSERVATION_SPACE` area of the config, `ACCESS_CONTROL_LIST` can be selected

They have default values if none are specified so for the older configs - these values are in the `TrainingConfig` dataclass.

### ACL and ANY Action Spaces
I changed the ACL space from length of 6 to 7. I have included the `position` of where the agent wants to position the ACL Rule.

`position` = index in `self.acl` with bounds [0 to ...]

As a result, total possible actions have gone up.

### ACL Observation Space
In the observations.py I have made a new observation component: Access Control List.
It has the following mappings/meanings:

        [0, 1, 2] - Permission (0 = NA, 1 = DENY, 2 = ALLOW)
        [0, num nodes] - Source IP (0 = NA, 1 = any, then 2 -> x resolving to Node IDs)
        [0, num nodes] - Dest IP (0 = NA, 1 = any, then 2 -> x resolving to Node IDs)
        [0, num services] - Protocol (0 = NA, 1 = any, then 2 -> x resolving to protocol)
        [0, num ports] - Port (0 = NA, 1 = any, then 2 -> x resolving to port)
        [0, max acl rules - 1] - Position (0 = NA, 1 = first index, then 2 -> x index resolving to acl rule in acl list)

I created a new 0 meaning, which means NA and represents the None objects in the ACLList.

Also, there is no 'flatten' in the observation space components and this has been done in the observations.py now if there are multiple components.

## Test process
I have written tests in a new `TestAccessControlList` object in `test_observations.py`.

I ran a single test which was 1000 episodes, SB3/PPO, Config 5 and ACL Observation Space. I seemed to get some interesting results which may need investigating on Monday.

![Figure_1.png](https://dev.azure.com/ma-dev-uk/b50a61ee-86c4-48bc-9a0b-a67645ba12ee/_apis/git/repositories/2825053e-bd3b-45b2-8680-1281809eefa2/pullRequests/120/attachments/Figure_1.png)

## Checklist
- ...
2023-07-18 10:31:15 +00:00
Marek Wolan
72e72c80c2 Get tests working with new ACL changes 2023-07-18 11:16:39 +01:00
Marek Wolan
652c9f1b90 Merge remote-tracking branch 'origin/dev' into feature/901-change-functionality-acl-rules 2023-07-18 10:55:31 +01:00
Marek Wolan
314e76f497 Merged PR 122: Typehint everything
## Summary
Added typehints to functions/methods, and class attributes.

## Test process
I used flake8-annotations and mypy to verify completeness and correctness. Mypy did throw up a very large number of errors and many of them point to some potential problems in the codebase. To elaborate, there are some places where there has been confusion as to whether objects should be strings, integers, or enums. Resolving this is out of scope of this PR but I will create more tickets with concrete examples.

## Checklist
- [x] This PR is linked to a **work item**
- [x] I have performed **self-review** of the code
- [ ] I have written **tests** for any new functionality added with this PR
- [ ] I have updated the **documentation** if this PR changes or adds functionality
- [x] I have run **pre-commit** checks for code style

Related work items: #1623
2023-07-18 09:43:08 +00:00
Marek Wolan
0d521bc96b Remove redundant 'if TYPE_CHECKING' statements 2023-07-18 10:21:06 +01:00
Marek Wolan
6c31034dba Ensure everything is still typehinted 2023-07-18 10:13:54 +01:00
Chris McCarthy
7054b775ff #1632 - Added bench marking script 2023-07-18 10:11:01 +01:00
Marek Wolan
9c28de5b49 Mark failing tests as Xfail to force build success 2023-07-18 10:08:02 +01:00
Marek Wolan
471826e5ce Merge branch 'dev' into feature/1623-typehints 2023-07-18 10:03:48 +01:00
Christopher McCarthy
2c4b4801b0 Merged PR 123: #1631 - Added the DEFCON 703 header to all possible files
## Summary
Added the DEFCON 703 header to all possible files

## Test process
Built docs to confirm that the top-of-the-page comment does not break anything

## Checklist
- [X] This PR is linked to a **work item**
- [X] I have performed **self-review** of the code
- [ ] I have written **tests** for any new functionality added with this PR
- [X] I have updated the **documentation** if this PR changes or adds functionality
- [X] I have run **pre-commit** checks for code style

#1631 - Added the DEFCON 703 header to all possible files

Related work items: #1631
2023-07-17 19:51:29 +00:00
SunilSamra
f5b18e882c #901 - Replaced "ALLOW" with RulePermissionType.ALLOW
- Added Explicit ALLOW to test_configs in order for tests to work
- Added typing to access_control_list.py and acl_rule.py
2023-07-17 20:40:00 +01:00
Chris McCarthy
f4683f3b66 #1631 - Updated the copyright statement to comply with DEFCON 703 Edition 08/13 2023-07-17 19:57:34 +01:00
SunilSamra
37dd2838df #901 - merged dev into branch 2023-07-17 19:54:07 +01:00
SunilSamra
2eb6223aad Merge remote-tracking branch 'origin/feature/901-change-functionality-acl-rules' into feature/901-change-functionality-acl-rules 2023-07-17 19:42:29 +01:00
SunilSamra
bacb42833f #901 - ran black pre-commit over observations.py to fix it 2023-07-17 19:42:05 +01:00
Sunil Samra
a2d99080cd Apply suggestions from code review 2023-07-17 18:36:13 +00:00
Chris McCarthy
678f953ced #1631 - Added the DEFCON 703 header to all possible files 2023-07-17 19:28:43 +01:00
Christopher McCarthy
3186fcb489 Merged PR 121: #1629 - Added rllib test
## Summary
Quick test that uses RLLIB in a session

## Test process
The learning session completes then we check that the number of rows in both the average reward per episode and all transactions csv files.

## Checklist
- [X] This PR is linked to a **work item**
- [X] I have performed **self-review** of the code
- [X] I have written **tests** for any new functionality added with this PR
- [ ] I have updated the **documentation** if this PR changes or adds functionality
- [X] I have run **pre-commit** checks for code style

#1629 - Added rllib test

Related work items: #1629
2023-07-17 17:28:51 +00:00
Czar Echavez
89fd8fb8dc Merged PR 119: Loading SB3 Agents + Loading agent via PrimaiteSession
## Summary
- Added a feature which allows a user to load a previous SB3 session
- Added a feature which allows a user to load a previous PrimaiteSession
- Added a feature which allows a user to load a previous session via the CLI: `primaite session --load "<SESSION_PATH>"`
- RLlib is TODO in another ticket #1626
- Parallel tests via the [pytest-xdist](https://pypi.org/project/pytest-xdist/) dependency (MIT licensed)
- Moved hardcoded agent into hardcoded_abc.py
- renamed agent.py to agent_abc.py to clarify it is an abstract base class
- Added documentation to clarify how to use the feature via CLI or using the run function via main.py

## Test process
Created [test_session_loading.py](https://dev.azure.com/ma-dev-uk/PrimAITE/_git/PrimAITE/pullrequest/119?_a=files&path=/tests/test_session_loading.py) which loads a previously run session and then performs a learn and evaluation run on the loaded agent/Primate session.

The test copies the saved session into a temporary folder, which is then set as the test session path. Once the test is done, the temporary folder should then be deleted

## Checklist
- [X] This PR is linked to a **work item**
- [X] I have performed **self-review** of the code
- [X] I have written **tests** for any new functionality added with this PR
- [X] I have updated the **documentation** if this PR changes or adds functionality
- [X] I have run **pre-commit** checks for code style

Related work items: #1595
2023-07-17 15:26:42 +00:00
Marek Wolan
4032f3a2a8 Change typehints after mypy analysis 2023-07-17 16:22:07 +01:00
SunilSamra
00d01157da #901 - Changed num_eval_steps back to 1 in ppo_seeded_training_config.yaml 2023-07-17 15:54:15 +01:00
SunilSamra
5f46438ba8 Merge remote-tracking branch 'origin/dev' into feature/901-change-functionality-acl-rules 2023-07-17 15:51:01 +01:00
Czar Echavez
1d0a211b44 Merge branch 'dev' into feature/1595-finalise-and-test-the-loading-of-trained-agents 2023-07-17 15:23:46 +01:00
Sunil Samra
d67df9234d Apply suggestions from code review 2023-07-17 14:21:37 +00:00
Brian Kanyora
12339aa970 Merged PR 113: feature/1597-Getting-Started
## Summary
Add a Getting started page to the docs file.

## Checklist
- [x] This PR is linked to a **work item**
- [x] I have performed **self-review** of the code
- [na] I have written **tests** for any new functionality added with this PR
- [x] I have updated the **documentation** if this PR changes or adds functionality
- [x] I have run **pre-commit** checks for code style

Related work items: #1597
2023-07-17 14:19:16 +00:00
SunilSamra
e500138b8f #901 - Changed num_eval_steps back to 1 in ppo_seeded_training_config.yaml 2023-07-17 14:06:33 +01:00
SunilSamra
04c6a96a23 Merge remote-tracking branch 'origin/feature/901-change-functionality-acl-rules' into feature/901-change-functionality-acl-rules 2023-07-17 14:01:32 +01:00
SunilSamra
ded5a6f352 #901 - Fixed bug in implicit rule - comparing it to string ALLOW or DENY in access_control_list.py 2023-07-17 13:58:06 +01:00
Sunil Samra
5685db804a Removed apply_implicit_rule comment 2023-07-17 12:45:31 +00:00
SunilSamra
8008fab523 #901 - Removed flatten from training configs
- Added flatten operation in observations.py when there are multiple obs components
- Updated config.rst docs
2023-07-17 13:44:16 +01:00
SunilSamra
cb4089a0ba #901
- Removed bool apply_implicit_rule
- Set default implicit_rule to EXPLICIT DENY
- Added position to ACLs in laydown configs
- Removed apply_implicit_rule from training configs
2023-07-17 13:00:58 +01:00
Chris McCarthy
ee0c797c3c #1629 - Added assertion in the test that checks the length of the all transactions file too.
- Added supporting function on the TempPrimaiteSession class that reads the all transactions csv file.
- Some renaming of the functions.
2023-07-17 12:14:47 +01:00
Czar Echavez
6cb475ecdc #1595: set default tc and ldc to None for AgentABC and PrimaiteSession + adding a comment for cli load flag 2023-07-17 11:54:54 +01:00
Chris McCarthy
0732eb2f5c #1629 - Added rllib test 2023-07-17 11:50:07 +01:00
Marek Wolan
ef8f6de646 Add typehint for agent config class 2023-07-17 11:21:29 +01:00
Brian Kanyora
9374646758 Merge remote-tracking branch 'origin/dev' into feature/1597-Getting-Started 2023-07-17 10:33:59 +01:00
SunilSamra
3e7f6cc98d #901
- Added check in access_control_list.py which sets implicit permission to NA if boolean is False
- Changed the defaults in training_config.py so that each scenario has an EXPLICIT ALLOW rule as default implicit rule
- Updated the test_seeding_and_deterministic_session.py because of change no2 adds an extra rule to that scenario
2023-07-17 10:27:56 +01:00
Brian Kanyora
ff6c8c0c6b Apply suggestions from code review 2023-07-17 09:23:11 +00:00
SunilSamra
ab45c7e3f9 #901 - added to config.rst and added new ACL main config options 2023-07-17 10:08:12 +01:00
Marek Wolan
98ac228f90 Fix types according to mypy 2023-07-14 16:38:55 +01:00
Czar Echavez
232908ac00 #1595: minor fix to cli command 2023-07-14 16:04:34 +01:00
SunilSamra
a2461d29b4 #901 - amended comment in observations.py 2023-07-14 16:04:13 +01:00
Czar Echavez
c783965001 #1595: added loading sessions to run command + test + documentation for how to use loading sessions 2023-07-14 15:51:38 +01:00
SunilSamra
b4f8514206 #901 - amended comment in training_config_main.yaml 2023-07-14 15:49:18 +01:00
SunilSamra
fc1a575fd0 #901 -
- Added comments in access_control_list.py
- Changed obs_shape to max_number_acl_rules from max_number_acl_rules + 1 as index starts from 1
- Commented episode and step print line from test_single_action_space.py
2023-07-14 15:27:37 +01:00
SunilSamra
6b8cf73207 901 - Added another test and tidied up comments in test_observation_space.py and tidied up comments in observations.py 2023-07-14 14:51:26 +01:00
Marek Wolan
e522e56ff1 Add typehints 2023-07-14 14:43:47 +01:00
SunilSamra
e5debcfc6c 901 - Changed the default expected_mean_reward_per_episode values in test_seeding_and_deterministic_session.py 2023-07-14 14:26:10 +01:00
Czar.Echavez
fbdb8aab28 #1595:
- Added ability to load sessions via PrimaiteSession
- PrimaiteSession loading test
- Added a NotImplemented RLlib loading for now
- Added the ability to load sessions for hardcoded agents
- Moved Session metadata parsing to utils
2023-07-14 14:14:03 +01:00
Chris McCarthy
8c0ca8cfbc #901 - Dropped temp_primaite_sessiion_2 from conftest.py.
- Re-added the hard-coded mean rewards per episode values from a rpe-trained agent to the deterministic test in test_seeding_and_deterministic_session.py
- Partially tidies up some tests in test_observation_space.py; Still some work to be done on this at a later date.
2023-07-14 14:13:11 +01:00
SunilSamra
4a0d688ae6 901 - fixed test_observation_space.py, added test fixture for test_seeding_and_deterministic_session.py and increased default max number of acls 2023-07-14 12:29:50 +01:00
Marek Wolan
c57ed6edcd Added type hints 2023-07-14 12:01:38 +01:00
Czar Echavez
dce0d10383 #1595: fix poorly merged tests + files 2023-07-14 11:21:59 +01:00
Czar Echavez
a92ef3f4ad #1595: test to make sure that the loaded agent trains + remove unnecessary files + fixing agent save output name 2023-07-14 10:56:28 +01:00
Czar Echavez
bc7c32697f Merge branch 'dev' into feature/1595-finalise-and-test-the-loading-of-trained-agents 2023-07-14 08:39:52 +01:00
Marek Wolan
a923d818d3 Add More Typehint 2023-07-13 18:08:44 +01:00
SunilSamra
0bcaf0696d 901 - removed print statements and merged with dev 2023-07-13 17:14:59 +01:00
SunilSamra
79d77c85c4 Merge remote-tracking branch 'origin/dev' into feature/901-change-functionality-acl-rules 2023-07-13 16:48:02 +01:00
Czar.Echavez
c3023d4d7c #1595 missed hardcoded_abc file in commit 2023-07-13 16:24:30 +01:00
Czar.Echavez
e2d5f0bcff #1595:
- SB3 Agent loading
- rename agent.py -> agent_abc.py
- rename hardcoded.py -> hardcoded_abc.py
- Tests
- Added in test asset that is used to load the SB3 Agent
2023-07-13 16:24:03 +01:00
Marek Wolan
4e4166d4d4 Continue Adding Typehints 2023-07-13 12:25:54 +01:00
SunilSamra
771061a218 901 - fixed test_single_action_space.py test 2023-07-13 11:45:23 +01:00
SunilSamra
ad4198da13 901 - changed acl current obs from list to numpy.array, changed default ACL list in training_config.py to FALSE, and tried to make test_seeding_and_deterministic_session.py test without fixed reward results 2023-07-13 11:04:11 +01:00
Brian Kanyora
345b89d5ee feature/1597:
Added dependencies to the index.rst since v1.1.0.
2023-07-13 09:36:04 +01:00
Brian Kanyora
3874d08a7e feature/1597:
Added dependencies to the index.rst since v1.1.0.
2023-07-13 09:35:42 +01:00
Marek Wolan
d2bac4307a Type hint ACLs 2023-07-12 16:58:12 +01:00
Marek Wolan
f3809054bf Merged PR 116: Update documentation
## Summary
* Update observation space information and standardise formatting of code blocks in that section
* Remove non-ascii quotation characters
* Update custom blue agent page to match new AgentSession classes.
* Introduce glossary
* Provide a first draft of migration guide for 1.2 to 2.0 (probably not comprehensive)

## Test process
Sphinx is able to build the documentation as checked on my local machine

## Checklist
- [x] This PR is linked to a **work item**
- [x] I have performed **self-review** of the code
- [ ] I have written **tests** for any new functionality added with this PR
- [x] I have updated the **documentation** if this PR changes or adds functionality
- [x] I have run **pre-commit** checks for code style

Related work items: #1602
2023-07-12 14:28:41 +00:00
Sunil Samra
8caec4eaa1 Merged PR 115: Configure Different Episode and Step Counts for Training and Evaluation
## Summary
Training configs now have 2 different types of episode and step counts - one for train and one for evaluation.

`num_train_episodes`
`num_train_steps`
`num_eval_episodes`
`num_eval_steps`

## Test process
A test file `test_train_eval_episode_steps.py` has been implemented which runs train and evaluation session on two particular configs.

The train and evaluation sessions have different episodes and step count and the test checks that the output log files have the correct number of `total_steps` and `total_episodes`.

## Checklist
- [X] This PR is linked to a **work item**
- [X] I have performed **self-review** of the code
- [X] I have written **tests** for any new functionality added with this PR
- [X] I have updated the **documentation** if this PR changes or adds functionality
- [X] I have run **pre-commit** checks for code style

Related work items: #1566, #1589
2023-07-12 13:34:58 +00:00
Czar Echavez
54e4da1250 #1595: run tests in parallel 2023-07-12 12:04:26 +01:00
SunilSamra
e192d24800 Merge remote-tracking branch 'origin/dev' into feature/901-change-functionality-acl-rules
# Conflicts:
#	src/primaite/acl/access_control_list.py
2023-07-12 10:45:03 +01:00
SunilSamra
bd8d9f278d 1566 - removed redundant config file 2023-07-12 09:52:54 +01:00
SunilSamra
ae6c90a670 901 - fixed how acls are added into list with new logic - agent cannot overwrite another acl in the list 2023-07-12 09:47:16 +01:00
Marek Wolan
5d5d70c0b6 Add better hyperlinks 2023-07-12 09:16:40 +01:00
SunilSamra
92f94b7be7 Merge remote-tracking branch 'origin/dev' into feature/1566-configure_episode-steps-learn-eval 2023-07-11 17:18:05 +01:00
Chris McCarthy
8eba54f81c #1597 - Fixed Project Links side bar 2023-07-11 15:50:37 +01:00
Chris McCarthy
32f2444102 Merge remote-tracking branch 'origin/feature/1597-Getting-Started' into feature/1597-Getting-Started
# Conflicts:
#	docs/source/getting_started.rst
2023-07-11 15:47:47 +01:00
Chris McCarthy
646ac3cf02 #1597 - Added code tabs to getting started page 2023-07-11 15:47:13 +01:00
Czar.Echavez
e51391b0cf #1595: Moved hardcoded agent into its own file 2023-07-11 15:03:02 +01:00
Brian Kanyora
70798b6c04 Added a space 2023-07-11 14:15:02 +01:00
Brian Kanyora
e99560f720 Addressing Sunils comments from my 2023-07-11 13:49:01 +01:00
Marek Wolan
fdec452e7a Merge remote-tracking branch 'origin/dev' into feature/1602-update-docs 2023-07-11 13:13:02 +01:00
Marek Wolan
93a9d7732e Merged PR 114: Change build pipeline to only run once on commits
## Summary
Unfortunately, I had to do away with the nice and neat matrix strategy for builds, because they do not support conditionals. Instead, I manually replicated the behaviour of the matrix but added a conditional to run every platform only when the 'build reason' is PR.

## Test process
*How have you tested this (if applicable)?*

## Checklist
- [x] This PR is linked to a **work item**
- [x] I have performed **self-review** of the code
- [ ] I have written **tests** for any new functionality added with this PR
- [ ] I have updated the **documentation** if this PR changes or adds functionality
- [x] I have run **pre-commit** checks for code style

Related work items: #1603
2023-07-11 12:12:32 +00:00
SunilSamra
14d7317b6b 1566 - updated docs for new items in training_config 2023-07-11 12:40:25 +01:00
SunilSamra
5d88003230 1566 - applied pre-commit 2023-07-11 12:37:14 +01:00
SunilSamra
6547789d5d 901 - changed implicit_acl_rule from str to enum name 2023-07-11 12:36:22 +01:00
Marek Wolan
a01984b0ac Updated migration guide 2023-07-11 12:10:20 +01:00
Marek Wolan
42e8a65227 Added draft migration guide. 2023-07-11 12:01:48 +01:00
SunilSamra
f14963b6fb Merge remote-tracking branch 'origin/dev' into feature/1566-configure_episode-steps-learn-eval
# Conflicts:
#	src/primaite/config/training_config.py
2023-07-11 11:39:21 +01:00
Marek Wolan
4f36ffd909 Improved order of glossary terms 2023-07-11 11:31:29 +01:00
Marek Wolan
35263ee140 Completed glossary 2023-07-11 11:13:28 +01:00
Marek Wolan
520784e357 Merge remote-tracking branch 'origin/dev' into feature/1602-update-docs 2023-07-11 10:12:40 +01:00
Marek Wolan
f1457f36cb Fix typo in Build.Reason 2023-07-11 09:01:43 +00:00
Marek Wolan
36320968f2 Fixed formatting with pre-commit 2023-07-11 09:57:27 +01:00
Marek Wolan
1297d61a7a Added glossary 2023-07-11 09:56:52 +01:00
Marek Wolan
7796ad98f3 Fix syntax 2023-07-11 08:54:22 +00:00
Marek Wolan
186ba09400 Changed structure of build pipeline yaml 2023-07-11 08:53:37 +00:00
Marek Wolan
98414a58f3 Change parameter matrix to list instead of dict 2023-07-11 08:22:30 +00:00
Marek Wolan
3085057406 Capitalisation error in value 2023-07-11 08:15:16 +00:00
Marek Wolan
de630d11de Fix indent 2023-07-11 08:14:34 +00:00
Marek Wolan
ebf07ce5c1 Typo in word only 2023-07-11 08:14:08 +00:00
Marek Wolan
65d91e01a7 Potentially fix syntax error 2023-07-11 08:08:29 +00:00
Marek Wolan
0911efe4d0 Edit pipeline to use runtime parameters
https://stackoverflow.com/a/70046417
2023-07-11 08:05:38 +00:00
Marek Wolan
71f02d46d1 Updated azure-ci-build-pipeline.yaml 2023-07-11 07:19:58 +00:00
Marek Wolan
d90a00d063 Built matrix conditionally 2023-07-11 07:16:11 +00:00
Marek Wolan
40bbde1981 Merged PR 105: Fix errors while trying to run Hardcoded agent
## Summary
Since we added File System State as a new part of the observation space, some of the assumptions made by imported ADSP code were not met. This is addressed by these changes.

The code no longer crashes, but the hardcoded ACL agent doesn't work very well, it keeps returning action 0 and receives a low reward. Also if there are ACL rules with 'ANY' as a source IP, it crashes the function `get_node_of_ip` within the HardCodedACLAgent._calculate_action_full_view() method.

I'm not sure how much effort we need to spend fixing the hardcoded agents as they don't seem like they were delivered in a finished state.

## Test process
Can confirm the hardcoded agent can run within a primaite session now.

## Checklist
- [x] This PR is linked to a **work item**
- [x] I have performed **self-review** of the code
- [ ] I have written **tests** for any new functionality added with this PR
- [ ] I have updated the **documentation** if this PR changes or adds functionality
- [x] I have run **pre-commit** checks for code style

## note
I would appreciate some input about what we should do with hardcoded agents for release 2.0.0, it may require significant effort to get them working correctly.

Related work items: #1587
2023-07-10 15:10:12 +00:00
Brian Kanyora
ecc56ce5eb Merge remote-tracking branch 'origin/dev' into feature/1597-Getting-Started
# Conflicts:
#	docs/source/primaite-dependencies.rst
2023-07-10 15:48:32 +01:00
Brian Kanyora
270690a647 feature/1597:
pre commit fix
2023-07-10 15:41:50 +01:00
Marek Wolan
31703c54e2 Finished writing custom agent example. 2023-07-10 14:56:06 +01:00
SunilSamra
728ff01076 1566 - fixed the test_training_config.py test file by removing num_steps from init 2023-07-10 13:24:34 +01:00
Marek Wolan
59b34ffdf2 Changed build pipeline experimentally. 2023-07-10 10:25:26 +00:00
SunilSamra
9738d2b889 1566 - added correct num_train_episodes etc values to configs, fixed test_reward.py 2023-07-10 11:25:26 +01:00
Marek Wolan
55f958bb39 Merged PR 110: Update Observation spaces description
## Summary
This minor update adds more detail and links to relevant pages within the API docs.

## Test process
Locally built docs in HTML format to verify all content displays correctly.

Related work items: #1596
2023-07-10 10:20:42 +00:00
Marek Wolan
cc5e31c9b5 Changed order of text in custom agent docs 2023-07-10 11:19:47 +01:00
Brian Kanyora
4df9fc57a8 Additional syntax changes 2023-07-10 10:28:27 +01:00
Brian Kanyora
5ca939cdeb feature/1597:
Small syntax changes
2023-07-10 10:01:25 +01:00
Marek Wolan
56f369cfe0 Merge remote-tracking branch 'origin/dev' into bugfix/1587-hardcoded-agent 2023-07-10 09:15:25 +01:00
Marek Wolan
b293898913 Merged PR 104: Fix formatting in docstrings
## Summary
Fixes some incorrectly formatted documentations, such as in the observation module. Also adds some missing module-level docstrings. Also adds a PrimAITE Favicon to docs.

Removed Primaite-dependencies.rst as it's autogenerated.

## Test process
Purely cosmetic, so functionality not tested. I did render the HTML output to observe that some mistakes have been fixed.

## Checklist
- [x] This PR is linked to a **work item**
- [x] I have performed **self-review** of the code
- [na] I have written **tests** for any new functionality added with this PR
- [x] I have updated the **documentation** if this PR changes or adds functionality
- [ ] I have run **pre-commit** checks for code style

Related work items: #1572
2023-07-10 08:14:08 +00:00
Marek Wolan
c6ed921643 Update docs 2023-07-09 20:23:53 +01:00
Marek Wolan
07a0581fce Merge remote-tracking branch 'origin/dev' into feature/1572-fix-docs-formatting 2023-07-09 18:13:57 +01:00
Marek Wolan
aac0e2cc0f Merge remote-tracking branch 'origin/dev' into bugfix/1587-hardcoded-agent 2023-07-09 18:07:30 +01:00
Marek Wolan
105fcaecf4 Removed comment 2023-07-09 18:07:21 +01:00
Marek Wolan
ef23e504d6 Merge remote-tracking branch 'origin/dev' into feature/1596-better-observation-docs 2023-07-09 18:05:13 +01:00
Brian Kanyora
77cce645f9 Resolved more syntax errors 2023-07-07 16:32:35 +01:00
SunilSamra
af4fd4f66b 1566 - updated configs to correct values of step count and number of episodes 2023-07-07 16:26:12 +01:00
Brian Kanyora
9567afbab1 Fixed the rst syntax 2023-07-07 16:25:55 +01:00
Marek Wolan
72aef78391 Merged PR 106: Resolve TODOs about documenting functions
## Summary
- Added type hints and docstrings to functions imported from ADSP.
- Imported `get_relevant_rules` which was referenced but didn't exist.
- Removed duplicated function definitions in `agents.utils`

## Test process
The changes in this PR are almost exclusively cosmetic. I can confirm that after adding/removing functions, the unit tests passed fine. I was also able to run the Hardcoded node and ACL agents without problems.

## Checklist
- [x] This PR is linked to a **work item**
- [x] I have performed **self-review** of the code
- [na] I have written **tests** for any new functionality added with this PR
- [na] I have updated the **documentation** if this PR changes or adds functionality
- [x] I have run **pre-commit** checks for code style

Related work items: #1575
2023-07-07 15:10:44 +00:00
Chris McCarthy
1ddfca6459 #1566 - Refactored the test_train_eval_episode_steps.py to sue TempPrimaiteSession.
- Fixed all errors that were caused b fixing the above.
- Some tests still fail, these are for SS to fix.
- Dropped the old run_generic stuff from conftest.py
2023-07-07 15:50:14 +01:00
SunilSamra
4902ccd2b4 Merge remote-tracking branch 'origin/dev' into feature/901-change-functionality-acl-rules 2023-07-07 15:14:05 +01:00
Chris McCarthy
8edb26a65c Merge remote-tracking branch 'origin/dev' into 1566-configure-episode-steps-learn-eval
# Conflicts:
#	src/primaite/agents/rllib.py
2023-07-07 14:34:20 +01:00
Marek Wolan
2effe31523 Reworded observation description 2023-07-07 14:24:37 +01:00
SunilSamra
79d98e977b 1566 - added test file and edited configs to include types of num steps and modifed agents to use correct step and episode counts 2023-07-07 14:13:47 +01:00
Marek Wolan
179301e068 Update observation space documentation 2023-07-07 13:52:14 +01:00
Brian Kanyora
15ca48ec6c Added a getting started file 2023-07-07 11:37:57 +01:00
Marek Wolan
1d1f3f2403 Merge remote-tracking branch 'origin/dev' into feature/1572-fix-docs-formatting 2023-07-07 10:30:11 +01:00
Marek Wolan
5618283cc5 Standardise docstring summary line placement. 2023-07-07 10:28:00 +01:00
Czar Echavez
4acb220c0c Merged PR 89: #1386 Enable a repeatable/deterministic baseline test
## Summary
- Added the fix from #1535 with minor changes to make sure that the `primaite_env.step()` function can properly parse the action
- added the config deterministic and seed to training config
- added the deterministic and seed to the Training config class, with defaults `False` and `None` respectively
- minor fix to `primaite_env.close()` function so that it now works

## Test process
Added e2e tests for generic, ppo and a2c which evaluates a trained agent twice to make sure that the seeding and deterministic action works

## Checklist
- [x] This PR is linked to a **work item**
- [x] I have performed **self-review** of the code
- [x] I have written **tests** for any new functionality added with this PR
- [x] I have updated the **documentation** if this PR changes or adds functionality
- [x] I have run **pre-commit** checks for code style

#1386: added the ability to set deterministic and seeding RNG when training and evaluating + the fix provided in #1535

Related work items: #1386, #1535
2023-07-07 09:22:47 +00:00
Czar Echavez
76997f403e Merge branch 'dev' into feature/1386-enable-a-repeatable-or-deterministic-baseline-test 2023-07-06 22:22:37 +01:00
Christopher McCarthy
5ac196b3cb Merged PR 109: Auto save agent at end of training
## Summary
* Made RLlib and SB3 agents save at the end of each learning session by default using a common file naming format. Also now agents only checkpoint every n and not on the final episode.

## Test process
*Tests saved agent file in the test_primaite_session test.

## Checklist
- [X] This PR is linked to a **work item**
- [X] I have performed **self-review** of the code
- [X] I have written **tests** for any new functionality added with this PR
- [ ] I have updated the **documentation** if this PR changes or adds functionality
- [X] I have run **pre-commit** checks for code style

Related work items: #1593
2023-07-06 16:29:48 +00:00
Marek Wolan
87710ec22b Merged PR 108: Divide default rewards by 10000
## Summary
As per the discussion this morning, this PR reimplements changes that were made by ADSP to make the default rewards smaller. This also adds type hints rewards as floats.

## Test process
I checked that sessions are able to run and that they report values similar to what we are used to but smaller by a factor of 10000. I did not change the reward values in the integration test configs, and the tests still pass.

## Checklist
- [x] This PR is linked to a **work item**
- [x] I have performed **self-review** of the code
- [x] I have written **tests** for any new functionality added with this PR
- [x] I have updated the **documentation** if this PR changes or adds functionality
- [x] I have run **pre-commit** checks for code style

Related work items: #889, #1586
2023-07-06 15:17:47 +00:00
Marek Wolan
653d76ec62 Added docstrings to class intialisers 2023-07-06 16:08:51 +01:00
Marek Wolan
9167816896 Removed reference to file that no longer exists 2023-07-06 15:18:49 +01:00
Marek Wolan
8d466accf5 Add __init__ to class special members doc 2023-07-06 15:18:33 +01:00
Marek Wolan
eb068e22b6 undeleted api (lol) 2023-07-06 15:05:39 +01:00
Marek Wolan
70bde700b7 Deleted icon 2023-07-06 15:04:46 +01:00
Chris McCarthy
ddabf991ce #1593 - Ran pre-commit hook 2023-07-06 14:18:49 +01:00
Chris McCarthy
fc98441a11 #1593 - Check that agent saved file exists 2023-07-06 14:13:02 +01:00
Chris McCarthy
1e7f5b62f3 #1963 - Made RLlib and SB3 agents save at the end of each learning session by default using a common file naming format. Also now agents only checkpoint every n and not on the final episode 2023-07-06 13:56:12 +01:00
Czar Echavez
08220ff6ea #1386: remove redundant config files + test fixtures + fixing deterministic and seed config description in documentation to avoid misunderstandings 2023-07-06 13:27:44 +01:00
Marek Wolan
33f6f8bc34 Updated rewards type description in docs 2023-07-06 12:56:24 +01:00
Marek Wolan
dd8593e489 Change reward to float and divide by 10000 2023-07-06 12:52:14 +01:00
Czar Echavez
bb9bfc50a5 #1386: remove setting of global seed + running pre-commit checks 2023-07-06 12:10:26 +01:00
Chris McCarthy
a35c363345 #1386 - Updated tests in test_seeding_and_deterministic_session.py to use TempPrimaiteSession.
- Added test_seeded_learning test and test_deterministic_evaluation test.
- Passed config values seed and deterministic to ppo agent
- Dropped deterministic override in evaluate functions
- TempPrimaiteSession now writes files to a UUID folder rather than datetime
- Added seed to Ray RLlib agent setup in rllib.py
- Added seed to SB3 agent setup in sb3.py
2023-07-06 11:35:44 +01:00
SunilSamra
3ff081ea71 1566 - added train_episodes, train_steps, eval_episodes and eval_steps to training_config_main.yaml 2023-07-06 11:12:51 +01:00
SunilSamra
7a02661c66 901 - changed how acl rules are added to access control list and added structure to AccessControlList observation 2023-07-06 11:07:21 +01:00
Marek Wolan
30b08fd48b Rescaled default rewards by a factor of 1/10000 2023-07-06 10:51:34 +01:00
Marek Wolan
d9394d274d Updated documentation 2023-07-06 10:34:27 +01:00
Marek Wolan
b9549497d2 Removed duplicated function definitions 2023-07-06 10:23:14 +01:00
Chris McCarthy
f92d2fb65d temp 2023-07-06 10:07:54 +01:00
Marek Wolan
ead02ed691 Updated docstrings 2023-07-05 16:46:23 +01:00
Marek Wolan
013dcb94a8 Add docstrings and type hints. 2023-07-05 16:19:43 +01:00
Marek Wolan
d598ffaa65 Merge branch 'bugfix/1587-hardcoded-agent' into feature/1575-docstring-param-desc 2023-07-05 15:22:13 +01:00
Czar Echavez
0068092d8b #1386: remove unneeded configs + setting the seed globally + temp test 2023-07-05 15:02:41 +01:00
Marek Wolan
8f4e8bf538 typo 2023-07-05 14:50:03 +01:00
Marek Wolan
5f98c9b1bd Fix minor typos in docstrings 2023-07-05 14:13:43 +01:00
Marek Wolan
376ff9f597 Imported ADSP function for ACL 2023-07-05 14:10:52 +01:00
Marek Wolan
0664389bdc Changed hardcoded agent helper for new obs space 2023-07-05 13:58:46 +01:00
Czar Echavez
b0c83d7148 #1386: fix saving of agent 2023-07-05 11:41:18 +01:00
SunilSamra
35045f4842 901 - merged with dev 2023-07-05 11:34:15 +01:00
Marek Wolan
247136ed6d Merge branch 'feature/1572-fix-docs-formatting' of https://dev.azure.com/ma-dev-uk/PrimAITE/_git/PrimAITE into feature/1572-fix-docs-formatting 2023-07-05 10:14:20 +01:00
Marek Wolan
fa6dbd8338 Move class docstrings out of init function. 2023-07-05 10:14:16 +01:00
Marek Wolan
d7bf90e6f4 Updated access_control_list.py 2023-07-05 09:00:41 +00:00
Marek Wolan
b81c29d46e Update some param descriptions for hardcoded agent 2023-07-05 09:54:50 +01:00
Marek Wolan
24a4f96ed0 Add blank lines at the end of file. 2023-07-05 09:22:49 +01:00
Marek Wolan
17b5c6bf92 Add missing module level docstrings. 2023-07-05 09:19:58 +01:00
SunilSamra
766ee9624a 901 - updated observations.py to change and add new mapping of ACL rules to represent no rule present in list 2023-07-05 09:08:03 +01:00
Czar Echavez
818d64f330 #1386: fix bug with agent zip file not being saved after run 2023-07-04 16:30:31 +01:00
Marek Wolan
544d8777ea add module level docstrings 2023-07-04 13:11:06 +01:00
Marek Wolan
3aacd71a5e remove primaite dependencies as it's autogenerated 2023-07-04 11:57:10 +01:00
Marek Wolan
5db8bd7c4c Resolve remaining build warnings for docs 2023-07-04 11:34:36 +01:00
Marek Wolan
9244c160b1 Format docstrings 2023-07-04 11:11:52 +01:00
Marek Wolan
91273b2f99 fix formatting on Observation docs 2023-07-04 10:57:00 +01:00
Marek Wolan
2bcaf79a51 Add Favicon 2023-07-04 10:55:07 +01:00
Czar Echavez
c7de7bf21b Merge branch 'dev' into feature/1386-enable-a-repeatable-or-deterministic-baseline-test 2023-07-04 09:41:07 +01:00
Christopher McCarthy
6006f022a1 Merged PR 101: Integrate ADSP RLlib and use PrimaiteSession for running between agent frameworks
## Summary
* Brought over the RLlib, hardcoded agents, and simple agents from ADSP 1.1.0. This opened a can of worms... ADSP got their stuff working in notebooks (***_stares at data scientists!_** 😂) but hadn't integrated it into the PrimAITE package or made the other PrimAITE functionality work with it.
* RLlib agents have been fully integrated with the wider PrimAITE package. This was done by:
  * The creation of an `AgentSessionABC` and `HardCodedAgentSessionABC` classes.
  * `SB3Agent` and `RLlibAgent` classes then inherited from `AgentSessionABC`.
  * The ADSP hardcoded agents were integrated into subclasses of `HardCodedAgentSessionABC`.
  * The random and dummy agents were also integrated into subclasses of `HardCodedagentSessionABC`.
  * A set of session output directories were created and managed by the agent session to enable consistent storage of session outputs in a common format regardless of the agent type.
  * The main config was rafactored so that it had
    * **agent_framework** - To identify whether SB3, RLlib, or Custom.
    * **agent_identifier** - To identify whether PPO, A2C, hardcoded, random, or dummy.
    *  **deep_learning_framework** - To identify which framework to use for RLlib.
* Transactions have been overhauled to simplify the process. It also means that they're written in real time so they're not lost if the agent crashes.
* Tests completely overhauled to use `PrimaiteSession`, or at least a test subclass, `TempPrimaiteSession`. It's temp because it uses temp directory rather than main primaite session directory, and it cleans up after itself.
* All the crap removed from `main.py` and made it so that it just runs `PrimaiteSession`.

Now this is where I went off on a tangent...
* CLI added to just make my life and everyone else's life easier.
* Primaite app config added to hold things like logging format, levels etc.
* A `primaite.data_viz.session_plots` module added so that the average reward per episode for each session is plotted and saves for each session (this helped while we were testing and bug fixing).

## Test process
* All tests use `TempPrimaiteSession`, which uses `PrimaiteSession`.
* I still need to write a tests that runs the RLlib, hardcoded, and random/dummy agents. I'll do that now while this is being reviewed.

## Still to do
* Update docs. I'm getting this PR up now so we can get it in to make use of the features. I'll get the docs updated today either on this branch or another branch (depending on how long this review takes).

## Checklist
- [X] This PR is linked to a **work item**
- [X] I have performed **self-review** of the code
- [X] I have written **tests** for any new functionality added with this PR
- [ ] I have updated the **documentation** if this PR changes or adds functionality
- [X] I have run **pre-commit** checks for code style

Related work items: #917, #1563
2023-07-04 08:08:31 +00:00
Chris McCarthy
27e22edaf1 #917 - Reinstalled the pre-commit hook 2023-07-03 20:40:38 +01:00
Chris McCarthy
e271a28bf0 #917 - Synced with dev and integrated the new observation space 2023-07-03 20:36:21 +01:00
Chris McCarthy
1716786441 Merge remote-tracking branch 'origin/dev' into feature/917_Integrate_with_RLLib
# Conflicts:
#	src/primaite/config/_package_data/training/training_config_main.yaml
#	src/primaite/environment/primaite_env.py
#	src/primaite/main.py
#	src/primaite/transactions/transaction.py
#	src/primaite/transactions/transactions_to_file.py
2023-07-03 19:51:52 +01:00
Chris McCarthy
c36ddfa03f #917 - Synced with dev (at the point of random red agent) 2023-07-03 17:25:21 +01:00
Chris McCarthy
72b0050b1b Merge remote-tracking branch 'origin/feature/917_Integrate_with_RLLib' into feature/917_Integrate_with_RLLib 2023-07-03 17:12:03 +01:00
Marek Wolan
adf70b7d04 Merged PR 103: Change build pipeline to enable installing from wheel on windows
## Summary
Just splits the install primaite step into two depending if agent is using windows or not.

## Test process
Ran a build successfully.

## Checklist
- [ ] This PR is linked to a **work item**
- [ ] I have performed **self-review** of the code
- [ ] I have written **tests** for any new functionality added with this PR
- [ ] I have updated the **documentation** if this PR changes or adds functionality
- [ ] I have run **pre-commit** checks for code style
2023-07-03 16:10:09 +00:00
Marek Wolan
0fcc5c0179 Updated azure-ci-build-pipeline.yaml 2023-07-03 16:02:59 +00:00
Czar Echavez
409743dee9 Merge branch 'dev' into feature/1386-enable-a-repeatable-or-deterministic-baseline-test 2023-07-03 16:56:44 +01:00
Marek Wolan
2a481bc57c Merged PR 100: Flatten observation spaces and improve transactions for observations
## Summary
*Replace this text with an explanation of what the changes are and how you implemented them. Can this impact any other parts of the codebase that we should keep in mind?*

## Test process
I ran some training sessions to ensure that the outputted transaction list has the correct data and headers. I was also able to verify that the agent is able to train with observation spaces containing multiple components.

I trained an agent on laydown 3 with NODE_LINK_TABLE both as normal and flattened spaces and the agent learned in both instances.
![image.png](https://dev.azure.com/ma-dev-uk/b50a61ee-86c4-48bc-9a0b-a67645ba12ee/_apis/git/repositories/2825053e-bd3b-45b2-8680-1281809eefa2/pullRequests/100/attachments/image.png)  ![image (2).png](https://dev.azure.com/ma-dev-uk/b50a61ee-86c4-48bc-9a0b-a67645ba12ee/_apis/git/repositories/2825053e-bd3b-45b2-8680-1281809eefa2/pullRequests/100/attachments/image%20%282%29.png)
## Checklist
- [x] This PR is linked to a **work item**
- [x] I have performed **self-review** of the code
- [ ] I have written **tests** for any new functionality added with this PR
- [ ] I have updated the **documentation** if this PR changes or adds functionality
- [x] I have run **pre-commit** checks for code style

Related work items: #1558
2023-07-03 15:54:00 +00:00
Chris McCarthy
d55225dd41 Merge remote-tracking branch 'origin/dev' into feature/917_Integrate_with_RLLib
# Conflicts:
#	src/primaite/config/_package_data/training/training_config_main.yaml
#	src/primaite/environment/primaite_env.py
2023-07-03 15:07:09 +01:00
Marek Wolan
93881e5d2c Merge remote-tracking branch 'origin/dev' into feature/1558-flatten-spaces 2023-07-03 15:03:10 +01:00
Marek Wolan
8a95e66b63 Merge branch 'dev' into feature/1558-flatten-spaces 2023-07-03 15:01:56 +01:00
Marek Wolan
9964ac4cea Updated azure-ci-build-pipeline.yaml 2023-07-03 13:36:33 +00:00
Czar Echavez
9ff85207c6 Merged PR 102: 1522 Red Agent random behaviour
## Summary
Ported over ADSP changes regarding the randomised red agent.
Red agent currently only works on laydown configs which contain links.

Each episode generates random red agent instructions

## Test process
Written a test that ensures that the random red agent produces random red agent instructions

| Random red agent | Laydown                | Agent Identifier | Run 1                                                                              | Run 2                                                                              | Run 3                                                                              |
|------------------|------------------------|------------------|------------------------------------------------------------------------------------|------------------------------------------------------------------------------------|------------------------------------------------------------------------------------|
| NONE             | Very Basic (Laydown 3) | A2C              | ![image (4).png](https://dev.azure.com/ma-dev-uk/b50a61ee-86c4-48bc-9a0b-a67645ba12ee/_apis/git/repositories/2825053e-bd3b-45b2-8680-1281809eefa2/pullRequests/102/attachments/image%20%284%29.png)  | ![image (8).png](https://dev.azure.com/ma-dev-uk/b50a61ee-86c4-48bc-9a0b-a67645ba12ee/_apis/git/repositories/2825053e-bd3b-45b2-8680-1281809eefa2/pullRequests/102/attachments/image%20%288%29.png)  | ![image (9).png](https://dev.azure.com/ma-dev-uk/b50a61ee-86c4-48bc-9a0b-a67645ba12ee/_apis/git/repositories/2825053e-bd3b-45b2-8680-1281809eefa2/pullRequests/102/attachments/image%20%289%29.png)  |
| RANDOM           | Very Basic (Laydown 3) | A2C              | ![image (5).png](https://dev.azure.com/ma-dev-uk/b50a61ee-86c4-48bc-9a0b-a67645ba12ee/_apis/git/repositories/2825053e-bd3b-45b2-8680-1281809eefa2/pullRequests/102/attachments/image%20%285%29.png)  | ![image (6).png](https://dev.azure.com/ma-dev-uk/b50a61ee-86c4-48bc-9a0b-a67645ba12ee/_apis/git/repositories/2825053e-bd3b-45b2-8680-1281809eefa2/pullRequests/102/attachments/image%20%286%29.png)  | ![image (7).png](https://dev.azure.com/ma-dev-uk/b50a61ee-86c4-48bc-9a0b-a67645ba12ee/_apis/git/repositories/2825053e-bd3b-45b2-8680-1281809eefa2/pullRequests/102/attachments/image%20%287%29.png)  |
| NONE             | Very Basic (Laydown 3) | PPO              | ![image (10).png](https://dev.azure.com/ma-dev-uk/b50a61ee-86c4-48bc-9a0b-a67645ba12ee/_apis/git/repositories/2825053e-bd3b-45b2-8680-1281809eefa2/pullRequests/102/attachments/image%20%2810%29.png) | ![image (11).png](https://dev.azure.com/ma-dev-uk/b50a61ee-86c4-48bc-9a0b-a67645ba12ee/_apis/git/repositories/2825053e-bd3b-45b2-8680-1281809eefa2/pullRequests/102/attachments/image%20%2811%29.png) | ![image (12).png](https://dev.azure.com/ma-dev-uk/b50a61ee-86c4-48bc-9a0b-a67645ba12ee/_apis/git/repositories/2825053e-bd3b-45b2-8680-1281809eefa2/pullRequests/102/attachments/image%20%2812%29.png) |
| RANDOM           | Very Basic (Laydown 3) | PPO              ...
2023-07-03 13:09:32 +00:00
Marek Wolan
fa231057a8 Updated azure-ci-build-pipeline.yaml 2023-07-03 12:44:01 +00:00
Marek Wolan
4b56e7bd3a Updated azure-ci-build-pipeline.yaml 2023-07-03 12:40:02 +00:00
Marek Wolan
0a5d25fe01 Add windows build option 2023-07-03 12:37:08 +00:00
Czar Echavez
a7913487b8 #1522: create_random_red_agent -> _create_random_red_agent + converting NodeStateInstructionRed into a dataclass 2023-07-03 13:36:14 +01:00
Czar Echavez
befd183b2c #1522: refactor red_agent_identifier -> random_red_agent so that it is a boolean + documentation 2023-07-03 12:18:58 +01:00
Chris McCarthy
9999ed9b00 #917 - Added Windows and MacOS to build pipeline. Updated so that runs only Python 3.8 and 3.10 (middle version not required) 2023-07-03 12:03:36 +01:00
Chris McCarthy
676bca70bb Merge remote-tracking branch 'origin/dev' into feature/917_Integrate_with_RLLib
# Conflicts:
#	tests/test_reward.py
2023-07-03 11:59:16 +01:00
Christopher McCarthy
7fe46ef99c Apply suggestions from code review 2023-07-03 10:47:26 +00:00
Czar Echavez
6b4530bded #1522: run pre-commit 2023-07-03 10:08:25 +01:00
Czar Echavez
22849c18da Merge branch 'dev' into feature/1522-Random-Red-Agent-Behaviour 2023-07-03 09:59:25 +01:00
Czar Echavez
68457aa0b2 #1522: added a check for existing links in laydown + test that checks if red agent instructions are random 2023-07-03 09:46:52 +01:00
Sunil Samra
78751de717 Merged PR 93: 1555 - updated doc-string to make test understanding easier
## Summary
Changed doc-string of test_reward.py to reflect the new test and what it is trying to do rather than the old outdated one.

## Test process
NA - no logic changes

## Checklist
- [X] This PR is linked to a **work item**
- [X] I have performed **self-review** of the code
- [X] I have written **tests** for any new functionality added with this PR
- [X] I have updated the **documentation** if this PR changes or adds functionality
- [X] I have run **pre-commit** checks for code style

1555 - updated doc-string to make test understanding easier

Related work items: #1555, #1556
2023-07-03 08:10:17 +00:00
Marek Wolan
046937d838 Apply suggestions from code review 2023-07-03 08:00:51 +00:00
SunilSamra
b3d9a6e79d 901 - merged with changes made to dev 2023-07-03 08:17:52 +01:00
SunilSamra
5f2e8b547a Merge remote-tracking branch 'origin/dev' into feature/1555-update-test-reward-doc-string 2023-07-03 08:10:28 +01:00
Chris McCarthy
06d5004695 #917 - Dropped VerboseLevel in enums.py and changed OutputVerboseLevel to SB3OutputVerboseLevel 2023-06-30 17:09:50 +01:00
Chris McCarthy
e11fd2ced4 #917 - Fixed the RLlib integration
- Dropped support for overriding the num_episodes and num_steps at the agent level. It's just not needed and will add complexity when overriding and writing output files.
2023-06-30 16:52:57 +01:00
Marek Wolan
7e6fe2759b Fix flattening when there are no components. 2023-06-30 15:43:15 +01:00
Marek Wolan
d86489a9c2 revert unnecessary changes. 2023-06-30 13:16:30 +01:00
Chris McCarthy
00185d3dad #917 - Fixed primaite_config.yaml issue in cli.py
- Added kaleido to deps in pyproject.toml
2023-06-30 11:40:26 +01:00
Marek Wolan
09883e13c2 Update docs 2023-06-30 10:44:04 +01:00
Marek Wolan
99ba05c6ee Remove redundant cols from transactions 2023-06-30 10:41:56 +01:00
Czar Echavez
4e1e0ef4b4 #1522: remove numpy randomisation + added random red agent config 2023-06-30 10:37:23 +01:00
Chris McCarthy
cf09202e96 #917 - Added tensorflow to main deps for RLlib.
- Dropped support for Python 3.11 due to not supported on Ray RLlib.
- Made release pipeline only run once as we're now no longer using pure path wheels.
2023-06-30 10:24:59 +01:00
Marek Wolan
fb48f75adf Remove temporary file 2023-06-30 09:54:34 +01:00
Chris McCarthy
7b1f889415 #917 - Integrated the PrimaiteSession into all tests.
- Ran a full pre-commit hook and thus encountered tons of fixes required
2023-06-30 09:08:13 +01:00
Marek Wolan
c9f58fdb2a Fix observation representation in transactions 2023-06-29 15:26:07 +01:00
Czar Echavez
10e432eb01 #1522: fixing create random red agent function 2023-06-29 15:03:11 +01:00
Czar Echavez
15b3bad5d4 Merge branch 'dev' into feature/1522-Random-Red-Agent-Behaviour 2023-06-29 14:17:41 +01:00
Chris McCarthy
b6d93ad33f #917 - Began the process of reloading existing agents into the session 2023-06-28 19:54:00 +01:00
Chris McCarthy
4866722911 #917 - Overhauled transaction and mean reward writing.
- Separated out learning outputs from evaluation outputs
2023-06-28 16:34:00 +01:00
Chris McCarthy
a9ebfd7917 #917 - Synced with dev and added better logging 2023-06-28 12:01:01 +01:00
Marek Wolan
e086d419ad Attempt to add flat spaces 2023-06-28 11:07:45 +01:00
Chris McCarthy
edab1a393d Merge remote-tracking branch 'origin/dev' into feature/917_Integrate_with_RLLib
# Conflicts:
#	src/primaite/config/training_config.py
#	src/primaite/main.py
2023-06-28 10:11:03 +01:00
Marek Wolan
d28db68c02 Merged PR 95: Apply precommits and add precommit to build pipeline
## Summary
The code changes are purely cosmetic- the result of applying pre-commit to all our files. I also added a pre-commit step to the build pipeline to reject non-conforming PRs

## Test process
I saw that the build pipeline passes with this new step.

## Checklist
- [ ] This PR is linked to a **work item**
- [x] I have performed **self-review** of the code
- [ ] I have written **tests** for any new functionality added with this PR
- [ ] I have updated the **documentation** if this PR changes or adds functionality
- [x] I have run **pre-commit** checks for code style

Related work items: #1557
2023-06-28 08:14:49 +00:00
SunilSamra
9623b1450a 1555 - added specific steps to doc string 2023-06-27 16:59:43 +01:00
SunilSamra
f368aae982 Merge remote-tracking branch 'origin/dev' into feature/1555-update-test-reward-doc-string 2023-06-27 16:55:00 +01:00
Marek Wolan
3e620c5633 Merged PR 94: Fix ier reward calculation
## Summary
Logic error with negation of booleans.

## Test process
Run with debug logging to verify that no longer getting warnings about reference IERS being blocked.

## Checklist
- [x] This PR is linked to a **work item**
- [x] I have performed **self-review** of the code
- [ ] I have written **tests** for any new functionality added with this PR
- [ ] I have updated the **documentation** if this PR changes or adds functionality
- [x] I have run **pre-commit** checks for code style

Fix ier reward calculation

Related work items: #1554
2023-06-27 15:10:19 +00:00
Chris McCarthy
20b65ae9ab Merge remote-tracking branch 'origin/bugfix/1554-fix-not-learning-iers' into feature/917_Integrate_with_RLLib 2023-06-27 15:56:56 +01:00
Marek Wolan
afe5bf8fe8 Merge branch 'dev' into feature/build-pipeline-precommit 2023-06-27 15:49:49 +01:00
Marek Wolan
349a18a4eb Fix ier reward calculation 2023-06-27 15:27:56 +01:00
Czar Echavez
be041f5e5c Merge branch 'dev' into feature/1386-enable-a-repeatable-or-deterministic-baseline-test 2023-06-27 14:16:10 +01:00
SunilSamra
7bed0d59cb Merge remote-tracking branch 'origin/dev' into feature/1555-update-test-reward-doc-string 2023-06-27 14:09:36 +01:00
Marek Wolan
33f7e9f506 Add pre-commit 2023-06-27 13:07:54 +00:00
Marek Wolan
f71d4488b8 Merged PR 92: Fix reference IERs
## Summary
As per the ticket and James's explanation, there are now separate reference IERs which are used for the reference environment.

## Test process
I verified that the training can occur.
![image.png](https://dev.azure.com/ma-dev-uk/b50a61ee-86c4-48bc-9a0b-a67645ba12ee/_apis/git/repositories/2825053e-bd3b-45b2-8680-1281809eefa2/pullRequests/92/attachments/image.png)

## Checklist
- [x] This PR is linked to a **work item**
- [x] I have performed **self-review** of the code
- [n/a] I have written **tests** for any new functionality added with this PR
- [n/a] I have updated the **documentation** if this PR changes or adds functionality
- [x] I have run **pre-commit** checks for code style

Fix reference IERs

Related work items: #1554
2023-06-27 13:07:39 +00:00
Marek Wolan
a3e50293b7 Add pre-commits to build pipeline 2023-06-27 12:07:33 +00:00
Marek Wolan
beae1e5c4f Cosmetic changes to satisfy pre-commit 2023-06-27 13:06:10 +01:00
Marek Wolan
de91a50581 Improve readability 2023-06-27 12:56:15 +01:00
Marek Wolan
cdeb6abf60 More descriptive debug msg 2023-06-27 12:44:42 +01:00
SunilSamra
36f1dff9b8 1555 - updated doc-string to make test understanding easier 2023-06-27 12:27:57 +01:00
Marek Wolan
dc43e5dc15 rename to prevent confusion 2023-06-27 10:45:45 +00:00
SunilSamra
913c244c64 901 - fixed test_single_action_space.py to reflect new acl structure and added new acl_implicit_rule class attribute 2023-06-27 11:43:33 +01:00
Marek Wolan
3774fb8319 apply pre-commits 2023-06-27 11:20:18 +01:00
Marek Wolan
cd991a7d61 Fix reference IERs 2023-06-27 11:10:21 +01:00
Czar Echavez
2e2b098a3c #1386: Apply suggestions from code review - make seed an optional variable 2023-06-23 07:57:31 +00:00
Brian Kanyora
57315a6789 feature\1522:
Create random red agent behaviour.
2023-06-22 15:34:13 +01:00
Chris McCarthy
8f6e930ba2 #917 - Updated main config 2023-06-22 14:10:38 +01:00
Chris McCarthy
dce6fe55ee #917 - Got things working'ish 2023-06-20 22:29:46 +01:00
Chris McCarthy
7b0f47d6f8 #917 -Finished integrating all agents to either train (policy agents) or evaluate (hard-coded agents). Still some fixing up to do, tidying up, loading etc. also docs. But this is all now working. 2023-06-20 16:06:55 +01:00
SunilSamra
9c17b54073 901 - changed ACL instantiation and changed acl t private _acl (list not dict) attribute, added laydown_ACL.yaml for testing, fixed encoding of acl rules to integers for obs space, added ACL position to node action space and added generic test where agents adds two ACL rules. 2023-06-20 11:47:20 +01:00
Czar Echavez
65024320dd #1386: fix README.md 2023-06-20 11:22:29 +01:00
Czar Echavez
99399cbda6 #1386: added documentation + dealing with pre-commit checks 2023-06-20 11:19:05 +01:00
Czar Echavez
9fb30ffe1b #1386: added the ability to set deterministic and seeding RNG when training and evaluating + the fix provided in #1535 2023-06-20 10:41:30 +01:00
Chris McCarthy
10c94954a5 #917 - Almost there. All output files being writen for SB3/RLLIB PPO & A2C. Just need to bring in the hardcoded agents then update the testa and docs. 2023-06-19 21:53:25 +01:00
Chris McCarthy
3670f16766 #917 - Integrated both SB3 and RLlib agents into PrimaiteSession 2023-06-19 20:27:08 +01:00
Chris McCarthy
c09874edbe #917 - Got RLlib fully training in PrimAITE. Started integrating the the other agents into the Session class 2023-06-18 22:40:56 +01:00
Chris McCarthy
31eb36c75a #917 - started working on the Agent abstract classes and sub-classes 2023-06-15 09:48:44 +01:00
SunilSamra
52d759bcd9 901 - started testing for observation space 2023-06-13 16:23:32 +01:00
SunilSamra
53a7001963 901 - added max_acl_rules, implicit_acl_rule and apply_implicit rule to main_config, changed observations.py for ACLs to match the action space for ACLs, added position of acl rule to ACL action type 2023-06-13 14:51:55 +01:00
SunilSamra
33251fcc89 901 - fixed test_acl.py tests 2023-06-13 10:01:55 +01:00
SunilSamra
f275f3e9d7 901 - added changes back to ticket 2023-06-13 09:45:45 +01:00
Chris McCarthy
40686031e6 temp commit 2023-06-13 09:42:54 +01:00
SunilSamra
ce5d38a1cd 901 - merged dev into my branch 2023-06-13 08:54:33 +01:00
Christopher McCarthy
dc0349c37b Merged PR 81: #915 Packaging & Deployment
## Summary
- Created app dirs and set as constants in the top-level init.
- Renamed _config_values_main to training_config.py and renamed the ConfigValuesMain class to TrainingConfig.
- Moved training_config.py to src/primaite/config/training_config.py
- Renamed all training config yaml file keys to make creating an instance of TrainingConfig easier.
- Moved action_type and num_steps over to the training config.
- Decoupled the training config and lay down config.
- Refactored main.py so that it can be ran from CLI and can take a training config path and a lay down config path.
- Refactored all outputs so that they save to the session dir.
- Added some necessary setup scripts that handle creating app dirs, fronting example config files to the user, fronting demo notebooks to the user, performing clean-up in between installations etc.
- Added functions that attempt to retrieve the file path of users example config files that have been fronted by the primaite setup.
- Added logging config and a getLogger function in the top-level init.
- Refactored all logs entries logged to use a logger using the primaite logging config.
- Added basic typer CLI for doing things like setup, viewing logs, viewing primaite version, running a basic session.
- Updated test to use new features and config structures.
- Made tests log to temp directory
- typer==0.9.0 added to pyproject.toml
- Refactored documentation and included APi docs, dependencies.
- Make files now re-build autosummary and deps file.
- Added typer and platformdirs to deps in pyproject.toml.
- Made root_is_pure = True in setup.py as platform/python specific wheels don't need to be built but the option is there should we need to.

## Test process
- Added an e2e test for primaite.main.run func.
- Added legacy config file conversion tests
- added

## Checklist
- [X] This PR is linked to a **work item**
- [X] I have performed **self-review** of the code
- [X] I have written **tests** for any new functionality added with this PR
- [X] I have updated the **documentation** if this PR changes or adds functionality
- [X] I have run **pre-commit** checks for code style

Related work items: #915
2023-06-12 18:17:46 +00:00
Chris McCarthy
9563a8a121 Synced with dev 2023-06-12 16:59:31 +01:00
Chris McCarthy
fc6ec69dee Merge remote-tracking branch 'origin/dev' into feature/915_PRI-31_Packaging_Deployment
# Conflicts:
#	docs/source/about.rst
#	src/primaite/main.py
#	src/primaite/nodes/node.py
2023-06-12 16:42:26 +01:00
Brian Kanyora
173e6d77a3 Merged PR 75: Fixing the functionality of resetting a node
## Summary:
Split the ticket into two task

Task 1: Fixed the resetting operating state to set compromised or overwhelmed services or operating system back to a good state. Added a reset count that switches the node into a good state.

Task 2: Created a "SHUTTING DOWN" operating state to last for a (configurable) and a "BOOTING" operating state to last for a (configurable).

## Test process
First test was to test the reset changes the node to a good state when its set to a COMPROMISED state. The last two test makes sure that the node boots and shutdowns correctly.

## Checklist
- [x] This PR is linked to a **work item**
- [x] I have performed **self-review** of the code
- [x] I have written **tests** for any new functionality added with this PR
- [x] I have updated the **documentation** if this PR changes or adds functionality
- [x] I have run **pre-commit** checks for code style

Related work items: #898, #1438
2023-06-12 15:21:47 +00:00
Chris McCarthy
4596687e35 Merge remote-tracking branch 'origin/dev' into feature/898-Fix-the-functionality-of-resetting-a-node 2023-06-12 14:20:16 +01:00
Chris McCarthy
4c4f351534 #951 - Can not view and change the log level from the cli.
- Fixed write transaction issue in transactions_to_file.py
2023-06-09 22:23:45 +01:00
Christopher McCarthy
3016f4b984 Apply suggestions from code review 2023-06-09 20:31:12 +00:00
SunilSamra
ed8b53f5ef 901 - added logic to add acls to list (needs more logic adding to it) 2023-06-09 16:56:42 +01:00
Chris McCarthy
149a534851 #915 - Annotated logs func in cli.py to take -n.
- Fixed entry point on main.py
- Commented out the print reward line in step func of primaite_env.py.
- Added jupyterlab==3.6.1 to pyproject.toml
2023-06-09 16:44:49 +01:00
Chris McCarthy
1a7d158d77 #915 - Force app dir creation before config file sink 2023-06-09 16:04:56 +01:00
Chris McCarthy
86b813afa1 #915 - Synced with dev 2023-06-09 15:49:48 +01:00
SunilSamra
f7b0617dc3 901 - changed name of enum in enums.py and added class attriubutes in access_control_list.py 2023-06-09 15:45:13 +01:00
SunilSamra
33127abcc3 901 - added ACL list to observations.py as its own observation space with the ACL attributes and the position of the ACL rule in the ACL list, added ImplicitFirewallRule to enums.py and added acl_implicit_rule, max_acl_list to primaite_env.py 2023-06-09 15:17:20 +01:00
Chris McCarthy
2fccbbd9df Merge remote-tracking branch 'origin/dev' into feature/915_PRI-31_Packaging_Deployment
# Conflicts:
#	docs/source/about.rst
#	docs/source/config.rst
#	src/primaite/common/config_values_main.py
#	src/primaite/environment/primaite_env.py
#	src/primaite/main.py
#	tests/config/multidiscrete_obs_space_laydown_config.yaml
#	tests/config/obs_tests/laydown.yaml
#	tests/conftest.py
#	tests/test_observation_space.py
2023-06-09 13:41:05 +01:00
Chris McCarthy
3a5d982991 #915 - Synced with dev to bring in changes from #898 2023-06-09 13:11:14 +01:00
SunilSamra
f989deb198 901 - changed AccessControlList in access_control_list.py from a dict to a list 2023-06-09 11:25:45 +01:00
Marek Wolan
495357a4bc Merged PR 69: Configurable observation space.
## Summary
This PR implements a new module called `observations` within `primaite.environment`.

The module is able to keep track of the observation space and to generate observations for the blue agent. It builds the observation space from components. Each component can be configured by supplying parameters at instantiation. For example, the Link Traffic Levels component lets the user customise how many levels there should be.

Note: If a space contains multiple components, they are combined into a 'gym.spaces.Tuple' Space. This is not compatible with some learning agents so we may need to add the options to flatten the observation space.

## Test process
I was able to run the main script with a single-component obs space. I also wrote several unit and integration tests for the new functionality.

## Checklist
- [x] This PR is linked to a **work item**
- [x] I have performed **self-review** of the code
- [x] I have written **tests** for any new functionality added with this PR
- [x] I have updated the **documentation** if this PR changes or adds functionality
- [x] I have run **pre-commit** checks for code style

If you review this, please check the linked tickets and make sure you agree that this PR addresses them fully.

Related work items: #886, #924, #1468, #1469
2023-06-09 09:52:47 +00:00
Chris McCarthy
6c2c95b329 Merge remote-tracking branch 'origin/dev' into feature/915_PRI-31_Packaging_Deployment
# Conflicts:
#	tests/conftest.py
#	tests/test_observation_space.py
#	tests/test_reward.py
2023-06-09 10:35:14 +01:00
Christopher McCarthy
ec7306ec39 Apply suggestions from code review 2023-06-09 09:31:01 +00:00
Marek Wolan
a597cf95d7 Fix obs tests with new changes 2023-06-09 10:28:24 +01:00
Marek Wolan
00a30bcb7a Merge remote-tracking branch 'origin/dev' into feature/1468-observations-class 2023-06-09 09:01:54 +01:00
Sunil Samra
0c962a7576 Merged PR 76: 893 - Combine NODE and ACL action spaces into single action space
## Summary
To do this, I have altered `primaite_env` to add the changes from ADSP branch for implementing the `ANY` action space.

It impacts `NODE` and `ACL` action spaces in `primaite_env.py` as all three of them are now discrete action spaces, using dictionary keys to represent different valid actions a node can take on each step.

Previously they were multi-discrete where a single action would look like this `[1,2,1,0]`.

Now an action looks like this, a dictionary entry `{.. 5: [1,2,1,0] ... }` whereby the new action is `5` for example.

It changes the `enums.py` where I added the `ANY` into `ActionType`.

I have also added a package from the ADSP branch agents to add the file utils.py. The file contains functions used by primaite_env.py to decide and check valid actions a node can take and removes the ones which are unnecessary and invalid. This is done for all three types, `NODE`, `ACL` and `ANY`.

## Test process
I have written an unit test in `test_single_action_space.py` which checks the new action space for an `ANY` laydown config has both types of actions in the `action_space` dictionary stored by the environment.

I have written an integration tests to check an agent is carrying out both `NODE` and `ACL` actions in a single episode, where I have hard coded the agent to do two specific things on two different steps.
On one step, I tell the `computer_1` node to turn off one of the nodes and on the other step it creates an ACL rule denying communication between `computer_1` and `switch_1` nodes.

## Checklist
- [X] This PR is linked to a **work item**
- [X] I have performed **self-review** of the code
- [X] I have written **tests** for any new functionality added with this PR
- [X] I have updated the **documentation** if this PR changes or adds functionality
- [X] I have run **pre-commit** checks for code style

Related work items: #893, #1429
2023-06-09 07:28:31 +00:00
Chris McCarthy
5558750f13 #915 - Refactored documentation and included APi docs, dependencies.
- make files now re-build autosummary and deps file.
- Added typer and platformdirs to deps in pyproject.toml.
- Made root_is_pure = True in setup.py as platform/python specific wheels don't need to be built but the option is there should we need to.
-
Added an e2e test for primaite.main.run func.
2023-06-08 15:57:38 +01:00
Chris McCarthy
92334133c9 #915 - typer==0.9.0 added to pyproject.toml 2023-06-08 08:56:39 +01:00
Chris McCarthy
58186dc958 #915 - Ensured LOG_DIR is created so primaite package can be used to perform setup while still logging using primaite logs. 2023-06-08 08:49:06 +01:00
Chris McCarthy
bf9fcddaa3 #915 - Ensured primaite setup is carried out on devops pipelines that install primaite. 2023-06-08 08:39:00 +01:00
Chris McCarthy
c03dc8fd6b # 915 - Fixed issue in conftest.py where session_path and timestamp_str were not being passed to Primaite.
- Also now logging all test outputs to temp directory.
2023-06-07 22:57:37 +01:00
Chris McCarthy
98fc1e4c71 #915 - Created app dirs and set as constants in the top-level init.
- renamed _config_values_main to training_config.py and renamed the ConfigValuesMain class to TrainingConfig.
Moved training_config.py to src/primaite/config/training_config.py
- Renamed all training config yaml file keys to make creating an instance of TrainingConfig easier.
Moved action_type and num_steps over to the training config.
- Decoupled the training config and lay down config.
- Refactored main.py so that it can be ran from CLI and can take a training config path and a lay down config path.
- refactored all outputs so that they save to the session dir.
- Added some necessary setup scripts that handle creating app dirs, fronting example config files to the user, fronting demo notebooks to the user, performing clean-up in between installations etc.
- Added functions that attempt to retrieve the file path of users example config files that have been fronted by the primaite setup.
- Added logging config and a getLogger function in the top-level init.
- Refactored all logs entries logged to use a logger using the primaite logging config.
- Added basic typer CLI for doing things like setup, viewing logs, viewing primaite version, running a basic session.
- Updated test to use new features and config structures.
- Began updating docs. More to do here.
2023-06-07 22:40:16 +01:00
Marek Wolan
4329c65211 Apply suggestions from code review. 2023-06-07 15:25:11 +01:00
SunilSamra
6089fb6950 893 - removed unnecessary functions from utils.py and changed single_action_space_fixed_blue_actions_main_config.yaml back to GENERIC agentIdentifier after PR comments 2023-06-07 14:39:52 +01:00
Marek Wolan
718cd8acd6 Merge remote-tracking branch 'origin/dev' into feature/1468-observations-class 2023-06-07 14:39:20 +01:00
Brian Kanyora
f9bb97300a feature\898:
Added doc strings
2023-06-07 11:09:00 +01:00
SunilSamra
281bb78612 893 - removed print statements for demonstration 2023-06-07 09:19:30 +01:00
SunilSamra
bb98900759 Merge remote-tracking branch 'origin/dev' into feature/893-node-acl-into-one-action-space 2023-06-07 09:18:24 +01:00
Marek Wolan
a8ce699df3 Merged PR 61: Fix minor logic errors in main script
This PR fixes some minor issues that I found in the main.py script. Namely:

1. The first observation was always all zeroes when using a generic agent. This is because the `update_environment_obs()` method is not called automatically and is only called by `env.reset()`.
2. The config yaml is never closed as the close function of the file reader was only referenced but never called.

Related work items: #1441
2023-06-06 15:02:40 +00:00
SunilSamra
e17e5ac4b9 893 - added new line for assert statements 2023-06-06 15:54:35 +01:00
Marek Wolan
91fb063797 Merge remote-tracking branch 'origin/dev' into bugfix/1441-main-py-minor-bugs 2023-06-06 15:50:35 +01:00
SunilSamra
0817a4cad3 893 - added consistent action for test_reward.py 2023-06-06 13:49:22 +01:00
SunilSamra
10585490fe 893 - 2023-06-06 13:47:07 +01:00
SunilSamra
d572c033e1 Merge remote-tracking branch 'origin/dev' into feature/893-node-acl-into-one-action-space 2023-06-06 13:46:01 +01:00
Marek Wolan
a85c653feb Merge remote-tracking branch 'origin/dev' into feature/1468-observations-class 2023-06-06 13:40:17 +01:00
Marek Wolan
3c9061ff8f Merged PR 62: Make reward calculation consider red POL
Check out the linked bug ticket to understand the issue.

The fix was very simple- just changing which variable is passed to the reward calculation funciton.

Related work items: #1442
2023-06-06 12:27:55 +00:00
SunilSamra
2e1bdf2361 893 - changed action in conftest.py back to sample of the environment action space 2023-06-06 13:23:08 +01:00
SunilSamra
efd0f6ed08 893 - returned config_values in conftest to move run_generic_set_actions into test_single_action_space.py 2023-06-06 13:21:04 +01:00
SunilSamra
7cef392f14 Merge remote-tracking branch 'origin/feature/893-node-acl-into-one-action-space' into feature/893-node-acl-into-one-action-space 2023-06-06 13:12:58 +01:00
SunilSamra
58a87ee0c8 893 - applied changes raised during PR 2023-06-06 13:12:28 +01:00
Sunil Samra
e0ed97be36 Apply suggestions from code review 2023-06-06 12:07:22 +00:00
SunilSamra
5add9d620c 893 - updated the docs to reflect changes made to action space 2023-06-06 11:57:04 +01:00
SunilSamra
a45f0d1979 Merge remote-tracking branch 'origin/dev' into feature/893-node-acl-into-one-action-space 2023-06-06 11:56:52 +01:00
SunilSamra
dc7be7d8e6 893 - set the action_space to NOTHING so test_reward.py passes and removed unnecessary test print statements 2023-06-06 11:10:38 +01:00
Brian Kanyora
5cfc46c4e4 feature\898:
Fixed the resetting operating state to set compromised or overwhelmed services or operating system back to a good state. Added a reset count that switches the node into a good state.
Created a "SHUTTING DOWN" operating state to last for a (configurable) and a "BOOTING" operating state to last for a (configurable).
Created a test file to test the reset changes the node to a good state when its set to a COMPROMISED state. The last two test tests makes sure that the node boots and shutdowns correctly.
Lastly, updated the docs file as well.
2023-06-06 11:03:43 +01:00
SunilSamra
1a7d629d5a 893 - added new tests to test action space size and node is completing both sets of actions in a single episode and created new main config 2023-06-06 11:00:41 +01:00
Brian Kanyora
4dd064cab8 feature\898:
Fixed the resetting operating state to set compromised or overwhelmed services or operating system back to a good state. Added a reset count that switches the node into a good state.
Created a "SHUTTING DOWN" operating state to last for a (configurable) and a "BOOTING" operating state to last for a (configurable).
Created a test file to test the reset changes the node to a good state when its set to a COMPROMISED state. The last two test tests makes sure that the node boots and shutdowns correctly.
Lastly, updated the docs file as well.
2023-06-05 23:59:32 +01:00
Brian Kanyora
7432b91f53 feature\898: 2023-06-02 16:13:16 +01:00
Brian Kanyora
b3ea1938bf Merge branch 'dev' into feature/898-Fix-the-functionality-of-resetting-a-node 2023-06-02 14:56:31 +01:00
Brian Kanyora
a1d7f9e57c feature\898: 2023-06-02 14:54:23 +01:00
Marek Wolan
bb42b4f55d Merge remote-tracking branch 'origin/dev' into bugfix/1442-reward-ignores-red-pol 2023-06-02 14:22:45 +01:00
Marek Wolan
6c94419bf3 Merge remote-tracking branch 'origin/dev' into feature/1468-observations-class 2023-06-02 13:41:49 +01:00
Marek Wolan
eaa192eeec Update docs with configurable obs space info 2023-06-02 13:23:03 +01:00
Marek Wolan
f14910ca96 Fix Link Traffic Levels observation encoding 2023-06-02 13:15:38 +01:00
Marek Wolan
73adfbb6dd Get observation tests passing 2023-06-02 13:08:11 +01:00
Marek Wolan
14096b3dd1 Add tests for observations 2023-06-02 12:59:01 +01:00
SunilSamra
66fdae5df1 893 - added test which shows the new action space has been created when ANY is selected in single_action_space_lay_down_config.yaml 2023-06-02 11:55:31 +01:00
SunilSamra
d0c11a14ed 893 - added ANY to enums.py 2023-06-02 09:51:15 +01:00
Marek Wolan
602bf9ba9a Edit configs for observation space 2023-06-02 09:10:53 +01:00
Marek Wolan
16777b30ad begin updating observations tests 2023-06-01 21:56:05 +01:00
Marek Wolan
ac31c996a7 Update docs page on observations 2023-06-01 21:42:34 +01:00
Marek Wolan
084112a2e4 Add docstrings to new observation code 2023-06-01 21:28:38 +01:00
Marek Wolan
d473794963 Let single-component spaces not use Tuple Spaces 2023-06-01 18:01:47 +01:00
Marek Wolan
0a804e714d Better Obs default handling 2023-06-01 17:50:18 +01:00
Marek Wolan
e43649a838 Fix trying to init obs before building network 2023-06-01 17:42:35 +01:00
Marek Wolan
bab6c27f06 Integrate obs handler with Primaite Env 2023-06-01 16:42:10 +01:00
SunilSamra
f72a80c9d2 1443 - added in print test statements 2023-06-01 16:27:25 +01:00
Marek Wolan
d351e575ae Integrate observation handler with components 2023-06-01 13:28:40 +01:00
Marek Wolan
4a09673e98 Merged PR 65: Add MultiDiscrete observation spaces
**Summary:**

This adds support for the MultiDiscrete observation spaces, the same as what exists in the ADSP branch. The observation space is now configurable in the same way as the action space- by selecting a config item within the laydown config yaml.
The 'box' option has the same behaviour as before.

**Test Process:**

I added two integration tests to ensure that creating the environment is possible with both types of observation space. I also checked that all existing unit tests run fine as long as I update the observation space in the yaml to box.

**Other comments:**
I also updated the documentation relating to observation spaces, please check if the explanation makes sense.

Related work items: #1463
2023-06-01 11:05:00 +00:00
Marek Wolan
fe32d83782 Merge branch 'feature/1463-multidiscrete-observation-option' into feature/1468-observations-class 2023-06-01 11:09:21 +01:00
Marek Wolan
357add05c7 More info in docstring 2023-06-01 11:02:10 +01:00
Marek Wolan
f0e1cb2138 Separate obs functions and provide docstrings 2023-06-01 10:57:11 +01:00
Marek Wolan
5e506b1499 Type hint init_observations return type 2023-06-01 09:57:33 +01:00
Marek Wolan
72f76705a9 Fix docstrings to use ReST format 2023-06-01 09:54:45 +01:00
Marek Wolan
2b2c7ad22d Improve observation space test 2023-06-01 09:45:46 +01:00
Marek Wolan
5201cf630f Merge remote-tracking branch 'origin/dev' into feature/1463-multidiscrete-observation-option 2023-06-01 09:02:48 +01:00
Marek Wolan
4108f8036c Start creating observations module 2023-05-31 17:03:53 +01:00
SunilSamra
ae2f4d472e 1443 - reverted changes made to observation space and added config files for testing 2023-05-31 14:11:15 +01:00
SunilSamra
7159d7c63b Merge remote-tracking branch 'origin/dev' into feature/893-node-acl-into-one-action-space 2023-05-31 13:28:39 +01:00
SunilSamra
20d13f42a2 1443 - added changes from ADSP to observation space in primaite_env.py 2023-05-31 13:15:25 +01:00
Marek Wolan
ec8aef36af Merged PR 66: Add a Pull Request template
I wanted to add this pull request template just as a checklist for everyone to ensure they add tests and update documentation.

Do you think it's necessary? Feel free to discuss in the comments of this PR or accept/reject the suggestion.

Related work items: #1467
2023-05-31 11:55:38 +00:00
Marek Wolan
581d137e1e Merge remote-tracking branch 'origin/dev' into bugfix/1441-main-py-minor-bugs 2023-05-31 11:07:06 +01:00
Marek Wolan
fb32043fa5 Merge remote-tracking branch 'origin/dev' into bugfix/1442-reward-ignores-red-pol 2023-05-31 11:04:00 +01:00
Marek Wolan
e15eb1d9c6 Revert unnecessary main.py change 2023-05-31 09:55:28 +00:00
Marek Wolan
41910797b5 Revert config changes by removing observations 2023-05-31 10:52:57 +01:00
Marek Wolan
3d4053b56a Add default observation type 2023-05-31 10:51:29 +01:00
Marek Wolan
317549225f Merge remote-tracking branch 'origin/dev' into feature/1463-multidiscrete-observation-option 2023-05-31 10:46:18 +01:00
SunilSamra
82371b210e Merge remote-tracking branch 'origin/dev' into feature/893-node-acl-into-one-action-space 2023-05-31 10:34:42 +01:00
Sunil Samra
c0f67af204 Merged PR 64: 1443-check-reward-function
In reward.py, the comparisons for the IF statements used when assigning config_values reward values currently compares the initial state to the reference state. However, it should be comparing the reference state (What it should be without any blue/red agent interference) and the final state (state after red and blue actions have taken affect).

Change the IF statement logic to say if `reference_node_os_state` and then in the following IF statement if `final_node_os_state` to compare it.
Do this for all reward functions
Write tests to evaluate step rewards

Related work items: #1443
2023-05-31 09:31:01 +00:00
Marek Wolan
6294a873ea Added pull_request_template.md 2023-05-31 09:26:40 +00:00
Sunil Samra
f843f6e149 Apply suggestions from code review 2023-05-31 08:09:09 +00:00
Marek Wolan
3eaf210d93 Update docs on MultiDiscrete observation spaces. 2023-05-30 16:54:34 +01:00
Marek Wolan
082e3b7307 Add test for new multidiscrete spaces 2023-05-30 15:48:11 +01:00
Marek Wolan
7bc938229b Update configs and transactions to include new obs 2023-05-30 15:24:13 +01:00
Marek Wolan
23f0f41378 Fix observation node shape 2023-05-30 15:16:14 +01:00
Marek Wolan
3a1f0b7659 Configure observation type MULTIDISCRETE 2023-05-30 15:11:41 +01:00
Marek Wolan
847c0fe2ae Setup testing scripts 2023-05-30 13:14:43 +01:00
SunilSamra
7aa8d89dfe 1443 - updated test_reward.py to reflect updates to reward.py so that the correct config values are called i.e. compromisedShouldBeGood on the correct steps during the training run 2023-05-30 11:50:54 +01:00
SunilSamra
9d34dceddc 1443 - changed IF statements from if initial ... if reference to if reference ... if final to compare the final state (state after red and blue actions) with the reference state (state with no red or blue action and with green normal network traffic occurring) 2023-05-30 11:40:40 +01:00
Marek Wolan
dd780b7451 Make reward calculation consider red POL 2023-05-30 08:50:57 +00:00
Marek Wolan
843f32bf71 Fix minor logic errors in main script 2023-05-26 14:50:15 +01:00
SunilSamra
e2fb03b9bd 1429 - added code from ADSP branch to primaite_env.py and added NONE = 0 to NodePOLType in enums.py 2023-05-26 14:29:02 +01:00
SunilSamra
3cd5864f25 1429 - created new branch from dev, added enums to enums.py, created agents package and utils.py file, added option to primaite_env.py for ANY action type and changed the action spaces are defined using ADSP branch 2023-05-26 10:17:45 +01:00
Christopher McCarthy
f7638ddb0c Merged PR 60: #1355 - Carried out full renaming in node.py, active_node.py, passive_node.py...
**The following changes are made to constructor params in the Node class and its children (ActiveNode, PassiveNode, and ServiceNode):**
- _id -> node_id
- _name -> name
- _type -> node_type
- _priority -> priority
- _state -> hardware_state
- _ip_address -> ip_address
- _os_state -> software state
- _file_system_state -> file_system_state
- _config_values -> config_values
- Add type hints to all params.

(node_id, name, and ip_address are str, states and other defines types are the respective enums, leave config_values without a type for now.)

**The following changes are made to instance variables in the Node class and its children:**
- self.type -> self.node_type
- self.operating_state -> self.hardware_state
- self.os_state -> self.software_state
- Add type hints to all instance variables.

(node_id, name, and ip_address are str, states and other defines types are the respective enums, leave config_values without a type for now.)

**The following changes are made to the config files where itemType is NODE:**
- itemType -> item_type
- id -> node_id
- portsList -> ports_list
- serviceList -> service_list
- baseType -> base_type
- nodeType -> node_type
- hardwareState -> hardware_state
- ipAddress -> ip_address
- softwareState -> software_state
- fileSystemState -> file_system_state

**The following changes are made in the primaite/environment/primaite_env.py module:
In the create_node function, the id of the node needs to be retrieved using the new "node_id" key.**
- _id -> node_id
- _name -> name
- _type -> node_type
- _priority -> priority
- _state -> hardware_state
- _ip_address -> ip_address
- _os_state -> software state
- _file_system_state -> file_system_state
- _config_values -> config_values

**Few other cosmetic/code style changes too:**
- Enum classes renamed to use CamelCase.
Started refactoring out unnescessary getters and setters by using `@property` and `@<property name>.setter`.
- Have started to add Type Hints.
- Have started to move docstrings over to the Sphinx ReStructured text format.

Related work items: #1355
2023-05-26 09:01:21 +00:00
Chris McCarthy
b62ea525e9 #1355 - Renamed the NodeType custom type in custom_typing.py as it clased with the NodeType enum in enums.py 2023-05-26 09:43:37 +01:00
Chris McCarthy
32a4d9e459 #1355 - Carried out full renaming in node.py, active_node.py, passive_node.py, and service_node.py to make params and variable names explicit.
- Made the same renaming in the yaml laydown config files.
- Added Type hints wherever I've been.
- Added a custom NodeType in custom_typing.py to encompass the Union of ActiveNode, PassiveNode, ServiceNode.
2023-05-25 21:03:11 +01:00
Christopher McCarthy
00e9d1f88d Merged PR 56: #902 - Fix the reward functionality for node operating system state
#902 - replaced 'final_node_<placeholder>' with 'reference_node_<placeholder>' in methods for scoring of os_state, file_system_state, service state and operating state. This fixed the reward function so it is checked at each step for node operating system state, operating state, file system state and service state.
- Added unit tests.

Related work items: #902
2023-05-25 15:28:19 +00:00
Christopher McCarthy
b462af0061 Merged PR 59: v1.2.1
v1.2.1
2023-05-25 14:23:55 +00:00
Christopher McCarthy
3e1ff0db17 Merged PR 58: v1.2.1
v1.2.1
2023-05-25 14:21:16 +00:00
Chris McCarthy
2e9b43f43b v1.2.1 2023-05-25 15:20:19 +01:00
SunilSamra
cabbe4797d 902 - changed test comment to explain the outcome of the average reward 2023-05-25 14:36:26 +01:00
Christopher McCarthy
af62d85aea Merged PR 57: Resync dev with v1.2.0
Resync dev with v1.2.0
2023-05-25 13:16:29 +00:00
Christopher McCarthy
b9fb2775c9 Merged PR 55: Release v1.2.0
Updated artifact-release-pipeline.yaml pipeline to build for Python 3.8 to 3.10 and MacOS, Windows, and Linux.
2023-05-25 13:11:20 +00:00
Chris McCarthy
fc1b374cb2 #902 - replaced 'final_node_<placeholder>' with 'reference_node_<placeholder>' in methods for scoring of os_state, file_system_state, service state and operating state. This fixed the reward function so it is checked at each step for node operating system state, operating state, file system state and service state.
- Added unit tests.
2023-05-25 14:05:53 +01:00
Christopher McCarthy
75581921ea Merged PR 54: #1356 - added if statements to set class methods for file system state, os st...
#1356 - added if statements to set class methods for file system state, os state and service states. Refactored file enums.py
- Added unit tests

Related work items: #1356
2023-05-25 12:33:16 +00:00
Chris McCarthy
4c13f79b06 Updated artifact-release-pipeline.yaml pipeline to build for Python 3.8 to 3.10 and MacOS, Windows, and Linux. 2023-05-25 13:24:49 +01:00
Christopher McCarthy
79ece6f78a Merged PR 53: release v1.2.0 2023-05-25 12:03:54 +00:00
Chris McCarthy
e1bcbd1a34 #1356 - added if statements to set class methods for file system state, os state and service states. Refactored file enums.py
- Added unit tests
2023-05-25 13:02:15 +01:00
Christopher McCarthy
e35360edb8 Merged PR 52: #1378 - Ordering of actions in step
#1378 - Re-arranged the action step function in the following order:
1. Implement the Blue Action
2. Perform any time-based activities
3. Apply PoL
4. Implement Red Action
5. Calculate reward signal
6. Output Verbose (currently disabled)
7. Update env_obs
8. Add transaction to the list of transactions

Related work items: #1378
2023-05-25 11:42:19 +00:00
Chris McCarthy
07cebc0a63 #1378 - Re-added post blue and snapshots 2023-05-25 12:37:42 +01:00
Chris McCarthy
958506ef33 #1378 - Re-arranged the action step function in the following order:
1. Implement the Blue Action
2. Perform any time-based activities
3. Apply PoL
4. Implement Red Action
5. Calculate reward signal
6. Output Verbose (currently disabled)
7. Update env_obs
8. Add transaction to the list of transactions
2023-05-25 11:58:54 +01:00
Chris McCarthy
4eb1658966 Ran pre-commit hook on all files and performed changes to fix flake8 failures 2023-05-25 11:42:19 +01:00
Chris McCarthy
aa8284897a Package restructuring and renaming for 1.2.0 2023-05-25 10:52:29 +01:00
Chris McCarthy
4f0d8807d6 Package restructuring 2023-05-25 10:31:37 +01:00
487 changed files with 73690 additions and 7032 deletions

View File

@@ -3,4 +3,4 @@ Index-servers =
PrimAITE
[PrimAITE]
Repository = https://pkgs.dev.azure.com/ma-dev-uk/PrimAITE/_packaging/PrimAITE/pypi/upload/
Repository = https://pkgs.dev.azure.com/ma-dev-uk/PrimAITE/_packaging/PrimAITE/pypi/upload/

View File

@@ -15,16 +15,17 @@ steps:
displayName: 'Use Python $(python.version)'
- script: |
python -m pip install --upgrade pip
pip install build
pip install wheel
python -m pip install --upgrade pip==23.0.1
pip install wheel==0.38.4 --upgrade
pip install setuptools==66 --upgrade
pip install build==0.10.0
pip install twine
pip install keyring
pip install artifacts-keyring
displayName: 'Install build dependencies'
- script: |
python setup.py sdist bdist_wheel
python -m build
displayName: 'Build PrimAITE sdist and wheel'
- task: TwineAuthenticate@1
@@ -33,5 +34,5 @@ steps:
artifactFeed: PrimAITE/PrimAITE
- script: |
python -m twine upload --verbose -r PrimAITE --config-file $(PYPIRC_PATH) dist/*
python -m twine upload --verbose -r PrimAITE --config-file $(PYPIRC_PATH) dist/*.whl
displayName: 'Artifact Upload'

View File

@@ -0,0 +1,108 @@
trigger:
- release/*
schedules:
- cron: "0 2 * * 1-5" # Run at 2 AM every weekday
displayName: "Weekday Schedule"
branches:
include:
- 'refs/heads/dev'
variables:
VERSION: ''
MAJOR_VERSION: ''
jobs:
- job: PrimAITE_Benchmark
timeoutInMinutes: 360 # 6-hour maximum
pool:
name: 'Imaginary Yak Pool'
workspace:
clean: all
steps:
- checkout: self
persistCredentials: true
- script: |
python3.10 -m venv venv
displayName: 'Create venv'
- script: |
VERSION=$(cat src/primaite/VERSION | tr -d '\n')
if [[ "$(Build.SourceBranch)" == "refs/heads/dev" ]]; then
DATE=$(date +%Y%m%d)
echo "${VERSION}+dev.${DATE}" > src/primaite/VERSION
fi
displayName: 'Update VERSION file for Dev Benchmark'
- script: |
VERSION=$(cat src/primaite/VERSION | tr -d '\n')
MAJOR_VERSION=$(echo $VERSION | cut -d. -f1)
echo "##vso[task.setvariable variable=VERSION]$VERSION"
echo "##vso[task.setvariable variable=MAJOR_VERSION]$MAJOR_VERSION"
displayName: 'Set Version Variables'
- script: |
source venv/bin/activate
pip install --upgrade pip
pip install -e .[dev,rl]
primaite setup
displayName: 'Install Dependencies'
- script: |
set -e
source venv/bin/activate
cd benchmark
python primaite_benchmark.py
cd ..
displayName: 'Run Benchmarking Script'
- script: |
tar czf primaite_v$(VERSION)_benchmark.tar.gz benchmark/results/v$(MAJOR_VERSION)/v$(VERSION)
displayName: 'Prepare Artifacts for Publishing'
- task: PublishPipelineArtifact@1
inputs:
targetPath: primaite_v$(VERSION)_benchmark.tar.gz
artifactName: 'benchmark-zip-output'
publishLocation: 'pipeline'
displayName: 'Publish Benchmark Output zip as Artifact'
- script: |
git config --global user.email "oss@dstl.gov.uk"
git config --global user.name "Defence Science and Technology Laboratory UK"
workingDirectory: $(System.DefaultWorkingDirectory)
displayName: 'Configure Git'
condition: and(succeeded(), startsWith(variables['Build.SourceBranch'], 'refs/heads/release'))
- script: |
echo "Fetching all branches..."
git fetch --all --prune
echo "Stashing files..."
git stash push -u
echo "Resolving branch name..."
# Extracting just the branch name from the full ref path
branch_name=$(echo "$(Build.SourceBranch)" | sed 's|refs/heads/||')
echo "Branch Name: $branch_name"
echo "Checking out branch $branch_name..."
git checkout $branch_name
echo "Popping stash..."
git stash pop
echo "Adding benchmark results..."
git add benchmark/results/v$(MAJOR_VERSION)/v$(VERSION)/*
echo "Committing changes..."
git commit -m "Automated benchmark output commit for version $(VERSION) [skip ci]"
echo "Pushing to remote..."
git push origin $branch_name
displayName: 'Commit and Push Benchmark Results'
workingDirectory: $(System.DefaultWorkingDirectory)
env:
GIT_CREDENTIALS: $(System.AccessToken)
condition: and(succeeded(), startsWith(variables['Build.SourceBranch'], 'refs/heads/release'))

View File

@@ -0,0 +1,53 @@
name: Azure Static Web Apps CI/CD
pr: none
trigger:
branches:
include:
- dev
jobs:
- job: build_and_deploy_job
displayName: Build and Deploy Job
condition: or(eq(variables['Build.Reason'], 'Manual'),or(eq(variables['Build.Reason'], 'PullRequest'),eq(variables['Build.Reason'], 'IndividualCI')))
pool:
vmImage: ubuntu-latest
variables:
- group: Azure-Static-Web-Apps-nice-bay-0ad032c03-variable-group
steps:
- checkout: self
submodules: true
- script: |
python -m pip install --upgrade pip==23.0.1
pip install wheel==0.38.4 --upgrade
pip install setuptools==66 --upgrade
pip install build==0.10.0
displayName: 'Install build dependencies'
- script: |
pip install -e .[dev,rl]
displayName: 'Install PrimAITE for docs autosummary'
- script: |
apt-get install pandoc
displayName: 'Install Pandoc'
- script: |
primaite setup
displayName: 'Perform PrimAITE Setup'
- script: |
cd docs
make html
cd ..
cd ..
displayName: 'Build Docs'
- task: AzureStaticWebApp@0
inputs:
azure_static_web_apps_api_token: $(AZURE_STATIC_WEB_APPS_API_TOKEN_NICE_BAY_0AD032C03)
app_location: "/docs/_build/html"
api_location: ""
output_location: "/"
displayName: 'Deploy Docs to nice-bay-0ad032c03'

View File

@@ -0,0 +1,128 @@
trigger:
- main
- dev
- feature/*
- hotfix/*
- bugfix/*
- release/*
pr:
autoCancel: true
drafts: false
parameters:
# https://stackoverflow.com/a/70046417
- name: matrix
type: object
default:
# - job_name: 'UbuntuPython38'
# py: '3.8'
# img: 'ubuntu-latest'
# every_time: false
# publish_coverage: false
- job_name: 'UbuntuPython311'
py: '3.11'
img: 'ubuntu-latest'
every_time: true
publish_coverage: true
# - job_name: 'WindowsPython38'
# py: '3.8'
# img: 'windows-latest'
# every_time: false
# publish_coverage: false
- job_name: 'WindowsPython311'
py: '3.11'
img: 'windows-latest'
every_time: false
publish_coverage: false
# - job_name: 'MacOSPython38'
# py: '3.8'
# img: 'macOS-latest'
# every_time: false
# publish_coverage: false
- job_name: 'MacOSPython311'
py: '3.11'
img: 'macOS-latest'
every_time: false
publish_coverage: false
stages:
- stage: Test
jobs:
- ${{ each item in parameters.matrix }}:
- job: ${{ item.job_name }}
timeoutInMinutes: 90
cancelTimeoutInMinutes: 1
pool:
vmImage: ${{ item.img }}
condition: and(succeeded(), or( eq(variables['Build.Reason'], 'PullRequest'), ${{ item.every_time }} ))
steps:
- task: UsePythonVersion@0
inputs:
versionSpec: ${{ item.py }}
displayName: 'Use Python ${{ item.py }}'
- script: |
python -m pip install pre-commit
pre-commit install
pre-commit run --all-files
displayName: 'Run pre-commits'
- script: |
python -m pip install --upgrade pip==23.0.1
pip install wheel==0.38.4 --upgrade
pip install setuptools==66 --upgrade
pip install build==0.10.0
pip install pytest-azurepipelines
displayName: 'Install build dependencies'
- script: |
python -m build
displayName: 'Build PrimAITE'
- script: |
PRIMAITE_WHEEL=$(ls ./dist/primaite*.whl)
python -m pip install $PRIMAITE_WHEEL[dev,rl]
displayName: 'Install PrimAITE'
condition: or(eq( variables['Agent.OS'], 'Linux' ), eq( variables['Agent.OS'], 'Darwin' ))
- script: |
forfiles /p dist\ /m *.whl /c "cmd /c python -m pip install @file[dev,rl]"
displayName: 'Install PrimAITE'
condition: eq( variables['Agent.OS'], 'Windows_NT' )
- script: |
primaite setup
displayName: 'Perform PrimAITE Setup'
- task: UseDotNet@2
displayName: 'Install dotnet dependencies'
inputs:
packageType: 'sdk'
version: '2.1.x'
- script: |
coverage run -m --source=primaite pytest -v -o junit_family=xunit2 --junitxml=junit/test-results.xml --cov-fail-under=80
coverage xml -o coverage.xml -i
coverage html -d htmlcov -i
displayName: 'Run tests and code coverage'
- task: PublishTestResults@2
condition: succeededOrFailed()
inputs:
testRunner: JUnit
testResultsFiles: 'junit/**.xml'
testRunTitle: 'Publish test results'
failTaskOnFailedTests: true
- publish: $(System.DefaultWorkingDirectory)/htmlcov/
# publish the html report - so we can debug the coverage if needed
condition: ${{ item.publish_coverage }} # should only be run once
artifact: coverage_report
- task: PublishCodeCoverageResults@2
# publish the code coverage so it can be viewed in the run coverage page
condition: ${{ item.publish_coverage }} # should only be run once
inputs:
codeCoverageTool: Cobertura
summaryFileLocation: '$(System.DefaultWorkingDirectory)/**/coverage.xml'

View File

@@ -0,0 +1,16 @@
## Summary
*Replace this text with an explanation of what the changes are and how you implemented them. Can this impact any other parts of the codebase that we should keep in mind?*
## Test process
*How have you tested this (if applicable)?*
## Checklist
- [ ] PR is linked to a **work item**
- [ ] **acceptance criteria** of linked ticket are met
- [ ] performed **self-review** of the code
- [ ] written **tests** for any new functionality added with this PR
- [ ] updated the **documentation** if this PR changes or adds functionality
- [ ] written/updated **design docs** if this PR implements new functionality
- [ ] updated the **change log**
- [ ] ran **pre-commit** checks for code style
- [ ] attended to any **TO-DOs** left in the code

20
.flake8 Normal file
View File

@@ -0,0 +1,20 @@
[flake8]
max-line-length=120
extend-ignore =
D105
D107
D100
D104
E203
E712
D401
F811
ANN002
ANN003
ANN101
ANN102
exclude =
docs/source/*
tests/*
suppress-none-returning=True
suppress-dummy-args=True

41
.github/ISSUE_TEMPLATE/bug_report.md vendored Normal file
View File

@@ -0,0 +1,41 @@
---
name: Bug report
about: Create a report to help us improve
title: "[BUG] - <bug title goes here>"
labels: bug
assignees: ''
---
### Describe the bug:
A clear and concise description of what the bug is.
### To Reproduce:
Steps to reproduce the behaviour:
1. Import '...'
2. Instantiate '....'
3. Pass to '....'
4. Run '....'
5. See error
### Expected behaviour
A clear and concise description of what you expected to happen.
### Screenshots/Outputs
If applicable, add screenshots to help explain your problem.
### Environment (please complete the following information)
- **OS:** [e.g. Ubuntu 22.04]
- **Python:** [e.g. 3.10.11]
- **PrimAITE Version:** [e.g. v2.0.0]
- **Software:** [e.g. cli, Jupyter, PyCharm, VSCode etc.]
### Additional context
Add any other context about the problem here.

View File

@@ -0,0 +1,24 @@
---
name: Feature request
about: Suggest an idea for this project
title: "[REQUEST] - <request title goes here>"
labels: feature_request
assignees: ''
---
### Is your feature request related to a problem?
If so, please give a concise description of what the problem is. Ex. I'm always frustrated when [...]
### Describe the solution you'd like:
A clear and concise description of what you want to happen.
### Describe alternatives you've considered:
A clear and concise description of any alternative solutions or features you've considered.
### Additional context:
Add any other context or screenshots about the feature request here.

60
.github/workflows/build-sphinx.yml vendored Normal file
View File

@@ -0,0 +1,60 @@
name: build-sphinx-to-github-pages
env:
GITHUB_ACTOR: Autonomous-Resilient-Cyber-Defence
GITHUB_REPOSITORY: Autonomous-Resilient-Cyber-Defence/PrimAITE
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN}}
on:
push:
branches: [main]
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.10"]
steps:
- uses: actions/checkout@v3
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python-version }}
- name: Install python dev
run: |
set -x
sudo apt-get update
sudo add-apt-repository ppa:deadsnakes/ppa -y
sudo apt install python${{ matrix.python-version}}-dev -y
- name: Install Git
run: |
set -x
sudo apt-get install -y git
shell: bash
- name: Set pip, wheel, setuptools versions
run: |
python -m pip install --upgrade pip==23.0.1
pip install wheel==0.38.4 --upgrade
pip install setuptools==66 --upgrade
pip install build
- name: Install PrimAITE for docs autosummary
run: |
set -x
python -m pip install -e .[dev,rl]
- name: Run build script for Sphinx pages
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -x
bash $PWD/docs/build-sphinx-docs-to-github-pages.sh

66
.github/workflows/python-package.yml vendored Normal file
View File

@@ -0,0 +1,66 @@
name: Python package
on:
push:
branches:
- main
- dev
- dev-gui
- 'release/**'
pull_request:
branches:
- main
- dev
- dev-gui
- 'release/**'
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.8", "3.9", "3.10"]
steps:
- uses: actions/checkout@v3
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python-version }}
- name: Install python dev
run: |
sudo apt update
sudo add-apt-repository ppa:deadsnakes/ppa -y
sudo apt install python${{ matrix.python-version}}-dev -y
- name: Install Build Dependencies
run: |
python -m pip install --upgrade pip==23.0.1
pip install wheel==0.38.4 --upgrade
pip install setuptools==66 --upgrade
pip install build
- name: Build PrimAITE
run: |
python -m build
- name: Install PrimAITE
run: |
PRIMAITE_WHEEL=$(ls ./dist/primaite*.whl)
python -m pip install $PRIMAITE_WHEEL[dev,rl]
- name: Perform PrimAITE Setup
run: |
primaite setup
- name: Lint with flake8
run: |
# stop the build if there are Python syntax errors or undefined names
flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics
# exit-zero treats all errors as warnings.
flake8 . --count --exit-zero --max-complexity=10 --max-line-length=120 --statistics
- name: Run tests
run: |
pytest tests/

37
.gitignore vendored
View File

@@ -1,8 +1,3 @@
# PrimAITE Package
PRIMAITE/outputs
PRIMAITE/outputs/*
TestResults
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
@@ -42,6 +37,7 @@ pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
junit/
htmlcov/
.tox/
.nox/
@@ -55,6 +51,9 @@ coverage.xml
.hypothesis/
.pytest_cache/
cover/
tests/assets/**/*.png
tests/assets/**/tensorboard_logs/
tests/assets/**/checkpoints/
# Translations
*.mo
@@ -75,6 +74,7 @@ instance/
# Sphinx documentation
docs/_build/
docs/source/_autosummary
# PyBuilder
.pybuilder/
@@ -82,6 +82,10 @@ target/
# Jupyter Notebook
.ipynb_checkpoints
PPO_UC2/
# ignore everything but the executed notebooks rst in the docs/source/notebooks directory
!docs/source/notebooks/executed_notebooks.rst
docs/source/notebooks/**/*
# IPython
profile_default/
@@ -141,3 +145,26 @@ dmypy.json
# Cython debug symbols
cython_debug/
# IDE
.idea/
docs/source/primaite-dependencies.rst
.vscode/
# outputs
src/primaite/outputs/
simulation_output/
sessions/
PrimAITE-PPO-example-agent.zip
# benchmark session outputs
benchmark/output
# src/primaite/notebooks/scratch.ipynb
src/primaite/notebooks/scratch.py
sandbox.py
sandbox/
sandbox.ipynb
# benchmarking
**/benchmark/sessions/
**/benchmark/output/

35
.pre-commit-config.yaml Normal file
View File

@@ -0,0 +1,35 @@
repos:
- repo: http://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0
hooks:
- id: check-yaml
exclude: scenario_with_placeholders/
- id: end-of-file-fixer
- id: trailing-whitespace
- id: check-added-large-files
args: ['--maxkb=5000']
- id: mixed-line-ending
- id: requirements-txt-fixer
- repo: http://github.com/psf/black
rev: 23.1.0
hooks:
- id: black
args: [ "--line-length=120" ]
additional_dependencies:
- jupyter
- repo: http://github.com/pycqa/isort
rev: 5.12.0
hooks:
- id: isort
args: [ "--profile", "black" ]
- repo: http://github.com/PyCQA/flake8
rev: 6.0.0
hooks:
- id: flake8
additional_dependencies:
- flake8-docstrings
- flake8-annotations
- repo: https://github.com/kynan/nbstripout
rev: 0.7.1
hooks:
- id: nbstripout

240
CHANGELOG.md Normal file
View File

@@ -0,0 +1,240 @@
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## 3.0.0b9
- Removed deprecated `PrimaiteSession` class.
- Added ability to set log levels via configuration.
- Upgraded pydantic to version 2.7.0
- Upgraded Ray to version >= 2.9
- Added ipywidgets to the dependencies
- Added ability to define scenarios that change depending on the episode number.
- Standardised Environment API by renaming the config parameter of `PrimaiteGymEnv` from `game_config` to `env_config`
- Database Connection ID's are now created/issued by DatabaseService and not DatabaseClient
- Updated DatabaseClient so that it can now have a single native DatabaseClientConnection along with a collection of DatabaseClientConnection's.
- Implemented the uninstall functionality for DatabaseClient so that all connections are terminated at the DatabaseService.
- Added the ability for a DatabaseService to terminate a connection.
- Added active_connection to DatabaseClientConnection so that if the connection is terminated active_connection is set to False and the object can no longer be used.
- Added additional show functions to enable connection inspection.
- Updates to agent logging, to include the reward both per step and per episode.
- Introduced Developer CLI tools to assist with developing/debugging PrimAITE
- Can be enabled via `primaite dev-mode enable`
- Activating dev-mode will change the location where the sessions will be output - by default will output where the PrimAITE repository is located
- Refactored all air-space usage to that a new instance of AirSpace is created for each instance of Network. This 1:1 relationship between network and airspace will allow parallelization.
- Added notebook to demonstrate use of SubprocVecEnv from SB3 to vectorise environments to speed up training.
## [Unreleased]
- Made requests fail to reach their target if the node is off
- Added responses to requests
- Made environment reset completely recreate the game object.
- Changed the red agent in the data manipulation scenario to randomly choose client 1 or client 2 to start its attack.
- Changed the data manipulation scenario to include a second green agent on client 1.
- Refactored actions and observations to be configurable via object name, instead of UUID.
- Made database patch correctly take 2 timesteps instead of being immediate
- Made database patch only possible when the software is compromised or good, it's no longer possible when the software is OFF or RESETTING
- Added a notebook which explains Data manipulation scenario, demonstrates the attack, and shows off blue agent's action space, observation space, and reward function.
- Made packet capture and system logging optional (off by default). To turn on, change the io_settings.save_pcap_logs and io_settings.save_sys_logs settings in the config.
- Made observation space flattening optional (on by default). To turn off for an agent, change the `agent_settings.flatten_obs` setting in the config.
- Added support for SQL INSERT command.
- Added ability to log each agent's action choices in each step to a JSON file.
- Removal of Link bandwidth hardcoding. This can now be configured via the network configuraiton yaml. Will default to 100 if not present.
### Bug Fixes
- ACL rules were not resetting on episode reset.
- ACLs were not showing up correctly in the observation space.
- Blue agent's ACL actions were being applied against the wrong IP addresses
- Deleted files and folders did not reset correctly on episode reset.
- Service health status was using the actual health state instead of the visible health state
- Database file health status was using the incorrect value for negative rewards
- Preventing file actions from reaching their intended file
- The data manipulation attack was triggered at episode start.
- FTP STOR stored an additional copy on the client machine's filesystem
- The red agent acted to early
- Order of service health state
- Starting a node didn't start the services on it
- Fixed an issue where the services were still able to run even though the node the service is installed on is turned off
- The use of NODE_FILE_CHECKHASH and NODE_FOLDER_CHECKHASH in the current release is marked as 'Not Implemented'.
### Added
- Network Hardware - Added base hardware module with NIC, SwitchPort, Node, and Link. Nodes have
fundamental services like ARP, ICMP, and PCAP running them by default.
- Network Transmission - Modelled OSI Model layers 1 through to 5 with various classes for creating network frames and
transmitting them from a Service/Application, down through the layers, over the wire, and back up through the layers to
a Service/Application another machine.
- Introduced `Router` and `Switch` classes to manage networking routes more effectively.
- Added `ACLRule` and `RouteTableEntry` classes as part of the `Router`.
- New `.show()` methods in all network component classes to inspect the state in either plain text or markdown formats.
- Added `Computer` and `Server` class to better differentiate types of network nodes.
- Integrated a new Use Case 2 network into the system.
- New unit tests to verify routing between different subnets using `.ping()`.
- system - Added the core structure of Application, Services, and Components. Also added a SoftwareManager and
SessionManager.
- Permission System - each action can define criteria that will be used to permit or deny agent actions.
- File System - ability to emulate a node's file system during a simulation
- Example notebooks - There are 5 jupyter notebook which walk through using PrimAITE
1. Training a Stable Baselines 3 agent
2. Training a single agent system using Ray RLLib
3. Training a multi-agent system Ray RLLib
4. Data manipulation end to end demonstration
5. Data manipulation scenario with customised red agents
- Database:
- `DatabaseClient` and `DatabaseService` created to allow emulation of database actions
- Ability for `DatabaseService` to backup its data to another server via FTP and restore data from backup
- Red Agent Services:
- Data Manipulator Bot - A red agent service which sends a payload to a target machine. (By default this payload is a SQL query that breaks a database). The attack runs in stages with a random, configurable probability of succeeding.
- `DataManipulationAgent` runs the Data Manipulator Bot according to a configured start step, frequency and variance.
- DNS Services: `DNSClient` and `DNSServer`
- FTP Services: `FTPClient` and `FTPServer`
- HTTP Services: `WebBrowser` to simulate a web client and `WebServer`
- NTP Services: `NTPClient` and `NTPServer`
- **RouterNIC Class**: Introduced a new class `RouterNIC`, extending the standard `NIC` functionality. This class is specifically designed for router operations, optimizing the processing and routing of network traffic.
- **Custom Layer-3 Processing**: The `RouterNIC` class includes custom handling for network frames, bypassing standard Node NIC's Layer 3 broadcast/unicast checks. This allows for more efficient routing behavior in network scenarios where router-specific frame processing is required.
- **Enhanced Frame Reception**: The `receive_frame` method in `RouterNIC` is tailored to handle frames based on Layer 2 (Ethernet) checks, focusing on MAC address-based routing and broadcast frame acceptance.
- **Subnet-Wide Broadcasting for Services and Applications**: Implemented the ability for services and applications to conduct broadcasts across an entire IPv4 subnet within the network simulation framework.
- Introduced the `NetworkInterface` abstract class to provide a common interface for all network interfaces. Subclasses are divided into two main categories: `WiredNetworkInterface` and `WirelessNetworkInterface`, each serving as an abstract base class (ABC) for more specific interface types. Under `WiredNetworkInterface`, the subclasses `NIC` and `SwitchPort` were added. For wireless interfaces, `WirelessNIC` and `WirelessAccessPoint` are the subclasses under `WirelessNetworkInterface`.
- Added `Layer3Interface` as an abstract base class for networking functionalities at layer 3, including IP addressing and routing capabilities. This class is inherited by `NIC`, `WirelessNIC`, and `WirelessAccessPoint` to provide them with layer 3 capabilities, facilitating their role in both wired and wireless networking contexts with IP-based communication.
- Created the `ARP` and `ICMP` service classes to handle Address Resolution Protocol operations and Internet Control Message Protocol messages, respectively, with `RouterARP` and `RouterICMP` for router-specific implementations.
- Created `HostNode` as a subclass of `Node`, extending its functionality with host-specific services and applications. This class is designed to represent end-user devices like computers or servers that can initiate and respond to network communications.
- Introduced a new `IPV4Address` type in the Pydantic model for enhanced validation and auto-conversion of IPv4 addresses from strings using an `ipv4_validator`.
- Comprehensive documentation for the Node and its network interfaces, detailing the operational workflow from frame reception to application-level processing.
- Detailed descriptions of the Session Manager and Software Manager functionalities, including their roles in managing sessions, software services, and applications within the simulation.
- Documentation for the Packet Capture (PCAP) service and SysLog functionality, highlighting their importance in logging network frames and system events, respectively.
- Expanded documentation on network devices such as Routers, Switches, Computers, and Switch Nodes, explaining their specific processing logic and protocol support.
- **Firewall Node**: Introduced the `Firewall` class extending the functionality of the existing `Router` class. The `Firewall` class incorporates advanced features to scrutinize, direct, and filter traffic between various network zones, guided by predefined security rules and policies. Key functionalities include:
- Access Control Lists (ACLs) for traffic filtering based on IP addresses, protocols, and port numbers.
- Network zone segmentation for managing traffic across external, internal, and DMZ (De-Militarized Zone) networks.
- Interface configuration to establish connectivity and define network parameters for external, internal, and DMZ interfaces.
- Protocol and service management to oversee traffic and enforce security policies.
- Dynamic traffic processing and filtering to ensure network security and integrity.
- `AirSpace` class to simulate wireless communications, managing wireless interfaces and facilitating the transmission of frames within specified frequencies.
- `AirSpaceFrequency` enum for defining standard wireless frequencies, including 2.4 GHz and 5 GHz bands, to support realistic wireless network simulations.
- `WirelessRouter` class, extending the `Router` class, to incorporate wireless networking capabilities alongside traditional wired connections. This class allows the configuration of wireless access points with specific IP settings and operating frequencies.
- Documentation Updates:
- Examples include how to set up PrimAITE session via config
- Examples include how to create nodes and install software via config
- Examples include how to set up PrimAITE session via Python
- Examples include how to create nodes and install software via Python
- Added missing ``DoSBot`` documentation page
- Added diagrams where needed to make understanding some things easier
- Templated parts of the documentation to prevent unnecessary repetition and for easier maintaining of documentation
- Separated documentation pages of some items i.e. client and server software were on the same pages - which may make things confusing
- Configuration section at the bottom of the software pages specifying the configuration options available (and which ones are optional)
- Ability to add ``Firewall`` node via config
- Ability to add ``Router`` routes via config
- Ability to add ``Router``/``Firewall`` ``ACLRule`` via config
- NMNE capturing capabilities to `NetworkInterface` class for detecting and logging Malicious Network Events.
- New `nmne_config` settings in the simulation configuration to enable NMNE capturing and specify keywords such as "DELETE".
- Router-specific SessionManager Implementation: Introduced a specialized version of the SessionManager tailored for router operations. This enhancement enables the SessionManager to determine the routing path by consulting the route table.
### Changed
- Integrated the RouteTable into the Routers frame processing.
- Frames are now dropped when their TTL reaches 0
- **NIC Functionality Update**: Updated the Network Interface Card (`NIC`) functionality to support Layer 3 (L3) broadcasts.
- **Layer 3 Broadcast Handling**: Enhanced the existing `NIC` classes to correctly process and handle Layer 3 broadcasts. This update allows devices using standard NICs to effectively participate in network activities that involve L3 broadcasting.
- **Improved Frame Reception Logic**: The `receive_frame` method of the `NIC` class has been updated to include additional checks and handling for L3 broadcasts, ensuring proper frame processing in a wider range of network scenarios.
- Standardised the way network interfaces are accessed across all `Node` subclasses (`HostNode`, `Router`, `Switch`) by maintaining a comprehensive `network_interface` attribute. This attribute captures all network interfaces by their port number, streamlining the management and interaction with network interfaces across different types of nodes.
- Refactored all tests to utilise new `Node` subclasses (`Computer`, `Server`, `Router`, `Switch`) instead of creating generic `Node` instances and manually adding network interfaces. This change aligns test setups more closely with the intended use cases and hierarchies within the network simulation framework.
- Updated all tests to employ the `Network()` class for managing nodes and their connections, ensuring a consistent and structured approach to setting up network topologies in testing scenarios.
- **ACLRule Wildcard Masking**: Updated the `ACLRule` class to support IP ranges using wildcard masking. This enhancement allows for more flexible and granular control over traffic filtering, enabling the specification of broader or more specific IP address ranges in ACL rules.
- Updated `NetworkInterface` documentation to reflect the new NMNE capturing features and how to use them.
- Integration of NMNE capturing functionality within the `NICObservation` class.
- Changed blue action set to enable applying node scan, reset, start, and shutdown to every host in data manipulation scenario
### Removed
- Removed legacy simulation modules: `acl`, `common`, `environment`, `links`, `nodes`, `pol`
- Removed legacy training modules
- Removed tests for legacy code
### Fixed
- Addressed network transmission issues that previously allowed ARP requests to be incorrectly routed and repeated across different subnets. This fix ensures ARP requests are correctly managed and confined to their appropriate network segments.
- Resolved problems in `Node` and its subclasses where the default gateway configuration was not properly utilized for communications across different subnets. This correction ensures that nodes effectively use their configured default gateways for outbound communications to other network segments, thereby enhancing the network's routing functionality and reliability.
- Network Interface Port name/num being set properly for sys log and PCAP output.
## [2.0.0] - 2023-07-26
### Added
- Command Line Interface (CLI) for easy access and streamlined usage of PrimAITE.
- Application Directories to enable PrimAITE as a Python package with predefined directories for storage.
- Support for Ray Rllib, allowing training of PPO and A2C agents using Stable Baselines3 and Ray RLlib.
- Random Red Agent to train the blue agent against, with options for randomised Red Agent `POL` and `IER`.
- Repeatability of sessions through seed settings, and deterministic or stochastic evaluation options.
- Session loading to revisit previously run sessions for SB3 Agents.
- Agent Session Classes (`AgentSessionABC` and `HardCodedAgentSessionABC`) to standardise agent training with a common interface.
- Standardised Session Output in a structured format in the user's app sessions directory, providing four types of outputs:
1. Session Metadata
2. Results
3. Diagrams
4. Saved agents (training checkpoints and a final trained agent).
- Configurable Observation Space managed by the `ObservationHandler` class for a more flexible observation space setup.
- Benchmarking of PrimAITE performance, showcasing session and step durations for reference.
- Documentation overhaul, including automatic API and test documentation with recursive Sphinx auto-summary, using the Furo theme for responsive light/dark theme, and enhanced navigation with `sphinx-code-tabs` and `sphinx-copybutton`.
### Changed
- Action Space updated to discrete spaces, introducing a new `ANY` action space option for combined `NODE` and `ACL` actions.
- Improved `Node` attribute naming convention for consistency, now adhering to `Pascal Case`.
- Package Structure has been refactored for better build, distribution, and installation, with all source code now in the `src/` directory, and the `PRIMAITE` Python package renamed to `primaite` to adhere to PEP-8 Package & Module Names.
- Docs and Tests now sit outside the `src/` directory.
- Non-python files (example config files, Jupyter notebooks, etc.) now sit inside a `*/_package_data/` directory in their respective sub-packages.
- All dependencies are now defined in the `pyproject.toml` file.
- Introduced individual configuration for the number of episodes and time steps for training and evaluation sessions, with separate config values for each.
- Decoupled the lay down config file from the training config, allowing more flexibility in configuration management.
- Updated `Transactions` to only report pre-action observation, improving the CSV header and providing more human-readable descriptions for columns relating to observations.
- Changes to `AccessControlList`, where the `acl` dictionary is now a list to accommodate changes to ACL action space and positioning of `ACLRules` inside the list to signal their level of priority.
### Fixed
- Various bug fixes, including Green IERs separation, correct clearing of links in the reference environment, and proper reward calculation.
- Logic to check if a node is OFF before executing actions on the node by the blue agent, preventing erroneous state changes.
- Improved functionality of Resetting a Node, adding "SHUTTING DOWN" and "BOOTING" operating states for more reliable reset commands.
- Corrected the order of actions in the `Primaite` env to ensure the blue agent uses the current state for decision-making.
## [1.1.1] - 2023-06-27
### Bug Fixes
* Fixed bug whereby 'reference' environment links reach bandwidth capacity and are never cleared due to green & red IERs being applied to them. This bug had a knock-on effect that meant IERs were being blocked based on the full capacity of links on the reference environment which was not correct; they should only be based on the link capacity of the 'live' environment. This fix has been addressed by:
* Implementing a reference copy of all green IERs (`self.green_iers_reference`).
* Clearing the traffic on reference IERs at the same time as the live IERs.
* Passing the `green_iers_reference` to the `apply_iers` function at the reference stage.
* Passing the `green_iers_reference` as an additional argument to `calculate_reward_function`.
* Updating the green IERs section of the `calculate_reward_function` to now take into account both the green reference IERs and live IERs. The `green_ier_blocked` reward is only applied if the IER is blocked in the live environment but is running in the reference environment.
* Re-ordering the actions taken as part of the step function to ensure the blue action happens first before other changes.
* Removing the unnecessary "Reapply PoL and IERs" action from the step function.
* Moving the deep-copy of nodes and links to below the "Implement blue action" stage of the step function.
## [1.1.0] - 2023-03-13
### Added
* The user can now initiate either a TRAINING session or an EVALUATION (test) session with the Stable Baselines 3 (SB3) agents via the config_main.yaml file. During evaluation/testing, the agent policy will be fixed (no longer learning) and subjected to the SB3 `evaluate_policy()` function.
* The user can choose whether a saved agent is loaded into the session (with reference to a URL) via the `config_main.yaml` file. They specify a Boolean true/false indicating whether a saved agent should be loaded, and specify the URL and file name.
* Active and Service nodes now possess a new "File System State" attribute. This attribute is permitted to have the states GOOD, CORRUPT, DESTROYED, REPAIRING, and RESTORING. This new feature affects the following components:
* Blue agent observation space;
* Blue agent action space;
* Reward function;
* Node pattern-of-life.
* The Red Agent node pattern-of-life has been enhanced so that node PoL is triggered by an 'initiator'. The initiator is either DIRECT (state change is applied to the node without any conditions), IER (state change is applied to the node based on IER entry condition), or SERVICE (state change is applied to the node based on a service state condition on the same node or a different node within the network).
* New default config named "config_5_DATA_MANIPULATION.yaml" and associated Training Use Case Profile.
* NodeStateInstruction has been split into `NodeStateInstructionGreen` and `NodeStateInstructionRed` to reflect the changes within the red agent pattern-of-life capability.
* The reward function has been enhanced so that node attribute states of resetting, patching, repairing, and restarting contribute to the overall reward value.
* The User Guide has been updated to reflect all the above changes.
### Changed
* "config_1_DDOS_BASIC.yaml" modified to make it more simplistic to aid evaluation testing.
* "config_2_DDOS_BASIC.yaml" updated to reflect the addition of the File System State and the Red Agent node pattern-of-life enhancement.
* "config_3_DOS_VERY_BASIC.yaml" updated to reflect the addition of the File System State and the Red Agent node pattern-of-life enhancement.
* "config_UNIT_TEST.yaml" is a copy of the new "config_5_DATA_MANIPULATION.yaml" file.
* Updates to Transactions.
### Fixed
* Fixed "config_2_DDOS_BASIC.yaml" by adding another ACL rule to allow traffic to flow from Node 9 to Node 3. Previously, there was no rule, so one of the green IERs could not flow by default.
[unreleased]: https://github.com/Autonomous-Resilient-Cyber-Defence/PrimAITE/compare/v2.0.0...HEAD
[2.0.0]: https://github.com/Autonomous-Resilient-Cyber-Defence/PrimAITE/releases/tag/v2.0.0

39
CONTRIBUTING.md Normal file
View File

@@ -0,0 +1,39 @@
# How to contribute to PrimAITE?
### **Did you find a bug?**
* **Ensure the bug was not already reported** by searching on GitHub under [Issues](https://github.com/Autonomous-Resilient-Cyber-Defence/PrimAITE/issues).
* If you're unable to find an open issue addressing the problem, [open a new one](https://github.com/Autonomous-Resilient-Cyber-Defence/PrimAITE/issues/new?assignees=&labels=bug&projects=&template=bug_report.md&title=%5BBUG%5D+-+%3Cbug+title+goes+here%3E). Be sure to follow our bug report template with the headers **Describe the bug**, **To Reproduce**, **Expected behaviour**, **Screenshots/Outputs**, **Environment**, and **Additional context**
### **Do you have a solution to fix the bug?**
* [Fork the repository](https://github.com/Autonomous-Resilient-Cyber-Defence/PrimAITE/fork).
* Install the pre-commit hook with `pre-commit install`.
* Implement the bug fix.
* Update documentation where applicable.
* Update the **UNRELEASED** section of the [CHANGELOG.md](CHANGELOG.md) file
* Write a suitable test/tests.
* Commit the bug fix to the dev branch on your fork. If the bug has an open issue under [Issues](https://github.com/Autonomous-Resilient-Cyber-Defence/PrimAITE/issues), reference the issue in the commit message (e.g. #1 references issue 1).
* Submit a pull request from your dev branch to the Autonomous-Resilient-Cyber-Defence/PrimAITE dev branch. Again, if the bug has an open issue under [Issues](https://github.com/Autonomous-Resilient-Cyber-Defence/PrimAITE/issues), reference the issue in the pull request description.
### **Did you fix whitespace, format code, or make a purely cosmetic patch?**
Changes that are cosmetic in nature and do not add anything substantial to the stability, functionality, or testability of PrimAITE will generally not be accepted.
### **Do you intend to add a new feature or change an existing one?**
* Submit a [feature request issue](https://github.com/Autonomous-Resilient-Cyber-Defence/PrimAITE/issues/new?assignees=&labels=feature_request&projects=&template=feature_request.md&title=%5BREQUEST%5D+-+%3Crequest+title+goes+here%3E).
* Know how to implement the new feature or change? Follow the same steps in the bug fix section above to fork, build, document, test, commit, and submit a pull request.
### **Do you have questions about the source code?**
Ask any question about how to use PrimAITE in our discussions section.
### **Do you want to contribute to the PrimAITE documentation?**
Please follow the "Do you intend to add a new feature or change an existing one?" section above and tag your feature request issue and pull request with the documentation tag.
Thank you from the PrimAITE dev team! 🙌

21
LICENSE Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2023 - 2025 Defence Science and Technology Laboratory UK (https://dstl.gov.uk)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

3
MANIFEST.in Normal file
View File

@@ -0,0 +1,3 @@
include src/primaite/setup/_package_data/primaite_config.yaml
include src/primaite/config/_package_data/*.yaml
include src/primaite/simulator/_package_data/*.ipynb

View File

@@ -1,312 +0,0 @@
# Crown Copyright (C) Dstl 2022. DEFCON 703. Shared in confidence.
"""
PRIMAITE - main (harness) module
Coding Standards: PEP 8
"""
from sys import exc_info
import time
import yaml
import os.path
import logging
from datetime import datetime
from environment.primaite import PRIMAITE
from transactions.transactions_to_file import write_transaction_to_file
from common.config_values_main import config_values_main
from stable_baselines3 import PPO
from stable_baselines3.ppo import MlpPolicy as PPOMlp
from stable_baselines3 import A2C
from stable_baselines3.common.env_checker import check_env
from stable_baselines3.common.evaluation import evaluate_policy
################################# FUNCTIONS ######################################
def run_generic():
"""
Run against a generic agent
"""
for episode in range(0, config_values.num_episodes):
for step in range(0, config_values.num_steps):
# Send the observation space to the agent to get an action
# TEMP - random action for now
# action = env.blue_agent_action(obs)
action = env.action_space.sample()
# Run the simulation step on the live environment
obs, reward, done, info = env.step(action)
# Break if done is True
if done:
break
# Introduce a delay between steps
time.sleep(config_values.time_delay / 1000)
# Reset the environment at the end of the episode
env.reset()
env.close()
def run_stable_baselines3_ppo():
"""
Run against a stable_baselines3 PPO agent
"""
if config_values.load_agent == True:
try:
agent = PPO.load(config_values.agent_load_file, env, verbose=0, n_steps=config_values.num_steps)
except:
print("ERROR: Could not load agent at location: " + config_values.agent_load_file)
logging.error("Could not load agent")
logging.error("Exception occured", exc_info=True)
else:
agent = PPO(PPOMlp, env, verbose=0, n_steps=config_values.num_steps)
if config_values.session_type == "TRAINING":
# We're in a training session
print("Starting training session...")
logging.info("Starting training session...")
for episode in range(0, config_values.num_episodes):
agent.learn(total_timesteps=1)
save_agent(agent)
else:
# Default to being in an evaluation session
print("Starting evaluation session...")
logging.info("Starting evaluation session...")
evaluate_policy(agent, env, n_eval_episodes=config_values.num_episodes)
env.close()
def run_stable_baselines3_a2c():
"""
Run against a stable_baselines3 A2C agent
"""
if config_values.load_agent == True:
try:
agent = A2C.load(config_values.agent_load_file, env, verbose=0, n_steps=config_values.num_steps)
except:
print("ERROR: Could not load agent at location: " + config_values.agent_load_file)
logging.error("Could not load agent")
logging.error("Exception occured", exc_info=True)
else:
agent = A2C("MlpPolicy", env, verbose=0, n_steps=config_values.num_steps)
if config_values.session_type == "TRAINING":
# We're in a training session
print("Starting training session...")
logging.info("Starting training session...")
for episode in range(0, config_values.num_episodes):
agent.learn(total_timesteps=1)
save_agent(agent)
else:
# Default to being in an evaluation session
print("Starting evaluation session...")
logging.info("Starting evaluation session...")
evaluate_policy(agent, env, n_eval_episodes=config_values.num_episodes)
env.close()
def save_agent(_agent):
"""
Persist an agent (only works for stable baselines3 agents at present)
"""
now = datetime.now() # current date and time
time = now.strftime("%Y%m%d_%H%M%S")
try:
path = 'outputs/agents/'
is_dir = os.path.isdir(path)
if not is_dir:
os.makedirs(path)
filename = "outputs/agents/agent_saved_" + time
_agent.save(filename)
logging.info("Trained agent saved as " + filename)
except Exception as e:
logging.error("Could not save agent")
logging.error("Exception occured", exc_info=True)
def configure_logging():
"""
Configures logging
"""
try:
now = datetime.now() # current date and time
time = now.strftime("%Y%m%d_%H%M%S")
filename = "logs/app_" + time + ".log"
path = 'logs/'
is_dir = os.path.isdir(path)
if not is_dir:
os.makedirs(path)
logging.basicConfig(filename=filename, filemode='w', format='%(asctime)s - %(levelname)s - %(message)s', datefmt='%d-%b-%y %H:%M:%S', level=logging.INFO)
except:
print("ERROR: Could not start logging")
def load_config_values():
"""
Loads the config values from the main config file into a config object
"""
try:
# Generic
config_values.agent_identifier = config_data['agentIdentifier']
config_values.num_episodes = int(config_data['numEpisodes'])
config_values.time_delay = int(config_data['timeDelay'])
config_values.config_filename_use_case = config_data['configFilename']
config_values.session_type = config_data['sessionType']
config_values.load_agent = bool(config_data['loadAgent'])
config_values.agent_load_file = config_data['agentLoadFile']
# Environment
config_values.observation_space_high_value = int(config_data['observationSpaceHighValue'])
# Reward values
# Generic
config_values.all_ok = int(config_data['allOk'])
# Node Operating State
config_values.off_should_be_on = int(config_data['offShouldBeOn'])
config_values.off_should_be_resetting = int(config_data['offShouldBeResetting'])
config_values.on_should_be_off = int(config_data['onShouldBeOff'])
config_values.on_should_be_resetting = int(config_data['onShouldBeResetting'])
config_values.resetting_should_be_on = int(config_data['resettingShouldBeOn'])
config_values.resetting_should_be_off = int(config_data['resettingShouldBeOff'])
config_values.resetting = int(config_data['resetting'])
# Node O/S or Service State
config_values.good_should_be_patching = int(config_data['goodShouldBePatching'])
config_values.good_should_be_compromised = int(config_data['goodShouldBeCompromised'])
config_values.good_should_be_overwhelmed = int(config_data['goodShouldBeOverwhelmed'])
config_values.patching_should_be_good = int(config_data['patchingShouldBeGood'])
config_values.patching_should_be_compromised = int(config_data['patchingShouldBeCompromised'])
config_values.patching_should_be_overwhelmed = int(config_data['patchingShouldBeOverwhelmed'])
config_values.patching = int(config_data['patching'])
config_values.compromised_should_be_good = int(config_data['compromisedShouldBeGood'])
config_values.compromised_should_be_patching = int(config_data['compromisedShouldBePatching'])
config_values.compromised_should_be_overwhelmed = int(config_data['compromisedShouldBeOverwhelmed'])
config_values.compromised = int(config_data['compromised'])
config_values.overwhelmed_should_be_good = int(config_data['overwhelmedShouldBeGood'])
config_values.overwhelmed_should_be_patching = int(config_data['overwhelmedShouldBePatching'])
config_values.overwhelmed_should_be_compromised = int(config_data['overwhelmedShouldBeCompromised'])
config_values.overwhelmed = int(config_data['overwhelmed'])
# Node File System State
config_values.good_should_be_repairing = int(config_data['goodShouldBeRepairing'])
config_values.good_should_be_restoring = int(config_data['goodShouldBeRestoring'])
config_values.good_should_be_corrupt = int(config_data['goodShouldBeCorrupt'])
config_values.good_should_be_destroyed = int(config_data['goodShouldBeDestroyed'])
config_values.repairing_should_be_good = int(config_data['repairingShouldBeGood'])
config_values.repairing_should_be_restoring = int(config_data['repairingShouldBeRestoring'])
config_values.repairing_should_be_corrupt = int(config_data['repairingShouldBeCorrupt'])
config_values.repairing_should_be_destroyed = int(config_data['repairingShouldBeDestroyed'])
config_values.repairing = int(config_data['repairing'])
config_values.restoring_should_be_good = int(config_data['restoringShouldBeGood'])
config_values.restoring_should_be_repairing = int(config_data['restoringShouldBeRepairing'])
config_values.restoring_should_be_corrupt = int(config_data['restoringShouldBeCorrupt'])
config_values.restoring_should_be_destroyed = int(config_data['restoringShouldBeDestroyed'])
config_values.restoring = int(config_data['restoring'])
config_values.corrupt_should_be_good = int(config_data['corruptShouldBeGood'])
config_values.corrupt_should_be_repairing = int(config_data['corruptShouldBeRepairing'])
config_values.corrupt_should_be_restoring = int(config_data['corruptShouldBeRestoring'])
config_values.corrupt_should_be_destroyed = int(config_data['corruptShouldBeDestroyed'])
config_values.corrupt = int(config_data['corrupt'])
config_values.destroyed_should_be_good = int(config_data['destroyedShouldBeGood'])
config_values.destroyed_should_be_repairing = int(config_data['destroyedShouldBeRepairing'])
config_values.destroyed_should_be_restoring = int(config_data['destroyedShouldBeRestoring'])
config_values.destroyed_should_be_corrupt = int(config_data['destroyedShouldBeCorrupt'])
config_values.destroyed = int(config_data['destroyed'])
config_values.scanning = int(config_data['scanning'])
# IER status
config_values.red_ier_running = int(config_data['redIerRunning'])
config_values.green_ier_blocked = int(config_data['greenIerBlocked'])
# Patching / Reset durations
config_values.os_patching_duration = int(config_data['osPatchingDuration'])
config_values.node_reset_duration = int(config_data['nodeResetDuration'])
config_values.service_patching_duration = int(config_data['servicePatchingDuration'])
config_values.file_system_repairing_limit = int(config_data['fileSystemRepairingLimit'])
config_values.file_system_restoring_limit = int(config_data['fileSystemRestoringLimit'])
config_values.file_system_scanning_limit = int(config_data['fileSystemScanningLimit'])
logging.info("Training agent: " + config_values.agent_identifier)
logging.info("Training environment config: " + config_values.config_filename_use_case)
logging.info("Training cycle has " + str(config_values.num_episodes) + " episodes")
except Exception as e:
logging.error("Could not save load config data")
logging.error("Exception occured", exc_info=True)
################################# MAIN PROCESS ############################################
# Starting point
# Welcome message
print("Welcome to the Primary-level AI Training Environment (PrimAITE)")
# Configure logging
configure_logging()
# Open the main config file
try:
config_file_main = open("config/config_main.yaml", "r")
config_data = yaml.safe_load(config_file_main)
# Create a config class
config_values = config_values_main()
# Load in config data
load_config_values()
except Exception as e:
logging.error("Could not load main config")
logging.error("Exception occured", exc_info=True)
# Create a list of transactions
# A transaction is an object holding the:
# - episode #
# - step #
# - initial observation space
# - action
# - reward
# - new observation space
transaction_list = []
# Create the PRIMAITE environment
try:
env = PRIMAITE(config_values, transaction_list)
logging.info("PrimAITE environment created")
except Exception as e:
logging.error("Could not create PrimAITE environment")
logging.error("Exception occured", exc_info=True)
# Get the number of steps (which is stored in the child config file)
config_values.num_steps = env.episode_steps
# Run environment against an agent
if config_values.agent_identifier == "GENERIC":
run_generic()
elif config_values.agent_identifier == "STABLE_BASELINES3_PPO":
run_stable_baselines3_ppo()
elif config_values.agent_identifier == "STABLE_BASELINES3_A2C":
run_stable_baselines3_a2c()
print("Session finished")
logging.info("Session finished")
print("Saving transaction logs...")
logging.info("Saving transaction logs...")
write_transaction_to_file(transaction_list)
config_file_main.close
print("Finished")
logging.info("Finished")

View File

@@ -1 +0,0 @@
# Crown Copyright (C) Dstl 2022. DEFCON 703. Shared in confidence.

View File

@@ -1,134 +0,0 @@
# Crown Copyright (C) Dstl 2022. DEFCON 703. Shared in confidence.
"""
A class that implements the access control list implementation for the network
"""
from acl.acl_rule import ACLRule
class AccessControlList():
"""
Access Control List class
"""
def __init__(self):
"""
Init
"""
self.acl = {} # A dictionary of ACL Rules
def check_address_match(self, _rule, _source_ip_address, _dest_ip_address):
"""
Checks for IP address matches
Args:
_rule: The rule being checked
_source_ip_address: the source IP address to compare
_dest_ip_address: the destination IP address to compare
Returns:
True if match; False otherwise.
"""
if ((_rule.get_source_ip() == _source_ip_address and _rule.get_dest_ip() == _dest_ip_address) or
(_rule.get_source_ip() == "ANY" and _rule.get_dest_ip() == _dest_ip_address) or
(_rule.get_source_ip() == _source_ip_address and _rule.get_dest_ip() == "ANY") or
(_rule.get_source_ip() == "ANY" and _rule.get_dest_ip() == "ANY")):
return True
else:
return False
def is_blocked(self, _source_ip_address, _dest_ip_address, _protocol, _port):
"""
Checks for rules that block a protocol / port
Args:
_source_ip_address: the source IP address to check
_dest_ip_address: the destination IP address to check
_protocol: the protocol to check
_port: the port to check
Returns:
Indicates block if all conditions are satisfied.
"""
for rule_key, rule_value in self.acl.items():
if self.check_address_match(rule_value, _source_ip_address, _dest_ip_address):
if ((rule_value.get_protocol() == _protocol or rule_value.get_protocol() == "ANY") and
(str(rule_value.get_port()) == str(_port) or rule_value.get_port() == "ANY")):
# There's a matching rule. Get the permission
if rule_value.get_permission() == "DENY":
return True
elif rule_value.get_permission() == "ALLOW":
return False
# If there has been no rule to allow the IER through, it will return a blocked signal by default
return True
def add_rule(self, _permission, _source_ip, _dest_ip, _protocol, _port):
"""
Adds a new rule
Args:
_permission: the permission value (e.g. "ALLOW" or "DENY")
_source_ip: the source IP address
_dest_ip: the destination IP address
_protocol: the protocol
_port: the port
"""
new_rule = ACLRule(_permission, _source_ip, _dest_ip, _protocol, str(_port))
hash_value = hash(new_rule)
self.acl[hash_value] = new_rule
def remove_rule(self, _permission, _source_ip, _dest_ip, _protocol, _port):
"""
Removes a rule
Args:
_permission: the permission value (e.g. "ALLOW" or "DENY")
_source_ip: the source IP address
_dest_ip: the destination IP address
_protocol: the protocol
_port: the port
"""
rule = ACLRule(_permission, _source_ip, _dest_ip, _protocol, str(_port))
hash_value = hash(rule)
# There will not always be something 'popable' since the agent will be trying random things
try:
self.acl.pop(hash_value)
except:
return
def remove_all_rules(self):
"""
Removes all rules
"""
self.acl.clear()
def get_dictionary_hash(self, _permission, _source_ip, _dest_ip, _protocol, _port):
"""
Produces a hash value for a rule
Args:
_permission: the permission value (e.g. "ALLOW" or "DENY")
_source_ip: the source IP address
_dest_ip: the destination IP address
_protocol: the protocol
_port: the port
Returns:
Hash value based on rule parameters.
"""
rule = ACLRule(_permission, _source_ip, _dest_ip, _protocol, str(_port))
hash_value = hash(rule)
return hash_value

View File

@@ -1,88 +0,0 @@
# Crown Copyright (C) Dstl 2022. DEFCON 703. Shared in confidence.
"""
A class that implements an access control list rule
"""
class ACLRule():
"""
Access Control List Rule class
"""
def __init__(self, _permission, _source_ip, _dest_ip, _protocol, _port):
"""
Init
Args:
_permission: The permission (ALLOW or DENY)
_source_ip: The source IP address
_dest_ip: The destination IP address
_protocol: The rule protocol
_port: The rule port
"""
self.permission = _permission
self.source_ip = _source_ip
self.dest_ip = _dest_ip
self.protocol = _protocol
self.port = _port
def __hash__(self):
"""
Override the hash function
Returns:
Returns hash of core parameters.
"""
return hash((self.permission, self.source_ip, self.dest_ip, self.protocol, self.port))
def get_permission(self):
"""
Gets the permission attribute
Returns:
Returns permission attribute
"""
return self.permission
def get_source_ip(self):
"""
Gets the source IP address attribute
Returns:
Returns source IP address attribute
"""
return self.source_ip
def get_dest_ip(self):
"""
Gets the desintation IP address attribute
Returns:
Returns destination IP address attribute
"""
return self.dest_ip
def get_protocol(self):
"""
Gets the protocol attribute
Returns:
Returns protocol attribute
"""
return self.protocol
def get_port(self):
"""
Gets the port attribute
Returns:
Returns port attribute
"""
return self.port

View File

@@ -1,2 +0,0 @@
# Crown Copyright (C) Dstl 2022. DEFCON 703. Shared in confidence.

View File

@@ -1,91 +0,0 @@
# Crown Copyright (C) Dstl 2022. DEFCON 703. Shared in confidence.
"""
The config class
"""
class config_values_main(object):
"""
Class to hold main config values
"""
def __init__(self):
"""
Init
"""
# Generic
self.agent_identifier = "" # the agent in use
self.num_episodes = 0 # number of episodes to train over
self.num_steps = 0 # number of steps in an episode
self.time_delay = 0 # delay between steps (ms) - applies to generic agents only
self.config_filename_use_case = "" # the filename for the Use Case config file
self.session_type = "" # the session type to run (TRAINING or EVALUATION)
# Environment
self.observation_space_high_value = 0 # The high value for the observation space
# Reward values
# Generic
self.all_ok = 0
# Node Operating State
self.off_should_be_on = 0
self.off_should_be_resetting = 0
self.on_should_be_off = 0
self.on_should_be_resetting = 0
self.resetting_should_be_on = 0
self.resetting_should_be_off = 0
self.resetting = 0
# Node O/S or Service State
self.good_should_be_patching = 0
self.good_should_be_compromised = 0
self.good_should_be_overwhelmed = 0
self.patching_should_be_good = 0
self.patching_should_be_compromised = 0
self.patching_should_be_overwhelmed = 0
self.patching = 0
self.compromised_should_be_good = 0
self.compromised_should_be_patching = 0
self.compromised_should_be_overwhelmed = 0
self.compromised = 0
self.overwhelmed_should_be_good = 0
self.overwhelmed_should_be_patching = 0
self.overwhelmed_should_be_compromised = 0
self.overwhelmed = 0
# Node File System State
self.good_should_be_repairing = 0
self.good_should_be_restoring = 0
self.good_should_be_corrupt = 0
self.good_should_be_destroyed = 0
self.repairing_should_be_good = 0
self.repairing_should_be_restoring = 0
self.repairing_should_be_corrupt = 0
self.repairing_should_be_destroyed = 0 # Repairing does not fix destroyed state - you need to restore
self.repairing = 0
self.restoring_should_be_good = 0
self.restoring_should_be_repairing = 0
self.restoring_should_be_corrupt = 0 # Not the optimal method (as repair will fix corruption)
self.restoring_should_be_destroyed = 0
self.restoring = 0
self.corrupt_should_be_good = 0
self.corrupt_should_be_repairing = 0
self.corrupt_should_be_restoring = 0
self.corrupt_should_be_destroyed = 0
self.corrupt = 0
self.destroyed_should_be_good = 0
self.destroyed_should_be_repairing = 0
self.destroyed_should_be_restoring = 0
self.destroyed_should_be_corrupt = 0
self.destroyed = 0
self.scanning = 0
# IER status
self.red_ier_running = 0
self.green_ier_blocked = 0
# Patching / Reset
self.os_patching_duration = 0 # The time taken to patch the OS
self.node_reset_duration = 0 # The time taken to reset a node (hardware)
self.service_patching_duration = 0 # The time taken to patch a service
self.file_system_repairing_limit = 0 # The time take to repair a file
self.file_system_restoring_limit = 0 # The time take to restore a file
self.file_system_scanning_limit = 0 # The time taken to scan the file system

View File

@@ -1,104 +0,0 @@
# Crown Copyright (C) Dstl 2022. DEFCON 703. Shared in confidence.
"""
Enumerations for APE
"""
from enum import Enum
class TYPE(Enum):
"""
Node type enumeration
"""
CCTV = 1
SWITCH = 2
COMPUTER = 3
LINK = 4
MONITOR = 5
PRINTER = 6
LOP = 7
RTU = 8
ACTUATOR = 9
SERVER = 10
class PRIORITY(Enum):
"""
Node priority enumeration
"""
P1 = 1
P2 = 2
P3 = 3
P4 = 4
P5 = 5
class HARDWARE_STATE(Enum):
"""
Node hardware state enumeration
"""
ON = 1
OFF = 2
RESETTING = 3
class SOFTWARE_STATE(Enum):
"""
O/S or Service state enumeration
"""
GOOD = 1
PATCHING = 2
COMPROMISED = 3
OVERWHELMED = 4
class NODE_POL_TYPE(Enum):
"""
Node Pattern of Life type enumeration
"""
OPERATING = 1
OS = 2
SERVICE = 3
FILE = 4
class NODE_POL_INITIATOR(Enum):
"""
Node Pattern of Life initiator enumeration
"""
DIRECT = 1
IER = 2
SERVICE = 3
class PROTOCOL(Enum):
"""
Service protocol enumeration
"""
LDAP = 0
FTP = 1
HTTPS = 2
SMTP = 3
RTP = 4
IPP = 5
TCP = 6
NONE = 7
class ACTION_TYPE(Enum):
"""
Action type enumeration
"""
NODE = 0
ACL = 1
class FILE_SYSTEM_STATE(Enum):
"""
File System State
"""
GOOD = 1
CORRUPT = 2
DESTROYED = 3
REPAIRING = 4
RESTORING = 5

View File

@@ -1,59 +0,0 @@
# Crown Copyright (C) Dstl 2022. DEFCON 703. Shared in confidence.
"""
The protocol class
"""
class Protocol(object):
"""
Protocol class
"""
def __init__(self, _name):
"""
Init
Args:
_name: The protocol name
"""
self.name = _name
self.load = 0 # bps
def get_name(self):
"""
Gets the protocol name
Returns:
The protocol name
"""
return self.name
def get_load(self):
"""
Gets the protocol load
Returns:
The protocol load (bps)
"""
return self.load
def add_load(self, _load):
"""
Adds load to the protocol
Args:
_load: The load to add
"""
self.load += _load
def clear_load(self):
"""
Clears the load on this protocol
"""
self.load = 0

View File

@@ -1,100 +0,0 @@
# Crown Copyright (C) Dstl 2022. DEFCON 703. Shared in confidence.
"""
The Service class
"""
from common.enums import SOFTWARE_STATE
class Service(object):
"""
Service class
"""
def __init__(self, _name, _port, _state):
"""
Init
Args:
_name: The service name
_port: The service port
_state: The service state
"""
self.name = _name
self.port = _port
self.state = _state
self.patching_count = 0
def set_name(self, _name):
"""
Sets the service name
Args:
_name: The service name
"""
self.name = _name
def get_name(self):
"""
Gets the service name
Returns:
The service name
"""
return self.name
def set_port(self, _port):
"""
Sets the service port
Args:
_port: The service port
"""
self.port = _port
def get_port(self):
"""
Gets the service port
Returns:
The service port
"""
return self.port
def set_state(self, _state):
"""
Sets the service state
Args:
_state: The service state
"""
self.state = _state
def get_state(self):
"""
Gets the service state
Returns:
The service state
"""
return self.state
def reduce_patching_count(self):
"""
Reduces the patching count for the service
"""
self.patching_count -= 1
if self.patching_count <= 0:
self.patching_count = 0
self.state = SOFTWARE_STATE.GOOD

View File

@@ -1,169 +0,0 @@
- itemType: ACTIONS
type: NODE
- itemType: STEPS
steps: 128
- itemType: PORTS
portsList:
- port: '80'
- itemType: SERVICES
serviceList:
- name: TCP
- itemType: NODE
id: '1'
name: PC1
baseType: SERVICE
nodeType: COMPUTER
priority: P5
hardwareState: 'ON'
ipAddress: 192.168.1.2
softwareState: GOOD
fileSystemState: GOOD
services:
- name: TCP
port: '80'
state: GOOD
- itemType: NODE
id: '2'
name: SERVER
baseType: SERVICE
nodeType: SERVER
priority: P5
hardwareState: 'ON'
ipAddress: 192.168.1.3
softwareState: GOOD
fileSystemState: GOOD
services:
- name: TCP
port: '80'
state: GOOD
- itemType: NODE
id: '3'
name: PC2
baseType: SERVICE
nodeType: COMPUTER
priority: P5
hardwareState: 'ON'
ipAddress: 192.168.1.4
softwareState: GOOD
fileSystemState: GOOD
services:
- name: TCP
port: '80'
state: GOOD
- itemType: NODE
id: '4'
name: SWITCH1
baseType: ACTIVE
nodeType: SWITCH
priority: P2
hardwareState: 'ON'
ipAddress: 192.168.1.5
softwareState: GOOD
fileSystemState: GOOD
- itemType: NODE
id: '5'
name: SWITCH2
baseType: ACTIVE
nodeType: SWITCH
priority: P2
hardwareState: 'ON'
ipAddress: 192.168.1.6
softwareState: GOOD
fileSystemState: GOOD
- itemType: NODE
id: '6'
name: SWITCH3
baseType: ACTIVE
nodeType: SWITCH
priority: P2
hardwareState: 'ON'
ipAddress: 192.168.1.7
softwareState: GOOD
fileSystemState: GOOD
- itemType: LINK
id: '7'
name: link1
bandwidth: 1000000000
source: '1'
destination: '4'
- itemType: LINK
id: '8'
name: link2
bandwidth: 1000000000
source: '4'
destination: '2'
- itemType: LINK
id: '9'
name: link3
bandwidth: 1000000000
source: '2'
destination: '5'
- itemType: LINK
id: '10'
name: link4
bandwidth: 1000000000
source: '2'
destination: '6'
- itemType: LINK
id: '11'
name: link5
bandwidth: 1000000000
source: '5'
destination: '3'
- itemType: LINK
id: '12'
name: link6
bandwidth: 1000000000
source: '6'
destination: '3'
- itemType: GREEN_IER
id: '13'
startStep: 1
endStep: 128
load: 100000
protocol: TCP
port: '80'
source: '3'
destination: '2'
missionCriticality: 5
- itemType: RED_POL
id: '14'
startStep: 50
endStep: 50
targetNodeId: '1'
initiator: DIRECT
type: SERVICE
protocol: TCP
state: COMPROMISED
sourceNodeId: NA
sourceNodeService: NA
sourceNodeServiceState: NA
- itemType: RED_IER
id: '15'
startStep: 60
endStep: 100
load: 1000000
protocol: TCP
port: '80'
source: '1'
destination: '2'
missionCriticality: 0
- itemType: RED_POL
id: '16'
startStep: 80
endStep: 80
targetNodeId: '2'
initiator: IER
type: SERVICE
protocol: TCP
state: COMPROMISED
sourceNodeId: NA
sourceNodeService: NA
sourceNodeServiceState: NA
- itemType: ACL_RULE
id: '17'
permission: ALLOW
source: ANY
destination: ANY
protocol: ANY
port: ANY

View File

@@ -1,361 +0,0 @@
- itemType: ACTIONS
type: NODE
- itemType: STEPS
steps: 128
- itemType: PORTS
portsList:
- port: '80'
- itemType: SERVICES
serviceList:
- name: TCP
- itemType: NODE
id: '1'
name: PC1
baseType: SERVICE
nodeType: COMPUTER
priority: P5
hardwareState: 'ON'
ipAddress: 192.168.10.11
softwareState: GOOD
fileSystemState: GOOD
services:
- name: TCP
port: '80'
state: GOOD
- itemType: NODE
id: '2'
name: PC2
baseType: SERVICE
nodeType: COMPUTER
priority: P5
hardwareState: 'ON'
ipAddress: 192.168.10.12
softwareState: GOOD
fileSystemState: GOOD
services:
- name: TCP
port: '80'
state: GOOD
- itemType: NODE
id: '3'
name: PC3
baseType: SERVICE
nodeType: COMPUTER
priority: P5
hardwareState: 'ON'
ipAddress: 192.168.10.13
softwareState: GOOD
fileSystemState: GOOD
services:
- name: TCP
port: '80'
state: GOOD
- itemType: NODE
id: '4'
name: PC4
baseType: SERVICE
nodeType: COMPUTER
priority: P5
hardwareState: 'ON'
ipAddress: 192.168.20.14
softwareState: GOOD
fileSystemState: GOOD
services:
- name: TCP
port: '80'
state: GOOD
- itemType: NODE
id: '5'
name: SWITCH1
baseType: ACTIVE
nodeType: SWITCH
priority: P2
hardwareState: 'ON'
ipAddress: 192.168.1.2
softwareState: GOOD
fileSystemState: GOOD
- itemType: NODE
id: '6'
name: IDS
baseType: SERVICE
nodeType: SERVER
priority: P5
hardwareState: 'ON'
ipAddress: 192.168.1.4
softwareState: GOOD
fileSystemState: GOOD
services:
- name: TCP
port: '80'
state: GOOD
- itemType: NODE
id: '7'
name: SWITCH2
baseType: ACTIVE
nodeType: SWITCH
priority: P2
hardwareState: 'ON'
ipAddress: 192.168.1.3
softwareState: GOOD
fileSystemState: GOOD
- itemType: NODE
id: '8'
name: LOP1
baseType: SERVICE
nodeType: LOP
priority: P5
hardwareState: 'ON'
ipAddress: 192.168.1.12
softwareState: GOOD
fileSystemState: GOOD
services:
- name: TCP
port: '80'
state: GOOD
- itemType: NODE
id: '9'
name: SERVER1
baseType: SERVICE
nodeType: SERVER
priority: P5
hardwareState: 'ON'
ipAddress: 192.168.10.14
softwareState: GOOD
fileSystemState: GOOD
services:
- name: TCP
port: '80'
state: GOOD
- itemType: NODE
id: '10'
name: SERVER2
baseType: SERVICE
nodeType: SERVER
priority: P5
hardwareState: 'ON'
ipAddress: 192.168.20.15
softwareState: GOOD
fileSystemState: GOOD
services:
- name: TCP
port: '80'
state: GOOD
- itemType: LINK
id: '11'
name: link1
bandwidth: 1000000000
source: '1'
destination: '5'
- itemType: LINK
id: '12'
name: link2
bandwidth: 1000000000
source: '2'
destination: '5'
- itemType: LINK
id: '13'
name: link3
bandwidth: 1000000000
source: '3'
destination: '5'
- itemType: LINK
id: '14'
name: link4
bandwidth: 1000000000
source: '4'
destination: '5'
- itemType: LINK
id: '15'
name: link5
bandwidth: 1000000000
source: '5'
destination: '6'
- itemType: LINK
id: '16'
name: link6
bandwidth: 1000000000
source: '5'
destination: '8'
- itemType: LINK
id: '17'
name: link7
bandwidth: 1000000000
source: '6'
destination: '7'
- itemType: LINK
id: '18'
name: link8
bandwidth: 1000000000
source: '8'
destination: '7'
- itemType: LINK
id: '19'
name: link9
bandwidth: 1000000000
source: '7'
destination: '9'
- itemType: LINK
id: '20'
name: link10
bandwidth: 1000000000
source: '7'
destination: '10'
- itemType: GREEN_IER
id: '21'
startStep: 1
endStep: 128
load: 100000
protocol: TCP
port: '80'
source: '1'
destination: '9'
missionCriticality: 2
- itemType: GREEN_IER
id: '22'
startStep: 1
endStep: 128
load: 100000
protocol: TCP
port: '80'
source: '2'
destination: '9'
missionCriticality: 2
- itemType: GREEN_IER
id: '23'
startStep: 1
endStep: 128
load: 100000
protocol: TCP
port: '80'
source: '9'
destination: '3'
missionCriticality: 5
- itemType: GREEN_IER
id: '24'
startStep: 1
endStep: 128
load: 100000
protocol: TCP
port: '80'
source: '4'
destination: '10'
missionCriticality: 2
- itemType: ACL_RULE
id: '25'
permission: ALLOW
source: 192.168.10.11
destination: 192.168.10.14
protocol: TCP
port: 80
- itemType: ACL_RULE
id: '26'
permission: ALLOW
source: 192.168.10.12
destination: 192.168.10.14
protocol: TCP
port: 80
- itemType: ACL_RULE
id: '27'
permission: ALLOW
source: 192.168.10.13
destination: 192.168.10.14
protocol: TCP
port: 80
- itemType: ACL_RULE
id: '28'
permission: ALLOW
source: 192.168.20.14
destination: 192.168.20.15
protocol: TCP
port: 80
- itemType: ACL_RULE
id: '29'
permission: ALLOW
source: 192.168.10.14
destination: 192.168.10.13
protocol: TCP
port: 80
- itemType: ACL_RULE
id: '30'
permission: DENY
source: 192.168.10.11
destination: 192.168.20.15
protocol: TCP
port: 80
- itemType: ACL_RULE
id: '31'
permission: DENY
source: 192.168.10.12
destination: 192.168.20.15
protocol: TCP
port: 80
- itemType: ACL_RULE
id: '32'
permission: DENY
source: 192.168.10.13
destination: 192.168.20.15
protocol: TCP
port: 80
- itemType: ACL_RULE
id: '33'
permission: DENY
source: 192.168.20.14
destination: 192.168.10.14
protocol: TCP
port: 80
- itemType: RED_POL
id: '34'
startStep: 20
endStep: 20
targetNodeId: '1'
initiator: DIRECT
type: SERVICE
protocol: TCP
state: COMPROMISED
sourceNodeId: NA
sourceNodeService: NA
sourceNodeServiceState: NA
- itemType: RED_POL
id: '35'
startStep: 20
endStep: 20
targetNodeId: '2'
initiator: DIRECT
type: SERVICE
protocol: TCP
state: COMPROMISED
sourceNodeId: NA
sourceNodeService: NA
sourceNodeServiceState: NA
- itemType: RED_IER
id: '36'
startStep: 30
endStep: 128
load: 440000000
protocol: TCP
port: '80'
source: '1'
destination: '9'
missionCriticality: 0
- itemType: RED_IER
id: '37'
startStep: 30
endStep: 128
load: 440000000
protocol: TCP
port: '80'
source: '2'
destination: '9'
missionCriticality: 0
- itemType: RED_POL
id: '38'
startStep: 30
endStep: 30
targetNodeId: '9'
initiator: IER
type: SERVICE
protocol: TCP
state: OVERWHELMED
sourceNodeId: NA
sourceNodeService: NA
sourceNodeServiceState: NA

View File

@@ -1,165 +0,0 @@
- itemType: ACTIONS
type: NODE
- itemType: STEPS
steps: 256
- itemType: PORTS
portsList:
- port: '80'
- itemType: SERVICES
serviceList:
- name: TCP
- itemType: NODE
id: '1'
name: PC1
baseType: SERVICE
nodeType: COMPUTER
priority: P5
hardwareState: 'ON'
ipAddress: 192.168.1.2
softwareState: GOOD
fileSystemState: GOOD
services:
- name: TCP
port: '80'
state: GOOD
- itemType: NODE
id: '2'
name: PC2
baseType: SERVICE
nodeType: COMPUTER
priority: P5
hardwareState: 'ON'
ipAddress: 192.168.1.3
softwareState: GOOD
fileSystemState: GOOD
services:
- name: TCP
port: '80'
state: GOOD
- itemType: NODE
id: '3'
name: SWITCH1
baseType: ACTIVE
nodeType: SWITCH
priority: P2
hardwareState: 'ON'
ipAddress: 192.168.1.1
softwareState: GOOD
fileSystemState: GOOD
- itemType: NODE
id: '4'
name: SERVER1
baseType: SERVICE
nodeType: SERVER
priority: P5
hardwareState: 'ON'
ipAddress: 192.168.1.4
softwareState: GOOD
fileSystemState: GOOD
services:
- name: TCP
port: '80'
state: GOOD
- itemType: LINK
id: '5'
name: link1
bandwidth: 1000000000
source: '1'
destination: '3'
- itemType: LINK
id: '6'
name: link2
bandwidth: 1000000000
source: '2'
destination: '3'
- itemType: LINK
id: '7'
name: link3
bandwidth: 1000000000
source: '3'
destination: '4'
- itemType: GREEN_IER
id: '8'
startStep: 1
endStep: 256
load: 10000
protocol: TCP
port: '80'
source: '1'
destination: '4'
missionCriticality: 1
- itemType: GREEN_IER
id: '9'
startStep: 1
endStep: 256
load: 10000
protocol: TCP
port: '80'
source: '2'
destination: '4'
missionCriticality: 1
- itemType: GREEN_IER
id: '10'
startStep: 1
endStep: 256
load: 10000
protocol: TCP
port: '80'
source: '4'
destination: '2'
missionCriticality: 5
- itemType: ACL_RULE
id: '11'
permission: ALLOW
source: 192.168.1.2
destination: 192.168.1.4
protocol: TCP
port: 80
- itemType: ACL_RULE
id: '12'
permission: ALLOW
source: 192.168.1.3
destination: 192.168.1.4
protocol: TCP
port: 80
- itemType: ACL_RULE
id: '13'
permission: ALLOW
source: 192.168.1.4
destination: 192.168.1.3
protocol: TCP
port: 80
- itemType: RED_POL
id: '14'
startStep: 20
endStep: 20
targetNodeId: '1'
initiator: DIRECT
type: SERVICE
protocol: TCP
state: COMPROMISED
sourceNodeId: NA
sourceNodeService: NA
sourceNodeServiceState: NA
- itemType: RED_IER
id: '15'
startStep: 30
endStep: 256
load: 10000000
protocol: TCP
port: '80'
source: '1'
destination: '4'
missionCriticality: 0
- itemType: RED_POL
id: '16'
startStep: 40
endStep: 40
targetNodeId: '4'
initiator: IER
type: SERVICE
protocol: TCP
state: OVERWHELMED
sourceNodeId: NA
sourceNodeService: NA
sourceNodeServiceState: NA

View File

@@ -1,533 +0,0 @@
- itemType: ACTIONS
type: NODE
- itemType: STEPS
steps: 256
- itemType: PORTS
portsList:
- port: '80'
- port: '1433'
- port: '53'
- itemType: SERVICES
serviceList:
- name: TCP
- name: TCP_SQL
- name: UDP
- itemType: NODE
id: '1'
name: CLIENT_1
baseType: SERVICE
nodeType: COMPUTER
priority: P5
hardwareState: 'ON'
ipAddress: 192.168.10.11
softwareState: GOOD
fileSystemState: GOOD
services:
- name: TCP
port: '80'
state: GOOD
- name: UDP
port: '53'
state: GOOD
- itemType: NODE
id: '2'
name: CLIENT_2
baseType: SERVICE
nodeType: COMPUTER
priority: P5
hardwareState: 'ON'
ipAddress: 192.168.10.12
softwareState: GOOD
fileSystemState: GOOD
services:
- name: TCP
port: '80'
state: GOOD
- itemType: NODE
id: '3'
name: SWITCH_1
baseType: ACTIVE
nodeType: SWITCH
priority: P2
hardwareState: 'ON'
ipAddress: 192.168.10.1
softwareState: GOOD
fileSystemState: GOOD
- itemType: NODE
id: '4'
name: SECURITY_SUITE
baseType: SERVICE
nodeType: SERVER
priority: P5
hardwareState: 'ON'
ipAddress: 192.168.1.10
softwareState: GOOD
fileSystemState: GOOD
services:
- name: TCP
port: '80'
state: GOOD
- name: UDP
port: '53'
state: GOOD
- itemType: NODE
id: '5'
name: MANAGEMENT_CONSOLE
baseType: SERVICE
nodeType: SERVER
priority: P5
hardwareState: 'ON'
ipAddress: 192.168.1.12
softwareState: GOOD
fileSystemState: GOOD
services:
- name: TCP
port: '80'
state: GOOD
- name: UDP
port: '53'
state: GOOD
- itemType: NODE
id: '6'
name: SWITCH_2
baseType: ACTIVE
nodeType: SWITCH
priority: P2
hardwareState: 'ON'
ipAddress: 192.168.2.1
softwareState: GOOD
fileSystemState: GOOD
- itemType: NODE
id: '7'
name: WEB_SERVER
baseType: SERVICE
nodeType: SERVER
priority: P5
hardwareState: 'ON'
ipAddress: 192.168.2.10
softwareState: GOOD
fileSystemState: GOOD
services:
- name: TCP
port: '80'
state: GOOD
- name: TCP_SQL
port: '1433'
state: GOOD
- itemType: NODE
id: '8'
name: DATABASE_SERVER
baseType: SERVICE
nodeType: SERVER
priority: P5
hardwareState: 'ON'
ipAddress: 192.168.2.14
softwareState: GOOD
fileSystemState: GOOD
services:
- name: TCP
port: '80'
state: GOOD
- name: TCP_SQL
port: '1433'
state: GOOD
- name: UDP
port: '53'
state: GOOD
- itemType: NODE
id: '9'
name: BACKUP_SERVER
baseType: SERVICE
nodeType: SERVER
priority: P5
hardwareState: 'ON'
ipAddress: 192.168.2.16
softwareState: GOOD
fileSystemState: GOOD
services:
- name: TCP
port: '80'
state: GOOD
- itemType: LINK
id: '10'
name: LINK_1
bandwidth: 1000000000
source: '1'
destination: '3'
- itemType: LINK
id: '11'
name: LINK_2
bandwidth: 1000000000
source: '2'
destination: '3'
- itemType: LINK
id: '12'
name: LINK_3
bandwidth: 1000000000
source: '3'
destination: '4'
- itemType: LINK
id: '13'
name: LINK_4
bandwidth: 1000000000
source: '3'
destination: '5'
- itemType: LINK
id: '14'
name: LINK_5
bandwidth: 1000000000
source: '4'
destination: '6'
- itemType: LINK
id: '15'
name: LINK_6
bandwidth: 1000000000
source: '5'
destination: '6'
- itemType: LINK
id: '16'
name: LINK_7
bandwidth: 1000000000
source: '6'
destination: '7'
- itemType: LINK
id: '17'
name: LINK_8
bandwidth: 1000000000
source: '6'
destination: '8'
- itemType: LINK
id: '18'
name: LINK_9
bandwidth: 1000000000
source: '6'
destination: '9'
- itemType: GREEN_IER
id: '19'
startStep: 1
endStep: 256
load: 10000
protocol: TCP
port: '80'
source: '1'
destination: '7'
missionCriticality: 5
- itemType: GREEN_IER
id: '20'
startStep: 1
endStep: 256
load: 10000
protocol: TCP
port: '80'
source: '7'
destination: '1'
missionCriticality: 5
- itemType: GREEN_IER
id: '21'
startStep: 1
endStep: 256
load: 10000
protocol: TCP
port: '80'
source: '2'
destination: '7'
missionCriticality: 5
- itemType: GREEN_IER
id: '22'
startStep: 1
endStep: 256
load: 10000
protocol: TCP
port: '80'
source: '7'
destination: '2'
missionCriticality: 5
- itemType: GREEN_IER
id: '23'
startStep: 1
endStep: 256
load: 5000
protocol: TCP_SQL
port: '1433'
source: '7'
destination: '8'
missionCriticality: 5
- itemType: GREEN_IER
id: '24'
startStep: 1
endStep: 256
load: 100000
protocol: TCP_SQL
port: '1433'
source: '8'
destination: '7'
missionCriticality: 5
- itemType: GREEN_IER
id: '25'
startStep: 1
endStep: 256
load: 50000
protocol: TCP
port: '80'
source: '1'
destination: '9'
missionCriticality: 2
- itemType: GREEN_IER
id: '26'
startStep: 1
endStep: 256
load: 50000
protocol: TCP
port: '80'
source: '2'
destination: '9'
missionCriticality: 2
- itemType: GREEN_IER
id: '27'
startStep: 1
endStep: 256
load: 5000
protocol: TCP
port: '80'
source: '5'
destination: '7'
missionCriticality: 1
- itemType: GREEN_IER
id: '28'
startStep: 1
endStep: 256
load: 5000
protocol: TCP
port: '80'
source: '7'
destination: '5'
missionCriticality: 1
- itemType: GREEN_IER
id: '29'
startStep: 1
endStep: 256
load: 5000
protocol: TCP
port: '80'
source: '5'
destination: '8'
missionCriticality: 1
- itemType: GREEN_IER
id: '30'
startStep: 1
endStep: 256
load: 5000
protocol: TCP
port: '80'
source: '8'
destination: '5'
missionCriticality: 1
- itemType: GREEN_IER
id: '31'
startStep: 1
endStep: 256
load: 5000
protocol: TCP
port: '80'
source: '5'
destination: '9'
missionCriticality: 1
- itemType: GREEN_IER
id: '32'
startStep: 1
endStep: 256
load: 5000
protocol: TCP
port: '80'
source: '9'
destination: '5'
missionCriticality: 1
- itemType: ACL_RULE
id: '33'
permission: ALLOW
source: 192.168.10.11
destination: 192.168.2.10
protocol: ANY
port: ANY
- itemType: ACL_RULE
id: '34'
permission: ALLOW
source: 192.168.10.11
destination: 192.168.2.14
protocol: ANY
port: ANY
- itemType: ACL_RULE
id: '35'
permission: ALLOW
source: 192.168.10.12
destination: 192.168.2.14
protocol: ANY
port: ANY
- itemType: ACL_RULE
id: '36'
permission: ALLOW
source: 192.168.10.12
destination: 192.168.2.10
protocol: ANY
port: ANY
- itemType: ACL_RULE
id: '37'
permission: ALLOW
source: 192.168.2.10
destination: 192.168.10.11
protocol: ANY
port: ANY
- itemType: ACL_RULE
id: '38'
permission: ALLOW
source: 192.168.2.10
destination: 192.168.10.12
protocol: ANY
port: ANY
- itemType: ACL_RULE
id: '39'
permission: ALLOW
source: 192.168.2.10
destination: 192.168.2.14
protocol: ANY
port: ANY
- itemType: ACL_RULE
id: '40'
permission: ALLOW
source: 192.168.2.14
destination: 192.168.2.10
protocol: ANY
port: ANY
- itemType: ACL_RULE
id: '41'
permission: ALLOW
source: 192.168.10.11
destination: 192.168.2.16
protocol: ANY
port: ANY
- itemType: ACL_RULE
id: '42'
permission: ALLOW
source: 192.168.10.12
destination: 192.168.2.16
protocol: ANY
port: ANY
- itemType: ACL_RULE
id: '43'
permission: ALLOW
source: 192.168.1.12
destination: 192.168.2.10
protocol: ANY
port: ANY
- itemType: ACL_RULE
id: '44'
permission: ALLOW
source: 192.168.1.12
destination: 192.168.2.14
protocol: ANY
port: ANY
- itemType: ACL_RULE
id: '45'
permission: ALLOW
source: 192.168.1.12
destination: 192.168.2.16
protocol: ANY
port: ANY
- itemType: ACL_RULE
id: '46'
permission: ALLOW
source: 192.168.2.10
destination: 192.168.1.12
protocol: ANY
port: ANY
- itemType: ACL_RULE
id: '47'
permission: ALLOW
source: 192.168.2.14
destination: 192.168.1.12
protocol: ANY
port: ANY
- itemType: ACL_RULE
id: '48'
permission: ALLOW
source: 192.168.2.16
destination: 192.168.1.12
protocol: ANY
port: ANY
- itemType: ACL_RULE
id: '49'
permission: DENY
source: ANY
destination: ANY
protocol: ANY
port: ANY
- itemType: RED_POL
id: '50'
startStep: 50
endStep: 50
targetNodeId: '1'
initiator: DIRECT
type: SERVICE
protocol: UDP
state: COMPROMISED
sourceNodeId: NA
sourceNodeService: NA
sourceNodeServiceState: NA
- itemType: RED_IER
id: '51'
startStep: 75
endStep: 105
load: 10000
protocol: UDP
port: '53'
source: '1'
destination: '8'
missionCriticality: 0
- itemType: RED_POL
id: '52'
startStep: 100
endStep: 100
targetNodeId: '8'
initiator: IER
type: SERVICE
protocol: UDP
state: COMPROMISED
sourceNodeId: NA
sourceNodeService: NA
sourceNodeServiceState: NA
- itemType: RED_POL
id: '53'
startStep: 105
endStep: 105
targetNodeId: '8'
initiator: SERVICE
type: FILE
protocol: NA
state: CORRUPT
sourceNodeId: '8'
sourceNodeService: UDP
sourceNodeServiceState: COMPROMISED
- itemType: RED_POL
id: '54'
startStep: 105
endStep: 105
targetNodeId: '8'
initiator: SERVICE
type: SERVICE
protocol: TCP_SQL
state: COMPROMISED
sourceNodeId: '8'
sourceNodeService: UDP
sourceNodeServiceState: COMPROMISED
- itemType: RED_POL
id: '55'
startStep: 125
endStep: 125
targetNodeId: '7'
initiator: SERVICE
type: SERVICE
protocol: TCP
state: OVERWHELMED
sourceNodeId: '8'
sourceNodeService: TCP_SQL
sourceNodeServiceState: COMPROMISED

View File

@@ -1,533 +0,0 @@
- itemType: ACTIONS
type: NODE
- itemType: STEPS
steps: 256
- itemType: PORTS
portsList:
- port: '80'
- port: '1433'
- port: '53'
- itemType: SERVICES
serviceList:
- name: TCP
- name: TCP_SQL
- name: UDP
- itemType: NODE
id: '1'
name: CLIENT_1
baseType: SERVICE
nodeType: COMPUTER
priority: P5
hardwareState: 'ON'
ipAddress: 192.168.10.11
softwareState: GOOD
fileSystemState: GOOD
services:
- name: TCP
port: '80'
state: GOOD
- name: UDP
port: '53'
state: GOOD
- itemType: NODE
id: '2'
name: CLIENT_2
baseType: SERVICE
nodeType: COMPUTER
priority: P5
hardwareState: 'ON'
ipAddress: 192.168.10.12
softwareState: GOOD
fileSystemState: GOOD
services:
- name: TCP
port: '80'
state: GOOD
- itemType: NODE
id: '3'
name: SWITCH_1
baseType: ACTIVE
nodeType: SWITCH
priority: P2
hardwareState: 'ON'
ipAddress: 192.168.10.1
softwareState: GOOD
fileSystemState: GOOD
- itemType: NODE
id: '4'
name: SECURITY_SUITE
baseType: SERVICE
nodeType: SERVER
priority: P5
hardwareState: 'ON'
ipAddress: 192.168.1.10
softwareState: GOOD
fileSystemState: GOOD
services:
- name: TCP
port: '80'
state: GOOD
- name: UDP
port: '53'
state: GOOD
- itemType: NODE
id: '5'
name: MANAGEMENT_CONSOLE
baseType: SERVICE
nodeType: SERVER
priority: P5
hardwareState: 'ON'
ipAddress: 192.168.1.12
softwareState: GOOD
fileSystemState: GOOD
services:
- name: TCP
port: '80'
state: GOOD
- name: UDP
port: '53'
state: GOOD
- itemType: NODE
id: '6'
name: SWITCH_2
baseType: ACTIVE
nodeType: SWITCH
priority: P2
hardwareState: 'ON'
ipAddress: 192.168.2.1
softwareState: GOOD
fileSystemState: GOOD
- itemType: NODE
id: '7'
name: WEB_SERVER
baseType: SERVICE
nodeType: SERVER
priority: P5
hardwareState: 'ON'
ipAddress: 192.168.2.10
softwareState: GOOD
fileSystemState: GOOD
services:
- name: TCP
port: '80'
state: GOOD
- name: TCP_SQL
port: '1433'
state: GOOD
- itemType: NODE
id: '8'
name: DATABASE_SERVER
baseType: SERVICE
nodeType: SERVER
priority: P5
hardwareState: 'ON'
ipAddress: 192.168.2.14
softwareState: GOOD
fileSystemState: GOOD
services:
- name: TCP
port: '80'
state: GOOD
- name: TCP_SQL
port: '1433'
state: GOOD
- name: UDP
port: '53'
state: GOOD
- itemType: NODE
id: '9'
name: BACKUP_SERVER
baseType: SERVICE
nodeType: SERVER
priority: P5
hardwareState: 'ON'
ipAddress: 192.168.2.16
softwareState: GOOD
fileSystemState: GOOD
services:
- name: TCP
port: '80'
state: GOOD
- itemType: LINK
id: '10'
name: LINK_1
bandwidth: 1000000000
source: '1'
destination: '3'
- itemType: LINK
id: '11'
name: LINK_2
bandwidth: 1000000000
source: '2'
destination: '3'
- itemType: LINK
id: '12'
name: LINK_3
bandwidth: 1000000000
source: '3'
destination: '4'
- itemType: LINK
id: '13'
name: LINK_4
bandwidth: 1000000000
source: '3'
destination: '5'
- itemType: LINK
id: '14'
name: LINK_5
bandwidth: 1000000000
source: '4'
destination: '6'
- itemType: LINK
id: '15'
name: LINK_6
bandwidth: 1000000000
source: '5'
destination: '6'
- itemType: LINK
id: '16'
name: LINK_7
bandwidth: 1000000000
source: '6'
destination: '7'
- itemType: LINK
id: '17'
name: LINK_8
bandwidth: 1000000000
source: '6'
destination: '8'
- itemType: LINK
id: '18'
name: LINK_9
bandwidth: 1000000000
source: '6'
destination: '9'
- itemType: GREEN_IER
id: '19'
startStep: 1
endStep: 256
load: 10000
protocol: TCP
port: '80'
source: '1'
destination: '7'
missionCriticality: 5
- itemType: GREEN_IER
id: '20'
startStep: 1
endStep: 256
load: 10000
protocol: TCP
port: '80'
source: '7'
destination: '1'
missionCriticality: 5
- itemType: GREEN_IER
id: '21'
startStep: 1
endStep: 256
load: 10000
protocol: TCP
port: '80'
source: '2'
destination: '7'
missionCriticality: 5
- itemType: GREEN_IER
id: '22'
startStep: 1
endStep: 256
load: 10000
protocol: TCP
port: '80'
source: '7'
destination: '2'
missionCriticality: 5
- itemType: GREEN_IER
id: '23'
startStep: 1
endStep: 256
load: 5000
protocol: TCP_SQL
port: '1433'
source: '7'
destination: '8'
missionCriticality: 5
- itemType: GREEN_IER
id: '24'
startStep: 1
endStep: 256
load: 100000
protocol: TCP_SQL
port: '1433'
source: '8'
destination: '7'
missionCriticality: 5
- itemType: GREEN_IER
id: '25'
startStep: 1
endStep: 256
load: 50000
protocol: TCP
port: '80'
source: '1'
destination: '9'
missionCriticality: 2
- itemType: GREEN_IER
id: '26'
startStep: 1
endStep: 256
load: 50000
protocol: TCP
port: '80'
source: '2'
destination: '9'
missionCriticality: 2
- itemType: GREEN_IER
id: '27'
startStep: 1
endStep: 256
load: 5000
protocol: TCP
port: '80'
source: '5'
destination: '7'
missionCriticality: 1
- itemType: GREEN_IER
id: '28'
startStep: 1
endStep: 256
load: 5000
protocol: TCP
port: '80'
source: '7'
destination: '5'
missionCriticality: 1
- itemType: GREEN_IER
id: '29'
startStep: 1
endStep: 256
load: 5000
protocol: TCP
port: '80'
source: '5'
destination: '8'
missionCriticality: 1
- itemType: GREEN_IER
id: '30'
startStep: 1
endStep: 256
load: 5000
protocol: TCP
port: '80'
source: '8'
destination: '5'
missionCriticality: 1
- itemType: GREEN_IER
id: '31'
startStep: 1
endStep: 256
load: 5000
protocol: TCP
port: '80'
source: '5'
destination: '9'
missionCriticality: 1
- itemType: GREEN_IER
id: '32'
startStep: 1
endStep: 256
load: 5000
protocol: TCP
port: '80'
source: '9'
destination: '5'
missionCriticality: 1
- itemType: ACL_RULE
id: '33'
permission: ALLOW
source: 192.168.10.11
destination: 192.168.2.10
protocol: ANY
port: ANY
- itemType: ACL_RULE
id: '34'
permission: ALLOW
source: 192.168.10.11
destination: 192.168.2.14
protocol: ANY
port: ANY
- itemType: ACL_RULE
id: '35'
permission: ALLOW
source: 192.168.10.12
destination: 192.168.2.14
protocol: ANY
port: ANY
- itemType: ACL_RULE
id: '36'
permission: ALLOW
source: 192.168.10.12
destination: 192.168.2.10
protocol: ANY
port: ANY
- itemType: ACL_RULE
id: '37'
permission: ALLOW
source: 192.168.2.10
destination: 192.168.10.11
protocol: ANY
port: ANY
- itemType: ACL_RULE
id: '38'
permission: ALLOW
source: 192.168.2.10
destination: 192.168.10.12
protocol: ANY
port: ANY
- itemType: ACL_RULE
id: '39'
permission: ALLOW
source: 192.168.2.10
destination: 192.168.2.14
protocol: ANY
port: ANY
- itemType: ACL_RULE
id: '40'
permission: ALLOW
source: 192.168.2.14
destination: 192.168.2.10
protocol: ANY
port: ANY
- itemType: ACL_RULE
id: '41'
permission: ALLOW
source: 192.168.10.11
destination: 192.168.2.16
protocol: ANY
port: ANY
- itemType: ACL_RULE
id: '42'
permission: ALLOW
source: 192.168.10.12
destination: 192.168.2.16
protocol: ANY
port: ANY
- itemType: ACL_RULE
id: '43'
permission: ALLOW
source: 192.168.1.12
destination: 192.168.2.10
protocol: ANY
port: ANY
- itemType: ACL_RULE
id: '44'
permission: ALLOW
source: 192.168.1.12
destination: 192.168.2.14
protocol: ANY
port: ANY
- itemType: ACL_RULE
id: '45'
permission: ALLOW
source: 192.168.1.12
destination: 192.168.2.16
protocol: ANY
port: ANY
- itemType: ACL_RULE
id: '46'
permission: ALLOW
source: 192.168.2.10
destination: 192.168.1.12
protocol: ANY
port: ANY
- itemType: ACL_RULE
id: '47'
permission: ALLOW
source: 192.168.2.14
destination: 192.168.1.12
protocol: ANY
port: ANY
- itemType: ACL_RULE
id: '48'
permission: ALLOW
source: 192.168.2.16
destination: 192.168.1.12
protocol: ANY
port: ANY
- itemType: ACL_RULE
id: '49'
permission: DENY
source: ANY
destination: ANY
protocol: ANY
port: ANY
- itemType: RED_POL
id: '50'
startStep: 50
endStep: 50
targetNodeId: '1'
initiator: DIRECT
type: SERVICE
protocol: UDP
state: COMPROMISED
sourceNodeId: NA
sourceNodeService: NA
sourceNodeServiceState: NA
- itemType: RED_IER
id: '51'
startStep: 75
endStep: 105
load: 10000
protocol: UDP
port: '53'
source: '1'
destination: '8'
missionCriticality: 0
- itemType: RED_POL
id: '52'
startStep: 100
endStep: 100
targetNodeId: '8'
initiator: IER
type: SERVICE
protocol: UDP
state: COMPROMISED
sourceNodeId: NA
sourceNodeService: NA
sourceNodeServiceState: NA
- itemType: RED_POL
id: '53'
startStep: 105
endStep: 105
targetNodeId: '8'
initiator: SERVICE
type: FILE
protocol: NA
state: CORRUPT
sourceNodeId: '8'
sourceNodeService: UDP
sourceNodeServiceState: COMPROMISED
- itemType: RED_POL
id: '54'
startStep: 105
endStep: 105
targetNodeId: '8'
initiator: SERVICE
type: SERVICE
protocol: TCP_SQL
state: COMPROMISED
sourceNodeId: '8'
sourceNodeService: UDP
sourceNodeServiceState: COMPROMISED
- itemType: RED_POL
id: '55'
startStep: 125
endStep: 125
targetNodeId: '7'
initiator: SERVICE
type: SERVICE
protocol: TCP
state: OVERWHELMED
sourceNodeId: '8'
sourceNodeService: TCP_SQL
sourceNodeServiceState: COMPROMISED

View File

@@ -1,89 +0,0 @@
# Main Config File
# Generic config values
# Choose one of these (dependent on Agent being trained)
# "STABLE_BASELINES3_PPO"
# "STABLE_BASELINES3_A2C"
# "GENERIC"
agentIdentifier: STABLE_BASELINES3_A2C
# Number of episodes to run per session
numEpisodes: 10
# Time delay between steps (for generic agents)
timeDelay: 10
# Filename of the scenario / laydown
configFilename: config_5_DATA_MANIPULATION.yaml
# Type of session to be run (TRAINING or EVALUATION)
sessionType: TRAINING
# Determine whether to load an agent from file
loadAgent: False
# File path and file name of agent if you're loading one in
agentLoadFile: C:\[Path]\[agent_saved_filename.zip]
# Environment config values
# The high value for the observation space
observationSpaceHighValue: 1000000000
# Reward values
# Generic
allOk: 0
# Node Operating State
offShouldBeOn: -10
offShouldBeResetting: -5
onShouldBeOff: -2
onShouldBeResetting: -5
resettingShouldBeOn: -5
resettingShouldBeOff: -2
resetting: -3
# Node O/S or Service State
goodShouldBePatching: 2
goodShouldBeCompromised: 5
goodShouldBeOverwhelmed: 5
patchingShouldBeGood: -5
patchingShouldBeCompromised: 2
patchingShouldBeOverwhelmed: 2
patching: -3
compromisedShouldBeGood: -20
compromisedShouldBePatching: -20
compromisedShouldBeOverwhelmed: -20
compromised: -20
overwhelmedShouldBeGood: -20
overwhelmedShouldBePatching: -20
overwhelmedShouldBeCompromised: -20
overwhelmed: -20
# Node File System State
goodShouldBeRepairing: 2
goodShouldBeRestoring: 2
goodShouldBeCorrupt: 5
goodShouldBeDestroyed: 10
repairingShouldBeGood: -5
repairingShouldBeRestoring: 2
repairingShouldBeCorrupt: 2
repairingShouldBeDestroyed: 0
repairing: -3
restoringShouldBeGood: -10
restoringShouldBeRepairing: -2
restoringShouldBeCorrupt: 1
restoringShouldBeDestroyed: 2
restoring: -6
corruptShouldBeGood: -10
corruptShouldBeRepairing: -10
corruptShouldBeRestoring: -10
corruptShouldBeDestroyed: 2
corrupt: -10
destroyedShouldBeGood: -20
destroyedShouldBeRepairing: -20
destroyedShouldBeRestoring: -20
destroyedShouldBeCorrupt: -20
destroyed: -20
scanning: -2
# IER status
redIerRunning: -5
greenIerBlocked: -10
# Patching / Reset durations
osPatchingDuration: 5 # The time taken to patch the OS
nodeResetDuration: 5 # The time taken to reset a node (hardware)
servicePatchingDuration: 5 # The time taken to patch a service
fileSystemRepairingLimit: 5 # The time take to repair the file system
fileSystemRestoringLimit: 5 # The time take to restore the file system
fileSystemScanningLimit: 5 # The time taken to scan the file system

View File

@@ -1,345 +0,0 @@
.. _about:
About PrimAITE
==============
Features
********
PrimAITE provides the following features:
* A flexible network / system laydown based on the Python networkx framework
* Nodes and links (edges) host Python classes in order to present attributes and methods (and hence, a more representative model of a platform / system)
* A green agent Information Exchange Requirement (IER) function allows the representation of traffic (protocols and loading) on any / all links. Application of IERs is based on the status of node operating systems and services
* A green agent node Pattern-of-Life (PoL) function allows the representation of core behaviours on nodes (e.g. Operating state, Operating System state, Service state, File System state)
* An Access Control List (ACL) function, mimicking the behaviour of a network firewall, is applied across the model, following standard ACL rule format (e.g. DENY/ALLOW, source IP, destination IP, protocol and port). Application of IERs adheres to any ACL restrictions
* Presents an OpenAI Gym interface to the environment, allowing integration with any OpenAI Gym compliant defensive agents
* Red agent activity based on red IERs and red PoL
* Defined reward function for use with RL agents (based on nodes status, and green / red IER success)
* Fully configurable (network / system laydown, IERs, node PoL, ACL, episode step period, episode max steps) and repeatable to suit the training requirements of agents. Therefore, not bound to a representation of any particular platform, system or technology
* Full capture of discrete metrics relating to agent training (full system state, agent actions taken, average reward)
* Networkx provides laydown visualisation capability
Architecture - Nodes and Links
******************************
**Nodes**
An inheritance model has been adopted in order to model nodes. All nodes have the following base attributes (Class: Node):
* ID
* Name
* Type (e.g. computer, switch, RTU - enumeration)
* Priority (P1, P2, P3, P4 or P5 - enumeration)
* Operating State (ON, OFF, RESETTING - enumeration)
Active Nodes also have the following attributes (Class: Active Node):
* IP Address
* Operating System State (GOOD, PATCHING, COMPROMISED - enumeration)
* File System State (GOOD, CORRUPT, DESTROYED, REPAIRING, RESTORING - enumeration)
Service Nodes also have the following attributes (Class: Service Node):
* List of Services (where service is composed of service name and port). There is no theoretical limit on the number of services that can be modelled. Services and protocols are currently intrinsically linked (i.e. a service is an application on a node transmitting traffic of this protocol type)
* Service state (GOOD, PATCHING, COMPROMISED, OVERWHELMED - enumeration)
Passive Nodes are currently not used (but may be employed for non IP-based components such as machinery actuators in future releases).
**Links**
Links are modelled both as network edges (networkx) and as Python classes, in order to extend their functionality. Links include the following attributes:
* ID
* Name
* Bandwidth (bits/s)
* Source node ID
* Destination node ID
* Protocol list (containing the loading of protocols currently running on the link)
When the simulation runs, IERs are applied to the links in order to model traffic loading, individually assigned to each protocol. This allows green (background) and red agent behaviour to be modelled, and defensive agents to identify suspicious traffic patterns at a protocol / traffic loading level of fidelity.
Information Exchange Requirements (IERs)
****************************************
PrimAITE adopts the concept of Information Exchange Requirements (IERs) to model both green agent (background) and red agent (adversary) behaviour. IERs are used to initiate modelling of traffic loading on the network, and have the following attributes:
* ID
* Start step (i.e. which step in the training episode should the IER start)
* End step (i.e. which step in the training episode should the IER end)
* Source node ID
* Destination node ID
* Load (bits/s)
* Protocol
* Port
* Running status (i.e. on / off)
The application of green agent IERs between a source and destination follows a number of rules. Specifically:
1. Does the current simulation time step fall between IER start and end step
2. Is the source node operational (both physically and at an O/S level), and is the service (protocol / port) associated with the IER (a) present on this node, and (b) in an operational state (i.e. not PATCHING)
3. Is the destination node operational (both physically and at an O/S level), and is the service (protocol / port) associated with the IER (a) present on this node, and (b) in an operational state (i.e. not PATCHING)
4. Are there any Access Control List rules in place that prevent the application of this IER
5. Are all switches in the (OSPF) path between source and destination operational (both physically and at an O/S level)
For red agent IERs, the application of IERs between a source and destination follows a number of subtly different rules. Specifically:
1. Does the current simulation time step fall between IER start and end step
2. Is the source node operational, and is the service (protocol / port) associated with the IER (a) present on that node and (b) already in a compromised state
3. Is the destination node operational, and is the service (protocol / port) associated with the IER present on that node
4. Are there any Access Control List rules in place that prevent the application of this IER
5. Are all switches in the (OSPF) path between source and destination operational (both physically and at an O/S level)
Assuming the rules pass, the IER is applied to all relevant links (based on use of OSPF) between source and destination.
Node Pattern-of-Life
********************
Every node can be impacted (i.e. have a status change applied to it) by either green agent pattern-of-life or red agent pattern-of-life. This is distinct from IERs, and allows for attacks (and defence) to be modelled purely within the confines of a node.
The status changes that can be made to a node are as follows:
* All Nodes:
* Operating State:
* ON
* OFF
* RESETTING - when a status of resetting is entered, the node will automatically exit this state after a number of steps (as defined by the nodeResetDuration configuration item) after which it returns to an ON state
* Active Nodes and Service Nodes:
* Operating System State:
* GOOD
* PATCHING - when a status of patching is entered, the node will automatically exit this state after a number of steps (as defined by the osPatchingDuration configuration item) after which it returns to a GOOD state
* COMPROMISED
* File System State:
* GOOD
* CORRUPT (can be resolved by repair or restore)
* DESTROYED (can be resolved by restore only)
* REPAIRING - when a status of repairing is entered, the node will automatically exit this state after a number of steps (as defined by the fileSystemRepairingLimit configuration item) after which it returns to a GOOD state
* RESTORING - when a status of repairing is entered, the node will automatically exit this state after a number of steps (as defined by the fileSystemRestoringLimit configuration item) after which it returns to a GOOD state
* Service Nodes only:
* Service State (for any associated service):
* GOOD
* PATCHING - when a status of patching is entered, the service will automatically exit this state after a number of steps (as defined by the servicePatchingDuration configuration item) after which it returns to a GOOD state
* COMPROMISED
* OVERWHELMED
Red agent pattern-of-life has an additional feature not found in the green pattern-of-life. This is the ability to influence the state of the attributes of a node via a number of different conditions:
* DIRECT:
The pattern-of-life described by the configuration file item will be applied regardless of any other conditions in the network. This is particularly useful for direct red agent entry into the network.
* IER:
The pattern-of-life described by the configuration file item will be applied to the service on the node, only if there is an IER of the same protocol / service type incoming at the specified timestep.
* SERVICE:
The pattern-of-life described by the configuration file item will be applied to the node based on the state of a service. The service can either be on the same node, or a different node within the network.
Access Control List modelling
*****************************
An Access Control List (ACL) is modelled to provide the means to manage traffic flows in the system. This will allow defensive agents the means to turn on / off rules, or potentially create new rules, to counter an attack.
The ACL follows a standard network firewall format. For example:
.. list-table:: ACL example
:widths: 25 25 25 25 25
:header-rows: 1
* - Permission
- Source IP
- Dest IP
- Protocol
- Port
* - DENY
- 192.168.1.2
- 192.168.1.3
- HTTPS
- 443
* - ALLOW
- 192.168.1.4
- ANY
- SMTP
- 25
* - DENY
- ANY
- 192.168.1.5
- ANY
- ANY
All ACL rules are considered when applying an IER. Logic follows the order of rules, so a DENY or ALLOW for the same parameters will override an earlier entry.
Observation Spaces
******************
The OpenAI Gym observation space provides the status of all nodes and links across the whole system:
* Nodes (in terms of operating state, operating system state, file system state and services state)
* Links (in terms of current loading for each service/protocol)
An example observation space is provided below:
.. list-table:: Observation Space example
:widths: 25 25 25 25 25 25 25
:header-rows: 1
* -
- ID
- Operating State
- O/S State
- File System State
- Service / Protocol A
- Service / Protocol B
* - Node A
- 1
- 1
- 1
- 1
- 1
- 1
* - Node B
- 2
- 1
- 3
- 1
- 1
- 1
* - Node C
- 3
- 2
- 1
- 1
- 3
- 2
* - Link 1
- 5
- 0
- 0
- 0
- 0
- 10000
* - Link 2
- 6
- 0
- 0
- 0
- 0
- 10000
* - Link 3
- 7
- 0
- 0
- 0
- 5000
- 0
The observation space is a 6 x 6 Box type (OpenAI Gym Space) in this example. This is made up from the node and link information detailed below.
For the nodes, the following values are represented:
* ID
* Operating State:
* 1 = ON
* 2 = OFF
* 3 = RESETTING
* O/S State:
* 1 = GOOD
* 2 = PATCHING
* 3 = COMPROMISED
* Service State:
* 1 = GOOD
* 2 = PATCHING
* 3 = COMPROMISED
* 4 = OVERWHELMED
* File System State:
* 1 = GOOD
* 2 = CORRUPT
* 3 = DESTROYED
* 4 = REPAIRING
* 5 = RESTORING
(Note that each service available in the network is provided as a column, although not all nodes may utilise all services)
For the links, the following statuses are represented:
* ID
* Operating State = N/A
* O/S State = N/A
* Protocol = loading in bits/s
Action Spaces
**************
The action space available to the blue agent comes in two types:
1. Node-based
2. Access Control List
The choice of action space used during a training session is determined in the config_[name].yaml file.
**Node-Based**
The agent is able to influence the status of nodes by switching them off, resetting, or patching operating systems and services. In this instance, the action space is an OpenAI Gym multidiscrete type, as follows:
* [0, num nodes] - Node ID (0 = nothing, node ID)
* [0, 4] - What property it's acting on (0 = nothing, 1 = state, 2 = O/S state, 3 = service state, 4 = file system state)
* [0, 3] - Action on property (0 = nothing, 1 = on / scan, 2 = off / repair, 3 = reset / patch / restore)
* [0, num services] - Resolves to service ID (0 = nothing, resolves to service)
**Access Control List**
The blue agent is able to influence the configuration of the Access Control List rule set (which implements a system-wide firewall). In this instance, the action space is an OpenAI multidiscrete type, as follows:
* [0, 2] - Action (0 = do nothing, 1 = create rule, 2 = delete rule)
* [0, 1] - Permission (0 = DENY, 1 = ALLOW)
* [0, num nodes] - Source IP (0 = any, then 1 -> x resolving to IP addresses)
* [0, num nodes] - Dest IP (0 = any, then 1 -> x resolving to IP addresses)
* [0, num services] - Protocol (0 = any, then 1 -> x resolving to protocol)
* [0, num ports] - Port (0 = any, then 1 -> x resolving to port)
Rewards
*******
A reward value is presented back to the blue agent on the conclusion of every step. The reward value is calculated via two methods which combine to give the total value:
1. Node and service status
2. IER status
**Node and service status**
On every step, the status of each node is compared against both a reference environment (simulating the situation if the red and blue agents had not impacted the environment)
and the before and after state of the environment. If the comparison against the reference environment shows no difference, then the score provided is "AllOK". If there is a
difference with respect to the reference environment, the before and after states are compared, and a score determined. See :ref:`config` for details of reward values.
**IER status**
On every step, the full IER set is examined to determine whether green and red agent IERs are being permitted to run. Any red agent IERs running incur a penalty; any green agent
IERs not permitted to run also incur a penalty. See :ref:`config` for details of reward values.
Future Enhancements
*******************
The PrimAITE project has an ambition to include the following enhancements in future releases:
* Integration with a suitable standardised framework to allow multi-agent integration
* Integration with external threat emulation tools, either using off-line data, or integrating at runtime
* Provision of data such that agents can construct alternative observation spaces (as an alternative to the default PrimAITE observation space)

View File

@@ -1,28 +0,0 @@
# Configuration file for the Sphinx documentation builder.
#
# For the full list of built-in configuration values, see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Project information -----------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information
project = 'PrimAITE'
copyright = '2022, jashort'
author = 'jashort'
release = '0.1.0'
# -- General configuration ---------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration
extensions = ['sphinx_rtd_theme']
templates_path = ['_templates']
exclude_patterns = []
# -- Options for HTML output -------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output
html_theme = 'sphinx_rtd_theme'
html_static_path = ['_static']

View File

@@ -1,397 +0,0 @@
.. _config:
The Config Files Explained
==========================
PrimAITE uses two configuration files for its operation:
* config_main.yaml - used to define the top-level settings of the PrimAITE environment, and the session that is to be run.
* config_[name].yaml - used to define the low-level settings of a session, including the network laydown, green / red agent information exchange requirements (IERSs), Access Control Rules, Action Space type, and the number of steps in each episode.
config_main.yaml:
*****************
The config_main.yaml file consists of the following attributes:
**Generic Config Values**
* **agentIdentifier** [enum]
This identifies the agent to use for the session. Select from one of the following:
* GENERIC - Where a user developed agent is to be used
* STABLE_BASELINES3_PPO - Use a SB3 PPO agent
* STABLE_BASELINES3_A2C - use a SB3 A2C agent
* **numEpisodes** [int]
This defines the number of episodes that the agent will train or be evaluated over. Each episode consists of a number of steps (with step number defined in the config_[name].yaml file)
* **timeDelay** [int]
The time delay (in milliseconds) to take between each step when running a GENERIC agent session
* **configFilename** [filename]
The name of the config_[name].yaml file to use for this session
* **sessionType** [text]
Type of session to be run (TRAINING or EVALUATION)
* **loadAgent** [bool]
Determine whether to load an agent from file
* **agentLoadFile** [text]
File path and file name of agent if you're loading one in
* **observationSpaceHighValue** [int]
The high value to use for values in the observation space. This is set to 1000000000 by default, and should not need changing in most cases
**Reward-Based Config Values**
* **Generic [allOk]** [int]
The score to give when the current situation (for a given component) is no different from that expected in the baseline (i.e. as though no blue or red agent actions had been undertaken)
* **Node Operating State [offShouldBeOn]** [int]
The score to give when the node should be on, but is off
* **Node Operating State [offShouldBeResetting]** [int]
The score to give when the node should be resetting, but is off
* **Node Operating State [onShouldBeOff]** [int]
The score to give when the node should be off, but is on
* **Node Operating State [onShouldBeResetting]** [int]
The score to give when the node should be resetting, but is on
* **Node Operating State [resettingShouldBeOn]** [int]
The score to give when the node should be on, but is resetting
* **Node Operating State [resettingShouldBeOff]** [int]
The score to give when the node should be off, but is resetting
* **Node Operating State [resetting]** [int]
The score to give when the node is resetting
* **Node Operating System or Service State [goodShouldBePatching]** [int]
The score to give when the state should be patching, but is good
* **Node Operating System or Service State [goodShouldBeCompromised]** [int]
The score to give when the state should be compromised, but is good
* **Node Operating System or Service State [goodShouldBeOverwhelmed]** [int]
The score to give when the state should be overwhelmed, but is good
* **Node Operating System or Service State [patchingShouldBeGood]** [int]
The score to give when the state should be good, but is patching
* **Node Operating System or Service State [patchingShouldBeCompromised]** [int]
The score to give when the state should be compromised, but is patching
* **Node Operating System or Service State [patchingShouldBeOverwhelmed]** [int]
The score to give when the state should be overwhelmed, but is patching
* **Node Operating System or Service State [patching]** [int]
The score to give when the state is patching
* **Node Operating System or Service State [compromisedShouldBeGood]** [int]
The score to give when the state should be good, but is compromised
* **Node Operating System or Service State [compromisedShouldBePatching]** [int]
The score to give when the state should be patching, but is compromised
* **Node Operating System or Service State [compromisedShouldBeOverwhelmed]** [int]
The score to give when the state should be overwhelmed, but is compromised
* **Node Operating System or Service State [compromised]** [int]
The score to give when the state is compromised
* **Node Operating System or Service State [overwhelmedShouldBeGood]** [int]
The score to give when the state should be good, but is overwhelmed
* **Node Operating System or Service State [overwhelmedShouldBePatching]** [int]
The score to give when the state should be patching, but is overwhelmed
* **Node Operating System or Service State [overwhelmedShouldBeCompromised]** [int]
The score to give when the state should be compromised, but is overwhelmed
* **Node Operating System or Service State [overwhelmed]** [int]
The score to give when the state is overwhelmed
* **Node File System State [goodShouldBeRepairing]** [int]
The score to give when the state should be repairing, but is good
* **Node File System State [goodShouldBeRestoring]** [int]
The score to give when the state should be restoring, but is good
* **Node File System State [goodShouldBeCorrupt]** [int]
The score to give when the state should be corrupt, but is good
* **Node File System State [goodShouldBeDestroyed]** [int]
The score to give when the state should be destroyed, but is good
* **Node File System State [repairingShouldBeGood]** [int]
The score to give when the state should be good, but is repairing
* **Node File System State [repairingShouldBeRestoring]** [int]
The score to give when the state should be restoring, but is repairing
* **Node File System State [repairingShouldBeCorrupt]** [int]
The score to give when the state should be corrupt, but is repairing
* **Node File System State [repairingShouldBeDestroyed]** [int]
The score to give when the state should be destroyed, but is repairing
* **Node File System State [repairing]** [int]
The score to give when the state is repairing
* **Node File System State [restoringShouldBeGood]** [int]
The score to give when the state should be good, but is restoring
* **Node File System State [restoringShouldBeRepairing]** [int]
The score to give when the state should be repairing, but is restoring
* **Node File System State [restoringShouldBeCorrupt]** [int]
The score to give when the state should be corrupt, but is restoring
* **Node File System State [restoringShouldBeDestroyed]** [int]
The score to give when the state should be destroyed, but is restoring
* **Node File System State [restoring]** [int]
The score to give when the state is restoring
* **Node File System State [corruptShouldBeGood]** [int]
The score to give when the state should be good, but is corrupt
* **Node File System State [corruptShouldBeRepairing]** [int]
The score to give when the state should be repairing, but is corrupt
* **Node File System State [corruptShouldBeRestoring]** [int]
The score to give when the state should be restoring, but is corrupt
* **Node File System State [corruptShouldBeDestroyed]** [int]
The score to give when the state should be destroyed, but is corrupt
* **Node File System State [corrupt]** [int]
The score to give when the state is corrupt
* **Node File System State [destroyedShouldBeGood]** [int]
The score to give when the state should be good, but is destroyed
* **Node File System State [destroyedShouldBeRepairing]** [int]
The score to give when the state should be repairing, but is destroyed
* **Node File System State [destroyedShouldBeRestoring]** [int]
The score to give when the state should be restoring, but is destroyed
* **Node File System State [destroyedShouldBeCorrupt]** [int]
The score to give when the state should be corrupt, but is destroyed
* **Node File System State [destroyed]** [int]
The score to give when the state is destroyed
* **Node File System State [scanning]** [int]
The score to give when the state is scanning
* **IER Status [redIerRunning]** [int]
The score to give when a red agent IER is permitted to run
* **IER Status [greenIerBlocked]** [int]
The score to give when a green agent IER is prevented from running
**Patching / Reset Durations**
* **osPatchingDuration** [int]
The number of steps to take when patching an Operating System
* **nodeResetDuration** [int]
The number of steps to take when resetting a node's operating state
* **servicePatchingDuration** [int]
The number of steps to take when patching a service
* **fileSystemRepairingLimit** [int]:
The number of steps to take when repairing the file system
* **fileSystemRestoringLimit** [int]
The number of steps to take when restoring the file system
* **fileSystemScanningLimit** [int]
The number of steps to take when scanning the file system
config_[name].yaml:
*******************
The config_[name].yaml file consists of the following attributes:
* **itemType: ACTIONS** [enum]
Determines whether a NODE or ACL action space format is adopted for the session
* **itemType: STEPS** [int]
Determines the number of steps to run in each episode of the session
* **itemType: PORTS** [int]
Provides a list of ports modelled in this session
* **itemType: SERVICES** [freetext]
Provides a list of services modelled in this session
* **itemType: NODE**
Defines a node included in the system laydown being simulated. It should consist of the following attributes:
* **id** [int]: Unique ID for this YAML item
* **name** [freetext]: Human-readable name of the component
* **baseType** [enum]: Relates to the base type of the node. Can be SERVICE, ACTIVE or PASSIVE. PASSIVE nodes do not have an operating system or services. ACTIVE nodes have an operating system, but no services. SERVICE nodes have both an operating system and one or more services
* **nodeType** [enum]: Relates to the component type. Can be one of CCTV, SWITCH, COMPUTER, LINK, MONITOR, PRINTER, LOP, RTU, ACTUATOR or SERVER
* **priority** [enum]: Provides a priority for each node. Can be one of P1, P2, P3, P4 or P5 (which P1 being the highest)
* **hardwareState** [enum]: The initial hardware state of the node. Can be one of ON, OFF or RESETTING
* **ipAddress** [IP address]: The IP address of the component in format xxx.xxx.xxx.xxx
* **softwareState** [enum]: The intial state of the node operating system. Can be GOOD, PATCHING or COMPROMISED
* **fileSystemState** [enum]: The initial state of the node file system. Can be GOOD, CORRUPT, DESTROYED, REPAIRING or RESTORING
* **services**: For each service associated with the node:
* **name** [freetext]: Free-text name of the service, but must match one of the services defined for the system in the services list
* **port** [int]: Integer value of the port related to this service, but must match one of the ports defined for the system in the ports list
* **state** [enum]: The initial state of the service. Can be one of GOOD, PATCHING, COMPROMISED or OVERWHELMED
* **itemType: LINK**
Defines a link included in the system laydown being simulated. It should consist of the following attributes:
* **id** [int]: Unique ID for this YAML item
* **name** [freetext]: Human-readable name of the component
* **bandwidth** [int]: The bandwidth (in bits/s) of the link
* **source** [int]: The ID of the source node
* **destination** [int]: The ID of the destination node
* **itemType: GREEN_IER**
Defines a green agent Information Exchange Requirement (IER). It should consist of:
* **id** [int]: Unique ID for this YAML item
* **startStep** [int]: The start step (in the episode) for this IER to begin
* **endStep** [int]: The end step (in the episode) for this IER to finish
* **load** [int]: The load (in bits/s) for this IER to apply to links
* **protocol** [freetext]: The protocol to apply to the links. This must match a value in the services list
* **port** [int]: The port that the protocol is running on. This must match a value in the ports list
* **source** [int]: The ID of the source node
* **destination** [int]: The ID of the destination node
* **missionCriticality** [enum]: The mission criticality of this IER (with 5 being highest, 1 lowest)
* **itemType: RED_IER**
Defines a red agent Information Exchange Requirement (IER). It should consist of:
* **id** [int]: Unique ID for this YAML item
* **startStep** [int]: The start step (in the episode) for this IER to begin
* **endStep** [int]: The end step (in the episode) for this IER to finish
* **load** [int]: The load (in bits/s) for this IER to apply to links
* **protocol** [freetext]: The protocol to apply to the links. This must match a value in the services list
* **port** [int]: The port that the protocol is running on. This must match a value in the ports list
* **source** [int]: The ID of the source node
* **destination** [int]: The ID of the destination node
* **missionCriticality** [enum]: Not currently used. Default to 0
* **itemType: GREEN_POL**
Defines a green agent pattern-of-life instruction. It should consist of:
* **id** [int]: Unique ID for this YAML item
* **startStep** [int]: The start step (in the episode) for this PoL to begin
* **endStep** [int]: Not currently used. Default to same as start step
* **nodeId** [int]: The ID of the node to apply the PoL to
* **type** [enum]: The type of PoL to apply. Can be one of OPERATING, OS or SERVICE
* **protocol** [freetext]: The protocol to be affected if SERVICE type is chosen. Must match a value in the services list
* **state** [enuum]: The state to apply to the node (which represents the PoL change). Can be one of ON, OFF or RESETTING (for node state) or GOOD, PATCHING or COMPROMISED (for operating system state) or GOOD, PATCHING, COMPROMISED or OVERWHELMED (for service state)
* **itemType: RED_POL**
Defines a red agent pattern-of-life instruction. It should consist of:
* **id** [int]: Unique ID for this YAML item
* **startStep** [int]: The start step (in the episode) for this PoL to begin
* **endStep** [int]: Not currently used. Default to same as start step
* **targetNodeId** [int]: The ID of the node to apply the PoL to
* **initiator** [enum]: What initiates the PoL. Can be DIRECT, IER or SERVICE
* **type** [enum]: The type of PoL to apply. Can be one of OPERATING, OS or SERVICE
* **protocol** [freetext]: The protocol to be affected if SERVICE type is chosen. Must match a value in the services list
* **state** [enum]: The state to apply to the node (which represents the PoL change). Can be one of ON, OFF or RESETTING (for node state) or GOOD, PATCHING or COMPROMISED (for operating system state) or GOOD, PATCHING, COMPROMISED or OVERWHELMED (for service state) or GOOD, CORRUPT, DESTROYED, REPAIRING or RESTORING (for file system state)
* **sourceNodeId** [int] The ID of the source node containing the service to check (used for SERVICE initiator)
* **sourceNodeService** [freetext]: The service on the source node to check (used for SERVICE initiator). Must match a value in the services list for this node
* **sourceNodeServiceState** [enum]: The state of the source node service to check (used for SERVICE initiator). Can be one of GOOD, PATCHING, COMPROMISED or OVERWHELMED
* **itemType: ACL_RULE**
Defines an initial Access Control List (ACL) rule. It should consist of:
* **id** [int]: Unique ID for this YAML item
* **permission** [enum]: Defines either an allow or deny rule. Value must be either DENY or ALLOW
* **source** [IP address]: Defines the source IP address for the rule in xxx.xxx.xxx.xxx format
* **destination** [IP address]: Defines the destination IP address for the rule in xxx.xxx.xxx.xxx format
* **protocol** [freetext]: Defines the protocol for the rule. Must match a value in the services list
* **port** [int]: Defines the port for the rule. Must match a value in the ports list

View File

@@ -1,26 +0,0 @@
.. _dependencies:
PrimAITE Dependencies
=====================
PrimAITE is built with the following versions of dependencies:
* Python 3.10.9
* PyYAML 6.0
* numpy 1.23.5
* networkx 2.8.8
* gym 0.21.0
* matplotlib 3.6.2
* stable_baselines_3 1.6.2
The latest release of PrimAITE has been tested against the following versions of dependencies:
* Python 3.10.9
* PyYAML 6.0
* numpy 1.23.5
* networkx 2.8.8
* gym 0.21.0
* matplotlib 3.6.2
* stable_baselines_3 1.6.2

View File

@@ -1,42 +0,0 @@
.. PrimAITE documentation master file, created by
sphinx-quickstart on Thu Dec 8 09:51:18 2022.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
Welcome to PrimAITE's documentation
====================================
What is PrimAITE?
------------------------
PrimAITE (Primary-level AI Training Environment) is a simulation environment for training AI under the ARCD programme. It incorporates the functionality required of a Primary-level environment, as specified in the Dstl ARCD Training Environment Matrix document:
* The ability to model a relevant platform / system context;
* The ability to model key characteristics of a platform / system by representing connections, IP addresses, ports, traffic loading, operating systems, file system, services and processes;
* Operates at machine-speed to enable fast training cycles.
PrimAITE aims to evolve into an ARCD environment that could be used as the follow-on from Reception level approaches (e.g. YAWNING TITAN), and help bridge the Sim-to-Real gap into Secondary level environments (e.g. IMAGINARY YAK).
This is similar to the approach taken by FVEY international partners (e.g. AUS CyBORG, US NSA FARLAND and CAN CyGil). These environments are referenced by the Dstl ARCD Agent Training Environments Knowledge Transfer document (TR141342).
What is PrimAITE built with
--------------------------------------
* `OpenAI's Gym <https://gym.openai.com/>`_ is used as the basis for AI blue agent interaction with the PrimAITE environment
* `Networkx <https://github.com/networkx/networkx>`_ is used as the underlying data structure used for the PrimAITE environment
* `Stable Baselines 3 <https://github.com/DLR-RM/stable-baselines3>`_ is used as a default source of RL algorithms (although PrimAITE is not limited to SB3 agents)
Where next?
------------
The best place to start is :ref:`about`
.. toctree::
:maxdepth: 8
:caption: Contents:
about
dependencies
config
session
results

View File

@@ -1,42 +0,0 @@
.. _results:
Results, Output and Logging from PrimAITE
=========================================
PrimAITE produces four types of data:
* Outputs - Results
* Outputs - Diagrams
* Outputs - Saved agents
* Logging
Outputs can be found in the *[Install Directory]\\PRIMAITE\\PRIMAITE\\outputs* directory
Logging can be found in the *[Install Directory]\\PRIMAITE\\PRIMAITE\\logs* directory
**Outputs - Results**
PrimAITE automatically creates two sets of results from each session, and stores them in the *Results* folder:
* Average reward per episode - a csv file listing the average reward for each episode of the session. This provides, for example, an indication of the change over a training session of the reward value
* All transactions - a csv file listing the following values for every step of every episode:
* Timestamp
* Episode number
* Step number
* Initial observation space (before red and blue agent actions have been taken). Individual elements of the observation space are presented in the format OSI_X_Y
* Resulting observation space (after the red and blue agent actions have been taken) Individual elements of the observation space are presented in the format OSN_X_Y
* Reward value
* Action space (as presented by the blue agent on this step). Individual elements of the action space are presented in the format AS_X
**Outputs - Diagrams**
For each session, PrimAITE automatically creates a visualisation of the system / network laydown configuration, and stores it in the *Diagrams* folder.
**Outputs - Saved agents**
For each training session, assuming the agent being trained implements the *save()* function and this function is called by the code, PrimAITE automatically saves the agent state and stores it in the *agents* folder.
**Logging**
PrimAITE also provides output logs (for diagnosis) using the Python Logging package. These can be found in the *[Install Directory]\\PRIMAITE\\PRIMAITE\\logs* directory

View File

@@ -1,88 +0,0 @@
.. _session:
Running a PrimAITE Training or Evaluation Session
=================================================
The application will determine whether a Training or Evaluation session is being executed via the 'sessionType' value in the config_mail.yaml file. A PrimAITE session will usually be associated with a "Use Case Profile"; this document will present:
* The Use Case name, default number of steps in an episode and default number of episodes in a session. The number of steps and episodes can be modified in the configuration files
* The system laydown being modelled
* The objectives of the session (steady-state), the red agent and the blue agent (in a defensive role)
* The green agent pattern-of-life profile
* The red agent attack profile
* The observation space definition
* The action space definition
* Agent integration guidance
* Initial Access Control List settings (if applicable)
* The reward function definition
**Integrating a user defined blue agent**
Integrating a blue agent with PrimAITE requires some modification of the code within the main.py file. The main.py file consists of a number of functions, each of which will invoke training for a particular agent. These are:
* Generic (run_generic)
* Stable Baselines 3 PPO (run_stable_baselines3_ppo)
* Stable Baselines 3 A2C (run_stable_baselines3_a2c)
The selection of which agent type to use is made via the config_main.yaml file. In order to train a user generated agent,
the run_generic function should be selected, and should be modified (typically) to be:
.. code:: python
agent = MyAgent(environment, max_steps)
for episode in range(0, num_episodes):
agent.learn()
env.close()
save_agent(agent)
Where:
* *MyAgent* is the user created agent
* *environment* is the PrimAITE environment
* *max_steps* is the number of steps in an episode, as defined in the config_[name].yaml file
* *num_episodes* is the number of episodes in the session, as defined in the config_main.yaml file
* the *.learn()* function should be defined in the user created agent
* the *env.close()* function is defined within PrimAITE
* the *save_agent()* assumes that a *save()* function has been defined in the user created agent. If not, this line can be ommitted (although it is encouraged, since it will allow the agent to be saved and ported)
The code below provides a suggested format for the learn() function within the user created agent.
It's important to include the *self.environment.reset()* call within the episode loop in order that the
environment is reset between episodes. Note that the example below should not be considered exhaustive.
.. code:: python
def learn(self) :
# pre-reqs
# reset the environment
self.environment.reset()
done = False
for step in range(max_steps):
# calculate the action
action = ...
# execute the environment step
new_state, reward, done, info = self.environment.step(action)
# algorithm updates
...
# update to our new state
state = new_state
# if done, finish episode
if done == True:
break
**Running the session**
In order to execute a session, carry out the following steps:
1. Navigate to "[Install directory]\\PRIMAITE\\PRIMAITE\\”
2. Start a console window (type “CMD” in path window, or start a console window first and navigate to “[Install Directory]\\PRIMAITE\\PRIMAITE\\”)
3. Type “python main.py”
4. The session will start with an output indicating the current episode, and average reward value for the episode

View File

@@ -1,2 +0,0 @@
# Crown Copyright (C) Dstl 2022. DEFCON 703. Shared in confidence.

File diff suppressed because it is too large Load Diff

View File

@@ -1,340 +0,0 @@
# Crown Copyright (C) Dstl 2022. DEFCON 703. Shared in confidence.
"""
Implements reward function
"""
from common.enums import *
from nodes.active_node import ActiveNode
from nodes.service_node import ServiceNode
def calculate_reward_function(initial_nodes, final_nodes, reference_nodes, green_iers, red_iers, step_count, config_values):
"""
Compares the states of the initial and final nodes/links to get a reward
Args:
initial_nodes: The nodes before red and blue agents take effect
final_nodes: The nodes after red and blue agents take effect
reference_nodes: The nodes if there had been no red or blue effect
green_iers: The green IERs (should be running)
red_iers: Should be stopeed (ideally) by the blue agent
step_count: current step
config_values: Config values
"""
reward_value = 0
# For each node, compare operating state, o/s operating state, service states
for node_key, final_node in final_nodes.items():
initial_node = initial_nodes[node_key]
reference_node = reference_nodes[node_key]
# Operating State
reward_value += score_node_operating_state(final_node, initial_node, reference_node, config_values)
# Operating System State
if (isinstance(final_node, ActiveNode) or isinstance(final_node, ServiceNode)):
reward_value += score_node_os_state(final_node, initial_node, reference_node, config_values)
# Service State
if (isinstance(final_node, ServiceNode)):
reward_value += score_node_service_state(final_node, initial_node, reference_node, config_values)
# File System State
if isinstance(final_node, ActiveNode):
reward_value += score_node_file_system(final_node, initial_node, reference_node, config_values)
# Go through each red IER - penalise if it is running
for ier_key, ier_value in red_iers.items():
start_step = ier_value.get_start_step()
stop_step = ier_value.get_end_step()
if step_count >= start_step and step_count <= stop_step:
if ier_value.get_is_running():
reward_value += config_values.red_ier_running
# Go through each green IER - penalise if it's not running (weighted)
for ier_key, ier_value in green_iers.items():
start_step = ier_value.get_start_step()
stop_step = ier_value.get_end_step()
if step_count >= start_step and step_count <= stop_step:
if not ier_value.get_is_running():
reward_value += config_values.green_ier_blocked * ier_value.get_mission_criticality()
return reward_value
def score_node_operating_state(final_node, initial_node, reference_node, config_values):
"""
Calculates score relating to the operating state of a node
Args:
final_node: The node after red and blue agents take effect
initial_node: The node before red and blue agents take effect
reference_node: The node if there had been no red or blue effect
config_values: Config values
"""
score = 0
final_node_operating_state = final_node.get_state()
initial_node_operating_state = initial_node.get_state()
reference_node_operating_state = reference_node.get_state()
if final_node_operating_state == reference_node_operating_state:
# All is well - we're no different from the reference situation
score += config_values.all_ok
else:
# We're different from the reference situation
# Need to compare initial and final state of node (i.e. after red and blue actions)
if initial_node_operating_state == HARDWARE_STATE.ON:
if final_node_operating_state == HARDWARE_STATE.OFF:
score += config_values.off_should_be_on
elif final_node_operating_state == HARDWARE_STATE.RESETTING:
score += config_values.resetting_should_be_on
else:
pass
elif initial_node_operating_state == HARDWARE_STATE.OFF:
if final_node_operating_state == HARDWARE_STATE.ON:
score += config_values.on_should_be_off
elif final_node_operating_state == HARDWARE_STATE.RESETTING:
score += config_values.resetting_should_be_off
else:
pass
elif initial_node_operating_state == HARDWARE_STATE.RESETTING:
if final_node_operating_state == HARDWARE_STATE.ON:
score += config_values.on_should_be_resetting
elif final_node_operating_state == HARDWARE_STATE.OFF:
score += config_values.off_should_be_resetting
elif final_node_operating_state == HARDWARE_STATE.RESETTING:
score += config_values.resetting
else:
pass
else:
pass
return score
def score_node_os_state(final_node, initial_node, reference_node, config_values):
"""
Calculates score relating to the operating system state of a node
Args:
final_node: The node after red and blue agents take effect
initial_node: The node before red and blue agents take effect
reference_node: The node if there had been no red or blue effect
config_values: Config values
"""
score = 0
final_node_os_state = final_node.get_os_state()
initial_node_os_state = initial_node.get_os_state()
reference_node_os_state = reference_node.get_os_state()
if final_node_os_state == reference_node_os_state:
# All is well - we're no different from the reference situation
score += config_values.all_ok
else:
# We're different from the reference situation
# Need to compare initial and final state of node (i.e. after red and blue actions)
if initial_node_os_state == SOFTWARE_STATE.GOOD:
if final_node_os_state == SOFTWARE_STATE.PATCHING:
score += config_values.patching_should_be_good
elif final_node_os_state == SOFTWARE_STATE.COMPROMISED:
score += config_values.compromised_should_be_good
else:
pass
elif initial_node_os_state == SOFTWARE_STATE.PATCHING:
if final_node_os_state == SOFTWARE_STATE.GOOD:
score += config_values.good_should_be_patching
elif final_node_os_state == SOFTWARE_STATE.COMPROMISED:
score += config_values.compromised_should_be_patching
elif final_node_os_state == SOFTWARE_STATE.PATCHING:
score += config_values.patching
else:
pass
elif initial_node_os_state == SOFTWARE_STATE.COMPROMISED:
if final_node_os_state == SOFTWARE_STATE.GOOD:
score += config_values.good_should_be_compromised
elif final_node_os_state == SOFTWARE_STATE.PATCHING:
score += config_values.patching_should_be_compromised
elif final_node_os_state == SOFTWARE_STATE.COMPROMISED:
score += config_values.compromised
else:
pass
else:
pass
return score
def score_node_service_state(final_node, initial_node, reference_node, config_values):
"""
Calculates score relating to the service state(s) of a node
Args:
final_node: The node after red and blue agents take effect
initial_node: The node before red and blue agents take effect
reference_node: The node if there had been no red or blue effect
config_values: Config values
"""
score = 0
final_node_services = final_node.get_services()
initial_node_services = initial_node.get_services()
reference_node_services = reference_node.get_services()
for service_key, final_service in final_node_services.items():
reference_service = reference_node_services[service_key]
initial_service = initial_node_services[service_key]
if final_service.get_state() == reference_service.get_state():
# All is well - we're no different from the reference situation
score += config_values.all_ok
else:
# We're different from the reference situation
# Need to compare initial and final state of node (i.e. after red and blue actions)
if initial_service.get_state() == SOFTWARE_STATE.GOOD:
if final_service.get_state() == SOFTWARE_STATE.PATCHING:
score += config_values.patching_should_be_good
elif final_service.get_state() == SOFTWARE_STATE.COMPROMISED:
score += config_values.compromised_should_be_good
elif final_service.get_state() == SOFTWARE_STATE.OVERWHELMED:
score += config_values.overwhelmed_should_be_good
else:
pass
elif initial_service.get_state() == SOFTWARE_STATE.PATCHING:
if final_service.get_state() == SOFTWARE_STATE.GOOD:
score += config_values.good_should_be_patching
elif final_service.get_state() == SOFTWARE_STATE.COMPROMISED:
score += config_values.compromised_should_be_patching
elif final_service.get_state() == SOFTWARE_STATE.OVERWHELMED:
score += config_values.overwhelmed_should_be_patching
elif final_service.get_state() == SOFTWARE_STATE.PATCHING:
score += config_values.patching
else:
pass
elif initial_service.get_state() == SOFTWARE_STATE.COMPROMISED:
if final_service.get_state() == SOFTWARE_STATE.GOOD:
score += config_values.good_should_be_compromised
elif final_service.get_state() == SOFTWARE_STATE.PATCHING:
score += config_values.patching_should_be_compromised
elif final_service.get_state() == SOFTWARE_STATE.COMPROMISED:
score += config_values.compromised
elif final_service.get_state() == SOFTWARE_STATE.OVERWHELMED:
score += config_values.overwhelmed_should_be_compromised
else:
pass
elif initial_service.get_state() == SOFTWARE_STATE.OVERWHELMED:
if final_service.get_state() == SOFTWARE_STATE.GOOD:
score += config_values.good_should_be_overwhelmed
elif final_service.get_state() == SOFTWARE_STATE.PATCHING:
score += config_values.patching_should_be_overwhelmed
elif final_service.get_state() == SOFTWARE_STATE.COMPROMISED:
score += config_values.compromised_should_be_overwhelmed
elif final_service.get_state() == SOFTWARE_STATE.OVERWHELMED:
score += config_values.overwhelmed
else:
pass
else:
pass
return score
def score_node_file_system(final_node, initial_node, reference_node, config_values):
"""
Calculates score relating to the file system state of a node
Args:
final_node: The node after red and blue agents take effect
initial_node: The node before red and blue agents take effect
reference_node: The node if there had been no red or blue effect
"""
score = 0
final_node_file_system_state = final_node.get_file_system_state_actual()
initial_node_file_system_state = initial_node.get_file_system_state_actual()
reference_node_file_system_state = reference_node.get_file_system_state_actual()
final_node_scanning_state = final_node.is_scanning_file_system()
reference_node_scanning_state = reference_node.is_scanning_file_system()
# File System State
if final_node_file_system_state == reference_node_file_system_state:
# All is well - we're no different from the reference situation
score += config_values.all_ok
else:
# We're different from the reference situation
# Need to compare initial and final state of node (i.e. after red and blue actions)
if initial_node_file_system_state == FILE_SYSTEM_STATE.GOOD:
if final_node_file_system_state == FILE_SYSTEM_STATE.REPAIRING:
score += config_values.repairing_should_be_good
elif final_node_file_system_state == FILE_SYSTEM_STATE.RESTORING:
score += config_values.restoring_should_be_good
elif final_node_file_system_state == FILE_SYSTEM_STATE.CORRUPT:
score += config_values.corrupt_should_be_good
elif final_node_file_system_state == FILE_SYSTEM_STATE.DESTROYED:
score += config_values.destroyed_should_be_good
else:
pass
elif initial_node_file_system_state == FILE_SYSTEM_STATE.REPAIRING:
if final_node_file_system_state == FILE_SYSTEM_STATE.GOOD:
score += config_values.good_should_be_repairing
elif final_node_file_system_state == FILE_SYSTEM_STATE.RESTORING:
score += config_values.restoring_should_be_repairing
elif final_node_file_system_state == FILE_SYSTEM_STATE.CORRUPT:
score += config_values.corrupt_should_be_repairing
elif final_node_file_system_state == FILE_SYSTEM_STATE.DESTROYED:
score += config_values.destroyed_should_be_repairing
elif final_node_file_system_state == FILE_SYSTEM_STATE.REPAIRING:
score += config_values.repairing
else:
pass
elif initial_node_file_system_state == FILE_SYSTEM_STATE.RESTORING:
if final_node_file_system_state == FILE_SYSTEM_STATE.GOOD:
score += config_values.good_should_be_restoring
elif final_node_file_system_state == FILE_SYSTEM_STATE.REPAIRING:
score += config_values.repairing_should_be_restoring
elif final_node_file_system_state == FILE_SYSTEM_STATE.CORRUPT:
score += config_values.corrupt_should_be_restoring
elif final_node_file_system_state == FILE_SYSTEM_STATE.DESTROYED:
score += config_values.destroyed_should_be_restoring
elif final_node_file_system_state == FILE_SYSTEM_STATE.RESTORING:
score += config_values.restoring
else:
pass
elif initial_node_file_system_state == FILE_SYSTEM_STATE.CORRUPT:
if final_node_file_system_state == FILE_SYSTEM_STATE.GOOD:
score += config_values.good_should_be_corrupt
elif final_node_file_system_state == FILE_SYSTEM_STATE.REPAIRING:
score += config_values.repairing_should_be_corrupt
elif final_node_file_system_state == FILE_SYSTEM_STATE.RESTORING:
score += config_values.restoring_should_be_corrupt
elif final_node_file_system_state == FILE_SYSTEM_STATE.DESTROYED:
score += config_values.destroyed_should_be_corrupt
elif final_node_file_system_state == FILE_SYSTEM_STATE.CORRUPT:
score += config_values.corrupt
else:
pass
elif initial_node_file_system_state == FILE_SYSTEM_STATE.DESTROYED:
if final_node_file_system_state == FILE_SYSTEM_STATE.GOOD:
score += config_values.good_should_be_destroyed
elif final_node_file_system_state == FILE_SYSTEM_STATE.REPAIRING:
score += config_values.repairing_should_be_destroyed
elif final_node_file_system_state == FILE_SYSTEM_STATE.RESTORING:
score += config_values.restoring_should_be_destroyed
elif final_node_file_system_state == FILE_SYSTEM_STATE.CORRUPT:
score += config_values.corrupt_should_be_destroyed
elif final_node_file_system_state == FILE_SYSTEM_STATE.DESTROYED:
score += config_values.destroyed
else:
pass
else:
pass
# Scanning State
if final_node_scanning_state == reference_node_scanning_state:
# All is well - we're no different from the reference situation
score += config_values.all_ok
else:
# We're different from the reference situation
# We're scanning the file system which incurs a penalty (as it slows down systems)
score += config_values.scanning
return score

View File

@@ -1 +0,0 @@
# Crown Copyright (C) Dstl 2022. DEFCON 703. Shared in confidence.

View File

@@ -1,132 +0,0 @@
# Crown Copyright (C) Dstl 2022. DEFCON 703. Shared in confidence.
"""
The link class
"""
from common.protocol import Protocol
from common.enums import *
class Link(object):
"""
Link class
"""
def __init__(self, _id, _bandwidth, _source_node_name, _dest_node_name, _services):
"""
Init
Args:
_id: The IER id
_bandwidth: The bandwidth of the link (bps)
_source_node_name: The name of the source node
_dest_node_name: The name of the destination node
_protocols: The protocols to add to the link
"""
self.id = _id
self.bandwidth = _bandwidth
self.source_node_name = _source_node_name
self.dest_node_name = _dest_node_name
self.protocol_list = []
# Add the default protocols
for protocol_name in _services:
self.add_protocol(protocol_name)
def add_protocol(self, _protocol):
"""
Adds a new protocol to the list of protocols on this link
Args:
_protocol: The protocol to be added (enum)
"""
self.protocol_list.append(Protocol(_protocol))
def get_id(self):
"""
Gets link ID
Returns:
Link ID
"""
return self.id
def get_source_node_name(self):
"""
Gets source node name
Returns:
Source node name
"""
return self.source_node_name
def get_dest_node_name(self):
"""
Gets destination node name
Returns:
Destination node name
"""
return self.dest_node_name
def get_bandwidth(self):
"""
Gets bandwidth of link
Returns:
Link bandwidth (bps)
"""
return self.bandwidth
def get_protocol_list(self):
"""
Gets list of protocols on this link
Returns:
List of protocols on this link
"""
return self.protocol_list
def get_current_load(self):
"""
Gets current total load on this link
Returns:
Total load on this link (bps)
"""
total_load = 0
for protocol in self.protocol_list:
total_load += protocol.get_load()
return total_load
def add_protocol_load(self, _protocol, _load):
"""
Adds a loading to a protocol on this link
Args:
_protocol: The protocol to load
_load: The amount to load (bps)
"""
for protocol in self.protocol_list:
if protocol.get_name() == _protocol:
protocol.add_load(_load)
else:
pass
def clear_traffic(self):
"""
Clears all traffic on this link
"""
for protocol in self.protocol_list:
protocol.clear_load()

View File

@@ -1 +0,0 @@
# Crown Copyright (C) Dstl 2022. DEFCON 703. Shared in confidence.

View File

@@ -1,205 +0,0 @@
# Crown Copyright (C) Dstl 2022. DEFCON 703. Shared in confidence.
"""
An Active Node (i.e. not an actuator)
"""
from nodes.node import Node
from common.enums import *
class ActiveNode(Node):
"""
Active Node class
"""
def __init__(self, _id, _name, _type, _priority, _state, _ip_address, _os_state, _file_system_state, _config_values):
"""
Init
Args:
_id: The node ID
_name: The node name
_type: The node type (enum)
_priority: The node priority (enum)
_state: The node state (enum)
_ip_address: The node IP address
_os_state: The node Operating System state
_file_system_state: The node file system state
_config_values: The config values
"""
super().__init__(_id, _name, _type, _priority, _state, _config_values)
self.ip_address = _ip_address
# Related to O/S
self.os_state = _os_state
self.patching_count = 0
# Related to File System
self.file_system_state_actual = _file_system_state
self.file_system_state_observed = _file_system_state
self.file_system_scanning = False
self.file_system_scanning_count = 0
self.file_system_action_count = 0
def set_ip_address(self, _ip_address):
"""
Sets IP address
Args:
_ip_address: IP address
"""
self.ip_address = _ip_address
def get_ip_address(self):
"""
Gets IP address
Returns:
IP address
"""
return self.ip_address
def set_os_state(self, _os_state):
"""
Sets operating system state
Args:
_os_state: Operating system state
"""
self.os_state = _os_state
if _os_state == SOFTWARE_STATE.PATCHING:
self.patching_count = self.config_values.os_patching_duration
def set_os_state_if_not_compromised(self, _os_state):
"""
Sets operating system state if the node is not compromised
Args:
_os_state: Operating system state
"""
if self.os_state != SOFTWARE_STATE.COMPROMISED:
self.os_state = _os_state
if _os_state == SOFTWARE_STATE.PATCHING:
self.patching_count = self.config_values.os_patching_duration
def get_os_state(self):
"""
Gets operating system state
Returns:
Operating system state
"""
return self.os_state
def update_os_patching_status(self):
"""
Updates operating system status based on patching cycle
"""
self.patching_count -= 1
if self.patching_count <= 0:
self.patching_count = 0
self.os_state = SOFTWARE_STATE.GOOD
def set_file_system_state(self, _file_system_state):
"""
Sets the file system state (actual and observed)
Args:
_file_system_state: File system state
"""
self.file_system_state_actual = _file_system_state
if _file_system_state == FILE_SYSTEM_STATE.REPAIRING:
self.file_system_action_count = self.config_values.file_system_repairing_limit
self.file_system_state_observed = FILE_SYSTEM_STATE.REPAIRING
elif _file_system_state == FILE_SYSTEM_STATE.RESTORING:
self.file_system_action_count = self.config_values.file_system_restoring_limit
self.file_system_state_observed = FILE_SYSTEM_STATE.RESTORING
elif _file_system_state == FILE_SYSTEM_STATE.GOOD:
self.file_system_state_observed = FILE_SYSTEM_STATE.GOOD
def set_file_system_state_if_not_compromised(self, _file_system_state):
"""
Sets the file system state (actual and observed) if not in a compromised state
Use for green PoL to prevent it overturning a compromised state
Args:
_file_system_state: File system state
"""
if self.file_system_state_actual != FILE_SYSTEM_STATE.CORRUPT and self.file_system_state_actual != FILE_SYSTEM_STATE.DESTROYED:
self.file_system_state_actual = _file_system_state
if _file_system_state == FILE_SYSTEM_STATE.REPAIRING:
self.file_system_action_count = self.config_values.file_system_repairing_limit
self.file_system_state_observed = FILE_SYSTEM_STATE.REPAIRING
elif _file_system_state == FILE_SYSTEM_STATE.RESTORING:
self.file_system_action_count = self.config_values.file_system_restoring_limit
self.file_system_state_observed = FILE_SYSTEM_STATE.RESTORING
elif _file_system_state == FILE_SYSTEM_STATE.GOOD:
self.file_system_state_observed = FILE_SYSTEM_STATE.GOOD
def get_file_system_state_actual(self):
"""
Gets file system state (actual)
Returns:
File system state (actual)
"""
return self.file_system_state_actual
def get_file_system_state_observed(self):
"""
Gets file system state (observed)
Returns:
File system state (observed)
"""
return self.file_system_state_observed
def start_file_system_scan(self):
"""
Starts a file system scan
"""
self.file_system_scanning = True
self.file_system_scanning_count = self.config_values.file_system_scanning_limit
def is_scanning_file_system(self):
"""
Gets true/false on whether file system is being scanned
Returns:
True if file system is being scanned
"""
return self.file_system_scanning
def update_file_system_state(self):
"""
Updates file system status based on scanning / restore / repair cycle
"""
# Deprecate both the action count (for restoring or reparing) and the scanning count
self.file_system_action_count -= 1
self.file_system_scanning_count -= 1
# Reparing / Restoring updates
if self.file_system_action_count <= 0:
self.file_system_action_count = 0
if self.file_system_state_actual == FILE_SYSTEM_STATE.REPAIRING or self.file_system_state_actual == FILE_SYSTEM_STATE.RESTORING:
self.file_system_state_actual = FILE_SYSTEM_STATE.GOOD
self.file_system_state_observed = FILE_SYSTEM_STATE.GOOD
# Scanning updates
if self.file_system_scanning == True and self.file_system_scanning_count < 0:
self.file_system_state_observed = self.file_system_state_actual
self.file_system_scanning = False
self.file_system_scanning_count = 0

View File

@@ -1,176 +0,0 @@
# Crown Copyright (C) Dstl 2022. DEFCON 703. Shared in confidence.
"""
The base Node class
"""
from common.enums import *
class Node:
"""
Node class
"""
def __init__(self, _id, _name, _type, _priority, _state, _config_values):
"""
Init
Args:
_id: The node id
_name: The name of the node
_type: The type of the node
_priority: The priority of the node
_state: The state of the node
"""
self.id = _id
self.name = _name
self.type = _type
self.priority = _priority
self.operating_state = _state
self.resetting_count = 0
self.config_values = _config_values
def __repr__(self):
"""
Returns the name of the node
"""
return self.name
def set_id(self, _id):
"""
Sets the node ID
Args:
_id: The node ID
"""
self.id = _id
def get_id(self):
"""
Gets the node ID
Returns:
The node ID
"""
return self.id
def set_name(self, _name):
"""
Sets the node name
Args:
_name: The node name
"""
self.name = _name
def get_name(self):
"""
Gets the node name
Returns:
The node name
"""
return self.name
def set_type(self, _type):
"""
Sets the node type
Args:
_type: The node type
"""
self.type = _type
def get_type(self):
"""
Gets the node type
Returns:
The node type
"""
return self.type
def set_priority(self, _priority):
"""
Sets the node priority
Args:
_priority: The node priority
"""
self.priority = _priority
def get_priority(self):
"""
Gets the node priority
Returns:
The node priority
"""
return self.priority
def set_state(self, _state):
"""
Sets the node state
Args:
_state: The node state
"""
self.operating_state = _state
def get_state(self):
"""
Gets the node operating state
Returns:
The node operating state
"""
return self.operating_state
def turn_on(self):
"""
Sets the node state to ON
"""
self.operating_state = HARDWARE_STATE.ON
def turn_off(self):
"""
Sets the node state to OFF
"""
self.operating_state = HARDWARE_STATE.OFF
def reset(self):
"""
Sets the node state to Resetting and starts the reset count
"""
self.operating_state = HARDWARE_STATE.RESETTING
self.resetting_count = self.config_values.node_reset_duration
def update_resetting_status(self):
"""
Updates the resetting count
"""
self.resetting_count -= 1
if self.resetting_count <= 0:
self.resetting_count = 0
self.operating_state = HARDWARE_STATE.ON

View File

@@ -1,92 +0,0 @@
# Crown Copyright (C) Dstl 2022. DEFCON 703. Shared in confidence.
"""
Defines node behaviour for Green PoL
"""
class NodeStateInstructionGreen(object):
"""
The Node State Instruction class
"""
def __init__(self, _id, _start_step, _end_step, _node_id, _node_pol_type, _service_name, _state):
"""
Init
Args:
_id: The node state instruction id
_start_step: The start step of the instruction
_end_step: The end step of the instruction
_node_id: The id of the associated node
_node_pol_type: The pattern of life type
_service_name: The service name
_state: The state (node or service)
"""
self.id = _id
self.start_step = _start_step
self.end_step = _end_step
self.node_id = _node_id
self.node_pol_type = _node_pol_type
self.service_name = _service_name # Not used when not a service instruction
self.state = _state
def get_start_step(self):
"""
Gets the start step
Returns:
The start step
"""
return self.start_step
def get_end_step(self):
"""
Gets the end step
Returns:
The end step
"""
return self.end_step
def get_node_id(self):
"""
Gets the node ID
Returns:
The node ID
"""
return self.node_id
def get_node_pol_type(self):
"""
Gets the node pattern of life type (enum)
Returns:
The node pattern of life type (enum)
"""
return self.node_pol_type
def get_service_name(self):
"""
Gets the service name
Returns:
The service name
"""
return self.service_name
def get_state(self):
"""
Gets the state (node or service)
Returns:
The state (node or service)
"""
return self.state

View File

@@ -1,140 +0,0 @@
# Crown Copyright (C) Dstl 2022. DEFCON 703. Shared in confidence.
"""
Defines node behaviour for Green PoL
"""
class NodeStateInstructionRed(object):
"""
The Node State Instruction class
"""
def __init__(self, _id, _start_step, _end_step, _target_node_id, _pol_initiator, _pol_type, pol_protocol, _pol_state, _pol_source_node_id, _pol_source_node_service, _pol_source_node_service_state):
"""
Init
Args:
_id: The node state instruction id
_start_step: The start step of the instruction
_end_step: The end step of the instruction
_target_node_id: The id of the associated node
-pol_initiator: The way the PoL is applied (DIRECT, IER or SERVICE)
_pol_type: The pattern of life type
-pol_protocol: The pattern of life protocol/service affected
_pol_state: The state (node or service)
_pol_source_node_id: The source node Id (used for initiator type SERVICE)
_pol_source_node_service: The source node service (used for initiator type SERVICE)
_pol_source_node_service_state: The source node service state (used for initiator type SERVICE)
"""
self.id = _id
self.start_step = _start_step
self.end_step = _end_step
self.target_node_id = _target_node_id
self.initiator = _pol_initiator
self.pol_type = _pol_type
self.service_name = pol_protocol # Not used when not a service instruction
self.state = _pol_state
self.source_node_id = _pol_source_node_id
self.source_node_service = _pol_source_node_service
self.source_node_service_state = _pol_source_node_service_state
def get_start_step(self):
"""
Gets the start step
Returns:
The start step
"""
return self.start_step
def get_end_step(self):
"""
Gets the end step
Returns:
The end step
"""
return self.end_step
def get_target_node_id(self):
"""
Gets the node ID
Returns:
The node ID
"""
return self.target_node_id
def get_initiator(self):
"""
Gets the initiator
Returns:
The initiator
"""
return self.initiator
def get_pol_type(self):
"""
Gets the node pattern of life type (enum)
Returns:
The node pattern of life type (enum)
"""
return self.pol_type
def get_service_name(self):
"""
Gets the service name
Returns:
The service name
"""
return self.service_name
def get_state(self):
"""
Gets the state (node or service)
Returns:
The state (node or service)
"""
return self.state
def get_source_node_id(self):
"""
Gets the source node id (used for initiator type SERVICE)
Returns:
The source node id
"""
return self.source_node_id
def get_source_node_service(self):
"""
Gets the source node service (used for initiator type SERVICE)
Returns:
The source node service
"""
return self.source_node_service
def get_source_node_service_state(self):
"""
Gets the source node service state (used for initiator type SERVICE)
Returns:
The source node service state
"""
return self.source_node_service_state

View File

@@ -1,37 +0,0 @@
# Crown Copyright (C) Dstl 2022. DEFCON 703. Shared in confidence.
"""
The Passive Node class (i.e. an actuator)
"""
from nodes.node import Node
class PassiveNode(Node):
"""
The Passive Node class
"""
def __init__(self, _id, _name, _type, _priority, _state, _config_values):
"""
Init
Args:
_id: The node id
_name: The name of the node
_type: The type of the node
_priority: The priority of the node
_state: The state of the node
"""
# Pass through to Super for now
super().__init__(_id, _name, _type, _priority, _state, _config_values)
def get_ip_address(self):
"""
Gets the node IP address
Returns:
The node IP address
"""
# No concept of IP address for passive nodes for now
return ""

View File

@@ -1,162 +0,0 @@
# Crown Copyright (C) Dstl 2022. DEFCON 703. Shared in confidence.
"""
A Service Node (i.e. not an actuator)
"""
from nodes.active_node import ActiveNode
from common.enums import *
class ServiceNode(ActiveNode):
"""
ServiceNode class
"""
def __init__(self, _id, _name, _type, _priority, _state, _ip_address, _os_state, _file_system_state, _config_values):
"""
Init
Args:
_id: The node id
_name: The name of the node
_type: The type of the node
_priority: The priority of the node
_state: The state of the node
_ipAddress: The IP address of the node
_osState: The operating system state of the node
_file_system_state: The file system state of the node
"""
super().__init__(_id, _name, _type, _priority, _state, _ip_address, _os_state, _file_system_state, _config_values)
self.services = {}
def add_service(self, _service):
"""
Adds a service to the node
Args:
_service: The service to add
"""
self.services[_service.get_name()] = _service
def get_services(self):
"""
Gets the dictionary of services on this node
Returns:
Dictionary of services on this node
"""
return self.services
def has_service(self, _protocol):
"""
Indicates whether a service is on a node
Returns:
True if service (protocol) is on the node
"""
for service_key, service_value in self.services.items():
if service_key == _protocol:
return True
else:
pass
return False
def service_running(self, _protocol):
"""
Indicates whether a service is in a running state on the node
Returns:
True if service (protocol) is in a running state on the node
"""
for service_key, service_value in self.services.items():
if service_key == _protocol:
if service_value.get_state() != SOFTWARE_STATE.PATCHING:
return True
else:
return False
else:
pass
return False
def service_is_overwhelmed(self, _protocol):
"""
Indicates whether a service is in an overwhelmed state on the node
Returns:
True if service (protocol) is in an overwhelmed state on the node
"""
for service_key, service_value in self.services.items():
if service_key == _protocol:
if service_value.get_state() == SOFTWARE_STATE.OVERWHELMED:
return True
else:
return False
else:
pass
return False
def set_service_state(self, _protocol, _state):
"""
Sets the state of a service (protocol) on the node
Args:
_protocol: The service (protocol)
_state: The state value
"""
for service_key, service_value in self.services.items():
if service_key == _protocol:
# Can't set to compromised if you're in a patching state
if (_state == SOFTWARE_STATE.COMPROMISED and service_value.get_state() != SOFTWARE_STATE.PATCHING) or _state != SOFTWARE_STATE.COMPROMISED:
service_value.set_state(_state)
else:
# Do nothing
pass
if _state == SOFTWARE_STATE.PATCHING:
service_value.patching_count = self.config_values.service_patching_duration
else:
# Do nothing
pass
def set_service_state_if_not_compromised(self, _protocol, _state):
"""
Sets the state of a service (protocol) on the node if the operating state is not "compromised"
Args:
_protocol: The service (protocol)
_state: The state value
"""
for service_key, service_value in self.services.items():
if service_key == _protocol:
if service_value.get_state() != SOFTWARE_STATE.COMPROMISED:
service_value.set_state(_state)
if _state == SOFTWARE_STATE.PATCHING:
service_value.patching_count = self.config_values.service_patching_duration
def get_service_state(self, _protocol):
"""
Gets the state of a service
Returns:
The state of the service
"""
for service_key, service_value in self.services.items():
if service_key == _protocol:
return service_value.get_state()
def update_services_patching_status(self):
"""
Updates the patching counter for any service that are patching
"""
for service_key, service_value in self.services.items():
if service_value.get_state() == SOFTWARE_STATE.PATCHING:
service_value.reduce_patching_count()

View File

@@ -1 +0,0 @@
# Crown Copyright (C) Dstl 2022. DEFCON 703. Shared in confidence.

View File

@@ -1,230 +0,0 @@
# Crown Copyright (C) Dstl 2022. DEFCON 703. Shared in confidence.
"""
Implements Pattern of Life on the network (nodes and links)
"""
from networkx import shortest_path
from common.enums import *
from nodes.active_node import ActiveNode
from nodes.service_node import ServiceNode
_VERBOSE = False
def apply_iers(network, nodes, links, iers, acl, step):
"""
Applies IERs to the links (link pattern of life)
Args:
network: The network modelled in the environment
nodes: The nodes within the environment
links: The links within the environment
iers: The IERs to apply to the links
acl: The Access Control List
step: The step number
"""
if _VERBOSE:
print("Applying IERs")
# Go through each IER and check the conditions for it being applied
# If everything is in place, apply the IER protocol load to the relevant links
for ier_key, ier_value in iers.items():
start_step = ier_value.get_start_step()
stop_step = ier_value.get_end_step()
protocol = ier_value.get_protocol()
port = ier_value.get_port()
load = ier_value.get_load()
source_node_id = ier_value.get_source_node_id()
dest_node_id = ier_value.get_dest_node_id()
# Need to set the running status to false first for all IERs
ier_value.set_is_running(False)
source_valid = True
dest_valid = True
acl_block = False
if step >= start_step and step <= stop_step:
# continue --------------------------
# Get the source and destination node for this link
source_node = nodes[source_node_id]
dest_node = nodes[dest_node_id]
# 1. Check the source node situation
if source_node.get_type() == TYPE.SWITCH:
# It's a switch
if source_node.get_state() == HARDWARE_STATE.ON and source_node.get_os_state() != SOFTWARE_STATE.PATCHING:
source_valid = True
else:
# IER no longer valid
source_valid = False
elif source_node.get_type() == TYPE.ACTUATOR:
# It's an actuator
# TO DO
pass
else:
# It's not a switch or an actuator (so active node)
if source_node.get_state() == HARDWARE_STATE.ON and source_node.get_os_state() != SOFTWARE_STATE.PATCHING:
if source_node.has_service(protocol):
if source_node.service_running(protocol) and not source_node.service_is_overwhelmed(protocol):
source_valid = True
else:
source_valid = False
else:
# Do nothing - IER is not valid on this node
# (This shouldn't happen if the IER has been written correctly)
source_valid = False
else:
# Do nothing - IER no longer valid
source_valid = False
# 2. Check the dest node situation
if dest_node.get_type() == TYPE.SWITCH:
# It's a switch
if dest_node.get_state() == HARDWARE_STATE.ON and dest_node.get_os_state() != SOFTWARE_STATE.PATCHING:
dest_valid = True
else:
# IER no longer valid
dest_valid = False
elif dest_node.get_type() == TYPE.ACTUATOR:
# It's an actuator
pass
else:
# It's not a switch or an actuator (so active node)
if dest_node.get_state() == HARDWARE_STATE.ON and dest_node.get_os_state() != SOFTWARE_STATE.PATCHING:
if dest_node.has_service(protocol):
if dest_node.service_running(protocol) and not dest_node.service_is_overwhelmed(protocol):
dest_valid = True
else:
dest_valid = False
else:
# Do nothing - IER is not valid on this node
# (This shouldn't happen if the IER has been written correctly)
dest_valid = False
else:
# Do nothing - IER no longer valid
dest_valid = False
# 3. Check that the ACL doesn't block it
acl_block = acl.is_blocked(source_node.get_ip_address(), dest_node.get_ip_address(), protocol, port)
if acl_block:
if _VERBOSE:
print("ACL block on source: " + source_node.get_ip_address() + ", dest: " + dest_node.get_ip_address() + ", protocol: " + protocol + ", port: " + port)
else:
if _VERBOSE:
print("No ACL block")
# Check whether both the source and destination are valid, and there's no ACL block
if source_valid and dest_valid and not acl_block:
# Load up the link(s) with the traffic
if _VERBOSE:
print("Source, Dest and ACL valid")
# Get the shortest path (i.e. nodes) between source and destination
path_node_list = shortest_path(network, source_node, dest_node)
path_node_list_length = len(path_node_list)
path_valid = True
# We might have a switch in the path, so check all nodes are operational
for node in path_node_list:
if node.get_state() != HARDWARE_STATE.ON or node.get_os_state() == SOFTWARE_STATE.PATCHING:
path_valid = False
if path_valid:
if _VERBOSE:
print("Applying IER to link(s)")
count = 0
link_capacity_exceeded = False
# Check that the link capacity is not exceeded by the new load
while count < path_node_list_length - 1:
# Get the link between the next two nodes
edge_dict = network.get_edge_data(path_node_list[count], path_node_list[count+1])
link_id = edge_dict[0].get('id')
link = links[link_id]
# Check whether the new load exceeds the bandwidth
if (link.get_current_load() + load) > link.get_bandwidth():
link_capacity_exceeded = True
if _VERBOSE:
print("Link capacity exceeded")
pass
count+=1
# Check whether the link capacity for any links on this path have been exceeded
if link_capacity_exceeded == False:
# Now apply the new loads to the links
count = 0
while count < path_node_list_length - 1:
# Get the link between the next two nodes
edge_dict = network.get_edge_data(path_node_list[count], path_node_list[count+1])
link_id = edge_dict[0].get('id')
link = links[link_id]
# Add the load from this IER
link.add_protocol_load(protocol, load)
count+=1
# This IER is now valid, so set it to running
ier_value.set_is_running(True)
else:
# One of the nodes is not operational
if _VERBOSE:
print("Path not valid - one or more nodes not operational")
pass
else:
if _VERBOSE:
print("Source, Dest or ACL were not valid")
pass
# ------------------------------------
else:
# Do nothing - IER no longer valid
pass
def apply_node_pol(nodes, node_pol, step):
"""
Applies node pattern of life
Args:
nodes: The nodes within the environment
node_pol: The node pattern of life to apply
step: The step number
"""
if _VERBOSE:
print("Applying Node PoL")
for key, node_instruction in node_pol.items():
start_step = node_instruction.get_start_step()
stop_step = node_instruction.get_end_step()
node_id = node_instruction.get_node_id()
node_pol_type = node_instruction.get_node_pol_type()
service_name = node_instruction.get_service_name()
state = node_instruction.get_state()
if step >= start_step and step <= stop_step:
# continue --------------------------
node = nodes[node_id]
if node_pol_type == NODE_POL_TYPE.OPERATING:
# Change operating state
node.set_state(state)
elif node_pol_type == NODE_POL_TYPE.OS:
# Change OS state
# Don't allow PoL to fix something that is compromised. Only the Blue agent can do this
if isinstance(node, ActiveNode) or isinstance(node, ServiceNode):
node.set_os_state_if_not_compromised(state)
elif node_pol_type == NODE_POL_TYPE.SERVICE:
# Change a service state
# Don't allow PoL to fix something that is compromised. Only the Blue agent can do this
if isinstance(node, ServiceNode):
node.set_service_state_if_not_compromised(service_name, state)
else:
# Change the file system status
if isinstance(node, ActiveNode) or isinstance(node, ServiceNode):
node.set_file_system_state_if_not_compromised(state)
else:
# PoL is not valid in this time step
pass

View File

@@ -1,147 +0,0 @@
# Crown Copyright (C) Dstl 2022. DEFCON 703. Shared in confidence.
"""
Information Exchange Requirements for APE
Used to represent an information flow from source to destination
"""
class IER(object):
"""
Information Exchange Requirement class
"""
def __init__(self, _id, _start_step, _end_step, _load, _protocol, _port, _source_node_id, _dest_node_id, _mission_criticality, _running=False):
"""
Init
Args:
_id: The IER id
_start_step: The step when this IER should start
_end_step: The step when this IER should end
_load: The load this IER should put on a link (bps)
_protocol: The protocol of this IER
_port: The port this IER runs on
_source_node_id: The source node ID
_dest_node_id: The destination node ID
_mission_criticality: Criticality of this IER to the mission (0 none, 5 mission critical)
_running: Indicates whether the IER is currently running
"""
self.id = _id
self.start_step = _start_step
self.end_step = _end_step
self.source_node_id = _source_node_id
self.dest_node_id = _dest_node_id
self.load = _load
self.protocol = _protocol
self.port = _port
self.mission_criticality = _mission_criticality
self.running = _running
def get_id(self):
"""
Gets IER ID
Returns:
IER ID
"""
return self.id
def get_start_step(self):
"""
Gets IER start step
Returns:
IER start step
"""
return self.start_step
def get_end_step(self):
"""
Gets IER end step
Returns:
IER end step
"""
return self.end_step
def get_load(self):
"""
Gets IER load
Returns:
IER load
"""
return self.load
def get_protocol(self):
"""
Gets IER protocol
Returns:
IER protocol
"""
return self.protocol
def get_port(self):
"""
Gets IER port
Returns:
IER port
"""
return self.port
def get_source_node_id(self):
"""
Gets IER source node ID
Returns:
IER source node ID
"""
return self.source_node_id
def get_dest_node_id(self):
"""
Gets IER destination node ID
Returns:
IER destination node ID
"""
return self.dest_node_id
def get_is_running(self):
"""
Informs whether the IER is currently running
Returns:
True if running
"""
return self.running
def set_is_running(self, _value):
"""
Sets the running state of the IER
Args:
_value: running status
"""
self.running = _value
def get_mission_criticality(self):
"""
Gets the IER mission criticality (used in the reward function)
Returns:
Mission criticality value (0 lowest to 5 highest)
"""
return self.mission_criticality

View File

@@ -1,301 +0,0 @@
# Crown Copyright (C) Dstl 2022. DEFCON 703. Shared in confidence.
"""
Implements Pattern of Life on the network (nodes and links) resulting from the red agent attack
"""
from networkx import shortest_path
from common.enums import *
from nodes.active_node import ActiveNode
from nodes.service_node import ServiceNode
_VERBOSE = False
def apply_red_agent_iers(network, nodes, links, iers, acl, step):
"""
Applies IERs to the links (link pattern of life) resulting from red agent attack
Args:
network: The network modelled in the environment
nodes: The nodes within the environment
links: The links within the environment
iers: The red agent IERs to apply to the links
acl: The Access Control List
step: The step number
"""
# Go through each IER and check the conditions for it being applied
# If everything is in place, apply the IER protocol load to the relevant links
for ier_key, ier_value in iers.items():
start_step = ier_value.get_start_step()
stop_step = ier_value.get_end_step()
protocol = ier_value.get_protocol()
port = ier_value.get_port()
load = ier_value.get_load()
source_node_id = ier_value.get_source_node_id()
dest_node_id = ier_value.get_dest_node_id()
# Need to set the running status to false first for all IERs
ier_value.set_is_running(False)
source_valid = True
dest_valid = True
acl_block = False
if step >= start_step and step <= stop_step:
# continue --------------------------
# Get the source and destination node for this link
source_node = nodes[source_node_id]
dest_node = nodes[dest_node_id]
# 1. Check the source node situation
if source_node.get_type() == TYPE.SWITCH:
# It's a switch
if source_node.get_state() == HARDWARE_STATE.ON:
source_valid = True
else:
# IER no longer valid
source_valid = False
elif source_node.get_type() == TYPE.ACTUATOR:
# It's an actuator
# TO DO
pass
else:
# It's not a switch or an actuator (so active node)
if source_node.get_state() == HARDWARE_STATE.ON:
if source_node.has_service(protocol):
# Red agents IERs can only be valid if the source service is in a compromised state
if source_node.get_service_state(protocol) == SOFTWARE_STATE.COMPROMISED:
source_valid = True
else:
source_valid = False
else:
# Do nothing - IER is not valid on this node
# (This shouldn't happen if the IER has been written correctly)
source_valid = False
else:
# Do nothing - IER no longer valid
source_valid = False
# 2. Check the dest node situation
if dest_node.get_type() == TYPE.SWITCH:
# It's a switch
if dest_node.get_state() == HARDWARE_STATE.ON:
dest_valid = True
else:
# IER no longer valid
dest_valid = False
elif dest_node.get_type() == TYPE.ACTUATOR:
# It's an actuator
pass
else:
# It's not a switch or an actuator (so active node)
if dest_node.get_state() == HARDWARE_STATE.ON:
if dest_node.has_service(protocol):
# We don't care what state the destination service is in for an IER
dest_valid = True
else:
# Do nothing - IER is not valid on this node
# (This shouldn't happen if the IER has been written correctly)
dest_valid = False
else:
# Do nothing - IER no longer valid
dest_valid = False
# 3. Check that the ACL doesn't block it
acl_block = acl.is_blocked(source_node.get_ip_address(), dest_node.get_ip_address(), protocol, port)
if acl_block:
if _VERBOSE:
print("ACL block on source: " + source_node.get_ip_address() + ", dest: " + dest_node.get_ip_address() + ", protocol: " + protocol + ", port: " + port)
else:
if _VERBOSE:
print("No ACL block")
# Check whether both the source and destination are valid, and there's no ACL block
if source_valid and dest_valid and not acl_block:
# Load up the link(s) with the traffic
if _VERBOSE:
print("Source, Dest and ACL valid")
# Get the shortest path (i.e. nodes) between source and destination
path_node_list = shortest_path(network, source_node, dest_node)
path_node_list_length = len(path_node_list)
path_valid = True
# We might have a switch in the path, so check all nodes are operational
# We're assuming here that red agents can get past switches that are patching
for node in path_node_list:
if node.get_state() != HARDWARE_STATE.ON:
path_valid = False
if path_valid:
if _VERBOSE:
print("Applying IER to link(s)")
count = 0
link_capacity_exceeded = False
# Check that the link capacity is not exceeded by the new load
while count < path_node_list_length - 1:
# Get the link between the next two nodes
edge_dict = network.get_edge_data(path_node_list[count], path_node_list[count+1])
link_id = edge_dict[0].get('id')
link = links[link_id]
# Check whether the new load exceeds the bandwidth
if (link.get_current_load() + load) > link.get_bandwidth():
link_capacity_exceeded = True
if _VERBOSE:
print("Link capacity exceeded")
pass
count+=1
# Check whether the link capacity for any links on this path have been exceeded
if link_capacity_exceeded == False:
# Now apply the new loads to the links
count = 0
while count < path_node_list_length - 1:
# Get the link between the next two nodes
edge_dict = network.get_edge_data(path_node_list[count], path_node_list[count+1])
link_id = edge_dict[0].get('id')
link = links[link_id]
# Add the load from this IER
link.add_protocol_load(protocol, load)
count+=1
# This IER is now valid, so set it to running
ier_value.set_is_running(True)
if _VERBOSE:
print("Red IER was allowed to run in step " + str(step))
else:
# One of the nodes is not operational
if _VERBOSE:
print("Path not valid - one or more nodes not operational")
pass
else:
if _VERBOSE:
print("Red IER was NOT allowed to run in step " + str(step))
print("Source, Dest or ACL were not valid")
pass
# ------------------------------------
else:
# Do nothing - IER no longer valid
pass
pass
def apply_red_agent_node_pol(nodes, iers, node_pol, step):
"""
Applies node pattern of life
Args:
nodes: The nodes within the environment
iers: The red agent IERs
node_pol: The red agent node pattern of life to apply
step: The step number
"""
if _VERBOSE:
print("Applying Node Red Agent PoL")
for key, node_instruction in node_pol.items():
start_step = node_instruction.get_start_step()
stop_step = node_instruction.get_end_step()
target_node_id = node_instruction.get_target_node_id()
initiator = node_instruction.get_initiator()
pol_type = node_instruction.get_pol_type()
service_name = node_instruction.get_service_name()
state = node_instruction.get_state()
source_node_id = node_instruction.get_source_node_id()
source_node_service_name = node_instruction.get_source_node_service()
source_node_service_state_value = node_instruction.get_source_node_service_state()
passed_checks = False
if step >= start_step and step <= stop_step:
# continue --------------------------
target_node = nodes[target_node_id]
# Based the action taken on the initiator type
if initiator == NODE_POL_INITIATOR.DIRECT:
# No conditions required, just apply the change
passed_checks = True
elif initiator == NODE_POL_INITIATOR.IER:
# Need to check there is a red IER incoming
passed_checks = is_red_ier_incoming(target_node, iers, pol_type)
elif initiator == NODE_POL_INITIATOR.SERVICE:
# Need to check the condition of a service on another node
source_node = nodes[source_node_id]
if source_node.has_service(source_node_service_name):
if source_node.get_service_state(source_node_service_name) == SOFTWARE_STATE[source_node_service_state_value]:
passed_checks = True
else:
# Do nothing, no matching state value
pass
else:
# Do nothing, service not on this node
pass
else:
if _VERBOSE:
print("Node Red Agent PoL not allowed - misconfiguration")
# Only apply the PoL if the checks have passed (based on the initiator type)
if passed_checks:
# Apply the change
if pol_type == NODE_POL_TYPE.OPERATING:
# Change operating state
target_node.set_state(state)
elif pol_type == NODE_POL_TYPE.OS:
# Change OS state
if isinstance(target_node, ActiveNode) or isinstance(target_node, ServiceNode):
target_node.set_os_state(state)
elif pol_type == NODE_POL_TYPE.SERVICE:
# Change a service state
if isinstance(target_node, ServiceNode):
target_node.set_service_state(service_name, state)
else:
# Change the file system status
if isinstance(target_node, ActiveNode) or isinstance(target_node, ServiceNode):
target_node.set_file_system_state(state)
else:
if _VERBOSE:
print("Node Red Agent PoL not allowed - did not pass checks")
else:
# PoL is not valid in this time step
pass
def is_red_ier_incoming(node, iers, node_pol_type):
node_id = node.get_id()
for ier_key, ier_value in iers.items():
if ier_value.get_is_running() and ier_value.get_dest_node_id() == node_id:
if node_pol_type == NODE_POL_TYPE.OPERATING or node_pol_type == NODE_POL_TYPE.OS or node_pol_type == NODE_POL_TYPE.FILE:
# It's looking to change operating state, file system or O/S state, so valid
return True
elif node_pol_type == NODE_POL_TYPE.SERVICE:
# Check if the service is present on the node and running
ier_protocol = ier_value.get_protocol()
if isinstance(node, ServiceNode):
if node.has_service(ier_protocol):
if node.service_running(ier_protocol):
# Matching service is present and running, so valid
return True
else:
# Service is present, but not running
return False
else:
# Service is not present
return False
else:
# Not a service node
return False
else:
# Shouldn't get here - instruction type is undefined
return False
else:
# The IER destination is not this node, or the IER is not running
return False

View File

@@ -1,105 +0,0 @@
# Crown Copyright (C) Dstl 2022. DEFCON 703. Shared in confidence.
"""
Used to tes the ACL functions
"""
from acl.acl_rule import ACLRule
from acl.access_control_list import AccessControlList
def test_acl_address_match_1():
"""
Test that matching IP addresses produce True
"""
acl = AccessControlList()
rule = ACLRule("ALLOW", "192.168.1.1", "192.168.1.2", "TCP", "80")
assert acl.check_address_match(rule, "192.168.1.1", "192.168.1.2") == True
def test_acl_address_match_2():
"""
Test that mismatching IP addresses produce False
"""
acl = AccessControlList()
rule = ACLRule("ALLOW", "192.168.1.1", "192.168.1.2", "TCP", "80")
assert acl.check_address_match(rule, "192.168.1.1", "192.168.1.3") == False
def test_acl_address_match_3():
"""
Test the ANY condition for source IP addresses produce True
"""
acl = AccessControlList()
rule = ACLRule("ALLOW", "ANY", "192.168.1.2", "TCP", "80")
assert acl.check_address_match(rule, "192.168.1.1", "192.168.1.2") == True
def test_acl_address_match_4():
"""
Test the ANY condition for dest IP addresses produce True
"""
acl = AccessControlList()
rule = ACLRule("ALLOW", "192.168.1.1", "ANY", "TCP", "80")
assert acl.check_address_match(rule, "192.168.1.1", "192.168.1.2") == True
def test_check_acl_block_affirmative():
"""
Test the block function (affirmative)
"""
# Create the Access Control List
acl = AccessControlList()
# Create a rule
acl_rule_permission = "ALLOW"
acl_rule_source = "192.168.1.1"
acl_rule_destination = "192.168.1.2"
acl_rule_protocol = "TCP"
acl_rule_port = "80"
acl.add_rule(acl_rule_permission, acl_rule_source, acl_rule_destination, acl_rule_protocol, acl_rule_port)
assert acl.is_blocked("192.168.1.1", "192.168.1.2", "TCP", "80") == False
def test_check_acl_block_negative():
"""
Test the block function (negative)
"""
# Create the Access Control List
acl = AccessControlList()
# Create a rule
acl_rule_permission = "DENY"
acl_rule_source = "192.168.1.1"
acl_rule_destination = "192.168.1.2"
acl_rule_protocol = "TCP"
acl_rule_port = "80"
acl.add_rule(acl_rule_permission, acl_rule_source, acl_rule_destination, acl_rule_protocol, acl_rule_port)
assert acl.is_blocked("192.168.1.1", "192.168.1.2", "TCP", "80") == True
def test_rule_hash():
"""
Test the rule hash
"""
# Create the Access Control List
acl = AccessControlList()
rule = ACLRule("DENY", "192.168.1.1", "192.168.1.2", "TCP", "80")
hash_value_local = hash(rule)
hash_value_remote = acl.get_dictionary_hash("DENY", "192.168.1.1", "192.168.1.2", "TCP", "80")
assert hash_value_local == hash_value_remote

View File

@@ -1 +0,0 @@
# Crown Copyright (C) Dstl 2022. DEFCON 703. Shared in confidence.

View File

@@ -1,69 +0,0 @@
# Crown Copyright (C) Dstl 2022. DEFCON 703. Shared in confidence.
"""
The Transaction class
"""
class Transaction(object):
"""
Transaction class
"""
def __init__(self, _timestamp, _agent_identifier, _episode_number, _step_number):
"""
Init
Args:
_timestamp: The time this object was created
_agent_identifier: An identifier for the agent in use
_episode_number: The episode number
_step_number: The step number
"""
self.timestamp = _timestamp
self.agent_identifier = _agent_identifier
self.episode_number = _episode_number
self.step_number = _step_number
def set_obs_space_pre(self, _obs_space_pre):
"""
Sets the observation space (pre)
Args:
_obs_space_pre: The observation space before any actions are taken
"""
self.obs_space_pre = _obs_space_pre
def set_obs_space_post(self, _obs_space_post):
"""
Sets the observation space (post)
Args:
_obs_space_post: The observation space after any actions are taken
"""
self.obs_space_post = _obs_space_post
def set_reward(self, _reward):
"""
Sets the reward
Args:
_reward: The reward value
"""
self.reward = _reward
def set_action_space(self, _action_space):
"""
Sets the action space
Args:
_action_space: The action space invoked by the agent
"""
self.action_space = _action_space

View File

@@ -1,104 +0,0 @@
# Crown Copyright (C) Dstl 2022. DEFCON 703. Shared in confidence.
"""
Writes the Transaction log list out to file for evaluation to utilse
"""
import csv
import logging
import os.path
from datetime import datetime
from transactions.transaction import Transaction
def turn_action_space_to_array(_action_space):
"""
Turns action space into a string array so it can be saved to csv
Args:
_action_space: The action space
"""
return_array = []
for x in range(len(_action_space)):
return_array.append(str(_action_space[x]))
return return_array
def turn_obs_space_to_array(_obs_space, _obs_assets, _obs_features):
"""
Turns observation space into a string array so it can be saved to csv
Args:
_obs_space: The observation space
_obs_assets: The number of assets (i.e. nodes or links) in the observation space
_obs_features: The number of features associated with the asset
"""
return_array = []
for x in range(_obs_assets):
for y in range(_obs_features):
return_array.append(str(_obs_space[x][y]))
return return_array
def write_transaction_to_file(_transaction_list):
"""
Writes transaction logs to file to support training evaluation
Args:
_transaction_list: The list of transactions from all steps and all episodes
_num_episodes: The number of episodes that were conducted
"""
# Get the first transaction and use it to determine the makeup of the observation space and action space
# Label the obs space fields in csv as "OSI_1_1", "OSN_1_1" and action space as "AS_1"
# This will be tied into the PrimAITE Use Case so that they make sense
template_transation = _transaction_list[0]
action_length = template_transation.action_space.size
obs_assets = template_transation.obs_space_post.shape[0]
obs_features = template_transation.obs_space_post.shape[1]
# Create the action space headers array
action_header = []
for x in range(action_length):
action_header.append('AS_' + str(x))
# Create the observation space headers array
obs_header_initial = []
obs_header_new = []
for x in range(obs_assets):
for y in range(obs_features):
obs_header_initial.append('OSI_' + str(x) + '_' + str(y))
obs_header_new.append('OSN_' + str(x) + '_' + str(y))
# Open up a csv file
header = ['Timestamp', 'Episode', 'Step', 'Reward']
header = header + action_header + obs_header_initial + obs_header_new
now = datetime.now() # current date and time
time = now.strftime("%Y%m%d_%H%M%S")
try:
path = 'outputs/results/'
is_dir = os.path.isdir(path)
if not is_dir:
os.makedirs(path)
filename = "outputs/results/all_transactions_" + time + ".csv"
csv_file = open(filename, 'w', encoding='UTF8', newline='')
csv_writer = csv.writer(csv_file)
csv_writer.writerow(header)
for transaction in _transaction_list:
csv_data = [str(transaction.timestamp), str(transaction.episode_number), str(transaction.step_number), str(transaction.reward)]
csv_data = csv_data + turn_action_space_to_array(transaction.action_space) + \
turn_obs_space_to_array(transaction.obs_space_pre, obs_assets, obs_features) + \
turn_obs_space_to_array(transaction.obs_space_post, obs_assets, obs_features)
csv_writer.writerow(csv_data)
csv_file.close()
except Exception as e:
logging.error("Could not save the transaction file")
logging.error("Exception occured", exc_info=True)

Binary file not shown.

After

Width:  |  Height:  |  Size: 274 KiB

176
README.md
View File

@@ -1 +1,175 @@
# PrimAITE
# PrimAITE
![image](./PrimAITE_logo_transparent.png)
The ARCD Primary-level AI Training Environment (**PrimAITE**) provides an effective simulation capability for the purposes of training and evaluating AI in a cyber-defensive role. It incorporates the functionality required of a primary-level ARCD environment, which includes:
- The ability to model a relevant platform / system context;
- The ability to model key characteristics of a platform / system by representing connections, IP addresses, ports, traffic loading, operating systems and services;
- Operates at machine-speed to enable fast training cycles.
PrimAITE presents the following features:
- Highly configurable (via YAML files) to provide the means to model a variety of platform / system laydowns and adversarial attack scenarios;
- A Reinforcement Learning (RL) reward function based on (a) the ability to counter the specific modelled adversarial cyber-attack, and (b) the ability to ensure success;
- Provision of logging to support AI evaluation and metrics gathering;
- Realistic network traffic simulation, including address and sending packets via internet protocols like TCP, UDP, ICMP, and others
- Routers with traffic routing and firewall capabilities
- Support for multiple agents, each having their own customisable observation space, action space, and reward function definition, and either deterministic or RL-directed behaviour
## Getting Started with PrimAITE
### 💫 Installation
**PrimAITE** is designed to be OS-agnostic, and thus should work on most variations/distros of Linux, Windows, and MacOS.
Currently, the PrimAITE wheel can only be installed from GitHub. This may change in the future with release to PyPi.
#### Windows (PowerShell)
**Prerequisites:**
* Manual install of Python >= 3.8 < 3.12
**Install:**
``` powershell
mkdir ~\primaite
cd ~\primaite
python3 -m venv .venv
attrib +h .venv /s /d # Hides the .venv directory
.\.venv\Scripts\activate
pip install primaite-3.0.0-py3-none-any.whl[rl]
primaite setup
```
#### Unix
**Prerequisites:**
* Manual install of Python >= 3.8 < 3.12
``` bash
sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt install python3.10
sudo apt-get install python3-pip
sudo apt-get install python3-venv
```
**Install:**
``` bash
mkdir ~/primaite
cd ~/primaite
python3 -m venv .venv
source .venv/bin/activate
pip install primaite-3.0.0-py3-none-any.whl[rl]
primaite setup
```
### Developer Install from Source
To make your own changes to PrimAITE, perform the install from source (developer install)
#### 1. Clone the PrimAITE repository
``` unix
git clone git@github.com:Autonomous-Resilient-Cyber-Defence/PrimAITE.git
```
#### 2. CD into the repo directory
``` unix
cd PrimAITE
```
#### 3. Create a new python virtual environment (venv)
```unix
python3 -m venv venv
```
#### 4. Activate the venv
##### Unix
```bash
source venv/bin/activate
```
##### Windows (Powershell)
```powershell
.\venv\Scripts\activate
```
#### 5. Install `primaite` with the dev extra into the venv along with all of it's dependencies
```bash
python3 -m pip install -e .[dev,rl]
```
#### 6. Perform the PrimAITE setup:
```bash
primaite setup
```
#### Note
*It is possible to install PrimAITE without Ray RLLib, StableBaselines3, or any deep learning libraries by omitting the `rl` flag in the pip install command.*
### Running PrimAITE
Use the provided jupyter notebooks as a starting point to try running PrimAITE. They are automatically copied to your PrimAITE notebook folder when you run `primaite setup`.
#### 1. Activate the virtual environment
##### Windows (Powershell)
```powershell
.\venv\Scripts\activate
```
##### Unix
```bash
source venv/bin/activate
```
#### 2. Open jupyter notebook
```bash
python -m jupyter notebook
```
Then, click the URL provided by the jupyter command to open the jupyter application in your browser. You can also open notebooks in your IDE if supported.
## 📚 Documentation
### Pre requisites
Building the documentation requires the installation of Pandoc
##### Unix
```bash
sudo apt-get install pandoc
```
##### Other operating systems
Follow the steps in https://pandoc.org/installing.html
### Building the documentation
The PrimAITE documentation can be built with the following commands:
##### Unix
```bash
cd docs
make html
```
##### Windows (Powershell)
```powershell
cd docs
.\make.bat html
```
## Example notebooks
Check out the example notebooks to learn more about how PrimAITE works and how you can use it to train agents. They are automatically copied to your primaite installation directory when you run `primaite setup`.

22
benchmark/benchmark.py Normal file
View File

@@ -0,0 +1,22 @@
# © Crown-owned copyright 2024, Defence Science and Technology Laboratory UK
from typing import Any, Dict, Optional, Tuple
from gymnasium.core import ObsType
from primaite.session.environment import PrimaiteGymEnv
class BenchmarkPrimaiteGymEnv(PrimaiteGymEnv):
"""
Class that extends the PrimaiteGymEnv.
The reset method is extended so that the average rewards per episode are recorded.
"""
total_time_steps: int = 0
def reset(self, seed: Optional[int] = None) -> Tuple[ObsType, Dict[str, Any]]:
"""Overrides the PrimAITEGymEnv reset so that the total timesteps is saved."""
self.total_time_steps += self.game.step_counter
return super().reset(seed=seed)

View File

@@ -0,0 +1,164 @@
# © Crown-owned copyright 2023, Defence Science and Technology Laboratory UK
# Training Config File
# Sets which agent algorithm framework will be used.
# Options are:
# "SB3" (Stable Baselines3)
# "RLLIB" (Ray RLlib)
# "CUSTOM" (Custom Agent)
agent_framework: SB3
# Sets which deep learning framework will be used (by RLlib ONLY).
# Default is TF (Tensorflow).
# Options are:
# "TF" (Tensorflow)
# TF2 (Tensorflow 2.X)
# TORCH (PyTorch)
deep_learning_framework: TF2
# Sets which Agent class will be used.
# Options are:
# "A2C" (Advantage Actor Critic coupled with either SB3 or RLLIB agent_framework)
# "PPO" (Proximal Policy Optimization coupled with either SB3 or RLLIB agent_framework)
# "HARDCODED" (The HardCoded agents coupled with an ACL or NODE action_type)
# "DO_NOTHING" (The DoNothing agents coupled with an ACL or NODE action_type)
# "RANDOM" (primaite.agents.simple.RandomAgent)
# "DUMMY" (primaite.agents.simple.DummyAgent)
agent_identifier: PPO
# Sets whether Red Agent POL and IER is randomised.
# Options are:
# True
# False
random_red_agent: False
# The (integer) seed to be used in random number generation
# Default is None (null)
seed: null
# Set whether the agent will be deterministic instead of stochastic
# Options are:
# True
# False
deterministic: False
# Sets what view of the environment the deterministic hardcoded agent has. The default is BASIC.
# Options are:
# "BASIC" (The current observation space only)
# "FULL" (Full environment view with actions taken and reward feedback)
hard_coded_agent_view: FULL
# Sets How the Action Space is defined:
# "NODE"
# "ACL"
# "ANY" node and acl actions
action_type: NODE
# observation space
observation_space:
flatten: true
components:
- name: NODE_LINK_TABLE
- name: NODE_STATUSES
- name: LINK_TRAFFIC_LEVELS
# Number of episodes for training to run per session
num_train_episodes: 500
# Number of time_steps for training per episode
num_train_steps: 256
# Number of episodes for evaluation to run per session
num_eval_episodes: 1
# Number of time_steps for evaluation per episode
num_eval_steps: 256
# Sets how often the agent will save a checkpoint (every n time episodes).
# Set to 0 if no checkpoints are required. Default is 10
checkpoint_every_n_episodes: 0
# Time delay (milliseconds) between steps for CUSTOM agents.
time_delay: 5
# Type of session to be run. Options are:
# "TRAIN" (Trains an agent)
# "EVAL" (Evaluates an agent)
# "TRAIN_EVAL" (Trains then evaluates an agent)
session_type: TRAIN
# Environment config values
# The high value for the observation space
observation_space_high_value: 1000000000
# The Stable Baselines3 learn/eval output verbosity level:
# Options are:
# "NONE" (No Output)
# "INFO" (Info Messages (such as devices and wrappers used))
# "DEBUG" (All Messages)
sb3_output_verbose_level: NONE
# Reward values
# Generic
all_ok: 0
# Node Hardware State
off_should_be_on: -0.001
off_should_be_resetting: -0.0005
on_should_be_off: -0.0002
on_should_be_resetting: -0.0005
resetting_should_be_on: -0.0005
resetting_should_be_off: -0.0002
resetting: -0.0003
# Node Software or Service State
good_should_be_patching: 0.0002
good_should_be_compromised: 0.0005
good_should_be_overwhelmed: 0.0005
patching_should_be_good: -0.0005
patching_should_be_compromised: 0.0002
patching_should_be_overwhelmed: 0.0002
patching: -0.0003
compromised_should_be_good: -0.002
compromised_should_be_patching: -0.002
compromised_should_be_overwhelmed: -0.002
compromised: -0.002
overwhelmed_should_be_good: -0.002
overwhelmed_should_be_patching: -0.002
overwhelmed_should_be_compromised: -0.002
overwhelmed: -0.002
# Node File System State
good_should_be_repairing: 0.0002
good_should_be_restoring: 0.0002
good_should_be_corrupt: 0.0005
good_should_be_destroyed: 0.001
repairing_should_be_good: -0.0005
repairing_should_be_restoring: 0.0002
repairing_should_be_corrupt: 0.0002
repairing_should_be_destroyed: 0.0000
repairing: -0.0003
restoring_should_be_good: -0.001
restoring_should_be_repairing: -0.0002
restoring_should_be_corrupt: 0.0001
restoring_should_be_destroyed: 0.0002
restoring: -0.0006
corrupt_should_be_good: -0.001
corrupt_should_be_repairing: -0.001
corrupt_should_be_restoring: -0.001
corrupt_should_be_destroyed: 0.0002
corrupt: -0.001
destroyed_should_be_good: -0.002
destroyed_should_be_repairing: -0.002
destroyed_should_be_restoring: -0.002
destroyed_should_be_corrupt: -0.002
destroyed: -0.002
scanning: -0.0002
# IER status
red_ier_running: -0.0005
green_ier_blocked: -0.001
# Patching / Reset durations
os_patching_duration: 5 # The time taken to patch the OS
node_reset_duration: 5 # The time taken to reset a node (hardware)
service_patching_duration: 5 # The time taken to patch a service
file_system_repairing_limit: 5 # The time take to repair the file system
file_system_restoring_limit: 5 # The time take to restore the file system
file_system_scanning_limit: 5 # The time taken to scan the file system

View File

@@ -0,0 +1,200 @@
# © Crown-owned copyright 2024, Defence Science and Technology Laboratory UK
import json
import shutil
from datetime import datetime
from pathlib import Path
from typing import Any, Dict, Final, Tuple
from report import build_benchmark_md_report
from stable_baselines3 import PPO
import primaite
from benchmark import BenchmarkPrimaiteGymEnv
from primaite.config.load import data_manipulation_config_path
_LOGGER = primaite.getLogger(__name__)
_MAJOR_V = primaite.__version__.split(".")[0]
_BENCHMARK_ROOT = Path(__file__).parent
_RESULTS_ROOT: Final[Path] = _BENCHMARK_ROOT / "results" / f"v{_MAJOR_V}"
_VERSION_ROOT: Final[Path] = _RESULTS_ROOT / f"v{primaite.__version__}"
_SESSION_METADATA_ROOT: Final[Path] = _VERSION_ROOT / "session_metadata"
_SESSION_METADATA_ROOT.mkdir(parents=True, exist_ok=True)
class BenchmarkSession:
"""Benchmark Session class."""
gym_env: BenchmarkPrimaiteGymEnv
"""Gym environment used by the session to train."""
num_episodes: int
"""Number of episodes to run the training session."""
episode_len: int
"""The number of steps per episode."""
total_steps: int
"""Number of steps to run the training session."""
batch_size: int
"""Number of steps for each episode."""
learning_rate: float
"""Learning rate for the model."""
start_time: datetime
"""Start time for the session."""
end_time: datetime
"""End time for the session."""
def __init__(
self,
gym_env: BenchmarkPrimaiteGymEnv,
episode_len: int,
num_episodes: int,
n_steps: int,
batch_size: int,
learning_rate: float,
):
"""Initialise the BenchmarkSession."""
self.gym_env = gym_env
self.episode_len = episode_len
self.n_steps = n_steps
self.num_episodes = num_episodes
self.total_steps = self.num_episodes * self.episode_len
self.batch_size = batch_size
self.learning_rate = learning_rate
def train(self):
"""Run the training session."""
# start timer for session
self.start_time = datetime.now()
model = PPO(
policy="MlpPolicy",
env=self.gym_env,
learning_rate=self.learning_rate,
n_steps=self.n_steps,
batch_size=self.batch_size,
verbose=0,
tensorboard_log="./PPO_UC2/",
)
model.learn(total_timesteps=self.total_steps)
# end timer for session
self.end_time = datetime.now()
self.session_metadata = self.generate_learn_metadata_dict()
def _learn_benchmark_durations(self) -> Tuple[float, float, float]:
"""
Calculate and return the learning benchmark durations.
Calculates the:
- Total learning time in seconds
- Total learning time per time step in seconds
- Total learning time per 100 time steps per 10 nodes in seconds
:return: The learning benchmark durations as a Tuple of three floats:
Tuple[total_s, s_per_step, s_per_100_steps_10_nodes].
"""
delta = self.end_time - self.start_time
total_s = delta.total_seconds()
total_steps = self.batch_size * self.num_episodes
s_per_step = total_s / total_steps
num_nodes = len(self.gym_env.game.simulation.network.nodes)
num_intervals = total_steps / 100
av_interval_time = total_s / num_intervals
s_per_100_steps_10_nodes = av_interval_time / (num_nodes / 10)
return total_s, s_per_step, s_per_100_steps_10_nodes
def generate_learn_metadata_dict(self) -> Dict[str, Any]:
"""Metadata specific to the learning session."""
total_s, s_per_step, s_per_100_steps_10_nodes = self._learn_benchmark_durations()
self.gym_env.total_reward_per_episode.pop(0) # remove episode 0
return {
"total_episodes": self.gym_env.episode_counter,
"total_time_steps": self.gym_env.total_time_steps,
"total_s": total_s,
"s_per_step": s_per_step,
"s_per_100_steps_10_nodes": s_per_100_steps_10_nodes,
"total_reward_per_episode": self.gym_env.total_reward_per_episode,
}
def _get_benchmark_primaite_environment() -> BenchmarkPrimaiteGymEnv:
"""
Create an instance of the BenchmarkPrimaiteGymEnv.
This environment will be used to train the agents on.
"""
env = BenchmarkPrimaiteGymEnv(env_config=data_manipulation_config_path())
return env
def _prepare_session_directory():
"""Prepare the session directory so that it is easier to clean up after the benchmarking is done."""
# override session path
session_path = _BENCHMARK_ROOT / "sessions"
if session_path.is_dir():
shutil.rmtree(session_path)
primaite.PRIMAITE_PATHS.user_sessions_path = session_path
primaite.PRIMAITE_PATHS.user_sessions_path.mkdir(exist_ok=True, parents=True)
def run(
number_of_sessions: int = 5,
num_episodes: int = 1000,
episode_len: int = 128,
n_steps: int = 1280,
batch_size: int = 32,
learning_rate: float = 3e-4,
) -> None:
"""Run the PrimAITE benchmark."""
benchmark_start_time = datetime.now()
session_metadata_dict = {}
_prepare_session_directory()
# run training
for i in range(1, number_of_sessions + 1):
print(f"Starting Benchmark Session: {i}")
with _get_benchmark_primaite_environment() as gym_env:
session = BenchmarkSession(
gym_env=gym_env,
num_episodes=num_episodes,
n_steps=n_steps,
episode_len=episode_len,
batch_size=batch_size,
learning_rate=learning_rate,
)
session.train()
# Dump the session metadata so that we're not holding it in memory as it's large
with open(_SESSION_METADATA_ROOT / f"{i}.json", "w") as file:
json.dump(session.session_metadata, file, indent=4)
for i in range(1, number_of_sessions + 1):
with open(_SESSION_METADATA_ROOT / f"{i}.json", "r") as file:
session_metadata_dict[i] = json.load(file)
# generate report
build_benchmark_md_report(
benchmark_start_time=benchmark_start_time,
session_metadata=session_metadata_dict,
config_path=data_manipulation_config_path(),
results_root_path=_RESULTS_ROOT,
)
if __name__ == "__main__":
run()

426
benchmark/report.py Normal file
View File

@@ -0,0 +1,426 @@
# © Crown-owned copyright 2024, Defence Science and Technology Laboratory UK
import json
import sys
from datetime import datetime
from pathlib import Path
from typing import Dict, Optional
import plotly.graph_objects as go
import polars as pl
import yaml
from plotly.graph_objs import Figure
from utils import _get_system_info
import primaite
PLOT_CONFIG = {
"size": {"auto_size": False, "width": 1500, "height": 900},
"template": "plotly_white",
"range_slider": False,
"av_s_per_100_steps_10_nodes_benchmark_threshold": 5,
"benchmark_line_color": "grey",
}
def _build_benchmark_results_dict(start_datetime: datetime, metadata_dict: Dict, config: Dict) -> dict:
"""
Constructs a dictionary aggregating benchmark results from multiple sessions.
:param start_datetime: The datetime when the benchmarking started.
:param metadata_dict: Dictionary containing metadata for each session.
:param config: Configuration settings used during the benchmarking.
:return: A dictionary containing aggregated data and metadata from the benchmarking sessions.
"""
num_sessions = len(metadata_dict) # number of sessions
averaged_data = {
"start_timestamp": start_datetime.isoformat(),
"end_datetime": datetime.now().isoformat(),
"primaite_version": primaite.__version__,
"system_info": _get_system_info(),
"total_sessions": num_sessions,
"total_episodes": sum(d["total_episodes"] for d in metadata_dict.values()),
"total_time_steps": sum(d["total_time_steps"] for d in metadata_dict.values()),
"av_s_per_session": sum(d["total_s"] for d in metadata_dict.values()) / num_sessions,
"av_s_per_step": sum(d["s_per_step"] for d in metadata_dict.values()) / num_sessions,
"av_s_per_100_steps_10_nodes": sum(d["s_per_100_steps_10_nodes"] for d in metadata_dict.values())
/ num_sessions,
"combined_total_reward_per_episode": {},
"session_total_reward_per_episode": {k: v["total_reward_per_episode"] for k, v in metadata_dict.items()},
"config": config,
}
# find the average of each episode across all sessions
episodes = metadata_dict[1]["total_reward_per_episode"].keys()
for episode in episodes:
combined_av_reward = (
sum(metadata_dict[k]["total_reward_per_episode"][episode] for k in metadata_dict.keys()) / num_sessions
)
averaged_data["combined_total_reward_per_episode"][episode] = combined_av_reward
return averaged_data
def _get_df_from_episode_av_reward_dict(data: Dict) -> pl.DataFrame:
"""
Converts a dictionary of episode average rewards into a Polars DataFrame.
:param data: Dictionary with episodes as keys and average rewards as values.
:return: Polars DataFrame with episodes and average rewards, including a rolling average.
"""
data: Dict = {"episode": data.keys(), "av_reward": data.values()}
return (
pl.from_dict(data)
.with_columns(rolling_mean=pl.col("av_reward").rolling_mean(window_size=25))
.rename({"rolling_mean": "rolling_av_reward"})
)
def _plot_benchmark_metadata(
benchmark_metadata_dict: Dict,
title: Optional[str] = None,
subtitle: Optional[str] = None,
) -> Figure:
"""
Plots benchmark metadata as a line graph using Plotly.
:param benchmark_metadata_dict: Dictionary containing the total reward per episode and session.
:param title: Optional title for the graph.
:param subtitle: Optional subtitle for the graph.
:return: Plotly figure object representing the benchmark metadata plot.
"""
if title:
if subtitle:
title = f"{title} <br>{subtitle}</sup>"
else:
if subtitle:
title = subtitle
layout = go.Layout(
autosize=PLOT_CONFIG["size"]["auto_size"],
width=PLOT_CONFIG["size"]["width"],
height=PLOT_CONFIG["size"]["height"],
)
# Create the line graph with a colored line
fig = go.Figure(layout=layout)
fig.update_layout(template=PLOT_CONFIG["template"])
for session, av_reward_dict in benchmark_metadata_dict["session_total_reward_per_episode"].items():
df = _get_df_from_episode_av_reward_dict(av_reward_dict)
fig.add_trace(
go.Scatter(
x=df["episode"],
y=df["av_reward"],
mode="lines",
name=f"Session {session}",
opacity=0.25,
line={"color": "#a6a6a6"},
)
)
df = _get_df_from_episode_av_reward_dict(benchmark_metadata_dict["combined_total_reward_per_episode"])
fig.add_trace(
go.Scatter(
x=df["episode"], y=df["av_reward"], mode="lines", name="Combined Session Av", line={"color": "#FF0000"}
)
)
fig.add_trace(
go.Scatter(
x=df["episode"],
y=df["rolling_av_reward"],
mode="lines",
name="Rolling Av (Combined Session Av)",
line={"color": "#4CBB17"},
)
)
# Set the layout of the graph
fig.update_layout(
xaxis={
"title": "Episode",
"type": "linear",
},
yaxis={"title": "Total Reward"},
title=title,
)
return fig
def _plot_all_benchmarks_combined_session_av(results_directory: Path) -> Figure:
"""
Plot the Benchmark results for each released version of PrimAITE.
Does this by iterating over the ``benchmark/results`` directory and
extracting the benchmark metadata json for each version that has been
benchmarked. The combined_total_reward_per_episode is extracted from each,
converted into a polars dataframe, and plotted as a scatter line in plotly.
"""
major_v = primaite.__version__.split(".")[0]
title = f"Learning Benchmark of Minor and Bugfix Releases for Major Version {major_v}"
subtitle = "Rolling Av (Combined Session Av)"
if title:
if subtitle:
title = f"{title} <br>{subtitle}</sup>"
else:
if subtitle:
title = subtitle
layout = go.Layout(
autosize=PLOT_CONFIG["size"]["auto_size"],
width=PLOT_CONFIG["size"]["width"],
height=PLOT_CONFIG["size"]["height"],
)
# Create the line graph with a colored line
fig = go.Figure(layout=layout)
fig.update_layout(template=PLOT_CONFIG["template"])
for dir in results_directory.iterdir():
if dir.is_dir():
metadata_file = dir / f"{dir.name}_benchmark_metadata.json"
with open(metadata_file, "r") as file:
metadata_dict = json.load(file)
df = _get_df_from_episode_av_reward_dict(metadata_dict["combined_total_reward_per_episode"])
fig.add_trace(go.Scatter(x=df["episode"], y=df["rolling_av_reward"], mode="lines", name=dir.name))
# Set the layout of the graph
fig.update_layout(
xaxis={
"title": "Episode",
"type": "linear",
},
yaxis={"title": "Total Reward"},
title=title,
)
fig["data"][0]["showlegend"] = True
return fig
def _get_performance_benchmark_for_all_version_dict(results_directory: Path) -> Dict[str, float]:
"""
Gathers performance benchmarks for all versions of the software stored in a specified directory.
This function iterates through each directory within the specified results directory,
extracts the av_s_per_100_steps_10_nodes from the benchmark_metadata.json files, and aggregates it into a
dictionary.
:param results_directory: The directory containing subdirectories for each version's benchmark data.
:return: A dictionary with version numbers as keys and their corresponding average performance benchmark
(average time per 100 steps on 10 nodes) as values.
"""
performance_benchmark_dict = {}
for dir in results_directory.iterdir():
if dir.is_dir():
metadata_file = dir / f"{dir.name}_benchmark_metadata.json"
with open(metadata_file, "r") as file:
metadata_dict = json.load(file)
version = metadata_dict["primaite_version"]
performance_benchmark_dict[version] = metadata_dict["av_s_per_100_steps_10_nodes"]
return performance_benchmark_dict
def _plot_av_s_per_100_steps_10_nodes(
version_times_dict: Dict[str, float],
) -> Figure:
"""
Creates a bar chart visualising the performance of each version of PrimAITE.
Performance is based on the average training time per 100 steps on 10 nodes. The function also includes a benchmark
line indicating the target maximum time.
Versions that perform under this time are marked in green, and those over are marked in red.
:param version_times_dict: A dictionary with software versions as keys and average times as values.
:return: A Plotly figure object representing the bar chart of the performance metrics.
"""
major_v = primaite.__version__.split(".")[0]
title = f"Performance of Minor and Bugfix Releases for Major Version {major_v}"
subtitle = (
f"Average Training Time per 100 Steps on 10 Nodes "
f"(target: <= {PLOT_CONFIG['av_s_per_100_steps_10_nodes_benchmark_threshold']} seconds)"
)
title = f"{title} <br><sub>{subtitle}</sub>"
layout = go.Layout(
autosize=PLOT_CONFIG["size"]["auto_size"],
width=PLOT_CONFIG["size"]["width"],
height=PLOT_CONFIG["size"]["height"],
)
fig = go.Figure(layout=layout)
fig.update_layout(template=PLOT_CONFIG["template"])
versions = sorted(list(version_times_dict.keys()))
times = [version_times_dict[version] for version in versions]
av_s_per_100_steps_10_nodes_benchmark_threshold = PLOT_CONFIG["av_s_per_100_steps_10_nodes_benchmark_threshold"]
benchmark_line_color = PLOT_CONFIG["benchmark_line_color"]
# Calculate the appropriate maximum y-axis value
max_y_axis_value = max(max(times), av_s_per_100_steps_10_nodes_benchmark_threshold) + 1
fig.add_trace(
go.Bar(
x=versions,
y=times,
marker_color=[
"green" if time < av_s_per_100_steps_10_nodes_benchmark_threshold else "red" for time in times
],
text=times,
textposition="auto",
)
)
# Add a horizontal line for the benchmark
fig.add_shape(
type="line",
x0=-0.5, # start slightly before the first bar
x1=len(versions) - 0.5, # end slightly after the last bar
y0=av_s_per_100_steps_10_nodes_benchmark_threshold,
y1=av_s_per_100_steps_10_nodes_benchmark_threshold,
line=dict(
color=benchmark_line_color,
width=2,
dash="dot",
),
)
fig.update_layout(
xaxis_title="PrimAITE Version",
yaxis_title="Avg Time per 100 Steps on 10 Nodes (seconds)",
yaxis=dict(range=[0, max_y_axis_value]),
title=title,
)
return fig
def build_benchmark_md_report(
benchmark_start_time: datetime, session_metadata: Dict, config_path: Path, results_root_path: Path
) -> None:
"""
Generates a Markdown report for a benchmarking session, documenting performance metrics and graphs.
This function orchestrates the creation of several graphs depicting various performance benchmarks and aggregates
them into a markdown document that includes comprehensive system and benchmark information.
:param benchmark_start_time: The datetime object representing when the benchmarking process was initiated.
:param session_metadata: A dictionary containing metadata for each benchmarking session.
:param config_path: A pathlib.Path object pointing to the configuration file used for the benchmark sessions.
:param results_root_path: A pathlib.Path object pointing to the directory where the results and graphs should be
saved.
"""
# generate report folder
v_str = f"v{primaite.__version__}"
version_result_dir = results_root_path / v_str
version_result_dir.mkdir(exist_ok=True, parents=True)
# load the config file as dict
with open(config_path, "r") as f:
cfg_data = yaml.safe_load(f)
# generate the benchmark metadata dict
benchmark_metadata_dict = _build_benchmark_results_dict(
start_datetime=benchmark_start_time, metadata_dict=session_metadata, config=cfg_data
)
major_v = primaite.__version__.split(".")[0]
with open(version_result_dir / f"{v_str}_benchmark_metadata.json", "w") as file:
json.dump(benchmark_metadata_dict, file, indent=4)
title = f"PrimAITE v{primaite.__version__.strip()} Learning Benchmark"
fig = _plot_benchmark_metadata(benchmark_metadata_dict, title=title)
this_version_plot_path = version_result_dir / f"{title}.png"
fig.write_image(this_version_plot_path)
fig = _plot_all_benchmarks_combined_session_av(results_directory=results_root_path)
filename = f"PrimAITE Learning Benchmark of Minor and Bugfix Releases for Major Version {major_v}.png"
all_version_plot_path = version_result_dir / filename
fig.write_image(all_version_plot_path)
performance_benchmark_dict = _get_performance_benchmark_for_all_version_dict(results_directory=results_root_path)
fig = _plot_av_s_per_100_steps_10_nodes(performance_benchmark_dict)
filename = f"PrimAITE Performance of Minor and Bugfix Releases for Major Version {major_v}.png"
performance_benchmark_plot_path = version_result_dir / filename
fig.write_image(performance_benchmark_plot_path)
data = benchmark_metadata_dict
primaite_version = data["primaite_version"]
with open(version_result_dir / f"PrimAITE v{primaite_version} Benchmark Report.md", "w") as file:
# Title
file.write(f"# PrimAITE v{primaite_version} Learning Benchmark\n")
file.write("## PrimAITE Dev Team\n")
file.write(f"### {datetime.now().date()}\n")
file.write("\n---\n")
sessions = data["total_sessions"]
episodes = session_metadata[1]["total_episodes"] - 1
steps = data["config"]["game"]["max_episode_length"]
# Body
file.write("## 1 Introduction\n")
file.write(
f"PrimAITE v{primaite_version} was benchmarked automatically upon release. Learning rate metrics "
f"were captured to be referenced during system-level testing and user acceptance testing (UAT).\n"
)
file.write(
f"The benchmarking process consists of running {sessions} training session using the same "
f"config file. Each session trains an agent for {episodes} episodes, "
f"with each episode consisting of {steps} steps.\n"
)
file.write(
f"The total reward per episode from each session is captured. This is then used to calculate an "
f"caverage total reward per episode from the {sessions} individual sessions for smoothing. "
f"Finally, a 25-widow rolling average of the average total reward per session is calculated for "
f"further smoothing.\n"
)
file.write("## 2 System Information\n")
i = 1
file.write(f"### 2.{i} Python\n")
file.write(f"**Version:** {sys.version}\n")
for section, section_data in data["system_info"].items():
i += 1
if section_data:
file.write(f"### 2.{i} {section}\n")
if isinstance(section_data, dict):
for key, value in section_data.items():
file.write(f"- **{key}:** {value}\n")
headers_map = {
"total_sessions": "Total Sessions",
"total_episodes": "Total Episodes",
"total_time_steps": "Total Steps",
"av_s_per_session": "Av Session Duration (s)",
"av_s_per_step": "Av Step Duration (s)",
"av_s_per_100_steps_10_nodes": "Av Duration per 100 Steps per 10 Nodes (s)",
}
file.write("## 3 Stats\n")
for section, header in headers_map.items():
if section.startswith("av_"):
file.write(f"- **{header}:** {data[section]:.4f}\n")
else:
file.write(f"- **{header}:** {data[section]}\n")
file.write("## 4 Graphs\n")
file.write(f"### 4.1 v{primaite_version} Learning Benchmark Plot\n")
file.write(f"![PrimAITE {primaite_version} Learning Benchmark Plot]({this_version_plot_path.name})\n")
file.write(f"### 4.2 Learning Benchmark of Minor and Bugfix Releases for Major Version {major_v}\n")
file.write(
f"![Learning Benchmark of Minor and Bugfix Releases for Major Version {major_v}]"
f"({all_version_plot_path.name})\n"
)
file.write(f"### 4.3 Performance of Minor and Bugfix Releases for Major Version {major_v}\n")
file.write(
f"![Performance of Minor and Bugfix Releases for Major Version {major_v}]"
f"({performance_benchmark_plot_path.name})\n"
)

Binary file not shown.

After

Width:  |  Height:  |  Size: 79 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 225 KiB

File diff suppressed because it is too large Load Diff

Binary file not shown.

After

Width:  |  Height:  |  Size: 104 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

View File

@@ -0,0 +1,38 @@
# PrimAITE v3.0.0 Learning Benchmark
## PrimAITE Dev Team
### 2024-07-20
---
## 1 Introduction
PrimAITE v3.0.0 was benchmarked automatically upon release. Learning rate metrics were captured to be referenced during system-level testing and user acceptance testing (UAT).
The benchmarking process consists of running 5 training session using the same config file. Each session trains an agent for 1000 episodes, with each episode consisting of 128 steps.
The total reward per episode from each session is captured. This is then used to calculate an caverage total reward per episode from the 5 individual sessions for smoothing. Finally, a 25-widow rolling average of the average total reward per session is calculated for further smoothing.
## 2 System Information
### 2.1 Python
**Version:** 3.10.14 (main, Apr 6 2024, 18:45:05) [GCC 9.4.0]
### 2.2 System
- **OS:** Linux
- **OS Version:** #76~20.04.1-Ubuntu SMP Thu Jun 13 18:00:23 UTC 2024
- **Machine:** x86_64
- **Processor:** x86_64
### 2.3 CPU
- **Physical Cores:** 2
- **Total Cores:** 4
- **Max Frequency:** 0.00Mhz
### 2.4 Memory
- **Total:** 15.62GB
- **Swap Total:** 0.00B
## 3 Stats
- **Total Sessions:** 5
- **Total Episodes:** 5005
- **Total Steps:** 640000
- **Av Session Duration (s):** 1452.5910
- **Av Step Duration (s):** 0.0454
- **Av Duration per 100 Steps per 10 Nodes (s):** 4.5393
## 4 Graphs
### 4.1 v3.0.0 Learning Benchmark Plot
![PrimAITE 3.0.0 Learning Benchmark Plot](PrimAITE v3.0.0 Learning Benchmark.png)
### 4.2 Learning Benchmark of Minor and Bugfix Releases for Major Version 3
![Learning Benchmark of Minor and Bugfix Releases for Major Version 3](PrimAITE Learning Benchmark of Minor and Bugfix Releases for Major Version 3.png)
### 4.3 Performance of Minor and Bugfix Releases for Major Version 3
![Performance of Minor and Bugfix Releases for Major Version 3](PrimAITE Performance of Minor and Bugfix Releases for Major Version 3.png)

Binary file not shown.

After

Width:  |  Height:  |  Size: 316 KiB

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

47
benchmark/utils.py Normal file
View File

@@ -0,0 +1,47 @@
# © Crown-owned copyright 2024, Defence Science and Technology Laboratory UK
import platform
from typing import Dict
import psutil
from GPUtil import GPUtil
def get_size(size_bytes: int) -> str:
"""
Scale bytes to its proper format.
e.g:
1253656 => '1.20MB'
1253656678 => '1.17GB'
:
"""
factor = 1024
for unit in ["", "K", "M", "G", "T", "P"]:
if size_bytes < factor:
return f"{size_bytes:.2f}{unit}B"
size_bytes /= factor
def _get_system_info() -> Dict:
"""Builds and returns a dict containing system info."""
uname = platform.uname()
cpu_freq = psutil.cpu_freq()
virtual_mem = psutil.virtual_memory()
swap_mem = psutil.swap_memory()
gpus = GPUtil.getGPUs()
return {
"System": {
"OS": uname.system,
"OS Version": uname.version,
"Machine": uname.machine,
"Processor": uname.processor,
},
"CPU": {
"Physical Cores": psutil.cpu_count(logical=False),
"Total Cores": psutil.cpu_count(logical=True),
"Max Frequency": f"{cpu_freq.max:.2f}Mhz",
},
"Memory": {"Total": get_size(virtual_mem.total), "Swap Total": get_size(swap_mem.total)},
"GPU": [{"Name": gpu.name, "Total Memory": f"{gpu.memoryTotal}MB"} for gpu in gpus],
}

521
diagram/classes.puml Normal file
View File

@@ -0,0 +1,521 @@
@startuml classes
set namespaceSeparator none
class "ACLRule" as primaite.acl.acl_rule.ACLRule {
dest_ip : str
permission
port : str
protocol : str
source_ip : str
get_dest_ip() -> str
get_permission() -> str
get_port() -> str
get_protocol() -> str
get_source_ip() -> str
}
class "AbstractObservationComponent" as primaite.environment.observations.AbstractObservationComponent {
current_observation : NotImplementedType, ndarray
env : str
space : Space
structure : List[str]
{abstract}generate_structure() -> List[str]
{abstract}update() -> None
}
class "AccessControlList" as primaite.acl.access_control_list.AccessControlList {
acl
acl_implicit_permission
acl_implicit_rule
max_acl_rules : int
add_rule(_permission: RulePermissionType, _source_ip: str, _dest_ip: str, _protocol: str, _port: str, _position: str) -> None
check_address_match(_rule: ACLRule, _source_ip_address: str, _dest_ip_address: str) -> bool
get_dictionary_hash(_permission: RulePermissionType, _source_ip: str, _dest_ip: str, _protocol: str, _port: str) -> int
get_relevant_rules(_source_ip_address: str, _dest_ip_address: str, _protocol: str, _port: str) -> Dict[int, ACLRule]
is_blocked(_source_ip_address: str, _dest_ip_address: str, _protocol: str, _port: str) -> bool
remove_all_rules() -> None
remove_rule(_permission: RulePermissionType, _source_ip: str, _dest_ip: str, _protocol: str, _port: str) -> None
}
class "AccessControlList_" as primaite.environment.observations.AccessControlList_ {
current_observation : ndarray
space : MultiDiscrete
structure : list
generate_structure() -> List[str]
update() -> None
}
class "ActiveNode" as primaite.nodes.active_node.ActiveNode {
file_system_action_count : int
file_system_scanning : bool
file_system_scanning_count : int
file_system_state_actual : GOOD
file_system_state_observed : REPAIRING, RESTORING, GOOD
ip_address : str
fixing_count : int
software_state
software_state : GOOD
set_file_system_state(file_system_state: FileSystemState) -> None
set_file_system_state_if_not_compromised(file_system_state: FileSystemState) -> None
set_software_state_if_not_compromised(software_state: SoftwareState) -> None
start_file_system_scan() -> None
update_booting_status() -> None
update_file_system_state() -> None
update_os_patching_status() -> None
update_resetting_status() -> None
}
class "AgentSessionABC" as primaite.agents.agent_abc.AgentSessionABC {
checkpoints_path
evaluation_path
is_eval : bool
learning_path
sb3_output_verbose_level : NONE
session_path : Union[str, Path]
session_timestamp : datetime
timestamp_str
uuid
close() -> None
{abstract}evaluate() -> None
{abstract}export() -> None
{abstract}learn() -> None
load(path: Union[str, Path]) -> None
{abstract}save() -> None
}
class "DoNothingACLAgent" as primaite.agents.simple.DoNothingACLAgent {
}
class "DoNothingNodeAgent" as primaite.agents.simple.DoNothingNodeAgent {
}
class "DummyAgent" as primaite.agents.simple.DummyAgent {
}
class "HardCodedACLAgent" as primaite.agents.hardcoded_acl.HardCodedACLAgent {
get_allow_acl_rules(source_node_id: int, dest_node_id: str, protocol: int, port: str, acl: AccessControlList, nodes: Dict[str, NodeUnion], services_list: List[str]) -> Dict[int, ACLRule]
get_allow_acl_rules_for_ier(ier: IER, acl: AccessControlList, nodes: Dict[str, NodeUnion]) -> Dict[int, ACLRule]
get_blocked_green_iers(green_iers: Dict[str, IER], acl: AccessControlList, nodes: Dict[str, NodeUnion]) -> Dict[str, IER]
get_blocking_acl_rules_for_ier(ier: IER, acl: AccessControlList, nodes: Dict[str, NodeUnion]) -> Dict[int, ACLRule]
get_deny_acl_rules(source_node_id: int, dest_node_id: str, protocol: int, port: str, acl: AccessControlList, nodes: Dict[str, NodeUnion], services_list: List[str]) -> Dict[int, ACLRule]
get_matching_acl_rules(source_node_id: str, dest_node_id: str, protocol: str, port: str, acl: AccessControlList, nodes: Dict[str, Union[ServiceNode, ActiveNode]], services_list: List[str]) -> Dict[int, ACLRule]
get_matching_acl_rules_for_ier(ier: IER, acl: AccessControlList, nodes: Dict[str, NodeUnion]) -> Dict[int, ACLRule]
}
class "HardCodedAgentSessionABC" as primaite.agents.hardcoded_abc.HardCodedAgentSessionABC {
is_eval : bool
evaluate() -> None
export() -> None
learn() -> None
load(path: Union[str, Path]) -> None
save() -> None
}
class "HardCodedNodeAgent" as primaite.agents.hardcoded_node.HardCodedNodeAgent {
}
class "IER" as primaite.pol.ier.IER {
dest_node_id : str
end_step : int
id : str
load : int
mission_criticality : int
port : str
protocol : str
running : bool
source_node_id : str
start_step : int
get_dest_node_id() -> str
get_end_step() -> int
get_id() -> str
get_is_running() -> bool
get_load() -> int
get_mission_criticality() -> int
get_port() -> str
get_protocol() -> str
get_source_node_id() -> str
get_start_step() -> int
set_is_running(_value: bool) -> None
}
class "Link" as primaite.links.link.Link {
bandwidth : int
dest_node_name : str
id : str
protocol_list : List[Protocol]
source_node_name : str
add_protocol(_protocol: str) -> None
add_protocol_load(_protocol: str, _load: int) -> None
clear_traffic() -> None
get_bandwidth() -> int
get_current_load() -> int
get_dest_node_name() -> str
get_id() -> str
get_protocol_list() -> List[Protocol]
get_source_node_name() -> str
}
class "LinkTrafficLevels" as primaite.environment.observations.LinkTrafficLevels {
current_observation : ndarray
space : MultiDiscrete
structure : list
generate_structure() -> List[str]
update() -> None
}
class "Node" as primaite.nodes.node.Node {
booting_count : int
config_values
hardware_state : BOOTING, ON, RESETTING, OFF
name : Final[str]
node_id : Final[str]
node_type : Final[NodeType]
priority
resetting_count : int
shutting_down_count : int
reset() -> None
turn_off() -> None
turn_on() -> None
update_booting_status() -> None
update_resetting_status() -> None
update_shutdown_status() -> None
}
class "NodeLinkTable" as primaite.environment.observations.NodeLinkTable {
current_observation : ndarray
space : Box
structure : list
generate_structure() -> List[str]
update() -> None
}
class "NodeStateInstructionGreen" as primaite.nodes.node_state_instruction_green.NodeStateInstructionGreen {
end_step : int
id : str
node_id : str
node_pol_type : str
service_name : str
start_step : int
state : Union['HardwareState', 'SoftwareState', 'FileSystemState']
get_end_step() -> int
get_node_id() -> str
get_node_pol_type() -> 'NodePOLType'
get_service_name() -> str
get_start_step() -> int
get_state() -> Union['HardwareState', 'SoftwareState', 'FileSystemState']
}
class "NodeStateInstructionRed" as primaite.nodes.node_state_instruction_red.NodeStateInstructionRed {
end_step : int
id : str
initiator : str
pol_type
service_name : str
source_node_id : str
source_node_service : str
source_node_service_state : str
start_step : int
state : Union['HardwareState', 'SoftwareState', 'FileSystemState']
target_node_id : str
get_end_step() -> int
get_initiator() -> 'NodePOLInitiator'
get_pol_type() -> NodePOLType
get_service_name() -> str
get_source_node_id() -> str
get_source_node_service() -> str
get_source_node_service_state() -> str
get_start_step() -> int
get_state() -> Union['HardwareState', 'SoftwareState', 'FileSystemState']
get_target_node_id() -> str
}
class "NodeStatuses" as primaite.environment.observations.NodeStatuses {
current_observation : ndarray
space : MultiDiscrete
structure : list
generate_structure() -> List[str]
update() -> None
}
class "ObservationsHandler" as primaite.environment.observations.ObservationsHandler {
current_observation
registered_obs_components : List[AbstractObservationComponent]
space
deregister(obs_component: AbstractObservationComponent) -> None
describe_structure() -> List[str]
from_config(env: 'Primaite', obs_space_config: dict) -> 'ObservationsHandler'
register(obs_component: AbstractObservationComponent) -> None
update_obs() -> None
update_space() -> None
}
class "PassiveNode" as primaite.nodes.passive_node.PassiveNode {
ip_address
}
class "Primaite" as primaite.environment.primaite_env.Primaite {
ACTION_SPACE_ACL_ACTION_VALUES : int
ACTION_SPACE_ACL_PERMISSION_VALUES : int
ACTION_SPACE_NODE_ACTION_VALUES : int
ACTION_SPACE_NODE_PROPERTY_VALUES : int
acl
action_dict : dict, Dict[int, List[int]]
action_space : Discrete, Space
action_type : int
actual_episode_count
agent_identifier
average_reward : float
env_obs : ndarray, tuple
episode_av_reward_writer
episode_count : int
episode_steps : int
green_iers : Dict[str, IER]
green_iers_reference : Dict[str, IER]
lay_down_config
links : Dict[str, Link]
links_post_blue : dict
links_post_pol : dict
links_post_red : dict
links_reference : Dict[str, Link]
max_number_acl_rules : int
network : Graph
network_reference : Graph
node_pol : Dict[str, NodeStateInstructionGreen]
nodes : Dict[str, NodeUnion]
nodes_post_blue : dict
nodes_post_pol : dict
nodes_post_red : dict
nodes_reference : Dict[str, NodeUnion]
num_links : int
num_nodes : int
num_ports : int
num_services : int
obs_config : dict
obs_handler
observation_space : Tuple, Box, Space
observation_type
ports_list : List[str]
red_iers : Dict[str, IER], dict
red_node_pol : dict, Dict[str, NodeStateInstructionRed]
services_list : List[str]
session_path : Final[Path]
step_count : int
step_info : Dict[Any]
timestamp_str : Final[str]
total_reward : float
total_step_count : int
training_config
transaction_writer
apply_actions_to_acl(_action: int) -> None
apply_actions_to_nodes(_action: int) -> None
apply_time_based_updates() -> None
close() -> None
create_acl_action_dict() -> Dict[int, List[int]]
create_acl_rule(item: Dict) -> None
create_green_ier(item: Dict) -> None
create_green_pol(item: Dict) -> None
create_link(item: Dict) -> None
create_node(item: Dict) -> None
create_node_action_dict() -> Dict[int, List[int]]
create_node_and_acl_action_dict() -> Dict[int, List[int]]
create_ports_list(ports: Dict) -> None
create_red_ier(item: Dict) -> None
create_red_pol(item: Dict) -> None
create_services_list(services: Dict) -> None
get_action_info(action_info: Dict) -> None
get_observation_info(observation_info: Dict) -> None
init_acl() -> None
init_observations() -> Tuple[spaces.Space, np.ndarray]
interpret_action_and_apply(_action: int) -> None
load_lay_down_config() -> None
output_link_status() -> None
reset() -> np.ndarray
reset_environment() -> None
reset_node(item: Dict) -> None
save_obs_config(obs_config: dict) -> None
set_as_eval() -> None
step(action: int) -> Tuple[np.ndarray, float, bool, Dict]
update_environent_obs() -> None
}
class "PrimaiteSession" as primaite.primaite_session.PrimaiteSession {
evaluation_path : Optional[Path], Path
is_load_session : bool
learning_path : Optional[Path], Path
session_path : Optional[Path], Path
timestamp_str : str, Optional[str]
close() -> None
evaluate() -> None
learn() -> None
setup() -> None
}
class "Protocol" as primaite.common.protocol.Protocol {
load : int
name : str
add_load(_load: int) -> None
clear_load() -> None
get_load() -> int
get_name() -> str
}
class "RLlibAgent" as primaite.agents.rllib.RLlibAgent {
{abstract}evaluate() -> None
{abstract}export() -> None
learn() -> None
{abstract}load(path: Union[str, Path]) -> RLlibAgent
save(overwrite_existing: bool) -> None
}
class "RandomAgent" as primaite.agents.simple.RandomAgent {
}
class "SB3Agent" as primaite.agents.sb3.SB3Agent {
is_eval : bool
evaluate() -> None
{abstract}export() -> None
learn() -> None
save() -> None
}
class "Service" as primaite.common.service.Service {
name : str
fixing_count : int
port : str
software_state : GOOD
reduce_fixing_count() -> None
}
class "ServiceNode" as primaite.nodes.service_node.ServiceNode {
services : Dict[str, Service]
add_service(service: Service) -> None
get_service_state(protocol_name: str) -> SoftwareState
has_service(protocol_name: str) -> bool
service_is_overwhelmed(protocol_name: str) -> bool
service_running(protocol_name: str) -> bool
set_service_state(protocol_name: str, software_state: SoftwareState) -> None
set_service_state_if_not_compromised(protocol_name: str, software_state: SoftwareState) -> None
update_booting_status() -> None
update_resetting_status() -> None
update_services_patching_status() -> None
}
class "SessionOutputWriter" as primaite.utils.session_output_writer.SessionOutputWriter {
learning_session : bool
transaction_writer : bool
close() -> None
write(data: Union[Tuple, Transaction]) -> None
}
class "TrainingConfig" as primaite.config.training_config.TrainingConfig {
action_type
agent_framework
agent_identifier
agent_load_file : Optional[str]
all_ok : float
checkpoint_every_n_episodes : int
compromised : float
compromised_should_be_good : float
compromised_should_be_overwhelmed : float
compromised_should_be_patching : float
corrupt : float
corrupt_should_be_destroyed : float
corrupt_should_be_good : float
corrupt_should_be_repairing : float
corrupt_should_be_restoring : float
deep_learning_framework
destroyed : float
destroyed_should_be_corrupt : float
destroyed_should_be_good : float
destroyed_should_be_repairing : float
destroyed_should_be_restoring : float
deterministic : bool
file_system_repairing_limit : int
file_system_restoring_limit : int
file_system_scanning_limit : int
good_should_be_compromised : float
good_should_be_corrupt : float
good_should_be_destroyed : float
good_should_be_overwhelmed : float
good_should_be_patching : float
good_should_be_repairing : float
good_should_be_restoring : float
green_ier_blocked : float
hard_coded_agent_view
implicit_acl_rule
load_agent : bool
max_number_acl_rules : int
node_booting_duration : int
node_reset_duration : int
node_shutdown_duration : int
num_eval_episodes : int
num_eval_steps : int
num_train_episodes : int
num_train_steps : int
observation_space : dict
observation_space_high_value : int
off_should_be_on : float
off_should_be_resetting : float
on_should_be_off : float
on_should_be_resetting : float
os_patching_duration : int
overwhelmed : float
overwhelmed_should_be_compromised : float
overwhelmed_should_be_good : float
overwhelmed_should_be_patching : float
patching : float
patching_should_be_compromised : float
patching_should_be_good : float
patching_should_be_overwhelmed : float
random_red_agent : bool
red_ier_running : float
repairing : float
repairing_should_be_corrupt : float
repairing_should_be_destroyed : float
repairing_should_be_good : float
repairing_should_be_restoring : float
resetting : float
resetting_should_be_off : float
resetting_should_be_on : float
restoring : float
restoring_should_be_corrupt : float
restoring_should_be_destroyed : float
restoring_should_be_good : float
restoring_should_be_repairing : float
sb3_output_verbose_level
scanning : float
seed : Optional[int]
service_fixing_duration : int
session_type
time_delay : int
from_dict(config_dict: Dict[str, Any]) -> TrainingConfig
to_dict(json_serializable: bool) -> Dict
}
class "Transaction" as primaite.transactions.transaction.Transaction {
action_space : Optional[int]
agent_identifier
episode_number : int
obs_space : str
obs_space_description : NoneType, Optional[List[str]], list
obs_space_post : Optional[Union['np.ndarray', Tuple['np.ndarray']]]
obs_space_pre : Optional[Union['np.ndarray', Tuple['np.ndarray']]]
reward : Optional[float], float
step_number : int
timestamp : datetime
as_csv_data() -> Tuple[List, List]
}
primaite.agents.hardcoded_abc.HardCodedAgentSessionABC --|> primaite.agents.agent_abc.AgentSessionABC
primaite.agents.hardcoded_acl.HardCodedACLAgent --|> primaite.agents.hardcoded_abc.HardCodedAgentSessionABC
primaite.agents.hardcoded_node.HardCodedNodeAgent --|> primaite.agents.hardcoded_abc.HardCodedAgentSessionABC
primaite.agents.rllib.RLlibAgent --|> primaite.agents.agent_abc.AgentSessionABC
primaite.agents.sb3.SB3Agent --|> primaite.agents.agent_abc.AgentSessionABC
primaite.agents.simple.DoNothingACLAgent --|> primaite.agents.hardcoded_abc.HardCodedAgentSessionABC
primaite.agents.simple.DoNothingNodeAgent --|> primaite.agents.hardcoded_abc.HardCodedAgentSessionABC
primaite.agents.simple.DummyAgent --|> primaite.agents.hardcoded_abc.HardCodedAgentSessionABC
primaite.agents.simple.RandomAgent --|> primaite.agents.hardcoded_abc.HardCodedAgentSessionABC
primaite.environment.observations.AccessControlList_ --|> primaite.environment.observations.AbstractObservationComponent
primaite.environment.observations.LinkTrafficLevels --|> primaite.environment.observations.AbstractObservationComponent
primaite.environment.observations.NodeLinkTable --|> primaite.environment.observations.AbstractObservationComponent
primaite.environment.observations.NodeStatuses --|> primaite.environment.observations.AbstractObservationComponent
primaite.nodes.active_node.ActiveNode --|> primaite.nodes.node.Node
primaite.nodes.passive_node.PassiveNode --|> primaite.nodes.node.Node
primaite.nodes.service_node.ServiceNode --|> primaite.nodes.active_node.ActiveNode
primaite.common.service.Service --|> primaite.nodes.service_node.ServiceNode
primaite.acl.access_control_list.AccessControlList --* primaite.environment.primaite_env.Primaite : acl
primaite.acl.acl_rule.ACLRule --* primaite.acl.access_control_list.AccessControlList : acl_implicit_rule
primaite.agents.hardcoded_acl.HardCodedACLAgent --* primaite.primaite_session.PrimaiteSession : _agent_session
primaite.agents.hardcoded_node.HardCodedNodeAgent --* primaite.primaite_session.PrimaiteSession : _agent_session
primaite.agents.rllib.RLlibAgent --* primaite.primaite_session.PrimaiteSession : _agent_session
primaite.agents.sb3.SB3Agent --* primaite.primaite_session.PrimaiteSession : _agent_session
primaite.agents.simple.DoNothingACLAgent --* primaite.primaite_session.PrimaiteSession : _agent_session
primaite.agents.simple.DoNothingNodeAgent --* primaite.primaite_session.PrimaiteSession : _agent_session
primaite.agents.simple.DummyAgent --* primaite.primaite_session.PrimaiteSession : _agent_session
primaite.agents.simple.RandomAgent --* primaite.primaite_session.PrimaiteSession : _agent_session
primaite.config.training_config.TrainingConfig --* primaite.agents.agent_abc.AgentSessionABC : _training_config
primaite.config.training_config.TrainingConfig --* primaite.environment.primaite_env.Primaite : training_config
primaite.environment.observations.ObservationsHandler --* primaite.environment.primaite_env.Primaite : obs_handler
primaite.environment.primaite_env.Primaite --* primaite.agents.agent_abc.AgentSessionABC : _env
primaite.environment.primaite_env.Primaite --* primaite.agents.hardcoded_abc.HardCodedAgentSessionABC : _env
primaite.environment.primaite_env.Primaite --* primaite.agents.sb3.SB3Agent : _env
primaite.utils.session_output_writer.SessionOutputWriter --* primaite.environment.primaite_env.Primaite : episode_av_reward_writer
primaite.utils.session_output_writer.SessionOutputWriter --* primaite.environment.primaite_env.Primaite : transaction_writer
primaite.config.training_config.TrainingConfig --o primaite.nodes.node.Node : config_values
primaite.nodes.node_state_instruction_green.NodeStateInstructionGreen --* primaite.environment.primaite_env.Primaite
primaite.nodes.node_state_instruction_red.NodeStateInstructionRed --* primaite.environment.primaite_env.Primaite
primaite.pol.ier.IER --* primaite.environment.primaite_env.Primaite
primaite.common.protocol.Protocol --o primaite.links.link.Link
primaite.links.link.Link --* primaite.environment.primaite_env.Primaite
primaite.config.training_config.TrainingConfig --o primaite.nodes.active_node.ActiveNode
primaite.utils.session_output_writer.SessionOutputWriter --> primaite.transactions.transaction.Transaction
primaite.transactions.transaction.Transaction --> primaite.environment.primaite_env.Primaite
@enduml

View File

@@ -1,12 +1,21 @@
# Minimal makefile for Sphinx documentation
#
# You can set these variables from the command line, and also
# from the environment for the first two.
SPHINXOPTS ?=
SPHINXBUILD ?= sphinx-build
SOURCEDIR = source
BUILDDIR = build
SOURCEDIR = .
BUILDDIR = _build
AUTOSUMMARY="source/_autosummary"
# Remove command is different depending on OS
ifdef OS
RM = IF exist $(AUTOSUMMARY) ( RMDIR $(AUTOSUMMARY) /s /q )
else
ifeq ($(shell uname), Linux)
RM = rm -rf $(AUTOSUMMARY)
endif
endif
# Put it first so that "make" without argument is like "make help".
help:
@@ -14,7 +23,11 @@ help:
.PHONY: help Makefile
clean:
$(RM)
# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
%: Makefile | clean
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)

BIN
docs/_static/component_relationship.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 80 KiB

BIN
docs/_static/firewall_acl.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 88 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

BIN
docs/_static/notebooks/extensions.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 68 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 193 KiB

BIN
docs/_static/primAITE_architecture.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 106 KiB

BIN
docs/_static/switched_p2p_network.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.0 KiB

View File

@@ -0,0 +1,41 @@
.. only:: comment
© Crown-owned copyright 2023, Defence Science and Technology Laboratory UK
..
Credit to https://github.com/JamesALeedham/Sphinx-Autosummary-Recursion for the custom templates.
..
{{ fullname | escape | underline}}
.. currentmodule:: {{ module }}
.. autoclass:: {{ objname }}
:members:
:show-inheritance:
:inherited-members:
:special-members: __init__, __call__, __add__, __mul__
{% block methods %}
{% if methods %}
.. rubric:: {{ _('Methods') }}
.. autosummary::
:nosignatures:
{% for item in methods %}
{%- if not item.startswith('_') %}
~{{ name }}.{{ item }}
{%- endif -%}
{%- endfor %}
{% endif %}
{% endblock %}
{% block attributes %}
{% if attributes %}
.. rubric:: {{ _('Attributes') }}
.. autosummary::
{% for item in attributes %}
~{{ name }}.{{ item }}
{%- endfor %}
{% endif %}
{% endblock %}

View File

@@ -0,0 +1,73 @@
.. only:: comment
© Crown-owned copyright 2023, Defence Science and Technology Laboratory UK
..
Credit to https://github.com/JamesALeedham/Sphinx-Autosummary-Recursion for the custom templates.
..
{{ fullname | escape | underline}}
.. automodule:: {{ fullname }}
{% block attributes %}
{% if attributes %}
.. rubric:: Module attributes
.. autosummary::
:toctree:
{% for item in attributes %}
{{ item }}
{%- endfor %}
{% endif %}
{% endblock %}
{% block functions %}
{% if functions %}
.. rubric:: {{ _('Functions') }}
.. autosummary::
:toctree:
:nosignatures:
{% for item in functions %}
{{ item }}
{%- endfor %}
{% endif %}
{% endblock %}
{% block classes %}
{% if classes %}
.. rubric:: {{ _('Classes') }}
.. autosummary::
:toctree:
:template: custom-class-template.rst
:nosignatures:
{% for item in classes %}
{{ item }}
{%- endfor %}
{% endif %}
{% endblock %}
{% block exceptions %}
{% if exceptions %}
.. rubric:: {{ _('Exceptions') }}
.. autosummary::
:toctree:
{% for item in exceptions %}
{{ item }}
{%- endfor %}
{% endif %}
{% endblock %}
{% block modules %}
{% if modules %}
.. autosummary::
:toctree:
:template: custom-module-template.rst
:recursive:
{% for item in modules %}
{{ item }}
{%- endfor %}
{% endif %}
{% endblock %}

21
docs/api.rst Normal file
View File

@@ -0,0 +1,21 @@
:orphan:
.. only:: comment
© Crown-owned copyright 2023, Defence Science and Technology Laboratory UK
..
DO NOT DELETE THIS FILE! It contains the all-important `.. autosummary::` directive with `:recursive:` option, without
which API documentation wouldn't get extracted from docstrings by the `sphinx.ext.autosummary` engine. It is hidden
(not declared in any toctree) to remove an unnecessary intermediate page; index.rst instead points directly to the
package page. DO NOT REMOVE THIS FILE!
Credit to https://github.com/JamesALeedham/Sphinx-Autosummary-Recursion for the custom templates.
..
.. autosummary::
:toctree: source/_autosummary
:template: custom-module-template.rst
:recursive:
primaite

View File

@@ -0,0 +1,67 @@
#!/bin/bash
set -x
apt-get update
apt-get -y install git rsync python3-sphinx
pwd ls -lah
export SOURCE_DATE_EPOCH=$(git log -1 --pretty=%ct)
##############
# BUILD DOCS #
##############
cd docs
# Python Sphinx, configured with source/conf.py
# See https://www.sphinx-doc.org/
make clean
make html
cd ..
#######################
# Update GitHub Pages #
#######################
git config --global user.name "${GITHUB_ACTOR}"
git config --global user.email "${GITHUB_ACTOR}@users.noreply.github.com"
docroot=`mktemp -d`
rsync -av $PWD/docs/_build/html/ "${docroot}/"
pushd "${docroot}"
git init
git remote add deploy "https://token:${GITHUB_TOKEN}@github.com/${GITHUB_REPOSITORY}.git"
git checkout -b sphinx-docs-github-pages
# Adds .nojekyll file to the root to signal to GitHub that
# directories that start with an underscore (_) can remain
touch .nojekyll
# Add README
cat > README.md <<EOF
# README for the Sphinx Docs GitHub Pages Branch
This branch is simply a cache for the website served from https://Autonomous-Resilient-Cyber-Defence.github.io/PrimAITE/,
and is not intended to be viewed on github.com.
For more information on how this site is built using Sphinx, Read the Docs, GitHub Actions/Pages, and demo
implementation from https://github.com/annegentle, see:
* https://www.docslikecode.com/articles/github-pages-python-sphinx/
* https://tech.michaelaltfield.net/2020/07/18/sphinx-rtd-github-pages-1
* https://github.com/annegentle/create-demo
EOF
# Copy the resulting html pages built from Sphinx to the sphinx-docs-github-pages branch
git add .
# Make a commit with changes and any new files
msg="Updating Docs for commit ${GITHUB_SHA} made on `date -d"@${SOURCE_DATE_EPOCH}" --iso-8601=seconds` from ${GITHUB_REF} by ${GITHUB_ACTOR}"
git commit -am "${msg}"
# overwrite the contents of the sphinx-docs-github-pages branch on our github.com repo
git push deploy sphinx-docs-github-pages --force
popd # return to main repo sandbox root
# exit cleanly
exit 0

185
docs/conf.py Normal file
View File

@@ -0,0 +1,185 @@
# © Crown-owned copyright 2023, Defence Science and Technology Laboratory UK
# Configuration file for the Sphinx documentation builder.
#
# For the full list of built-in configuration values, see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
import datetime
# -- Project information -----------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information
import os
import shutil
import sys
from pathlib import Path
from typing import Any, List, Optional
import furo # noqa
sys.path.insert(0, os.path.abspath("../"))
# -- Project information -----------------------------------------------------
year = datetime.datetime.now().year
project = "PrimAITE"
copyright = f"Copyright (C) Defence Science and Technology Laboratory UK 2021 - {year}"
author = "Defence Science and Technology Laboratory UK"
# The short Major.Minor.Build version
with open("../src/primaite/VERSION", "r") as file:
version = file.readline()
# The full version, including alpha/beta/rc tags
release = version
# set global variables
rst_prolog = f"""
.. |VERSION| replace:: {release}
"""
html_title = f"{project} v{release} docs"
# -- General configuration ---------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
"sphinx.ext.autodoc", # Core Sphinx library for auto html doc generation from docstrings
"sphinx.ext.autosummary", # Create summary tables for modules/classes/methods etc
"sphinx.ext.intersphinx", # Link to other project's documentation (see mapping below)
"sphinx.ext.viewcode", # Add a link to the Python source code for classes, functions etc.
"sphinx.ext.todo",
"sphinx_copybutton", # Adds a copy button to code blocks
"nbsphinx",
]
templates_path = ["_templates"]
exclude_patterns = [
"_build",
"Thumbs.db",
".DS_Store",
]
# -- Options for HTML output -------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output
html_theme = "furo"
html_static_path = ["_static"]
html_theme_options = {"globaltoc_collapse": True, "globaltoc_maxdepth": 2}
html_copy_source = False
nbsphinx_allow_errors = False # set to True to take shortcuts
html_scaled_image_link = False
# make some stuff easier to read
nbsphinx_prolog = """
.. raw:: html
<style>
.stderr {
color: #000 !important
}
</style>
"""
def replace_token(app: Any, docname: Any, source: Any):
"""Replaces a token from the list of tokens."""
result = source[0]
for key in app.config.tokens:
result = result.replace(key, app.config.tokens[key])
source[0] = result
tokens = {
"{VERSION}": release,
} # Token VERSION is replaced by the value of the PrimAITE version in the version file
"""Dict containing the tokens that need to be replaced in documentation."""
def notebook_assets(ignored_files: Optional[List[str]] = [], include_file_types: Optional[List[str]] = []) -> Any:
"""
Creates a function to be used with `shutil.copytree`'s `ignore` parameter.
:param ignored_files: A list of specific file names to ignore. If a file in the directory matches one of these
names, it will be excluded from the copy process.
:type ignored_files: Optional[List[str]]
:param include_file_types: A list of file extensions to include in the copy process. Files that do not match these
extensions will be excluded. If this list is empty, all files will be excluded, effectively copying only
directories.
:type include_file_types: Optional[List[str]]
"""
def ignore_items(directory: List[str], contents: List[str]) -> List[str]:
"""
Determines which files and directories should be ignored during the copy process.
:param directory: The directory being copied.
:type directory: str
:param contents: A list of contents in the directory.
:type contents: List[str]
:return: A list of items to exclude from the copy process.
:rtype: List[str]
"""
exclude_items = []
for item in contents:
if item in ignored_files:
exclude_items.append(item)
continue
if len(include_file_types) > 0:
if not any(item.lower().endswith(ext.lower()) for ext in include_file_types) and os.path.isdir(item):
exclude_items.append(item)
else:
# if we dont specify which files to include, exclude everything
exclude_items.append(item)
# exclude files but not directories
return [path for path in exclude_items if not (Path(directory) / path).is_dir()]
return ignore_items
def copy_notebooks_to_docs() -> Any:
"""
Incredibly over-engineered method that copies the notebooks and its assets to a directory within the docs directory.
This allows developers to create new notebooks without having to worry about updating documentation when
a new notebook is included within PrimAITE.
"""
notebook_asset_types = [".ipynb", ".png"]
notebook_directories = []
# find paths where notebooks are contained
for notebook in Path("../src/primaite").rglob("*.ipynb"):
# add parent path to notebook directory if not already added
if notebook.parent not in notebook_directories:
notebook_directories.append(notebook.parent)
# go through the notebook directories and copy the notebooks and extra assets
for notebook_parent in notebook_directories:
shutil.copytree(
src=notebook_parent,
dst=Path("source") / "notebooks" / notebook_parent.name,
ignore=notebook_assets(include_file_types=notebook_asset_types),
dirs_exist_ok=True,
)
def suppress_log_output():
"""Sets the log level while building the documentation."""
from primaite import _FILE_HANDLER, _LOGGER, _STREAM_HANDLER
log_level = "WARN"
_LOGGER.setLevel(log_level)
_STREAM_HANDLER.setLevel(log_level)
_FILE_HANDLER.setLevel(log_level)
def setup(app: Any):
"""Custom setup for sphinx."""
suppress_log_output()
copy_notebooks_to_docs()
app.add_config_value("tokens", {}, True)
app.connect("source-read", replace_token)

142
docs/index.rst Normal file
View File

@@ -0,0 +1,142 @@
.. only:: comment
© Crown-owned copyright 2024, Defence Science and Technology Laboratory UK
Welcome to PrimAITE's documentation
====================================
What is PrimAITE?
-----------------
Overview
^^^^^^^^
The ARCD Primary-level AI Training Environment (**PrimAITE**) provides an effective simulation capability for training and evaluating AI in a cyber-defensive role. It incorporates the functionality required of a primary-level ARCD environment:
- The ability to model a relevant system context;
- Modelling an adversarial agent that the defensive agent can be trained and evaluated against;
- The ability to model key characteristics of a system by representing hosts, servers, network devices, IP addresses, ports, operating systems, folders / files, applications, services and links;
- Modelling background (green) pattern-of-life;
- Operates at machine-speed to enable fast training cycles via Reinforcement Learning (RL).
Features
^^^^^^^^
PrimAITE incorporates the following features:
- Architected with a separate Simulation layer and Game layer. This separation of concerns defines a clear path towards transfer learning with environments of differing fidelity;
- Ability to reconfigure an RL reward function based on (a) the ability to counter the modelled adversarial cyber-attack, and (b) the ability to ensure success for green agents;
- Access Control List (ACL) functions for network devices (routers and firewalls), following standard ACL rule format (e.g., DENY / ALLOW, source / destination IP addresses, protocol and port);
- Application of traffic to the links of the system laydown adheres to the ACL rulesets and routing tables contained within each network device;
- Provides RL environments adherent to the Farama Foundation Gymnasium (Previously OpenAI Gym) API, allowing integration with any compliant RL Agent frameworks;
- Provides RL environments adherent to Ray RLlib environment specifications for single-agent and multi-agent scenarios;
- Assessed for compatibility with Stable-Baselines3 (SB3), Ray RLlib, and bespoke agents;
- Persona-based adversarial (Red) agent behaviour; several out-the-box personas are provided, and more can be developed to suit the needs of the task. Stochastic variations in Red agent behaviour are also included as required;
- A robust system logging tool, automatically enabled at the node level and featuring various log levels and terminal output options, enables PrimAITE users to conduct in-depth network simulations;
- A PCAP service is seamlessly integrated within the simulation, automatically capturing and logging frames for both
inbound and outbound traffic at the network interface level. This automatic functionality, combined with the ability
to separate traffic directions, significantly enhances network analysis and troubleshooting capabilities;
- Agent action logs provide a description of every action taken by each agent during the episode. This includes timestep, action, parameters, request and response, for all Blue agent activity, which is aligned with the Track 2 Common Action / Observation Space (CAOS) format. Action logs also details of all scripted / stochastic red / green agent actions;
- Environment ground truth is provided at every timestep, providing a full description of the environments true state;
- Alignment with CAOS provides the ability to transfer agents between CAOS compliant environments.
Architecture
^^^^^^^^^^^^
PrimAITE is a Python application and will operate on multiple Operating Systems (Windows, Linux and Mac);
a comprehensive installation and user guide is provided with each release to support its usage.
Configuration of PrimAITE is achieved via included YAML files which support full control over the network / system laydown being modelled, background pattern of life, adversarial (red agent) behaviour, and step and episode count.
A Simulation Controller layer manages the overall running of the simulation, keeping track of all low-level objects.
It is agnostic to the number of agents, their action / observation spaces, and the RL library being used.
It presents a public API providing a method for describing the current state of the simulation, a method that accepts action requests and provides responses, and a method that triggers a timestep advancement.
The Game Layer converts the simulation into a playable game for the agent(s).
It translates between simulation state and Gymnasium.Spaces to pass action / observation data between the agent(s) and the simulation. It is responsible for calculating rewards, managing Multi-Agent RL (MARL) action turns, and via a single agent interface can interact with Blue, Red and Green agents.
Agents can either generate their own scripted behaviour or accept input behaviour from an RL agent.
Finally, a Gymnasium / Ray RLlib Environment Layer forwards requests to the Game Layer as the agent sends them. This layer also manages most of the I/O, such as reading in the configuration files and saving agent logs.
.. image:: ../../_static/primAITE_architecture.png
:width: 500
:align: center
Training & Evaluation Capability
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
PrimAITE provides a training and evaluation capability to AI agents in the context of cyber-attack, via its Gymnasium / Ray RLlib compliant interface.
Scenarios can be constructed to reflect network / system laydowns consisting of any configuration of nodes (e.g., PCs, servers etc.) and the networking equipment and links between them.
All nodes can be configured to contain applications, services, folders and files (and their status).
Traffic flows between services and applications as directed by an execution definition, with the traffic flow on the network governed by the network equipment (switches, routers and firewalls) and the ACL rules and routing tables they employ.
Highlights of PrimAITEs training and evaluation capability are:
- The scenario is not bound to a representation of any platform, system, or technology;
- Fully configurable (network / system laydown, green pattern-of-life, red personas, reward function, ACL rules for each device, number of episodes / steps, action / observation space) and repeatable to suit the requirements of AI agents;
- Can integrate with any Gymnasium / Ray RLlib compliant AI agent .
PrimAITE provides a number of use cases (network and red/green action configurations) by default which the user is able to extend and modify as required.
What is PrimAITE built with
---------------------------
* `Gymnasium <https://gymnasium.farama.org/>`_ is used as the basis for AI blue agent interaction with the PrimAITE environment
* `Networkx <https://github.com/networkx/networkx>`_ is used as the underlying data structure used for the PrimAITE environment
* `Stable Baselines 3 <https://github.com/DLR-RM/stable-baselines3>`_ is used as a default source of RL algorithms (although PrimAITE is not limited to SB3 agents)
* `Ray RLlib <https://github.com/ray-project/ray>`_ is used as an additional source of RL algorithms
* `Typer <https://github.com/tiangolo/typer>`_ is used for building CLIs (Command Line Interface applications)
* `Jupyterlab <https://github.com/jupyterlab/jupyterlab>`_ is used as an extensible environment for interactive and reproducible computing, based on the Jupyter Notebook Architecture
* `Platformdirs <https://github.com/platformdirs/platformdirs>`_ is used for finding the right location to store user data and configuration but varies per platform
* `Plotly <https://github.com/plotly/plotly.py>`_ is used for building high level charts
Getting Started with PrimAITE
-----------------------------
Head over to the :ref:`getting-started` page to install and setup PrimAITE!
.. toctree::
:maxdepth: 8
:caption: About PrimAITE:
:hidden:
source/about
source/dependencies
source/glossary
.. toctree::
:caption: Usage:
:hidden:
source/getting_started
source/simulation
source/game_layer
source/config
source/environment
source/customising_scenarios
source/varying_config_files
.. toctree::
:caption: Notebooks:
:hidden:
source/example_notebooks
source/notebooks/executed_notebooks
.. toctree::
:caption: Developer information:
:hidden:
source/developer_tools
source/state_system
source/request_system
PrimAITE API <source/_autosummary/primaite>
PrimAITE Tests <source/_autosummary/tests>

View File

@@ -1,5 +1,7 @@
@ECHO OFF
setlocal EnableDelayedExpansion
pushd %~dp0
REM Command file for Sphinx documentation
@@ -7,8 +9,10 @@ REM Command file for Sphinx documentation
if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=sphinx-build
)
set SOURCEDIR=source
set BUILDDIR=build
set SOURCEDIR=.
set BUILDDIR=_build
set AUTOSUMMARYDIR="%cd%\source\_autosummary\"
%SPHINXBUILD% >NUL 2>NUL
if errorlevel 9009 (
@@ -25,11 +29,25 @@ if errorlevel 9009 (
if "%1" == "" goto help
REM delete autosummary if it exists
IF EXIST %AUTOSUMMARYDIR% (
echo deleting %AUTOSUMMARYDIR%
RMDIR %AUTOSUMMARYDIR% /s /q
)
%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
goto end
:help
%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
:clean
IF EXIST %AUTOSUMMARYDIR% (
echo deleting %AUTOSUMMARYDIR%
RMDIR %AUTOSUMMARYDIR% /s /q
)
:end
popd

317
docs/source/about.rst Normal file
View File

@@ -0,0 +1,317 @@
.. only:: comment
© Crown-owned copyright 2024, Defence Science and Technology Laboratory UK
.. _about:
About PrimAITE
==============
PrimAITE is a simulation environment for training agents to protect a computer network from cyber attacks.
Features
********
PrimAITE provides the following features:
* A flexible system for defining network layouts and host configurations
* Highly configurable network hosts, including definition of software, file system, and network interfaces,
* Realistic network traffic simulation, including address and sending packets via internet protocols like TCP, UDP, ICMP, etc.
* Routers with traffic routing and firewall capabilities
* Simulation of customisable deterministic agents
* Support for multiple agents, each having their own customisable observation space, action space, and reward function definition.
Structure
*********
PrimAITE consists of a simulator and a 'game' layer that allows agents to interact with the simulator. The simulator is built in a modular way where each component such as network hosts, links, networking devices, softwares, etc. are implemented as instances of a base class, meaning they all support the same interface. This allows for standardised configuration using either the Python API or YAML files.
The game layer is built on top of the simulator and it consumes the simulation action/state interface to allow agents to interact with the simulator. The game layer is also responsible for defining the reward function and observation space for the agents.
..
Architecture - Nodes and Links
******************************
**Nodes**
An inheritance model has been adopted in order to model nodes. All nodes have the following base attributes (Class: Node):
* ID
* Name
* Type (e.g. computer, switch, RTU - enumeration)
* Priority (P1, P2, P3, P4 or P5 - enumeration)
* Hardware State (ON, OFF, RESETTING, SHUTTING_DOWN, BOOTING - enumeration)
Active Nodes also have the following attributes (Class: Active Node):
* IP Address
* Software State (GOOD, FIXING, COMPROMISED - enumeration)
* File System State (GOOD, CORRUPT, DESTROYED, REPAIRING, RESTORING - enumeration)
Service Nodes also have the following attributes (Class: Service Node):
* List of Services (where service is composed of service name and port). There is no theoretical limit on the number of services that can be modelled. Services and protocols are currently intrinsically linked (i.e. a service is an application on a node transmitting traffic of this protocol type)
* Service state (GOOD, FIXING, COMPROMISED, OVERWHELMED - enumeration)
Passive Nodes are currently not used (but may be employed for non IP-based components such as machinery actuators in future releases).
**Links**
Links are modelled both as network edges (networkx) and as Python classes, in order to extend their functionality. Links include the following attributes:
* ID
* Name
* Bandwidth (bits/s)
* Source node ID
* Destination node ID
* Protocol list (containing the loading of protocols currently running on the link)
When the simulation runs, IERs are applied to the links in order to model traffic loading, individually assigned to each protocol. This allows green (background) and red agent behaviour to be modelled, and defensive agents to identify suspicious traffic patterns at a protocol / traffic loading level of fidelity.
Information Exchange Requirements (IERs)
****************************************
PrimAITE adopts the concept of Information Exchange Requirements (IERs) to model both green agent (background) and red agent (adversary) behaviour. IERs are used to initiate modelling of traffic loading on the network, and have the following attributes:
* ID
* Start step (i.e. which step in the training episode should the IER start)
* End step (i.e. which step in the training episode should the IER end)
* Source node ID
* Destination node ID
* Load (bits/s)
* Protocol
* Port
* Running status (i.e. on / off)
The application of green agent IERs between a source and destination follows a number of rules. Specifically:
1. Does the current simulation time step fall between IER start and end step
2. Is the source node operational (both physically and at an O/S level), and is the service (protocol / port) associated with the IER (a) present on this node, and (b) in an operational state (i.e. not FIXING)
3. Is the destination node operational (both physically and at an O/S level), and is the service (protocol / port) associated with the IER (a) present on this node, and (b) in an operational state (i.e. not FIXING)
4. Are there any Access Control List rules in place that prevent the application of this IER
5. Are all switches in the (OSPF) path between source and destination operational (both physically and at an O/S level)
For red agent IERs, the application of IERs between a source and destination follows a number of subtly different rules. Specifically:
1. Does the current simulation time step fall between IER start and end step
2. Is the source node operational, and is the service (protocol / port) associated with the IER (a) present on that node and (b) already in a compromised state
3. Is the destination node operational, and is the service (protocol / port) associated with the IER present on that node
4. Are there any Access Control List rules in place that prevent the application of this IER
5. Are all switches in the (OSPF) path between source and destination operational (both physically and at an O/S level)
Assuming the rules pass, the IER is applied to all relevant links (based on use of OSPF) between source and destination.
Node Pattern-of-Life
********************
Every node can be impacted (i.e. have a status change applied to it) by either green agent pattern-of-life or red agent pattern-of-life. This is distinct from IERs, and allows for attacks (and defence) to be modelled purely within the confines of a node.
The status changes that can be made to a node are as follows:
* All Nodes:
* Hardware State:
* ON
* OFF
* RESETTING - when a status of resetting is entered, the node will automatically exit this state after a number of steps (as defined by the nodeResetDuration configuration item) after which it returns to an ON state
* BOOTING
* SHUTTING_DOWN
* Active Nodes and Service Nodes:
* Software State:
* GOOD
* FIXING - when a status of FIXING is entered, the node will automatically exit this state after a number of steps (as defined by the osFIXINGDuration configuration item) after which it returns to a GOOD state
* COMPROMISED
* File System State:
* GOOD
* CORRUPT (can be resolved by repair or restore)
* DESTROYED (can be resolved by restore only)
* REPAIRING - when a status of repairing is entered, the node will automatically exit this state after a number of steps (as defined by the fileSystemRepairingLimit configuration item) after which it returns to a GOOD state
* RESTORING - when a status of repairing is entered, the node will automatically exit this state after a number of steps (as defined by the fileSystemRestoringLimit configuration item) after which it returns to a GOOD state
* Service Nodes only:
* Service State (for any associated service):
* GOOD
* FIXING - when a status of FIXING is entered, the service will automatically exit this state after a number of steps (as defined by the serviceFIXINGDuration configuration item) after which it returns to a GOOD state
* COMPROMISED
* OVERWHELMED
Red agent pattern-of-life has an additional feature not found in the green pattern-of-life. This is the ability to influence the state of the attributes of a node via a number of different conditions:
* DIRECT:
The pattern-of-life described by the configuration file item will be applied regardless of any other conditions in the network. This is particularly useful for direct red agent entry into the network.
* IER:
The pattern-of-life described by the configuration file item will be applied to the service on the node, only if there is an IER of the same protocol / service type incoming at the specified timestep.
* SERVICE:
The pattern-of-life described by the configuration file item will be applied to the node based on the state of a service. The service can either be on the same node, or a different node within the network.
Access Control List modelling
*****************************
An Access Control List (ACL) is modelled to provide the means to manage traffic flows in the system. This will allow defensive agents the means to turn on / off rules, or potentially create new rules, to counter an attack.
The ACL follows a standard network firewall format. For example:
.. list-table:: ACL example
:widths: 25 25 25 25 25
:header-rows: 1
* - Permission
- Source IP
- Dest IP
- Protocol
- Port
* - DENY
- 192.168.1.2
- 192.168.1.3
- HTTPS
- 443
* - ALLOW
- 192.168.1.4
- ANY
- SMTP
- 25
* - DENY
- ANY
- 192.168.1.5
- ANY
- ANY
All ACL rules are considered when applying an IER. Logic follows the order of rules, so a DENY or ALLOW for the same parameters will override an earlier entry.
Observation Spaces
******************
The observation space provides the blue agent with information about the current status of nodes and links.
PrimAITE builds on top of Gymnasium Spaces to create an observation space that is easily configurable for users. It's made up of components which are managed by the :py:class:`primaite.environment.observations.ObservationsHandler`. Each training scenario can define its own observation space, and the user can choose which information to inlude, and how it should be formatted.
NodeLinkTable component
-----------------------
For example, the :py:class:`primaite.environment.observations.NodeLinkTable` component represents the status of nodes and links as a ``gym.spaces.Box`` with an example format shown below:
An example observation space is provided below:
.. list-table:: Observation Space example
:widths: 25 25 25 25 25 25 25
:header-rows: 1
* -
- ID
- Hardware State
- Software State
- File System State
- Service / Protocol A
- Service / Protocol B
* - Node A
- 1
- 1
- 1
- 1
- 1
- 1
* - Node B
- 2
- 1
- 3
- 1
- 1
- 1
* - Node C
- 3
- 2
- 1
- 1
- 3
- 2
* - Link 1
- 5
- 0
- 0
- 0
- 0
- 10000
* - Link 2
- 6
- 0
- 0
- 0
- 0
- 10000
* - Link 3
- 7
- 0
- 0
- 0
- 5000
- 0
For the nodes, the following values are represented:
.. code-block::
[
ID
Hardware State (1=ON, 2=OFF, 3=RESETTING, 4=SHUTTING_DOWN, 5=BOOTING)
Operating System State (0=none, 1=GOOD, 2=PATCHING, 3=COMPROMISED)
File System State (0=none, 1=GOOD, 2=CORRUPT, 3=DESTROYED, 4=REPAIRING, 5=RESTORING)
Service1/Protocol1 state (0=none, 1=GOOD, 2=FIXING, 3=COMPROMISED)
Service2/Protocol2 state (0=none, 1=GOOD, 2=FIXING, 3=COMPROMISED)
]
(Note that each service available in the network is provided as a column, although not all nodes may utilise all services)
For the links, the following statuses are represented:
.. code-block::
[
ID
Hardware State (0=not applicable)
Operating System State (0=not applicable)
File System State (0=not applicable)
Service1/Protocol1 state (Traffic load from this protocol on this link)
Service2/Protocol2 state (Traffic load from this protocol on this link)
]
NodeStatus component
----------------------
This is a MultiDiscrete observation space that can be though of as a one-dimensional vector of discrete states.
The example above would have the following structure:
.. code-block::
[
node1_info
node2_info
node3_info
]
Each ``node_info`` contains the following:
.. code-block::
[
hardware_state (0=none, 1=ON, 2=OFF, 3=RESETTING, 4=SHUTTING_DOWN, 5=BOOTING)
software_state (0=none, 1=GOOD, 2=PATCHING, 3=COMPROMISED)
file_system_state (0=none, 1=GOOD, 2=CORRUPT, 3=DESTROYED, 4=REPAIRING, 5=RESTORING)
service1_state (0=none, 1=GOOD, 2=FIXING, 3=COMPROMISED)
service2_state (0=none, 1=GOOD, 2=FIXING, 3=COMPROMISED)
]
In a network with three nodes and two services, the full observation space would have 15 elements. It can be written with ``gym`` notation to indicate the number of discrete options for each of the elements of the observation space. For example:
.. code-block::
gym.spaces.MultiDiscrete([4,5,6,4,4,4,5,6,4,4,4,5,6,4,4])
.. note::
NodeStatus observation component provides information only about nodes. Links are not considered.
LinkTrafficLevels
-----------------
This component is a MultiDiscrete space showing the traffic flow levels on the links in the network, after applying a threshold to convert it from a continuous to a discrete value.
There are two configurable parameters:
* ``quantisation_levels`` determines how many discrete bins to use for converting the continuous traffic value to discrete (default is 5).
* ``combine_service_traffic`` determines whether to separately output traffic use for each network protocol or whether to combine them into an overall value for the link. (default is ``True``)
For example, with default parameters and a network with three links, the structure of this component would be:
.. code-block::
[
link1_status
link2_status
link3_status
]
Each ``link_status`` is a number from 0-4 representing the network load in relation to bandwidth.
.. code-block::
0 = No traffic (0%)
1 = low traffic (1%-33%)
2 = medium traffic (33%-66%)
3 = high traffic (66%-99%)
4 = max traffic/ overwhelmed (100%)
Using ``gym`` notation, the shape of the obs space is: ``gym.spaces.MultiDiscrete([5,5,5])``.
Action Spaces
**************
The action space available to the blue agent comes in two types:
1. Node-based
2. Access Control List
3. Any (Agent can take both node-based and ACL-based actions)
The choice of action space used during a training session is determined in the config_[name].yaml file.
**Node-Based**
The agent is able to influence the status of nodes by switching them off, resetting, or FIXING operating systems and services. In this instance, the action space is a Gymnasium spaces.Discrete type, as follows:
* Dictionary item {... ,1: [x1, x2, x3,x4] ...}
The placeholders inside the list under the key '1' mean the following:
* [0, num nodes] - Node ID (0 = nothing, node ID)
* [0, 4] - What property it's acting on (0 = nothing, 1 = state, 2 = SoftwareState, 3 = service state, 4 = file system state)
* [0, 3] - Action on property (0 = nothing, 1 = on / scan, 2 = off / repair, 3 = reset / patch / restore)
* [0, num services] - Resolves to service ID (0 = nothing, resolves to service)
**Access Control List**
The blue agent is able to influence the configuration of the Access Control List rule set (which implements a system-wide firewall). In this instance, the action space is an Gymnasium spaces.Discrete type, as follows:
* Dictionary item {... ,1: [x1, x2, x3, x4, x5, x6] ...}
The placeholders inside the list under the key '1' mean the following:
* [0, 2] - Action (0 = do nothing, 1 = create rule, 2 = delete rule)
* [0, 1] - Permission (0 = DENY, 1 = ALLOW)
* [0, num nodes] - Source IP (0 = any, then 1 -> x resolving to IP addresses)
* [0, num nodes] - Dest IP (0 = any, then 1 -> x resolving to IP addresses)
* [0, num services] - Protocol (0 = any, then 1 -> x resolving to protocol)
* [0, num ports] - Port (0 = any, then 1 -> x resolving to port)
**ANY**
The agent is able to carry out both **Node-Based** and **Access Control List** operations.
This means the dictionary will contain key-value pairs in the format of BOTH Node-Based and Access Control List as seen above.
Rewards
*******
A reward value is presented back to the blue agent on the conclusion of every step. The reward value is calculated via two methods which combine to give the total value:
1. Node and service status
2. IER status
**Node and service status**
On every step, the status of each node is compared against both a reference environment (simulating the situation if the red and blue agents had not impacted the environment)
and the before and after state of the environment. If the comparison against the reference environment shows no difference, then the score provided is "AllOK". If there is a
difference with respect to the reference environment, the before and after states are compared, and a score determined. See :ref:`config` for details of reward values.
**IER status**
On every step, the full IER set is examined to determine whether green and red agent IERs are being permitted to run. Any red agent IERs running incur a penalty; any green agent
IERs not permitted to run also incur a penalty. See :ref:`config` for details of reward values.
Future Enhancements
*******************
The PrimAITE project has an ambition to include the following enhancements in future releases:
* Integration with a suitable standardised framework to allow multi-agent integration
* Integration with external threat emulation tools, either using off-line data, or integrating at runtime

41
docs/source/config.rst Normal file
View File

@@ -0,0 +1,41 @@
.. only:: comment
© Crown-owned copyright 2024, Defence Science and Technology Laboratory UK
PrimAITE |VERSION| Configuration
********************************
PrimAITE uses YAML configuration files to define everything needed to create the training environment for RL agents, including the network, the scripted agents, and the RL agent's action space, observation space, and reward function.
Example Configuration Hierarchy
###############################
The top level configuration items in a configuration file is as follows
.. code-block:: yaml
io_settings:
...
game:
...
agents:
...
simulation:
...
These are expanded upon in the Configurable items section below
Configurable items
##################
.. toctree::
:maxdepth: 1
configuration/io_settings.rst
configuration/game.rst
configuration/agents.rst
configuration/simulation.rst
Varying The Configuration Each Episode
######################################
PrimAITE allows for the configuration to be varied each episode. This is done by specifying a configuration folder instead of a single file. A full explanation is provided in the notebook `Using-Episode-Schedules.ipynb`. Please find the notebook in the user notebooks directory.

Some files were not shown because too many files have changed in this diff Show More