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

What's hot (20)

PPTX
Architecture Best Practices
AWS Germany
 
PPTX
Introduction about-ajax-framework
Sakthi Bro
 
PPTX
The ASP.NET Web API for Beginners
Kevin Hazzard
 
PPT
Web Fundamentals
arunv
 
PDF
Web Fundamental
SiliconExpert Technologies
 
PDF
Restful Web Services
Angelin R
 
PPT
Web servers
webhostingguy
 
PDF
Rest api design by george reese
buildacloud
 
PDF
What is REST API? REST API Concepts and Examples | Edureka
Edureka!
 
PPTX
Day03 api
ABDEL RAHMAN KARIM
 
PPT
Asp.net.
Naveen Sihag
 
PPTX
Http and REST APIs.
Rahul Tanwani
 
PDF
Who Are You and What Do You Want? Working with OAuth in SharePoint 2013.
Eric Shupps
 
PPTX
Asp Net Advance Topics
Ali Taki
 
PPT
Cics web interface new
Balmukundb
 
PDF
Build an API the right way
Software Guru
 
PPTX
Are you getting Sleepy. REST in SharePoint Apps
Liam Cleary [MVP]
 
PPTX
Jsf login logout project
Gagandeep Singh
 
PPT
Web Servers (ppt)
webhostingguy
 
Architecture Best Practices
AWS Germany
 
Introduction about-ajax-framework
Sakthi Bro
 
The ASP.NET Web API for Beginners
Kevin Hazzard
 
Web Fundamentals
arunv
 
Restful Web Services
Angelin R
 
Web servers
webhostingguy
 
Rest api design by george reese
buildacloud
 
What is REST API? REST API Concepts and Examples | Edureka
Edureka!
 
Asp.net.
Naveen Sihag
 
Http and REST APIs.
Rahul Tanwani
 
Who Are You and What Do You Want? Working with OAuth in SharePoint 2013.
Eric Shupps
 
Asp Net Advance Topics
Ali Taki
 
Cics web interface new
Balmukundb
 
Build an API the right way
Software Guru
 
Are you getting Sleepy. REST in SharePoint Apps
Liam Cleary [MVP]
 
Jsf login logout project
Gagandeep Singh
 
Web Servers (ppt)
webhostingguy
 

Viewers also liked (20)

PDF
iOS Layout Overview
Make School
 
PDF
Layout with Stack View, Table View, and Collection View
Make School
 
PDF
Persistence on iOS
Make School
 
PDF
Intro to Core Data
Make School
 
PDF
Make School 2017 - Mastering iOS Development
Make School
 
PDF
Advanced Core Data
Make School
 
PDF
Standard libraries on iOS
Make School
 
PDF
Error Handling in Swift
Make School
 
PDF
Localization and Accessibility on iOS
Make School
 
PDF
Multithreading on iOS
Make School
 
PDF
Intro to iOS Application Architecture
Make School
 
PDF
Distributing information on iOS
Make School
 
PDF
Core Data presentation
joaopmaia
 
PDF
Swift Objective-C Interop
Make School
 
PDF
Xcode Project Infrastructure
Make School
 
PDF
Dependency Management on iOS
Make School
 
PDF
Swift 2 intro
Make School
 
PDF
Client Server Communication on iOS
Make School
 
PDF
Client Server Synchronization iOS
Make School
 
PDF
Memory Management on iOS
Make School
 
iOS Layout Overview
Make School
 
Layout with Stack View, Table View, and Collection View
Make School
 
Persistence on iOS
Make School
 
Intro to Core Data
Make School
 
Make School 2017 - Mastering iOS Development
Make School
 
Advanced Core Data
Make School
 
Standard libraries on iOS
Make School
 
Error Handling in Swift
Make School
 
Localization and Accessibility on iOS
Make School
 
Multithreading on iOS
Make School
 
Intro to iOS Application Architecture
Make School
 
Distributing information on iOS
Make School
 
Core Data presentation
joaopmaia
 
Swift Objective-C Interop
Make School
 
Xcode Project Infrastructure
Make School
 
Dependency Management on iOS
Make School
 
Swift 2 intro
Make School
 
Client Server Communication on iOS
Make School
 
Client Server Synchronization iOS
Make School
 
Memory Management on iOS
Make School
 
Ad

Similar to Client Server Security with Flask and iOS (20)

PPT
Secure payment systems
Abdulaziz Mohd
 
PDF
SSL/TLS Handshake
Arpit Agarwal
 
