30 Haziran 2020 Salı

Hybrid Encryption

Giriş
Açıklaması şöyle. Veri simetrik şifreleme ile şifrelenir. Bu yöntem hızlıdır. Daha sonra anahtar asimetrik şifreleme ile şifrelenir. Bu da hızlıdır çünhü anahtar çok büyük değildir.
Hybrid encryption as the name suggests combines the best of both the worlds of symmetric and asymmetric encryption and allows us to encrypt the data efficiently while ensuring secrecy is not compromised .

At the client end, we encrypt the data with symmetric encryption using secret key. The secret key is then encrypted with the asymmetric public key. Then, both the encrypted key and encrypted data are sent to the receiver.

At the receiver end the secret key is retrieved by decrypting the encrypted secret key with the private key. The secret key is then used to decrypt the encrypted data.
Hybrid Encryption Neden Gerekli?
Açıklaması şöyle
But the time to encrypt the data with asymmetric encryption grows significantly proportionately with the size of data. Here symmetric encryption does the job quite efficiently.



Yazılım Kalite Etmenleri - Adaptability

Giriş
Açıklaması şöyle
Configurability to meet different requirements

Open standard for Authorization (OAuth2) Grant Tipleri

Grant Tipleri Nedir
Tipler şöyle
1. Authorization Code Grant
2. Implicit Grant
3. Resource Owner Credentials Grant - Password Grant
4. Client Credentials Grant
5. Refresh Token Grant

OAuth 2.1 İle Farkı
Açıklaması şöyle
Following lists down a set of changes OAuth 2.1 introduces on top of OAuth 2.0.

- The authorization code grant is extended with the functionality from PKCE (RFC7636) such that the default method of using - the authorization code grant according to this specification requires the addition of the PKCE parameters
- Redirect URIs must be compared using exact string matching
- The Implicit grant (response_type=token) is omitted
- The Resource Owner Password Credentials grant is omitted
- Bearer token usage omits the use of bearer tokens in the query string of URIs
- Refresh tokens should either be sender-constrained or one-time use
- In addition to the confidential and public client types in OAuth 2.0, 2.1 introduces another new client type: credentialed.
Yani sadece 
- Authorization Code Grant
- Client Credentials Grant
- Refresh Token Grant
kaldı

1. Authorization Code Grant Nedir
OAuth2 Authorization Code Grant yazısına taşıdım

2. Implicit Grant Nedir
Bu akış OAuth2.1 ile deprecate edildi.

Açıklaması şöyle. Authorization Code Grant'in biraz daha basitleştirilmiş hali. Authorization Token yerine direkt Access Token veriliyor.
  ... when the client redirects you to the authorization server's login page and the moment you authorize the client ..., the authorization server grants the client access token. Unless you are left with no options, please prefer using the authorization code grant because it is a more secure way to authenticate the third party sites. 
Akış şöyle
     +--------+                               +---------------+
     |        |<-(B)-- Authorization Grant ---|   Resource    |
     |        |                               |     Owner     |
     |        |                               |               |
     |        |                               +---------------+
     |        |
     |        |                               +---------------+
     |        |--(A)- Authorization Request ->| Authorization |
     | Client |                               |     Server    |
     |        |<-(c)----- Access Token -------|               |
     |        |                               +---------------+
     |        |
     |        |                               +---------------+
     |        |--(D)----- Access Token ------>|    Resource   |
     |        |                               |     Server    |
     |        |<-(E)--- Protected Resource ---|               |
     +--------+                               +---------------+
3. Resource Owner Credentials Grant (Yani Password Grant) Nedir

Bu akış OAuth2.1 ile deprecate edildi.

Açıklaması şöyle. Burada aslında Authorization Server login işlemi için kullanılıyor. Yani authorization amaçlı değil, authentication amaçlı
Requires logging in with a username and password. In that case, the credentials will be a part of the request. This flow is suitable only for trusted clients (for example, official applications released by the API provider).
Örnek - keycloak
Kullanıcı kim olduğunu, ismini ve şifresini gönderir. Şöyle yaparız.
curl -X POST \
  http://localhost:8080/oauth/token \
  -H 'authorization: Basic c3ByaW5nLXNlY3VyaXR5LW9hdXRoMi1yZWFkLXdyaXRlLWNsaWVudDpzcHJpbmctc2VjdXJpdHktb2F1dGgyLXJlYWQtd3JpdGUtY2xpZW50LXBhc3N3b3JkMTIzNA==' \
  -F grant_type=password \
  -F username=admin \
  -F password=admin1234 \
  -F client_id=spring-security-oauth2-read-write-client
Örnek - keycloak
keycload sunucusundan şifremizi almak için şöyle yaparız
# Connect to Keycloak
./kcadm.sh config credentials --server http://localhost:8080 
  --realm master --user admin --password admin

