| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
package vmcheck |
| 16 |
|
| 17 |
import ( |
| 18 |
"encoding/binary" |
| 19 |
"fmt" |
| 20 |
"testing" |
| 21 |
) |
| 22 |
|
| 23 |
var ( |
| 24 |
intelID = []byte("GenuineIntel") |
| 25 |
vmwID = []byte("VMwareVMware") |
| 26 |
|
| 27 |
errPerm = fmt.Errorf("operation not permitted") |
| 28 |
errAccess = fmt.Errorf("access denied") |
| 29 |
) |
| 30 |
|
| 31 |
func TestVirtualWorld(t *testing.T) { |
| 32 |
leUint32 := binary.LittleEndian.Uint32 |
| 33 |
data := []struct { |
| 34 |
scenario string |
| 35 |
hv bool |
| 36 |
id []byte |
| 37 |
portAccess error |
| 38 |
bdoorKnock error |
| 39 |
resp bool |
| 40 |
}{ |
| 41 |
{"vmware", true, vmwID, nil, nil, true}, |
| 42 |
{"vmware no backdoor", true, vmwID, errPerm, errAccess, false}, |
| 43 |
{"physical", false, intelID, errPerm, errAccess, false}, |
| 44 |
} |
| 45 |
|
| 46 |
for _, tt := range data { |
| 47 |
tt := tt |
| 48 |
t.Run(tt.scenario, func(t *testing.T) { |
| 49 |
p := platform{ |
| 50 |
accessPorts: func() error { return tt.portAccess }, |
| 51 |
cpuid: func(eax, _ uint32) (uint32, uint32, uint32, uint32) { |
| 52 |
if eax == 0x1 { |
| 53 |
if tt.hv { |
| 54 |
return 0, 0, uint32(1 << 31), 0 |
| 55 |
} |
| 56 |
return 0, 0, 0, 0 |
| 57 |
} |
| 58 |
if eax == 0x40000000 { |
| 59 |
return 0, leUint32(tt.id[:]), leUint32(tt.id[4:]), leUint32(tt.id[8:]) |
| 60 |
} |
| 61 |
t.Fatal(fmt.Errorf("unexpected cpuid call")) |
| 62 |
return 0, 0, 0, 0 |
| 63 |
}, |
| 64 |
knock: func() (bool, error) { |
| 65 |
if tt.bdoorKnock == nil { |
| 66 |
return true, nil |
| 67 |
} |
| 68 |
return false, tt.bdoorKnock |
| 69 |
}, |
| 70 |
} |
| 71 |
v, err := p.isVirtualWorld(false) |
| 72 |
if tt.resp { |
| 73 |
if !v || err != nil { |
| 74 |
t.Fatal("expected to be virtual") |
| 75 |
} |
| 76 |
return |
| 77 |
} |
| 78 |
|
| 79 |
if v { |
| 80 |
t.Fatal("wrongly detected as virtual") |
| 81 |
} |
| 82 |
|
| 83 |
if err != nil { |
| 84 |
if tt.portAccess != nil && err == tt.portAccess { |
| 85 |
return |
| 86 |
} |
| 87 |
if tt.bdoorKnock != nil && err == tt.bdoorKnock { |
| 88 |
return |
| 89 |
} |
| 90 |
t.Fatal("unexpected error") |
| 91 |
} |
| 92 |
}) |
| 93 |
} |
| 94 |
} |