ztna 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
ztna-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,37 @@
1
+ Metadata-Version: 2.4
2
+ Name: ztna
3
+ Version: 0.1.0
4
+ Summary: Zero-trust, on-demand access to private resources: a ≈ $0 Lambda console starts a stateless EC2 jump host you tunnel through over SSM, then terminate.
5
+ Author: Frank Zhang
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/cloudformer/ztna
8
+ Project-URL: IdleFree, https://cloudformer.github.io/
9
+ Project-URL: Repository, https://github.com/cloudformer/ztna
10
+ Project-URL: Deploy, https://registry.terraform.io/modules/cloudformer/infra/aws/latest/submodules/ztna
11
+ Project-URL: Changelog, https://github.com/cloudformer/ztna/blob/main/CHANGELOG.md
12
+ Project-URL: Issues, https://github.com/cloudformer/ztna/issues
13
+ Keywords: serverless,aws,lambda,ec2,ssm,bastion,ztna,vpn
14
+ Classifier: Development Status :: 3 - Alpha
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: License :: OSI Approved :: MIT License
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Topic :: Security
19
+ Requires-Python: >=3.9
20
+ Description-Content-Type: text/markdown
21
+ Requires-Dist: idlefree-auth
22
+ Requires-Dist: idlefree-ui
23
+
24
+ # ztna
25
+
26
+ **Zero-trust, on-demand access to private resources: a persistent ≈ $0 Lambda console starts a stateless EC2 jump
27
+ host in the network you pick, you tunnel through it over SSM — a port-forward to your laptop, or a SOCKS tunnel
28
+ (VPN-like) — and it is terminated when you are done.** Part of [IdleFree](https://cloudformer.github.io/).
29
+
30
+ ![the ztna console](https://raw.githubusercontent.com/cloudformer/ztna/main/docs/console.svg)
31
+
32
+ ![ztna architecture](https://raw.githubusercontent.com/cloudformer/ztna/main/docs/architecture.svg)
33
+
34
+ This package holds the service: the Lambda (web console + API) and the jump agent (self-terminate on lease / idle).
35
+ Deploy it with the Terraform module
36
+ [cloudformer/infra/aws//modules/ztna](https://registry.terraform.io/modules/cloudformer/infra/aws/latest/submodules/ztna),
37
+ which installs this package from PyPI. Project: [cloudformer/ztna](https://github.com/cloudformer/ztna).
ztna-0.1.0/README.md ADDED
@@ -0,0 +1,14 @@
1
+ # ztna
2
+
3
+ **Zero-trust, on-demand access to private resources: a persistent ≈ $0 Lambda console starts a stateless EC2 jump
4
+ host in the network you pick, you tunnel through it over SSM — a port-forward to your laptop, or a SOCKS tunnel
5
+ (VPN-like) — and it is terminated when you are done.** Part of [IdleFree](https://cloudformer.github.io/).
6
+
7
+ ![the ztna console](https://raw.githubusercontent.com/cloudformer/ztna/main/docs/console.svg)
8
+
9
+ ![ztna architecture](https://raw.githubusercontent.com/cloudformer/ztna/main/docs/architecture.svg)
10
+
11
+ This package holds the service: the Lambda (web console + API) and the jump agent (self-terminate on lease / idle).
12
+ Deploy it with the Terraform module
13
+ [cloudformer/infra/aws//modules/ztna](https://registry.terraform.io/modules/cloudformer/infra/aws/latest/submodules/ztna),
14
+ which installs this package from PyPI. Project: [cloudformer/ztna](https://github.com/cloudformer/ztna).
@@ -0,0 +1,35 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "ztna"
7
+ version = "0.1.0"
8
+ description = "Zero-trust, on-demand access to private resources: a ≈ $0 Lambda console starts a stateless EC2 jump host you tunnel through over SSM, then terminate."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = { text = "MIT" }
12
+ authors = [{ name = "Frank Zhang" }]
13
+ keywords = ["serverless", "aws", "lambda", "ec2", "ssm", "bastion", "ztna", "vpn"]
14
+ classifiers = [
15
+ "Development Status :: 3 - Alpha",
16
+ "Intended Audience :: Developers",
17
+ "License :: OSI Approved :: MIT License",
18
+ "Programming Language :: Python :: 3",
19
+ "Topic :: Security",
20
+ ]
21
+ dependencies = ["idlefree-auth", "idlefree-ui"]
22
+
23
+ [project.urls]
24
+ Homepage = "https://github.com/cloudformer/ztna"
25
+ IdleFree = "https://cloudformer.github.io/"
26
+ Repository = "https://github.com/cloudformer/ztna"
27
+ Deploy = "https://registry.terraform.io/modules/cloudformer/infra/aws/latest/submodules/ztna"
28
+ Changelog = "https://github.com/cloudformer/ztna/blob/main/CHANGELOG.md"
29
+ Issues = "https://github.com/cloudformer/ztna/issues"
30
+
31
+ [tool.setuptools]
32
+ packages = ["ztna", "ztna.server"]
33
+
34
+ [tool.setuptools.package-data]
35
+ "ztna.server" = ["index.html"]
ztna-0.1.0/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,9 @@
1
+ """ztna — zero-trust, on-demand access to private resources. A persistent ≈ $0 Lambda console starts a stateless EC2
2
+ jump host in a chosen network profile; you tunnel through it over SSM Session Manager — a port-forward to your laptop,
3
+ or a SOCKS tunnel (VPN-like) — and it is terminated when you are done.
4
+
5
+ ztna.server is the Lambda (the web console and its API). The Terraform module cloudformer/infra/aws//modules/ztna
6
+ deploys it along with the launch template, the network profiles and the IAM.
7
+ """
8
+
9
+ __version__ = "0.1.0"
File without changes
@@ -0,0 +1,252 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>ztna</title>
7
+ <style>
8
+ /* idlefree-ui */
9
+
10
+ /* ---- ztna ---- */
11
+ :root { --width: 1000px; }
12
+ .page { max-width: calc(var(--width) + 32px); margin-inline: auto; }
13
+ .bar, .status { padding-inline: max(16px, calc((100% - var(--width)) / 2)); }
14
+ .panel { padding: 14px 16px; }
15
+ .field { display: inline-flex; align-items: center; gap: 6px; }
16
+ .field select { padding: 5px 8px; }
17
+ .start-row { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
18
+ .start-row .spacer { flex: 1; }
19
+ .rows { display: flex; flex-direction: column; margin-top: 10px; border: 1px solid var(--line); border-radius: 8px; overflow: hidden; }
20
+ .rows:empty { display: none; }
21
+ .row { display: grid; grid-template-columns: 150px minmax(0, 1fr) auto auto; align-items: center; gap: 12px; padding: 9px 12px;
22
+ border-bottom: 1px solid var(--line); cursor: pointer; font-size: 13px; background: var(--panel); }
23
+ .row:last-child { border-bottom: none; }
24
+ .row:hover { background: var(--panel2); }
25
+ .row.picked { background: var(--accent-bg); }
26
+ .row .id { font: 12px var(--mono); }
27
+ .row .meta { color: var(--muted); font-size: 12px; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
28
+ .row .left { font: 12px var(--mono); color: var(--muted); white-space: nowrap; }
29
+ .row .left.soon { color: var(--err); font-weight: 600; }
30
+ .row .act { display: flex; gap: 6px; justify-content: flex-end; }
31
+ .empty-row { padding: 10px 12px; color: var(--muted); font-size: 13px; }
32
+ .connect { display: grid; gap: 10px; }
33
+ .connect .who { color: var(--muted); font-size: 13px; }
34
+ .connect .who b { color: var(--text); }
35
+ .seg { display: inline-flex; border: 1px solid var(--line2); border-radius: 8px; overflow: hidden; }
36
+ .seg button { border: none; background: none; padding: 6px 14px; font: inherit; font-size: 13px; color: var(--muted); cursor: pointer; border-right: 1px solid var(--line2); }
37
+ .seg button:last-child { border-right: none; }
38
+ .seg button.on { background: var(--accent-bg); color: var(--accent-text); font-weight: 600; }
39
+ .ctl { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; }
40
+ .ctl select, .ctl input { padding: 6px 9px; }
41
+ .ctl input { font: 12px var(--mono); min-width: 170px; }
42
+ .cmd { position: relative; }
43
+ .cmd pre { margin: 0; padding: 11px 12px; border-radius: 8px; background: var(--code-bg); color: var(--code-text);
44
+ font: 12px/1.7 var(--mono); white-space: pre-wrap; overflow-wrap: anywhere; }
45
+ .cmd .copy { position: absolute; top: 8px; right: 8px; }
46
+ .note { color: var(--muted); font-size: 12px; }
47
+ </style>
48
+ </head>
49
+ <body>
50
+ <header class="bar">
51
+ <span class="brand"><span class="logo">🛡</span>ztna</span>
52
+ <span class="meta"><span class="k">Endpoint</span><span class="chip" id="info-host">-</span></span>
53
+ <span class="meta" id="who-meta" hidden><span class="k">Signed in</span><span class="chip" id="who">-</span></span>
54
+ <span class="spacer"></span>
55
+ <button class="tb" id="logout">Sign out</button>
56
+ </header>
57
+
58
+ <div class="page">
59
+ <section class="panel">
60
+ <div class="start-row">
61
+ <label class="field"><span class="hint">Network</span><select id="network"></select></label>
62
+ <label class="field"><span class="hint">For</span><select id="duration"></select></label>
63
+ <button class="btn btn-primary" id="power-on">⏻ Start jump</button>
64
+ <span class="spacer"></span>
65
+ <span class="hint" id="jumps-sum"></span>
66
+ </div>
67
+ <div class="rows" id="jumps"></div>
68
+ </section>
69
+
70
+ <section class="panel connect">
71
+ <div class="who" id="who-jump">Start a jump, then pick it to connect.</div>
72
+ <div class="ctl">
73
+ <div class="seg" id="mode" role="radiogroup" aria-label="Mode">
74
+ <button data-m="map" class="on" type="button">Map</button>
75
+ <button data-m="vpn" type="button">VPN-like</button>
76
+ </div>
77
+ <label class="field" id="target-field"><span class="hint">Target</span><select id="target"></select></label>
78
+ <input id="custom" placeholder="db-host:3306" hidden>
79
+ </div>
80
+ <div class="cmd"><button class="btn btn-small copy" id="copy">Copy</button><pre id="cmd"># start a jump first</pre></div>
81
+ <div class="note" id="hint"></div>
82
+ </section>
83
+ </div>
84
+
85
+ <div class="history" id="history" hidden></div>
86
+ <footer class="status" id="status" title="Click: this session's calls">
87
+ <span class="last" id="last">ready</span>
88
+ <a class="ver" href="https://github.com/cloudformer/ztna/blob/main/CHANGELOG.md" target="_blank" rel="noopener noreferrer"
89
+ title="What changed in each release">ztna __VERSION__</a>
90
+ </footer>
91
+
92
+ <dialog id="dlg">
93
+ <form method="dialog">
94
+ <h3>Sign in</h3>
95
+ <div class="form-grid">
96
+ <div class="form-field"><label for="u">user</label><input id="u" autocomplete="username"></div>
97
+ <div class="form-field"><label for="p">password</label><input id="p" type="password" autocomplete="current-password"></div>
98
+ </div>
99
+ <div class="actions">
100
+ <button class="btn btn-primary" value="ok">OK</button>
101
+ <button class="btn" value="cancel" formnovalidate>Cancel</button>
102
+ </div>
103
+ </form>
104
+ </dialog>
105
+
106
+ <script>
107
+ const $ = s => document.querySelector(s);
108
+ const h = (tag, props, ...kids) => { const e = Object.assign(document.createElement(tag), props || {}); e.append(...kids.filter(k => k != null)); return e; };
109
+ const store = {
110
+ get: k => { try { return localStorage.getItem('ztna_' + k); } catch(e){ return null; } },
111
+ set: (k, v) => { try { v == null ? localStorage.removeItem('ztna_' + k) : localStorage.setItem('ztna_' + k, v); } catch(e){} },
112
+ };
113
+ let cred = store.get('cred') || '';
114
+ $('#info-host').textContent = location.host;
115
+ let cfg = null, jumps = [], picked = null, mode = 'map';
116
+ const POLL_MS = 4000;
117
+
118
+ // ---- sign-in ----
119
+ function askCred(){
120
+ return new Promise(resolve => {
121
+ const dlg = $('#dlg'); dlg.returnValue = 'cancel';
122
+ dlg.onclose = () => { if (dlg.returnValue === 'ok' && $('#u').value) { cred = $('#u').value.trim() + ':' + $('#p').value; store.set('cred', cred); } $('#p').value = ''; resolve(dlg.returnValue === 'ok'); };
123
+ dlg.showModal(); $('#u').focus();
124
+ });
125
+ }
126
+ async function api(path, opts = {}, retried){
127
+ const headers = {'content-type': 'application/json'};
128
+ if (cred) headers.authorization = 'Basic ' + btoa(cred);
129
+ const r = await fetch(path, Object.assign({}, opts, {headers}));
130
+ let data = {}; try { data = await r.json(); } catch(e) {}
131
+ if (r.status === 401){
132
+ if (!data.http_auth) throw new Error('sign in through Cloudflare Access, then reload');
133
+ cred = ''; store.set('cred', null);
134
+ if (!retried && await askCred()) return api(path, opts, true);
135
+ throw new Error('not signed in');
136
+ }
137
+ if (!r.ok) throw new Error(data.error || ('HTTP ' + r.status));
138
+ return data;
139
+ }
140
+
141
+ // ---- status bar ----
142
+ const calls = []; let historyOpen = store.get('history') === '1';
143
+ function ts(){ const d = new Date(), p = n => String(n).padStart(2, '0'); return `${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`; }
144
+ function note(text, ok){ calls.push({text: `[${ts()}] ${text}`, cls: ok ? 'ok' : 'err'}); if (calls.length > 300) calls.shift();
145
+ const last = calls[calls.length - 1]; $('#last').textContent = last.text; $('#last').className = 'last ' + last.cls; renderHistory(); }
146
+ function renderHistory(){ const box = $('#history'); box.hidden = !historyOpen;
147
+ if (historyOpen) box.replaceChildren(...(calls.length ? calls.slice().reverse().map(c => h('div', {className: c.cls, textContent: c.text})) : [h('div', {textContent: 'No calls yet.'})])); }
148
+ $('#status').onclick = e => { if (e.target.closest('a')) return; historyOpen = !historyOpen; store.set('history', historyOpen ? '1' : '0'); renderHistory(); };
149
+
150
+ // ---- helpers ----
151
+ function short(id){ return id.replace('i-', '').slice(0, 8); }
152
+ function hours(m){ return m % 60 ? `${m} min` : `${m / 60} h`; }
153
+ function left(until){ const s = Math.max(0, Math.round((new Date(until) - new Date()) / 1000));
154
+ return [s >= 3600 ? `${Math.floor(s/3600)} h ${String(Math.floor(s/60)%60).padStart(2,'0')} min left` : `${Math.ceil(s/60)} min left`, s < 600]; }
155
+
156
+ // ---- jumps list ----
157
+ function render(){
158
+ const up = jumps.filter(j => j.state === 'running' || j.state === 'pending');
159
+ $('#jumps-sum').textContent = `${up.length} up · at most ${cfg.max_jumps} · each terminates after ${cfg.idle_shutdown_minutes} min idle`;
160
+ $('#power-on').disabled = up.length >= cfg.max_jumps;
161
+ $('#jumps').replaceChildren(...jumps.map(j => {
162
+ const [rest, soon] = j.until ? left(j.until) : ['', false];
163
+ const starting = j.state === 'pending';
164
+ const acts = [h('button', {className: 'btn btn-small', textContent: '+' + hours(cfg.extend_minutes), title: 'Keep it up longer',
165
+ onclick: e => { e.stopPropagation(); extend(j); }}),
166
+ h('button', {className: 'btn-danger', textContent: 'Terminate', onclick: e => { e.stopPropagation(); terminate(j); }})];
167
+ const r = h('div', {className: 'row' + (picked === j.id ? ' picked' : '')},
168
+ h('span', {className: 'id', textContent: short(j.id)}),
169
+ h('span', {className: 'meta', textContent: `${j.network} · ${j.id}${starting ? ' · starting' : ''} · ${j.by || ''}`}),
170
+ h('span', {className: 'left' + (soon ? ' soon' : ''), textContent: rest}),
171
+ h('span', {className: 'act'}, ...acts));
172
+ r.onclick = () => { picked = j.id; renderConnect(); render(); };
173
+ return r;
174
+ }));
175
+ if (!jumps.length) $('#jumps').replaceChildren(h('div', {className: 'empty-row', textContent: 'No jump up. Start one above.'}));
176
+ }
177
+
178
+ // ---- connect ----
179
+ function fillTargets(){
180
+ if (mode === 'map'){
181
+ $('#target').replaceChildren(...cfg.targets.map(t => h('option', {value: t, textContent: t})), h('option', {value: '__c', textContent: '自定义…'}));
182
+ $('#target').disabled = false; $('#target-field').style.display = '';
183
+ } else {
184
+ $('#target').replaceChildren(h('option', {textContent: 'all · 0.0.0.0/0 → SOCKS :1080'}));
185
+ $('#target').disabled = true; $('#custom').hidden = true;
186
+ }
187
+ }
188
+ function tval(){ return $('#target').value === '__c' ? $('#custom').value.trim() : $('#target').value; }
189
+ function renderConnect(){
190
+ const j = jumps.find(x => x.id === picked);
191
+ $('#custom').hidden = !(mode === 'map' && $('#target').value === '__c');
192
+ if (!j){ $('#who-jump').textContent = 'Start a jump, then pick it to connect.'; $('#cmd').textContent = '# pick a jump'; $('#hint').textContent = ''; return; }
193
+ $('#who-jump').innerHTML = `Connect · <b>${short(j.id)}</b> · ${j.network} · ${j.id}`;
194
+ const region = cfg.region ? ` --region ${cfg.region}` : '';
195
+ if (mode === 'map'){
196
+ const t = (tval() || 'host:port'), [host, port] = t.split(':');
197
+ $('#cmd').textContent =
198
+ `aws ssm start-session --target ${j.id}${region} \\
199
+ --document-name AWS-StartPortForwardingSessionToRemoteHost \\
200
+ --parameters host=${host || 'host'},portNumber=${port || 'PORT'},localPortNumber=${port || 'PORT'}`;
201
+ $('#hint').textContent = `localhost:${port || 'PORT'} = ${host || 'host'}(through ${short(j.id)})`;
202
+ } else {
203
+ $('#cmd').textContent =
204
+ `ssh -N -D 1080 \\
205
+ -o ProxyCommand="aws ssm start-session --target ${j.id}${region} --document-name AWS-StartSSHSession --parameters portNumber=22" \\
206
+ ${cfg.ssh_user}@${j.id}`;
207
+ $('#hint').textContent = `SOCKS5 on 127.0.0.1:1080 — point your browser/apps here (all traffic via ${short(j.id)})`;
208
+ }
209
+ }
210
+ $('#mode').querySelectorAll('button').forEach(b => b.onclick = () => { mode = b.dataset.m;
211
+ $('#mode').querySelectorAll('button').forEach(x => x.classList.toggle('on', x === b)); fillTargets(); renderConnect(); });
212
+ $('#target').onchange = renderConnect;
213
+ $('#custom').oninput = renderConnect;
214
+ $('#copy').onclick = () => { navigator.clipboard?.writeText($('#cmd').textContent).then(() => note('command copied', true)).catch(() => {}); };
215
+
216
+ // ---- actions ----
217
+ $('#power-on').onclick = async () => {
218
+ $('#power-on').disabled = true;
219
+ try { const j = await api('/api/jumps', {method: 'POST', body: JSON.stringify({network: $('#network').value, minutes: +$('#duration').value})});
220
+ note(`jump ${short(j.id)} starting in ${j.network}, for ${hours(+$('#duration').value)}`, true);
221
+ jumps.unshift(j); picked = j.id; render(); renderConnect();
222
+ } catch(e) { note(e.message, false); render(); }
223
+ };
224
+ async function extend(j){ try { const d = await api(`/api/jumps/${j.id}/extend`, {method: 'POST'}); j.until = d.until; render();
225
+ note(`jump ${short(j.id)} kept until ${new Date(d.until).toLocaleTimeString()}`, true); } catch(e) { note(e.message, false); } }
226
+ async function terminate(j){ try { await api(`/api/jumps/${j.id}/stop`, {method: 'POST'}); note(`jump ${short(j.id)} terminating`, true); } catch(e) { note(e.message, false); } }
227
+ $('#logout').onclick = () => { cred = ''; store.set('cred', null); note('signed out', true); };
228
+
229
+ // ---- poll ----
230
+ async function poll(){
231
+ try { jumps = (await api('/api/jumps')).jumps;
232
+ if (picked && !jumps.some(j => j.id === picked)) { picked = null; renderConnect(); }
233
+ render();
234
+ } catch(e) { note(e.message, false); }
235
+ setTimeout(poll, POLL_MS);
236
+ }
237
+
238
+ async function start(){
239
+ cfg = await api('/api/config');
240
+ $('#network').replaceChildren(...cfg.networks.map(n => h('option', {value: n, textContent: n})));
241
+ $('#network').value = cfg.default_network;
242
+ $('#duration').replaceChildren(...cfg.durations.map(m => h('option', {value: m, textContent: hours(m)})));
243
+ $('#duration').value = cfg.default_minutes;
244
+ fillTargets(); renderConnect();
245
+ const me = await api('/api/me'); $('#who').textContent = me.identity; $('#who-meta').hidden = false;
246
+ poll();
247
+ }
248
+ renderHistory();
249
+ start().catch(e => note(e.message, false));
250
+ </script>
251
+ </body>
252
+ </html>
@@ -0,0 +1,303 @@
1
+ """ztna server: one Lambda behind a Function URL — starts and terminates on-demand EC2 jump hosts you tunnel through.
2
+
3
+ A jump is one EC2 instance launched from a launch template into a chosen network profile (a subnet + security
4
+ group defined in Terraform), with a lease (how long it stays up, extendable from the page up to MAX_SESSION_MINUTES).
5
+ It is always terminated, never stopped, so it is stateless: the instance carries no state; configuration comes from
6
+ the launch template, and you connect through SSM Session Manager (no inbound, no SSH key). The jump self-terminates
7
+ when its lease runs out or after IDLE_SHUTDOWN_MINUTES with no SSM session.
8
+
9
+ This Lambda never connects to anything: it launches / terminates instances, writes the lease, and serves the page.
10
+ The page builds the connect command — a port-forward (map one service to localhost) or a SOCKS tunnel (VPN-like) —
11
+ from the jump and the target you pick.
12
+
13
+ The first half (JSON, request body, sign-in, routing, error mapping, timing) is the series' shared shell; the
14
+ routes are in the second half.
15
+
16
+ Sign-in: two methods, each on or off; a request passes when any method that is on accepts it.
17
+ HTTP_AUTH=1 HTTP Basic (USER_NAME / PASSWORD). Identity = the user name.
18
+ CLOUDFLARE_AUTH=1 Cloudflare Access: the Cf-Access-Jwt-Assertion header, an RS256 JWT checked against the team's
19
+ public keys, aud, issuer and expiry. Identity = the email in it.
20
+
21
+ GET / , /api/ping , /api/me
22
+ GET /api/config networks, targets, durations, idle shutdown, region, version
23
+ GET /api/jumps the running jumps, newest first, each with its lease end
24
+ POST /api/jumps {"network", "minutes"}: launch a jump in that network profile for that long
25
+ POST /api/jumps/<id>/extend its lease + 1 hour, never past MAX_SESSION_MINUTES after launch
26
+ POST /api/jumps/<id>/stop terminate it
27
+
28
+ Layout: leases/<instance id>.json ({"until": ISO time, "by"}). The jump reads its own lease to self-terminate; the
29
+ bucket's lifecycle rule expires old leases.
30
+ """
31
+ import base64
32
+ import datetime
33
+ import hashlib
34
+ import json
35
+ import os
36
+ import re
37
+ import time
38
+ import urllib.parse
39
+
40
+ import boto3
41
+
42
+ import idlefree_auth as auth
43
+ import idlefree_ui
44
+
45
+ BUCKET = os.environ.get("BUCKET", "")
46
+ PROJECT = os.environ.get("PROJECT", "") # the tag value every jump carries (and the Name prefix)
47
+ LAUNCH_TEMPLATE_ID = os.environ.get("LAUNCH_TEMPLATE_ID", "")
48
+ INSTANCE_TYPE = os.environ.get("INSTANCE_TYPE", "t4g.micro")
49
+ REGION = os.environ.get("AWS_REGION", "")
50
+ SSH_USER = os.environ.get("SSH_USER", "ec2-user") # for the VPN-like SOCKS command
51
+ LEASES = "leases/"
52
+ NETWORKS = json.loads(os.environ.get("NETWORKS", "{}")) # {name: {"subnets": [...], "groups": [...], "public": bool}}
53
+ DEFAULT_NETWORK = os.environ.get("DEFAULT_NETWORK", next(iter(NETWORKS), ""))
54
+ TARGETS = json.loads(os.environ.get("TARGETS", "[]")) # ["db-host:3306", ...]: the map-mode dropdown
55
+ IDLE_SHUTDOWN_MINUTES = int(os.environ.get("IDLE_SHUTDOWN_MINUTES", "30"))
56
+ MAX_SESSION_MINUTES = int(os.environ.get("MAX_SESSION_MINUTES", "480"))
57
+ DURATIONS = [m for m in (60, 120, 240, 480) if m <= MAX_SESSION_MINUTES] or [MAX_SESSION_MINUTES]
58
+ DEFAULT_MINUTES = 240 if 240 in DURATIONS else DURATIONS[-1]
59
+ EXTEND_MINUTES = 60
60
+ MAX_JUMPS = int(os.environ.get("MAX_JUMPS", "3"))
61
+ LIST_LIMIT = 20
62
+
63
+ HERE = os.path.dirname(__file__)
64
+ with open(os.path.join(HERE, "..", "__init__.py"), encoding="utf-8") as f:
65
+ VERSION = re.search(r'__version__ = "([^"]+)"', f.read()).group(1)
66
+ with open(os.path.join(HERE, "index.html"), encoding="utf-8") as f:
67
+ INDEX_HTML = f.read().replace("__VERSION__", VERSION).replace("/* idlefree-ui */", idlefree_ui.CSS)
68
+
69
+ _HASHES = " ".join("'sha256-%s'" % base64.b64encode(hashlib.sha256(s.encode()).digest()).decode()
70
+ for s in re.findall(r"<script>(.*?)</script>", INDEX_HTML, re.S))
71
+ CSP = (f"default-src 'none'; script-src {_HASHES}; style-src 'unsafe-inline'; connect-src 'self'; "
72
+ "img-src 'self' data:; base-uri 'none'; frame-ancestors 'none'")
73
+ PAGE_HEADERS = {"content-security-policy": CSP, "x-content-type-options": "nosniff",
74
+ "referrer-policy": "no-referrer", "x-frame-options": "DENY"}
75
+
76
+ INSTANCE_ID = re.compile(r"i-[0-9a-f]{8,17}")
77
+
78
+ ec2 = boto3.client("ec2")
79
+ s3 = boto3.client("s3")
80
+
81
+
82
+ class BadRequest(Exception):
83
+ pass
84
+
85
+
86
+ class Forbidden(Exception):
87
+ pass
88
+
89
+
90
+ class NotFound(Exception):
91
+ pass
92
+
93
+
94
+ class Busy(Exception):
95
+ """max_jumps are up already."""
96
+
97
+
98
+ # ---------------- shared: the same shell as the rest of the series ----------------
99
+
100
+ def _json(status, data):
101
+ return {"statusCode": status, "headers": {"content-type": "application/json"},
102
+ "body": json.dumps(data, ensure_ascii=False, default=str)}
103
+
104
+
105
+ def _body(event):
106
+ raw = event.get("body") or "{}"
107
+ try:
108
+ if event.get("isBase64Encoded"):
109
+ raw = base64.b64decode(raw)
110
+ data = json.loads(raw)
111
+ except ValueError:
112
+ raise BadRequest("request body is not valid JSON") from None
113
+ if not isinstance(data, dict):
114
+ raise BadRequest("request body must be a JSON object")
115
+ return data
116
+
117
+
118
+ ERRORS = [(BadRequest, 400), (Forbidden, 403), (NotFound, 404), (Busy, 409)]
119
+
120
+
121
+ def lambda_handler(event, context):
122
+ http = (event.get("requestContext") or {}).get("http") or {}
123
+ method, path = http.get("method", "GET"), urllib.parse.unquote(event.get("rawPath", "/"))
124
+ problem = auth.problem()
125
+ if problem:
126
+ return _json(503, {"error": problem})
127
+ signed = auth.identity(event)
128
+ if signed is None and not auth.HTTP_AUTH:
129
+ return _json(401, {"error": "sign in through Cloudflare Access", "http_auth": False})
130
+ if method == "GET" and path in ("/", "/index.html"):
131
+ return {"statusCode": 200, "body": INDEX_HTML,
132
+ "headers": dict(PAGE_HEADERS, **{"content-type": "text/html; charset=utf-8", "cache-control": "no-cache"})}
133
+ if signed is None:
134
+ return _json(401, {"error": "bad credentials", "http_auth": True})
135
+ event["identity"], event["auth_method"] = signed
136
+ t0 = time.perf_counter()
137
+ status, data = 404, {"error": f"no route: {method} {path}"}
138
+ try:
139
+ for route_method, pattern, handler in ROUTES:
140
+ match = pattern.fullmatch(path)
141
+ if match and route_method == method:
142
+ out = handler(event, **match.groupdict())
143
+ status, data = out if isinstance(out, tuple) else (200, out)
144
+ break
145
+ except Exception as e: # noqa: BLE001
146
+ status = next((s for cls, s in ERRORS if isinstance(e, cls)), 500)
147
+ data = {"error": str(e) if status < 500 else f"{type(e).__name__}: {e}"}
148
+ data.setdefault("ms", round((time.perf_counter() - t0) * 1000, 1))
149
+ return _json(status, data)
150
+
151
+
152
+ # ---------------- the project's API: jumps = EC2 instances tagged with PROJECT ----------------
153
+
154
+ def _instance_id(jump_id):
155
+ if not INSTANCE_ID.fullmatch(jump_id):
156
+ raise BadRequest(f"jump id: an instance id (i-…), got {jump_id!r}")
157
+ return jump_id
158
+
159
+
160
+ def _iso(t):
161
+ return t.strftime("%Y-%m-%dT%H:%M:%SZ")
162
+
163
+
164
+ def _utc(t):
165
+ if isinstance(t, str):
166
+ t = datetime.datetime.fromisoformat(t.replace("Z", "+00:00"))
167
+ return t.astimezone(datetime.timezone.utc)
168
+
169
+
170
+ def _lease(jump_id):
171
+ try:
172
+ return json.loads(s3.get_object(Bucket=BUCKET, Key=f"{LEASES}{jump_id}.json")["Body"].read())
173
+ except s3.exceptions.NoSuchKey:
174
+ return None
175
+
176
+
177
+ def _write_lease(jump_id, until, who):
178
+ s3.put_object(Bucket=BUCKET, Key=f"{LEASES}{jump_id}.json", ContentType="application/json",
179
+ Body=json.dumps({"until": _iso(until), "by": who}).encode())
180
+
181
+
182
+ def _tags(instance):
183
+ return {t["Key"]: t["Value"] for t in instance.get("Tags", [])}
184
+
185
+
186
+ def _summary(instance):
187
+ tags = _tags(instance)
188
+ jid = instance["InstanceId"]
189
+ return {"id": jid, "network": tags.get("Network", ""), "state": instance["State"]["Name"],
190
+ "launched": instance.get("LaunchTime"), "by": tags.get("StartedBy", ""),
191
+ "until": (_lease(jid) or {}).get("until")}
192
+
193
+
194
+ def _running():
195
+ """The project's jumps that are pending or running, newest first."""
196
+ out = []
197
+ pager = ec2.get_paginator("describe_instances").paginate(
198
+ Filters=[{"Name": "tag:Project", "Values": [PROJECT]},
199
+ {"Name": "instance-state-name", "Values": ["pending", "running"]}])
200
+ for page in pager:
201
+ for res in page["Reservations"]:
202
+ out += res["Instances"]
203
+ out.sort(key=lambda i: i.get("LaunchTime") or datetime.datetime.min, reverse=True)
204
+ return out[:LIST_LIMIT]
205
+
206
+
207
+ def ping(event):
208
+ return {"ok": True}
209
+
210
+
211
+ def me(event):
212
+ return {"identity": event["identity"], "auth_method": event["auth_method"]}
213
+
214
+
215
+ def config(event):
216
+ return {"networks": list(NETWORKS), "default_network": DEFAULT_NETWORK, "targets": TARGETS,
217
+ "durations": DURATIONS, "default_minutes": DEFAULT_MINUTES, "extend_minutes": EXTEND_MINUTES,
218
+ "max_session_minutes": MAX_SESSION_MINUTES, "idle_shutdown_minutes": IDLE_SHUTDOWN_MINUTES,
219
+ "max_jumps": MAX_JUMPS, "region": REGION, "ssh_user": SSH_USER, "version": VERSION}
220
+
221
+
222
+ def list_jumps(event):
223
+ return {"jumps": [_summary(i) for i in _running()]}
224
+
225
+
226
+ def start_jump(event):
227
+ body = _body(event)
228
+ network, minutes = body.get("network", DEFAULT_NETWORK), body.get("minutes", DEFAULT_MINUTES)
229
+ if network not in NETWORKS:
230
+ raise BadRequest(f"network: one of {', '.join(NETWORKS)}, got {network!r}")
231
+ if minutes not in DURATIONS:
232
+ raise BadRequest(f"minutes: one of {', '.join(map(str, DURATIONS))}, got {minutes!r}")
233
+ if len(_running()) >= MAX_JUMPS:
234
+ raise Busy(f"{MAX_JUMPS} jump(s) up already (max_jumps): terminate one first")
235
+ net = NETWORKS[network]
236
+ nic = {"DeviceIndex": 0, "SubnetId": net["subnets"][0], "Groups": net["groups"],
237
+ "AssociatePublicIpAddress": bool(net.get("public", False))}
238
+ name = f"{PROJECT}-{network}"
239
+ resp = ec2.run_instances(
240
+ LaunchTemplate={"LaunchTemplateId": LAUNCH_TEMPLATE_ID}, InstanceType=INSTANCE_TYPE,
241
+ MinCount=1, MaxCount=1, NetworkInterfaces=[nic],
242
+ TagSpecifications=[{"ResourceType": "instance", "Tags": [
243
+ {"Key": "Project", "Value": PROJECT}, {"Key": "Network", "Value": network},
244
+ {"Key": "StartedBy", "Value": event["identity"]}, {"Key": "Name", "Value": name}]}])
245
+ inst = resp["Instances"][0]
246
+ until = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(minutes=minutes)
247
+ _write_lease(inst["InstanceId"], until, event["identity"])
248
+ out = _summary(inst)
249
+ out["until"] = _iso(until)
250
+ print(json.dumps({"event": "jump_started", "id": inst["InstanceId"], "network": network,
251
+ "until": out["until"], "by": event["identity"]}))
252
+ return 201, out
253
+
254
+
255
+ def extend_jump(event, jump_id):
256
+ _instance_id(jump_id)
257
+ inst = _one(jump_id)
258
+ if inst["State"]["Name"] not in ("pending", "running"):
259
+ raise BadRequest(f"jump {jump_id} is not up")
260
+ now = datetime.datetime.now(datetime.timezone.utc)
261
+ lease = _lease(jump_id)
262
+ until = max(now, _utc(lease["until"]) if lease else now) + datetime.timedelta(minutes=EXTEND_MINUTES)
263
+ limit = _utc(inst["LaunchTime"]) + datetime.timedelta(minutes=MAX_SESSION_MINUTES)
264
+ if until > limit:
265
+ if lease and _utc(lease["until"]) >= limit - datetime.timedelta(minutes=1):
266
+ raise BadRequest(f"jump {jump_id} is at its limit, {MAX_SESSION_MINUTES} min after launch (max_session_minutes)")
267
+ until = limit
268
+ _write_lease(jump_id, until, event["identity"])
269
+ print(json.dumps({"event": "jump_extended", "id": jump_id, "until": _iso(until), "by": event["identity"]}))
270
+ return dict(_summary(inst), until=_iso(until))
271
+
272
+
273
+ def stop_jump(event, jump_id):
274
+ _instance_id(jump_id)
275
+ ec2.terminate_instances(InstanceIds=[jump_id])
276
+ try:
277
+ s3.delete_object(Bucket=BUCKET, Key=f"{LEASES}{jump_id}.json")
278
+ except Exception: # noqa: BLE001
279
+ pass
280
+ print(json.dumps({"event": "jump_stopped", "id": jump_id, "by": event["identity"]}))
281
+ return {"id": jump_id, "state": "shutting-down"}
282
+
283
+
284
+ def _one(jump_id):
285
+ r = ec2.describe_instances(InstanceIds=[jump_id])["Reservations"]
286
+ if not r or not r[0]["Instances"]:
287
+ raise NotFound(f"no jump {jump_id}")
288
+ inst = r[0]["Instances"][0]
289
+ if _tags(inst).get("Project") != PROJECT:
290
+ raise NotFound(f"no jump {jump_id}")
291
+ return inst
292
+
293
+
294
+ JUMP = r"/api/jumps/(?P<jump_id>[^/]+)"
295
+ ROUTES = [
296
+ ("GET", re.compile(r"/api/ping"), ping),
297
+ ("GET", re.compile(r"/api/me"), me),
298
+ ("GET", re.compile(r"/api/config"), config),
299
+ ("GET", re.compile(r"/api/jumps"), list_jumps),
300
+ ("POST", re.compile(r"/api/jumps"), start_jump),
301
+ ("POST", re.compile(JUMP + "/extend"), extend_jump),
302
+ ("POST", re.compile(JUMP + "/stop"), stop_jump),
303
+ ]
@@ -0,0 +1,37 @@
1
+ Metadata-Version: 2.4
2
+ Name: ztna
3
+ Version: 0.1.0
4
+ Summary: Zero-trust, on-demand access to private resources: a ≈ $0 Lambda console starts a stateless EC2 jump host you tunnel through over SSM, then terminate.
5
+ Author: Frank Zhang
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/cloudformer/ztna
8
+ Project-URL: IdleFree, https://cloudformer.github.io/
9
+ Project-URL: Repository, https://github.com/cloudformer/ztna
10
+ Project-URL: Deploy, https://registry.terraform.io/modules/cloudformer/infra/aws/latest/submodules/ztna
11
+ Project-URL: Changelog, https://github.com/cloudformer/ztna/blob/main/CHANGELOG.md
12
+ Project-URL: Issues, https://github.com/cloudformer/ztna/issues
13
+ Keywords: serverless,aws,lambda,ec2,ssm,bastion,ztna,vpn
14
+ Classifier: Development Status :: 3 - Alpha
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: License :: OSI Approved :: MIT License
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Topic :: Security
19
+ Requires-Python: >=3.9
20
+ Description-Content-Type: text/markdown
21
+ Requires-Dist: idlefree-auth
22
+ Requires-Dist: idlefree-ui
23
+
24
+ # ztna
25
+
26
+ **Zero-trust, on-demand access to private resources: a persistent ≈ $0 Lambda console starts a stateless EC2 jump
27
+ host in the network you pick, you tunnel through it over SSM — a port-forward to your laptop, or a SOCKS tunnel
28
+ (VPN-like) — and it is terminated when you are done.** Part of [IdleFree](https://cloudformer.github.io/).
29
+
30
+ ![the ztna console](https://raw.githubusercontent.com/cloudformer/ztna/main/docs/console.svg)
31
+
32
+ ![ztna architecture](https://raw.githubusercontent.com/cloudformer/ztna/main/docs/architecture.svg)
33
+
34
+ This package holds the service: the Lambda (web console + API) and the jump agent (self-terminate on lease / idle).
35
+ Deploy it with the Terraform module
36
+ [cloudformer/infra/aws//modules/ztna](https://registry.terraform.io/modules/cloudformer/infra/aws/latest/submodules/ztna),
37
+ which installs this package from PyPI. Project: [cloudformer/ztna](https://github.com/cloudformer/ztna).
@@ -0,0 +1,11 @@
1
+ README.md
2
+ pyproject.toml
3
+ ztna/__init__.py
4
+ ztna.egg-info/PKG-INFO
5
+ ztna.egg-info/SOURCES.txt
6
+ ztna.egg-info/dependency_links.txt
7
+ ztna.egg-info/requires.txt
8
+ ztna.egg-info/top_level.txt
9
+ ztna/server/__init__.py
10
+ ztna/server/index.html
11
+ ztna/server/lambda_function.py
@@ -0,0 +1,2 @@
1
+ idlefree-auth
2
+ idlefree-ui
@@ -0,0 +1 @@
1
+ ztna