# Get clientId
./kcadm.sh get clients -r spring-boot-keycloak --fields id,clientId

# Get clientSecret
./kcadm.sh get clients/{CLIENT_ID_FROM_PREVIOUS_COMMAND}/client-secret 
  -r spring-boot-keycloak
Şöyle yaparız
curl --location --request POST 'http://localhost:8080/realms/spring-boot-keycloak/protocol/openid-connect/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'username=john.smith' \
--data-urlencode 'password=password' \
--data-urlencode 'client_id=spring-boot-keycloak-country-api-client' \
--data-urlencode 'client_secret={CLIENT_SECRET_FROM_PREVIOUS_STEP}' \
--data-urlencode 'grant_type=password'
Cevap şöyle
{
"access_token": "{HERE_YOU_GET_AN_ACCESS_TOKEN}",
"expires_in": 300,
"refresh_expires_in": 1800,
"refresh_token": "{HERE_YOU_GET_A_REFRESH_TOKEN}",
"token_type": "Bearer",
"not-before-policy": 0,
"session_state": "{HERE_YOU_GET_A_SESSION_STATE}",
"scope": "profile email"
}
Artık access_token ile bir Resource Server'a istekte bulunuruz. Şöyle yaparız
curl --location --request GET 'http://localhost:8085/countries' \
--header 'Authorization: Bearer {ACCESS_TOKEN_FROM_PREVIOUS_STEP}'
Örnek - Azure
Şöyle yaparız
URI https://login.microsoftonline.com/<tenant-id>/oauth2/token
Method - POST
Form urlencoded body
grant_type=password
username=<username>
password=<password>
resource=<clientId>
client_id=<clientId>
Doğrulama işlemi başarılı ise karşılığında bir nesne gelir. Açıklaması şöyle
The authorization server will respond with a JSON object containing the following properties:

- token_type with the value Bearer
- expires_in with an integer representing the TTL of the access token
- access_token the access token itself
- refresh_token a refresh token that can be used to acquire a new access token when the original expires
Access token içinde scope alanında yetkiler (read, write yetkisi gibi) tanımlıdır.
Akış şöyle
     +----------+
     | Resource |
     |  Owner   |
     |          |
     +----------+
          v
          |    Resource Owner
         (A) Password Credentials
          |
          v
     +---------+                                  +---------------+
     |         |>--(B)---- Resource Owner ------->|               |
     |         |         Password Credentials     | Authorization |
     | Client  |                                  |     Server    |
     |         |<--(C)---- Access Token ---------<|               |
     |         |    (w/ Optional Refresh Token)   |               |
     +---------+                                  +---------------+

4. Client Credentials Grant Nedir?
OAuth2 Client Credentials Grant yazısına taşıdım

5. Refresh Token Grant
OAuth2 Refresh Token Grant yazısına taşıdım

29 Haziran 2020 Pazartesi

Http Post ve application/x-www-form-urlencoded

Giriş
Http ile POST işlemi için 3 seçenek var.

1. application/x-www-form-urlencoded (the default) - Parametre Gönderir
2. multipart/form-data - Dosya Gönderir
3. text/plain - Bilmiyorum

1. application/x-www-form-urlencoded - Parametre Göndermek İçindir
Sorgu string'i gibi şeyleri göndermek için kullanılır.

Http Get isteğinde veri key1=value1&key2=value2 şeklindeki URL içinde gönderilir.
Post isteğinde veriyi URL içine koyma imkanı yok ancak benzer bir mantık güdülerek parametreler Body içine koyuluyor.

Örnek
Post isteğini Postman ile şöyle görürürüz.
Headers: 
  Content-Type: application/x-www-form-urlencoded
Body:
  username: <my-username>
  password: <my-password>
Örnek
Şöyle yaparız
POST /test HTTP/1.1
Host: foo.example
Content-Type: application/x-www-form-urlencoded
Content-Length: 27

field1=value1&field2=value2
Örnek
Şöyle yaparız.
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL);
request.Method = "POST";
request.ContentLength = data.Length;
request.ContentType = "application/x-www-form-urlencoded";

using (StreamWriter sw = new StreamWriter(request.GetRequestStream(),
  System.Text.Encoding.ASCII))
{
  sw.Write(data);
  sw.Close();
 }
Örnek
Swift ile pot işlemi için şöyle yaparız.
func post (){
 let url = URL(string: "https://the-game-stevens-apps.c9users.io/index.html/")!
 var request = URLRequest(url: url)
 request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Accept")
 request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
 request.httpMethod = "POST"
 let postString = "name=henry&message=HelloWorld"
 request.httpBody = postString.data(using: .utf8)
  ...
}
2. multipart/form-data
Dosya yüklemek için kullanılır. Açıklaması şöyle.
The content type "application/x-www-form-urlencoded" is inefficient for sending large quantities of binary data or text containing non-ASCII characters. The content type "multipart/form-data" should be used for submitting forms that contain files, non-ASCII data, and binary data.

