Skip to content

fix: prevent panic in getHostByName on DNS lookup failure#475

Open
Yanhu007 wants to merge 1 commit intoMasterminds:masterfrom
Yanhu007:fix/getHostByName-dns-panic
Open

fix: prevent panic in getHostByName on DNS lookup failure#475
Yanhu007 wants to merge 1 commit intoMasterminds:masterfrom
Yanhu007:fix/getHostByName-dns-panic

Conversation

@Yanhu007
Copy link
Copy Markdown

Partially addresses #473 (Finding 3: CWE-476)

Problem

getHostByName discards the error from net.LookupHost and unconditionally indexes into the result slice:

func getHostByName(name string) string {
    addrs, _ := net.LookupHost(name)
    //TODO: add error handing when release v3 comes out
    return addrs[rand.Intn(len(addrs))]
}

When DNS resolution fails (e.g. NXDOMAIN, network error), addrs is nil, and rand.Intn(0) panics with an unrecoverable crash. The TODO comment acknowledges this was supposed to be fixed.

Fix

Check for errors and empty results. Return the input hostname unchanged when lookup fails, instead of panicking:

func getHostByName(name string) string {
    addrs, err := net.LookupHost(name)
    if err != nil || len(addrs) == 0 {
        return name
    }
    return addrs[rand.Intn(len(addrs))]
}

Testing

All tests pass (one pre-existing timezone-dependent failure in TestHtmlDate is unrelated).

getHostByName discards the error from net.LookupHost and
unconditionally indexes into the result slice. When DNS resolution
fails, the slice is nil and rand.Intn(0) panics, crashing the
entire program.

Return the input hostname unchanged when lookup fails or returns
no addresses, instead of panicking.

Partially addresses Masterminds#473 (Finding 3: CWE-476)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant