knownhosts.go 12 KB

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