SlideShare a Scribd company logo
Client Server Security with Flask and iOS
CLIENT SERVER SECURITY
AGENDA
3 Aspects of Security
Encryption
3 Practical Security Lessons
Implementing Security with Flask
3 ASPECTS OF SECURITY
1. Authentication: Ensuring a user is who they claim to be (e.g.
checking a password)
2. Authorization: Defining rules for access and modification of
resources (e.g. users only allowed to delete their own posts)
3. Secure Coding: Ensuring that your application has no
security flaws that would allow attackers to access sensitive
data or manipulate your server
INTERLUDE:
CRYPTOGRAPHY
ENCRYPTION AND HASHING
Symmetric encryption: There is one key for encryption
and decryption (secret key encryption)
Asymmetric encryption: One key is used for encryption
other key is used decryption (public key encryption)
Hashing: Generates an (almost) unique fixed length
output from an arbitrary input
SYMMETRIC ENCRYPTION
One key for encryption and decryption:
“I like you!”
sharedSecret
algorithm
134$%Q
$ksg,mcdl
“I like you!”
134$%Q
$ksg,mcdl
Encryption
Decryption
sharedSecret
algorithm
ASYMMETRIC ENCRYPTION
One Key for encryption a different key for decryption
Anyone can encrypt content for a receiver
Only receiver can decrypt the content
“I like you!”
sharedSecret
algorithm
134$%Q
$ksg,mcdl
“I like you!”
134$%Q
$ksg,mcdl
Encryption
Decryption
sharedSecret
algorithm
Public Key
Private Key
DIGITAL SIGNATURE
Uses asymmetric encryption
to verify identity
Only sender knows the
private key used to encrypt
a signature
Anyone can use a public
key to decrypt signature
Image Source: http://en.wikipedia.org/wiki/Digital_signature#mediaviewer/File:Digital_Signature_diagram.svg
HASHING
Hashing generates an (almost) unique fixed length output from
an arbitrary input
This is considered a one way operation, generating the content
from the hash is not possible (except by brute-force)
Let’s see if this actually works
because this is a really amazing
algorithms that basically does not
create any collisions between
different generated hashes
Hash Algorithm
Salt
0714b76586b8823707080083c
1fa2ddd67dfbd2d
Hashing
3 SECURITY LESSONS
LESSON #1: HTTPS
WHY USE HTTPS
You should (almost) always communicate with a server using HTTPS
HTTPS will encrypt the traffic between the client and the server so
that network traffic cannot be read by other participants
When using HTTP instead of HTTPS messages between client and
server are sent unencrypted; this allows attackers on the same
network and attackers in connection points between client and server
to read the entire communication (passwords and other private
information)
HOW DOES HTTPS WORK
Browsers and other applications accessing the web
have a pool of trusted authorities
These authorities issue certificates to websites
Authorities ensure identity of website host
Certificate is used to encrypt handshake between
client and server
HOW DOES HTTPS WORK
This addresses two problems:
Authentication: We can be sure we we are talking
to the website we are wanting to talk to (not some
server pretending to be that website)
Secure Coding: Communication between Client
and Server is encrypted
HTTPS HANDSHAKE
During handshake asymmetric encryption is used to arrange a
shared secret
During handshake client verifies Server Certificate (Certificate is
signed with private key of Certificate Authority (CA), Client has
public keys of trusted CAs that can be used to verify signature
After handshake Client and Server have a shared secret that is
used for symmetric encryption
HTTPS HANDSHAKE (SIMPLIFIED) [1]
Client
Server
ClientHello
ServerHello
Certificate
ServerHelloEnd
Client
Server
Premaster Secret
(encrypted with public key
from certificate)randomNumberClient randomNumberServer
Client
Server
Master Secret =
generateMaster(Premaster Secret,
randomNumberClient,
randomNumberServer)
Client
Server
ChangeCipherSpec ChangeCipherSpec
FinishedFinished
Encrypted with
Master Secret
Encrypted with
Master Secret
1 2 3 4
Client
Server
5
Communication
Encrypted with
Master Secret
CA
Check Certificate
Master Secret =
generateMaster(Premaster Secret,
randomNumberClient,
randomNumberServer)
HTTPS Handshake Symmetricly Encrypted
Communication
HOW DO I USE HTTPS?
Easy answer: get a certificate and use a cloud hosting service that
provides HTTPS
Hard answer: get a certificate and configure your server to use 

HTTPS with that certificate
Trick: Heroku apps can use the Heroku SSL certificate
LESSON #2: STORING
PASSWORDS
LESSON #2: STORING PASSWORDS
Never ever store passwords!
Store hashes of passwords
If someone gets access to your DB you do not want them to be
able to read the users’ passwords
LESSON #2: STORING PASSWORDS
Store passwords with the most secure considered hash algorithm
When a user signs up, hash the password and store it in the DB
When a user signs in, hash the password and compare it to the hashed
password in the DB
If a user forgot their password, send them a link to reset it - no secure
application should provide a way to retrieve the old password!
LESSON #2: STORING PASSWORDS
Client
Server
Ben-G
simplePW
Client
Server
encrypt
=
Login OK
encrypt
Signup Login
PW: 2eff28320f
77620a23
User: Ben-G
PW: simplePW
User: Ben-G
PW: simplePW
User: Ben-G
PW: 2eff28320f
77620a23
User: Ben-G
PW: 2eff28320f
77620a23
User: Ben-G
LESSON #3: SANITIZE 

USER INPUT
LESSON #3: SANITIZE USER INPUT
This is typically more relevant for web applications than for mobile
applications
Never allow a user to write an entire DB Request or a piece of
executable code
LESSON #3: SANITIZE USER INPUT
Examples:
XSS: Cross-Site Scripting. If User Input is not sanitized it can be
possible to inject JS code
SQL Injections: Possible to send queries to DB
Shellshock: Execute arbitrary code on target machine
IMPLEMENTING SECURITY
WITH FLASK
USER SIGNUP
USER SIGNUP
User should be a RESTful resource
Signup means a POST request against that User Resource
Encrypt the password and store along with username in database
Recommended to use bcrypt with 12 rounds for encryption
BCRYPT
The bcrypt library provides a convenient way to store a password
securely
It automatically generates a random salt for each stored password
By generating an individual salt for each password, an attacker
needs to brute force every password individually
BCRYPT
We can define how many rounds the encryption algorithm runs to
generate the encrypted password, as processors get faster this
value can be increased
The more rounds, the longer it takes to generate the encrypted key
This means brute force attacks take longer as well!
ATTACKING ENCRYPTED PASSWORDS
With no access to DB:
Brute Force through web interface or API
Can easily be prevented by rate-limiting API accesses
With access to DB:
Compare hashed passwords to a rainbow table [3]
If you aren’t using a unique salt per entry, one compromised password
means that all your users’ passwords are compromised
LOGIN / AUTHENTICATION
AUTHENTICATION
Authentication should conform with HTTP standard
→ use a specified HTTP authentication method
Authentication needs to conform with REST Webservice Design
Patterns
→ Server needs to get the full information to fulfill a Client Request
with each request → We need to send credentials with every
request
HTTP BASIC AUTH
Uses the Authorization header of an HTTPS Request
1. Username and password are combined into a string "username:password"
2. The resulting string is then encoded using Base64
3. The authorization method and a space i.e. "Basic " is then put before the
encoded string
Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
HTTP BASIC AUTH
Client
Server
HTTP-Request
Authorization: Basic
QWxhZGRpbjpvcGVuIHNlc2FtZQ==
HTTP-Response
BASIC AUTH FLASK [2]
from functools import wraps
from flask import request, Response
def check_auth(username, password):
return username == 'admin' and password == 'secret'
def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
message = {'error': 'Basic Auth Required.'}
resp = jsonify(message)
resp.status_code = 401
return resp
return f(*args, **kwargs)
return decorated
BASIC AUTH FLASK
class Trip(Resource):
@requires_auth
def get(self, trip_id=None):
if trip_id is None:
…
else:
…
Methods annotated with requires_auth will require the client to provide valid
username and password
BASIC AUTH ON IOS
// Thanks to Nate Cook: http://stackoverflow.com/questions/24379601/how-to-make-an-http-request-basic-auth-in-swift
struct BasicAuth {
static func generateBasicAuthHeader(username: String, password: String) -> String {
let loginString = NSString(format: "%@:%@", username, password)
let loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)!
let base64LoginString = loginData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
let authHeaderString = "Basic (base64LoginString)"
return authHeaderString
}
}
PASSWORD RESET
Send user an email that allows them to reset their password, only
send to to email address that they used to sign up
The password reset should only be possible for a certain amount
of time, typically this is accomplished by providing an expiring
token
REFERENCES
REFERENCES
[1] First Few Milliseconds of HTTPS
[2] Flask Basic Authentication
[3] Wikipedia: Rainbow Table
ADDITIONAL RESOURCES
ADDITIONAL RESOURCES
How does HTTPS actually work?
XSS Example
Everything you need to know about ShellShock
Why SHA-1 should no longer be used as hash algorithm for TLS

More Related Content

Client Server Security with Flask and iOS

  • 3. AGENDA 3 Aspects of Security Encryption 3 Practical Security Lessons Implementing Security with Flask
  • 4. 3 ASPECTS OF SECURITY 1. Authentication: Ensuring a user is who they claim to be (e.g. checking a password) 2. Authorization: Defining rules for access and modification of resources (e.g. users only allowed to delete their own posts) 3. Secure Coding: Ensuring that your application has no security flaws that would allow attackers to access sensitive data or manipulate your server
  • 6. ENCRYPTION AND HASHING Symmetric encryption: There is one key for encryption and decryption (secret key encryption) Asymmetric encryption: One key is used for encryption other key is used decryption (public key encryption) Hashing: Generates an (almost) unique fixed length output from an arbitrary input
  • 7. SYMMETRIC ENCRYPTION One key for encryption and decryption: “I like you!” sharedSecret algorithm 134$%Q $ksg,mcdl “I like you!” 134$%Q $ksg,mcdl Encryption Decryption sharedSecret algorithm
  • 8. ASYMMETRIC ENCRYPTION One Key for encryption a different key for decryption Anyone can encrypt content for a receiver Only receiver can decrypt the content “I like you!” sharedSecret algorithm 134$%Q $ksg,mcdl “I like you!” 134$%Q $ksg,mcdl Encryption Decryption sharedSecret algorithm Public Key Private Key
  • 9. DIGITAL SIGNATURE Uses asymmetric encryption to verify identity Only sender knows the private key used to encrypt a signature Anyone can use a public key to decrypt signature Image Source: http://en.wikipedia.org/wiki/Digital_signature#mediaviewer/File:Digital_Signature_diagram.svg
  • 10. HASHING Hashing generates an (almost) unique fixed length output from an arbitrary input This is considered a one way operation, generating the content from the hash is not possible (except by brute-force) Let’s see if this actually works because this is a really amazing algorithms that basically does not create any collisions between different generated hashes Hash Algorithm Salt 0714b76586b8823707080083c 1fa2ddd67dfbd2d Hashing
  • 13. WHY USE HTTPS You should (almost) always communicate with a server using HTTPS HTTPS will encrypt the traffic between the client and the server so that network traffic cannot be read by other participants When using HTTP instead of HTTPS messages between client and server are sent unencrypted; this allows attackers on the same network and attackers in connection points between client and server to read the entire communication (passwords and other private information)
  • 14. HOW DOES HTTPS WORK Browsers and other applications accessing the web have a pool of trusted authorities These authorities issue certificates to websites Authorities ensure identity of website host Certificate is used to encrypt handshake between client and server
  • 15. HOW DOES HTTPS WORK This addresses two problems: Authentication: We can be sure we we are talking to the website we are wanting to talk to (not some server pretending to be that website) Secure Coding: Communication between Client and Server is encrypted
  • 16. HTTPS HANDSHAKE During handshake asymmetric encryption is used to arrange a shared secret During handshake client verifies Server Certificate (Certificate is signed with private key of Certificate Authority (CA), Client has public keys of trusted CAs that can be used to verify signature After handshake Client and Server have a shared secret that is used for symmetric encryption
  • 17. HTTPS HANDSHAKE (SIMPLIFIED) [1] Client Server ClientHello ServerHello Certificate ServerHelloEnd Client Server Premaster Secret (encrypted with public key from certificate)randomNumberClient randomNumberServer Client Server Master Secret = generateMaster(Premaster Secret, randomNumberClient, randomNumberServer) Client Server ChangeCipherSpec ChangeCipherSpec FinishedFinished Encrypted with Master Secret Encrypted with Master Secret 1 2 3 4 Client Server 5 Communication Encrypted with Master Secret CA Check Certificate Master Secret = generateMaster(Premaster Secret, randomNumberClient, randomNumberServer) HTTPS Handshake Symmetricly Encrypted Communication
  • 18. HOW DO I USE HTTPS? Easy answer: get a certificate and use a cloud hosting service that provides HTTPS Hard answer: get a certificate and configure your server to use 
 HTTPS with that certificate Trick: Heroku apps can use the Heroku SSL certificate
  • 20. LESSON #2: STORING PASSWORDS Never ever store passwords! Store hashes of passwords If someone gets access to your DB you do not want them to be able to read the users’ passwords
  • 21. LESSON #2: STORING PASSWORDS Store passwords with the most secure considered hash algorithm When a user signs up, hash the password and store it in the DB When a user signs in, hash the password and compare it to the hashed password in the DB If a user forgot their password, send them a link to reset it - no secure application should provide a way to retrieve the old password!
  • 22. LESSON #2: STORING PASSWORDS Client Server Ben-G simplePW Client Server encrypt = Login OK encrypt Signup Login PW: 2eff28320f 77620a23 User: Ben-G PW: simplePW User: Ben-G PW: simplePW User: Ben-G PW: 2eff28320f 77620a23 User: Ben-G PW: 2eff28320f 77620a23 User: Ben-G
  • 23. LESSON #3: SANITIZE 
 USER INPUT
  • 24. LESSON #3: SANITIZE USER INPUT This is typically more relevant for web applications than for mobile applications Never allow a user to write an entire DB Request or a piece of executable code
  • 25. LESSON #3: SANITIZE USER INPUT Examples: XSS: Cross-Site Scripting. If User Input is not sanitized it can be possible to inject JS code SQL Injections: Possible to send queries to DB Shellshock: Execute arbitrary code on target machine
  • 28. USER SIGNUP User should be a RESTful resource Signup means a POST request against that User Resource Encrypt the password and store along with username in database Recommended to use bcrypt with 12 rounds for encryption
  • 29. BCRYPT The bcrypt library provides a convenient way to store a password securely It automatically generates a random salt for each stored password By generating an individual salt for each password, an attacker needs to brute force every password individually
  • 30. BCRYPT We can define how many rounds the encryption algorithm runs to generate the encrypted password, as processors get faster this value can be increased The more rounds, the longer it takes to generate the encrypted key This means brute force attacks take longer as well!
  • 31. ATTACKING ENCRYPTED PASSWORDS With no access to DB: Brute Force through web interface or API Can easily be prevented by rate-limiting API accesses With access to DB: Compare hashed passwords to a rainbow table [3] If you aren’t using a unique salt per entry, one compromised password means that all your users’ passwords are compromised
  • 33. AUTHENTICATION Authentication should conform with HTTP standard → use a specified HTTP authentication method Authentication needs to conform with REST Webservice Design Patterns → Server needs to get the full information to fulfill a Client Request with each request → We need to send credentials with every request
  • 34. HTTP BASIC AUTH Uses the Authorization header of an HTTPS Request 1. Username and password are combined into a string "username:password" 2. The resulting string is then encoded using Base64 3. The authorization method and a space i.e. "Basic " is then put before the encoded string Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
  • 35. HTTP BASIC AUTH Client Server HTTP-Request Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== HTTP-Response
  • 36. BASIC AUTH FLASK [2] from functools import wraps from flask import request, Response def check_auth(username, password): return username == 'admin' and password == 'secret' def requires_auth(f): @wraps(f) def decorated(*args, **kwargs): auth = request.authorization if not auth or not check_auth(auth.username, auth.password): message = {'error': 'Basic Auth Required.'} resp = jsonify(message) resp.status_code = 401 return resp return f(*args, **kwargs) return decorated
  • 37. BASIC AUTH FLASK class Trip(Resource): @requires_auth def get(self, trip_id=None): if trip_id is None: … else: … Methods annotated with requires_auth will require the client to provide valid username and password
  • 38. BASIC AUTH ON IOS // Thanks to Nate Cook: http://stackoverflow.com/questions/24379601/how-to-make-an-http-request-basic-auth-in-swift struct BasicAuth { static func generateBasicAuthHeader(username: String, password: String) -> String { let loginString = NSString(format: "%@:%@", username, password) let loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)! let base64LoginString = loginData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0)) let authHeaderString = "Basic (base64LoginString)" return authHeaderString } }
  • 39. PASSWORD RESET Send user an email that allows them to reset their password, only send to to email address that they used to sign up The password reset should only be possible for a certain amount of time, typically this is accomplished by providing an expiring token
  • 41. REFERENCES [1] First Few Milliseconds of HTTPS [2] Flask Basic Authentication [3] Wikipedia: Rainbow Table
  • 43. ADDITIONAL RESOURCES How does HTTPS actually work? XSS Example Everything you need to know about ShellShock Why SHA-1 should no longer be used as hash algorithm for TLS