rustpbx 0.4.9

A SIP PBX implementation in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
use super::{
    ProxyAction, ProxyModule,
    dialog_auth_cache::{AuthCacheKey, DialogAuthCache},
    server::SipServerRef,
};
use crate::call::cookie::SpamResult;
use crate::call::user::SipUser;
use crate::call::{CalleeDisplayName, TransactionCookie, TrunkContext};
use crate::config::ProxyConfig;
use anyhow::{Error, Result};
use async_trait::async_trait;
use rsipstack::dialog::authenticate::verify_digest;
use rsipstack::sip::Header;
use rsipstack::sip::headers::{ProxyAuthenticate, WwwAuthenticate};
use rsipstack::sip::prelude::{HeadersExt, ToTypedHeader};
use rsipstack::sip::typed::Authorization;
use rsipstack::transaction::transaction::Transaction;
use rsipstack::transport::SipAddr;
use std::net::IpAddr;
use std::sync::Arc;
use tokio_util::sync::CancellationToken;
use tracing::{debug, info, trace};

#[derive(Debug)]
pub enum AuthError {
    NotFound,
    Disabled,
    InvalidCredentials,
    SpamDetected,
    PaymentRequired,
    Other(Error),
}

impl std::fmt::Display for AuthError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            AuthError::NotFound => write!(f, "User not found"),
            AuthError::InvalidCredentials => write!(f, "Invalid credentials"),
            AuthError::SpamDetected => write!(f, "Spam detected"),
            AuthError::PaymentRequired => write!(f, "Payment required"),
            AuthError::Disabled => write!(f, "User is disabled"),
            AuthError::Other(e) => write!(f, "{}", e),
        }
    }
}

impl std::error::Error for AuthError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            AuthError::Other(e) => Some(e.as_ref()),
            _ => None,
        }
    }
}

impl From<Error> for AuthError {
    fn from(e: Error) -> Self {
        AuthError::Other(e)
    }
}

#[async_trait]
pub trait AuthBackend: Send + Sync {
    async fn authenticate(
        &self,
        original: &rsipstack::sip::Request,
        cookie: &TransactionCookie,
    ) -> Result<Option<SipUser>, AuthError>;
}

#[derive(Clone)]
pub struct AuthModule {
    server: SipServerRef,
    dialog_auth_cache: Option<DialogAuthCache>,
}

impl AuthModule {
    pub fn create(server: SipServerRef, config: Arc<ProxyConfig>) -> Result<Box<dyn ProxyModule>> {
        let module = AuthModule::new(server, config);
        Ok(Box::new(module))
    }

    pub fn new(server: SipServerRef, config: Arc<ProxyConfig>) -> Self {
        let dialog_auth_cache = config.dialog_auth_cache.as_ref().and_then(|cache_config| {
            if cache_config.enabled {
                Some(DialogAuthCache::new(cache_config))
            } else {
                None
            }
        });

        Self {
            server,
            dialog_auth_cache,
        }
    }

    pub async fn authenticate_request(
        &self,
        tx: &Transaction,
    ) -> Result<Option<SipUser>, AuthError> {
        let mut auth_inner: Option<(Authorization, &str)> = None;
        for header in tx.original.headers.iter() {
            match header {
                Header::Authorization(h) => {
                    auth_inner = Authorization::parse(h.value())
                        .ok()
                        .map(|auth| (auth, h.value()));
                    break;
                }
                Header::ProxyAuthorization(h) => {
                    auth_inner = Authorization::parse(h.value())
                        .ok()
                        .map(|auth| (auth, h.value()));
                    break;
                }
                _ => {}
            }
        }
        let (auth_inner, raw_auth_header) = match auth_inner {
            Some(auth) => auth,
            None => {
                return Ok(None);
            }
        };
        let user = SipUser::try_from(tx).map_err(AuthError::Other)?;
        // Check if user exists and is enabled
        match self
            .server
            .user_backend
            .get_user(&user.username, user.realm.as_deref(), Some(&tx.original))
            .await?
        {
            Some(mut stored_user) => {
                if !stored_user.enabled {
                    info!(username = user.username, realm = ?user.realm, "User is disabled");
                    return Ok(None);
                }
                if let Some(realm) = user.realm.as_ref()
                    && !self.server.is_same_realm(realm).await
                {
                    info!(username = user.username, realm = ?user.realm, "User is not in the same realm");
                    return Ok(None);
                }
                stored_user.merge_with(&user);
                match self.verify_credentials(
                    &stored_user,
                    &tx.original.method,
                    &auth_inner,
                    raw_auth_header,
                ) {
                    true => Ok(Some(stored_user)),
                    false => Ok(None),
                }
            }
            None => {
                info!(username = user.username, realm = ?user.realm, "authenticate_request missing");
                Ok(None)
            }
        }
    }

    fn verify_credentials(
        &self,
        user: &SipUser,
        method: &rsipstack::sip::Method,
        auth: &Authorization,
        raw_auth_header: &str,
    ) -> bool {
        let empty_string = "".to_string();
        let password = user.password.as_ref().unwrap_or(&empty_string);

        verify_digest(auth, password, method, raw_auth_header)
    }

    /// Check if a request is an in-dialog request (has To tag)
    fn is_in_dialog_request(&self, tx: &Transaction) -> bool {
        if let Ok(to_header) = tx.original.to_header() {
            if let Ok(typed_to) = to_header.typed() {
                // In-dialog requests have a tag parameter in the To header
                return typed_to
                    .params
                    .iter()
                    .any(|p| matches!(p, rsipstack::sip::Param::Tag(_)));
            }
        }
        false
    }

    /// Get the source address from the transaction
    fn get_source_addr(&self, tx: &Transaction) -> Option<SipAddr> {
        tx.connection
            .as_ref()
            .and_then(|conn| conn.get_remote_addr().cloned())
    }

    /// Extract cache key (call_id, from_tag) from a transaction.
    /// Uses from_tag because it is stable throughout the dialog lifetime,
    /// unlike to_tag which is absent in the initial INVITE.
    fn extract_auth_cache_key(&self, tx: &Transaction) -> Option<AuthCacheKey> {
        let call_id = tx.original.call_id_header().ok()?.value().to_string();
        let from_tag = tx
            .original
            .from_header()
            .ok()?
            .tag()
            .ok()??
            .value()
            .to_string();
        Some((call_id, from_tag))
    }

    /// Build the shared `Digest realm="...", nonce="...", algorithm=MD5`
    /// challenge string used by both `create_proxy_auth_challenge` and
    /// `create_www_auth_challenge`. Centralising the format prevents the two
    /// variants from drifting out of sync.
    fn build_digest_challenge(&self, realm: &str) -> String {
        // NOTE: a fresh nonce is generated on every call so callers must not
        // share the returned string between two distinct challenges.
        let nonce = rsipstack::transaction::random_text(16);
        format!(
            r#"Digest realm="{}", nonce="{}", algorithm=MD5"#,
            realm, nonce
        )
    }

    pub fn create_proxy_auth_challenge(&self, realm: &str) -> Result<ProxyAuthenticate> {
        Ok(ProxyAuthenticate::new(self.build_digest_challenge(realm)))
    }

    pub fn create_www_auth_challenge(&self, realm: &str) -> Result<WwwAuthenticate> {
        Ok(WwwAuthenticate::new(self.build_digest_challenge(realm)))
    }

    fn is_cluster_peer_source(&self, tx: &Transaction) -> bool {
        let Some(source) = self.get_source_addr(tx) else {
            return false;
        };
        let source_ip: IpAddr = source.addr.host.clone().try_into().ok().unwrap_or_else(|| {
            // Host isn't an IP (domain/invalid) — treat as non-cluster source.
            IpAddr::from([0, 0, 0, 0])
        });
        if source_ip == IpAddr::from([0, 0, 0, 0]) {
            return false;
        }

        self.server
            .cluster_peer_ips
            .iter()
            .any(|peer_ip| *peer_ip == source_ip)
    }
}

#[async_trait]
impl ProxyModule for AuthModule {
    fn name(&self) -> &str {
        "auth"
    }

    fn allow_methods(&self) -> Vec<rsipstack::sip::Method> {
        vec![
            rsipstack::sip::Method::Invite,
            rsipstack::sip::Method::Register,
            rsipstack::sip::Method::Bye,
            rsipstack::sip::Method::Options,
            rsipstack::sip::Method::Ack,
            rsipstack::sip::Method::Cancel,
            rsipstack::sip::Method::Update,
            rsipstack::sip::Method::Refer,
            rsipstack::sip::Method::Notify,
            rsipstack::sip::Method::Message,
            rsipstack::sip::Method::Info,
            rsipstack::sip::Method::Subscribe,
            rsipstack::sip::Method::Publish,
        ]
    }

