Skip to content

fix(postgres) use signed int for length prefix in PgCopyIn#3701

Merged
abonander merged 1 commit into
transact-rs:mainfrom
joeydewaal:postgres-copy
Jan 24, 2025
Merged

fix(postgres) use signed int for length prefix in PgCopyIn#3701
abonander merged 1 commit into
transact-rs:mainfrom
joeydewaal:postgres-copy

Conversation

@joeydewaal
Copy link
Copy Markdown
Contributor

@joeydewaal joeydewaal commented Jan 24, 2025

While looking into #3696 I noticed that CopyData uses an i32 to represent the length prefix. However, the AsyncRead impl uses an u32. https://github.com/launchbadge/sqlx/blob/a83395a360296db1251e6e4138b6e6331912c3d4/sqlx-postgres/src/copy.rs#L233

@abonander
Copy link
Copy Markdown
Collaborator

Yeah, ultimately this doesn't really matter because Postgres is hardcoded to reject messages above a certain size depending on the message type:

This includes the 4-byte length prefix, which is why it's actually 1 GiB - 5 for the message contents.

Writing a u32 instead of an i32 would just overflow to negative, which it also rejects. So while this is a tiny correctness improvement, it won't fix the bug.

The reason why #3440 is so dangerous is that unchecked casts from usize could overflow back around to a valid value, producing a buffer underflow attack.

I commented on #3696 (comment) for what the fix should look like.

@abonander abonander changed the title fix(postgres) use signed int for length prefix fix(postgres) use signed int for length prefix in PgCopyIn Jan 24, 2025
@abonander abonander merged commit a408c49 into transact-rs:main Jan 24, 2025
@joeydewaal
Copy link
Copy Markdown
Contributor Author

Writing a u32 instead of an i32 would just overflow to negative, which it also rejects. So while this is a tiny correctness improvement, it won't fix the bug.

I figured that's why postgres would still work with small payloads but would hang with big ones.

Thanks for the detailed reply, I'll try and come up with a more correct solution for this PR and #3696.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants