SIP (Session Initiation Protocol) - HackTricks

# SIP (Session Initiation Protocol)

> [!TIP] Learn & practice AWS Hacking:HackTricks Training AWS Red Team Expert (ARTE)
> Learn & practice GCP Hacking: HackTricks Training GCP Red Team Expert (GRTE)

> Support HackTricks
> - Check the subscription plans!
> - Join the 💬 Discord group or the telegram group or follow us on Twitter 🐦 @hacktricks_live.
> - Share hacking tricks by submitting PRs to the HackTricks and HackTricks Cloud github repos.

## Basic Information

SIP (Session Initiation Protocol) is a signaling and call control protocol widely used for establishing, modifying, and terminating multimedia sessions, including voice, video, and instant messaging, over IP networks. Developed by the Internet Engineering Task Force (IETF), SIP is defined in RFC 3261 and has become the de facto standard for VoIP and unified communications.

Some key features of SIP include:

1. Text-based Protocol: SIP is a text-based protocol, which makes it human-readable and easier to debug. It is based on a request-response model, similar to HTTP, and uses methods like INVITE, ACK, BYE, and CANCEL for controlling call sessions.
2. Scalability and Flexibility: SIP is highly scalable and can be used in small-scale deployments as well as large enterprise and carrier-grade environments. It can be easily extended with new features, making it adaptable to various use cases and requirements.
3. Interoperability: SIP's widespread adoption and standardization ensure better interoperability between different devices, applications, and service providers, promoting seamless communication across various platforms.
4. Modular Design: SIP works with other protocols like RTP (Real-time Transport Protocol) for media transmission and SDP (Session Description Protocol) for describing multimedia sessions. This modular design allows for greater flexibility and compatibility with different media types and codecs.
5. Proxy and Redirect Servers: SIP can use proxy and redirect servers to facilitate call routing and provide advanced features like call forwarding, call transfer, and voicemail services.
6. Presence and Instant Messaging: SIP is not limited to voice and video communication. It also supports presence and instant messaging, enabling a wide range of unified communication applications.

Despite its many advantages, SIP can be complex to configure and manage, particularly when dealing with NAT traversal and firewall issues. However, its versatility, scalability, and extensive support across the industry make it a popular choice for VoIP and multimedia communication.

### SIP Methods

The core SIP methods defined in RFC 3261 include:

1. INVITE: Used to initiate a new session (call) or modify an existing one. The INVITE method carries the session description (typically using SDP) to inform the recipient about the details of the proposed session, such as media types, codecs, and transport protocols.
2. ACK: Sent to confirm the receipt of a final response to an INVITE request. The ACK method ensures the reliability of INVITE transactions by providing end-to-end acknowledgement.
3. BYE: Used to terminate an established session (call). The BYE method is sent by either party in the session to indicate that they wish to end the communication.
4. CANCEL: Sent to cancel a pending INVITE request before the session is established. The CANCEL method allows the sender to abort an INVITE transaction if they change their mind or if there is no response from the recipient.
5. OPTIONS: Used to query the capabilities of a SIP server or user agent. The OPTIONS method can be sent to request information about supported methods, media types, or other extensions without actually establishing a session.
6. REGISTER: Used by a user agent to register its current location with a SIP registrar server. The REGISTER method helps in maintaining an up-to-date mapping between a user's SIP URI and their current IP address, enabling call routing and delivery.

> [!WARNING] Note that to call someone it's not neccesary to use the REGISTER for anything.
> However, it's possible that in order to perform an INVITE the caller needs to authenticate first or he will receive a `401 Unauthorized` response.

In addition to these core methods, there are several SIP extension methods defined in other RFCs, such as:

1. SUBSCRIBE: Defined in RFC 6665, the SUBSCRIBE method is used to request notifications about the state of a specific resource, such as a user's presence or call status.
2. NOTIFY: Also defined in RFC 6665, the NOTIFY method is sent by a server to inform a subscribed user agent about changes in the state of a monitored resource.
3. REFER: Defined in RFC 3515, the REFER method is used to request that the recipient performs a transfer or refers to a third party. This is typically used for call transfer scenarios.
4. MESSAGE: Defined in RFC 3428, the MESSAGE method is used to send instant messages between SIP user agents, enabling text-based communication within the SIP framework.
5. UPDATE: Defined in RFC 3311, the UPDATE method allows modifying a session without affecting the state of the existing dialog. This is useful for updating session parameters, such as codecs or media types, during an ongoing call.
6. PUBLISH: Defined in RFC 3903, the PUBLISH method is used by a user agent to publish event state information to a server, making it available to other interested parties.

### SIP Response Codes

- 1xx (Provisional Responses): These responses indicate that the request was received, and the server is continuing to process it.
  - 100 Trying: The request was received, and the server is working on it.
  - 180 Ringing: The callee is being alerted and will take the call.
  - 183 Session Progress: Provides information about the progress of the call.
- 2xx (Successful Responses): These responses indicate that the request was successfully received, understood, and accepted.
  - 200 OK: The request was successful, and the server has fulfilled it.
  - 202 Accepted: The request was accepted for processing, but it hasn't been completed yet.
- 3xx (Redirection Responses): These responses indicate that further action is required to fulfill the request, typically by contacting an alternate resource.
  - 300 Multiple Choices: There are multiple options available, and the user or client must choose one.
  - 301 Moved Permanently: The requested resource has been assigned a new permanent URI.
  - 302 Moved Temporarily: The requested resource is temporarily available at a different URI.
  - 305 Use Proxy: The request must be sent to a specified proxy.
- 4xx (Client Error Responses): These responses indicate that the request contains bad syntax or cannot be fulfilled by the server.
  - 400 Bad Request: The request was malformed or invalid.
  - 401 Unauthorized: The request requires user authentication.
  - 403 Forbidden: The server understood the request but refuses to fulfill it.
  - 404 Not Found: The requested resource was not found on the server.
  - 408 Request Timeout: The server did not receive a complete request within the time it was prepared to wait.
  - 486 Busy Here: The callee is currently busy and unable to take the call.
- 5xx (Server Error Responses): These responses indicate that the server failed to fulfill a valid request.
  - 500 Internal Server Error: The server encountered an error while processing the request.
  - 501 Not Implemented: The server does not support the functionality required to fulfill the request.
  - 503 Service Unavailable: The server is currently unable to handle the request due to maintenance or overload.
- 6xx (Global Failure Responses): These responses indicate that the request cannot be fulfilled by any server.
  - 600 Busy Everywhere: All possible destinations for the call are busy.
  - 603 Decline: The callee does not wish to participate in the call.
  - 604 Does Not Exist Anywhere: The requested resource is not available anywhere in the network.

## Examples

### SIP INVITE Example

    INVITE sip:jdoe@example.com SIP/2.0
    Via: SIP/2.0/UDP pc33.example.com;branch=z9hG4bK776asdhds
    Max-Forwards: 70
    To: John Doe <sip:jdoe@example.com>
    From: Jane Smith <sip:jsmith@example.org>;tag=1928301774
    Call-ID: a84b4c76e66710
    CSeq: 314159 INVITE
    Contact: <sip:jsmith@pc33.example.com>
    User-Agent: ExampleSIPClient/1.0
    Allow: INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, NOTIFY, MESSAGE, SUBSCRIBE, INFO
    Content-Type: application/sdp
    Content-Length: 142

    v=0
    o=jsmith 2890844526 2890842807 IN IP4 pc33.example.com
    s=-
    c=IN IP4 pc33.example.com
    t=0 0
    m=audio 49170 RTP/AVP 0
    a=rtpmap:0 PCMU/8000te

Each Param Explained

1. Request-Line: `INVITE sip:jdoe@example.com SIP/2.0` - This line indicates the method (INVITE), the request URI (sip:jdoe@example.com), and the SIP version (SIP/2.0).
2. Via: `Via: SIP/2.0/UDP pc33.example.com;branch=z9hG4bK776asdhds` - The Via header specifies the transport protocol (UDP) and the client's address (pc33.example.com). The "branch" parameter is used for loop detection and transaction matching.
3. Max-Forwards: `Max-Forwards: 70` - This header field limits the number of times the request can be forwarded by proxies to avoid infinite loops.
4. To: `To: John Doe <sip:jdoe@example.com>` - The To header specifies the recipient of the call, including their display name (John Doe) and SIP URI (sip:jdoe@example.com).
5. From: `From: Jane Smith <sip:jsmith@example.org>;tag=1928301774` - The From header specifies the sender of the call, including their display name (Jane Smith) and SIP URI (sip:jsmith@example.org). The "tag" parameter is used to uniquely identify the sender's role in the dialog.
6. Call-ID: `Call-ID: a84b4c76e66710` - The Call-ID header uniquely identifies a call session between two user agents.
7. CSeq: `CSeq: 314159 INVITE` - The CSeq header contains a sequence number and the method used in the request. It's used to match responses to requests and detect out-of-order messages.
8. Contact: `Contact: <sip:jsmith@pc33.example.com>` - The Contact header provides a direct route to the sender, which can be used for subsequent requests and responses.
9. User-Agent: `User-Agent: ExampleSIPClient/1.0` - The User-Agent header provides information about the software or hardware of the sender, including its name and version.
10. Allow: `Allow: INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, NOTIFY, MESSAGE, SUBSCRIBE, INFO` - The Allow header lists the SIP methods supported by the sender. This helps the recipient understand which methods can be used during the communication.
11. Content-Type: `Content-Type: application/sdp` - The Content-Type header specifies the media type of the message body, in this case, SDP (Session Description Protocol).
12. Content-Length: `Content-Length: 142` - The Content-Length header indicates the size of the message body in bytes.
13. Message Body: The message body contains the SDP session description, which includes information about the media types, codecs, and transport protocols for the proposed session.

- `v=0` - Protocol version (0 for SDP)
- `o=jsmith 2890844526 2890842807 IN IP4 pc33.example.com` - Originator and session identifier
- `s=-` - Session name (a single hyphen indicates no session name)
- `c=IN IP4 pc33.example.com` - Connection information (network type, address type, and address)
- `t=0 0` - Timing information (start and stop times, 0 0 means the session is not bounded)
- `m=audio 49170 RTP/AVP 0` - Media description (media type, port number, transport protocol, and format list). In this case, it specifies an audio stream using RTP/AVP (Real-time Transport Protocol / Audio Video Profile) and format 0 (PCMU/8000).
- `a=rtpmap:0 PCMU/8000` - Attribute mapping the format (0) to the codec (PCMU) and its clock rate (8000 Hz).

### SIP REGISTER Example

The REGISTER method is used in Session Initiation Protocol (SIP) to allow a user agent (UA), such as a VoIP phone or a softphone, to register its location with a SIP registrar server. This process lets the server know where to route incoming SIP requests destined for the registered user. The registrar server is usually part of a SIP proxy server or a dedicated registration server.

Here's a detailed example of the SIP messages involved in a REGISTER authentication process:

1. Initial REGISTER request from UA to the registrar server:

    REGISTER sip:example.com SIP/2.0
    Via: SIP/2.0/UDP 192.168.1.100:5060;branch=z9hG4bK776asdhds
    Max-Forwards: 70
    From: Alice <sip:alice@example.com>;tag=565656
    To: Alice <sip:alice@example.com>
    Call-ID: 1234567890@192.168.1.100
    CSeq: 1 REGISTER
    Contact: <sip:alice@192.168.1.100:5060>;expires=3600
    Expires: 3600
    Content-Length: 0

This initial REGISTER message is sent by the UA (Alice) to the registrar server. It includes important information such as the desired registration duration (Expires), the user's SIP URI (sip:alice@example.com), and the user's contact address (sip:alice@192.168.1.100:5060).

2. 401 Unauthorized response from the registrar server:

    cssCopy codeSIP/2.0 401 Unauthorized
    Via: SIP/2.0/UDP 192.168.1.100:5060;branch=z9hG4bK776asdhds
    From: Alice <sip:alice@example.com>;tag=565656
    To: Alice <sip:alice@example.com>;tag=7878744
    Call-ID: 1234567890@192.168.1.100
    CSeq: 1 REGISTER
    WWW-Authenticate: Digest realm="example.com", nonce="abcdefghijk", algorithm=MD5, qop="auth"
    Content-Length: 0