    async fn on_start(&mut self) -> Result<()> {
        debug!("Auth module started");
        Ok(())
    }

    async fn on_stop(&self) -> Result<()> {
        debug!("Auth module stopped");
        Ok(())
    }

    async fn on_transaction_begin(
        &self,
        _token: CancellationToken,
        tx: &mut Transaction,
        cookie: TransactionCookie,
    ) -> Result<ProxyAction> {
        let tx_user = SipUser::try_from(&*tx)?;
        let source = tx_user
            .destination
            .as_ref()
            .map(|d| d.to_string())
            .unwrap_or_else(|| "unknown".to_string());

        // Check if this is an in-dialog request and if we can skip authentication via cache
        if let Some(ref cache) = self.dialog_auth_cache {
            if self.is_in_dialog_request(tx) {
                if let (Some(cache_key), Some(source_addr)) =
                    (self.extract_auth_cache_key(tx), self.get_source_addr(tx))
                {
                    trace!(
                        call_id = %cache_key.0,
                        from_tag = %cache_key.1,
                        method = %tx.original.method,
                        %source,
                        "Checking in-dialog request against auth cache"
                    );

                    if cache.is_authenticated(&cache_key, &source_addr).await {
                        debug!(
                            call_id = %cache_key.0,
                            from_tag = %cache_key.1,
                            method = %tx.original.method,
                            %source,
                            "In-dialog request authenticated via cache, skipping auth"
                        );
                        cookie.set_user(tx_user.clone());
                        return Ok(ProxyAction::Continue);
                    }
                }
            }
        }

        // Only authenticate INVITE and REGISTER requests (out-of-dialog)
        if tx.original.method != rsipstack::sip::Method::Invite
            && tx.original.method != rsipstack::sip::Method::Register
        {
            return Ok(ProxyAction::Continue);
        }

        for backend in self.server.auth_backend.iter() {
            match backend.authenticate(&tx.original, &cookie).await {
                Ok(Some(mut user)) => {
                    user.merge_with(&tx_user);
                    cookie.set_user(user);

                    // Cache the authenticated dialog for in-dialog requests
                    if let (Some(ref cache), Some(source_addr)) =
                        (self.dialog_auth_cache.as_ref(), self.get_source_addr(tx))
                    {
                        if let Some(cache_key) = self.extract_auth_cache_key(tx) {
                            cache.put(cache_key, source_addr).await;
                        }
                    }

                    return Ok(ProxyAction::Continue);
                }
                Err(e) => {
                    if matches!(e, AuthError::SpamDetected) {
                        cookie.mark_as_spam(SpamResult::Spam);
                    }
                    info!(error=%e, key = %tx.key, %source, "auth_backend authenticate failed");
                }
                _ => {}
            }
        }

        if cookie.is_spam() {
            return Ok(ProxyAction::Abort);
        }

        let is_from_trunk = cookie.get_extension::<TrunkContext>().is_some();
        if is_from_trunk {
            cookie.set_user(tx_user.clone());
            return Ok(ProxyAction::Continue);
        }

        if self.is_cluster_peer_source(tx) {
            let request_host = tx.original.uri().host().to_string();
            if self.server.is_same_realm(&request_host).await {
                cookie.set_user(tx_user.clone());
                return Ok(ProxyAction::Continue);
            }
        }

        // Path B: Check WebSocket pre-authentication via JWT
        if let Some(ref registry) = self.server.pre_auth_registry {
            if let Some(source_addr) = self.get_source_addr(tx) {
                if let Some(agent_id) = registry.lookup(&source_addr).await {
                    if tx.original.method == rsipstack::sip::Method::Register {
                        let realm = tx.original.uri().host().to_string();
                        match self
                            .server
                            .user_backend
                            .get_user(&agent_id, Some(&realm), Some(&tx.original))
                            .await
                        {
                            Ok(Some(mut user)) => {
                                if !user.enabled {
                                    info!(username = %agent_id, "Pre-authed user is disabled");
                                } else {
                                    user.username = agent_id;
                                    cookie.set_user(user);
                                    return Ok(ProxyAction::Continue);
                                }
                            }
                            _ => {
                                // User not found in backend — create minimal SipUser from JWT identity
                                let user = SipUser {
                                    username: agent_id,
                                    enabled: true,
                                    realm: Some(realm),
                                    ..Default::default()
                                };
                                cookie.set_user(user);
                                return Ok(ProxyAction::Continue);
                            }
                        }
                    }
                }
            }
        }

        match self.authenticate_request(tx).await {
            Ok(authenticated) => {
                if let Some(user) = authenticated {
                    cookie.set_user(user);

                    // Cache the authenticated dialog for in-dialog requests
                    if let (Some(ref cache), Some(source_addr)) =
                        (self.dialog_auth_cache.as_ref(), self.get_source_addr(tx))
                    {
                        if let Some(cache_key) = self.extract_auth_cache_key(tx) {
                            cache.put(cache_key, source_addr).await;
                        }
                    }

                    return Ok(ProxyAction::Continue);
                }

                let to_header = tx.original.to_header()?.uri()?;
                let callee_user = to_header.user().unwrap_or("");
                let callee_realm = to_header.host().to_string();

                if tx.original.method == rsipstack::sip::Method::Invite {
                    match self
                        .server
                        .user_backend
                        .get_user(callee_user, Some(&callee_realm), Some(&tx.original))
                        .await
                    {
                        Ok(Some(callee_profile)) if callee_profile.allow_guest_calls => {
                            info!(
                                caller = %tx_user.username,
                                extension = %callee_user,
                                %source,
                                "Allowing guest call without authentication"
                            );
                            cookie.set_user(tx_user.clone());
                            if let Some(display_name) = callee_profile.display_name {
                                cookie.insert_extension(CalleeDisplayName(display_name));
                            }
                            return Ok(ProxyAction::Continue);
                        }
                        Ok(_) => {}
                        Err(e) => {
                            info!(
                                extension = %callee_user,
                                error = %e,
                                %source,
                                "Failed to evaluate guest call permission"
                            );
                        }
                    }
                }

                let from_uri = tx.original.from_header()?.uri()?;
                let request_host = tx.original.uri().host().to_string();
                let realm = self.server.proxy_config.select_realm(request_host.as_str());

                if self.server.proxy_config.ensure_user.unwrap_or_default() {
                    match self
                        .server
                        .user_backend
                        .get_user(
                            from_uri.user().unwrap_or(""),
                            Some(&realm),
                            Some(&tx.original),
                        )
                        .await
                    {
                        Ok(Some(_)) => {}
                        _ => {
                            info!(
                                from = %from_uri,
                                %source,
                                "User not found, don't send authentication challenge"
                            );
                            cookie.mark_as_spam(SpamResult::Spam);
                            return Ok(ProxyAction::Abort);
                        }
                    };
                }

                let (status_code, headers) =
                    if tx.original.method == rsipstack::sip::Method::Register {
                        let www_auth = self.create_www_auth_challenge(&realm)?;
                        (
                            rsipstack::sip::StatusCode::Unauthorized,
                            vec![Header::WwwAuthenticate(www_auth)],
                        )
                    } else {
                        let www_auth = self.create_www_auth_challenge(&realm)?;
                        let proxy_auth = self.create_proxy_auth_challenge(&realm)?;
                        (
                            rsipstack::sip::StatusCode::ProxyAuthenticationRequired,
                            vec![
                                Header::WwwAuthenticate(www_auth),
                                Header::ProxyAuthenticate(proxy_auth),
                            ],
                        )
                    };

                info!(
                    from = from_uri.to_string(),
                    realm = realm,
                    status = %status_code,
                    %source,
                    "Authentication failed, sending challenge"
                );
                tx.reply_with(status_code, headers, None).await.ok();
                Ok(ProxyAction::Abort)
            }
            Err(e) => {
                info!(error=%e, key = %tx.key, %source, "Authentication error");
                if matches!(e, AuthError::SpamDetected) {
                    cookie.mark_as_spam(SpamResult::Spam);
                }
                Err(anyhow::anyhow!("Authentication error: {}", e))
            }
        }
    }
}