05 - Form, Authentication, Session, and Cookie
05 - Form, Authentication, Session, and Cookie
display_name content
phone_number published_date
Budi +6281676732
3
Django Admin
• By default, the admin site url is http://localhost:8000/admin/
4
HTTP Requests
• The most commonly used HTTP request methods are GET, POST, PUT,
PATCH, and DELETE. These are equivalent to the CRUD operations (create,
read, update, and delete).
▪ GET: GET request is used to read/retrieve data from a web server. GET returns an HTTP
status code of 200 (OK) if the data is successfully retrieved from the server.
▪ POST: POST request is used to send data (file, form data, etc.) to the server. On successful
creation, it returns an HTTP status code of 201.
▪ PUT: A PUT request is used to modify the data on the server. It replaces the entire content
at a particular location with data that is passed in the body payload. If there are no resources
that match the request, it will generate one.
▪ PATCH: PATCH is similar to PUT request, but the only difference is, it modifies a part of the
data. It will only replace the content that you want to update.
▪ DELETE: A DELETE request is used to delete the data on the server at a specified location.
https://www.geeksforgeeks.org/different-kinds-of-http-requests/
5
Passing Argument
Passing Arguments
Request with
Your Webserver Environment ARGUMENTS
Run
# manage.py Internet
Web
Merged of html Page
ARGUMENTS
Request with
template and
Value from Extracted
Page
Web
process arguments
from Request
index.html views.py
style.css It’s your python
script.js code
GET:
• Never use GET to send sensitive data! (will be visible in the URL)
• Useful for form submissions where a user want to bookmark the
result
• GET is better for non-secure data, like query strings in Google
8
Form
About Form
<form action=[URL DESTINATION] method=[METHOD]>
<input type=[INPUT TYPE] other attributes> <form action="http://www.sesuatu.com/proses"
method="POST">
....
Name: <input type="text">
.... <input type="submit" value="Submit">
</form>
<input type=[INPUT TYPE] other attributes>
</form>
URL DESTINATION :
Posting data to URL endpoint
METHOD :
Method on passing variables to URL DESTINATION (GET or POST)
10
Submission Flows
Browser Server
User
Generate HTTP Request Receive HTTP Request
Type Address: to http://host/path
http://host/path Display HTML Layout to Which views.py to handle path?
User Generate HTML page FORM
Generate HTTP Request, Receive HTTP Request
Insert Form Which views.py to handle path?
Method, and arguments
to URL Destination Do Whatever you want to do in this
based on HTML page step
FORM
Generate HTML page
Display HTML Layout to
User
11
Django HTML Form
(Example Form definition in forms.py)
class Input_Form(forms.ModelForm):
class Meta:
model = Person
fields = ['display_name']
error_messages = {
input_attrs = {
'type' : 'text',
12
Django HTML Form
(Import from forms.py in views.py)
from .forms import Input_Form
def formulir(request):
13
Django HTML Form
(Merge HTML parts from forms.py in HTML
template)
14
Django HTML Form
(Generated HTML parts from forms.py)
forms.py HTML template
class Input_Form(forms.ModelForm):
class Meta:
model = Person
fields = ['display_name’]
error_messages = {
'required' : 'Please Type’
}
input_attrs = {
'type' : 'text',
'placeholder' : 'Nama Kamu’
}
display_name = forms.CharField(label='', required=False,
max_length=27, widget=forms.TextInput(attrs=input_attrs))
15
Django HTML Form
(Validate POST arguments based on forms.py)
views.py
16
Authentication and Authorization
Authentication and Authorization
● Authentication is the process of verifying who
you are: login
● Authorization is the process of verifying that you
have access to something
18
Question
Do we need both authentication and authorization?
Butuh agar tidak sembarang orang bisa masuk, klo authorization, misalkan ada siswa dan dosen yang memiliki hak akses yang berbeda.
Authorization untuk mengatur role para pengunjung.
Authentication is hard
Trying to write your own login system is difficult:
● How are you doing to save your password securely?
● How do you help with forgotten password?
● How do you make sure users set a good password?
20
Django Framework With Authentication
Session
Your Webserver Environment Authentication/ Request
Authorization
Run
# manage.py Internet
Web
Merged of html Page
template and
Value from Extracted
Request
Page
Web
process arguments
from Request
index.html views.py
style.css It’s your python
script.js code
● Creating superusers
$ python manage.py createsuperuser --username=kakpebepe [email protected]
22
Changing Password
• Django does not store raw (clear text) passwords on the user model,
but only a hash
• Do not attempt to manipulate the password attribute of the
user directly.
• A helper function is used when creating a user.
>>> from django.contrib.auth.models import User
>>> u = User.objects.get(username=‘pewe')
>>> u.set_password('new password')
>>> u.save()
Hashing is the transformation of a string of characters into a usually shorter fixed-length value or key that
represents the original string. Eg: hash(‘ini password saya’) == ‘AF3627731ABE63FF’
23
How to log a user in?
from django.contrib.auth import authenticate, login
def my_view(request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user is not None:
# Register in Session
# Redirect to a success page.
...
else:
# Return an 'invalid login' error message.
# Sometimes return HTTP 403
...
24
Alternative login mechanism
● By using available libraries ?
● Open Authentication (OAuth) ?
25
OAuth (Open Authentication)
● OAuth is a standard for user authentication
● For users:
○ It allows a user to log into a website like AirBnB via some other
service, like Gmail or Facebook
● For developers:
○ It lets you authenticate a user without having to implement log in
○ Examples: "Log in with Facebook"
26
OAuth2
● Companies like Google, Facebook, Twitter, and GitHub have OAuth2 APIs:
○ Google Sign-in API
○ Facebook Login API
○ Twitter Login API
○ GitHub Apps/Integrations
● OAuth2 is standardized, but the libraries that these companies provide are
all different.
● You must read the documentation to understand how to connect via their
API.
27
Session and Cookie
Komunikasi antar website pake HTTP dengan sifat stateless sehingga agar user berada di satu jalur menggunakan sessions dan cookie.
Session
29
Why a webserver need to handle sessions?
Why a web user needs to keep their session?
Browser 1 WebServer Browser 2
empty
empty
33
Myths and Facts about Cookies
Myths Facts
● Like worms or viruses that can erase data from ● Only data, not program code
user harddisk
● A form of spyware that can steal personal ● Cannot erase or read information from the user’s
information computer
34
Storing a Cookie
• Session cookie (default): temporary cookie
• Stored in the browser memory
• When the browser is closed, it will be erased
• Can’t be used for tracking long-term information
• Safer, only browser can access
• Persistent cookie:
• Stored in a file on the browser’s computer
• Can track long term information
• Less secure: users or programs can open cookie files
Please try:
Open multiple tab for the same website
Open multiple browser for the same website, 35
Server Session
• Server Session in Django, consists of
• Database (a model to keep session data)
• Webserver automatic handling
■ Read cookie parameter passed by Browser
■ Fetch / store data in session model
■ Modify information in the session
■ Send corresponding cookie back to Browser
• Implementation in Django:
• https://developer.mozilla.org/en-US/docs/Learn/Server-
side/Django/Sessions#Enabling_sessions
• https://developer.mozilla.org/en-US/docs/Learn/Server-
side/Django/Sessions#Using_sessions
36
Security Risks
OWASP Top 10 Web Application Security Risks
The OWASP (Open Source Foundation for Application Security) Top
10 is a standard awareness document for developers and web
application security. It represents a broad consensus about the most
critical security risks to web applications. (https://owasp.org/www-
project-top-ten/)
A01:2021-Broken Access Control - CSRF
CSRF (Cross Site Request
Forgery) adalah sebuah
tipe vulnerability di mana
seseorang bisa
melakukan request dari
origin yang tidak
seharusnya.
A01:2021-Broken Access Control - CSRF
Salah satu mitigasi untuk menghindari CSRF adalah dengan melakukan
implementasi token CSRF. Dengan token CSRF yang disertakan pada
request, sebuah web bisa memastikan bahwa request yang diterima
merupakan request yang dapat dipercaya. Token CSRF dibuat
menggunakan algoritma kriptografi yang aman sehingga tidak bisa di-
generate secara sembarang.
A01:2021-Broken Access Control - CSRF
● Django has built-in protection against most types of Cross
Site Request Forgery (CSRF) attacks
● Activated by default on MIDDLEWARE parameter in
settings.py. The 'django.middleware.csrf.CsrfViewMiddleware'
will be executed before any view
41
A01:2021-Broken Access Control - CSRF
● CSRF in HTML Template Form field:
<form action="." method="post">
{% csrf_token %}
</form>
● CSRF in views.py:
With CSRF check:
def my_view(request):
# my implementation goes here
return render(request, "a_template.html")
42
A01:2021-Broken Access Control - IDOR
IDOR (Insecure Direct Object Reference) adalah sebuah vulnerability di
mana seseorang bisa melakukan enumerasi terhadap ID sebuah object
yang ada. IDOR juga bisa terjadi jika sebuah object tidak memiliki
authorization yang baik.
A01:2021-Broken Access Control - IDOR
Solusi untuk menghindari IDOR adalah untuk mengimplementasikan
authorization yang baik dan benar terhadap sebuah object dalam API. ID
dari sebuah object juga bisa diubah menggunakan tipe data yang tidak
mudah dienumerasi, misalnya UUIDv4, UUIDv7, dan GUID.
A01:2021-Broken Access Control - CORS
Misconfig
CORS (Cross Origin Resource Sharing) adalah sebuah mekanisme browser
supaya bisa memperbolehkan origin lain melakukan request ke sebuah
website/API. Jika konfigurasi tidak dilakukan dengan benar, seorang
attacker bisa saja melakukan request ke endpoint internal yang tidak
seharusnya bisa diakses oleh jaringan luar.
A01:2021-Broken Access Control - CORS
Misconfig
Salah satu prinsip yang bisa digunakan untuk memperbaiki konfigurasi
CORS adalah Principle of Least Privileges, di mana konfigurasi yang
ditentukan hanya membuka akses untuk origin dan method yang
diperlukan saja. Hindari penggunaan konfigurasi dengan sifat
“enable/allow all” dan “wildcard”.
A02:2021-Cryptographic Failures
Salah satu vulnerability yang masuk di kategori ini adalah Use of Hard-
coded Password. Salah satu contoh konkret pada PBP adalah secret key
Django yang belum diubah dari default dan turut di-push pada GitHub
sehingga ter-expose ke publik.
A02:2021-Cryptographic Failures - Practical
Examples
Mengutip dokumentasi Django
(https://docs.djangoproject.com/en/5.1/topics/signing/):
“When you create a new Django project using startproject, the
settings.py file is generated automatically and gets a random
SECRET_KEY value. This value is the key to securing signed data – it is
vital you keep this secure, or attackers could use it to generate their
own signed values.”
A03:2021-Injection - XSS
XSS (Cross Site Scripting) adalah sebuah vulnerability di mana seseorang
bisa melakukan injeksi kode Javascript yang akan dieksekusi oleh client.
Masalah yang bisa terjadi dari vulnerability ini adalah oknum attacker
bisa saja mencuri cookies dari pengguna yang sudah melakukan login ke
sebuah website.
51
A03:2021-Injection - XSS
● Django templates escape specific characters which are particularly dangerous to HTML
● While this protects users from most malicious input, it is not entirely foolproof, eg:
“class1 onmouseover=alert(‘Hacked’)”
Note: be very careful when storing HTML in the database, especially when that HTML is
retrieved and displayed.
52
A03:2021-Injection - SQL Injection
SQL Injection bisa terjadi jika user input tidak divalidasi dan di-sanitize
dengan baik yang mengakibatkan terjadinya operasi SQL yang tidak
seharusnya. Oknum attacker bisa saja melakukan operasi INSERT,
UPDATE, DELETE, dan lain-lain untuk mengubah data yang ada di
database.
● Prepared Statements
SELECT * FROM users WHERE email = ? AND password = ?;
(MySQL)
● Database Specific Defenses
Oracle DB: ESAPI.encoder().encodeForSQL(new
OracleCodec(), str);
MySQL: SELECT QUOTE('test''case');
A03:2021-Injection - SSTI
SSTI (Server Side Template Injection) adalah sebuah vulnerability di mana
seseorang bisa memanfaatkan library templating untuk melakukan injeksi
kode yang akan dieksekusi di server. Attacker bisa saja memanfaatkan
vulnerability ini untuk mengakses file di server atau bahkan mendapatkan
akses server tersebut.
A03:2021-Injection - SSTI
Mitigasi untuk SSTI adalah dengan tidak memperbolehkan user untuk
membuat atau melakukan modifikasi template. Jika memang
dibutuhkan, user input harus selalu melewati sanitization sebelum
dimasukkan ke template.
A04:2021-Insecure Design - Error Message
Kegagalan pada autentikasi bisa memberikan informasi yang berpeluang
membantu seorang attacker. Pada contoh berikut, seorang attacker
menjadi tahu bahwa username yang dicoba sudah benar. Hal ini dapat
menjadi masalah jika tidak ada sistem blokir untuk percobaan login
sehingga memungkinkan dilakukan brute-force terhadap password.
A04:2021-Insecure Design - Error Message
Mitigasi dari vulnerability ini adalah dengan tidak memberikan informasi
sensitif dalam error message yang ditampilkan di client. Hal ini bisa
dicapai dengan memberikan error message yang ambigu.
Dari contoh sebelumnya, error message tersebut bisa diubah menjadi
“Sorry, incorrect username or password”.
A04:2021-Insecure Design - Plaintext Storage of
a Password
Credentials yang disimpan pada basis data dalam bentuk plaintext juga
merupakan salah satu bentuk insecure design. Dalam kasus terburuk,
apabila basis data yang digunakan untuk menyimpan data terbobol
maka credentials pengguna juga ikut bocor dan dapat disalahgunakan.
A04:2021-Insecure Design - Plaintext Storage of
a Password
Bentuk mitigasi yang bisa dilakukan adalah dengan menyimpan
credentials pengguna dalam bentuk hash, umumnya menggunakan
algoritma Bcrypt. By default, hal ini sudah diimplementasikan
menggunakan User model di Django.
A04:2021-Insecure Design - Clear Text Storage
of Sensitive Information
Contoh lain dari insecure design adalah penyimpanan informasi sensitif
tanpa adanya usaha enkripsi (atau usaha enkripsi yang sangat
minimum) pada tempat penyimpanan data yang kurang aman, misalnya
cookies.
base64.decode(“ZmFsc2U=”) = “false”
base64.encode(“true”) = “dHJ1ZQ==”
A04:2021-Insecure Design - Clear Text Storage
of Sensitive Information
Solusi untuk menghindari vulnerability ini adalah dengan menyimpan
informasi sensitif di server. Namun, jika informasi sensitif tersebut
harus disimpan di client, informasi tersebut harus melalui medium yang
aman dan terenkripsi, seperti token JWT, di mana pengguna bisa
melihat, tetapi tidak bisa mengubah informasi tersebut.
A05:2021-Security Misconfiguration
Salah satu contoh misconfiguration keamanan di Django adalah dengan
membiarkan variabel “DEBUG” bernilai “True” pada produk yang dirilis.
Hal ini membuka banyak sekali celah untuk aktor pengancam melihat
seluk-beluk dari produk yang dirilis.
A05:2021-Security Misconfiguration
Selain melihat endpoint, attacker juga bisa melihat file structure dan
stacktrace dari error yang diberikan.
A06:2021-Vulnerable and Outdated Components
Vulnerability ini terjadi karena library dan komponen lain yang
digunakan oleh aplikasi tidak di-update secara berkala dan bisa saja
versi library yang belum di-update itu memiliki vulnerability yang bisa
disalahgunakan.
A07:2021-Identification and Authentication
Failures
Vulnerability yang masuk ke dalam kategori ini adalah Improper
Authentication. Salah satu contoh dari vulnerability ini adalah
memperbolehkan pengguna untuk menggunakan password yang lemah
(contoh: admin dan password123). Attacker bisa memanfaatkan
vulnerability ini untuk melakukan percobaan login secara brute-force
dengan password-password yang umum digunakan.
A07:2021-Identification and Authentication
Failures
Untuk memaksa pengguna membuat password yang lebih kuat, dibutuhkan
rules yang ketat dalam pembuatan password. Contohnya, password harus 8
karakter atau lebih, password harus memiliki setidaknya 1 karakter angka
dan 1 karakter simbol, password tidak boleh mirip dengan username,
password tidak boleh menggunakan common password, dan lain-lain.
A08:2021-Software and Data Integrity Failures
Salah satu vulnerability di kategori ini adalah Insecure Deserialization. Contohnya
adalah jika sebuah JSON tidak di-deserialize secara baik dan benar, ada
kemungkinan seseorang bisa melakukan prototype pollution (untuk Javascript) dan
class pollution (untuk Python). Seseorang bisa saja melakukan perubahan atribut
pada superclass dari sebuah class yang jika ada pembuatan instance baru dari class
tersebut maka akan terpolusi dengan atribut yang telah dibuat.
A08:2021-Software and Data Integrity Failures
Mitigasi paling ampuh untuk menghindari vulnerability ini adalah
dengan tidak menerima input yang tidak dipercaya untuk dilakukan
deserialization. Jika memang diperlukan, perlu ada proteksi tambahan
seperti integrity checking, memberlakukan restriction yang ketat,
melakukan deserialization dalam environment yang memiliki low privilege,
dan lain-lain.
A09:2021-Security Logging and Monitoring Failures
• Many-to-many relationships
- To define a many-to-many relationship, use ManyToManyField.
- In this example, an Article can be published in multiple Publication objects,
and a Publication has multiple Article objects.
• Many-to-one relationships
- To define a many-to-one relationship, use ForeignKey.
- In this example, a Reporter can be associated with many Article objects, but
an Article can only have one Reporter object.
• One-to-one relationships
- To define a one-to-one relationship, use OneToOneField.
- In this example, a Place optionally can be a Restaurant.
75
References
● Django Documentation: https://docs.djangoproject.com/en/5.0/
● https://courses.cs.washington.edu/courses/cse190m/10su/lectures/slides/lecture22-
cookies.shtml
● https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Forms
● https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Sessions
● https://www.w3schools.com/tags/ref_httpmethods.asp
● Andrew Hoffman. Web Application Security (1st Edition), O’Reilly, 2020
76