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
28 self.verbose = verbose
30 self.ctx = WebKit2.WebContext.get_default()
31 self.cookies = self.ctx.get_cookie_manager()
33 self.cookies.set_accept_policy(WebKit2.CookieAcceptPolicy.ALWAYS)
34 self.cookies.set_persistent_storage(args.cookies, WebKit2.CookiePersistentStorage.TEXT)
35 self.wview = WebKit2.WebView()
37 window.resize(500, 500)
38 window.add(self.wview)
40 window.set_title("SAML Login")
41 window.connect('delete-event', Gtk.main_quit)
42 self.wview.connect('load-changed', self.get_saml_headers)
43 self.wview.connect('resource-load-started', self.log_resources)
46 self.wview.load_html(html, uri)
48 self.wview.load_uri(uri)
50 def log_resources(self, webview, resource, request):
52 print('%s for resource %s' % (request.get_http_method() or 'Request', resource.get_uri()), file=stderr)
54 def get_saml_headers(self, webview, event):
55 if event != WebKit2.LoadEvent.FINISHED:
58 mr = webview.get_main_resource()
60 print("Finished loading %s" % mr.get_uri(), file=stderr)
61 rs = mr.get_response()
62 h = rs.get_http_headers()
65 def listify(name, value, t=l):
66 if (name.startswith('saml-') or name in ('prelogin-cookie', 'portal-userauthcookie')):
67 t.append((name, value))
70 if d and self.verbose:
71 print("Got SAML result headers: %r" % d, file=stderr)
74 if 'saml-username' in d and ('prelogin-cookie' in d or 'portal-userauthcookie' in d):
75 print("Got all required SAML headers, done.", file=stderr)
79 def parse_args(args = None):
80 p = argparse.ArgumentParser()
81 p.add_argument('server', help='GlobalProtect server (portal or gateway)')
82 p.add_argument('--no-verify', dest='verify', action='store_false', default=True, help='Ignore invalid server certificate')
83 p.add_argument('-C', '--no-cookies', dest='cookies', action='store_const', const=None,
84 default='~/.gp-saml-gui-cookies', help="Don't use cookies (stored in %(default)s)")
85 x = p.add_mutually_exclusive_group()
86 x.add_argument('-p','--portal', dest='portal', action='store_true', help='SAML auth to portal')
87 x.add_argument('-g','--gateway', dest='portal', action='store_false', help='SAML auth to gateway (default)')
88 g = p.add_argument_group('Client certificate')
89 g.add_argument('-c','--cert', help='PEM file containing client certificate (and optionally private key)')
90 g.add_argument('--key', help='PEM file containing client private key (if not included in same file as certificate)')
91 g = p.add_argument_group('Debugging and advanced options')
92 g.add_argument('-v','--verbose', default=0, action='count')
93 g.add_argument('-x','--external', action='store_true', help='Launch external browser (for debugging)')
94 g.add_argument('-u','--uri', action='store_true', help='Treat server as the complete URI of the SAML entry point, rather than GlobalProtect server')
95 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")')
96 args = p.parse_args(args = None)
98 args.extra = dict(x.split('=', 1) for x in args.extra)
101 args.cookies = os.path.expanduser(args.cookies)
103 if args.cert and args.key:
104 args.cert, args.key = (args.cert, args.key), None
106 args.cert = (args.cert, None)
108 p.error('--key specified without --cert')
114 if __name__ == "__main__":
115 p, args = parse_args()
117 s = requests.Session()
118 s.headers['User-Agent'] = 'PAN GlobalProtect'
121 # query prelogin.esp and parse SAML bits
123 sam, uri, html = 'URI', args.server, None
125 endpoint = 'https://{}/{}/prelogin.esp'.format(args.server, ('global-protect' if args.portal else 'ssl-vpn'))
126 res = s.post(endpoint, verify=args.verify, data=args.extra)
127 xml = ET.fromstring(res.content)
128 sam = xml.find('saml-auth-method')
129 sr = xml.find('saml-request')
130 if sam is None or sr is None:
131 p.error("This does not appear to be a SAML prelogin response (<saml-auth-method> or <saml-request> tags missing)")
133 sr = a2b_base64(sr.text).decode()
136 elif sam == 'REDIRECT':
139 p.error("Unknown SAML method (%s)" % sam)
141 # launch external browser for debugging
143 print("Got SAML %s, opening external browser for debugging..." % sam, file=stderr)
146 uri = 'data:text/html;base64,' + b2a_base64(html.encode()).decode()
150 # spawn WebKit view to do SAML interactive login
152 print("Got SAML %s, opening browser..." % sam, file=stderr)
153 slv = SAMLLoginView(uri, html, verbose=args.verbose, cookies=args.cookies)
156 p.error('''Login window closed without producing SAML cookie''')
158 # extract response and convert to OpenConnect command-line
159 un = slv.saml_result.get('saml-username')
160 for cn in ('prelogin-cookie', 'portal-userauthcookie'):
161 cv = slv.saml_result.get(cn)
168 print('''\n\nSAML response converted to OpenConnect command line invocation:\n''', file=stderr)
169 print(''' echo {!r} |\n openconnect --protocol=gp --user={!r} --usergroup={}:{} --passwd-on-stdin {}\n'''.format(
170 cv, un, ('portal' if args.portal else 'gateway'), cn, args.server), file=stderr)
172 print("HOST={!r}\nUSER={!r}\nCOOKIE={!r}".format('https://%s/%s:%s' % (args.server, ('portal' if args.portal else 'gateway'), cn), un, cv))