blob: cb7f38d718ef75bb57b40c0d4b883c8eef0452b8 [file] [log] [blame]
Paul Crowley9da969e2022-09-16 23:42:24 +00001// Copyright (C) 2022 The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! FIPS compliant random number conditioner. Reads from /dev/hw_random
16//! and applies the NIST SP 800-90A CTR DRBG strategy to provide
17//! pseudorandom bytes to clients which connect to a socket provided
18//! by init.
19
20mod conditioner;
21mod cutils_socket;
22mod drbg;
23
24use std::{
25 convert::Infallible,
Paul Crowley021cf552022-09-28 18:37:43 +000026 fs::remove_file,
Paul Crowley9da969e2022-09-16 23:42:24 +000027 io::ErrorKind,
Paul Crowley021cf552022-09-28 18:37:43 +000028 os::unix::net::UnixListener,
Paul Crowley9da969e2022-09-16 23:42:24 +000029 path::{Path, PathBuf},
30};
31
Paul Crowley021cf552022-09-28 18:37:43 +000032use anyhow::{ensure, Context, Result};
Paul Crowley9da969e2022-09-16 23:42:24 +000033use clap::Parser;
Jeff Vander Stoep940820c2024-01-31 10:55:29 +010034use log::{error, info, LevelFilter};
Paul Crowley021cf552022-09-28 18:37:43 +000035use nix::sys::signal;
Paul Crowley9da969e2022-09-16 23:42:24 +000036use tokio::{io::AsyncWriteExt, net::UnixListener as TokioUnixListener};
37
Paul Crowley021cf552022-09-28 18:37:43 +000038use crate::conditioner::ConditionerBuilder;
Paul Crowley9da969e2022-09-16 23:42:24 +000039
Andrew Walbran13335de2022-12-01 15:05:39 +000040#[derive(Debug, Parser)]
Paul Crowley9da969e2022-09-16 23:42:24 +000041struct Cli {
42 #[clap(long, default_value = "/dev/hw_random")]
43 source: PathBuf,
44 #[clap(long)]
45 socket: Option<PathBuf>,
46}
47
Paul Crowley021cf552022-09-28 18:37:43 +000048fn configure_logging() -> Result<()> {
49 ensure!(
50 logger::init(
Jeff Vander Stoep940820c2024-01-31 10:55:29 +010051 logger::Config::default()
52 .with_tag_on_device("prng_seeder")
53 .with_max_level(LevelFilter::Info)
Paul Crowley021cf552022-09-28 18:37:43 +000054 ),
55 "log configuration failed"
56 );
57 Ok(())
Paul Crowley9da969e2022-09-16 23:42:24 +000058}
59
60fn get_socket(path: &Path) -> Result<UnixListener> {
61 if let Err(e) = remove_file(path) {
62 if e.kind() != ErrorKind::NotFound {
Paul Crowley021cf552022-09-28 18:37:43 +000063 return Err(e).context(format!("Removing old socket: {}", path.display()));
Paul Crowley9da969e2022-09-16 23:42:24 +000064 }
65 } else {
Paul Crowley021cf552022-09-28 18:37:43 +000066 info!("Deleted old {}", path.display());
Paul Crowley9da969e2022-09-16 23:42:24 +000067 }
Paul Crowley021cf552022-09-28 18:37:43 +000068 UnixListener::bind(path)
69 .with_context(|| format!("In get_socket: binding socket to {}", path.display()))
Paul Crowley9da969e2022-09-16 23:42:24 +000070}
71
Paul Crowley021cf552022-09-28 18:37:43 +000072fn setup() -> Result<(ConditionerBuilder, UnixListener)> {
73 configure_logging()?;
74 let cli = Cli::try_parse()?;
Andrew Walbranc7687332023-07-21 17:26:09 +010075 // SAFETY: Nothing else sets the signal handler, so either it was set here or it is the default.
Paul Crowley021cf552022-09-28 18:37:43 +000076 unsafe { signal::signal(signal::Signal::SIGPIPE, signal::SigHandler::SigIgn) }
77 .context("In setup, setting SIGPIPE to SIG_IGN")?;
78
79 let listener = match cli.socket {
80 Some(path) => get_socket(path.as_path())?,
81 None => cutils_socket::android_get_control_socket("prng_seeder")
82 .context("In setup, calling android_get_control_socket")?,
83 };
84 let hwrng = std::fs::File::open(&cli.source)
85 .with_context(|| format!("Unable to open hwrng {}", cli.source.display()))?;
86 let cb = ConditionerBuilder::new(hwrng)?;
87 Ok((cb, listener))
88}
89
90async fn listen_loop(cb: ConditionerBuilder, listener: UnixListener) -> Result<Infallible> {
91 let mut conditioner = cb.build();
92 listener.set_nonblocking(true).context("In listen_loop, on set_nonblocking")?;
93 let listener = TokioUnixListener::from_std(listener).context("In listen_loop, on from_std")?;
94 info!("Starting listen loop");
Paul Crowley9da969e2022-09-16 23:42:24 +000095 loop {
96 match listener.accept().await {
97 Ok((mut stream, _)) => {
98 let new_bytes = conditioner.request()?;
99 tokio::spawn(async move {
100 if let Err(e) = stream.write_all(&new_bytes).await {
101 error!("Request failed: {}", e);
102 }
103 });
104 conditioner.reseed_if_necessary().await?;
105 }
106 Err(e) if e.kind() == ErrorKind::Interrupted => {}
Paul Crowley021cf552022-09-28 18:37:43 +0000107 Err(e) => return Err(e).context("accept on socket failed"),
Paul Crowley9da969e2022-09-16 23:42:24 +0000108 }
109 }
110}
111
Paul Crowley021cf552022-09-28 18:37:43 +0000112fn run() -> Result<Infallible> {
113 let (cb, listener) = match setup() {
114 Ok(t) => t,
115 Err(e) => {
116 // If setup fails, just hang forever. That way init doesn't respawn us.
117 error!("Hanging forever because setup failed: {:?}", e);
118 // Logs are sometimes mysteriously not being logged, so print too
119 println!("prng_seeder: Hanging forever because setup failed: {:?}", e);
120 loop {
121 std::thread::park();
122 error!("std::thread::park() finished unexpectedly, re-parking thread");
123 }
124 }
Paul Crowley9da969e2022-09-16 23:42:24 +0000125 };
Paul Crowley9da969e2022-09-16 23:42:24 +0000126
127 tokio::runtime::Builder::new_current_thread()
128 .enable_all()
Paul Crowley021cf552022-09-28 18:37:43 +0000129 .build()
130 .context("In run, building reactor")?
131 .block_on(async { listen_loop(cb, listener).await })
Paul Crowley9da969e2022-09-16 23:42:24 +0000132}
133
134fn main() {
Paul Crowley021cf552022-09-28 18:37:43 +0000135 let e = run();
136 error!("Launch terminated: {:?}", e);
137 // Logs are sometimes mysteriously not being logged, so print too
138 println!("prng_seeder: launch terminated: {:?}", e);
Paul Crowley9da969e2022-09-16 23:42:24 +0000139 std::process::exit(-1);
140}
Andrew Walbran13335de2022-12-01 15:05:39 +0000141
142#[cfg(test)]
143mod tests {
144 use super::*;
145 use clap::CommandFactory;
146
147 #[test]
148 fn verify_cli() {
149 Cli::command().debug_assert();
150 }
151}