GitBook: [master] 511 pages and one asset modified

This commit is contained in:
CPol 2021-08-30 22:36:25 +00:00 committed by gitbook-bot
parent e2608b3318
commit b06aa6854b
No known key found for this signature in database
GPG Key ID: 07D2180C7B12D0FF
12 changed files with 1102 additions and 12 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

View File

@ -474,6 +474,10 @@
* [BIM Bruteforcer](a.i.-exploiting/bra.i.nsmasher-presentation/bim-bruteforcer.md)
* [Hybrid Malware Classifier Part 1](a.i.-exploiting/bra.i.nsmasher-presentation/hybrid-malware-classifier-part-1.md)
## Blockchain
* [Blockchain & Crypto Currencies](blockchain/blockchain-and-crypto-currencies.md)
## Courses and Certifications Reviews
* [INE Courses and eLearnSecurity Certifications Reviews](courses-and-certifications-reviews/ine-courses-and-elearnsecurity-certifications-reviews.md)
@ -513,15 +517,15 @@
* [PwnTools](exploiting/tools/pwntools.md)
* [Windows Exploiting \(Basic Guide - OSCP lvl\)](exploiting/windows-exploiting-basic-guide-oscp-lvl.md)
## Crypto
## Cryptography
* [Certificates](crypto/certificates.md)
* [Cipher Block Chaining CBC-MAC](crypto/cipher-block-chaining-cbc-mac-priv.md)
* [Crypto CTFs Tricks](crypto/crypto-ctfs-tricks.md)
* [Electronic Code Book \(ECB\)](crypto/electronic-code-book-ecb.md)
* [Hash Length Extension Attack](crypto/hash-length-extension-attack.md)
* [Padding Oracle](crypto/padding-oracle-priv.md)
* [RC4 - Encrypt&Decrypt](crypto/rc4-encrypt-and-decrypt.md)
* [Certificates](cryptography/certificates.md)
* [Cipher Block Chaining CBC-MAC](cryptography/cipher-block-chaining-cbc-mac-priv.md)
* [Crypto CTFs Tricks](cryptography/crypto-ctfs-tricks.md)
* [Electronic Code Book \(ECB\)](cryptography/electronic-code-book-ecb.md)
* [Hash Length Extension Attack](cryptography/hash-length-extension-attack.md)
* [Padding Oracle](cryptography/padding-oracle-priv.md)
* [RC4 - Encrypt&Decrypt](cryptography/rc4-encrypt-and-decrypt.md)
## BACKDOORS

View File

