eiwd

no dbus iwd with iwctl functionality
git clone https://git.daat.foo/repos/eiwd.git
Log | Files | Refs | Submodules | README | LICENSE

ios_convert.py (15858B)


      1 #!/usr/bin/python3
      2 
      3 import subprocess
      4 import sys
      5 import os
      6 import argparse
      7 from xml.etree import ElementTree
      8 
      9 class Network:
     10         def __init__(self):
     11                 self.eap_types = []
     12                 self.outer_id = None
     13                 self.inner_eap = None
     14                 self.nai_realms = []
     15                 self.cert_path = None
     16                 self.is_hotspot = False
     17                 self.username = None
     18                 self.password = None
     19                 self.ssid = None
     20                 self.display_name = None
     21                 self.tls_trusted_servers = []
     22 
     23 def process_eap_config(eap_conf, network):
     24         for m in range(len(eap_conf)):
     25                 if eap_conf[m].text == "AcceptEAPTypes":
     26                         tarray = eap_conf[m + 1]
     27                         for i in range(len(tarray)):
     28                                 network.eap_types.append(tarray[i].text)
     29 
     30                 elif eap_conf[m].text == "TTLSInnerAuthentication":
     31                         network.inner_eap = eap_conf[m + 1].text
     32                 elif eap_conf[m].text == "OuterIdentity":
     33                         network.outer_id = eap_conf[m + 1].text
     34                 elif eap_conf[m].text == "UserName" and args.user:
     35                         network.username =  eap_conf[m + 1].text
     36                 elif eap_conf[m].text == "UserPassword" and args.passwd:
     37                         network.password =  eap_conf[m + 1].text
     38                 elif eap_conf[m].text == "TLSTrustedServerNames":
     39                         tarray = eap_conf[m + 1]
     40                         for i in range(len(tarray)):
     41                                 network.tls_trusted_servers.append(tarray[i].text)
     42 
     43 def process_payload_array(parray):
     44         network = Network()
     45 
     46         for l in range(len(parray)):
     47                 if parray[l].text == "NAIRealmNames":
     48                         nai_array = parray[l + 1]
     49                         for i in range(len(nai_array)):
     50                                 network.nai_realms.append(nai_array[i].text)
     51                         continue
     52                 elif parray[l].text == "IsHotspot":
     53                         if parray[l + 1].tag.lower() == "true":
     54                                 network.is_hotspot = True
     55                         else:
     56                                 network.is_hotspot = False
     57                 elif parray[l].text == "SSID_STR":
     58                         network.ssid = parray[l + 1].text
     59                 elif parray[l].text == "DisplayedOperatorName":
     60                         network.display_name = parray[l + 1].text
     61                 elif parray[l].text == "EAPClientConfiguration":
     62                         process_eap_config(parray[l + 1], network)
     63 
     64         return network
     65 
     66 def process_payload(payload):
     67         networks = []
     68         for k in range(len(payload)):
     69                 if payload[k].tag != "dict":
     70                         continue
     71 
     72                 n = process_payload_array(payload[k])
     73                 if n:
     74                         networks.append(n)
     75 
     76         return networks
     77 
     78 
     79 def write_network(network, root_ca_path):
     80         global cert_path
     81         output = ""
     82         eap = None
     83 
     84         # TODO: Handle multiple EAP types?
     85         if len(network.eap_types) < 1:
     86                 print("Not configuring open network %s" % network.ssid)
     87                 return
     88 
     89         if network.eap_types[0] == '21':
     90                 eap = 'TTLS'
     91         elif network.eap_types[0] == '25':
     92                 eap = 'PEAP'
     93 
     94         if not eap:
     95                 print("TTLS or PEAP config was not found in XML")
     96                 return
     97 
     98         if not network.inner_eap:
     99                 print("No inner EAP method found in XML")
    100                 return
    101 
    102         if network.is_hotspot and len(network.nai_realms) == 0:
    103                 print("No NAI realms found in XML")
    104                 return
    105 
    106         output = "[Security]\n"
    107         output += "EAP-Method=%s\n" % eap
    108 
    109         # Use OuterIdentity if specified. But if not use "anonymous". Some AP's
    110         # do not like an empty identity packet and will timeout.
    111         if network.outer_id:
    112                 output += "EAP-Identity=%s\n" % network.outer_id
    113         else:
    114                 output += "EAP-Identity=anonymous\n"
    115 
    116         if root_ca_path:
    117                 output += "EAP-%s-CACert=embed:root_ca\n" % eap
    118 
    119         output += "EAP-%s-Phase2-Method=Tunneled-%s\n" % \
    120                                                         (eap, network.inner_eap)
    121 
    122         if network.username:
    123                 output += "EAP-%s-Phase2-Identity=%s\n" % \
    124                                                         (eap, network.username)
    125 
    126         if network.password:
    127                 output += "EAP-%s-Phase2-Password=%s\n" % \
    128                                                         (eap, network.password)
    129 
    130         if len(network.tls_trusted_servers) > 0:
    131                 output += "EAP-%s-ServerDomainMask=" % eap
    132                 output += ';'.join(network.tls_trusted_servers)
    133                 output += '\n'
    134 
    135         if network.display_name:
    136                 name = network.display_name
    137         elif network.ssid:
    138                 name = network.ssid
    139         else:
    140                 name = "NameUnknown"
    141 
    142         if network.is_hotspot:
    143                 conf_file = iwd_dir + '/hotspot/' + \
    144                                 name + '.conf'
    145                 output += "[Hotspot]\n"
    146                 output += "NAIRealmNames="
    147                 output += ','.join(network.nai_realms)
    148                 output += "\n"
    149                 output += "Name=%s\n" % name
    150 
    151         else:
    152                 conf_file = iwd_dir + '/' + name + '.8021x'
    153 
    154         # Some AP's require older protocol versions. There should be no harm in
    155         # setting this all the time.
    156         output += "[EAPoL]\n"
    157         output += "ProtocolVersion=1\n"
    158 
    159         output += "\n"
    160 
    161         if root_ca_path:
    162                 output += "[@pem@root_ca]\n"
    163                 with open(root_ca_path) as f:
    164                         output += f.read()
    165 
    166         print("Provisioning network %s\n" % conf_file)
    167 
    168         if args.verbose:
    169                 print(output)
    170 
    171         with open(conf_file, 'w+') as f:
    172                 f.write(output)
    173 
    174 def find_root_ca(chain):
    175         def cleanup(certs):
    176                 for c in certs:
    177                         os.remove(c)
    178 
    179         def parse_cert_chain(file):
    180                 certs = []
    181                 in_cert = False
    182                 current = ""
    183                 f = open(file, 'r')
    184                 for l in f:
    185                         if '-----BEGIN CERTIFICATE-----' in l:
    186                                 if in_cert:
    187                                         print("invalid BEGIN")
    188                                         exit()
    189                                 in_cert = True
    190                         elif '-----END CERTIFICATE-----' in l:
    191                                 if not in_cert:
    192                                         print("invalid END")
    193                                         exit()
    194                                 in_cert = False
    195                                 current += l
    196                                 certs.append(current)
    197                                 current = ""
    198                                 continue
    199 
    200                         current += l
    201 
    202                 return certs
    203 
    204         def find_root_ca_path(hash):
    205                 path = '/etc/ssl/certs/%s.0' % hash
    206                 if os.path.exists(path):
    207                         return os.path.realpath(path)
    208 
    209                 return None
    210 
    211         #
    212         # Parse each cert out of the chain.
    213         #
    214         certs = parse_cert_chain(chain)
    215         files = []
    216         subjects = []
    217         self_signed = None
    218 
    219         if len(certs) < 1:
    220                 print("No certs found")
    221                 exit()
    222 
    223         #
    224         # Write each cert into an intermediate#.pem file, get subject and see if
    225         # any are self-signed (Root CA). If one is self signed, save this file
    226         # to be used later when verifying the chain.
    227         #
    228         for index, c in enumerate(certs):
    229                 with open("/tmp/intermediate" + str(index) + ".pem", 'w+') as f:
    230                         f.write(c)
    231 
    232                         files.append("/tmp/intermediate%d.pem" % index)
    233 
    234                 with open(os.devnull, 'w') as devnull:
    235                         proc = subprocess.Popen(['openssl', 'x509', '-subject',
    236                                         '-hash', '-issuer_hash', '-noout', '-in',
    237                                         '/tmp/intermediate%d.pem' % index],
    238                                         stdout=subprocess.PIPE, stderr=devnull)
    239 
    240                 result, err = proc.communicate()
    241                 results = result.decode("utf-8").split('\n')
    242 
    243                 sub = results[0]
    244                 own_hash = results[1]
    245                 issuer_hash = results[2]
    246 
    247                 #
    248                 # Get rid of "depth=#" openssl output
    249                 #
    250                 sub = sub[sub.index('C ='):].strip()
    251                 subjects.append(sub)
    252 
    253                 if own_hash == issuer_hash:
    254                         self_signed = '/tmp/intermediate%d.pem' % index
    255 
    256         #
    257         # Let openssl verify and print the subject of the cert chain. If there
    258         # is a self signed cert we want openssl to bypass looking in the cert
    259         # store (-no-CApath), and provide this CA (-CAfile). Otherwise, let
    260         # openssl verify the chain as usual.
    261         #
    262         if not self_signed:
    263                 with open(os.devnull, 'w') as devnull:
    264                         proc = subprocess.Popen(['openssl', 'verify',
    265                                         '-show_chain', '-untrusted', chain,
    266                                         '/tmp/intermediate0.pem'],
    267                                         stdout=subprocess.PIPE, stderr=devnull)
    268         else:
    269                 with open(os.devnull, 'w') as devnull:
    270                         proc = subprocess.Popen(['openssl', 'verify',
    271                                         '-show_chain', '-no-CApath', '-CAfile',
    272                                         self_signed, '-untrusted', chain,
    273                                         '/tmp/intermediate0.pem'],
    274                                         stdout=subprocess.PIPE, stderr=devnull)
    275 
    276         results, err = proc.communicate()
    277         results = results.decode("utf-8").strip().split('\n')
    278 
    279         #
    280         # We only want lines starting with depth=
    281         #
    282         results = [e for e in results if e.startswith('depth=')]
    283 
    284         print("Found %d certs in chain" % len(results))
    285 
    286         #
    287         # Get rid of prepended "depth=#"
    288         #
    289         ca_sub = results[-1]
    290         ca_sub = ca_sub[ca_sub.index('C ='):].strip()
    291 
    292         #
    293         # The last cert in the chain will either be a Root CA, or issued by a
    294         # Root CA. If we find a matching subject in our previous -show_chain
    295         # command we know there is a Root CA in the chain, if not we need to
    296         # find the Root CA on the system.
    297         #
    298         ca_cert_index = len(results) - 2
    299 
    300         for i, sub in enumerate(subjects):
    301                 if ca_sub == sub:
    302                         print("Root CA found in chain, index=%d" % i)
    303                         ca_cert_index = i
    304 
    305         #
    306         # Now that we have this last cert, check if its a Root CA or not by
    307         # checking if its hash matches the issuer hash.
    308         #
    309         with open(os.devnull, 'w') as devnull:
    310                 proc = subprocess.Popen(['openssl', 'x509', '-hash',
    311                                 '-issuer_hash', '-noout', '-in',
    312                                 '/tmp/intermediate%d.pem' % ca_cert_index],
    313                                 stdout=subprocess.PIPE, stderr=devnull)
    314         hashes, err = proc.communicate()
    315         hashes = hashes.decode('utf-8').strip().split('\n')
    316 
    317         own = hashes[0]
    318         issuer = hashes[1]
    319 
    320         if own == issuer:
    321                 #
    322                 # Since this is a Root CA, we should already have a copy on the
    323                 # system. Verify the hash links to a system cert.
    324                 #
    325                 path = find_root_ca_path(issuer)
    326                 if path is not None:
    327                         print("Verified Root CA exists: %s" % path)
    328                 else:
    329                         print("Root CA in chain could not be found on system")
    330                         return None
    331 
    332                 cleanup(files)
    333                 return path
    334 
    335         print("Root CA not found in cert chain, looking on system")
    336 
    337         #
    338         # The final cert in the chain was not a Root CA, check if we have a Root
    339         # CA on the system matching the last certs issuer hash.
    340         #
    341         path = find_root_ca_path(issuer)
    342         if path is None:
    343                 print("Could not find issuer %s" % issuer)
    344                 return None
    345 
    346         with open(os.devnull, 'w') as devnull:
    347                 proc = subprocess.Popen(['openssl', 'x509', '-hash',
    348                                         '-issuer_hash', '-noout', '-in', path],
    349                                         stdout=subprocess.PIPE, stderr=devnull)
    350 
    351         hashes, err = proc.communicate()
    352         hashes = hashes.decode('utf-8').strip().split('\n')
    353 
    354         own = hashes[0]
    355         issuer = hashes[1]
    356 
    357         if own == issuer:
    358                 path = find_root_ca_path(issuer)
    359                 if path is not None:
    360                         print("Verified Root CA exists: %s" % path)
    361                 else:
    362                         print("Root CA could not be found on system")
    363                         return None
    364 
    365         cleanup(files)
    366 
    367         return path
    368 
    369 iwd_dir='/var/lib/iwd'
    370 cert_path = None
    371 
    372 description = '''
    373 Convert iOS mobileconfig file to IWD format. Currently only TTLS and PEAP are
    374 supported. Inner methods supported are PAP, CHAP, MSCHAP, MSCHAPv2.
    375 '''
    376 
    377 parser = argparse.ArgumentParser(description=description)
    378 group = parser.add_mutually_exclusive_group(required=True)
    379 group.add_argument('-i', '--input', nargs='?', metavar='mobileconfig',
    380                 help='iOS mobileconfig file')
    381 parser.add_argument('-o', '--iwd-out', nargs='?', metavar='dir',
    382                 help='IWD configuration directory (default /var/lib/iwd)')
    383 parser.add_argument('-u', '--user', action='store_true',
    384                 help='Store username in provisioning file')
    385 parser.add_argument('-p', '--passwd', action='store_true',
    386                 help='Store password (plaintext) in provisioning file')
    387 parser.add_argument('-v', '--verbose', action='store_true',
    388                 help='Enable verbose output')
    389 group.add_argument('-x', '--xml', nargs='?',
    390                 help='Directly pass XML')
    391 
    392 args = parser.parse_args()
    393 
    394 if args.iwd_out:
    395         iwd_dir = args.iwd_out
    396 
    397 if args.input:
    398         with open(os.devnull, 'w') as devnull:
    399                 proc = subprocess.Popen(['openssl', 'cms', '-in', args.input, '-inform',
    400                                         'der', '-verify', '-noverify'],
    401                                         stdout=subprocess.PIPE, stderr=devnull)
    402 
    403         xml, err = proc.communicate()
    404 
    405         xml = xml.decode('utf-8')
    406 else:
    407         with open(args.xml) as f:
    408                 xml = f.read()
    409 
    410 if args.verbose:
    411         print(xml)
    412 
    413 if args.input:
    414         subprocess.call(['openssl', 'cms', '-in', args.input, '-inform', 'der',
    415                         '-outform', 'pem', '-noout', '-cmsout', '-certsout',
    416                         '/tmp/certchain.crt'])
    417 
    418 root = ElementTree.fromstring(xml)
    419 
    420 for i in range(len(root)):
    421         for j in range(len(root[i])):
    422                 if root[i][j].text != "PayloadContent":
    423                         continue
    424                 if (root[i][j + 1].tag != "array"):
    425                         continue
    426 
    427                 payload = root[i][j + 1]
    428                 nets = process_payload(payload)
    429 
    430 if args.input:
    431         root_ca_path = find_root_ca('/tmp/certchain.crt')
    432 else:
    433         root_ca_path = None
    434 
    435 for n in nets:
    436         write_network(n, root_ca_path)