8 import xml.etree.ElementTree as ET
11 from operator import setitem
13 from shlex import quote
14 from sys import stderr, platform
15 from binascii import a2b_base64, b2a_base64
16 from urllib.parse import urlparse, urlencode
18 gi.require_version('Gtk', '3.0')
19 gi.require_version('WebKit2', '4.0')
20 from gi.repository import Gtk, WebKit2, GLib
23 def __init__(self, uri, html=None, verbose=False, cookies=None, verify=True):
26 # API reference: https://lazka.github.io/pgi-docs/#WebKit2-4.0
31 self.verbose = verbose
33 self.ctx = WebKit2.WebContext.get_default()
35 self.ctx.set_tls_errors_policy(WebKit2.TLSErrorsPolicy.IGNORE)
36 self.cookies = self.ctx.get_cookie_manager()
38 self.cookies.set_accept_policy(WebKit2.CookieAcceptPolicy.ALWAYS)
39 self.cookies.set_persistent_storage(args.cookies, WebKit2.CookiePersistentStorage.TEXT)
40 self.wview = WebKit2.WebView()
42 window.resize(500, 500)
43 window.add(self.wview)
45 window.set_title("SAML Login")
46 window.connect('delete-event', self.close)
47 self.wview.connect('load-changed', self.get_saml_headers)
48 self.wview.connect('resource-load-started', self.log_resources)
51 self.wview.load_html(html, uri)
53 self.wview.load_uri(uri)
55 def close(self, window, event):
59 def log_resources(self, webview, resource, request):
61 print('[REQUEST] %s for resource %s' % (request.get_http_method() or 'Request', resource.get_uri()), file=stderr)
63 resource.connect('finished', self.log_resource_details, request)
65 def log_resource_details(self, resource, request):
66 m = request.get_http_method() or 'Request'
67 uri = resource.get_uri()
68 rs = resource.get_response()
69 h = rs.get_http_headers() if rs else None
71 ct, cl = h.get_content_type(), h.get_content_length()
72 content_type, charset = ct[0], ct.params.get('charset')
73 content_details = '%d bytes of %s%s for ' % (cl, content_type, ('; charset='+charset) if charset else '')
74 print('[RECEIVE] %sresource %s %s' % (content_details if h else '', m, uri), file=stderr)
76 def log_resource_text(self, resource, result, content_type, charset=None, show_headers=None):
77 data = resource.get_data_finish(result)
78 content_details = '%d bytes of %s%s for ' % (len(data), content_type, ('; charset='+charset) if charset else '')
79 print('[DATA ] %sresource %s' % (content_details, resource.get_uri()), file=stderr)
81 for h,v in show_headers.items():
82 print('%s: %s' % (h, v), file=stderr)
84 if charset or content_type.startswith('text/'):
85 print(data.decode(charset or 'utf-8'), file=stderr)
87 def get_saml_headers(self, webview, event):
88 if event != WebKit2.LoadEvent.FINISHED:
91 mr = webview.get_main_resource()
93 rs = mr.get_response()
94 h = rs.get_http_headers()
96 print('[PAGE ] Finished loading page %s' % uri, file=stderr)
100 # convert to normal dict
102 h.foreach(lambda k, v: setitem(d, k, v))
103 # filter to interesting headers
104 fd = {name:v for name, v in d.items() if name.startswith('saml-') or name in ('prelogin-cookie', 'portal-userauthcookie')}
105 if fd and self.verbose:
106 print("[SAML ] Got SAML result headers: %r" % fd, file=stderr)
108 # display everything we found
109 ct = h.get_content_type()
110 mr.get_data(None, self.log_resource_text, ct[0], ct.params.get('charset'), d)
112 # check if we're done
113 self.saml_result.update(fd, server=urlparse(uri).netloc)
114 GLib.timeout_add(1000, self.check_done)
116 def check_done(self):
118 if 'saml-username' in d and ('prelogin-cookie' in d or 'portal-userauthcookie' in d):
120 print("[SAML ] Got all required SAML headers, done.", file=stderr)
124 def parse_args(args = None):
125 clientos_map = dict(linux='Linux', darwin='Mac', win32='Windows', cygwin='Windows')
126 default_clientos = clientos_map.get(platform, 'Windows')
128 p = argparse.ArgumentParser()
129 p.add_argument('server', help='GlobalProtect server (portal or gateway)')
130 p.add_argument('--no-verify', dest='verify', action='store_false', default=True, help='Ignore invalid server certificate')
131 x = p.add_mutually_exclusive_group()
132 x.add_argument('-C', '--cookies', default='~/.gp-saml-gui-cookies',
133 help='Use and store cookies in this file (instead of default %(default)s)')
134 x.add_argument('-K', '--no-cookies', dest='cookies', action='store_const', const=None,
135 help="Don't use or store cookies at all")
136 x = p.add_mutually_exclusive_group()
137 x.add_argument('-p','--portal', dest='interface', action='store_const', const='portal', default='gateway',
138 help='SAML auth to portal')
139 x.add_argument('-g','--gateway', dest='interface', action='store_const', const='gateway',
140 help='SAML auth to gateway (default)')
141 g = p.add_argument_group('Client certificate')
142 g.add_argument('-c','--cert', help='PEM file containing client certificate (and optionally private key)')
143 g.add_argument('--key', help='PEM file containing client private key (if not included in same file as certificate)')
144 g = p.add_argument_group('Debugging and advanced options')
145 g.add_argument('-v','--verbose', default=0, action='count')
146 g.add_argument('-x','--external', action='store_true', help='Launch external browser (for debugging)')
147 g.add_argument('-u','--uri', action='store_true', help='Treat server as the complete URI of the SAML entry point, rather than GlobalProtect server')
148 g.add_argument('--clientos', choices=set(clientos_map.values()), default=default_clientos, help="clientos value to send (default is %(default)s)")
149 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")')
150 args = p.parse_args(args = None)
152 args.extra = dict(x.split('=', 1) for x in args.extra)
155 args.cookies = path.expanduser(args.cookies)
157 if args.cert and args.key:
158 args.cert, args.key = (args.cert, args.key), None
160 args.cert = (args.cert, None)
162 p.error('--key specified without --cert')
168 if __name__ == "__main__":
169 p, args = parse_args()
171 s = requests.Session()
172 s.headers['User-Agent'] = 'PAN GlobalProtect'
175 if2prelogin = {'portal':'global-protect/prelogin.esp','gateway':'ssl-vpn/prelogin.esp'}
176 if2auth = {'portal':'global-protect/getconfig.esp','gateway':'ssl-vpn/login.esp'}
178 # query prelogin.esp and parse SAML bits
180 sam, uri, html = 'URI', args.server, None
182 endpoint = 'https://{}/{}'.format(args.server, if2prelogin[args.interface])
183 data = {'tmp':'tmp', 'kerberos-support':'yes', 'ipv6-support':'yes', 'clientVer':4100, 'clientos':args.clientos, **args.extra}
185 print("Looking for SAML auth tags in response to %s..." % endpoint, file=stderr)
187 res = s.post(endpoint, verify=args.verify, data=data)
188 except Exception as ex:
191 if isinstance(rootex, ssl.SSLError):
193 elif not rootex.__cause__ and not rootex.__context__:
195 rootex = rootex.__cause__ or rootex.__context__
196 if isinstance(rootex, ssl.CertificateError):
197 p.error("SSL certificate error (try --no-verify to ignore): %s" % rootex)
198 elif isinstance(rootex, ssl.SSLError):
199 p.error("SSL error: %s" % rootex)
202 xml = ET.fromstring(res.content)
203 if xml.tag != 'prelogin-response':
204 p.error("This does not appear to be a GlobalProtect prelogin response\nCheck in browser: {}?{}".format(endpoint, urlencode(data)))
205 sam = xml.find('saml-auth-method')
206 sr = xml.find('saml-request')
207 if sam is None or sr is None:
208 p.error("{} prelogin response does not contain SAML tags (<saml-auth-method> or <saml-request> missing)\n\n"
210 "1) Spoof an officially supported OS (e.g. --clientos=Windows or --clientos=Mac)\n"
211 "2) Check in browser: {}?{}".format(args.interface.title(), endpoint, urlencode(data)))
213 sr = a2b_base64(sr.text).decode()
216 elif sam == 'REDIRECT':
219 p.error("Unknown SAML method (%s)" % sam)
221 # launch external browser for debugging
223 print("Got SAML %s, opening external browser for debugging..." % sam, file=stderr)
226 uri = 'data:text/html;base64,' + b2a_base64(html.encode()).decode()
230 # spawn WebKit view to do SAML interactive login
232 print("Got SAML %s, opening browser..." % sam, file=stderr)
233 slv = SAMLLoginView(uri, html, verbose=args.verbose, cookies=args.cookies, verify=args.verify)
236 print("Login window closed by user.", file=stderr)
239 p.error('''Login window closed without producing SAML cookies.''')
241 # extract response and convert to OpenConnect command-line
242 un = slv.saml_result.get('saml-username')
243 server = slv.saml_result.get('server', args.server)
245 for cn, ifh in (('prelogin-cookie','gateway'), ('portal-userauthcookie','portal')):
246 cv = slv.saml_result.get(cn)
251 p.error("Didn't get an expected cookie. Something went wrong.")
254 # Warn about ambiguities
255 if server != args.server and not args.uri:
256 print('''IMPORTANT: During the SAML auth, you were redirected from {} to {}. This probably'''
257 '''means you should specify {} as the server for final connection, but we're not 100%'''
258 '''sure about this. You should probably try both.\n'''.format(args.server, server), file=stderr)
259 if ifh != args.interface and not args.uri:
260 print('''IMPORTANT: We started with SAML auth to the {} interface, but received a cookie'''
261 '''that's associated with the {} interface. You should probably try both.\n'''.format(args.interface, ifh),
264 print('''\nSAML response converted to OpenConnect command line invocation:\n''', file=stderr)
265 print(''' echo {} |\n openconnect --protocol=gp --user={} --usergroup={}:{} --passwd-on-stdin {}'''.format(
266 quote(cv), quote(un), quote(ifh), quote(cn), quote(server)), file=stderr)
268 print('''\nSAML response converted to test-globalprotect-login.py invocation:\n''', file=stderr)
269 print(''' test-globalprotect-login.py --user={} -p '' \\\n https://{}{} {}={}\n'''.format(
270 quote(un), quote(server), quote(if2auth[ifh]), quote(cn), quote(cv)), file=stderr)
273 'HOST': quote('https://%s/%s:%s' % (server, if2auth[ifh], cn)),
274 'USER': quote(un), 'COOKIE': quote(cv),
276 print('\n'.join('%s=%s' % pair for pair in varvals.items()))