@ -0,0 +1,189 @@
# Blockchain & Crypto Currencies
## Basic Terminology
* **Smart contract**: Smart contracts are simply **programs stored on a blockchain that run when predetermined conditions are met**. They typically are used to automate the **execution** of an **agreement** so that all participants can be immediately certain of the outcome, without any intermediarys involvement or time loss. \(From [here](https://www.ibm.com/topics/smart-contracts)\).
* Basically, a smart contract is a **piece of code** that is going to be executed when people access and accept the contract. Smart contracts **run in blockchains** \(so the results are stored inmutable\) and can be read by the people before accepting them.
* **dApps**: **Decentralised applications** are implemented on top of **smart** **contracts**. They usually have a front-end where the user can interact with the app, the **back-end** is public \(so it can be audited\) and is implemented as a **smart contract**. Sometimes the use of a database is needed, Ethereum blockchain allocates certain storage to each account.
* **Tokens & coins**: A **coin** is a cryptocurrency that act as **digital** **money** and a **token** is something that **represents** some **value** but it's not a coin.
* **Utility Tokens**: These tokens allow the user to **access certain service later** \(it's something that have some value in a specific environment\).
* **Security Tokens**: These represents the **ownership** or some asset.
* **DeFi**: **Decentralized Finance**.
* **DEX: Decentralized Exchange Platforms**.
* **DAOs**: **Decentralized Autonomous Organizations**.
## Consensus Mechanisms
For a blockchain transaction to be recognized, it must be **appended** to the **blockchain**. Validators \(miners\) carry out this appending; in most protocols, they **receive a reward** for doing so. For the blockchain to remain secure, it must have a mechanism to **prevent a malicious user or group from taking over a majority of validation**.
Proof of work, another commonly used consensus mechanism, uses a validation of computational prowess to verify transactions, requiring a potential attacker to acquire a large fraction of the computational power of the validator network.
### Proof Of Work \(PoW\)
This uses a **validation of computational prowess** to verify transactions, requiring a potential attacker to acquire a large fraction of the computational power of the validator network.
The **miners** will **select several transactions** and then start **computing the Proof Of Work**. The **miner with the greatest computation resources** is more probably to **finish** **earlier** the Proof of Work and get the fees of all the transactions.
### Proof Of Stake \(PoS\)
PoS accomplishes this by **requiring that validators have some quantity of blockchain tokens**, requiring **potential attackers to acquire a large fraction of the tokens** on the blockchain to mount an attack.
In this kind of consensus, the more tokens a miner has, the more probably it will be that the miner will be asked to create the next block.
Compared with PoW, this greatly **reduced the energy consumption** the miners are expending.
## Bitcoin
### Transactions
A simple **transaction** is a **movement of money** from an address to another one.
An **address** in bitcoin is the hash of the **public** **key**, therefore, someone in order to make a transaction from an address he needs to know the private key associated to that public key \(the address\).
Then, when a **transaction** is performed, it's **signed** with the private key of the address to show that the transaction is **legit**.
The first part of producing a digital signature in Bitcoin can be represented mathematically in the following way:
_**Sig**_ = _**Fsig**_\(_**Fhash**_\(_**m**_\),_**dA**_\)
Where:
* _d_A is the signing **private key**
* _m_ is the **transaction**
* Fhash is the hashing function
* Fsig is the signing algorithm
* Sig is the resulting signature
The signing function \(Fsig\) produces a signature \(Sig\) that comprises of two values: R and S:
* Sig = \(R, S\)
Once R and S have been calculated, they are serialized into a byte stream that is encoded using an international standard encoding scheme that is known as the Distinguished Encoding Rules \(or DER\). In order to verify that the signature is valid, a signature verification algorithm is used. Verification of a digital signature requires the following:
* Signature \(R and S\)
* Transaction hash
* The public key that corresponds to the private key that was used to create the signature
Verification of a signature effectively means that only the owner of the private key \(that generated the public key\) could have produced the signature on the transaction. The signature verification algorithm will return TRUE if the signature is indeed valid.
#### Multisignature Transactions
A multi-signature **address** is an address that is associated with more than one ECDSA private key. The simplest type is an m-of-n address - it is associated with n private keys, and sending bitcoins from this address requires signatures from at least m keys. A multi-signature **transaction** is one that sends funds from a multi-signature address.
#### Transactions Fields
Each bitcoin transaction has several fields:
* **Inputs**: The amount and address **from** where **bitcoins** are **being** transferred
* **Outputs**: The address and amounts that each **transferred** to **each** **output**
* **Fee:** The amount of **money** that is **payed** to the **miner** of the transaction
* **Script\_sig**: Script signature of the transaction
* **Script\_type**: Type of transaction
There are **2 main types** of transactions:
* **P2PKH: "Pay To Public Key Hash"**: This is how transactions are made. You are requiring the **sender** to supply a valid **signature** \(from the private key\) and **public** **key**. The transaction output script will use the signature and public key and through some cryptographic functions will check **if it matches** with the public key hash, if it does, then the **funds** will be **spendable**. This method conceals your public key in the form of a hash for extra security.
* **P2SH: "Pay To Script Hash":** The outputs of a transaction are just **scripts** \(this means the person how want this money send a script\) that, if are **executed with specific parameters, will result in a boolean of `true` or `false`**. If a miner runs the output script with the supplied parameters and results in `true`, the **money will be sent to your desired output**. `P2SH` is used for **multi-signature** wallets making the output scripts **logic that checks for multiple signatures before accepting the transaction**. `P2SH` can also be used to allow anyone, or no one, to spend the funds. If the output script of a P2SH transaction is just `1` for true, then attempting to spend the output without supplying parameters will just result in `1` making the money spendable by anyone who tries. This also applies to scripts that return `0`, making the output spendable by no one.
### Lightning Network
This protocol helps to **perform several transactions to a channe**l and **just** **sent** the **final** **state** to the blockchain to save it.
This **improves** bitcoin blockchain **speed** \(it just on allow 7 payments per second\) and it allows to create **transactions more difficult to trace** as the channel is created via nodes of the bitcoin blockchain:
![](../.gitbook/assets/image%20%28611%29.png)
Normal use of the Lightning Network consists of **opening a payment channel** by committing a funding transaction to the relevant base blockchain \(layer 1\), followed by making **any number** of Lightning Network **transactions** that update the tentative distribution of the channel's funds **without broadcasting those to the blockchain**, optionally followed by closing the payment channel by **broadcasting** the **final** **version** of the settlement transaction to distribute the channel's funds.
Note that any of the both members of the channel can stop and send the final state of the channel to the blockchain at any time.
## Bitcoin Tracing Transactions Techniques
### Common Input
Theoretically the inputs of one transaction can belong to different users, but in reality that is unusual as it requires extra steps. Therefore, very often it can be assumed that **2 input addresses in the same transaction belongs to the same owner**.
### UTXO Change Address Detection
**UTXO** means **Unspent Transaction Outputs** \(UTXOs\). In a transaction that uses the output from a previous transaction as an input, the **whole output need to be spent** \(to avoid double-spend attacks\). Therefore, if the intention was to **send** just **part** of the money from that output to an address and **keep** the **other** **part**, **2 different outputs** will appear: the **intended** one and a **random new change address** where the rest of the money will be saved.
Then, a watcher can make the assumption that **the new change address generated belong to the owner of the UTXO**.
### Social Networks & Forums
Some people gives data about theirs bitcoin addresses in different webs on Internet. **This make pretty easy to identify the owner of an address**.
### Transaction Graphs
By representing the transactions in graphs, i**t's possible to know with certain probability to where the money of an account were**. Therefore, it's possible to know something about **users** that are **related** in the blockchain.
### **Unnecessary input heuristic**
Also called the "optimal change heuristic". Consider this bitcoin transaction. It has two inputs worth 2 BTC and 3 BTC and two outputs worth 4 BTC and 1 BTC.
```text
2 btc --> 4 btc
3 btc 1 btc
```
Assuming one of the outputs is change and the other output is the payment. There are two interpretations: the payment output is either the 4 BTC output or the 1 BTC output. But if the 1 BTC output is the payment amount then the 3 BTC input is unnecessary, as the wallet could have spent only the 2 BTC input and paid lower miner fees for doing so. This is an indication that the real payment output is 4 BTC and that 1 BTC is the change output.
This is an issue for transactions which have more than one input. One way to fix this leak is to add more inputs until the change output is higher than any input, for example:
```text
2 btc --> 4 btc
3 btc 6 btc
5 btc
```
### Other Analysis
* **Exact Payment Amounts**: In order to avoid transactions with a change, the payment needs to be equal to the UTXO \(which is highly unexpected\). Therefore, a **transaction with no change address are probably transfer between 2 addresses of the same user**.
* **Round Numbers**: In a transaction, if one of the outputs is a "**round number**", it's highly probable that this is a **payment to a human that put that** "round number" **price**, so the other part must be the leftover.
* **Wallet fingerprinting:** A careful analyst sometimes deduce which software created a certain transaction, because the many **different wallet softwares don't always create transactions in exactly the same way**. Wallet fingerprinting can be used to detect change outputs because a change output is the one spent with the same wallet fingerprint.
* **Amount & Timing correlations**: If the person that performed the transaction **discloses** the **time** and/or **amount** of the transaction, it can be easily **discoverable**.
## Ethereum
### Gas
Gas refers to the unit that measures the **amount** of **computational** **effort** required to execute specific operations on the Ethereum network. Gas refers to the **fee** required to successfully conduct a **transaction** on Ethereum.
Gas prices are denoted in **gwei**, which itself is a denomination of ETH - each gwei is equal to **0.000000001 ETH** \(10-9 ETH\). For example, instead of saying that your gas costs 0.000000001 ether, you can say your gas costs 1 gwei. The word 'gwei' itself means 'giga-wei', and it is equal to **1,000,000,000 wei**. Wei itself is the **smallest unit of ETH**.
To calculate the gas that a transaction is going to cost read this example:
Lets say Jordan has to pay Taylor 1 ETH. In the transaction the gas limit is 21,000 units and the base fee is 100 gwei. Jordan includes a tip of 10 gwei.
Using the formula above we can calculate this as `21,000 * (100 + 10) = 2,310,000 gwei` or 0.00231 ETH.
When Jordan sends the money, 1.00231 ETH will be deducted from Jordan's account. Taylor will be credited 1.0000 ETH. Miner receives the tip of 0.00021 ETH. Base fee of 0.0021 ETH is burned.
Additionally, Jordan can also set a max fee \(`maxFeePerGas`\) for the transaction. The difference between the max fee and the actual fee is refunded to Jordan, i.e. `refund = max fee - (base fee + priority fee)`. Jordan can set a maximum amount to pay for the transaction to execute and not worry about overpaying "beyond" the base fee when the transaction is executed.
As the base fee is calculated by the network based on demand for block space, this last param: maxFeePerGas helps to control the maximum fee that is going to be payed.
### Transactions
Notice that in the **Ethereum** network a transaction is performed between 2 addresses and these can be **user or smart contract addresses**.
**Smart Contracts** are stored in the distributed ledger via a **special** **transaction**.
Transactions, which change the state of the EVM, need to be broadcast to the whole network. Any node can broadcast a request for a transaction to be executed on the EVM; after this happens, a **miner** will **execute** the **transaction** and propagate the resulting state change to the rest of the network.
Transactions require a **fee** and must be mined to become valid.
A submitted transaction includes the following information:
* `recipient` the receiving address \(if an externally-owned account, the transaction will transfer value. If a contract account, the transaction will execute the contract code\)
* `signature` the identifier of the sender. This is generated when the sender's private key signs the transaction and confirms the sender has authorised this transaction
* `value` amount of ETH to transfer from sender to recipient \(in WEI, a denomination of ETH\)
* `data` optional field to include arbitrary data
* `gasLimit` the maximum amount of gas units that can be consumed by the transaction. Units of gas represent computational steps
* `maxPriorityFeePerGas` - the maximum amount of gas to be included as a tip to the miner
* `maxFeePerGas` - the maximum amount of gas willing to be paid for the transaction \(inclusive of `baseFeePerGas` and `maxPriorityFeePerGas`\)
Note that there isn't any field for the origin address, this is because this can be extrapolated from the signature.
## References
* [https://en.wikipedia.org/wiki/Proof\_of\_stake](https://en.wikipedia.org/wiki/Proof_of_stake)
* [https://www.mycryptopedia.com/public-key-private-key-explained/](https://www.mycryptopedia.com/public-key-private-key-explained/)
* [https://bitcoin.stackexchange.com/questions/3718/what-are-multi-signature-transactions](https://bitcoin.stackexchange.com/questions/3718/what-are-multi-signature-transactions)
* [https://ethereum.org/en/developers/docs/transactions/](https://ethereum.org/en/developers/docs/transactions/)
* [https://ethereum.org/en/developers/docs/gas/](https://ethereum.org/en/developers/docs/gas/)
* [https://en.bitcoin.it/wiki/Privacy](https://en.bitcoin.it/wiki/Privacy#Forced_address_reuse)

View File

@ -0,0 +1,176 @@
# Certificates
## What is a Certificate
In cryptography, a **public key certificate,** also known as a **digital certificate** or **identity certificate,** is an electronic document used to prove the ownership of a public key. The certificate includes information about the key, information about the identity of its owner \(called the subject\), and the digital signature of an entity that has verified the certificate's contents \(called the issuer\). If the signature is valid, and the software examining the certificate trusts the issuer, then it can use that key to communicate securely with the certificate's subject.
In a typical [public-key infrastructure](https://en.wikipedia.org/wiki/Public-key_infrastructure) \(PKI\) scheme, the certificate issuer is a [certificate authority](https://en.wikipedia.org/wiki/Certificate_authority) \(CA\), usually a company that charges customers to issue certificates for them. By contrast, in a [web of trust](https://en.wikipedia.org/wiki/Web_of_trust) scheme, individuals sign each other's keys directly, in a format that performs a similar function to a public key certificate.
The most common format for public key certificates is defined by [X.509](https://en.wikipedia.org/wiki/X.509). Because X.509 is very general, the format is further constrained by profiles defined for certain use cases, such as [Public Key Infrastructure \(X.509\)](https://en.wikipedia.org/wiki/PKIX) as defined in RFC 5280.
## x509 Common Fields
* **Version Number:** Version of x509 format.
* **Serial Number**: Used to uniquely identify the certificate within a CA's systems. In particular this is used to track revocation information.
* **Subject**: The entity a certificate belongs to: a machine, an individual, or an organization.
* **Common Name**: Domains affected by the certificate. Can be 1 or more and can contain wildcards.
* **Country \(C\)**: Country
* **Distinguished name \(DN\)**: The whole subject: `C=US, ST=California, L=San Francisco, O=Example, Inc., CN=shared.global.example.net`
* **Locality \(L\)**: Local place
* **Organization \(O\)**: Organization name
* **Organizational Unit \(OU\)**: Division of an organisation \(like "Human Resources"\).
* **State or Province \(ST, S or P\)**: List of state or province names
* **Issuer**: The entity that verified the information and signed the certificate.
* **Common Name \(CN\)**: Name of the certificate authority
* **Country \(C\)**: Country of the certificate authority
* **Distinguished name \(DN\)**: Distinguished name of the certificate authority
* **Locality \(L\)**: Local place where the organisation can be found.
* **Organization \(O\)**: Organisation name
* **Organizational Unit \(OU\)**: Division of an organisation \(like "Human Resources"\).
* **Not Before**: The earliest time and date on which the certificate is valid. Usually set to a few hours or days prior to the moment the certificate was issued, to avoid [clock skew](https://en.wikipedia.org/wiki/Clock_skew#On_a_network) problems.
* **Not After**: The time and date past which the certificate is no longer valid.
* **Public Key**: A public key belonging to the certificate subject. \(This is one of the main parts as this is what is signed by the CA\)
* **Public Key Algorithm**: Algorithm used to generate the public key. Like RSA.
* **Public Key Curve**: The curve used by the elliptic curve public key algorithm \(if apply\). Like nistp521.
* **Public Key Exponent**: Exponent used to derive the public key \(if apply\). Like 65537.
* **Public Key Size**: The size of the public key space in bits. Like 2048.
* **Signature Algorithm**: The algorithm used to sign the public key certificate.
* **Signature**: A signature of the certificate body by the issuer's private key.
* **x509v3 extensions**
* **Key Usage**: The valid cryptographic uses of the certificate's public key. Common values include digital signature validation, key encipherment, and certificate signing.
* In a Web certificate this will appear as a _X509v3 extension_ and will have the value `Digital Signature`
* **Extended Key Usage**: The applications in which the certificate may be used. Common values include TLS server authentication, email protection, and code signing.
* In a Web certificate this will appear as a _X509v3 extension_ and will have the value `TLS Web Server Authentication`
* **Subject Alternative Name:** Allows users to specify additional host **names** for a single SSL **certificate**. The use of the SAN extension is standard practice for SSL certificates, and it's on its way to replacing the use of the common **name**.
* **Basic Constraint:** This extension describes whether the certificate is a CA certificate or an end entity certificate. A CA certificate is something that signs certificates of others and a end entity certificate is the certificate used in a web page for example \(the last par of the chain\).
* **Subject Key Identifier** \(SKI\): This extension declares a unique **identifier** for the public **key** in the certificate. It is required on all CA certificates. CAs propagate their own SKI to the Issuer **Key Identifier** \(AKI\) extension on issued certificates. It's the hash of the subject public key.
* **Authority Key Identifier**: It contains a key identifier which is derived from the public key in the issuer certificate. It's the hash of the issuer public key.
* **Authority Information Access** \(AIA\): This extension contains at most two types of information :
* Information about **how to get the issuer of this certificate** \(CA issuer access method\)
* Address of the **OCSP responder from where revocation of this certificate** can be checked \(OCSP access method\).
* **CRL Distribution Points**: This extension identifies the location of the CRL from which the revocation of this certificate can be checked. The application that processes the certificate can get the location of the CRL from this extension, download the CRL and then check the revocation of this certificate.
* **CT Precertificate SCTs**: Logs of Certificate transparency regarding the certificate
### Difference between OSCP and CRL Distribution Points
**OCSP** \(RFC 2560\) is a standard protocol that consists of an **OCSP client and an OCSP responder**. This protocol **determines revocation status of a given digital public-key certificate** **without** having to **download** the **entire CRL**.
**CRL** is the **traditional method** of checking certificate validity. A **CRL provides a list of certificate serial numbers** that have been revoked or are no longer valid. CRLs let the verifier check the revocation status of the presented certificate while verifying it. CRLs are limited to 512 entries.
From [here](https://www.arubanetworks.com/techdocs/ArubaOS%206_3_1_Web_Help/Content/ArubaFrameStyles/CertRevocation/About_OCSP_and_CRL.htm#:~:text=OCSP%20%28RFC%202560%29%20is%20a,to%20download%20the%20entire%20CRL.&text=A%20CRL%20provides%20a%20list,or%20are%20no%20longer%20valid.).
### What is Certificate Transparency
Certificate Transparency aims to remedy certificate-based threats by **making the issuance and existence of SSL certificates open to scrutiny by domain owners, CAs, and domain users**. Specifically, Certificate Transparency has three main goals:
* Make it impossible \(or at least very difficult\) for a CA to **issue a SSL certificate for a domain without the certificate being visible to the owner** of that domain.
* Provide an **open auditing and monitoring system that lets any domain owner or CA determine whether certificates have been mistakenly or maliciously** issued.
* **Protect users** \(as much as possible\) from being duped by certificates that were mistakenly or maliciously issued.
#### **Certificate Logs**
Certificate logs are simple network services that maintain **cryptographically assured, publicly auditable, append-only records of certificates**. **Anyone can submit certificates to a log**, although certificate authorities will likely be the foremost submitters. Likewise, anyone can query a log for a cryptographic proof, which can be used to verify that the log is behaving properly or verify that a particular certificate has been logged. The number of log servers doesnt have to be large \(say, much less than a thousand worldwide\), and each could be operated independently by a CA, an ISP, or any other interested party.
#### Query
You can query the logs of Certificate Transparency of any domain in [https://crt.sh/](https://crt.sh/).
## Formats
There are different formats that can be used to store a certificate.
#### **PEM Format**
* It is the most common format used for certificates
* Most servers \(Ex: Apache\) expects the certificates and private key to be in a separate files - Usually they are Base64 encoded ASCII files - Extensions used for PEM certificates are .cer, .crt, .pem, .key files - Apache and similar server uses PEM format certificates
#### **DER Format**
* The DER format is the binary form of the certificate
* All types of certificates & private keys can be encoded in DER format
* DER formatted certificates do not contain the "BEGIN CERTIFICATE/END CERTIFICATE" statements
* DER formatted certificates most often use the .cer and '.der' extensions
* DER is typically used in Java Platforms
#### **P7B/PKCS\#7 Format**
* The PKCS\#7 or P7B format is stored in Base64 ASCII format and has a file extension of .p7b or .p7c
* A P7B file only contains certificates and chain certificates \(Intermediate CAs\), not the private key
* The most common platforms that support P7B files are Microsoft Windows and Java Tomcat
#### **PFX/P12/PKCS\#12 Format**
* The PKCS\#12 or PFX/P12 format is a binary format for storing the server certificate, intermediate certificates, and the private key in one encryptable file
* These files usually have extensions such as .pfx and .p12
* They are typically used on Windows machines to import and export certificates and private keys
### Formats conversions
**Convert x509 to PEM**
```text
openssl x509 -in certificatename.cer -outform PEM -out certificatename.pem
```
#### **Convert PEM to DER**
```text
openssl x509 -outform der -in certificatename.pem -out certificatename.der
```
**Convert DER to PEM**
```text
openssl x509 -inform der -in certificatename.der -out certificatename.pem
```
**Convert PEM to P7B**
**Note:** The PKCS\#7 or P7B format is stored in Base64 ASCII format and has a file extension of .p7b or .p7c. ****A P7B file only contains certificates and chain certificates \(Intermediate CAs\), not the private key. The most common platforms that support P7B files are Microsoft Windows and Java Tomcat.
```text
openssl crl2pkcs7 -nocrl -certfile certificatename.pem -out certificatename.p7b -certfile CACert.cer
```
**Convert PKCS7 to PEM**
```text
openssl pkcs7 -print_certs -in certificatename.p7b -out certificatename.pem
```
**Convert pfx to PEM**
**Note:** The PKCS\#12 or PFX format is a binary format for storing the server certificate, intermediate certificates, and the private key in one encryptable file. PFX files usually have extensions such as .pfx and .p12. PFX files are typically used on Windows machines to import and export certificates and private keys.
```text
openssl pkcs12 -in certificatename.pfx -out certificatename.pem
```
**Convert PFX to PKCS\#8**
**Note:** This requires 2 commands
**1- Convert PFX to PEM**
```text
openssl pkcs12 -in certificatename.pfx -nocerts -nodes -out certificatename.pem
```
**2- Convert PEM to PKCS8**
```text
openSSL pkcs8 -in certificatename.pem -topk8 -nocrypt -out certificatename.pk8
```
**Convert P7B to PFX**
**Note:** This requires 2 commands
1- **Convert P7B to CER**
```text
openssl pkcs7 -print_certs -in certificatename.p7b -out certificatename.cer
```
**2- Convert CER and Private Key to PFX**
```text
openssl pkcs12 -export -in certificatename.cer -inkey privateKey.key -out certificatename.pfx -certfile cacert.cer
```

View File

@ -0,0 +1,65 @@
---
description: 'https://pentesterlab.com/'
---
# Cipher Block Chaining CBC-MAC
**Post from** [**https://pentesterlab.com/**](https://pentesterlab.com/)\*\*\*\*
## CBC
The easiest attack to test is that if the cookie just the username encrypted.
If the cookie is only the username \(or the first part of the cookie is the username\) and you want to impersonate the username "**admin**". Then, you can create the username **"bdmin"** and bruteforce the first byte of the cookie.
## CBC-MAC
CBC-MAC is a method to ensure integrity of a message by encrypting it using CBC mode and keeping the last encrypted block as "signature". This ensures that a malicious user can not modify any part of the data without having to change the signature. The key used for the "encryption" ensures that the signature can't be guessed.
However, when using CBC-MAC, the developer needs to be very careful if the message are not of fixed length. In this example, we will use the fact that there is no protection in place to get the application to sign two messages and build another message by concatenating the two messages.
## Theory
With CBC-MAC, we can generate two signatures `t` and `t'` for the messages `m` and `m'`. By using `m` and `m'` we can forge another message `m''` that will have the same signature as `m'` \(`t'`\). One thing to keep in mind is that the recommended way to use CBC-MAC is to use a NULL IV.
To keep things simple, we are going to work on a single block for each message.
We can see below how signing both messages works \(NB: both signatures are completely independent from each other\):
![](https://pentesterlab.com/cbc-mac/cbc-mac-1.png)
If we try to concatenate those messages, the signature is no longer valid \(since `t` is now the IV for the second block where it was only NULL before\):
![](https://pentesterlab.com/cbc-mac/cbc-mac-2.png)
However, if we XOR `m'` and `t`, the signature is now `t'`:
![](https://pentesterlab.com/cbc-mac/cbc-mac-3.png)
## Implementation
Based on the size of the signature, we can guess that the block size is likely to be 8. With this information, we will split `administrator`:
* `administ`
* `rator\00\00\00`
We can trivially generate the signature for the first block, by just logging in and retrieving the signature `t`.
For the second block, we want the `m'` XOR `t` to be equal to `rator\00\00\00`. So to generate the second username we will need to XOR `rator\00\00\00` with `t` \(since the application will sign it with a NULL IV instead of `t`\). Once we have this value, we can get the signature `t'`.
Finally, we just need to concatenate `m` and `m'` to get `administrator` and use `t'` as signature.
#### Resume
1. Get the signature of username **administ** = **t**
2. Get the signature of username **rator\x00\x00\x00 XOR t** = **t'**
3. Set in the cookie the value **administrator+t'** \(**t'** will be a valid signature of **\(rator\x00\x00\x00 XOR t\) XOR t** = **rator\x00\x00\x00**
### CBC-MAC simple attack \(controlling IV\)
If you can control the used IV the attack could be very easy.
To impersonate the user "**administrator**" you can create the user "**Administrator**" and you will have the cookie with the **username+signature** and the cookie with the **IV**.
To generate the cookies of the username "**administrator**" change the first cookie and set the username from "**Administrator**" to "**administrator**". Change the first byte of the cookie of the **IV** so **IV\[0\] XOR "A" == IV'\[0\] XOR "a"**. Using these cookies you can login as administrator.

View File

@ -0,0 +1,256 @@
# Crypto CTFs Tricks
## Online Hashes DBs
* _**Google it**_
* [http://hashtoolkit.com/reverse-hash?hash=4d186321c1a7f0f354b297e8914ab240](http://hashtoolkit.com/reverse-hash?hash=4d186321c1a7f0f354b297e8914ab240)
* [https://www.onlinehashcrack.com/](https://www.onlinehashcrack.com/)
* [https://crackstation.net/](https://crackstation.net/)
* [https://md5decrypt.net/](https://md5decrypt.net/)
* [https://www.onlinehashcrack.com](https://www.onlinehashcrack.com)
* [https://gpuhash.me/](https://gpuhash.me/)
* [https://hashes.org/search.php](https://hashes.org/search.php)
* [https://www.cmd5.org/](https://www.cmd5.org/)
* [https://hashkiller.co.uk/Cracker/MD5](https://hashkiller.co.uk/Cracker/MD5)
* [https://www.md5online.org/md5-decrypt.html](https://www.md5online.org/md5-decrypt.html)
## Encoders
Most of encoded data can be decoded with these 2 ressources:
* [https://www.dcode.fr/tools-list](https://www.dcode.fr/tools-list)
* [https://gchq.github.io/CyberChef/](https://gchq.github.io/CyberChef/)
### Substitution Autosolvers
* [https://www.boxentriq.com/code-breaking/cryptogram](https://www.boxentriq.com/code-breaking/cryptogram)
* [https://quipqiup.com/](https://quipqiup.com/) - Very good !
#### Caesar - ROTx Autosolvers
* [https://www.nayuki.io/page/automatic-caesar-cipher-breaker-javascript](https://www.nayuki.io/page/automatic-caesar-cipher-breaker-javascript)
#### Atbash Cipher
* [http://rumkin.com/tools/cipher/atbash.php](http://rumkin.com/tools/cipher/atbash.php)
### Similar to BASE64
Check all bases with: [https://github.com/mufeedvh/basecrack](https://github.com/mufeedvh/basecrack)
* **Base32** \[_A-Z2-7=_\]
* `NBXWYYLDMFZGCY3PNRQQ====`
* **Base58** \[_123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz_\]
* `2yJiRg5BF9gmsU6AC`
* **Base62** \[_0-9A-Za-z_\]
* `g2AextRZpBKRBzQ9`
* **Base64** \[_A-Za-z0-9+/=_\]
* `aG9sYWNhcmFjb2xh`
* **Base85 --> Like Ascii85**
* **ATOM-128** \[_/128GhIoPQROSTeUbADfgHijKLM+n0pFWXY456xyzB7=39VaqrstJklmNuZvwcdEC_\]
* `MIc3KiXa+Ihz+lrXMIc3KbCC`
* **HAZZ15** \[_HNO4klm6ij9n+J2hyf0gzA8uvwDEq3X1Q7ZKeFrWcVTts/MRGYbdxSo=ILaUpPBC5_\]
* `DmPsv8J7qrlKEoY7`
* **MEGAN35** \[_3GHIJKLMNOPQRSTUb=cdefghijklmnopWXYZ/12+406789VaqrstuvwxyzABCDEF5_\]
* `kLD8iwKsigSalLJ5`
* **ZONG22** \[_ZKj9n+yf0wDVX1s/5YbdxSo=ILaUpPBCHg8uvNO4klm6iJGhQ7eFrWczAMEq3RTt2_\]
* `ayRiIo1gpO+uUc7g`
* **ESAB46** \[\]
* `3sHcL2NR8WrT7mhR`
* **MEGAN45** \[\]
* `kLD8igSXm2KZlwrX`
* **TIGO3FX** \[\]
* `7AP9mIzdmltYmIP9mWXX`
* **TRIPO5** \[\]
* `UE9vSbnBW6psVzxB`
* **FERON74** \[\]
* `PbGkNudxCzaKBm0x`
* **GILA7** \[\]
* `D+nkv8C1qIKMErY1`
* **Citrix CTX1** \[\]
* `MNGIKCAHMOGLKPAKMMGJKNAINPHKLOBLNNHILCBHNOHLLPBK`
[http://k4.cba.pl/dw/crypo/tools/eng\_atom128c.html](http://k4.cba.pl/dw/crypo/tools/eng_atom128c.html) - 404 Dead: [https://web.archive.org/web/20190228181208/http://k4.cba.pl/dw/crypo/tools/eng\_hackerize.html](https://web.archive.org/web/20190228181208/http://k4.cba.pl/dw/crypo/tools/eng_hackerize.html)
### HackerizeXS \[_╫Λ↻├☰┏_\]
```text
╫☐↑Λ↻Λ┏Λ↻☐↑Λ
```
* [http://k4.cba.pl/dw/crypo/tools/eng\_hackerize.html](http://k4.cba.pl/dw/crypo/tools/eng_hackerize.html) - 404 Dead: [https://web.archive.org/web/20190228181208/http://k4.cba.pl/dw/crypo/tools/eng\_hackerize.html](https://web.archive.org/web/20190228181208/http://k4.cba.pl/dw/crypo/tools/eng_hackerize.html)
### Morse
```text
.... --- .-.. -.-. .- .-. .- -.-. --- .-.. .-
```
* [http://k4.cba.pl/dw/crypo/tools/eng\_morse-encode.html](http://k4.cba.pl/dw/crypo/tools/eng_morse-encode.html) - 404 Dead: [https://gchq.github.io/CyberChef/](https://gchq.github.io/CyberChef/)
### UUencoder
```text
begin 644 webutils_pl
M2$],04A/3$%(3TQ!2$],04A/3$%(3TQ!2$],04A/3$%(3TQ!2$],04A/3$%(
M3TQ!2$],04A/3$%(3TQ!2$],04A/3$%(3TQ!2$],04A/3$%(3TQ!2$],04A/
F3$%(3TQ!2$],04A/3$%(3TQ!2$],04A/3$%(3TQ!2$],04A/3$$`
`
end
```
* [http://www.webutils.pl/index.php?idx=uu](http://www.webutils.pl/index.php?idx=uu)
### XXEncoder
```text
begin 644 webutils_pl
hG2xAEIVDH236Hol-G2xAEIVDH236Hol-G2xAEIVDH236Hol-G2xAEIVDH236
5Hol-G2xAEE++
end
```
* [www.webutils.pl/index.php?idx=xx](https://github.com/carlospolop/hacktricks/tree/bf578e4c5a955b4f6cdbe67eb4a543e16a3f848d/crypto/www.webutils.pl/index.php?idx=xx)
### YEncoder
```text
=ybegin line=128 size=28 name=webutils_pl
ryvkryvkryvkryvkryvkryvkryvk
=yend size=28 crc32=35834c86
```
* [http://www.webutils.pl/index.php?idx=yenc](http://www.webutils.pl/index.php?idx=yenc)
### BinHex
```text
(This file must be converted with BinHex 4.0)
:#hGPBR9dD@acAh"X!$mr2cmr2cmr!!!!!!!8!!!!!-ka5%p-38K26%&)6da"5%p
-38K26%'d9J!!:
```
* [http://www.webutils.pl/index.php?idx=binhex](http://www.webutils.pl/index.php?idx=binhex)
### ASCII85
```text
<~85DoF85DoF85DoF85DoF85DoF85DoF~>
```
* [http://www.webutils.pl/index.php?idx=ascii85](http://www.webutils.pl/index.php?idx=ascii85)
### Dvorak keyboard
```text
drnajapajrna
```
* [https://www.geocachingtoolbox.com/index.php?lang=en&page=dvorakKeyboard](https://www.geocachingtoolbox.com/index.php?lang=en&page=dvorakKeyboard)
### A1Z26
Letters to their numerical value
```text
8 15 12 1 3 1 18 1 3 15 12 1
```
### Affine Cipher Encode
Letter to num `(ax+b)%26` \(_a_ and _b_ are the keys and _x_ is the letter\) and the result back to letter
```text
krodfdudfrod
```
### SMS Code
**Multitap** [replaces a letter](https://www.dcode.fr/word-letter-change) by repeated digits defined by the corresponding key code on a mobile [phone keypad](https://www.dcode.fr/phone-keypad-cipher) \(This mode is used when writing SMS\).
For example: 2=A, 22=B, 222=C, 3=D...
You can identify this code because you will see **several numbers repeated**.
You can decode this code in: [https://www.dcode.fr/multitap-abc-cipher](https://www.dcode.fr/multitap-abc-cipher)
### Bacon Code
Substitude each letter for 4 As or Bs \(or 1s and 0s\)
```text
00111 01101 01010 00000 00010 00000 10000 00000 00010 01101 01010 00000
AABBB ABBAB ABABA AAAAA AAABA AAAAA BAAAA AAAAA AAABA ABBAB ABABA AAAAA
```
### Runes
![](../.gitbook/assets/runes.jpg)
## Compression
**Raw Deflate** and **Raw Inflate** \(you can find both in Cyberchef\) can compress and decompress data without headers.
## Easy Crypto
### XOR - Autosolver
* [https://wiremask.eu/tools/xor-cracker/](https://wiremask.eu/tools/xor-cracker/)
### Bifid
A keywork is needed
```text
fgaargaamnlunesuneoa
```
### Vigenere
A keywork is needed
```text
wodsyoidrods
```
* [https://www.guballa.de/vigenere-solver](https://www.guballa.de/vigenere-solver)
* [https://www.dcode.fr/vigenere-cipher](https://www.dcode.fr/vigenere-cipher)
* [https://www.mygeocachingprofile.com/codebreaker.vigenerecipher.aspx](https://www.mygeocachingprofile.com/codebreaker.vigenerecipher.aspx)
## Strong Crypto
### Fernet
2 base64 strings \(token and key\)
```text
Token:
gAAAAABWC9P7-9RsxTz_dwxh9-O2VUB7Ih8UCQL1_Zk4suxnkCvb26Ie4i8HSUJ4caHZuiNtjLl3qfmCv_fS3_VpjL7HxCz7_Q==
Key:
-s6eI5hyNh8liH7Gq0urPC-vzPgNnxauKvRO4g03oYI=
```
* [https://asecuritysite.com/encryption/ferdecode](https://asecuritysite.com/encryption/ferdecode)
### Samir Secret Sharing
A secret is splitted in X parts and to recover it you need Y parts \(_Y &lt;=X_\).
```text
8019f8fa5879aa3e07858d08308dc1a8b45
80223035713295bddf0b0bd1b10a5340b89
803bc8cf294b3f83d88e86d9818792e80cd
```
[http://christian.gen.co/secrets/](http://christian.gen.co/secrets/)
### OpenSSL brute-force
* [https://github.com/glv2/bruteforce-salted-openssl](https://github.com/glv2/bruteforce-salted-openssl)
* [https://github.com/carlospolop/easy\_BFopensslCTF](https://github.com/carlospolop/easy_BFopensslCTF)
## Tools
* [https://github.com/Ganapati/RsaCtfTool](https://github.com/Ganapati/RsaCtfTool)
* [https://github.com/lockedbyte/cryptovenom](https://github.com/lockedbyte/cryptovenom)
* [https://github.com/nccgroup/featherduster](https://github.com/nccgroup/featherduster)

View File

@ -0,0 +1,226 @@
---
description: 'https://pentesterlab.com/'
---
# Electronic Code Book \(ECB\)
**Post from:** [**https://pentesterlab.com/**](https://pentesterlab.com/)\*\*\*\*
## ECB
ECB is an encryption mode in which the message is splitted into blocks of X bytes length and each block is encrypted separetely using a key.
The following schema \(source: [Wikipedia](http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation)\) explains this method:
![License](https://assets.pentesterlab.com/ecb/ECB_encryption.png)
You can check the [recent XKCD on the Adobe's password leak](http://xkcd.com/1286/) to get an humoristic idea of the problems tied to ECB.
During the decryption, the reverse operation is used. Using ECB has multiple security implications:
* Blocks from encrypted message can be removed without disturbing the decryption process.
* Blocks from encrypted message can be moved around without disturbing the decryption process.
In this exercise, we will see how we can exploit these two weaknesses.
## Detection of the vulnerability
In this exercise, you can register an account and log in with this account \(to make things easier, you get automatically logged in when you register\).
If you create an account and log in two times with this account, you can see that the cookie sent by the application didn't change.If you log in many times and always get the same cookie, there is probably something wrong in the application. The cookie sent back should be unique each time you log in. If the cookie is always the same, it will probably always be valid and there won't be anyway to invalidate it.
If we look at the cookie, we can see that it seems uri-encoded and base64-encoded:
![License](https://assets.pentesterlab.com/ecb/cookie.png)
The 2 equals sign encoded as `%3d%3d` are a good indicator of base64-encoded string.
We can decode it using the following ruby code:
```text
% irb
> require 'base64' ; require 'uri'
=> true
> Base64.decode64(URI.decode("OR9hcp18%2BC1bChK10NlRRg%3d%3d"))
=> "9\x1Far\x9D|\xF8-[\n\x12\xB5\xD0\xD9QF"
```
Or by decoding the URI to a string manually and use the base64 command:
```text
% echo "OR9hcp18+C1bChK10NlRRg==" | base64 -D | hexdump -C
0000000 39 1f 61 72 9d 7c f8 2d 5b 0a 12 b5 d0 d9 51 46 |9.ar.|.-[.....QF|
0000010
```
On osX, the command `base64 -D` replaces `base64 -d`
In both cases, we can see that the information seems to be encrypted.
First, we can start by creating two accounts `test1` and `test2` with the same password: `password` and compare the cookies sent by the application. We get the following cookies \(after URI-decoding\):
| Account: | test1 | test2 |
| :--- | :--- | :--- |
| Cookie: | vHMQ+Nq9C3MHT8ZkGeMr4w== | Mh+JMH1OMhcHT8ZkGeMr4w== |
If we base64-decode both cookies, we get the following strings:
| Account: | test1 | test2 |
| :--- | :--- | :--- |
| Decoded cookie: | \xBCs\x10\xF8\xDA\xBD\vs**\aO\xC6d\x19\xE3+\xE3** | 2\x1F\x890}N2\x17**\aO\xC6d\x19\xE3+\xE3** |
We can see that part of the decrypted values look really similar.
Now we can try to create a user with an arbitrary long username and password. For example, a username composed of 20 `a` and a password composed of 20 `a`. By creating this user, we get the following cookie:
```text
> document.cookie
"auth=GkzSM2vKHdcaTNIza8od1wS28inRHiC2GkzSM2vKHdcaTNIza8od1ys96EXmirn5"
```
If we decode this value, we get the following value:
```text
\x1AL\xD23k\xCA\x1D\xD7\x1AL\xD23k\xCA\x1D\xD7\x04\xB6\xF2)\xD1\x1E \xB6\x1AL\xD23k\xCA\x1D\xD7\x1AL\xD23k\xCA\x1D\xD7+=\xE8E\xE6\x8A\xB9\xF9
```
We can see that the following pattern \(composed of 8 bytes\): **`\x1AL\xD23k\xCA\x1D\xD7`** comes back multiple times:
```text
\x1AL\xD23k\xCA\x1D\xD7\x1AL\xD23k\xCA\x1D\xD7\x04\xB6\xF2)\xD1\x1E \xB6\x1AL\xD23k\xCA\x1D\xD7\x1AL\xD23k\xCA\x1D\xD7+=\xE8E\xE6\x8A\xB9\xF9
```
Based on the size of the pattern, we can infer that the ECB encryption uses a block size of 8 bytes.This example is using a weak encryption mechanism and it's likely that real life examples will use bigger block size.
The decoded information also shows us that the username and password are not directly concatenated and that a delimiter is added \(since one of the block in the middle is different from the previous one\).
We can think of the encrypted stream has one of the two following possibilities:
* The stream contains the username, a delimiter and the password:
![Schema username password](https://assets.pentesterlab.com/ecb/del_u_p.png)
* The stream contains the password, a delimiter and the username:
![Schema password username](https://assets.pentesterlab.com/ecb/del_p_u.png)
By creating another user with a long username and a short password, we can see that the following pattern is used: `username|delimiter|password`.
Now let's try to find the size of the delimiter, if we play with different size of username and password we get the following results:
| Username length: | Password length: | Username+Password length: | Cookie's length \(after decoding\): |
| :--- | :--- | :--- | :--- |
| 2 | 3 | 5 | 8 |
| 3 | 3 | 6 | 8 |
| 3 | 4 | 7 | 8 |
| 4 | 4 | 8 | 16 |
| 4 | 5 | 9 | 16 |
We can see that the size of the decoded cookie goes from 8 to 16 bytes when the length of the Username+Password is greater than 7. We can infer from this value that the delimiter is a single byte since the encryption is done per block of 8 bytes.
Another important thing is to see what part of the encrypted stream is used by the application when we send the cookie back. If we remove everything after the block corresponding to the delimiter, we can see that we are still authenticated. The password does not seem to be used when the cookie gets used by the application.
We now know that we just need to get the correct `username|delimiter` to get authenticated within the application as `username`.If you can find what delimiter is used \(or brute force it\), you can try to create a user with a username that contains the delimiter \(for example the username "`admin:`"\). Using this method, you may be able to get logged in as `admin`. This web application prevents this type of attack.
## Exploitation of the vulnerability
### By removing information
The easiest way to get `admin` access is to remove some of the encrypted data. We know that the application uses the following format:
```text
\[username\]:\[separator\]
```
and only uses the `username` when the cookie is sent back to the application. We also know that each block of 8 bytes is completely independant \(ECB\). To exploit this issue, we can create a username that contains 8 characters followed by the word `admin`:
```text
aaaaaaaaadmin
```
And we will receive the cookie \(retrieved using the Javascript Console\):
```text
> document.cookie
"auth=GkzSM2vKHdfgVmQuKXLregdPxmQZ4yvj"
```
This value will get decoded as:
```text
\x1AL\xD23k\xCA\x1D\xD7\xE0Vd.)r\xEBz\aO\xC6d\x19\xE3+\xE3
```
We can see the pattern `\x1AL\xD23k\xCA\x1D\xD7` detected previously with the username that contained 20 `a`.
We can then remove the first 8 bytes of information and reencode our payload to get a new cookie:
```text
\xE0Vd.)r\xEBz\aO\xC6d\x19\xE3+\xE3
```
That will get encoded by the following ruby code:
```text
% irb
> require 'cgi'; require 'base64'
=> true
> CGI.escape(Base64.strict_encode64("\xE0Vd.)r\xEBz\aO\xC6d\x19\xE3+\xE3"))
=> "4FZkLily63oHT8ZkGeMr4w%3D%3D"
```
Once you modify the cookie:
![Cookie tampering with JS console](https://assets.pentesterlab.com/ecb/cookiemod.png)
And send this value back to the application \(by reloading the page\), you get logged in as `admin`:
![License](https://assets.pentesterlab.com/ecb/admin.png)
### By swapping blocks around
A more complicated way to bypass this is to swap data around. We can make the assumption that the application will use an SQL query to retrieve information from the user based on his `username`. For some databases, when using the type of data `VARCHAR` \(as opposed to `BINARY` for example\), the following will give the same result:
```text
SELECT * FROM users WHERE username='admin';
```
```text
SELECT * FROM users WHERE username='admin ';
```
The spaces after the value `admin` are ignored during the string comparison. We will use this to play with the encrypted blocks.
Our goal is to end up with the following encrypted data:
```text
ECB(admin [separator]password)
```
We know that our separator is only composed of one byte. We can use this information to create the perfect `username` and `password`to be able to swap the blocks and get the correct forged value.
We need to find a username and a password for which:
* the password starts with `admin` to be used as the new username.
* the encrypted password should be located at the start of a new block.
* the `username+delimiter` length should be divisible by the block size \(from previous conditions\)
By playing around, we can see that the following values work:
* a `username` composed of `password` \(8 bytes\) followed by 7 spaces \(1 byte will be used by the delimiter\).
* a `password` composed of `admin` followed by 3 spaces \(`8 - length("admin")`\).
When creating this user, use a proxy to intercept the request and make sure your browser didn't remove the space characters.
If you create correctly this user, the encrypted information will look like:![License](https://assets.pentesterlab.com/ecb/swap-b.png)
Using some Ruby \(or even with Burp decoder\), you can swap the first 8 bytes with the last 8 bytes to get the following encrypted stream:![License](https://assets.pentesterlab.com/ecb/swap-a.png)
Once you modify your cookie, and you reload the page, you should be logged in as `admin`:
![License](https://assets.pentesterlab.com/ecb/admin.png)
## Conclusion
This exercise showed you how you can tamper encrypted information without decrypting them and use this behaviour to gain access to other accounts. It showed you that encryption can not be used as a replacement to signature and how it's possible to use ECB encryption to get control on the decrypted information. I hope you enjoyed learning with PentesterLab.

View File

@ -0,0 +1,35 @@
# Hash Length Extension Attack
## Summary of the attack
Imagine a server which is **signing** some **data** by **appending** a **secret** to some known clear text data and then hashing that data. If you know:
* **The length of the secret** \(this can be also bruteforced from a given length range\)
* **The clear text data**
* **The algorithm \(and it's vulnerable to this attack\)**
* **The padding is known**
* Usually a default one is used, so if the other 3 requirements are met, this also is
* The padding vary depending on the length of the secret+data, that's why the length of the secret is needed
Then, it's possible for an **attacker** to **append** **data** and **generate** a valid **signature** for the **previos data + appended data**.
### How?
Basically the vulnerable algorithms generate the hashes by firstly **hashing a block of data**, and then, **from** the **previously** created **hash** \(state\), they **add the next block of data** and **hash it**.
Then, imagine that the secret is "secret" and the data is "data", the MD5 of "secretdata" is 6036708eba0d11f6ef52ad44e8b74d5b.
If an attacker wants to append the string "append" he can:
* Generate a MD5 of 64 "A"s
* Change the state of the previously initialized hash to 6036708eba0d11f6ef52ad44e8b74d5b
* Append the string "append"
* Finish the hash and the resulting hash will be a **valid one for "secret" + "data" + "padding" + "append"**
### **Tool**
{% embed url="https://github.com/iagox86/hash\_extender" %}
## References
You can find this attack good explained in [https://blog.skullsecurity.org/2012/everything-you-need-to-know-about-hash-length-extension-attacks](https://blog.skullsecurity.org/2012/everything-you-need-to-know-about-hash-length-extension-attacks)

View File

@ -0,0 +1,125 @@
---
description: 'https://pentesterlab.com/'
---
# Padding Oracle
**Post from** [**https://pentesterlab.com/**](https://pentesterlab.com/)\*\*\*\*
## Cipher Block Chaining
CBC is an encryption mode in which the message is split into blocks of X bytes length and each block is XORed with the previous encrypted block. The result is then encrypted.
The following schema \(source: [Wikipedia](http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation)\) explains this method:
![CBC encryption](https://assets.pentesterlab.com/padding_oracle/CBC_encryption.png)
During the decryption, the reverse operation is used. The encrypted data is split in block of X bytes. Then the block is decrypted and XORed with the previous encrypted block to get the cleartext. The following schema \(source: [Wikipedia](http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation)\) highlights this behavior:
![CBC decryption](https://assets.pentesterlab.com/padding_oracle/CBC_decryption.png)
Since the first block does not have a previous block, an initialization vector \(IV\) is used.
## Padding
As we saw, the encryption is done by blocks of fixed size. To ensure that the cleartext exactly fit in one or multiple blocks, padding is often used. Padding can be done in multiple ways. A common way is to use PKCS7. With PKCS7, the padding will be composed of the same number: the number of bytes missing. For example, if the cleartext is missing 2 bytes, the padding will be `\x02\x02`.
Let's look at more examples with a 2 blocks:
| Block \#0 | Block \#1 | | | | | | | | | | | | | | |
| :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- |
| byte \#0 | byte \#1 | byte \#2 | byte \#3 | byte \#4 | byte \#5 | byte \#6 | byte \#7 | byte \#0 | byte \#1 | byte \#2 | byte \#3 | byte \#4 | byte \#5 | byte \#6 | byte \#7 |
| 'S' | 'U' | 'P' | 'E' | 'R' | 'S' | 'E' | 'C' | 'R' | 'E' | 'T' | '1' | '2' | '3' | **0x02** | **0x02** |
| 'S' | 'U' | 'P' | 'E' | 'R' | 'S' | 'E' | 'C' | 'R' | 'E' | 'T' | '1' | '2' | **0x03** | **0x03** | **0x03** |
| 'S' | 'U' | 'P' | 'E' | 'R' | 'S' | 'E' | 'C' | 'R' | 'E' | 'T' | **0x05** | **0x05** | **0x05** | **0x05** | **0x05** |
| 'S' | 'U' | 'P' | 'E' | 'R' | 'S' | 'E' | 'C' | **0x08** | **0x08** | **0x08** | **0x08** | **0x08** | **0x08** | **0x08** | **0x08** |
## Padding Oracle
When an application decrypts encrypted data, it will first decrypt the data; then it will remove the padding. During the cleanup of the padding, **if** an **invalid** **padding** triggers a detectable **behaviour**, you have a **padding oracle vulnerability**. The detectable behaviour can be an **error**, a **lack** of **results**, or a **slower response**.
If you detect this behaviour, you can **decrypt the encrypted data** and even **encrypt any cleartext**.
### How to exploit
You could use [https://github.com/AonCyberLabs/PadBuster](https://github.com/AonCyberLabs/PadBuster) to exploit this kind of vulnerability or just do
```text
sudo apt-get install padbuster
```
In order to test if the cookie of a site is vulnerable you could try:
```bash
perl ./padBuster.pl http://10.10.181.45/index.php "Nl0OpaQYeGPMJeWSih2iiQ==" 8 -encoding 0 -cookies "auth=Nl0OpaQYeGPMJeWSih2iiQ=="
```
**Encoding 0** means that **base64** is used \(but others are available, check the help menu\).
You could also **abuse** this **vulnerability** to **encrypt new data**. For example, imagine that the content of the cookie is "_user=MyUsername_", then you may change it to "_**user=administrator**_" and escalate privileges inside the application. You could also do it using `paduster`specifying the **-plaintext** parameter:
```bash
perl ./padBuster.pl http://10.10.181.45/index.php "Nl0OpaQYeGPMJeWSih2iiQ==" 8 -encoding 0 -cookies "auth=Nl0OpaQYeGPMJeWSih2iiQ==" -plaintext "user=administrator"
```
If the site is vulnerable `padbuster`will automatically try to find when the padding error occurs, but you can also indicating the error message it using the **-error** parameter.
```bash
perl ./padBuster.pl http://10.10.181.45/index.php "Nl0OpaQYeGPMJeWSih2iiQ==" 8 -encoding 0 -cookies "hcon=Nl0OpaQYeGPMJeWSih2iiQ==" -error "Invalid padding"
```
### The theory
In **summary**, you can start decrypting the encrypted data by **guessing** the correct **values** that can be used to **create** all the **different paddings**. Then, the padding oracle attack will start **decrypting** bytes **from** the **end** to the start by **guessing** which will be the correct **value** that **creates a padding of 1, 2, 3, etc**.
If we zoom in, we can see that the cleartext byte `C15` is just a XOR between the encrypted byte `E7` from the previous block, and byte `I15` which came out of the block decryption step:
![CBC zoom in](https://assets.pentesterlab.com/padding_oracle/zoomin.png)
This is also valid for all other bytes:
* `C14 = I14 ^ E6`
* `C13 = I13 ^ E5`
* `C12 = I12 ^ E4`
* ...
Now if we modify `E7` and keep changing its value, we will keep getting an invalid padding. Since we need `C15` to be `\x01`. However, there is one value of `E7` that will give us a valid padding. Let's call it `E'7`. With `E'7`, we get a valid padding. And since we know we get a valid padding we know that `C'15` \(as in `C15` for `E'7`\) is `\x01`.
`\x01 = I15 ^ E'7`
The gives us:
`I15 = \x01 ^ E'7`
So we are able to compute `I15`.
Since we know `I15`, we can now compute `C15`
`C15 = E7 ^ I15 = E7 ^ \x01 ^ E'7`
Now that we have `C15`, we can move to brute-forcing `C14`. First we need to compute another `E7` \(let's call it `E''7`\) that gives us `C15 = \x02`. We need to do that since we want the padding to be `\x02\x02` now. It's really simple to compute using the property above and by replacing the value of `C15` we want \(`\x02`\) and `I15` we now know:
`E''7 = \x02 ^ I15`
After brute force `E6`, to find the value that gives us a valid padding `E''6`, we can re-use the formula:
`C14 = I14 ^ E6`
to get
`I14 = \x02 ^ E''6`
Once we get `I14`, we can compute `C14`:
`C14 = E6 ^ I14 = E6 ^ \x02 ^ E''6`
Using this method, we can keep going until we get all the ciphertext decrypted.
### Detection of the vulnerability
To get started, you can register an account and log in with this account \(to make things easier, you get automatically logged in when you register\).
If you create an account and log in two times with this account, you can see that the cookie sent by the application didn't change.If you log in many times and always get the same cookie, there is probably something wrong in the application. The cookie sent back should be unique each time you log in. If the cookie is always the same, it will probably always be valid and there won't be anyway to invalidate it.
Now, if you try to modify the cookie, you can see that you get an error from the application.

View File

@ -0,0 +1,14 @@
# RC4 - Encrypt&Decrypt
If you can somehow encrypt a plaintext using a RC4**,** you can decrypt any content encrypted by that RC4\(using the same password\) just using the encryption function.
If you can encrypt a known plaintext you can also extract the password. More references can be found in the HTB Kryptos machine:
{% embed url="https://0xrick.github.io/hack-the-box/kryptos/" %}
{% embed url="https://0xrick.github.io/hack-the-box/kryptos/" %}
\*\*\*\*

View File

@ -20,7 +20,7 @@ And if you change some **byte** of the **cookie** you get this error:
![](../../.gitbook/assets/image%20%28109%29.png)
With this information and[ **reading the padding oracle vulnerability**](../../crypto/padding-oracle-priv.md) I was able to exploit it:
With this information and[ **reading the padding oracle vulnerability**](../../cryptography/padding-oracle-priv.md) I was able to exploit it:
```bash
perl ./padBuster.pl http://10.10.231.5/index.php "GVrfxWD0mmxRM0RPLht/oUpybgnBn/Oy" 8 -encoding 0 -cookies "hcon=GVrfxWD0mmxRM0RPLht/oUpybgnBn/Oy"

View File

@ -138,9 +138,9 @@ Check also the page about [**NTLM**](windows/ntlm/), it could be very useful to
### **Crypto tricks**
* [**ECB**](crypto/electronic-code-book-ecb.md)
* [**CBC-MAC**](crypto/cipher-block-chaining-cbc-mac-priv.md)
* [**Padding Oracle**](crypto/padding-oracle-priv.md)
* [**ECB**](cryptography/electronic-code-book-ecb.md)
* [**CBC-MAC**](cryptography/cipher-block-chaining-cbc-mac-priv.md)
* [**Padding Oracle**](cryptography/padding-oracle-priv.md)
![](.gitbook/assets/68747470733a2f2f7777772e6275796d6561636f666665652e636f6d2f6173736574732f696d672f637573746f6d5f696d616765732f6f72616e67655f696d672e706e67%20%286%29%20%284%29%20%281%29.png)