summaryrefslogtreecommitdiffstats
path: root/third_party/rust/authenticator/src/openbsd/device.rs
blob: 2238e034e2c5942a21b1d3a259eb9cdd97257cd2 (plain)
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

extern crate libc;

use std::ffi::OsString;
use std::io;
use std::io::{Read, Result, Write};
use std::mem;

use crate::consts::{CID_BROADCAST, MAX_HID_RPT_SIZE};
use crate::platform::monitor::FidoDev;
use crate::u2ftypes::{U2FDevice, U2FDeviceInfo};
use crate::util::{from_unix_result, io_err};

#[derive(Debug)]
pub struct Device {
    path: OsString,
    fd: libc::c_int,
    cid: [u8; 4],
    out_len: usize,
    dev_info: Option<U2FDeviceInfo>,
}

impl Device {
    pub fn new(fido: FidoDev) -> Result<Self> {
        debug!("device found: {:?}", fido);
        Ok(Self {
            path: fido.os_path,
            fd: fido.fd,
            cid: CID_BROADCAST,
            out_len: 64,
            dev_info: None,
        })
    }

    pub fn is_u2f(&mut self) -> bool {
        debug!("device {:?} is U2F/FIDO", self.path);

        // From OpenBSD's libfido2 in 6.6-current:
        // "OpenBSD (as of 201910) has a bug that causes it to lose
        // track of the DATA0/DATA1 sequence toggle across uhid device
        // open and close. This is a terrible hack to work around it."
        match self.ping() {
            Ok(_) => true,
            Err(err) => {
                debug!("device {:?} is not responding: {}", self.path, err);
                false
            }
        }
    }

    fn ping(&mut self) -> Result<()> {
        let capacity = 256;

        for _ in 0..10 {
            let mut data = vec![0u8; capacity];

            // Send 1 byte ping
            self.write_all(&[0, 0xff, 0xff, 0xff, 0xff, 0x81, 0, 1])?;

            // Wait for response
            let mut pfd: libc::pollfd = unsafe { mem::zeroed() };
            pfd.fd = self.fd;
            pfd.events = libc::POLLIN;
            if from_unix_result(unsafe { libc::poll(&mut pfd, 1, 100) })? == 0 {
                debug!("device {:?} timeout", self.path);
                continue;
            }

            // Read response
            self.read(&mut data[..])?;

            return Ok(());
        }

        Err(io_err("no response from device"))
    }
}

impl Drop for Device {
    fn drop(&mut self) {
        // Close the fd, ignore any errors.
        let _ = unsafe { libc::close(self.fd) };
        debug!("device {:?} closed", self.path);
    }
}

impl PartialEq for Device {
    fn eq(&self, other: &Device) -> bool {
        self.path == other.path
    }
}

impl Read for Device {
    fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
        let buf_ptr = buf.as_mut_ptr() as *mut libc::c_void;
        let rv = unsafe { libc::read(self.fd, buf_ptr, buf.len()) };
        from_unix_result(rv as usize)
    }
}

impl Write for Device {
    fn write(&mut self, buf: &[u8]) -> Result<usize> {
        // Always skip the first byte (report number)
        let data = &buf[1..];
        let data_ptr = data.as_ptr() as *const libc::c_void;
        let rv = unsafe { libc::write(self.fd, data_ptr, data.len()) };
        Ok(from_unix_result(rv as usize)? + 1)
    }

    fn flush(&mut self) -> Result<()> {
        Ok(())
    }
}

impl U2FDevice for Device {
    fn get_cid(&self) -> &[u8; 4] {
        &self.cid
    }

    fn set_cid(&mut self, cid: [u8; 4]) {
        self.cid = cid;
    }

    fn in_rpt_size(&self) -> usize {
        MAX_HID_RPT_SIZE
    }

    fn out_rpt_size(&self) -> usize {
        MAX_HID_RPT_SIZE
    }

    fn get_property(&self, _prop_name: &str) -> io::Result<String> {
        Err(io::Error::new(io::ErrorKind::Other, "Not implemented"))
    }

    fn get_device_info(&self) -> U2FDeviceInfo {
        // unwrap is okay, as dev_info must have already been set, else
        // a programmer error
        self.dev_info.clone().unwrap()
    }

    fn set_device_info(&mut self, dev_info: U2FDeviceInfo) {
        self.dev_info = Some(dev_info);
    }
}