Седмицата (24–29 юни)

Post Syndicated from Надежда Радулова original https://www.toest.bg/sedmitsata-24-29-yuni/

Седмицата (24–29 юни)

От известно време ни стана навик посред лято да сваляме правителства, да ходим на избори, да гледаме парламентарен цирк, в който се подхвърлят мандати и се сглобяват и разглобяват мнозинства и малцинства, широки и тесни, стабилни и паянтови коалиции. Лош навик, бих казала. Защото при 36 градуса, на чаша узо или пък пред екрана със смразяващи кръвта новини от света, лека-полека вътрешнополитическите събития заприличват на умиляващ междуфамилен селски събор, който от година на година все повече преставаме да забелязваме („Говори си, не ми пречиш!“). В седмичния си анализ „България в средата на нищото“ Емилия Милчева обобщава ситуацията така: политическата нестабилност, подсилена с краен популизъм, води до тежък застой и липса на каквато и да било управленска последователност и визия. И какво от това?! Вече сме претръпнали. И претръпването, разбира се, се отразява на избирателната активност, а оттам и на изборните резултати, и на какво ли още не.

Лошото е, че претръпването към тясно политическото има общоанестетичен ефект. Ето така например проспиваме факта, че само през първите три седмици на юни (най-малко) четири жени в България са били убити от свои близки мъже – партньори, синове… Светла Енчева разглежда случаите през призмата на променящото се законодателство, но и в една по-широка ценностна рамка, защото „Насилието над жени не чака България да се оправи“.

Анестетичен ефект сковава все повече и реактивността ни към войните, които се водят в Украйна и в Близкия изток. Лесно е от привидно безопасно разстояние да слагаме етикети и да раздаваме присъди, да сме винаги прави, да се прилепяме към бързо смилаеми лозунги, които да „осмислят“ вместо нас трудни или дори немислими неща. Повече за всекидневната сложност да живееш във война и да формулираш (дори и само за себе си) какво се случва и какво може да се направи, четете в разговора на Еми Барух с израелския писател Етгар Керет „Проблемът е, че всички искат да е просто и ясно, а то не е“.

Яснота и еднозначност няма и по отношение на един на пръв поглед ясен казус – този, свързан с цифровите ни права и уреждащото ги законодателство. Белгийското председателство се отказа да подложи на гласуване в ЕС предложенията за изключения по Директивата за правото на неприкосновеност на личния живот и електронни комуникации (2002/58/ЕО). Това е пореден бюрократичен опит за премахване на криптирането от приложенията за съобщения и разговори, или с други думи – ново посегателство върху тайната на личната кореспонденция. Предложенията включват автоматизирано масово наблюдение на комуникациите чрез използване на компютърни алгоритми и изкуствен интелект.

Идеята е особено опасна, защото изхожда от изключително благородни мотиви, а именно „борба със сексуалните посегателства срещу деца в интернет“, което би провокирало напълно разбираема подкрепа. Проблемът е, че винаги когато се жертва малко свобода, за да се постигне малко сигурност, в крайна сметка се губят и двете. Защото престъпниците няма да спрат да ползват нелегални системи за комуникации с криптиране, а всички останали ще сме в паноптикума на „Големия дигитален брат“.

Опасността #chatcontrol не е отминала, а е само отложена. И макар Съдът на Европейския съюз вече да е постановявал, че постоянното и цялостно автоматизирано претърсване и следене на частни комуникации нарушава основни права и поради това следва да е недопустимо, темата се връща непрекъснато на дневен ред заради популизъм и елементарно мислене от неадекватни политици.

Какво е становището на България по този въпрос, е напълно неясно. Обществен дебат у нас също изцяло липсва. С този въпрос се е заел Богомил Шопов от Сдружението за свободен софтуер, софтyер с отворен код и цифрови права, който се опитва да разбере как възнамерява да гласува българският представител в Съвета на Европа, и да подскаже опасностите от евентуална подкрепа на такова изключение на неприкосновеността на комуникациите. „Тоест“ ще следи развитието по темата.

