Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add functionality to restrict server access #171

Merged
merged 6 commits into from
Jul 26, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 25 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
- [Executing Optional Tasks](#executing-optional-tasks)
- [SSL Configuration](#ssl-configuration)
- [Setup OpenId Connect (OIDC) via Federate](#setup-openid-connect-oidc-via-federate)
- [Restricting Server Access](#restricting-server-access)
- [Data Retention](#data-retention)
- [Add environment variable](#add-environment-variables)
- [Assume role](#cross-account-assume-role)
Expand Down Expand Up @@ -74,6 +75,19 @@ $aws secretsmanager put-secret-value \
1. If you want to destroy the stack make sure you delete the agent nodes manually (via jenkins UI or AWS console) so that shared resources (like vpc, security groups, etc) can be deleted.

### Executing Optional Tasks
#### Construct Props
| Name | Type | Description |
| ------------- |:-------------| :-----|
| [useSsl](#ssl-configuration) | boolean | Should the Jenkins use https |
| [runWithOidc](#setup-openid-connect-oidc-via-federate) | boolean | Should an OIDC provider be installed on Jenkins |
| [ignoreResourcesFailures]() | boolean | Additional verification during deployment and resource startup |
| [adminUsers](#setup-openid-connect-oidc-via-federate) | string[] | List of users with admin access during initial deployment |
| [additionalCommands](#runnning-additional-commands) | string | Additional logic that needs to be run on Master Node. The value has to be path to a file |
| [dataRetention](#data-retention) | boolean | Do you want to retain jenkins jobs and build history |
| [agentAssumeRole](#assume-role) | string | IAM role ARN to be assumed by jenkins agent nodes |
| [envVarsFilePath](#add-environment-variables) | string | Path to file containing env variables in the form of key value pairs |
| [macAgent](#mac-agents) | boolean | Add mac agents to jenkins |
| [restrictServerAccessTo](#restricting-server-access) | Ipeer | Restrict jenkins server access |
#### SSL Configuration
1. Locate the secret manager arns in the ci-config-stack outputs
1. Update the secret value ([see docs](https://docs.aws.amazon.com/cli/latest/reference/secretsmanager/put-secret-value.html)) for the `certContentsSecret` with the certificate contents
Expand Down Expand Up @@ -117,6 +131,16 @@ $aws secretsmanager put-secret-value \
1. `cdk deploy OpenSearch-CI-Dev -c runWithOidc=true -c useSsl=true`
1. Continue with [next steps](#dev-deployment)

#### Restricting Server Access
You can now restrict access to your jenkins endpoint (load balancer). Here's how:
1. Update the `restrictServerAccessTo` property in `ciSettings` to your desired [Ipeer](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-ec2.IPeer.html). By default it is open to all.
See [CIStackProps](./lib/ci-stack.ts) for details.

Example:
```
const stack = new CIStack(app, 'MyStack', { restrictServerAccessTo: Peer.ipv4('10.0.0.0/24') });
```

#### Data Retention
Change in any EC2 config (specially init config) leads to replacement of EC2. The jenkins configuration is managed via code using configuration as code plugin. [More details](https://plugins.jenkins.io/configuration-as-code/).
See inital [jenkins.yaml](./resources/baseJenkins.yaml)
Expand Down Expand Up @@ -219,4 +243,4 @@ This project is licensed under the [Apache v2.0 License](LICENSE.txt).

## Copyright

Copyright OpenSearch Contributors. See [NOTICE](NOTICE.txt) for details.
Copyright OpenSearch Contributors. See [NOTICE](NOTICE.txt) for details.
13 changes: 8 additions & 5 deletions lib/ci-stack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,15 @@
* compatible open source license.
*/

import { FlowLogDestination, FlowLogTrafficType, Vpc } from '@aws-cdk/aws-ec2';
import {
FlowLogDestination, FlowLogTrafficType, IPeer, Vpc,
} from '@aws-cdk/aws-ec2';
import { Secret } from '@aws-cdk/aws-secretsmanager';
import {
CfnOutput,
CfnParameter, Construct, Fn, RemovalPolicy, Stack, StackProps,
CfnParameter, Construct, Fn, Stack, StackProps,
} from '@aws-cdk/core';
import { ListenerCertificate } from '@aws-cdk/aws-elasticloadbalancingv2';
import { FileSystem } from '@aws-cdk/aws-efs';
import { Bucket } from '@aws-cdk/aws-s3';
import { CIConfigStack } from './ci-config-stack';
import { JenkinsMainNode } from './compute/jenkins-main-node';
Expand All @@ -38,12 +39,14 @@ export interface CIStackProps extends StackProps {
readonly additionalCommands?: string;
/** Do you want to retain jenkins jobs and build history */
readonly dataRetention?: boolean;
/** Policy for agent node role to assume a cross-account role */
/** IAM role ARN to be assumed by jenkins agent nodes eg: cross-account */
readonly agentAssumeRole?: string;
/** File path containing global environment variables to be added to jenkins enviornment */
readonly envVarsFilePath?: string;
/** Add Mac agent to jenkins */
readonly macAgent?: boolean;
/** Restrict jenkins access to */
readonly restrictServerAccessTo? : IPeer;
}

export class CIStack extends Stack {
Expand Down Expand Up @@ -93,7 +96,7 @@ export class CIStack extends Stack {
default: useSsl,
});

const securityGroups = new JenkinsSecurityGroups(this, vpc, useSsl);
const securityGroups = new JenkinsSecurityGroups(this, vpc, useSsl, props?.restrictServerAccessTo);
const importedContentsSecretBucketValue = Fn.importValue(`${CIConfigStack.CERTIFICATE_CONTENTS_SECRET_EXPORT_VALUE}`);
const importedContentsChainBucketValue = Fn.importValue(`${CIConfigStack.CERTIFICATE_CHAIN_SECRET_EXPORT_VALUE}`);
const importedCertSecretBucketValue = Fn.importValue(`${CIConfigStack.PRIVATE_KEY_SECRET_EXPORT_VALUE}`);
Expand Down
4 changes: 2 additions & 2 deletions lib/network/ci-external-load-balancer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
*/

import {
Instance, Peer, SecurityGroup, Vpc,
Instance, SecurityGroup, Vpc,
} from '@aws-cdk/aws-ec2';
import {
ApplicationListener, ApplicationLoadBalancer, ApplicationProtocol, ApplicationProtocolVersion, ApplicationTargetGroup,
Expand Down Expand Up @@ -44,7 +44,7 @@ export class JenkinsExternalLoadBalancer {
this.listener = this.loadBalancer.addListener('JenkinsListener', {
sslPolicy: props.useSsl ? SslPolicy.RECOMMENDED : undefined,
port: accessPort,
open: true,
open: false,
certificates: props.useSsl ? [props.listenerCertificate] : undefined,
});

Expand Down
21 changes: 14 additions & 7 deletions lib/security/ci-security-groups.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@
* compatible open source license.
*/

import { Port, SecurityGroup, Vpc } from '@aws-cdk/aws-ec2';
import {
IPeer, Peer, Port, SecurityGroup, Vpc,
} from '@aws-cdk/aws-ec2';
import { Stack } from '@aws-cdk/core';

export class JenkinsSecurityGroups {
Expand All @@ -18,22 +20,27 @@ export class JenkinsSecurityGroups {

public readonly efsSG: SecurityGroup;

constructor(stack: Stack, vpc: Vpc, useSsl: boolean) {
constructor(stack: Stack, vpc: Vpc, useSsl: boolean, restrictServerAccessTo?: IPeer) {
let accessPort = 80;
if (useSsl) {
accessPort = 443;
}

this.externalAccessSG = new SecurityGroup(stack, 'ExternalAccessSG', {
vpc,
description: 'External access to Jenkins',
});
if (restrictServerAccessTo) {
this.externalAccessSG.addIngressRule(restrictServerAccessTo, Port.tcp(accessPort), 'Restrict access to this source');
} else {
this.externalAccessSG.addIngressRule(Peer.anyIpv4(), Port.tcp(accessPort), 'Allow anyone to connect');
}

this.mainNodeSG = new SecurityGroup(stack, 'MainNodeSG', {
vpc,
description: 'Main node of Jenkins',
});

const accessPort = 80;
this.mainNodeSG.addIngressRule(this.externalAccessSG, Port.tcp(accessPort));
if (useSsl) {
this.mainNodeSG.addIngressRule(this.externalAccessSG, Port.tcp(443));
}

this.agentNodeSG = new SecurityGroup(stack, 'AgentNodeSG', {
vpc,
Expand Down
29 changes: 29 additions & 0 deletions test/ci-stack.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import {
expect, countResources, haveResourceLike, ResourcePart,
} from '@aws-cdk/assert';
import { Peer } from '@aws-cdk/aws-ec2';
import { App } from '@aws-cdk/core';
import { CIStack } from '../lib/ci-stack';

Expand Down Expand Up @@ -64,6 +65,34 @@ test('External security group is open', () => {
}));
});

test('External security group is restricted', () => {
const app = new App({
context: { useSsl: 'true', runWithOidc: 'true' },
});

// WHEN
const stack = new CIStack(app, 'MyTestStack', { restrictServerAccessTo: Peer.ipv4('10.0.0.0/24') });

// THEN
expect(stack).to(haveResourceLike('AWS::EC2::SecurityGroup', {
GroupDescription: 'External access to Jenkins',
SecurityGroupEgress: [
{
CidrIp: '0.0.0.0/0',
},
],
}));

// Make sure that load balancer access is restricted to given Ipeer
expect(stack).to(haveResourceLike('AWS::EC2::SecurityGroup', {
SecurityGroupIngress: [
{
CidrIp: '10.0.0.0/24',
},
],
}));
});

test('MainNode', () => {
const app = new App({
context: { useSsl: 'true', runWithOidc: 'true' },
Expand Down