8 import xml.etree.ElementTree as ET
11 from operator import setitem
13 from shlex import quote
14 from sys import stderr
15 from binascii import a2b_base64, b2a_base64
17 gi.require_version('Gtk', '3.0')
18 gi.require_version('WebKit2', '4.0')
19 from gi.repository import Gtk, WebKit2, GLib
22 def __init__(self, uri, html=None, verbose=False, cookies=None, verify=True):
25 # API reference: https://lazka.github.io/pgi-docs/#WebKit2-4.0
30 self.verbose = verbose
32 self.ctx = WebKit2.WebContext.get_default()
34 self.ctx.set_tls_errors_policy(WebKit2.TLSErrorsPolicy.IGNORE)
35 self.cookies = self.ctx.get_cookie_manager()
37 self.cookies.set_accept_policy(WebKit2.CookieAcceptPolicy.ALWAYS)
38 self.cookies.set_persistent_storage(args.cookies, WebKit2.CookiePersistentStorage.TEXT)
39 self.wview = WebKit2.WebView()
41 window.resize(500, 500)
42 window.add(self.wview)
44 window.set_title("SAML Login")
45 window.connect('delete-event', self.close)
46 self.wview.connect('load-changed', self.get_saml_headers)
47 self.wview.connect('resource-load-started', self.log_resources)
50 self.wview.load_html(html, uri)
52 self.wview.load_uri(uri)
54 def close(self, window, event):
58 def log_resources(self, webview, resource, request):
60 print('[REQUEST] %s for resource %s' % (request.get_http_method() or 'Request', resource.get_uri()), file=stderr)
62 resource.connect('finished', self.log_resource_details, request)
64 def log_resource_details(self, resource, request):
65 m = request.get_http_method() or 'Request'
66 uri = resource.get_uri()
67 rs = resource.get_response()
68 h = rs.get_http_headers() if rs else None
70 ct, cl = h.get_content_type(), h.get_content_length()
71 content_type, charset = ct[0], ct.params.get('charset')
72 content_details = '%d bytes of %s%s for ' % (cl, content_type, ('; charset='+charset) if charset else '')
73 print('[RECEIVE] %sresource %s %s' % (content_details if h else '', m, uri), file=stderr)
75 def log_resource_text(self, resource, result, content_type, charset=None, show_headers=None):
76 data = resource.get_data_finish(result)
77 content_details = '%d bytes of %s%s for ' % (len(data), content_type, ('; charset='+charset) if charset else '')
78 print('[DATA ] %sresource %s' % (content_details, resource.get_uri()), file=stderr)
80 for h,v in show_headers.items():
81 print('%s: %s' % (h, v), file=stderr)
83 if charset or content_type.startswith('text/'):
84 print(data.decode(charset or 'utf-8'), file=stderr)
86 def get_saml_headers(self, webview, event):
87 if event != WebKit2.LoadEvent.FINISHED:
90 mr = webview.get_main_resource()
91 rs = mr.get_response()
92 h = rs.get_http_headers()
94 print('[PAGE ] Finished loading page %s' % mr.get_uri(), file=stderr)
98 # convert to normal dict
100 h.foreach(lambda k, v: setitem(d, k, v))
101 # filter to interesting headers
102 fd = {name:v for name, v in d.items() if name.startswith('saml-') or name in ('location', 'prelogin-cookie', 'portal-userauthcookie')}
103 if fd and self.verbose:
104 print("[SAML ] Got SAML result headers: %r" % fd, file=stderr)
106 # display everything we found
107 ct = h.get_content_type()
108 mr.get_data(None, self.log_resource_text, ct[0], ct.params.get('charset'), d)
110 # check if we're done
111 self.saml_result.update(fd)
112 GLib.timeout_add(1000, self.check_done)
114 def check_done(self):
116 if 'saml-username' in d and ('prelogin-cookie' in d or 'portal-userauthcookie' in d):
118 print("[SAML ] Got all required SAML headers, done.", file=stderr)
122 def parse_args(args = None):
123 p = argparse.ArgumentParser()
124 p.add_argument('server', help='GlobalProtect server (portal or gateway)')
125 p.add_argument('--no-verify', dest='verify', action='store_false', default=True, help='Ignore invalid server certificate')
126 x = p.add_mutually_exclusive_group()
127 x.add_argument('-C', '--cookies', default='~/.gp-saml-gui-cookies',
128 help='Use and store cookies in this file (instead of default %(default)s)')
129 x.add_argument('-K', '--no-cookies', dest='cookies', action='store_const', const=None,
130 help="Don't use or store cookies at all")
131 x = p.add_mutually_exclusive_group()
132 x.add_argument('-p','--portal', dest='portal', action='store_true', help='SAML auth to portal')
133 x.add_argument('-g','--gateway', dest='portal', action='store_false', help='SAML auth to gateway (default)')
134 g = p.add_argument_group('Client certificate')
135 g.add_argument('-c','--cert', help='PEM file containing client certificate (and optionally private key)')
136 g.add_argument('--key', help='PEM file containing client private key (if not included in same file as certificate)')
137 g = p.add_argument_group('Debugging and advanced options')
138 g.add_argument('-v','--verbose', default=0, action='count')
139 g.add_argument('-x','--external', action='store_true', help='Launch external browser (for debugging)')
140 g.add_argument('-u','--uri', action='store_true', help='Treat server as the complete URI of the SAML entry point, rather than GlobalProtect server')
141 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")')
142 args = p.parse_args(args = None)
144 args.extra = dict(x.split('=', 1) for x in args.extra)
147 args.cookies = path.expanduser(args.cookies)
149 if args.cert and args.key:
150 args.cert, args.key = (args.cert, args.key), None
152 args.cert = (args.cert, None)
154 p.error('--key specified without --cert')
160 if __name__ == "__main__":
161 p, args = parse_args()
163 s = requests.Session()
164 s.headers['User-Agent'] = 'PAN GlobalProtect'
167 # query prelogin.esp and parse SAML bits
169 sam, uri, html = 'URI', args.server, None
171 endpoint = 'https://{}/{}/prelogin.esp'.format(args.server, ('global-protect' if args.portal else 'ssl-vpn'))
173 print("Looking for SAML auth tags in response to %s..." % endpoint, file=stderr)
175 res = s.post(endpoint, verify=args.verify, data=args.extra)
176 except Exception as ex:
179 if isinstance(rootex, ssl.SSLError):
181 elif not rootex.__cause__ and not rootex.__context__:
183 rootex = rootex.__cause__ or rootex.__context__
184 if isinstance(rootex, ssl.CertificateError):
185 p.error("SSL certificate error (try --no-verify to ignore): %s" % rootex)
186 elif isinstance(rootex, ssl.SSLError):
187 p.error("SSL error: %s" % rootex)
190 xml = ET.fromstring(res.content)
191 sam = xml.find('saml-auth-method')
192 sr = xml.find('saml-request')
193 if sam is None or sr is None:
194 p.error("This does not appear to be a SAML prelogin response (<saml-auth-method> or <saml-request> tags missing)")
196 sr = a2b_base64(sr.text).decode()
199 elif sam == 'REDIRECT':
202 p.error("Unknown SAML method (%s)" % sam)
204 # launch external browser for debugging
206 print("Got SAML %s, opening external browser for debugging..." % sam, file=stderr)
209 uri = 'data:text/html;base64,' + b2a_base64(html.encode()).decode()
213 # spawn WebKit view to do SAML interactive login
215 print("Got SAML %s, opening browser..." % sam, file=stderr)
216 slv = SAMLLoginView(uri, html, verbose=args.verbose, cookies=args.cookies, verify=args.verify)
219 print("Login window closed by user.", file=stderr)
222 p.error('''Login window closed without producing SAML cookies.''')
224 # extract response and convert to OpenConnect command-line
225 un = slv.saml_result.get('saml-username')
226 for cn in ('prelogin-cookie', 'portal-userauthcookie'):
227 cv = slv.saml_result.get(cn)
233 fullpath = ('/global-protect/getconfig.esp' if args.portal else '/ssl-vpn/login.esp')
234 shortpath = ('portal' if args.portal else 'gateway')
236 print('''\nSAML response converted to OpenConnect command line invocation:\n''', file=stderr)
237 print(''' echo {} |\n openconnect --protocol=gp --user={} --usergroup={}:{} --passwd-on-stdin {}'''.format(
238 quote(cv), quote(un), quote(shortpath), quote(cn), quote(args.server)), file=stderr)
240 print('''\nSAML response converted to test-globalprotect-login.py invocation:\n''', file=stderr)
241 print(''' test-globalprotect-login.py --user={} -p '' \\\n https://{}{} {}={}\n'''.format(
242 quote(un), quote(args.server), quote(fullpath), quote(cn), quote(cv)), file=stderr)
245 'HOST': quote('https://%s/%s:%s' % (args.server, shortpath, cn)),
246 'USER': quote(un), 'COOKIE': quote(cv),
248 print('\n'.join('%s=%s' % pair for pair in varvals.items()))