Не е проста и ясна и ситуацията с предстоящите избори в САЩ. При все че Съединените щати са ключов глобален политически играч, за избирателите приоритет продължава да бъде „Икономиката, глупако!“. За това „Кои са най-важните проблеми за американците в изборната година? Част 1: Икономиката“ четете анализа на Йоанна Елми.

Тази седмица ви предлагаме още един външнополитически текст – и образователен, и аналитичен: „За Китай, Европа и червените линии“ от Искрен Иванов. И докато у нас думички като „възраждане“, „величие“ и „възход“ вече отчетливо кънтят на тенекия и папиемаше, в случая с Китай не става дума за „исторически парк“, отделен от европейското с безкрайна стена, а за „острието на триъгълника, което балансира отношенията между глобалните актьори“ (по Кисинджър).

Доста жилава за осмисляне е „порцията език“, която ни поднася Павлина Върбанова този месец. „Слонът в стаята на българския правопис“ се оказва разделът с правилата за слято, полуслято и разделно писане. Защо вкъщи не е като у дома, е въпрос, на който няма да можете да си отговорите дори след като прочетете текста. Пореден пример за това, че липсата на бързи и окончателни отговори не отменя валидността на въпросите.

Стихотворението на месеца „Вниманието“ е от ирландския поет Ник Леърд и пристига при нас в превод на Ангел Игов. Красиво и тъжно размишление за обичта, загубата и деликатния, осмислящ света начин, по който бихме могли да извървим пътя си, ако не бързахме с отговорите, ако не обезболявахме мислите си.

Приятно четене (с разбиране)! И безгрижно – доколкото е възможно – лято! Без да забравяме, че след по-малко от три месеца ще свърши.

Metasploit Weekly Wrap-Up 06/28/2024

Post Syndicated from Jack Heysel original https://blog.rapid7.com/2024/06/28/metasploit-weekly-wrap-up-06-28-2024/

Unauthenticated Command Injection in Netis Router

Metasploit Weekly Wrap-Up 06/28/2024

This week’s Metasploit release includes an exploit module for an unauthenticated command injection vulnerability in the Netis MW5360 router which is being tracked as CVE-2024-22729. The vulnerability stems from improper handling of the password parameter within the router’s web interface which allows for command injection. Fortunately for attackers, the router’s login page authorization can be bypassed by simply deleting the authorization header, leading to the vulnerability. All router firmware versions up to V1.0.1.3442 are vulnerable.

New module content (2)

MS-NRPC Domain Users Enumeration

Author: Haidar Kabibo https://x.com/haider_kabibo
Type: Auxiliary
Pull request: #19205 contributed by sud0Ru
Path: scanner/dcerpc/nrpc_enumusers

Description: This adds a new module that can enumerate accounts on a target Active Directory Domain Controller without authenticating to it; instead the module does so by issuing a DCERPC request and analyzing the returned error status.

Netis router MW5360 unauthenticated RCE.

Authors: Adhikara13 and h00die-gr3y [email protected]
Type: Exploit
Pull request: #19188 contributed by h00die-gr3y
Path: linux/http/netis_unauth_rce_cve_2024_22729
AttackerKB reference: CVE-2024-22729

Description: This adds an exploit module that leverages CVE-2024-22729, a command injection vulnerability in Netis router MW5360 to achieve remote code execution as the user root. All router firmware versions up to V1.0.1.3442 are vulnerable.

Bugs fixed (3)

  • #19259 from dledda-r7 – This updates Metasploit to check for a new flag that is sent as part of the encryption key negotiation with Meterpreter which indicates if Meterpreter had to use a weak source of entropy to generate the key.
  • #19267 from zeroSteiner – Fixes a crash in the ldap_esc_vulnerable_cert_finder module when targeting an AD CS server that has a certificate template containing parenthesis.
  • #19283 from adeherdt-r7 – Fixes the auxiliary/scanner/redis/redis_login module to correctly track the registered service name as redis – previously it was blank.

Documentation

You can find the latest Metasploit documentation on our docsite at docs.metasploit.com.

Get it

As always, you can update to the latest Metasploit Framework with msfupdate
and you can get more details on the changes since the last blog post from
GitHub:

