This file is indexed.

/usr/lib/python3/dist-packages/adal/mex.py is in python3-adal 0.4.6-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
#------------------------------------------------------------------------------
#
# Copyright (c) Microsoft Corporation. 
# All rights reserved.
# 
# This code is licensed under the MIT License.
# 
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files(the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions :
# 
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
#------------------------------------------------------------------------------

try:
    from urllib.parse import urlparse
except ImportError:
    from urlparse import urlparse # pylint: disable=import-error

try:
    from xml.etree import cElementTree as ET
except ImportError:
    from xml.etree import ElementTree as ET

import requests

from . import log
from . import util
from . import xmlutil
from .constants import XmlNamespaces, WSTrustVersion
from .adal_error import AdalError

TRANSPORT_BINDING_XPATH = 'wsp:ExactlyOne/wsp:All/sp:TransportBinding'
TRANSPORT_BINDING_2005_XPATH = 'wsp:ExactlyOne/wsp:All/sp2005:TransportBinding' #pylint: disable=invalid-name

SOAP_ACTION_XPATH = 'wsdl:operation/soap12:operation'
RST_SOAP_ACTION_13 = 'http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Issue'
RST_SOAP_ACTION_2005 = 'http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue' #pylint: disable=invalid-name
SOAP_TRANSPORT_XPATH = 'soap12:binding'
SOAP_HTTP_TRANSPORT_VALUE = 'http://schemas.xmlsoap.org/soap/http'

PORT_XPATH = 'wsdl:service/wsdl:port'
ADDRESS_XPATH = 'wsa10:EndpointReference/wsa10:Address'

def _url_is_secure(endpoint_url):
    parsed = urlparse(endpoint_url)
    return parsed.scheme == 'https'

class Mex(object):

    def __init__(self, call_context, url):

        self._log = log.Logger("MEX", call_context.get('log_context'))
        self._call_context = call_context
        self._url = url
        self._dom = None
        self._parents = None
        self._mex_doc = None
        self.username_password_policy = {}
        self._log.debug("Mex created with url: %s", self._url)

    def discover(self):
        self._log.debug("Retrieving mex at: %s", self._url)
        options = util.create_request_options(self, {'headers': {'Content-Type': 'application/soap+xml'}})

        try:
            operation = "Mex Get"
            resp = requests.get(self._url, headers=options['headers'],
                                verify=self._call_context.get('verify_ssl', None))
            util.log_return_correlation_id(self._log, operation, resp)
        except Exception:
            self._log.info("%s request failed", operation)
            raise

        if not util.is_http_success(resp.status_code):
            return_error_string = u"{} request returned http error: {}".format(operation, resp.status_code)
            error_response = ""
            if resp.text:
                return_error_string = u"{} and server response: {}".format(return_error_string, resp.text)
                try:
                    error_response = resp.json()
                except ValueError:
                    pass
            raise AdalError(return_error_string, error_response)
        else:
            try:
                self._mex_doc = resp.text
                #options = {'errorHandler':self._log.error}
                self._dom = ET.fromstring(self._mex_doc)
                self._parents = {c:p for p in self._dom.iter() for c in p}
                self._parse()
            except Exception:
                self._log.info('Failed to parse mex response in to DOM')
                raise

    def _check_policy(self, policy_node):
        policy_id = policy_node.attrib["{{{}}}Id".format(XmlNamespaces.namespaces['wsu'])]
        
        # Try with Transport Binding XPath
        transport_binding_nodes = xmlutil.xpath_find(policy_node, TRANSPORT_BINDING_XPATH)
        
        # If unsuccessful, try again with 2005 XPath
        if not transport_binding_nodes:
            transport_binding_nodes = xmlutil.xpath_find(policy_node, TRANSPORT_BINDING_2005_XPATH)

        # If we did not find any binding, this is potentially bad.
        if not transport_binding_nodes:
            self._log.debug(
                "Potential policy did not match required transport binding: %s", 
                policy_id)
        else:
            self._log.debug("Found matching policy id: %s", policy_id)

        return policy_id

    def _select_username_password_polices(self, xpath):

        policies = {}
        username_token_nodes = xmlutil.xpath_find(self._dom, xpath)
        if not username_token_nodes:
            self._log.warn("No username token policy nodes found.")
            return

        for node in username_token_nodes:
            policy_node = self._parents[self._parents[self._parents[self._parents[self._parents[self._parents[self._parents[node]]]]]]]
            policy_id = self._check_policy(policy_node)
            if policy_id:
                id_ref = '#' + policy_id
                policies[id_ref] = {id:id_ref}

        return policies if policies else None

    def _check_soap_action_and_transport(self, binding_node):

        soap_action = ""
        soap_transport = ""
        name = binding_node.get('name')

        soap_transport_attributes = ""
        soap_action_attributes = xmlutil.xpath_find(binding_node, SOAP_ACTION_XPATH)[0].attrib['soapAction']

        if soap_action_attributes:
            soap_action = soap_action_attributes
            soap_transport_attributes = xmlutil.xpath_find(binding_node, SOAP_TRANSPORT_XPATH)[0].attrib['transport']

        if soap_transport_attributes:
            soap_transport = soap_transport_attributes

        if soap_transport == SOAP_HTTP_TRANSPORT_VALUE:
            if soap_action == RST_SOAP_ACTION_13:
                self._log.debug('found binding matching Action and Transport: %s', name)
                return WSTrustVersion.WSTRUST13
            elif soap_action == RST_SOAP_ACTION_2005:
                self._log.debug('found binding matching Action and Transport: %s', name)
                return WSTrustVersion.WSTRUST2005

        self._log.debug('binding node did not match soap Action or Transport: %s', name)
        return WSTrustVersion.UNDEFINED

    def _get_matching_bindings(self, policies):

        bindings = {}
        binding_policy_ref_nodes = xmlutil.xpath_find(self._dom, 'wsdl:binding/wsp:PolicyReference')

        for node in binding_policy_ref_nodes:
            uri = node.get('URI')
            policy = policies.get(uri)
            if policy:
                binding_node = self._parents[node]
                binding_name = binding_node.get('name')

                version = self._check_soap_action_and_transport(binding_node)
                if version != WSTrustVersion.UNDEFINED:                  
                    bindings[binding_name] = {
                        'url': uri,
                        'version': version
                        }

        return bindings if bindings else None

    def _get_ports_for_policy_bindings(self, bindings, policies):

        port_nodes = xmlutil.xpath_find(self._dom, PORT_XPATH)
        if not port_nodes:
            self._log.warn("No ports found")

        for node in port_nodes:
            binding_id = node.get('binding')
            binding_id = binding_id.split(':')[-1]

            trust_policy = bindings.get(binding_id)
            if trust_policy:
                binding_policy = policies.get(trust_policy.get('url'))
                if binding_policy and not binding_policy.get('url', None):
                    binding_policy['version'] = trust_policy['version']
                    address_node = node.find(ADDRESS_XPATH, XmlNamespaces.namespaces)
                    if address_node is None:
                        raise AdalError("No address nodes on port")

                    address = xmlutil.find_element_text(address_node)
                    if _url_is_secure(address):
                        binding_policy['url'] = address
                    else:
                        self._log.warn("Skipping insecure endpoint: %s", 
                                       address)

    def _select_single_matching_policy(self, policies):

        matching_policies = [p for p in policies.values() if p.get('url')]
        if not matching_policies:
            self._log.warn("No policies found with a url.")
            return

        wstrust13_policy = None
        wstrust2005_policy = None
        for policy in matching_policies:
            version = policy.get('version', None)
            if  version == WSTrustVersion.WSTRUST13:
                wstrust13_policy = policy
            elif version == WSTrustVersion.WSTRUST2005:
                wstrust2005_policy = policy

        if wstrust13_policy is None and wstrust2005_policy is None:
            self._log.warn('No policies found for either wstrust13 or wstrust2005')

        self.username_password_policy = wstrust13_policy or wstrust2005_policy

    def _parse(self):
        policies = self._select_username_password_polices(
            'wsp:Policy/wsp:ExactlyOne/wsp:All/sp:SignedEncryptedSupportingTokens/wsp:Policy/sp:UsernameToken/wsp:Policy/sp:WssUsernameToken10')

        xpath2005 = 'wsp:Policy/wsp:ExactlyOne/wsp:All/sp2005:SignedSupportingTokens/wsp:Policy/sp2005:UsernameToken/wsp:Policy/sp2005:WssUsernameToken10'       
        if policies:
            policies2005 = self._select_username_password_polices(xpath2005)
            if policies2005:
                policies.update(policies2005)
        else:
            policies = self._select_username_password_polices(xpath2005)

        if not policies:
            raise AdalError("No matching policies.")
            

        bindings = self._get_matching_bindings(policies)
        if not bindings:
            raise AdalError("No matching bindings.")

        self._get_ports_for_policy_bindings(bindings, policies)
        self._select_single_matching_policy(policies)

        if not self._url:
            raise AdalError("No ws-trust endpoints match requirements.")