Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/scapy/route6.py: 32%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

167 statements  

1# SPDX-License-Identifier: GPL-2.0-only 

2# This file is part of Scapy 

3# See https://scapy.net/ for more information 

4# Copyright (C) Philippe Biondi <phil@secdev.org> 

5# Copyright (C) 2005 Guillaume Valadon <guedou@hongo.wide.ad.jp> 

6# Arnaud Ebalard <arnaud.ebalard@eads.net> 

7 

8""" 

9Routing and network interface handling for IPv6. 

10""" 

11 

12############################################################################# 

13# Routing/Interfaces stuff # 

14############################################################################# 

15 

16import socket 

17from scapy.config import conf 

18from scapy.interfaces import resolve_iface, NetworkInterface 

19from scapy.utils6 import in6_ptop, in6_cidr2mask, in6_and, \ 

20 in6_islladdr, in6_ismlladdr, in6_isincluded, in6_isgladdr, \ 

21 in6_isaddr6to4, in6_ismaddr, construct_source_candidate_set, \ 

22 get_source_addr_from_candidate_set 

23from scapy.arch import read_routes6, in6_getifaddr 

24from scapy.pton_ntop import inet_pton, inet_ntop 

25from scapy.error import warning, log_loading 

26from scapy.utils import pretty_list 

27 

28from typing import ( 

29 Any, 

30 Dict, 

31 List, 

32 Optional, 

33 Set, 

34 Tuple, 

35 Union, 

36) 

37 

38 

39class Route6: 

40 

41 def __init__(self): 

42 # type: () -> None 

43 self.routes = [] # type: List[Tuple[str, int, str, str, List[str], int]] # noqa: E501 

44 self.ipv6_ifaces = set() # type: Set[Union[str, NetworkInterface]] 

45 self.invalidate_cache() 

46 if conf.route6_autoload: 

47 self.resync() 

48 

49 def invalidate_cache(self): 

50 # type: () -> None 

51 self.cache = {} # type: Dict[str, Tuple[str, str, str]] 

52 

53 def flush(self): 

54 # type: () -> None 

55 self.invalidate_cache() 

56 self.routes.clear() 

57 self.ipv6_ifaces.clear() 

58 

59 def resync(self): 

60 # type: () -> None 

61 # TODO : At the moment, resync will drop existing Teredo routes 

62 # if any. Change that ... 

63 self.invalidate_cache() 

64 self.routes = read_routes6() 

65 self.ipv6_ifaces = set() 

66 for route in self.routes: 

67 self.ipv6_ifaces.add(route[3]) 

68 if self.routes == []: 

69 log_loading.info("No IPv6 support in kernel") 

70 

71 def __repr__(self): 

72 # type: () -> str 

73 rtlst = [] # type: List[Tuple[Union[str, List[str]], ...]] 

74 

75 for net, msk, gw, iface, cset, metric in self.routes: 

76 if_repr = resolve_iface(iface).description 

77 rtlst.append(('%s/%i' % (net, msk), 

78 gw, 

79 if_repr, 

80 cset, 

81 str(metric))) 

82 

83 return pretty_list(rtlst, 

84 [('Destination', 'Next Hop', "Iface", "Src candidates", "Metric")], # noqa: E501 

85 sortBy=1) 

86 

87 # Unlike Scapy's Route.make_route() function, we do not have 'host' and 'net' # noqa: E501 

88 # parameters. We only have a 'dst' parameter that accepts 'prefix' and 

89 # 'prefix/prefixlen' values. 

90 def make_route(self, 

91 dst, # type: str 

92 gw=None, # type: Optional[str] 

93 dev=None, # type: Optional[str] 

94 ): 

95 # type: (...) -> Tuple[str, int, str, str, List[str], int] 

96 """Internal function : create a route for 'dst' via 'gw'. 

97 """ 

98 prefix, plen_b = (dst.split("/") + ["128"])[:2] 

99 plen = int(plen_b) 

100 

101 if gw is None: 

102 gw = "::" 

103 if dev is None: 

104 dev, ifaddr_uniq, x = self.route(gw) 

105 ifaddr = [ifaddr_uniq] 

106 else: 

107 lifaddr = in6_getifaddr() 

108 devaddrs = (x for x in lifaddr if x[2] == dev) 

109 ifaddr = construct_source_candidate_set(prefix, plen, devaddrs) 

110 

111 self.ipv6_ifaces.add(dev) 

112 

113 return (prefix, plen, gw, dev, ifaddr, 1) 

114 

115 def add(self, *args, **kargs): 

116 # type: (*Any, **Any) -> None 

