OWASP’s 2017 top ten adds a new category called 'underprotected APIs', reflecting the growth of RESTful Web APIs and richer front-end clients which stress current security and access authorization approaches. You’ll learn about potential threats resulting from undersecured Web APIs and techniques to strengthen your API security posture. You'll gain a clear understanding of user authorization via OAuth2, software authorization via static API keys and the critical interplay between them. Of particular concern are mobile API consumers whose code is statically published with secrets which are often poorly concealed. Practical advice with code examples will show how to improve mobile API security. TLS is necessary but insufficient to fully secure client-server communications. Certificate pinning is explained with code examples to show how to strengthen channel communications. Some advanced techniques will be discussed such as app hardening, white box cryptography and mobile app attestation. You should gain a good understanding of the underprotected API problem, with some immediately practical tips to improve your API security posture and a sense of emerging tools and technologies that enable a significant step change in API security.
2. About Me
2
• Growth Hacker at CriticalBlue
• Chips -> HW/SW -> Embedded Performance -> Mobile Security
• Moved into security via Android and HSM optimization
• Focused on mobile API security
medium.com/@skiph approov.io critcalblue.com
5. Existing Attacks Intensified
APIs – More of the Same but Different
Traditional OWASP Top 10 applicable
Nothing fundamentally different
New Variations
Header tampering
Verb tampering
Increased Risk
Business logic moves to the client
Richer interfaces mean more API calls
More chances to miss input validation
5
6. The API Economy
6
Massive Growth in the Use of APIs
REST with JSON over https
Increased push and streaming flows
APIs Driving Digital Transformation
Monetize digital assets, B2C & B2B
Development and maintenance savings
Increasing Concern Over Security
Deeper interface into the enterprise
Customer facing APIs attractive target
8. Mobile API Threats
8
Gartner:
“… with the increase in mobile apps also comes an
increased desire for exposing more data and transactional
systems via Web APIs, which raises the bar for both the
client and the server security design.”
“Through 2019, the majority of mobile security breaches
will be exploiting vulnerabilities in the communication
of apps with the server.”
NowSecure 2016
9. Architecture Evolution - Client Complexity
9
Image: www.pingidentity.com, Application Integration Guide
Browser API
Serves web pages
Simple data transfer
Web Browser
Limited local functionality
Web Backend
Business logic here
Mobile App
Deep local business logic
Mobile API
Rich protocol
Complex data
App Backend
Server access point
11. API Taxonomy
11
● Accessible to anyone
● Public documentation
● Often simple sign-up API key protection
● Restricted documentation
● Restricted onboarding process
● Only as restricted as secrets
Public (Open) APIs
Private APIs
Partner APIs
● No public documentation
● Require access protection in place
● Only as private as the client app
12. Single App, Single API?
Mix of Public, Private and Partner APIs. Huge and complex overall attack surface
12
Mapping
API
Hotel
Availability
API
Hire Car
Availability
API
User
Authorization
API
Weather
API
Travel App
14. Instagram API Attack
On a password reset, capture the
request with a proxy rather than
the real Instagram servers.
Attackers modified the captured
request to substitute the
username with those of targeted
celebrities.
The Instagram server would then
send a JSON-formatted response
that included the target's
personal information.
14
August 2017
15. Pokemon Reverse Engineering
Mobile Game Released July 2016
>100 countries, >500M downloads
Mapping Features Caused Excess Server Load
Unofficial Pokeman dynamic maps appear online
API between Pokemon App and Niantic Servers
Undocumented and “private”
Man-in-the-Middle reverse engineering
Checksums Introduced, Community Breaks Them
Legal threats, Restrictive root checks, Captchas
15
16. Reverse Engineering Has Never Been Easier
Public APIs are well documented
Easy to probe and brute force
Leaky APIs disclose implementation
details and error handling
Hidden APIs accidentally exposed by
autodoc services
16
17. Shared Secrets - Using Without Losing
17
Mobile
App
Protect In Motion
Protect At Rest
APIe54499be5aed e54499be5aed
Proof of Possession
Lifetime and Revocation
18. Don’t Publish Your Secret
Ryan Hellyer had always wanted to open
source his website.
Satisfied that he had taken all the
necessary security precautions, Hellyer
pushed all the contents of his site to a
new GitHub repository.
Not four hours later, Hellyer received an
urgent message from Amazon...
18
https://wptavern.com/ryan-hellyers-aws-nightmare-
leaked-access-keys-result-in-a-6000-bill-overnight
21. Transport Layer Security
TLS (https) ensures message integrity and
confidentiality between client and server...
...If you trust the certification
The Heartbleed (CVE-2014-0160) bug enables
attackers to expose encrypted content,
usernames, passwords, and private keys for
X.509 certificates
Both 1-way (client trusts server) and 2-way
(mutual trust) are used
21
IBM
22. Man in the Middle Attack
22
API
Mobile
App
Intended Communication Channel
Actual Channel
Actual Channel
Attacker installs fake server certificate at client
If client trusts the certificate, snooping and tampering are possible
23. Certificate Pinning
Defends against MitM attacks
Client keeps whitelist of trusted
certificates
Only accepts connections from a
whitelisted certificate
Attacker cannot match a
whitelisted certificate or know the
certificate’s private key
23
24. Pinning Implementations
Implementation need not be difficult
Android OkHttpClient has direct support
Add SHA256 hashes of one or more server certificates
24
CertificatePinner certificatePinner = new CertificatePinner.Builder()
.add("publicobject.com", "sha256/afwiKY3RxoMmLkuRW1l7QsPZTJPwDS2pdDROQjXw8ig=")
.add("bikewise.org", "sha256/x9SZw6TwIqfmvrLZ/kz1o0Ossjmn728BnBKpUFqGNVM=")
.build();
OkHttpClient client = OkHttpClient.Builder().certificatePinner(certificatePinner)
.build();
When involving TrustManager, easy to introduce subtle flaws
See excellent resource by John Kozyrakis (https://koz.io/android-pinning-bugs/)
25. Pinning Upkeep
Server certificates, their public keys or
fingerprints are client secrets
Certificates may expire or be revoked
Updating the certificates on the client is a
maintenance challenge and a possible attack
vector
Depends on app integrity to prevent attacker
bypassing pinning logic (e.g SSL-TrustKiller)
25
Mobile
App
e54499be5aed
27. Detect and Block Abnormal Usage of APIs
API Probing and Fuzzing
App layer DDOS attacks
Data Scraping / Exfiltration
Credential Stuffing
27
28. Boost, Limit or Deny Service
28
Enforce whitelists, blacklists, service tiers
IP addresses
Device fingerprints
IMEI
API key
User identifier
GPS
Usage history
29. Rate Limiting and Load Shedding
Quotas, spike arrests, concurrency limits
Vary by expense of call (DB access)
Fixed or load adaptive
Tend to be very lenient - don't risk rejecting
legitimate customer usage
29
“Leaky Bucket”
Rate Limiting
Filled by Maximum API
Request Rate
Drained by Actual API
Request Rate
Overflow
Discarded
Practical Intro: https://stripe.com/blog/rate-limiters
30. Big Data with Machine Learning
Detect malicious API usage patterns
Can be self-learning
Lag zero day events
May emit false positives
30
Elastic Beam
32. API Key
Developers sign up to be issued an “API Key”
Random strings - “id and password for your program”
Best Practices
Keep the secret safe!
Do not embed in public code
32
e54499be5aed
33. Basic API Key ID Usage
Shared identifier or secret between client and service:
33
Prefer API key in header rather than query string
34. Request Signing
Signing proves client possesses secret and request is untampered
Does not prove that client is authentic unless secret is guaranteed secure
Responses can be signed; can use full encryption 34
35. Mobile App Reverse Engineering Tools
Publishing an App Exposes it to the World
Wide variety of analysis frameworks on iOS/Android
Decompile code, modify and repackage apps
Secrets can be reversed and abused
35
see: https://skillsmatter.com/skillscasts/10783-how-to-keep-your-api-keys-safe
https://github.com/approov/shipfast-api-protection
36. Reverse Engineering 16k Apps
Protecting Static Secrets in code
Roughly 2500 apps were found to
have either a key or a secret of a third
party service hardcoded in the app.
304 apps contained exploitable 3rd
party secrets
36
Source: https://hackernoon.com/we-reverse-engineered-16k-apps-heres-what-we-found-51bdf3b456bb
Fallible, 2016
37. There’s a Fake App for That
Use API keys to impersonate
real apps
Use API keys to impersonate
apps that don’t even exist!
37
Source: https://www.approov.io/blog/theres-a-fake-app-for-that.html
38. App Hardening
38
● White-Box Cryptography
○ Applied to secrets keys embedded in the app
○ Mathematically obfuscated operations
○ Risk of being run within attacker system
● Obfuscation and Anti-Tamper
○ Obfuscate app code and make tamper resistant
○ Increases the difficulty of reversing APIs
○ Protects secrets and code comprehension
● Software and Hardware Backed KeyStores
○ Safest place to store keys
○ Operations performed without exposing keys
○ Complexities in secure hardware usage
Mobile
App
39. Secret as a Service
Secret never stored in app
Signed, short-lived token retrieved on request and token never stored
Secret can be revoked or updated without touching app
39
40. App Integrity Measurement
For protection, use the app’s DNA rather than a secret
Reliably perform non-replayable dynamic app integrity measurement
Use best practice SDK and communication hardening practices
Can also do dynamic MitM protection by comparing server certs 40
41. Migrating to Tokens
●Static secret signs
dynamic payload
●Limited lifetime
●Standard and extensible
claims
●Bearer tokens - like cash
41
Image: https://jwt.io/
44. API Proxy with Dynamic Integrity
44
Convert secret key to runtime tokens
45. Additional API Proxy Pattern Benefits
Tailor exposed APIs to device
capabilities
Collapse multiple backend
function calls to single front
end call
Common logging, rate limiting,
caching, and authorization
services
45
http://microservices.io/patterns/apigateway.html
47. Is Anyone There?
Bot Attacks – DDoS Potential
Bots generating synthetic API traffic
Mitigation Challenges
Distributed IP addresses
Spoofed user agent strings
Spoofed fingerprint challenges
Mitigation Approaches
Strong client authentication
Non-user friendly CAPTCHAs
47
Bot Mitigation
API Servers
48. User Authentication Approaches
Many approaches
Username and password
Security tokens
Multi-factor authentication
Biometrics
Required for access authorization
Independent of authorization approach
Maximize security and ease of use for your use case
48
49. Trust On First Use
Trust on first use (TOFU)
Enter credentials and permissions once
Assume correct for future requests
May expire over time or by user logging out
May apply across apps
49
51. OAuth2 Overview
51
● Authorization protocol
○ Resource owner requests resource access for a client app
● Not authentication, but requires authentication services
○ Resource owner authenticates with auth server at auth request
○ Client authenticates with auth server at token request
● Often extended with OpenID-Connect (OIDC)
● Different authorization grant types
○ Client credentials grant
○ Code grant
○ Others
52. Abstract Protocol Flow
52
Client
Resource
Owner
Authorization
Server
Resource
Server
Authorization Request
Authorization Grant
Authorization Grant
Access Token
Access Token
Protected Resource
- Resource Owner is typically the user
- Consents to authorization scope
Software App on
User’s Device
- Verifies Resource Owner identity
- Issues tokens for access
- Holds the protected user resources
- The API backend that provides content
54. OAuth2 Access Control
● Access Control
○ OAuth provides delegated access
through scopes
○ Ensure access control is fine grain
○ Consider in terms of API endpoints,
not the client app
● The Risk
○ Compromised access token can
extract additional information
○ Broad scopes enable broad TOFU
54
https://zachholman.com/2011/01/
oauth_will_murder_your_children/
56. Good OAuth2 Hygiene
Token Hijacking
Strong TLS security
Strong client authentication
Use auth header not query parameters
Session Hijacking
Ensure auth code is one time use only
Redirect URI Attacks
Maintain exact match redirect URI whitelist
example.com/auth/* might match
example.com/auth/../attackers_page
56
57. OAuth2 Cross Site Protection
57
Mitigates against CSRF attack
Client compares request state with
returned state
58. OAuth2 Proof of Key Code Exchange (PKCE)
58
Mitigates against leaky client_secret
Code_challenge is hash of random value
Server compares with hash of code_verifier
60. OpenID Connect Extensions
● User Info
○ Structured user authentication handling
○ Common user info
● Introspection
○ Resource server can query auth server for additional info about token
○ Lets client see core info, sensitive info can be restricted to server
● Dynamic Registration
○ Register to receive initial client ID and client secret
○ Combine with client auth as a service
● Discovery Docs
○ Discover authorization capabilities, allowable scopes
○ Uses a well known endpoint
60
62. Putting it all together
62
Strong authorization practice
Only time-limited, run time tokens
Easy secret maintenance
App - API decoupling
63. Best Practices
Insist on TLS-only communication
Minimize secrets with API proxy pattern
Remove static secrets with app integrity
service
Use strong OAuth2 code grant flow
Unify OAuth2 interface using mediator
Short token lifetimes tokens with refresh
63
64. Related Recommendations
● DevSecOps
○ Manage your API lifecycle
○ Maintain strong operational logging
and monitoring practices
○ Make API security part of your API
lifecycle rather than an afterthought
● Leverage 3rd party implementations
○ API Gateways and Management
○ Identity and OAuth2 Providers
○ Client Authentication Services
64
https://protectingca.com/
65. Additional References
● Mobile API Security
○ https://hackernoon.com/mobile-api-security-techniques-682a5da4fe10
● Hands On API Proxy and Pinning
○ https://hackernoon.com/hands-on-mobile-api-security-get-rid-of-client-secrets-a79f111b6844
● All things OAuth2
○ OAuth2 in Action by Justin Richer and Antonio Sanso
● OAuth2 AppAuth on Android and iOS
○ https://hackernoon.com/adding-oauth2-to-mobile-android-and-ios-clients-using-the-appauth-s
dk-f8562f90ecff
65