3. text/plain
Tam olarak ne işe yarar bilmiyorum.

Transport Layer Security - TLS

Giriş
HTTP'nin eksiklikleri var. Açıklaması şöyle.  Yani HTTP "Man In The Middle Attack" saldırısına açık.
HTTP has no mechanism...
- to verify that you are actually connected to the server that you intend to connect to,
- or actually downloading the file that you expected to receive.
DTLS - Datagram Transport Layer Security
Yazıya başlamadan önce TLS alternatiflerinden bahsetme gerek :) TLS TCP kullanır, DTLS ise UDP kullanır. Açıklaması şöyle
DTLS is basically TLS, but for UDP. The reason you might want to use DTLS is because your application uses UDP instead of TCP (e.g. a VoIP program), but you still want your datagrams to be encrypted.

DTLS is not more or less secure than TLS, but instead is designed to work with a different underlying layer.
TLS - Transport Layer Security
Transport Layer Security 3 tane önemli şey sağlar. Confidentiality (Gizlilik), Integrity (Bütünlük), Authenticity (Sahicilik) Açıklaması şöyle
Confidentiality: that nobody can see the traffic between you and facebook.com (including the guy at the next table at Starbucks, your ISP, some sketchy network equipment in the datacentre COUGH NSA, nobody).

Integrity: that nobody is modifying the messages as they travel between you and facebook.com (this is separate from Confidentiality because some kinds of attacks allow you to modify the message in a malicious way even if you don't know what the messages are).

Authenticity: that you are talking to the authentic facebook.com server, not a spoofed version of it.
TLS ve E-Posta
Açıklaması şöyle. E-Posta tümüyle TLS kullanmadığı için, tam anlamıyla güvenli değil.
Mail delivery using TLS and signing using DKIM are weak protections, compared to accessing a web site using HTTPS. They should not be assumed to provide the same security and the indicators better should not suggest such interpretation.
..
Mail is delivered hop-by-hop between client and final mail server, i.e. there are multiple servers in between. TLS cares only about protection between these hops, not on these hops. Each of these servers has access to the plain unencrypted mail. The indicator in GMail shows only if the last hop of delivery was done over TLS - and this is all what the final mail server can control.
TLS ve Application Layer
HTTP isteğinin tamamı şifrelenir. Açıklama HTTPs için ancak TLS içinde geçerli. Açıklaması şöyle
HTTPS protects the whole HTTP request. The url path, the parameters, cookies, http headers, the body... The only thing it doesn't protect (other than tcp parameters like ip addresses and ports) is the hostname you are connecting to, which is leaked through the SNI extension (this should be fixed by tls-esni, just a draft for now)
TLS Layer 3'te de Kullanılabilir
TLS normalde Layer 3'ten yukarıda yani Application Layer'da kullanılır diye düşünüyoruz. Ancak daha alt seviyede de kullanılabiliyormuş. Açıklaması şöyle.
TLS is a protocol that has many different uses. The most common one is in HTTPS but many other protocols use it too as it's a standard way to encrypt network traffic. That's the application level.

In AWS Client VPN it's being used one level down - to encrypt the actual network layer traffic (level 3), regardless of what's passing through the tunnel. They chose to use TLS because it's a standard well known protocol.
SSL
Artık kullanılmamalı. Açıklaması şöyle.
30 June 2018 is the deadline for disabling SSL/early TLS and implementing a more secure encryption protocol – TLS 1.1 or higher (TLS v1.2 is strongly encouraged) in order to meet the PCI Data Security Standard (PCI DSS) for safeguarding payment data.
Sürümleri şöyle
SSL 1.0 (obsolete)
SSL 2.0 (obsolete)
SSL 3.0 (mostly obsolete)
TLS 1.0
TLS 1.1
TLS 1.2
TLS 1.1
Artık kullanılmamalı. Chrome Açıklaması şöyle
In Chrome 81, which will be released to the Stable channel in March 2020, we will begin blocking connections to sites using TLS 1.0 or 1.1, showing a full page interstitial warning:
TLS 1.2
TLS 1.2 internetteki varsayılan kripto. Açıklaması şöyle
TLS v.1.2 is the defacto standard for encrypted communications today. There are other protocols, like IPSEC, or even TLS v.1.3, but TLS v.1.2 is the default choice for web browsers at this point. And this makes it the most widely distributed encryption protocol ever.
Bir önceki sürüme yeni kripto ekliyor. Açıklaması şöyle.
TLS 1.2 did add new crypto, for example you can now use AES instead of 3DES, or ECDHE instead of DHE. At the moment, there are no known attacks against those ciphers so you can't directly say that it's for security. 1.2 also replaces MD5 and SHA1. That is a security improvement, but for something as short-lived as a TLS connection, it's unlikely to be a major weakness.
TLS 1.3
TLS v1.3 yazısına taşıdım.

TLS ve TCP
TLS altta TCP kullanır. Açıklaması şöyle
TLS requires a reliable transport. On the internet, this leaves only TCP, as UDP does not offer reliability.

TLS does require a reliable transport because (in compliance with the layered architecture of the ISO/OSI reference model) it does not handle transport errors, lost packets or other disturbances that may occur with IP.

TLS is designed to offer a secure channel on top of a reliable transport and it does this quite well. DTLS does (I assume) the necessary error handling within the protocol.

If TLS was to be performed over UDP, connections and handshakes could fail just because a packet got lost in transit and no one noticed.
TLS ve Overhead
Açıklaması şöyle
  • he total overhead to establish a new TLS session comes to about 6.5k bytes on average
  • The total overhead to resume an existing TLS session comes to about 330 bytes on average
  • The total overhead of the encrypted data is about 40 bytes (20 + 15 + 5)
  • It is easy to modify the above calculations to reflect more precisely the specifics of an environment, so this should be considered a basis for TLS overhead and not the authoritative answer to the question posed.
TLS ve Replay Protection
Açıklaması şöyle. Yani TLS çift gelen paketleri tespit edebilir.
There are multiple mechanisms to detect duplicates.

- At the TCP level there is the sequence number sent within each TCP packet, which allows to detect if a packet was received twice, or more generally if it overlaps with already received data. This is not actually a security feature but to detect packet reordering, duplication and loss and this way provide a reliable transport layer on top of an unreliable network layer. If such a duplicate gets detected it will simply be discarded.

- At the TLS level no sequence number are explicitly sent on the wire, but sequence numbers are still maintained inside the TLS state of each peer and are included in the computation of the payload protection. Thus TLS has a replay protection by design - see TLS sequence number for more. Since a successfully replayed packet essentially means that an attacker was able to actively fiddle with the underlying reliable TCP connection, this connection will usually be treated as compromised and abandoned.

- Additionally each new TLS session results in a different encryption key, i.e. the server would not be able to decrypt a HTTP request sniffed from a different TLS session in the first place. Thanks to user253751 pointing this out in a comment.
TLS ve Sıkıştırma (Compression)
Açıklaması şöyle.
...a famous attack, called CRIME, and has lead to TLS abandoning compression at the security protocol level.
Server Name Indication Eklentisi- SNI
Açıklaması şöyle. Kısaca TSL kullanarak bağlanmak istediğmiz sunucunun ismi SNI ile belirtilir.
HTTPS does not hide the server that is being accessed, because it needs the SNI (Server Name Indication) to be on the clear, so the server can know which certificate to use on the connection. Once the handshake is established, everything else is encrypted, including which page you are requesting.
Açıklaması şöyle
SNI (Server Name Indication) is a TLS (Transport Layer Security) extension in which the client presents the server the domain name for the target it wants to access within the TLS handshake. It is used in cases where there are multiple virtual servers with different certificates on the same IP address, so that the server can present the correct certificate.

Insofar it is similar to the HTTP host header in the HTTP request which is used to select the matching virtual host configuration - only that the Host header can not be used to select the certificate since it gets only sent inside the HTTP request. (i.e. after the TLS handshake is already done).

Since the SNI TLS extension is optional, some clients may not sent this extension. This is the case with openssl s_client without -servername argument but also with many TLS libraries in different programming languages. And while all modern browsers use SNI older browser like IE8 on XP do not use it.

If such a client connects to a server which has multiple certificates, the server does not know which certificate the client actually needs, i.e. the client falls into the "SNI hole" by not using the SNI extension. In this case the server usually either send an error back (or sometimes just closes the connection) or uses a default certificate explicitly or implicitly configured for this purpose.
Bu alana IP adresi yazılamaz. Açıklaması şöyle.
Literal IPv4 and IPv6 addresses are not permitted in "HostName".
Eğer istek içinde SNI belirtilmezse sunucu geçersiz sertifika dönebilir. Açıklaması şöyle.
That server apparently, like many today, supports multiple 'virtual' hosts with different certificates using the TLS extension 'Server Name Indication' aka SNI. If contacted using SNI for www.isi.gov.ie it provides a certificate which is valid for that domain and isi.gov.ie, but if contacted using no SNI it provides an expired certificate for the domains *.rdccremote.ie and rdccremote.ie;
Encrypted Server Name Indication Eklentisi
Açıklaması şöyle. Bir başka açıklama burada.
 It is part of the TLS 1.3 specification,...
mTLS 
Mutual TLS - mTLS yazısına taşıdım