8 import xml.etree.ElementTree as ET
 
  11 from shlex import quote
 
  12 from sys import stderr
 
  13 from binascii import a2b_base64, b2a_base64
 
  15 gi.require_version('Gtk', '3.0')
 
  16 from gi.repository import Gtk
 
  18 gi.require_version('WebKit2', '4.0')
 
  19 from gi.repository import WebKit2
 
  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
 
  29         self.verbose = verbose
 
  31         self.ctx = WebKit2.WebContext.get_default()
 
  33             self.ctx.set_tls_errors_policy(WebKit2.TLSErrorsPolicy.IGNORE)
 
  34         self.cookies = self.ctx.get_cookie_manager()
 
  36             self.cookies.set_accept_policy(WebKit2.CookieAcceptPolicy.ALWAYS)
 
  37             self.cookies.set_persistent_storage(args.cookies, WebKit2.CookiePersistentStorage.TEXT)
 
  38         self.wview = WebKit2.WebView()
 
  40         window.resize(500, 500)
 
  41         window.add(self.wview)
 
  43         window.set_title("SAML Login")
 
  44         window.connect('delete-event', Gtk.main_quit)
 
  45         self.wview.connect('load-changed', self.get_saml_headers)
 
  46         self.wview.connect('resource-load-started', self.log_resources)
 
  49             self.wview.load_html(html, uri)
 
  51             self.wview.load_uri(uri)
 
  53     def log_resources(self, webview, resource, request):
 
  55             print('%s for resource %s' % (request.get_http_method() or 'Request', resource.get_uri()), file=stderr)
 
  57     def get_saml_headers(self, webview, event):
 
  58         if event != WebKit2.LoadEvent.FINISHED:
 
  61         mr = webview.get_main_resource()
 
  63             print("Finished loading %s" % mr.get_uri(), file=stderr)
 
  64         rs = mr.get_response()
 
  65         h = rs.get_http_headers()
 
  68             def listify(name, value, t=l):
 
  69                 if (name.startswith('saml-') or name in ('prelogin-cookie', 'portal-userauthcookie')):
 
  70                     t.append((name, value))
 
  73             if d and self.verbose:
 
  74                 print("Got SAML result headers: %r" % d, file=stderr)
 
  77             if 'saml-username' in d and ('prelogin-cookie' in d or 'portal-userauthcookie' in d):
 
  78                 print("Got all required SAML headers, done.", file=stderr)
 
  82 def parse_args(args = None):
 
  83     p = argparse.ArgumentParser()
 
  84     p.add_argument('server', help='GlobalProtect server (portal or gateway)')
 
  85     p.add_argument('--no-verify', dest='verify', action='store_false', default=True, help='Ignore invalid server certificate')
 
  86     p.add_argument('-C', '--no-cookies', dest='cookies', action='store_const', const=None,
 
  87                    default='~/.gp-saml-gui-cookies', help="Don't use cookies (stored in %(default)s)")
 
  88     x = p.add_mutually_exclusive_group()
 
  89     x.add_argument('-p','--portal', dest='portal', action='store_true', help='SAML auth to portal')
 
  90     x.add_argument('-g','--gateway', dest='portal', action='store_false', help='SAML auth to gateway (default)')
 
  91     g = p.add_argument_group('Client certificate')
 
  92     g.add_argument('-c','--cert', help='PEM file containing client certificate (and optionally private key)')
 
  93     g.add_argument('--key', help='PEM file containing client private key (if not included in same file as certificate)')
 
  94     g = p.add_argument_group('Debugging and advanced options')
 
  95     g.add_argument('-v','--verbose', default=0, action='count')
 
  96     g.add_argument('-x','--external', action='store_true', help='Launch external browser (for debugging)')
 
  97     g.add_argument('-u','--uri', action='store_true', help='Treat server as the complete URI of the SAML entry point, rather than GlobalProtect server')
 
  98     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")')
 
  99     args = p.parse_args(args = None)
 
 101     args.extra = dict(x.split('=', 1) for x in args.extra)
 
 104         args.cookies = os.path.expanduser(args.cookies)
 
 106     if args.cert and args.key:
 
 107         args.cert, args.key = (args.cert, args.key), None
 
 109         args.cert = (args.cert, None)
 
 111         p.error('--key specified without --cert')
 
 117 if __name__ == "__main__":
 
 118     p, args = parse_args()
 
 120     s = requests.Session()
 
 121     s.headers['User-Agent'] = 'PAN GlobalProtect'
 
 124     # query prelogin.esp and parse SAML bits
 
 126         sam, uri, html = 'URI', args.server, None
 
 128         endpoint = 'https://{}/{}/prelogin.esp'.format(args.server, ('global-protect' if args.portal else 'ssl-vpn'))
 
 129         res = s.post(endpoint, verify=args.verify, data=args.extra)
 
 130         xml = ET.fromstring(res.content)
 
 131         sam = xml.find('saml-auth-method')
 
 132         sr = xml.find('saml-request')
 
 133         if sam is None or sr is None:
 
 134             p.error("This does not appear to be a SAML prelogin response (<saml-auth-method> or <saml-request> tags missing)")
 
 136         sr = a2b_base64(sr.text).decode()
 
 139         elif sam == 'REDIRECT':
 
 142             p.error("Unknown SAML method (%s)" % sam)
 
 144     # launch external browser for debugging
 
 146         print("Got SAML %s, opening external browser for debugging..." % sam, file=stderr)
 
 149             uri = 'data:text/html;base64,' + b2a_base64(html.encode()).decode()
 
 153     # spawn WebKit view to do SAML interactive login
 
 155         print("Got SAML %s, opening browser..." % sam, file=stderr)
 
 156     slv = SAMLLoginView(uri, html, verbose=args.verbose, cookies=args.cookies, verify=args.verify)
 
 159         p.error('''Login window closed without producing SAML cookie''')
 
 161     # extract response and convert to OpenConnect command-line
 
 162     un = slv.saml_result.get('saml-username')
 
 163     for cn in ('prelogin-cookie', 'portal-userauthcookie'):
 
 164         cv = slv.saml_result.get(cn)
 
 170     fullpath = ('/global-protect/getconfig.esp' if args.portal else '/ssl-vpn/login.esp')
 
 171     shortpath = ('portal' if args.portal else 'gateway')
 
 173         print('''\n\nSAML response converted to OpenConnect command line invocation:\n''', file=stderr)
 
 174         print('''    echo {} |\n        openconnect --protocol=gp --user={} --usergroup={}:{} --passwd-on-stdin {}\n'''.format(
 
 175             quote(cv), quote(un), quote(shortpath), quote(cn), quote(args.server)), file=stderr)
 
 178         'HOST': quote('https://%s/%s:%s' % (args.server, shortpath, cn)),
 
 179         'USER': quote(un), 'COOKIE': quote(cv),
 
 181     print('\n'.join('%s=%s' % pair for pair in varvals.items()))