Simple Swift Firewall Middleware
Implementation od Firewall middleware used to track incoming HTTP requests to the server and block incoming traffic early, before passing requests to API.
- Temporarily block incoming requests from particular address if number of requests exceeds defined threshold (number of requests in one minute)
- Allow access to API only from known client IP addresses
- Permanently block incoming traffic from a list of known IPs.
- When using Swift Firewall in addition to Swift-Crypto-Tools, the firewall will also prevent access to API if "User-Agent" header is different from the one stored inside the token from Swift-Crypto-Tools.
- Open Source Swift 4.0.0 or higher
- macOS Sierra 10.12.6 or higher
- Xcode Version 9.0 (9A325) or higher
- Ubuntu 16.04 & 16.10 (only tested on 16.04)
Initialize an instance of Swift Firewall using:
let firewall = SwiftFirewall()
To add firewall as a middleware use:
router.all("/", middleware: firewall)
To explicitely define firewall tresholds use:
let firewall = SwiftFirewall(allowedNumberOfRequestsInOneMinute: numberOfRequests, banDurationInSeconds: banDuration, disableAccessFor: listOfIPs, onlyAllowedFrom: listOfOtherIPs) // where: // numberOfRequests: Int, defaults to 30 per minute // banDurationInSeconds: Int, defaults to 600 seconds // listOfIPs: [String], empty by default // listOfOtherIPs: [String], empty by default
In case, Swift Firewall is used alongside Swift-Crypto-Tools, another parameter can be used to pass Token secret key to firewall, in order to examine token content and match its header["User-Agent"]
let firewall = SwiftFirewall(allowedNumberOfRequestsInOneMinute: numberOfRequests, banDurationInSeconds: banDuration, disableAccessFor: listOfIPs, onlyAllowedFrom: listOfOtherIPs, swiftCryptoToolsTokenSecretKey: secretKey)
Blocking particular routes
Multiple instances of firewall can be used to prevent access to individual routes by defining a list of allowable IP addresses for particular route
// allow all incoming traffic let firewall = SwiftFirewall() router.all("/", middleware: firewall) // allow incoming traffic only from known IP address to "/admin" route let allowedList = [ "127.0.0.1", "127.0.0.2" ] let firewallAdmin = SwiftFirewall(onlyAllowedFrom: allowedList) router.all("/admin", middleware: firewallAdmin)