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.
5 // Package knownhosts implements a parser for the OpenSSH
6 // known_hosts host key database.
23 "golang.org/x/crypto/ssh"
26 // See the sshd manpage
27 // (http://man.openbsd.org/sshd#SSH_KNOWN_HOSTS_FILE_FORMAT) for
30 type addr struct{ host, port string }
32 func (a *addr) String() string {
34 if strings.Contains(h, ":") {
37 return h + ":" + a.port
40 type matcher interface {
44 type hostPattern struct {
49 func (p *hostPattern) String() string {
55 return n + p.addr.String()
58 type hostPatterns []hostPattern
60 func (ps hostPatterns) match(addrs []addr) bool {
62 for _, p := range ps {
63 for _, a := range addrs {
78 // https://android.googlesource.com/platform/external/openssh/+/ab28f5495c85297e7a597c1ba62e996416da7c7e/addrmatch.c
79 // The matching of * has no regard for separators, unlike filesystem globs
80 func wildcardMatch(pat []byte, str []byte) bool {
95 if wildcardMatch(pat[1:], str[j:]) {
102 if pat[0] == '?' || pat[0] == str[0] {
111 func (l *hostPattern) match(a addr) bool {
112 return wildcardMatch([]byte(l.addr.host), []byte(a.host)) && l.addr.port == a.port
115 type keyDBLine struct {
121 func serialize(k ssh.PublicKey) string {
122 return k.Type() + " " + base64.StdEncoding.EncodeToString(k.Marshal())
125 func (l *keyDBLine) match(addrs []addr) bool {
126 return l.matcher.match(addrs)
129 type hostKeyDB struct {
130 // Serialized version of revoked keys
131 revoked map[string]*KnownKey
135 func newHostKeyDB() *hostKeyDB {
137 revoked: make(map[string]*KnownKey),
143 func keyEq(a, b ssh.PublicKey) bool {
144 return bytes.Equal(a.Marshal(), b.Marshal())
147 // IsAuthorityForHost can be used as a callback in ssh.CertChecker
148 func (db *hostKeyDB) IsHostAuthority(remote ssh.PublicKey, address string) bool {
149 h, p, err := net.SplitHostPort(address)
153 a := addr{host: h, port: p}
155 for _, l := range db.lines {
156 if l.cert && keyEq(l.knownKey.Key, remote) && l.match([]addr{a}) {
163 // IsRevoked can be used as a callback in ssh.CertChecker
164 func (db *hostKeyDB) IsRevoked(key *ssh.Certificate) bool {
165 _, ok := db.revoked[string(key.Marshal())]
169 const markerCert = "@cert-authority"
170 const markerRevoked = "@revoked"
172 func nextWord(line []byte) (string, []byte) {
173 i := bytes.IndexAny(line, "\t ")
175 return string(line), nil
178 return string(line[:i]), bytes.TrimSpace(line[i:])
181 func parseLine(line []byte) (marker, host string, key ssh.PublicKey, err error) {
182 if w, next := nextWord(line); w == markerCert || w == markerRevoked {
187 host, line = nextWord(line)
189 return "", "", nil, errors.New("knownhosts: missing host pattern")
192 // ignore the keytype as it's in the key blob anyway.
193 _, line = nextWord(line)
195 return "", "", nil, errors.New("knownhosts: missing key type pattern")
198 keyBlob, _ := nextWord(line)
200 keyBytes, err := base64.StdEncoding.DecodeString(keyBlob)
202 return "", "", nil, err
204 key, err = ssh.ParsePublicKey(keyBytes)
206 return "", "", nil, err
209 return marker, host, key, nil
212 func (db *hostKeyDB) parseLine(line []byte, filename string, linenum int) error {
213 marker, pattern, key, err := parseLine(line)
218 if marker == markerRevoked {
219 db.revoked[string(key.Marshal())] = &KnownKey{
229 cert: marker == markerCert,
237 if pattern[0] == '|' {
238 entry.matcher, err = newHashedHost(pattern)
240 entry.matcher, err = newHostnameMatcher(pattern)
247 db.lines = append(db.lines, entry)
251 func newHostnameMatcher(pattern string) (matcher, error) {
253 for _, p := range strings.Split(pattern, ",") {
266 return nil, errors.New("knownhosts: negation without following hostname")
271 a.host, a.port, err = net.SplitHostPort(p)
276 a.host, a.port, err = net.SplitHostPort(p)
282 hps = append(hps, hostPattern{
290 // KnownKey represents a key declared in a known_hosts file.
291 type KnownKey struct {
297 func (k *KnownKey) String() string {
298 return fmt.Sprintf("%s:%d: %s", k.Filename, k.Line, serialize(k.Key))
301 // KeyError is returned if we did not find the key in the host key
302 // database, or there was a mismatch. Typically, in batch
303 // applications, this should be interpreted as failure. Interactive
304 // applications can offer an interactive prompt to the user.
305 type KeyError struct {
306 // Want holds the accepted host keys. For each key algorithm,
307 // there can be one hostkey. If Want is empty, the host is
308 // unknown. If Want is non-empty, there was a mismatch, which
309 // can signify a MITM attack.
313 func (u *KeyError) Error() string {
314 if len(u.Want) == 0 {
315 return "knownhosts: key is unknown"
317 return "knownhosts: key mismatch"
320 // RevokedError is returned if we found a key that was revoked.
321 type RevokedError struct {
325 func (r *RevokedError) Error() string {
326 return "knownhosts: key is revoked"
329 // check checks a key against the host database. This should not be
330 // used for verifying certificates.
331 func (db *hostKeyDB) check(address string, remote net.Addr, remoteKey ssh.PublicKey) error {
332 if revoked := db.revoked[string(remoteKey.Marshal())]; revoked != nil {
333 return &RevokedError{Revoked: *revoked}
336 host, port, err := net.SplitHostPort(remote.String())
338 return fmt.Errorf("knownhosts: SplitHostPort(%s): %v", remote, err)
346 host, port, err := net.SplitHostPort(address)
348 return fmt.Errorf("knownhosts: SplitHostPort(%s): %v", address, err)
351 addrs = append(addrs, addr{host, port})
354 return db.checkAddrs(addrs, remoteKey)
357 // checkAddrs checks if we can find the given public key for any of
358 // the given addresses. If we only find an entry for the IP address,
359 // or only the hostname, then this still succeeds.
360 func (db *hostKeyDB) checkAddrs(addrs []addr, remoteKey ssh.PublicKey) error {
361 // TODO(hanwen): are these the right semantics? What if there
362 // is just a key for the IP address, but not for the
366 knownKeys := map[string]KnownKey{}
367 for _, l := range db.lines {
369 typ := l.knownKey.Key.Type()
370 if _, ok := knownKeys[typ]; !ok {
371 knownKeys[typ] = l.knownKey
376 keyErr := &KeyError{}
377 for _, v := range knownKeys {
378 keyErr.Want = append(keyErr.Want, v)
381 // Unknown remote host.
382 if len(knownKeys) == 0 {
386 // If the remote host starts using a different, unknown key type, we
387 // also interpret that as a mismatch.
388 if known, ok := knownKeys[remoteKey.Type()]; !ok || !keyEq(known.Key, remoteKey) {
395 // The Read function parses file contents.
396 func (db *hostKeyDB) Read(r io.Reader, filename string) error {
397 scanner := bufio.NewScanner(r)
402 line := scanner.Bytes()
403 line = bytes.TrimSpace(line)
404 if len(line) == 0 || line[0] == '#' {
408 if err := db.parseLine(line, filename, lineNum); err != nil {
409 return fmt.Errorf("knownhosts: %s:%d: %v", filename, lineNum, err)
415 // New creates a host key callback from the given OpenSSH host key
416 // files. The returned callback is for use in
417 // ssh.ClientConfig.HostKeyCallback. Hashed hostnames are not supported.
418 func New(files ...string) (ssh.HostKeyCallback, error) {
420 for _, fn := range files {
421 f, err := os.Open(fn)
426 if err := db.Read(f, fn); err != nil {
431 var certChecker ssh.CertChecker
432 certChecker.IsHostAuthority = db.IsHostAuthority
433 certChecker.IsRevoked = db.IsRevoked
434 certChecker.HostKeyFallback = db.check
436 return certChecker.CheckHostKey, nil
439 // Normalize normalizes an address into the form used in known_hosts
440 func Normalize(address string) string {
441 host, port, err := net.SplitHostPort(address)
448 entry = "[" + entry + "]:" + port
449 } else if strings.Contains(host, ":") && !strings.HasPrefix(host, "[") {
450 entry = "[" + entry + "]"
455 // Line returns a line to add append to the known_hosts files.
456 func Line(addresses []string, key ssh.PublicKey) string {
458 for _, a := range addresses {
459 trimmed = append(trimmed, Normalize(a))
462 return strings.Join(trimmed, ",") + " " + serialize(key)
465 // HashHostname hashes the given hostname. The hostname is not
466 // normalized before hashing.
467 func HashHostname(hostname string) string {
468 // TODO(hanwen): check if we can safely normalize this always.
469 salt := make([]byte, sha1.Size)
471 _, err := rand.Read(salt)
473 panic(fmt.Sprintf("crypto/rand failure %v", err))
476 hash := hashHost(hostname, salt)
477 return encodeHash(sha1HashType, salt, hash)
480 func decodeHash(encoded string) (hashType string, salt, hash []byte, err error) {
481 if len(encoded) == 0 || encoded[0] != '|' {
482 err = errors.New("knownhosts: hashed host must start with '|'")
485 components := strings.Split(encoded, "|")
486 if len(components) != 4 {
487 err = fmt.Errorf("knownhosts: got %d components, want 3", len(components))
491 hashType = components[1]
492 if salt, err = base64.StdEncoding.DecodeString(components[2]); err != nil {
495 if hash, err = base64.StdEncoding.DecodeString(components[3]); err != nil {
501 func encodeHash(typ string, salt []byte, hash []byte) string {
502 return strings.Join([]string{"",
504 base64.StdEncoding.EncodeToString(salt),
505 base64.StdEncoding.EncodeToString(hash),
509 // See https://android.googlesource.com/platform/external/openssh/+/ab28f5495c85297e7a597c1ba62e996416da7c7e/hostfile.c#120
510 func hashHost(hostname string, salt []byte) []byte {
511 mac := hmac.New(sha1.New, salt)
512 mac.Write([]byte(hostname))
516 type hashedHost struct {
521 const sha1HashType = "1"
523 func newHashedHost(encoded string) (*hashedHost, error) {
524 typ, salt, hash, err := decodeHash(encoded)
529 // The type field seems for future algorithm agility, but it's
530 // actually hardcoded in openssh currently, see
531 // https://android.googlesource.com/platform/external/openssh/+/ab28f5495c85297e7a597c1ba62e996416da7c7e/hostfile.c#120
532 if typ != sha1HashType {
533 return nil, fmt.Errorf("knownhosts: got hash type %s, must be '1'", typ)
536 return &hashedHost{salt: salt, hash: hash}, nil
539 func (h *hashedHost) match(addrs []addr) bool {
540 for _, a := range addrs {
541 if bytes.Equal(hashHost(Normalize(a.String()), h.salt), h.hash) {