File: hmac.go

package info (click to toggle)
yubikey-touch-detector 1.12.5-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 228 kB
  • sloc: makefile: 4
file content (95 lines) | stat: -rw-r--r-- 2,375 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package detector

import (
	"fmt"
	"os"
	"path"
	"strings"
	"sync"
	"time"

	"github.com/deckarep/golang-set"
	"github.com/rjeczalik/notify"
	log "github.com/sirupsen/logrus"

	"github.com/maximbaz/yubikey-touch-detector/notifier"
)

// WatchHMAC watches when YubiKey is waiting for a touch on a HMAC request
func WatchHMAC(notifiers *sync.Map) {
	devicesEvents := initInotifyWatcher("HMAC", "/dev", notify.Create, notify.Remove)
	defer notify.Stop(devicesEvents)

	yubikeyHidrawDevices := mapset.NewSet[string]()
	if devices, err := os.ReadDir("/dev"); err == nil {
		for _, device := range devices {
			devicePath := path.Join("/dev", device.Name())
			if isYubikeyHidrawDevice(devicePath) {
				yubikeyHidrawDevices.Add(devicePath)
			}
		}
	} else {
		log.Errorf("Cannot list devices in '/dev' to find connected YubiKeys: %v", err)
	}

	lastMessage := notifier.HMAC_OFF
	var onRemoveTimer *time.Timer
	for event := range devicesEvents {
		switch event.Event() {
		case notify.Create:
			if onRemoveTimer != nil {
				onRemoveTimer.Stop()
			}
			// Give a second for device to initialize
			time.Sleep(1 * time.Second)

			if isYubikeyHidrawDevice(event.Path()) {
				yubikeyHidrawDevices.Add(event.Path())

				newMessage := notifier.HMAC_OFF
				if lastMessage != newMessage {
					notifiers.Range(func(_, v interface{}) bool {
						v.(chan notifier.Message) <- newMessage
						return true
					})
				}
				lastMessage = newMessage
			}
		case notify.Remove:
			if yubikeyHidrawDevices.Contains(event.Path()) {
				if onRemoveTimer != nil {
					onRemoveTimer.Stop()
				}

				yubikeyHidrawDevices.Remove(event.Path())

				onRemoveTimer = time.AfterFunc(1*time.Second, func() {
					newMessage := notifier.HMAC_OFF
					if yubikeyHidrawDevices.Cardinality() > 0 {
						newMessage = notifier.HMAC_ON
					}

					if lastMessage != newMessage {
						notifiers.Range(func(_, v interface{}) bool {
							v.(chan notifier.Message) <- newMessage
							return true
						})
					}

					lastMessage = newMessage
				})
			}
		}
	}
}

func isYubikeyHidrawDevice(devicePath string) bool {
	if strings.HasPrefix(devicePath, "/dev/hidraw") {
		if info, err := os.ReadFile(fmt.Sprintf("/sys/class/hidraw/%v/device/uevent", path.Base(devicePath))); err == nil {
			if strings.Contains(strings.ToLower(string(info)), "yubikey") {
				return true
			}
		}
	}
	return false
}