|
| 1 | +/* |
| 2 | + * Copyright (c) OpenIPC https://openipc.org Prosperity Public License 3.0.0 |
| 3 | + * |
| 4 | + * RtspAuth.java — RTSP Basic and Digest (RFC 2617) authentication |
| 5 | + * |
| 6 | + */ |
| 7 | + |
| 8 | +package com.openipc.decoder; |
| 9 | + |
| 10 | +import android.util.Base64; |
| 11 | + |
| 12 | +import java.nio.charset.StandardCharsets; |
| 13 | +import java.security.MessageDigest; |
| 14 | +import java.security.NoSuchAlgorithmException; |
| 15 | +import java.security.SecureRandom; |
| 16 | +import java.util.HashMap; |
| 17 | +import java.util.List; |
| 18 | +import java.util.Locale; |
| 19 | +import java.util.Map; |
| 20 | + |
| 21 | +/** |
| 22 | + * Builds the Authorization header for each request. Basic is sent pre-emptively, as cameras |
| 23 | + * running OpenIPC expect; after a Digest challenge every request is signed with Digest. |
| 24 | + */ |
| 25 | +class RtspAuth { |
| 26 | + private final String user; |
| 27 | + private final String password; |
| 28 | + |
| 29 | + private boolean digest; |
| 30 | + private String realm; |
| 31 | + private String nonce; |
| 32 | + private String opaque; |
| 33 | + private String algorithm; |
| 34 | + private boolean qopAuth; |
| 35 | + private int nonceCount; |
| 36 | + /** MD5-sess: one client nonce per server nonce, used in H(A1) and sent every time. */ |
| 37 | + private String sessCnonce; |
| 38 | + /** Fixed client nonce for tests; random when null. */ |
| 39 | + String testCnonce; |
| 40 | + |
| 41 | + /** @param userInfo decoded "user:password" from the URL, or null */ |
| 42 | + RtspAuth(String userInfo) { |
| 43 | + if (userInfo == null) { |
| 44 | + user = null; |
| 45 | + password = null; |
| 46 | + } else { |
| 47 | + int colon = userInfo.indexOf(':'); |
| 48 | + user = colon >= 0 ? userInfo.substring(0, colon) : userInfo; |
| 49 | + password = colon >= 0 ? userInfo.substring(colon + 1) : ""; |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + boolean hasCredentials() { return user != null; } |
| 54 | + |
| 55 | + /** "Authorization: ...\r\n" for this request, or "" without credentials. */ |
| 56 | + String header(String method, String uri) { |
| 57 | + if (user == null) return ""; |
| 58 | + if (!digest) { |
| 59 | + String token = Base64.encodeToString( |
| 60 | + (user + ":" + password).getBytes(StandardCharsets.UTF_8), Base64.NO_WRAP); |
| 61 | + return "Authorization: Basic " + token + "\r\n"; |
| 62 | + } |
| 63 | + |
| 64 | + String ha1 = md5(user + ":" + realm + ":" + password); |
| 65 | + String cnonce = null; |
| 66 | + String nc = null; |
| 67 | + if ("MD5-SESS".equals(algorithm)) { |
| 68 | + if (sessCnonce == null) sessCnonce = newCnonce(); |
| 69 | + cnonce = sessCnonce; |
| 70 | + ha1 = md5(ha1 + ":" + nonce + ":" + cnonce); |
| 71 | + } else if (qopAuth) { |
| 72 | + cnonce = newCnonce(); |
| 73 | + } |
| 74 | + String ha2 = md5(method + ":" + uri); |
| 75 | + String response; |
| 76 | + if (qopAuth) { |
| 77 | + nc = String.format(Locale.ROOT, "%08x", ++nonceCount); |
| 78 | + response = md5(ha1 + ":" + nonce + ":" + nc + ":" + cnonce + ":auth:" + ha2); |
| 79 | + } else { |
| 80 | + response = md5(ha1 + ":" + nonce + ":" + ha2); |
| 81 | + } |
| 82 | + |
| 83 | + StringBuilder h = new StringBuilder("Authorization: Digest "); |
| 84 | + h.append("username=").append(quote(user)).append(", "); |
| 85 | + h.append("realm=").append(quote(realm)).append(", "); |
| 86 | + h.append("nonce=").append(quote(nonce)).append(", "); |
| 87 | + h.append("uri=").append(quote(uri)).append(", "); |
| 88 | + h.append("response=\"").append(response).append('"'); |
| 89 | + if (algorithm != null) h.append(", algorithm=").append(algorithm); |
| 90 | + if (opaque != null) h.append(", opaque=").append(quote(opaque)); |
| 91 | + if (qopAuth) h.append(", qop=auth, nc=").append(nc); |
| 92 | + // MD5-sess needs the cnonce even without qop, or the server cannot verify H(A1) |
| 93 | + if (cnonce != null) h.append(", cnonce=").append(quote(cnonce)); |
| 94 | + return h.append("\r\n").toString(); |
| 95 | + } |
| 96 | + |
| 97 | + /** |
| 98 | + * Handle a 401 reply. Returns true if the request should be repeated: a first Digest |
| 99 | + * challenge, or a stale nonce. Returns false when retrying cannot help (no |
| 100 | + * credentials, an unsupported scheme, or the same credentials were already rejected). |
| 101 | + */ |
| 102 | + boolean onUnauthorized(List<String> challenges) { |
| 103 | + if (user == null || challenges == null) return false; |
| 104 | + for (String c : challenges) { |
| 105 | + String trimmed = c.trim(); |
| 106 | + if (!trimmed.regionMatches(true, 0, "Digest", 0, 6)) continue; |
| 107 | + Map<String, String> p = parseParams(trimmed.substring(6)); |
| 108 | + String alg = p.get("algorithm"); |
| 109 | + if (alg != null && !alg.equalsIgnoreCase("MD5") && !alg.equalsIgnoreCase("MD5-sess")) { |
| 110 | + continue; // SHA-256 etc. are not supported |
| 111 | + } |
| 112 | + String qop = p.get("qop"); |
| 113 | + boolean hasAuth = false; |
| 114 | + if (qop != null) { |
| 115 | + for (String q : qop.split(",")) { |
| 116 | + if (q.trim().equalsIgnoreCase("auth")) hasAuth = true; |
| 117 | + } |
| 118 | + // Only auth-int offered: we cannot produce that, look for another challenge |
| 119 | + if (!hasAuth) continue; |
| 120 | + } |
| 121 | + boolean stale = "true".equalsIgnoreCase(p.get("stale")); |
| 122 | + boolean retry = !digest || stale; |
| 123 | + digest = true; |
| 124 | + realm = p.containsKey("realm") ? p.get("realm") : ""; |
| 125 | + nonce = p.containsKey("nonce") ? p.get("nonce") : ""; |
| 126 | + opaque = p.get("opaque"); |
| 127 | + algorithm = alg != null ? alg.toUpperCase(Locale.ROOT) : null; |
| 128 | + qopAuth = hasAuth; |
| 129 | + nonceCount = 0; |
| 130 | + sessCnonce = null; |
| 131 | + return retry; |
| 132 | + } |
| 133 | + // Basic was already sent pre-emptively: another attempt would fail the same way |
| 134 | + return false; |
| 135 | + } |
| 136 | + |
| 137 | + /** Parse "k=v, k="quoted, value", ..." into lower-case keys. */ |
| 138 | + static Map<String, String> parseParams(String s) { |
| 139 | + Map<String, String> out = new HashMap<>(); |
| 140 | + int i = 0; |
| 141 | + int n = s.length(); |
| 142 | + while (i < n) { |
| 143 | + while (i < n && (s.charAt(i) == ',' || Character.isWhitespace(s.charAt(i)))) i++; |
| 144 | + int eq = s.indexOf('=', i); |
| 145 | + if (eq < 0) break; |
| 146 | + String key = s.substring(i, eq).trim().toLowerCase(Locale.ROOT); |
| 147 | + i = eq + 1; |
| 148 | + while (i < n && Character.isWhitespace(s.charAt(i))) i++; |
| 149 | + StringBuilder value = new StringBuilder(); |
| 150 | + if (i < n && s.charAt(i) == '"') { |
| 151 | + i++; |
| 152 | + while (i < n && s.charAt(i) != '"') { |
| 153 | + if (s.charAt(i) == '\\' && i + 1 < n) i++; |
| 154 | + value.append(s.charAt(i++)); |
| 155 | + } |
| 156 | + i++; // closing quote |
| 157 | + } else { |
| 158 | + while (i < n && s.charAt(i) != ',') value.append(s.charAt(i++)); |
| 159 | + } |
| 160 | + out.put(key, value.toString().trim()); |
| 161 | + } |
| 162 | + return out; |
| 163 | + } |
| 164 | + |
| 165 | + private String newCnonce() { |
| 166 | + return testCnonce != null ? testCnonce : randomHex(8); |
| 167 | + } |
| 168 | + |
| 169 | + /** Quoted-string with '"' and '\\' escaped (RFC 2616 2.2). */ |
| 170 | + static String quote(String v) { |
| 171 | + return '"' + v.replace("\\", "\\\\").replace("\"", "\\\"") + '"'; |
| 172 | + } |
| 173 | + |
| 174 | + static String md5(String s) { |
| 175 | + try { |
| 176 | + byte[] d = MessageDigest.getInstance("MD5").digest(s.getBytes(StandardCharsets.UTF_8)); |
| 177 | + StringBuilder hex = new StringBuilder(32); |
| 178 | + for (byte b : d) hex.append(String.format(Locale.ROOT, "%02x", b & 0xFF)); |
| 179 | + return hex.toString(); |
| 180 | + } catch (NoSuchAlgorithmException e) { |
| 181 | + throw new IllegalStateException(e); |
| 182 | + } |
| 183 | + } |
| 184 | + |
| 185 | + private static String randomHex(int bytes) { |
| 186 | + byte[] b = new byte[bytes]; |
| 187 | + new SecureRandom().nextBytes(b); |
| 188 | + StringBuilder hex = new StringBuilder(bytes * 2); |
| 189 | + for (byte x : b) hex.append(String.format(Locale.ROOT, "%02x", x & 0xFF)); |
| 190 | + return hex.toString(); |
| 191 | + } |
| 192 | +} |
0 commit comments