If you are a git user, you can clone the Metasploit Framework repo (master branch) for the latest.
To install fresh without using git, you can use the open-source-only Nightly Installers or the
commercial edition Metasploit Pro

Metasploit Weekly Wrap-Up 06/28/2024

[$] FreeDOS turns 30

Post Syndicated from jzb original https://lwn.net/Articles/979780/

FreeDOS is an open-source
operating system designed to be compatible with the now-defunct MS-DOS. Three decades
have now passed since the FreeDOS project was first announced, and it
is still alive and well with a small community of developers and
users committed to running legacy DOS software, classic DOS games, and
developing modern applications that extend its functionality well beyond the
original MS-DOS. It may well be around in another 30 years.

NVIDIA NVLink Switch Chips Change to the HGX B200

Post Syndicated from Patrick Kennedy original https://www.servethehome.com/ingrasys-shows-big-nvidia-nvlink-switch-chips-change-to-the-hgx-b200-b100/

The NVIDIA HGX B200 and HGX B100 platforms use only two NVLink Switches (down from four) and reposition them for shorter trace lengths

The post NVIDIA NVLink Switch Chips Change to the HGX B200 appeared first on ServeTheHome.

How the first 2024 US presidential debate influenced Internet traffic and security trends

Post Syndicated from João Tomé original https://blog.cloudflare.com/how-the-first-2024-us-presidential-debate-influenced-internet-traffic-and-security-trends


Key findings:

  • The Biden vs. Trump debate influenced Internet traffic at the state level in the US, with drops in traffic as high as 17% (in Vermont) during the debate.
  • Microblogging and video streaming platforms saw traffic changes during the debate.
  • Trump-related sites, including donation platforms, gained much more traction than Biden’s during and after the debate.
  • Emails with “Trump” in the subject had higher rates of spam and malicious content compared to those with “Biden.”
  • No increase in cyberattacks during the debate, but frequent DDoS attacks targeted government and political sites in the preceding months.

Internet traffic ebbs and flows usually follow human patterns, and high visibility events that are broadcast on TV usually have an impact. Let’s take a look at the first of the 2024 United States presidential debates between the two major presumptive candidates, Joe Biden and Donald Trump, for the November presidential election.

2024 has been dubbed “the year of elections,” with elections taking place in over 60 countries, as we have mentioned before (1, 2, 3). We are regularly updating our election report on Cloudflare Radar, including analysis of recent elections in South Africa, India, Iceland, Mexico, and the European Union.

Typically, from what we usually observe, election days don’t come with highly intensive changes to Internet traffic, and the same is true for debates. Yet, debates can also draw attention that impacts traffic, especially when there is heightened anticipation. The 2024 debates are not only aired on broadcast and cable television but also streamed on platforms like YouTube, enhancing their reach and impact.

During the June 27, 2024, debate between Biden and Trump, hosted by CNN at 21:00 EST (01:00 UTC), Cloudflare noted a slight drop in nationwide Internet requests, falling to 2% below the same time a week prior at 21:15 EST (01:15 UTC). Interestingly, Internet traffic was 4% higher just before the debate started and surged to 6% above the previous week’s levels after the debate concluded at 23:45 EST (03:45 UTC).

Internet traffic dips across US states

Traffic shifts at the time of the debate, as compared to the previous week, are much more revealing at a state-level perspective than at the country level. The map below summarizes traffic changes observed at a state level:

The most significant traffic drops were seen in Vermont (-17%), South Dakota (-16%), Wyoming (-16%), and Alaska (-16%). More populous states like California, Texas, and New York saw milder reductions of between 5% and 6%, and Florida experienced a 9% drop at 21:45 local time (01:45 UTC) during the debate.

The six swing states that are said to be decisive in the election, Arizona, Georgia, Michigan, Nevada, Pennsylvania and Wisconsin, all saw traffic drop between 5% and 8%.

The initial minutes of the Biden vs. Trump debate triggered the largest traffic declines in most states, though several, including Florida, Louisiana, Georgia, Nevada, and Wisconsin, observed deeper dips midway through. States like Ohio and Missouri recorded their most substantial traffic drops towards the debate’s conclusion.

