8 import xml.etree.ElementTree as ET
12 from shlex import quote
13 from sys import stderr
14 from binascii import a2b_base64, b2a_base64
16 gi.require_version('Gtk', '3.0')
17 from gi.repository import Gtk
19 gi.require_version('WebKit2', '4.0')
20 from gi.repository import WebKit2
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
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', Gtk.main_quit)
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 log_resources(self, webview, resource, request):
56 print('%s for resource %s' % (request.get_http_method() or 'Request', resource.get_uri()), file=stderr)
58 def get_saml_headers(self, webview, event):
59 if event != WebKit2.LoadEvent.FINISHED:
62 mr = webview.get_main_resource()
64 print("Finished loading %s" % mr.get_uri(), file=stderr)
65 rs = mr.get_response()
66 h = rs.get_http_headers()
69 def listify(name, value, t=l):
70 if (name.startswith('saml-') or name in ('prelogin-cookie', 'portal-userauthcookie')):
71 t.append((name, value))
74 if d and self.verbose:
75 print("Got SAML result headers: %r" % d, file=stderr)
78 if 'saml-username' in d and ('prelogin-cookie' in d or 'portal-userauthcookie' in d):
79 print("Got all required SAML headers, done.", file=stderr)
83 def parse_args(args = None):
84 p = argparse.ArgumentParser()
85 p.add_argument('server', help='GlobalProtect server (portal or gateway)')
86 p.add_argument('--no-verify', dest='verify', action='store_false', default=True, help='Ignore invalid server certificate')
87 p.add_argument('-C', '--no-cookies', dest='cookies', action='store_const', const=None,
88 default='~/.gp-saml-gui-cookies', help="Don't use cookies (stored in %(default)s)")
89 x = p.add_mutually_exclusive_group()
90 x.add_argument('-p','--portal', dest='portal', action='store_true', help='SAML auth to portal')
91 x.add_argument('-g','--gateway', dest='portal', action='store_false', help='SAML auth to gateway (default)')
92 g = p.add_argument_group('Client certificate')
93 g.add_argument('-c','--cert', help='PEM file containing client certificate (and optionally private key)')
94 g.add_argument('--key', help='PEM file containing client private key (if not included in same file as certificate)')
95 g = p.add_argument_group('Debugging and advanced options')
96 g.add_argument('-v','--verbose', default=0, action='count')
97 g.add_argument('-x','--external', action='store_true', help='Launch external browser (for debugging)')
98 g.add_argument('-u','--uri', action='store_true', help='Treat server as the complete URI of the SAML entry point, rather than GlobalProtect server')
99 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")')
100 args = p.parse_args(args = None)
102 args.extra = dict(x.split('=', 1) for x in args.extra)
105 args.cookies = os.path.expanduser(args.cookies)
107 if args.cert and args.key:
108 args.cert, args.key = (args.cert, args.key), None
110 args.cert = (args.cert, None)
112 p.error('--key specified without --cert')
118 if __name__ == "__main__":
119 p, args = parse_args()
121 s = requests.Session()
122 s.headers['User-Agent'] = 'PAN GlobalProtect'
125 # query prelogin.esp and parse SAML bits
127 sam, uri, html = 'URI', args.server, None
129 endpoint = 'https://{}/{}/prelogin.esp'.format(args.server, ('global-protect' if args.portal else 'ssl-vpn'))
130 print("Looking for SAML auth tags in response to %s..." % endpoint, file=stderr)
132 res = s.post(endpoint, verify=args.verify, data=args.extra)
133 except Exception as ex:
136 if isinstance(rootex, ssl.SSLError):
138 elif not rootex.__cause__ and not rootex.__context__:
140 rootex = rootex.__cause__ or rootex.__context__
141 if isinstance(rootex, ssl.CertificateError):
142 p.error("SSL certificate error (try --no-verify to ignore): %s" % rootex)
143 elif isinstance(rootex, ssl.SSLError):
144 p.error("SSL error: %s" % rootex)
147 xml = ET.fromstring(res.content)
148 sam = xml.find('saml-auth-method')
149 sr = xml.find('saml-request')
150 if sam is None or sr is None:
151 p.error("This does not appear to be a SAML prelogin response (<saml-auth-method> or <saml-request> tags missing)")
153 sr = a2b_base64(sr.text).decode()
156 elif sam == 'REDIRECT':
159 p.error("Unknown SAML method (%s)" % sam)
161 # launch external browser for debugging
163 print("Got SAML %s, opening external browser for debugging..." % sam, file=stderr)
166 uri = 'data:text/html;base64,' + b2a_base64(html.encode()).decode()
170 # spawn WebKit view to do SAML interactive login
172 print("Got SAML %s, opening browser..." % sam, file=stderr)
173 slv = SAMLLoginView(uri, html, verbose=args.verbose, cookies=args.cookies, verify=args.verify)
176 p.error('''Login window closed without producing SAML cookie''')
178 # extract response and convert to OpenConnect command-line
179 un = slv.saml_result.get('saml-username')
180 for cn in ('prelogin-cookie', 'portal-userauthcookie'):
181 cv = slv.saml_result.get(cn)
187 fullpath = ('/global-protect/getconfig.esp' if args.portal else '/ssl-vpn/login.esp')
188 shortpath = ('portal' if args.portal else 'gateway')
190 print('''\n\nSAML response converted to OpenConnect command line invocation:\n''', file=stderr)
191 print(''' echo {} |\n openconnect --protocol=gp --user={} --usergroup={}:{} --passwd-on-stdin {}\n'''.format(
192 quote(cv), quote(un), quote(shortpath), quote(cn), quote(args.server)), file=stderr)
195 'HOST': quote('https://%s/%s:%s' % (args.server, shortpath, cn)),
196 'USER': quote(un), 'COOKIE': quote(cv),
198 print('\n'.join('%s=%s' % pair for pair in varvals.items()))