3 from __future__ import print_function
4 from sys import stderr, version_info, platform
5 if (version_info >= (3, 0)):
6 from urllib.parse import urlparse, urlencode
9 from urlparse import urlparse
10 from urllib import urlencode
15 import xml.etree.ElementTree as ET
17 from binascii import a2b_base64
18 from tempfile import NamedTemporaryFile
19 from shlex import quote
20 from itertools import chain
22 clientos_map = dict(linux='Linux', darwin='Mac', win32='Windows', cygwin='Windows')
23 default_clientos = clientos_map.get(platform, 'Windows')
25 p = argparse.ArgumentParser()
26 p.add_argument('-v','--verbose', default=0, action='count')
27 p.add_argument('endpoint', help='GlobalProtect server; can append /ssl-vpn/login.esp (default) or /global-protect/getconfig.esp or /{ssl-vpn,global-protect}/prelogin.esp')
28 p.add_argument('extra', nargs='*', help='Extra field to pass to include in the login query string (e.g. "portal-userauthcookie=deadbeef01234567")')
29 g = p.add_argument_group('Login credentials')
30 g.add_argument('-u','--user', help='Username (will prompt if unspecified)')
31 g.add_argument('-p','--password', help='Password (will prompt if unspecified)')
32 g.add_argument('-c','--cert', help='PEM file containing client certificate (and optionally private key)')
33 g.add_argument('--computer', default=os.uname()[1], help="Computer name (default is `hostname`)")
34 g.add_argument('--clientos', choices=set(clientos_map.values()), default=default_clientos, help="clientos value to send (default is %(default)s)")
35 g.add_argument('-k','--key', help='PEM file containing client private key (if not included in same file as certificate)')
36 p.add_argument('-b','--browse', action='store_true', help='Automatically spawn browser for SAML')
37 p.add_argument('--no-verify', dest='verify', action='store_false', default=True, help='Ignore invalid server certificate')
40 extra = dict(x.split('=', 1) for x in args.extra)
41 endpoint = urlparse(('https://' if '//' not in args.endpoint else '') + args.endpoint, 'https:')
43 print("Endpoint path unspecified: defaulting to /ssl-vpn/login.esp", file=stderr)
44 endpoint = endpoint._replace(path = '/ssl-vpn/login.esp')
45 prelogin = (posixpath.split(endpoint.path)[-1] == 'prelogin.esp')
47 if args.cert and args.key:
48 cert = (args.cert, args.key)
50 cert = (args.cert, None)
52 p.error('--key specified without --cert')
56 s = requests.Session()
57 s.headers['User-Agent'] = 'PAN GlobalProtect'
62 # sent by many clients but not known to have any effect
63 'tmp': 'tmp', 'clientVer': 4100, 'kerberos-support': 'yes', 'ipv6-support': 'yes',
64 # affects some clients' behavior (https://github.com/dlenski/gp-saml-gui/issues/6#issuecomment-599743060)
65 'clientos': args.clientos,
69 # same request params work for /global-protect/getconfig.esp as for /ssl-vpn/login.esp
71 args.user = raw_input('Username: ')
72 if args.password == None:
73 args.password = getpass.getpass('Password: ')
74 data=dict(user=args.user, passwd=args.password,
76 jnlpReady='jnlpReady', ok='Login', direct='yes',
77 # optional but might affect behavior
78 clientVer=4100, server=endpoint.netloc, prot='https:',
79 computer=args.computer,
81 res = s.post(endpoint.geturl(), verify=args.verify, data=data)
84 print("Request body:\n", res.request.body, file=stderr)
86 res.raise_for_status()
88 # build openconnect "cookie" if the result is a <jnlp>
91 xml = ET.fromstring(res.text)
96 cert_and_key = '\\\n ' + ' '.join('%s "%s"' % (opt, quote(fn)) for opt, fn in zip(('-c','-k'), cert) if fn) + ' \\\n'
100 if xml is not None and xml.tag == 'jnlp':
101 arguments = [(t.text or '') for t in xml.iter('argument')]
102 arguments += [''] * (16-len(arguments))
103 cookie = urlencode({'authcookie': arguments[1], 'portal': arguments[3], 'user': arguments[4], 'domain': arguments[7],
104 'computer': args.computer, 'preferred-ip': arguments[15]})
108 Extracted connection cookie from <jnlp>. Use this to connect:
110 openconnect --protocol=gp --usergroup=gateway %s \\
112 ''' % (quote(endpoint.netloc), quote(cookie), cert_and_key), file=stderr)
114 # do SAML request if the result is <prelogin-response><saml...>
116 elif xml is not None and xml.tag == 'prelogin-response' and None not in (xml.find('saml-auth-method'), xml.find('saml-request')):
118 sam = xml.find('saml-auth-method').text
119 sr = a2b_base64(xml.find('saml-request').text)
121 with NamedTemporaryFile(delete=False, suffix='.html') as tf:
124 print("Got SAML POST, browsing to %s" % tf.name)
125 webbrowser.open('file://' + tf.name)
127 print("Got SAML POST, saved to:\n\t%s" % tf.name)
128 elif sam == 'REDIRECT':
131 print("Got SAML REDIRECT, browsing to %s" % sr)
134 print("Got SAML REDIRECT to:\n\t%s" % sr)
136 # if it's a portal config response, pass along to gateway
138 elif xml is not None and xml.tag == 'policy':
140 uemail = xml.find('user-email')
141 if uemail: uemail = uemail.text
142 cookies = [(cn, xml.find(cn).text) for cn in ('portal-prelogonuserauthcookie', 'portal-userauthcookie')]
143 gateways = [(e.find('description').text, e.get('name')) for e in set(chain(xml.findall('gateways/external/list/entry'), xml.findall('gateways6/external/list/entry')))]
145 print('''\nPortal config response response converted to new test-globalprotect-login.py invocation for gateway login:\n'''
146 ''' test-globalprotect-login.py --user={} --clientos={} -p {} {}\\\n'''
147 ''' https://{}/ssl-vpn/login.esp \\\n'''
149 quote(args.user), quote(args.clientos), quote(args.password), cert_and_key, quote(gateways[0][1]),
150 ' '.join(cn+'='+quote(cv) for cn, cv in cookies),
153 if uemail and uemail != args.user:
154 print('''IMPORTANT: Portal config contained different username. You might need to try\n'''
155 '''{} instead.\n'''.format(uemail))
157 print('''Received multiple gateways. Options include:\n {}\n'''.format('\n '.join('%s => %s' % (desc, host) for desc, host in gateways)))
159 # Just print the result
163 print(res.headers, file=stderr)