In the next table, we provide a detailed breakdown of the same perspective shown on the US map ordered by the magnitude of the drop in traffic. We include the time of the biggest traffic drop compared to the previous week, at a 5-minute granularity, and also the percentage of the drop compared to the previous week. (Illinois is not included due to data issues.)

State Drop in traffic (%) Time of drop in traffic (local) Time of drop in traffic (UTC)
Vermont -17% 21:00 1:00
Alaska -16% 17:30 1:30
South Dakota -16% 20:10 / 19:10 1:10
Wyoming -16% 19:25 1:25
New Hampshire -13% 21:05 1:05
Rhode Island -12% 21:05 1:05
Louisiana -11% 20:45 1:45
Massachusetts -11% 21:05 1:05
Connecticut -10% 21:30 1:30
Montana -10% 19:10 / 18:10 1:10
Nebraska -10% 20:05 / 19:05 1:05
Oklahoma -10% 20:05 1:05
Florida -9% 21:45 1:45
Georgia -8% 21:45 1:45
Nevada -8% 18:40 1:40
New Jersey -8% 21:05 1:05
Ohio -8% 22:25 2:25
Washington -8% 18:30 1:30
Kentucky -7% 21:15 1:15
North Carolina -7% 21:15 1:15
North Dakota -7% 20:10 / 19:10 1:10
Wisconsin -7% 20:45 1:45
California -6% 18:05 1:05
Iowa -6% 20:35 1:35
Kansas -6% 20:05 1:05
Maine -6% 21:05 1:05
Michigan -6% 21:05 1:05
Minnesota -6% 20:05 1:05
New Mexico -6% 19:10 1:10
Tennessee -6% 20:30 / 21:30 1:30
Alabama -5% 20:10 1:10
Arizona -5% 18:20 1:20
Arkansas -5% 20:25 1:25
Colorado -5% 19:15 1:15
Indiana -5% 21:10 1:10
New York -5% 21:25 1:25
Pennsylvania -5% 21:15 1:15
South Carolina -5% 21:35 1:35
Texas -5% 20:20 / 19:20 1:20
Idaho -4% 19:45 / 18:45 1:45
Utah -4% 19:05 1:05
Virginia -4% 21:05 1:05
Delaware -3% 21:05 1:05
Oregon -3% 18:15 1:15
West Virginia -3% 21:05 1:05
District of Columbia -2% 21:55 1:55
Hawaii -2% 15:20 1:20
Maryland -2% 21:10 1:10
Mississippi -2% 20:20 1:20
Missouri -2% 21:10 2:10
Illinois – – –

DNS trends: Trump-related sites see accelerated growth

Switching focus to domain trends, our 1.1.1.1 resolver data reveals a more targeted impact from the debate. Considering the candidates individually (using the official sites related to both candidates), we found that Biden-associated websites saw a 176% surge in DNS queries at around 23:00 EST (03:00 UTC), compared to the previous week.

However, Trump-associated sites saw a greater increase than Biden-associated sites, showing an increase before, during, and after the debate, with the peak growth reaching 803% over the previous week at 01:00 EST (05:00 UTC).

For donation sites, those linked to Biden were busiest before the debate on June 17 and 18, thanks to events with Barack Obama and Bill and Hillary Clinton. DNS traffic for Trump’s donation sites, as compared with the previous week, increased during the debate, growing 830% at 22:00 EST (02:00 UTC) and reaching a high of 1270% increase by 01:00 EST.

The debate aired on multiple TV channels and was streamed on YouTube. During the debate, video streaming platforms like TikTok and YouTube, which are among the top Internet services globally, saw a 4% increase in DNS traffic at 22:00 EST (02:00 UTC). Significant changes in DNS traffic on these platforms are uncommon due to their widespread popularity.

Political news sites also spiked, with a 68% traffic increase around 22:00 EST (02:00 UTC).

Microblogging social platforms like X or Threads outperformed their previous week’s traffic throughout the debate day, with growth peaking at 41% at the start of the debate around 21:00 EST (01:00 UTC).

