kanidmd_core/https/
mod.rs

1mod apidocs;
2pub(crate) mod cache_buster;
3pub(crate) mod errors;
4mod extractors;
5mod generic;
6mod javascript;
7mod manifest;
8pub(crate) mod middleware;
9mod oauth2;
10pub(crate) mod trace;
11mod v1;
12mod v1_domain;
13mod v1_oauth2;
14mod v1_scim;
15mod views;
16
17use self::extractors::ClientConnInfo;
18use self::javascript::*;
19use crate::actors::{QueryServerReadV1, QueryServerWriteV1};
20use crate::config::{AddressSet, Configuration, ServerRole};
21use crate::CoreAction;
22use axum::{
23    body::Body,
24    extract::connect_info::IntoMakeServiceWithConnectInfo,
25    http::{HeaderMap, HeaderValue, Request},
26    middleware::{from_fn, from_fn_with_state},
27    response::Redirect,
28    routing::*,
29    Router,
30};
31use axum_extra::extract::cookie::CookieJar;
32use cidr::IpCidr;
33use compact_jwt::{error::JwtError, JwsCompact, JwsHs256Signer, JwsVerifier};
34use futures::pin_mut;
35use haproxy_protocol::{ProxyHdrV2, RemoteAddress};
36use hyper::body::Incoming;
37use hyper_util::rt::{TokioExecutor, TokioIo};
38use kanidm_lib_crypto::x509_cert::{der::Decode, x509_public_key_s256, Certificate};
39use kanidm_proto::{constants::KSESSIONID, internal::COOKIE_AUTH_SESSION_ID};
40use kanidmd_lib::{idm::ClientCertInfo, status::StatusActor};
41use openssl::ssl::{Ssl, SslAcceptor};
42use serde::de::DeserializeOwned;
43use sketching::*;
44use std::fmt::Write;
45use std::io::ErrorKind;
46use std::path::PathBuf;
47use std::pin::Pin;
48use std::sync::Arc;
49use std::{net::SocketAddr, str::FromStr};
50use tokio::{
51    io::{AsyncRead, AsyncWrite},
52    net::{TcpListener, TcpStream},
53    sync::broadcast,
54    sync::mpsc,
55    task,
56};
57use tokio_openssl::SslStream;
58use tower::Service;
59use tower_http::{services::ServeDir, trace::TraceLayer};
60use url::Url;
61use uuid::Uuid;
62
63#[derive(Clone)]
64pub struct ServerState {
65    pub(crate) status_ref: &'static StatusActor,
66    pub(crate) qe_w_ref: &'static QueryServerWriteV1,
67    pub(crate) qe_r_ref: &'static QueryServerReadV1,
68    // Store the token management parts.
69    pub(crate) jws_signer: JwsHs256Signer,
70    pub(crate) trust_x_forward_for_ips: Option<Arc<AddressSet>>,
71    pub(crate) csp_header: HeaderValue,
72    pub(crate) origin: Url,
73    pub(crate) domain: String,
74    // This is set to true by default, and is only false on integration tests.
75    pub(crate) secure_cookies: bool,
76}
77
78impl ServerState {
79    /// Deserialize some input string validating that it was signed by our instance's
80    /// HMAC signer. This is used for short lived server-only sessions and context
81    /// data. This has applications in both accessing cookie content and header content.
82    fn deserialise_from_str<T: DeserializeOwned>(&self, input: &str) -> Option<T> {
83        match JwsCompact::from_str(input) {
84            Ok(val) => match self.jws_signer.verify(&val) {
85                Ok(val) => val.from_json::<T>().ok(),
86                Err(err) => {
87                    error!(?err, "Failed to deserialise JWT from request");
88                    if matches!(err, JwtError::InvalidSignature) {
89                        // The server has an ephemeral in memory HMAC signer. This is important as
90                        // auth (login) sessions on one node shouldn't validate on another. Sessions
91                        // that are shared beween nodes use the internal ECDSA signer.
92                        //
93                        // But because of this if the server restarts it rolls the key. Additionally
94                        // it can occur if the load balancer isn't sticking sessions to the correct
95                        // node. That can cause this error. So we want to specifically call it out
96                        // to admins so they can investigate that the fault is occurring *outside*
97                        // of kanidm.
98                        warn!("Invalid Signature errors can occur if your instance restarted recently, if a load balancer is not configured for sticky sessions, or a session was tampered with.");
99                    }
100                    None
101                }
102            },
103            Err(_) => None,
104        }
105    }
106
107    #[instrument(level = "trace", skip_all)]
108    fn get_current_auth_session_id(&self, headers: &HeaderMap, jar: &CookieJar) -> Option<Uuid> {
109        // We see if there is a signed header copy first.
110        headers
111            .get(KSESSIONID)
112            .and_then(|hv| {
113                trace!("trying header");
114                // Get the first header value.
115                hv.to_str().ok()
116            })
117            .or_else(|| {
118                trace!("trying cookie");
119                jar.get(COOKIE_AUTH_SESSION_ID).map(|c| c.value())
120            })
121            .and_then(|s| {
122                trace!(id_jws = %s);
123                self.deserialise_from_str::<Uuid>(s)
124            })
125    }
126}
127
128pub(crate) fn get_js_files(role: ServerRole) -> Result<Vec<JavaScriptFile>, ()> {
129    let mut all_pages: Vec<JavaScriptFile> = Vec::new();
130
131    if !matches!(role, ServerRole::WriteReplicaNoUI) {
132        // let's set up the list of js module hashes
133        let pkg_path = env!("KANIDM_SERVER_UI_PKG_PATH").to_owned();
134
135        let filelist = [
136            "external/bootstrap.bundle.min.js",
137            "external/htmx.min.1.9.12.js",
138            "external/confetti.js",
139            "external/base64.js",
140            "modules/cred_update.mjs",
141            "pkhtml.js",
142            "style.js",
143        ];
144
145        for filepath in filelist {
146            match generate_integrity_hash(format!("{}/{}", pkg_path, filepath,)) {
147                Ok(hash) => {
148                    debug!("Integrity hash for {}: {}", filepath, hash);
149                    let js = JavaScriptFile { hash };
150                    all_pages.push(js)
151                }
152                Err(err) => {
153                    admin_error!(
154                        ?err,
155                        "Failed to generate integrity hash for {} - cancelling startup!",
156                        filepath
157                    );
158                    return Err(());
159                }
160            }
161        }
162    }
163    Ok(all_pages)
164}
165
166pub async fn create_https_server(
167    config: Configuration,
168    jws_signer: JwsHs256Signer,
169    status_ref: &'static StatusActor,
170    qe_w_ref: &'static QueryServerWriteV1,
171    qe_r_ref: &'static QueryServerReadV1,
172    server_message_tx: broadcast::Sender<CoreAction>,
173    maybe_tls_acceptor: Option<SslAcceptor>,
174    tls_acceptor_reload_rx: mpsc::Receiver<SslAcceptor>,
175) -> Result<task::JoinHandle<()>, ()> {
176    let rx = server_message_tx.subscribe();
177
178    let all_js_files = get_js_files(config.role)?;
179    // set up the CSP headers
180    // script-src 'self'
181    //      'sha384-Zao7ExRXVZOJobzS/uMp0P1jtJz3TTqJU4nYXkdmsjpiVD+/wcwCyX7FGqRIqvIz'
182    //      'sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM';
183
184    let js_directives = all_js_files
185        .into_iter()
186        .map(|f| f.hash)
187        .collect::<Vec<String>>();
188
189    let js_checksums: String = js_directives
190        .iter()
191        .fold(String::new(), |mut output, value| {
192            let _ = write!(output, " 'sha384-{}'", value);
193            output
194        });
195
196    let csp_header = format!(
197        concat!(
198            "default-src 'self'; ",
199            "base-uri 'self' https:; ",
200            "form-action 'self' https:;",
201            "frame-ancestors 'none'; ",
202            "img-src 'self' data:; ",
203            "worker-src 'none'; ",
204            "script-src 'self' 'unsafe-eval'{};",
205        ),
206        js_checksums
207    );
208
209    let csp_header = HeaderValue::from_str(&csp_header).map_err(|err| {
210        error!(?err, "Unable to generate content security policy");
211    })?;
212
213    let trust_x_forward_for_ips = config
214        .http_client_address_info
215        .trusted_x_forward_for()
216        .map(Arc::new);
217
218    let trusted_proxy_v2_ips = config
219        .http_client_address_info
220        .trusted_proxy_v2()
221        .map(Arc::new);
222
223    let state = ServerState {
224        status_ref,
225        qe_w_ref,
226        qe_r_ref,
227        jws_signer,
228        trust_x_forward_for_ips,
229        csp_header,
230        origin: config.origin,
231        domain: config.domain.clone(),
232        secure_cookies: config.integration_test_config.is_none(),
233    };
234
235    let static_routes = match config.role {
236        ServerRole::WriteReplica | ServerRole::ReadOnlyReplica => {
237            Router::new()
238                .route("/ui/images/oauth2/:rs_name", get(oauth2::oauth2_image_get))
239                .route("/ui/images/domain", get(v1_domain::image_get))
240                .route("/manifest.webmanifest", get(manifest::manifest)) // skip_route_check
241                // Layers only apply to routes that are *already* added, not the ones
242                // added after.
243                .layer(middleware::compression::new())
244                .layer(from_fn(middleware::caching::cache_me_short))
245                .route("/", get(|| async { Redirect::to("/ui") }))
246                .nest("/ui", views::view_router())
247            // Can't compress on anything that changes
248        }
249        ServerRole::WriteReplicaNoUI => Router::new(),
250    };
251    let app = Router::new()
252        .merge(oauth2::route_setup(state.clone()))
253        .merge(v1_scim::route_setup())
254        .merge(v1::route_setup(state.clone()))
255        .route("/robots.txt", get(generic::robots_txt))
256        .route(
257            views::constants::Urls::WellKnownChangePassword.as_ref(),
258            get(generic::redirect_to_update_credentials),
259        );
260
261    let app = match config.role {
262        ServerRole::WriteReplicaNoUI => app,
263        ServerRole::WriteReplica | ServerRole::ReadOnlyReplica => {
264            let pkg_path = PathBuf::from(env!("KANIDM_SERVER_UI_PKG_PATH"));
265            if !pkg_path.exists() {
266                eprintln!(
267                    "Couldn't find htmx UI package path: ({}), quitting.",
268                    env!("KANIDM_SERVER_UI_PKG_PATH")
269                );
270                std::process::exit(1);
271            }
272            let pkg_router = Router::new()
273                .nest_service("/pkg", ServeDir::new(pkg_path))
274                // TODO: Add in the br precompress
275                .layer(from_fn(middleware::caching::cache_me_short));
276
277            app.merge(pkg_router)
278        }
279    };
280
281    // this sets up the default span which logs the URL etc.
282    let trace_layer = TraceLayer::new_for_http()
283        .make_span_with(trace::DefaultMakeSpanKanidmd::new())
284        // setting these to trace because all they do is print "started processing request", and we are already doing that enough!
285        .on_response(trace::DefaultOnResponseKanidmd::new());
286
287    let app = app
288        .merge(static_routes)
289        .layer(from_fn_with_state(
290            state.clone(),
291            middleware::security_headers::security_headers_layer,
292        ))
293        .layer(from_fn(middleware::version_middleware))
294        .layer(from_fn(
295            middleware::hsts_header::strict_transport_security_layer,
296        ));
297
298    // layer which checks the responses have a content-type of JSON when we're in debug mode
299    #[cfg(any(test, debug_assertions))]
300    let app = app.layer(from_fn(middleware::are_we_json_yet));
301
302    let app = app
303        .route("/status", get(generic::status))
304        // This must be the LAST middleware.
305        // This is because the last middleware here is the first to be entered and the last
306        // to be exited, and this middleware sets up ids' and other bits for for logging
307        // coherence to be maintained.
308        .layer(from_fn(middleware::kopid_middleware))
309        .merge(apidocs::router())
310        // this MUST be the last layer before with_state else the span never starts and everything breaks.
311        .layer(trace_layer)
312        .with_state(state)
313        // the connect_info bit here lets us pick up the remote address of the client
314        .into_make_service_with_connect_info::<ClientConnInfo>();
315
316    let addr = SocketAddr::from_str(&config.address).map_err(|err| {
317        error!(
318            "Failed to parse address ({:?}) from config: {:?}",
319            config.address, err
320        );
321    })?;
322
323    info!("Starting the web server...");
324
325    let listener = match TcpListener::bind(addr).await {
326        Ok(l) => l,
327        Err(err) => {
328            error!(?err, "Failed to bind tcp listener");
329            return Err(());
330        }
331    };
332
333    match maybe_tls_acceptor {
334        Some(tls_acceptor) => Ok(task::spawn(server_tls_loop(
335            tls_acceptor,
336            listener,
337            app,
338            rx,
339            server_message_tx,
340            tls_acceptor_reload_rx,
341            trusted_proxy_v2_ips,
342        ))),
343        None => Ok(task::spawn(server_plaintext_loop(
344            listener,
345            app,
346            rx,
347            trusted_proxy_v2_ips,
348        ))),
349    }
350}
351
352async fn server_tls_loop(
353    mut tls_acceptor: SslAcceptor,
354    listener: TcpListener,
355    app: IntoMakeServiceWithConnectInfo<Router, ClientConnInfo>,
356    mut rx: broadcast::Receiver<CoreAction>,
357    server_message_tx: broadcast::Sender<CoreAction>,
358    mut tls_acceptor_reload_rx: mpsc::Receiver<SslAcceptor>,
359    trusted_proxy_v2_ips: Option<Arc<Vec<IpCidr>>>,
360) {
361    pin_mut!(listener);
362
363    loop {
364        tokio::select! {
365            Ok(action) = rx.recv() => {
366                match action {
367                    CoreAction::Shutdown => break,
368                }
369            }
370            accept = listener.accept() => {
371                match accept {
372                    Ok((stream, addr)) => {
373                        let tls_acceptor = tls_acceptor.clone();
374                        let app = app.clone();
375                        task::spawn(handle_tls_conn(tls_acceptor, stream, app, addr, trusted_proxy_v2_ips.clone()));
376                    }
377                    Err(err) => {
378                        error!("Web server exited with {:?}", err);
379                        if let Err(err) = server_message_tx.send(CoreAction::Shutdown) {
380                            error!("Web server failed to send shutdown message! {:?}", err)
381                        };
382                        break;
383                    }
384                }
385            }
386            Some(mut new_tls_acceptor) = tls_acceptor_reload_rx.recv() => {
387                std::mem::swap(&mut tls_acceptor, &mut new_tls_acceptor);
388                info!("Reloaded http tls acceptor");
389            }
390        }
391    }
392
393    info!("Stopped {}", super::TaskName::HttpsServer);
394}
395
396async fn server_plaintext_loop(
397    listener: TcpListener,
398    app: IntoMakeServiceWithConnectInfo<Router, ClientConnInfo>,
399    mut rx: broadcast::Receiver<CoreAction>,
400    trusted_proxy_v2_ips: Option<Arc<Vec<IpCidr>>>,
401) {
402    pin_mut!(listener);
403
404    loop {
405        tokio::select! {
406            Ok(action) = rx.recv() => {
407                match action {
408                    CoreAction::Shutdown => break,
409                }
410            }
411            accept = listener.accept() => {
412                match accept {
413                    Ok((stream, addr)) => {
414                        let app = app.clone();
415                        task::spawn(handle_conn(stream, app, addr, trusted_proxy_v2_ips.clone()));
416                    }
417                    Err(err) => {
418                        error!("Web server exited with {:?}", err);
419                        break;
420                    }
421                }
422            }
423        }
424    }
425
426    info!("Stopped {}", super::TaskName::HttpsServer);
427}
428
429/// This handles an individual connection.
430pub(crate) async fn handle_conn(
431    stream: TcpStream,
432    app: IntoMakeServiceWithConnectInfo<Router, ClientConnInfo>,
433    connection_addr: SocketAddr,
434    trusted_proxy_v2_ips: Option<Arc<Vec<IpCidr>>>,
435) -> Result<(), std::io::Error> {
436    let (stream, client_addr) =
437        process_client_addr(stream, connection_addr, trusted_proxy_v2_ips).await?;
438
439    let client_conn_info = ClientConnInfo {
440        connection_addr,
441        client_addr,
442        client_cert: None,
443    };
444
445    // Hyper has its own `AsyncRead` and `AsyncWrite` traits and doesn't use tokio.
446    // `TokioIo` converts between them.
447    let stream = TokioIo::new(stream);
448
449    process_client_hyper(stream, app, client_conn_info).await
450}
451
452/// This handles an individual connection.
453pub(crate) async fn handle_tls_conn(
454    acceptor: SslAcceptor,
455    stream: TcpStream,
456    app: IntoMakeServiceWithConnectInfo<Router, ClientConnInfo>,
457    connection_addr: SocketAddr,
458    trusted_proxy_v2_ips: Option<Arc<Vec<IpCidr>>>,
459) -> Result<(), std::io::Error> {
460    let (stream, client_addr) =
461        process_client_addr(stream, connection_addr, trusted_proxy_v2_ips).await?;
462
463    let ssl = Ssl::new(acceptor.context()).map_err(|e| {
464        error!("Failed to create TLS context: {:?}", e);
465        std::io::Error::from(ErrorKind::ConnectionAborted)
466    })?;
467
468    let mut tls_stream = SslStream::new(ssl, stream).map_err(|err| {
469        error!(?err, "Failed to create TLS stream");
470        std::io::Error::from(ErrorKind::ConnectionAborted)
471    })?;
472
473    match SslStream::accept(Pin::new(&mut tls_stream)).await {
474        Ok(_) => {
475            // Process the client cert (if any)
476            let client_cert = if let Some(peer_cert) = tls_stream.ssl().peer_certificate() {
477                // TODO: This is where we should be checking the CRL!!!
478
479                // Extract the cert from openssl to x509-cert which is a better
480                // parser to handle the various extensions.
481
482                let cert_der = peer_cert.to_der().map_err(|ossl_err| {
483                    error!(?ossl_err, "unable to process x509 certificate as DER");
484                    std::io::Error::from(ErrorKind::ConnectionAborted)
485                })?;
486
487                let certificate = Certificate::from_der(&cert_der).map_err(|ossl_err| {
488                    error!(?ossl_err, "unable to process DER certificate to x509");
489                    std::io::Error::from(ErrorKind::ConnectionAborted)
490                })?;
491
492                let public_key_s256 = x509_public_key_s256(&certificate).ok_or_else(|| {
493                    error!("subject public key bitstring is not octet aligned");
494                    std::io::Error::from(ErrorKind::ConnectionAborted)
495                })?;
496
497                Some(ClientCertInfo {
498                    public_key_s256,
499                    certificate,
500                })
501            } else {
502                None
503            };
504
505            let client_conn_info = ClientConnInfo {
506                connection_addr,
507                client_addr,
508                client_cert,
509            };
510
511            // Hyper has its own `AsyncRead` and `AsyncWrite` traits and doesn't use tokio.
512            // `TokioIo` converts between them.
513            let stream = TokioIo::new(tls_stream);
514
515            process_client_hyper(stream, app, client_conn_info).await
516        }
517        Err(error) => {
518            trace!("Failed to handle connection: {:?}", error);
519            Ok(())
520        }
521    }
522}
523
524async fn process_client_addr(
525    stream: TcpStream,
526    connection_addr: SocketAddr,
527    trusted_proxy_v2_ips: Option<Arc<Vec<IpCidr>>>,
528) -> Result<(TcpStream, SocketAddr), std::io::Error> {
529    let enable_proxy_v2_hdr = trusted_proxy_v2_ips
530        .map(|trusted| {
531            trusted
532                .iter()
533                .any(|ip_cidr| ip_cidr.contains(&connection_addr.ip()))
534        })
535        .unwrap_or_default();
536
537    let (stream, client_addr) = if enable_proxy_v2_hdr {
538        match ProxyHdrV2::parse_from_read(stream).await {
539            Ok((stream, hdr)) => {
540                let remote_socket_addr = match hdr.to_remote_addr() {
541                    RemoteAddress::Local => {
542                        debug!("PROXY protocol liveness check - will not contain client data");
543                        return Err(std::io::Error::from(ErrorKind::ConnectionAborted));
544                    }
545                    RemoteAddress::TcpV4 { src, dst: _ } => SocketAddr::from(src),
546                    RemoteAddress::TcpV6 { src, dst: _ } => SocketAddr::from(src),
547                    remote_addr => {
548                        error!(?remote_addr, "remote address in proxy header is invalid");
549                        return Err(std::io::Error::from(ErrorKind::ConnectionAborted));
550                    }
551                };
552
553                (stream, remote_socket_addr)
554            }
555            Err(err) => {
556                error!(?connection_addr, ?err, "Unable to process proxy v2 header");
557                return Err(std::io::Error::from(ErrorKind::ConnectionAborted));
558            }
559        }
560    } else {
561        (stream, connection_addr)
562    };
563
564    Ok((stream, client_addr))
565}
566
567async fn process_client_hyper<T>(
568    stream: TokioIo<T>,
569    mut app: IntoMakeServiceWithConnectInfo<Router, ClientConnInfo>,
570    client_conn_info: ClientConnInfo,
571) -> Result<(), std::io::Error>
572where
573    T: AsyncRead + AsyncWrite + std::marker::Unpin + std::marker::Send + 'static,
574{
575    debug!(?client_conn_info);
576
577    let svc = tower::MakeService::<ClientConnInfo, hyper::Request<Body>>::make_service(
578        &mut app,
579        client_conn_info,
580    );
581
582    let svc = svc.await.map_err(|e| {
583        error!("Failed to build HTTP response: {:?}", e);
584        std::io::Error::from(ErrorKind::Other)
585    })?;
586
587    // Hyper also has its own `Service` trait and doesn't use tower. We can use
588    // `hyper::service::service_fn` to create a hyper `Service` that calls our app through
589    // `tower::Service::call`.
590    let hyper_service = hyper::service::service_fn(move |request: Request<Incoming>| {
591        // We have to clone `tower_service` because hyper's `Service` uses `&self` whereas
592        // tower's `Service` requires `&mut self`.
593        //
594        // We don't need to call `poll_ready` since `Router` is always ready.
595        svc.clone().call(request)
596    });
597
598    hyper_util::server::conn::auto::Builder::new(TokioExecutor::new())
599        .serve_connection_with_upgrades(stream, hyper_service)
600        .await
601        .map_err(|e| {
602            debug!("Failed to complete connection: {:?}", e);
603            std::io::Error::from(ErrorKind::ConnectionAborted)
604        })
605}