uuid: Tighten uuid parse
authorFam Zheng <famz@redhat.com>
Wed, 21 Sep 2016 04:27:23 +0000 (12:27 +0800)
committerFam Zheng <famz@redhat.com>
Fri, 23 Sep 2016 03:42:52 +0000 (11:42 +0800)
sscanf is relatively loose (tolerate) on some invalid formats that we
should fail instead of generating a wrong uuid structure, like with
whitespaces and short strings.

Add and use a helper function to first check the format.

Signed-off-by: Fam Zheng <famz@redhat.com>
Reviewed-by: Eric Blake <eblake@redhat.com>
Reviewed-by: Jeff Cody <jcody@redhat.com>
Message-Id: <1474432046-325-11-git-send-email-famz@redhat.com>

util/uuid.c

index 4701903..dd6b5fd 100644 (file)
@@ -61,12 +61,34 @@ char *qemu_uuid_unparse_strdup(const QemuUUID *uuid)
                            uu[13], uu[14], uu[15]);
 }
 
+static bool qemu_uuid_is_valid(const char *str)
+{
+    int i;
+
+    for (i = 0; i < strlen(str); i++) {
+        const char c = str[i];
+        if (i == 8 || i == 13 || i == 18 || i == 23) {
+            if (str[i] != '-') {
+                return false;
+            }
+        } else {
+            if ((c >= '0' && c <= '9') ||
+                (c >= 'A' && c <= 'F') ||
+                (c >= 'a' && c <= 'f')) {
+                continue;
+            }
+            return false;
+        }
+    }
+    return i == 36;
+}
+
 int qemu_uuid_parse(const char *str, QemuUUID *uuid)
 {
     unsigned char *uu = &uuid->data[0];
     int ret;
 
-    if (strlen(str) != 36) {
+    if (!qemu_uuid_is_valid(str)) {
         return -1;
     }