<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Chien Hao Tan on Medium]]></title>
        <description><![CDATA[Stories by Chien Hao Tan on Medium]]></description>
        <link>https://medium.com/@chienhaotan?source=rss-c8144e286ba4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*M2xEVfYUb_mpby8U.</url>
            <title>Stories by Chien Hao Tan on Medium</title>
            <link>https://medium.com/@chienhaotan?source=rss-c8144e286ba4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 17:08:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chienhaotan/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Custom Binaries on AWS Lambda + Poking Around (Bonus)]]></title>
            <link>https://medium.com/@chienhaotan/custom-binaries-on-aws-lambda-poking-around-bonus-2aad6e4da3a5?source=rss-c8144e286ba4------2</link>
            <guid isPermaLink="false">https://medium.com/p/2aad6e4da3a5</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Chien Hao Tan]]></dc:creator>
            <pubDate>Wed, 27 Dec 2023 18:31:11 GMT</pubDate>
            <atom:updated>2023-12-27T18:31:11.606Z</atom:updated>
            <content:encoded><![CDATA[<p>AWS Lambda is a serverless computing platform that allows you to run code without provisioning or managing servers. It is a great way to run code without having to worry about the underlying infrastructure. It is also very cheap, and you only pay for the time your code is running.</p><p>If your workload is a simple script, you can use their inline editor to write your code. But if you want to use a custom binary, you need to package it into a zip file and upload it to AWS Lambda. This is a guide on how to do that.</p><p>In my example, I will upload a binary that I compiled from source. I will not be using the CLI and will be using the AWS Web Console instead.</p><h3>Creating the Lambda Function</h3><p>First create a Lambda function. I will be using the Amazon Linux 2 runtime. I will also be using the default execution role.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oeAFovCYGeMx5iTi.png" /></figure><p>Select Amazon Linux 2</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*s1EHq8dC365IXfH4.png" /></figure><p>We will now be uploading a bootstrap file in the next section</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ptOqTsnahSF_Lq0l.png" /></figure><p>When the function has finished creating, the Code dashboard will look like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/0*bQ4A-WoHegx803tT.png" /></figure><p>The README.md file reads</p><pre>A runtime is a program that runs a Lambda function&#39;s handler method when the function is invoked. The runtime can be included in your function&#39;s deployment package, or in a [layer](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html). [Learn more](https://docs.aws.amazon.com/lambda/latest/dg/runtimes-custom.html) about custom Lambda runtimes.</pre><pre>For reference, this function includes a sample [Bash](https://www.gnu.org/software/bash/) runtime in `bootstrap.sample` and a corresponding handler file `hello.sh.sample`. As a next step, you should provide your own bootstrap by either adding a layer implementing a custom runtime or including a `bootstrap` file in this function&#39;s deployment package.</pre><p>We may be tempted to just rename the function bootstrap.sample to bootstrap and the function hello.sh.sample to hello.sh.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/0*KPWJ2CWlIzZZYfXu.png" /></figure><p>Then create a new test event and run it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5_E03HciDLR86E4W.png" /></figure><p>We should see a successful test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/0*EezgjvLHwOAQnZ_b.png" /></figure><h3>Common Error: Creating a new file instead of renaming</h3><p>If you create a new file instead of renaming, you will see this error</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*syuzLInk1bmFkFx6.png" /></figure><h3>Common Error: Not deploying the function</h3><p>After you make changes to the files (including renaming), you need to deploy the function. Otherwise the old files will still be used. And they will say they cannot find the bootstrap file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JhlLCkIRwIp32OUh.png" /></figure><h3>Common Error: I accidentally deleted the bootstrap file</h3><p>If you accidentally deleted the old bootstrap.sh.sample file, and now you can&#39;t create one that has executable permissions, you must do the following.</p><pre><br>cat &gt; bootstrap &lt;&lt; EOF<br>#!/bin/sh<br>set -euo pipefail<br><br># Handler format: &lt;script_name&gt;.&lt;bash_function_name&gt;<br>#<br># The script file &lt;script_name&gt;.sh  must be located at the root of your<br># function&#39;s deployment package, alongside this bootstrap executable.<br>source $(dirname &quot;$0&quot;)/&quot;$(echo $_HANDLER | cut -d. -f1).sh&quot;<br><br>while true<br>do<br>    # Request the next event from the Lambda runtime<br>    HEADERS=&quot;$(mktemp)&quot;<br>    EVENT_DATA=$(curl -v -sS -LD &quot;$HEADERS&quot; -X GET &quot;http://${AWS_LAMBDA_RUNTIME_API}/2018-06-01/runtime/invocation/next&quot;)<br>    INVOCATION_ID=$(grep -Fi Lambda-Runtime-Aws-Request-Id &quot;$HEADERS&quot; | tr -d &#39;[:space:]&#39; | cut -d: -f2)<br><br>    # Execute the handler function from the script<br>    RESPONSE=$($(echo &quot;$_HANDLER&quot; | cut -d. -f2) &quot;$EVENT_DATA&quot;)<br><br>    # Send the response to Lambda runtime<br>    curl -v -sS -X POST &quot;http://${AWS_LAMBDA_RUNTIME_API}/2018-06-01/runtime/invocation/$INVOCATION_ID/response&quot; -d &quot;$RESPONSE&quot;<br>done<br>EOF<br><br>cat &gt; hello.sh &lt;&lt; EOF<br>function handler () {<br>    EVENT_DATA=$1<br><br>    RESPONSE=&quot;{\&quot;statusCode\&quot;: 200, \&quot;body\&quot;: \&quot;Hello from Lambda!\&quot;}&quot;<br>    echo $RESPONSE<br>}<br>EOF</pre><p>Change the permissions</p><pre>chmod +x bootstrap<br>chmod +x hello.sh</pre><p>Then zip it up and upload it</p><pre>zip my_bootstrap.zip bootstrap hello.sh</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*B5vVLf3bQr36K_us.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/0*smEa2Q7ugFVpOfx7.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/0*EGlzH6Jd1NarXNUO.png" /></figure><h3>Custom Binary</h3><p>Do note that whatever scripts or binaries you want to run, you need to compile it on the same OS as the Lambda runtime. In this case, it is Amazon Linux 2. So I will be using a Docker container to compile my binary.</p><h3>Docker Container</h3><p>First setup our build environment. By looking at our runtime image, we can refer to the docs to find the Dockerfile for the image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CWMcNUoF3pJErOxV.png" /></figure><p>Which we can find the image for <a href="https://docs.aws.amazon.com/lambda/latest/dg/images-create.html#runtimes-images-provided">here</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/0*29m380EwYtXqS1k8.png" /></figure><p>We go ahead and clone the repo</p><pre>git clone --branch provided.al2 --depth 1 https://github.com/aws/aws-lambda-base-images.git <br>cd aws-lambda-base-images<br># either of the following<br>sed -i &#39;s/scratch/public.ecr.aws\/lambda\/nodejs:18/g&#39; Dockerfile.provided.al2<br>sed -i &#39;s/scratch/amazonlinux:2/g&#39; Dockerfile.provided.al2<br>docker build -f Dockerfile.provided.al2 -t lambda_image:1.0.0 .</pre><p>We had to replace the FROM scratch with FROM public.ecr.aws/lambda/nodejs:18 because we want to docker exec into the container later and have a nice shell, and scratch does not have a shell. Also because it seems like we can&#39;t run /lambda-entrypoint.sh the scratch image (either this is bug in Amazon&#39;s GitHub, or Lambda loads containers differently from our local Docker runc).</p><h3>Creating our image</h3><p>Then we can run our build environment</p><pre>docker run -d -v $PWD:/tmp/meow --name lambda_image lambda_image:1.0.0<br>docker exec -it lambda_image bash</pre><h3>Writing our binary</h3><p>Install build environment in the interative shell</p><pre>yum install -y gcc-c++ vim</pre><p>Or you could bake it into the image by adding it to the Dockerfile</p><h3>Compiling our binary</h3><p>Then we can write a simple C++ program</p><pre>cat &gt; test.cpp &lt;&lt; EOF<br>#include &lt;stdio.h&gt;<br>int main(){<br>    printf(&quot;Hello, world!\n&quot;);<br>}<br>EOF</pre><p>And compile it</p><pre>g++ test.cpp -o my_binary<br>cp my_binary /tmp/meow</pre><p>Exit the container and zip it up</p><pre>chmod +x my_binary<br>zip my_binary.zip my_binary</pre><h3>Uploading our binary</h3><p>Then we can upload it to our Lambda function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/0*V_tlDezd8KGLC378.png" /></figure><p>We use hello.sh to make sure it works</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/0*usgIev-eOkxtrAL5.png" /></figure><p>The output is</p><pre>total 8<br>-rwxr-xr-x 1 root root 8176 Dec 27 18:01 my_binary<br>Hello, world!</pre><h3>Extra: Understanding AWS Lambda Runtime</h3><p>Nice that you are here at the end! Let’s have some fun and dig deep into AWS Lambda.</p><pre>docker exec -it --entrypoint bash lambda_image:1.0.0 <br>cat /lambda-entrypoint.sh</pre><p>We see that</p><pre>#!/bin/sh<br># Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.<br><br>if [ $# -ne 1 ]; then<br>  echo &quot;entrypoint requires the handler name to be the first argument&quot; 1&gt;&amp;2<br>  exit 142<br>fi<br>export _HANDLER=&quot;$1&quot;<br><br>RUNTIME_ENTRYPOINT=/var/runtime/bootstrap<br>if [ -z &quot;${AWS_LAMBDA_RUNTIME_API}&quot; ]; then<br>  exec /usr/local/bin/aws-lambda-rie $RUNTIME_ENTRYPOINT<br>else<br>  exec $RUNTIME_ENTRYPOINT<br>fi</pre><p>Curiously,</p><pre>cat /usr/local/bin/aws-lambda-rie # binary file garbage<br>cat /var/runtime/bootstrap</pre><p>We see</p><pre>#!/bin/sh<br># Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.<br><br>if [ -z &quot;$NODE_PATH&quot; ]; then<br>  nodejs_mods=&quot;/opt/nodejs/node_modules&quot;<br>  nodejs18_mods=&quot;/opt/nodejs/node18/node_modules&quot;<br>  runtime_mods=&quot;/var/runtime/node_modules&quot;<br>  task=&quot;/var/runtime:/var/task&quot;<br>  export NODE_PATH=&quot;$nodejs18_mods:$nodejs_mods:$runtime_mods:$task&quot;<br>fi<br><br>if [ -n &quot;$AWS_LAMBDA_FUNCTION_MEMORY_SIZE&quot; ]; then<br>  new_space=$(expr $AWS_LAMBDA_FUNCTION_MEMORY_SIZE / 10)<br>  semi_space=$(expr $new_space / 2)<br>  old_space=$(expr $AWS_LAMBDA_FUNCTION_MEMORY_SIZE - $new_space)<br>  MEMORY_ARGS=(<br>    &quot;--max-semi-space-size=$semi_space&quot;<br>    &quot;--max-old-space-size=$old_space&quot;<br>  )<br>fi<br><br># If NODE_EXTRA_CA_CERTS is being set by the customer, don&#39;t override. Else, include RDS CA<br>if [ -z &quot;${NODE_EXTRA_CA_CERTS+set}&quot; ]; then<br>  # Use the default CA bundle in CN regions and regions that have 3 dashes in their name<br>  if [ &quot;${AWS_REGION:0:3}&quot; == &quot;cn-&quot; ] || [ &quot;${AWS_REGION//[^-]}&quot; == &quot;---&quot; ]; then<br>    export NODE_EXTRA_CA_CERTS=/etc/pki/tls/certs/ca-bundle.crt<br>  else<br>    # /var/runtime/ca-cert.pem contains all certs in &quot;/etc/pki/tls/certs/ca-bundle.crt&quot; that<br>    # are not already embedded in the node binary.<br>    export NODE_EXTRA_CA_CERTS=/var/runtime/ca-cert.pem<br>  fi<br>fi<br><br>export AWS_EXECUTION_ENV=AWS_Lambda_nodejs18.x<br><br>NODE_ARGS=(<br>    --expose-gc<br>    --max-http-header-size 81920<br>    &quot;${MEMORY_ARGS[@]}&quot;<br>    /var/runtime/index.mjs<br>    )<br><br>if [ -z &quot;$AWS_LAMBDA_EXEC_WRAPPER&quot; ]; then<br>  exec /var/lang/bin/node &quot;${NODE_ARGS[@]}&quot;<br>else<br>  wrapper=&quot;$AWS_LAMBDA_EXEC_WRAPPER&quot;<br>  if [ ! -f &quot;$wrapper&quot; ]; then<br>    echo &quot;$wrapper: does not exist&quot;<br>    exit 127<br>  fi<br>  if [ ! -x &quot;$wrapper&quot; ]; then<br>    echo &quot;$wrapper: is not an executable&quot;<br>    exit 126<br>  fi<br>    exec -- &quot;$wrapper&quot; /var/lang/bin/node &quot;${NODE_ARGS[@]}&quot;<br>fi</pre><p>It seems to be invoking nodejs. I wonder if other images will have different bootstrap files. Let&#39;s go to the Amazon Lambda console and use hello.sh to probe around.</p><p>With my hello.sh file as</p><pre>function handler () {<br>    ls -l /var/runtime<br>}</pre><p>I get a funny result that</p><pre>total 9852<br>-rwxr-xr-x 1 root root 10085351 Oct 19 17:20 init</pre><p>I tried to cat it but it timed out (since it&#39;s 10Mb afterall).</p><h3>Where is layers uploaded to?</h3><p>AWS Lambda Layers are uploaded to /opt in the container. We can verify this by creating a layer and uploading it to our function.</p><pre>echo &quot;meow&quot; &gt; test.txt<br>zip test.zip test.txt</pre><p>Then after uploading, we can use hello.sh to again probe around.</p><pre>function handler () {<br>    ls -l /opt<br>}</pre><p>and we see</p><pre>total 1<br>-rwxr-xr-x 1 root root 5 Dec 27 17:37 test.txt</pre><p>Now what if we wanted to upload it to a different path? Idk</p><h3>Environment variables</h3><p>I used env in hello.sh to see the environment variables. I redacted some of the values.</p><pre>AWS_LAMBDA_FUNCTION_VERSION=$LATEST<br>AWS_SESSION_TOKEN=REDACTED<br>LAMBDA_TASK_ROOT=/var/task<br>AWS_LAMBDA_LOG_GROUP_NAME=/aws/lambda/custom_runtime<br>LD_LIBRARY_PATH=/lib64:/usr/lib64:/var/runtime:/var/runtime/lib:/var/task:/var/task/lib:/opt/lib<br>AWS_LAMBDA_RUNTIME_API=127.0.0.1:9001<br>AWS_LAMBDA_LOG_STREAM_NAME=2023/12/27/[$LATEST]REDACTED_UUID<br>AWS_LAMBDA_FUNCTION_NAME=custom_runtime<br>AWS_XRAY_DAEMON_ADDRESS=REDACTED_IPV4_ADDRESS:2000<br>PATH=/usr/local/bin:/usr/bin/:/bin:/opt/bin<br>AWS_DEFAULT_REGION=us-east-1<br>PWD=/var/task<br>AWS_SECRET_ACCESS_KEY=REDACTED<br>LANG=en_US.UTF-8<br>LAMBDA_RUNTIME_DIR=/var/runtime<br>AWS_LAMBDA_INITIALIZATION_TYPE=on-demand<br>TZ=:UTC<br>AWS_REGION=us-east-1<br>AWS_ACCESS_KEY_ID=REDACTED<br>SHLVL=1<br>_AWS_XRAY_DAEMON_ADDRESS=REDACTED_IPV4_ADDRESS<br>_AWS_XRAY_DAEMON_PORT=2000<br>AWS_XRAY_CONTEXT_MISSING=LOG_ERROR<br>_HANDLER=hello.handler<br>AWS_LAMBDA_FUNCTION_MEMORY_SIZE=128<br>_=/usr/bin/env</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2aad6e4da3a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting Up SSL Manually on Kubernetes Traefik: ACME HTTP Challenge]]></title>
            <link>https://medium.com/@chienhaotan/setting-up-ssl-manually-on-kubernetes-traefik-acme-http-challenge-ccdea1584c5d?source=rss-c8144e286ba4------2</link>
            <guid isPermaLink="false">https://medium.com/p/ccdea1584c5d</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[https]]></category>
            <category><![CDATA[ssl]]></category>
            <category><![CDATA[acme]]></category>
            <category><![CDATA[dns]]></category>
            <dc:creator><![CDATA[Chien Hao Tan]]></dc:creator>
            <pubDate>Wed, 27 Dec 2023 15:59:41 GMT</pubDate>
            <atom:updated>2023-12-27T15:59:41.932Z</atom:updated>
            <content:encoded><![CDATA[<p>Today, I will show you how to setup SSL on Kubernetes the manual way. I will be using Traefik as the Ingress Controller and Let’s Encrypt as the Certificate Authority. In the <a href="https://tch1001.github.io/kubernetes/traefik/ssl/2023/03/06/ssl.html">previous</a> article, I talked about how to perform ACME using DNS. But today I had to perform a renewal of cert without access to the DNS (but having access to the web server). So I had to use the HTTP ACME challenge instead.</p><h3>Refer to <a href="https://medium.com/@chienhaotan/test-78eeb72cc22c">https://medium.com/@chienhaotan/test-78eeb72cc22c</a> for server setup</h3><h3>Certbot SSL Setup</h3><p>If you want to use “DNS only” and still have SSL, or you want “Proxied” with Full encryption mode, you need to create a certificate using <a href="https://certbot.eff.org/">Certbot</a>. Certbot is a free, open-source tool for automatically using Let’s Encrypt certificates on manually-configured HTTPS servers.</p><p>Usually, people use certbot because it’s very automatic, but in this case I have chosen to manually obtain my certificates and upload it because I want to learn how it works, and have greater control over the process. I have found that when I try to do it automatically using Traefik, there is a lot of fiddling and restarting the services, possibly resulting in downtime. Through the manual method, you don’t need to touch the my-service Service, and just need to update the IngressRoutes.</p><p>First, you need to install certbot. After that you can run</p><pre>sudo certbot certonly --manual --preferred-challenge http -d my3.domain.com</pre><ul><li>--manual is required if we want to use the HTTP acme challenge.</li><li>-d my3.domain.com indicates the domain (leaving it out will prompt you to input it manually).</li></ul><p>You will see something like</p><pre>Create a file containing just this data:</pre><pre>3H7J8MdG5anbZ0bIi3kNarqT1QxESoMdbCGMmemFHDd.ypmiVlOlYgU_sU-90HbZhcPvk6BiHkxyIxWjYRQllEQ</pre><pre>And make it available on your web server at this URL:</pre><pre>http://my3.domain.com/.well-known/acme-challenge/3H7J8MdG5anbZ0bIi3kNarqT1QxESoMdbCGMmemFHDd</pre><pre>Press Enter to Continue</pre><p>So now you need to create a txt file that the ACME certbot can access via your domain to prove that you have control over the domain. This will differ according to the web server you have. But for me it was nodejs so I just put the file in static/.well-known/acme-challenge folder</p><p>And then built and pushed the new docker image</p><pre>docker build -t tch1001/newimage:v2<br>docker push tch1001/newimage:v2<br>vim kubernetes/servers/webserver.yaml # edit the version<br>k apply -f kubernetes/servers/webserver.yaml</pre><p>After that I return to the ACME certbot and press enter. If all goes well, you will see</p><pre>Successfully received certificate.<br>Certificate is saved at: /etc/letsencrypt/live/my3.domain.com/fullchain.pem<br>Key is saved at:         /etc/letsencrypt/live/my3.domain.com/privkey.pem<br>This certificate expires on 2023-06-04.<br>These files will be updated when the certificate renews.</pre><h3>Setting HTTP redirection to HTTPS</h3><p>The rest of the blog is a duplicate of <a href="https://medium.com/@chienhaotan/test-78eeb72cc22c">part 1</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ccdea1584c5d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Playing with xv6]]></title>
            <link>https://medium.com/@chienhaotan/playing-with-xv6-175cd1bc80f8?source=rss-c8144e286ba4------2</link>
            <guid isPermaLink="false">https://medium.com/p/175cd1bc80f8</guid>
            <category><![CDATA[linux-kernel]]></category>
            <category><![CDATA[risc-v]]></category>
            <category><![CDATA[kernel]]></category>
            <category><![CDATA[xv6]]></category>
            <category><![CDATA[kernel-debugging]]></category>
            <dc:creator><![CDATA[Chien Hao Tan]]></dc:creator>
            <pubDate>Wed, 27 Dec 2023 15:56:59 GMT</pubDate>
            <atom:updated>2023-12-27T15:56:59.964Z</atom:updated>
            <content:encoded><![CDATA[<p>I chose to do riscv today but doing x86 will probably be faster.</p><h3>Compiling the RISCV Toolchain</h3><p>We need to do this to obtain riscv64-unknown-linux-gnu-gcc</p><pre>git clone --depth 1 https://github.com/mit-pdos/xv6-riscv<br>git clone --depth 1 https://github.com/riscv-collab/riscv-gnu-toolchain<br>cd riscv-gnu-toolchain<br>sudo apt-get install autoconf automake autotools-dev curl python3 python3-pip libmpc-dev libmpfr-dev libgmp-dev gawk build-essential bison flex texinfo gperf libtool patchutils bc zlib1g-dev libexpat-dev ninja-build git cmake libglib2.0-dev<br>./configure --prefix=/opt/riscv<br>sudo make linux # this takes forever</pre><h3>Compiling QEMU</h3><p>We need to do this to obtain qemu-system-riscv64</p><pre>git clone --branch v5.0.0 --depth 1 https://github.com/qemu/qemu<br>cd qemu<br>./configure --target-list=riscv64-softmmu --disable-docs<br>make -j8<br>sudo make install</pre><h3>Compiling xv6</h3><pre>cd ../xv6-riscv<br>TOOLPREFIX=/opt/riscv/bin/riscv64-unknown-linux-gnu- make qemu</pre><p>If all goes well, you should boot into a shell</p><pre>xv6 kernel is booting</pre><pre>hart 1 starting<br>hart 2 starting<br>init: starting sh<br>$ <br>$ ls<br>.              1 1 1024<br>..             1 1 1024<br>README         2 2 2305</pre><p>To exit qemu, press Ctrl-A X.</p><h3>Debugging xv6</h3><p>Optionally, run with gdb attached</p><pre>TOOLPREFIX=/opt/riscv/bin/riscv64-unknown-linux-gnu- make qemu-gdb</pre><p>Then, in another terminal, run</p><pre>/opt/riscv/bin/riscv64-unknown-linux-gnu-gdb<br>target remote :26000 # or whatever port they said above<br>continue<br>Ctrl-C # to send interrupt<br>break swtch<br>c<br># go back and type something in the shell</pre><h3>Poking the kernel code</h3><h3>sh.c Command Types</h3><p>I injected the following into sh.c.</p><pre>struct pipecmd *pcmd;<br>  struct redircmd *rcmd;<br>  fprintf(2, &quot;tch is here, type = %d\n&quot;, cmd-&gt;type);</pre><pre>  if(cmd == 0)<br>    exit(1);</pre><p>Then I recompiled using make qemu. The output is</p><pre>$ ls <br>tch is here, type = 1<br>... # rest of output</pre><p>If we look at sh.c, we see that 1 corresponds to EXEC.</p><pre>#define EXEC  1<br>#define REDIR 2<br>#define PIPE  3<br>#define LIST  4<br>#define BACK  5</pre><ul><li>EXEC is running any command</li><li>REDIR is for redirecting output via &gt; to a file</li><li>PIPE is for piping output via | to another program</li><li>LIST is for a list of commands, separated by ;</li><li>BACK is for running a command in the background using &amp;</li></ul><p><a href="https://medium.com/@balemarthyvamsi/xv6-deep-dive-part5-8455899670e0">Balemarthy Part 5</a> talks about the implementation in detail.</p><p>Let’s try to implement a few new features following this <a href="https://medium.com/@harshalshree03/xv6-implementing-ps-nice-system-calls-and-priority-scheduling-b12fa10494e4">Harshal</a> tutorial. We will do that in another post!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=175cd1bc80f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fun with QEMU Arguments and Character Devices]]></title>
            <link>https://medium.com/@chienhaotan/fun-with-qemu-arguments-and-character-devices-b4ef72c6795d?source=rss-c8144e286ba4------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4ef72c6795d</guid>
            <category><![CDATA[character-device]]></category>
            <category><![CDATA[console]]></category>
            <category><![CDATA[kernel]]></category>
            <category><![CDATA[qemu]]></category>
            <category><![CDATA[linux]]></category>
            <dc:creator><![CDATA[Chien Hao Tan]]></dc:creator>
            <pubDate>Wed, 27 Dec 2023 15:55:41 GMT</pubDate>
            <atom:updated>2023-12-27T15:56:06.924Z</atom:updated>
            <content:encoded><![CDATA[<p>If you do man qemu-system and search for -serial you would come across a good explanation of how the qemu terminal emulation works. Let’s have abit of fun with it.</p><h3>Playing with Character Devices</h3><pre>qemu-system-x86_64 -kernel ./vmlinux</pre><p>pops up a window with a few tabs, VGA, compat_monitor0, serial0, parallel0 (Ctrl-Alt M &gt; View &gt; Show Tabs)</p><ul><li>VGA is what you would see if you connected a monitor to the system you are booting up.</li><li>compat_monitor0 is the qemu monitor that you can use to interact with the qemu instance. (qemu). You can type help to see the commands you can use.</li><li>serial0 and parallel0 are buses or channels of communication between the host and the emulated qemu instance. I like to think of parallel as the 64-bit bus and serial as RX/TX UART communication.</li></ul><pre>qemu-system-x86_64 -kernel ./vmlinux -append &quot;console=ttyS0 meowmeow&quot;</pre><p>Just like how you can parse arguments into an executable like ./a.out param1 param2, you can also parse arguments into ./vmlinux (just that you can’t execute it directly and need to use qemu or boot it from a bootloader). In this case we pass an argument console=ttyS0 to tell the kernel to use ttyS0 as the console. We also pass meowmeow as an argument, which is just a random marker I will find in the kernel logs (when we log to a file). For now you see a lot of stuff spew out in the serial0 tab.</p><p>You could try other consoles too listed <a href="https://docs.kernel.org/admin-guide/serial-console.html">here</a>. I tried putting a funny Baud rate but nothing happened.</p><pre>qemu-system-x86_64 -kernel ./vmlinux -append &quot;console=ttyS0&quot; -serial file:serial.log <br>cat serial.log # see kernel boot logs<br>cat serial.log | grep meowmeow<br>[    0.000000] Command line: console=ttyS0 meowmeow<br>[    0.058980] Kernel command line: console=ttyS0 meowmeow<br>[    0.059534] Unknown kernel command line parameters &quot;meowmeow&quot;, will be passed to user space.</pre><p>You can specify many -serial flags, it would correspond to serial0, serial1, etc. After each -serial, you specify a character device, which could be many things. In this example, we chose a write-only chardev which writes to a file. Read the man page or -chardev help to see all options.</p><p>We also observe that whatever we parse into -append gets sent to the kernel file vmlinux. So it comes as no surprise later we send things like console=ttyS0 panic=1 root=/dev/sda rootfstype=ext2. Basically just telling the kernel what to do when it panics and how to work with the emulated hardware we pass it.</p><pre>qemu-system-x86_64 -kernel ./vmlinux -append &quot;console=ttyS0&quot; -serial file:serial.log -chardev file,path=mon.log,mux=on,id=char0 -mon chardev=char0,mode=readline</pre><p>This binds the file mon.log to the qemu monitor. When we open it up, we see</p><pre>$ cat mon.log<br>QEMU 4.2.1 monitor - type &#39;help&#39; for more information<br>(qemu)</pre><p>Practically speaking, it doesn’t make sense to bind a monitor interactive console to a write-only file. So let’s bind it to stdio instead.</p><pre>qemu-system-x86_64 -chardev stdio,id=char0 -mon chardev=char0,mode=readline -kernel ./vmlinux -append &quot;console=ttyS0&quot;</pre><p>In the graphical window, open the serial0 tab. Then in the monitor, you can play around</p><pre>(qemu) info chardev<br>parallel0: filename=vc<br>char0: filename=stdio<br>serial0: filename=vc<br>(qemu) system_reset<br>(qemu) stop<br>(qemu) cont</pre><p>If you don’t like the kernel logs to appear in graphical window, you can bind -serial chardev:char0 too. Now you can cycle between compat-monitor0 and serial0 using C-A C.</p><p>If we do this to -parallel 0 (which is currently blank anyway), and also do -display none. Then we have effectively done -nographic ourselves using:</p><pre>NOGRAPHIC=&quot;-chardev stdio,mux=on,id=char0 -mon chardev=char0,mode=readline -serial chardev:char0 -parallel chardev:char0 -display none&quot;</pre><p>Here are some differences, but please DO NOT use $NOGRAPHIC because I found it causes later issues with the shell (busybox segfault).</p><p>You can have abit more fun here with some <a href="https://fadeevab.com/how-to-setup-qemu-output-to-console-and-automate-using-shell-script/">automation</a>.</p><h3>Trying to Boot</h3><pre>qemu-system-x86_64 -nographic -kernel ./vmlinux -append &quot;console=ttyS0&quot;</pre><p>Anyway, enough playing with chardevs and terminals, we see that the kernel is looking for a blockdev root device</p><pre>[    1.332198] /dev/root: Can&#39;t open blockdev<br>[    1.332485] VFS: Cannot open root device &quot;(null)&quot; or unknown-block(0,0): error -6<br>[    1.332612] Please append a correct &quot;root=&quot; boot option; here are the available partitions:<br>[    1.332827] 0b00         1048575 sr0</pre><p>So let’s try to add a root device</p><pre>dd if=/dev/zero of=rootfs.ext2 bs=1024k count=256<br>mkfs.ext2 rootfs.ext2<br>qemu-system-x86_64 -nographic -kernel ./vmlinux -append &quot;console=ttyS0 root=/dev/sda&quot; -hda rootfs.ext2</pre><p>You can pass in more drives using -hda, -hdb, -hdc, -hdd. But it will fill up /dev/sda,sdb,sdc,sdd sequentially. Then</p><pre>(qemu) info block</pre><p>It still crashes, but now it complains there is no init.</p><pre>Kernel panic - not syncing: No working init found.  Try passing init= option to kernel. See Linux Documentation/admin-guide/init.rst for guidance.</pre><p>Let’s try writing out own init to get a feel for what the kernel wants.</p><pre>$ mkdir vfs &amp;&amp; cd vfs<br>$ cat &lt;&lt; EOF &gt; hello-kernel.c<br>#include &lt;stdio.h&gt;</pre><pre>int main(){<br>        printf(&quot;Hello, kernel!\n&quot;);<br>        sleep(9999999999999);<br>}<br>EOF<br>$ gcc --static hello-kernel.c -o init<br>$ find . | cpio -o -H newc | gzip &gt; root.cpio.gz<br>$ qemu-system-x86_64 -nographic -kernel ./vmlinux -append &quot;console=ttyS0 root=/dev/sda&quot; -hda rootfk.ext2 -initrd vfs/root.cpio.gz</pre><p>This shows</p><pre>[    1.504610] Run /init as init process<br>Hello, kernel!</pre><p>Yay! If you have segmentation fault after typing, make sure you are using -nographic (instead of my $NOGRAPHIC) because I think when you do your own multiplexing it confuses qemu (probably a bug, would be interesting to investigate).</p><p>Interestingly, if we have an -initrd we actually don’t need a -hda. We can just do</p><pre>qemu-system-x86_64 -kernel ./vmlinux -append &quot;console=ttyS0&quot; -initrd vfs/root.cpio.gz</pre><p>it works fine too. Instead of using our own init, we can use busybox’s init. Check out my <a href="https://tch1001.github.io/linux/kernel/2023/01/31/minimal-kernel.html">minimal kernel blog</a> for details.</p><p>Anyway, the main purpose of this blog was to document my understanding of character devices and the many qemu parameters, so I will stop here. Hope you found it useful! Contact me at telegram @tch1001 if you need any help!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4ef72c6795d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adding Users to Kubernetes (RBAC)]]></title>
            <link>https://medium.com/@chienhaotan/adding-users-to-kubernetes-rbac-ac00c0dd4c1b?source=rss-c8144e286ba4------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac00c0dd4c1b</guid>
            <category><![CDATA[rbac]]></category>
            <category><![CDATA[rbac-access-control]]></category>
            <category><![CDATA[certificate-authority]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[kubernetes-administration]]></category>
            <dc:creator><![CDATA[Chien Hao Tan]]></dc:creator>
            <pubDate>Wed, 27 Dec 2023 15:53:42 GMT</pubDate>
            <atom:updated>2023-12-27T15:53:42.906Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Why add users to Kubernetes? There are 2 main reasons.</p><h3>Security</h3><p>You work in a big team of developers. You’re the techlead so it’s your job to make sure that the team doesn’t mess up the cluster. You can’t just give everyone admin access. So you need to create a user for each developer. This way, junior developers will not be able to singlehandedly bring down production (that’s the job of senior developers!). And you can revoke access if someone leaves the company.</p><h3>CI/CD</h3><p>While I was setting up CI/CD, I ran into a need to add users. I rent a managed DigitalOcean Kubernetes cluster for my personal projects. It uses doctl for authentication. Namely, in the kubeconfig file,</p><pre>users:<br>- name: do-sgp1-test-admin<br>  user:<br>    exec:<br>      apiVersion: client.authentication.k8s.io/v1beta1<br>      args:<br>      - kubernetes<br>      - cluster<br>      - kubeconfig<br>      - exec-credential<br>      - --version=v1beta1<br>      - --context=k8_testing<br>      - REDACTED <br>      command: doctl<br>      env: null<br>      interactiveMode: IfAvailable<br>      provideClusterInfo: false</pre><p>If I copied this kubeconfig file to GitHub actions, it would fail because GitHub actions doesn’t have doctl installed in the GH actions runner. So I needed to add a user to the cluster that uses a key and cert instead of doctl.</p><h3>Creating a Private Key and CSR</h3><p>First, we need to create a private key and a certificate signing request (CSR). The CSR will be signed by the Kubernetes cluster to create a certificate. The certificate will be used to authenticate the user.</p><h3>Private Key</h3><pre>openssl genrsa -out tom.key 2048<br># note whatever comes after CN= (CN stands for Common Name) will be the username of the user in kubernetes<br>openssl req -new -key tom.key -out tom.csr -subj &quot;/CN=tom&quot;</pre><h3>Certificate Signing Request (CSR)</h3><h4>Self Hosted Kubernetes</h4><p>Note that if you host your <strong>own</strong> kubernetes cluster and have direct SSH access to the master node, you can sign it manually using</p><pre>openssl x509 -req -in tom.csr \<br>  -CA /etc/kubernetes/pki/ca.crt \<br>  -CAkey /etc/kubernetes/pki/ca.key \<br>  -CAcreateserial \<br>  -out tom.crt -days 500</pre><h4>Managed Kubernetes</h4><p>Otherwise, you don’t have direct access to the CA cert so you have to create a CSR to send to the Kubernetes cluster via kubectl.</p><pre>$ cat tom.csr | base64 | tr -d &#39;\n&#39;<br>REDACTED_CSR_IN_BASE64</pre><p>Then, create a file called tom-csr.yaml with the following contents</p><pre>apiVersion: certificates.k8s.io/v1<br>kind: CertificateSigningRequest<br>metadata:<br>  name: tom-csr<br>spec:<br>  groups:<br>  - system:authenticated<br>  # I found that using $(cat tom.csr | base64 | tr -d &#39;\n&#39;) doesn&#39;t work<br>  # so I just copy pasted the output of the command above<br>  request: REDACTED_CSR_IN_BASE64<br>  signerName: kubernetes.io/kube-apiserver-client<br>  usages:<br>  - digital signature<br>  - key encipherment<br>  - client auth</pre><p>After that send it to the Kubernetes API server</p><pre>$ kubectl apply -f tom-csr.yaml<br>$ kubectl get csr<br>NAME        AGE   SIGNERNAME                            REQUESTOR               REQUESTEDDURATION   CONDITION<br>tom-csr     68m   kubernetes.io/kube-apiserver-client   your-email@gmail.com    &lt;none&gt;              Pending</pre><h3>Approve the CSR</h3><p>Now we have to tell Kubernetes to approve the CSR and give us a certificate.</p><pre>$ kubectl certificate approve tom-csr<br>$ kubectl get csr<br>NAME        AGE   SIGNERNAME                            REQUESTOR               REQUESTEDDURATION   CONDITION<br>tom-csr     68m   kubernetes.io/kube-apiserver-client   your-email@gmail.com    &lt;none&gt;              Approved,Issued<br>$ k get csr testuser-authentication -o jsonpath=&#39;{.status.certificate}&#39; | base64 -d &gt; tom.crt</pre><h3>Add it to a context</h3><p>If you manage multiple clusters (or have multiple users in a cluster), you will be comfortable with the KUBECONFIG file.</p><p>The most common way of using KUBECONFIG is to set the KUBECONFIG environment variable to the path of the kubeconfig file.</p><pre>$ KUBECONFIG=/path/to/kubeconfig kubectl get node<br>NAME                      STATUS   ROLES    AGE   VERSION<br>node-default-pool-mk771   Ready    &lt;none&gt;   70d   v1.70.3<br>node-default-pool-mk772   Ready    &lt;none&gt;   70d   v1.70.3<br>$ KUBECONFIG=/another/kubeconfig kubectl get node <br>NAME                      STATUS   ROLES    AGE   VERSION<br>some-other-pool           Ready    &lt;none&gt;   10d   v1.70.2</pre><p>A convenient way to manage kubenetes contexts is to use <a href="https://github.com/ahmetb/kubectx">kubectx</a>.</p><p>The caveman way to edit kubeconfig files is to use vim. A more civilised way is to use kubectl config.</p><pre>$ kubectl config get-contexts<br>CURRENT NAME         CLUSTER         AUTHINFO     NAMESPACE<br>*       ctx-name     cluster-name    authinfo     default<br>        ctx-2        cluster-name    authinfo-2   other-namespace<br># if you didn&#39;t do --embed-certs then it will be a file path, which might cause portability issues (when copying it to CI/CD, for instance)<br>$ kubectl config set-credentials tom --client-key=tom.key --client-certificate=tom.crt --embed-certs=true<br># if you don&#39;t set the namespace, it will default to the namespace in the current context<br># namespace could be a source of errors! (see section below on errors)<br>$ kubectl config set-context tom-context --cluster cluster-name --user=tom --namespace=tom-namespace<br>Context &quot;tom-context&quot; modified.<br>$ kubectl config get-contexts<br>CURRENT NAME         CLUSTER         AUTHINFO     NAMESPACE<br>*       ctx-name     cluster-name    authinfo     default<br>        ctx-2        cluster-name    authinfo-2   other-namespace<br>        tom-context  cluster-name    tom          tom-namespace<br>$ kubectl config use-context tom-context<br>$ kubectl config current-context <br>tom-context</pre><p>Awesome! so we have created our user. But unfortunately he can’t do anything at the moment</p><pre>$ kubectl get pods<br>Error from server (Forbidden): nodes is forbidden: User &quot;tom&quot; cannot list resource &quot;pods&quot; in API group &quot;&quot; at the cluster scope</pre><p>We need to give him some permissions using roles and role bindings.</p><h3>Create Role and Role Binding</h3><p>There is also a ClusterRole and ClusterRoleBinding but we will stick to Role and RoleBinding for now. It’s more or less similar too just that ClusterRole and ClusterRoleBinding are cluster scoped while Role and RoleBinding are namespace scoped.</p><h3>Switching back to admin</h3><p>We can’t create roles and role bindings as tom, so we have to switch back to the admin context</p><pre>$ kubectl config use-context ctx-name<br>$ kubectl config current-context <br>ctx-name</pre><h3>Role</h3><pre>kubectl create role developer --verb=create --verb=get --verb=list --verb=update --verb=delete --resource=pods --resource=pods/exec --resource=pods/attach</pre><h3>Role Binding</h3><pre>kubectl create rolebinding tom-rolebinding --role=developer --user=tom</pre><h3>Testing</h3><pre>$ kubectl config use-context tom-context<br>$ kubectl config current-context <br>tom-context<br>$ kubectl get pods<br>NAME                                     READY   STATUS    RESTARTS      AGE<br>some-prevly-created-pod-fb7dc94b-pr2x8   1/1     Running   7 (73m ago)   136m</pre><h3>Common Errors</h3><h3>Error from server (Forbidden)</h3><p>Suppose after you switched context to the newly added user, you try to run kubectl get pods and you get the following error</p><pre>Error from server (Forbidden): services is forbidden: User &quot;tom&quot; cannot list resource &quot;pods&quot; in API group &quot;&quot; in the namespace &quot;default&quot;</pre><p>There are a few things to check</p><ul><li>Role Binding and Roles are namespaced. You can check which namespace you created them in using</li></ul><pre>kubectl get role -A<br>kubectl get rolebinding -A</pre><p>Then check that the context is bound to the correct namespace. Sometimes the namespace is not set.</p><pre>kubectl config get-contexts | less -S<br>CURRENT NAME         CLUSTER         AUTHINFO     NAMESPACE<br>*       ctx-name     cluster-name    authinfo     default<br>        ctx-2        cluster-name    authinfo-2   other-namespace</pre><ul><li>You can check for authorization using</li></ul><pre>$ kubectl auth can-i list pods --as tom<br>yes<br>$ kubectl auth can-i list pods --as tommy<br>no</pre><ul><li>Check the Role. Stare at your previous kubectl command for a while.</li></ul><pre>kubectl create role developer --verb=create --verb=get --verb=list --verb=update --verb=delete --resource=pods</pre><ul><li>Check the Role Binding. Stare at your previous kubectl command for a while. <strong>Especially</strong> the --user field. It must match the CN= in the CSR.</li></ul><pre>kubectl create rolebinding testuser-authentication-rolebinding-2 --role=developer --user=tom</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac00c0dd4c1b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Compiling and Running a Minimal Kernel with Busybox]]></title>
            <link>https://medium.com/@chienhaotan/compiling-and-running-a-minimal-kernel-with-busybox-bfc45a991017?source=rss-c8144e286ba4------2</link>
            <guid isPermaLink="false">https://medium.com/p/bfc45a991017</guid>
            <category><![CDATA[busybox]]></category>
            <category><![CDATA[qemu]]></category>
            <category><![CDATA[kernel]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[linux-kernel]]></category>
            <dc:creator><![CDATA[Chien Hao Tan]]></dc:creator>
            <pubDate>Wed, 27 Dec 2023 15:49:32 GMT</pubDate>
            <atom:updated>2023-12-27T15:49:49.220Z</atom:updated>
            <content:encoded><![CDATA[<p>The exploration logs are found at <a href="https://github.com/tch1001/kernel">here</a>.</p><h3>Building the Kernel</h3><p>Of course the small kernel must still be functional, so we will test it using <a href="https://www.qemu.org/">qemu</a>. One can also use virtualbox but I chose qemu because I will be working remotely using SSH and VNC takes too much mobile data lol.</p><pre>$ git clone git://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git --depth 1 --branch v6.1.4<br>$ cd linux<br>$ git log<br>commit 2cb8e624295ffa0c4d659fcec7d9e7a6c48de156 (grafted, HEAD, tag: v6.1.4)<br>    Author: Greg Kroah-Hartman &lt;gregkh@linuxfoundation.org&gt;<br>        Date:   Sat Jan 7 11:12:04 2023 +0100<br>	Linux 6.1.4<br>$ apt install -y libncurses5 libncurses5-dev bison flex<br>$ make menuconfig <br># go enable PVH if u want to run in QEMU<br>$ vim .config # remove &quot;debian&quot; things, and the &quot;certs/signing_key.pem&quot;<br>$ apt install -y libssl-dev libelf-dev<br>$ make -j$(nproc) # change -jN to your liking<br># if they prompt something involving certs, just press enter (default choices)</pre><p>Important: Don’t forget to enable CONFIG_PVH=y in .config if you want to run in QEMU.</p><pre>$ ls -lh vmlinux</pre><p>vmlinux should exist, if it doesn’t, something went wrong and go back to <a href="https://tch1001.github.io/linux/kernel/2023/01/31/minimal-kernel.html#building-the-kernel">build</a>.</p><p>Otherwise, let’s run our kernel!</p><h3>Running in QEMU</h3><p>We need an Initrd? What’s Init RAM Disk? It is the first thing that the kernel looks for when it wakes up.</p><p>You can try the following command and see it complain that it was unable to find an init.</p><pre>$ qemu-system-x86_64 -kernel ./vmlinux -nographic --append &quot;console=tty0 console=ttyS0 panic=1 root=/dev/sda rootfstype=ext2&quot; -hda rootfs.ext2 -m 1024 -vga none -display none -serial mon:stdio -no-reboot <br># Some kernel logs before we see<br>[    1.512696] Run /sbin/init as init process<br>[    1.513360] Run /etc/init as init process<br>[    1.513575] Run /bin/init as init process<br>[    1.513772] Run /bin/sh as init process<br>[    1.514056] Kernel panic - not syncing: No working init found.  Try passing init= option to kernel.</pre><p>The kernel was frantically looking for an init executable in /sbin,/etc,/bin. Really just any executable (can be a shell script, or a binary executable).</p><h3>Our own init</h3><p>Let’s write our own init for now. The sleep is to prevent the kernel from panicing (it will panic if init exits).</p><pre>$ mkdir vfs &amp;&amp; cd vfs<br>$ cat &lt;&lt; EOF &gt; hello-kernel.c<br>#include &lt;stdio.h&gt;</pre><pre>int main(){<br>        printf(&quot;Hello, kernel!\n&quot;);<br>        sleep(9999999999999);<br>}<br>EOF<br>$ gcc --static hello-kernel.c -o init</pre><p>Now we just need to package it up into a cpio format.</p><pre>$ find . | cpio -o -H newc | gzip &gt; root.cpio.gz</pre><p>Then we can run QEMU successfully</p><pre>$ qemu-system-x86_64 -kernel ./vmlinux -nographic --append &quot;console=tty0 console=ttyS0 panic=1 root=/dev/sda rootfstype=ext2&quot; -hda rootfs.ext2 -m 1024 -vga none -display none -serial mon:stdio -no-reboot -initrd initrd/root.cpio.gz<br>[    1.461412] x86/mm: Checked W+X mappings: passed, no W+X pages found.<br>[    1.461651] Run /init as init process<br>Hello, kernel!<br>[    1.946056] tsc: Refined TSC clocksource calibration: 3399.960 MHz<br>[    1.946430] clocksource: tsc: mask: 0xffffffffffffffff max_cycles: 0x3102293934f, max_idle_ns: 440795316s<br>[    1.946791] clocksource: Switched to clocksource tsc</pre><p>Great! But now we don’t just want our init to say hello, we want our init to be able to put us into a shell and let us navigate and do productive work! That is where <a href="https://busybox.net/">busybox</a> comes in!</p><h3>Busybox</h3><p>Git clone and compile Busybox</p><pre>$ cd .. # don&#39;t do stuff in the linux directory, git will be confused<br>$ git clone --depth=1 https://github.com/mirror/busybox.git &amp;&amp; cd busybox<br>$ make defconfig <br>$ vi .config # set CONFIG_STATIC=y<br>$ make -j$(nproc)<br>$ make CONFIG_PREFIX=$PWD/BUSYBOX install<br>$ ls BUSYBOX <br>bin  linuxrc  sbin  usr</pre><p>Then we make out initrd with busybox</p><pre>$ cd ../linux # return back to linux directory<br>$ mkdir initrd &amp;&amp; cd initrd # like vfs (from previously), this will house our new initrd<br>$ mkdir etc proc sys<br>$ cat &lt;&lt; EOF &gt; init                              <br>#!/bin/sh<br>                           <br>mount -t proc proc /proc<br>mount -t sysfs none /sys<br>                                                      <br># https://busybox.net/FAQ.html#job_control<br>                                                      <br>mknod /dev/ttyS0 c 4 64<br>setsid sh -c &#39;exec sh &lt;/dev/ttyS0 &gt;/dev/ttyS0 2&gt;&amp;1&#39;<br>EOF                                                   <br>$ chmod +x init</pre><p>The above init shell script will be our entrypoint</p><pre>$ cp ../../busybox/BUSYBOX/* . # copy over our compiled busybox utilities<br>$ find . | cpio -o -H newc | gzip &gt; root.cpio.gz # package it</pre><p>Basically, init will call our busybox utilities! Internally, /bin/ls is a symlink to /bin/busybox ls</p><p>Fun fact: Alpine linux uses busybox, Alpine linux is popular in docker containers due to it’s small size.</p><h3>Booting</h3><pre>$ qemu-system-x86_64 -kernel ./vmlinux -nographic --append &quot;console=tty0 console=ttyS0 panic=1 root=/dev/sda rootfstype=ext2&quot; -hda rootfs.ext2 -m 1024 -vga none -display none -serial mon:stdio -no-reboot -initrd initrd/root.cpio.gz</pre><p>We should be dropped into a shell and now we can type busybox to see the commands we can use.</p><h3>Running the Kernel on Hardware</h3><p>If you’re on ubuntu, you can replace your current kernel (uname -r) with the one you compiled</p><pre>$ update-grub2 # make sure you&#39;re using the grub bootloader<br>$ make modules_install<br>$ make install</pre><p>When booting up, press and hold &lt;Shift&gt; to go to the grub menu, then go to advanced options to select the kernel you want to boot with.</p><h3>Minimizing the Kernel Size</h3><p>Let’s try to compile a kernel that is as small as possible.</p><h3>Measuring Size</h3><p>The kernel size can be determined using</p><pre>$ ls -lh vmlinux<br>-rwxr-xr-x 1 tch tch 1.1G Jan 31 16:19 vmlinux</pre><p>In this case, I will measure the size of vmlinux instead of vmlinuz since compression is cheating.</p><p>Using the default, we get a size of 1103946480 or 1.1G.</p><h3>My Personal Best</h3><p>I managed to get it down to 51M with <a href="https://tch1001.github.io/downloads/minimal.config">this</a> config.</p><pre>ls -lh vmlinux<br>-rwxrwxr-x 1 tch tch 51M Feb  4 11:49 vmlinux</pre><p>Theoretically it should be able to get down to around 10M as that is what I saw on some embedded linux forums. But I have other projects on hand that require my immediate attention, I’ll come back to it one day…</p><h3>Happy Coding!</h3><p>If you run into any errors, you may drop me a text on telegram!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bfc45a991017" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting Up SSL Manually on Kubernetes Traefik: ACME DNS Challenge]]></title>
            <link>https://medium.com/@chienhaotan/test-78eeb72cc22c?source=rss-c8144e286ba4------2</link>
            <guid isPermaLink="false">https://medium.com/p/78eeb72cc22c</guid>
            <category><![CDATA[acme]]></category>
            <category><![CDATA[https]]></category>
            <category><![CDATA[httpscertificate]]></category>
            <category><![CDATA[ssl-certificate]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Chien Hao Tan]]></dc:creator>
            <pubDate>Wed, 27 Dec 2023 15:38:10 GMT</pubDate>
            <atom:updated>2023-12-27T15:47:27.197Z</atom:updated>
            <content:encoded><![CDATA[<p>Today, I will show you how to setup SSL on Kubernetes the manual way. I will be using Traefik as the Ingress Controller and Let’s Encrypt as the Certificate Authority.</p><h3>Kubernetes Setup</h3><p>Suppose we have created a service (with accompanying deployment, pods, and all that) called my-service and we want to expose it to the internet.</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: my-deployment<br>spec:<br>  selector:<br>    matchLabels:<br>      app: my-webserver<br>  replicas: 1<br>  template:<br>    metadata:<br>      labels:<br>        app: my-webserver<br>    spec:<br>      containers:<br>      - name: my-container<br>        image: username/my-image<br>        ports:<br>        - containerPort: 8000<br>---<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: my-service<br>spec:<br>  selector:<br>    app: my-webserver<br>  ports:<br>    - protocol: TCP<br>      port: 80<br>      targetPort: 8000<br>#      nodePort: 30002<br>  type: ClusterIP</pre><p>We can expose it to the internet by creating an IngressRoute resource. (<strong>Note</strong>: This is not the final version)</p><pre>apiVersion: traefik.containo.us/v1alpha1<br>kind: IngressRoute<br>metadata:<br>  name: my-ingressroute<br>spec:<br>  entryPoints:<br>    - websecure<br>  routes:<br>    - match: Host(`my.domain.com`)<br>      priority: 1000<br>      kind: Rule<br>      services:<br>        - name: my-service<br>          port: 80<br>          namespace: my-namespace</pre><p>Then over on your DNS provider, you just need to point my.domain.com to your <em>Traefik</em> Service’s External IP address, which you can obtain using</p><pre>&gt; kubectl get svc -A # -A for all namespaces<br>NAME         TYPE          CLUSTER-IP       EXTERNAL-IP       PORT(S)                   AGE<br>traefik      LoadBalancer  10.245.211.251   137.184.250.51    80/TCP,8080/TCP,443/TCP   20d<br>my-service   ClusterIP     10.245.210.243   &lt;none&gt;            80/TCP                    20d</pre><p>Traefik will point to my-service through the IngressRoute, and you can check the ingressroutes by going to http://&lt;traefik-service-ip&gt;:8080/dashboard/#/http/routers. After adding a DNS record (<strong>note</strong>: use DNS only first (if you’re using Cloudflare), we will get to SSL later)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Wj7s93ORuC2-9Eu8.png" /></figure><p>Going to http://my.domain.com will show you the website (note the <strong>http</strong>, we have not setup SSL yet).</p><h3>Setting up SSL</h3><p>There are 2 different ways I will cover. The first being significantly easier but not without some drawbacks.</p><h3>Bless Cloudflare (Flexible SSL)</h3><p>If you’re using cloudflare, you’re in luck, because you just need to use “Proxied” instead of “DNS only” and you’re done.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Wyt32Ia-ork2QXDZ.png" /></figure><p><strong>Note</strong>: If you run into errors, chances are that caching is the issue. I haven’t figured out where this caching occurs exactly. What I do is just create a <em>new</em> record, using a different domain name (e.g. my.domain.com and my2.domain.com).</p><p>This is known as a “Flexible SSL Setup”, where the SSL is terminated at Cloudflare’s edge servers. This means that the traffic between the browser and Cloudflare is encrypted, but the traffic between Cloudflare and your site is not. This is okay for non-security-critical applications like blogs, but is not okay for things that require sensitive traffic like login credentials.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*N6xfPofNbqmky504.png" /></figure><p>This is the easiest way to setup SSL, but another drawback is you will not be able to use HTTP/2, which is a newer version of HTTP that is much faster than HTTP/1.1. This is because Cloudflare does not support HTTP/2 for Flexible SSL. If you want to use HTTP/2, you will need to use a different method.</p><p>One upside is that using “Proxied” will hide your server’s IP address (increased security), and you can check this by running</p><pre>&gt; ping my2.domain.com<br>PING my2.domain.com (104.21.39.182): 56 data bytes<br>64 bytes from 104.21.39.182: icmp_seq=0 ttl=49 time=84.412 ms</pre><p>104.21.39.182 is not my IP! It is Cloudflare’s IP.</p><h3>Certbot SSL Setup</h3><p>If you want to use “DNS only” and still have SSL, or you want “Proxied” with Full encryption mode, you need to create a certificate using <a href="https://certbot.eff.org/">Certbot</a>. Certbot is a free, open-source tool for automatically using Let’s Encrypt certificates on manually-configured HTTPS servers.</p><p>Usually, people use certbot because it’s very automatic, but in this case I have chosen to manually obtain my certificates and upload it because I want to learn how it works, and have greater control over the process. I have found that when I try to do it automatically using Traefik, there is a lot of fiddling and restarting the services, possibly resulting in downtime. Through the manual method, you don’t need to touch the my-service Service, and just need to update the IngressRoutes.</p><p>First, you need to install certbot. After that you can run</p><pre>sudo certbot certonly --manual --preferred-challenge dns -d my3.domain.com</pre><ul><li>--manual is required if we want to use the DNS acme challenge.</li><li>-d my3.domain.com indicates the domain (leaving it out will prompt you to input it manually).</li></ul><p>You will see something like</p><pre>Please deploy a DNS TXT record under the name:<br>_acme-challenge.my3.domain.com<br>with the following value:<br>NaeXRxo_oQnpUzeZQ1xj3mhSGaAJ_NXN0wTcOo-_wdA</pre><pre>Before continuing, verify the TXT record has been deployed. Depending on the DNS<br>provider, this may take some time, from a few seconds to multiple minutes. You can<br>check if it has finished deploying with aid of online tools, such as the Google<br>Admin Toolbox: <a href="https://toolbox.googleapps.com/apps/dig/#TXT/_acme-challenge.my3.domain.com.">https://toolbox.googleapps.com/apps/dig/#TXT/_acme-challenge.my3.domain.com.</a><br>Look for one or more bolded line(s) below the line &#39;;ANSWER&#39;. It should show the<br>value(s) you&#39;ve just added.</pre><pre>Press Enter to Continue</pre><p>You need to create a TXT record with the value NaeXRxo_oQnpUzeZQ1xj3mhSGaAJ_NXN0wTcOo-_wdA under _acme-challenge.my3.domain.com. Then check using Google Admin Toolbox (<a href="https://toolbox.googleapps.com/apps/dig/#TXT/_acme-challenge.my3.domain.com.">https://toolbox.googleapps.com/apps/dig/#TXT/_acme-challenge.my3.domain.com.</a>) whether the TXT record is up. If it is, then press Enter</p><pre>Successfully received certificate.<br>Certificate is saved at: /etc/letsencrypt/live/my3.domain.com/fullchain.pem<br>Key is saved at:         /etc/letsencrypt/live/my3.domain.com/privkey.pem<br>This certificate expires on 2023-06-04.<br>These files will be updated when the certificate renews.</pre><p>Now we need to upload it to Kubernetes and let IngressRoute access it. This is done via <a href="https://kubernetes.io/docs/concepts/configuration/secret/">Secrets</a>.</p><pre>mkdir certs<br>sudo cat /etc/letsencrypt/live/my3.domain.com/fullchain.pem &gt; certs/fullchain.pem<br>sudo cat /etc/letsencrypt/live/my3.domain.com/privkey.pem &gt; certs/privkey.pem<br># do the above if you can&#39;t access /etc<br>sudo kubectl create secret generic my-secret \<br>    --from-file=tls.crt=/etc/letsencrypt/live/my3.domain.com/fullchain.pem \<br>    --from-file=tls.key=/etc/letsencrypt/live/my3.domain.com/privkey.pem</pre><p>All that remains is to update the IngressRoute.</p><pre>apiVersion: traefik.containo.us/v1alpha1<br>kind: IngressRoute<br>metadata:<br>  name: my-ingressroute<br>spec:<br>  entryPoints:<br>    - websecure<br>  routes:<br>    - match: Host(`my3.domain.com`)<br>      priority: 1000<br>      kind: Rule<br>      services:<br>        - name: my-service<br>          port: 80<br>          namespace: my-namespace<br>  tls:<br>    secretName: my-secret<br>    domains:<br>    - main: my3.domain.com<br>      sans:<br>      - blah.com</pre><p>The Host(`my.domain.com`) changed to Host(`my3.domain.com`) and added part is</p><pre>tls:<br>    secretName: my-secret<br>    domains:<br>    - main: my3.domain.com<br>      sans:<br>      - blah.com</pre><p>Now add the DNS record for my3.domain.com, change your encryption mode to “Full” and visit the site and all should be good!</p><p>SANS is just alternative DNS names.</p><h3>Setting HTTP redirection to HTTPS</h3><p>Great so now if you visit the site https://my3.domain.com you get a nicely secured site! But if you visit http://my3.domain.com you get 404 error. Oh no. The fix is simple, simply create another IngressRoute that accepts the - web entrypoint, and use a redirection middleware.</p><pre>apiVersion: traefik.containo.us/v1alpha1<br>kind: Middleware<br>metadata:<br>  name: redirection-middleware<br>spec:<br>  redirectScheme:<br>    scheme: https<br>---<br>apiVersion: traefik.containo.us/v1alpha1<br>kind: IngressRoute<br>metadata:<br>  name: my-ingressroute-no-tls<br>spec:<br>  entryPoints:<br>    - web<br>  routes:<br>    - match: Host(`my3.domain.com`)<br>      priority: 1000<br>      middlewares:<br>        - name: redirection-middleware<br>      kind: Rule<br>      services:<br>        - name: my-service<br>          port: 80<br>          namespace: my-namespace</pre><h3>Common errors</h3><h3>Too many redirects</h3><p>Most likely your SSL encryption mode is “Off” in Cloudflare.</p><h3>404</h3><p>Most likely your SSL encryption mode is “Flexible”. Cloudflare is trying to access the non-SSL version of your site while your site is forcing it to use SSL (redirecting it to https, which confuses Cloudflare).</p><h3>502 Bad Gateway</h3><p>It could also be that your encryption mode is “Full” or “Full (Strict)” but the SSL on your Kubernetes Traefik end is not setup properly. Cloudflare is trying to establish an encrypted connection with Traefik but Traefik can’t provide one. Check that your Service is running too (can be done using NodePort on Kubernetes, or port-forward tunneling).</p><h3>Still not working :(</h3><p>Try setting up on a different domain name. I know that’s dumb but it seems like either the browser or some intermediate server along the way has cached the SSL settings. In other words, when working with SSL, you either get it the first time round or you never get it (because updating the configs don’t seem to affect much).</p><p>What I do personally is try out a bunch of test domains first, before finding out the process that works for the actual one.</p><h3>Renewing</h3><p>By manual provisioning method, the certificates will not auto-renew. I will write another blog on this when I have time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78eeb72cc22c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>