8 import xml.etree.ElementTree as ET
11 from sys import stderr
12 from binascii import a2b_base64, b2a_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
27 self.verbose = verbose
29 self.ctx = WebKit2.WebContext.get_default()
30 self.cookies = self.ctx.get_cookie_manager()
32 self.cookies.set_accept_policy(WebKit2.CookieAcceptPolicy.ALWAYS)
33 self.cookies.set_persistent_storage(args.cookies, WebKit2.CookiePersistentStorage.TEXT)
34 self.wview = WebKit2.WebView()
36 window.resize(500, 500)
37 window.add(self.wview)
39 window.set_title("SAML Login")
40 window.connect('delete-event', Gtk.main_quit)
41 self.wview.connect('load-changed', self.get_saml_headers)
42 self.wview.connect('resource-load-started', self.log_resources)
45 self.wview.load_html(html, uri)
47 self.wview.load_uri(uri)
49 def log_resources(self, webview, resource, request):
51 print('%s for resource %s' % (request.get_http_method() or 'Request', resource.get_uri()), file=stderr)
53 def get_saml_headers(self, webview, event):
54 if event != WebKit2.LoadEvent.FINISHED:
57 mr = webview.get_main_resource()
59 print("Finished loading %s" % mr.get_uri(), file=stderr)
60 rs = mr.get_response()
61 h = rs.get_http_headers()
64 def listify(name, value, t=l):
65 if (name.startswith('saml-') or name in ('prelogin-cookie', 'portal-userauthcookie')):
66 t.append((name, value))
68 self.saml_result = d = dict(l)
71 print("Got SAML relevant headers, done: %r" % d, file=stderr)
75 def parse_args(args = None):
76 p = argparse.ArgumentParser()
77 p.add_argument('server', help='GlobalProtect server (portal or gateway)')
78 p.add_argument('--no-verify', dest='verify', action='store_false', default=True, help='Ignore invalid server certificate')
79 p.add_argument('-C', '--no-cookies', dest='cookies', action='store_const', const=None,
80 default='~/.gp-saml-gui-cookies', help="Don't use cookies (stored in %(default)s)")
81 x = p.add_mutually_exclusive_group()
82 x.add_argument('-p','--portal', dest='portal', action='store_true', help='SAML auth to portal')
83 x.add_argument('-g','--gateway', dest='portal', action='store_false', help='SAML auth to gateway (default)')
84 g = p.add_argument_group('Client certificate')
85 g.add_argument('-c','--cert', help='PEM file containing client certificate (and optionally private key)')
86 g.add_argument('--key', help='PEM file containing client private key (if not included in same file as certificate)')
87 g = p.add_argument_group('Debugging and advanced options')
88 g.add_argument('-v','--verbose', default=0, action='count')
89 g.add_argument('-x','--external', action='store_true', help='Launch external browser (for debugging)')
90 g.add_argument('-u','--uri', action='store_true', help='Treat server as the complete URI of the SAML entry point, rather than GlobalProtect server')
91 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")')
92 args = p.parse_args(args = None)
94 args.extra = dict(x.split('=', 1) for x in args.extra)
97 args.cookies = os.path.expanduser(args.cookies)
99 if args.cert and args.key:
100 args.cert, args.key = (args.cert, args.key), None
102 args.cert = (args.cert, None)
104 p.error('--key specified without --cert')
110 if __name__ == "__main__":
111 p, args = parse_args()
113 s = requests.Session()
114 s.headers['User-Agent'] = 'PAN GlobalProtect'
117 # query prelogin.esp and parse SAML bits
119 sam, uri, html = 'URI', args.server, None
121 endpoint = 'https://{}/{}/prelogin.esp'.format(args.server, ('global-protect' if args.portal else 'ssl-vpn'))
122 res = s.post(endpoint, verify=args.verify, data=args.extra)
123 xml = ET.fromstring(res.content)
124 sam = xml.find('saml-auth-method')
125 sr = xml.find('saml-request')
126 if sam is None or sr is None:
127 p.error("This does not appear to be a SAML prelogin response (<saml-auth-method> or <saml-request> tags missing)")
129 sr = a2b_base64(sr.text).decode()
132 elif sam == 'REDIRECT':
135 p.error("Unknown SAML method (%s)" % sam)
137 # launch external browser for debugging
139 print("Got SAML %s, opening external browser for debugging..." % sam, file=stderr)
142 uri = 'data:text/html;base64,' + b2a_base64(html.encode()).decode()
146 # spawn WebKit view to do SAML interactive login
148 print("Got SAML %s, opening browser..." % sam, file=stderr)
149 slv = SAMLLoginView(uri, html, verbose=args.verbose, cookies=args.cookies)
152 p.error('''Login window closed without producing SAML cookie''')
154 # extract response and convert to OpenConnect command-line
155 un = slv.saml_result.get('saml-username')
156 for cn in ('prelogin-cookie', 'portal-userauthcookie'):
157 cv = slv.saml_result.get(cn)
164 print('''\n\nSAML response converted to OpenConnect command line invocation:\n''', file=stderr)
165 print(''' echo {!r} |\n openconnect --protocol=gp --user={!r} --usergroup={}:{} --passwd-on-stdin {}\n'''.format(
166 cv, un, ('portal' if args.portal else 'gateway'), cn, args.server), file=stderr)
168 print("HOST={!r}\nUSER={!r}\nCOOKIE={!r}".format('https://%s/%s:%s' % (args.server, ('portal' if args.portal else 'gateway'), cn), un, cv))