1 /*
2  * Copyright (C) 2016 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 <errno.h>
18 #include <fcntl.h>
19 #include <scsi/sg.h>
20 #include <stdint.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <sys/ioctl.h>
25 #include <sys/socket.h>
26 #include <sys/un.h>
27 #include <unistd.h>
28 
29 #include <linux/major.h>
30 #include <linux/mmc/ioctl.h>
31 
32 #include "ipc.h"
33 #include "log.h"
34 #include "rpmb.h"
35 #include "storage.h"
36 
37 #define MMC_READ_MULTIPLE_BLOCK 18
38 #define MMC_WRITE_MULTIPLE_BLOCK 25
39 #define MMC_RELIABLE_WRITE_FLAG (1 << 31)
40 
41 #define MMC_RSP_PRESENT (1 << 0)
42 #define MMC_RSP_CRC (1 << 2)
43 #define MMC_RSP_OPCODE (1 << 4)
44 #define MMC_CMD_ADTC (1 << 5)
45 #define MMC_RSP_SPI_S1 (1 << 7)
46 #define MMC_RSP_R1 (MMC_RSP_PRESENT | MMC_RSP_CRC | MMC_RSP_OPCODE)
47 #define MMC_RSP_SPI_R1 (MMC_RSP_SPI_S1)
48 
49 #define MMC_WRITE_FLAG_R 0
50 #define MMC_WRITE_FLAG_W 1
51 #define MMC_WRITE_FLAG_RELW (MMC_WRITE_FLAG_W | MMC_RELIABLE_WRITE_FLAG)
52 
53 #define MMC_BLOCK_SIZE 512
54 
55 /*
56  * There should be no timeout for security protocol ioctl call, so we choose a
57  * large number for timeout.
58  * 20000 millisecs == 20 seconds
59  */
60 #define TIMEOUT 20000
61 
62 /*
63  * The sg device driver that supports new interface has a major version number of "3".
64  * SG_GET_VERSION_NUM ioctl() will yield a number greater than or 30000.
65  */
66 #define RPMB_MIN_SG_VERSION_NUM 30000
67 
68 /*
69  * CDB format of SECURITY PROTOCOL IN/OUT commands
70  * (JEDEC Standard No. 220D, Page 264)
71  */
72 struct sec_proto_cdb {
73     /*
74      * OPERATION CODE = A2h for SECURITY PROTOCOL IN command,
75      * OPERATION CODE = B5h for SECURITY PROTOCOL OUT command.
76      */
77     uint8_t opcode;
78     /* SECURITY PROTOCOL = ECh (JEDEC Universal Flash Storage) */
79     uint8_t sec_proto;
80     /*
81      * The SECURITY PROTOCOL SPECIFIC field specifies the RPMB Protocol ID.
82      * CDB Byte 2 = 00h and CDB Byte 3 = 01h for RPMB Region 0.
83      */
84     uint8_t cdb_byte_2;
85     uint8_t cdb_byte_3;
86     /*
87      * Byte 4 and 5 are reserved.
88      */
89     uint8_t cdb_byte_4;
90     uint8_t cdb_byte_5;
91     /* ALLOCATION/TRANSFER LENGTH in big-endian */
92     uint32_t length;
93     /* Byte 9 is reserved. */
94     uint8_t cdb_byte_10;
95     /* CONTROL = 00h. */
96     uint8_t ctrl;
97 } __packed;
98 
99 static int rpmb_fd = -1;
100 static uint8_t read_buf[4096];
101 static enum dev_type dev_type = UNKNOWN_RPMB;
102 
103 #ifdef RPMB_DEBUG
104 
print_buf(const char * prefix,const uint8_t * buf,size_t size)105 static void print_buf(const char* prefix, const uint8_t* buf, size_t size) {
106     size_t i;
107 
108     printf("%s @%p [%zu]", prefix, buf, size);
109     for (i = 0; i < size; i++) {
110         if (i && i % 32 == 0) printf("\n%*s", (int)strlen(prefix), "");
111         printf(" %02x", buf[i]);
112     }
113     printf("\n");
114     fflush(stdout);
115 }
116 
117 #endif
118 
set_sg_io_hdr(sg_io_hdr_t * io_hdrp,int dxfer_direction,unsigned char cmd_len,unsigned char mx_sb_len,unsigned int dxfer_len,void * dxferp,unsigned char * cmdp,void * sbp)119 static void set_sg_io_hdr(sg_io_hdr_t* io_hdrp, int dxfer_direction, unsigned char cmd_len,
120                           unsigned char mx_sb_len, unsigned int dxfer_len, void* dxferp,
121                           unsigned char* cmdp, void* sbp) {
122     memset(io_hdrp, 0, sizeof(sg_io_hdr_t));
123     io_hdrp->interface_id = 'S';
124     io_hdrp->dxfer_direction = dxfer_direction;
125     io_hdrp->cmd_len = cmd_len;
126     io_hdrp->mx_sb_len = mx_sb_len;
127     io_hdrp->dxfer_len = dxfer_len;
128     io_hdrp->dxferp = dxferp;
129     io_hdrp->cmdp = cmdp;
130     io_hdrp->sbp = sbp;
131     io_hdrp->timeout = TIMEOUT;
132 }
133 
send_mmc_rpmb_req(int mmc_fd,const struct storage_rpmb_send_req * req)134 static int send_mmc_rpmb_req(int mmc_fd, const struct storage_rpmb_send_req* req) {
135     struct {
136         struct mmc_ioc_multi_cmd multi;
137         struct mmc_ioc_cmd cmd_buf[3];
138     } mmc = {};
139     struct mmc_ioc_cmd* cmd = mmc.multi.cmds;
140     int rc;
141 
142     const uint8_t* write_buf = req->payload;
143     if (req->reliable_write_size) {
144         cmd->write_flag = MMC_WRITE_FLAG_RELW;
145         cmd->opcode = MMC_WRITE_MULTIPLE_BLOCK;
146         cmd->flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_ADTC;
147         cmd->blksz = MMC_BLOCK_SIZE;
148         cmd->blocks = req->reliable_write_size / MMC_BLOCK_SIZE;
149         mmc_ioc_cmd_set_data((*cmd), write_buf);
150 #ifdef RPMB_DEBUG
151         ALOGI("opcode: 0x%x, write_flag: 0x%x\n", cmd->opcode, cmd->write_flag);
152         print_buf("request: ", write_buf, req->reliable_write_size);
153 #endif
154         write_buf += req->reliable_write_size;
155         mmc.multi.num_of_cmds++;
156         cmd++;
157     }
158 
159     if (req->write_size) {
160         cmd->write_flag = MMC_WRITE_FLAG_W;
161         cmd->opcode = MMC_WRITE_MULTIPLE_BLOCK;
162         cmd->flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_ADTC;
163         cmd->blksz = MMC_BLOCK_SIZE;
164         cmd->blocks = req->write_size / MMC_BLOCK_SIZE;
165         mmc_ioc_cmd_set_data((*cmd), write_buf);
166 #ifdef RPMB_DEBUG
167         ALOGI("opcode: 0x%x, write_flag: 0x%x\n", cmd->opcode, cmd->write_flag);
168         print_buf("request: ", write_buf, req->write_size);
169 #endif
170         write_buf += req->write_size;
171         mmc.multi.num_of_cmds++;
172         cmd++;
173     }
174 
175     if (req->read_size) {
176         cmd->write_flag = MMC_WRITE_FLAG_R;
177         cmd->opcode = MMC_READ_MULTIPLE_BLOCK;
178         cmd->flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_ADTC, cmd->blksz = MMC_BLOCK_SIZE;
179         cmd->blocks = req->read_size / MMC_BLOCK_SIZE;
180         mmc_ioc_cmd_set_data((*cmd), read_buf);
181 #ifdef RPMB_DEBUG
182         ALOGI("opcode: 0x%x, write_flag: 0x%x\n", cmd->opcode, cmd->write_flag);
183 #endif
184         mmc.multi.num_of_cmds++;
185         cmd++;
186     }
187 
188     rc = ioctl(mmc_fd, MMC_IOC_MULTI_CMD, &mmc.multi);
189     if (rc < 0) {
190         ALOGE("%s: mmc ioctl failed: %d, %s\n", __func__, rc, strerror(errno));
191     }
192     return rc;
193 }
194 
send_ufs_rpmb_req(int sg_fd,const struct storage_rpmb_send_req * req)195 static int send_ufs_rpmb_req(int sg_fd, const struct storage_rpmb_send_req* req) {
196     int rc;
197     const uint8_t* write_buf = req->payload;
198     /*
199      * Meaning of member values are stated on the definition of struct sec_proto_cdb.
200      */
201     struct sec_proto_cdb in_cdb = {0xA2, 0xEC, 0x00, 0x01, 0x00, 0x00, 0, 0x00, 0x00};
202     struct sec_proto_cdb out_cdb = {0xB5, 0xEC, 0x00, 0x01, 0x00, 0x00, 0, 0x00, 0x00};
203     unsigned char sense_buffer[32];
204 
205     if (req->reliable_write_size) {
206         /* Prepare SECURITY PROTOCOL OUT command. */
207         out_cdb.length = __builtin_bswap32(req->reliable_write_size);
208         sg_io_hdr_t io_hdr;
209         set_sg_io_hdr(&io_hdr, SG_DXFER_TO_DEV, sizeof(out_cdb), sizeof(sense_buffer),
210                       req->reliable_write_size, (void*)write_buf, (unsigned char*)&out_cdb,
211                       sense_buffer);
212         rc = ioctl(sg_fd, SG_IO, &io_hdr);
213         if (rc < 0) {
214             ALOGE("%s: ufs ioctl failed: %d, %s\n", __func__, rc, strerror(errno));
215         }
216         write_buf += req->reliable_write_size;
217     }
218 
219     if (req->write_size) {
220         /* Prepare SECURITY PROTOCOL OUT command. */
221         out_cdb.length = __builtin_bswap32(req->write_size);
222         sg_io_hdr_t io_hdr;
223         set_sg_io_hdr(&io_hdr, SG_DXFER_TO_DEV, sizeof(out_cdb), sizeof(sense_buffer),
224                       req->write_size, (void*)write_buf, (unsigned char*)&out_cdb, sense_buffer);
225         rc = ioctl(sg_fd, SG_IO, &io_hdr);
226         if (rc < 0) {
227             ALOGE("%s: ufs ioctl failed: %d, %s\n", __func__, rc, strerror(errno));
228         }
229         write_buf += req->write_size;
230     }
231 
232     if (req->read_size) {
233         /* Prepare SECURITY PROTOCOL IN command. */
234         in_cdb.length = __builtin_bswap32(req->read_size);
235         sg_io_hdr_t io_hdr;
236         set_sg_io_hdr(&io_hdr, SG_DXFER_FROM_DEV, sizeof(in_cdb), sizeof(sense_buffer),
237                       req->read_size, read_buf, (unsigned char*)&in_cdb, sense_buffer);
238         rc = ioctl(sg_fd, SG_IO, &io_hdr);
239         if (rc < 0) {
240             ALOGE("%s: ufs ioctl failed: %d, %s\n", __func__, rc, strerror(errno));
241         }
242     }
243     return rc;
244 }
245 
send_virt_rpmb_req(int rpmb_fd,void * read_buf,size_t read_size,const void * payload,size_t payload_size)246 static int send_virt_rpmb_req(int rpmb_fd, void* read_buf, size_t read_size, const void* payload,
247                               size_t payload_size) {
248     int rc;
249     uint16_t res_count = read_size / MMC_BLOCK_SIZE;
250     uint16_t cmd_count = payload_size / MMC_BLOCK_SIZE;
251     rc = write(rpmb_fd, &res_count, sizeof(res_count));
252     if (rc < 0) {
253         return rc;
254     }
255     rc = write(rpmb_fd, &cmd_count, sizeof(cmd_count));
256     if (rc < 0) {
257         return rc;
258     }
259     rc = write(rpmb_fd, payload, payload_size);
260     if (rc < 0) {
261         return rc;
262     }
263     rc = read(rpmb_fd, read_buf, read_size);
264     return rc;
265 }
266 
rpmb_send(struct storage_msg * msg,const void * r,size_t req_len)267 int rpmb_send(struct storage_msg* msg, const void* r, size_t req_len) {
268     int rc;
269     const struct storage_rpmb_send_req* req = r;
270 
271     if (req_len < sizeof(*req)) {
272         ALOGW("malformed rpmb request: invalid length (%zu < %zu)\n", req_len, sizeof(*req));
273         msg->result = STORAGE_ERR_NOT_VALID;
274         goto err_response;
275     }
276 
277     size_t expected_len = sizeof(*req) + req->reliable_write_size + req->write_size;
278     if (req_len != expected_len) {
279         ALOGW("malformed rpmb request: invalid length (%zu != %zu)\n", req_len, expected_len);
280         msg->result = STORAGE_ERR_NOT_VALID;
281         goto err_response;
282     }
283 
284     if ((req->reliable_write_size % MMC_BLOCK_SIZE) != 0) {
285         ALOGW("invalid reliable write size %u\n", req->reliable_write_size);
286         msg->result = STORAGE_ERR_NOT_VALID;
287         goto err_response;
288     }
289 
290     if ((req->write_size % MMC_BLOCK_SIZE) != 0) {
291         ALOGW("invalid write size %u\n", req->write_size);
292         msg->result = STORAGE_ERR_NOT_VALID;
293         goto err_response;
294     }
295 
296     if (req->read_size % MMC_BLOCK_SIZE != 0 || req->read_size > sizeof(read_buf)) {
297         ALOGE("%s: invalid read size %u\n", __func__, req->read_size);
298         msg->result = STORAGE_ERR_NOT_VALID;
299         goto err_response;
300     }
301 
302     if (dev_type == MMC_RPMB) {
303         rc = send_mmc_rpmb_req(rpmb_fd, req);
304         if (rc < 0) {
305             msg->result = STORAGE_ERR_GENERIC;
306             goto err_response;
307         }
308     } else if (dev_type == UFS_RPMB) {
309         rc = send_ufs_rpmb_req(rpmb_fd, req);
310         if (rc < 0) {
311             ALOGE("send_ufs_rpmb_req failed: %d, %s\n", rc, strerror(errno));
312             msg->result = STORAGE_ERR_GENERIC;
313             goto err_response;
314         }
315     } else if ((dev_type == VIRT_RPMB) || (dev_type == SOCK_RPMB)) {
316         size_t payload_size = req->reliable_write_size + req->write_size;
317         rc = send_virt_rpmb_req(rpmb_fd, read_buf, req->read_size, req->payload, payload_size);
318         if (rc < 0) {
319             ALOGE("send_virt_rpmb_req failed: %d, %s\n", rc, strerror(errno));
320             msg->result = STORAGE_ERR_GENERIC;
321             goto err_response;
322         }
323         if (rc != req->read_size) {
324             ALOGE("send_virt_rpmb_req got incomplete response: "
325                   "(size %d, expected %d)\n",
326                   rc, req->read_size);
327             msg->result = STORAGE_ERR_GENERIC;
328             goto err_response;
329         }
330     } else {
331         ALOGE("Unsupported dev_type\n");
332         msg->result = STORAGE_ERR_GENERIC;
333         goto err_response;
334     }
335 #ifdef RPMB_DEBUG
336     if (req->read_size) print_buf("response: ", read_buf, req->read_size);
337 #endif
338 
339     if (msg->flags & STORAGE_MSG_FLAG_POST_COMMIT) {
340         /*
341          * Nothing todo for post msg commit request as MMC_IOC_MULTI_CMD
342          * is fully synchronous in this implementation.
343          */
344     }
345 
346     msg->result = STORAGE_NO_ERROR;
347     return ipc_respond(msg, read_buf, req->read_size);
348 
349 err_response:
350     return ipc_respond(msg, NULL, 0);
351 }
352 
rpmb_open(const char * rpmb_devname,enum dev_type open_dev_type)353 int rpmb_open(const char* rpmb_devname, enum dev_type open_dev_type) {
354     int rc, sg_version_num;
355     dev_type = open_dev_type;
356 
357     if (dev_type != SOCK_RPMB) {
358         rc = open(rpmb_devname, O_RDWR, 0);
359         if (rc < 0) {
360             ALOGE("unable (%d) to open rpmb device '%s': %s\n", errno, rpmb_devname, strerror(errno));
361             return rc;
362         }
363         rpmb_fd = rc;
364 
365         /* For UFS, it is prudent to check we have a sg device by calling an ioctl */
366         if (dev_type == UFS_RPMB) {
367             if ((ioctl(rpmb_fd, SG_GET_VERSION_NUM, &sg_version_num) < 0) ||
368                 (sg_version_num < RPMB_MIN_SG_VERSION_NUM)) {
369                 ALOGE("%s is not a sg device, or old sg driver\n", rpmb_devname);
370                 return -1;
371             }
372         }
373     } else {
374         struct sockaddr_un unaddr;
375         struct sockaddr *addr = (struct sockaddr *)&unaddr;
376         rc = socket(AF_UNIX, SOCK_STREAM, 0);
377         if (rc < 0) {
378             ALOGE("unable (%d) to create socket: %s\n", errno, strerror(errno));
379             return rc;
380         }
381         rpmb_fd = rc;
382 
383         memset(&unaddr, 0, sizeof(unaddr));
384         unaddr.sun_family = AF_UNIX;
385         // TODO if it overflowed, bail rather than connecting?
386         strncpy(unaddr.sun_path, rpmb_devname, sizeof(unaddr.sun_path)-1);
387         rc = connect(rpmb_fd, addr, sizeof(unaddr));
388         if (rc < 0) {
389             ALOGE("unable (%d) to connect to rpmb socket '%s': %s\n", errno, rpmb_devname, strerror(errno));
390             return rc;
391         }
392     }
393 
394     return 0;
395 }
396 
rpmb_close(void)397 void rpmb_close(void) {
398     close(rpmb_fd);
399     rpmb_fd = -1;
400 }
401