-
Notifications
You must be signed in to change notification settings - Fork 4k
/
Copy pathnat.ts
627 lines (554 loc) · 19.9 KB
/
nat.ts
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
import { Connections, IConnectable } from './connections';
import { Instance } from './instance';
import { InstanceArchitecture, InstanceType } from './instance-types';
import { IKeyPair } from './key-pair';
import { CpuCredits } from './launch-template';
import { AmazonLinuxCpuType, AmazonLinuxGeneration, AmazonLinuxImage, IMachineImage, LookupMachineImage } from './machine-image';
import { Port } from './port';
import { ISecurityGroup, SecurityGroup } from './security-group';
import { UserData } from './user-data';
import { PrivateSubnet, PublicSubnet, RouterType, Vpc } from './vpc';
import * as iam from '../../aws-iam';
import { Fn, Token } from '../../core';
/**
* Direction of traffic to allow all by default.
*/
export enum NatTrafficDirection {
/**
* Allow all outbound traffic and disallow all inbound traffic.
*/
OUTBOUND_ONLY = 'OUTBOUND_ONLY',
/**
* Allow all outbound and inbound traffic.
*/
INBOUND_AND_OUTBOUND = 'INBOUND_AND_OUTBOUND',
/**
* Disallow all outbound and inbound traffic.
*/
NONE = 'NONE',
}
/**
* Pair represents a gateway created by NAT Provider
*/
export interface GatewayConfig {
/**
* Availability Zone
*/
readonly az: string;
/**
* Identity of gateway spawned by the provider
*/
readonly gatewayId: string;
}
/**
* NAT providers
*
* Determines what type of NAT provider to create, either NAT gateways or NAT
* instance.
*
*
*/
export abstract class NatProvider {
/**
* Use NAT Gateways to provide NAT services for your VPC
*
* NAT gateways are managed by AWS.
*
* @see https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html
*/
public static gateway(props: NatGatewayProps = {}): NatProvider {
return new NatGatewayProvider(props);
}
/**
* Use NAT instances to provide NAT services for your VPC
*
* NAT instances are managed by you, but in return allow more configuration.
*
* Be aware that instances created using this provider will not be
* automatically replaced if they are stopped for any reason. You should implement
* your own NatProvider based on AutoScaling groups if you need that.
*
* @see https://docs.aws.amazon.com/vpc/latest/userguide/VPC_NAT_Instance.html
*
* @deprecated use instanceV2. 'instance' is deprecated since NatInstanceProvider
* uses a instance image that has reached EOL on Dec 31 2023
*/
public static instance(props: NatInstanceProps): NatInstanceProvider {
return new NatInstanceProvider(props);
}
/**
* Use NAT instances to provide NAT services for your VPC
*
* NAT instances are managed by you, but in return allow more configuration.
*
* Be aware that instances created using this provider will not be
* automatically replaced if they are stopped for any reason. You should implement
* your own NatProvider based on AutoScaling groups if you need that.
*
* @see https://docs.aws.amazon.com/vpc/latest/userguide/VPC_NAT_Instance.html
*/
public static instanceV2(props: NatInstanceProps): NatInstanceProviderV2 {
return new NatInstanceProviderV2(props);
}
/**
* Return list of gateways spawned by the provider
*/
public abstract readonly configuredGateways: GatewayConfig[];
/**
* Called by the VPC to configure NAT
*
* Don't call this directly, the VPC will call it automatically.
*/
public abstract configureNat(options: ConfigureNatOptions): void;
/**
* Configures subnet with the gateway
*
* Don't call this directly, the VPC will call it automatically.
*/
public abstract configureSubnet(subnet: PrivateSubnet): void;
}
/**
* Options passed by the VPC when NAT needs to be configured
*
*
*/
export interface ConfigureNatOptions {
/**
* The VPC we're configuring NAT for
*/
readonly vpc: Vpc;
/**
* The public subnets where the NAT providers need to be placed
*/
readonly natSubnets: PublicSubnet[];
/**
* The private subnets that need to route through the NAT providers.
*
* There may be more private subnets than public subnets with NAT providers.
*/
readonly privateSubnets: PrivateSubnet[];
}
/**
* Properties for a NAT gateway
*
*/
export interface NatGatewayProps {
/**
* EIP allocation IDs for the NAT gateways
*
* @default - No fixed EIPs allocated for the NAT gateways
*/
readonly eipAllocationIds?: string[];
}
/**
* Properties for a NAT instance
*
*
*/
export interface NatInstanceProps {
/**
* The machine image (AMI) to use
*
* By default, will do an AMI lookup for the latest NAT instance image.
*
* If you have a specific AMI ID you want to use, pass a `GenericLinuxImage`. For example:
*
* ```ts
* ec2.NatProvider.instance({
* instanceType: new ec2.InstanceType('t3.micro'),
* machineImage: new ec2.GenericLinuxImage({
* 'us-east-2': 'ami-0f9c61b5a562a16af'
* })
* })
* ```
*
* @default - Latest NAT instance image
*/
readonly machineImage?: IMachineImage;
/**
* Instance type of the NAT instance
*/
readonly instanceType: InstanceType;
/**
* Name of SSH keypair to grant access to instance
*
* @default - No SSH access will be possible.
* @deprecated - Use `keyPair` instead - https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ec2-readme.html#using-an-existing-ec2-key-pair
*/
readonly keyName?: string;
/**
* The SSH keypair to grant access to the instance.
*
* @default - No SSH access will be possible.
*/
readonly keyPair?: IKeyPair;
/**
* Security Group for NAT instances
*
* @default - A new security group will be created
* @deprecated - Cannot create a new security group before the VPC is created,
* and cannot create the VPC without the NAT provider.
* Set {@link defaultAllowedTraffic} to {@link NatTrafficDirection.NONE}
* and use {@link NatInstanceProviderV2.gatewayInstances} to retrieve
* the instances on the fly and add security groups
*
* @example
* const natGatewayProvider = ec2.NatProvider.instanceV2({
* instanceType: new ec2.InstanceType('t3.small'),
* defaultAllowedTraffic: ec2.NatTrafficDirection.NONE,
* });
* const vpc = new ec2.Vpc(this, 'Vpc', { natGatewayProvider });
*
* const securityGroup = new ec2.SecurityGroup(this, 'SecurityGroup', {
* vpc,
* allowAllOutbound: false,
* });
* securityGroup.addEgressRule(ec2.Peer.anyIpv4(), ec2.Port.tcp(443));
* for (const gatewayInstance of natGatewayProvider.gatewayInstances) {
* gatewayInstance.addSecurityGroup(securityGroup);
* }
*/
readonly securityGroup?: ISecurityGroup;
/**
* Allow all inbound traffic through the NAT instance
*
* If you set this to false, you must configure the NAT instance's security
* groups in another way, either by passing in a fully configured Security
* Group using the `securityGroup` property, or by configuring it using the
* `.securityGroup` or `.connections` members after passing the NAT Instance
* Provider to a Vpc.
*
* @default true
* @deprecated - Use `defaultAllowedTraffic`.
*/
readonly allowAllTraffic?: boolean;
/**
* Direction to allow all traffic through the NAT instance by default.
*
* By default, inbound and outbound traffic is allowed.
*
* If you set this to another value than INBOUND_AND_OUTBOUND, you must
* configure the NAT instance's security groups in another way, either by
* passing in a fully configured Security Group using the `securityGroup`
* property, or by configuring it using the `.securityGroup` or
* `.connections` members after passing the NAT Instance Provider to a Vpc.
*
* @default NatTrafficDirection.INBOUND_AND_OUTBOUND
*/
readonly defaultAllowedTraffic?: NatTrafficDirection;
/**
* Specifying the CPU credit type for burstable EC2 instance types (T2, T3, T3a, etc).
* The unlimited CPU credit option is not supported for T3 instances with dedicated host (`host`) tenancy.
*
* @default - T2 instances are standard, while T3, T4g, and T3a instances are unlimited.
*/
readonly creditSpecification?: CpuCredits;
/**
* Custom user data to run on the NAT instances
*
* @default UserData.forLinux().addCommands(...NatInstanceProviderV2.DEFAULT_USER_DATA_COMMANDS); - Appropriate user data commands to initialize and configure the NAT instances
* @see https://docs.aws.amazon.com/vpc/latest/userguide/VPC_NAT_Instance.html#create-nat-ami
*/
readonly userData?: UserData;
}
/**
* Provider for NAT Gateways
*/
export class NatGatewayProvider extends NatProvider {
private gateways: PrefSet<string> = new PrefSet<string>();
constructor(private readonly props: NatGatewayProps = {}) {
super();
}
public configureNat(options: ConfigureNatOptions) {
if (
this.props.eipAllocationIds != null
&& !Token.isUnresolved(this.props.eipAllocationIds)
&& this.props.eipAllocationIds.length < options.natSubnets.length
) {
throw new Error(`Not enough NAT gateway EIP allocation IDs (${this.props.eipAllocationIds.length} provided) for the requested subnet count (${options.natSubnets.length} needed).`);
}
// Create the NAT gateways
let i = 0;
for (const sub of options.natSubnets) {
const eipAllocationId = this.props.eipAllocationIds ? pickN(i, this.props.eipAllocationIds) : undefined;
const gateway = sub.addNatGateway(eipAllocationId);
this.gateways.add(sub.availabilityZone, gateway.ref);
i++;
}
// Add routes to them in the private subnets
for (const sub of options.privateSubnets) {
this.configureSubnet(sub);
}
}
public configureSubnet(subnet: PrivateSubnet) {
const az = subnet.availabilityZone;
const gatewayId = this.gateways.pick(az);
subnet.addRoute('DefaultRoute', {
routerType: RouterType.NAT_GATEWAY,
routerId: gatewayId,
enablesInternetConnectivity: true,
});
}
public get configuredGateways(): GatewayConfig[] {
return this.gateways.values().map(x => ({ az: x[0], gatewayId: x[1] }));
}
}
/**
* NAT provider which uses NAT Instances
*
* @deprecated use NatInstanceProviderV2. NatInstanceProvider is deprecated since
* the instance image used has reached EOL on Dec 31 2023
*/
export class NatInstanceProvider extends NatProvider implements IConnectable {
private gateways: PrefSet<Instance> = new PrefSet<Instance>();
private _securityGroup?: ISecurityGroup;
private _connections?: Connections;
constructor(private readonly props: NatInstanceProps) {
super();
if (props.defaultAllowedTraffic !== undefined && props.allowAllTraffic !== undefined) {
throw new Error('Can not specify both of \'defaultAllowedTraffic\' and \'defaultAllowedTraffic\'; prefer \'defaultAllowedTraffic\'');
}
if (props.keyName && props.keyPair) {
throw new Error('Cannot specify both of \'keyName\' and \'keyPair\'; prefer \'keyPair\'');
}
}
public configureNat(options: ConfigureNatOptions) {
const defaultDirection = this.props.defaultAllowedTraffic ??
(this.props.allowAllTraffic ?? true ? NatTrafficDirection.INBOUND_AND_OUTBOUND : NatTrafficDirection.OUTBOUND_ONLY);
// Create the NAT instances. They can share a security group and a Role.
const machineImage = this.props.machineImage ?? new NatInstanceImage();
this._securityGroup = this.props.securityGroup ?? new SecurityGroup(options.vpc, 'NatSecurityGroup', {
vpc: options.vpc,
description: 'Security Group for NAT instances',
allowAllOutbound: isOutboundAllowed(defaultDirection),
});
this._connections = new Connections({ securityGroups: [this._securityGroup] });
if (isInboundAllowed(defaultDirection)) {
this.connections.allowFromAnyIpv4(Port.allTraffic());
}
// FIXME: Ideally, NAT instances don't have a role at all, but
// 'Instance' does not allow that right now.
const role = new iam.Role(options.vpc, 'NatRole', {
assumedBy: new iam.ServicePrincipal('ec2.amazonaws.com'),
});
for (const sub of options.natSubnets) {
const natInstance = new Instance(sub, 'NatInstance', {
instanceType: this.props.instanceType,
machineImage,
sourceDestCheck: false, // Required for NAT
vpc: options.vpc,
vpcSubnets: { subnets: [sub] },
securityGroup: this._securityGroup,
role,
keyPair: this.props.keyPair,
keyName: this.props.keyName,
creditSpecification: this.props.creditSpecification,
});
// NAT instance routes all traffic, both ways
this.gateways.add(sub.availabilityZone, natInstance);
}
// Add routes to them in the private subnets
for (const sub of options.privateSubnets) {
this.configureSubnet(sub);
}
}
/**
* The Security Group associated with the NAT instances
*/
public get securityGroup(): ISecurityGroup {
if (!this._securityGroup) {
throw new Error('Pass the NatInstanceProvider to a Vpc before accessing \'securityGroup\'');
}
return this._securityGroup;
}
/**
* Manage the Security Groups associated with the NAT instances
*/
public get connections(): Connections {
if (!this._connections) {
throw new Error('Pass the NatInstanceProvider to a Vpc before accessing \'connections\'');
}
return this._connections;
}
public get configuredGateways(): GatewayConfig[] {
return this.gateways.values().map(x => ({ az: x[0], gatewayId: x[1].instanceId }));
}
public configureSubnet(subnet: PrivateSubnet) {
const az = subnet.availabilityZone;
const gatewayId = this.gateways.pick(az).instanceId;
subnet.addRoute('DefaultRoute', {
routerType: RouterType.INSTANCE,
routerId: gatewayId,
enablesInternetConnectivity: true,
});
}
}
/**
* Preferential set
*
* Picks the value with the given key if available, otherwise distributes
* evenly among the available options.
*/
class PrefSet<A> {
private readonly map: Record<string, A> = {};
private readonly vals = new Array<[string, A]>();
private next: number = 0;
public add(pref: string, value: A) {
this.map[pref] = value;
this.vals.push([pref, value]);
}
public pick(pref: string): A {
if (this.vals.length === 0) {
throw new Error('Cannot pick, set is empty');
}
if (pref in this.map) { return this.map[pref]; }
return this.vals[this.next++ % this.vals.length][1];
}
public values(): Array<[string, A]> {
return this.vals;
}
}
/**
* Modern NAT provider which uses NAT Instances.
* The instance uses Amazon Linux 2023 as the operating system.
*/
export class NatInstanceProviderV2 extends NatProvider implements IConnectable {
/**
* Amazon Linux 2023 NAT instance user data commands
* Enable iptables on the instance, enable persistent IP forwarding, configure NAT on instance
* @see https://docs.aws.amazon.com/vpc/latest/userguide/VPC_NAT_Instance.html#create-nat-ami
*/
public static readonly DEFAULT_USER_DATA_COMMANDS = [
'yum install iptables-services -y',
'systemctl enable iptables',
'systemctl start iptables',
'echo "net.ipv4.ip_forward=1" > /etc/sysctl.d/custom-ip-forwarding.conf',
'sudo sysctl -p /etc/sysctl.d/custom-ip-forwarding.conf',
"sudo /sbin/iptables -t nat -A POSTROUTING -o $(route | awk '/^default/{print $NF}') -j MASQUERADE",
'sudo /sbin/iptables -F FORWARD',
'sudo service iptables save',
];
private gateways: PrefSet<Instance> = new PrefSet<Instance>();
private _securityGroup?: ISecurityGroup;
private _connections?: Connections;
/**
* Array of gateway instances spawned by the provider after internal configuration
*/
public get gatewayInstances(): Instance[] {
return this.gateways.values().map(([, instance]) => instance);
}
constructor(private readonly props: NatInstanceProps) {
super();
if (props.defaultAllowedTraffic !== undefined && props.allowAllTraffic !== undefined) {
throw new Error('Can not specify both of \'defaultAllowedTraffic\' and \'defaultAllowedTraffic\'; prefer \'defaultAllowedTraffic\'');
}
if (props.keyName && props.keyPair) {
throw new Error('Cannot specify both of \'keyName\' and \'keyPair\'; prefer \'keyPair\'');
}
}
public configureNat(options: ConfigureNatOptions) {
const defaultDirection = this.props.defaultAllowedTraffic ??
(this.props.allowAllTraffic ?? true ? NatTrafficDirection.INBOUND_AND_OUTBOUND : NatTrafficDirection.OUTBOUND_ONLY);
// Create the NAT instances. They can share a security group and a Role. The new NAT instance created uses latest
// Amazon Linux 2023 image. This is important since the original NatInstanceProvider uses an instance image that has
// reached EOL on Dec 31 2023
const machineImage = this.props.machineImage || new AmazonLinuxImage({
generation: AmazonLinuxGeneration.AMAZON_LINUX_2023,
cpuType: this.props.instanceType.architecture == InstanceArchitecture.ARM_64 ? AmazonLinuxCpuType.ARM_64 : undefined,
});
this._securityGroup = this.props.securityGroup ?? new SecurityGroup(options.vpc, 'NatSecurityGroup', {
vpc: options.vpc,
description: 'Security Group for NAT instances',
allowAllOutbound: isOutboundAllowed(defaultDirection),
});
this._connections = new Connections({ securityGroups: [this._securityGroup] });
if (isInboundAllowed(defaultDirection)) {
this.connections.allowFromAnyIpv4(Port.allTraffic());
}
let userData = this.props.userData;
if (!userData) {
userData = UserData.forLinux();
userData.addCommands(...NatInstanceProviderV2.DEFAULT_USER_DATA_COMMANDS);
}
for (const sub of options.natSubnets) {
const natInstance = new Instance(sub, 'NatInstance', {
instanceType: this.props.instanceType,
machineImage,
sourceDestCheck: false, // Required for NAT
vpc: options.vpc,
vpcSubnets: { subnets: [sub] },
securityGroup: this._securityGroup,
keyPair: this.props.keyPair,
keyName: this.props.keyName,
creditSpecification: this.props.creditSpecification,
userData,
});
// NAT instance routes all traffic, both ways
this.gateways.add(sub.availabilityZone, natInstance);
}
// Add routes to them in the private subnets
for (const sub of options.privateSubnets) {
this.configureSubnet(sub);
}
}
/**
* The Security Group associated with the NAT instances
*/
public get securityGroup(): ISecurityGroup {
if (!this._securityGroup) {
throw new Error('Pass the NatInstanceProvider to a Vpc before accessing \'securityGroup\'');
}
return this._securityGroup;
}
/**
* Manage the Security Groups associated with the NAT instances
*/
public get connections(): Connections {
if (!this._connections) {
throw new Error('Pass the NatInstanceProvider to a Vpc before accessing \'connections\'');
}
return this._connections;
}
public get configuredGateways(): GatewayConfig[] {
return this.gateways.values().map(x => ({ az: x[0], gatewayId: x[1].instanceId }));
}
public configureSubnet(subnet: PrivateSubnet) {
const az = subnet.availabilityZone;
const gatewayId = this.gateways.pick(az).instanceId;
subnet.addRoute('DefaultRoute', {
routerType: RouterType.INSTANCE,
routerId: gatewayId,
enablesInternetConnectivity: true,
});
}
}
/**
* Machine image representing the latest NAT instance image
*
*
*/
export class NatInstanceImage extends LookupMachineImage {
constructor() {
super({
name: 'amzn-ami-vpc-nat-*',
owners: ['amazon'],
});
}
}
function isOutboundAllowed(direction: NatTrafficDirection) {
return direction === NatTrafficDirection.INBOUND_AND_OUTBOUND ||
direction === NatTrafficDirection.OUTBOUND_ONLY;
}
function isInboundAllowed(direction: NatTrafficDirection) {
return direction === NatTrafficDirection.INBOUND_AND_OUTBOUND;
}
/**
* Token-aware pick index function
*/
function pickN(i: number, xs: string[]) {
if (Token.isUnresolved(xs)) { return Fn.select(i, xs); }
if (i >= xs.length) {
throw new Error(`Cannot get element ${i} from ${xs}`);
}
return xs[i];
}