Biden vs Trump: spam and malicious emails

In June 2024 (through June 27), Cloudflare’s Cloud Email Security service processed over 2.5 million emails containing “Biden” or “Trump” in the subject line. Trump-related subjects appeared 13% more often than those related to Biden. Moreover, emails with “Trump” had higher percentages of spam, at 3%, and malicious messages, at 0.6%, compared to 0.8% for spam and 0.2% for malicious messages with “Biden.”

The peak occurrence of spam emails with “Trump” was on June 9, at 19.8%, and the highest rate of malicious messages was on June 12, at 2.9%. For “Biden,” the highest spam rate was on June 21, at 1.2%, and the peak for malicious messages was also on June 9, at 0.8%.

Attacks: government and political impact

Focusing on attacks, those are usually constant, and aren’t necessarily driven always by elections. But, as we’ve seen at the start of the war in Ukraine or more recently in the Netherlands, events do trigger attacks. Already in June 2024, during the European elections, we recently published a blog post about the cyberattack on Dutch political-related websites that lasted two days – June 5 and 6. The main DDoS (Distributed Denial of Service attack) attack on June 5, the day before the Dutch election, reached 73,000 requests per second (rps).

Shifting our focus to the US in particular, in the weeks since April 2024, we’ve seen some DDoS attacks targeting both government, state or political-related websites in the United States. That said, we haven’t seen any substantial attacks targeting political sites during the day of debate, June 27. The most recent one we saw was this week, on June 24, and targeted a political-related website involved in the current elections. It was a small attack that lasted under 10 minutes and peaked at 35,000 requests per second (rps).

Now that we’ve explored the US presidential debate trends, let’s compare it with Internet trends from other debates in the UK and France from the week of June 24, 2024.

UK and France: debates with an impact

In other countries like the UK and France, election-related debates during the week of June 24 also serve as examples for comparison with the Biden vs Trump debate. Both the UK and France experienced more significant nationwide traffic impacts during their debates compared to the US. However, the geographic and population size of the US, coupled with the debate’s broad availability on streaming platforms, could have influenced this disparity.

In France, the snap election is scheduled for Sunday, June 30, 2024, and the runoff on July 7, 2024. The final debate among the leading candidates on Tuesday, June 25, 2024 (21:00 local time), led to a 14% drop in Internet HTTP requests, as it was broadcast nationally and carried broad interest. Despite this, the UEFA Euro 2024 football match between France and Poland on the same day, at 18:00 local time, caused an even greater traffic decrease of 16%.

The following day, Wednesday, June 26, 2024, the two main candidates for the snap UK general election — scheduled for July 4, 2024 — participated in their final debate on BBC national TV. The debate between Rishi Sunak and Sir Keir Starmer, which started at 20:15 local time, resulted in a 7% drop in UK Internet traffic compared to the previous week. The most significant decrease occurred at 20:45. At a more detailed level, Wales experienced an 11% drop during the debate, followed by England at 8%, Scotland at 7%, and Northern Ireland at 5%.

Conclusion: high intensity election year

Even if major political events don’t always bring significant changes to Internet traffic, our data shows that the Biden vs. Trump debate had an impact, especially at the state level. Microblogging and video streaming social platforms also saw traffic shifts during the debate, with Trump-related sites seeing larger spikes in DNS traffic than Biden-related sites, especially after the debate.

We also observed a higher percentage of spam and malicious emails sent with “Trump” in the subject of the messages than with “Biden.” Although we didn’t see an uptick in cyberattacks during the debate, we note that these have been frequent, especially DDoS attacks in the months before, targeting both federal and state government services as well as politically related sites.

If you want to follow more trends and insights about the Internet and elections in particular, you can check Cloudflare Radar, and more specifically our new 2024 Elections Insights report, which will be updated as elections take place throughout the year.

FSF Europe condemns Apple’s DMA noncompliance

Post Syndicated from daroc original https://lwn.net/Articles/980003/

The Free Software Foundation Europe has

