-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.template.yaml
861 lines (817 loc) · 33.1 KB
/
main.template.yaml
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
---
AWSTemplateFormatVersion: "2010-09-09"
Description: VPN on the Go
Parameters:
pStageName:
Type: String
Description: Name of the stage, used to build the invoke URL
Default: vpnonthego
pVpnPassword:
Type: String
Description: Password for auth
MinLength: 20
pVpnIpsecPsk:
Type: String
Description: IPSec PSK
Resources:
VpnOnTheGoCleanVpnLambdaRuleRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service: events.amazonaws.com
Action: sts:AssumeRole
VpnOnTheGoInstanceRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service: ec2.amazonaws.com
Action: sts:AssumeRole
VpnOnTheGoInstanceRolePolicy:
Type: AWS::IAM::Policy
Properties:
PolicyName: root
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- s3:GetObject
- s3:PutObject
- s3:DeleteObject
Resource: arn:aws:s3:::*
Roles:
- !Ref VpnOnTheGoInstanceRole
VpnOnTheGoApiGetClientRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service: apigateway.amazonaws.com
Action: sts:AssumeRole
VpnOnTheGoApiGetClientPolicy:
Type: AWS::IAM::Policy
Properties:
PolicyName: root
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- s3:GetObject
Resource: arn:aws:s3:::*
Roles:
- !Ref VpnOnTheGoApiGetClientRole
VpnOnTheGoInstanceProfile:
Type: AWS::IAM::InstanceProfile
Properties:
Roles:
- !Ref VpnOnTheGoInstanceRole
VpnOnTheGoBucket:
Type: AWS::S3::Bucket
VpnOnTheGoLambdasRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Action: sts:AssumeRole
Effect: Allow
Principal:
Service: lambda.amazonaws.com
ManagedPolicyArns:
- arn:aws:iam::aws:policy/AWSLambdaFullAccess
- arn:aws:iam::aws:policy/AmazonEC2FullAccess
- arn:aws:iam::aws:policy/AmazonAPIGatewayAdministrator
- arn:aws:iam::aws:policy/service-role/AmazonEC2SpotFleetRole
VpnOnTheGoCleanVpnLambdaPermission1:
Type: AWS::Lambda::Permission
Properties:
FunctionName: !Ref VpnOnTheGoCleanVpnLambda
Action: lambda:InvokeFunction
Principal: events.amazonaws.com
VpnOnTheGoCleanVpnLambdaPermission2:
Type: AWS::Lambda::Permission
Properties:
FunctionName: !Ref VpnOnTheGoCleanVpnLambda
Action: lambda:InvokeFunction
Principal: apigateway.amazonaws.com
VpnOnTheGoNewVpnLambda:
Type: AWS::Lambda::Function
Properties:
Description: This lambda creates a new OpenVPN instance
Handler: index.handler
Role: !GetAtt VpnOnTheGoLambdasRole.Arn
Runtime: python3.6
Timeout: 60
Code:
ZipFile: !Sub |
import json
import boto3
import uuid
import time
def die(msg): return { 'statusCode': 400, 'body': msg }
def handler(event, context):
# Checks
try:
body = json.loads(event['body'])
except Exception:
return die('No JSON body')
try:
region = body['region']
expire_in = int(body['expire_in'])
except Exception:
return die('No region or expire_in in body')
# Do
s = boto3.Session(region_name=region)
expire_tt = 0 if expire_in == 0 else int(time.time()) + ( expire_in * 60)
id = "{}_{}_{}".format(uuid.uuid4(), region, expire_tt)
bucket = '${VpnOnTheGoBucket}'
for name in [ 'in_progress', 'first_run_cleaner_ignore' ]:
s.client("s3").put_object(Bucket=bucket, Key=id + '/' + name)
# SG
ec2_client = s.client('ec2', region_name=region)
sg_group_id = ec2_client.create_security_group(Description='VPNONTHEGO', GroupName=id)['GroupId']
ports = [ 'udp500', 'udp4500', 'tcp1701', 'udp1194', 'tcp443', 'tcp5555' ]
for p in ports:
ec2_client.authorize_security_group_ingress(GroupId=sg_group_id, IpProtocol=p[:3], FromPort=int(p[3:]), ToPort=int(p[3:]), CidrIp='0.0.0.0/0')
# Find latest image
response = ec2_client.describe_images(
Filters=[
{ 'Name': 'owner-alias', 'Values': [ 'amazon' ] },
{ 'Name': 'virtualization-type', 'Values': [ 'hvm' ] },
{ 'Name': 'description', 'Values': [ 'Amazon Linux AMI * x86_64 HVM GP2' ] }
]
)
latest_image = sorted(response['Images'], key=lambda k: k['CreationDate'], reverse=True)[0]['ImageId']
# Request Spot instances
ports_to_expose = ''.join([' -p {n}:{n}/{p}'.format(p=p[:3], n=p[3:]) for p in ports])
ec2_resource = s.resource('ec2')
instance = ec2_resource.create_instances(
MinCount=1,
MaxCount=1,
SecurityGroupIds=[ sg_group_id ],
UserData="""#!/bin/bash -e
yum update -y
yum install -y docker
PASS=$(shuf -n 3 /usr/share/dict/words | sed ':a;N;$!ba;s/\\n/-/g')
export USERS=''
for n in $(seq 0 9); do
USERS+="vpnonthego$n:$PASS;"
done
service docker start
docker run -d -e PSK=${pVpnIpsecPsk} -e USERS --cap-add NET_ADMIN {ports_to_expose} siomiz/softethervpn > container
while
docker logs $(<container) > config.ovpn
! grep -q 'initial setup OK' < config.ovpn
do
sleep 1
done
echo "$(curl http://169.254.169.254/latest/meta-data/public-ipv4);$PASS" > metadata
aws s3 mv ./config.ovpn s3://{bucket}/{id}/
aws s3 mv ./metadata s3://{bucket}/{id}/
aws s3 rm s3://{bucket}/{id}/in_progress
""".format(bucket=bucket, id=id, ports_to_expose=ports_to_expose),
IamInstanceProfile={ 'Arn': '${VpnOnTheGoInstanceProfile.Arn}' },
InstanceMarketOptions={'MarketType': 'spot'},
InstanceType="t2.micro",
ImageId=latest_image,
TagSpecifications=[
{ 'ResourceType': 'instance', 'Tags': [ { 'Key': 'id', 'Value': id } ] },
#{ 'ResourceType': 'spot-instances-request', 'Tags': [ { 'Key': 'id', 'Value': id } ] }
],
)
# Plan deletion
if expire_in > 0:
cloudwatch_events = boto3.client('events')
cloudwatch_events.put_rule(
Name=id,
RoleArn='${VpnOnTheGoCleanVpnLambdaRuleRole.Arn}',
ScheduleExpression='rate({} minutes)'.format(expire_in), #TODO hours
State='ENABLED'
)
cloudwatch_events.put_targets(
Rule=id,
Targets=[ { 'Arn': '${VpnOnTheGoCleanVpnLambda.Arn}', 'Id': id, 'Input': json.dumps({'id': id}) } ]
)
return { 'statusCode': 200, 'body': id }
VpnOnTheGoNewVpnLambdaPermission:
Type: AWS::Lambda::Permission
Properties:
Action: lambda:InvokeFunction
FunctionName: !GetAtt VpnOnTheGoNewVpnLambda.Arn
Principal: apigateway.amazonaws.com
SourceArn: !Sub "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${VpnOnTheGoApi}/*"
VpnOnTheGoNewVpnLambdaLogGroup:
Type: AWS::Logs::LogGroup
Properties:
LogGroupName: !Sub "/aws/lambda/${VpnOnTheGoNewVpnLambda}"
RetentionInDays: 7
VpnOnTheGoGetVpnLambda:
Type: AWS::Lambda::Function
Properties:
Description: This lambda return the state of all OpenVpn instances
Handler: index.handler
Role: !GetAtt VpnOnTheGoLambdasRole.Arn
Runtime: python3.6
Timeout: 60
Code:
ZipFile: !Sub |
import json
import boto3
import time
from datetime import timedelta
def handler(event, context):
client_s3 = boto3.client('s3')
bucket = client_s3.list_objects(Bucket='${VpnOnTheGoBucket}')
res = {}
if 'Contents' in bucket:
for f in bucket['Contents']:
key, file = f['Key'].split('/')
if not key in res or not isinstance(res[key], dict):
_, region, expire_tt = key.split('_')
if expire_tt == 0:
expire = "never"
else:
now = int(time.time())
expire_tt = int(expire_tt)
expire = str(timedelta(seconds=(expire_tt - now)))
res[key] = { 'region': region, 'expire_tt': expire_tt, 'expire': expire}
if file == 'in_progress':
res[key]['in_progress'] = True
elif file == 'metadata':
metadata = client_s3.get_object(Bucket='${VpnOnTheGoBucket}', Key=f['Key'])['Body'].read().decode("utf-8")
res[key]['ip'], res[key]['pass'] = metadata.split(';')
elif file == 'first_run_cleaner_ignore' or file == 'config.ovpn':
continue
return { 'statusCode': 200, 'body': json.dumps(res) }
VpnOnTheGoGetVpnLambdaPermission:
Type: AWS::Lambda::Permission
Properties:
Action: lambda:InvokeFunction
FunctionName: !GetAtt VpnOnTheGoGetVpnLambda.Arn
Principal: apigateway.amazonaws.com
SourceArn: !Sub "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${VpnOnTheGoApi}/*"
VpnOnTheGoGetVpnLambdaLogGroup:
Type: AWS::Logs::LogGroup
Properties:
LogGroupName: !Sub "/aws/lambda/${VpnOnTheGoGetVpnLambda}"
RetentionInDays: 7
VpnOnTheGoCleanVpnLambda:
Type: AWS::Lambda::Function
Properties:
Description: Remove an OpenVpn instance
Handler: index.handler
Role: !GetAtt VpnOnTheGoLambdasRole.Arn
Runtime: python3.6
Timeout: 15
Code:
ZipFile: !Sub |
import boto3
def handler(event, context):
print(event)
if 'queryStringParameters' in event:
qs = event['queryStringParameters']
if not isinstance(qs, dict) or not 'id' in qs:
return { 'statusCode': 401 }
id = qs['id']
http = True
else:
id = event['id']
http = False
region = id.split('_')[1]
client_s3 = boto3.client('s3')
bucket = client_s3.list_objects(Bucket='${VpnOnTheGoBucket}', Prefix=id)
if not 'Contents' in bucket:
print('No content, so ignored')
return 0
for file in bucket['Contents']:
k = id + '/first_run_cleaner_ignore'
if file['Key'] == k:
client_s3.delete_object(Bucket='${VpnOnTheGoBucket}', Key=k)
print('First run ignored')
return 0
for file in bucket['Contents']:
client_s3.delete_object(Bucket='${VpnOnTheGoBucket}', Key=file['Key'])
client_ec2 = boto3.client('ec2', region_name=region)
r = client_ec2.describe_instances(Filters=[ { 'Name': 'tag:id', 'Values': [ id ] }])['Reservations'][0]['Instances'][0]
instance_id = r['InstanceId']
sir_id = r['SpotInstanceRequestId']
client_ec2.terminate_instances(InstanceIds=[ instance_id ])
client_ec2.cancel_spot_instance_requests(SpotInstanceRequestIds=[ sir_id ])
#client_ec2.delete_security_group(GroupName=id)
client_events = boto3.client('events')
client_events.remove_targets(Rule=id, Ids=[ id ])
client_events.delete_rule(Name=id)
print('All deleted')
if http:
return { 'statusCode': 200 }
VpnOnTheGoCleanVpnLambdaLogGroup:
Type: AWS::Logs::LogGroup
Properties:
LogGroupName: !Sub "/aws/lambda/${VpnOnTheGoCleanVpnLambda}"
RetentionInDays: 1
VpnOnTheGoNewVpnLambdaPermission:
Type: AWS::Lambda::Permission
Properties:
Action: lambda:InvokeFunction
FunctionName: !GetAtt VpnOnTheGoNewVpnLambda.Arn
Principal: apigateway.amazonaws.com
SourceArn: !Sub "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${VpnOnTheGoApi}/*"
VpnOnTheGoApi:
Type: AWS::ApiGateway::RestApi
Properties:
Name: VPN on the GO
FailOnWarnings: true
VpnOnTheGoApiGetHtmlMethod:
Type: AWS::ApiGateway::Method
Properties:
AuthorizationType: NONE
RestApiId: !Ref VpnOnTheGoApi
ResourceId: !GetAtt VpnOnTheGoApi.RootResourceId
HttpMethod: GET
MethodResponses:
- StatusCode: 200
ResponseParameters:
method.response.header.Content-Type: true
Integration:
Type: MOCK
PassthroughBehavior: WHEN_NO_MATCH
RequestTemplates:
application/json: '{"statusCode": 200}'
IntegrationResponses:
- StatusCode: 200
ResponseParameters:
method.response.header.Content-Type: "'text/html'"
ResponseTemplates:
text/html: |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>VPN on the Go</title>
<link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">
<link href="data:image/x-icon;base64,AAABAAEAEBAQAAEABAAoAQAAFgAAACgAAAAQAAAAIAAAAAEABAAAAAAAgAAAAAAAAAAAAAAAEAAAAAAAAACi5jgA////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABEAAAAAAAAAERAAAAAAAAAREQAAAAAAABEBEAAAAAAAEQARAAAAAAARAAEQAAAAABEAABEAAAAAEQAAARAAAAARAAAAEQAAABEAAAABEAAAEQAAAAARAAARAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" rel="icon" type="image/x-icon"/>
<style>
:root {
font-family: 'Montserrat', sans-serif;
}
section {
max-width: 900px;
margin: 40px auto 0;
border: solid 1px grey;
padding: 10px;
}
section h2 {
margin-top: -23px;
background: white;
float: left;
}
section h2 + * {
clear: left;
}
.flex {
display:flex;
flex-direction:row;
justify-content: space-between;
flex-wrap: nowrap;
align-items: center;
}
form label {
padding-right: 5px;
}
form input[type='number'] {
width: 50px;
}
.accent {
color: #38e6a2;
text-shadow: 0px 1px 0px #b4b4b4;
}
h1, h2 {
text-align: center;
}
h1 {
font-size: 50px;
}
.b {
background-color: Transparent;
border: 1px solid black;
outline: none;
}
input {
height: 30px;
}
article {
background: #f8f8f8;
margin-top: 10px;
padding: 5px;
text-transform: uppercase;
}
.access-denied, .access-granted, #template, #download-anchor, #toast, .hidden {
display: none;
}
.bold {
font-weight: bold;
}
input[type="submit"]:hover, .download {
cursor: pointer;
}
.shortId {
overflow: hidden;
max-width: 9ch;
white-space: nowrap;
text-overflow: ellipsis;
}
.about {
text-align: center;
margin: 27px auto 0;
display: block;
font-size: 14px;
}
#toast {
position: absolute;
bottom: 0;
margin: 0 auto;
text-align: center;
width: 100%;
background: #38e6a2;
color: white;
padding: 10px;
font-size: 20px;
}
.nott {
text-transform: none;
}
:focus {outline:none;}
::-moz-focus-inner {border:0;}
</style>
</head>
<body>
<h1 class="accent">VPN ON THE GO</h1>
<h2 class='access-denied accent'>Access Denied</h2>
<section id="passwordsection" style="display: block;">
<h2 class="accent">PASSWORD?</h2>
<form id="formpassword" class="flex">
<input id="password" style="width: 80%;" type="password">
<input value="SUBMIT" class="b accent" type="submit">
</form>
</section>
<section class='access-granted'>
<h2 class="accent">NEW</h2>
<form id="form" class="flex">
<div>
<label for="region">REGION</label>
<select id="region">
<option value='us-east-1'>USA, North Virginia</option>
<option value='us-west-1'>USA, North California</option>
<option value='us-west-2'>USA, Oregon</option>
<option selected="selected" value='eu-west-1'>Ireland</option>
<option value='ap-southeast-1'>Singapore</option>
<option value='ap-southeast-2 '>Australia, Sydney</option>
<option value='ap-northeast-1'>Japan, Tokyo</option>
<option value='sa-east-1'>São Paulo</option>
</select>
</div>
<div>
<label for="exp-value">EXPIRATION</label>
<input id="exp-value" type="number" min="1" value="6">
<select id="exp-unit">
<option value="1">MINUTES</option>
<option value="60" selected="selected">HOURS</option>
<option value="3600">DAYS</option>
</select>
</div>
<input type="submit" value="SUBMIT" class="b accent">
</form>
</section>
<section id="existing" class='access-granted'>
<h2 class="accent">EXISTING</h2>
<p></p>
<article>
<div class="flex bold">
<span>REGION</span>
<span>EXPIRATION</span>
<span>ID</span>
<input id="refresh" type="submit" value="REFRESH" class="b accent">
</div>
</article>
<article id='template'>
<div class="flex">
<span>{{region}}</span>
<span>{{expire}}</span>
<span class='shortId'>{{id}}</span>
<input type="submit" value="DELETE" class="b accent delete" data-id="{{id}}">
</div>
<p class="{{class_in_progress}}">IN PROGRESS...</p>
<ul class="{{class_metadata}}">
<li><span class="accent">IP:</span> <span class="nott">{{ip}}</span></li>
<li><span class="accent">PASSWORD:</span> <span class="nott">{{pass}}</span></li>
<li class="download" data-href="./api/client/?id={{id}}"><span class="accent">Download OpenVPN config file</span></li>
</ul>
</article>
</section>
<a class="accent about" href="https://github.com/sd65/VPN-on-the-Go">Help & info</a>
<p id="toast"></p>
<a id='download-anchor'></a>
<script>
password = ''
const showElements = (s) => Array.from(document.querySelectorAll(s)).forEach(e => e.style.display = 'block')
const getSelectValue = (e) => e.options[e.selectedIndex].value
const submitpassword = (e) => {
showToast('Logging in...')
e.preventDefault()
password = document.getElementById("password").value
document.getElementById("passwordsection").style.display = 'none'
refresh()
}
const submit = (e) => {
e.preventDefault()
showToast('Submiting...')
var expValue = parseInt(document.getElementById("exp-value").value)
var expUnit = parseInt(getSelectValue(document.getElementById("exp-unit")))
var payload = {
region: getSelectValue(document.getElementById("region")),
expire_in: expValue * expUnit
}
fetch("./api/server/",
{
method: "POST",
body: JSON.stringify(payload),
headers: {
'Content-Type': 'application/json',
'x-api-key': password
}
})
.then((res) => {
hideToast()
if(res.ok) {
return res.text()
} else {
throw new Error('Error while submiting')
}
})
.then((id) => {
showToast("New VPN " + id + " created.");
setTimeout(() => {
refresh()
}, 3000)
})
.catch(alert)
}
const refresh = () => {
showToast('Refreshing...')
fetch('./api/server/', { headers: { 'x-api-key': password } })
.then((res) => {
hideToast()
if(res.ok) {
return res.json()
} else {
throw new Error()
}
})
.then((r) => {
showElements(".access-granted")
Array.from(document.querySelectorAll("#existing > *:nth-child(n+5)")).forEach(e => e.parentNode.removeChild(e))
var template = '<p style="text-align: center">No content</p>'
if (Object.keys(r).length !== 0) {
template = document.getElementById("template").outerHTML.replace("id=", 'data-id=')
for (id in r) {
for (key of [ 'region', 'expire', 'id' ]) {
let replacement = (key === 'id') ? id : r[id][key]
template = template.replace(new RegExp('{{' + key + '}}', 'g'), replacement)
}
if (r[id].ip && r[id].pass) {
template = template.replace(new RegExp('{{class_metadata}}', 'g'), '')
template = template.replace(new RegExp('{{class_in_progress}}', 'g'), 'hidden')
template = template.replace(new RegExp('{{ip}}', 'g'), r[id].ip)
template = template.replace(new RegExp('{{pass}}', 'g'), r[id].pass)
} else {
template = template.replace(new RegExp('{{class_metadata}}', 'g'), 'hidden')
template = template.replace(new RegExp('{{class_in_progress}}', 'g'), '')
}
}
}
document.getElementById("existing").insertAdjacentHTML( 'beforeend', template );
})
.catch(() => showElements(".access-denied"))
}
const clickHandler = (e) => {
var initElem = e.target;
if(initElem.className === 'download') {
var anchor = document.getElementById("download-anchor")
client = initElem.getAttribute("data-href")
fetch(client, { headers: { 'x-api-key': password } })
.then(response => response.blob())
.then(blob => URL.createObjectURL(blob))
.then(url => {
anchor.setAttribute("href", url)
anchor.setAttribute("download", client.split('=')[1].replace('/', '--'))
anchor.click()
URL.revokeObjectURL(url);
});
} else if(initElem.className.includes('delete')) {
showToast('Deleting...')
var id = initElem.getAttribute("data-id")
fetch('./api/server/?id=' + id, { headers: { 'x-api-key': password }, method: 'DELETE' })
.then((res) => {
hideToast()
if(res.ok) {
return
} else {
throw new Error()
}
})
.then(() => {
setTimeout(refresh, 3000)
})
.catch((e) => {
alert('Error')
})
}
}
const showToast = (msg) => {
var t = document.getElementById("toast")
t.style.display = 'block'
t.innerText = msg
}
const hideToast = () => {
document.getElementById("toast").style.display = 'none'
}
document.getElementById("form").addEventListener("submit", submit)
document.getElementById("refresh").addEventListener("click", refresh)
document.getElementById('existing').addEventListener('click', clickHandler)
document.getElementById("formpassword").addEventListener("submit", submitpassword)
</script>
</body>
</html>
VpnOnTheGoApiResource:
Type: AWS::ApiGateway::Resource
Properties:
RestApiId: !Ref VpnOnTheGoApi
ParentId: !GetAtt VpnOnTheGoApi.RootResourceId
PathPart: 'api'
VpnOnTheGoVpnResource:
Type: AWS::ApiGateway::Resource
Properties:
RestApiId: !Ref VpnOnTheGoApi
ParentId: !Ref VpnOnTheGoApiResource
PathPart: 'server'
VpnOnTheGoApiGetMethod:
Type: AWS::ApiGateway::Method
Properties:
AuthorizationType: NONE
ApiKeyRequired: true
RestApiId: !Ref VpnOnTheGoApi
ResourceId: !Ref VpnOnTheGoVpnResource
HttpMethod: GET
Integration:
Type: AWS_PROXY
IntegrationHttpMethod: POST
Uri: !Sub "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${VpnOnTheGoGetVpnLambda.Arn}/invocations"
VpnOnTheGoApiPostMethod:
Type: AWS::ApiGateway::Method
Properties:
AuthorizationType: NONE
ApiKeyRequired: true
RestApiId: !Ref VpnOnTheGoApi
ResourceId: !Ref VpnOnTheGoVpnResource
HttpMethod: POST
Integration:
Type: AWS_PROXY
IntegrationHttpMethod: POST
Uri: !Sub "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${VpnOnTheGoNewVpnLambda.Arn}/invocations"
VpnOnTheGoApiDeleteMethod:
Type: AWS::ApiGateway::Method
Properties:
AuthorizationType: NONE
ApiKeyRequired: true
RestApiId: !Ref VpnOnTheGoApi
ResourceId: !Ref VpnOnTheGoVpnResource
HttpMethod: DELETE
Integration:
Type: AWS_PROXY
IntegrationHttpMethod: POST
Uri: !Sub "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${VpnOnTheGoCleanVpnLambda.Arn}/invocations"
VpnOnTheGoClientResource:
Type: AWS::ApiGateway::Resource
Properties:
RestApiId: !Ref VpnOnTheGoApi
ParentId: !Ref VpnOnTheGoApiResource
PathPart: 'client'
VpnOnTheGoApiGetClientMethod:
Type: AWS::ApiGateway::Method
Properties:
AuthorizationType: NONE
ApiKeyRequired: true
RestApiId: !Ref VpnOnTheGoApi
ResourceId: !Ref VpnOnTheGoClientResource
HttpMethod: GET
RequestParameters:
method.request.querystring.id: true
MethodResponses:
- StatusCode: 200
ResponseParameters:
method.response.header.Content-Type: true
Integration:
Type: AWS
IntegrationHttpMethod: GET
Credentials: !GetAtt VpnOnTheGoApiGetClientRole.Arn
RequestParameters:
integration.request.path.id: method.request.querystring.id
Uri: !Sub "arn:aws:apigateway:${AWS::Region}:s3:path/${VpnOnTheGoBucket}/{id}/config.ovpn"
IntegrationResponses:
- StatusCode: 200
ResponseParameters:
method.response.header.Content-Type: "'binary/octet-stream'"
VpnOnTheGoApiDeployment:
Type: AWS::ApiGateway::Deployment
DependsOn:
- VpnOnTheGoApiGetHtmlMethod
- VpnOnTheGoApiGetMethod
- VpnOnTheGoApiPostMethod
Properties:
RestApiId: !Ref VpnOnTheGoApi
StageName: !Ref pStageName
VpnOnTheGoApiKeyCreatorLambdaCustomResource:
Type: AWS::CloudFormation::CustomResource
DependsOn:
- VpnOnTheGoApi
- VpnOnTheGoApiDeployment
Properties:
ServiceToken: !GetAtt VpnOnTheGoApiKeyCreatorLambda.Arn
VpnOnTheGoApiKeyCreatorLambda:
Type: AWS::Lambda::Function
Properties:
Description: This lambda called as a Cloudfomation Custom Resource create a Api Gateway Key with a specified password
Handler: index.handler
Role: !GetAtt VpnOnTheGoLambdasRole.Arn
Runtime: python3.6
Code:
ZipFile: !Sub |
import boto3
import cfnresponse
apigateway_client = boto3.client("apigateway")
def handler(event, context):
print(event)
name = 'VpnOnTheGoApiKey'
if event['RequestType'] == 'Delete':
key_id = apigateway_client.get_api_keys(
nameQuery=name,
includeValues=False
)['items'][0]['id']
apigateway_client.delete_api_key(apiKey=key_id)
cfnresponse.send(event, context, cfnresponse.SUCCESS, {})
return 0
key_id = apigateway_client.create_api_key(
name=name,
enabled=True,
value='${pVpnPassword}',
stageKeys=[
{
'restApiId': '${VpnOnTheGoApi}',
'stageName': '${pStageName}'
},
],
)['id']
cfnresponse.send(event, context, cfnresponse.SUCCESS, {'KeyId': key_id})
VpnOnTheGoOpenVpnInstallScriptLambdaLogGroup:
Type: AWS::Logs::LogGroup
Properties:
LogGroupName: !Sub "/aws/lambda/${VpnOnTheGoApiKeyCreatorLambda}"
RetentionInDays: 1
VpnOnTheGoUsagePlan:
Type: AWS::ApiGateway::UsagePlan
DependsOn:
- VpnOnTheGoApi
- VpnOnTheGoApiDeployment
Properties:
UsagePlanName: VpnOnTheGoUsagePlan
ApiStages:
- ApiId: !Ref VpnOnTheGoApi
Stage: !Ref pStageName
Quota:
Limit: 1000
Period: DAY
Throttle:
BurstLimit: 1
RateLimit: 1
VpnOnTheGoUsagePlanKey:
Type: AWS::ApiGateway::UsagePlanKey
Properties :
KeyId: !GetAtt VpnOnTheGoApiKeyCreatorLambdaCustomResource.KeyId
KeyType: API_KEY
UsagePlanId: !Ref VpnOnTheGoUsagePlan
Outputs:
ApiUrl:
Description: API URL
Value: !Sub "https://${VpnOnTheGoApi}.execute-api.${AWS::Region}.amazonaws.com/${pStageName}/"