Commit f4b1ce4c authored by Jorge Moratinos's avatar Jorge Moratinos
Browse files

Review of PSK security Method

parent ba2d275c
Loading
Loading
Loading
Loading
Loading
+5 −2
Changes for .gitignore: 5 added lines, 2 removed lines.
Original line number Diff line number Diff line
@@ -35,9 +35,12 @@ docs/testing_with_postman/package-lock.json

results

helm/capif/*.lock
helm/capif/charts/tempo*
helm/monitoring-stack/*.lock
helm/monitoring-stack/charts/tempo*
*.bakresults/
*.bak

helm/scripts/envs/*.env
services/envs/*.env

helm/vault_keys*.*
+104
Changes for services/TS29222_CAPIF_Security_API/capif_security/core/psk.py: 104 added lines, 0 removed lines.
Original line number Diff line number Diff line
"""AEF_PSK of the TLS-PSK security method (3GPP TS 33.122 clause 6.5.2.1 and Annex A).

The AEF_PSK is derived with the KDF of 3GPP TS 33.220 Annex B from the CAPIF-1e TLS 1.2 session
of the request that creates the security context:

    AEF_PSK = HMAC-SHA-256(master secret, FC || P0 || L0 || P1 || L1)

    FC = 0x7A, P0 = Service API interface information, P1 = TLS Session ID,
    L0/L1 = length of P0/P1 in octets, two octets big-endian.
"""
import hashlib
import hmac
import ipaddress
import unicodedata

# FC value allocated to TS 33.122 (TS 33.220 clause B.2.2)
AEF_PSK_FC = 0x7A
TLS_MASTER_SECRET_LENGTH = 48
TLS_MAX_SESSION_ID_LENGTH = 32
HTTPS_DEFAULT_PORT = 443
MAX_PARAMETER_LENGTH = 65535


def _value(interface, snake_case, camel_case):
    value = interface.get(snake_case)
    return interface.get(camel_case) if value is None else value


def interface_information(interface):
    """Service API interface information used as P0.

    TS 23.222 and TS 29.222 do not define a text encoding of the interface, so OpenCAPIF uses
    https://{host}[:{port}]{apiPrefix}, where host is the fqdn in lowercase, the IPv4 address or the
    IPv6 address in compressed form between brackets, and the port is omitted when it is 443 or absent.
    An AEF profile published without interfaces is identified by https://{domainName}.

    :param interface: InterfaceDescription as a dict (snake_case or camelCase keys) or the domainName
    :raises ValueError: when there is no interface or it has no address
    """
    if not interface:
        raise ValueError("No interface or domain name is available to derive the AEF_PSK")

    if isinstance(interface, str):
        return f"https://{interface.lower()}"

    fqdn = _value(interface, "fqdn", "fqdn")
    ipv4_addr = _value(interface, "ipv4_addr", "ipv4Addr")
    ipv6_addr = _value(interface, "ipv6_addr", "ipv6Addr")
    if fqdn:
        host = fqdn.lower()
    elif ipv4_addr:
        host = ipv4_addr
    elif ipv6_addr:
        try:
            host = f"[{ipaddress.IPv6Address(ipv6_addr).compressed}]"
        except ValueError:
            host = f"[{ipv6_addr.lower()}]"
    else:
        raise ValueError("The interface has no fqdn, ipv4Addr or ipv6Addr to derive the AEF_PSK")

    info = f"https://{host}"
    port = _value(interface, "port", "port")
    if port is not None and int(port) != HTTPS_DEFAULT_PORT:
        info += f":{int(port)}"
    return info + (_value(interface, "api_prefix", "apiPrefix") or "")


def tls_session_parameters(master_secret_hex, session_id_hex):
    """TLS master secret and Session ID in octets from their hexadecimal form (nginx headers).

    :raises ValueError: when they are missing or do not have the TLS 1.2 lengths
    """
    try:
        master_secret = bytes.fromhex(master_secret_hex or "")
        session_id = bytes.fromhex(session_id_hex or "")
    except ValueError as exc:
        raise ValueError(f"The TLS session parameters are not hexadecimal: {exc}") from exc

    if len(master_secret) != TLS_MASTER_SECRET_LENGTH:
        raise ValueError(f"The TLS master secret has {len(master_secret)} octets, "
                         f"{TLS_MASTER_SECRET_LENGTH} expected")
    if not 0 < len(session_id) <= TLS_MAX_SESSION_ID_LENGTH:
        raise ValueError(f"The TLS Session ID has {len(session_id)} octets, "
                         f"1 to {TLS_MAX_SESSION_ID_LENGTH} expected")
    return master_secret, session_id


def derive_aef_psk(master_secret, session_id, interface_info):
    """AEF_PSK (32 octets) with the KDF of TS 33.220 Annex B (FC 0x7A, TS 33.122 Annex A).

    :param master_secret: TLS master secret of the CAPIF-1e session, in octets
    :param session_id: TLS Session ID of the CAPIF-1e session, in octets
    :param interface_info: Service API interface information (see interface_information)
    """
    # Character strings are encoded in UTF-8 after NFKC normalization (TS 33.220 clause B.2.1.2)
    p0 = unicodedata.normalize("NFKC", interface_info).encode("utf-8")
    p1 = bytes(session_id)
    if len(p0) > MAX_PARAMETER_LENGTH:
        raise ValueError("The interface information is longer than 65535 octets")

    s = (bytes([AEF_PSK_FC])
         + p0 + len(p0).to_bytes(2, "big")
         + p1 + len(p1).to_bytes(2, "big"))
    return hmac.new(bytes(master_secret), s, hashlib.sha256).digest()
+188 −364

File changed.

Preview size limit exceeded, changes collapsed.

+89
Changes for services/TS29222_CAPIF_Security_API/capif_security/test/test_psk.py: 89 added lines, 0 removed lines.
Original line number Diff line number Diff line
"""Unit tests of the AEF_PSK derivation (3GPP TS 33.122 Annex A, KDF of TS 33.220 Annex B)."""
import hashlib
import hmac
import unittest

from capif_security.core.psk import derive_aef_psk, interface_information, tls_session_parameters

MASTER_SECRET = bytes(range(48))
SESSION_ID = bytes(range(0xA0, 0xC0))
INTERFACE_INFO = "https://aef.example.com:8443/psk"

# S = FC || P0 || L0 || P1 || L1, built by hand from the values above
KDF_INPUT = bytes.fromhex(
    "7a"
    "68747470733a2f2f6165662e6578616d706c652e636f6d3a383434332f70736b" "0020"
    "a0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebf" "0020")
AEF_PSK = bytes.fromhex("138dc84772619e798c388abc651e434f394afabd700169fd3d18df21a01e9ad8")


class TestInterfaceInformation(unittest.TestCase):

    def test_fqdn_with_port_and_api_prefix(self):
        interface = {"fqdn": "AEF.Example.com", "port": 8443, "api_prefix": "/psk"}
        self.assertEqual(interface_information(interface), "https://aef.example.com:8443/psk")

    def test_port_443_or_absent_is_omitted(self):
        self.assertEqual(interface_information({"fqdn": "aef.example.com", "port": 443}), "https://aef.example.com")
        self.assertEqual(interface_information({"fqdn": "aef.example.com"}), "https://aef.example.com")

    def test_ipv4_with_camel_case_keys(self):
        interface = {"ipv4Addr": "10.1.1.1", "port": 8080, "apiPrefix": "/api"}
        self.assertEqual(interface_information(interface), "https://10.1.1.1:8080/api")

    def test_ipv6_in_compressed_form(self):
        interface = {"ipv6_addr": "2001:0DB8:0000::1", "port": 9443}
        self.assertEqual(interface_information(interface), "https://[2001:db8::1]:9443")

    def test_null_attributes_are_ignored(self):
        interface = {"fqdn": None, "ipv4_addr": "10.1.1.1", "ipv6_addr": None, "port": None, "api_prefix": None}
        self.assertEqual(interface_information(interface), "https://10.1.1.1")

    def test_domain_name_of_a_profile_without_interfaces(self):
        self.assertEqual(interface_information("AEF.example.com"), "https://aef.example.com")

    def test_interface_without_address_is_rejected(self):
        for interface in (None, "", {}, {"port": 8443}):
            with self.assertRaises(ValueError):
                interface_information(interface)


class TestDeriveAefPsk(unittest.TestCase):

    def test_known_answer(self):
        self.assertEqual(derive_aef_psk(MASTER_SECRET, SESSION_ID, INTERFACE_INFO), AEF_PSK)

    def test_kdf_input_is_built_over_octets(self):
        self.assertEqual(derive_aef_psk(MASTER_SECRET, SESSION_ID, INTERFACE_INFO),
                         hmac.new(MASTER_SECRET, KDF_INPUT, hashlib.sha256).digest())

    def test_interface_information_is_nfkc_normalized(self):
        # Fullwidth letters are normalized to ASCII by NFKC (TS 33.220 clause B.2.1.2)
        self.assertEqual(derive_aef_psk(MASTER_SECRET, SESSION_ID, "https://aef.example.com:8443/psk"),
                         AEF_PSK)

    def test_each_interface_has_its_own_psk(self):
        self.assertNotEqual(derive_aef_psk(MASTER_SECRET, SESSION_ID, "https://aef2.example.com"), AEF_PSK)


class TestTlsSessionParameters(unittest.TestCase):

    def test_hexadecimal_headers_are_converted_to_octets(self):
        master_secret, session_id = tls_session_parameters(MASTER_SECRET.hex().upper(), SESSION_ID.hex())
        self.assertEqual((master_secret, session_id), (MASTER_SECRET, SESSION_ID))

    def test_invalid_parameters_are_rejected(self):
        invalid = [
            (None, SESSION_ID.hex()),
            (MASTER_SECRET[:32].hex(), SESSION_ID.hex()),  # not a TLS 1.2 master secret
            (MASTER_SECRET.hex(), ""),  # no Session ID
            (MASTER_SECRET.hex(), (SESSION_ID + b"\x00").hex()),  # longer than 32 octets
            ("not-hex", SESSION_ID.hex()),
        ]
        for master_secret_hex, session_id_hex in invalid:
            with self.assertRaises(ValueError):
                tls_session_parameters(master_secret_hex, session_id_hex)


if __name__ == "__main__":
    unittest.main()
+102
Changes for tests/features/CAPIF Security Api/capif_security_api.robot: 102 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -1317,3 +1317,105 @@ Retrieve Security Context from AEF using PKI-secured API Invoker

    # Check Results
    Dictionaries Should Be Equal    ${resp.json()}    ${service_security_context_filtered}

Retrieve Security Context from AEF using PSK-secured API Invoker
    [Tags]    capif_security_api-29    smoke
    # Default Invoker Registration and Onboarding
    ${register_user_info_invoker}    ${url}    ${request_body}=    Invoker Default Onboarding

    # Register Provider
    ${register_user_info_provider}=    Provider Default Registration

    # Publish Service API with an interface supporting PSK
    ${security_methods}=    Create List     PSK
    ${interface_description}=    Create Interface Description
    ...    fqdn=AEF.Example.com
    ...    port=${8443}
    ...    api_prefix=/psk
    ...    security_methods=${security_methods}
    ${interface_descriptions}=    Create List    ${interface_description}
    ${service_api_description_published_1}    ${resource_url}    ${request_body}=    Publish Service Api
    ...    ${register_user_info_provider}
    ...    service_1
    ...    security_methods=${security_methods}
    ...    interface_descriptions=${interface_descriptions}

    # Store apiId1
    ${service_api_id_1}=    Set Variable    ${service_api_description_published_1['apiId']}

    # Create Security Context over TLS 1.2, the AEF_PSK is derived from its master secret and Session ID
    ${request_body}=    Create Service Security Default Body
    ...    ${NOTIFICATION_DESTINATION_URL}
    ...    aef_id=${register_user_info_provider['aef_id']}
    ...    api_id=${service_api_id_1}
    ${resp}    ${tls_session}=    Request Capif Over Tls
    ...    PUT
    ...    /capif-security/v1/trustedInvokers/${register_user_info_invoker['api_invoker_id']}
    ...    json=${request_body}
    ...    server=${CAPIF_HTTPS_URL}
    ...    username=${INVOKER_USERNAME}
    ...    tls_version=TLSv1_2

    Check Response Variable Type And Values    ${resp}    201    ServiceSecurity
    ${resource_url}=    Check Location Header    ${resp}    ${LOCATION_SECURITY_RESOURCE_REGEX}

    # PSK is selected and the AEF_PSK is not returned to the API invoker
    Should Be Equal    ${resp.json()['securityInfo'][0]['selSecurityMethod']}    PSK
    Dictionary Should Not Contain Key    ${resp.json()['securityInfo'][0]}    authenticationInfo
    Dictionary Should Not Contain Key    ${resp.json()['securityInfo'][0]}    authorizationInfo

    # Retrieve Security context from the AEF with the authentication information
    ${resp}=    Get Request Capif
    ...    /capif-security/v1/trustedInvokers/${register_user_info_invoker['api_invoker_id']}?authenticationInfo=true&authorizationInfo=true
    ...    server=${CAPIF_HTTPS_URL}
    ...    verify=ca.crt
    ...    username=${AEF_PROVIDER_USERNAME}

    # Check Results
    Check Response Variable Type And Values    ${resp}    200    ServiceSecurity

    # authenticationInfo contains the AEF_PSK (TS 33.122 Annex A) derived for the interface of the AEF
    ${aef_psk}=    Derive Aef Psk
    ...    ${tls_session['master_secret']}
    ...    ${tls_session['session_id']}
    ...    https://aef.example.com:8443/psk
    Should Be Equal    ${resp.json()['securityInfo'][0]['authenticationInfo']}    ${aef_psk}
    Dictionary Should Not Contain Key    ${resp.json()['securityInfo'][0]}    authorizationInfo

Create a security context with PSK over TLS 1.3
    [Tags]    capif_security_api-30
    # Default Invoker Registration and Onboarding
    ${register_user_info_invoker}    ${url}    ${request_body}=    Invoker Default Onboarding

    # Register Provider
    ${register_user_info_provider}=    Provider Default Registration

    # Publish Service API only with PSK
    ${security_methods}=    Create List     PSK
    ${service_api_description_published_1}    ${resource_url}    ${request_body}=    Publish Service Api
    ...    ${register_user_info_provider}
    ...    service_1
    ...    security_methods=${security_methods}

    # Store apiId1
    ${service_api_id_1}=    Set Variable    ${service_api_description_published_1['apiId']}

    # Create Security Context over TLS 1.3, which has no master secret nor Session ID to derive the AEF_PSK
    ${request_body}=    Create Service Security Default Body
    ...    ${NOTIFICATION_DESTINATION_URL}
    ...    aef_id=${register_user_info_provider['aef_id']}
    ...    api_id=${service_api_id_1}
    ${resp}    ${tls_session}=    Request Capif Over Tls
    ...    PUT
    ...    /capif-security/v1/trustedInvokers/${register_user_info_invoker['api_invoker_id']}
    ...    json=${request_body}
    ...    server=${CAPIF_HTTPS_URL}
    ...    username=${INVOKER_USERNAME}
    ...    tls_version=TLSv1_3

    # Check Results
    Check Response Variable Type And Values    ${resp}    400    ProblemDetails
    ...    title=Bad Request
    ...    status=400
    ...    detail=The PSK security method requires the security context to be requested over TLS 1.2
    ...    cause=The AEF_PSK is derived from the TLS 1.2 master secret and session ID .*, but this request used TLSv1.3
Loading