DescLen = sizeof (EFI_USB_ENDPOINT_DESCRIPTOR);\r
CtrlLen = sizeof (USB_ENDPOINT_DESC);\r
break;\r
+\r
+ default:\r
+ ASSERT (FALSE);\r
+ return NULL;\r
+ }\r
+\r
+ //\r
+ // Total length is too small that cannot hold the single descriptor header plus data. \r
+ //\r
+ if (Len <= sizeof (USB_DESC_HEAD)) {\r
+ DEBUG ((DEBUG_ERROR, "UsbCreateDesc: met mal-format descriptor, total length = %d!\n", Len));\r
+ return NULL;\r
}\r
\r
//\r
// format. Skip the descriptor that isn't of this Type\r
//\r
Offset = 0;\r
- Head = (USB_DESC_HEAD*)DescBuf;\r
+ Head = (USB_DESC_HEAD *)DescBuf;\r
+ while (Offset < Len - sizeof (USB_DESC_HEAD)) {\r
+ //\r
+ // Above condition make sure Head->Len and Head->Type are safe to access\r
+ //\r
+ Head = (USB_DESC_HEAD *)&DescBuf[Offset];\r
\r
- while ((Offset < Len) && (Head->Type != Type)) {\r
- Offset += Head->Len;\r
- if (Len <= Offset) {\r
- DEBUG (( EFI_D_ERROR, "UsbCreateDesc: met mal-format descriptor, Beyond boundary!\n"));\r
+ if (Head->Len == 0) {\r
+ DEBUG ((DEBUG_ERROR, "UsbCreateDesc: met mal-format descriptor, Head->Len = 0!\n"));\r
return NULL;\r
}\r
- Head = (USB_DESC_HEAD*)(DescBuf + Offset);\r
- if (Head->Len == 0) {\r
- DEBUG (( EFI_D_ERROR, "UsbCreateDesc: met mal-format descriptor, Head->Len = 0!\n"));\r
+\r
+ //\r
+ // Make sure no overflow when adding Head->Len to Offset.\r
+ //\r
+ if (Head->Len > MAX_UINTN - Offset) {\r
+ DEBUG ((DEBUG_ERROR, "UsbCreateDesc: met mal-format descriptor, Head->Len = %d!\n", Head->Len));\r
return NULL;\r
}\r
+\r
+ Offset += Head->Len;\r
+\r
+ if (Head->Type == Type) {\r
+ break;\r
+ }\r
+ }\r
+\r
+ //\r
+ // Head->Len is invalid resulting data beyond boundary, or\r
+ // Descriptor cannot be found: No such type.\r
+ //\r
+ if (Len < Offset) {\r
+ DEBUG ((DEBUG_ERROR, "UsbCreateDesc: met mal-format descriptor, Offset/Len = %d/%d!\n", Offset, Len));\r
}\r
\r
- if ((Len <= Offset) || (Len < Offset + Head->Len) ||\r
- (Head->Type != Type) || (Head->Len < DescLen)) {\r
- DEBUG (( EFI_D_ERROR, "UsbCreateDesc: met mal-format descriptor\n"));\r
+ if ((Head->Type != Type) || (Head->Len < DescLen)) {\r
+ DEBUG ((DEBUG_ERROR, "UsbCreateDesc: descriptor cannot be found, Header(T/L) = %d/%d!\n", Head->Type, Head->Len));\r
return NULL;\r
}\r
\r
\r
CopyMem (Desc, Head, (UINTN) DescLen);\r
\r
- *Consumed = Offset + Head->Len;\r
+ *Consumed = Offset;\r
\r
return Desc;\r
}\r