<?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 Calum Hunter on Medium]]></title>
        <description><![CDATA[Stories by Calum Hunter on Medium]]></description>
        <link>https://medium.com/@calum-h?source=rss-fc272f24dd85------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*E76FJKm1BKZQ21DHaMZong.jpeg</url>
            <title>Stories by Calum Hunter on Medium</title>
            <link>https://medium.com/@calum-h?source=rss-fc272f24dd85------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 13:10:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@calum-h/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[I Recovered a Deleted Lubluelu SL60D Pro Map by Reverse-Engineering Tuya’s Map Format]]></title>
            <link>https://calum-h.medium.com/i-recovered-a-deleted-lubluelu-sl60d-pro-map-by-reverse-engineering-tuyas-map-format-13cbe9bf2898?source=rss-fc272f24dd85------2</link>
            <guid isPermaLink="false">https://medium.com/p/13cbe9bf2898</guid>
            <dc:creator><![CDATA[Calum Hunter]]></dc:creator>
            <pubDate>Fri, 21 Aug 2026 13:17:25 GMT</pubDate>
            <atom:updated>2026-08-21T13:20:43.645Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J0A9efmQNlxAKFz0xOy7-A.jpeg" /></figure><h3>How I rebuilt a deleted Smart Life robot-vacuum map from cleaning history, reconstructed the robot’s proprietary relocation data, restored nine rooms, room names, six virtual walls and a no-go zone — and saved the whole thing back into Tuya as a normal map.</h3><p>I recently managed to recover a deleted map from a <strong>Lubluelu SL60D Pro robot vacuum running through Smart Life</strong>.</p><p>Not just the outline of the house.</p><p>The final recovery included:</p><ul><li>the original full-house map</li><li>all nine room divisions</li><li>the original room names</li><li>six virtual walls</li><li>the original no-go zone</li><li>a working navigation/relocation map the robot could actually use</li><li>a normal saved map in Smart Life with a working <strong>Use Map</strong> button</li></ul><p>The map had been deleted from the robot and no longer existed as a usable current or saved map.</p><p>What saved me was one important fact:</p><blockquote><strong><em>The map still existed inside an old cleaning-history record.</em></strong></blockquote><p>Unfortunately, Smart Life provides no way to promote a cleaning-history map back into a current map.</p><p>So this turned into a reverse-engineering exercise.</p><p>What follows is the process I used.</p><h3>A warning before you try this</h3><p>This worked on my:</p><p><strong>Lubluelu SL60D Pro / D40 family robot using Smart Life and Tuya.</strong></p><p>There is no guarantee another model or firmware version uses exactly the same binary format.</p><p>Some of the commands discussed below can replace or remove the robot’s current map.</p><p>Before experimenting, create and save a known-good temporary map so you have a rollback option.</p><p>Also:</p><p><strong>Never publish your Tuya Client Secret, access token, refresh token or signed S3 URLs.</strong></p><p>All such values in this article have been removed or replaced with examples.</p><h3>The problem</h3><p>My original house map had been working for weeks.</p><p>It contained all my rooms, room divisions, virtual walls and exclusion zones.</p><p>The last known-good cleaning history entry was:</p><pre>5 August 2026<br>Map ID: 1<br>Cleaning time: 72 minutes<br>Area: 85 m²</pre><p>Tuya’s history metadata looked like this:</p><pre>1_20260805_131659_72_85_15207_15385</pre><p>At some point afterwards, the robot lost/reset its current map.</p><p>Smart Life then wanted me to perform another full global cleaning and rebuild everything.</p><p>Fortunately, the old 5 August map was still visible under <strong>Cleaning History</strong>.</p><p>That became the recovery source.</p><h3>Step 1 — Link Smart Life to Tuya Cloud</h3><p>I created a Tuya Cloud project and linked my existing Smart Life account.</p><p>The important cloud service was:</p><pre>Sweeping Robot Open Service</pre><p>Tuya exposes several useful laser-vacuum APIs, including:</p><pre>Get Map File List<br>Get Download Link of Map<br>Get Link of Real-Time Map<br>Delete Cleaning Map<br>Modify Cleaning Map Name</pre><p>The important endpoint for discovering old cleaning maps is:</p><pre>GET /v1.0/users/sweepers/file/{device_id}/list</pre><p>For cleaning history:</p><pre>file_type = pic<br>page_no   = 1<br>page_size = 1000</pre><p>That returned my complete retained history.</p><p>A shortened version looked like:</p><pre>2026-08-05  map 1<br>2026-08-03  map 1<br>2026-07-31  map 1<br>2026-07-29  map 1<br>...<br>2026-06-26  map 1</pre><p>That was useful in itself.</p><p>It showed that <strong>map ID 1 had been my stable house map from late June until 5 August</strong>.</p><h3>Step 2 — Download the old cleaning-history binary</h3><p>For my known-good record I called <strong>Get Download Link of Map</strong> using its history record ID.</p><p>Tuya returned an app_map URL similar to:</p><pre>/common/history/time_1785899819_mapid_1.bin</pre><p>The resulting file was:</p><pre>30,670 bytes</pre><p>This file turned out to contain almost everything necessary for the recovery.</p><p>Its history metadata had already given us a major clue:</p><pre>1_20260805_131659_72_85_15207_15385</pre><p>The final two numbers were:</p><pre>15207<br>15385</pre><p>And:</p><pre>15,207 + 15,385 = 30,592</pre><p>The file itself was:</p><pre>30,670 bytes</pre><p>Leaving:</p><pre>78 bytes</pre><p>So the history file could be divided into:</p><pre>15,207 bytes   map/layout<br>15,385 bytes   cleaning route<br>78 bytes       virtual-wall / exclusion-zone data<br>-----------------------------------------------<br>30,670 bytes</pre><p>That turned out to be exactly right.</p><h3>Step 3 — Discover that the first 15,207 bytes are a complete Tuya map</h3><p>This was the first major breakthrough.</p><p>The first 15,207 bytes were not merely some historical image.</p><p>They were a complete, internally valid <strong>Tuya laser map file</strong>.</p><p>Its header decoded as:</p><pre>Version:              1<br>Map ID:               1<br>Map width:            574<br>Map height:           378<br>Resolution:           4<br>Compressed payload:   15,183 bytes</pre><p>The header itself was 24 bytes.</p><p>So:</p><pre>24 + 15,183 = 15,207</pre><p>Exactly matching the history metadata.</p><p>The payload was LZ4 compressed.</p><p>After decompression:</p><pre>217,679 bytes total</pre><p>The map grid occupied:</p><pre>574 × 378 = 216,972 bytes</pre><p>Leaving:</p><pre>707 bytes</pre><p>of room metadata.</p><p>That room metadata contained 15 room slots, of which nine were active in the final map.</p><p>The active room IDs were:</p><pre>1   Lounge Room<br>2   Spare bedroom<br>3   Kitchen<br>4   Dining<br>5   Kitchen<br>6   Hallway2<br>9   Livingroom<br>10  Master Bedroom<br>13  Laundry</pre><p>So at this point the supposedly “deleted” map still contained:</p><p><strong>The complete physical map, room segmentation and room metadata.</strong></p><h3>A minimal Python extractor</h3><p>The basic extraction looked like this:</p><pre>from pathlib import Path<br>import lz4.block</pre><pre>history = Path(&quot;old_history.bin&quot;).read_bytes()</pre><pre>layout_length = 15207<br>layout = history[:layout_length]</pre><pre>version = layout[0]<br>map_id = int.from_bytes(layout[1:3], &quot;big&quot;)</pre><pre>width = int.from_bytes(layout[4:6], &quot;big&quot;)<br>height = int.from_bytes(layout[6:8], &quot;big&quot;)</pre><pre>total_count = int.from_bytes(layout[18:22], &quot;big&quot;)<br>compressed_len = int.from_bytes(layout[22:24], &quot;big&quot;)</pre><pre>compressed = layout[24:24 + compressed_len]</pre><pre>decoded = lz4.block.decompress(<br>    compressed,<br>    uncompressed_size=total_count<br>)</pre><pre>pixel_count = width * height</pre><pre>pixels = decoded[:pixel_count]<br>room_metadata = decoded[pixel_count:]</pre><pre>print(&quot;map ID:&quot;, map_id)<br>print(&quot;dimensions:&quot;, width, &quot;x&quot;, height)<br>print(&quot;decoded:&quot;, len(decoded))<br>print(&quot;room metadata:&quot;, len(room_metadata))</pre><p>For my map:</p><pre>map ID: 1<br>dimensions: 574 x 378<br>decoded: 217679<br>room metadata: 707</pre><h3>Step 4 — Recover the virtual walls and no-go area</h3><p>Remember those extra 78 bytes at the end of the history file?</p><p>They divided perfectly into two Tuya DP command frames.</p><p>The first was:</p><pre>AA 00 32 13 ...</pre><p>Opcode:</p><pre>0x13</pre><p>It contained six wall segments.</p><p>Their original coordinates were:</p><pre>Wall 1: (-1530,-1350) -&gt; ( -930,-1350)<br>Wall 2: (-1540,  400) -&gt; (-1540, -110)<br>Wall 3: ( -500,  660) -&gt; (  100,  660)<br>Wall 4: ( -280,  720) -&gt; ( -280,  540)<br>Wall 5: (  240,  580) -&gt; (  230,  310)<br>Wall 6: ( 1250,  650) -&gt; ( 1860,  650)</pre><p>The second frame was:</p><pre>AA 00 14 1B ...</pre><p>It contained one four-point exclusion rectangle:</p><pre>(1960,1080)<br>(2270,1080)<br>(2270, 780)<br>(1960, 780)</pre><p>So even the deleted map’s virtual restrictions had survived intact.</p><h3>Step 5 — Understand Tuya’s DP15 map commands</h3><p>The robot exposes a raw datapoint:</p><pre>DP15<br>code = command_trans<br>type = Raw</pre><p>Tuya’s public laser-sweeper panel source was incredibly useful here.</p><p>It revealed the map-management commands used by Smart Life.</p><h3>Save Current Map</h3><p>The panel sends:</p><pre>AB 00 00000002 2A 01 2B</pre><p>So:</p><pre>0x2A = Save Current Map</pre><p>Base64:</p><pre>qwAAAAACKgEr</pre><h3>Use Map</h3><p>The panel builds:</p><pre>AB<br>version<br>4-byte length<br>2E<br>4-byte map ID<br>4-byte URL length<br>URL<br>checksum</pre><p>So:</p><pre>0x2E = Use Map</pre><h3>Delete Map</h3><p>Similarly:</p><pre>0x2C = Delete Map</pre><p>This was important because it told us that Smart Life does <strong>not</strong> directly upload a saved map.</p><p>Instead:</p><pre>Smart Life<br>    |<br>    | DP15 / 0x2A<br>    v<br>Robot firmware<br>    |<br>    | device-side Tuya SDK<br>    v<br>Tuya cloud map storage</pre><p>The robot itself creates the saved-map files.</p><h3>Step 6 — Discover the difference between history maps and saved maps</h3><p>Tuya has two different concepts.</p><p>Cleaning-history files appear under:</p><pre>file_type = pic</pre><p>Saved multi-floor maps appear under:</p><pre>file_type = collect_recode</pre><p>To understand the difference, I deliberately created a tiny temporary laundry map.</p><p>Before saving it:</p><pre>collect_recode = []</pre><p>I then pressed <strong>Save Map</strong> in Smart Life.</p><p>Afterwards:</p><pre>extend = /mm_map_5_</pre><p>A proper saved-map record now existed.</p><p>When I requested its download links, Tuya returned <strong>two files</strong>:</p><pre>...-map_5.bin<br>...-bin_5.bin</pre><p>This turned out to be crucial.</p><h3>Step 7 — Identify what those two saved-map files actually are</h3><p>The smaller file:</p><pre>-bin_5.bin</pre><p>was essentially the same Tuya layout format as lay.bin.</p><p>The larger file:</p><pre>-map_5.bin</pre><p>was gzip compressed.</p><p>After decompression it was:</p><pre>179,290 bytes</pre><p>I repeated the experiment with another map.</p><p>The new file decompressed to:</p><pre>194,914 bytes</pre><p>The difference was:</p><pre>15,624 bytes</pre><p>The map dimensions had changed from:</p><pre>96 × 93</pre><p>to:</p><pre>117 × 93</pre><p>And:</p><pre>(117 - 96) × 93 × 8<br>= 15,624</pre><p>That was the key observation.</p><p>The proprietary file contained an:</p><pre>8-byte structure per map cell</pre><p>Tuya’s own device SDK documentation describes these two saved-map files conceptually as:</p><pre>bitmap_file   = map used for display in the app<br>datamap_file  = vendor-defined map used for relocation</pre><p>We had found the SL60D’s <strong>relocation map</strong>.</p><h3>Why simply restoring the history file did not work</h3><p>Before reconstructing the proprietary relocation file, I tried feeding the old history binary directly to 0x2E Use Map.</p><p>The robot downloaded it.</p><p>It even returned:</p><pre>AB 00 00000002 2F 01 30</pre><p>which is:</p><pre>0x2F response<br>status 0x01</pre><p>But Smart Life then displayed:</p><pre>No current map<br>Please start global cleaning for map scanning</pre><p>So the command itself had been accepted.</p><p>The file was simply not a valid relocation map.</p><p>That proved:</p><blockquote><strong><em>The historical Tuya display map and the robot’s internal relocation map are different things.</em></strong></blockquote><p>Luckily I had saved my temporary map first, so I could simply press <strong>Use Map</strong> and restore it.</p><p>That rollback step is something I strongly recommend before experimenting.</p><h3>Step 8 — Reverse-engineer the SL60D relocation grid</h3><p>I compared the proprietary relocation files from multiple genuine saved maps against their corresponding Tuya layout files.</p><p>The format was remarkably consistent.</p><p>At the beginning were coordinate/bounds values.</p><p>For example:</p><pre>Y max<br>Y min<br>X min<br>X max<br>640<br>640</pre><p>The dimensions calculated from those bounds exactly matched the Tuya layout:</p><pre>width  = Xmax - Xmin + 1<br>height = Ymax - Ymin + 1</pre><p>The relationship between the Tuya layout header and relocation coordinates was also consistent:</p><pre>xmin = 640 - origin_x // 10<br>xmax = xmin + width - 1</pre><pre>ymax = 640 + origin_y // 10<br>ymin = ymax - height + 1</pre><p>For the recovered map this produced:</p><pre>X min = 406<br>X max = 979</pre><pre>Y min = 417<br>Y max = 794</pre><p>And:</p><pre>979 - 406 + 1 = 574<br>794 - 417 + 1 = 378</pre><p>Exactly matching the recovered map dimensions.</p><h3>Mapping Tuya pixels back into SL60D relocation cells</h3><p>The proprietary grid uses <strong>eight bytes per cell</strong>.</p><p>By aligning genuine saved relocation maps against their corresponding Tuya layout maps, I collected mappings between:</p><pre>Tuya display pixel<br>+<br>surrounding pixel neighbourhood</pre><p>and:</p><pre>SL60D 8-byte relocation cell</pre><p>There were hundreds of distinct 8-byte patterns, but they correlated consistently with the display-map structures.</p><p>For reconstruction I used known-good saved maps as training samples.</p><p>The basic idea was:</p><pre>For every pixel in recovered map 1:</pre><pre>1. Look for the same surrounding 7×7 pattern<br>   in a known genuine saved map.</pre><pre>2. If no exact match exists, try 5×5.</pre><pre>3. Then 3×3.</pre><pre>4. Finally fall back to the most common<br>   SL60D cell seen for that Tuya pixel type.</pre><p>Using this approach, roughly <strong>92% of the recovered map’s cells</strong> could use a learned neighbourhood pattern rather than a simple fallback.</p><p>As a validation test, reconstructing one known map using patterns learned from another achieved roughly <strong>91% byte-level agreement</strong> with the genuine relocation grid.</p><p>That was good enough to try.</p><h3>Step 9 — Build a synthetic relocation map</h3><p>I constructed a new proprietary relocation file with:</p><pre>map ID:      1<br>width:       574<br>height:      378</pre><pre>Y max:       794<br>Y min:       417<br>X min:       406<br>X max:       979</pre><p>The resulting uncompressed file was:</p><pre>1,843,642 bytes</pre><p>It was then gzip compressed.</p><p>But how do you get your own file into the robot?</p><p>That led to another useful discovery.</p><h3>Step 10 — The SL60D will download relocation files from your LAN</h3><p>I started a simple HTTP server on my Mac:</p><pre>python3 -m http.server 8000 --bind 0.0.0.0</pre><p>Then found the Mac’s LAN address:</p><pre>ipconfig getifaddr en0</pre><p>For example:</p><pre>192.168.0.200</pre><p>Before risking the reconstructed map, I tested this with a <strong>genuine saved relocation file</strong>.</p><p>I generated an 0x2E Use Map packet pointing to:</p><pre>http://192.168.0.200:8000/saved_map6_app.bin</pre><p>The robot immediately made:</p><pre>GET /saved_map6_app.bin HTTP/1.1</pre><p>and Smart Life continued displaying the map correctly.</p><p>That proved something incredibly useful:</p><blockquote><strong><em>The SL60D will accept a relocation-map URL on the local network.</em></strong></blockquote><p>No need to upload experimental binaries to a public server.</p><h3>Python encoder for Use Map</h3><p>This generates the required 0x2E packet:</p><pre>import base64</pre><pre>def encode_use_map(map_id: int, url: str) -&gt; str:<br>    url_bytes = url.encode(&quot;utf-8&quot;)</pre><pre>    cmd = 0x2E<br>    map_bytes = map_id.to_bytes(4, &quot;big&quot;)<br>    url_len = len(url_bytes).to_bytes(4, &quot;big&quot;)</pre><pre>    payload_length = (<br>        1 +<br>        len(map_bytes) +<br>        len(url_len) +<br>        len(url_bytes)<br>    )</pre><pre>    checksum = (<br>        cmd +<br>        sum(map_bytes) +<br>        sum(url_len) +<br>        sum(url_bytes)<br>    ) &amp; 0xFF</pre><pre>    packet = (<br>        bytes([0xAB, 0x00]) +<br>        payload_length.to_bytes(4, &quot;big&quot;) +<br>        bytes([cmd]) +<br>        map_bytes +<br>        url_len +<br>        url_bytes +<br>        bytes([checksum])<br>    )</pre><pre>    return base64.b64encode(packet).decode()</pre><pre>url = (<br>    &quot;http://192.168.0.200:8000/&quot;<br>    &quot;recovered_map.bin&quot;<br>)</pre><pre>print(encode_use_map(1, url))</pre><p>The resulting Base64 goes into Tuya’s <strong>Send commands</strong> API:</p><pre>{<br>  &quot;commands&quot;: [<br>    {<br>      &quot;code&quot;: &quot;command_trans&quot;,<br>      &quot;value&quot;: &quot;&lt;BASE64 VALUE&gt;&quot;<br>    }<br>  ]<br>}</pre><h3>Step 11 — Load the reconstructed map</h3><p>I served the synthetic map over HTTP and sent:</p><pre>Use Map<br>map ID = 1<br>URL = local reconstructed relocation file</pre><p>My Python server logged:</p><pre>GET /SL60D_map1_relocation_candidate.bin HTTP/1.1&quot; 200</pre><p>I opened Smart Life.</p><p>And there it was.</p><p><strong>The original full house map was back in the Current Map section.</strong></p><p>At this stage the physical geometry was correct, but initially Smart Life considered almost everything to be one giant room.</p><p>Still, this was the hardest milestone.</p><p>The robot had successfully accepted a synthetic relocation map constructed from a deleted cleaning-history record.</p><h3>Step 12 — Save the recovered geometry normally</h3><p>Once the recovered house existed as the <strong>current map</strong>, I pressed Smart Life’s normal:</p><p><strong>Save Map</strong></p><p>That triggered the legitimate 0x2A save operation.</p><p>Tuya then created:</p><pre>/mm_map_1_</pre><p>under:</p><pre>collect_recode</pre><p>So map 1 was no longer just an experimental file on my Mac.</p><p>The robot itself had uploaded it back to Tuya as a genuine saved multi-map.</p><h3>Step 13 — Recover the room segmentation</h3><p>The physical map was back, but the rooms needed more work.</p><p>I created another controlled experiment using the temporary laundry map.</p><p>First I saved it with one room.</p><p>Then I split it into two rooms and saved it again.</p><p>Comparing the two proprietary relocation grids exposed another important detail.</p><p>Room IDs were encoded in the <strong>first byte of each 8-byte grid cell</strong>.</p><p>Patterns changed like:</p><pre>01 → 02<br>21 → 22<br>41 → 42<br>81 → 82<br>C1 → C2</pre><p>In other words, the lower part of that byte carried the room identity while higher bits represented other cell properties.</p><p>But that wasn’t the whole story.</p><h3>Grid segmentation and room metadata both matter</h3><p>I performed two deliberately broken tests.</p><h3>Test A</h3><pre>two-room grid<br>+<br>one-room metadata</pre><p>Smart Life visually showed the split.</p><p>But the second room was not a real editable room.</p><p>I could not:</p><pre>select it independently<br>rename it<br>merge it</pre><h3>Test B</h3><pre>one-room grid<br>+<br>two-room metadata</pre><p>Smart Life still behaved as though there was only one real room.</p><p>Therefore:</p><blockquote><strong><em>The room IDs in the SLAM grid and the trailing room metadata must agree.</em></strong></blockquote><p>I rebuilt both.</p><p>Using the original map’s pixel segmentation I restored the nine original active room IDs:</p><pre>1<br>2<br>3<br>4<br>5<br>6<br>9<br>10<br>13</pre><p>I also regenerated their room bounding boxes and populated the matching room records in the relocation file.</p><p>After loading this version:</p><p><strong>all nine original rooms appeared and were individually editable.</strong></p><p>They could be selected, renamed and merged normally.</p><h3>Step 14 — Restore the original room names</h3><p>Tuya’s panel protocol contains another useful command:</p><pre>0x24 = set room names</pre><p>Its response is:</p><pre>0x25</pre><p>The frame format used here is the older AA protocol:</p><pre>AA 00 &lt;length&gt; &lt;command&gt; &lt;payload&gt; &lt;checksum&gt;</pre><p>The checksum is simply:</p><pre>(command + sum(payload)) &amp; 0xFF</pre><p>For room names, each record contains:</p><pre>1 byte   room ID<br>1 byte   name length<br>19 bytes UTF-8 name field, zero padded</pre><p>A generic encoder is:</p><pre>import base64</pre><pre>def encode_aa(cmd, payload):<br>    length = 1 + len(payload)<br>    checksum = (cmd + sum(payload)) &amp; 0xFF</pre><pre>    packet = (<br>        bytes([0xAA, 0x00, length, cmd]) +<br>        payload +<br>        bytes([checksum])<br>    )</pre><pre>    return base64.b64encode(packet).decode()<br></pre><pre>def encode_room_names(rooms):<br>    payload = bytearray()</pre><pre>    payload.append(len(rooms))</pre><pre>    for room_id, name in rooms:<br>        encoded = name.encode(&quot;utf-8&quot;)</pre><pre>        if len(encoded) &gt; 19:<br>            raise ValueError(&quot;Room name is too long&quot;)</pre><pre>        payload.append(room_id)<br>        payload.append(len(encoded))<br>        payload += encoded.ljust(19, b&quot;\x00&quot;)</pre><pre>    return encode_aa(0x24, payload)</pre><p>For my recovered map I restored:</p><pre>rooms = [<br>    (1,  &quot;Lounge Room&quot;),<br>    (2,  &quot;Spare bedroom&quot;),<br>    (3,  &quot;Kitchen&quot;),<br>    (4,  &quot;Dining&quot;),<br>    (5,  &quot;Kitchen&quot;),<br>    (6,  &quot;Hallway2&quot;),<br>    (9,  &quot;Livingroom&quot;),<br>    (10, &quot;Master Bedroom&quot;),<br>    (13, &quot;Laundry&quot;),<br>]</pre><pre>print(encode_room_names(rooms))</pre><p>I sent that Base64 through command_trans.</p><p>Every room name appeared immediately.</p><h3>Step 15 — Restore the six virtual walls</h3><p>The history file contained a report frame using:</p><pre>0x13</pre><p>The corresponding set command is:</p><pre>0x12</pre><p>So restoring the walls was simply a matter of taking the historical coordinates and sending them back using the set opcode.</p><p>A generic encoder looks like:</p><pre>def signed_be16(value):<br>    return int(value).to_bytes(<br>        2,<br>        &quot;big&quot;,<br>        signed=True<br>    )<br></pre><pre>def encode_virtual_walls(walls):<br>    payload = bytearray()<br>    payload.append(len(walls))</pre><pre>    for x1, y1, x2, y2 in walls:<br>        payload += signed_be16(x1)<br>        payload += signed_be16(y1)<br>        payload += signed_be16(x2)<br>        payload += signed_be16(y2)</pre><pre>    return encode_aa(0x12, payload)</pre><p>My recovered walls were:</p><pre>walls = [<br>    (-1530, -1350, -930, -1350),<br>    (-1540,   400, -1540, -110),<br>    ( -500,   660,   100,  660),<br>    ( -280,   720,  -280,  540),<br>    (  240,   580,   230,  310),<br>    ( 1250,   650,  1860,  650),<br>]</pre><p>I sent them.</p><p>All six virtual walls immediately reappeared in their original locations.</p><h3>Step 16 — Restore the no-go zone</h3><p>The historical exclusion-zone report used:</p><pre>0x1B</pre><p>The corresponding set command was:</p><pre>0x1A</pre><p>Its payload consisted of:</p><pre>number of zones<br>00<br>number of vertices<br>signed big-endian X/Y coordinates</pre><p>For one four-point zone:</p><pre>def encode_no_go_area(points):<br>    payload = bytearray()</pre><pre>    # one area<br>    payload.append(1)</pre><pre>    # observed SL60D format<br>    payload.append(0)<br>    payload.append(len(points))</pre><pre>    for x, y in points:<br>        payload += signed_be16(x)<br>        payload += signed_be16(y)</pre><pre>    return encode_aa(0x1A, payload)</pre><p>My original rectangle was:</p><pre>no_go = [<br>    (1960, 1080),<br>    (2270, 1080),<br>    (2270,  780),<br>    (1960,  780),<br>]</pre><p>After sending that command:</p><p><strong>the original no-go area reappeared exactly where it had been before.</strong></p><h3>Step 17 — Final save</h3><p>At this point the current map contained:</p><pre>original house geometry<br>original nine room divisions<br>original room names<br>six original virtual walls<br>original no-go rectangle</pre><p>I pressed <strong>Save Map</strong> one final time.</p><p>The robot then uploaded a fresh proper saved-map pair through Tuya’s normal device-side process.</p><p>The recovered map was now a normal saved map under:</p><pre>/mm_map_1_</pre><p>with a working:</p><pre>Use Map</pre><p>button.</p><p>At that point the recovery was complete.</p><h3>What surprised me most</h3><p>Several things about this process were unexpected.</p><p>The first was how much information remained in the cleaning-history file.</p><p>It contained far more than a rendered historical image.</p><p>It retained:</p><pre>complete map geometry<br>room IDs<br>room metadata<br>cleaning route<br>virtual walls<br>no-go zones</pre><p>The only major thing missing was the robot’s vendor-specific <strong>relocation map</strong>.</p><p>The second surprise was that the relocation map was not encrypted or completely opaque.</p><p>Once multiple legitimate saved-map examples were compared, its dimensions and eight-byte-per-cell structure became visible.</p><p>And finally, I did not expect the robot to happily download a relocation map from an ordinary HTTP server on my LAN.</p><p>That made safe iterative testing considerably easier.</p><h3>The architecture, in one diagram</h3><p>The whole system now makes much more sense:</p><pre>SMART LIFE / TUYA</pre><pre>Cleaning History<br>      |<br>      | file_type=pic<br>      |<br>      +---- Tuya display map<br>      +---- cleaning route<br>      +---- walls/no-go metadata<br></pre><pre>Current Robot Map<br>      |<br>      +---- live lay.bin<br>      +---- internal SL60D relocation state<br></pre><pre>Saved Multi-Map<br>      |<br>      | file_type=collect_recode<br>      |<br>      +---- Tuya display-map file<br>      |<br>      +---- SL60D vendor relocation file<br>                    |<br>                    |<br>             used by 0x2E Use Map</pre><p>And:</p><pre>Smart Life &quot;Save Map&quot;<br>        |<br>        | 0x2A<br>        v<br>SL60D firmware<br>        |<br>        | tuya_iot_map_upload_files(...)<br>        v<br>Tuya saved multi-map</pre><p>That explains why there is no obvious public cloud API that simply says:</p><pre>upload this file and make it a saved map</pre><p>The robot is expected to do that part.</p><h3>If you are trying this yourself</h3><p>The safest order I would recommend is:</p><pre>1. Find a known-good historical cleaning record.</pre><pre>2. Download its history binary.</pre><pre>3. Identify the historical layout length from `extend`.</pre><pre>4. Extract and decode the Tuya layout.</pre><pre>5. Verify that it contains the map and rooms you want.</pre><pre>6. Save whatever current map you have as a rollback.</pre><pre>7. Download that genuine saved-map pair.</pre><pre>8. Create at least one or preferably several controlled<br>   saved maps so you can study your firmware&#39;s relocation format.</pre><pre>9. Compare the proprietary relocation grid with the matching<br>   Tuya layout grid.</pre><pre>10. Reconstruct the old relocation map.</pre><pre>11. Test local HTTP delivery using a known-good relocation file.</pre><pre>12. Load the reconstructed map using 0x2E.</pre><pre>13. If the geometry appears, save it normally.</pre><pre>14. Reconstruct room IDs and room metadata.</pre><pre>15. Restore room names.</pre><pre>16. Restore virtual walls.</pre><pre>17. Restore no-go zones.</pre><pre>18. Save the finished map again.</pre><pre>19. Download and archive the final saved-map pair.</pre><p>Do not start by blindly replaying old command_trans values.</p><p>And do not experiment without first creating a saved rollback map.</p><h3>Back up the final files</h3><p>Once everything was restored, I downloaded the final saved-map pair.</p><p>If you have gone through this much effort, keep those files somewhere safe.</p><p>I would archive:</p><pre>final saved relocation file<br>final Tuya display-map file<br>original cleaning-history binary<br>historical record ID<br>map ID<br>room list<br>virtual-wall coordinates<br>no-go coordinates</pre><p>If something breaks again, having those files should make recovery dramatically easier.</p><h3>Final thoughts</h3><p>This started with what looked like a simple question:</p><blockquote><em>“Can I restore an old map from Smart Life cleaning history?”</em></blockquote><p>The official answer appears to effectively be <strong>no</strong>.</p><p>There is no Restore button.</p><p>But the underlying data told a different story.</p><p>The old map still existed.</p><p>The room information still existed.</p><p>The virtual boundaries still existed.</p><p>And with a few controlled experiments, it was possible to infer enough of the SL60D’s proprietary relocation format to rebuild the one missing component.</p><p>The result was not a screenshot or approximate recreation.</p><p>The robot accepted the reconstructed data as a real map, localised against it, allowed Smart Life to edit the recovered rooms, and then uploaded the restored map back into Tuya through its normal save mechanism.</p><p>So the final recovery path became:</p><pre>deleted map<br>    ↓<br>cleaning-history binary<br>    ↓<br>recover Tuya layout<br>    ↓<br>reverse-engineer SL60D relocation grid<br>    ↓<br>reconstruct vendor relocation file<br>    ↓<br>0x2E Use Map<br>    ↓<br>original house becomes current map<br>    ↓<br>restore room metadata<br>    ↓<br>restore room names<br>    ↓<br>restore virtual walls<br>    ↓<br>restore no-go zone<br>    ↓<br>0x2A Save Map<br>    ↓<br>normal Tuya /mm_map_1_ saved map</pre><p>And somehow, against all expectations:</p><p><strong>It worked.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13cbe9bf2898" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automating Apache Guacamole on GCP — The Full Enchilada.]]></title>
            <link>https://calum-h.medium.com/automating-apache-guacamole-on-gcp-the-full-enchilada-a2c8c5075b18?source=rss-fc272f24dd85------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2c8c5075b18</guid>
            <category><![CDATA[apache-guacamole]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Calum Hunter]]></dc:creator>
            <pubDate>Thu, 30 May 2024 23:50:51 GMT</pubDate>
            <atom:updated>2024-05-30T23:50:51.480Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Automating Apache Guacamole on GCP — The Full Enchilada.</strong></h3><h4><strong>Introduction</strong></h4><p>This blog post outlines a solution I have implemented for my GCP environment, offering a centralised bastion solution tailored for the multi-project configurations within GCP.</p><p>This solution prioritises top tier security and traceability, meeting the stringent requirements of compliance teams.</p><p>I’m excited to share this insight as it showcases an event driven architecture utilising GCP services and serverless technology which is able to seamlessly augment and integrate existing software into cloud environments, even if they were not initially designed with cloud native principles in mind</p><h4>Why do we need this?</h4><p>Within most enterprise GCP environments, there is often a need or a requirement for a centralised remote access solution to manage access to Windows VM instances across various projects and associated networks.</p><p>Unfortunately, GCP lacks a native remote access feature like AWS session manager. Apache Guacamole emerges as a crucial tool that can be used to bridge this gap.</p><p>As part of this solution the bastion system should possess the following capabilities:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*OsqMwa18sUfuZo54wXxHTg.png" /></figure><h4>What’s the solution?</h4><p>A similar solution for AWS exists and uses CloudWatch events to trigger automation for Instance Auto discovery— this project has been dubbed Enchilada.</p><p>We will utilise similar frameworks — but swapping out the AWS components for GCP components such as Pubsub, Cloud Log Sinks and Cloud Functions.</p><p>The core components of this solution are:</p><p><strong>Apache Guacamole</strong><br>Deployed as a GCE Instance in a managed instance group, sitting behind a internal application load balancer.</p><p>Guacamole is integrated with Active Directory for Identity. Guacamole is a client-less remote desktop gateway. It supports standard protocols like VNC, RDP and SSH.</p><p>It uses HTML5 — so it can be used to access remote sessions with only a standard web browser. It provides integration to common single sign on systems such as Active Directory. It also has the capability to utilise MFA (Multi Factor Authentication)</p><p>To provide high quality compliance data, the GCE instances upon which Guacamole is running are configured with cron jobs to regularly copy the recorded session data from the GCE instances to a GCE bucket for storage.</p><p><strong>Instance Auto Discovery automation — The Enchilada<br></strong>This automation functions by leveraging Log sinks and Pubsub when GCE Instances are launched or terminated in GCP projects.</p><p>When these events occur they are passed through to a centralised project which contains a cloud function that is able to connect to the Apache Guacamole instance and utilising the Guacamole REST API, it is able to update the configuration to add or remove the corresponding instance from its configuration.</p><p>To ensure that the GCE instances that are populated automatically inside the Guacamole application and configured correctly, the Cloud Function retrieves the DNS name, IP address, project id and other metadata about the instance for use when adding the instance record to Guacamole.</p><p>As a result when GCE instances are launched and terminated across the GCP Organisation they are automatically configured in Guacamole so that end users do not need to configure or remove any connections themselves as it is automatically handled for them. All the end users need to do is find their GCE instance by name and double click on it and it will automatically connect for them and pass through their authentication credentials.</p><p>The solution utilises the following GCP services:<br>- Cloud Functions<br>- PubSub<br>- Cloud Log Sink<br>- Secret Manager<br>- CloudSQL Postgresql<br>- Cloud Storage<br>- Compute Engine / Managed Instance Group<br>- Cloud Load Balancing<br>- Cloud DNS</p><h4>High Level Solution Overview</h4><p>The two core components of the solution are detailed above. To align with well architected principals, these components:</p><ul><li>Are deployed using Terraform (Infrastructure as Code) and utilise GitLab CI/CD pipelines for deployment.</li><li>Ensure the use of least privilege model for all IAM Policies.</li><li>Any secrets are stored securely in GCP Secret Manager.</li><li>Utilise event driven and serverless components where possible to ensure cost of the solution is kept to a minimum.</li></ul><h4>Apache Guacamole Deployment</h4><p>A typical GCP organisation structure utilises a Shared VPC model, so I will use that as our structure for this example.</p><p>Here Apache Guacamole is deployed into a standard service project in the Shared VPC</p><p>A CI/CD pipeline utilising HashiCorp Packer is used to create the Apache Guacamole VM image, based upon the latest Ubuntu image.</p><p>We use a simple bash script to boot strap the image with all the required packages and configuration settings.</p><p>An example of this bootstrap script is shown here:</p><pre>#!/bin/bash<br><br># Ref: https://computingforgeeks.com/install-guacamole-remote-desktop-on-ubuntu-jammy-jellyfish/<br><br>## Install Guac ##<br># Set the guacamole client/server version here<br>VERS=&quot;1.5.3&quot;<br><br># Configure needrestart for Ubuntu 22<br>sed -i &quot;/#\$nrconf{restart} = &#39;i&#39;;/s/.*/\$nrconf{restart} = &#39;a&#39;;/&quot; /etc/needrestart/needrestart.conf<br><br># Install deps<br>apt-get update<br><br>apt-get install -y \<br>libcairo2-dev \<br>libjpeg-turbo8-dev \<br>libpng-dev \<br>libtool-bin \<br>uuid-dev \<br>libavcodec-dev \<br>libavformat-dev \<br>libavutil-dev \<br>libswscale-dev \<br>freerdp2-dev \<br>libpango1.0-dev \<br>libssh2-1-dev \<br>libtelnet-dev \<br>libvncserver-dev \<br>libwebsockets-dev \<br>libpulse-dev \<br>libssl-dev \<br>libvorbis-dev \<br>libwebp-dev \<br>make \<br>maven \<br>npm \<br>postgresql-client \<br>openjdk-11-jdk<br><br># Download the Guac Server source code<br>wget https://dlcdn.apache.org/guacamole/$VERS/source/guacamole-server-$VERS.tar.gz<br><br># Extract zip<br>tar -xzf guacamole-server-$VERS.tar.gz<br><br># Do the build<br>cd guacamole-server-$VERS/<br>autoreconf -fi<br>./configure --with-init-dir=/etc/init.d<br>make<br>make install<br>ldconfig<br>cd ..<br><br># ensure java home is set<br>export JAVA_HOME=$(update-alternatives --query javadoc | grep Value: | head -n1 | sed &#39;s/Value: //&#39; | sed &#39;s@bin/javadoc$@@&#39;)<br><br># Install Tomcat 9<br>apt-get install -y tomcat9 tomcat9-admin tomcat9-common tomcat9-user tomcat9-docs tomcat9-examples<br><br># Enable tomcat<br>systemctl enable tomcat9<br><br># Open fw<br>ufw allow 8080/tcp<br><br># Set up Guac Server<br>mkdir -p /etc/guacamole/{extensions,lib}<br><br># Create guacd.conf<br>touch /etc/guacamole/guacd.conf<br>cat &lt;&lt;EOT &gt;&gt; /etc/guacamole/guacd.conf<br>[daemon]<br>pid_file = /var/run/guacd.pid<br>#log_level = debug<br><br>[server]<br>#bind_host = localhost<br>bind_host = 127.0.0.1<br>bind_port = 4822<br><br>#[ssl]<br>#server_certificate = /etc/ssl/certs/guacd.crt<br>#server_key = /etc/ssl/private/guacd.key<br>EOT<br><br># Refresh deamons<br>systemctl daemon-reload<br><br># start and enable guacd<br>systemctl enable guacd<br>systemctl start guacd<br><br><br>##### Guac Client setup #######<br><br># Download the prebuild binary - We don&#39;t build this from source because we are unable to build v1.5.3 due to this error:<br># [ERROR] Failed to execute goal com.github.eirslett:frontend-maven-plugin:1.11.3:npm (npm-build) on project guacamole: Failed to run task: &#39;npm run build&#39; failed.<br># See: https://aur.archlinux.org/packages/guacamole-client<br><br># Download the binary <br>wget https://dlcdn.apache.org/guacamole/$VERS/binary/guacamole-$VERS.war<br><br># Move it into the tomcat dir<br>mv guacamole-$VERS.war /var/lib/tomcat9/webapps/ROOT.war<br># Move aside the default tomcat ROOT folder<br>mv /var/lib/tomcat9/webapps/ROOT /var/lib/tomcat9/webapps/ROOT-TCMGR-BKUP<br><br># Config guac <br>echo &#39;GUACAMOLE_HOME=/etc/guacamole&#39; &gt;&gt; /etc/default/tomcat9<br>echo &quot;export GUACAMOLE_HOME=/etc/guacamole&quot; &gt;&gt; /etc/profile<br><br># Configure Database Auth using PostgreSQL on CloudSQL<br># A Cloud SQL Instance with a database for guacamole should be created already<br><br># Install cloudsql proxy to talk to our Cloud SQL PostgreSQL DB<br>CLOUD_SQL_PROXY_VERS=&quot;2.7.2&quot;<br><br>curl -o cloud-sql-proxy https://storage.googleapis.com/cloud-sql-connectors/cloud-sql-proxy/v${CLOUD_SQL_PROXY_VERS}/cloud-sql-proxy.linux.amd64<br>mv cloud-sql-proxy /usr/local/bin<br>chmod +x /usr/local/bin/cloud-sql-proxy<br><br># Download the postgres DB Auth Extension<br>wget https://dlcdn.apache.org/guacamole/$VERS/binary/guacamole-auth-jdbc-$VERS.tar.gz<br>tar -xzf guacamole-auth-jdbc-$VERS.tar.gz<br><br># Move the Auth extension into the guac folder<br>mv guacamole-auth-jdbc-$VERS/postgresql/guacamole-auth-jdbc-postgresql-$VERS.jar /etc/guacamole/extensions/<br><br># Download the Posgres JDBC Driver<br>wget https://jdbc.postgresql.org/download/postgresql-42.6.0.jar<br><br># Move the jdbc driver into the guac folder<br>mv postgresql-42.6.0.jar /etc/guacamole/lib/<br><br># Configure Guacamole with Active Directory auth<br>wget https://dlcdn.apache.org/guacamole/$VERS/binary/guacamole-auth-ldap-$VERS.tar.gz<br>tar -xzf guacamole-auth-ldap-$VERS.tar.gz<br>cp guacamole-auth-ldap-$VERS/guacamole-auth-ldap-$VERS.jar /etc/guacamole/extensions<br><br>## Make directory to store session recordings<br>mkdir -p /session_recordings<br>mkdir -p /usr/local/scripts<br><br># Create the log file first<br>touch &quot;/var/log/session_recordings_sync.log&quot;<br>chmod 0640 &quot;/var/log/session_recordings_sync.log&quot;<br><br>## Setup log rotation for the sessions script<br>touch /etc/logrotate.d/session_recordings_sync<br>cat &lt;&lt;EOT &gt;&gt; /etc/logrotate.d/session_recordings_sync<br>/var/log/session_recordings_sync.log {<br>    daily<br>    rotate 30<br>    compress<br>    delaycompress<br>    missingok<br>    notifempty<br>    create 0640 root root<br>}<br>EOT<br><br># update the root crontab<br>echo &quot;*/15 * * * * /usr/local/scripts/sync_rdp_sessions_to_gcloud.sh&quot; &gt;&gt; new_cron_job<br>crontab new_cron_job<br>rm new_cron_job</pre><p>Additional site specific configuration is added via a startup script which is attached to the instance metadata.</p><p>A managed instance group is then created containing the instances running the Guacamole VM image.</p><p>This managed instance group is then sitting behind an Application Load Balancer.</p><p>Cloud DNS is utilised for name resolution to the ALB</p><p>Apache Guacamole utilises a PostgreSQL database backend and this is deployed on Cloud SQL. This database contains the application state, integration of the service into AD and the configuration of connection settings for Instances that are exposed to end users (Connection Name, Instance Name, IP address, OS Type, Connection Type)</p><p>Remote desktop sessions over RDP are recorded as MP4 files and stored on a GCS bucket with the appropriate retention and lifecycle configuration.</p><h4>The Enchilada Deployment</h4><p>The automatic creation of connections in the Guacamole user interface leverages the instance discovery automation solution we have called ‘The Full Enchilada” as a homage to the AWS solution.</p><p>The diagram below shows the core components of the solution and their connections.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7rV-QeRIPH_sSIOjlK7myA.png" /></figure><h4>Cloud Log Sink</h4><p>Log sink lets us send specific log events from services to a Pubsub topic. In our case for discovery the events we are interested in are:</p><pre>protoPayload.methodName=&quot;v1.compute.instances.start&quot;<br>OR protoPayload.methodName=&quot;v1.compute.instances.startWithEncryptionKey&quot;<br>OR protoPayload.methodName=&quot;v1.compute.instances.resume&quot;<br>OR protoPayload.methodName=&quot;v1.compute.instances.reset&quot;<br>OR protoPayload.methodName=&quot;v1.compute.instances.insert&quot;<br><br>OR protoPayload.methodName=&quot;beta.compute.instances.start&quot;<br>OR protoPayload.methodName=&quot;beta.compute.instances.startWithEncryptionKey&quot;<br>OR protoPayload.methodName=&quot;beta.compute.instances.resume&quot;<br>OR protoPayload.methodName=&quot;beta.compute.instances.reset&quot;<br>OR protoPayload.methodName=&quot;beta.compute.instances.insert&quot;<br><br>OR protoPayload.methodName=&quot;v1.compute.instances.stop&quot;<br>OR protoPayload.methodName=&quot;v1.compute.instances.suspend&quot;<br>OR protoPayload.methodName=&quot;v1.compute.instances.delete&quot;<br><br>OR protoPayload.methodName=&quot;beta.compute.instances.stop&quot;<br>OR protoPayload.methodName=&quot;beta.compute.instances.suspend&quot;<br>OR protoPayload.methodName=&quot;beta.compute.instances.delete&quot;</pre><p>When an event in the consumer project occurs that matches one of these method types the log is then sent as a message to our Pubsub topic in our Guacamole GCP project.</p><h4>Cloud Function</h4><p>The Enchilada cloud function is really where all the magic occurs.<br>The function is trigged by messages sent to a Pubsub topic. For our purposes we wrote the function in Python so as to take advantage of the Python Guacamole API Wrapper:<br><a href="https://pypi.org/project/guacamole-api-wrapper/">https://pypi.org/project/guacamole-api-wrapper/</a><br><a href="https://gitlab.com/gacybercenter/open/guacamole-api-wrapper">https://gitlab.com/gacybercenter/open/guacamole-api-wrapper</a></p><h4>Guacamole REST API</h4><p>The Guacamole API is not very well (or at all) documented by Apache.<br>The best resource I was able to find at the time was here:<br><a href="https://github.com/ridvanaltun/guacamole-rest-api-documentation">https://github.com/ridvanaltun/guacamole-rest-api-documentation</a></p><p>One thing that I did find that was missing from the Guacamole API wrapper was a method to return child connections for a given connection group ID.</p><p>Here is an example using the requests module to retrieve this data directly from the Guacamole REST API for reference.</p><pre>def get_connection_group_connections(connection_group_id):<br>    &#39;&#39;&#39;<br>    Returns a json output containing child connections for a given connection group id <br>    &#39;&#39;&#39;<br>    try:<br>        response = requests.get(<br>            f&quot;{GUACAMOLE_BASE_URL}/api/session/data/{DATASOURCE}/connectionGroups/{connection_group_id}/tree&quot;,<br>            params={&quot;token&quot;: generate_token()},<br>            verify=False,<br>            timeout=12<br>        ).text<br>    except Exception as e:<br>        error_message = &quot;There was an error retreiving a json output of child connections for a given connection group id&quot;<br>        print(f&quot;{error_message}&quot;, {e})<br>    try:<br>        return json.loads(response)<br>    except json.JSONDecodeError:<br>        error_message = &quot;There was an error generating a guacamole auth token&quot;<br>        print(f&quot;{error_message}&quot;, {response})<br>        return response</pre><p>Rather than simply copy paste our full cloud function code here which would not be appropriate due the number of organisation specific customisations and business logic. I will instead detail the general workflow process and provide a basic example of how our workflow operates.</p><p>We start off by declaring our modules and global variables</p><pre>import guacamole<br>import requests<br>import base64<br>import json<br>import os<br>from pprint import pprint<br>from google.cloud import compute_v1<br>from google.cloud import exceptions<br>from google.cloud import pubsub_v1<br><br># Get and set some GLOBAL VARS<br>GUACAMOLE_BASE_URL  = &#39;https://guacamole.local&#39;<br>DATASOURCE          = &#39;postgresql&#39;<br>AD_USER_GROUP       = &#39;guacamole-users&#39;<br><br># Get some secrets from secret manager<br># This account is the guacadmin account used to access guacamole API<br>GUAC_USERNAME = &#39;guacamole-admin&#39;<br>GUAC_PASSWORD = &#39;guacamole-password&#39;<br></pre><p>We then define all our required functions.</p><pre>def client_session(guacamole_base_url, datasource, guac_username, guac_password):<br>    &#39;&#39;&#39;<br>    This will establish a Guacamole API session and retun it as an object    <br>    &#39;&#39;&#39;<br>    try:<br>        session = guacamole.session(<br>            guacamole_base_url,<br>            datasource,<br>            guac_username,<br>            guac_password<br>        )<br>    except Exception as e:<br>        error_message = &quot;An error occured establishing a Guacamole API Session object&quot;<br>        print(f&quot;{error_message}&quot;, {e})<br>    return session<br><br><br>def get_parent_identifier(session, connection_group_name):<br>    &#39;&#39;&#39;<br>    This will return a identifer for a given connection group name<br>    &#39;&#39;&#39;<br>    # Get all the Connection Groups<br>    try:<br>        result = session.list_connection_groups()<br>        for key, value in result.items():<br>            if value[&#39;name&#39;] == connection_group_name:<br>                con_group_parent_id = value[&#39;identifier&#39;] <br>                break<br>        else:<br>            print(f&quot;No connection group with the name {connection_group_name} found in the connection groups&quot;)<br>            return None<br>        return con_group_parent_id<br>    except Exception as e:<br>        error_message = &quot;An Error occured retrieving the identifier for a given connection group name&quot;<br>        print(f&quot;{error_message}&quot;, {e})<br><br><br>def create_connection_group(session, connection_group_name):<br>    &#39;&#39;&#39;<br>    Creates a new connection group<br>    &#39;&#39;&#39;<br>    try:<br>        result = session.create_connection_group(group_name=connection_group_name)<br>        return result<br>    except Exception as e:<br>        error_message = &quot;An error occured creating a new connection group&quot;<br>        print(f&quot;{error_message}&quot;, {e})<br><br><br>def manage_rdp_connection(session, connection_name, connection_ip_address, connection_group_id, connection_id: str | None = None):<br>    &#39;&#39;&#39; <br>    Managess a RDP connection<br>    Will create or update the connection under the given parent connection group<br>    &#39;&#39;&#39;<br>    # Define the RDP connection <br>    rdp_session_params = {<br>    &quot;port&quot;: &quot;3389&quot;,<br>    &quot;hostname&quot;: connection_ip_address,<br>    &quot;username&quot;: &#39;${GUAC_USERNAME}&#39;,<br>    &quot;password&quot;: &#39;${GUAC_PASSWORD}&#39;,<br>    &quot;ignore-cert&quot;: True,<br>    &quot;enable-wallpaper&quot;: True,<br>    &quot;enable-theming&quot;: True,<br>    &quot;enable-font-smoothing&quot;: True,<br>    &quot;enable-full-window-drag&quot;: True,<br>    &quot;enable-desktop-composition&quot;: True,<br>    &quot;enable-menu-animations&quot;: True,<br>    &quot;recording-path&quot;: &quot;/session_recordings&quot;,<br>    &quot;recording-name&quot;: &#39;${GUAC_USERNAME}_${GUAC_DATE}_${GUAC_TIME}&#39;<br>    }<br><br>    try:<br>        result = session.manage_connection(<br>            protocol=&quot;rdp&quot;,<br>            name=connection_name,<br>            parent_identifier=connection_group_id,<br>            identifier=connection_id,<br>            parameters=rdp_session_params<br>        )<br>        print(&quot;&quot;)<br>        return result<br>    except Exception as e:<br>        error_message = &quot;There was an error creating or updating the RDP connection.&quot;<br>        print(f&quot;{error_message}&quot;, {e})<br><br><br>def get_user_groups(session, ad_user_group):<br>    &#39;&#39;&#39;<br>    This will return a identifer for a given user group if it exists <br>    &#39;&#39;&#39;<br>    # Get all the user groups<br>    try:<br>        user_groups = session.list_usergroups()<br>        print(f&quot;- Checking for AD User group: {ad_user_group}&quot;)<br>        # Check if we have a group that matches {ad_user_group}<br>        if ad_user_group in user_groups:<br>            print(f&quot;  - User group: {ad_user_group} already exists as: {user_groups[ad_user_group]}&quot;)<br>            print(&quot;&quot;)<br>            return user_groups[ad_user_group]<br>        else:<br>            return None<br>    except Exception as e:<br>        error_message = &quot;There was an error retrieving the identifer for a given user group.&quot;<br>        print(f&quot;{error_message}&quot;, {e})<br><br><br>def create_user_group(session, ad_user_group):<br>    &#39;&#39;&#39;<br>    Creates a new user group<br>    &#39;&#39;&#39;<br>    print(f&quot;- Creating user group: {ad_user_group}&quot;)<br>    try:<br>        user_group = session.create_usergroup(ad_user_group)<br>        print(&quot;- User group created successfully!&quot;)<br>        print(&quot;&quot;)<br>        return user_group<br>    except Exception as e:<br>        error_message = &quot;There was an error creating a new user group&quot;<br>        print(f&quot;{error_message}&quot;, {e})<br><br><br>def update_user_group_connections(session, ad_user_group, connection_id, operation, connection_type):<br>    &#39;&#39;&#39;<br>    Adds or removes a connection ID or connection group ID to a given user group<br>    &#39;&#39;&#39;<br>    try:<br>        group_connections = session.update_usergroup_connections(<br>            ad_user_group,<br>            connection_id,<br>            operation,<br>            connection_type<br>        )<br>        print(f&quot;- Successfully added connection {connection_type} id: {connection_id} to: {ad_user_group}&quot;)<br>        return group_connections<br>    except Exception as e:<br>        error_message = &quot;There was an error updating a user group with connection ids&quot;<br>        print(f&quot;{error_message}&quot;, {e})<br><br><br>def delete_connection(session, connection_id):<br>    &#39;&#39;&#39;<br>    Deletes a connection with the given connection id<br>    &#39;&#39;&#39;<br>    try:<br>        connection = session.delete_connection(connection_id)<br>        return connection<br>    except Exception as e:<br>        error_message = &quot;There was an error Deleting a connection with the given connection id&quot;<br>        print(f&quot;{error_message}&quot;, {e})<br><br><br>def delete_connection_group(session, connection_group_id):<br>    &#39;&#39;&#39;<br>    Deletes a connection group with the given connection id<br>    &#39;&#39;&#39;<br>    try:<br>        connection_group = session.delete_connection_group(connection_group_id)<br>        return connection_group<br>    except Exception as e:<br>        error_message = &quot;There was an error Deleting a connection group with the given connection id&quot;<br>        print(f&quot;{error_message}&quot;, {e})<br><br><br>def generate_token():<br>    &#39;&#39;&#39;<br>    Generates a token by sending a POST request to the API endpoint<br>    &#39;/api/tokens&#39; with the provided username and password.<br><br>    Returns:<br>    The authentication token extracted from the JSON response.<br>    &#39;&#39;&#39;<br>    try:<br>        response = requests.post(<br>            f&quot;{GUACAMOLE_BASE_URL}/api/tokens&quot;,<br>            data={&quot;username&quot;: GUAC_USERNAME, &quot;password&quot;: GUAC_PASSWORD},<br>            verify=False,<br>            timeout=12,<br>            headers={&quot;Content-Type&quot;: &quot;application/x-www-form-urlencoded&quot;}<br>        ).text<br><br>        try:<br>            return json.loads(response)[&#39;authToken&#39;]<br>        except json.JSONDecodeError:<br>            error_message = &quot;There was an error generating a guacamole auth token&quot;<br>            print(f&quot;{error_message}&quot;, {response})<br>            return response<br>    except Exception as e:<br>        error_message = &quot;There was an error generating a guacamole auth token&quot;<br>        print(f&quot;{error_message}&quot;, {e})<br><br><br>def get_connection_group_connections(connection_group_id):<br>    &#39;&#39;&#39;<br>    Returns a json output containing child connections for a given connection group id <br>    &#39;&#39;&#39;<br>    try:<br>        response = requests.get(<br>            f&quot;{GUACAMOLE_BASE_URL}/api/session/data/{DATASOURCE}/connectionGroups/{connection_group_id}/tree&quot;,<br>            params={&quot;token&quot;: generate_token()},<br>            verify=False,<br>            timeout=12<br>        ).text<br>    except Exception as e:<br>        error_message = &quot;There was an error retreiving a json output of child connections for a given connection group id&quot;<br>        print(f&quot;{error_message}&quot;, {e})<br>  <br>    try:<br>        return json.loads(response)<br>    except json.JSONDecodeError:<br>        error_message = &quot;There was an error generating a guacamole auth token&quot;<br>        print(f&quot;{error_message}&quot;, {response})<br>        return response<br><br><br>def get_connection_id_from_connection_group(connection_name, connection_group_id):<br>    &#39;&#39;&#39;<br>    This will retrieve a list of connections in a given connection group id<br>    It will then return the connection id for a given connection name, in the connection group (if it exists)<br>    &#39;&#39;&#39;<br>    try:<br>        connection_group_connections = get_connection_group_connections(connection_group_id)<br>        for connection in connection_group_connections[&#39;childConnections&#39;]:<br>            if connection[&#39;name&#39;] == connection_name:<br>                return connection[&#39;identifier&#39;]<br>        return None<br>    except Exception as e:<br>        error_message = &quot;There was an error getting a list of connections in a given connection group id&quot;<br>        print(f&quot;{error_message}&quot;, {e})<br><br><br>def get_connection_details(session, connection_id, detail):<br>    &#39;&#39;&#39;<br>    Get details about a connection based on the given connection_id and the request &#39;detail&#39;<br><br>    Args:<br>    connection_id: The connection identifier<br>    detail: the detail requested, options are &#39;parameters&#39;, &#39;history&#39; and &#39;sharing profiles&#39;<br>    &#39;&#39;&#39;<br>    try:<br>        details = session.detail_connection(<br>                                    identifier=connection_id,<br>                                    option=detail<br>                                    )<br>        return details<br>    except Exception as e:<br>        error_message = &quot;There was an error getting details about a connection based on the connection id and the request detail.&quot;<br>        print(f&quot;{error_message}&quot;, {e})<br><br><br>def get_instance_info(project_id, zone, instance_name):<br>    &#39;&#39;&#39;<br>    Get the info about an GCE Instance<br>    &#39;&#39;&#39;<br>    compute_client = compute_v1.InstancesClient()<br>    try: <br>    # Get the instance details<br>        instance = compute_client.get(project=project_id, zone=zone, instance=instance_name)<br>        return instance<br>    except exceptions.NotFound:<br>        print(f&quot;Instance: {instance} not found.&quot;)<br>        return None<br>    except exceptions.GoogleAuthError as auth_error:<br>        print(f&quot;Google Auth Error: {auth_error}&quot;)<br>        return None<br>    except Exception as e:<br>        return None<br><br><br>def get_instance_ip(instance):<br>    &#39;&#39;&#39;<br>    Extract the instance IP from the instance info block passed in<br>    &#39;&#39;&#39;<br>    try:<br>        ip_address = instance.network_interfaces[0].network_i_p<br>        return ip_address<br>    except Exception as e:<br>        error_message = &quot;There was an error retrieving the IP address from the instance info block&quot;<br>        print(f&quot;{error_message}&quot;, {e})<br><br><br>def determine_os_type(instance):<br>    &#39;&#39;&#39;<br>    Determine the OS type without needing to enable and use the OS Config (VM Manager) API<br>    and instead just inspec the instance info and look at the licences for the disks<br>    &#39;&#39;&#39;<br>    try:<br>        if instance and instance.disks:<br>            for disk in instance.disks:<br>                if disk.licenses and any(&#39;windows&#39; in license.lower() for license in disk.licenses):<br>                    return &#39;Windows&#39;<br>            return &quot;Linux&quot;<br>        else:<br>            return &quot;Unknown&quot;<br>    except Exception as e:<br>        error_message = &quot;There was an error determining the OS type&quot;<br>        print(f&quot;{error_message}&quot;, {e})<br><br></pre><p>Now we get into the nitty gritty workflow.</p><p>We receive the log message from Pubsub, we then look through this message to find out the operation type (add/remove)</p><p>We also get a bunch of information about the VM including the OS Type, as we only care about Windows machines at this time.</p><p>If we receive an add operation we go ahead and check to see if we have an existing connection group (GCP Project) that we can add this connection (VM) to. If not, we will go ahead and create one.</p><p>Next, we check to see if we already have a VM by this name in that connection group, if we do, then we check to see if we need to update details for it like the IP address, if not then we go ahead and create the connection.</p><p>Then we check to see if we have created the required user group to match our AD group for access control to these machines. If it doesn’t exist we go ahead and create it</p><p>Once that is done we then add the appropriate AD Group/User group to the connection and the connection group so that members of the user group are able to access the Connections and Connection Groups</p><p>If we received a delete operation, then we look for the connection group the connection should be a member of, and we check to see if a connection with the same name exists here, if it does then we delete it.</p><p>After that we check to see if there are still connections in the connection group, if there are then we do nothing. But if there are no more connections in the connection group then we delete the connection group as well to clean it up.</p><p>Below is some example code for the above workflow:</p><pre>def hello_pubsub(event, context):<br>    &#39;&#39;&#39;<br>    This function runs our main script to configure Guacamole<br>    &#39;&#39;&#39;<br>    try:<br>        print(&quot; - BEGINNING GUACAMOLE CONNECTION CLOUD FUNCTION&quot;)<br>        pubsub_message = base64.b64decode(event[&#39;data&#39;]).decode(&#39;utf-8&#39;)<br>        payload_json = json.loads(pubsub_message)<br>        payload = payload_json[&#39;protoPayload&#39;]<br>        if &#39;response&#39; in payload:<br>            print(&quot; - GETTING THE CLOUD EVENT PAYLOAD&quot;)<br>            print(&quot;&quot;)<br>            print(f&quot;    - OperationType:    {payload[&#39;response&#39;][&#39;operationType&#39;]}&quot;)<br><br>            resource_name   = payload.get(&#39;resourceName&#39;)<br>            resource_parts  = resource_name.split(&quot;/&quot;)<br>            instance_index  = resource_parts.index(&quot;instances&quot;)<br>            project_index   = resource_parts.index(&quot;projects&quot;)<br>            zone_index      = resource_parts.index(&quot;zones&quot;)<br>            connection_name = resource_parts[instance_index + 1]<br>            vm_zone         = resource_parts[zone_index + 1]<br><br>            connection_group_name   = resource_parts[project_index + 1]<br>            operation_type          = payload[&#39;response&#39;][&#39;operationType&#39;]<br>            instance_info           = get_instance_info(connection_group_name, vm_zone, connection_name)<br>            vm_os                   = determine_os_type(instance_info)<br>            connection_ip_address   = get_instance_ip(instance_info)<br><br>            if operation_type == &quot;start&quot; or operation_type == &quot;resume&quot; or operation_type == &quot;insert&quot; or operation_type == &quot;reset&quot;:<br>                operation = &quot;add&quot;<br>                <br>            elif operation_type == &quot;stop&quot; or operation_type == &quot;suspend&quot; or operation_type == &quot;delete&quot;:<br>                operation = &quot;remove&quot;<br><br>            print(f&quot;    - VM Name:          {connection_name}&quot;)<br>            print(f&quot;    - VM Project:       {connection_group_name}&quot;)<br>            print(f&quot;    - VM Zone:          {vm_zone}&quot;)<br>            print(f&quot;    - VM IP Address:    {connection_ip_address}&quot;)<br>            print(f&quot;    - VM OS:            {vm_os}&quot;)<br>        else:<br>            print(&quot;Payload does not contain a response section.. nothing to do...&quot;)<br>            return None<br><br>        # Start our processing here<br>        client_auth = client_session(GUACAMOLE_BASE_URL,DATASOURCE,GUAC_USERNAME,GUAC_PASSWORD)<br>        if operation == &#39;add&#39; and vm_os == &#39;Windows&#39;:<br>            print(f&quot;Creating new connection with the following details...&quot;)<br>            print(f&quot;  - Connection Name: {connection_name}&quot;)<br>            print(f&quot;  - Connection Group Name: {connection_group_name}&quot;)<br>            print(&quot;&quot;)<br>            # Create a Connection Group if one does not already exist<br>            connection_group_id = get_parent_identifier(client_auth, connection_group_name)<br>            if connection_group_id == None: <br>                print(f&quot;- No existing Connection Group called {connection_group_name} was found!&quot;)<br>                print(f&quot;  - Creating connection group: {connection_group_name}&quot;)<br>                connection_group_id = create_connection_group(client_auth, connection_group_name)[&#39;identifier&#39;]<br>                print(f&quot;- Connection group created successfully with connection group id: {connection_group_id}&quot;)<br>                print(&quot;&quot;)<br>            else:<br>                print(f&quot;- Connection Group: {connection_group_name} already exists with ID: {connection_group_id}&quot;)<br>                print(&quot;&quot;)<br>            # Look for conenctions in connection group<br>            print(f&quot;- Checking for connections in connection group id: {connection_group_id}&quot;)<br>            connections_in_group = get_connection_group_connections(connection_group_id)<br>            if &#39;childConnections&#39; not in connections_in_group:<br>                print(f&quot;- Connection Group: {connection_group_name}, ID: {connection_group_id} is empty!&quot;)<br>                # If the connection groups exists but it contains no conenctions, create a mew connection under the connection group.<br>                print(&quot;- No existing connection found, creating new connection&quot;)<br><br>                connection_id = manage_rdp_connection(<br>                                                client_auth,<br>                                                connection_name,<br>                                                connection_ip_address,<br>                                                connection_group_id<br>                                                )[&#39;identifier&#39;]<br>                print(f&quot;- Connection {connection_name} created successfully with connection id: {connection_id} under connection group: {connection_group_id}&quot;)<br>                # set a flag to say a connection has been created<br>                new_connection_created = True<br>            else:<br>                new_connection_created = False<br>            # If connection group is NOT empty (it has connections in it) AND we didn&#39;t just create a new connection in it.<br>            if new_connection_created is not True:<br>                print(f&quot;- Checking for existing connection in connection group...&quot;)<br>                connection_id = get_connection_id_from_connection_group(connection_name, connection_group_id)<br>                # If no existing connection is found, create a new connection.<br>                if connection_id == None:<br>                    # Create the connection under the connection group<br>                    print(&quot;- No existing connection found, creating new connection&quot;)<br>                    connection_id = manage_rdp_connection(<br>                                                    client_auth,<br>                                                    connection_name,<br>                                                    connection_ip_address,<br>                                                    connection_group_id<br>                                                    )[&#39;identifier&#39;]<br>                    print(f&quot;- Connection {connection_name} created successfully with connection id: {connection_id} under connection group: {connection_group_id}&quot;)<br>                else:<br>                    print(f&quot;- Connection name: {connection_name} already exists in connection group: {connection_group_name}, with connection ID: {connection_id}&quot;)<br>                    # Check if the IP address has changed <br>                    print(f&quot; - Checking if connection details have been updated...&quot;)<br>                    print(&quot;&quot;)<br>                    current_connection_ip = get_connection_details(client_auth, connection_id, &quot;parameters&quot;)[&#39;hostname&#39;]<br>                    requested_connection_ip = connection_ip_address<br>                    print(f&quot; - Current connection IP address:   {current_connection_ip}&quot;)<br>                    print(f&quot; - Requested connection IP address: {requested_connection_ip}&quot;)<br>                    print(&quot;&quot;)<br>                    if current_connection_ip != requested_connection_ip:<br>                        print(f&quot;- New IP address for connection: {connection_name}&quot;)<br>                        print(f&quot; - Updating connection with new address...&quot;)<br>                        manage_rdp_connection(client_auth, connection_name, requested_connection_ip, connection_group_id, connection_id)<br>                        print(f&quot; - Updated connection successfully!&quot;)<br>                    else:<br>                        print(f&quot; - No changes required! Updating permissions and bailing out here.&quot;)<br>            print(&quot;&quot;)<br>            # Check if we actually have a user group created in Guac to sync up with the AD group - <br>            # we need to manually create the group in guac with the same name as the AD group the user is a member of<br>            print(f&quot;Checking if AD group {AD_USER_GROUP} already exists in Guacamole...&quot;)<br>            ad_group_id = get_user_groups(client_auth, AD_USER_GROUP)<br>            # Check for AD User Group (All users)<br>            if ad_group_id is not None:<br>                print(f&quot;AD user group: {AD_USER_GROUP} already exists with ID: {ad_group_id}&quot;)<br>            else:<br>                print(f&quot;AD user group: {AD_USER_GROUP} does not exist!&quot;)<br>                print(f&quot;Creating new AD User group: {AD_USER_GROUP}&quot;)<br>                ad_group_id = create_user_group(client_auth, AD_USER_GROUP)<br>                print(f&quot;Created AD group with ID: {ad_group_id}&quot;)<br><br>            # Add the connection group to the ad_user_group<br>            print(f&quot;- Performing: {operation} of connection type: group with connection ID: {connection_group_id} on group: {AD_USER_GROUP}&quot;)<br>            update_user_group_connections(<br>                                        client_auth,<br>                                        AD_USER_GROUP,<br>                                        connection_group_id,<br>                                        operation,<br>                                        &quot;group&quot;<br>                                        )<br>            # Add the connection to the ad_user_group<br>            print(&quot;&quot;)<br>            print(f&quot;- Performing: {operation} of connection type: connection with connection ID: {connection_id} on group: {AD_USER_GROUP}&quot;)<br>            update_user_group_connections(<br>                                        client_auth,<br>                                        AD_USER_GROUP,<br>                                        connection_id,<br>                                        operation,<br>                                        &quot;connection&quot;<br>                                        )<br>            print(&quot;&quot;)<br>            print(&quot;- Connection added successfully&quot;)<br>        elif operation == &#39;remove&#39; and vm_os == &#39;Windows&#39;:<br>            print(f&quot;Removing connection...&quot;)<br>            print(f&quot;  - Connection name:        {connection_name}&quot;)<br>            print(f&quot;  - Connection group name:  {connection_group_name}&quot;)<br>            print(&quot;&quot;)<br>            # Get the connection group id<br>            connection_group_id = get_parent_identifier(client_auth, connection_group_name)<br>            if connection_group_id == None: <br>                print(f&quot;- No existing connection group called {connection_group_name} was found!&quot;)<br>            else:<br>                print(f&quot;  - Connection group ID:    {connection_group_id}&quot;)<br>            # Get the connection id<br>            connection_id        = get_connection_id_from_connection_group(connection_name, connection_group_id)<br>            if connection_id == None:<br>                print(f&quot;- No connection with name: {connection_name} found in connection group: {connection_group_name}&quot;)<br>            else:<br>                print(f&quot;  - Connection ID:          {connection_id}&quot;)<br>                print(&quot;&quot;)<br>            # Delete the connection!<br>            print(f&quot;- Deleting connection ID:   {connection_id}&quot;)<br>            delete_connection(client_auth, connection_id)<br>            # Check if there are any connections in the connection group<br>            # If not, we should delete the connection group as well<br>            connections_in_group = get_connection_group_connections(connection_group_id)<br>            if &#39;childConnections&#39; not in connections_in_group:<br>                print(f&quot;- Connection group: {connection_group_name}, ID: {connection_group_id} is empty!&quot;)<br>                # Create the connection under the connection group<br>                print(f&quot;- Deleting empty connection group...&quot;)<br>                delete_connection_group(client_auth, connection_group_id)<br>                print(f&quot;- Connection group ID: {connection_group_id} deleted successfully.&quot;)<br>        elif vm_os == &#39;Linux&#39;:<br>            print(f&quot;VM is Linux - not creating or removing any connections Linux VM&#39;s at this stage. Bailing out here&quot;)<br>            exit(0)<br>    except Exception as e:<br>        error_message = &quot;There was an error during the execution the main hello_pubsub function&quot;<br>        print(f&quot;{error_message}&quot;, {e})<br><br></pre><p>All this results in something like the following in Apache Guacamole where the VM’s are shown under a folder (Connection Group) which contains the name of the GCP project that the VM’s (connections) are in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*LWZLbc4uolcOCMwrsgZRaA.png" /></figure><h4>RDP Session recording</h4><p>The final component of our solution that is the recording and archival of RDP sessions.</p><p>As can be seen in the connection templated code block in the function ‘manage_rdp_connection’ we have the following section:</p><pre>&quot;recording-path&quot;: &quot;/session_recordings&quot;,<br>&quot;recording-name&quot;: &#39;${GUAC_USERNAME}_${GUAC_DATE}_${GUAC_TIME}&#39;</pre><p>We then have a simple bash script on the Guacamole instance that is triggered by cron every fifteen minutes.</p><p>An example of the RDP session recording script is shown below:</p><pre>#!/bin/bash<br><br># Get some variables from metadata<br>GCP_BUCKET_NAME=$(curl -H &quot;Metadata-Flavor: Google&quot; http://169.254.169.254/computeMetadata/v1/instance/attributes/RDP_SESSIONS_BUCKET)<br>GCP_PROJECT_ID=$(curl -H &quot;Metadata-Flavor: Google&quot; http://169.254.169.254/computeMetadata/v1/project/project-id)<br># Set variables<br>SESSION_RECORDINGS_DIR=&quot;/session_recordings&quot;<br>GCP_STORAGE_CLASS=&quot;STANDARD&quot;  # Choose the appropriate storage class (e.g., STANDARD, NEARLINE, COLDLINE)<br>LOG_FILE=&quot;/var/log/session_recordings_sync.log&quot;<br><br>## The GCP Bucket retention policy should be for 90 days.<br><br># Function to log messages<br>log() {<br>    echo &quot;$(date +&quot;%Y-%m-%d %H:%M:%S&quot;) $1&quot; &gt;&gt; &quot;$LOG_FILE&quot;<br>}<br><br># Function to check if the file is open by another process<br>is_file_open() {<br>    lsof &quot;$1&quot; &gt;/dev/null 2&gt;&amp;1<br>}<br><br># Sync files to GCP Cloud Storage<br>log &quot;Beginning Sync of the RDP Session Recording files to GCP Cloud Storage...&quot;<br>cd &quot;${SESSION_RECORDINGS_DIR}&quot; || exit<br>for file in $(ls); do<br>    # Check if the file is currently open (could be a session recording in progress - so don&#39;t try to copy these yet)<br>    if is_file_open &quot;${file}&quot;; then<br>        log &quot;Skipping file ${file} - Open file handle detected. Could be a recording in progress, we only copy completed recordings&quot;<br>        continue<br>    fi<br><br>    # Copy files to GCP Cloud Storage<br>    log &quot;Copying file ${file} to GCP Cloud Storage...&quot;<br>    gsutil -o &quot;GSUtil:project_id=${GCP_PROJECT_ID}&quot; cp &quot;${file}&quot; &quot;gs://${GCP_BUCKET_NAME}/&quot;<br><br>    log &quot;Verifying MD5 hash for ${file}...&quot;<br>    local_md5=$(md5sum &quot;$file&quot; | awk &#39;{print $1}&#39;)<br>    gcp_md5=$(gsutil hash -h &quot;gs://${GCP_BUCKET_NAME}/${file}&quot; | grep &quot;Hash (md5):&quot; | awk &#39;{print $3}&#39;)<br><br>    log &quot;Comparing MD5 hashes for local and remote file: ${file} ...&quot;<br>    if [ &quot;$local_md5&quot; = &quot;$gcp_md5&quot; ]; then<br>        log &quot;MD5 hash verification successful for file ${file}. Deleting local file...&quot;<br>        rm -f &quot;${file}&quot;<br>    else<br>        log &quot;ERROR: MD5 hash mismatch for file ${file}&quot;<br>    fi<br>done<br>log &quot;Sync process completed successfully.&quot;</pre><h4>Outcomes</h4><p>After the deployment of this solution, end users now have:</p><ul><li>A seamless, secure and highly automated bastion solution for GCP and associated GCP Instances.</li><li>High confidence of audit and regulatory compliance of the environment through high quality log data and session recording.</li><li>Simplified bastion environment authentication through the integration of SSO.</li><li>Single point of administration traffic for instances on the network.</li><li>A solution that requires nothing more than a web browser to use.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2c8c5075b18" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Terraform to create secure IAP tunnels on GCP with conditional IAM policies!]]></title>
            <link>https://calum-h.medium.com/using-terraform-to-create-secure-iap-tunnels-on-gcp-with-conditional-iam-policies-188ac37b528a?source=rss-fc272f24dd85------2</link>
            <guid isPermaLink="false">https://medium.com/p/188ac37b528a</guid>
            <dc:creator><![CDATA[Calum Hunter]]></dc:creator>
            <pubDate>Mon, 24 May 2021 01:19:42 GMT</pubDate>
            <atom:updated>2021-05-24T01:19:42.569Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Summary.</strong></h3><p>This post will detail how to create a secure IAP (Identity Aware Proxy) tunnel to a VM (Virtual Machine) inside a VPC<strong> without </strong>requiring a public IP address or VPN</p><p>This will enable you to establish secure remote access to VM’s over protocols such as SSH, RDP or VNC</p><p>As part of this process, we will use also use a <strong>conditional IAM policy</strong> that will ensure that access to the VM is secured based upon the <strong>source IP address range</strong>.</p><p>We will use Google’s <a href="https://cloud.google.com/iap">IAP (Identity Aware Proxy)</a> service to provide authentication and then leverage Google’s conditional IAM policies with an <strong>‘Access Level’</strong> defined in Google’s <a href="https://cloud.google.com/access-context-manager">Access Context Manager</a> to restrict access to a specific region, source IP address or IP address range.</p><p>First we will run through the problem, some simple diagrams to illustrate it, and finally how we will go about using Google’s services mentioned above to solve the problem.</p><p>At the end of the post will be some example Terraform code that will show how to create the resources required for this solution.</p><h3><strong>The Why.</strong></h3><p>Remote working has increased dramatically in the last year or so thanks to COVID, so providing secure remote access to services for users has become more and more important.</p><p>In years gone by, simply being on the ‘corporate network’ was often enough to provide secure access to services, but with the rise of remote working this is often no longer possible, or the corporate VPN that is provided is too broad and is not sufficient to provide effective controls to services.</p><p>For this example, let’s assume that you have a simple HTTP web server created in a private VPC, on a private IP subnet in a GCP project.</p><p>We will make this an overly simple example using the below diagram, showing connections from a client device on the public internet to this web server going via a load balancer and the request is then forwarded on to the web server in the private VPC.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*q-8EwomjZrGLT6TV1_tBdA.png" /></figure><h3>The problem.</h3><p>A user may need to access the remote HTTP web server over a remote access protocol such as SSH, VNC or RDP in order to perform administrative tasks or maintenance.</p><p>As the HTTP web server does not have a public IP address and is not directly accessible from the internet this presents a problem. How do we easily and securely access this server with out additional complex infrastructure such as a VPN.</p><h3><strong>The solution.</strong></h3><p>Introducing <a href="https://cloud.google.com/iap">IAP (Identity Aware Proxy)</a><br>Google’s IAP service is able to solve this problem by providing a method to allow a user to securely connect to an instance by establishing a TCP tunnel through Google’s IAP servers.</p><p>In this example we will show how we can use IAP to allow SSH access to a VM instance.</p><p>An overly simple diagram shows how we will be configuring access to the VM via SSH</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*m7VNaEb9bMNg_AFreD2fAQ.png" /></figure><h3><strong>Authentication and Authorisation.</strong></h3><p>In the example above the client requests a ssh connection to the web server using Google’s gcloudcommand line tool.</p><p>By using the --<a href="https://cloud.google.com/sdk/gcloud/reference/compute/ssh#--tunnel-through-iap">tunnel-through-iap</a> flag we can tell gcloud to tunnel the ssh connection through the IAP servers.</p><p>Example command:</p><pre>gcloud compute ssh &lt;instance-name&gt; \<br>--tunnel-through-iap --project=&lt;project-name&gt; \<br>--zone=&lt;zone&gt;</pre><p>What this command will do, is to first attempt to authenticate the user to GCP. Then GCP will check the IAM policy to see if it user has the required permission (roles/iap.tunnelResourceAccessor) to establish an IAP tunnel to the IAP servers.<br>(The IAP servers sit in this IP address range 35.235.240.0/20)</p><p>In this case, we will be using a conditional IAM role whereby the incoming connection will be checked against an Access List (Access Context Manager) to ensure that the IP address range the client device is on is within the range specified and if this evaluates to true the user will be granted the required role: <a href="https://cloud.google.com/iap/docs/managing-access#roles">roles/iap.tunnelResourceAccessor</a></p><p>Once the user has been authenticated and had their IAM policy checked to ensure the user is authorised to access the service, the next step is to make a connection from the IAP servers to the VM.</p><p>This will require a firewall rule in the VPC allowing incoming connections to the VM from the IAP servers subnet 35.235.240.0/20</p><p><strong>With all this in place, we will be able to securely establish a remote access connection!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*scji0CTdeJ2ZZBAoPP06Mw.jpeg" /></figure><h3><strong>Terraform code.</strong></h3><p>Now we know what we are trying to achieve and how, we can get stuck into implementing this in Terraform.</p><h4>Assumptions</h4><p>The assumption here is that you already have access to the following:</p><ul><li><a href="https://cloud.google.com/resource-manager/docs/creating-managing-organization">A GCP environment with an organisation. (Access Context Manager requires a Google Cloud Organisation to be setup.)</a></li><li><a href="https://cloud.google.com/resource-manager/docs/creating-managing-projects">A GCP project</a> with a <a href="https://cloud.google.com/vpc/docs/using-vpc">VPC and subnets</a> already configured (default is fine)</li><li><a href="https://cloud.google.com/sdk/docs/install">The Google Cloud SDK installed on the machine you are using</a> to connect to the VM instance.</li><li><a href="https://cloud.google.com/iam/docs/creating-managing-service-accounts">A service account</a> that Terraform will use to provision the resources into the GCP project. (<a href="https://registry.terraform.io/providers/hashicorp/google/latest/docs/guides/provider_reference#authentication">We will assume terraform will be running as this highly privileged service account</a>)</li></ul><h3>Getting started.</h3><h4>Create a Linux VM in the project and enable OS Login.</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4abd2410fba327602f42dbb23cc40609/href">https://medium.com/media/4abd2410fba327602f42dbb23cc40609/href</a></iframe><h4>Create the Firewall rule to allow incoming ssh connections from Google IAP servers to our instance.</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/68d2329dded1a562dd1aa055f31af117/href">https://medium.com/media/68d2329dded1a562dd1aa055f31af117/href</a></iframe><h4><strong>Create the Access List on the default Access Policy.</strong></h4><p>Note: In order to get the ID for the Access Policy try the following commands</p><ol><li>Get your organization ID<br>gcloud organizations list</li><li>Find your Access Policy ID<br>gcloud access-context-manager policies list --organization &lt;org-id&gt;</li></ol><p>The <strong>access-policy-id</strong> or name will be the number under the NAME column <br>eg:</p><pre>NAME          ORGANIZATION  TITLE</pre><pre>965510000000  465000000000</pre><p><strong>Create the Access List</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b3177f887b46a6d5d144644fd083a7c2/href">https://medium.com/media/b3177f887b46a6d5d144644fd083a7c2/href</a></iframe><p><strong>Create the conditional IAM policy assigning the role </strong>roles/iap.tunnelResourceAccessor<strong>to a user <em>if</em> the Access List evaluates to true (Eg. the user is making the request from an IP in the defined ip_subnetworks above)</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce8c8471b32a523d98dada09b7d1bbc3/href">https://medium.com/media/ce8c8471b32a523d98dada09b7d1bbc3/href</a></iframe><p><strong>Thats it we are done!</strong></p><p>Ok not quite.</p><p>There are a couple of extra settings we need to make to ensure we can connect to the VM:</p><p><strong>Assign compute roles to user to allow them access to the VM</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c316001c3ee869652704d3b1647d1220/href">https://medium.com/media/c316001c3ee869652704d3b1647d1220/href</a></iframe><h3>Connecting to the instance with SSH via the IAP secure tunnel</h3><pre>gcloud compute ssh my-instance-01 <br>   --tunnel-through-iap <br>   --project=&lt;my-project&gt; <br>   --zone=&lt;my-zone&gt;</pre><h3>Bonus — Connecting via VNC and RDP</h3><p>While this post focused on access to a VM using SSH. This solution can easily be extended to use any TCP port.<br>(See: <a href="https://cloud.google.com/iap/docs/using-tcp-forwarding#tunneling_other_tcp_connections">tunneling_other_tcp_connections</a>)</p><p>So obtaining remote access via VNC or RDP to a VM is as simple as adding the required port/protocol to the firewall rule that allows connections to the VM from the IAP servers.</p><p>Accessing the VM using VNC or RDP, however, is a little bit different. <br>Instead we will use the gcloudcommand to create a tunnel bound to a port on the localhost.</p><p>Then we can point our VNC or RDP client to this localhost address and have it tunnel through to our VM</p><p><strong>Update the firewall rule to enable VNC (port 5901) and RDP (port 3389)</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fbf0715e2d77971435226b21b9182478/href">https://medium.com/media/fbf0715e2d77971435226b21b9182478/href</a></iframe><p><strong>Create a tunnel using VNC</strong></p><pre>gcloud compute start-iap-tunnel &lt;my-instance-name&gt; 5901 <br>  --local-host-port=localhost:5901</pre><p><strong>Connect to your VM using your VNC client<br></strong>Now that we have established a tunnel to the instance using VNC we can use our VNC viewer application to connect to localhost:5901 and use the tunnel to make the connection to our VM</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/265/1*Swgz3jFs-GxHr6upv_rHzw.png" /><figcaption>Connect to the instance by connecting to the tunnel that has been established at localhost:5901</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J6FrJIVgkl5ySgRHFIH3Gg.png" /><figcaption>Connected to our VM in GCP</figcaption></figure><p>The same process as above works for Microsoft RDP as well, simply change the port in the gcloud command from 5901 to 3389 then use your remote desktop application to connect to localhost:3389 and the connection will go through as well.</p><p><strong>Other possibilities</strong></p><p>From here you can also see that it is trivial to open a tunnel over any TCP port to our VM in GCP. (Don’t forget to update the list of ports to allow in from our IAP servers in the firewall rule)</p><p>For example, we might have a web server running on our VM in GCP that we wish to access, but without having a public IP address or load balancer setup, we can simply create an IAP tunnel to port 80 (or whatever port our web server is listening on) and then establish that on our local host. From here we could access it in a web browser by going to http://localhost:80</p><p><strong>Example:</strong><br>Start a simple web server on our VM in GCP <br>python -m SimpleHTTPServer</p><p>Update our firewall to allow port 8000 from IAP servers to our VM</p><pre>resource &quot;google_compute_firewall&quot; &quot;inbound-ip-ssh&quot; {<br>  name        = &quot;allow-incoming-ssh-from-iap&quot;<br>  project     = var.project_id<br>  network     = &quot;default&quot;<br>  direction = &quot;INGRESS&quot;<br>  <br>  allow {<br>    protocol = &quot;tcp&quot;<br>    ports    = [&quot;22&quot;, &quot;5901&quot;, &quot;3389&quot;, &quot;8000&quot;]<br>  }<br>  <br>  source_ranges = [&quot;35.235.240.0/20&quot;]</pre><pre>  target_service_accounts = [<br>    &quot;&lt;project-id&gt; compute@developer.gserviceaccount.com&quot;<br>  ]<br>}</pre><p>Now lets start a tunnel a try connecting to it via the tunnel</p><pre>gcloud compute start-iap-tunnel &lt;my-instance-name&gt; 8000<br>  --local-host-port=localhost:8000</pre><p>Access it in a browser</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*3rmHc2AsliuOGHGDPzq8Cg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=188ac37b528a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>