Last active
November 5, 2024 13:37
-
-
Save ChrisPhillips-cminion/4979bf545c0e806bcdb1c36cd320724e to your computer and use it in GitHub Desktop.
APIC-GlobalPolicy-filterIp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| global-policy: 1.0.0 | |
| info: | |
| title: Filter-IP | |
| name: filterip | |
| version: 1.0.0 | |
| description: Only allow specific IPs through | |
| contact: | |
| name: Chris Phillips & Amit Kumar Singh | |
| email: [email protected] | |
| mode: before-builtin | |
| gateways: | |
| - datapower-api-gateway | |
| assembly: | |
| execute: | |
| - gatewayscript: | |
| version: 2.0.0 | |
| title: gatewayscript | |
| source: >+ | |
| // You can use the command oc get network.config/cluster -o jsonpath='{.spec.clusterNetwork[0].cidr}' | |
| // to get the cidr range of OCP cluster which gets used to compare in script | |
| // Get the source IP Address from the request context | |
| var sourceIp = context.get('message.headers')['X-Client-IP']; | |
| // Log source IP to console.error | |
| console.error("Source IP is " + sourceIp); | |
| // Check if sourceIp is from ingress layer | |
| var xForwardedFor = context.get('message.headers')['X-Forwarded-For']; | |
| if(xForwardedFor) | |
| { | |
| var ips = xForwardedFor.split(','); | |
| sourceIp = ips[0].trim(); | |
| console.error("Originating sourceIp " + sourceIp); | |
| } | |
| else | |
| { | |
| console.error("Originating sourceIp " + sourceIp); | |
| } | |
| function ipToLongConv(sourceIp) | |
| { | |
| return sourceIp.split('.').reduce((acc, octet) => (acc << 8) + parseInt(octet, 10), 0) >>> 0; | |
| } | |
| function issourceIpInsideOCP(sourceIp, clusterCIDR) | |
| { | |
| const [range, mask] = clusterCIDR.split('/'); | |
| const ipLong = ipToLongConv(sourceIp); | |
| const rangeLong = ipToLongConv(range); | |
| const maskLong = ~(Math.pow(2, (32 - mask)) - 1); | |
| return (ipLong & maskLong) === (rangeLong & maskLong); | |
| } | |
| var clusterCIDR = '9.129.0.0/14'; | |
| if(!issourceIpInsideOCP(sourceIp, clusterCIDR)) | |
| { | |
| console.error("SourceError "+" SourceIp is outside of expected range "+sourceIp+" "+clusterCIDR) | |
| context.reject("SourceError","SourceIp is outside of expected range"); | |
| } | |
| else | |
| { | |
| console.error("sourceIp is inside of OCP") | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment