Skip to content

Instantly share code, notes, and snippets.

@jcward
Created March 27, 2023 18:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jcward/5a64c17a6b61de0f7a4d85d004e7679e to your computer and use it in GitHub Desktop.
Save jcward/5a64c17a6b61de0f7a4d85d004e7679e to your computer and use it in GitHub Desktop.
Remove github IP addresses from known_hosts
#!/usr/bin/env ruby
#
# https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/githubs-ssh-key-fingerprints
# https://stackoverflow.com/questions/75830783
#
# Scan for github IP addresses in your knwon_hosts and remove them
# - Takes ~1.5 minutes on my machine
# - Skips the huge "actions" IP ranges
# - Skips IPv6
require 'json'
meta = JSON.parse `curl -s https://api.github.com/meta`
def num_to_ipv4 v
(v >> 24 & 255).to_i.to_s + "." +
(v >> 16 & 255).to_i.to_s + "." +
(v >> 8 & 255).to_i.to_s + "." +
(v >> 0 & 255).to_i.to_s
end
def get_ips_for octals, bits
ips = []
base = (octals[0] << 24) | (octals[1] << 16) | (octals[2] << 8) | octals[3]
num = 2**(32-bits)
0.upto(num) { |add|
ips.push( num_to_ipv4( base + add ) )
}
return ips
end
meta.each { |key, value|
next if key=="actions" # These ranges are too large
if (value.is_a?(Array)) then
value.each { |ip|
if (ip.match(/(\d+)\.(\d+)\.(\d+)\.(\d+)\/(\d+)/)) then
octals = [$1, $2, $3, $4].map(&:to_i)
bits = $5.to_i
ips = get_ips_for(octals, bits)
puts "# Scanning #{ key } range -- #{ ips.length } IPs"
ips.each { |ip|
search = `ssh-keygen -H -F #{ ip }`
if (search.length > 10) then
puts "Running: ssh-keygen -R #{ ip }"
`ssh-keygen -R #{ ip }`
end
}
end
}
end
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment