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
// Licensed under the Apache License, Version 2.0 or the MIT License.
// SPDX-License-Identifier: Apache-2.0 OR MIT
// Copyright Tock Contributors 2024.

//! Signature credential checker for checking process credentials.

use crate::hil;
use crate::process_checker::CheckResult;
use crate::process_checker::{AppCredentialsPolicy, AppCredentialsPolicyClient};
use crate::utilities::cells::MapCell;
use crate::utilities::cells::OptionalCell;
use crate::utilities::leasable_buffer::{SubSlice, SubSliceMut};
use crate::ErrorCode;
use tock_tbf::types::TbfFooterV2Credentials;
use tock_tbf::types::TbfFooterV2CredentialsType;

/// Checker that validates a correct signature credential.
///
/// This checker provides the scaffolding on top of a hasher (`&H`) and a
/// verifier (`&S`) for a given `TbfFooterV2CredentialsType`.
///
/// This assumes the `TbfFooterV2CredentialsType` data format only contains the
/// signature (i.e. the data length of the credential in the TBF footer is the
/// same as `SL`).
pub struct AppCheckerSignature<
    'a,
    S: hil::public_key_crypto::signature::SignatureVerify<'static, HL, SL>,
    H: hil::digest::DigestDataHash<'a, HL>,
    const HL: usize,
    const SL: usize,
> {
    hasher: &'a H,
    verifier: &'a S,
    hash: MapCell<&'static mut [u8; HL]>,
    signature: MapCell<&'static mut [u8; SL]>,
    client: OptionalCell<&'static dyn AppCredentialsPolicyClient<'static>>,
    credential_type: TbfFooterV2CredentialsType,
    credentials: OptionalCell<TbfFooterV2Credentials>,
    binary: OptionalCell<&'static [u8]>,
}

impl<
        'a,
        S: hil::public_key_crypto::signature::SignatureVerify<'static, HL, SL>,
        H: hil::digest::DigestDataHash<'a, HL>,
        const HL: usize,
        const SL: usize,
    > AppCheckerSignature<'a, S, H, HL, SL>
{
    pub fn new(
        hasher: &'a H,
        verifier: &'a S,
        hash_buffer: &'static mut [u8; HL],
        signature_buffer: &'static mut [u8; SL],
        credential_type: TbfFooterV2CredentialsType,
    ) -> AppCheckerSignature<'a, S, H, HL, SL> {
        Self {
            hasher,
            verifier,
            hash: MapCell::new(hash_buffer),
            signature: MapCell::new(signature_buffer),
            client: OptionalCell::empty(),
            credential_type,
            credentials: OptionalCell::empty(),
            binary: OptionalCell::empty(),
        }
    }
}

