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