├── .gitignore
├── LICENSE
├── README.md
└── deepsecurity
├── agent
├── awsAgentInstallSamples
│ ├── sampleCfnInitLx.json
│ ├── sampleCfnInitMs.json
│ ├── sampleCfnUserDataLx.json
│ └── sampleCfnUserDataMs.json
└── bash
│ ├── get-dsaPolicy.sh
│ ├── install-dsa.sh
│ ├── isKernelSupported.sh
│ └── kernel-version.sh
├── manager-apis
├── bash
│ ├── config-dsRelay.sh
│ ├── config-rehomeAwsDsManager.sh
│ ├── create-iamCloudAccount.sh
│ ├── ds10-rest-cloudAccountCreateWithCrossAccountRole.sh
│ ├── ds10-rest-cloudAccountCreateWithInstanceRole.sh
│ ├── ds10-rest-cloudAccountCreateWithKeys.sh
│ ├── ds10-rest-cloudAccountCreateWithKeysSpecialRegion.sh
│ ├── ds10-rest-cloudAccountsGet.sh
│ ├── rest-cloudAccountsCreateAws.sh
│ ├── rest-cloudAccountsCreateAwsGovCloud.sh
│ ├── rest-cloudAccountsGet.sh
│ └── rest-tenantsCreate.sh
├── powershell
│ ├── config-dsrelay.ps1
│ ├── config-ipsXforwardedForRule.ps1
│ ├── config-policy-agentcomm.ps1
│ ├── ds10-cloudAccountCreateWithKeysSpecialRegion.ps1
│ ├── get-allHostsSummary.ps1
│ ├── get-amComponentVersions.ps1
│ ├── get-computerCreatedEvents.ps1
│ ├── get-cross-tenant-ips-report.ps1
│ ├── get-firewallrules.ps1
│ ├── get-hostIpsRules.ps1
│ ├── get-hostRecoAndAssignedRules.ps1
│ ├── get-macFromInterfaces.ps1
│ ├── get-managedHostCounts.ps1
│ ├── rest-authenticationLogin.ps1
│ ├── rest-managerInfoComponents.ps1
│ └── setup-dsSoap.ps1
└── python
│ ├── listComputers.py
│ ├── listComputersExpands.py
│ ├── listComputersParallel.py
│ └── listComputersParallelExpands.py
└── manager
├── EnableStrongCiphers.script
├── EnableStrongCiphers12.script
├── README.md
├── awsFastDsm.sh
├── azure
├── SetupAzureForConnector.ps1
├── addAzureConnector.py
└── readme.md
├── docker-dsmdb
└── gcpFastDsm.sh
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | env/
12 | build/
13 | develop-eggs/
14 | dist/
15 | downloads/
16 | eggs/
17 | .eggs/
18 | lib/
19 | lib64/
20 | parts/
21 | sdist/
22 | var/
23 | *.egg-info/
24 | .installed.cfg
25 | *.egg
26 |
27 | # PyInstaller
28 | # Usually these files are written by a python script from a template
29 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
30 | *.manifest
31 | *.spec
32 |
33 | # Installer logs
34 | pip-log.txt
35 | pip-delete-this-directory.txt
36 |
37 | # Unit test / coverage reports
38 | htmlcov/
39 | .tox/
40 | .coverage
41 | .coverage.*
42 | .cache
43 | nosetests.xml
44 | coverage.xml
45 | *,cover
46 | .hypothesis/
47 |
48 | # Translations
49 | *.mo
50 | *.pot
51 |
52 | # Django stuff:
53 | *.log
54 |
55 | # Sphinx documentation
56 | docs/_build/
57 |
58 | # PyBuilder
59 | target/
60 |
61 | #Ipython Notebook
62 | .ipynb_checkpoints
63 |
64 | #IntelliJ project files
65 | .idea
66 | *.iml
67 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Ops Tools for Deep Security
2 |
3 | A set of handy tools to make it easier to run to Deep Security.
4 |
5 | ## Table of Contents
6 |
7 | * [Manager tools](#manager-tools)
8 | * [Agent tools](#agent-tools)
9 | * [Support](#support)
10 | * [Contribute](#contribute)
11 |
12 | ## Manager Tools
13 |
14 | ### Bash
15 |
16 |
17 | - config-dsRelay.sh
18 | - Query the status of, enable, or disable relay functionality on an agent
19 | - config-rehomeAwsDsManager.sh
20 | - Used by our cloud formation projects to ensure the correct cloud connector sync'd object is activated
21 | - create-iamCloudAccount.sh
22 | - Create an IAM user and associated keys, then use those keys to create the DS cloud connector
23 | - rest-cloudAccountsCreateAws.sh
24 | - Create cloud accounts for all regions
25 | - rest-cloudAccountsCreateAws.sh
26 | - Create cloud account for GovCloud
27 | - rest-tenantsCreate.sh
28 | - Create new tenant
29 |
30 |
31 | ### PowerShell
32 |
33 |
34 | - config-dsRelay.ps1
35 | - Query the status of, enable, or disable relay functionality on an agent
36 | - config-ipsXforwardedForRule.ps1
37 | - Create or update an IPS rule which a list of IPS to be blocked based on header added by an AWS ELB
38 | - config-plicy-agentcomm.ps1
39 | - Configure manager agent communication direction on a policy
40 | - get-allHostsSummary.ps1
41 | - Get summary of all host objects in deep security manager similar to dashboard status widget
42 | - get-amComponentVersions.ps1
43 | - Get detailed agent and am engine versions for a host object
44 | - get-computerCreatedEvents.ps1
45 | - Get all computer created system events for a given time frame
46 | - get-firewallrules.ps1
47 | - Get all firewall rules for a given host object
48 | - get-hostIpsRules.ps1
49 | - Get all ips rules assigned to a policy for each host object in the DSM
50 | - get-hostRecoAndAssignedRules.ps1
51 | - Get count of assigned and recommended rules for each host object in the DSM
52 | - get-macFromInterfaces.ps1
53 | - Get all interfaces and their mac addresses for a given host object
54 | - get-managedHostCounts.ps1
55 | - Get a simple count of all Unmanaged vs not Unmanaged hosts in the DSM
56 | - rest-authenticationLogin.ps1
57 | - Rest call to get a Security ID token for subsequent calls. SID returned may be used for SOAP or REST calls
58 | - rest-managerInfoComponents.ps1
59 | - Rest call to get list of current components available in the DSM
60 | - setup-dsSoap.ps1
61 | - Setup script to leave the caller with a current token in $SID and ManagerService instance in $DSM for use in interactive shell. Also starting authenticaiton for new scripts
62 |
63 |
64 | ### Scheduled Task Scripts
65 |
66 |
67 | - EnableStrongCiphers.script
68 | - Allows Deep Security to communicate exclusively with strong ciphers
69 |
70 |
71 | ## Agent tools
72 |
73 |
74 | - awsAgentInstallSamples
75 | - UserData and CfnInit snippets for use in integrating Deep Security Agent deployment in AWS automation tooling
76 |
77 |
78 | ### Bash
79 |
80 |
81 | - get-dsaPolicy.sh
82 | - Query the local DSA for its current policyid and policyname
83 | - install-dsa.sh
84 | - Working project 'one script to rule them all'; single bash script to download, install, and activate a deep security agent on any linux distro, arch, and version
85 |
86 |
87 | ## Support
88 |
89 | This is an Open Source community project. Project contributors may be able to help,
90 | depending on their time and availability. Please be specific about what you're
91 | trying to do, your system, and steps to reproduce the problem.
92 |
93 | For bug reports or feature requests, please
94 | [open an issue](../issues).
95 | You are welcome to [contribute](#contribute).
96 |
97 | Official support from Trend Micro is not available. Individual contributors may be
98 | Trend Micro employees, but are not official support.
99 |
100 | ## Contribute
101 |
102 | We accept contributions from the community. To submit changes:
103 |
104 | 1. Fork this repository.
105 | 1. Create a new feature branch.
106 | 1. Make your changes.
107 | 1. Submit a pull request with an explanation of your changes or additions.
108 |
109 | We will review and work with you to release the code.
110 |
--------------------------------------------------------------------------------
/deepsecurity/agent/awsAgentInstallSamples/sampleCfnInitLx.json:
--------------------------------------------------------------------------------
1 | "InstanceName" : {
2 | "Type" : "AWS::EC2::Instance",
3 | "Metadata" : {
4 | "AWS::CloudFormation::Init" : {
5 | configSets : {
6 | "default" : [
7 | "appConfig",
8 | "managementConfig"
9 | ],
10 | "deepSecurityAgentActivation" : [
11 | "dsaActivation"
12 | ]
13 | },
14 | "appConfig" : {
15 | ...
16 | },
17 | "managementConfig": {
18 | ...
19 | }
20 | "dsaActivation" : {
21 | "commands" : {
22 | "1-download-agent" : {
23 | "command" : "curl -k https://PUTCUSTOMERDSMFQDN:PORTHERE/software/agent/PLATFORM/ARCH/ -o /tmp/agent.rpm"
24 | },
25 | "2-install-agent" : {
26 | "command" : "rpm -ivh /tmp/agent.rpm"
27 | },
28 | "3-reset-agent" : {
29 | "command" : "/opt/ds_agent/dsa_control -r",
30 | },
31 | "4-activate-agent" : {
32 | "command" : "/opt/ds_agent/dsa_control -a dsm://PUTCUSTOMERDSMFQDN:PORTHERE/"
33 | }
34 | }
35 | }
36 | }
37 | },
38 | "UserData" : {
39 | "Fn::Base64" : {
40 | "Fn::Join" : [
41 | "",
42 | [
43 | "#!/bin/bash -xe ",
44 | "# cloud-init ",
45 | "/opt/aws/bin/cfn-init -v ",
46 | " --stack ",
47 | {
48 | "Ref" : "AWS::StackName"
49 | },
50 | " --resource INSTANCENAME",
51 | " --region ",
52 | {
53 | "Ref" : "AWS::Region"
54 | },
55 | " -c default,deepSecurityAgentActivation",
56 | " ",
57 | "/opt/aws/bin/cfn-signal -e $?"
58 | ]
59 | ]
60 | }
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/deepsecurity/agent/awsAgentInstallSamples/sampleCfnInitMs.json:
--------------------------------------------------------------------------------
1 | "InstanceName" : {
2 | "Type" : "AWS::EC2::Instance",
3 | "Metadata" : {
4 | "AWS::CloudFormation::Init" : {
5 | configSets : {
6 | "default" : [
7 | "appConfig",
8 | "managementConfig"
9 | ],
10 | "deepSecurityAgentActivation" : [
11 | "dsaActivation"
12 | ]
13 | },
14 | "appConfig" : {
15 | ...
16 | },
17 | "managementConfig": {
18 | ...
19 | }
20 | "dsaActivation" : {
21 | "commands" : {
22 | "1-reset-agent" : {
23 | "command" : "powershell.exe -Command $Env:ProgramFiles\"\\Trend Micro\\Deep Security Agent\\dsa_control\" -r",
24 | },
25 | "2-activate-agent" : {
26 | "command" : "powershell.exe -Command $Env:ProgramFiles\"\\Trend Micro\\Deep Security Agent\\dsa_control\" -a dsm://PUTCUSTOMERDSMFQDN:PORTHERE/"
27 | }
28 | }
29 | }
30 | }
31 | },
32 | "UserData" : {
33 | "Fn::Base64" : {
34 | "Fn::Join" : [
35 | "",
36 | [
37 | ""
53 | ]
54 | ]
55 | }
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/deepsecurity/agent/awsAgentInstallSamples/sampleCfnUserDataLx.json:
--------------------------------------------------------------------------------
1 | "InstanceName" : {
2 | "Type" : "AWS::EC2::Instance",
3 | "Metadata" : {....},
4 | "UserData" : {
5 | "Fn::Base64" : {
6 | "Fn::Join" : [
7 | "",
8 | [
9 | "#!/bin/bash -xe"
10 | "curl -k https://PUTCUSTOMERDSMFQDN:PORTHERE/software/agent/PLATFORM/ARCH/ -o /tmp/agent.rpm"
11 | "rpm -ivh /tmp/agent.rpm"
12 | "/opt/ds_agent/dsa_control -r"
13 | "/opt/ds_agent/dsa_control -a dsm://PUTCUSTOMERDSMFQDN:PORTHERE/"
14 | ]
15 | ]
16 | }
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/deepsecurity/agent/awsAgentInstallSamples/sampleCfnUserDataMs.json:
--------------------------------------------------------------------------------
1 | "InstanceName" : {
2 | "Type" : "AWS::EC2::Instance",
3 | "Metadata" : {....},
4 | "UserData" : {
5 | "Fn::Base64" : {
6 | "Fn::Join" : [
7 | "",
8 | [
9 | "\n",
10 | "[Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}",
11 | "New-Object System.Net.WebClient).DownloadFile(\"https://dsm://PUTCUSTOMERDSMFQDN:PORTHERE/software/agent/Windows/x86_64/\", \"$env:temp\\agent.msi\")"
12 | "$Env:ProgramFiles\"\\Trend Micro\\Deep Security Agent\\dsa_control\" -r \n",
13 | "$Env:ProgramFiles\"\\Trend Micro\\Deep Security Agent\\dsa_control\" -a dsm://PUTCUSTOMERDSMFQDN:PORTHERE/ \n",
14 | ""
15 | ]
16 | ]
17 | }
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/deepsecurity/agent/bash/get-dsaPolicy.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | if [ -a tempDsaConfig ]
4 | then
5 | rm tempDsaConfig
6 | fi
7 |
8 | /opt/ds_agent/sendCommand --get GetConfiguration | tail -n +4 > tempDsaConfig
9 |
10 | policyid=$(xmllint -xpath 'string(//SecurityProfile/@id)' tempDsaConfig)
11 | policyname=$(xmllint -xpath 'string(//SecurityProfile/@name)' tempDsaConfig)
12 |
13 | rm tempDsaConfig
14 |
15 | if [ -z $policyid ]
16 | then
17 | exit 1
18 | fi
19 |
20 | echo ${policyname},${policyid}
21 | exit 0
22 |
23 |
--------------------------------------------------------------------------------
/deepsecurity/agent/bash/install-dsa.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | ##one line DSA Linux install script
3 |
4 | managerfqdn="$1"
5 | managerconsoleport="$2"
6 | policyid="$3"
7 | tenantid="$5"
8 | tenantpassword="$5"
9 | distro=""
10 | majversion=""
11 | agentidstring=""
12 | arch=$(uname -m)
13 | if [ $arch == i686 ]
14 | then
15 | arch=i386
16 | fi
17 |
18 | ##detect distros with systemd
19 |
20 | if [ -f /etc/os-release ]
21 | then
22 | . /etc/os-release
23 | distro=$ID
24 | majversion=${VERSION_ID:0:1}
25 |
26 | case $distro in
27 | rhel)
28 | echo "Redhat 7 detected"
29 | agentidstring="RedHat_EL7"
30 | ;;
31 | centos)
32 | echo "Centos 7 detected"
33 | agentidstring="RedHat_EL7"
34 | ;;
35 | amzn)
36 | echo "amazon detected"
37 | agentidstring="amzn1"
38 | ;;
39 | ol)
40 | echo "Oracle Linux detected"
41 | agentidstring="Oracle_OL7"
42 | ;;
43 | sles)
44 | majversion=${VERSION_ID:0:2}
45 | case $majversion in
46 | 11)
47 | echo "SUSE 11 detected"
48 | agentidstring="SuSE_11"
49 | ;;
50 | 12)
51 | echo "SUSE 12 detected"
52 | agentidstring="SuSE_12"
53 | ;;
54 | esac
55 | ;;
56 | ubuntu)
57 | majversion=${VERSION_ID:0:2}
58 | case $majversion in
59 | 12)
60 | echo "Ubuntu 12 detected"
61 | agentidstring="Ubuntu_12.04"
62 | ;;
63 | 14)
64 | echo "Ubuntu 14 detected"
65 | agentidstring="Ubuntu_14.04"
66 | ;;
67 | esac
68 | ;;
69 |
70 | *)
71 | echo "os-release detected but OS not implemented"
72 | exit 1
73 | esac
74 | else
75 | #older than systemd
76 | #Oracle Linux
77 | if [ -f /etc/oracle-release ]
78 | then
79 | distro="ol"
80 | VERSION_ID=$(lsb_release -sr)
81 | majorversion=${VERSION_ID:0:1}
82 | case $majorversion in
83 | 5)
84 | echo "Oracle Linux 5 Detected"
85 | agentidstring="Oracle_OL5"
86 | ;;
87 | 6)
88 | echo "Oracle Linux 6 Detected"
89 | agentidstring="Oracle_OL6"
90 | ;;
91 | esac
92 | else
93 | #rhel and CentOS
94 | if [ -f /etc/redhat-release ]
95 | then
96 | distro="rhel"
97 | VERSION_ID=$(lsb_release -sr)
98 | majorversion=${VERSION_ID:0:1}
99 | case $majorversion in
100 | 5)
101 | echo "RedHat 5 Detected"
102 | agentidstring="RedHat_EL5"
103 | ;;
104 | 6)
105 | echo "RedHat 6 Detected"
106 | agentidstring="RedHat_EL6"
107 | ;;
108 | esac
109 | else
110 | #SUSE 10
111 | if [ -f /etc/SuSE-release ]
112 | then
113 | distro="SuSE"
114 | VERSION_ID=$(lsb_release -sr)
115 | majorversion=${VERSION_ID:0:2}
116 | echo "SuSE 10 Decteted"
117 | agentidstring="SuSE_10"
118 | else
119 | echo "Failed to determine OS"
120 | exit 1
121 | fi
122 | fi
123 | fi
124 | fi
125 |
126 |
127 |
128 |
129 |
130 | #build deployment script
131 | if [ ! -z $tenantid ]
132 | then
133 | $tenantid="\"tenantID:${tenantid}\""
134 | $tenantpassword="\"tenantPassword:${tenantpassword}\""
135 | fi
136 | if [ ! -z $policyid ]
137 | then
138 | $policyid="\"policyid:${policyid}\""
139 | fi
140 | echo "Downloading Agent from: "
141 | echo "https://${managerfqdn}:${managerconsoleport}/software/agent/${agentidstring}/${arch}/ "
142 | curl -k https://${managerfqdn}:${managerconsoleport}/software/agent/${agentidstring}/${arch}/ -o /tmp/agent.rpm
143 | echo "Installing Agent"
144 | if [ $distro == ubuntu ]
145 | then
146 | dpkg -i /tmp/agent.deb
147 | else
148 | rpm -ivh /tmp/agent.rpm
149 | fi
150 | sleep 15
151 | /opt/ds_agent/dsa_control -r
152 | echo "Activating Agent"
153 | /opt/ds_agent/dsa_control -a dsm://${managerfqdn}:4120/ ${policyid} ${tenantid} ${tenantpassword}
154 |
155 |
156 |
--------------------------------------------------------------------------------
/deepsecurity/agent/bash/isKernelSupported.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # Description
4 | # This script looks up the current kernel version and check if it is supported by Deep Security.
5 | # A webservice is called to find the currently support kernel.
6 | #
7 | # You can call with the Deep Security version on the command line or
8 | # it will ask the installed DSA directly.
9 | #
10 | # Example with DSA version 12.0:
11 | # ./isKernelSupported.sh 12.0
12 | #
13 | # Example autodetecting the currently installed DSA verison:
14 | # ./isKernelSupported.sh
15 |
16 |
17 |
18 |
19 | KERNEL_SITE='https://c3utfermrk.execute-api.us-east-1.amazonaws.com/dev/';
20 | dsaVersion='';
21 | linuxPlatform='';
22 | platform='';
23 | majorVersion='';
24 | latestVersion='';
25 | kernelVersion=`uname -r`
26 | ### Main
27 | main()
28 | {
29 | if [ -z ${1} ]; then
30 | getDSAVersion
31 | else
32 | dsaVersion=${1}
33 | fi
34 | platform_detect
35 | url="$KERNEL_SITE$linuxPlatform/$dsaVersion/$kernelVersion"
36 | echo $url
37 | latestVersion=`curl -f -s --ssl-reqd $url`
38 | if [ $? -ne 0 ]; then
39 | echo "Unsupported combination"
40 | exit -1
41 | fi
42 | echo "Supported Kernel"
43 | #Useful for debugging
44 | #echo "dsaVersion" $dsaVersion
45 | #echo "linuxPlatform" $linuxPlatform
46 | #echo "platform" $platform
47 | #echo "majorVersion" $majorVersion
48 | }
49 |
50 | ### Get DSA Version
51 | getDSAVersion()
52 | {
53 | dsaVersion=`/opt/ds_agent/dsa_query -c GetPluginVersion | grep PluginVersion.core | cut -d ':' -f 2 | cut -d '.' -f 1-2`
54 | dsaVersion=`echo $dsaVersion | awk '{$1=$1};1'`
55 | }
56 |
57 |
58 |
59 | ###PlatformDetection
60 |
61 | # Detect Linux platform
62 |
63 | platform_detect() {
64 | if !(type lsb_release &>/dev/null); then
65 | distribution=$(cat /etc/*-release | grep '^NAME' );
66 | release=$(cat /etc/*-release | grep '^VERSION_ID');
67 | else
68 | distribution=$(lsb_release -i | grep 'ID' | grep -v 'n/a');
69 | release=$(lsb_release -r | grep 'Release' | grep -v 'n/a');
70 | fi;
71 | if [ -z "$distribution" ]; then
72 | distribution=$(cat /etc/*-release);
73 | release=$(cat /etc/*-release);
74 | fi;
75 |
76 | releaseVersion=${release//[!0-9.]};
77 | case $distribution in
78 | *"Debian"*)
79 | platform='debian';
80 | if [[ $releaseVersion =~ ^7.* ]]; then
81 | majorVersion='7';
82 | elif [[ $releaseVersion =~ ^8.* ]]; then
83 | majorVersion='8';
84 | elif [[ $releaseVersion =~ ^9.* ]]; then
85 | majorVersion='9';
86 | fi;
87 | ;;
88 |
89 | *"Ubuntu"*)
90 | platform='ubuntu';
91 | if [[ $releaseVersion =~ ^14.* ]]; then
92 | majorVersion='14';
93 | elif [[ $releaseVersion =~ ^16.* ]]; then
94 | majorVersion='16';
95 | elif [[ $releaseVersion =~ ^18.* ]]; then
96 | majorVersion='18';
97 | fi;
98 | ;;
99 |
100 | *"SUSE"* | *"SLES"*)
101 | platform='suse';
102 | if [[ $releaseVersion =~ ^11.* ]]; then
103 | majorVersion='11';
104 | elif [[ $releaseVersion =~ ^12.* ]]; then
105 | majorVersion='12';
106 | fi;
107 | ;;
108 |
109 | *"Oracle"* | *"EnterpriseEnterpriseServer"*)
110 | platform='oracle';
111 | if [[ $releaseVersion =~ ^5.* ]]; then
112 | majorVersion='5'
113 | elif [[ $releaseVersion =~ ^6.* ]]; then
114 | majorVersion='6';
115 | elif [[ $releaseVersion =~ ^7.* ]]; then
116 | majorVersion='7';
117 | fi;
118 | ;;
119 |
120 | *"CentOS"*)
121 | platform='rhel';
122 | if [[ $releaseVersion =~ ^5.* ]]; then
123 | majorVersion='5';
124 | elif [[ $releaseVersion =~ ^6.* ]]; then
125 | majorVersion='6';
126 | elif [[ $releaseVersion =~ ^7.* ]]; then
127 | majorVersion='7';
128 | elif [[ $releaseVersion =~ ^8.* ]]; then
129 | majorVersion='8';
130 | fi;
131 | ;;
132 |
133 | *"CloudLinux"*)
134 | platform='cloud';
135 | if [[ $releaseVersion =~ ^6.* ]]; then
136 | majorVersion='6';
137 | elif [[ $releaseVersion =~ ^7.* ]]; then
138 | majorVersion='7';
139 | fi;
140 | ;;
141 |
142 | *"Amazon"*)
143 | platform='amazon';
144 | if [[ $(uname -r) == *"amzn2"* ]]; then
145 | majorVersion='2';
146 | elif [[ $(uname -r) == *"amzn1"* ]]; then
147 | majorVersion='1';
148 | fi;
149 | ;;
150 |
151 | *"RedHat"* | *"Red Hat"*)
152 | platform='rhel';
153 | if [[ $releaseVersion =~ ^5.* ]]; then
154 | majorVersion='5';
155 | elif [[ $releaseVersion =~ ^6.* ]]; then
156 | majorVersion='6';
157 | elif [[ $releaseVersion =~ ^7.* ]]; then
158 | majorVersion='7';
159 | elif [[ $releaseVersion =~ ^8.* ]]; then
160 | majorVersion='8';
161 | fi;
162 | ;;
163 |
164 | esac
165 |
166 | if [[ -z "${platform}" ]] || [[ -z "${majorVersion}" ]]; then
167 | echo Unsupported platform is detected
168 | logger -t Unsupported platform is detected
169 | false
170 | else
171 | archType='/32'; architecture=$(arch);
172 | if [[ ${architecture} == *"x86_64"* ]]; then
173 | archType='/64';
174 | fi
175 |
176 | linuxPlatform=$platform$majorVersion$archType;
177 | fi
178 | }
179 |
180 | ###End PlatformDetection
181 |
182 | main "$@"
--------------------------------------------------------------------------------
/deepsecurity/agent/bash/kernel-version.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # Prerequisite
4 | #
5 | # Deep Security Manager must be downloading the latest agent packages.
6 | # This is when the latest kernel package support the kernel, the
7 | # latest kernel package is avaliable in the DSM for download.
8 | #
9 |
10 | # Description
11 | # This script detects which version of the Deep Security agent is installed,
12 | # which OS and makes a call to a webservice to find the current highest support kernel.
13 | # It then updates either yum or apt to prevent installing a kernel newer than DSA
14 | # currently support for that platform.
15 | #
16 | # You can run this script daily or weekly to keep the kernel limit up to date.
17 | # It can be run from cron, manually, or any other automated process.
18 | #
19 |
20 |
21 | KERNEL_SITE='https://c3utfermrk.execute-api.us-east-1.amazonaws.com/dev/';
22 | dsaVersion='';
23 | linuxPlatform='';
24 | isRPM='';
25 | platform='';
26 | majorVersion='';
27 | latestVersion='';
28 | subKernel='';
29 |
30 | ### Main
31 | main()
32 | {
33 | platform_detect
34 | getDSAVersion
35 | getSubKernelType
36 | getLatestKernel
37 | updatelock $latestVersion
38 | #Useful for debugging
39 | #echo "dsaVersion" $dsaVersion
40 | #echo "linuxPlatform" $linuxPlatform
41 | #echo "isRPM" $isRPM
42 | #echo "platform" $platform
43 | #echo "majorVersion" $majorVersion
44 | #echo "latestVersion" $latestVersion
45 | }
46 | ### Find a kernel subtype if there is one
47 | getSubKernelType()
48 | {
49 | aws=`uname -r | grep aws`
50 | gcp=`uname -r | grep gcp`
51 | azure=`uname -r | grep azure`
52 | k8s=`uname -r | grep k8s`
53 | if [ -z ${aws+x} ]; then
54 | if [ -z ${gcp+x} ]; then
55 | if [ -z ${azure+x} ]; then
56 | if [ -z ${k8s+x} ]; then
57 | subKernel=""
58 | else
59 | subKernel="k8s"
60 | fi
61 | else
62 | subKernel="azure"
63 | fi
64 | else
65 | subKernel="gcp"
66 | fi
67 | else
68 | subKernel="aws"
69 | fi
70 |
71 | }
72 |
73 | ### Get DSA Version
74 | getDSAVersion()
75 | {
76 | dsaVersion=`/opt/ds_agent/dsa_query -c GetPluginVersion | grep PluginVersion.core | cut -d ':' -f 2 | cut -d '.' -f 1-2`
77 | dsaVersion=`echo $dsaVersion | awk '{$1=$1};1'`
78 | }
79 |
80 | ### Get updated kernel version
81 | getLatestKernel()
82 | {
83 | if [ -z ${subKernel+x} ]; then
84 | url="$KERNEL_SITE$linuxPlatform/$dsaVersion"
85 | else
86 | url="$KERNEL_SITE$linuxPlatform/$dsaVersion?subtype=$subKernel"
87 | fi
88 | echo $url
89 | latestVersion=`curl -s --ssl-reqd $url | sed -e 's/^"//' -e 's/"$//'`
90 |
91 | }
92 |
93 | ### locking functions
94 | installVersionLock(){
95 | if [[ $isRPM == 1 ]]; then
96 | yum install -y yum-plugin-versionlock
97 | else
98 | FILE=/etc/apt/preferences
99 | if [ ! -f $FILE ]; then
100 | echo "# Deep Security Agent Pinning camptable kernel version" >> $FILE
101 | echo "# End Deep Security Pin" >> $FILE
102 | fi
103 | fi
104 | }
105 |
106 | lockVersion(){
107 | if [[ $isRPM == 1 ]]; then
108 | yum versionlock kernel-$1
109 |
110 | fi
111 | }
112 |
113 | updatelock()
114 | {
115 | echo "updating lock to $1"
116 | if [[ $isRPM == 1 ]]; then
117 | FILE=/etc/yum/pluginconf.d/versionlock.list
118 | if [ -f "$FILE" ]; then
119 | sed -i 's/kernel-*/kernel-$1/' $FILE
120 | else
121 | installVersionLock
122 | lockVersion $1
123 | fi
124 | else
125 | FILE=/etc/apt/preferences
126 | installVersionLock $FILE
127 | KernelVersion_1=`echo $latestVersion | cut -d '-' -f 1`
128 | KernelVersion_2=`echo $latestVersion | cut -d '-' -f 2`
129 | KernelVersion=$KernelVersion_1.$KernelVersion_2
130 | if [ -z ${subKernel+x} ]; then
131 | KernelType="linux-generic"
132 | else
133 | KernelType="linux-$subKernel"
134 | fi
135 |
136 | awk "/# Deep Security Agent Pinning camptable kernel version/{p=1;print;print \"Package: $KernelType\nPin: version $KernelVersion*\nPin-Priority: 1100\"}/# End Deep Security Pin/{p=0}!p" /etc/apt/preferences > /tmp/preferences.tmp
137 | mv /tmp/preferences.tmp /etc/apt/preferences
138 | fi
139 | }
140 | ### end locking functions
141 |
142 |
143 |
144 |
145 | ###PlatformDetection
146 |
147 | # Detect Linux platform
148 |
149 | platform_detect() {
150 | isRPM=1
151 | if !(type lsb_release &>/dev/null); then
152 | distribution=$(cat /etc/*-release | grep '^NAME' );
153 | release=$(cat /etc/*-release | grep '^VERSION_ID');
154 | else
155 | distribution=$(lsb_release -i | grep 'ID' | grep -v 'n/a');
156 | release=$(lsb_release -r | grep 'Release' | grep -v 'n/a');
157 | fi;
158 | if [ -z "$distribution" ]; then
159 | distribution=$(cat /etc/*-release);
160 | release=$(cat /etc/*-release);
161 | fi;
162 |
163 | releaseVersion=${release//[!0-9.]};
164 | case $distribution in
165 | *"Debian"*)
166 | platform='debian'; isRPM=0;
167 | if [[ $releaseVersion =~ ^7.* ]]; then
168 | majorVersion='7';
169 | elif [[ $releaseVersion =~ ^8.* ]]; then
170 | majorVersion='8';
171 | elif [[ $releaseVersion =~ ^9.* ]]; then
172 | majorVersion='9';
173 | fi;
174 | ;;
175 |
176 | *"Ubuntu"*)
177 | platform='ubuntu'; isRPM=0;
178 | if [[ $releaseVersion =~ ^14.* ]]; then
179 | majorVersion='14';
180 | elif [[ $releaseVersion =~ ^16.* ]]; then
181 | majorVersion='16';
182 | elif [[ $releaseVersion =~ ^18.* ]]; then
183 | majorVersion='18';
184 | fi;
185 | ;;
186 |
187 | *"SUSE"* | *"SLES"*)
188 | platform='suse';
189 | if [[ $releaseVersion =~ ^11.* ]]; then
190 | majorVersion='11';
191 | elif [[ $releaseVersion =~ ^12.* ]]; then
192 | majorVersion='12';
193 | fi;
194 | ;;
195 |
196 | *"Oracle"* | *"EnterpriseEnterpriseServer"*)
197 | platform='oracle';
198 | if [[ $releaseVersion =~ ^5.* ]]; then
199 | majorVersion='5'
200 | elif [[ $releaseVersion =~ ^6.* ]]; then
201 | majorVersion='6';
202 | elif [[ $releaseVersion =~ ^7.* ]]; then
203 | majorVersion='7';
204 | fi;
205 | ;;
206 |
207 | *"CentOS"*)
208 | platform='rhel';
209 | if [[ $releaseVersion =~ ^5.* ]]; then
210 | majorVersion='5';
211 | elif [[ $releaseVersion =~ ^6.* ]]; then
212 | majorVersion='6';
213 | elif [[ $releaseVersion =~ ^7.* ]]; then
214 | majorVersion='7';
215 | fi;
216 | ;;
217 |
218 | *"CloudLinux"*)
219 | platform='cloud';
220 | if [[ $releaseVersion =~ ^6.* ]]; then
221 | majorVersion='6';
222 | elif [[ $releaseVersion =~ ^7.* ]]; then
223 | majorVersion='7';
224 | fi;
225 | ;;
226 |
227 | *"Amazon"*)
228 | platform='amazon';
229 | if [[ $(uname -r) == *"amzn2"* ]]; then
230 | majorVersion='2';
231 | elif [[ $(uname -r) == *"amzn1"* ]]; then
232 | majorVersion='1';
233 | fi;
234 | ;;
235 |
236 | *"RedHat"* | *"Red Hat"*)
237 | platform='rhel';
238 | if [[ $releaseVersion =~ ^5.* ]]; then
239 | majorVersion='5';
240 | elif [[ $releaseVersion =~ ^6.* ]]; then
241 | majorVersion='6';
242 | elif [[ $releaseVersion =~ ^7.* ]]; then
243 | majorVersion='7';
244 | fi;
245 | ;;
246 |
247 | esac
248 |
249 | if [[ -z "${platform}" ]] || [[ -z "${majorVersion}" ]]; then
250 | echo Unsupported platform is detected
251 | logger -t Unsupported platform is detected
252 | false
253 | else
254 | archType='/32'; architecture=$(arch);
255 | if [[ ${architecture} == *"x86_64"* ]]; then
256 | archType='/64';
257 | fi
258 |
259 | linuxPlatform=$platform$majorVersion$archType;
260 | fi
261 | }
262 |
263 | ###End PlatformDetection
264 |
265 | main "$@"
--------------------------------------------------------------------------------
/deepsecurity/manager-apis/bash/config-dsRelay.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | ## usage:
3 | ## ds-cfg-relay
4 | if [[ $1 == *"help"* ]]
5 | then
6 | echo -e "## usage:\n## ds-cfg-relay \n"
7 | echo -e "## example to enable relay on an agent:\n"
8 | echo -e "## ds-cfg-relay dsm.example.local:443 administrator relay.example.local true"
9 | echo -e "## example to show relay status for an agent in DSaaS\n"
10 | echo -e "## ds-cfg-relay app.deepsecurity.trendmicro.com:443 administrator relay.customer.local status CustomerTenant\n"
11 | exit 0
12 | fi
13 | command -v xml_grep >/dev/null 2>&1 || { echo >&2 "This script requires xml_grep. Please install perl-XML-Twig before proceeding."; exit 1; }
14 |
15 | manager=$1
16 | SID=
17 |
18 | read -sr -p $'Password: ' password
19 |
20 | if [[ -z $5 ]]
21 | then
22 | SID=`curl -ks -H "Content-Type: application/json" -X POST "https://${manager}/rest/authentication/login/primary" -d '{"dsCredentials":{"userName":"'${2}'","password":"'$password'"}}'`
23 | else
24 | SID=`curl -ks -H "Content-Type: application/json" -X POST "https://${manager}/rest/authentication/login" -d '{"dsCredentials":{"userName":"'${2}'","password":"'${password}'","tenantName":"'${5}'"}}'`
25 | fi
26 | unset Password
27 |
28 | ## get hostid
29 | hostId=$(curl -ks -H "Content-Type: text/xml;charset=UTF-8" -H 'SOAPAction: "hostRetrieveByName"' "https://${manager}/webservice/Manager" -d ''$3''$SID'' | xml_grep ID --text_only)
30 |
31 | echo -e "\n\nhostId is ${hostId}\n\n"
32 |
33 | case $4 in
34 | true)
35 | ## turn on relay
36 | curl -ks -H "Content-Type: text/xml;charset=UTF-8" -H 'SOAPAction: "hostSettingSet"' "https://${manager}/webservice/Manager" -d \
37 | ''\
38 | ''\
39 | ''\
40 | ''\
41 | ''$hostId''\
42 | ''\
43 | 'CONFIGURATION_RELAYSTATE'\
44 | 'NONE'\
45 | 'true'\
46 | ''\
47 | ''$SID''\
48 | ''\
49 | ''\
50 | ''
51 | ;;
52 | false)
53 | ## turn off relay
54 | curl -ks -H "Content-Type: text/xml;charset=UTF-8" -H 'SOAPAction: "hostSettingSet"' "https://${manager}/webservice/Manager" -d \
55 | ''\
56 | ''\
57 | ''\
58 | ''\
59 | ''$hostId''\
60 | ''\
61 | 'CONFIGURATION_RELAYSTATE'\
62 | 'NONE'\
63 | 'false'\
64 | ''\
65 | ''$SID''\
66 | ''\
67 | ''\
68 | ''
69 | ;;
70 | status)
71 | ## get relay setting value
72 | status=$(curl -ks -H "Content-Type: text/xml;charset=UTF-8" -H 'SOAPAction: "hostSettingGet"' "https://${manager}/webservice/Manager" -d \
73 | ''\
74 | ''\
75 | ''\
76 | ''\
77 | ''$hostId''\
78 | 'CONFIGURATION_RELAYSTATE'\
79 | ''$SID''\
80 | ''\
81 | ''\
82 | '' | xml_grep settingValue --text_only)
83 | echo "Relay setting is now set to ${status}. If you've just modified the setting, it may not be reflected in status until next agent heartbeat."
84 |
85 | esac
86 |
87 |
88 | unset SID
89 |
--------------------------------------------------------------------------------
/deepsecurity/manager-apis/bash/config-rehomeAwsDsManager.sh:
--------------------------------------------------------------------------------
1 | ##reactivate-manager
2 | dnsHostNamesOn=
3 | ## get a token
4 | SID=`curl -k -H "Content-Type: application/json" -X POST "https://localhost:$3/rest/authentication/login/primary" -d '{"dsCredentials":{"userName":"'$1'","password":"'$2'"}}'`
5 |
6 | ## get public hostname from metadata
7 | public_hostname=$(curl -s http://169.254.169.254/latest/meta-data/public-hostname)
8 | echo -e "public hostname returned from meta-data endpoint was \"$public_hostname\"\n" > mgract.log
9 |
10 | if [ -z $public_hostname ]
11 | then
12 | dnsHostnamesOn=false
13 | echo -e "dnsHostnamesOn=false\n" >> mgract.log
14 | else
15 | dnsHostnamesOn=true
16 | echo -e "dnsHostnamesOn=true\n" >> mgract.log
17 | fi
18 |
19 | ## delete host object matching local-hostname metadata
20 | curl -k -H "Content-Type: text/xml;charset=UTF-8" -H 'SOAPAction: "hostdelete"' "https://localhost:$3/webservice/Manager" -d ''$(curl -ks -H "Content-Type: text/xml;charset=UTF-8" -H 'SOAPAction: "hostRetrieveByName"' "https://localhost:$3/webservice/Manager" -d ''$(curl http://169.254.169.254/latest/meta-data/local-hostname)''$SID'' | xml_grep ID --text_only)''$SID''>>mgract.log
21 | echo -e "\n" >> mgract.log
22 | ## delete host object matching local hostname from hostname command just to be thorough
23 | curl -k -H "Content-Type: text/xml;charset=UTF-8" -H 'SOAPAction: "hostdelete"' "https://localhost:$3/webservice/Manager" -d ''$(curl -ks -H "Content-Type: text/xml;charset=UTF-8" -H 'SOAPAction: "hostRetrieveByName"' "https://localhost:$3/webservice/Manager" -d ''${hostname}''$SID'' | xml_grep ID --text_only)''$SID''>>mgract.log
24 | echo -e "\n" >> mgract.log
25 | ## delete host object matching local hostname from hostname command just to be thorough
26 | curl -k -H "Content-Type: text/xml;charset=UTF-8" -H 'SOAPAction: "hostdelete"' "https://localhost:$3/webservice/Manager" -d ''$(curl -ks -H "Content-Type: text/xml;charset=UTF-8" -H 'SOAPAction: "hostRetrieveByName"' "https://localhost:$3/webservice/Manager" -d ''$(curl http://169.254.169.254/latest/meta-data/local-ipv4)''$SID'' | xml_grep ID --text_only)''$SID''>>mgract.log
27 | echo -e "\n" >> mgract.log
28 | ## get Deep Security Manager policyId
29 | policyid=$(curl -ks -H "Content-Type: text/xml;charset=UTF-8" -H 'SOAPAction: "securityProfileRetrieveByName"' "https://localhost:$3/webservice/Manager" -d 'Deep Security Manager'$SID'' | xml_grep ID --text_only)
30 |
31 | echo -e "policyid for Deep Security Manager Policy is $policyid\n" >> mgract.log
32 |
33 | ## If the Manager node is launched into a VPC with dns names turned off, we'll need to use AIA to get the Manager nodes activated
34 | case $dnsHostnamesOn in
35 | false)
36 | echo -e "public hostname returned from meta-data endpoint was zero length; using AIA\n" >> mgract.log
37 |
38 | ## Set Communication Direction to Agent Initated on Deep Security Manager Policy
39 | curl -ks -H "Content-Type: text/xml;charset=UTF-8" -H 'SOAPAction: "securityProfileSettingGet"' "https://localhost:$3/webservice/Manager" -d \
40 | ''\
41 | ''\
42 | ''\
43 | ''\
44 | ''${policyid}''\
45 | ''\
46 | 'CONFIGURATION_AGENTCOMMUNICATIONS'\
47 | 'NONE'\
48 | '1'\
49 | ''\
50 | ''${SID}''\
51 | ''\
52 | ''\
53 | ''
54 |
55 | ## AIA for manager node
56 | /opt/ds_agent/dsa_control -r
57 | /opt/ds_agent/dsa_control -a dsm://localhost:4120/ "policyid:${policyid}"
58 | ## get hostid for this manager
59 | publicip_hostId=$(curl -ks -H "Content-Type: text/xml;charset=UTF-8" -H 'SOAPAction: "hostRetrieveByName"' "https://localhost:$3/webservice/Manager" -d ''$(curl http://169.254.169.254/latest/meta-data/public-ipv4)''$SID'' | xml_grep ID --text_only)
60 | ## enable relay for this agent
61 | curl -k -v -H "Content-Type: text/xml;charset=UTF-8" -H 'SOAPAction: "hostSettingSet"' "https://localhost:$3/webservice/Manager" -d \
62 | ''\
63 | ''\
64 | ''\
65 | ''\
66 | ''$publicip_hostId''\
67 | ''\
68 | 'CONFIGURATION_RELAYSTATE'\
69 | 'NONE'\
70 | 'true'\
71 | ''\
72 | ''${SID}''\
73 | ''\
74 | ''\
75 | ''
76 |
77 | ;;
78 | true)
79 | echo -e "public hostname returned from meta-data endpoint was non-zero length; using MIA\n" >> mgract.log
80 | ## get hostId of object matcihng public-hostname metadata
81 | public_hostId=$(curl -ks -H "Content-Type: text/xml;charset=UTF-8" -H 'SOAPAction: "hostRetrieveByName"' "https://localhost:$3/webservice/Manager" -d ''$public_hostname''$SID'' | xml_grep ID --text_only)
82 | echo -e "public host Id returned from manager was $public_hostId\n" >> mgract.log
83 | ## activate that hostId
84 | curl -k -H "Content-Type: text/xml;charset=UTF-8" -H 'SOAPAction: "hostAgentActivate"' "https://localhost:$3/webservice/Manager" -d ''$public_hostId''$SID''>>mgract.log
85 | echo -e "\n" >> mgract.log
86 | ## assign Deep Security Manager Policy to that hostId
87 | curl -k -H "Content-Type: text/xml;charset=UTF-8" -H 'SOAPAction: "securityProfileAssignToHost"' "https://localhost:$3/webservice/Manager" -d ''$policyid''$public_hostId''$SID''>>mgract.log
88 | esac
89 |
90 | ## log out
91 | curl -k -X DELETE https://localhost:$3/rest/authentication/logout?sID="$SID"
92 | exit 0
93 |
--------------------------------------------------------------------------------
/deepsecurity/manager-apis/bash/create-iamCloudAccount.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | # createcloudaccount dsmuser dsmFQDNorIP connectorName newAwsUserToCreate (TenantID if needed)
3 | if [[ $1 == *"help"* ]]
4 | then
5 | echo -e "## usage:\n## create-iam-cloudaccount Amazon \n"
6 | echo -e "## example to create User and Cloud account on a DeepSecurity Manager:\n"
7 | echo -e "## create-iam-cloudaccount administrator dsm.example.local:443 Amazon DsmSyncUser"
8 | echo -e "## example to create User and Cloud account in DSaaS\n"
9 | echo -e "## create-iam-cloudaccount administrator app.deepsecurity.trendmicro.com:443 DsmSyncUser CustomerTenant\n"
10 | exit 0
11 | fi
12 |
13 | command -v aws >/dev/null 2>&1 || { echo >&2 "This script requires AWS CLI. Please install AWS CLI before proceeding."; exit 1; }
14 |
15 |
16 | if [ ! -f ~/.aws/credentials ]
17 | then
18 | echo “please run aws configure before using this script”
19 | exit 2
20 | fi
21 |
22 | username=$1
23 | DSMFQDN=$2
24 | AWSKEYS=
25 | tempDSSID=
26 |
27 | read -sr -p $'Password: ' password
28 |
29 | echo " "
30 |
31 |
32 | # Remove regions you don't want from this list
33 | REGIONS=(useast1 uswest1 uswest2 euwest1 apsoutheast1 apsoutheast2 apnortheast1 saeast1 eucentral1)
34 |
35 | # map aws regions to dsm region keys
36 | useast1=amazon.cloud.region.key.1
37 | uswest2=amazon.cloud.region.key.2
38 | uswest1=amazon.cloud.region.key.3
39 | euwest1=amazon.cloud.region.key.4
40 | apsoutheast1=amazon.cloud.region.key.5
41 | apnortheast1=amazon.cloud.region.key.6
42 | saeast1=amazon.cloud.region.key.7
43 | apsoutheast2=amazon.cloud.region.key.8
44 | eucentral1=amazon.cloud.region.key.9
45 | #apnortheast2=amazon.cloud.region.key.12
46 |
47 | # map aws regions to ec2 endpoints
48 | useast1ep=ec2.us-east-1.amazonaws.com
49 | uswest2ep=ec2.us-west-2.amazonaws.com
50 | uswest1ep=ec2.us-west-1.amazonaws.com
51 | euwest1ep=ec2.eu-west-1.amazonaws.com
52 | apsoutheast1ep=ec2.ap-southeast-1.amazonaws.com
53 | apnortheast1ep=ec2.ap-northeast-1.amazonaws.com
54 | saeast1ep=ec2.sa-east-1.amazonaws.com
55 | apsoutheast2ep=ec2.ap-southeast-2.amazonaws.com
56 | eucentral1ep=ec2.eu-central-1.amazonaws.com
57 | #apnortheast2ep=ec2.ap-northeast-2.amazonaws.com
58 |
59 |
60 | echo "#####Creating user"
61 | aws iam create-user --user-name $4
62 |
63 | echo "#####Putting user policy"
64 | aws iam put-user-policy --user-name $4 --policy-name DSMUserRole --policy-document '{"Statement" : [{"Effect" : "Allow","Action" : ["ec2:DescribeInstances","ec2:DescribeImages","ec2:DescribeTags"],"Resource" : "*"}]}'
65 | echo "#####Creating accesskeys"
66 | AWSKEYS=($(aws iam create-access-key --user-name $4 --query 'AccessKey.[AccessKeyId,SecretAccessKey]' --output text))
67 |
68 | echo "#####Login to DSM"
69 | #tempDSSID=$(curl -ks -H "Content-Type: application/json" -X POST "https://$DSMFQDN/rest/authentication/login/primary" -d "{"dsCredentials":{"userName":"$username","password":"$password"}}")
70 |
71 | if [[ -z $5 ]]
72 | then
73 | tempDSSID=`curl -ks -H "Content-Type: application/json" -X POST "https://${DSMFQDN}/rest/authentication/login/primary" -d '{"dsCredentials":{"userName":"'${1}'","password":"'${password}'"}}'`
74 | else
75 | tempDSSID=`curl -ks -H "Content-Type: application/json" -X POST "https://${DSMFQDN}/rest/authentication/login" -d '{"dsCredentials":{"userName":"'${1}'","password":"'${password}'","tenantName":"'${5}'"}}'`
76 | fi
77 |
78 |
79 |
80 | echo "#####Looping through regions to create connectors"
81 | for region in "${REGIONS[@]}"
82 | do
83 | echo "##### creating connector for $region region"
84 | curl -ks -H "Content-Type: application/json" "Accept: application/json" -X POST "https://$DSMFQDN/rest/cloudaccounts" -d '{"createCloudAccountRequest":{"cloudAccountElement":{"accessKey":"'${AWSKEYS[0]}'","cloudRegion":"'${!region}'","cloudType":"AMAZON","name":"'$3$region'","secretKey":"'${AWSKEYS[1]}'","endpoint":"'${!endpoint}'","azureCertificate":"-"},"sessionId":"'$tempDSSID'"}}'
85 | done
86 |
87 | curl -k -X DELETE https://$DSMFQDN/rest/authentication/logout?sID=$tempDSSID
88 |
89 | unset AWSKEYS
90 | unset tempDSSID
91 | unset username
92 | unset password
93 |
94 |
95 |
--------------------------------------------------------------------------------
/deepsecurity/manager-apis/bash/ds10-rest-cloudAccountCreateWithCrossAccountRole.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | # cloudAccountCreateWithCrossAccountRole.sh dsmuser dsmpass managerAddress guiPort roleArn externalId tenant
3 | username=$1
4 | password=$2
5 | DSMURL="$3:$4"
6 | arn="$5"
7 | externalId="$6"
8 | tenant=$7
9 |
10 |
11 |
12 |
13 | echo "#####Login to DSM"
14 | if [[ -z $tenant ]]
15 | then
16 | SID=`curl -ks -H "Content-Type: application/json" -X POST "https://${DSMURL}/rest/authentication/login/primary" -d '{"dsCredentials":{"userName":"'${username}'","password":"'${password}'"}}'`
17 | else
18 | SID=`curl -ks -H "Content-Type: application/json" -X POST "https://${DSMURL}/rest/authentication/login" -d '{"dsCredentials":{"userName":"'${username}'","password":"'${password}'","tenantName":"'${tenant}'"}}'`
19 | fi
20 |
21 | curl -ks --cookie "sID=${SID}" -H "Content-Type: application/json" "Accept: application/json" -X POST "https://${DSMURL}/rest/cloudaccounts/aws" -d '{"AddAwsAccountRequest":{"crossAccountRole":{"roleArn":"'${arn}'","externalId":"'${externalId}'"}}}'
22 |
23 | curl -k -X DELETE https://$DSMURL/rest/authentication/logout?sID=${SID}
24 |
25 | unset SID
26 | unset username
27 | unset password
28 |
29 |
30 |
--------------------------------------------------------------------------------
/deepsecurity/manager-apis/bash/ds10-rest-cloudAccountCreateWithInstanceRole.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | # cloudAccountCreateWithInstanceRole.sh dsmuser dsmpass manager address guiPort tenant
3 | username=$1
4 | password=$2
5 | tenant=$5
6 |
7 | # replace this with your DSM IP or FQDN
8 | DSMURL="$3:$4"
9 |
10 |
11 | echo "#####Login to DSM"
12 | if [[ -z $tenant ]]
13 | then
14 | SID=`curl -ks -H "Content-Type: application/json" -X POST "https://${DSMURL}/rest/authentication/login/primary" -d '{"dsCredentials":{"userName":"'${username}'","password":"'${password}'"}}'`
15 | else
16 | SID=`curl -ks -H "Content-Type: application/json" -X POST "https://${DSMURL}/rest/authentication/login" -d '{"dsCredentials":{"userName":"'${username}'","password":"'${password}'","tenantName":"'${tenant}'"}}'`
17 | fi
18 |
19 | curl -ks --cookie "sID=${SID}" -H "Content-Type: application/json" "Accept: application/json" -X POST "https://${DSMURL}/rest/cloudaccounts/aws" -d '{"AddAwsAccountRequest":{"useInstanceRole":true}}'
20 |
21 | curl -k -X DELETE https://$DSMURL/rest/authentication/logout?sID=$tempDSSID
22 |
23 | unset SID
24 | unset username
25 | unset password
26 |
27 |
28 |
--------------------------------------------------------------------------------
/deepsecurity/manager-apis/bash/ds10-rest-cloudAccountCreateWithKeys.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | # cloudAccountCreateWithInstanceRole.sh dsmuser dsmpass manager address guiPort tenant
3 | username=$1
4 | password=$2
5 | tenant=$5
6 | accesskey=$6
7 | secretkey=$7
8 |
9 | # replace this with your DSM IP or FQDN
10 | DSMURL="$3:$4"
11 |
12 |
13 |
14 | echo "#####Login to DSM"
15 | if [[ -z $tenant ]]
16 | then
17 | SID=`curl -ks -H "Content-Type: application/json" -X POST "https://${DSMURL}/rest/authentication/login/primary" -d '{"dsCredentials":{"userName":"'${username}'","password":"'${password}'"}}'`
18 | else
19 | SID=`curl -ks -H "Content-Type: application/json" -X POST "https://${DSMURL}/rest/authentication/login" -d '{"dsCredentials":{"userName":"'${username}'","password":"'${password}'","tenantName":"'${tenant}'"}}'`
20 | fi
21 |
22 | curl -ks --cookie "sID=${SID}" -H "Content-Type: application/json" "Accept: application/json" -X POST "https://${DSMURL}/rest/cloudaccounts/aws" -d '{"AddAwsAccountRequest":{"awsCredentials":{"accessKeyId":"'${accesskey}'","secretKey":"'${secretkey}'"}}}'
23 |
24 | curl -k -X DELETE https://$DSMURL/rest/authentication/logout?sID=$tempDSSID
25 |
26 | unset SID
27 | unset username
28 | unset password
29 |
30 |
31 |
--------------------------------------------------------------------------------
/deepsecurity/manager-apis/bash/ds10-rest-cloudAccountCreateWithKeysSpecialRegion.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | # cloudAccountCreateWithKeysSpecialRegion.sh dsmuser dsmpass manager_address guiPort awsAccessKey awsSecretKey seedRegion tenant
3 | username=$1
4 | password=$2
5 | tenant=$8
6 | accesskey=$5
7 | secretkey=$6
8 | seedregion=$7
9 |
10 | # replace this with your DSM IP or FQDN
11 | DSMURL="$3:$4"
12 |
13 |
14 |
15 | echo "#####Login to DSM"
16 | if [[ -z $tenant ]]
17 | then
18 | SID=`curl -ks -H "Content-Type: application/json" -X POST "https://${DSMURL}/rest/authentication/login/primary" -d '{"dsCredentials":{"userName":"'${username}'","password":"'${password}'"}}'`
19 | else
20 | SID=`curl -ks -H "Content-Type: application/json" -X POST "https://${DSMURL}/rest/authentication/login" -d '{"dsCredentials":{"userName":"'${username}'","password":"'${password}'","tenantName":"'${tenant}'"}}'`
21 | fi
22 |
23 | echo "#####Create connector"
24 | curl -ks --cookie "sID=${SID}" -H "Content-Type: application/json" "Accept: application/json" -X POST "https://${DSMURL}/rest/cloudaccounts/aws" -d '{"AddAwsAccountRequest":{"awsCredentials":{"accessKeyId":"'${accesskey}'","secretKey":"'${secretkey}'"},"seedRegion":"'${seedregion}'"}}'
25 |
26 | echo -e "\n#####Log out"
27 | curl -k -X DELETE https://$DSMURL/rest/authentication/logout?sID=${SID}
28 |
29 | unset SID
30 | unset username
31 | unset password
32 |
33 |
34 |
--------------------------------------------------------------------------------
/deepsecurity/manager-apis/bash/ds10-rest-cloudAccountsGet.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | # cloudAccountGet.sh dsmuser dsmpass manager address guiPort tenant
3 | username=$1
4 | password=$2
5 | tenant=$5
6 |
7 | # replace this with your DSM IP or FQDN
8 | DSMURL="$3:$4"
9 |
10 |
11 | echo "#####Login to DSM"
12 | if [[ -z $tenant ]]
13 | then
14 | SID=`curl -ks -H "Content-Type: application/json" -X POST "https://${DSMURL}/rest/authentication/login/primary" -d '{"dsCredentials":{"userName":"'${username}'","password":"'${password}'"}}'`
15 | else
16 | SID=`curl -ks -H "Content-Type: application/json" -X POST "https://${DSMURL}/rest/authentication/login" -d '{"dsCredentials":{"userName":"'${username}'","password":"'${password}'","tenantName":"'${tenant}'"}}'`
17 | fi
18 |
19 |
20 |
21 | curl -ks --cookie "sID=${SID}" -H "Content-Type: application/json" "Accept: application/json" -X Get "https://${DSMURL}/rest/cloudaccounts"
22 |
23 | curl -k -X DELETE https://$DSMURL/rest/authentication/logout?sID=$tempDSSID
24 |
25 | unset accesskey
26 | unset secretkey
27 | unset tempDSSID
28 | unset username
29 | unset password
30 |
31 |
32 |
--------------------------------------------------------------------------------
/deepsecurity/manager-apis/bash/rest-cloudAccountsCreateAws.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | # createcloudaccount dsmuser dsmpass connectorName guiPort accesskey secretkey
3 | username=$1
4 | password=$2
5 | accesskey=$5
6 | secretkey=$6
7 |
8 | # replace this with your DSM IP or FQDN
9 | DSMURL="localhost:$4"
10 |
11 | # Remove regions you don't want from this list
12 | REGIONS=(useast1 uswest1 uswest2 euwest1 apsoutheast1 apsoutheast2 apnortheast1 saeast1 eucentral1 apnortheast2)
13 |
14 | # map aws regions to dsm region keys
15 | useast1=amazon.cloud.region.key.1
16 | uswest2=amazon.cloud.region.key.2
17 | uswest1=amazon.cloud.region.key.3
18 | euwest1=amazon.cloud.region.key.4
19 | apsoutheast1=amazon.cloud.region.key.5
20 | apnortheast1=amazon.cloud.region.key.6
21 | saeast1=amazon.cloud.region.key.7
22 | apsoutheast2=amazon.cloud.region.key.8
23 | eucentral1=amazon.cloud.region.key.9
24 | apnortheast2=amazon.cloud.region.key.12
25 |
26 | # map aws regions to ec2 endpoints
27 | useast1ep=ec2.us-east-1.amazonaws.com
28 | uswest2ep=ec2.us-west-2.amazonaws.com
29 | uswest1ep=ec2.us-west-1.amazonaws.com
30 | euwest1ep=ec2.eu-west-1.amazonaws.com
31 | apsoutheast1ep=ec2.ap-southeast-1.amazonaws.com
32 | apnortheast1ep=ec2.ap-northeast-1.amazonaws.com
33 | saeast1ep=ec2.sa-east-1.amazonaws.com
34 | apsoutheast2ep=ec2.ap-southeast-2.amazonaws.com
35 | eucentral1ep=ec2.eu-central-1.amazonaws.com
36 | apnortheast2ep=ec2.ap-northeast-2.amazonaws.com
37 |
38 |
39 | echo "#####Login to DSM"
40 | tempDSSID=$(curl -k -H "Content-Type: application/json" -X POST "https://$DSMURL/rest/authentication/login/primary" -d "{"dsCredentials":{"userName":"$username","password":"$password"}}")
41 |
42 | echo "#####Looping through regions to create connectors"
43 | for region in "${REGIONS[@]}"
44 | do
45 | endpoint="${region}ep"
46 | echo "##### creating connector for $region region with endpoint ${!endpoint}"
47 | curl -ks -H "Content-Type: application/json" "Accept: application/json" -X POST "https://$DSMURL/rest/cloudaccounts" -d '{"createCloudAccountRequest":{"cloudAccountElement":{"accessKey":"'${accesskey}'","cloudRegion":"'${!region}'","cloudType":"AMAZON","name":"'$3'","secretKey":"'${secretkey}'","endpoint":"'${!endpoint}'","azureCertificate":"-"},"sessionId":"'$tempDSSID'"}}'
48 | done
49 |
50 | curl -k -X DELETE https://$DSMURL/rest/authentication/logout?sID=$tempDSSID
51 |
52 | unset accesskey
53 | unset secretkey
54 | unset tempDSSID
55 | unset username
56 | unset password
57 |
58 |
59 |
--------------------------------------------------------------------------------
/deepsecurity/manager-apis/bash/rest-cloudAccountsCreateAwsGovCloud.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | # createcloudaccount dsmuser dsmpass connectorName guiPort accesskey secretkey
3 | username=$1
4 | password=$2
5 | accesskey=$5
6 | secretkey=$6
7 |
8 | # replace this with your DSM IP or FQDN
9 | DSMURL="localhost:$4"
10 |
11 | echo "#####Login to DSM"
12 | tempDSSID=$(curl -k -H "Content-Type: application/json" -X POST "https://$DSMURL/rest/authentication/login/primary" -d "{"dsCredentials":{"userName":"$username","password":"$password"}}")
13 |
14 | curl -ks -H "Content-Type: application/json" "Accept: application/json" -X POST "https://$DSMURL/rest/cloudaccounts" -d '{"createCloudAccountRequest":{"cloudAccountElement":{"accessKey":"'${accesskey}'","cloudRegion":"'amazon.cloud.region.key.10'","cloudType":"AMAZON","name":"'$3'","secretKey":"'${secretkey}'","endpoint":"'ec2.us-gov-west-1.amazonaws.com'","azureCertificate":"-"},"sessionId":"'$tempDSSID'"}}'
15 |
16 | curl -k -X DELETE https://$DSMURL/rest/authentication/logout?sID=$tempDSSID
17 |
18 | unset accesskey
19 | unset secretkey
20 | unset tempDSSID
21 | unset username
22 | unset password
23 |
24 |
--------------------------------------------------------------------------------
/deepsecurity/manager-apis/bash/rest-cloudAccountsGet.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | # cloudAccountGet.sh dsmuser dsmpass manager address guiPort tenant
3 | username=$1
4 | password=$2
5 | tenant=$5
6 |
7 | # replace this with your DSM IP or FQDN
8 | DSMURL="$3:$4"
9 |
10 |
11 | echo "#####Login to DSM"
12 | if [[ -z $tenant ]]
13 | then
14 | SID=`curl -ks -H "Content-Type: application/json" -X POST "https://${DSMURL}/rest/authentication/login/primary" -d '{"dsCredentials":{"userName":"'${username}'","password":"'${password}'"}}'`
15 | else
16 | SID=`curl -ks -H "Content-Type: application/json" -X POST "https://${DSMURL}/rest/authentication/login" -d '{"dsCredentials":{"userName":"'${username}'","password":"'${password}'","tenantName":"'${tenant}'"}}'`
17 | fi
18 |
19 |
20 |
21 | curl -ks -H "Content-Type: application/json" "Accept: application/json" -X Get "https://${DSMURL}/rest/cloudaccounts?sID=$SID"
22 |
23 | curl -k -X DELETE https://$DSMURL/rest/authentication/logout?sID=$tempDSSID
24 |
25 | unset accesskey
26 | unset secretkey
27 | unset tempDSSID
28 | unset username
29 | unset password
30 |
31 |
32 |
--------------------------------------------------------------------------------
/deepsecurity/manager-apis/bash/rest-tenantsCreate.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | ## createTenant
3 |
4 | username=$1
5 | password=$2
6 | dsmurl="$3:$4"
7 | tenantName=$5
8 | tenantAdminPassword="$6"
9 |
10 | #echo "#####Login to DSM at ${dsmurl}"
11 | tempDSSID=$(curl -ks -H "Content-Type: application/json" -X POST "https://${dsmurl}/rest/authentication/login/primary" -d "{"dsCredentials":{"userName":"$username","password":"$password"}}")
12 |
13 | #echo "####Create tenant ${tenantName}"
14 | createTenantResponse=$(curl -ks -H "Content-Type: application/xml" -X POST "https://${dsmurl}/rest/tenants" -d \
15 | '
16 |
17 | MasterAdmin
18 | '${tenantAdminPassword}'
19 | MasterAdmin@ctf.labs.local
20 |
21 |
22 | '${tenantName}'
23 | en
24 | US
25 | US/Eastern"
26 |
27 | '${tempDSSID}'
28 | ')
29 |
30 | tenantId=$(echo $createTenantResponse | xml_grep --text_only tenantID)
31 |
32 | tenantElement=$(curl -ks -H "Content-Type: application/xml" -X GET "https://${dsmurl}/rest/tenants/id/${tenantId}?sID=${tempDSSID}")
33 |
34 |
35 | curl -k -X DELETE https://${dsmurl}/rest/authentication/logout?sID=$tempDSSID
36 |
37 | unset tempDSSID
38 | unset username
39 | unset password
40 |
41 | echo $tenantElement | xml_grep --text_only agentInitiatedActivationPassword
42 | echo $tenantElement | xml_grep --text_only guid
43 |
--------------------------------------------------------------------------------
/deepsecurity/manager-apis/powershell/config-dsrelay.ps1:
--------------------------------------------------------------------------------
1 | <#
2 |
3 | .SYNOPSIS
4 | PowerShell Script to enable, disable, or query status of a Deep Security Relay.
5 |
6 | .DESCRIPTION
7 | The config-dsrelay script can enable, disable, or query the status of a relay enabled agent activated against a Deep Security Manager. It requires the Web Services API to be enabled on Deep Security Manager.
8 |
9 | .PARAMETER relaystate
10 | To enable a relay, set -relaystate true.
11 | To disable a relay, set -relaystate false.
12 | To discover the status of a relay, set -relaystate status.
13 | If no value is supplied, status will be used.
14 |
15 | .PARAMETER hostname
16 | The -hostname parameter requires the DisplayName of a computer object in Deep Security Manager which has an activated Deep Security Agent. Hostnames are case sensitive and must appear as they do in Deep Security Manager console.
17 |
18 | .PARAMETER manager
19 | The -manager parameter requires a hostname or IP and port in the format hostname.local:4119 or 198.51.100.10:443.
20 |
21 | .PARAMETER user
22 | The -user parameter requires a Deep Security Manager Administrator with permission to use the SOAP API.
23 |
24 | .PARAMETER tenant
25 | The -tenant parameter is optional and can be used to specify a tenant (other than T0) for relay operations.
26 |
27 |
28 | .EXAMPLE
29 | config-dsrelay.ps1 -manager manager.domain.local:4119 -user admin -hostname relay.domain.local -relaystate status
30 | This example gets the status of enabled relay for a host with DisplayName relay.domain.local.
31 |
32 | config-dsrelay.ps1 -manager manager.domain.com:443 -user tenantAdmin -hostname 198.51.100.100 -relaystate true -tenant CustomerTenant
33 | This example enables the relay on an agent with DisplayName 198.51.100.100 in tenant named CustomerTenant.
34 |
35 | .LINK
36 | http://aws.trendmicro.com
37 |
38 | #>
39 |
40 |
41 | param (
42 | [Parameter(Mandatory=$true)][string]$manager,
43 | [Parameter(Mandatory=$true)][string]$user,
44 | [Parameter(Mandatory=$true)][string]$hostname,
45 | [ValidateSet("true","false","status")][string]$relaystate = "status",
46 | [Parameter(Mandatory=$false)][string]$tenant
47 | )
48 | $passwordinput = Read-host "Password for Deep Security Manager" -AsSecureString
49 | $password = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($passwordinput))
50 |
51 |
52 | [System.Net.ServicePointManager]::ServerCertificateValidationCallback={$true}
53 | [Net.ServicePointManager]::SecurityProtocol += [Net.SecurityProtocolType]::Tls12
54 | $DSMSoapService = New-WebServiceProxy -uri "https://$manager/webservice/Manager?WSDL" -Namespace "DSSOAP" -ErrorAction Stop
55 | $DSM = New-Object DSSOAP.ManagerService
56 | $SID
57 | try {
58 | if (!$tenant) {
59 | $SID = $DSM.authenticate($user, $password)
60 | }
61 | else {
62 | $SID = $DSM.authenticateTenant($tenant, $user, $password)
63 | }
64 | }
65 | catch {
66 | echo "An error occurred during authentication. Verify username and password and try again. `nError returned was: $($_.Exception.Message)"
67 | exit
68 | }
69 |
70 | $HT = $DSM.hostRetrieveByName($hostname,$SID)
71 | try {
72 | if ($relaystate -eq "status") {
73 | [DSSOAP.EnumEditableSettingKey[]] $settingskeyarray = @([DSSOAP.EnumEditableSettingKey]::CONFIGURATION_RELAYSTATE)
74 | $ESSTreturn = $DSM.hostSettingGet($HT.ID, $settingskeyarray, $SID)
75 | echo $ESSTreturn[0].settingValue
76 | }
77 | else {
78 | $EST = New-Object DSSOAP.EditableSettingTransport
79 | $EST.settingUnit = [DSSOAP.EnumEditableSettingUnit]::NONE
80 | $EST.settingValue = $relaystate
81 | $EST.settingKey = @([DSSOAP.EnumEditableSettingKey]::CONFIGURATION_RELAYSTATE)
82 | [DSSOAP.EditableSettingTransport[]] $ESTArray = @($EST)
83 | $DSM.hostSettingSet($HT.ID, $ESTArray, $SID)
84 | }
85 | }
86 | catch {
87 | echo "Hostname $($hostname) was not found. Note that hostnames are case sensitive. `nError returned from DSM was: $($_.Exception.Message)"
88 | }
89 | $DSMSoapService.endSession($SID)
90 |
91 |
--------------------------------------------------------------------------------
/deepsecurity/manager-apis/powershell/config-ipsXforwardedForRule.ps1:
--------------------------------------------------------------------------------
1 | <#
2 |
3 | .SYNOPSIS
4 | PowerShell Script to create and manage a Deep Security IPS rule which can block source IP addresses from behind an ELB based on x-forwarded-for header value.
5 |
6 | .DESCRIPTION
7 | The set-xForwardedFor script creates or updates an IPS rule in Deep Security Manager which can block addresses based on the X-Forwarded-For header provided by an AWS Elastic Load Balancer.
8 | The Username and Password supplied will be used to authenticate to the Deep Security Manager.
9 | IPs for the block list must be placed in a directory with this script in a file called ips.txt. IPs must be added to the file one address per line.
10 | This script requires the Web Services API to be enabled on Deep Security Manager.
11 |
12 | .PARAMETER manager
13 | The -manager parameter requires a hostname or IP and port in the format hostname.local:4119 or 198.51.100.10:443.
14 |
15 | .PARAMETER user
16 | The -user parameter requires a Deep Security Manager Administrator with permission to use the SOAP API.
17 |
18 | .PARAMETER tenant
19 | The -tenant parameter is optional and can be used to specify a tenant (other than T0).
20 |
21 | .EXAMPLE
22 | set-xForwardedFor.ps1 -manager manager.domain.com:443 -user MasterAdmin
23 | This example logs into tenant 0 on the Deep Security Manager.
24 |
25 | set-xForwardedFor.ps1 -manager manager.domain.com:443 -user tenantAdmin -tenant CustomerTenant
26 | This example logs into tenant named Customer Tenant on the Deep Security Manager.
27 |
28 | .LINK
29 | http://aws.trendmicro.com
30 |
31 | #>
32 |
33 | param (
34 | [Parameter(Mandatory=$true)][string]$manager,
35 | [Parameter(Mandatory=$true)][string]$user,
36 | [Parameter(Mandatory=$false)][string]$tenant
37 | )
38 |
39 | ## To use this script completely automated without user input, uncomment these lines and set appropraite values
40 | #$manager=""
41 | #$user=""
42 | #$password=""
43 |
44 | ## To use this script completely automated without user input, comment out these lines
45 | $passwordinput = Read-host "Password for Deep Security Manager" -AsSecureString
46 | $password = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($passwordinput))
47 |
48 |
49 | [System.Net.ServicePointManager]::ServerCertificateValidationCallback={$true}
50 | [Net.ServicePointManager]::SecurityProtocol += [Net.SecurityProtocolType]::Tls12
51 | $DSMSoapService = New-WebServiceProxy -uri "https://$manager/webservice/Manager?WSDL" -Namespace "DSSOAP" -ErrorAction Stop
52 | $DSM = New-Object DSSOAP.ManagerService
53 | $SID
54 |
55 | try {
56 | if (!$tenant) {
57 | $SID = $DSM.authenticate($user, $password)
58 | }
59 | else {
60 | $SID = $DSM.authenticateTenant($tenant, $user, $password)
61 | }
62 | }
63 | catch {
64 | echo "An error occurred during authentication. Verify username and password and try again. `nError returned was: $($_.Exception.Message)"
65 | exit
66 | }
67 | $ruleXML = ""
68 |
69 | Get-Content .\ips.txt | Foreach-Object{$ruleXML += "`
70 | drop `"Found IP from Block List in XFF Header`"`
71 | `
72 | "}
73 | $xfor = $DSM.DPIRuleRetrieveByName("Block-X-Forward-List", $SID)
74 | if ($xfor.ID -eq $null)
75 | {
76 | echo "Rule did not exist; creating new"
77 | $xfor = New-Object DSSOAP.DPIRuleTransport
78 | $xfor.name = "Block-X-Forward-List"
79 | $xfor.applicationTypeID = $DSM.applicationTypeRetrieveByName("Web Server Common", $SID).ID
80 | $xfor.eventOnPacketDrop = $true
81 | $xfor.eventOnPacketModify = $true
82 | $xfor.templateType = [DSSOAP.EnumDPIRuleTemplateType]::CUSTOM_XML
83 | $xfor.patternAction = [DSSOAP.EnumDPIRuleAction]::DROP_CLOSE
84 | $xfor.patternIf = [DSSOAP.EnumDPIRuleIf]::ANY_PATTERNS_FOUND
85 | $xfor.priority = [DSSOAP.EnumDPIRulePriority]::NORMAL
86 | $xfor.signatureAction = [DSSOAP.EnumDPIRuleAction]::DROP_CLOSE
87 | $xfor.severity = [DSSOAP.EnumDPIRuleSeverity]::MEDIUM
88 | }
89 | $xfor.ruleXML = $ruleXML
90 | $DSM.DPIRuleSave($xfor, $SID)
91 | $DSM.endSession($SID)
92 |
--------------------------------------------------------------------------------
/deepsecurity/manager-apis/powershell/config-policy-agentcomm.ps1:
--------------------------------------------------------------------------------
1 | param (
2 | [Parameter(Mandatory=$true)][string]$manager,
3 | [Parameter(Mandatory=$true)][string]$user,
4 | [Parameter(Mandatory=$true)][string]$policyname,
5 | [Parameter(Mandatory=$true,HelpMessage="enter Inherit, AIA, MIA, or Bi to set comm direction; status to query")][ValidateSet("Inherit","AIA","MIA","Bi","status")][string]$commdirection = "status",
6 | [Parameter(Mandatory=$false)][string]$tenant
7 | )
8 | $passwordinput = Read-host "Password for Deep Security Manager" -AsSecureString
9 | $password = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($passwordinput))
10 |
11 | $cd = 0
12 |
13 | switch ($commdirection)
14 | {
15 | Inherit {$cd=0}
16 | AIA {$cd=1}
17 | MIA {$cd=2}
18 | Bi {$cd=3}
19 | }
20 |
21 |
22 | [System.Net.ServicePointManager]::ServerCertificateValidationCallback={$true}
23 | [Net.ServicePointManager]::SecurityProtocol += [Net.SecurityProtocolType]::Tls12
24 | $DSMSoapService = New-WebServiceProxy -uri "https://$manager/webservice/Manager?WSDL" -Namespace "DSSOAP" -ErrorAction Stop
25 | $DSM = New-Object DSSOAP.ManagerService
26 | $SID
27 | try {
28 | if (!$tenant) {
29 | $SID = $DSM.authenticate($user, $password)
30 | }
31 | else {
32 | $SID = $DSM.authenticateTenant($tenant, $user, $password)
33 | }
34 | }
35 | catch {
36 | echo "An error occurred during authentication. Verify username and password and try again. `nError returned was: $($_.Exception.Message)"
37 | exit
38 | }
39 |
40 | $spt = $DSM.securityProfileRetrieveByName($policyname, $SID)
41 | try {
42 | if ($commdirection -eq "status") {
43 | [DSSOAP.EnumEditableSettingKey[]] $settingskeyarray = @([DSSOAP.EnumEditableSettingKey]::CONFIGURATION_AGENTCOMMUNICATIONS)
44 | $ESSTreturn = $DSM.securityProfileSettingGet($spt.ID, $settingskeyarray, $SID)
45 | echo $ESSTreturn[0].settingValue
46 | }
47 | elseif ($cd -eq 0) {
48 | [DSSOAP.EnumEditableSettingKey[]] $settingskeyarray = @([DSSOAP.EnumEditableSettingKey]::CONFIGURATION_AGENTCOMMUNICATIONS)
49 | $DSM.securityProfileSettingClear($spt.ID, $settingskeyarray, $SID)
50 | }
51 | else {
52 | $EST = New-Object DSSOAP.EditableSettingTransport
53 | $EST.settingUnit = [DSSOAP.EnumEditableSettingUnit]::NONE
54 | $EST.settingValue = $cd
55 | $EST.settingKey = @([DSSOAP.EnumEditableSettingKey]::CONFIGURATION_AGENTCOMMUNICATIONS)
56 | [DSSOAP.EditableSettingTransport[]] $ESTArray = @($EST)
57 | $DSM.securityProfileSettingSet($spt.ID, $ESTArray, $SID)
58 | }
59 | }
60 | catch {
61 | echo "Exception occured.`nError returned from DSM was: $($_.Exception.Message)"
62 | }
63 | finally {
64 | $DSM.endSession($SID)
65 | }
66 | $DSM.endSession($SID)
67 |
--------------------------------------------------------------------------------
/deepsecurity/manager-apis/powershell/ds10-cloudAccountCreateWithKeysSpecialRegion.ps1:
--------------------------------------------------------------------------------
1 |
2 | param (
3 | [Parameter(Mandatory=$true)][string]$manager,
4 | [Parameter(Mandatory=$true)][string]$user,
5 | [Parameter(Mandatory=$true)][string]$awsAccessKey,
6 | [Parameter(Mandatory=$true)][string]$awsSecretKey,
7 | [Parameter(Mandatory=$true)][string]$seedRegion,
8 | [Parameter(Mandatory=$false)][string]$tenant
9 | )
10 |
11 | $passwordinput = Read-host "Password for Deep Security Manager" -AsSecureString
12 | $password = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($passwordinput))
13 |
14 |
15 | [System.Net.ServicePointManager]::ServerCertificateValidationCallback={$true}
16 | [Net.ServicePointManager]::SecurityProtocol += [Net.SecurityProtocolType]::Tls12
17 |
18 | $managerUri="https://$manager/"
19 |
20 |
21 | $headers=@{'Content-Type'='application/json'}
22 |
23 |
24 | try {
25 | $data = @{
26 | dsCredentials = @{
27 | password=$password
28 | userName=$user
29 | }
30 | }
31 |
32 | if (!$tenant) {
33 | $authUri = $managerUri + "rest/authentication/login/primary"
34 | }
35 | else {
36 | $authUri = $managerUri + "rest/authentication/login"
37 | $data.dsCredentials.Add("tenantName", $tenant)
38 | }
39 | $requestbody = $data | ConvertTo-Json
40 | $SID=Invoke-RestMethod -Headers $headers -Method POST -Uri $authUri -Body $requestbody -SessionVariable session
41 | }
42 |
43 | catch {
44 | echo "An error occurred during authentication. Verify username and password and try again. `nError returned was: $($_.Exception.Message)"
45 | exit
46 | }
47 |
48 | [System.Uri]$uri=$managerUri
49 |
50 | $session.Cookies.Add((New-Object System.Net.Cookie -Property @{
51 | 'Name' = "sID"
52 | 'Value' = "$SID"
53 | 'domain' = $uri.Host
54 | }))
55 |
56 | $requestUri = $managerUri + "rest/cloudaccounts/aws"
57 |
58 | $requestdata = @{
59 | AddAwsAccountRequest = @{
60 | awsCredentials = @{
61 | accessKeyId=$awsAccessKey
62 | secretKey=$awsSecretKey
63 | }
64 | seedRegion=$seedRegion
65 | }
66 | }
67 |
68 | $requestbody = $requestdata | ConvertTo-Json
69 |
70 | $Global:response = Invoke-RestMethod -Headers $headers -Method POST -Uri $requestUri -WebSession $session -Body $requestbody
71 |
72 | $response
73 |
--------------------------------------------------------------------------------
/deepsecurity/manager-apis/powershell/get-allHostsSummary.ps1:
--------------------------------------------------------------------------------
1 |
2 | param (
3 | [Parameter(Mandatory=$true)][string]$manager,
4 | [Parameter(Mandatory=$true)][string]$user,
5 | [Parameter(Mandatory=$false)][string]$tenant
6 | )
7 |
8 | $passwordinput = Read-host "Password for Deep Security Manager" -AsSecureString
9 | $password = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($passwordinput))
10 |
11 | [System.Net.ServicePointManager]::ServerCertificateValidationCallback={$true}
12 | $Global:DSMSoapService = New-WebServiceProxy -uri "https://$manager/webservice/Manager?WSDL" -Namespace "DSSOAP" -ErrorAction Stop
13 | $Global:DSM = New-Object DSSOAP.ManagerService
14 | try {
15 | if (!$tenant) {
16 | $Global:SID = $DSM.authenticate($user, $password)
17 | }
18 | else {
19 | $Global:SID = $DSM.authenticateTenant($tenant, $user, $password)
20 | }
21 | }
22 | catch {
23 | echo "An error occurred during authentication. Verify username and password and try again. `nError returned was: $($_.Exception.Message)"
24 | exit
25 | }
26 |
27 | $hft = new-object DSSOAP.HostFilterTransport
28 | $hft.type = [DSSOAP.EnumHostFilterType]::ALL_HOSTS
29 | $status = $DSM.hostStatusSummaryRetrieve($hft, $SID)
30 | $status
31 |
32 | $DSM.endSession($SID)
--------------------------------------------------------------------------------
/deepsecurity/manager-apis/powershell/get-amComponentVersions.ps1:
--------------------------------------------------------------------------------
1 | <#
2 |
3 | .SYNOPSIS
4 | PowerShell Script to setup objects for remote control of Deep Security Manager via SOAP API.
5 |
6 | .LINK
7 | http://aws.trendmicro.com
8 |
9 | #>
10 |
11 | param (
12 | [Parameter(Mandatory=$true)][string]$manager,
13 | [Parameter(Mandatory=$true)][string]$user,
14 | [Parameter(Mandatory=$true)][string]$hostname,
15 | [Parameter(Mandatory=$false)][string]$tenant
16 | )
17 |
18 | $passwordinput = Read-host "Password for Deep Security Manager" -AsSecureString
19 | $password = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($passwordinput))
20 |
21 | [System.Net.ServicePointManager]::ServerCertificateValidationCallback={$true}
22 | [Net.ServicePointManager]::SecurityProtocol += [Net.SecurityProtocolType]::Tls12
23 | $Global:DSMSoapService = New-WebServiceProxy -uri "https://$manager/webservice/Manager?WSDL" -Namespace "DSSOAP" -ErrorAction Stop
24 | $Global:DSM = New-Object DSSOAP.ManagerService
25 | $Global:SID
26 | try {
27 | if (!$tenant) {
28 | $Global:SID = $DSM.authenticate($user, $password)
29 | }
30 | else {
31 | $Global:SID = $DSM.authenticateTenant($tenant, $user, $password)
32 | }
33 | }
34 | catch {
35 | echo "An error occurred during authentication. Verify username and password and try again. `nError returned was: $($_.Exception.Message)"
36 | exit
37 | }
38 |
39 |
40 | $hdt = $DSM.hostDetailRetrieveByName($hostname, [DSSOAP.EnumHostDetailLevel]::HIGH, $SID)
41 | echo "-------------------------------------------------------------------------------------"
42 | echo "AgentVersion: " + $hdt.overallVersion
43 | echo "Classic Pattern Version: " + $hdt.antiMalwareClassicPatternVersion
44 | echo "Engine Version " + $hdt.antiMalwareEngineVersion
45 | echo "IntelliTrap Version " + $hdt.antiMalwareIntelliTrapExceptionVersion
46 | echo "SmartScan Pattern Version: " + $hdt.antiMalwareSmartScanPatternVersion
47 | echo "Spyware Pattern Version: " + $hdt.antiMalwareSpywarePatternVersion
48 |
49 | $DSM.endSession($SID)
50 |
--------------------------------------------------------------------------------
/deepsecurity/manager-apis/powershell/get-computerCreatedEvents.ps1:
--------------------------------------------------------------------------------
1 | param (
2 | [Parameter(Mandatory=$true, HelpMessage="FQDN and port for Deep Security Manager; ex dsm.example.com:443--")][string]$manager,
3 | [Parameter(Mandatory=$true, HelpMessage="DeepSecurity Manager Username with api access--")][string]$user,
4 | [Parameter(Mandatory=$true, HelpMessage="Start Date for search in format mm/dd/yyyy; ex 12/31/1970--")][string]$fromDate,
5 | [Parameter(Mandatory=$true, HelpMessage="End Date for search in format mm/dd/yyyy; ex 12/31/1970--")][string]$toDate,
6 | [Parameter(Mandatory=$true, HelpMessage="Filename for csv output; if existing data will be appended--")][string]$filename,
7 | [Parameter(Mandatory=$false)][string]$tenant
8 | )
9 |
10 | $passwordinput = Read-host "Password for Deep Security Manager" -AsSecureString
11 | $password = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($passwordinput))
12 |
13 | [System.Net.ServicePointManager]::ServerCertificateValidationCallback={$true}
14 | [Net.ServicePointManager]::SecurityProtocol += [Net.SecurityProtocolType]::Tls12
15 | $DSMSoapService = New-WebServiceProxy -uri "https://$manager/webservice/Manager?WSDL" -Namespace "DSSOAP" -ErrorAction Stop
16 | $DSM = New-Object DSSOAP.ManagerService
17 | $SID = ""
18 | try {
19 | if (!$tenant) {
20 | $SID = $DSM.authenticate($user, $password)
21 | }
22 | else {
23 | $SID = $DSM.authenticateTenant($tenant, $user, $password)
24 | }
25 | }
26 | catch {
27 | echo "An error occurred during authentication. Verify username and password and try again. `nError returned was: $($_.Exception.Message)"
28 | exit
29 | }
30 |
31 | $hft = New-Object DSSOAP.HostFilterTransport
32 | $hft.type = [DSSOAP.EnumHostFilterType]::ALL_HOSTS
33 | $tft = New-Object DSSOAP.TimeFilterTransport
34 | $tft.rangeFrom = [datetime]"$fromDate"
35 | $tft.rangeTo = [datetime]"$toDate"
36 | $tft.type = [DSSOAP.EnumTimeFilterType]::CUSTOM_RANGE
37 | $idft = New-Object DSSOAP.IdFilterTransport2
38 | $idft.operator = [DSSOAP.EnumOperator]::EQUAL
39 |
40 |
41 | $shortdesc = $DSM.systemEventRetrieveShortDescription($tft, $hft, $null, $false, $SID)
42 |
43 | foreach ($evt in $shortdesc.systemEvents)
44 | {
45 | if ($evt.eventID -eq 250)
46 | {
47 | #Write-Host($evt.event,$evt.eventID) -Separator ","
48 | $idft.id = $evt.systemEventID
49 | $fullevents = $DSM.systemEventRetrieve2($tft, $hft, $idft, $false, $SID)
50 | #Write-Host($fullevents.systemEvents[0].event, $fullevents.systemEvents[0].eventID, $fullevents.systemEvents[0].target, $fullevents.systemEvents[0].description) -Separator ","
51 | $fullevents.systemEvents | export-csv -Path $filename -Append
52 | }
53 | }
54 |
55 |
56 | $DSMSoapService.endSession($SID)
57 |
--------------------------------------------------------------------------------
/deepsecurity/manager-apis/powershell/get-cross-tenant-ips-report.ps1:
--------------------------------------------------------------------------------
1 | param (
2 | [Parameter(Mandatory=$true)][string]$manager,
3 | [Parameter(Mandatory=$true)][string]$user,
4 | [Parameter(Mandatory=$true)][string]$filename
5 | )
6 |
7 | $passwordinput = Read-host "Password for Deep Security Manager" -AsSecureString
8 | $password = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($passwordinput))
9 |
10 | function login-restTenant
11 | {
12 | param( [string]$tenantName, [string]$SID )
13 | $signInAsTenantAuthUri = $managerUri + "authentication/signinastenant/name/" + $tenantName + "?sID=" + $Global:SID
14 | Invoke-RestMethod -Headers $headers -Method GET -Uri $signInAsTenantAuthUri
15 | }
16 |
17 | function evaluate-rules
18 | {
19 | param( [string]$token, [string]$tenantname )
20 | $allHosts = $DSM.hostRetrieveAll($token)
21 | $currentHostCouneter = 0
22 | Write-Host "Found $($allhosts.Count) hosts in tenant $($tenantname)."
23 |
24 | foreach ($ht in $allHosts)
25 | {
26 | $currentHostCouneter++
27 | Write-Progress -Activity "Checking rules on $($AllHosts.Count) hosts in $tenantname" -status "Looking at host $($ht.name)" -percentComplete ($currentHostCouneter / $allHosts.Count)
28 |
29 | if ($ht.hostType -like "ESX")
30 | {
31 | continue
32 | }
33 | $hs = $DSM.hostGetStatus($ht.ID, $token)
34 | $RecommendedAllDetectCount =0
35 | $recommendedUnassignedDetectCount = 0
36 | $detections = get-events $token $ht.id
37 |
38 | if ($hs.overallStatus -like 'Unmanaged*' -Or $hs.overallDpiStatus -like '*OFF*' -Or $hs.overallDpiStatus -like 'Not Activated')
39 | {
40 | $csvline = New-Object PSObject;
41 | $csvline | Add-Member -MemberType NoteProperty -Name TenantName -Value $tenantname
42 | $csvline | Add-Member -MemberType NoteProperty -Name DisplayName -Value $ht.DisplayName;
43 | $csvline | Add-Member -MemberType NoteProperty -Name HostName -Value $ht.name;
44 | $csvline | Add-Member -MemberType NoteProperty -Name OverallStatus -Value $hs.overallStatus
45 | #$csvline | Add-Member -MemberType NoteProperty -Name TotalAssignedRules -Value "N/A"
46 | $csvline | Add-Member -MemberType NoteProperty -Name TotalRecomendedRules -Value "N/A"
47 | $csvline | Add-Member -MemberType NoteProperty -Name UnassignedRecommendedRules -Value "N/A"
48 | $csvline | Add-Member -MemberType NoteProperty -Name AssignedRulesInDetect -Value "N/A"
49 | $csvline | Add-Member -MemberType NoteProperty -Name AssignedRulesInPrevent -Value "N/A"
50 | $csvline | Add-Member -MemberType NoteProperty -Name RecomendedRulesInDetect -Value "N/A"
51 | $csvline | Add-Member -MemberType NoteProperty -Name RecommendedRulesInPrevent -Value "N/A"
52 | $csvline | Add-Member -MemberType NoteProperty -Name DetectRulesTriggered -Value "N/A"
53 | $csvline | Add-Member -MemberType NoteProperty -Name PreventRulesTriggered -Value "N/A"
54 | $csvline | Add-Member -MemberType NoteProperty -Name LastRecommendationScan -Value "N/A"
55 | $csvline | export-csv $filename -Append -NoTypeInformation
56 | continue
57 | }
58 |
59 | $recommendedUnassigned = $DSM.hostRecommendationRuleIDsRetrieve($ht.ID, 2, $true, $token)
60 | $recommendedAll = $DSM.hostRecommendationRuleIDsRetrieve($ht.ID, 2, $false, $token)
61 | foreach($rule in $recommendedUnassigned)
62 | {
63 | if ($rule.detectOnly -eq $true) {$recommendedUnassignedDetectCount++}
64 | }
65 |
66 | foreach($rule in $recommendedAll)
67 | {
68 | if ($rule.detectOnly -eq $true) {$RecommendedAllDetectCount++}
69 | }
70 |
71 | $hft = new-object DSSOAP.HostFilterTransport
72 | $hft.type = [DSSOAP.EnumHostFilterType]::SPECIFIC_HOST
73 | $hft.hostID = $ht.id
74 | $hdt = $DSM.hostDetailRetrieve($hft, [DSSOAP.EnumHostDetailLevel]::LOW, $token)
75 |
76 | $detections = get-events $token $ht.id
77 | $csvline = New-Object PSObject;
78 | $csvline | Add-Member -MemberType NoteProperty -Name TenantName -Value $tenantname
79 | $csvline | Add-Member -MemberType NoteProperty -Name DisplayName -Value $ht.DisplayName;
80 | $csvline | Add-Member -MemberType NoteProperty -Name HostName -Value $ht.name;
81 | $csvline | Add-Member -MemberType NoteProperty -Name OverallStatus -Value $hs.overallStatus
82 | #$csvline | Add-Member -MemberType NoteProperty -Name TotalAssignedRules -Value $hs.overallDpiStatus.Split(",")[2]
83 | $csvline | Add-Member -MemberType NoteProperty -Name TotalRecomendedRules -Value $recommendedAll.Count
84 | $csvline | Add-Member -MemberType NoteProperty -Name UnassignedRecommendedRules -Value $recommendedUnassigned.Count
85 | $csvline | Add-Member -MemberType NoteProperty -Name AssignedRulesInDetect -Value ($RecommendedAllDetectCount - $recommendedUnassignedDetectCount)
86 | $csvline | Add-Member -MemberType NoteProperty -Name AssignedRulesInPrevent -Value ($recommendedAll.Count - $assignedDetectCount)
87 | $csvline | Add-Member -MemberType NoteProperty -Name RecomendedRulesInDetect -Value $RecommendedAllDetectCount
88 | $csvline | Add-Member -MemberType NoteProperty -Name RecommendedRulesInPrevent -Value ($recommendedAll.Count - $recommendedDetectCount)
89 | $csvline | Add-Member -MemberType NoteProperty -Name DetectRulesTriggered -Value $detections[0]
90 | $csvline | Add-Member -MemberType NoteProperty -Name PreventRulesTriggered -Value $detections[1]
91 | $csvline | Add-Member -MemberType NoteProperty -Name LastRecommendationScan -Value $hdt.overallLastRecommendationScan
92 | $csvline | export-csv $filename -Append -NoTypeInformation
93 | }
94 | }
95 |
96 | function get-events
97 | {
98 | param( [string]$token, [int]$hostid )
99 | $tagfilter = New-Object DSSOAP.TagFilterTransport
100 | $tagfilter.type = [DSSOAP.EnumTagFilterType]::ALL
101 | $timefilter = New-Object DSSOAP.TimeFilterTransport
102 | $timefilter.type = [DSSOAP.EnumTimeFilterType]::LAST_24_HOURS
103 | $hostfilter = New-Object DSSOAP.HostFilterTransport
104 | $hostfilter.type = [DSSOAP.EnumHostFilterType]::SPECIFIC_HOST
105 | $hostfilter.hostID = $hostid
106 | $idfilter = New-Object DSSOAP.IDFilterTransport2
107 | $detectCounter = $DSM.counterRetrieve([DSSOAP.EnumCounterFilter]::DPI_DETECT_COMPUTER_ACTIVITY, $timefilter, $hostfilter, $tagfilter, $token)
108 | $preventCounter = $DSM.counterRetrieve([DSSOAP.EnumCounterFilter]::DPI_PREVENT_COMPUTER_ACTIVITY, $timefilter, $hostfilter, $tagfilter, $token)
109 | if ($detectCounter -is [DSSOAP.CounterTransport[]])
110 | {
111 | $detectCounter[0].value
112 | }
113 | else
114 | {
115 | "N/A"
116 | }
117 |
118 | if ($preventCounter -is [DSSOAP.CounterTransport[]])
119 | {
120 | $preventCounter[0].value
121 | }
122 | else
123 | {
124 | "N/A"
125 | }
126 |
127 | }
128 |
129 | [System.Net.ServicePointManager]::ServerCertificateValidationCallback={$true}
130 | [Net.ServicePointManager]::SecurityProtocol += [Net.SecurityProtocolType]::Tls12
131 | $DSMSoapService = New-WebServiceProxy -uri "https://$manager/webservice/Manager?WSDL" -Namespace "DSSOAP" -ErrorAction Stop
132 | $DSM = New-Object DSSOAP.ManagerService
133 |
134 | $managerUri="https://$manager/rest/"
135 | $headers=@{'Content-Type'='application/json'}
136 |
137 | try {
138 | $data = @{
139 | dsCredentials = @{
140 | password=$password
141 | userName=$user
142 | }
143 | }
144 |
145 | $authUri = $managerUri + "authentication/login/primary"
146 |
147 | $requestbody = $data | ConvertTo-Json
148 |
149 | $Global:SID=Invoke-RestMethod -Headers $headers -Method POST -Uri $authUri -Body $requestbody
150 | }
151 | catch {
152 | echo "An error occurred during authentication. Verify username and password and try again. `nError returned was: $($_.Exception.Message)"
153 | exit
154 | }
155 |
156 | $multiTenant=$true
157 | try {
158 | $methodUri = $managerUri + "tenants?sID=" + $Global:SID
159 | $Global:tenantListing = Invoke-RestMethod -Headers $headers -Method GET -Uri $methodUri
160 | }
161 |
162 | catch {
163 | $multiTenant=$false
164 | echo "Multi-tenant feature is not enabled; processing T0 only"
165 | }
166 |
167 | try {
168 | evaluate-rules $Global:SID "T0"
169 | if ($multiTenant -eq $true)
170 | {
171 | foreach ($tenant in $tenantListing.tenantListing.tenants)
172 | {
173 | $tenantSid = login-restTenant $tenant.name $Global:SID
174 | evaluate-rules $tenantSid $tenant.name
175 | $DSM.endSession($tenantSid)
176 | }
177 | }
178 | }
179 | catch {
180 | echo "An error occurred while processing host rules. `nError returned was; $($_.Exception.Message)"
181 | }
182 |
183 | finally {
184 | $DSM.endSession($Global:SID)
185 | }
--------------------------------------------------------------------------------
/deepsecurity/manager-apis/powershell/get-firewallrules.ps1:
--------------------------------------------------------------------------------
1 | <#
2 |
3 | .SYNOPSIS
4 | PowerShell Script to setup objects for remote control of Deep Security Manager via SOAP API.
5 |
6 | .DESCRIPTION
7 | The ds-api script configures a Manager object for interfacing with the Deep Security Manager SOAP API. It will leave a DSSOAP.ManagerService() Object $DSM and the ManagerSerivce Namespace will be accessible as [DSSOAP].
8 | The Username and Password supplied will be used to authenticate to the Deep Security manager and store a token in $SID.
9 | Log out of the session when finished with $DSM.EndSession($SID).
10 | See the WebService SDK for more information. This script requires the Web Services API to be enabled on Deep Security Manager.
11 |
12 | .PARAMETER manager
13 | The -manager parameter requires a hostname or IP and port in the format hostname.local:4119 or 198.51.100.10:443.
14 |
15 | .PARAMETER user
16 | The -user parameter requires a Deep Security Manager Administrator with permission to use the SOAP API.
17 |
18 | .PARAMETER tenant
19 | The -tenant parameter is optional and can be used to specify a tenant (other than T0) for relay operations.
20 |
21 | .EXAMPLE
22 | ds-api.ps1 -manager manager.domain.com:443 -user MasterAdmin
23 | This example logs into tenant 0 on the Deep Security Manager.
24 |
25 | ds-api.ps1 -manager manager.domain.com:443 -user tenantAdmin -tenant CustomerTenant
26 | This example logs into tenant named Customer Tenant on the Deep Security Manager.
27 |
28 | .LINK
29 | http://aws.trendmicro.com
30 |
31 | #>
32 |
33 | param (
34 | [Parameter(Mandatory=$true)][string]$manager,
35 | [Parameter(Mandatory=$true)][string]$user,
36 | [Parameter(Mandatory=$true)][string]$computer,
37 | [Parameter(Mandatory=$false)][string]$tenant
38 | )
39 |
40 | $passwordinput = Read-host "Password for Deep Security Manager" -AsSecureString
41 | $password = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($passwordinput))
42 |
43 | [System.Net.ServicePointManager]::ServerCertificateValidationCallback={$true}
44 | [Net.ServicePointManager]::SecurityProtocol += [Net.SecurityProtocolType]::Tls12
45 | $Global:DSMSoapService = New-WebServiceProxy -uri "https://$manager/webservice/Manager?WSDL" -Namespace "DSSOAP" -ErrorAction Stop
46 | $Global:DSM = New-Object DSSOAP.ManagerService
47 | $Global:SID
48 | try {
49 | if (!$tenant) {
50 | $Global:SID = $DSM.authenticate($user, $password)
51 | }
52 | else {
53 | $Global:SID = $DSM.authenticateTenant($tenant, $user, $password)
54 | }
55 | }
56 | catch {
57 | echo "An error occurred during authentication. Verify username and password and try again. `nError returned was: $($_.Exception.Message)"
58 | exit
59 | }
60 |
61 |
62 | $HT = $DSM.hostRetrieveByName($computer, $Global:SID)
63 |
64 | $Policy = $DSM.securityProfileRetrieve($HT.securityProfileID, $Global:SID)
65 |
66 | foreach ($ruleId in $Policy.firewallRuleIDs)
67 | {
68 | $rule = $DSM.firewallRuleRetrieve($ruleId, $Global:SID)
69 | Echo "-------------------------------------------------------------------------------------"
70 | Echo "DestIP " + $rule.destinationId
71 | Echo "DestPorts " + $rule.destinationPorts
72 | Echo "SourceIP " + $rule.sourceIP
73 |
74 |
75 | }
--------------------------------------------------------------------------------
/deepsecurity/manager-apis/powershell/get-hostIpsRules.ps1:
--------------------------------------------------------------------------------
1 |
2 | param (
3 | [Parameter(Mandatory=$true)][string]$manager,
4 | [Parameter(Mandatory=$true)][string]$user,
5 | [Parameter(Mandatory=$false)][string]$tenant
6 | )
7 |
8 | $passwordinput = Read-host "Password for Deep Security Manager" -AsSecureString
9 | $password = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($passwordinput))
10 |
11 | [System.Net.ServicePointManager]::ServerCertificateValidationCallback={$true}
12 | [Net.ServicePointManager]::SecurityProtocol += [Net.SecurityProtocolType]::Tls12
13 | $Global:DSMSoapService = New-WebServiceProxy -uri "https://$manager/webservice/Manager?WSDL" -Namespace "DSSOAP" -ErrorAction Stop
14 | $Global:DSM = New-Object DSSOAP.ManagerService
15 | try {
16 | if (!$tenant) {
17 | $Global:SID = $DSM.authenticate($user, $password)
18 | }
19 | else {
20 | $Global:SID = $DSM.authenticateTenant($tenant, $user, $password)
21 | }
22 | }
23 | catch {
24 | echo "An error occurred during authentication. Verify username and password and try again. `nError returned was: $($_.Exception.Message)"
25 | exit
26 | }
27 |
28 | $timestamp = Get-Date -Format yyyyMMddhhmmss
29 | $filename = "ipsrules$($timestamp).csv"
30 |
31 | $hts = $DSM.hostRetrieveAll($SID);
32 | $csvline = New-Object PSObject;
33 |
34 | foreach ($ht in $hts)
35 | {
36 | $hft = new-object DSSOAP.HostFilterTransport
37 | $hft.type = [DSSOAP.EnumHostFilterType]::SPECIFIC_HOST
38 | $hft.hostID = $ht.ID
39 | $hostdetail = $DSM.hostDetailRetrieve($hft, [DSSOAP.EnumHostDetailLevel]::HIGH, $SID);
40 | if ($hostdetail.overallDpiStatus -like '*OFF*' -Or $hostdetail.overallDpiStatus -like '*Not Activated' -Or $hostdetail.overallDpiStatus -like 'Intrusion Prevention: ')
41 | {
42 | continue
43 | };
44 |
45 | Write-Host "Checking details for hostID: $($ht.ID) with status $($hostdetail.overallDpiStatus)"
46 | $hostPolicy = $DSM.securityProfileRetrieve($ht.securityProfileID, $SID)
47 | Write-Host "Found $($hostPolicy.DPIRuleIDs.count) ips rules"
48 |
49 | foreach ($ipsrule in $hostPolicy.DPIRuleIDs)
50 | {
51 | $csvline = $null
52 | $rule = $DSM.DPIRuleRetrieve($ipsrule, $SID);
53 | $csvline | Add-Member -MemberType NoteProperty -Name DisplayName -Value $ht.DisplayName;
54 | $csvline | Add-Member -MemberType NoteProperty -Name HostName -Value $ht.name;
55 | $csvline | Add-Member -MemberType NoteProperty -Name IP -Value $hostdetail.lastIPUsed;
56 | $csvline | Add-Member -MemberType NoteProperty -Name DpiRuleId -Value $rule.identifier;
57 | $csvline | Add-Member -MemberType NoteProperty -Name DpiRuleCveNumbers -Value $rule.cvenumbers;
58 | $csvline | Add-Member -MemberType NoteProperty -Name DpiRuleDescription -Value $rule.description;
59 | $csvline | export-csv $filename -Append -NoTypeInformation -NoClobber
60 | }
61 |
62 | }
63 |
64 | $DSM.endSession($SID)
65 |
--------------------------------------------------------------------------------
/deepsecurity/manager-apis/powershell/get-hostRecoAndAssignedRules.ps1:
--------------------------------------------------------------------------------
1 | param (
2 | [Parameter(Mandatory=$true)][string]$manager,
3 | [Parameter(Mandatory=$true)][string]$user,
4 | [Parameter(Mandatory=$false)][string]$tenant
5 | )
6 |
7 | $passwordinput = Read-host "Password for Deep Security Manager" -AsSecureString
8 | $password = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($passwordinput))
9 |
10 | [System.Net.ServicePointManager]::ServerCertificateValidationCallback={$true}
11 | [Net.ServicePointManager]::SecurityProtocol += [Net.SecurityProtocolType]::Tls12
12 | $Global:DSMSoapService = New-WebServiceProxy -uri "https://$manager/webservice/Manager?WSDL" -Namespace "DSSOAP" -ErrorAction Stop
13 | $Global:DSM = New-Object DSSOAP.ManagerService
14 | $Global:SID
15 | try {
16 | if (!$tenant) {
17 | $Global:SID = $DSM.authenticate($user, $password)
18 | }
19 | else {
20 | $Global:SID = $DSM.authenticateTenant($tenant, $user, $password)
21 | }
22 | }
23 | catch {
24 | echo "An error occurred during authentication. Verify username and password and try again. `nError returned was: $($_.Exception.Message)"
25 | exit
26 | }
27 |
28 |
29 | try {
30 | $timestamp = Get-Date -Format yyyyMMddhhmmss
31 | $filename = "ipsReport$($timestamp).csv"
32 |
33 | $hts = $dsm.hostRetrieveAll($SID)
34 | foreach ($ht in $hts)
35 | {
36 |
37 |
38 | $hs = $DSM.hostGetStatus($ht.ID, $SID)
39 | if ($hs.overallStatus -like 'Unmanaged*' -Or $hs.overallDpiStatus -like '*OFF*' -Or $hs.overallDpiStatus -like 'Not Activated')
40 | {
41 | continue
42 | }
43 | Write-Host "Checking details for hostID: $($ht.ID)"
44 | $assignedrules=$hs.overallDpiStatus
45 | $recommended = $DSM.hostRecommendationRuleIDsRetrieve($ht.ID, 2, $false, $SID)
46 | $csvline = New-Object PSObject;
47 | $csvline | Add-Member -MemberType NoteProperty -Name DisplayName -Value $ht.DisplayName;
48 | $csvline | Add-Member -MemberType NoteProperty -Name HostName -Value $ht.name;
49 | $csvline | Add-Member -MemberType NoteProperty -Name OverallStatus -Value $hs.overallStatus
50 | $csvline | Add-Member -MemberType NoteProperty -Name TotalAssignedRules -Value $hs.overallDpiStatus.Split(",")[2]
51 | $csvline | Add-Member -MemberType NoteProperty -Name RulesRecommendedTotal -Value $recommended.count
52 | $csvline | export-csv $filename -Append
53 |
54 | }
55 |
56 | }
57 | catch {
58 | echo "An error occurred while pulling records. 'nError returned was: $($_.Exception.Message)"
59 | }
60 | finally {
61 | $DSM.endSession($SID)
62 | }
63 |
64 | $DSM.endSession($SID)
--------------------------------------------------------------------------------
/deepsecurity/manager-apis/powershell/get-macFromInterfaces.ps1:
--------------------------------------------------------------------------------
1 | param (
2 | [Parameter(Mandatory=$true)][string]$manager,
3 | [Parameter(Mandatory=$true)][string]$user,
4 | [Parameter(Mandatory=$true)][string]$hostname,
5 | [Parameter(Mandatory=$false)][string]$tenant
6 | )
7 |
8 | $passwordinput = Read-host "Password for Deep Security Manager" -AsSecureString
9 | $password = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($passwordinput))
10 |
11 | [System.Net.ServicePointManager]::ServerCertificateValidationCallback={$true}
12 | [Net.ServicePointManager]::SecurityProtocol += [Net.SecurityProtocolType]::Tls12
13 | $Global:DSMSoapService = New-WebServiceProxy -uri "https://$manager/webservice/Manager?WSDL" -Namespace "DSSOAP" -ErrorAction Stop
14 | $Global:DSM = New-Object DSSOAP.ManagerService
15 | $Global:SID
16 | try {
17 | if (!$tenant) {
18 | $Global:SID = $DSM.authenticate($user, $password)
19 | }
20 | else {
21 | $Global:SID = $DSM.authenticateTenant($tenant, $user, $password)
22 | }
23 | }
24 | catch {
25 | echo "An error occurred during authentication. Verify username and password and try again. `nError returned was: $($_.Exception.Message)"
26 | exit
27 | }
28 |
29 | $hostdetails = $DSM.hostDetailRetrieveByName($hostname, [DSSOAP.EnumHostDetailLevel]::HIGH, $SID);
30 | $hostdetail = $hostdetails[0]
31 | Write-Host "Enumerating Interfaces via HostInterfaceTransport Objects in array HostDetailTransport.hostInterfaces:`n"
32 | $hostdetail.hostInterfaces
33 | Write-Host "Enumerating MAC Address on each HostInterfaceTransport:`n"
34 | foreach ($hostinterface in $hostdetail.hostInterfaces)
35 | {
36 | Write-Host "$($hostdetail.name)`t$($hostinterface.name)`t$($hostinterface.mac)"
37 | }
38 | $DSM.endSession($SID)
--------------------------------------------------------------------------------
/deepsecurity/manager-apis/powershell/get-managedHostCounts.ps1:
--------------------------------------------------------------------------------
1 |
2 | param (
3 | [Parameter(Mandatory=$true)][string]$manager,
4 | [Parameter(Mandatory=$true)][string]$user,
5 | [Parameter(Mandatory=$false)][string]$tenant
6 | )
7 |
8 | $passwordinput = Read-host "Password for Deep Security Manager" -AsSecureString
9 | $password = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($passwordinput))
10 |
11 | [System.Net.ServicePointManager]::ServerCertificateValidationCallback={$true}
12 | [Net.ServicePointManager]::SecurityProtocol += [Net.SecurityProtocolType]::Tls12
13 | $Global:DSMSoapService = New-WebServiceProxy -uri "https://$manager/webservice/Manager?WSDL" -Namespace "DSSOAP" -ErrorAction Stop
14 | $Global:DSM = New-Object DSSOAP.ManagerService
15 | try {
16 | if (!$tenant) {
17 | $Global:SID = $DSM.authenticate($user, $password)
18 | }
19 | else {
20 | $Global:SID = $DSM.authenticateTenant($tenant, $user, $password)
21 | }
22 | }
23 | catch {
24 | echo "An error occurred during authentication. Verify username and password and try again. `nError returned was: $($_.Exception.Message)"
25 | exit
26 | }
27 |
28 | $hft = new-object DSSOAP.HostFilterTransport
29 | $hft.type = [DSSOAP.EnumHostFilterType]::ALL_HOSTS
30 | $detailstatus = $DSM.hostDetailRetrieve($hft, [DSSOAP.EnumHostDetailLevel]::LOW, $SID)
31 |
32 | $managedCounter=0
33 | $unManagedCounter=0
34 | foreach ($detail in $detailstatus) {if ($detail.overallStatus -like "Unmanaged*") { $unManagedCounter++ } else { $managedCounter++} }
35 | Write-Host "Unmanaged hosts:" $unManagedCounter
36 | Write-Host "Managed hosts:" $managedCounter
37 |
38 |
39 | $DSM.endSession($SID)
--------------------------------------------------------------------------------
/deepsecurity/manager-apis/powershell/rest-authenticationLogin.ps1:
--------------------------------------------------------------------------------
1 | param (
2 | [Parameter(Mandatory=$true)][string]$manager,
3 | [Parameter(Mandatory=$true)][string]$user,
4 | [Parameter(Mandatory=$false)][string]$tenant
5 | )
6 |
7 | $passwordinput = Read-host "Password for Deep Security Manager" -AsSecureString
8 | $password = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($passwordinput))
9 |
10 |
11 | [System.Net.ServicePointManager]::ServerCertificateValidationCallback={$true}
12 | [Net.ServicePointManager]::SecurityProtocol += [Net.SecurityProtocolType]::Tls12
13 |
14 | $managerUri="https://$manager/rest/"
15 | $Global:SID
16 | $authUri
17 |
18 | $headers=@{'Content-Type'='application/json'}
19 |
20 | try {
21 | $data = @{
22 | dsCredentials = @{
23 | password=$password
24 | userName=$user
25 | }
26 | }
27 | if (!$tenant) {
28 | $authUri = $managerUri + "authentication/login/primary"
29 | }
30 | else {
31 | $authUri = $managerUri + "authentication/login"
32 | $data.dsCredentials.Add("tenantName", $tenant)
33 | }
34 |
35 |
36 | $requestbody = $data | ConvertTo-Json
37 |
38 | $Global:SID=Invoke-RestMethod -Headers $headers -Method POST -Uri $authUri -Body $requestbody
39 | }
40 | catch {
41 | echo "An error occurred during authentication. Verify username and password and try again. `nError returned was: $($_.Exception.Message)"
42 | exit
43 | }
44 |
45 |
46 |
47 |
--------------------------------------------------------------------------------
/deepsecurity/manager-apis/powershell/rest-managerInfoComponents.ps1:
--------------------------------------------------------------------------------
1 | param (
2 | [Parameter(Mandatory=$true)][string]$manager,
3 | [Parameter(Mandatory=$true)][string]$user,
4 | [Parameter(Mandatory=$false)][string]$tenant
5 | )
6 |
7 | $passwordinput = Read-host "Password for Deep Security Manager" -AsSecureString
8 | $password = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($passwordinput))
9 |
10 |
11 | [System.Net.ServicePointManager]::ServerCertificateValidationCallback={$true}
12 | [Net.ServicePointManager]::SecurityProtocol += [Net.SecurityProtocolType]::Tls12
13 |
14 | $managerUri="https://$manager/rest/"
15 | $Global:SID
16 | $authUri
17 |
18 | $headers=@{'Content-Type'='application/json'}
19 |
20 | try {
21 | $data = @{
22 | dsCredentials = @{
23 | password=$password
24 | userName=$user
25 | }
26 | }
27 | if (!$tenant) {
28 | $authUri = $managerUri + "authentication/login/primary"
29 | }
30 | else {
31 | $authUri = $managerUri + "authentication/login"
32 | $data.dsCredentials.Add("tenantName", $tenant)
33 | }
34 |
35 |
36 | $requestbody = $data | ConvertTo-Json
37 | $Global:SID=Invoke-RestMethod -Headers $headers -Method POST -Uri $authUri -Body $requestbody
38 | }
39 | catch {
40 | echo "An error occurred during authentication. Verify username and password and try again. `nError returned was: $($_.Exception.Message)"
41 | exit
42 | }
43 |
44 |
45 | $requestUri = $managerUri + "managerInfo/components?sID=$SID"
46 | $response=Invoke-RestMethod -Headers $headers -Method GET -Uri $requestUri
47 |
48 | $response
49 |
50 | ##log out
51 |
52 | $logoutUri = $managerUri + "authentication/logout?sID=$SID"
53 | $response=Invoke-RestMethod -Headers $headers -Method Delete -Uri $logoutUri
54 |
55 |
56 |
57 |
--------------------------------------------------------------------------------
/deepsecurity/manager-apis/powershell/setup-dsSoap.ps1:
--------------------------------------------------------------------------------
1 | <#
2 |
3 | .SYNOPSIS
4 | PowerShell Script to setup objects for remote control of Deep Security Manager via SOAP API.
5 |
6 | .DESCRIPTION
7 | The ds-api script configures a Manager object for interfacing with the Deep Security Manager SOAP API. It will leave a ManagerService.ManagerService() Object $DSM and the ManagerSerivce Namespace will be accessible as [ManagerService].
8 | The Username and Password supplied will be used to authenticate to the Deep Security manager and store a token in $SID.
9 | Log out of the session when finished with $DSM.EndSession($SID).
10 | See the WebService SDK for more information. This script requires the Web Services API to be enabled on Deep Security Manager.
11 |
12 | .PARAMETER manager
13 | The -manager parameter requires a hostname or IP and port in the format hostname.local:4119 or 198.51.100.10:443.
14 |
15 | .PARAMETER user
16 | The -user parameter requires a Deep Security Manager Administrator with permission to use the SOAP API.
17 |
18 | .PARAMETER tenant
19 | The -tenant parameter is optional and can be used to specify a tenant (other than T0) for relay operations.
20 |
21 | .EXAMPLE
22 | ds-api.ps1 -manager manager.domain.com:443 -user MasterAdmin
23 | This example logs into tenant 0 on the Deep Security Manager.
24 |
25 | ds-api.ps1 -manager manager.domain.com:443 -user tenantAdmin -tenant CustomerTenant
26 | This example logs into tenant named Customer Tenant on the Deep Security Manager.
27 |
28 | .LINK
29 | http://aws.trendmicro.com
30 |
31 | #>
32 |
33 | param (
34 | [Parameter(Mandatory=$true)][string]$manager,
35 | [Parameter(Mandatory=$true)][string]$user,
36 | [Parameter(Mandatory=$false)][string]$tenant
37 | )
38 |
39 | $passwordinput = Read-host "Password for Deep Security Manager" -AsSecureString
40 | $password = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($passwordinput))
41 |
42 | [System.Net.ServicePointManager]::ServerCertificateValidationCallback={$true}
43 | [Net.ServicePointManager]::SecurityProtocol += [Net.SecurityProtocolType]::Tls12
44 | $Global:DSMSoapService = New-WebServiceProxy -uri "https://$manager/webservice/Manager?WSDL" -Namespace "DSSOAP" -ErrorAction Stop
45 | $Global:DSM = New-Object DSSOAP.ManagerService
46 | $Global:SID
47 | try {
48 | if (!$tenant) {
49 | $Global:SID = $DSM.authenticate($user, $password)
50 | }
51 | else {
52 | $Global:SID = $DSM.authenticateTenant($tenant, $user, $password)
53 | }
54 | }
55 | catch {
56 | echo "An error occurred during authentication. Verify username and password and try again. `nError returned was: $($_.Exception.Message)"
57 | exit
58 | }
59 |
60 |
--------------------------------------------------------------------------------
/deepsecurity/manager-apis/python/listComputers.py:
--------------------------------------------------------------------------------
1 | import deepsecurity as api
2 | from deepsecurity.rest import ApiException as api_exception
3 | import codecs
4 | import re
5 | import time
6 | import pickle
7 | import os
8 | import datetime
9 |
10 | #DSM Host & port (must end in /api)
11 | HOST='https://app.deepsecurity.trendmicro.com:443/api'
12 | #API Key from the DSM defined in an environment varaible called "API_KEY"
13 | API_KEY=os.environ.get('API_KEY', None)
14 | # Output file
15 | FILENAME = 'report.csv'
16 | # API Version
17 | api_version = 'v1'
18 |
19 |
20 |
21 |
22 | def GetAllGroups(configuration):
23 | # Set search criteria
24 | search_criteria = api.SearchCriteria()
25 | search_criteria.id_value = 0
26 | search_criteria.id_test = "greater-than"
27 | # Create a search filter with maximum returned items
28 | page_size = 5000
29 | search_filter = api.SearchFilter()
30 | search_filter.max_items = page_size
31 | search_filter.search_criteria = [search_criteria]
32 |
33 | groupsapi = api.ComputerGroupsApi(api.ApiClient(configuration))
34 |
35 | paged_groups = []
36 | try:
37 | while True:
38 | t0 = time.time()
39 | groups = groupsapi.search_computer_groups(api_version, search_filter=search_filter)
40 | t1 = time.time()
41 | num_found = len(groups.computer_groups)
42 | if num_found == 0:
43 | print("No groups found.")
44 | break
45 | paged_groups.extend(groups.computer_groups)
46 | # Get the ID of the last group in the page and return it with the number of groups on the page
47 | last_id = groups.computer_groups[-1].id
48 | search_criteria.id_value = last_id
49 | print("Last ID: " + str(last_id), "Groups found: " + str(num_found))
50 | print ("Return rate: {0} groups/sec".format(num_found / (t1 - t0)))
51 | if num_found != page_size:
52 | print ("Num_found {0} - Page size is {1}".format(num_found, page_size))
53 |
54 |
55 | except api_exception as e:
56 | return "Exception: " + str(e)
57 |
58 | return paged_groups
59 |
60 | def GetAllComputers(configuration):
61 |
62 | # Set search criteria
63 | search_criteria = api.SearchCriteria()
64 | search_criteria.id_value = 0
65 | search_criteria.id_test = "greater-than"
66 |
67 | # Create a search filter with maximum returned items
68 | page_size = 50
69 | search_filter = api.SearchFilter()
70 | search_filter.max_items = page_size
71 | search_filter.search_criteria = [search_criteria]
72 |
73 | # Perform the search and do work on the results
74 | computers_api = api.ComputersApi(api.ApiClient(configuration))
75 | paged_computers = []
76 | while True:
77 | try:
78 | t0 = time.time()
79 | computers = computers_api.search_computers(api_version, search_filter=search_filter)
80 | t1 = time.time()
81 | num_found = len(computers.computers)
82 | current_paged_computers = []
83 |
84 | if num_found == 0:
85 | print("No computers found.")
86 | break
87 |
88 | for computer in computers.computers:
89 | current_paged_computers.append(computer)
90 |
91 | paged_computers.append(current_paged_computers)
92 |
93 | # Get the ID of the last computer in the page and return it with the number of computers on the page
94 | last_id = computers.computers[-1].id
95 | search_criteria.id_value = last_id
96 | print("Last ID: " + str(last_id), "Computers found: " + str(num_found))
97 | print ("Return rate: {0} hosts/sec".format( num_found / (t1-t0) ))
98 |
99 | if num_found != page_size:
100 | print ("Num_found {0} - Page size is {1}".format(num_found, page_size))
101 |
102 | except api_exception as e:
103 | print ("Exception: {0}".format(str(e)))
104 |
105 | return paged_computers
106 |
107 |
108 | def WriteToDisk(computers, groups):
109 | with open('computers.pkl', 'wb') as outfile:
110 | pickle.dump(computers, outfile)
111 | with open('rest_groups.pkl', 'wb') as outfile:
112 | pickle.dump(groups, outfile)
113 | return
114 |
115 | def ReadFromDisk():
116 | with open('rest_groups.pkl', 'rb') as infile:
117 | _Groups = pickle.load(infile)
118 | with open('computers.pkl', 'rb') as infile:
119 | _RestComputers = pickle.load(infile)
120 | return _Groups,_RestComputers
121 |
122 | def ConvertToHostLight( value):
123 | if value == "active":
124 | return "Managed"
125 | if value == "warning":
126 | return "Warning"
127 | if value == "error":
128 | return "Critical"
129 | if value == "inactive":
130 | return "Unmanaged"
131 | if value == "not-supported":
132 | return "Unmanaged"
133 | return "Unmanaged"
134 |
135 |
136 | def _getAmazonAccount(groupid, groups, _awsAccounts, _accountPattern):
137 | if groupid in _awsAccounts:
138 | return _awsAccounts[groupid]
139 |
140 | for g in groups:
141 | if g.id == groupid:
142 | if g.parent_group_id != None:
143 | cloudAccount = _getAmazonAccount(g.parent_group_id, groups, _awsAccounts, _accountPattern)
144 | _awsAccounts[g.id] = cloudAccount
145 | return cloudAccount
146 | if g.id in _awsAccounts:
147 | return _awsAccounts[g.name]
148 | _awsAccounts[g.id] = g.name
149 | return g.name
150 |
151 | return '0'
152 |
153 | def _convertTimeStamp(serverTime):
154 | if serverTime:
155 | t = datetime.datetime.fromtimestamp(serverTime / 1000).strftime('%Y-%m-%dT%H:%M:%S.%fZ')
156 | return t
157 | return " "
158 |
159 | def WriteCSV(pagedcomputers, groups):
160 | _awsAccounts = {}
161 | _accountPattern = re.compile("[0-9]{6,25}")
162 |
163 | with codecs.open(FILENAME, "w", "utf-8") as outfile:
164 | outfile.write(
165 | "AWS Instance Id,Computer Status,Status,amazon_account_id,displayName,host_name, Agent Version, Last Agent Communication\n")
166 | for computers in pagedcomputers:
167 | for restComputer in computers:
168 | try:
169 | account = _getAmazonAccount(restComputer.group_id,groups, _awsAccounts, _accountPattern)
170 | statusMessage = "{0}".format(restComputer.computer_status.agent_status_messages)
171 | statusMessage = statusMessage.replace(","," ")
172 | if restComputer.ec2_virtual_machine_summary:
173 | instanceid = restComputer.ec2_virtual_machine_summary.instance_id
174 | if instanceid is None:
175 | instanceid = "None"
176 | else:
177 | instanceid = "None"
178 |
179 | outfile.write("{0},{1},{2},{3},{4},{5}, {6}, {7}\n".format(
180 | instanceid,
181 | ConvertToHostLight(restComputer.computer_status.agent_status),
182 | statusMessage,
183 | account,
184 | restComputer.display_name,
185 | restComputer.host_name,
186 | restComputer.agent_version,
187 | _convertTimeStamp(restComputer.last_agent_communication)
188 | ))
189 | except Exception as err:
190 | print (err)
191 | return
192 |
193 |
194 | if __name__ == '__main__':
195 | if not API_KEY:
196 | raise ValueError('You must have "API_KEY" variable')
197 | # Add Deep Security Manager host information to the api client configuration
198 | configuration = api.Configuration()
199 | configuration.host = HOST
200 | configuration.verify_ssl = True
201 | # Authentication
202 | configuration.api_key['api-secret-key'] = API_KEY
203 |
204 | groups = GetAllGroups(configuration)
205 | allComputers = GetAllComputers(configuration)
206 | WriteToDisk(allComputers, groups)
207 | #groups,allComputers = ReadFromDisk()
208 | WriteCSV(allComputers, groups)
209 |
210 | print "finished"
211 |
--------------------------------------------------------------------------------
/deepsecurity/manager-apis/python/listComputersExpands.py:
--------------------------------------------------------------------------------
1 | import deepsecurity as api
2 | from deepsecurity.rest import ApiException as api_exception
3 | from deepsecurity.expand import Expand
4 | import codecs
5 | import re
6 | import time
7 | import pickle
8 | import os
9 | import datetime
10 |
11 | #DSM Host & port (must end in /api)
12 | HOST='https://app.deepsecurity.trendmicro.com:443/api'
13 | #API Key from the DSM defined in an environment varaible called "API_KEY"
14 | API_KEY=os.environ.get('API_KEY', None)
15 | # Output file
16 | FILENAME = 'report.csv'
17 | # API Version
18 | api_version = 'v1'
19 |
20 |
21 |
22 |
23 | def GetAllGroups(configuration):
24 | # Set search criteria
25 | search_criteria = api.SearchCriteria()
26 | search_criteria.id_value = 0
27 | search_criteria.id_test = "greater-than"
28 | # Create a search filter with maximum returned items
29 | page_size = 5000
30 | search_filter = api.SearchFilter()
31 | search_filter.max_items = page_size
32 | search_filter.search_criteria = [search_criteria]
33 |
34 | groupsapi = api.ComputerGroupsApi(api.ApiClient(configuration))
35 |
36 | paged_groups = []
37 | try:
38 | while True:
39 | t0 = time.time()
40 | groups = groupsapi.search_computer_groups(api_version, search_filter=search_filter)
41 | t1 = time.time()
42 | num_found = len(groups.computer_groups)
43 | if num_found == 0:
44 | print("No groups found.")
45 | break
46 | paged_groups.extend(groups.computer_groups)
47 | # Get the ID of the last group in the page and return it with the number of groups on the page
48 | last_id = groups.computer_groups[-1].id
49 | search_criteria.id_value = last_id
50 | print("Last ID: " + str(last_id), "Groups found: " + str(num_found))
51 | print ("Return rate: {0} groups/sec".format(num_found / (t1 - t0)))
52 | if num_found != page_size:
53 | print ("Num_found {0} - Page size is {1}".format(num_found, page_size))
54 |
55 |
56 | except api_exception as e:
57 | return "Exception: " + str(e)
58 |
59 | return paged_groups
60 |
61 | def GetAllComputers(configuration):
62 |
63 | expand = Expand(Expand.ec2_virtual_machine_summary)
64 | expndList = expand.list()
65 | # Set search criteria
66 | search_criteria = api.SearchCriteria()
67 | search_criteria.id_value = 0
68 | search_criteria.id_test = "greater-than"
69 |
70 | # Create a search filter with maximum returned items
71 | page_size = 50
72 | search_filter = api.SearchFilter()
73 | search_filter.max_items = page_size
74 | search_filter.search_criteria = [search_criteria]
75 |
76 | # Perform the search and do work on the results
77 | computers_api = api.ComputersApi(api.ApiClient(configuration))
78 | paged_computers = []
79 | while True:
80 | try:
81 | t0 = time.time()
82 | computers = computers_api.search_computers(api_version, search_filter=search_filter, expand=expndList)
83 | t1 = time.time()
84 | num_found = len(computers.computers)
85 | current_paged_computers = []
86 |
87 | if num_found == 0:
88 | print("No computers found.")
89 | break
90 |
91 | for computer in computers.computers:
92 | current_paged_computers.append(computer)
93 |
94 | paged_computers.append(current_paged_computers)
95 |
96 | # Get the ID of the last computer in the page and return it with the number of computers on the page
97 | last_id = computers.computers[-1].id
98 | search_criteria.id_value = last_id
99 | print("Last ID: " + str(last_id), "Computers found: " + str(num_found))
100 | print ("Return rate: {0} hosts/sec".format( num_found / (t1-t0) ))
101 |
102 | if num_found != page_size:
103 | print ("Num_found {0} - Page size is {1}".format(num_found, page_size))
104 |
105 | except api_exception as e:
106 | print ("Exception: {0}".format(str(e)))
107 |
108 | return paged_computers
109 |
110 |
111 | def WriteToDisk(computers, groups):
112 | with open('computers.pkl', 'wb') as outfile:
113 | pickle.dump(computers, outfile)
114 | with open('rest_groups.pkl', 'wb') as outfile:
115 | pickle.dump(groups, outfile)
116 | return
117 |
118 | def ReadFromDisk():
119 | with open('rest_groups.pkl', 'rb') as infile:
120 | _Groups = pickle.load(infile)
121 | with open('computers.pkl', 'rb') as infile:
122 | _RestComputers = pickle.load(infile)
123 | return _Groups,_RestComputers
124 |
125 | def ConvertToHostLight( value):
126 | if value == "active":
127 | return "Managed"
128 | if value == "warning":
129 | return "Warning"
130 | if value == "error":
131 | return "Critical"
132 | if value == "inactive":
133 | return "Unmanaged"
134 | if value == "not-supported":
135 | return "Unmanaged"
136 | return "Unmanaged"
137 |
138 |
139 | def _getAmazonAccount(groupid, groups, _awsAccounts, _accountPattern):
140 | if groupid in _awsAccounts:
141 | return _awsAccounts[groupid]
142 |
143 | for g in groups:
144 | if g.id == groupid:
145 | if g.parent_group_id != None:
146 | cloudAccount = _getAmazonAccount(g.parent_group_id, groups, _awsAccounts, _accountPattern)
147 | _awsAccounts[g.id] = cloudAccount
148 | return cloudAccount
149 | if g.id in _awsAccounts:
150 | return _awsAccounts[g.name]
151 | _awsAccounts[g.id] = g.name
152 | return g.name
153 |
154 | return '0'
155 |
156 | def _convertTimeStamp(serverTime):
157 | if serverTime:
158 | t = datetime.datetime.fromtimestamp(serverTime / 1000).strftime('%Y-%m-%dT%H:%M:%S.%fZ')
159 | return t
160 | return " "
161 |
162 | def WriteCSV(pagedcomputers, groups):
163 | _awsAccounts = {}
164 | _accountPattern = re.compile("[0-9]{6,25}")
165 |
166 | with codecs.open(FILENAME, "w", "utf-8") as outfile:
167 | outfile.write(
168 | "AWS Instance Id,Computer Status,Status,amazon_account_id,displayName,host_name, Agent Version, Last Agent Communication\n")
169 | for computers in pagedcomputers:
170 | for restComputer in computers:
171 | try:
172 | account = _getAmazonAccount(restComputer.group_id,groups, _awsAccounts, _accountPattern)
173 | statusMessage = "{0}".format(restComputer.computer_status.agent_status_messages)
174 | statusMessage = statusMessage.replace(","," ")
175 | if restComputer.ec2_virtual_machine_summary:
176 | instanceid = restComputer.ec2_virtual_machine_summary.instance_id
177 | if instanceid is None:
178 | instanceid = "None"
179 | else:
180 | instanceid = "None"
181 |
182 | outfile.write("{0},{1},{2},{3},{4},{5}, {6}, {7}\n".format(
183 | instanceid,
184 | ConvertToHostLight(restComputer.computer_status.agent_status),
185 | statusMessage,
186 | account,
187 | restComputer.display_name,
188 | restComputer.host_name,
189 | restComputer.agent_version,
190 | _convertTimeStamp(restComputer.last_agent_communication)
191 | ))
192 | except Exception as err:
193 | print (err)
194 | return
195 |
196 |
197 | if __name__ == '__main__':
198 | if not API_KEY:
199 | raise ValueError('You must have "API_KEY" variable')
200 | # Add Deep Security Manager host information to the api client configuration
201 | configuration = api.Configuration()
202 | configuration.host = HOST
203 | configuration.verify_ssl = True
204 | # Authentication
205 | configuration.api_key['api-secret-key'] = API_KEY
206 |
207 | groups = GetAllGroups(configuration)
208 | allComputers = GetAllComputers(configuration)
209 | WriteToDisk(allComputers, groups)
210 | #groups,allComputers = ReadFromDisk()
211 | WriteCSV(allComputers, groups)
212 |
213 | print "finished"
214 |
--------------------------------------------------------------------------------
/deepsecurity/manager-apis/python/listComputersParallel.py:
--------------------------------------------------------------------------------
1 | import deepsecurity as api
2 | from deepsecurity.rest import ApiException as api_exception
3 | from threading import Thread
4 | from threading import Lock
5 | import copy
6 | import codecs
7 | import re
8 | import time
9 | import pickle
10 | import os
11 | import datetime
12 |
13 | # DSM Host & port (must end in /api)
14 | HOST = 'https://app.deepsecurity.trendmicro.com:443/api'
15 | # API Key from the DSM defined in an environment variable called "API_KEY"
16 | API_KEY = os.environ.get('API_KEY', None)
17 | # Output file
18 | FILENAME = 'report.csv'
19 | # API Version
20 | api_version = 'v1'
21 |
22 |
23 | class DeepSecurityComputers:
24 |
25 | def __init__(self, config):
26 | self._lock = Lock()
27 | self._threadDataLock = Lock()
28 | self._threadsGroups = []
29 | self._threadCount = 12
30 | self._Groups = None
31 | self._Computers = []
32 | self._config = config
33 |
34 |
35 |
36 | def GetAllGroups(self, configuration):
37 | # Set search criteria
38 | search_criteria = api.SearchCriteria()
39 | search_criteria.id_value = 0
40 | search_criteria.id_test = "greater-than"
41 | # Create a search filter with maximum returned items
42 | page_size = 5000
43 | search_filter = api.SearchFilter()
44 | search_filter.max_items = page_size
45 | search_filter.search_criteria = [search_criteria]
46 |
47 | groupsapi = api.ComputerGroupsApi(api.ApiClient(configuration))
48 |
49 | paged_groups = []
50 | try:
51 | while True:
52 | t0 = time.time()
53 | groups = groupsapi.search_computer_groups(api_version, search_filter=search_filter)
54 | t1 = time.time()
55 | num_found = len(groups.computer_groups)
56 | if num_found == 0:
57 | print("No groups found.")
58 | break
59 | paged_groups.extend(groups.computer_groups)
60 | # Get the ID of the last group in the page and return it with the number of groups on the page
61 | last_id = groups.computer_groups[-1].id
62 | search_criteria.id_value = last_id
63 | print("Last ID: " + str(last_id), "Groups found: " + str(num_found))
64 | print ("Return rate: {0} groups/sec".format(num_found / (t1 - t0)))
65 | if num_found != page_size:
66 | print ("Num_found {0} - Page size is {1}".format(num_found, page_size))
67 |
68 | except api_exception as e:
69 | return "Exception: " + str(e)
70 |
71 | return paged_groups
72 |
73 | def _GetGroupComputers(self, configuration, groupID):
74 |
75 | # Set search group criteria
76 | search_group_criteria = api.SearchCriteria()
77 | search_group_criteria.field_name = "groupID"
78 | if groupID:
79 | search_group_criteria.numeric_value = groupID
80 | search_group_criteria.numeric_test = "equal"
81 | else:
82 | search_group_criteria.null_test = True
83 |
84 | # Set search criteria
85 | search_criteria = api.SearchCriteria()
86 | search_criteria.id_value = 0
87 | search_criteria.id_test = "greater-than"
88 |
89 | # Create a search filter with maximum returned items
90 | page_size = 250
91 | search_filter = api.SearchFilter()
92 | search_filter.max_items = page_size
93 | search_filter.search_criteria = [search_criteria, search_group_criteria]
94 |
95 | # Perform the search and do work on the results
96 | computers_api = api.ComputersApi(api.ApiClient(configuration))
97 | paged_computers = []
98 | while True:
99 | try:
100 | t0 = time.time()
101 | computers = computers_api.search_computers(api_version, search_filter=search_filter)
102 | t1 = time.time()
103 | num_found = len(computers.computers)
104 | current_paged_computers = []
105 |
106 | if num_found == 0:
107 | #This gets noise with so many threads
108 | #print("No computers found.")
109 | break
110 |
111 | for computer in computers.computers:
112 | current_paged_computers.append(computer)
113 |
114 | paged_computers.append(current_paged_computers)
115 |
116 | # Get the ID of the last computer in the page and return it with the number of computers on the page
117 | last_id = computers.computers[-1].id
118 | search_criteria.id_value = last_id
119 | print("Last ID: " + str(last_id), "Computers found: " + str(num_found))
120 | print ("Return rate: {0} hosts/sec".format(num_found / (t1 - t0)))
121 | if num_found != page_size:
122 | print ("Num_found {0} - Page size is {1}".format(num_found, page_size))
123 |
124 | except api_exception as e:
125 | print ("Exception: {0}".format(str(e)))
126 |
127 | return paged_computers
128 |
129 | def _computers_tread(self, configuration, groupID):
130 | computersReturn = self._GetGroupComputers(configuration=configuration, groupID=groupID)
131 | self._lock.acquire()
132 | self._Computers.extend(computersReturn)
133 | self._lock.release()
134 |
135 | def _computers_tread_array(self, configuration, groups):
136 | computerGroup = {}
137 | while True:
138 | self._threadDataLock.acquire()
139 | if self._threadsGroups:
140 | computerGroup = self._threadsGroups.pop()
141 | self._threadDataLock.release()
142 | else:
143 | self._threadDataLock.release()
144 | return
145 |
146 | if computerGroup:
147 | self._computers_tread(configuration=configuration, groupID=computerGroup.id)
148 | else:
149 | return
150 |
151 | return
152 |
153 | def GetAllComputers(self):
154 | self._Groups = self.GetAllGroups(self._config)
155 | return self._GetAllComputers(self._config, self._Groups)
156 |
157 | def _GetAllComputers(self, configuration, groups):
158 | threads = []
159 | thread_data = {}
160 | self._threadsGroups = copy.copy(groups)
161 |
162 |
163 | t0 = time.time()
164 | # this starts a thread to collect all computers that do not belong to any group
165 | nonGroupcomputersThread = Thread(target=self._computers_tread, args=(configuration,None,))
166 | nonGroupcomputersThread.start()
167 |
168 | # Setup each thread
169 | for i in range(self._threadCount):
170 | threads.append(Thread(target=self._computers_tread_array, args=(configuration, None)))
171 | # Start each thread
172 | for i in range(self._threadCount):
173 | threads[i].start()
174 | #Wait for each thread
175 | for i in range(self._threadCount):
176 | threads[i].join()
177 | # if needed, wait for the nno-group thread to finish.
178 | nonGroupcomputersThread.join()
179 | t1 = time.time()
180 | # Give some total time/rate metrics.
181 | print ("Total time {0} seconds for a rate of {1}hosts/second".format(t1-t0, len(self._Computers)/(t1-t0)))
182 | return self._Groups,self._Computers
183 |
184 |
185 | def WriteToDisk(computers, groups):
186 | with open('computers.pkl', 'wb') as outfile:
187 | pickle.dump(computers, outfile)
188 | with open('rest_groups.pkl', 'wb') as outfile:
189 | pickle.dump(groups, outfile)
190 | return
191 |
192 |
193 | def ReadFromDisk():
194 | with open('rest_groups.pkl', 'rb') as infile:
195 | _Groups = pickle.load(infile)
196 | with open('computers.pkl', 'rb') as infile:
197 | _RestComputers = pickle.load(infile)
198 | return _Groups, _RestComputers
199 |
200 |
201 | def ConvertToHostLight(value):
202 | if value == "active":
203 | return "Managed"
204 | if value == "warning":
205 | return "Warning"
206 | if value == "error":
207 | return "Critical"
208 | if value == "inactive":
209 | return "Unmanaged"
210 | if value == "not-supported":
211 | return "Unmanaged"
212 | return "Unmanaged"
213 |
214 |
215 | def _getAmazonAccount(groupid, groups, _awsAccounts, _accountPattern):
216 | if groupid in _awsAccounts:
217 | return _awsAccounts[groupid]
218 |
219 | for g in groups:
220 | if g.id == groupid:
221 | if g.parent_group_id != None:
222 | cloudAccount = _getAmazonAccount(g.parent_group_id, groups, _awsAccounts, _accountPattern)
223 | _awsAccounts[g.id] = cloudAccount
224 | return cloudAccount
225 | if g.id in _awsAccounts:
226 | return _awsAccounts[g.name]
227 | _awsAccounts[g.id] = g.name
228 | return g.name
229 |
230 | return '0'
231 |
232 |
233 | def _convertTimeStamp(serverTime):
234 | if serverTime:
235 | t = datetime.datetime.fromtimestamp(serverTime / 1000).strftime('%Y-%m-%dT%H:%M:%S.%fZ')
236 | return t
237 | return " "
238 |
239 | def WriteCSV(pagedcomputers, groups):
240 | _awsAccounts = {}
241 | _accountPattern = re.compile("[0-9]{6,25}")
242 |
243 | with codecs.open(FILENAME, "w", "utf-8") as outfile:
244 | outfile.write(
245 | "AWS Instance Id,Computer Status,Status,amazon_account_id,displayName,host_name, Agent Version, Last Agent Communication\n")
246 | for computers in pagedcomputers:
247 | for restComputer in computers:
248 | try:
249 | account = _getAmazonAccount(restComputer.group_id,groups, _awsAccounts, _accountPattern)
250 | statusMessage = "{0}".format(restComputer.computer_status.agent_status_messages)
251 | statusMessage = statusMessage.replace(","," ")
252 | if restComputer.ec2_virtual_machine_summary:
253 | instanceid = restComputer.ec2_virtual_machine_summary.instance_id
254 | if instanceid is None:
255 | instanceid = "None"
256 | else:
257 | instanceid = "None"
258 |
259 | outfile.write("{0},{1},{2},{3},{4},{5}, {6}, {7}\n".format(
260 | instanceid,
261 | ConvertToHostLight(restComputer.computer_status.agent_status),
262 | statusMessage,
263 | account,
264 | restComputer.display_name,
265 | restComputer.host_name,
266 | restComputer.agent_version,
267 | _convertTimeStamp(restComputer.last_agent_communication)
268 | ))
269 | except Exception as err:
270 | print (err)
271 | return
272 |
273 |
274 |
275 | if __name__ == '__main__':
276 | if not API_KEY:
277 | raise ValueError('You must have "API_KEY" variable')
278 | # Add Deep Security Manager host information to the api client configuration
279 | configuration = api.Configuration()
280 | configuration.host = HOST
281 | configuration.verify_ssl = True
282 | # Authentication
283 | configuration.api_key['api-secret-key'] = API_KEY
284 |
285 | dsComputers = DeepSecurityComputers(configuration)
286 | groups,allComputers = dsComputers.GetAllComputers()
287 | WriteToDisk(allComputers, groups)
288 | # groups,allComputers = ReadFromDisk()
289 | WriteCSV(allComputers, groups)
290 |
291 | print "finished"
292 |
--------------------------------------------------------------------------------
/deepsecurity/manager-apis/python/listComputersParallelExpands.py:
--------------------------------------------------------------------------------
1 | import deepsecurity as api
2 | from deepsecurity.rest import ApiException as api_exception
3 | from deepsecurity.expand import Expand
4 | from threading import Thread
5 | from threading import Lock
6 | import copy
7 | import codecs
8 | import re
9 | import time
10 | import pickle
11 | import os
12 | import datetime
13 |
14 | # DSM Host & port (must end in /api)
15 | HOST = 'https://app.deepsecurity.trendmicro.com:443/api'
16 | # API Key from the DSM defined in an environment variable called "API_KEY"
17 | API_KEY = os.environ.get('API_KEY', None)
18 | # Output file
19 | FILENAME = 'report.csv'
20 | # API Version
21 | api_version = 'v1'
22 |
23 |
24 | class DeepSecurityComputers:
25 |
26 | def __init__(self, config):
27 | self._lock = Lock()
28 | self._threadDataLock = Lock()
29 | self._threadsGroups = []
30 | self._threadCount = 12
31 | self._Groups = None
32 | self._Computers = []
33 | self._config = config
34 |
35 |
36 |
37 | def GetAllGroups(self, configuration):
38 | # Set search criteria
39 | search_criteria = api.SearchCriteria()
40 | search_criteria.id_value = 0
41 | search_criteria.id_test = "greater-than"
42 | # Create a search filter with maximum returned items
43 | page_size = 5000
44 | search_filter = api.SearchFilter()
45 | search_filter.max_items = page_size
46 | search_filter.search_criteria = [search_criteria]
47 |
48 | groupsapi = api.ComputerGroupsApi(api.ApiClient(configuration))
49 |
50 | paged_groups = []
51 | try:
52 | while True:
53 | t0 = time.time()
54 | groups = groupsapi.search_computer_groups(api_version, search_filter=search_filter)
55 | t1 = time.time()
56 | num_found = len(groups.computer_groups)
57 | if num_found == 0:
58 | print("No groups found.")
59 | break
60 | paged_groups.extend(groups.computer_groups)
61 | # Get the ID of the last group in the page and return it with the number of groups on the page
62 | last_id = groups.computer_groups[-1].id
63 | search_criteria.id_value = last_id
64 | print("Last ID: " + str(last_id), "Groups found: " + str(num_found))
65 | print ("Return rate: {0} groups/sec".format(num_found / (t1 - t0)))
66 | if num_found != page_size:
67 | print ("Num_found {0} - Page size is {1}".format(num_found, page_size))
68 |
69 | except api_exception as e:
70 | return "Exception: " + str(e)
71 |
72 | return paged_groups
73 |
74 | def _GetGroupComputers(self, configuration, groupID):
75 |
76 | # Set search group criteria
77 | search_group_criteria = api.SearchCriteria()
78 | search_group_criteria.field_name = "groupID"
79 | if groupID:
80 | search_group_criteria.numeric_value = groupID
81 | search_group_criteria.numeric_test = "equal"
82 | else:
83 | search_group_criteria.null_test = True
84 |
85 | # Set search criteria
86 | search_criteria = api.SearchCriteria()
87 | search_criteria.id_value = 0
88 | search_criteria.id_test = "greater-than"
89 |
90 | # Create a search filter with maximum returned items
91 | page_size = 250
92 | search_filter = api.SearchFilter()
93 | search_filter.max_items = page_size
94 | search_filter.search_criteria = [search_criteria, search_group_criteria]
95 |
96 | # Perform the search and do work on the results
97 | computers_api = api.ComputersApi(api.ApiClient(configuration))
98 | paged_computers = []
99 | while True:
100 | try:
101 | expand = Expand(Expand.ec2_virtual_machine_summary)
102 | t0 = time.time()
103 | computers = computers_api.search_computers(api_version, search_filter=search_filter, expand=expand.list())
104 | t1 = time.time()
105 | num_found = len(computers.computers)
106 | current_paged_computers = []
107 |
108 | if num_found == 0:
109 | #This gets noise with so many threads
110 | #print("No computers found.")
111 | break
112 |
113 | for computer in computers.computers:
114 | current_paged_computers.append(computer)
115 |
116 | paged_computers.append(current_paged_computers)
117 |
118 | # Get the ID of the last computer in the page and return it with the number of computers on the page
119 | last_id = computers.computers[-1].id
120 | search_criteria.id_value = last_id
121 | print("Last ID: " + str(last_id), "Computers found: " + str(num_found))
122 | print ("Return rate: {0} hosts/sec".format(num_found / (t1 - t0)))
123 | if num_found != page_size:
124 | print ("Num_found {0} - Page size is {1}".format(num_found, page_size))
125 |
126 | except api_exception as e:
127 | print ("Exception: {0}".format(str(e)))
128 |
129 | return paged_computers
130 |
131 | def _computers_tread(self, configuration, groupID):
132 | computersReturn = self._GetGroupComputers(configuration=configuration, groupID=groupID)
133 | self._lock.acquire()
134 | self._Computers.extend(computersReturn)
135 | self._lock.release()
136 |
137 | def _computers_tread_array(self, configuration, groups):
138 | computerGroup = {}
139 | while True:
140 | self._threadDataLock.acquire()
141 | if self._threadsGroups:
142 | computerGroup = self._threadsGroups.pop()
143 | self._threadDataLock.release()
144 | else:
145 | self._threadDataLock.release()
146 | return
147 |
148 | if computerGroup:
149 | self._computers_tread(configuration=configuration, groupID=computerGroup.id)
150 | else:
151 | return
152 |
153 | return
154 |
155 | def GetAllComputers(self):
156 | self._Groups = self.GetAllGroups(self._config)
157 | return self._GetAllComputers(self._config, self._Groups)
158 |
159 | def _GetAllComputers(self, configuration, groups):
160 | threads = []
161 | thread_data = {}
162 | self._threadsGroups = copy.copy(groups)
163 |
164 |
165 | t0 = time.time()
166 | # this starts a thread to collect all computers that do not belong to any group
167 | nonGroupcomputersThread = Thread(target=self._computers_tread, args=(configuration,None,))
168 | nonGroupcomputersThread.start()
169 |
170 | # Setup each thread
171 | for i in range(self._threadCount):
172 | threads.append(Thread(target=self._computers_tread_array, args=(configuration, None)))
173 | # Start each thread
174 | for i in range(self._threadCount):
175 | threads[i].start()
176 | #Wait for each thread
177 | for i in range(self._threadCount):
178 | threads[i].join()
179 | # if needed, wait for the nno-group thread to finish.
180 | nonGroupcomputersThread.join()
181 | t1 = time.time()
182 | # Give some total time/rate metrics.
183 | print ("Total time {0} seconds for a rate of {1}hosts/second".format(t1-t0, len(self._Computers)/(t1-t0)))
184 | return self._Groups,self._Computers
185 |
186 |
187 | def WriteToDisk(computers, groups):
188 | with open('computers.pkl', 'wb') as outfile:
189 | pickle.dump(computers, outfile)
190 | with open('rest_groups.pkl', 'wb') as outfile:
191 | pickle.dump(groups, outfile)
192 | return
193 |
194 |
195 | def ReadFromDisk():
196 | with open('rest_groups.pkl', 'rb') as infile:
197 | _Groups = pickle.load(infile)
198 | with open('computers.pkl', 'rb') as infile:
199 | _RestComputers = pickle.load(infile)
200 | return _Groups, _RestComputers
201 |
202 |
203 | def ConvertToHostLight(value):
204 | if value == "active":
205 | return "Managed"
206 | if value == "warning":
207 | return "Warning"
208 | if value == "error":
209 | return "Critical"
210 | if value == "inactive":
211 | return "Unmanaged"
212 | if value == "not-supported":
213 | return "Unmanaged"
214 | return "Unmanaged"
215 |
216 |
217 | def _getAmazonAccount(groupid, groups, _awsAccounts, _accountPattern):
218 | if groupid in _awsAccounts:
219 | return _awsAccounts[groupid]
220 |
221 | for g in groups:
222 | if g.id == groupid:
223 | if g.parent_group_id != None:
224 | cloudAccount = _getAmazonAccount(g.parent_group_id, groups, _awsAccounts, _accountPattern)
225 | _awsAccounts[g.id] = cloudAccount
226 | return cloudAccount
227 | if g.id in _awsAccounts:
228 | return _awsAccounts[g.name]
229 | _awsAccounts[g.id] = g.name
230 | return g.name
231 |
232 | return '0'
233 |
234 |
235 | def _convertTimeStamp(serverTime):
236 | if serverTime:
237 | t = datetime.datetime.fromtimestamp(serverTime / 1000).strftime('%Y-%m-%dT%H:%M:%S.%fZ')
238 | return t
239 | return " "
240 |
241 | def WriteCSV(pagedcomputers, groups):
242 | _awsAccounts = {}
243 | _accountPattern = re.compile("[0-9]{6,25}")
244 |
245 | with codecs.open(FILENAME, "w", "utf-8") as outfile:
246 | outfile.write(
247 | "AWS Instance Id,Computer Status,Status,amazon_account_id,displayName,host_name, Agent Version, Last Agent Communication\n")
248 | for computers in pagedcomputers:
249 | for restComputer in computers:
250 | try:
251 | account = _getAmazonAccount(restComputer.group_id,groups, _awsAccounts, _accountPattern)
252 | statusMessage = "{0}".format(restComputer.computer_status.agent_status_messages)
253 | statusMessage = statusMessage.replace(","," ")
254 | if restComputer.ec2_virtual_machine_summary:
255 | instanceid = restComputer.ec2_virtual_machine_summary.instance_id
256 | if instanceid is None:
257 | instanceid = "None"
258 | else:
259 | instanceid = "None"
260 |
261 | outfile.write("{0},{1},{2},{3},{4},{5}, {6}, {7}\n".format(
262 | instanceid,
263 | ConvertToHostLight(restComputer.computer_status.agent_status),
264 | statusMessage,
265 | account,
266 | restComputer.display_name,
267 | restComputer.host_name,
268 | restComputer.agent_version,
269 | _convertTimeStamp(restComputer.last_agent_communication)
270 | ))
271 | except Exception as err:
272 | print (err)
273 | return
274 |
275 |
276 |
277 | if __name__ == '__main__':
278 | if not API_KEY:
279 | raise ValueError('You must have "API_KEY" variable')
280 | # Add Deep Security Manager host information to the api client configuration
281 | configuration = api.Configuration()
282 | configuration.host = HOST
283 | configuration.verify_ssl = True
284 | # Authentication
285 | configuration.api_key['api-secret-key'] = API_KEY
286 |
287 | dsComputers = DeepSecurityComputers(configuration)
288 | groups,allComputers = dsComputers.GetAllComputers()
289 | WriteToDisk(allComputers, groups)
290 | # groups,allComputers = ReadFromDisk()
291 | WriteCSV(allComputers, groups)
292 |
293 | print "finished"
294 |
--------------------------------------------------------------------------------
/deepsecurity/manager/EnableStrongCiphers.script:
--------------------------------------------------------------------------------
1 | // Copyright(C) 2018 Trend Micro Inc. All Rights Reserved.
2 | //
3 | // Alters the configuration.properties file to add strong ciphers as well as
4 | // disabling TLSv1 and TLSv1.1 for dsm communication and forces the relay to
5 | // communicate exclusively over TLS1.2 as well. To get desired effects must be
6 | // run with the newest version of 10.0 and 11.0 that changes the outbound
7 | // ciphers to include the strong ciphers as well.
8 |
9 | package src.main.java.com.trendmicro.ds.fixes;
10 |
11 | import java.io.BufferedReader;
12 | import java.io.BufferedWriter;
13 | import java.io.File;
14 | import java.io.FileInputStream;
15 | import java.io.FileOutputStream;
16 | import java.io.FileReader;
17 | import java.io.FileWriter;
18 | import java.io.InputStream;
19 | import java.io.InputStreamReader;
20 | import java.io.OutputStream;
21 | import java.io.PrintWriter;
22 | import java.lang.Process;
23 | import java.util.Hashtable;
24 | import java.util.Properties;
25 | import com.thirdbrigade.manager.core.db.SystemEvent;
26 | import com.thirdbrigade.manager.core.db.SystemEventPeer;
27 | import com.thirdbrigade.manager.core.db.SystemSetting;
28 | import com.thirdbrigade.manager.core.db.SystemSettingPeer;
29 | import com.thirdbrigade.manager.core.db.settings.ISettingInfo;
30 | import com.thirdbrigade.manager.core.db.settings.ISystemSettingInfo;
31 | import com.thirdbrigade.manager.core.db.settings.Settings;
32 | import com.thirdbrigade.manager.core.ManagerGlobals;
33 | import com.thirdbrigade.manager.core.Tenants;
34 | import com.thirdbrigade.persistence1.Criteria;
35 | import com.thirdbrigade.persistence1.PersistentPeer;
36 | import com.thirdbrigade.persistence1.Values;
37 | import com.thirdbrigade.persistence1.Where;
38 | import com.thirdbrigade.persistence1.xml.XMLWriter;
39 | import com.trendmicro.ds.platform.objects.mt.Context;
40 | import com.trendmicro.ds.platform.objects.mt.SystemContext;
41 | import com.trendmicro.ds.platform.objects.mt.TNConnection;
42 |
43 |
44 | import org.apache.commons.logging.Log;
45 | import org.apache.commons.logging.LogFactory;
46 |
47 | public static final Log log = LogFactory.getLog("EnableStrongCiphers");
48 | public static final String cipherSuites = "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, " +
49 | "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256";
50 | public static final String disabledProtocols = ", TLSv1, TLSv1.1";
51 | public static final String allowedProtocols = "TLSv1.2";
52 | public static boolean isDS10 = false;
53 |
54 |
55 | String jreFile;
56 | String confFile;
57 | String jreDir;
58 | String versionCommand;
59 | String version;
60 | String [] versionPts;
61 | String os = System.getProperty("os.name");
62 | String currentWorkingDirectory = System.getProperty("user.dir");
63 |
64 | log.info("Start script");
65 | log.info("Current Operating System: " + os);
66 | log.info("Current Working directory: " + currentWorkingDirectory);
67 |
68 | if (os.contains("Windows")) {
69 | jreDir = "jre\\lib\\security\\";
70 | versionCommand = "dsm_version";
71 | } else {
72 | jreDir = "jre/lib/security/";
73 | versionCommand = "./dsm_version";
74 | }
75 |
76 | confFile = "configuration.properties";
77 | jreFile = jreDir + "java.security";
78 |
79 | try {
80 | Process proc = Runtime.getRuntime().exec(versionCommand);
81 | BufferedReader stdIn = new BufferedReader(new InputStreamReader(proc.getInputStream()));
82 | version = stdIn.readLine();
83 | log.info("DSM version number: " + version);
84 | versionPts = version.split("\\.");
85 |
86 | //Support for TLS was added in 10.0U8 so we need to check that the dsm version is greater then or equal to that
87 | if (versionPts[0].equals("10") && versionPts[1].equals("0") && Integer.parseInt(versionPts[2]) >= 3367) {
88 | isDS10 = true;
89 | } else if(!versionPts[0].equals("11")) {
90 | throw new Exception("You must have 10U8 or higher in order to run this script");
91 | } else if(ManagerGlobals.isFIPSMode()){
92 | throw new Exception("You must disable FIPS mode before enabling strong ciphers");
93 | }
94 |
95 | //Adding the preferred cipher suites to configuration.properties
96 | Properties configuration = new Properties();
97 | InputStream input;
98 | OutputStream output;
99 |
100 | try {
101 | input = new java.io.FileInputStream(confFile);
102 | configuration.load(input);
103 | } catch (Exception e) {
104 | log.error("Failed reading from configurations.properties: " + e);
105 | } finally {
106 | if (input != null) {
107 | input.close();
108 | }
109 | }
110 |
111 | try {
112 | configuration.setProperty("ciphers", cipherSuites);
113 | configuration.setProperty("protocols", allowedProtocols);
114 | output = new FileOutputStream(confFile);
115 | configuration.store(output, null);
116 | } catch (Exception e) {
117 | log.error("Failed writing to configurations.properties: " + e);
118 | } finally {
119 | if (output != null) {
120 | output.close();
121 | }
122 | }
123 |
124 | //Disable old TLS protocols
125 | configuration = new java.util.Properties();
126 | String currentValue;
127 |
128 | try {
129 | input = new FileInputStream(jreFile);
130 |
131 | configuration.load(input);
132 | currentValue = configuration.getProperty("jdk.tls.disabledAlgorithms");
133 | } catch (Exception e) {
134 | log.error("Failed reading from jre: " + e);
135 | } finally {
136 | if (input != null) {
137 | input.close();
138 | }
139 | }
140 |
141 | if (!currentValue.contains(disabledProtocols)) {
142 | try {
143 | configuration.setProperty("jdk.tls.disabledAlgorithms", currentValue + disabledProtocols);
144 | output = new FileOutputStream(jreFile);
145 | configuration.store(output, null);
146 | } catch (Exception e) {
147 | log.error("Failed writing to jre: " + e);
148 | } finally {
149 | if (output != null) {
150 | output.close();
151 | }
152 | }
153 | }
154 |
155 | try {
156 | SystemContext context = Tenants.getT0SystemContext();
157 | if(context == null){
158 | throw new Exception("No context received");
159 | }
160 | } catch (Exception e){
161 | log.error("Do not have the permission to alter system variables: " + e);
162 | }
163 |
164 | //Changing the minimum TLS protocol to communicate with the relay to TLSv1.2
165 | Class targetType = null;
166 | Long targetID = null;
167 | String targetName = null;
168 |
169 | TNConnection connection = null;
170 | try {
171 | connection = context.beginConnection();
172 |
173 | XMLWriter xmlWriter = new XMLWriter();
174 | xmlWriter.writeStartElement(SystemSetting.class.getSimpleName() + "s");
175 | Hashtable map = SystemSetting.getSettingInfoMap();
176 |
177 | String value = "TLSv1.2";
178 | ISettingInfo info = map.get("settings.configuration.restrictRelayMinimumTLSProtocol");
179 | Settings.saveSystemSetting((ISystemSettingInfo) info, value, xmlWriter, connection);
180 |
181 | if(!isDS10){
182 | info = map.get("settings.configuration.MinimumTLSProtocolNewNode");
183 | Settings.saveSystemSetting((ISystemSettingInfo) info, value, xmlWriter, connection);
184 | }
185 |
186 | value = "true";
187 | info = map.get("settings.configuration.enableStrongCiphers");
188 | Settings.saveSystemSetting((ISystemSettingInfo) info, value, xmlWriter, connection);
189 |
190 | xmlWriter.writeEndElement();
191 |
192 | SystemEventPeer.saveEvent(targetType, targetID, targetName, SystemEvent.Type.SYSTEM_SETTINGS_SAVED, xmlWriter.toString(), connection);
193 | } catch (Exception e) {
194 | log.error("Failed to change setting: " + e);
195 | } finally {
196 | connection.close();
197 | }
198 | }catch(Exception e) {
199 | log.error("Failed DSM version check:" + e);
200 | }
201 |
202 |
203 | log.info("Finished script");
204 |
--------------------------------------------------------------------------------
/deepsecurity/manager/EnableStrongCiphers12.script:
--------------------------------------------------------------------------------
1 | // Copyright(C) 2019 Trend Micro Inc. All Rights Reserved.
2 | //
3 | // Alters the configuration.properties file to add strong ciphers as well as
4 | // disabling TLSv1 and TLSv1.1 for dsm communication and forces the relay to
5 | // communicate exclusively over TLS1.2 as well. To get desired effects must be
6 | // run with 12.0+ on your Deep Security Manager, Deep Security Relay and
7 | // Deep Security Agent.
8 |
9 | package src.main.java.com.trendmicro.ds.fixes;
10 |
11 | import java.io.BufferedReader;
12 | import java.io.BufferedWriter;
13 | import java.io.File;
14 | import java.io.FileInputStream;
15 | import java.io.FileOutputStream;
16 | import java.io.FileReader;
17 | import java.io.FileWriter;
18 | import java.io.InputStream;
19 | import java.io.InputStreamReader;
20 | import java.io.OutputStream;
21 | import java.io.PrintWriter;
22 | import java.lang.Process;
23 | import java.util.Hashtable;
24 | import java.util.Properties;
25 | import com.thirdbrigade.manager.core.db.SystemEvent;
26 | import com.thirdbrigade.manager.core.db.SystemEventPeer;
27 | import com.thirdbrigade.manager.core.db.SystemSetting;
28 | import com.thirdbrigade.manager.core.db.SystemSettingPeer;
29 | import com.thirdbrigade.manager.core.db.settings.ISettingInfo;
30 | import com.thirdbrigade.manager.core.db.settings.ISystemSettingInfo;
31 | import com.thirdbrigade.manager.core.db.settings.Settings;
32 | import com.thirdbrigade.manager.core.ManagerGlobals;
33 | import com.thirdbrigade.manager.core.Tenants;
34 | import com.thirdbrigade.persistence1.Criteria;
35 | import com.thirdbrigade.persistence1.PersistentPeer;
36 | import com.thirdbrigade.persistence1.Values;
37 | import com.thirdbrigade.persistence1.Where;
38 | import com.trendmicro.ds.platform.objects.mt.Context;
39 | import com.trendmicro.ds.platform.objects.mt.SystemContext;
40 | import com.trendmicro.ds.platform.objects.mt.TNConnection;
41 | import com.trendmicro.ds.utils.io.XMLWriter;
42 |
43 |
44 | import org.apache.commons.logging.Log;
45 | import org.apache.commons.logging.LogFactory;
46 |
47 | public static final Log log = LogFactory.getLog("EnableStrongCiphers");
48 | public static final String cipherSuites = "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256";
49 | public static final String disabledProtocols = ", TLSv1, TLSv1.1";
50 | public static final String allowedProtocols = "TLSv1.2";
51 | public static boolean isDS10 = false;
52 |
53 |
54 | String jreFile;
55 | String confFile;
56 | String jreDir;
57 | String versionCommand;
58 | String version;
59 | String [] versionPts;
60 | String os = System.getProperty("os.name");
61 | String currentWorkingDirectory = System.getProperty("user.dir");
62 |
63 | log.info("Start script");
64 | log.info("Current Operating System: " + os);
65 | log.info("Current Working directory: " + currentWorkingDirectory);
66 |
67 | if (os.contains("Windows")) {
68 | jreDir = "jre\\lib\\security\\";
69 | versionCommand = "dsm_version";
70 | } else {
71 | jreDir = "jre/lib/security/";
72 | versionCommand = "./dsm_version";
73 | }
74 |
75 | confFile = "configuration.properties";
76 | jreFile = jreDir + "java.security";
77 |
78 | try {
79 | Process proc = Runtime.getRuntime().exec(versionCommand);
80 | BufferedReader stdIn = new BufferedReader(new InputStreamReader(proc.getInputStream()));
81 | version = stdIn.readLine();
82 | log.info("DSM version number: " + version);
83 | versionPts = version.split("\\.");
84 |
85 | //Support for TLS was added in 10.0U8 so we need to check that the dsm version is greater then or equal to that
86 | if(Integer.valueOf(versionPts[0]) < 12) {
87 | throw new Exception("You must have 12 or higher in order to run this script");
88 | } else if(ManagerGlobals.isFIPSMode()){
89 | throw new Exception("You must disable FIPS mode before enabling strong ciphers");
90 | }
91 |
92 | //Adding the preferred cipher suites to configuration.properties
93 | Properties configuration = new Properties();
94 | InputStream input;
95 | OutputStream output;
96 |
97 | try {
98 | input = new java.io.FileInputStream(confFile);
99 | configuration.load(input);
100 | } catch (Exception e) {
101 | log.error("Failed reading from configurations.properties: " + e);
102 | } finally {
103 | if (input != null) {
104 | input.close();
105 | }
106 | }
107 |
108 | try {
109 | configuration.setProperty("ciphers", cipherSuites);
110 | configuration.setProperty("protocols", allowedProtocols);
111 | output = new FileOutputStream(confFile);
112 | configuration.store(output, null);
113 | } catch (Exception e) {
114 | log.error("Failed writing to configurations.properties: " + e);
115 | } finally {
116 | if (output != null) {
117 | output.close();
118 | }
119 | }
120 |
121 | //Disable old TLS protocols
122 | configuration = new java.util.Properties();
123 | String currentValue;
124 |
125 | try {
126 | input = new FileInputStream(jreFile);
127 |
128 | configuration.load(input);
129 | currentValue = configuration.getProperty("jdk.tls.disabledAlgorithms");
130 | } catch (Exception e) {
131 | log.error("Failed reading from jre: " + e);
132 | } finally {
133 | if (input != null) {
134 | input.close();
135 | }
136 | }
137 |
138 | if (!currentValue.contains(disabledProtocols)) {
139 | try {
140 | configuration.setProperty("jdk.tls.disabledAlgorithms", currentValue + disabledProtocols);
141 | output = new FileOutputStream(jreFile);
142 | configuration.store(output, null);
143 | } catch (Exception e) {
144 | log.error("Failed writing to jre: " + e);
145 | } finally {
146 | if (output != null) {
147 | output.close();
148 | }
149 | }
150 | }
151 |
152 | try {
153 | SystemContext context = Tenants.getT0SystemContext();
154 | if(context == null){
155 | throw new Exception("No context received");
156 | }
157 | } catch (Exception e){
158 | log.error("Do not have the permission to alter system variables: " + e);
159 | }
160 |
161 | //Changing the minimum TLS protocol to communicate with the relay to TLSv1.2
162 | Class targetType = null;
163 | Long targetID = null;
164 | String targetName = null;
165 |
166 | TNConnection connection = null;
167 | try {
168 | connection = context.beginConnection();
169 |
170 | XMLWriter xmlWriter = new XMLWriter();
171 | xmlWriter.writeStartElement(SystemSetting.class.getSimpleName() + "s");
172 | Hashtable map = SystemSetting.getSettingInfoMap();
173 |
174 | String value = "TLSv1.2";
175 | ISettingInfo info = map.get("settings.configuration.restrictRelayMinimumTLSProtocol");
176 | Settings.saveSystemSetting((ISystemSettingInfo) info, value, xmlWriter, connection);
177 |
178 | if(!isDS10){
179 | info = map.get("settings.configuration.MinimumTLSProtocolNewNode");
180 | Settings.saveSystemSetting((ISystemSettingInfo) info, value, xmlWriter, connection);
181 | }
182 |
183 | value = "true";
184 | info = map.get("settings.configuration.enableStrongCiphers");
185 | Settings.saveSystemSetting((ISystemSettingInfo) info, value, xmlWriter, connection);
186 |
187 | xmlWriter.writeEndElement();
188 |
189 | SystemEventPeer.saveEvent(targetType, targetID, targetName, SystemEvent.Type.SYSTEM_SETTINGS_SAVED, xmlWriter.toString(), connection);
190 | } catch (Exception e) {
191 | log.error("Failed to change setting: " + e);
192 | } finally {
193 | connection.close();
194 | }
195 | }catch(Exception e) {
196 | log.error("Failed DSM version check:" + e);
197 | }
198 |
199 |
200 | log.info("Finished script");
201 |
--------------------------------------------------------------------------------
/deepsecurity/manager/README.md:
--------------------------------------------------------------------------------
1 | # Fast DSM
2 |
3 | The Fast DSM is designed to quickly and easily create a Trend Micro Deep Security Manager and database for POC or demo purposes. This script leverages Docker to a deploy the DSM manager and a Postgres database.
4 |
5 | Please note that this is **NOT** intended to protect a persistent and environment and should only be used as a temporary setup and is not officially supported.
6 |
7 | ## Getting Started
8 |
9 | The Fast DSM will require that you launch and EC2 instance. See the Prerequisties below for more details.
10 |
11 | ### Prerequisites
12 |
13 | EC2 Instance Requirements
14 |
15 | ```
16 | Red Hat Enterprise Linux 7 Operating System
17 | Min of 2 CPU and 8 GB RAM
18 | Min 30 GB of space in the root filesystem, 50 recommended
19 | Instance will need access to the internet
20 | Security groups: inbound access for 4118-4122 and 443
21 | ```
22 |
23 | ### Installing
24 |
25 | * Copy the awsFastDsm.sh script into your EC2 instance and execute it as root.
26 | * Once it's finished installing, open your web browswer and go to the instance's IP address using https.
27 | ```
28 | Default login is MasterAdmin and the Password is Password123!
29 | ```
30 | * Please change your MasterAdmin password after install.
31 |
32 | ## Running the DSM
33 |
34 | At this point your DSM should be up and running. In order to test it, you will need to add a license key under Administration > Licenses. You can then activate computers and being testing the modules.
35 |
36 |
37 | ## More Info
38 |
39 | If you need any additional information or want to learn more about the product, please visit our [Help Center.](http://help.deepsecurity.trendmicro.com/)
40 |
41 |
42 |
--------------------------------------------------------------------------------
/deepsecurity/manager/awsFastDsm.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | databasePassword='Password123!'
3 | activationCode=${1}
4 | dsmUser=${2}
5 | dsmPassword=${3}
6 | dsmMajorVersion="12.5"
7 | dsmMinorVersion="855"
8 | dsmVersion="$dsmMajorVersion.$dsmMinorVersion"
9 | downloadUrl="https://files.trendmicro.com"
10 |
11 | download(){
12 | until curl -f $@ ;
13 | do
14 | sleep 1
15 | done
16 | }
17 | if ! [ $(id -u) = 0 ]; then
18 | echo "This script must be run as root"
19 | exit 1
20 | fi
21 |
22 | # setup dir
23 | mkdir -p /opt/fastdsm/
24 | cd /opt/fastdsm/
25 |
26 | echo "$(date) -- Installing Docker Dependencies"
27 |
28 | #Docker dependencies
29 | yum install -y yum-utils \
30 | device-mapper-persistent-data \
31 | lvm2
32 |
33 | #Detect OS version for Extra repo enablement
34 | echo "$(date) -- Detecting OS and installing Docker"
35 |
36 | OS=`cat /etc/system-release`
37 | echo "${OS}"
38 | if [[ "${OS}" == *"7.6"* ]] ; then
39 | echo "setting up repos and installing docker for RHEL 7.6"
40 | yum-config-manager --enable rhui-REGION-rhel-server-extras
41 | yum install -y container-selinux
42 | yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
43 | yum -y install docker-ce
44 | elif [[ "${OS}" == *"7.7"* ]] ; then
45 | echo "setting up repos and installing docker for RHEL 7.7"
46 | yum-config-manager --enable rhui-rhel-7-server-rhui-extras-rpms
47 | yum install -y container-selinux
48 | yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
49 | yum -y install docker-ce
50 | elif [[ "${OS}" == *"7.8"* ]] ; then
51 | echo "setting up repos and installing docker for RHEL 7.8"
52 | yum-config-manager --enable rhel-7-server-rhui-extras-rpms
53 | yum install -y container-selinux
54 | yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
55 | yum -y install docker-ce
56 | elif [[ "${OS}" == *"Amazon"* ]] ; then
57 | echo "Installing docker for Amazon Linux 1, repos already available"
58 | yum -y install docker
59 | else echo "Platform not supported for install"
60 | fi
61 |
62 | #Download proper installer per OS
63 | if [[ "${OS}" == *"7.6"* || "${OS}" == *"7.7"* || "${OS}" == *"7.8"* ]] ; then
64 | managerInstaller="$downloadUrl/products/deepsecurity/en/$dsmMajorVersion/Manager-Linux-$dsmVersion.x64.sh"
65 | download ${managerInstaller} -o Manager-Linux.sh
66 | elif [[ "${OS}" == *"Amazon"* ]] ; then
67 | activationCode=""
68 | managerInstaller="$downloadUrl/products/deepsecurity/en/$dsmMajorVersion/Manager-AWS_Marketplace_Upgrade-$dsmVersion.x64.zip"
69 | curl ${managerInstaller} -o Manager-Amazon-Linux.zip
70 | mkdir /opt/fastdsm/amazonlinux
71 | unzip ./Manager-Amazon-Linux.zip -d /opt/fastdsm/amazonlinux
72 | mv /opt/fastdsm/amazonlinux/Manager-AWS-$dsmVersion.x64.sh /opt/fastdsm/Manager-Linux.sh
73 | rm -rf /opt/fastdsm/amazonlinux
74 | else echo "Platform not supported"
75 | fi
76 |
77 | service docker start
78 |
79 | echo "$(date) -- creating pgsql container for dsmdb"
80 | docker pull postgres:9
81 | docker run --name dsmpgsqldb -p 5432:5432 -e "POSTGRES_PASSWORD=${databasePassword}" -e POSTGRES_DB=dsm -d postgres:9
82 | echo "$(date) -- creating database in sql instance"
83 |
84 | # persist db across restart
85 | echo "$(date) -- creating service config to persiste db instance"
86 | download https://s3.amazonaws.com/424d57/fastDsm/docker-dsmdb -o /etc/init.d/docker-dsmdb
87 | chmod 755 /etc/init.d/docker-dsmdb
88 | chkconfig --add docker-dsmdb
89 | chkconfig docker-dsmdb on
90 | chkconfig --add docker
91 | chkconfig docker on
92 |
93 |
94 | # get ds files
95 | echo "$(date) -- downloading agent installers"
96 | download -O "https://files.trendmicro.com/products/deepsecurity/en/12.5/Agent-amzn1-12.5.0-814.x86_64.zip"
97 | download -O "http://files.trendmicro.com/products/deepsecurity/en/12.5/KernelSupport-amzn1-12.5.0-775.x86_64.zip"
98 | download -O "https://files.trendmicro.com/products/deepsecurity/en/12.5/Agent-amzn2-12.5.0-814.x86_64.zip"
99 | download -O "http://files.trendmicro.com/products/deepsecurity/en/12.5/KernelSupport-amzn2-12.5.0-827.x86_64.zip"
100 | download -O "https://files.trendmicro.com/products/deepsecurity/en/12.5/Agent-RedHat_EL7-12.5.0-814.x86_64.zip"
101 | download -O "http://files.trendmicro.com/products/deepsecurity/en/12.5/KernelSupport-RedHat_EL7-12.5.0-823.x86_64.zip"
102 | download -O "https://files.trendmicro.com/products/deepsecurity/en/12.5/Agent-RedHat_EL6-12.5.0-814.x86_64.zip"
103 | download -O "http://files.trendmicro.com/products/deepsecurity/en/12.5/KernelSupport-RedHat_EL6-12.5.0-816.x86_64.zip"
104 | download -O "https://files.trendmicro.com/products/deepsecurity/en/12.5/Agent-Windows-12.5.0-713.x86_64.zip"
105 | download -O "http://files.trendmicro.com/products/deepsecurity/en/12.0/KernelSupport-Ubuntu_18.04-12.0.0-522.x86_64.zip"
106 | download -O "https://files.trendmicro.com/products/deepsecurity/en/12.0/Agent-Ubuntu_18.04-12.0.0-481.x86_64.zip"
107 | download -O "https://files.trendmicro.com/products/deepsecurity/en/12.5/Agent-RedHat_EL8-12.5.0-814.x86_64.zip"
108 | download -O "http://files.trendmicro.com/products/deepsecurity/en/12.5/KernelSupport-RedHat_EL8-12.5.0-901.x86_64.zip"
109 |
110 | # make a properties file
111 | echo "$(date) -- creating dsm properties file"
112 | echo "AddressAndPortsScreen.ManagerPort=443" >> dsm.props
113 | echo "AddressAndPortsScreen.HeartbeatPort=4120" >> dsm.props
114 | echo "AddressAndPortsScreen.ManagerAddress=$(curl http://169.254.169.254/latest/meta-data/local-ipv4)" >> dsm.props
115 | echo "CredentialsScreen.Administrator.Username=${dsmUser}" >> dsm.props
116 | echo "CredentialsScreen.UseStrongPasswords=False" >> dsm.props
117 | echo "CredentialsScreen.Administrator.Password=${dsmPassword}" >> dsm.props
118 | echo "SecurityUpdatesScreen.UpdateComponents=True" >> dsm.props
119 | echo "DatabaseScreen.DatabaseType=PostgreSQL" >> dsm.props
120 | echo "DatabaseScreen.Hostname=localhost:5432" >> dsm.props
121 | echo "DatabaseScreen.Username=postgres" >> dsm.props
122 | echo "DatabaseScreen.Password=${databasePassword}" >> dsm.props
123 | echo "DatabaseScreen.DatabaseName=dsm" >> dsm.props
124 | echo "SecurityUpdateScreen.UpdateComponents=true" >> dsm.props
125 | echo "SecurityUpdateScreen.UpdateSoftware=true" >> dsm.props
126 | echo "SmartProtectionNetworkScreen.EnableFeedback=false" >> dsm.props
127 | echo "SmartProtectionNetworkScreen.IndustryType=blank" >> dsm.props
128 | echo "RelayScreen.Install=True" >> dsm.props
129 | echo "RelayScreen.AntiMalware=True" >> dsm.props
130 | echo "Override.Automation=True" >> dsm.props
131 | echo "LicenseScreen.License.-1=${activationCode}" >> dsm.props
132 |
133 | # install manager
134 | echo "$(date) -- installing manager"
135 | chmod 755 Manager-Linux.sh
136 | ./Manager-Linux.sh -q -console -varfile dsm.props
137 | if [ $? -ne 0 ]; then
138 | echo "$(date) -- manager install FAILED"
139 | cat /opt/fastdsm/DeepSecurityInstallerReport.csv
140 | exit -1
141 | fi
142 | echo "$(date) -- manager install complete"
143 | chkconfig dsm_s on
144 |
145 | # customize dsm
146 | yum -y install perl-XML-Twig
147 | echo "$(date) -- starting manager customization"
148 | curl -O https://s3.amazonaws.com/trend-micro-quick-start/v5.1/Common/Scripts/set-aia-settings.sh
149 | chmod 755 set-aia-settings.sh
150 | curl -O https://s3.amazonaws.com/trend-micro-quick-start/v3.7/Common/Scripts/set-lbSettings
151 | chmod 755 set-lbSettings
152 | curl -O https://raw.githubusercontent.com/deep-security/ops-tools/master/deepsecurity/manager-apis/bash/ds10-rest-cloudAccountCreateWithInstanceRole.sh
153 | chmod 755 ds10-rest-cloudAccountCreateWithInstanceRole.sh
154 | curl https://s3.amazonaws.com/trend-micro-quick-start/v5.2/Common/Scripts/dsm_s.service -o /etc/systemd/system/dsm_s.service
155 | chmod 755 /etc/systemd/system/dsm_s.service
156 |
157 |
158 | echo "$(date) -- waiting for manager startup to complete"
159 | until curl -vk https://127.0.0.1:443/rest/status/manager/current/ping; do echo \"manager not started yet\" >> /tmp/4-check-service; service dsm_s start >> /tmp/4-check-service; sleep 30; done
160 | echo "$(date) -- manager startup complete. continuing with API call customizations"
161 | ./set-aia-settings.sh ${dsmUser} ${dsmPassword} localhost 443
162 | name=$(curl http://169.254.169.254/latest/meta-data/public-hostname)
163 | if [ -z ${name} ]; then name=$(curl http://169.254.169.254/latest/meta-data/public-ipv4); fi
164 | ./set-lbSettings ${dsmUser} ${dsmPassword} ${name} 443 4120
165 | ./ds10-rest-cloudAccountCreateWithInstanceRole.sh ${dsmUser} ${dsmPassword} localhost 443
166 |
167 | echo "$(date) -- completed manager customizations"
--------------------------------------------------------------------------------
/deepsecurity/manager/azure/SetupAzureForConnector.ps1:
--------------------------------------------------------------------------------
1 | <#
2 | .SYNOPSIS
3 | Powershel script to setup an azure account for a cloud connector.
4 | .DESCRIPTION
5 | This script creates an App regestration and service principal for a Trend Micro Azure cloud connector.
6 | This script outputs json that works with the addAzureConnector.py script to add the connector to the DSM.
7 | #>
8 |
9 | #Name of the connector in Azure
10 | $appName = "Deep Security Azure Connector"
11 | #Password is 32 long
12 | Add-Type -AssemblyName System.Web
13 | $password = [System.Web.Security.Membership]::GeneratePassword(32,0)
14 |
15 |
16 | $psadCredential = New-Object Microsoft.Azure.Graph.RBAC.Version1_6.ActiveDirectory.PSADPasswordCredential
17 | $startDate = Get-Date
18 | $psadCredential.StartDate = $startDate
19 | $psadCredential.EndDate = $startDate.AddYears(10)
20 | $psadCredential.KeyId = [guid]::NewGuid()
21 | $psadCredential.Password = $password
22 |
23 | #If you need to login to a specific subscription otherwise just login
24 | #$c = Login-AzureRmAccount -SubscriptionId "b0ba4069-ce0a-4f1f-c623-711faae9620b"
25 | $c = Login-AzureRmAccount
26 |
27 | #Create the new application regestration
28 | $d = New-AzureRmADApplication -DisplayName $appName -HomePage "http://www.trendmicro.com" -IdentifierUris "http://NewApplication" -PasswordCredentials $psadCredential
29 | #Create the new service principal
30 | $f = New-AzureRmADServicePrincipal -ApplicationId $d.ApplicationId
31 | #Useful to debug
32 | #$f
33 | #Assign the new service princiapl rights to read from the Azure account
34 | $t = New-AzureRmRoleAssignment -RoleDefinitionName "Reader" -ServicePrincipalName $d.ApplicationId
35 | #Useful to debug
36 | #$t
37 |
38 |
39 | #Build the output to match what is expected in Deep Security API for createing the connector.
40 | $outputObject = New-Object -TypeName psobject
41 | #This will be the name of the connector in Deep Security.
42 | $outputObject | Add-Member -MemberType NoteProperty -Name name -Value $c.Context.Account.Id
43 | $outputObject | Add-Member -MemberType NoteProperty -Name cloudType -Value "AZURE_ARM"
44 | $outputObject | Add-Member -MemberType NoteProperty -Name subscriptionId -Value $c.Context.Subscription.SubscriptionId
45 | $outputObject | Add-Member -MemberType NoteProperty -Name subscriptionName -Value $c.Context.Subscription.Name
46 | $outputObject | Add-Member -MemberType NoteProperty -Name azureAdTenantId -Value $c.Context.Tenant.TenantId
47 | $outputObject | Add-Member -MemberType NoteProperty -Name azureAdTenantName -Value $c.Context.Tenant.Directory
48 | $outputObject | Add-Member -MemberType NoteProperty -Name azureAdApplicationId -Value $d.ApplicationId
49 | $outputObject | Add-Member -MemberType NoteProperty -Name azureAdApplicationName -Value $appName
50 | $outputObject | Add-Member -MemberType NoteProperty -Name azureAdApplicationPassword -Value $password
51 |
52 | $outputObject | ConvertTo-Json
53 |
--------------------------------------------------------------------------------
/deepsecurity/manager/azure/addAzureConnector.py:
--------------------------------------------------------------------------------
1 | import urllib3
2 | import json
3 | import certifi
4 | import sys
5 | import os
6 |
7 | class DeepSecurityRestApi:
8 | def __init__(self, config):
9 | self._config = config
10 | self._url = "https://{0}:{1}/rest".format(self._config["hostname"], self._config["port"])
11 | self._http = urllib3.PoolManager(cert_reqs='CERT_NONE', ca_certs=certifi.where(), assert_hostname=False)
12 | self._sID = ""
13 | self._headers = { 'Content-Type': 'application/json',
14 | 'Accept': 'application/json'}
15 |
16 | def PostRequest (self, uri, body):
17 | requestURL = self._url + uri
18 | requestHeaers = self._headers
19 | if self._sID:
20 | requestHeaers.add( 'Cookie: sID=' + self._sID)
21 | r = self._http.request( 'POST',
22 | requestURL,
23 | body=body,
24 | headers=requestHeaers)
25 | return json.loads(r.data.decode('utf-8'))['data']
26 |
27 | def GetReuqest(self, uri):
28 | requestURL = self._url + uri
29 | requestHeaers = self._headers
30 | if self._sID:
31 | requestHeaers.add('Cookie: sID=' + self._sID)
32 | r = self._http.request('GET',
33 | requestURL,
34 | headers=requestHeaers)
35 | return json.loads(r.data.decode('utf-8'))['data']
36 |
37 | def Logout(self):
38 | requestURL = self._url + '/authentication/logout'
39 | requestHeaers = self._headers
40 |
41 | r = self._http.request('DELETE', requestURL, fields={'sID' : self._sID},headers=requestHeaers)
42 | if r.status == 200:
43 | self._sID =""
44 | else:
45 | print("Failed to logout with error status: {0} and return {1} ".format(r.status, r.data))
46 | return
47 |
48 | def Authentiate(self, username, password, tenantName):
49 | requestURL = self._url + '/authentication/login'
50 | requestHeaers = self._headers
51 |
52 | if tenantName:
53 | AuthJson = {
54 | "dsCredentials": {
55 | "userName": username,
56 | "password": password,
57 | "tenantName": tenantName
58 | }
59 | }
60 | else:
61 | AuthJson = {
62 | "dsCredentials": {
63 | "userName": username,
64 | "password": password
65 | }
66 | }
67 | jsoon_string = json.dumps(AuthJson)
68 | r = self._http.request('POST', requestURL, body=jsoon_string, headers=requestHeaers)
69 | if r.status == 200:
70 | self._sID = r.data.decode("utf-8")
71 | else:
72 | print("Failed to authenticate with error status: {0} and return {1} ".format(r.status, r.data) )
73 | return
74 |
75 | def AddAzureFromFile(self, filename):
76 | with open(filename) as json_file:
77 | data = json.load(json_file)
78 | requestURL = self._url + '/cloudaccounts'
79 | requestHeaers = self._headers
80 | AzureConnector = {
81 | "createCloudAccountRequest": {
82 | "cloudAccountElement": {
83 | "name": data["name"],
84 | "cloudType": "AZURE_ARM",
85 | "subscriptionId": data["subscriptionId"],
86 | "subscriptionName": data["subscriptionName"],
87 | "azureAdTenantId": data["azureAdTenantId"],
88 | "azureAdTenantName": data["azureAdTenantName"],
89 | "azureAdApplicationId": data["azureAdApplicationId"],
90 | "azureAdApplicationName": data["azureAdApplicationName"],
91 | "azureAdApplicationPassword": data["azureAdApplicationPassword"]
92 | },
93 | "sessionId": self._sID
94 | }
95 | }
96 | jsoon_string = json.dumps(AzureConnector)
97 | print(jsoon_string)
98 | r = self._http.request('POST', requestURL, body=jsoon_string, headers=requestHeaers)
99 | if r.status == 200:
100 | self._sID = r.data
101 | else:
102 | print("Failed to authenticate with error status: {0} and return {1} ".format(r.status, r.data))
103 |
104 | return
105 |
106 |
107 |
108 | if __name__ == '__main__':
109 |
110 | config = { "hostname" : "localhost",
111 | "port": "443",
112 | }
113 | if len(sys.argv) != 2:
114 | print("Usage: addAzureConnector.py ")
115 | exit(0)
116 |
117 | dsRest = DeepSecurityRestApi(config=config)
118 | dsRest.Authentiate(username= os.environ.get('username', None), password=os.environ.get('password', None), tenantName="")
119 | dsRest.AddAzureFromFile(sys.argv[1])
120 | dsRest.Logout()
121 |
--------------------------------------------------------------------------------
/deepsecurity/manager/azure/readme.md:
--------------------------------------------------------------------------------
1 |
2 | # Azure Support
3 |
4 | ## Azure Connector
5 | To help make the Azure connector easy in Deep Security you can run the SetupAzureForConnector.ps1 powershell script to setup Azure side. It will create an app registration and service princaple in Azure and then output a json secion. This json is then consumed by the python script, addAzureConnector.py, to create the connection in the DSM.
6 |
7 | ## Example
8 |
9 | 1) Run the powershell script to create the app regestration. After a sucessful run you will get a json output.
10 | ~~~~JSON
11 | {
12 | "name": "My Azure Account",
13 | "cloudType": "AZURE_ARM",
14 | "subscriptionId": "24be60c9-e19a-4faf-9623-6b140a29620b",
15 | "subscriptionName": "Pay-As-You-Go",
16 | "azureAdTenantId": "d3e340ca-98bf-4dbf-9586-506a71f8d53c",
17 | "azureAdTenantName": "My Teant",
18 | "azureAdApplicationId": "164a6d85-9a55-4e19-84ba-54ec41040ac4",
19 | "azureAdApplicationName": "Deep Security Azure Connector",
20 | "azureAdApplicationPassword": "k7t|.-AE/Mqm3bn^2mdgFf\u003eQVm$|fz\u003eR"
21 | }
22 |
23 | ~~~~
24 | 2) Next Send the json output to the Deep Security administrator.
25 | The Deep Security administrator will then put the json into a file and call the python script. Note the python script requires a username/password (not an API key) and these values are set in environment variables "username" and "password"
26 |
27 | ~~~~bash
28 | python addAzureConnector.py account.json
29 | ~~~~
30 | 3) Verify the connector syncs correclty in the DSM.
--------------------------------------------------------------------------------
/deepsecurity/manager/docker-dsmdb:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | # chkconfig: 345 98 02
3 | # description: dsmdb in container
4 |
5 | ### BEGIN INIT INFO
6 | # Provides: docker-dsmdb
7 | # Required-Start: docker
8 | # Required-Stop:
9 | # Should-Start:
10 | # Should-Stop:
11 | # X-Start-Before: dsm_s
12 | # Default-Start: 3 4 5
13 | # Default-Stop: 0 1 6
14 | # Short-Description: start and stop dsm database container
15 | ### END INIT INFO
16 |
17 | # Source function library.
18 | . /etc/rc.d/init.d/functions
19 |
20 | start() {
21 | /usr/bin/docker start dsmpgsqldb
22 | }
23 |
24 | status() {
25 | /usr/bin/docker ps -a -f "name=dsmpgsqldb"
26 | }
27 |
28 | stop() {
29 | /usr/bin/docker stop dsmpgsqldb
30 | }
31 |
32 |
33 | case "$1" in
34 | start)
35 | start
36 | ;;
37 | stop)
38 | stop
39 | ;;
40 | status)
41 | status
42 | ;;
43 | esac
44 |
45 | exit $?
46 |
--------------------------------------------------------------------------------
/deepsecurity/manager/gcpFastDsm.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | dbpw='Password123!'
3 | dsmuser=MasterAdmin
4 | dsmpw='Password123!'
5 | managerInstaller='https://files.trendmicro.com/products/deepsecurity/en/12.0/Manager-Linux-12.0.296.x64.sh'
6 |
7 | download(){
8 | until curl -f $@ ;
9 | do
10 | sleep 1
11 | done
12 | }
13 | if ! [ $(id -u) = 0 ]; then
14 | echo "This script must be run as root"
15 | exit 1
16 | fi
17 |
18 | # setup dir
19 | mkdir -p /opt/fastdsm/
20 | cd /opt/fastdsm/
21 |
22 | #setup repos
23 | #curl -O https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
24 | #yum -y install epel-release-latest-7.noarch.rpm
25 | #yum-config-manager --add-repo https://docs.docker.com/engine/installation/linux/repo_files/centos/docker.repo
26 | #yum makecache fast
27 |
28 | sudo tee /etc/yum.repos.d/docker.repo <<-EOF
29 | [dockerrepo]
30 | name=Docker Repository
31 | baseurl=https://yum.dockerproject.org/repo/main/centos/7
32 | enabled=1
33 | gpgcheck=1
34 | gpgkey=https://yum.dockerproject.org/gpg
35 | EOF
36 |
37 | echo "$(date) -- starting docker Install"
38 |
39 | # get a db
40 | echo "$(date) -- RHEL7 on EC2 is occasionally slow to get enough network to find mirrors. Let it catch up"
41 | yum -y install docker-engine jq
42 | while [ $? -ne 0 ]; do !!; done
43 |
44 | service docker start
45 | echo "$(date) -- creating pgsql container for dsmdb"
46 | docker pull postgres:9
47 | docker run --name dsmpgsqldb -p 5432:5432 -e "POSTGRES_PASSWORD=${dbpw}" -e POSTGRES_DB=dsm -d postgres:9
48 | echo "$(date) -- creating database in sql instance"
49 |
50 | # persist db across restart
51 | echo "$(date) -- creating service config to persiste db instance"
52 | download https://s3.amazonaws.com/424d57/fastDsm/docker-dsmdb -o /etc/init.d/docker-dsmdb
53 | chmod 755 /etc/init.d/docker-dsmdb
54 | chkconfig --add docker-dsmdb
55 | chkconfig docker-dsmdb on
56 | chkconfig --add docker
57 | chkconfig docker on
58 |
59 |
60 | # get ds files
61 | echo "$(date) -- downloading manager and agent installers"
62 | download ${managerInstaller} -o Manager-Linux.sh
63 | download -O "https://files.trendmicro.com/products/deepsecurity/en/12.0/Agent-amzn1-12.0.0-364.x86_64.zip"
64 | download -O "https://files.trendmicro.com/products/deepsecurity/en/12.0/KernelSupport-amzn2-12.0.0-444.x86_64.zip"
65 | download -O "https://files.trendmicro.com/products/deepsecurity/en/12.0/Agent-amzn2-12.0.0-364.x86_64.zip"
66 | download -O "https://files.trendmicro.com/products/deepsecurity/en/12.0/KernelSupport-amzn1-12.0.0-458.x86_64.zip"
67 | download -O "https://files.trendmicro.com/products/deepsecurity/en/12.0/Agent-RedHat_EL7-12.0.0-364.x86_64.zip"
68 | download -O "https://files.trendmicro.com/products/deepsecurity/en/12.0/KernelSupport-RedHat_EL7-12.0.0-387.x86_64.zip"
69 | download -O "https://files.trendmicro.com/products/deepsecurity/en/12.0/Agent-Ubuntu_18.04-12.0.0-364.x86_64.zip"
70 | download -O "https://files.trendmicro.com/products/deepsecurity/en/12.0/KernelSupport-Ubuntu_18.04-12.0.0-454.x86_64.zip"
71 | download -O "https://files.trendmicro.com/products/deepsecurity/en/12.0/Agent-Windows-12.0.0-360.x86_64.zip"
72 | download -O "https://files.trendmicro.com/products/deepsecurity/en/12.0/Agent-RedHat_EL8-12.0.0-364.x86_64.zip"
73 | download -O "https://files.trendmicro.com/products/deepsecurity/en/12.0/KernelSupport-RedHat_EL8-12.0.0-385.x86_64.zip"
74 |
75 | # make a properties file
76 | echo "$(date) -- creating dsm properties file"
77 | echo "AddressAndPortsScreen.ManagerPort=443" > dsm.props
78 | echo "AddressAndPortsScreen.HeartbeatPort=4120" >> dsm.props
79 | echo "AddressAndPortsScreen.ManagerAddress=$(curl http://169.254.169.254/0.1/meta-data/network | jq -r .networkInterface[0].ip)" >> dsm.props
80 | echo "CredentialsScreen.Administrator.Username=${dsmuser}" >> dsm.props
81 | echo "CredentialsScreen.UseStrongPasswords=False" >> dsm.props
82 | echo "CredentialsScreen.Administrator.Password=${dsmpw}" >> dsm.props
83 | echo "SecurityUpdatesScreen.UpdateComponents=True" >> dsm.props
84 | echo "DatabaseScreen.DatabaseType=PostgreSQL" >> dsm.props
85 | echo "DatabaseScreen.Hostname=localhost:5432" >> dsm.props
86 | echo "DatabaseScreen.Username=postgres" >> dsm.props
87 | echo "DatabaseScreen.Password=${dbpw}" >> dsm.props
88 | echo "DatabaseScreen.DatabaseName=dsm" >> dsm.props
89 | echo "SecurityUpdateScreen.UpdateComponents=true" >> dsm.props
90 | echo "SecurityUpdateScreen.UpdateSoftware=true" >> dsm.props
91 | echo "SmartProtectionNetworkScreen.EnableFeedback=false" >> dsm.props
92 | echo "SmartProtectionNetworkScreen.IndustryType=blank" >> dsm.props
93 | echo "RelayScreen.Install=True" >> dsm.props
94 | echo "RelayScreen.AntiMalware=True" >> dsm.props
95 | echo "Override.Automation=True" >> dsm.props
96 |
97 | # install manager
98 | echo "$(date) -- installing manager"
99 | chmod 755 Manager-Linux.sh
100 | ./Manager-Linux.sh -q -console -varfile dsm.props
101 | if [ $? -ne 0 ]; then
102 | echo "$(date) -- manager install FAILED"
103 | cat /opt/fastdsm/DeepSecurityInstallerReport.csv
104 | exit -1
105 | fi
106 | echo "$(date) -- manager install complete"
107 | chkconfig --add dsm_s
108 | systemctl enable dsm_s
109 | chkconfig dsm_s on
110 |
111 | # customize dsm
112 | yum -y install perl-XML-Twig
113 | echo "$(date) -- starting manager customization"
114 | curl -O https://s3.amazonaws.com/trend-micro-quick-start/v5.1/Common/Scripts/set-aia-settings.sh
115 | chmod 755 set-aia-settings.sh
116 | curl -O https://s3.amazonaws.com/trend-micro-quick-start/v3.7/Common/Scripts/set-lbSettings
117 | chmod 755 set-lbSettings
118 | curl -O https://raw.githubusercontent.com/deep-security/ops-tools/master/deepsecurity/manager-apis/bash/ds10-rest-cloudAccountCreateWithInstanceRole.sh
119 | chmod 755 ds10-rest-cloudAccountCreateWithInstanceRole.sh
120 | curl https://s3.amazonaws.com/trend-micro-quick-start/v5.2/Common/Scripts/dsm_s.service -o /etc/systemd/system/dsm_s.service
121 | chmod 755 /etc/systemd/system/dsm_s.service
122 |
123 |
124 | echo "$(date) -- waiting for manager startup to complete"
125 | until curl -vk https://127.0.0.1:443/rest/status/manager/current/ping; do echo \"manager not started yet\" >> /tmp/4-check-service; service dsm_s start >> /tmp/4-check-service; sleep 30; done
126 | echo "$(date) -- manager startup complete. continuing with API call customizations"
127 | ./set-aia-settings.sh ${dsmuser} ${dsmpw} localhost 443
128 | # None on GCP?
129 | #name=$(curl http://169.254.169.254/latest/meta-data/public-hostname)
130 | if [ -z ${name} ]; then name=$(curl http://169.254.169.254/0.1/meta-data/network | jq -r .networkInterface[0].accessConfiguration[0].externalIp); fi
131 | ./set-lbSettings ${dsmuser} ${dsmpw} ${name} 443 4120
132 | ./ds10-rest-cloudAccountCreateWithInstanceRole.sh ${dsmuser} ${dsmpw} localhost 443
133 |
134 |
135 | echo "$(date) -- completed manager customizations"
136 |
--------------------------------------------------------------------------------