impl<
        'a,
        S: hil::public_key_crypto::signature::SignatureVerify<'static, HL, SL>,
        H: hil::digest::DigestDataHash<'a, HL>,
        const HL: usize,
        const SL: usize,
    > hil::digest::ClientData<HL> for AppCheckerSignature<'a, S, H, HL, SL>
{
    fn add_mut_data_done(&self, _result: Result<(), ErrorCode>, _data: SubSliceMut<'static, u8>) {}

    fn add_data_done(&self, result: Result<(), ErrorCode>, data: SubSlice<'static, u8>) {
        self.binary.set(data.take());

        // We added the binary data to the hasher, now we can compute the hash.
        match result {
            Err(e) => {
                self.client.map(|c| {
                    let binary = self.binary.take().unwrap();
                    let cred = self.credentials.take().unwrap();
                    c.check_done(Err(e), cred, binary)
                });
            }
            Ok(()) => {
                self.hash.take().map(|h| match self.hasher.run(h) {
                    Err((e, _)) => {
                        self.client.map(|c| {
                            let binary = self.binary.take().unwrap();
                            let cred = self.credentials.take().unwrap();
                            c.check_done(Err(e), cred, binary)
                        });
                    }
                    Ok(()) => {}
                });
            }
        }
    }
}

impl<
        'a,
        S: hil::public_key_crypto::signature::SignatureVerify<'static, HL, SL>,
        H: hil::digest::DigestDataHash<'a, HL>,
        const HL: usize,
        const SL: usize,
    > hil::digest::ClientHash<HL> for AppCheckerSignature<'a, S, H, HL, SL>
{
    fn hash_done(&self, result: Result<(), ErrorCode>, digest: &'static mut [u8; HL]) {
        match result {
            Err(e) => {
                self.hash.replace(digest);
                self.client.map(|c| {
                    let binary = self.binary.take().unwrap();
                    let cred = self.credentials.take().unwrap();
                    c.check_done(Err(e), cred, binary)
                });
            }
            Ok(()) => match self.signature.take() {
                Some(sig) => match self.verifier.verify(digest, sig) {
                    Err((e, d, s)) => {
                        self.hash.replace(d);
                        self.signature.replace(s);
                        self.client.map(|c| {
                            let binary = self.binary.take().unwrap();
                            let cred = self.credentials.take().unwrap();
                            c.check_done(Err(e), cred, binary)
                        });
                    }
                    Ok(()) => {}
                },
                None => {
                    self.hash.replace(digest);
                    self.client.map(|c| {
                        let binary = self.binary.take().unwrap();
                        let cred = self.credentials.take().unwrap();
                        c.check_done(Err(ErrorCode::FAIL), cred, binary)
                    });
                }
            },
        }
    }
}

impl<
        'a,
        S: hil::public_key_crypto::signature::SignatureVerify<'static, HL, SL>,
        H: hil::digest::DigestDataHash<'a, HL>,
        const HL: usize,
        const SL: usize,
    > hil::digest::ClientVerify<HL> for AppCheckerSignature<'a, S, H, HL, SL>
{
    fn verification_done(&self, _result: Result<bool, ErrorCode>, _compare: &'static mut [u8; HL]) {
        // Unused for this checker.
        // Needed to make the sha256 client work.
    }
}

impl<
        'a,
        S: hil::public_key_crypto::signature::SignatureVerify<'static, HL, SL>,
        H: hil::digest::DigestDataHash<'a, HL>,
        const HL: usize,
        const SL: usize,
    > hil::public_key_crypto::signature::ClientVerify<HL, SL>
    for AppCheckerSignature<'a, S, H, HL, SL>
{
    fn verification_done(
        &self,
        result: Result<bool, ErrorCode>,
        hash: &'static mut [u8; HL],
        signature: &'static mut [u8; SL],
    ) {
        self.hash.replace(hash);
        self.signature.replace(signature);

        self.client.map(|c| {
            let binary = self.binary.take().unwrap();
            let cred = self.credentials.take().unwrap();
            let check_result = if result.unwrap_or(false) {
                Ok(CheckResult::Accept)
            } else {
                Ok(CheckResult::Pass)
            };

            c.check_done(check_result, cred, binary)
        });
    }
}

impl<
        'a,
        S: hil::public_key_crypto::signature::SignatureVerify<'static, HL, SL>,
        H: hil::digest::DigestDataHash<'a, HL>,
        const HL: usize,
        const SL: usize,
    > AppCredentialsPolicy<'static> for AppCheckerSignature<'a, S, H, HL, SL>
{
    fn require_credentials(&self) -> bool {
        true
    }

    fn check_credentials(
        &self,
        credentials: TbfFooterV2Credentials,
        binary: &'static [u8],
    ) -> Result<(), (ErrorCode, TbfFooterV2Credentials, &'static [u8])> {
        self.credentials.set(credentials);

        if credentials.format() == self.credential_type {
            // Save the signature we are trying to compare with.
            self.signature.map(|b| {
                b.as_mut_slice()[..SL].copy_from_slice(&credentials.data()[..SL]);
            });

            // Add the process binary to compute the hash.
            self.hasher.clear_data();
            match self.hasher.add_data(SubSlice::new(binary)) {
                Ok(()) => Ok(()),
                Err((e, b)) => Err((e, credentials, b.take())),
            }
        } else {
            Err((ErrorCode::NOSUPPORT, credentials, binary))
        }
    }

    fn set_client(&self, client: &'static dyn AppCredentialsPolicyClient<'static>) {
        self.client.replace(client);
    }
}