The registrar server responds with a "401 Unauthorized" message, which includes a "WWW-Authenticate" header. This header contains information required for the UA to authenticate itself, such as the authentication realm, nonce, and algorithm.

3. REGISTER request with authentication credentials:

    REGISTER sip:example.com SIP/2.0
    Via: SIP/2.0/UDP 192.168.1.100:5060;branch=z9hG4bK776asdhds
    Max-Forwards: 70
    From: Alice <sip:alice@example.com>;tag=565656
    To: Alice <sip:alice@example.com>
    Call-ID: 1234567890@192.168.1.100
    CSeq: 2 REGISTER
    Contact: <sip:alice@192.168.1.100:5060>;expires=3600
    Expires: 3600
    Authorization: Digest username="alice", realm="example.com", nonce="abcdefghijk", uri="sip:example.com", response="65a8e2285879283831b664bd8b7f14d4", algorithm=MD5, cnonce="lmnopqrst", qop=auth, nc=00000001
    Content-Length: 0

The UA sends another REGISTER request, this time including the "Authorization" header with the necessary credentials, such as the username, realm, nonce, and a response value calculated using the provided information and the user's password.

This is how the Authorizarion response is calculated:

    import hashlib

    def calculate_sip_md5_response(username, password, realm, method, uri, nonce, nc, cnonce, qop):
        # 1. Calculate HA1 (concatenation of username, realm, and password)
        ha1_input = f"{username}:{realm}:{password}"
        ha1 = hashlib.md5(ha1_input.encode()).hexdigest()

        # 2. Calculate HA2 (concatenation of method and uri)
        ha2_input = f"{method}:{uri}"
        ha2 = hashlib.md5(ha2_input.encode()).hexdigest()

        # 3. Calculate the final response value (concatenation of h1, stuff and h2)
        response_input = f"{ha1}:{nonce}:{nc}:{cnonce}:{qop}:{ha2}"
        response = hashlib.md5(response_input.encode()).hexdigest()

        return response

    # Example usage
    username = "alice"
    password = "mysecretpassword"
    realm = "example.com"
    method = "REGISTER"
    uri = "sip:example.com"
    nonce = "abcdefghijk"
    nc = "00000001"
    cnonce = "lmnopqrst"
    qop = "auth"

    response = calculate_sip_md5_response(username, password, realm, method, uri, nonce, nc, cnonce, qop)
    print(f"MD5 response value: {response}")

4. Successful registration response from the registrar server:

    SIP/2.0 200 OK
    Via: SIP/2.0/UDP 192.168.1.100:5060;branch=z9hG4bK776asdhds
    From: Alice <sip:alice@example.com>;tag=565656
    To: Alice <sip:alice@example.com>;tag=7878744
    Call-ID: 1234567890@192.168.1.100
    CSeq: 2 REGISTER
    Contact: <sip:alice@192.168.1.100:5060>;expires=3600
    Expires: 3600
    Content-Length: 0

After the registrar server verifies the provided credentials, it sends a "200 OK" response to indicate that the registration was successful. The response includes the registered contact information and the expiration time for the registration. At this point, the user agent (Alice) is successfully registered with the SIP registrar server, and incoming SIP requests for Alice can be routed to the appropriate contact address.

### Call Example

> [!NOTE] It's not mentioned, but User B needs to have sent a REGISTER message to Proxy 2 before he is able to receive calls.

> [!TIP] Learn & practice AWS Hacking:HackTricks Training AWS Red Team Expert (ARTE)
> Learn & practice GCP Hacking: HackTricks Training GCP Red Team Expert (GRTE)

> Support HackTricks
> - Check the subscription plans!
> - Join the 💬 Discord group or the telegram group or follow us on Twitter 🐦 @hacktricks_live.
> - Share hacking tricks by submitting PRs to the HackTricks and HackTricks Cloud github repos.