This repository was archived by the owner on Sep 26, 2021. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 71
/
Copy pathindex.js
164 lines (157 loc) · 4.55 KB
/
index.js
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
/*
* AWS Lambda function to authorize the client IP for an EC2 security group.
* https://github.com/blueimp/aws-lambda
*
* Required environment variables:
* - groupid: The ID of the security group, e.g. "sg-xxxxxxxx".
*
* Optional environment variables:
* - protocol: The protocol to authorize, defaults to "tcp".
* - port: The port to authorize, defaults to 22 (SSH).
* - description: Description for the inbound rule, defaults to "authorize-ip".
* - keepipranges: Comma-separated IP ranges to exclude from cleanup.
*
* Meant to be used with Amazon API Gateway, which sets the following property:
* - event.requestContext.identity.sourceIp
*
* Copyright 2017, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* https://opensource.org/licenses/MIT
*/
'use strict'
const ENV = process.env
if (!ENV.groupid) throw new Error('Missing environment variable: groupid')
const PROTOCOL = ENV.protocol || 'tcp'
const PORT = ENV.port || 22
const DESCRIPTION = ENV.description || 'authorize-ip'
// eslint-disable-next-line node/no-unpublished-require
const AWS = require('aws-sdk')
const EC2 = new AWS.EC2()
/**
* Authprizes the given IP
*
* @param {string} ip IP address
* @returns {Promise} Resolves if the authorization succeeds
*/
function authorizeIP(ip) {
const permission = {
IpProtocol: PROTOCOL,
FromPort: PORT,
ToPort: PORT
}
if (ip.indexOf(':') > -1) {
permission.Ipv6Ranges = [
{
Description: DESCRIPTION,
CidrIpv6: ip + '/128'
}
]
} else {
permission.IpRanges = [
{
Description: DESCRIPTION,
CidrIp: ip + '/32'
}
]
}
const params = {
GroupId: ENV.groupid,
IpPermissions: [permission]
}
return new Promise((resolve, reject) => {
EC2.authorizeSecurityGroupIngress(params)
.promise()
.then(() => {
// eslint-disable-next-line no-console
console.log('IP newly authorized:', ip)
resolve({ ip })
})
.catch(err => {
if (err.code === 'InvalidPermission.Duplicate') {
// eslint-disable-next-line no-console
console.log('IP already authorized:', ip)
return resolve({ ip })
}
reject(err)
})
})
}
/**
* Cleans up authorized IPs
*
* @returns {Promise} Resolves if the cleanup operation succeeds
*/
function cleanupIPs() {
const params = {
GroupIds: [ENV.groupid],
Filters: [
{
Name: 'ip-permission.protocol',
Values: [PROTOCOL]
},
{
Name: 'ip-permission.from-port',
Values: [PORT.toString()]
},
{
Name: 'ip-permission.to-port',
Values: [PORT.toString()]
}
]
}
return EC2.describeSecurityGroups(params)
.promise()
.then(data => {
const ipPermissions = data.SecurityGroups.length
? data.SecurityGroups[0].IpPermissions
: []
// eslint-disable-next-line no-console
console.log('IP permissions:', JSON.stringify(ipPermissions))
if (!ipPermissions.length) return null
const keepIpRanges = (ENV.keepipranges || '').split(',')
const revokeIpPermissions = ipPermissions.reduce((permissions, perm) => {
const IpRanges = perm.IpRanges.filter(
ipRange => !keepIpRanges.includes(ipRange.CidrIp)
)
const Ipv6Ranges = perm.Ipv6Ranges.filter(
ipv6Range => !keepIpRanges.includes(ipv6Range.CidrIpv6)
)
if (!IpRanges.length && !Ipv6Ranges.length) return permissions
const permission = {
IpProtocol: perm.IpProtocol,
FromPort: perm.FromPort,
ToPort: perm.ToPort
}
// IpRanges/Ipv6Ranges produce parameter errors when empty:
if (IpRanges.length) permission.IpRanges = IpRanges
if (Ipv6Ranges.length) permission.Ipv6Ranges = Ipv6Ranges
return [...permissions, permission]
}, [])
if (!revokeIpPermissions.length) return null
const params = {
GroupId: ENV.groupid,
IpPermissions: revokeIpPermissions
}
return EC2.revokeSecurityGroupIngress(params).promise()
})
}
exports.handler = (event, context, callback) => {
// eslint-disable-next-line no-console
console.log('Event:', JSON.stringify(event))
if (event.source === 'aws.events') {
return cleanupIPs()
.then(data => callback(null, data))
.catch(callback)
}
const ip = event.requestContext.identity.sourceIp
authorizeIP(ip)
.then(data =>
callback(null, {
statusCode: 200,
body: JSON.stringify(data)
})
)
.catch(callback)
}