Skip to content

Commit

Permalink
Add initial support for RTSP with SHA-256 Digest Authentication
Browse files Browse the repository at this point in the history
Currently tested against a modified SharpRTSP Server
  • Loading branch information
RogerHardiman committed Aug 31, 2024
1 parent 6c08532 commit df37102
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 5 deletions.
23 changes: 18 additions & 5 deletions lib/RTSPClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
parseRTPPacket,
parseRTCPPacket,
getMD5Hash,
getSHA256Hash,
Transport,
parseTransport,
generateSSRC,
Expand Down Expand Up @@ -535,6 +536,7 @@ export default class RTSPClient extends EventEmitter {
// Get auth properties from WWW_AUTH header.
let realm = "";
let nonce = "";
let algorithm = "MD5"; // Default to MD5 if no algorthm is given. Milestone's RTSP server also supports SHA-256 for FIPS

let match = WWW_AUTH_REGEX.exec(authHeader);
while (match != null) {
Expand All @@ -548,6 +550,10 @@ export default class RTSPClient extends EventEmitter {
nonce = match[2];
}

if (prop == "algorithm" && match[2]) {
algorithm = match[2];
}

match = WWW_AUTH_REGEX.exec(authHeader);
}

Expand All @@ -557,13 +563,20 @@ export default class RTSPClient extends EventEmitter {
if (type === "Digest") {
// Digest Authentication

const ha1 = getMD5Hash(
// Select Hash Function, default to MD5
const HashFunction = (algorithm == "SHA-256" ? getSHA256Hash : getMD5Hash);

const ha1 = HashFunction(
`${this.username}:${realm}:${this.password}`
);
const ha2 = getMD5Hash(`${requestName}:${this._url}`);
const ha3 = getMD5Hash(`${ha1}:${nonce}:${ha2}`);

authString = `Digest username="${this.username}",realm="${realm}",nonce="${nonce}",uri="${this._url}",response="${ha3}"`;
const ha2 = HashFunction(`${requestName}:${this._url}`);
const ha3 = HashFunction(`${ha1}:${nonce}:${ha2}`);

// Some RTSP servers to not accept "algorithm=NNN" in the authString and reject the authentication. So only add algorithm=ZZZZ when not using MD5
if (algorithm == "MD5")
authString = `Digest username="${this.username}",realm="${realm}",nonce="${nonce}",uri="${this._url}",response="${ha3}"`;
else
authString = `Digest username="${this.username}",realm="${realm}",nonce="${nonce}",algorithm=${algorithm},uri="${this._url}",response="${ha3}"`;
} else if (type === "Basic") {
// Basic Authentication
// https://xkcd.com/538/
Expand Down
7 changes: 7 additions & 0 deletions lib/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,13 @@ export function getMD5Hash(str: string): string {
return md5.digest("hex");
}

export function getSHA256Hash(str: string): string {
const sha256 = createHash("sha-256");
sha256.update(str);

return sha256.digest("hex");
}

export interface Transport {
protocol: string;
parameters: { [key: string]: string };
Expand Down

0 comments on commit df37102

Please sign in to comment.