Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / communicate-dev / src / main / java / com / vayunmathur / communicate / data / signal / SignalProtocol.kt
SignalProtocol.kt357 lines · 15.6 KiBRaw
| 1 | package com.vayunmathur.communicate.data.signal |
| 2 | |
| 3 | import com.vayunmathur.library.log.Log |
| 4 | import com.google.protobuf.ByteString |
| 5 | import com.google.protobuf.InvalidProtocolBufferException |
| 6 | import org.whispersystems.signalservice.internal.push.SignalServiceProtos |
| 7 | import signal.proto.chat_websocket.SignalChatWebsocket.WebSocketMessage |
| 8 | import signal.proto.chat_websocket.SignalChatWebsocket.WebSocketRequestMessage |
| 9 | import signal.proto.chat_websocket.SignalChatWebsocket.WebSocketResponseMessage |
| 10 | import java.util.UUID |
| 11 | |
| 12 | /** |
| 13 | * Frame encode/decode and Envelope/Content handling for the Signal primary client. |
| 14 | * |
| 15 | * Real Signal wire (grounded in C:\Users\Vayun\signal-ref): |
| 16 | * - libsignal/rust/net/src/proto/chat_websocket.proto (WebSocketMessage, uint64 id) |
| 17 | * - lib/libsignal-service/src/main/protowire/SignalService.proto |
| 18 | * (Envelope, Content, DataMessage, ReceiptMessage, TypingMessage, etc.) |
| 19 | * - libsignal/rust/protocol/src/proto/{wire,sealed_sender}.proto (PQXDH wire) |
| 20 | * |
| 21 | * Inbound: WebSocketMessage (binary protobuf) -> WebSocketRequestMessage.body contains |
| 22 | * Envelope bytes (Envelope.content is a serialized CiphertextMessage; libsignal owns its |
| 23 | * version framing, so nothing is stripped from it here). |
| 24 | * Outbound: Build Content -> pad -> encrypt via SignalE2E -> PUT /v1/messages/{aci}. |
| 25 | */ |
| 26 | object SignalProtocol { |
| 27 | internal const val TAG = "SignalProtocol" |
| 28 | |
| 29 | private const val PADDING_BLOCK_SIZE = 80 |
| 30 | private const val TERMINATOR = 0x80.toByte() |
| 31 | private const val PADDING_ZERO = 0x00.toByte() |
| 32 | private const val UUID_SIZE = 16 |
| 33 | private const val UUID_PREFIXED_SIZE = 17 |
| 34 | private const val LONG_BYTES = 8 |
| 35 | private const val BYTE_MASK = 0xFFL |
| 36 | private const val BYTE_BITS = 8 |
| 37 | |
| 38 | /** A decrypted Signal service envelope: sender ACI/device, timestamp and plaintext content bytes. */ |
| 39 | data class SignalEnvelope( |
| 40 | val type: SignalServiceProtos.Envelope.Type, |
| 41 | val sourceAci: String, |
| 42 | val sourceDevice: Int, |
| 43 | val timestamp: Long, |
| 44 | val content: ByteArray, |
| 45 | val serverGuid: String? = null, |
| 46 | val serverGuidBinary: ByteArray? = null, |
| 47 | val serverTimestamp: Long = 0L, |
| 48 | val destinationAci: String? = null, |
| 49 | val isGroup: Boolean = false, |
| 50 | val groupId: ByteArray? = null, |
| 51 | val story: Boolean = false, |
| 52 | val urgent: Boolean = true, |
| 53 | val rawEnvelope: SignalServiceProtos.Envelope? = null, |
| 54 | ) |
| 55 | |
| 56 | /** The decoded payload of a Signal envelope, split by Signal protocol message kind. */ |
| 57 | sealed interface ParsedContent { |
| 58 | /** A normal data message (text, attachments, group traffic). */ |
| 59 | data class Data( |
| 60 | val dataMessage: SignalServiceProtos.DataMessage, |
| 61 | val raw: SignalServiceProtos.Content, |
| 62 | ) : ParsedContent |
| 63 | /** A delivery/read receipt. */ |
| 64 | data class Receipt(val receiptMessage: SignalServiceProtos.ReceiptMessage) : ParsedContent |
| 65 | /** A typing indicator. */ |
| 66 | data class Typing(val typingMessage: SignalServiceProtos.TypingMessage) : ParsedContent |
| 67 | /** An edit of a previously sent message. */ |
| 68 | data class Edit(val editMessage: SignalServiceProtos.EditMessage) : ParsedContent |
| 69 | /** A call signalling message. */ |
| 70 | data class Call(val callMessage: SignalServiceProtos.CallMessage) : ParsedContent |
| 71 | /** A null/padding message, used to keep sealed-sender traffic sizes uniform. */ |
| 72 | data class Null(val nullMessage: SignalServiceProtos.NullMessage) : ParsedContent |
| 73 | /** A sync message from our own other device. */ |
| 74 | data class Sync(val syncMessage: SignalServiceProtos.SyncMessage) : ParsedContent |
| 75 | /** A story message. */ |
| 76 | data class Story(val storyMessage: SignalServiceProtos.StoryMessage) : ParsedContent |
| 77 | /** Content that failed to decrypt; carries the raw bytes for diagnostics. */ |
| 78 | data class DecryptionError(val bytes: ByteArray) : ParsedContent |
| 79 | /** A content kind this client does not model yet; carries the raw proto. */ |
| 80 | data class Unknown(val raw: SignalServiceProtos.Content) : ParsedContent |
| 81 | } |
| 82 | |
| 83 | fun parseEnvelope(bytes: ByteArray): SignalServiceProtos.Envelope? = try { |
| 84 | SignalServiceProtos.Envelope.parseFrom(bytes) |
| 85 | } catch (e: InvalidProtocolBufferException) { |
| 86 | Log.status(TAG, "parseEnvelope failed: ${e.message}") |
| 87 | null |
| 88 | } |
| 89 | |
| 90 | fun parseEnvelopeFromRequest(request: WebSocketRequestMessage): SignalServiceProtos.Envelope? { |
| 91 | if (!request.hasBody()) return null |
| 92 | return parseEnvelope(request.body.toByteArray()) |
| 93 | } |
| 94 | |
| 95 | fun parseEnvelopeFromWsMessage(wsMessage: WebSocketMessage): SignalServiceProtos.Envelope? { |
| 96 | if (!wsMessage.hasRequest()) return null |
| 97 | return parseEnvelopeFromRequest(wsMessage.request) |
| 98 | } |
| 99 | |
| 100 | fun toSignalEnvelope(envelope: SignalServiceProtos.Envelope): SignalEnvelope { |
| 101 | return SignalEnvelope( |
| 102 | type = if (envelope.hasType()) envelope.type else SignalServiceProtos.Envelope.Type.UNKNOWN, |
| 103 | sourceAci = sourceAciFor(envelope), |
| 104 | sourceDevice = if (envelope.hasSourceDeviceId()) envelope.sourceDeviceId else 1, |
| 105 | timestamp = timestampFor(envelope), |
| 106 | content = if (envelope.hasContent()) envelope.content.toByteArray() else ByteArray(0), |
| 107 | serverGuid = serverGuidFor(envelope), |
| 108 | serverGuidBinary = serverGuidBinaryFor(envelope), |
| 109 | serverTimestamp = if (envelope.hasServerTimestamp()) envelope.serverTimestamp else 0L, |
| 110 | destinationAci = destAciFor(envelope), |
| 111 | story = if (envelope.hasStory()) envelope.story else false, |
| 112 | urgent = if (envelope.hasUrgent()) envelope.urgent else true, |
| 113 | rawEnvelope = envelope, |
| 114 | ) |
| 115 | } |
| 116 | |
| 117 | /** |
| 118 | * Pad to a multiple of [PADDING_BLOCK_SIZE] with a trailing `0x80` terminator followed by zeroes. |
| 119 | * Applied to the serialized Content before encryption. Port of the official client's |
| 120 | * `PushTransportDetails.getPaddedMessageBody`. |
| 121 | */ |
| 122 | fun padMessageBody(body: ByteArray): ByteArray { |
| 123 | // The +1/-1 leaves the cipher room for its own single padding byte; without it the cipher |
| 124 | // adds a full extra block. |
| 125 | val padded = ByteArray(paddedLength(body.size + 1) - 1) |
| 126 | body.copyInto(padded) |
| 127 | padded[body.size] = TERMINATOR |
| 128 | return padded |
| 129 | } |
| 130 | |
| 131 | /** |
| 132 | * Strip [padMessageBody]'s terminator and trailing zeroes from a decrypted plaintext. Returns the |
| 133 | * input unchanged when the padding is malformed, matching the official client rather than |
| 134 | * guessing at a length. |
| 135 | */ |
| 136 | fun stripMessagePadding(padded: ByteArray): ByteArray { |
| 137 | var paddingStart = 0 |
| 138 | for (i in padded.indices.reversed()) { |
| 139 | if (padded[i] == TERMINATOR) { |
| 140 | paddingStart = i |
| 141 | break |
| 142 | } |
| 143 | if (padded[i] != PADDING_ZERO) { |
| 144 | Log.status(TAG, "malformed padding, leaving message unstripped") |
| 145 | return padded |
| 146 | } |
| 147 | } |
| 148 | return padded.copyOfRange(0, paddingStart) |
| 149 | } |
| 150 | |
| 151 | private fun paddedLength(length: Int): Int { |
| 152 | val withTerminator = length + 1 |
| 153 | val blocks = (withTerminator + PADDING_BLOCK_SIZE - 1) / PADDING_BLOCK_SIZE |
| 154 | return blocks * PADDING_BLOCK_SIZE |
| 155 | } |
| 156 | |
| 157 | fun parseContent(plaintext: ByteArray): SignalServiceProtos.Content? = try { |
| 158 | if (plaintext.isEmpty()) return null |
| 159 | SignalServiceProtos.Content.parseFrom(plaintext) |
| 160 | } catch (e: InvalidProtocolBufferException) { |
| 161 | Log.status(TAG, "parseContent failed: ${e.message}") |
| 162 | null |
| 163 | } |
| 164 | |
| 165 | /** |
| 166 | * `PLAINTEXT_CONTENT` is the one unencrypted envelope type and may only carry a |
| 167 | * `DecryptionErrorMessage`. Official clients drop anything else, so accepting a plaintext |
| 168 | * DataMessage would be a spoofing hole rather than a compatibility feature. |
| 169 | */ |
| 170 | fun isValidPlaintextContent(content: SignalServiceProtos.Content): Boolean = |
| 171 | content.hasDecryptionErrorMessage() && |
| 172 | !content.hasDataMessage() && |
| 173 | !content.hasSyncMessage() && |
| 174 | !content.hasCallMessage() && |
| 175 | !content.hasNullMessage() && |
| 176 | !content.hasReceiptMessage() && |
| 177 | !content.hasTypingMessage() && |
| 178 | !content.hasStoryMessage() && |
| 179 | !content.hasEditMessage() |
| 180 | |
| 181 | fun classifyContent(content: SignalServiceProtos.Content): ParsedContent { |
| 182 | return when { |
| 183 | content.hasDataMessage() -> ParsedContent.Data(content.dataMessage, content) |
| 184 | content.hasReceiptMessage() -> ParsedContent.Receipt(content.receiptMessage) |
| 185 | content.hasTypingMessage() -> ParsedContent.Typing(content.typingMessage) |
| 186 | content.hasEditMessage() -> ParsedContent.Edit(content.editMessage) |
| 187 | content.hasCallMessage() -> ParsedContent.Call(content.callMessage) |
| 188 | content.hasNullMessage() -> ParsedContent.Null(content.nullMessage) |
| 189 | content.hasSyncMessage() -> ParsedContent.Sync(content.syncMessage) |
| 190 | content.hasStoryMessage() -> ParsedContent.Story(content.storyMessage) |
| 191 | content.hasDecryptionErrorMessage() -> { |
| 192 | ParsedContent.DecryptionError(content.decryptionErrorMessage.toByteArray()) |
| 193 | } |
| 194 | else -> ParsedContent.Unknown(content) |
| 195 | } |
| 196 | } |
| 197 | |
| 198 | fun parseAndClassifyContent(plaintext: ByteArray): ParsedContent? { |
| 199 | val content = parseContent(plaintext) ?: return null |
| 200 | return classifyContent(content) |
| 201 | } |
| 202 | |
| 203 | fun buildDataMessageContent( |
| 204 | body: String, |
| 205 | timestamp: Long = System.currentTimeMillis(), |
| 206 | groupMasterKey: ByteArray? = null, |
| 207 | groupRevision: Int? = null, |
| 208 | groupChange: ByteArray? = null, |
| 209 | bodyRanges: List<SignalServiceProtos.BodyRange> = emptyList(), |
| 210 | ): SignalServiceProtos.Content { |
| 211 | val dmBuilder = SignalServiceProtos.DataMessage.newBuilder().setBody(body).setTimestamp(timestamp) |
| 212 | if (groupMasterKey != null) { |
| 213 | val g = SignalServiceProtos.GroupContextV2.newBuilder().setMasterKey(ByteString.copyFrom(groupMasterKey)) |
| 214 | if (groupRevision != null) g.setRevision(groupRevision) |
| 215 | if (groupChange != null) g.setGroupChange(ByteString.copyFrom(groupChange)) |
| 216 | dmBuilder.setGroupV2(g) |
| 217 | } |
| 218 | if (bodyRanges.isNotEmpty()) dmBuilder.addAllBodyRanges(bodyRanges) |
| 219 | return SignalServiceProtos.Content.newBuilder().setDataMessage(dmBuilder).build() |
| 220 | } |
| 221 | |
| 222 | fun buildReceiptContent( |
| 223 | type: SignalServiceProtos.ReceiptMessage.Type, |
| 224 | timestamps: List<Long>, |
| 225 | ): SignalServiceProtos.Content { |
| 226 | val receipt = SignalServiceProtos.ReceiptMessage.newBuilder().setType(type) |
| 227 | timestamps.forEach { receipt.addTimestamp(it) } |
| 228 | return SignalServiceProtos.Content.newBuilder().setReceiptMessage(receipt).build() |
| 229 | } |
| 230 | |
| 231 | fun buildTypingContent( |
| 232 | action: SignalServiceProtos.TypingMessage.Action, |
| 233 | timestamp: Long = System.currentTimeMillis(), |
| 234 | groupId: ByteArray? = null, |
| 235 | ): SignalServiceProtos.Content { |
| 236 | val typing = SignalServiceProtos.TypingMessage.newBuilder().setTimestamp(timestamp).setAction(action) |
| 237 | if (groupId != null) typing.setGroupId(ByteString.copyFrom(groupId)) |
| 238 | return SignalServiceProtos.Content.newBuilder().setTypingMessage(typing).build() |
| 239 | } |
| 240 | |
| 241 | fun buildEditContent( |
| 242 | targetSentTimestamp: Long, |
| 243 | newDataMessage: SignalServiceProtos.DataMessage, |
| 244 | ): SignalServiceProtos.Content { |
| 245 | val edit = SignalServiceProtos.EditMessage.newBuilder() |
| 246 | .setTargetSentTimestamp(targetSentTimestamp) |
| 247 | .setDataMessage(newDataMessage) |
| 248 | return SignalServiceProtos.Content.newBuilder().setEditMessage(edit).build() |
| 249 | } |
| 250 | |
| 251 | fun generateMessageId(): String = UUID.randomUUID().toString() |
| 252 | |
| 253 | /** |
| 254 | * Conversation id for a message. Groups are keyed by their derived public identifier — never by the |
| 255 | * master key, which is secret material that must not end up in a database key or a log line. |
| 256 | */ |
| 257 | fun toConversationId(sourceAci: String, groupMasterKey: ByteArray?): String { |
| 258 | return when { |
| 259 | groupMasterKey != null -> { |
| 260 | val id = runCatching { SignalGroups.groupIdFromMasterKey(groupMasterKey) }.getOrElse { expected -> |
| 261 | Log.status(TAG, "could not derive a group identifier: ${expected.message}") |
| 262 | return if (sourceAci.isNotEmpty()) sourceAci else "unknown" |
| 263 | } |
| 264 | "$GROUP_PREFIX$id" |
| 265 | } |
| 266 | sourceAci.isNotEmpty() -> sourceAci |
| 267 | else -> "unknown" |
| 268 | } |
| 269 | } |
| 270 | |
| 271 | fun toConversationId(sourceAci: String, groupId: String?): String = when { |
| 272 | !groupId.isNullOrEmpty() -> "$GROUP_PREFIX$groupId" |
| 273 | sourceAci.isNotEmpty() -> sourceAci |
| 274 | else -> "unknown" |
| 275 | } |
| 276 | |
| 277 | const val GROUP_PREFIX = "group:" |
| 278 | |
| 279 | fun isGroupConversation(conversationId: String): Boolean = conversationId.startsWith(GROUP_PREFIX) |
| 280 | |
| 281 | /** The conversation id for a raw 32-byte group identifier, the inverse of what calling hands back. */ |
| 282 | internal fun bytesToAciString(bytes: ByteArray): String { |
| 283 | if (bytes.size == UUID_SIZE) return bytesToUuidString(bytes) |
| 284 | if (bytes.size == UUID_PREFIXED_SIZE) { |
| 285 | return bytesToUuidString(bytes.copyOfRange(1, UUID_PREFIXED_SIZE)) |
| 286 | } |
| 287 | return try { |
| 288 | String(bytes, Charsets.UTF_8) |
| 289 | .takeIf { it.isNotBlank() } |
| 290 | ?: bytesToUuidString(bytes.take(UUID_SIZE).toByteArray()) |
| 291 | } catch (_: Exception) { "" } |
| 292 | } |
| 293 | |
| 294 | internal fun bytesToUuidString(bytes: ByteArray): String { |
| 295 | if (bytes.size < UUID_SIZE) return "" |
| 296 | val b = if (bytes.size > UUID_SIZE) bytes.copyOfRange(0, UUID_SIZE) else bytes |
| 297 | return try { |
| 298 | UUID(bytesToLong(b, 0), bytesToLong(b, LONG_BYTES)).toString() |
| 299 | } catch (_: Exception) { "" } |
| 300 | } |
| 301 | |
| 302 | /** Big-endian 8 bytes at [offset] as a Long. */ |
| 303 | private fun bytesToLong(b: ByteArray, offset: Int): Long { |
| 304 | var v = 0L |
| 305 | for (i in 0 until LONG_BYTES) { |
| 306 | v = (v shl BYTE_BITS) or (b[offset + i].toLong() and BYTE_MASK) |
| 307 | } |
| 308 | return v |
| 309 | } |
| 310 | |
| 311 | /** Legacy text WebSocket frame; superseded by the binary WebSocket message helpers. */ |
| 312 | @Deprecated("Use binary WebSocketMessage helpers") |
| 313 | data class WsFrame( |
| 314 | val type: String, |
| 315 | val verb: String?, |
| 316 | val path: String?, |
| 317 | val id: String?, |
| 318 | val status: Int?, |
| 319 | val body: ByteArray?, |
| 320 | val raw: String, |
| 321 | ) |
| 322 | |
| 323 | @Deprecated("Use parseWebSocketMessage(bytes)") |
| 324 | fun parseWsFrame(text: String): WsFrame? { |
| 325 | val obj = runCatching { org.json.JSONObject(text) }.getOrElse { expected -> |
| 326 | Log.status(TAG, "parseWsFrame failed: ${expected.message}") |
| 327 | return null |
| 328 | } |
| 329 | val type = obj.optString("type", "") |
| 330 | val bodyB64 = obj.optString("body", "") |
| 331 | val body = if (bodyB64.isNotEmpty()) { |
| 332 | runCatching { |
| 333 | android.util.Base64.decode(bodyB64, android.util.Base64.NO_WRAP) |
| 334 | }.getOrNull() |
| 335 | } else { |
| 336 | null |
| 337 | } |
| 338 | return WsFrame( |
| 339 | type = type, |
| 340 | verb = if (obj.has("verb")) obj.optString("verb") else null, |
| 341 | path = if (obj.has("path")) obj.optString("path") else null, |
| 342 | id = if (obj.has("id")) obj.optString("id") else null, |
| 343 | status = if (obj.has("status")) obj.optInt("status") else null, |
| 344 | body = body, |
| 345 | raw = text, |
| 346 | ) |
| 347 | } |
| 348 | |
| 349 | @Deprecated("Use encodeWsAck(id: Long)") |
| 350 | fun buildWsResponse(id: String, status: Int = 200): String { |
| 351 | val o = org.json.JSONObject() |
| 352 | o.put("type", "RESPONSE") |
| 353 | o.put("id", id) |
| 354 | o.put("status", status) |
| 355 | return o.toString() |
| 356 | } |
| 357 | } |