Debian Codegraph @

vmcheck/vmcheck_test.go

raw symbols SCIP
1 // Copyright 2016-2017 VMware, Inc. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
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 }