submitted
a joint position to the European Commission (EC), claiming that Apple
has failed to comply with the EU’s Digital Markets Act (DMA). This is the law
that requires Apple to support alternative application stores on the devices it
makes.

Apple’s unfair behaviour against Free Software highlights the critical need to
monitor the implementation of the DMA. The FSFE collaborated with F-Droid, the
AppFair project, and other interoperability experts to scrutinize Apple’s DMA
compliance, and it’s impact on Free Software. Since then, we coordinated several
expert workshops with stakeholders,

discussed with regulators in FOSDEM
, had

official meetings with the EC’s DMA team
, and submitted a

comprehensive position

to the EC detailing several problematic elements in the Apple compliance that
will harm the Free Software.

[$] Redox: An operating system in Rust

Post Syndicated from daroc original https://lwn.net/Articles/979524/

With the

Rust-for-Linux
project starting to gain some ground, it is worth
looking at other operating systems that use Rust in their kernels. There
are
many
attempts to use
Rust for operating system development, but Redox
may be the most complete.
Redox is an MIT-licensed microkernel and corresponding user space, designed
around concepts taken from

Plan 9
. While nowhere near being usable as a
replacement for Linux, it already provides a graphical user interface and

the ability to run many POSIX programs
.

Supporting Postgres Named Prepared Statements in Hyperdrive

Post Syndicated from Andrew Repp original https://blog.cloudflare.com/postgres-named-prepared-statements-supported-hyperdrive


Hyperdrive (Cloudflare’s globally distributed SQL connection pooler and cache) recently added support for Postgres protocol-level named prepared statements across pooled connections. Named prepared statements allow Postgres to cache query execution plans, providing potentially substantial performance improvements. Further, many popular drivers in the ecosystem use these by default, meaning that not having them is a bit of a footgun for developers. We are very excited that Hyperdrive’s users will now have access to better performance and a more seamless development experience, without needing to make any significant changes to their applications!

While we’re not the first connection pooler to add this support (PgBouncer got to it in October 2023 in version 1.21, for example), there were some unique challenges in how we implemented it. To that end, we wanted to do a deep dive on what it took for us to deliver this.

Hyper-what?

One of the classic problems of building on the web is that your users are everywhere, but your database tends to be in one spot.  Combine that with pesky limitations like network routing, or the speed of light, and you can often run into situations where your users feel the pain of having your database so far away. This can look like slower queries, slower startup times, and connection exhaustion as everything takes longer to accomplish.

Hyperdrive is designed to make the centralized databases you already have feel like they’re global. We use our global network to get faster routes to your database, keep connection pools primed, and cache your most frequently run queries as close to users as possible.

Postgres Message Protocol

To understand exactly what the challenge with prepared statements is, it’s first necessary to dig in a bit to the Postgres Message Protocol. Specifically, we are going to take a look at the protocol for an “extended” query, which uses different message types and is a bit more complex than a “simple” query, but which is more powerful and thus more widely used.

A query using Hyperdrive might be coded something like this, but a lot goes on under the hood in order for Postgres to reliably return your response.

import postgres from "postgres";

// with Hyperdrive, we don't have to disable prepared statements anymore!
// const sql = postgres(env.HYPERDRIVE.connectionString, {prepare: false});

// make a connection, with the default postgres.js settings (prepare is set to true)
const sql = postgres(env.HYPERDRIVE.connectionString);

// This sends the query, and while it looks like a single action it contains several 
// messages implied within it
let [{ a, b, c, id }] = await sql`SELECT a, b, c, id FROM hyper_test WHERE id = ${target_id}`;

To prepare a statement, a Postgres client begins by sending a Parse message. This includes the query string, the number of parameters to be interpolated, and the statement’s name. The name is a key piece of this puzzle. If it is empty, then Postgres uses a special “unnamed” prepared statement slot that gets overwritten on each new Parse. These are relatively easy to support, as most drivers will keep the entirety of a message sequence for unnamed statements together, and will not try to get too aggressive about reusing the prepared statement because it is overwritten so often.

