1 /*
2  * Copyright (C) 2022 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <getopt.h>
18 #include <unistd.h>
19 
20 #include <android-base/file.h>
21 #include <android-base/logging.h>
22 #include <android-base/properties.h>
23 #include <android-base/strings.h>
24 #include <android-base/unique_fd.h>
25 #include <bootloader_message/bootloader_message.h>
26 
27 #include <functional>
28 #include <iostream>
29 
AddItem(std::string * s,const char * item)30 void AddItem(std::string* s, const char* item) {
31   if (!s->empty()) *s += ",";
32   *s += item;
33 }
34 
CheckAndUnset(uint32_t & mode,uint32_t mask)35 bool CheckAndUnset(uint32_t& mode, uint32_t mask) {
36   bool is_set = mode & mask;
37   mode &= ~mask;
38   return is_set;
39 }
40 
UpdateProp(const char * prop_name,const misc_memtag_message & m)41 bool UpdateProp(const char* prop_name, const misc_memtag_message& m) {
42   uint32_t mode = m.memtag_mode;
43   std::string prop_str;
44   if (CheckAndUnset(mode, MISC_MEMTAG_MODE_MEMTAG)) AddItem(&prop_str, "memtag");
45   if (CheckAndUnset(mode, MISC_MEMTAG_MODE_MEMTAG_ONCE)) AddItem(&prop_str, "memtag-once");
46   if (CheckAndUnset(mode, MISC_MEMTAG_MODE_MEMTAG_KERNEL)) AddItem(&prop_str, "memtag-kernel");
47   if (CheckAndUnset(mode, MISC_MEMTAG_MODE_MEMTAG_KERNEL_ONCE))
48     AddItem(&prop_str, "memtag-kernel-once");
49   if (CheckAndUnset(mode, MISC_MEMTAG_MODE_MEMTAG_OFF)) AddItem(&prop_str, "memtag-off");
50   if (CheckAndUnset(mode, MISC_MEMTAG_MODE_FORCED)) AddItem(&prop_str, "forced");
51   if (prop_str.empty()) prop_str = "none";
52   if (android::base::GetProperty(prop_name, "") != prop_str)
53     android::base::SetProperty(prop_name, prop_str);
54   if (mode) {
55     LOG(ERROR) << "MTE mode in misc message contained unknown bits: " << mode
56                << ". Ignoring and setting " << prop_name << " to " << prop_str;
57   }
58   return mode == 0;
59 }
60 
PrintUsage(const char * progname)61 void PrintUsage(const char* progname) {
62   std::cerr
63       << "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n"
64          "!!! YOU PROBABLY DO NOT NEED TO USE THIS                    !!!\n"
65          "!!! USE THE `arm64.memtag.bootctl` SYSTEM PROPERTY INSTEAD. !!!\n"
66          "!!! This program is an implementation detail that is used   !!!\n"
67          "!!! by the system to apply MTE settings.                    !!!\n"
68          "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n"
69          "\n"
70       << "USAGE: " << progname
71       << "\n"
72          "      [-s PROPERTY_NAME]\n"
73          "      [-f PROPERTY_NAME]\n"
74          "      [none,][memtag,][memtag-once,][memtag-kernel,][memtag-kernel-once,][memtag-off,]\n"
75          "      [default|force_on|force_off]\n"
76          "      [-t PATH_TO_FAKE_MISC_PARTITION]\n"
77 
78          "OPTIONS:\n"
79          "  -s PROPERTY_NAME\n"
80          "      Sets the system property 'PROPERTY_NAME' to the new MTE mode (if provided), or to\n"
81          "      the current value from the /misc partition.\n"
82          "  -f PROPERTY_NAME\n"
83          "      Used in combination with -s without a new MTE mode and sets the system property\n"
84          "      'PROPERTY_NAME' to 1 after reading the current value from the /misc partition\n"
85          "  [none,][memtag,][memtag-once,][memtag-kernel,][memtag-kernel-once,][memtag-off,]\n"
86          "      A set of MTE options to be applied, if provided. Multiple options may be\n"
87          "      specified as a ','-delimited list, e.g. 'memtag,memtag-kernel'.\n"
88          "      The options are described below:\n"
89          "        - none: default settings for MTE for the product will be applied on next\n"
90          "                reboot.\n"
91          "        - memtag: MTE is persistently enabled in userspace upon the next reboot.\n"
92          "        - memtag-once: MTE is enabled in userspace, only for the next reboot.\n"
93          "        - memtag-kernel: MTE is persistently enabled in the kernel upon the next \n"
94          "                         reboot.\n"
95          "        - memtag-kernel-once: MTE is enabled in the kernel, only for the next reboot.\n"
96          "        - memtag-off: MTE is persistently disabled in both userspace and kernel upon \n"
97          "                      the next reboot.\n"
98          "        - forced: the current state is the result of force_on or force_off in the next\n"
99          "                  argument. When the next argument is set back to \"default\", the\n"
100          "                  state will be cleared.\n"
101          "  [default|force_on|force_off]\n"
102          "      An alternative method of configuring the MTE options to be applied, if provided.\n"
103          "      This control is generally to be used by device_config only, and it overwrites\n"
104          "      the previously described settings that are expected to be utilized by the user.\n"
105          "      The options are described below:\n"
106          "        - default: This flag is not overwriting the MTE mode, and so the setting\n"
107          "                   should be inherited from the userspace controls (if present), or the\n"
108          "                   default value from the bootloader's ROM.\n"
109          "        - force_on: MTE is persistently enabled in userspace, overwriting the userspace\n"
110          "                    setting.\n"
111          "        - force_off: MTE is persistently disabled in userspace and the kernel, \n"
112          "                     overwriting the userspace setting.\n";
113 }
114 
StringToMode(const char * value)115 int StringToMode(const char* value) {
116   int memtag_mode = 0;
117   for (const auto& field : android::base::Split(value, ",")) {
118     if (field == "memtag") {
119       memtag_mode |= MISC_MEMTAG_MODE_MEMTAG;
120     } else if (field == "memtag-once") {
121       memtag_mode |= MISC_MEMTAG_MODE_MEMTAG_ONCE;
122     } else if (field == "memtag-kernel") {
123       memtag_mode |= MISC_MEMTAG_MODE_MEMTAG_KERNEL;
124     } else if (field == "memtag-kernel-once") {
125       memtag_mode |= MISC_MEMTAG_MODE_MEMTAG_KERNEL_ONCE;
126     } else if (field == "memtag-off") {
127       memtag_mode |= MISC_MEMTAG_MODE_MEMTAG_OFF;
128     } else if (field == "forced") {
129       memtag_mode |= MISC_MEMTAG_MODE_FORCED;
130     } else if (field != "none") {
131       LOG(ERROR) << "Unknown value for mode: " << field;
132       return -1;
133     }
134   }
135   return memtag_mode;
136 }
137 
138 // Handles the override flag and applies it to the memtag message.
139 // The logic is as follows:
140 // If the override changes the configuration (i.e., if MTE was not enabled
141 // through MODE_MEMTAG and the override is force_on, or MTE was not
142 // disabled through MEMTAG_OFF and the override is force_off), the MTE
143 // state is considered FORCED. In that case, if the override gets reset
144 // to "default" (i.e. no override), the default state of memtag config
145 // is restored. The theory for this is that disabling the override should
146 // only keep the non-default state if it has been active throughout the
147 // override, not restore it if it had been dormant for the duration of the
148 // override.
149 //
150 // State machine diagrams of the MTE state and the effect of override below:
151 //
152 //                      default,force_off
153 //                           ┌───┐
154 //                           │   │
155 //                        ┌──┴───▼───┐
156 //                        │memtag-off│
157 //                        └─────┬────┘
158 //                              │
159 //                     force_on │   ┌────┐
160 //                              │   │    │ force_on
161 //             force_off┌───────▼───┴─┐  │
162 //             ┌────────┤memtag,forced│◄─┘
163 //             │        └▲─────────┬──┘
164 // force_off   │         │         │
165 //   ┌────┐    │ force_on│         │ default
166 //   │    │    │         │         │
167 //   │  ┌─┴────▼─────────┴┐       ┌▼──────┐
168 //   └─►│memtag-off,forced├───────►none   │
169 //      └─────────────────┘default└───────┘
170 //
171 //
172 //
173 //                      default,force_on
174 //                           ┌───┐
175 //                           │   │
176 //                        ┌──┴───▼───┐
177 //                        │memtag    │
178 //                        └─────┬────┘
179 //                              │
180 //                     force_off│       ┌────┐
181 //                              │       │    │ force_off
182 //             force_on ┌───────┴───────┴─┐  │
183 //             ┌────────┤memtag-off,forced◄──┘
184 //             │        └▲─────────┬──────┘
185 // force_on    │         │         │
186 //   ┌────┐    │force_off│         │ default
187 //   │    │    │         │         │
188 //   │  ┌─┴────▼─────────┴┐       ┌▼──────┐
189 //   └─►│memtag,forced    ├───────►none   │
190 //      └─────────────────┘default└───────┘
191 //
192 //
193 //
194 //                           default
195 //                            ┌───┐
196 //                            │   │
197 //              force_off  ┌──┴───▼───┐
198 //           ┌─────────────┤none      │
199 //           │             └─────┬────┘
200 //           │                   │
201 //           │          force_on │   ┌────┐
202 //           │                   │   │    │ force_on
203 //           │  force_off┌───────▼───┴─┐  │
204 //           │  ┌────────┤memtag,forced│◄─┘
205 //           │  │        └▲─────────┬──┘
206 //  force_off│  │         │         │
207 //    ┌────┐ │  │ force_on│         │ default
208 //    │    │ │  │         │         │
209 //    │  ┌─┴─▼──▼─────────┴┐       ┌▼──────┐
210 //    └─►│memtag-off,forced├───────►none   │
211 //       └─────────────────┘default└───────┘
HandleOverride(const std::string & override_value,misc_memtag_message * m)212 bool HandleOverride(const std::string& override_value, misc_memtag_message* m) {
213   if (override_value == "force_off") {
214     // If the force_off override is active, only allow MEMTAG_MODE_MEMTAG_ONCE.
215     if ((m->memtag_mode & MISC_MEMTAG_MODE_MEMTAG_OFF) == 0) {
216       m->memtag_mode |= MISC_MEMTAG_MODE_FORCED;
217     }
218     m->memtag_mode |= MISC_MEMTAG_MODE_MEMTAG_OFF;
219     m->memtag_mode &= ~MISC_MEMTAG_MODE_MEMTAG;
220   } else if (override_value == "force_on") {
221     if ((m->memtag_mode & MISC_MEMTAG_MODE_MEMTAG) == 0) {
222       m->memtag_mode |= MISC_MEMTAG_MODE_FORCED;
223     }
224     m->memtag_mode |= MISC_MEMTAG_MODE_MEMTAG;
225     m->memtag_mode &= ~MISC_MEMTAG_MODE_MEMTAG_OFF;
226   } else if (override_value.empty() || override_value == "default") {
227     // The mode changed from forced_on or forced_off to default, which means we
228     // restore the normal state.
229     if (m->memtag_mode & MISC_MEMTAG_MODE_FORCED) {
230       m->memtag_mode &= ~MISC_MEMTAG_MODE_MEMTAG;
231       m->memtag_mode &= ~MISC_MEMTAG_MODE_MEMTAG_OFF;
232       m->memtag_mode &= ~MISC_MEMTAG_MODE_FORCED;
233     }
234   } else {
235     return false;
236   }
237   return true;
238 }
239 
DoSetProp(const std::function<bool (misc_memtag_message *,std::string *)> & read_memtag_message,const char * set_prop)240 int DoSetProp(const std::function<bool(misc_memtag_message*, std::string*)>& read_memtag_message,
241               const char* set_prop) {
242   // -s <property> is given on its own. This means we want to read the state
243   // of the misc partition into the property.
244   std::string err;
245   misc_memtag_message m = {};
246   if (!read_memtag_message(&m, &err)) {
247     LOG(ERROR) << "Failed to read memtag message: " << err;
248     return 1;
249   }
250   if (m.magic != MISC_MEMTAG_MAGIC_HEADER || m.version != MISC_MEMTAG_MESSAGE_VERSION) {
251     // This should not fail by construction.
252     CHECK(UpdateProp(set_prop, {}));
253     // This is an expected case, as the partition gets initialized to all zero.
254     return 0;
255   }
256   // Unlike above, setting the system property here can fail if the misc partition
257   // was corrupted by another program (e.g. the bootloader).
258   return UpdateProp(set_prop, m) ? 0 : 1;
259 }
260 
main(int argc,char ** argv)261 int main(int argc, char** argv) {
262   const char* set_prop = nullptr;
263   const char* flag_prop = nullptr;
264   int opt;
265   std::function<bool(misc_memtag_message*, std::string*)> read_memtag_message =
266       ReadMiscMemtagMessage;
267   std::function<bool(const misc_memtag_message&, std::string*)> write_memtag_message =
268       WriteMiscMemtagMessage;
269 
270   android::base::unique_fd fake_partition_fd;
271   while ((opt = getopt(argc, argv, "s:t:f:")) != -1) {
272     switch (opt) {
273       case 's':
274         // Set property in argument to state of misc partition. If given by
275         // itself, sets the property to the current state. We do this on device
276         // boot,
277         //
278         // Otherwise, applies new state and then sets property to newly applied
279         // state.
280         set_prop = optarg;
281         break;
282       case 'f':
283         flag_prop = optarg;
284         break;
285       case 't': {
286         // Use different fake misc partition for testing.
287         const char* filename = optarg;
288         fake_partition_fd.reset(open(filename, O_RDWR | O_CLOEXEC));
289         int raw_fd = fake_partition_fd.get();
290         CHECK_NE(raw_fd, -1);
291         CHECK_NE(ftruncate(raw_fd, sizeof(misc_memtag_message)), -1);
292         read_memtag_message = [raw_fd](misc_memtag_message* m, std::string*) {
293           CHECK(android::base::ReadFully(raw_fd, m, sizeof(*m)));
294           return true;
295         };
296         write_memtag_message = [raw_fd](const misc_memtag_message& m, std::string*) {
297           CHECK(android::base::WriteFully(raw_fd, &m, sizeof(m)));
298           return true;
299         };
300         break;
301       }
302       default:
303         PrintUsage(argv[0]);
304         return 1;
305     }
306   }
307 
308   const char* value = optind < argc ? argv[optind++] : nullptr;
309   const char* override_value = optind < argc ? argv[optind++] : nullptr;
310 
311   if ((optind != argc) ||       // Unknown argument.
312       (value && flag_prop) ||   // -f is only valid when no value given
313       (!value && !set_prop)) {  // value must be given if -s is not
314     PrintUsage(argv[0]);
315     return 1;
316   }
317 
318   if (!value && set_prop) {
319     int ret = DoSetProp(read_memtag_message, set_prop);
320     if (flag_prop) {
321       android::base::SetProperty(flag_prop, "1");
322     }
323     return ret;
324   }
325 
326   CHECK(value);
327 
328   misc_memtag_message m = {.version = MISC_MEMTAG_MESSAGE_VERSION,
329                            .magic = MISC_MEMTAG_MAGIC_HEADER};
330   int memtag_mode = StringToMode(value);
331   bool valid_value = memtag_mode != -1;
332   m.memtag_mode = valid_value ? memtag_mode : 0;
333 
334   bool valid_override = true;
335   if (override_value) valid_override = HandleOverride(override_value, &m);
336 
337   if (!valid_value && !valid_override) {
338     return 1;
339   }
340   std::string err;
341   if (!write_memtag_message(m, &err)) {
342     LOG(ERROR) << "Failed to apply mode: " << value << ", override: " << override_value << err;
343     return 1;
344   } else {
345     const char* parse_error = "";
346     const char* verb = "Applied";
347     if (!valid_value) {
348       parse_error = " (invalid mode)";
349       verb = "Partially applied";
350     } else if (!valid_override) {
351       // else if because we bail out if both are false above.
352       parse_error = " (invalid override)";
353       verb = "Partially applied";
354     }
355     LOG(INFO) << verb << " mode: " << value << ", "
356               << "override: " << (override_value ? override_value : "") << parse_error;
357     // Because all the bits in memtag_mode were set above, this should never fail.
358     if (set_prop) CHECK(UpdateProp(set_prop, m));
359     return !valid_value || !valid_override;
360   }
361 }
362