{
  "version": "https://jsonfeed.org/version/1.1",
  "title": "Aditya Bankoti",
  "home_page_url": "https://bankoti.dev/blog/",
  "feed_url": "https://bankoti.dev/feed.json",
  "authors": [
    {
      "name": "Aditya Bankoti",
      "url": "https://bankoti.dev"
    }
  ],
  "items": [
    {
      "id": "https://bankoti.dev/blog/posts/2026-05-21-buffer-overflows/",
      "url": "https://bankoti.dev/blog/posts/2026-05-21-buffer-overflows/",
      "title": "Morris Worm Incident",
      "summary": "Six lines of C you break by typing one character too many, and the 1988 worm that got in the same way.",
      "content_text": "# Morris Worm Incident\n\n2026-05-21 · 5 min · Systems, C, Memory\n\nhttps://bankoti.dev/blog/posts/2026-05-21-buffer-overflows/\n\n<img class=\"photo\" src=\"https://bankoti.dev/blog/posts/2026-05-21-buffer-overflows/morris-worm.jpg\" width=\"450\" height=\"600\" alt=\"A floppy disk in a clear display case at the Computer History Museum, under a placard reading The Morris Internet Worm source code.\" />\n<p class=\"credit\">Photo by Go Card USA, <a href=\"https://creativecommons.org/licenses/by-sa/2.0\" rel=\"license noopener noreferrer\" target=\"_blank\">CC BY-SA 2.0</a>, via <a href=\"https://commons.wikimedia.org/w/index.php?curid=3959700\" rel=\"noopener noreferrer\" target=\"_blank\">Wikimedia Commons</a></p>\n\n## The Disk\n\nThat floppy holds the source of the Morris worm. On November 2, 1988 the program on it spread across the early internet and jammed roughly 6,000 of the 60,000 machines connected at the time. Its author got the first conviction under the Computer Fraud and Abuse Act.\n\nOne of the ways it got in was a buffer overflow, and the version of that bug I actually learned came out of CS 354 at Wisconsin, in a program short enough to read in one sitting. Nothing here is a live security issue, since every compiler in the last twenty years stops it by default. It is just a good way to see what a stack frame is.\n\n## The Program\n\n<p class=\"code-label\">vuln.c</p>\n\n```c\n#include <stdio.h>\n\nint main(void) {\n    int  authorized = 0;   // the guard: 0 means \"no\"\n    char name[8];          // room for 8 characters\n\n    printf(\"What is your name?\\n\");\n    scanf(\"%s\", name);     // reads a word, with no length limit\n\n    if (authorized)\n        printf(\"Access granted.\\n\");\n    else\n        printf(\"Hello, %s. Access denied.\\n\", name);\n    return 0;\n}\n```\n\nNothing sets `authorized` to anything but `0`, so reading the source tells you no input can reach \"Access granted\". Typing nine characters gets you there anyway.\n\n## Where the Variables Live\n\nA function's locals go in one block of memory called the stack frame. Compile to 32-bit assembly and the offsets are printed for you:\n\n<p class=\"code-label\">x86 assembly (Intel syntax)</p>\n\n```asm\nmov   dword ptr [ebp-8], 0    ; authorized = 0\nlea   eax, [ebp-16]           ; &name[0]\ncall  scanf\ncmp   dword ptr [ebp-8], 0    ; if (authorized)\n```\n\n`name` starts at `ebp-16` and `authorized` sits at `ebp-8`, eight bytes further up. Number the bytes from `name[0]` and the frame reads `name` at `0x00` through `0x07`, `authorized` at `0x08` through `0x0B`, and the return address `main` jumps to at `0x0C`.\n\n`scanf` writes `name` starting at `name[0]` and works *upward*, toward `authorized` and then toward the return address. `%s` carries no length, so nothing stops it at eight.\n\n## Nine Characters\n\n<pre class=\"term\"><span class=\"t-p\">$</span> <span class=\"t-cmd\">cc -fno-stack-protector -O0 vuln.c -o vuln</span>\n\n<span class=\"t-p\">$</span> <span class=\"t-cmd\">./vuln</span>\nWhat is your name?\n<span class=\"t-in\">adi</span>\nHello, adi. <span class=\"t-bad\">Access denied.</span>\n\n<span class=\"t-p\">$</span> <span class=\"t-cmd\">./vuln</span>\nWhat is your name?\n<span class=\"t-in\">AAAAAAAA</span>\nHello, AAAAAAAA. <span class=\"t-bad\">Access denied.</span>\n\n<span class=\"t-p\">$</span> <span class=\"t-cmd\">./vuln</span>\nWhat is your name?\n<span class=\"t-in\">AAAAAAAAA</span>\n<span class=\"t-ok\">Access granted.</span>  <span class=\"t-dim\">authorized == 0x00000041</span></pre>\n\nEight A's are already an overflow. `scanf` writes the NUL terminator after the word, so `AAAAAAAA` puts eight `0x41` bytes in `name` and a ninth byte, `0x00`, into `authorized[0]`. Writing zero over a zero changes nothing, which is why eight is still denied.\n\nThe ninth `A` is the first byte that lands on `authorized` with something in it. `authorized` becomes `0x00000041`, decimal 65, and `if (authorized)` is true for anything that is not zero.\n\n<div class=\"stack-viz\"></div>\n\nThe buffer's size and the type of `authorized` are both live. Shrink `name` and the guard moves closer; make `authorized` a `char` and one byte is the whole guard. `flip` puts `0x00` at the bottom, if you would rather read the frame the way it is usually drawn.\n\n## Past the Guard\n\nKeep typing and you run out of `authorized`. Above it, at `0x0C`, is the return address, the value `main` pops into the instruction pointer when it returns. Flipping the guard gets you past an `if`. Overwriting the return address picks what runs next, and if your input is also sitting in memory somewhere you can address, it picks your bytes.\n\nThat is the version the worm used. BSD's `fingerd` read a request line with `gets`, which has no length argument at all, into a 512-byte buffer on the stack.\n\n## Try It Yourself\n\n[Godbolt](https://godbolt.org/) gives you the assembly. Paste `vuln.c`, pick x86-64 gcc, and set the options to `-m32 -O0 -fno-stack-protector -no-pie`. The `mov [ebp-8], 0` and the `lea` for `name` are where the number nine comes from, read off instead of guessed.\n\nTo run it, plain 64-bit is fine:\n\n```bash\ncc -fno-stack-protector -O0 vuln.c -o vuln\necho AAAAAAAAA | ./vuln     # Access granted.\n```\n\nNow drop the flag and let the compiler do its job:\n\n```bash\ncc -O0 vuln.c -o safe\necho AAAAAAAAAAAAAAAAAAAAAAAA | ./safe\n# *** stack smashing detected ***: terminated\n```\n\n`-fstack-protector` is on by default now. It puts a known value, the canary, between the locals and the return address and checks it before returning, and it reorders the locals so arrays sit closest to the canary. That second part alone moves `authorized` below `name`, out of reach. ASLR shuffles the addresses on every run and the stack is mapped non-executable. None of it existed in 1988.\n",
      "date_published": "2026-05-21T00:00:00.000Z",
      "tags": [
        "Systems",
        "C",
        "Memory"
      ],
      "image": "https://bankoti.dev/blog/posts/2026-05-21-buffer-overflows/morris-worm.jpg"
    },
    {
      "id": "https://bankoti.dev/blog/posts/2026-04-23-eigenfaces/",
      "url": "https://bankoti.dev/blog/posts/2026-04-23-eigenfaces/",
      "title": "Ways to Decompose a Face",
      "summary": "Using Machine Learning to deconstruct and reconstruct faces",
      "content_text": "# Ways to Decompose a Face\n\n2026-04-23 · 15 min · Machine Learning, Linear Algebra\n\nhttps://bankoti.dev/blog/posts/2026-04-23-eigenfaces/\n\n<img src=\"https://bankoti.dev/blog/posts/2026-04-23-eigenfaces/re1.png\" width=\"1184\" height=\"497\" alt=\"Grid of original CelebA faces beside their reconstructions.\" />\n\n## Introduction\n\nEigenfaces are a cool application of SVD. Feed a bunch of face photos into it and you get back a set of \"average\" faces that can be mixed together to rebuild any face in the dataset. We'll build them from scratch, then look at a second approach (NNMF) that pulls out localized features like eyes and noses instead of full-face blends.\n\n## SVD\n\nSVD, or Singular Value Decomposition, is a way of breaking any matrix down into three simpler pieces that reveal its underlying structure.\n\n**But what does this mean?**\n\nLet's say we have a matrix $M \\in \\mathbb{R}^{m \\times n}$. We can write it as $M = U \\Sigma V^T$, where $U \\in \\mathbb{R}^{m\\times m}$ and $V \\in \\mathbb{R}^{n \\times n}$ are orthogonal matrices, and $\\Sigma \\in \\mathbb{R}^{m \\times n}$ is a diagonal matrix whose entries $\\sigma_1 \\geq \\dotsb \\geq \\sigma_r > 0$ are the singular values. Visually, $\\Sigma$ looks something like this, where the empty spots are just zeros:\n\n$$\n\\Sigma =\n\\begin{pmatrix}\n\\sigma_1 & & & & & \\\\\n& \\sigma_2 & & & & \\\\\n& & \\ddots & & & \\\\\n& & & \\sigma_r & & \\\\\n& & & & \\ddots & \\\\\n& & & & & 0\n\\end{pmatrix}_{m \\times n}\n$$\n\nIntuitively, each piece has its own job:\n\n1. $V^T$: rotates the data into a new coordinate system aligned with its most important directions\n2. $\\Sigma$: scales each direction by how much variance it captures\n3. $U$: expresses each original data point as a combination of those directions\n\nThe nice thing is this works for _any_ real matrix $M$. Since the singular values are sorted from big to small, the most important structure in the data lives in the first few $\\sigma_i$. Keep just the top $r$ of them and you get the best rank-$r$ approximation of $M$.\n\n## Coding\n\n### Loading the Data\n\nLet's apply this. First we'll load a dataset and reshape it into something we can feed to SVD. This is mostly boilerplate, so feel free to copy it.\n\n```python\nimport kagglehub\nimport numpy as np\nimport os\nimport cv2\nimport matplotlib.pyplot as plt\n\npath = kagglehub.dataset_download(\"jessicali9530/celeba-dataset\")\n\ndef load_images(image_directory, count=1000, img_size=(64, 64)):\n  flattened_images = []\n  processed_count = 0\n  full_image_path = os.path.join(image_directory, 'img_align_celeba')\n  for root, _, files in os.walk(full_image_path):\n    for file in files:\n      if processed_count >= count:\n        break\n      if file.endswith(('.jpg', '.png', '.jpeg')):\n        filepath = os.path.join(root, file)\n        img = cv2.imread(filepath, cv2.IMREAD_GRAYSCALE)\n        if img is not None:\n          img_resized = cv2.resize(img, img_size, interpolation=cv2.INTER_CUBIC)\n          flattened_images.append(img_resized.flatten())\n          processed_count += 1\n\n  return np.array(flattened_images)\n```\n\nThis returns a matrix where each row is one flattened grayscale image. Going flat and grayscale turns each picture into a single vector, which is what SVD wants. We stick to 64×64 so the decomposition doesn't take forever to run.\n\n### SVD\n\nThankfully NumPy gives us an SVD function, so most of the work's already handled. Before calling it, we subtract the mean face from every image. That centers the data so SVD sees what varies between faces instead of what they all share, like background brightness or average skin tone.\n\n```python\nimages = load_images(path, count=1_000)\nmean_face = images.mean(axis=0)\nX = images - mean_face\nU, s, Vt = np.linalg.svd(X, full_matrices=False)\n# U: (1000, 1000), s: (1000,), Vt: (1000, 4096)\n```\n\nEach row of $V^T$ is a vector of length 4096. We can reshape it back into a 64×64 image and plot it, which gives us some pretty fun pictures:\n\n<img src=\"https://bankoti.dev/blog/posts/2026-04-23-eigenfaces/sc1.png\" width=\"1400\" height=\"891\" alt=\"Top rows of V-transpose reshaped into 64×64 images — the ghostly eigenfaces.\" loading=\"lazy\" />\n\n**Why do some rows look like faces?** Each row of $V^T$ is a direction in image-space, and $\\sigma_i$ says how much variance the data has along it. The top rows grab the most global patterns in the dataset, and since the dataset is faces, those patterns _are_ faces. Further down the list, the singular values shrink and the rows pick up on smaller variations, then just noise.\n\n### Generating a Face\n\nWe can also run the decomposition backwards to _make_ new faces. Pick some random coefficients, weight them by the singular values, and mix the top rows of $V^T$ together. Add the mean face back on and you've got a new face pulled from the same linear space as the dataset.\n\n```python\ndef generate_random_face(Vt, s, mean_face, r=100):\n  c = np.random.randn(r) * s[:r]\n  face = mean_face + c @ Vt[:r]\n  face = np.clip(face, 0, 255)\n  return face.reshape(64, 64)\n```\n\n$r$ is the rank of the approximation. Like we saw earlier, the top rows of $V^T$ carry the global structure and the tail is mostly noise, so a small $r$ keeps the big facial features and drops the rest. Here are some that I generated:\n\n<div class=\"face-grid\">\n  <img src=\"https://bankoti.dev/blog/posts/2026-04-23-eigenfaces/sc5.png\" width=\"1000\" height=\"740\" alt=\"A face sampled from the SVD model.\" loading=\"lazy\" />\n  <img src=\"https://bankoti.dev/blog/posts/2026-04-23-eigenfaces/sc6.png\" width=\"1000\" height=\"739\" alt=\"A face sampled from the SVD model.\" loading=\"lazy\" />\n  <img src=\"https://bankoti.dev/blog/posts/2026-04-23-eigenfaces/sc4.png\" width=\"1000\" height=\"744\" alt=\"A face sampled from the SVD model.\" loading=\"lazy\" />\n  <img src=\"https://bankoti.dev/blog/posts/2026-04-23-eigenfaces/sc3.png\" width=\"1000\" height=\"740\" alt=\"A face sampled from the SVD model.\" loading=\"lazy\" />\n  <img src=\"https://bankoti.dev/blog/posts/2026-04-23-eigenfaces/sc2.png\" width=\"1000\" height=\"741\" alt=\"A face sampled from the SVD model.\" loading=\"lazy\" />\n</div>\n\n## Another way...?\n\nSVD gave us faces, but they're globally blended — every eigenface is a ghostly mix of the whole dataset. We can do better.\n\nNon-Negative Matrix Factorization (NNMF) is another way to break apart the image matrix. It factors $V \\approx W H$ with the constraint that _both_ $W$ and $H$ only have non-negative entries. That constraint is the whole point. With no subtraction allowed, the decomposition can't build a face by cancelling features against each other, so it has to find additive **parts** instead of blends. In practice, the rows of $H$ come out looking like localized facial features (eyes, noses, hairlines) rather than full-face ghosts.\n\nYou can read more about Non-Negative Matrix Factorization [here](https://en.wikipedia.org/wiki/Non-negative_matrix_factorization).\n\n```python\ndef NNMF(V, k=100, MAX_ITERATION=500):\n  eps = 1e-9\n  tol = 1e-4\n\n  m, n = V.shape\n  W = np.random.rand(m, k)\n  H = np.random.rand(k, n)\n  previous_error = np.inf\n\n  for i in range(MAX_ITERATION):\n    H_num = W.T @ V\n    H_den = W.T @ W @ H + eps\n    H *= (H_num / H_den)\n\n    W_num = V @ H.T\n    W_den = W @ H @ H.T + eps\n    W *= (W_num / W_den)\n\n    current_error = np.linalg.norm(V - W @ H, 'fro')\n    diff = abs(previous_error - current_error)\n\n    if i > 0 and diff / previous_error < tol:\n      break\n\n    previous_error = np.linalg.norm(V - W @ H, 'fro')\n  return W, H\n```\n\nEach loop applies the multiplicative update rules from the Wiki page to push $\\|V - WH\\|_F$ down. We bail out early once the error stops changing much.\n\n### Errors\n\nWe still have to pick good values for $k$ (the number of components) and MAX_ITERATION. To do that, we'll sweep over a range of $k$ values and plot the reconstruction error.\n\n```python\nerrors = {}\nerror_ranges = list(range(1, 100, 10)) \\\n                + list(range(100, 200, 25)) \\\n                + list(range(200, 400, 75))  \\\n                + list(range(400, 500, 100)) \\\n                + list(range(500, 1000, 200))\n# same as\nerror_ranges = [1, 11, 21, 31, 41, 51, 61, 71,\n                81, 91, 100, 125, 150, 175, 200,\n                275, 350, 400, 500, 700, 900]\n```\n\nThat's just the list of $k$ values we'll try. Denser at the low end where the curve changes fast, sparser at the tail. Tweak it however you want.\n\nFor each $k$ we compute the reconstruction error $\\|V - WH\\|_F$. We also track its discrete derivative $d(\\text{error})/dk$ so we can spot the elbow.\n\n```python\nerrors = {}\nerror_ranges = list(range(1, 100, 10)) \\\n                + list(range(100, 200, 25)) \\\n                + list(range(200, 400, 75))  \\\n                + list(range(400, 500, 100)) \\\n                + list(range(500, 1000, 200))\nerror_ranges = sorted(set(error_ranges))\n\nfor k in tqdm.tqdm(error_ranges):\n    W, H = NNMF(images, k, 100)\n    WH = W @ H\n    errors[k] = np.linalg.norm(images - WH, 'fro')\n\nkeys = list(errors.keys())\nvals = list(errors.values())\n\nd_errs = {\n    keys[i]: (errors[keys[i]] - errors[keys[i-1]]) / (keys[i] - keys[i-1])\n    for i in range(1, len(keys))\n}\n\nfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 5))\n\nax1.plot(keys, vals)\nax1.set_title(\"Reconstruction Error\")\nax1.set_xlabel(\"k\")\nax1.set_ylabel(\"Frobenius Norm\")\n\nax2.plot(list(d_errs.keys()), list(d_errs.values()))\nax2.set_title(\"d(Error)/dk\")\nax2.set_xlabel(\"k\")\nax2.set_ylabel(\"Error Rate of Change\")\n\nplt.tight_layout()\n```\n\n<img src=\"https://bankoti.dev/blog/posts/2026-04-23-eigenfaces/err1.png\" width=\"1091\" height=\"385\" alt=\"Reconstruction error (Frobenius norm) plotted against k.\" loading=\"lazy\" />\n<img src=\"https://bankoti.dev/blog/posts/2026-04-23-eigenfaces/err2.png\" width=\"1091\" height=\"385\" alt=\"Derivative of reconstruction error with respect to k, flattening near k = 200.\" loading=\"lazy\" />\n\nThe error curve flattens out and $d(\\text{error})/dk$ settles near zero around $k \\approx 200$, so we'll go with $k = 200$ and MAX_ITERATION $= 200$.\n\nNow let's reconstruct some faces and see how the model does.\n\n### Reconstruction!\n\nRunning this plots each original next to what the model reconstructs from $W$ and $H$.\n\n```python\nW, H = NNMF(images, 200, 200)\ndef reconstruct_face(idx):\n    # W[idx] is the coefficient vector for image idx, shape (k,)\n    # W[idx] @ H is a weighted sum of the k components\n    reconstructed = W[idx] @ H  # shape (n,) = (4096,)\n    return reconstructed.reshape(64, 64)\n\n# Plot original vs reconstructed\nfig, axes = plt.subplots(2, 5, figsize=(12, 5))\ncounter = 0\namount = 5\npictures = random.choices(list(range(0, images.shape[0])), k = amount)\nfor i in pictures:\n    original = images[i].reshape(64, 64)\n    reconstructed = reconstruct_face(i)\n\n    # Normalize for display\n    reconstructed = np.clip(reconstructed, 0, 255)\n\n    axes[0, counter].imshow(original, cmap='gray')\n    axes[0, counter].set_title(f'Original {i}')\n    axes[0, counter].axis('off')\n\n    axes[1, counter].imshow(reconstructed, cmap='gray')\n    axes[1, counter].set_title(f'Reconstructed {i}')\n    axes[1, counter].axis('off')\n    counter += 1\n\nplt.tight_layout()\n```\n\n<img src=\"https://bankoti.dev/blog/posts/2026-04-23-eigenfaces/re1.png\" width=\"1184\" height=\"497\" alt=\"Five original faces (top row) beside their NNMF reconstructions (bottom row).\" loading=\"lazy\" />\n\nWe can also use NNMF as a compression scheme. Instead of storing a full 64×64 image per face, we only need that face's coefficient vector $W_i$ (length $k$), plus one shared $H$ for the whole dataset.\n\n```python\nper_image_original = images[0].nbytes\nper_image_compressed_amortized = W[0].nbytes + H.nbytes / len(images)\nratio = per_image_compressed_amortized / per_image_original\nprint(f\"Compressed size is {ratio:.4f}x the original\")\n```\n\nWhich gives me the output:\n\n```\nCompressed size is 0.4977x the original\n```\n\nRoughly half the size. Sick!\n\nWe can also look at the features themselves to see what the model learned:\n\n```python\nfig_row_count = 3\nfig_col_count = 4\n\nfeature_importance = W.sum(axis=0)\ntop_indices = np.argsort(feature_importance)[::-1][:fig_row_count * fig_col_count]\n\n# Auto-scale figure height based on grid size\nfig, axes = plt.subplots(fig_row_count, fig_col_count, figsize=(10, 10))\n\nfor i, ax in enumerate(axes.flat):\n    component = H[top_indices[i]]\n    component = np.clip((component - component.min()) / (component.max() - component.min() + 1e-9), 0, 1)\n    component = component.reshape(64, 64)\n    axes[i // fig_col_count, i % fig_col_count].imshow(component, cmap='gray')\n    axes[i // fig_col_count, i % fig_col_count].set_title(f\"Feature {top_indices[i]}\", fontsize=16)\n    # ax.axis('off')\n\nplt.tight_layout()\nplt.show()\n```\n\n<img src=\"https://bankoti.dev/blog/posts/2026-04-23-eigenfaces/re2.png\" width=\"989\" height=\"922\" alt=\"The top learned NNMF feature components rendered as 64×64 images — localized facial parts.\" loading=\"lazy\" />\n\nAlright, last step, just for fun: let's sample some random faces from the NNMF model, same as we did with SVD. Since every coefficient in $W$ has to be non-negative, we sample from a Gaussian fit to each column of $W$ and clip any negatives back to zero.\n\n```python\ndef generate_random_face(mean, std, H):\n    coeffs = np.clip(np.random.normal(mean, std), 0, None)\n    face = coeffs @ H\n    return np.clip(face, 0, 255).reshape(64, 64)\n\nmean = W.mean(axis=0)\nstd  = W.std(axis=0)\n\nfig, axes = plt.subplots(4, 5, figsize=(12, 10))\nfor ax in axes.flat:\n    ax.imshow(generate_random_face(mean, std, H), cmap='gray')\n    ax.axis('off')\nplt.tight_layout()\n```\n\n<img src=\"https://bankoti.dev/blog/posts/2026-04-23-eigenfaces/re3.png\" width=\"1189\" height=\"975\" alt=\"A grid of faces sampled from the NNMF model, with sharper localized features.\" loading=\"lazy\" />\n\nCompared to the SVD samples, these have **way** sharper facial features. The non-negativity constraint is doing exactly what we wanted: pushing the model toward parts instead of blends.\n",
      "date_published": "2026-04-23T00:00:00.000Z",
      "tags": [
        "Machine Learning",
        "Linear Algebra"
      ],
      "image": "https://bankoti.dev/blog/posts/2026-04-23-eigenfaces/re1.png"
    }
  ]
}