8 import xml.etree.ElementTree as ET
10 from sys import stderr
11 from binascii import a2b_base64
13 gi.require_version('Gtk', '3.0')
14 from gi.repository import Gtk
16 gi.require_version('WebKit2', '4.0')
17 from gi.repository import WebKit2
20 def __init__(self, uri, html=None, verbose=False):
23 # API reference: https://lazka.github.io/pgi-docs/#WebKit2-4.0
24 # TODO: cookies, see https://stackoverflow.com/questions/48368219/webkit2-webview-how-to-store-cookies-and-reuse-it-again
27 self.wview = WebKit2.WebView()
29 self.wview.load_html(html, uri)
31 self.wview.load_uri(uri)
32 window.resize(500, 500)
33 window.add(self.wview)
35 window.set_title("SAML Login")
36 window.connect('delete-event', Gtk.main_quit)
37 self.wview.connect('load-changed', self.get_saml_headers)
39 def get_saml_headers(self, webview, event):
40 if event != WebKit2.LoadEvent.FINISHED:
43 mr = webview.get_main_resource()
44 print("Finished loading %s..." % mr.get_uri(), file=stderr)
45 rs = mr.get_response()
46 h = rs.get_http_headers()
49 def listify(name, value, t=l):
50 if (name.startswith('saml-') or name in ('prelogin-cookie', 'portal-userauthcookie')):
51 t.append((name, value))
53 self.saml_result = d = dict(l)
55 print("Got SAML relevant headers, done: %r" % d, file=stderr)
59 def parse_args(args = None):
60 p = argparse.ArgumentParser()
61 p.add_argument('-v','--verbose', default=0, action='count')
62 p.add_argument('server', help='GlobalProtect server (portal or gateway)')
63 p.add_argument('--no-verify', dest='verify', action='store_false', default=True, help='Ignore invalid server certificate')
64 x = p.add_mutually_exclusive_group()
65 x.add_argument('-p','--portal', dest='portal', action='store_true', help='SAML auth to portal')
66 x.add_argument('-g','--gateway', dest='portal', action='store_false', help='SAML auth to gateway (default)')
67 g = p.add_argument_group('Client certificate')
68 g.add_argument('-c','--cert', help='PEM file containing client certificate (and optionally private key)')
69 g.add_argument('--key', help='PEM file containing client private key (if not included in same file as certificate)')
70 p.add_argument('extra', nargs='*', help='Extra form field(s) to pass to include in the login query string (e.g. "magic-cookie-value=deadbeef01234567")')
71 args = p.parse_args(args = None)
73 args.extra = dict(x.split('=', 1) for x in args.extra)
75 if args.cert and args.key:
76 args.cert, args.key = (args.cert, args.key), None
78 args.cert = (args.cert, None)
80 p.error('--key specified without --cert')
86 if __name__ == "__main__":
87 p, args = parse_args()
89 s = requests.Session()
90 s.headers['User-Agent'] = 'PAN GlobalProtect'
93 # query prelogin.esp and parse SAML bits
94 endpoint = 'https://{}/{}/prelogin.esp'.format(args.server, ('global-protect' if args.portal else 'ssl-vpn'))
95 res = s.post(endpoint, verify=args.verify, data=args.extra)
96 xml = ET.fromstring(res.content)
97 sam = xml.find('saml-auth-method')
98 sr = xml.find('saml-request')
99 if sam is None or sr is None:
100 p.error("This does not appear to be a SAML prelogin response (<saml-auth-method> or <saml-request> tags missing)")
101 elif sam.text == 'POST':
102 print("Got SAML POST content, opening browser...", file=stderr)
103 html, uri = a2b_base64(sr.text).decode(), None
104 elif sam.text == 'REDIRECT':
105 print("Got SAML REDIRECT to %s, opening browser..." % sr.text, file=stderr)
106 uri, html = sr.text, None
108 p.error("Unknown SAML method (%s)" % sam.text)
110 # spawn WebKit view to do SAML interactive login
111 slv = SAMLLoginView(uri, html, verbose=args.verbose)
114 p.error('''Login window closed without producing SAML cookie''')
116 # extract response and convert to OpenConnect command-line
117 un = slv.saml_result.get('saml-username')
118 for cn in ('prelogin-cookie', 'portal-userauthcookie'):
119 cv = slv.saml_result.get(cn)
126 print('''\n\nSAML response converted to OpenConnect command line invocation:\n''', file=stderr)
127 print(''' echo {!r} |\n openconnect --protocol=gp --user={!r} --usergroup={}:{} --passwd-on-stdin {}\n'''.format(
128 cv, un, ('portal' if args.portal else 'gateway'), cn, args.server), file=stderr)
130 print("HOST={!r}\nUSER={!r}\nCOOKIE={!r}".format('https://%s/%s:%s' % (args.server, ('portal' if args.portal else 'gateway'), cn), un, cv))