sdgathman / pyspf

Other
52 stars 26 forks source link

SPF checks throw exceptions if ipaddress module is installed beside ipaddr #7

Open jahlives opened 6 years ago

jahlives commented 6 years ago

If using pyspf on python2.7.5 (though think that all python2 is affected) the execution fails if spf.py finds ipaddress package and imports it. In my case ipaddress came as dependency of salt-minion

import spf
spf.check2('XX.YY.ZZ.YY', 'user@example.com', 'example.com')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/site-packages/spf.py", line 297, in check2
    receiver=receiver,timeout=timeout,verbose=verbose,querytime=querytime).check()
  File "/usr/lib/python2.7/site-packages/spf.py", line 378, in __init__
    self.set_ip(i)
  File "/usr/lib/python2.7/site-packages/spf.py", line 405, in set_ip
    self.ipaddr = ipaddress.ip_address(i)
  File "/usr/lib/python2.7/site-packages/ipaddress.py", line 163, in ip_address
    ' a unicode object?' % address)
ipaddress.AddressValueError: 'XX.YY.ZZ.YY' does not appear to be an IPv4 or IPv6 address. Did you pass in a bytes (str in Python 2) instead of a unicode object?

I tried to make it unicode

import spf
spf.check2(unicode('XX.YY.ZZ.YY'), 'user@example.com', 'example.com')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/site-packages/spf.py", line 297, in check2
    receiver=receiver,timeout=timeout,verbose=verbose,querytime=querytime).check()
  File "/usr/lib/python2.7/site-packages/spf.py", line 547, in check
    rc = self.check1(spf, self.d, 0)
  File "/usr/lib/python2.7/site-packages/spf.py", line 586, in check1
    return self.check0(spf, recursion)
  File "/usr/lib/python2.7/site-packages/spf.py", line 871, in check0
    res, code, txt = self.check1(d,arg, recursion + 1)
  File "/usr/lib/python2.7/site-packages/spf.py", line 586, in check1
    return self.check0(spf, recursion)
  File "/usr/lib/python2.7/site-packages/spf.py", line 895, in check0
    if self.cidrmatch(self.dns_a(arg,self.A), cidrlength):
  File "/usr/lib/python2.7/site-packages/spf.py", line 1348, in cidrmatch
    for netwrk in [ipaddress.ip_network(ip) for ip in ipaddrs]:
  File "/usr/lib/python2.7/site-packages/ipaddress.py", line 199, in ip_network
    ' a unicode object?' % address)
ipaddress.AddressValueError: 'XX.XX.XX.XX' does not appear to be an IPv4 or IPv6 address. Did you pass in a bytes (str in Python 2) instead of a unicode object?

note that using unicode() the reported IP address is NOT the one tested by spf.check2() but an ipv4 address from the senders domain spf record.

After trying some I found that if I use an inport like this

try:
    import ipaddr as ipadress

in /usr/lib/python2.7/site-packages/spf.py "solves" the issue and spf.check2() works as expected again

niftylettuce commented 4 years ago

I ran sudo rm -rf /usr/lib/python2.7/dist-packages/ipaddress* and it fixed the issue.