8 import xml.etree.ElementTree as ET
11 from sys import stderr
12 from binascii import a2b_base64
14 gi.require_version('Gtk', '3.0')
15 from gi.repository import Gtk
17 gi.require_version('WebKit2', '4.0')
18 from gi.repository import WebKit2
21 def __init__(self, uri, html=None, verbose=False, cookies=None):
24 # API reference: https://lazka.github.io/pgi-docs/#WebKit2-4.0
28 self.ctx = WebKit2.WebContext.get_default()
29 self.cookies = self.ctx.get_cookie_manager()
31 self.cookies.set_accept_policy(WebKit2.CookieAcceptPolicy.ALWAYS)
32 self.cookies.set_persistent_storage(args.cookies, WebKit2.CookiePersistentStorage.TEXT)
33 self.wview = WebKit2.WebView()
35 window.resize(500, 500)
36 window.add(self.wview)
38 window.set_title("SAML Login")
39 window.connect('delete-event', Gtk.main_quit)
40 self.wview.connect('load-changed', self.get_saml_headers)
43 self.wview.load_html(html, uri)
45 self.wview.load_uri(uri)
47 def get_saml_headers(self, webview, event):
48 if event != WebKit2.LoadEvent.FINISHED:
51 mr = webview.get_main_resource()
52 print("Finished loading %s..." % mr.get_uri(), file=stderr)
53 rs = mr.get_response()
54 h = rs.get_http_headers()
57 def listify(name, value, t=l):
58 if (name.startswith('saml-') or name in ('prelogin-cookie', 'portal-userauthcookie')):
59 t.append((name, value))
61 self.saml_result = d = dict(l)
63 print("Got SAML relevant headers, done: %r" % d, file=stderr)
67 def parse_args(args = None):
68 p = argparse.ArgumentParser()
69 p.add_argument('-v','--verbose', default=0, action='count')
70 p.add_argument('server', help='GlobalProtect server (portal or gateway)')
71 p.add_argument('--no-verify', dest='verify', action='store_false', default=True, help='Ignore invalid server certificate')
72 p.add_argument('-C', '--no-cookies', dest='cookies', action='store_const', const=None,
73 default='~/.gp-saml-gui-cookies', help="Don't use cookies (stored in %(default)s)")
74 x = p.add_mutually_exclusive_group()
75 x.add_argument('-p','--portal', dest='portal', action='store_true', help='SAML auth to portal')
76 x.add_argument('-g','--gateway', dest='portal', action='store_false', help='SAML auth to gateway (default)')
77 g = p.add_argument_group('Client certificate')
78 g.add_argument('-c','--cert', help='PEM file containing client certificate (and optionally private key)')
79 g.add_argument('--key', help='PEM file containing client private key (if not included in same file as certificate)')
80 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")')
81 args = p.parse_args(args = None)
83 args.extra = dict(x.split('=', 1) for x in args.extra)
86 args.cookies = os.path.expanduser(args.cookies)
88 if args.cert and args.key:
89 args.cert, args.key = (args.cert, args.key), None
91 args.cert = (args.cert, None)
93 p.error('--key specified without --cert')
99 if __name__ == "__main__":
100 p, args = parse_args()
102 s = requests.Session()
103 s.headers['User-Agent'] = 'PAN GlobalProtect'
106 # query prelogin.esp and parse SAML bits
107 endpoint = 'https://{}/{}/prelogin.esp'.format(args.server, ('global-protect' if args.portal else 'ssl-vpn'))
108 res = s.post(endpoint, verify=args.verify, data=args.extra)
109 xml = ET.fromstring(res.content)
110 sam = xml.find('saml-auth-method')
111 sr = xml.find('saml-request')
112 if sam is None or sr is None:
113 p.error("This does not appear to be a SAML prelogin response (<saml-auth-method> or <saml-request> tags missing)")
114 elif sam.text == 'POST':
115 print("Got SAML POST content, opening browser...", file=stderr)
116 html, uri = a2b_base64(sr.text).decode(), None
117 elif sam.text == 'REDIRECT':
118 print("Got SAML REDIRECT to %s, opening browser..." % sr.text, file=stderr)
119 uri, html = sr.text, None
121 p.error("Unknown SAML method (%s)" % sam.text)
123 # spawn WebKit view to do SAML interactive login
124 slv = SAMLLoginView(uri, html, verbose=args.verbose, cookies=args.cookies)
127 p.error('''Login window closed without producing SAML cookie''')
129 # extract response and convert to OpenConnect command-line
130 un = slv.saml_result.get('saml-username')
131 for cn in ('prelogin-cookie', 'portal-userauthcookie'):
132 cv = slv.saml_result.get(cn)
139 print('''\n\nSAML response converted to OpenConnect command line invocation:\n''', file=stderr)
140 print(''' echo {!r} |\n openconnect --protocol=gp --user={!r} --usergroup={}:{} --passwd-on-stdin {}\n'''.format(
141 cv, un, ('portal' if args.portal else 'gateway'), cn, args.server), file=stderr)
143 print("HOST={!r}\nUSER={!r}\nCOOKIE={!r}".format('https://%s/%s:%s' % (args.server, ('portal' if args.portal else 'gateway'), cn), un, cv))