knownhosts.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. // Copyright 2017 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Package knownhosts implements a parser for the OpenSSH
  5. // known_hosts host key database.
  6. package knownhosts
  7. import (
  8. "bufio"
  9. "bytes"
  10. "encoding/base64"
  11. "errors"
  12. "fmt"
  13. "io"
  14. "net"
  15. "os"
  16. "strings"
  17. "golang.org/x/crypto/ssh"
  18. )
  19. // See the sshd manpage
  20. // (http://man.openbsd.org/sshd#SSH_KNOWN_HOSTS_FILE_FORMAT) for
  21. // background.
  22. type addr struct{ host, port string }
  23. func (a *addr) String() string {
  24. return a.host + ":" + a.port
  25. }
  26. func (a *addr) eq(b addr) bool {
  27. return a.host == b.host && a.port == b.port
  28. }
  29. type hostPattern struct {
  30. negate bool
  31. addr addr
  32. }
  33. func (p *hostPattern) String() string {
  34. n := ""
  35. if p.negate {
  36. n = "!"
  37. }
  38. return n + p.addr.String()
  39. }
  40. // See
  41. // https://android.googlesource.com/platform/external/openssh/+/ab28f5495c85297e7a597c1ba62e996416da7c7e/addrmatch.c
  42. // The matching of * has no regard for separators, unlike filesystem globs
  43. func wildcardMatch(pat []byte, str []byte) bool {
  44. for {
  45. if len(pat) == 0 {
  46. return len(str) == 0
  47. }
  48. if len(str) == 0 {
  49. return false
  50. }
  51. if pat[0] == '*' {
  52. if len(pat) == 1 {
  53. return true
  54. }
  55. for j := range str {
  56. if wildcardMatch(pat[1:], str[j:]) {
  57. return true
  58. }
  59. }
  60. return false
  61. }
  62. if pat[0] == '?' || pat[0] == str[0] {
  63. pat = pat[1:]
  64. str = str[1:]
  65. } else {
  66. return false
  67. }
  68. }
  69. }
  70. func (l *hostPattern) match(a addr) bool {
  71. return wildcardMatch([]byte(l.addr.host), []byte(a.host)) && l.addr.port == a.port
  72. }
  73. type keyDBLine struct {
  74. cert bool
  75. patterns []*hostPattern
  76. knownKey KnownKey
  77. }
  78. func (l *keyDBLine) String() string {
  79. c := ""
  80. if l.cert {
  81. c = markerCert + " "
  82. }
  83. var ss []string
  84. for _, p := range l.patterns {
  85. ss = append(ss, p.String())
  86. }
  87. return c + strings.Join(ss, ",") + " " + serialize(l.knownKey.Key)
  88. }
  89. func serialize(k ssh.PublicKey) string {
  90. return k.Type() + " " + base64.StdEncoding.EncodeToString(k.Marshal())
  91. }
  92. func (l *keyDBLine) match(addrs []addr) bool {
  93. matched := false
  94. for _, p := range l.patterns {
  95. for _, a := range addrs {
  96. m := p.match(a)
  97. if p.negate {
  98. if m {
  99. return false
  100. } else {
  101. continue
  102. }
  103. }
  104. if m {
  105. matched = true
  106. }
  107. }
  108. }
  109. return matched
  110. }
  111. type hostKeyDB struct {
  112. // Serialized version of revoked keys
  113. revoked map[string]*KnownKey
  114. lines []keyDBLine
  115. }
  116. func (db *hostKeyDB) String() string {
  117. var ls []string
  118. for _, k := range db.revoked {
  119. ls = append(ls, markerRevoked+" * "+serialize(k.Key))
  120. }
  121. for _, l := range db.lines {
  122. ls = append(ls, l.String())
  123. }
  124. return strings.Join(ls, "\n")
  125. }
  126. func newHostKeyDB() *hostKeyDB {
  127. db := &hostKeyDB{
  128. revoked: make(map[string]*KnownKey),
  129. }
  130. return db
  131. }
  132. func keyEq(a, b ssh.PublicKey) bool {
  133. return bytes.Equal(a.Marshal(), b.Marshal())
  134. }
  135. // IsAuthority can be used as a callback in ssh.CertChecker
  136. func (db *hostKeyDB) IsAuthority(remote ssh.PublicKey) bool {
  137. for _, l := range db.lines {
  138. // TODO(hanwen): should we check the hostname against host pattern?
  139. if l.cert && keyEq(l.knownKey.Key, remote) {
  140. return true
  141. }
  142. }
  143. return false
  144. }
  145. // IsRevoked can be used as a callback in ssh.CertChecker
  146. func (db *hostKeyDB) IsRevoked(key *ssh.Certificate) bool {
  147. _, ok := db.revoked[string(key.Marshal())]
  148. return ok
  149. }
  150. const markerCert = "@cert-authority"
  151. const markerRevoked = "@revoked"
  152. func nextWord(line []byte) (string, []byte) {
  153. i := bytes.IndexAny(line, "\t ")
  154. if i == -1 {
  155. return string(line), nil
  156. }
  157. return string(line[:i]), bytes.TrimSpace(line[i:])
  158. }
  159. func parseLine(line []byte) (marker string, pattern []string, key ssh.PublicKey, err error) {
  160. if w, next := nextWord(line); w == markerCert || w == markerRevoked {
  161. marker = w
  162. line = next
  163. }
  164. hostPart, line := nextWord(line)
  165. if len(line) == 0 {
  166. return "", nil, nil, errors.New("knownhosts: missing host pattern")
  167. }
  168. if len(hostPart) > 0 && hostPart[0] == '|' {
  169. return "", nil, nil, errors.New("knownhosts: hashed hostnames not implemented")
  170. }
  171. pattern = strings.Split(hostPart, ",")
  172. // ignore the keytype as it's in the key blob anyway.
  173. _, line = nextWord(line)
  174. if len(line) == 0 {
  175. return "", nil, nil, errors.New("knownhosts: missing key type pattern")
  176. }
  177. keyBlob, _ := nextWord(line)
  178. keyBytes, err := base64.StdEncoding.DecodeString(keyBlob)
  179. if err != nil {
  180. return "", nil, nil, err
  181. }
  182. key, err = ssh.ParsePublicKey(keyBytes)
  183. if err != nil {
  184. return "", nil, nil, err
  185. }
  186. return marker, pattern, key, nil
  187. }
  188. func (db *hostKeyDB) parseLine(line []byte, filename string, linenum int) error {
  189. marker, patterns, key, err := parseLine(line)
  190. if err != nil {
  191. return err
  192. }
  193. if marker == markerRevoked {
  194. db.revoked[string(key.Marshal())] = &KnownKey{
  195. Key: key,
  196. Filename: filename,
  197. Line: linenum,
  198. }
  199. return nil
  200. }
  201. entry := keyDBLine{
  202. cert: marker == markerCert,
  203. knownKey: KnownKey{
  204. Filename: filename,
  205. Line: linenum,
  206. Key: key,
  207. },
  208. }
  209. for _, p := range patterns {
  210. if len(p) == 0 {
  211. continue
  212. }
  213. var a addr
  214. var negate bool
  215. if p[0] == '!' {
  216. negate = true
  217. p = p[1:]
  218. }
  219. if len(p) == 0 {
  220. return errors.New("knownhosts: negation without following hostname")
  221. }
  222. if p[0] == '[' {
  223. a.host, a.port, err = net.SplitHostPort(p)
  224. if err != nil {
  225. return err
  226. }
  227. } else {
  228. a.host, a.port, err = net.SplitHostPort(p)
  229. if err != nil {
  230. a.host = p
  231. a.port = "22"
  232. }
  233. }
  234. entry.patterns = append(entry.patterns, &hostPattern{
  235. negate: negate,
  236. addr: a,
  237. })
  238. }
  239. db.lines = append(db.lines, entry)
  240. return nil
  241. }
  242. // KnownKey represents a key declared in a known_hosts file.
  243. type KnownKey struct {
  244. Key ssh.PublicKey
  245. Filename string
  246. Line int
  247. }
  248. func (k *KnownKey) String() string {
  249. return fmt.Sprintf("%s:%d: %s", k.Filename, k.Line, serialize(k.Key))
  250. }
  251. // KeyError is returned if we did not find the key in the host key
  252. // database, or there was a mismatch. Typically, in batch
  253. // applications, this should be interpreted as failure. Interactive
  254. // applications can offer an interactive prompt to the user.
  255. type KeyError struct {
  256. // Want holds the accepted host keys. For each key algorithm,
  257. // there can be one hostkey. If Want is empty, the host is
  258. // unknown. If Want is non-empty, there was a mismatch, which
  259. // can signify a MITM attack.
  260. Want []KnownKey
  261. }
  262. func (u *KeyError) Error() string {
  263. if len(u.Want) == 0 {
  264. return "knownhosts: key is unknown"
  265. }
  266. return "knownhosts: key mismatch"
  267. }
  268. // RevokedError is returned if we found a key that was revoked.
  269. type RevokedError struct {
  270. Revoked KnownKey
  271. }
  272. func (r *RevokedError) Error() string {
  273. return "knownhosts: key is revoked"
  274. }
  275. // check checks a key against the host database. This should not be
  276. // used for verifying certificates.
  277. func (db *hostKeyDB) check(address string, remote net.Addr, remoteKey ssh.PublicKey) error {
  278. if revoked := db.revoked[string(remoteKey.Marshal())]; revoked != nil {
  279. return &RevokedError{Revoked: *revoked}
  280. }
  281. host, port, err := net.SplitHostPort(remote.String())
  282. if err != nil {
  283. return fmt.Errorf("knownhosts: SplitHostPort(%s): %v", remote, err)
  284. }
  285. addrs := []addr{
  286. {host, port},
  287. }
  288. if address != "" {
  289. host, port, err := net.SplitHostPort(address)
  290. if err != nil {
  291. return fmt.Errorf("knownhosts: SplitHostPort(%s): %v", address, err)
  292. }
  293. addrs = append(addrs, addr{host, port})
  294. }
  295. return db.checkAddrs(addrs, remoteKey)
  296. }
  297. // checkAddrs checks if we can find the given public key for any of
  298. // the given addresses. If we only find an entry for the IP address,
  299. // or only the hostname, then this still succeeds.
  300. func (db *hostKeyDB) checkAddrs(addrs []addr, remoteKey ssh.PublicKey) error {
  301. // TODO(hanwen): are these the right semantics? What if there
  302. // is just a key for the IP address, but not for the
  303. // hostname?
  304. // Algorithm => key.
  305. knownKeys := map[string]KnownKey{}
  306. for _, l := range db.lines {
  307. if l.match(addrs) {
  308. typ := l.knownKey.Key.Type()
  309. if _, ok := knownKeys[typ]; !ok {
  310. knownKeys[typ] = l.knownKey
  311. }
  312. }
  313. }
  314. keyErr := &KeyError{}
  315. for _, v := range knownKeys {
  316. keyErr.Want = append(keyErr.Want, v)
  317. }
  318. // Unknown remote host.
  319. if len(knownKeys) == 0 {
  320. return keyErr
  321. }
  322. // If the remote host starts using a different, unknown key type, we
  323. // also interpret that as a mismatch.
  324. if known, ok := knownKeys[remoteKey.Type()]; !ok || !keyEq(known.Key, remoteKey) {
  325. return keyErr
  326. }
  327. return nil
  328. }
  329. // The Read function parses file contents.
  330. func (db *hostKeyDB) Read(r io.Reader, filename string) error {
  331. scanner := bufio.NewScanner(r)
  332. lineNum := 0
  333. for scanner.Scan() {
  334. lineNum++
  335. line := scanner.Bytes()
  336. line = bytes.TrimSpace(line)
  337. if len(line) == 0 || line[0] == '#' {
  338. continue
  339. }
  340. if err := db.parseLine(line, filename, lineNum); err != nil {
  341. return err
  342. }
  343. }
  344. return scanner.Err()
  345. }
  346. // New creates a host key callback from the given OpenSSH host key
  347. // files. The returned callback is for use in
  348. // ssh.ClientConfig.HostKeyCallback. Hostnames are ignored for
  349. // certificates, ie. any certificate authority is assumed to be valid
  350. // for all remote hosts. Hashed hostnames are not supported.
  351. func New(files ...string) (ssh.HostKeyCallback, error) {
  352. db := newHostKeyDB()
  353. for _, fn := range files {
  354. f, err := os.Open(fn)
  355. if err != nil {
  356. return nil, err
  357. }
  358. defer f.Close()
  359. if err := db.Read(f, fn); err != nil {
  360. return nil, err
  361. }
  362. }
  363. // TODO(hanwen): properly supporting certificates requires an
  364. // API change in the SSH library: IsAuthority should provide
  365. // the address too?
  366. var certChecker ssh.CertChecker
  367. certChecker.IsAuthority = db.IsAuthority
  368. certChecker.IsRevoked = db.IsRevoked
  369. certChecker.HostKeyFallback = db.check
  370. return certChecker.CheckHostKey, nil
  371. }
  372. // Line returns a line to add append to the known_hosts files.
  373. func Line(addresses []string, key ssh.PublicKey) string {
  374. var trimmed []string
  375. for _, a := range addresses {
  376. host, port, err := net.SplitHostPort(a)
  377. if err != nil {
  378. host = a
  379. port = "22"
  380. }
  381. entry := host
  382. if port != "22" {
  383. entry = "[" + entry + "]:" + port
  384. } else if strings.Contains(host, ":") {
  385. entry = "[" + entry + "]"
  386. }
  387. trimmed = append(trimmed, entry)
  388. }
  389. return strings.Join(trimmed, ",") + " " + serialize(key)
  390. }