117 """Ex: 

118 add(dst="2001:db8:cafe:f000::/56") 

119 add(dst="2001:db8:cafe:f000::/56", gw="2001:db8:cafe::1") 

120 add(dst="2001:db8:cafe:f000::/64", gw="2001:db8:cafe::1", dev="eth0") 

121 """ 

122 self.invalidate_cache() 

123 self.routes.append(self.make_route(*args, **kargs)) 

124 

125 def remove_ipv6_iface(self, iface): 

126 # type: (str) -> None 

127 """ 

128 Remove the network interface 'iface' from the list of interfaces 

129 supporting IPv6. 

130 """ 

131 

132 if not all(r[3] == iface for r in conf.route6.routes): 

133 self.ipv6_ifaces.discard(iface) 

134 

135 def delt(self, dst, gw=None): 

136 # type: (str, Optional[str]) -> None 

137 """ Ex: 

138 delt(dst="::/0") 

139 delt(dst="2001:db8:cafe:f000::/56") 

140 delt(dst="2001:db8:cafe:f000::/56", gw="2001:db8:deca::1") 

141 """ 

142 tmp = dst + "/128" 

143 dst, plen_b = tmp.split('/')[:2] 

144 dst = in6_ptop(dst) 

145 plen = int(plen_b) 

146 to_del = [x for x in self.routes 

147 if in6_ptop(x[0]) == dst and x[1] == plen] 

148 if gw: 

149 gw = in6_ptop(gw) 

150 to_del = [x for x in self.routes if in6_ptop(x[2]) == gw] 

151 if len(to_del) == 0: 

152 warning("No matching route found") 

153 elif len(to_del) > 1: 

154 warning("Found more than one match. Aborting.") 

155 else: 

156 i = self.routes.index(to_del[0]) 

157 self.invalidate_cache() 

158 self.remove_ipv6_iface(self.routes[i][3]) 

159 del self.routes[i] 

160 

161 def ifchange(self, iff, addr): 

162 # type: (str, str) -> None 

163 the_addr, the_plen_b = (addr.split("/") + ["128"])[:2] 

164 the_plen = int(the_plen_b) 

165 

166 naddr = inet_pton(socket.AF_INET6, the_addr) 

167 nmask = in6_cidr2mask(the_plen) 

168 the_net = inet_ntop(socket.AF_INET6, in6_and(nmask, naddr)) 

169 

170 for i, route in enumerate(self.routes): 

171 net, plen, gw, iface, _, metric = route 

172 if iface != iff: 

173 continue 

174 

175 self.ipv6_ifaces.add(iface) 

176 

177 if gw == '::': 

178 self.routes[i] = (the_net, the_plen, gw, iface, [the_addr], metric) # noqa: E501 

179 else: 

180 self.routes[i] = (net, plen, gw, iface, [the_addr], metric) 

181 self.invalidate_cache() 

182 conf.netcache.in6_neighbor.flush() # type: ignore 

183 

184 def ifdel(self, iff): 

185 # type: (str) -> None 

186 """ removes all route entries that uses 'iff' interface. """ 

187 new_routes = [] 

188 for rt in self.routes: 

189 if rt[3] != iff: 

190 new_routes.append(rt) 

191 self.invalidate_cache() 

192 self.routes = new_routes 

193 self.remove_ipv6_iface(iff) 

194 

195 def ifadd(self, iff, addr): 

196 # type: (str, str) -> None 

197 """ 

198 Add an interface 'iff' with provided address into routing table. 

199 

200 Ex: ifadd('eth0', '2001:bd8:cafe:1::1/64') will add following entry into # noqa: E501 

201 Scapy6 internal routing table: 

202 

203 Destination Next Hop iface Def src @ Metric 

204 2001:bd8:cafe:1::/64 :: eth0 2001:bd8:cafe:1::1 1 

205 

206 prefix length value can be omitted. In that case, a value of 128 

207 will be used. 

208 """ 

209 addr, plen_b = (addr.split("/") + ["128"])[:2] 

210 addr = in6_ptop(addr) 

211 plen = int(plen_b) 

212 naddr = inet_pton(socket.AF_INET6, addr) 

213 nmask = in6_cidr2mask(plen) 

214 prefix = inet_ntop(socket.AF_INET6, in6_and(nmask, naddr)) 

215 self.invalidate_cache() 

216 self.routes.append((prefix, plen, '::', iff, [addr], 1)) 

217 self.ipv6_ifaces.add(iff) 

218 

219 def route(self, dst="", dev=None, verbose=conf.verb): 

220 # type: (str, Optional[str], int) -> Tuple[str, str, str] 

