Line data Source code
1 : //! Definitions for SCRAM messages.
2 :
3 : use super::base64_decode_array;
4 : use super::key::{ScramKey, SCRAM_KEY_LEN};
5 : use super::signature::SignatureBuilder;
6 : use crate::sasl::ChannelBinding;
7 : use std::fmt;
8 : use std::ops::Range;
9 :
10 : /// Faithfully taken from PostgreSQL.
11 : pub const SCRAM_RAW_NONCE_LEN: usize = 18;
12 :
13 : /// Although we ignore all extensions, we still have to validate the message.
14 132 : fn validate_sasl_extensions<'a>(parts: impl Iterator<Item = &'a str>) -> Option<()> {
15 132 : for mut chars in parts.map(|s| s.chars()) {
16 0 : let attr = chars.next()?;
17 0 : if !attr.is_ascii_alphabetic() {
18 0 : return None;
19 0 : }
20 0 : let eq = chars.next()?;
21 0 : if eq != '=' {
22 0 : return None;
23 0 : }
24 : }
25 :
26 132 : Some(())
27 132 : }
28 :
29 0 : #[derive(Debug)]
30 : pub struct ClientFirstMessage<'a> {
31 : /// `client-first-message-bare`.
32 : pub bare: &'a str,
33 : /// Channel binding mode.
34 : pub cbind_flag: ChannelBinding<&'a str>,
35 : /// (Client username)[<https://github.com/postgres/postgres/blob/94226d4506e66d6e7cbf/src/backend/libpq/auth-scram.c#L13>].
36 : pub username: &'a str,
37 : /// Client nonce.
38 : pub nonce: &'a str,
39 : }
40 :
41 : impl<'a> ClientFirstMessage<'a> {
42 : // NB: FromStr doesn't work with lifetimes
43 69 : pub fn parse(input: &'a str) -> Option<Self> {
44 69 : let mut parts = input.split(',');
45 :
46 69 : let cbind_flag = ChannelBinding::parse(parts.next()?)?;
47 :
48 : // PG doesn't support authorization identity,
49 : // so we don't bother defining GS2 header type
50 69 : let authzid = parts.next()?;
51 69 : if !authzid.is_empty() {
52 0 : return None;
53 69 : }
54 69 :
55 69 : // Unfortunately, `parts.as_str()` is unstable
56 69 : let pos = authzid.as_ptr() as usize - input.as_ptr() as usize + 1;
57 69 : let (_, bare) = input.split_at(pos);
58 :
59 : // In theory, these might be preceded by "reserved-mext" (i.e. "m=")
60 69 : let username = parts.next()?.strip_prefix("n=")?;
61 69 : let nonce = parts.next()?.strip_prefix("r=")?;
62 :
63 : // Validate but ignore auth extensions
64 69 : validate_sasl_extensions(parts)?;
65 :
66 69 : Some(Self {
67 69 : bare,
68 69 : cbind_flag,
69 69 : username,
70 69 : nonce,
71 69 : })
72 69 : }
73 :
74 : /// Build a response to [`ClientFirstMessage`].
75 61 : pub fn build_server_first_message(
76 61 : &self,
77 61 : nonce: &[u8; SCRAM_RAW_NONCE_LEN],
78 61 : salt_base64: &str,
79 61 : iterations: u32,
80 61 : ) -> OwnedServerFirstMessage {
81 61 : use std::fmt::Write;
82 61 :
83 61 : let mut message = String::new();
84 61 : write!(&mut message, "r={}", self.nonce).unwrap();
85 61 : base64::encode_config_buf(nonce, base64::STANDARD, &mut message);
86 61 : let combined_nonce = 2..message.len();
87 61 : write!(&mut message, ",s={},i={}", salt_base64, iterations).unwrap();
88 61 :
89 61 : // This design guarantees that it's impossible to create a
90 61 : // server-first-message without receiving a client-first-message
91 61 : OwnedServerFirstMessage {
92 61 : message,
93 61 : nonce: combined_nonce,
94 61 : }
95 61 : }
96 : }
97 :
98 0 : #[derive(Debug)]
99 : pub struct ClientFinalMessage<'a> {
100 : /// `client-final-message-without-proof`.
101 : pub without_proof: &'a str,
102 : /// Channel binding data (base64).
103 : pub channel_binding: &'a str,
104 : /// Combined client & server nonce.
105 : pub nonce: &'a str,
106 : /// Client auth proof.
107 : pub proof: [u8; SCRAM_KEY_LEN],
108 : }
109 :
110 : impl<'a> ClientFinalMessage<'a> {
111 : // NB: FromStr doesn't work with lifetimes
112 63 : pub fn parse(input: &'a str) -> Option<Self> {
113 63 : let (without_proof, proof) = input.rsplit_once(',')?;
114 :
115 63 : let mut parts = without_proof.split(',');
116 63 : let channel_binding = parts.next()?.strip_prefix("c=")?;
117 63 : let nonce = parts.next()?.strip_prefix("r=")?;
118 :
119 : // Validate but ignore auth extensions
120 63 : validate_sasl_extensions(parts)?;
121 :
122 63 : let proof = base64_decode_array(proof.strip_prefix("p=")?)?;
123 :
124 63 : Some(Self {
125 63 : without_proof,
126 63 : channel_binding,
127 63 : nonce,
128 63 : proof,
129 63 : })
130 63 : }
131 :
132 : /// Build a response to [`ClientFinalMessage`].
133 48 : pub fn build_server_final_message(
134 48 : &self,
135 48 : signature_builder: SignatureBuilder,
136 48 : server_key: &ScramKey,
137 48 : ) -> String {
138 48 : let mut buf = String::from("v=");
139 48 : base64::encode_config_buf(
140 48 : signature_builder.build(server_key),
141 48 : base64::STANDARD,
142 48 : &mut buf,
143 48 : );
144 48 :
145 48 : buf
146 48 : }
147 : }
148 :
149 : /// We need to keep a convenient representation of this
150 : /// message for the next authentication step.
151 : pub struct OwnedServerFirstMessage {
152 : /// Owned `server-first-message`.
153 : message: String,
154 : /// Slice into `message`.
155 : nonce: Range<usize>,
156 : }
157 :
158 : impl OwnedServerFirstMessage {
159 : /// Extract combined nonce from the message.
160 : #[inline(always)]
161 53 : pub fn nonce(&self) -> &str {
162 53 : &self.message[self.nonce.clone()]
163 53 : }
164 :
165 : /// Get reference to a text representation of the message.
166 : #[inline(always)]
167 114 : pub fn as_str(&self) -> &str {
168 114 : &self.message
169 114 : }
170 : }
171 :
172 : impl fmt::Debug for OwnedServerFirstMessage {
173 0 : fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
174 0 : f.debug_struct("ServerFirstMessage")
175 0 : .field("message", &self.as_str())
176 0 : .field("nonce", &self.nonce())
177 0 : .finish()
178 0 : }
179 : }
180 :
181 : #[cfg(test)]
182 : mod tests {
183 : use super::*;
184 :
185 2 : #[test]
186 2 : fn parse_client_first_message() {
187 2 : use ChannelBinding::*;
188 2 :
189 2 : // (Almost) real strings captured during debug sessions
190 2 : let cases = [
191 2 : (NotSupportedClient, "n,,n=pepe,r=t8JwklwKecDLwSsA72rHmVju"),
192 2 : (NotSupportedServer, "y,,n=pepe,r=t8JwklwKecDLwSsA72rHmVju"),
193 2 : (
194 2 : Required("tls-server-end-point"),
195 2 : "p=tls-server-end-point,,n=pepe,r=t8JwklwKecDLwSsA72rHmVju",
196 2 : ),
197 2 : ];
198 :
199 8 : for (cb, input) in cases {
200 6 : let msg = ClientFirstMessage::parse(input).unwrap();
201 6 :
202 6 : assert_eq!(msg.bare, "n=pepe,r=t8JwklwKecDLwSsA72rHmVju");
203 6 : assert_eq!(msg.username, "pepe");
204 6 : assert_eq!(msg.nonce, "t8JwklwKecDLwSsA72rHmVju");
205 6 : assert_eq!(msg.cbind_flag, cb);
206 : }
207 2 : }
208 :
209 2 : #[test]
210 2 : fn parse_client_final_message() {
211 2 : let input = [
212 2 : "c=eSws",
213 2 : "r=iiYEfS3rOgn8S3rtpSdrOsHtPLWvIkdgmHxA0hf3JNOAG4dU",
214 2 : "p=SRpfsIVS4Gk11w1LqQ4QvCUBZYQmqXNSDEcHqbQ3CHI=",
215 2 : ]
216 2 : .join(",");
217 2 :
218 2 : let msg = ClientFinalMessage::parse(&input).unwrap();
219 2 : assert_eq!(
220 2 : msg.without_proof,
221 2 : "c=eSws,r=iiYEfS3rOgn8S3rtpSdrOsHtPLWvIkdgmHxA0hf3JNOAG4dU"
222 2 : );
223 2 : assert_eq!(
224 2 : msg.nonce,
225 2 : "iiYEfS3rOgn8S3rtpSdrOsHtPLWvIkdgmHxA0hf3JNOAG4dU"
226 2 : );
227 2 : assert_eq!(
228 2 : base64::encode(msg.proof),
229 2 : "SRpfsIVS4Gk11w1LqQ4QvCUBZYQmqXNSDEcHqbQ3CHI="
230 2 : );
231 2 : }
232 : }
|