-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbastion.py
More file actions
212 lines (199 loc) · 8.62 KB
/
bastion.py
File metadata and controls
212 lines (199 loc) · 8.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
# Copyright 2022 Darktrace Holdings Ltd. All rights reserved.
# Based on modified example code: Copyright 2022 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Creates a Bastion host for accessing the vSensors in the private subnet."""
from common import getRef, prefixURLCompute
def GenerateConfig(context):
"""Generate one autoscaled_group resource Dict with a passed zone."""
name = context.env["name"]
project = context.env["project"]
prop = context.properties
gprop = prop["global"]
vpc_ref = prop["vpc-ref"]
deployment_hash = prop["deployment-hash"]
service_account_id = "-".join([name[:17], deployment_hash, "bsa"])
region = gprop["region"]
cidr_range = gprop["bastion-subnet-cidr"]
external_cidr_ranges = [gprop["bastion-external-cidr"]]
zone_1 = prefixURLCompute(context, "zones/" + gprop["zone1"])
zone_2 = prefixURLCompute(context, "zones/" + gprop["zone2"])
username_sshkey = (
gprop["bastion-ssh-user-key"] if "bastion-ssh-user-key" in gprop else None
)
INSTANCE_TEMPLATE_NAME = name + "-template"
INSTANCE_TEMPLATE_V2_NAME = INSTANCE_TEMPLATE_NAME + "-v2"
SUBNET_NAME = name + "-subnet"
# https://cloud.google.com/compute/docs/reference/rest/v1/instanceTemplates/insert
def make_template(name, image):
return {
"name": name,
"type": "compute.v1.instanceTemplate",
"properties": {
"properties": {
"items": ["darktrace-vsensor-bastion", "darktrace-ssh-iap"],
"machineType": "e2-micro",
"disks": [
{
"deviceName": "boot",
"type": "PERSISTENT",
"boot": True,
"autoDelete": True,
"initializeParams": {
"sourceImage": prefixURLCompute(context, image, False),
"diskSizeGb": 10,
"diskType": "pd-standard",
},
}
],
"networkInterfaces": [
{
"network": vpc_ref,
"subnetwork": getRef(SUBNET_NAME),
"accessConfigs": [
{
"name": "External NAT",
"type": "ONE_TO_ONE_NAT",
"networkTier": "PREMIUM",
}
],
}
],
"serviceAccounts": [
{
"email": getRef(service_account_id, "email"),
# Sets scope at the service account level, rather than at the instance level.
"scopes": [
"https://www.googleapis.com/auth/cloud-platform"
],
}
],
"metadata": {
"items": [
{
"key": "startup-script",
# Do not adjust the indentation of the script contents! Instance templates are
# immutable, so adjusting the whitespace will cause deployment updates to fail.
"value": """
#! /bin/bash -xe
exec > >(tee -a /var/log/user-data.log|logger -t user-data -s 2>/dev/console) 2>&1
echo "Installing Monitoring Agent"
curl -sSO https://dl.google.com/cloudagents/add-google-cloud-ops-agent-repo.sh
bash add-google-cloud-ops-agent-repo.sh --also-install
""",
}
]
},
}
},
}
instance_templates = [
make_template(
INSTANCE_TEMPLATE_V2_NAME,
"projects/ubuntu-os-cloud/global/images/family/ubuntu-minimal-2404-lts-amd64",
)
]
# We need to keep this around during Focal->Noble upgrade because instance templates are immutable.
# Effectively we make a new template, then switch the MIG to use the new one, then in a separate update remove the old one.
if gprop.get("vsensor-63-upgrade-in-progress", False):
instance_templates.append(
make_template(
INSTANCE_TEMPLATE_NAME,
"projects/ubuntu-os-cloud/global/images/family/ubuntu-2004-lts",
)
)
for instance_template in instance_templates:
if username_sshkey:
instance_template["properties"]["properties"]["metadata"]["items"].append(
{"key": "ssh-keys", "value": username_sshkey}
)
resources = [
{
"name": SUBNET_NAME,
"type": "compute.v1.subnetwork",
"properties": {
"description": "Public subnet containing bastion for Darktrace vSensors",
"network": vpc_ref,
"ipCidrRange": cidr_range,
"region": region,
"privateIpGoogleAccess": True,
},
},
{
"name": name + "-firewall-internal",
"type": "compute.v1.firewall",
"properties": {
"description": "vSensor Quickstart bastion public firewall policy. This allows access to the bastion (and therefore vSensors) from an external CIDR range.",
"name": "External SSH Access",
"priority": 1000,
"network": vpc_ref,
"sourceRanges": external_cidr_ranges,
"direction": "INGRESS",
"allowed": [
{"IPProtocol": "TCP", "ports": ["22"]},
{"IPProtocol": "icmp"},
],
},
},
# Service account to auth Bastion
{
"name": service_account_id,
"type": "iam.v1.serviceAccount",
"properties": {
"accountId": service_account_id,
"displayName": "Darktrace vSensor Quickstart Bastion",
"description": "Allows Bastion to send logs / metrics from Monitoring Ops Agent",
},
},
# Give Bastion service account permissions to send Ops Agent logging/metrics.
{
"name": service_account_id + "-iam",
"type": "iam_member.py",
"properties": {
"roles": [
{
"role": "roles/monitoring.metricWriter",
"members": [
"serviceAccount:$(ref.{}.email)".format(service_account_id)
],
},
{
"role": "roles/logging.logWriter",
"members": [
"serviceAccount:$(ref.{}.email)".format(service_account_id)
],
},
]
},
},
{
"name": name + "-mig",
"type": "compute.v1.regionInstanceGroupManager",
"properties": {
"description": "Managed Instance Group for Bastion in vSensor Quickstart.",
"project": project,
"distributionPolicy": {"zones": [{"zone": zone_1}, {"zone": zone_2}]},
"region": region,
"targetSize": 1,
"baseInstanceName": name + "-vm",
"instanceTemplate": getRef(INSTANCE_TEMPLATE_V2_NAME),
"updatePolicy": {"type": "PROACTIVE"},
},
},
]
resources.extend(instance_templates)
outputs = [
{"name": "subnet-ref", "value": getRef(SUBNET_NAME)},
{"name": "subnet-name", "value": SUBNET_NAME},
]
return {"resources": resources, "outputs": outputs}