PDF
Efficient Multi Server Authentication and Hybrid Authentication Method
IJCERT
 
PPT
Lecture17
Châu Thanh Chương
 
PPTX
Introduction to SSH & PGP
Sarang Ananda Rao
 
PPTX
Secure socket layer
BU
 
DOCX
SSL-image
Rajat Toshniwal
 
PDF
presentation2-151203145018-lva1-app6891.pdf
GumanSingh10
 
PDF
Oauth Nightmares Abstract OAuth Nightmares
Nino Ho
 
PPTX
The last picks
Nafiur Rahman Tuhin
 
PDF
Module 13 (web based password cracking techniques)
Wail Hassan
 
PPTX
Transport Layer Security (TLS)
Arun Shukla
 
PDF
An Introduction to Kerberos
Shumon Huque
 
PPTX
Network Security Practices-IP Security
Gayathridevi120
 
PDF
CRYPTOGRAPHY AND NETWORK SECURITY- Transport-level Security
Jyothishmathi Institute of Technology and Science Karimnagar
 
PPT
ssl
sjyuva
 
PPT
Securing RESTful API
Muhammad Zbeedat
 
PDF
OAuth 2.0 and Library
Kenji Otsuka
 
PPTX
Remote Accesserver, Introduction(Part1).pptx
songsavoeun571
 
Secure payment systems
Abdulaziz Mohd
 
SSL/TLS Handshake
Arpit Agarwal
 
Efficient Multi Server Authentication and Hybrid Authentication Method
IJCERT
 
Introduction to SSH & PGP
Sarang Ananda Rao
 
Secure socket layer
BU
 
SSL-image
Rajat Toshniwal
 
presentation2-151203145018-lva1-app6891.pdf
GumanSingh10
 
Oauth Nightmares Abstract OAuth Nightmares
Nino Ho
 
The last picks
Nafiur Rahman Tuhin
 
Module 13 (web based password cracking techniques)
Wail Hassan
 
Transport Layer Security (TLS)
Arun Shukla
 
An Introduction to Kerberos
Shumon Huque
 
Network Security Practices-IP Security
Gayathridevi120
 
CRYPTOGRAPHY AND NETWORK SECURITY- Transport-level Security
Jyothishmathi Institute of Technology and Science Karimnagar
 
ssl
sjyuva
 
Securing RESTful API
Muhammad Zbeedat
 
OAuth 2.0 and Library
Kenji Otsuka
 
Remote Accesserver, Introduction(Part1).pptx
songsavoeun571
 
Ad

Recently uploaded (20)

PDF
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
PPTX
Homogeneity of Variance Test Options IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
PDF
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
PPTX
Tally software_Introduction_Presentation
AditiBansal54083
 
PDF
Online Queue Management System for Public Service Offices in Nepal [Focused i...
Rishab Acharya
 
PPTX
Human Resources Information System (HRIS)
Amity University, Patna
 
PPTX
Transforming Mining & Engineering Operations with Odoo ERP | Streamline Proje...
SatishKumar2651
 
PPTX
ChiSquare Procedure in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PPTX
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
PDF
SAP Firmaya İade ABAB Kodları - ABAB ile yazılmıl hazır kod örneği
Salih Küçük
 
PDF
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
PDF
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
PPTX
AEM User Group: India Chapter Kickoff Meeting
jennaf3
 
PDF
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Nabin Dhakal
 
PPTX
Hardware(Central Processing Unit ) CU and ALU
RizwanaKalsoom2
 
PPTX
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
PDF
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
PPTX
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
PPTX
Help for Correlations in IBM SPSS Statistics.pptx
Version 1 Analytics
 
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
Homogeneity of Variance Test Options IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
Tally software_Introduction_Presentation
AditiBansal54083
 
Online Queue Management System for Public Service Offices in Nepal [Focused i...
Rishab Acharya
 
Human Resources Information System (HRIS)
Amity University, Patna
 
Transforming Mining & Engineering Operations with Odoo ERP | Streamline Proje...
SatishKumar2651
 
ChiSquare Procedure in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
SAP Firmaya İade ABAB Kodları - ABAB ile yazılmıl hazır kod örneği
Salih Küçük
 
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
AEM User Group: India Chapter Kickoff Meeting
jennaf3
 
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Nabin Dhakal
 
Hardware(Central Processing Unit ) CU and ALU
RizwanaKalsoom2
 
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
Help for Correlations in IBM SPSS Statistics.pptx
Version 1 Analytics
 

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