221 """ 

222 Provide best route to IPv6 destination address, based on Scapy 

223 internal routing table content. 

224 

225 When a set of address is passed (e.g. ``2001:db8:cafe:*::1-5``) an 

226 address of the set is used. Be aware of that behavior when using 

227 wildcards in upper parts of addresses ! 

228 

229 If 'dst' parameter is a FQDN, name resolution is performed and result 

230 is used. 

231 

232 if optional 'dev' parameter is provided a specific interface, filtering 

233 is performed to limit search to route associated to that interface. 

234 """ 

235 dst = dst or "::/0" # Enable route(None) to return default route 

236 # Transform "2001:db8:cafe:*::1-5:0/120" to one IPv6 address of the set 

237 dst = dst.split("/")[0] 

238 savedst = dst # In case following inet_pton() fails 

239 dst = dst.replace("*", "0") 

240 idx = dst.find("-") 

241 while idx >= 0: 

242 m = (dst[idx:] + ":").find(":") 

243 dst = dst[:idx] + dst[idx + m:] 

244 idx = dst.find("-") 

245 

246 try: 

247 inet_pton(socket.AF_INET6, dst) 

248 except socket.error: 

249 dst = socket.getaddrinfo(savedst, None, socket.AF_INET6)[0][-1][0] 

250 # TODO : Check if name resolution went well 

251 

252 # Deal with dev-specific request for cache search 

253 k = dst 

254 if dev is not None: 

255 k = dst + "%%" + dev 

256 if k in self.cache: 

257 return self.cache[k] 

258 

259 paths = [] # type: List[Tuple[int, int, Tuple[str, List[str], str]]] 

260 

261 # TODO : review all kinds of addresses (scope and *cast) to see 

262 # if we are able to cope with everything possible. I'm convinced 

263 # it's not the case. 

264 # -- arnaud 

265 for p, plen, gw, iface, cset, me in self.routes: 

266 if dev is not None and iface != dev: 

267 continue 

268 if in6_isincluded(dst, p, plen): 

269 paths.append((plen, me, (iface, cset, gw))) 

270 elif (in6_ismlladdr(dst) and in6_islladdr(p) and in6_islladdr(cset[0])): # noqa: E501 

271 paths.append((plen, me, (iface, cset, gw))) 

272 

273 if not paths: 

274 if dst == "::1": 

275 return (conf.loopback_name, "::1", "::") 

276 else: 

277 if verbose: 

278 warning("No route found for IPv6 destination %s " 

279 "(no default route?)", dst) 

280 return (dev or conf.loopback_name, "::", "::") 

281 

282 # Sort with longest prefix first then use metrics as a tie-breaker 

283 paths.sort(key=lambda x: (-x[0], x[1])) 

284 

285 best_plen = (paths[0][0], paths[0][1]) 

286 paths = [x for x in paths if (x[0], x[1]) == best_plen] 

287 

288 res = [] # type: List[Tuple[int, int, Tuple[str, str, str]]] 

289 for path in paths: # we select best source address for every route 

290 tmp_c = path[2] 

291 srcaddr = get_source_addr_from_candidate_set(dst, tmp_c[1]) 

292 if srcaddr is not None: 

293 res.append((path[0], path[1], (tmp_c[0], srcaddr, tmp_c[2]))) 

294 

295 if res == []: 

296 warning("Found a route for IPv6 destination '%s', but no possible source address.", dst) # noqa: E501 

297 return (conf.loopback_name, "::", "::") 

298 

299 # Symptom : 2 routes with same weight (our weight is plen) 

300 # Solution : 

301 # - dst is unicast global. Check if it is 6to4 and we have a source 

302 # 6to4 address in those available 

303 # - dst is link local (unicast or multicast) and multiple output 

304 # interfaces are available. Take main one (conf.iface) 

305 # - if none of the previous or ambiguity persists, be lazy and keep 

306 # first one 

307 

308 if len(res) > 1: 

309 tmp = [] # type: List[Tuple[int, int, Tuple[str, str, str]]] 

310 if in6_isgladdr(dst) and in6_isaddr6to4(dst): 

311 # TODO : see if taking the longest match between dst and 

312 # every source addresses would provide better results 

313 tmp = [x for x in res if in6_isaddr6to4(x[2][1])] 

314 elif in6_ismaddr(dst) or in6_islladdr(dst): 

315 # TODO : I'm sure we are not covering all addresses. Check that 

316 tmp = [x for x in res if x[2][0] == conf.iface] 

317 

318 if tmp: 

319 res = tmp 

320 

321 # Fill the cache (including dev-specific request) 

322 k = dst 

323 if dev is not None: 

324 k = dst + "%%" + dev 

325 self.cache[k] = res[0][2] 

326 

327 return res[0][2] 

328 

329 

330conf.route6 = Route6()