If the statement has a name, however, then it is kept prepared for the remainder of the Postgres session (unless it is explicitly removed with DEALLOCATE). This is convenient because parsing a query string and preparing the statement costs bytes sent on the wire and CPU cycles to process, so reusing a statement is quite a nice optimization.

Once done with Parse, there are a few remaining steps to (the simplest form of) an extended query:

  • A Bind message, which provides the specific values to be passed for the parameters in the statement (if any).
  • An Execute message, which tells the Postgres server to actually perform the data retrieval and processing.
  • And finally a Sync message, which causes the server to close the implicit transaction, return results, and provides a synchronization point for error handling.

While that is the core pattern for accomplishing an extended protocol query, there are many more complexities possible (named Portal, ErrorResponse, etc.).

We will briefly mention one other complexity we often encounter in this protocol, which is Describe messages. Many drivers leverage Postgres’ built-in types to help with deserialization of the results into structs or classes. This is accomplished by sending a Parse-Describe-Flush/Sync sequence, which will send a statement to be prepared, and will expect back information about the types and data the query will return. This complicates bookkeeping around named prepared statements, as now there are two separate queries, with two separate kinds of responses, that must be kept track of. We won’t go into much depth on the tradeoffs of an additional round-trip in exchange for advanced information about the results’ format, but suffice it to say that it must be handled explicitly in order for the overall system to gracefully support prepared statements.

So the basic query from our code above looks like this from a message perspective:

A more complete description and the full structure of each message type are well described in the Postgres documentation.

So, what’s so hard about that?

Buffering Messages

The first challenge that Hyperdrive must solve (that many other connection poolers don’t have) is that it’s also a cache.

The happiest path for a query on Hyperdrive never travels far, and we are quite proud of the low latency of our cache hits. However, this presents a particular challenge in the case of an extended protocol query. A Parse by itself is insufficient as a cache key, both because the parameter values in the Bind messages can alter the expected results, and because it might be followed up with either a Describe or an Execute message which will invoke drastically different responses.

So Hyperdrive cannot simply pass each message to the origin database, as we must buffer them in a message log until we have enough information to reliably distinguish between cache keys. It turns out that receiving a Sync is quite a natural point at which to check whether you have enough information to serve a response. For most scenarios, we buffer until we receive a Sync, and then (assuming the scenario is cacheable) we determine whether we can serve the response from cache or we need to take a connection to the origin database.

Taking a Connection From the Pool

Assuming we aren’t serving a response from cache, for whatever reason, we’ll need to take an origin connection from our pool. One of the key advantages any connection pooler offers is in allowing many client connections to share few database connections, so minimizing how often and for how long these connections are held is crucial to making Hyperdrive performant.

To this end, Hyperdrive operates in what is traditionally called “transaction mode”. This means that a connection taken from the pool for any given transaction is returned once that transaction concludes. This is in contrast to what is often called “session mode”, where once a connection is taken from the pool it is held by the client until the client disconnects.

For Hyperdrive, allowing any client to take any database connection is vital. This is because if we “pin” a client to a given database connection then we have one fewer available for every other possible client. You can run yourself out of database connections very quickly once you start down that path, especially when your clients are many small Workers spread around the world.

The challenge prepared statements present to this scenario is that they exist at the “session” scope, which is to say, at the scope of one connection. If a client prepares a statement on connection A, but tries to reuse it and gets assigned connection B, Postgres will naturally throw an error claiming the statement doesn’t exist in the given session. No results will be returned, the client is unhappy, and all that’s left is to retry with a Parse message included. This causes extra round-trips between client and server, defeating the whole purpose of what is meant to be an optimization.

One of the goals of a connection pooler is to be as transparent to the client and server as possible. There are limitations, as Postgres will let you do some powerful things to session state that cannot be reasonably shared across arbitrary client connections, but to the extent possible the endpoints should not have to know or care about any multiplexing happening between them.

This means that when a client sends a Parse message on its connection, it should expect that the statement will be available for reuse when it wants to send a Bind-Execute-Sync sequence later on. It also means that the server should not get Bind messages for statements that only exist on some other session. Maintaining this illusion is the crux of providing support for this feature.

Putting it all together

So, what does the solution look like? If a client sends Parse-Bind-Execute-Sync with a named prepared statement, then later sends Bind-Execute-Sync to reuse it, how can we make sure that everything happens as expected? The solution, it turns out, needs just a few built-in Rust data structures for efficiently capturing what we need (a HashMap, some LruCaches and a VecDeque), and some straightforward business logic to keep track of when to intervene in the messages being passed back and forth.

Whenever a named Parse comes in, we store it in an in-memory HashMap on the server that handles message processing for that client’s connection. This persists until the client is disconnected. This means that whenever we see anything referencing the statement, we can go retrieve the complete message defining it. We’ll come back to this in a moment.

Once we’ve buffered all the messages we can and gotten to the point where it’s time to return results (let’s say because the client sent a Sync), we need to start applying some logic. For the sake of brevity we’re going to omit talking through error handling here, as it does add some significant complexity but is somewhat out of scope for this discussion.

There are two main questions that determine how we should proceed:

  1. Does our message sequence include a Parse, or are we trying to reuse a pre-existing statement?
  2. Do we have a cache hit or are we serving from the origin database?

This gives us four scenarios to consider:

  1. Parse with cache hit
  2. Parse with cache miss
  3. Reuse with cache hit
  4. Reuse with cache miss

A Parse with a cache hit is the easiest path to address, as we don’t need to do anything special. We use the messages sent as a cache key, and serve the results back to the client. We will still keep the Parse in our HashMap in case we want it later (#2 below), but otherwise we’re good to go.

A Parse with a cache miss is a bit more complicated, as now we need to send these messages to the origin server. We take a connection at random from our pool and do so, passing the results back to the client. With that, we’ve begun to make changes to session state such that all our database connections are no longer identical to each other. To keep track of what we’ve done to muddy up our state, we keep a LruCache on each connection of which statements it already has prepared. In the case where we need to evict from such a cache, we will also DEALLOCATE the statement on the connection to keep things tracked correctly.

Reuse with a cache hit is yet more tricky, but still straightforward enough. In the example below, we are sent a Bind with the same parameters twice (#1 and #9). We must identify that we received a Bind without a preceding Parse, we must go retrieve that Parse (#10), and we must use the information from it to build our cache key. Once all that is accomplished, we can serve our results from cache, needing only to trim out the ParseComplete within the cached results before returning them to the client.

Reuse with a cache miss is the hardest scenario, as it may require us to lie in both directions. In the example below, we cache results for one set of parameters (#8), but are sent a Bind with different parameters (#9). As in the cache hit scenario, we must identify that we were not sent a Parse as part of the current message sequence, retrieve it from our HashMap (#10), and build our cache key to GET from cache and confirm the miss (#11). Once we take a connection from the pool, though, we then need to check if it already has the statement we want prepared. If not, we must take our saved Parse and prepend it to our message log to be sent along to the origin database (#13). Thus, what the server receives looks like a perfectly valid Parse-Bind-Execute-Sync sequence. This is where our VecDeque (mentioned above) comes in, as converting our message log to that structure allowed us to very ergonomically make such changes without needing to rebuild the whole byte sequence. Once we receive the response from the server, all that’s needed is to trim out the initial ParseComplete response from the server, as a well-made client would likely be very confused receiving such a response to a Parse it didn’t send. With that message trimmed out, however, the client is in the position of getting exactly what it asked for, and both sides of the conversation are happy.

Dénouement

Now that we’ve got a working solution, where all parties are functioning well, let’s review! Our solution lets us share database connections across arbitrary clients with no “pinning”, no custom handling on either client or server, and supports reuse of prepared statements to reduce CPU load on re-parsing queries and reduce network traffic on re-sending Parse messages. Engineering always involves tradeoffs, so the cost of this is that we will sometimes still need to sneak in a Parse because a client got assigned a different connection on reuse, and in those scenarios there is a small amount of additional memory overhead because the same statement is prepared on multiple connections.

And now, if you haven’t already, go give Hyperdrive a spin, and let us know what you think in the Hyperdrive Discord channel!

The collective thoughts of the interwebz