1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

cdkでip制限をやってみた

Posted at

はじめに

クラメソさんの記事のWAF実装をCDKでやってみようと思います。前の記事CloudFrontを使ってS3のウェブ公開とかやった分が残っていてのでそこに今回はIP制限を加えたいと思います。
ベースとなるコードはこちらです

準備

今回はv2がうまく動かせなかったので、aws-wafを使います。

yarn add @aws-cdk/aws-waf

これで面倒なのは他のCDKのライブラリも同じバージョンにしないといけないことなんですよね。。。

IPアドレスのホワイトリストを作成

CfnIPSetを使ってホワイトリストを作成します。今回は適当に0.0.0.0/32としておきます。

const ipSet = new waf.CfnIPSet(this, 'IpSet', {
  name: 'whiteList',
  ipSetDescriptors: [
    {
      type: 'IPV4',
      value: '0.0.0.0/32'
    }
  ]  
})

ルールを作成

CfnRuleを使ってホワイトリストのルールを作成します。

const rule = new waf.CfnRule(this, 'rule', {
  metricName: 'whiteListRule',
  name: 'whiteList',
  predicates: [
    {
      dataId: ipSet.ref,
      negated: false,
      type: 'IPMatch',
    }
  ]
})

WebAclの作成

最後にCfnRuleを使って、ホワイトリストに当てはまらないIPからのアクセスはすべてブロックするようなルールを記述します。

const webAcl = new waf.CfnWebACL(this, 'webAcl', {
  defaultAction: {
    type: 'BLOCK',
  },
  metricName: 'webAcl',
  name: 'webAcl',
  rules: [
    {
      action: {
        type: 'ALLOW',
      },
      priority: 1,
      ruleId: rule.ref,
    }
  ]
})

CloudFrontにあてる

前回用意したCloudFrontにwebAclをあてます。

const websiteDistribution = new cloudfront.CloudFrontWebDistribution(
  this,
  'WebsiteDistribution',
  {
    originConfigs: [
      {
        s3OriginSource: {
          s3BucketSource: websiteBucket,
          originAccessIdentity: websiteIdentity,
        },
        behaviors: [
          {
            isDefaultBehavior: true,
          },
        ],
      },
    ],
    webACLId: webAcl.ref,
  },
)

単純にwebACLId: webAcl.refが加わっただけですね。

さいごに

なんか個人的にはv2でない方が使いやすいなという印象なのですが(そもそも動かせなかったし)、どうなんでしょう。。。v2が使えないのは調べたところ、リージョン問題なのかなと思うのですがus-east-1でも失敗しました。他にも原因しらべてみたら成功するかもしれませんが、使い勝手があまり個人的に良くない気がするのでモチベーションが湧きませんでした。。cdkの方でなにかいいライブラリ作ってくれないですかね~(他力本願)。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?