<?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 Devrim Şahin on Medium]]></title>
        <description><![CDATA[Stories by Devrim Şahin on Medium]]></description>
        <link>https://medium.com/@kubuzetto?source=rss-d31bef4f742c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*IauGoFCHTctK86UDdflDRg.png</url>
            <title>Stories by Devrim Şahin on Medium</title>
            <link>https://medium.com/@kubuzetto?source=rss-d31bef4f742c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 15:21:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kubuzetto/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[Running concurrent jobs with ordered results]]></title>
            <link>https://medium.com/picus-security-engineering/running-concurrent-jobs-with-ordered-results-53ccd932c86b?source=rss-d31bef4f742c------2</link>
            <guid isPermaLink="false">https://medium.com/p/53ccd932c86b</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[concurrency]]></category>
            <dc:creator><![CDATA[Devrim Şahin]]></dc:creator>
            <pubDate>Mon, 19 Jun 2023 06:40:34 GMT</pubDate>
            <atom:updated>2023-06-19T06:40:34.952Z</atom:updated>
            <content:encoded><![CDATA[<h4>A peek into different execution models using a common pattern</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jiAzQ_Xs378g23fY6h5vuQ.png" /></figure><h3>Introduction</h3><p>In this post, we will discuss a pattern that keeps showing up in many concurrency problems. We will then consider some solutions to it in three different programming languages, namely <strong>Go</strong>, <strong>Rust</strong> and <strong>Java</strong>; hoping to provide some variety given how each provide different paradigms and execution models.</p><p>In <a href="https://www.picussecurity.com/">Picus Security</a>, we develop an automated security control validation platform. To measure the effectiveness of security controls and processes, we employ an <em>agent</em>; which is a client application that runs <em>actions</em> in order to validate the organization’s security posture.</p><p>For most cases, individual actions are independent of one another; so they can be run concurrently. However, the action <strong>order</strong> must be preserved during result calculation. Therefore, we want to run <strong>concurrent jobs,</strong> but retain the <strong>order of their outputs.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4UWwY5lq5CA7ZxyqJ62iKA.png" /><figcaption>Concurrent jobs with ordered results. Rectangles are jobs, squares are the results being handled. Horizontal axis is time.</figcaption></figure><p>The figure above shows four concurrent jobs spawned in quick succession. The squares at the end depict their results being handled. Note that even though <strong>Job3</strong> ends earlier than <strong>Job2</strong>, its result is not processed until <strong>Job2</strong>’s result is handled. In other words, each job’s result is<em> causally dependent</em> on not only the job itself, but also the previous job’s result.</p><p>This is a common pattern that keeps showing up in concurrent programming. <strong>Here’s another example:</strong></p><p>Imagine we were writing a distributed <a href="https://en.wikipedia.org/wiki/Actor_model">actor framework</a> (In short, an actor is a <em>concurrent</em> unit of execution, that receives <em>messages</em> and processes them <em>sequentially</em>). The messages to hit the “mailbox” (the input message queue of the actor) should first get <strong>deserialized</strong> (because they were sent over the wire), then the deserialized messages should be handled <strong>sequentially</strong> by the actor’s logic.</p><p>We prototype it and find out that the deserialization logic is so slow that it’s the bottleneck for the actor’s performance. We decide to <em>concurrently</em> deserialize the messages, since each can be deserialized independent of the others. However, we <strong>must not </strong>lose the order of messages. It’s the same problem.</p><p>One thing is different, though: In the latter example we don’t have an <em>array</em> of jobs handed to us at the beginning, but a <em>stream</em> of them that keeps coming, potentially indefinitely. For the agent case we could just decide to be lazy and wait for <em>all </em>results to be available before processing them (i.e. <strong>join()</strong>ing the jobs). For the actor example, that’s not possible because the messages keep flowing. So we must immediately start working on the next result as soon as it is available.</p><h3>Go</h3><p>Let’s implement this ‘concurrent jobs, ordered results’ pattern for different assumptions, in increasing complexity.</p><h4>Fixed number of jobs</h4><p>Let’s start with a very trivial case: The number of jobs to execute is known to us <strong>at the time of programming</strong>. For example, let’s say that we want to implement a very simple program that will execute <strong>exactly 3</strong> long-running calculations:</p><ul><li>Count the number of stars in the universe,</li><li>Count the number of grains of sand on Earth,</li><li>Calculate the answer to the ultimate question about life, universe and everything.</li></ul><p>We will then print their results in this specific order.</p><p>Let’s implement the jobs in Go first. Let’s also print the elapsed time in the beginning and end of each function, so that we can analyze the logs more easily:</p><pre>var startTime = time.Now()<br><br>func elapsed() int64 {<br>  return time.Now().Sub(startTime).Milliseconds() / 1000<br>}<br><br>func countStars() int64 {<br>  fmt.Printf(&quot;[%d] countStars(job0) STARTED\n&quot;, elapsed())<br>  time.Sleep(2 * time.Second)<br>  fmt.Printf(&quot;[%d] countStars(job0) DONE\n&quot;, elapsed())<br>  return 1 &lt;&lt; 62 // real number is much much higher by the way<br>}<br><br>func countGrainsOfSandOnEarth() int64 {<br>  fmt.Printf(&quot;[%d] countGrainsOfSandOnEarth(job1) STARTED\n&quot;, elapsed())<br>  time.Sleep(time.Second)<br>  fmt.Printf(&quot;[%d] countGrainsOfSandOnEarth(job1) DONE\n&quot;, elapsed())<br>  return 7.5e18<br>}<br><br>func meaningOfLife() int64 {<br>  fmt.Printf(&quot;[%d] meaningOfLife(job2) STARTED\n&quot;, elapsed())<br>  time.Sleep(3 * time.Second)<br>  fmt.Printf(&quot;[%d] meaningOfLife(job2) DONE\n&quot;, elapsed())<br>  return 42<br>}</pre><p>We want each of these functions to run concurrently. Go provides concurrency through <strong>goroutines</strong>, which are basically green threads scheduled in user space. Goroutines then communicate by passing values through <strong>channels</strong>. We want each long-running job to run in its own goroutine, then return the result through a channel. We can implement a helper function for that:</p><pre>func runInGoroutine[T any](longRunning func() T) &lt;-chan T {<br>  // result will be written on this channel<br>  future := make(chan T, 1)<br>  // long-running job is run in a goroutine<br>  go func() {<br>    // once result is obtained, it&#39;s sent to the channel<br>    future &lt;- longRunning()<br>  }()<br>  // we spawn the goroutine and return the channel<br>  return future<br>}</pre><p>This function returns a channel with a buffer of <strong>1</strong>. We are basically using the channel as a <strong>future</strong> here (granted, it’s the bare minimum to be called a ‘future’, but it does the job for now). Since Go’s goroutines sidestep all the <a href="https://journal.stuffwithstuff.com/2015/02/01/what-color-is-your-function/">“red function/blue function”</a> concept, we can simply block on these values like we used to do with actual OS-level threads in The Olden Days™, when an average server didn’t have to handle gazillion concurrent requests:</p><pre>func main() {<br>  // spawn concurrent tasks<br>  numStarsFut := runInGoroutine(countStars)<br>  numGrainsFut := runInGoroutine(countGrainsOfSandOnEarth)<br>  meaningFut := runInGoroutine(meaningOfLife)<br>  // await results in order<br>  numStars := &lt;-numStarsFut<br>  fmt.Printf(&quot;[%d] result of job #0: %d\n&quot;, elapsed(), numStars)<br>  numGrains := &lt;-numGrainsFut<br>  fmt.Printf(&quot;[%d] result of job #1: %d\n&quot;, elapsed(), numGrains)<br>  meaning := &lt;-meaningFut<br>  fmt.Printf(&quot;[%d] result of job #2: %d\n&quot;, elapsed(), meaning)<br>}</pre><p><em>(Examples in this blog post avoid handling errors, exceptions, panics etc. for the sake of simplicity.)</em></p><p>After we spawn three goroutines that execute the long-running computations, we start blocking on the results by reading from their respective channels.</p><p>Here is the output of the program:</p><pre>[0] meaningOfLife(job2) STARTED<br>[0] countGrainsOfSandOnEarth(job1) STARTED<br>[0] countStars(job0) STARTED<br>[1] countGrainsOfSandOnEarth(job1) DONE<br>[2] countStars(job0) DONE<br>[2] result of job #0: 4611686018427387904<br>[2] result of job #1: 7500000000000000000<br>[3] meaningOfLife(job2) DONE<br>[3] result of job #2: 42</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cwi_c9AolMGS35oblmDRwg.png" /><figcaption>Output of the program, plotted</figcaption></figure><p>Several things to note here:</p><ul><li>We don’t wait for <strong>all</strong> results to complete. <strong>Job0</strong> is completed in 2 seconds, and by that time <strong>Job1</strong>’s result is also available; so we print the results of both <strong>Job0</strong> and <strong>Job1</strong> in second 2. Third result is printed one second later, when it is also available. If we had waited for all tasks to join, we’d have printed everything in the 3rd second.</li><li>We print the results in order. If the <em>Printf</em> statements were instead at the end of the long-running functions, the second one could be printed first at second 1. In our example, <strong>this order never changes.</strong></li></ul><h4>Array of jobs</h4><p>What if we don’t get to hard-code the jobs, but receive a dynamic (but finite) number of them? Like an <em>array</em> of jobs? Well, we can easily extend the Go channel approach to accomodate:</p><pre>func main() {<br>  // array of jobs<br>  jobs := []func() int64{<br>    countStars, countGrainsOfSandOnEarth, meaningOfLife,<br>  }<br>  // spawn concurrent tasks, store future results in order<br>  orderedFutures := make([]&lt;-chan int64, len(jobs))<br>  for idx, job := range jobs {<br>    orderedFutures[idx] = runInGoroutine(job)<br>  }<br>  // await results in order<br>  for idx, future := range orderedFutures {<br>    // (do this in two lines so that elapsed time is logged correctly)<br>    value := &lt;-future<br>    fmt.Printf(&quot;[%d] result of job #%d: %d\n&quot;, elapsed(), idx, value)<br>  }<br>}</pre><p>We start all long-running functions concurrently, and store the <strong>futures</strong> in an array. As each task runs to completion, they send their results into the respective 1-sized channel; then we iterate the array of futures in order. This gives us the exact same output:</p><pre>[0] meaningOfLife(job2) STARTED<br>[0] countStars(job0) STARTED<br>[0] countGrainsOfSandOnEarth(job1) STARTED<br>[1] countGrainsOfSandOnEarth(job1) DONE<br>[2] countStars(job0) DONE<br>[2] result of job #0: 4611686018427387904<br>[2] result of job #1: 7500000000000000000<br>[3] meaningOfLife(job2) DONE<br>[3] result of job #2: 42</pre><h4>Stream of jobs</h4><p>What if the number of futures wasn’t finite? What if we had a <em>stream </em>of long-running jobs, and we had to handle their results while preserving order, like in the actor example? In that case, we cannot use an array; we’d need a <em>channel </em>of futures… A channel of channels!</p><p>We should implement a helper here; so that we can consume the stream of <em>futures</em> and turn it into a stream of <em>values:</em></p><pre>func processSequentially[T any](futStream &lt;-chan &lt;-chan T) &lt;-chan T {<br>  // output stream (of values)<br>  output := make(chan T, 1)<br>  go func() {<br>    // iterate each future in the input<br>    for fut := range futStream {<br>      // block until the next result is ready;<br>      // then push it to the output channel<br>      output &lt;- &lt;-fut // ***<br>    }<br>    // if we got here, futStream is closed.<br>    // also close the output and exit goroutine<br>    close(output)<br>  }()<br>  return output<br>}</pre><p>This function spawns its own goroutine which blocks on the head of the future stream (the future on the front). Once the future is resolved, it emits the result and blocks on the next.</p><p>The line marked with <strong>***</strong> can be expanded like this:</p><pre>// block on the future to get the value<br>value := &lt;-fut<br>// send the value to the output channel<br>output &lt;- value</pre><p>Let’s use the helper function to process a stream of jobs:</p><pre>func main() {<br>  futStream := make(chan (&lt;-chan int64), 1)<br>  orderedOutputs := processSequentially(futStream)<br>  // start spawning concurrent tasks, and pushing their futures to the stream<br>  futStream &lt;- runInGoroutine(countStars)<br>  futStream &lt;- runInGoroutine(countGrainsOfSandOnEarth)<br>  futStream &lt;- runInGoroutine(meaningOfLife)<br>  close(futStream)<br>  // the &#39;handler&#39; part<br>  jobIdx := 0<br>  for output := range orderedOutputs {<br>    fmt.Printf(&quot;[%d] result of job #%d: %d\n&quot;, elapsed(), jobIdx, output)<br>    jobIdx++<br>  }<br>}</pre><p>We push the spawned jobs’ futures into the <strong>futStream</strong>, which <strong>processSequentially</strong> blocks on and converts to a stream of results. We then iterate on the output in the handler part to write the results. The output is the same.</p><h3>Rust</h3><p>Let’s work on a Rust equivalent. Unlike Go, Rust employs an opt-in async/await model instead of a user-level scheduler that comes with the runtime. You get to choose the async runtime among many libraries, and for this blog post we use <a href="https://crates.io/crates/tokio"><strong><em>tokio</em></strong></a>. We also grab the <a href="https://crates.io/crates/futures"><strong><em>futures</em></strong></a> library for some very useful async building blocks:</p><pre># add to Cargo.toml<br>[dependencies]<br>futures = &quot;0.3.28&quot;<br>tokio = { version = &quot;1.28.0&quot;, features = [&quot;full&quot;] }</pre><p>Here are the jobs:</p><pre>use std::time::{Duration, Instant};<br>use tokio::time::sleep;<br><br>async fn count_stars(start: Instant) -&gt; u64 {<br>  println!(&quot;[{}] countStars(job0) STARTED&quot;, start.elapsed().as_secs());<br>  sleep(Duration::from_secs(2)).await;<br>  println!(&quot;[{}] countStars(job0) DONE&quot;, start.elapsed().as_secs());<br>  1u64 &lt;&lt; 62<br>}<br><br>async fn count_grains_of_sand_on_earth(start: Instant) -&gt; u64 {<br>  println!(&quot;[{}] countGrainsOfSandOnEarth(job1) STARTED&quot;, start.elapsed().as_secs());<br>  sleep(Duration::from_secs(1)).await;<br>  println!(&quot;[{}] countGrainsOfSandOnEarth(job1) DONE&quot;, start.elapsed().as_secs());<br>  7.5e18 as u64<br>}<br><br>async fn meaning_of_life(start: Instant) -&gt; u64 {<br>  println!(&quot;[{}] meaningOfLife(job2) STARTED&quot;, start.elapsed().as_secs());<br>  sleep(Duration::from_secs(3)).await;<br>  println!(&quot;[{}] meaningOfLife(job2) DONE&quot;, start.elapsed().as_secs());<br>  42<br>}</pre><p>Note that each of the long-running functions are defined as <strong><em>async fn</em></strong>. Instead of blocking on a channel; we will call <strong>.await</strong> on the outputs of these functions. Also note that the <strong>sleep</strong> function is that of the <em>tokio</em> framework, instead of the <em>std</em> version; so that we don’t block the whole OS thread as we sleep.</p><p>Let’s start with the fixed-number-of-jobs case. If we implement the main function like this…</p><pre>// WARNING: this code is WRONG intentionally! keep reading...<br>#[tokio::main]<br>async fn main() {<br>  let start = Instant::now();<br>  // start both calculations concurrently<br>  let num_stars = count_stars(start);<br>  let num_grains = count_grains_of_sand_on_earth(start);<br>  let meaning = meaning_of_life(start);<br>  // first result is received<br>  let num_stars = num_stars.await;<br>  println!(&quot;[{}] result of job #0: {}&quot;, start.elapsed().as_secs(), num_stars);<br>  // second result is received<br>  let num_grains = num_grains.await;<br>  println!(&quot;[{}] result of job #1: {}&quot;, start.elapsed().as_secs(), num_grains);<br>  // third result is received<br>  let meaning = meaning.await;<br>  println!(&quot;[{}] result of job #2: {}&quot;, start.elapsed().as_secs(), meaning);<br>}</pre><p>…here is the output:</p><pre>[0] countStars(job0) STARTED<br>[2] countStars(job0) DONE<br>[2] result of job #0: 4611686018427387904<br>[2] countGrainsOfSandOnEarth(job1) STARTED<br>[3] countGrainsOfSandOnEarth(job1) DONE<br>[3] result of job #1: 7500000000000000000<br>[3] meaningOfLife(job2) STARTED<br>[6] meaningOfLife(job2) DONE<br>[6] result of job #2: 42</pre><p>It’s the same ou- wait. WAIT. <strong>Everything ran sequentially!</strong> This is NOT what we were trying to do!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aS0vIxGSN7ZI5z7awiFx9w.png" /><figcaption>Jobs running sequentially</figcaption></figure><p>Ha, gotcha. Rust’s async model is special: In most languages, you would expect the async task to start executing immediately when invoked. Rust’s async is <strong>poll-based</strong>, therefore futures <a href="https://rust-lang.github.io/async-book/06_multiple_futures/02_join.html">won’t do any work</a> until actively <strong><em>await</em></strong>ed. <a href="https://tokio.rs/tokio/tutorial/async">Tokio</a> has a fantastic tutorial summarizing what ‘poll-based’ means here, and how async/await and Futures work in Rust.</p><p>OK, interesting; but we still want to achieve the ‘concurrent run, ordered result’ behavior. How do we do that?</p><p>For that, we would need to implement a <em>combinator.</em></p><h4>A primer to Futures and Streams</h4><p>A quick-and-dirty crash course, then. Rust has two traits that provide the async behavior: <a href="https://doc.rust-lang.org/std/future/trait.Future.html"><strong>Future</strong></a> and <a href="https://docs.rs/futures/latest/futures/stream/trait.Stream.html"><strong>Stream</strong></a>. <strong>Future</strong> asynchronously returns <em>one</em> result, and <strong>Stream</strong> can yield multiple. Since we want to receive the results of each future one by one; we want to implement a stream combinator.</p><pre>// (simplified)<br>pub trait Future {<br>  type Output;<br>  fn poll(self: Pin&lt;&amp;mut Self&gt;, cx: &amp;mut Context&lt;&#39;_&gt;) -&gt; Poll&lt;Self::Output&gt;;<br>}<br><br>// (simplified)<br>pub trait Stream {<br>  type Item;<br>  fn poll_next(self: Pin&lt;&amp;mut Self&gt;, cx: &amp;mut Context&lt;&#39;_&gt;) -&gt; Poll&lt;Option&lt;Self::Item&gt;&gt;;<br>}</pre><p>We check if a Future is completed by calling <strong>poll</strong>. If the value is ready, the Future returns <strong>Poll::Ready(<em>value</em>)</strong>, otherwise it returns <strong>Poll::Pending</strong>. A Future that returned Ready should not be called again. <strong><em>A Future does nothing unless poll is called repeatedly.</em></strong></p><p>Similarly for the Stream, we call <strong>poll_next()</strong>, if the result is <strong>Poll::Pending </strong>we must poll again later. <strong>Poll::Ready(Some(value))</strong> indicates that the next result is yielded, <strong>Poll::Ready(None)</strong> indicates that the stream is exhausted. Like Future, Stream should also be repeatedly polled to do work.</p><p>Who polls these async blocks then? That would be the <em>executor</em>; in our case <strong>tokio</strong>. For simplicity, we can say that the <strong>.await</strong> expression triggers the polling of a Future.</p><p>How frequently the executor polls a future is a <em>whole</em> other discussion. To prevent busy polling, Rust futures employs a very clever callback mechanism called <a href="https://doc.rust-lang.org/std/task/struct.Waker.html"><strong>Waker</strong></a><strong>,</strong> which is why there is a<a href="https://doc.rust-lang.org/std/task/struct.Context.html"> <strong>Context</strong></a><strong> </strong>parameter in the signature there. It’s out of scope for this blog post, but check that out some time; it’s very elegant.</p><h4>Our own Stream combinator</h4><p>Instead of defining a new <strong>Stream</strong> type ourselves; we can get lazy and inline our combinator using the <strong>futures::stream::poll_fn</strong> helper, which receives the body of <strong>poll_next</strong> as a <em>closure</em> and returns a stream combinator type:</p><pre>use std::task::Poll;<br>use futures::stream::poll_fn;<br>use futures::task::Context;<br><br>// &#39;futures&#39; is an anonymous type that implements Stream<br>let mut futures = poll_fn(move |cx: &amp;mut Context&lt;&#39;_&gt;| -&gt; Poll&lt;Option&lt;u64&gt;&gt; {<br>  // empty stream; directly returns &#39;None&#39;<br>  Poll::Ready(None)<br>}</pre><p>Let’s think about this for a second… We have a bunch of Futures; and to do any work, each of these Futures must be repeatedly polled. We are trying to consume the output of a Stream, which means that the executor will be polling the Stream. So whenever the Stream is polled; that’s when all its Futures should be polled. Then we should call each Future’s <strong>poll </strong>in our Stream’s <strong>poll_next</strong> function!</p><p>Keep in mind though, that we don’t want to keep polling any finished <strong>Future</strong>s: calling <strong>poll()</strong> <em>twice</em> on a completed Future violates its contract. So we must also keep track of completed Futures, and store their values somewhere. If we keep the Futures in an array (“<strong>futs</strong>”), and their results in another (“<strong>out</strong>”), we can keep track of completed Futures. Similarly, since we want to yield results one by one and in order; we should keep track of the next <strong>Future</strong>’s index (“<strong>next_job_idx</strong>”). Put together, something like the following should work for our case:</p><pre>use std::task::Poll;<br>use futures::stream::poll_fn;<br>use futures::task::Context;<br>use futures::{FutureExt, StreamExt};<br><br>#[tokio::main]<br>async fn main() {<br>  let start = Instant::now();<br>  let mut futs = vec![<br>    // the call to &#39;boxed&#39; is necessary because each function&#39;s<br>    // returned Future impl. is a different type. boxing it<br>    // makes the type dynamic (BoxFuture), and lets us put all<br>    // these futures in a Vec like this.<br>    count_stars(start).boxed(),<br>    count_grains_of_sand_on_earth(start).boxed(),<br>    meaning_of_life(start).boxed(),<br>  ];<br><br>  // index of the job we should be waiting on<br>  let mut next_job_idx = 0;<br>  // store completed results here. incomplete results are None<br>  let mut out = vec![None; futs.len()];<br>  // the &#39;futures&#39; variable implements the Stream trait<br>  let mut futures = poll_fn(move |cx: &amp;mut Context&lt;&#39;_&gt;| -&gt; Poll&lt;Option&lt;u64&gt;&gt; {<br>    // inside of the Stream&#39;s poll_next function. this closure<br>    // will be called multiple times, until it returns Poll::Ready(None).<br><br>    // if all jobs are complete; return Ready(None)<br>    // to indicate end of stream<br>    if next_job_idx &gt;= out.len() {<br>      return Poll::Ready(None);<br>    }<br><br>    // otherwise iterate all results<br>    for (i, o) in out.iter_mut().enumerate() {<br>      // for each *missing* result only...<br>      if o.is_none() {<br>        // ...poll the future that corresponds<br>        // (this is where the jobs do some work)<br>        if let Poll::Ready(v) = futs[i].as_mut().poll(cx) {<br>          // the future completed! save the result,<br>          // we won&#39;t call this future anymore<br>          *o = Some(v)<br>        }<br>      }<br>    }<br><br>    // now that all active futures are polled,<br>    // check out the job in next_job_idx<br>    match out.get_mut(next_job_idx) {<br>      // if the job is complete<br>      Some(Some(v)) =&gt; {<br>        // yield the result and move to the next<br>        next_job_idx += 1;<br>        Poll::Ready(Some(*v))<br>      }<br>      // otherwise tell that we&#39;re pending<br>      _ =&gt; Poll::Pending,<br>    }<br><br>  });<br><br>  // result handler part<br>  let mut idx = 0;<br>  while let Some(value) = futures.next().await {<br>    println!(&quot;[{}] result of job #{}: {}&quot;,<br>             start.elapsed().as_secs(), idx, value);<br>    idx += 1;<br>  }<br>}</pre><p><strong>…yeah.</strong> Implementing combinators by hand like this can get really complicated, and ours isn’t even a <em>good</em> implementation. Here’s the output though!</p><pre>[0] countStars(job0) STARTED<br>[0] countGrainsOfSandOnEarth(job1) STARTED<br>[0] meaningOfLife(job2) STARTED<br>[1] countGrainsOfSandOnEarth(job1) DONE<br>[2] countStars(job0) DONE<br>[2] result of job #0: 4611686018427387904<br>[2] result of job #1: 7500000000000000000<br>[3] meaningOfLife(job2) DONE<br>[3] result of job #2: 42</pre><p>Finally we get ordered results for concurrently running jobs!</p><h4>Fresh out of the oven</h4><p>Now, we implemented the combinator ourselves, because we wanted to see how things work. Luckily, we don’t normally have to implement these things by hand: It has been implemented for us. Enter <a href="https://docs.rs/futures/latest/futures/stream/struct.FuturesOrdered.html"><strong><em>FuturesOrdered</em></strong></a>:</p><pre>use futures::{FutureExt, StreamExt};<br>use futures::stream::FuturesOrdered;<br><br>#[tokio::main]<br>async fn main() {<br>  let start = Instant::now();<br>  // we simply push async jobs into FuturesOrdered<br>  let mut futures = FuturesOrdered::new();<br>  futures.push_back(count_stars(start).boxed());<br>  futures.push_back(count_grains_of_sand_on_earth(start).boxed());<br>  futures.push_back(meaning_of_life(start).boxed());<br><br>  // result handler part is the same<br>  let mut idx = 0;<br>  while let Some(value) = futures.next().await {<br>    println!(&quot;[{}] result of job #{}: {}&quot;,<br>             start.elapsed().as_secs(), idx, value);<br>    idx += 1;<br>  }<br>}</pre><p>This combinator gives us <strong>exactly </strong>the kind of behavior we need from our program with only a few lines of code! The async ecosystem in Rust is filled with such useful building blocks. The implementation of <strong>FuturesOrdered</strong> is quite sophisticated.</p><p>We can probably use it for the ‘streaming jobs’ case as well without changing anything.</p><h4>Can we, though?</h4><p><strong><em>Well, we don’t know yet, and we really should check.</em></strong> Here is a scenario specific to the streaming case: What if there is a point in time where some jobs are <strong>not yet queued,</strong> but the ones that <em>are </em>queued are<strong> already completed</strong>?</p><p>Imagine the actor implementation scenario, where the actor receives a message every second. Most of these poll_next calls will encounter an empty <strong>Stream.</strong> What then?</p><p>In all examples so far, we push<em> all futures in advance</em>; so by the time we start handling their results, all futures are in the queue already. But, consider what happens if the third job (<strong>meaning_of_life</strong>) was spawned 10 seconds after the second one. The while-loop in our handler would complete the first two jobs, try to pull the next one; and see that the queue is empty. Would it wait for an extra entry, or would it simply <strong>return</strong>? How would <strong>FuturesOrdered</strong> tell those two cases apart?</p><p>Remember that in the Go example, we <em>explicitly</em> closed our channel using a <strong>close()</strong> call once we were done. The channel of futures blocks forever until it is closed; so it immediately gave us the behavior we wanted.</p><p>In fact, how would we even <strong><em>test</em></strong> this case in Rust? We can’t just slap a 10-second sleep in betweeen two <strong>push_back</strong> calls; because that would also delay the handler. The part where we push futures and the handler part should also take place <strong>concurrently</strong>. We would have to split these two operations into their own async code blocks first:</p><pre>#[tokio::main]<br>async fn main() {<br>  let start = Instant::now();<br>  let mut futures = FuturesOrdered::new();<br>  <br>  // async block to push the futures<br>  let pusher = async {<br>    futures.push_back(count_stars(start).boxed());<br>    futures.push_back(count_grains_of_sand_on_earth(start).boxed());<br>    sleep(Duration::from_secs(10)).await;<br>    futures.push_back(meaning_of_life(start).boxed());<br>  };<br>  <br>  // another async block to handle the results<br>  let handler = async {<br>    // result handler part is the same<br>    let mut idx = 0;<br>    while let Some(value) = futures.next().await {<br>      println!(&quot;[{}] result of job #{}: {}&quot;,<br>               start.elapsed().as_secs(), idx, value);<br>      idx += 1;<br>    }<br>  };<br><br>  // run both blocks concurrently; wait until BOTH are resolved<br>  futures::join!(pusher, handler);<br>}</pre><p>Here we use the <strong>futures::join!</strong> <em>combinator</em> so that we can wait until both blocks are completed. But this simply <strong>won’t compile in Rust</strong>. The reason is that both async blocks are trying to <strong><em>mutably borrow</em></strong> the <strong>FuturesOrdered</strong>. In other words; both async blocks are trying to <strong><em>modify</em></strong> <strong>FuturesOrdered</strong>, which can cause a race condition. Rust won’t allow that.</p><p>In desperation, we slap a <strong>Mutex</strong> on the combinator and start acquiring locks everywhere:</p><pre>use tokio::sync::Mutex;<br>use std::sync::Arc;<br><br>#[tokio::main]<br>async fn main() {<br>  let start = Instant::now();<br><br>  // make two counted, mutex-protected references<br>  // one for read, one for write<br>  let rd = Arc::new(Mutex::new(FuturesOrdered::new()));<br>  let wr = Arc::clone(&amp;rd);<br>  <br>  let pusher = async move {<br>    // each operation briefly gets the lock; pushes a future and releases<br>    wr.lock().await.push_back(count_stars(start).boxed());<br>    wr.lock().await.push_back(count_grains_of_sand_on_earth(start).boxed());<br>    // 10 second wait before the 3rd job<br>    sleep(Duration::from_secs(10)).await;<br>    wr.lock().await.push_back(meaning_of_life(start).boxed());<br>  };<br>  <br>  // another async block that we handle them<br>  let handler = async {<br>    let mut idx = 0;<br>    while let Some(value) = rd.lock().await.next().await {<br>      println!(&quot;[{}] result of job #{}: {}&quot;,<br>               start.elapsed().as_secs(), idx, value);<br>      idx += 1;<br>    }<br>    // so that we can see when the handler loop terminates<br>    println!(&quot;[{}] stream terminated&quot;, start.elapsed().as_secs());<br>  };<br><br>  // concurrently run both blocks and join when BOTH are completed<br>  futures::join!(pusher, handler);<br>}</pre><p>Eugh. There are <em>many</em> ways we could make this code prettier, but we’re trying to keep things short here. The output of this function is:</p><pre>[0] countStars(job0) STARTED<br>[0] countGrainsOfSandOnEarth(job1) STARTED<br>[1] countGrainsOfSandOnEarth(job1) DONE<br>[2] countStars(job0) DONE<br>[2] result of job #0: 4611686018427387904<br>[2] result of job #1: 7500000000000000000<br>[2] stream terminated</pre><p>As we have suspected; <strong>FuturesOrdered</strong> does not wait for the third future to be enqueued. In fact, Job3 is nowhere to be seen: We couldn’t even <strong>run</strong> the job, let alone print its result! (This is because there is no one polling it).</p><p>We will have to handle this case ourselves!</p><p>Let’s not get intimidated; we’ve seen worse while trying to implement a <strong>FuturesOrdered</strong> clone. We can satisfy the <strong>Stream</strong> trait with a custom struct this time. We will wrap <strong>FuturesOrdered</strong> to intervene whenever it returns <strong>Poll::Ready(None)</strong>. If we keep the inner state behind a <strong>Mutex</strong>, that should make things easier:</p><pre>use futures::{FutureExt, Stream};<br>use futures::future::BoxFuture;<br>use futures::stream::FuturesOrdered;<br>use std::task::{Context, Poll};<br>use std::sync::Mutex;<br><br>struct FutOrdForStream&lt;&#39;a, T&gt; (Mutex&lt;InnerState&lt;&#39;a, T&gt;&gt;);<br>struct InnerState&lt;&#39;a, T&gt; {<br>  inner: FuturesOrdered&lt;BoxFuture&lt;&#39;a, T&gt;&gt;,<br>  closed: bool,<br>}<br><br>impl&lt;&#39;a, T&gt; FutOrdForStream&lt;&#39;a, T&gt; {<br>  fn new() -&gt; Self {<br>    Self(Mutex::new(InnerState {<br>      inner: FuturesOrdered::new(), closed: false,<br>    }))<br>  }<br>  fn close_write(&amp;self) {<br>    self.0.lock().unwrap().closed = true;<br>  }<br>  fn push_back&lt;E: Future&lt;Output=T&gt; + Send + &#39;a&gt;(&amp;self, f: E) {<br>    self.0.lock().unwrap().inner.push_back(f.boxed());<br>  }<br>}<br><br>impl&lt;T&gt; Future for &amp;FutOrdForStream&lt;&#39;_, T&gt; {<br>  type Output = Option&lt;T&gt;;<br>  fn poll(self: Pin&lt;&amp;mut Self&gt;, cx: &amp;mut Context&lt;&#39;_&gt;) -&gt; Poll&lt;Self::Output&gt; {<br>    let mut this = self.0.lock().unwrap();<br>    match (Pin::new(&amp;mut this.inner).poll_next(cx), this.closed) {<br>      (Poll::Ready(None), false) =&gt; {<br>        this.inner = FuturesOrdered::new();<br>        Poll::Pending<br>      }<br>      (v, _) =&gt; v,<br>    }<br>  }<br>}</pre><p>With this wrapper we do several things:</p><ul><li>We expose a <strong>close_write</strong> function that allows us to express our intent to end the handler loop.</li><li>Whenever the inner <strong>FuturesOrdered</strong> declares that it is resolved; we replace it with a brand new <strong>FuturesOrdered</strong> (so that we don’t poll the resolved one again) and return <strong>Poll::Pending</strong> instead. If <strong>close_write</strong> was called; we skip this step and simply relay the resolved response.</li><li>Finally, we use the <strong>Mutex </strong>to present a read-only interface that does not require mutable references. This sneaky case of “internal mutability” might be a bit offputting, but it helps us keep things short for the blog post. We also very carefully avoided dealing with <strong>Pin</strong> or <strong>Waker</strong> anywhere: Let’s not make this any more in-depth than it already is. (There is an async <strong>Mutex</strong> implementation in tokio, instead of the stdlib one we’re using here; but polling that is left as an exercise for the reader).</li><li>One other thing: Take a look at the <strong>push_back</strong> implementation here. There is a generic type <strong>E</strong> that’s not attached to the struct, but the <strong>method itself.</strong> This type can be different for each <strong>push_back</strong> call; and it helps us get rid of the <strong>.boxed()</strong> calls in <strong>main()</strong>. Internally we still call <strong>.boxed()</strong> to make the types homogeneous for <strong>FuturesOrdered</strong>. This prevents us from <a href="https://doc.rust-lang.org/nomicon/lifetime-elision.html">eliding lifetimes</a> (the <strong>‘a</strong> and <strong>‘_</strong> markers you see around the code), but that’s not a lot of boilerplate.</li><li>Even though <strong>FutOrdForStream</strong> is internally a <strong>Stream</strong>; we implement the <strong>Future</strong> trait here instead. Previously, the <strong>.next().await</strong> call in the handler loop returned a specific wrapper <strong>Future</strong> type called <a href="https://docs.rs/futures/latest/futures/stream/struct.Next.html"><strong>Next</strong></a> (provided by the <a href="https://docs.rs/futures/latest/futures/stream/trait.StreamExt.html"><strong>StreamExt</strong></a><strong> </strong>trait); which allowed us to treat the <strong>head of the Stream as a Future</strong>. This time, we directly implement <strong>poll</strong> instead of <strong>poll_next</strong>.</li></ul><p>Short and hacky, but does it work? Let’s see:</p><pre>// async function that spawns the jobs and pushes the futures<br>async fn pusher(f: &amp;FutOrdForStream&lt;&#39;_, u64&gt;, start: Instant) {<br>    f.push_back(count_stars(start));<br>    f.push_back(count_grains_of_sand_on_earth(start));<br>    // 10 second wait before the 3rd job<br>    sleep(Duration::from_secs(10)).await;<br>    f.push_back(meaning_of_life(start));<br>    println!(&quot;[{}] all futures pushed&quot;, start.elapsed().as_secs());<br>    // we declare the intent to close the stream,<br>    // which eventually signals the handler loop to terminate<br>    f.close_write();<br>}<br><br>// async function that handles (prints) the results<br>async fn handler(f: &amp;FutOrdForStream&lt;&#39;_, u64&gt;, start: Instant) {<br>    let mut idx = 0;<br>    while let Some(value) = f.await {<br>        println!(&quot;[{}] result of job #{}: {}&quot;,<br>                 start.elapsed().as_secs(), idx, value);<br>        idx += 1;<br>    }<br>    // to see when the handler loop terminates<br>    println!(&quot;[{}] stream terminated&quot;, start.elapsed().as_secs());<br>}<br><br>#[tokio::main]<br>async fn main() {<br>    let start = Instant::now();<br>    let f = FutOrdForStream::new();<br>    // concurrently run both blocks and join when BOTH are completed<br>    futures::join!(pusher(&amp;f, start), handler(&amp;f, start));<br>}</pre><p>Note that we got rid of the <strong>StreamExt</strong> trait’s <strong>.next().await</strong> call (the line marked with <strong>****</strong>); because <strong>&amp;FutOrdForStream</strong> directly implements <strong>Future</strong>, so we can call <strong>.await</strong> directly on it. Also all calls to <strong>.boxed()</strong> are gone. With <strong>handler</strong> and <strong>pusher</strong> becoming functions, the code is simple and clean again.</p><p>Let’s check the output:</p><pre>[0] countStars(job0) STARTED<br>[0] countGrainsOfSandOnEarth(job1) STARTED<br>[1] countGrainsOfSandOnEarth(job1) DONE<br>[2] countStars(job0) DONE<br>[2] result of job #0: 4611686018427387904<br>[2] result of job #1: 7500000000000000000<br>[10] all futures pushed<br>[10] meaningOfLife(job2) STARTED<br>[13] meaningOfLife(job2) DONE<br>[13] result of job #2: 42<br>[13] stream terminated</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ryLBo5ZZDqaPgc6roYdptQ.png" /><figcaption>Delayed job insertion case. Job2 starts at 10 sec.; the long wait is depicted with a gray bar.</figcaption></figure><p>There are so many things that we could improve upon here; but that should do for today.</p><h3>Java</h3><p>The third language we will attempt this is <strong>Java</strong>.</p><p>Java is, uh, interesting; because while it does have <a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Future.html">Future</a>s and <a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executor.html">Executor</a>s, it does not have async/await syntax. Java programs run on the Java Virtual Machine, yet each Java thread is one-to-one mapped to an OS thread, so Java does not have green threads, nor a user-space scheduler like Go does.</p><blockquote>There have been some attempts to implement <strong>fibers</strong> in Java in the past (like <a href="https://docs.paralleluniverse.co/quasar/">Quasar Fibers</a>, which is apparently no longer maintained); and more recently OpenJDK’s <a href="https://openjdk.org/projects/loom/">Project Loom</a> which seems to have made its way into Java 19. While the Java developers have been bringing many useful features into the language, your humble author did not keep up with what’s new in Java <strong>in a while</strong>, so I will primarily be talking about Java 8.</blockquote><p>Java separates the aspects of a asynchronous computation into two interfaces; <a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Future.html"><strong>Future</strong></a> and <a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletionStage.html"><strong>CompletionStage</strong></a>. Its standard library provides the very useful concrete class <a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html"><strong>CompletableFuture</strong></a> that implements both interfaces. Since there are no green threads and no async/await support in the language; we cannot <em>await</em> on a <strong>Future</strong>’s completion. It is of course possible to <strong><em>block the current thread</em></strong>, but the thread here is the OS-thread; which can mean trouble for your concurrent program.</p><p><strong>CompletionStage</strong> provides many ‘modifiers’ that allow us to pass a callback to the job’s completion: We can register a <a href="https://docs.oracle.com/javase/8/docs/api/java/util/function/Consumer.html"><strong>Consumer</strong></a> to handle the result, a <a href="https://docs.oracle.com/javase/8/docs/api/java/util/function/Function.html"><strong>Function</strong></a> to map the result into another type, and so on.</p><p>The asynchronous operations are explicitly triggered by passing a <a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Callable.html"><strong>Callable</strong></a><strong> </strong>to an <a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html"><strong>ExecutorService</strong></a>:</p><pre>// the lambda function here implements Callable&lt;Integer&gt;<br>// it is invoked on the ForkJoinPool.commonPool() ExecutorService.<br>final CompletableFuture&lt;Integer&gt; fut = CompletableFuture.supplyAsync(() -&gt; 123);<br>// once the result (123) is received; the registered Consumer&lt;Integer&gt;<br>// (which is another lambda function) prints the value<br>fut.thenAccept(value -&gt; System.out.printf(&quot;Value is %d\n&quot;, value));</pre><p>Unlike Rust, Java enqueues the job and <strong>starts running it</strong> ambiently as soon as possible, without the need for polling. One downside is that it is not possible to know which OS thread will execute the registered callbacks; so collecting the result of concurrent computations can get relatively trickier.</p><p>Let’s start by defining the jobs again:</p><pre>import java.time.LocalDateTime;<br>import java.time.temporal.ChronoUnit;<br>import java.util.concurrent.*;<br><br>public final class Entry {<br>  private static final LocalDateTime start = LocalDateTime.now();<br>  private static long elapsed() {<br>    return ChronoUnit.SECONDS.between(start, LocalDateTime.now());<br>  }<br><br>  private static void sleep(int secs) {<br>    try {<br>      Thread.sleep(secs * 1000L);<br>    } catch (final InterruptedException e) {<br>      throw new RuntimeException(e);<br>    }<br>  }<br><br>  private static long countStars() {<br>    System.out.printf(&quot;[%d] countStars(job0) STARTED\n&quot;, elapsed());<br>    sleep(2);<br>    System.out.printf(&quot;[%d] countStars(job0) DONE\n&quot;, elapsed());<br>    return 1L &lt;&lt; 62;<br>  }<br><br>  private static long countGrainsOfSandOnEarth() {<br>    System.out.printf(&quot;[%d] countGrainsOfSandOnEarth(job1) STARTED\n&quot;, elapsed());<br>    sleep(1);<br>    System.out.printf(&quot;[%d] countGrainsOfSandOnEarth(job1) DONE\n&quot;, elapsed());<br>    return (long) 7.5e18;<br>  }<br><br>  private static long meaningOfLife() {<br>    System.out.printf(&quot;[%d] meaningOfLife(job2) STARTED\n&quot;, elapsed());<br>    sleep(3);<br>    System.out.printf(&quot;[%d] meaningOfLife(job2) DONE\n&quot;, elapsed());<br>    return 42;<br>  }<br>}</pre><blockquote>Again, <strong>Thread.sleep()</strong> blocks the OS-thread; so we shouldn’t use it beyond toy examples. For a better approach, see <a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ScheduledExecutorService.html"><strong>ScheduledExecutorService</strong></a>.</blockquote><p>For a fixed number of jobs; we can hard-code the sequentiality here:</p><pre>public static void main(String[] args) {<br>  // spawn all three jobs<br>  final CompletableFuture&lt;Long&gt; numStarsFut = CompletableFuture.supplyAsync(Entry::countStars);<br>  final CompletableFuture&lt;Long&gt; numGrainsFut = CompletableFuture.supplyAsync(Entry::countGrainsOfSandOnEarth);<br>  final CompletableFuture&lt;Long&gt; meaningFut = CompletableFuture.supplyAsync(Entry::meaningOfLife);<br>  <br>  CompletableFuture.completedFuture(null)<br>    .thenCombine(numStarsFut, (n, v) -&gt; System.out.printf(&quot;[%d] result of job #0: %d\n&quot;, elapsed(), v))<br>    .thenCombine(numGrainsFut, (n, v) -&gt; System.out.printf(&quot;[%d] result of job #1: %d\n&quot;, elapsed(), v))<br>    .thenCombine(meaningFut, (n, v) -&gt; System.out.printf(&quot;[%d] result of job #2: %d\n&quot;, elapsed(), v))<br>    .join();<br>}</pre><blockquote>The modifier <a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html#thenCombine-java.util.concurrent.CompletionStage-java.util.function.BiFunction-"><strong>thenCombine</strong></a> essentially joins a future with another; and calls a <a href="https://docs.oracle.com/javase/8/docs/api/java/util/function/BiFunction.html"><strong>BiFunction</strong></a> with both results. We will discard the left parameter (<strong>n</strong> in our code) because we are not interested in the previous future’s result, just that it is completed. The first, already-resolved future is there so that the example is <strong>more readable.</strong></blockquote><p>The calls to <strong>thenCombine</strong> ensures that both the previous result and the future itself resolved; ensuring the results do not get reordered. The <a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html#join--"><strong>join</strong></a> at the end blocks the main thread; ensuring that we complete all the jobs before terminating the program. We add this because we want to see the logs, obviously.</p><p>The output is as expected:</p><pre>[0] countStars(job0) STARTED<br>[0] countGrainsOfSandOnEarth(job1) STARTED<br>[0] meaningOfLife(job2) STARTED<br>[1] countGrainsOfSandOnEarth(job1) DONE<br>[2] countStars(job0) DONE<br>[2] result of job #0: 4611686018427387904<br>[2] result of job #1: 7500000000000000000<br>[3] meaningOfLife(job2) DONE<br>[3] result of job #2: 42</pre><h4>Array of jobs</h4><p>For an array of jobs, we can trivially extend this approach like this:</p><pre>public static void main(String[] args) {<br>  final ArrayList&lt;CompletableFuture&lt;Long&gt;&gt; futures = new ArrayList&lt;&gt;();<br>  futures.add(CompletableFuture.supplyAsync(Entry::countStars));<br>  futures.add(CompletableFuture.supplyAsync(Entry::countGrainsOfSandOnEarth));<br>  futures.add(CompletableFuture.supplyAsync(Entry::meaningOfLife));<br><br>  // we start by a completed future, so that the first one joins immediately<br>  CompletableFuture&lt;Void&gt; f = CompletableFuture.completedFuture(null);<br>  for (int i = 0; i &lt; futures.size(); i++) {<br>    // closure requires that the captured index value is effectively final<br>    final int index = i;<br>    f = f.thenCombine(futures.get(i), (n, v) -&gt; {<br>      System.out.printf(&quot;[%d] result of job #%d: %d\n&quot;, elapsed(), index, v);<br>      // to unify future types here; we explicitly return null,<br>      // which is the only valid value for the type Void<br>      return null;<br>    });<br>  }<br>  // join at the end to block the main thread<br>  f.join();<br>}</pre><p>This approach works for arrays, but has problems with streams. Mainly, the futures combined in this way keep references to the previous ones, preventing them from being garbage collected. Keep combining futures like this indefinitely, and you’ll have an OOM. Instead we should move on to a queue-based approach.</p><h4>Stream of jobs</h4><p>First, we need a thread-safe queue, for that we will wrap a <strong>LinkedList</strong>. We want an <strong>enqueue</strong> operation that returns the element if it was the <strong><em>first insertion;</em></strong> and a <strong>dequeue</strong> that returns the <strong><em>next element</em></strong> after remove. Let’s call it Mailbox, to allude to the actor framework example:</p><pre>import java.util.LinkedList;<br><br>public final class Mailbox&lt;T&gt; {<br>  private final LinkedList&lt;T&gt; queue = new LinkedList&lt;&gt;();<br><br>  // returns the value if it was inserted in<br>  // an empty queue; null otherwise<br>  public T enqueue(final T t) {<br>    T first = null;<br>    if (t != null)<br>      synchronized (queue) {<br>        if (queue.isEmpty())<br>          first = t;<br>        queue.add(t);<br>      }<br>    return first;<br>  }<br><br>  // dequeues the first element; returns the next<br>  public T dequeue() {<br>    synchronized (queue) {<br>      queue.remove();<br>      return queue.peek();<br>    }<br>  }<br>}</pre><p>Basically, both operations return the<strong> next element to process.</strong> We get <strong>null</strong> if the queue is empty after <strong>dequeue</strong> (because there is nothing left to process), or if it already wasn’t empty before <strong>enqueue</strong> (because there is no need to trigger processing). It’ll make more sense when we use it.</p><p>First, we implement a <strong>JobProcessor</strong> that receives futures of jobs <strong>that return Runnable</strong>. That is, asynchronous tasks that give us a callback when completed. This is a bit awkward, but it’s as general-purpose as it gets, and it’s how <strong>ExecutorService</strong> does it anyway. We will extend this for futures that return <em>values</em>.</p><pre>import java.util.concurrent.*;<br><br>public class JobProcessor {<br>  private final ExecutorService executor;<br>  private final Mailbox&lt;CompletionStage&lt;Runnable&gt;&gt; queue = new Mailbox&lt;&gt;();<br><br>  public JobProcessor(final ExecutorService executor) {<br>    this.executor = executor;<br>  }<br><br>  public void enqueueJob(final CompletionStage&lt;Runnable&gt; future) {<br>    process(queue.enqueue(future));<br>  }<br><br>  private void process(final CompletionStage&lt;Runnable&gt; future) {<br>    if (future != null)<br>      // when the next future in line completes, start a new task<br>      future.thenAccept(orderedJob -&gt; executor.execute(() -&gt; {<br>        // the task first runs the ordered job (i.e. handles the result)<br>        orderedJob.run();<br>        // then triggers the process of the next future<br>        process(queue.dequeue());<br>      }));<br>  }<br>}</pre><p>The function <strong>enqueueJob </strong>first pushes the future into <strong>Mailbox</strong>. If the mailbox was empty before; we trigger <strong>process </strong>for the newly-inserted element. Each <strong>process </strong>call tails the future by first executing the runnable on the executor; then popping the handled future and triggering the next job until the queue is drained, then stops. The next time there is a future enqueued, <strong>enqueueJob</strong> will trigger a new drain.</p><blockquote>Note that the call to <strong>process</strong> within <strong>process</strong> here is not recursive; as we don’t invoke the inner lambda immediately. Also note that all ordered jobs are executed on the provided <strong>ExecutorService</strong>; whereas we can pick another <strong>ExecutorService</strong> for the original concurrent jobs to run. We can even separate the two executors and scale them independently if we like: “These two threads are dedicated to deserialization, and there three handle the messages”.</blockquote><p>Our previous implementations used <strong>join()</strong> to block the main thread until the jobs are done. We need a similar mechanism. Since <strong>JobProcessor</strong> receives <strong>Future</strong>s with <strong>Runnable</strong> callbacks that run in order, we can do something like this: Enqueue an already completed future, which has a callback. The callback will then resolve another future, on which we can <strong>join()</strong>. Let’s call this a <strong>barrier</strong>:</p><pre>public CompletableFuture&lt;Void&gt; barrier() {<br>  final CompletableFuture&lt;Void&gt; completion = new CompletableFuture&lt;&gt;();<br>  enqueueJob(CompletableFuture.completedFuture(() -&gt; completion.complete(null)));<br>  return completion;<br>}</pre><p>This way, we can push the jobs, then push a barrier; and join on the barrier; which will not resolve until all jobs are handled.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WT5K9Tam-9anuRSGepL94A.png" /><figcaption>Depiction of the ‘barrier’. Since the Future for the barrier job is already resolved; there is only the ‘handling’ part; which resolves when all previous results are handled.</figcaption></figure><p>This function is also why we started with <strong>CompletionStage&lt;Runnable&gt;</strong>.</p><p>To handle <strong>CompletionStage&lt;T&gt;</strong> for any T; we must specify how to handle T values. We can do that by passing a <strong>Consumer&lt;T&gt;.</strong> Let’s extend the class with this:</p><pre>import java.util.concurrent.*;<br>import java.util.function.Consumer;<br><br>public class Processor&lt;T&gt; extends JobProcessor {<br>  private final Consumer&lt;T&gt; consumer;<br><br>  public Processor(final ExecutorService executor, final Consumer&lt;T&gt; consumer) {<br>    super(executor);<br>    this.consumer = consumer;<br>  }<br><br>  public void enqueue(final CompletionStage&lt;T&gt; future) {<br>    // map CompletionStage&lt;T&gt; to CompletionStage&lt;Runnable&gt;<br>    enqueueJob(future.thenApply(v -&gt; () -&gt; consumer.accept(v)));<br>  }<br>}</pre><p>Here is how we can use it:</p><pre>  public static void main(String[] args) {<br>    final ExecutorService es = ForkJoinPool.commonPool();<br>    // we specify the result handler at the constructor<br>    final Processor&lt;Long&gt; p = new Processor&lt;&gt;(es, Entry::handleResult);<br>    // now we start spawning and pushing concurrent jobs<br>    p.enqueue(CompletableFuture.supplyAsync(Entry::countStars, es));<br>    p.enqueue(CompletableFuture.supplyAsync(Entry::countGrainsOfSandOnEarth, es));<br>    p.enqueue(CompletableFuture.supplyAsync(Entry::meaningOfLife, es));<br>    // then we push a barrier and join on it<br>    p.barrier().join();<br>  }<br><br>  private static int jobIdx = 0;<br>  private static void handleResult(long v) {<br>    System.out.printf(&quot;[%d] result of job #%d: %d\n&quot;, elapsed(), jobIdx++, v);<br>  }</pre><p>Simple and clean. The output is the same, and we don’t break the garbage collector’s heart.</p><p>One thing to note here: <strong>handleResult</strong> is called inside another task sent to the executor; therefore each result might be handled on a different OS-thread. This solution has no concept of thread affinity. However, two tasks cannot <strong><em>concurrently</em></strong> run <strong>handleResult </strong>here (as we don’t enqueue another until the first one is finished); therefore we can treat the function as critical section (which is why we don’t need to make <strong>jobIdx </strong>atomic here). Compare this to Rust’s poll-based approach; where the <strong>Future</strong> is polled on the OS-thread that awaits it, simplifying the result handling immensely (once we survive the combinator implementations, that is).</p><h3>Conclusion</h3><p>In this blog post, we identified a common concurrency problem and its variants; then tried to provide in-depth solutions to it in three different programming languages, revealing how they differ from one another.</p><p>In our case, we implement the <strong>Picus cross-platform agent</strong> in Go; therefore we went ahead with an approach essentially similar to the array-of-jobs case in Go. Obviously, our version is a bit more complicated with proper handling of errors, panics, context cancellation and telemetry. Our initial prototype for the cross-platform agent was in Rust; and we used the <strong>FuturesOrdered</strong> combinator there. Finally, I had to implement an actor framework in Java in a previous job, where I had implemented something similar to the <strong>Processor</strong> here for the actors’ execution model.</p><p>In <a href="https://www.picussecurity.com/">Picus Security</a>, we regularly tackle problems that challenge us to combine the most OS-specific minutiae with the highest-level system design concepts. We meticulously innovate at a junction where many concepts like concurrency, telemetry, network protocols, OS fingerprinting, scalability, graph theory, CI/CD, cryptography and binary obfuscation can casually come together. By bringing hard work and the joy of discovery together, we have been pushing boundaries on <strong>Breach and Attack Simulation</strong> for 10 years. We invite you to witness it yourself: <a href="https://discover.picussecurity.com/start-your-free-trial">Get started</a> with our <strong>Complete Security Validation Platform</strong> today!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53ccd932c86b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/picus-security-engineering/running-concurrent-jobs-with-ordered-results-53ccd932c86b">Running concurrent jobs with ordered results</a> was originally published in <a href="https://medium.com/picus-security-engineering">Picus Security Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Temporarily dropping root privileges in Go]]></title>
            <link>https://medium.com/picus-security-engineering/temporarily-dropping-root-privileges-in-go-ac50d80be70c?source=rss-d31bef4f742c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac50d80be70c</guid>
            <category><![CDATA[posix]]></category>
            <category><![CDATA[syscalls]]></category>
            <category><![CDATA[unix]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[picu]]></category>
            <dc:creator><![CDATA[Devrim Şahin]]></dc:creator>
            <pubDate>Wed, 26 Apr 2023 07:19:03 GMT</pubDate>
            <atom:updated>2023-04-26T07:19:03.939Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*68c5WnfPSV9-ZhRM2ND3lA.png" /></figure><h3>Introduction</h3><p>In this blog post, we will discuss a way of spawning <strong>root</strong> child processes from an <strong>effectively non-root</strong> parent process.</p><p>Now, before you grab your pitchforks, we would like to direct your attention to the ‘<em>effectively</em>’ part here. The parent process <em>will</em> start its lifecycle as a privileged process, but drop these privileges immediately. From there on, we want the parent process to <em>act like</em> a non-<strong>root</strong> process; until it’s time to spawn child processes.</p><p>(Notice that this is different from <em>permanently</em> dropping root privileges. Web servers used to do connect to lower ports as <strong>root</strong> and drop their privileges this way. Nowadays, users are recommended to set <strong>CAP_NET_BIND_SERVICE</strong> on the server binary and avoid <strong>root</strong> altogether.)</p><p>Before we get into the details, we should discuss <em>why</em> we want to do this.</p><h3>Background</h3><p>As you probably know, in <a href="https://www.picussecurity.com/">Picus Security</a> we specialize in <strong>security control validation</strong>. In order to assess the prevention capabilities of security controls, we continuously expand our library with the latest threats. These threats are categorized into <em>modules</em> by how these attacks are simulated; different modules verifying different kinds of security tools.</p><p>One of these modules is the <strong>Endpoint Scenario Attacks</strong> module, which simulates an attacker trying to run a malicious command or executable file in the victim’s computer (the <em>endpoint</em>); validating the effectiveness of endpoint security tools present in the endpoint. If the simulated process can successfully evade security tools; then the endpoint is deemed vulnerable to that kind of threat.</p><p>To run a simulation, Picus platform users download and run a <strong>simulation agent</strong> application. When the user defines a simulation run on the Picus platform and starts it, the agent is given a <em>recipe</em> of each threat in the simulation run. The agent then performs the actions requested; and returns results for each action. In the case of endpoint scenario attacks, the agent is asked to sequentially execute a list of commands, each in its own OS process.</p><p>In short; simulation agents should be able to execute a list of arbitrary commands.</p><p>Scenario actions can have different privilege requirements: While some commands may require that the agent acts like <strong>root</strong>, some may not need <strong>root</strong>, or may explicitly require a non-<strong>root</strong> user. For example, testing a privilege escalation threat does not make sense if the process is already <strong>root</strong>. This means that we should be able to ‘impersonate’ both <strong>root</strong> and non-<strong>root</strong> child processes.</p><p><em>(Quick intervention: This discussion concerns our Linux and macOS agents. The described ‘impersonation’ flow acts differently in our Windows agents, which has a different approach for user accounts.)</em></p><p>This is easier to achieve if the parent process is <strong>root</strong>: Child process can simply drop its privileges for non-<strong>root</strong> commands after being forked.</p><p>However, we can imagine a case where the parent process has other responsibilities; for example it may be creating log files, or access some critical resources. If we want the parent process to act as <strong>root</strong> <strong><em>only</em></strong> when spawning child processes; we have some work to do.</p><p><strong>The method we are about to describe is no longer used in the Picus simulation agent, due to changing requirements and other use cases.</strong></p><h3>Dropping privileges permanently</h3><p>Let’s first discuss how to drop <strong>root</strong> privileges permanently.</p><p>This method used to be rather common for web servers that needed to open a socket to lower ports (which requires either <strong>CAP_NET_BIND_SERVICE </strong>capability on the process, or <strong>root</strong>). Since the “binding to server port” part is done once at the beginning; the process is started as <strong>root</strong>, binds to the port, then it drops its privileges.</p><p>In Unix, access control is based on a set of user and group IDs that are associated with the process, limiting the system resources a process can access. Specifically, user ID <strong>0</strong> is reserved for <strong>root</strong>, who has unlimited access.</p><p>Unix also differentiates between multiple types of user IDs (<strong>uid</strong>s): <strong>Real</strong> uid (<strong>ruid</strong> or simply <strong>uid</strong>), and <strong>effective</strong> uid (<strong>euid</strong>). There is also <strong>saved</strong> uid (<strong>suid</strong>), which the kernel uses internally to memorize changes in between the former two, and in Linux <strong>filesystem</strong> uid (<strong>fsuid</strong>), which controls file resource accesses. However <strong>suid</strong> is mostly an implementation detail, and <strong>fsuid</strong> is equal to <strong>euid</strong> unless explicitly set; so we can skip these. <a href="https://people.eecs.berkeley.edu/~daw/papers/setuid-usenix02.pdf">SetUID Demystified</a> is a great resource for detailed explanation of these concepts, but we will try to summarize them.</p><p>(Group IDs have similar semantics: Real group ID is <strong>gid</strong> or <strong>rgid</strong>, effective group ID is <strong>egid</strong>, and so on.)</p><p>A process can set its <strong>uid</strong>, <strong>euid</strong>, <strong>gid</strong> or <strong>egid</strong> using the system calls <strong>setuid</strong>, <strong>seteuid</strong>, <strong>setgid</strong> or <strong>setegid</strong> respectively. There are other syscalls such as <strong>setreuid</strong>, <strong>setresuid</strong>, <strong>setfsuid</strong> etc. but these are not readily available in Go, nor needed in our case.</p><p>While <strong>setuid</strong> assigns both <strong>uid</strong> and <strong>euid</strong> values; <strong>set<em>e</em>uid</strong> <em>doesn’t affect</em> <strong>uid</strong>. <strong>setgid</strong> and <strong>setegid</strong> work similarly. Whether the process has the permission to invoke these syscalls or not is determined by the <strong>uid</strong> value.</p><p>Let’s say that we have a system where there are two users: <strong>root</strong><em> {uid=0 gid=0}</em> and <strong>user</strong><em> {uid=501 gid=20}.</em> (Linux systems often start at <em>uid=gid=1000</em>, but let’s use 501 and 20 so that we can tell them apart).</p><p>A process started as <strong>root</strong> will have <em>{uid=0 euid=0}</em>. Calling <strong>setuid(501)</strong> on this process will yield <em>{uid=501 euid=501}</em>. Therefore, using <strong>setuid</strong> also sets <strong>euid=uid</strong>. The <strong>uid</strong> value is permanently dropped to 501 and cannot be re-escalated to 0.</p><pre>package main<br><br>import (<br>  &quot;log&quot;<br>  &quot;os&quot;<br>  &quot;syscall&quot;<br>)<br><br>func main() {<br>  // program must be run as root<br>  if os.Getuid() != 0 {<br>    log.Fatalln(&quot;program was not run as root&quot;)<br>  }<br><br>  // do something as root<br>  log.Println(&quot;Doing some tasks as root...&quot;)<br>  log.Printf(&quot;    {uid=%d euid=%d gid=%d egid=%d}\n&quot;,<br>    os.Getuid(), os.Geteuid(), os.Getgid(), os.Getegid())<br>  _ = os.WriteFile(&quot;./root_owned&quot;, []byte(&quot;hi&quot;), 0o666)<br><br>  // drop privileges<br>  log.Println(&quot;Dropping privileges...&quot;)<br>  log.Printf(&quot;  - setgid(20):   %v\n&quot;, syscall.Setgid(20))<br>  log.Printf(&quot;  - setuid(501):  %v\n&quot;, syscall.Setuid(501))<br><br>  // we are no longer root<br>  log.Println(&quot;Root privileges permanently dropped.&quot;)<br>  log.Printf(&quot;    {uid=%d euid=%d gid=%d egid=%d}\n&quot;,<br>    os.Getuid(), os.Geteuid(), os.Getgid(), os.Getegid())<br>  _ = os.WriteFile(&quot;./user_owned&quot;, []byte(&quot;hi&quot;), 0o666)<br><br>  // from here on; we cannot be root again: these calls will fail<br>  log.Println(&quot;Trying to re-escalate:&quot;)<br>  log.Printf(&quot;  - setuid(0):  %v\n&quot;, syscall.Setuid(0))<br>  log.Printf(&quot;  - setgid(0):  %v\n&quot;, syscall.Setgid(0))<br>}</pre><p>Several things to note here:</p><ul><li>We start by asserting that the program is run as <strong>root</strong>. We do this by verifying that <strong>os.Getuid()</strong> returns 0. Unless this is true, the <strong>set*id</strong> syscalls will not work (To keep things brief, we are blatantly ignoring the <strong>CAP_SETUID</strong> <a href="https://man7.org/linux/man-pages/man7/capabilities.7.html">file capability</a> here. There is also a <strong>setuid</strong> <a href="https://linux.die.net/man/1/chmod"><em>file mode bit</em></a>, which is a can of worms that we will gleefully omit here).</li><li>We print the <strong>uid</strong>, <strong>euid</strong>, <strong>gid</strong> and <strong>egid</strong> values for the process using corresponding functions under the <strong>os</strong> package (All four functions <em>also</em> exist under the <strong>syscall</strong> package, if that’s what you prefer). For <strong>root</strong>, we expect all these values to be 0. At this stage, we also write a file to observe that the file is <strong>root</strong>-owned (Which will show us that <em>fsuid=0</em> as well; equal to <strong>euid</strong>).</li><li>To drop privileges, we use <strong>syscall.Setgid(20)</strong> and <strong>syscall.Setuid(501)</strong>. Note that these functions are under the <strong>syscall</strong> package <strong><em>only</em></strong>, and not under <strong>os</strong>. Also, the order of these two calls matter: If we were to call <strong>Setuid</strong> first; we would not have the permission to call <strong>Setgid</strong> anymore, so the latter would fail with an <em>“operation not permitted”</em> error.</li><li>Once <strong>root</strong> privileges are dropped; we print all four IDs again; and write another file to check its ownership.</li><li>Finally, to prove that the privilege drop was permanent; we attempt to re-acquire <strong>root</strong> IDs. These calls <strong>should fail</strong>.</li></ul><p>We can visualize what is happening as follows. Once <strong>setuid(501)</strong> is called, we can’t regain privileges:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qRs6Iec8xf5No02mgyu5vg.png" /><figcaption>Permanent permission drop via setuid</figcaption></figure><p>Output of the program when run as <strong>root</strong>:</p><pre>Doing some tasks as root...<br>    {uid=0 euid=0 gid=0 egid=0}<br>Dropping privileges...<br>  - setgid(20):   &lt;nil&gt;<br>  - setuid(501):  &lt;nil&gt;<br>Root privileges permanently dropped.<br>    {uid=501 euid=501 gid=20 egid=20}<br>Trying to re-escalate:<br>  - setuid(0):  operation not permitted<br>  - setgid(0):  operation not permitted</pre><p>Generated files have the following owners:</p><ul><li><strong>./root_owned</strong> belongs to <strong>root</strong> (implying <em>fsuid=0</em>)</li><li><strong>./user_owned</strong> belongs to <strong>user</strong> (implying <em>fsuid=501</em>)</li></ul><p><em>(On macOS, default group behavior for files may differ slightly.)</em></p><p>There is one annoying thing before we move on: We had to hard-code <strong>user</strong>’s IDs! Can we get them dynamically?</p><p>As we start the program as <strong>root</strong>; somehow we should obtain the <strong>uid</strong>/<strong>gid</strong> of the non-<strong>root</strong> user that we want to impersonate.</p><p>Well, if we <strong>don’t</strong> run the process from a <strong>root </strong>user’s <strong><em>session</em></strong>, but from a non-<strong>root</strong> user’s terminal instead; we can drop to the session owner user’s IDs. There <em>is</em> a way for (some) non-<strong>root</strong> users to start <strong>root</strong> processes: <strong>sudo</strong>.</p><p>Conveniently, <strong>sudo</strong> <a href="https://www.sudo.ws/docs/man/1.9.6/sudo.man/#SUDO_UID">sets the environment variables</a> <strong>SUDO_UID</strong> and <strong>SUDO_GID</strong> to the original <strong>user</strong>’s IDs (that is, the user in the terminal session: <strong>user</strong><em> {uid=501 gid=20}</em> in our case). We can try to parse these environment variables:</p><pre>// getEnvInt is a helper function to get an int value from the environment<br>func getEnvInt(key string) (parsed int, err error) {<br>  if value := os.Getenv(key); value == &quot;&quot; {<br>    err = fmt.Errorf(&quot;missing env key %s&quot;, key)<br>  } else if parsed, err = strconv.Atoi(value); err != nil {<br>    err = fmt.Errorf(&quot;cannot parse env key %s=%q: %v&quot;, key, value, err)<br>  }<br>  return<br>}<br><br>func main() {<br>  if os.Getuid() != 0 {<br>    log.Fatalln(&quot;program was not run as root&quot;)<br>  }<br><br>  // get original user uid/gid from environment variables<br>  uid, err := getEnvInt(&quot;SUDO_UID&quot;)<br>  if err != nil {<br>    log.Fatalf(&quot;program was not run as sudo: %v\n&quot;, err)<br>  }<br>  gid, err := getEnvInt(&quot;SUDO_GID&quot;)<br>  if err != nil {<br>    log.Fatalf(&quot;program was not run as sudo: %v\n&quot;, err)<br>  }<br><br>  // -- snip --<br><br>  log.Println(&quot;Dropping privileges...&quot;)<br>  log.Printf(&quot;  - setgid(%d):  %v\n&quot;, gid, syscall.Setgid(gid)) // gid instead of 20<br>  log.Printf(&quot;  - setuid(%d):  %v\n&quot;, uid, syscall.Setuid(uid)) // uid instead of 501<br><br>  // -- snip --<br>}</pre><p>This program works <em>exactly</em> the same as the one above; except we don’t hardcode 501 and 20 anymore. However, if we try to run it <em>directly as </em><strong><em>root</em></strong><em> </em>(i.e. from the <strong>root</strong>’s terminal session), we are presented with this output, because there isn’t an ‘original’ user to return to:</p><pre>program was not run as sudo: missing env key SUDO_UID</pre><p>Obviously, <strong>user</strong> should be defined as a <em>“sudoer”</em> for this trick to work. Also, the code should actually <em>verify</em> that <strong>SUDO_UID</strong> and <strong>SUDO_GID</strong> are non-zero, but that part is left as an exercise. There are more edge cases that we didn’t handle here, but let’s move on: <em>We have more ground to cover.</em></p><h3>Dropping privileges temporarily</h3><p>In the code above; once we call <strong>setuid(501)</strong>, its effect is <strong>permanent</strong>: We cannot re-escalate privileges to <strong>root</strong>. Recall however, that there is a <strong>real</strong> and an <strong>effective</strong> uid: <strong>setuid</strong> assigns <strong><em>both</em></strong>, but <strong>seteuid</strong> <em>does not assign</em> <strong>uid</strong>.</p><p>But how are these two user IDs different?</p><p><strong>Effective user ID</strong> is what actually determines the current, <strong>apparent</strong> access level of the process. When a process attempts to access a system resource (for example, a TCP socket), the kernel checks its <strong>euid</strong> to see if the process has that kind of permission.</p><p>By default, <em>euid=uid</em>; but we can assign a different value to <strong>euid</strong> using the <strong>seteuid</strong> syscall. For example, if we set <em>euid=501</em> while <em>uid=0</em>, it can no longer access system resources as <strong>root</strong>! Since <em>fsuid=euid</em> unless explicitly changed; all our file accesses will belong to <strong>user</strong> as well (and not to <strong>root</strong>).</p><p><em>However,</em> <strong>setuid</strong> capabilities are determined using <strong>uid</strong>, not <strong>euid</strong>: This means that at a later time, we can still call <strong>seteuid(0)</strong>, and restore our <strong>root</strong> privileges! So, if the process has <em>uid=0</em> and <em>euid != 0</em>, for all intents and purposes it will act like a non-<strong>root</strong> process; while secretly retaining <strong>setuid</strong> permissions!</p><p><em>(Again, before you grab your pitchforks; we are simplifying this </em><strong><em>a lot</em></strong><em> so that we can cover a specific scenario.)</em></p><p>Let’s try it!</p><pre>func main() {<br>  // -- snip --<br>  // get original user uid/gid from environment variables<br>  // removed err checks to keep the code short<br>  uid, _ := getEnvInt(&quot;SUDO_UID&quot;)<br>  gid, _ := getEnvInt(&quot;SUDO_GID&quot;)<br><br>  // do something as root<br>  log.Println(&quot;Doing some tasks as root...&quot;)<br>  log.Printf(&quot;    {uid=%d euid=%d gid=%d egid=%d}\n&quot;,<br>    os.Getuid(), os.Geteuid(), os.Getgid(), os.Getegid())<br>  _ = os.WriteFile(&quot;./root_owned_1&quot;, []byte(&quot;hi&quot;), 0o666)<br><br>  // drop privileges<br>  log.Println(&quot;Dropping privileges...&quot;)<br>  log.Printf(&quot;  - setegid(%d):  %v\n&quot;, gid, syscall.Setegid(gid)) // note the use of Setegid<br>  log.Printf(&quot;  - seteuid(%d):  %v\n&quot;, uid, syscall.Seteuid(uid)) // note the use of Seteuid<br><br>  // we are no longer root<br>  log.Println(&quot;Root privileges temporarily dropped.&quot;)<br>  log.Printf(&quot;    {uid=%d euid=%d gid=%d egid=%d}\n&quot;,<br>    os.Getuid(), os.Geteuid(), os.Getgid(), os.Getegid())<br>  _ = os.WriteFile(&quot;./user_owned&quot;, []byte(&quot;hi&quot;), 0o666)<br><br>  // from here on; we CAN be root again<br>  log.Println(&quot;Trying to re-escalate:&quot;)<br>  log.Printf(&quot;  - seteuid(0):  %v\n&quot;, syscall.Seteuid(0))<br>  log.Printf(&quot;  - setegid(0):  %v\n&quot;, syscall.Setegid(0))<br><br>  // do something as root<br>  log.Println(&quot;Doing some tasks as root again...&quot;)<br>  log.Printf(&quot;    {uid=%d euid=%d gid=%d egid=%d}\n&quot;,<br>    os.Getuid(), os.Geteuid(), os.Getgid(), os.Getegid())<br>  _ = os.WriteFile(&quot;./root_owned_2&quot;, []byte(&quot;hi&quot;), 0o666)<br>}</pre><p>Again, we can visualize it as follows. It is the <strong>seteuid </strong>call that allows us to regain privileges later:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8WaTc27OcySf3EdkNgvQGw.png" /><figcaption>Temporary permission drop via seteuid</figcaption></figure><p>The output:</p><pre>Doing some tasks as root...<br>    {uid=0 euid=0 gid=0 egid=0}<br>Dropping privileges...<br>  - setegid(20):  &lt;nil&gt;<br>  - seteuid(501):  &lt;nil&gt;<br>Root privileges temporarily dropped.<br>    {uid=0 euid=501 gid=0 egid=20}<br>Trying to re-escalate:<br>  - seteuid(0):  &lt;nil&gt;<br>  - setegid(0):  &lt;nil&gt;<br>Doing some tasks as root again...<br>    {uid=0 euid=0 gid=0 egid=0}</pre><p>Now we can go back to being <strong>root</strong> again! If we check the ownership of the created files, we also see that the <em>fsuid=euid</em> invariant is still maintained in each.</p><p>Even though we demonstrated how to re-establish <strong>root</strong> privileges; we still have things to do:</p><ul><li>We had ultimately wanted to spawn <strong>root</strong> and non-<strong>root</strong> <strong><em>child processes</em></strong>, which we haven’t done yet.</li><li>The non-<strong>root</strong> state no longer satisfies <em>euid=uid</em>; which is uncommon for most processes. There are some cases where a child program (such as <strong>bash</strong> without <a href="https://www.man7.org/linux/man-pages/man1/bash.1.html">“privileged mode”</a>) may try to rectify this and cause unexpected behavior.</li><li>We keep invoking <strong>set*id</strong> syscalls during the lifetime of the program. This is undesirable, because these attributes belong to the <strong><em>entire program, not one goroutine</em></strong>. Imagine that the parent process has multiple goroutines that each access some system resources <em>concurrently</em>. If we were to call <strong>setuid</strong> in the main goroutine just as one of these worker goroutines was creating a file, some of these files would arbitrarily belong to <strong>root</strong>. Ideally, we want to make all necessary <strong>set*id</strong> calls in the <strong>beginning</strong> of each (parent and child) process <strong><em>only</em></strong>; before any goroutines were spawned.</li></ul><p>With these requirements, we implement a final version. To keep the code together; parent and child processes are implemented as one program, differentiated by a <strong>CHILD_PRIV</strong> environment variable: If the key is not set, we behave as the <strong>parent process</strong>, otherwise it is the <strong>child</strong>. The assigned value determines if the child process should be <strong>root</strong> or non-<strong>root</strong>:</p><pre>func main() {<br>  if priv := os.Getenv(&quot;CHILD_PRIV&quot;); priv != &quot;&quot; {<br>    childMain(priv == &quot;true&quot;)<br>  } else {<br>    parentMain()<br>  }<br>}<br><br>func spawnChildProcess(isPrivileged bool) {<br>  cmd := exec.Command(os.Args[0]) // self path<br><br>  // pass the privilege info in an environment variable<br>  cmd.Env = append(cmd.Env, fmt.Sprintf(&quot;CHILD_PRIV=%v&quot;, isPrivileged))<br><br>  log.Printf(&quot;Spawning child process (isPrivileged=%v)...\n&quot;, isPrivileged)<br>  <br>  // this waits until the child is terminated<br>  out, err := cmd.CombinedOutput()<br>  if err != nil {<br>    log.Fatalf(&quot;cannot run child command: %v\n&quot;, err)<br>  }<br>  log.Printf(&quot;Child process output: \n|  %s\n&quot;,<br>    strings.ReplaceAll(strings.TrimRight(string(out), &quot;\n&quot;), &quot;\n&quot;, &quot;\n|  &quot;))<br>}<br><br>func parentMain() {<br>  if os.Getuid() != 0 {<br>    log.Fatalln(&quot;program was not run as root&quot;)<br>  }<br>  // removed err checks to keep the code short<br>  uid, _ := getEnvInt(&quot;SUDO_UID&quot;)<br>  gid, _ := getEnvInt(&quot;SUDO_GID&quot;)<br><br>  log.Println(&quot;Dropping privileges...&quot;)<br>  log.Printf(&quot;  - setegid(%d):  %v\n&quot;, gid, syscall.Setegid(gid))<br>  log.Printf(&quot;  - seteuid(%d):  %v\n&quot;, uid, syscall.Seteuid(uid))<br>  log.Printf(&quot;    {uid=%d euid=%d gid=%d egid=%d}\n&quot;,<br>    os.Getuid(), os.Geteuid(), os.Getgid(), os.Getegid())<br><br>  // [POINT_1]<br>  log.Println(&quot;Spawning non-root child...&quot;)<br>  spawnChildProcess(false)<br><br>  log.Println(&quot;Spawning root child...&quot;)<br>  spawnChildProcess(true)<br>}<br><br>func childMain(isPrivileged bool) {<br>  var uid, gid int<br>  if isPrivileged {<br>    uid, gid = os.Getuid(), os.Getgid() // 0, 0<br>  } else {<br>    uid, gid = os.Geteuid(), os.Getegid() // 501, 20<br>  }<br>  _ = syscall.Setuid(os.Getuid()) // [POINT_2] <br><br>  log.Printf(&quot;setgid(%d):  %v\n&quot;, gid, syscall.Setgid(gid))<br>  log.Printf(&quot;setuid(%d):  %v\n&quot;, uid, syscall.Setuid(uid))<br><br>  // [POINT_3]<br>  log.Printf(&quot;{uid=%d euid=%d gid=%d egid=%d}&quot;,<br>    os.Getuid(), os.Geteuid(), os.Getgid(), os.Getegid())<br>}</pre><p>Visualizing this (purple boxes are child processes):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zA-CJRUTTdLxX1dkmxbwIg.png" /><figcaption>Spawning non-root and root child processes from an effectively non-root parent</figcaption></figure><p>Output of the code:</p><pre>Dropping privileges...<br>  - setegid(20):  &lt;nil&gt;<br>  - seteuid(501):  &lt;nil&gt;<br>    {uid=0 euid=501 gid=0 egid=20}<br>Spawning non-root child...<br>Spawning child process (isPrivileged=false)...<br>Child process output: <br>|  setgid(20):  &lt;nil&gt;<br>|  setuid(501):  &lt;nil&gt;<br>|  {uid=501 euid=501 gid=20 egid=20}<br>Spawning root child...<br>Spawning child process (isPrivileged=true)...<br>Child process output: <br>|  setgid(0):  &lt;nil&gt;<br>|  setuid(0):  &lt;nil&gt;<br>|  {uid=0 euid=0 gid=0 egid=0}</pre><p>The parent process first retrieves the sudoer <strong>user</strong>’s <strong>uid</strong> and <strong>gid</strong> as before; which are 501 and 20 in our example. Then we invoke <strong>seteuid(501)</strong> and <strong>setegid(20)</strong> in the parent process. From this point on (<strong>POINT_1</strong>), parent process will <strong><em>never</em></strong> call <strong>set*id</strong> syscalls again. Since parent process IDs are <em>{uid=0 euid=501 gid=0 egid=20}</em>, it will behave like non-<strong>root</strong> user while keep accessing system resources; but its <em>child</em> processes will have <strong>set*id </strong>privileges as well.</p><p><strong>spawnChildProcess</strong> passes the desired privilege level to the child process via the environment key’s value (We could have also used a program argument for this). The child process should attempt to restore the <em>euid=uid</em> and <em>egid=gid</em> invariants. We can use <strong>setuid</strong> for both cases, since it also assigns <strong>euid</strong>. For the privileged case we call <strong>setuid(getuid())</strong> (i.e. <strong>setuid(0)</strong>), and for the unprivileged case, <strong>setuid(geteuid())</strong> (i.e. <strong>setuid(501)</strong>). The same logic applies for <strong>gid</strong>/<strong>egid</strong>.</p><p><em>Keen-eyed readers will have noticed that we didn’t describe the line of code at </em><strong><em>POINT_2</em></strong><em>.</em></p><p>Due to a detail regarding how <strong><em>s</em>uid</strong> behaves, the <em>child </em>process does not actually have the privilege to call <strong>setuid(501)</strong> <em>yet</em>. Therefore, we first -restore the child node to <em>{uid=0 euid=0}</em> by calling <strong>setuid(getuid())</strong> (Since we didn’t discuss <strong>suid</strong> <em>at all</em>; we will leave it at that). Then we can restore the invariants like described above.</p><p>We are finally at <strong>POINT_3</strong> where the child process is done with syscalls as well. At this point, the child process also satisfies <em>euid=uid</em> and <em>egid=gid</em>; and we can move on to doing other things like open file descriptors, spawn goroutines etc.</p><h3>Final words</h3><p>In this article, we tried to present a case that can be solved using Unix access control mechanics. Keeping the size of this discussion to a blog post forced us to make <em>many</em> sacrifices: We tried to write the shortest code possible in each case as one-file programs; never discussed how group IDs and user IDs interact with one another, completely skipped the <strong>SysProcAttr</strong> field of <strong>exec.Cmd</strong>, and made many implicit assumptions that we didn’t check in the code (For example, what would happen if the <em>parent</em> process was spawned by another process<em> that called </em><strong><em>setfsuid</em></strong><em> first?</em>). We didn’t discuss the <strong>setuid</strong> <em>file mode bit</em>, nor the <strong>CAP_SETUID</strong> <em>file capability</em>. We didn’t spawn child processes <em>from</em> child processes, and we didn’t get into how <strong>sh</strong>, <strong>bash</strong> and <strong>bash -p</strong> behave differently when <em>euid!=uid</em>…</p><p>Also, what do you think happens to $<strong>HOME</strong>, (or <strong>$PATH</strong>, or any other environment variable) when we change users like this?</p><p>In our case, with all the quirks and pitfalls of <strong>setuid</strong>, we eventually applied a different, more robust approach in our simulation agent. Instead, we decided to share some of our findings in a blog post. All in all, we hope that the result was brief, educational and enjoyable, and not a rambling, incoherent mess.</p><p>In <a href="https://www.picussecurity.com/">Picus Security</a>, we regularly tackle problems that challenge us to combine the most OS-specific minutiae with the highest-level system design concepts. We meticulously innovate at a junction where many concepts like concurrency, telemetry, network protocols, OS fingerprinting, scalability, graph theory, CI/CD, cryptography and binary obfuscation can casually come together. By bringing hard work and the joy of discovery together, we have been pushing boundaries on <strong>Breach and Attack Simulation</strong> for 10 years. We invite you to witness it yourself: <a href="https://discover.picussecurity.com/start-your-free-trial">Get started</a> with our <strong>Complete Security Validation Platform</strong> today!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac50d80be70c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/picus-security-engineering/temporarily-dropping-root-privileges-in-go-ac50d80be70c">Temporarily dropping root privileges in Go</a> was originally published in <a href="https://medium.com/picus-security-engineering">Picus Security Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>