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
// Copyright lowRISC contributors (OpenTitan project).
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0

use anyhow::Result;
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use serde::{Deserialize, Serialize};
use serde_annotate::Annotate;
use std::convert::TryFrom;
use std::io::{Read, Write};

use super::misc::{TlvHeader, TlvTag};
use crate::chip::boot_svc::BootSvcKind;
use crate::with_unknown;

with_unknown! {
    pub enum RescueType: u32 [default = Self::None] {
        None = 0,
        Xmodem = u32::from_le_bytes(*b"XMDM"),
    }

    pub enum CommandTag: u32 [default = Self::Unknown] {
        Unknown = 0,
        Empty = BootSvcKind::EmptyRequest.0,
        MinBl0SecVerRequest = BootSvcKind::MinBl0SecVerRequest.0,
        NextBl0SlotRequest = BootSvcKind::NextBl0SlotRequest.0,
        OwnershipUnlockRequest = BootSvcKind::OwnershipUnlockRequest.0,
        OwnershipActivateRequest =   BootSvcKind::OwnershipActivateRequest.0,

        // The rescue protocol-level commands are represented in big-endian order.
        Rescue = u32::from_be_bytes(*b"RESQ"),
        Reboot = u32::from_be_bytes(*b"REBO"),
        GetBootLog = u32::from_be_bytes(*b"BLOG"),
        BootSvcReq = u32::from_be_bytes(*b"BREQ"),
        BootSvcRsp = u32::from_be_bytes(*b"BRSP"),
        OwnerBlock = u32::from_be_bytes(*b"OWNR"),
    }
}

/// Describes the configuration of the rescue feature of the ROM_EXT.
#[derive(Debug, Serialize, Deserialize, Annotate)]
pub struct OwnerRescueConfig {
    /// Header identifying this struct.
    #[serde(default)]
    pub header: TlvHeader,
    /// The type of rescue protocol to use (ie: Xmodem).
    pub rescue_type: RescueType,
    /// The start of the rescue flash region (in pages).
    pub start: u16,
    /// The size of the rescue flash region (in pages).
    pub size: u16,
    /// An allow-list of commands permitted to be executed by the rescue module.
    pub command_allow: Vec<CommandTag>,
}

impl Default for OwnerRescueConfig {
    fn default() -> Self {
        Self {
            header: TlvHeader::new(TlvTag::Rescue, 0),
            rescue_type: RescueType::default(),
            start: 0u16,
            size: 0u16,
            command_allow: Vec::new(),
        }
    }
}

impl OwnerRescueConfig {
    const BASE_SIZE: usize = 16;
    pub fn read(src: &mut impl Read, header: TlvHeader) -> Result<Self> {
        let rescue_type = RescueType(src.read_u32::<LittleEndian>()?);
        let start = src.read_u16::<LittleEndian>()?;
        let size = src.read_u16::<LittleEndian>()?;
        let allow_len = (header.length - Self::BASE_SIZE) / std::mem::size_of::<u32>();
        let mut command_allow = Vec::new();
        for _ in 0..allow_len {
            command_allow.push(CommandTag(src.read_u32::<LittleEndian>()?));
        }
        Ok(Self {
            header,
            rescue_type,
            start,
            size,
            command_allow,
        })
    }
    pub fn write(&self, dest: &mut impl Write) -> Result<()> {
        let header = TlvHeader::new(
            TlvTag::Rescue,
            Self::BASE_SIZE + self.command_allow.len() * std::mem::size_of::<u32>(),
        );
        header.write(dest)?;
        dest.write_u32::<LittleEndian>(u32::from(self.rescue_type))?;
        dest.write_u16::<LittleEndian>(self.start)?;
        dest.write_u16::<LittleEndian>(self.size)?;
        for allow in self.command_allow.iter() {
            dest.write_u32::<LittleEndian>(u32::from(*allow))?;
        }
        Ok(())
    }

    pub fn all() -> Self {
        OwnerRescueConfig {
            rescue_type: RescueType::Xmodem,
            // Start after the ROM_EXT.
            start: 32,
            // End at the end of the partition.
            size: 224,
            command_allow: vec![
                CommandTag::Empty,
                CommandTag::MinBl0SecVerRequest,
                CommandTag::NextBl0SlotRequest,
                CommandTag::OwnershipUnlockRequest,
                CommandTag::OwnershipActivateRequest,
                CommandTag::Rescue,
                CommandTag::GetBootLog,
                CommandTag::BootSvcReq,
                CommandTag::BootSvcRsp,
                CommandTag::OwnerBlock,
            ],
            ..Default::default()
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::util::hexdump::{hexdump_parse, hexdump_string};

    const OWNER_RESCUE_CONFIG_BIN: &str = "\
00000000: 52 45 53 51 38 00 00 00 58 4d 44 4d 20 00 64 00  RESQ8...XMDM .d.\n\
00000010: 45 4d 50 54 4d 53 45 43 4e 45 58 54 55 4e 4c 4b  EMPTMSECNEXTUNLK\n\
00000020: 41 43 54 56 51 53 45 52 47 4f 4c 42 51 45 52 42  ACTVQSERGOLBQERB\n\
00000030: 50 53 52 42 52 4e 57 4f                          PSRBRNWO\n\
";
    const OWNER_RESCUE_CONFIG_JSON: &str = r#"{
  header: {
    identifier: "Rescue",
    length: 56
  },
  rescue_type: "Xmodem",
  start: 32,
  size: 100,
  command_allow: [
    "Empty",
    "MinBl0SecVerRequest",
    "NextBl0SlotRequest",
    "OwnershipUnlockRequest",
    "OwnershipActivateRequest",
    "Rescue",
    "GetBootLog",
    "BootSvcReq",
    "BootSvcRsp",
    "OwnerBlock"
  ]
}"#;

    #[test]
    fn test_owner_rescue_config_write() -> Result<()> {
        let orc = OwnerRescueConfig {
            header: TlvHeader::default(),
            rescue_type: RescueType::Xmodem,
            start: 32,
            size: 100,
            command_allow: vec![
                CommandTag::Empty,
                CommandTag::MinBl0SecVerRequest,
                CommandTag::NextBl0SlotRequest,
                CommandTag::OwnershipUnlockRequest,
                CommandTag::OwnershipActivateRequest,
                CommandTag::Rescue,
                CommandTag::GetBootLog,
                CommandTag::BootSvcReq,
                CommandTag::BootSvcRsp,
                CommandTag::OwnerBlock,
            ],
        };

        let mut bin = Vec::new();
        orc.write(&mut bin)?;
        eprintln!("{}", hexdump_string(&bin)?);
        assert_eq!(hexdump_string(&bin)?, OWNER_RESCUE_CONFIG_BIN);
        Ok(())
    }

    #[test]
    fn test_owner_rescue_config_read() -> Result<()> {
        let buf = hexdump_parse(OWNER_RESCUE_CONFIG_BIN)?;
        let mut cur = std::io::Cursor::new(&buf);
        let header = TlvHeader::read(&mut cur)?;
        let orc = OwnerRescueConfig::read(&mut cur, header)?;
        let doc = serde_annotate::serialize(&orc)?.to_json5().to_string();
        eprintln!("{}", doc);
        assert_eq!(doc, OWNER_RESCUE_CONFIG_JSON);
        Ok(())
    }
}