Traditionally, a Web Application Firewall (WAF) would be the first layer requests would hit, before reaching the API gateway. This is not possible if the Gateway has to terminate SSL, for things such as mTLS.So what do you do if you still want to run your requests through a WAF to automatically scan for malicious action? We incorporate a WAF as part of the request lifecycle by using Tyk’s plugin architecture.
Copy the JS Plugin as a local .js file to the Gateway’s file system.From the Gateway root, this will download the plugin called waf.js into the middleware directory:
(Instructions)
If you are running Tyk in Docker, you can get into Tyk Gateway with docker exec
Copy
Ask AI
$ docker ps | grep gateway670039a3e0b8 tykio/tyk-gateway:latest "./entrypoint.sh" 14 minutes ago Up 14 minutes 0.0.0.0:8080->8080/tcp tyk-demo_tyk-gateway_1## copy container name or ID $ docker exec -it 670039a3e0b8 bash## Now SSH'd into Tyk Gateway container and can perform curlroot@670039a3e0b8:/opt/tyk-gateway# lsapps entrypoint.sh install middleware templates tyk-gateway.pid tyk.conf.examplecoprocess event_handlers js policies tyk tyk.conf utils## Download the pluginroot@670039a3e0b8:/opt/tyk-gateway# curl https://raw.githubusercontent.com/TykTechnologies/custom-plugins/master/plugins/js-pre-post-waf/waf.js | cat > middleware/waf.js % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed100 1125 100 1125 0 0 3906 0 --:--:-- --:--:-- --:--:-- 3975
Copy the following Tyk API definition and import it into your environment.API Definition JSONHere’s the important section which adds the plugin to the request lifecycle for this API:
$ curl 'localhost/?param="><script>alert(1);</script>'<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"><html><head><title>403 Forbidden</title></head><body><h1>Forbidden</h1><p>You don't have permission to access /on this server.<br /></p></body></html>
Our WAF catches the response and returns a 403.Now we try through Tyk.
Copy
Ask AI
## Clean requests, should get response from upstream's IP endpoint$ curl localhost:8080/waf/ip{ "origin": "172.30.0.1, 147.253.129.30"}## WAF will detect malicious payload and instruct Tyk to deny$ curl 'localhost:8080/waf/ip?param="><script>alert(1);</script>{ "error": "Bad request!"}