-
Notifications
You must be signed in to change notification settings - Fork 9.1k
/
Adapters.kt
529 lines (471 loc) · 15 KB
/
Adapters.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
/*
* Copyright (C) 2020 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3.tls.internal.der
import java.math.BigInteger
import java.net.ProtocolException
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.Date
import java.util.TimeZone
import kotlin.reflect.KClass
import okio.ByteString
/**
* Built-in adapters for reading standard ASN.1 types.
*/
internal object Adapters {
val BOOLEAN =
BasicDerAdapter(
name = "BOOLEAN",
tagClass = DerHeader.TAG_CLASS_UNIVERSAL,
tag = 1L,
codec =
object : BasicDerAdapter.Codec<Boolean> {
override fun decode(reader: DerReader): Boolean = reader.readBoolean()
override fun encode(
writer: DerWriter,
value: Boolean,
) = writer.writeBoolean(value)
},
)
val INTEGER_AS_LONG =
BasicDerAdapter(
name = "INTEGER",
tagClass = DerHeader.TAG_CLASS_UNIVERSAL,
tag = 2L,
codec =
object : BasicDerAdapter.Codec<Long> {
override fun decode(reader: DerReader): Long = reader.readLong()
override fun encode(
writer: DerWriter,
value: Long,
) = writer.writeLong(value)
},
)
val INTEGER_AS_BIG_INTEGER =
BasicDerAdapter(
name = "INTEGER",
tagClass = DerHeader.TAG_CLASS_UNIVERSAL,
tag = 2L,
codec =
object : BasicDerAdapter.Codec<BigInteger> {
override fun decode(reader: DerReader): BigInteger = reader.readBigInteger()
override fun encode(
writer: DerWriter,
value: BigInteger,
) = writer.writeBigInteger(value)
},
)
val BIT_STRING =
BasicDerAdapter(
name = "BIT STRING",
tagClass = DerHeader.TAG_CLASS_UNIVERSAL,
tag = 3L,
codec =
object : BasicDerAdapter.Codec<BitString> {
override fun decode(reader: DerReader): BitString = reader.readBitString()
override fun encode(
writer: DerWriter,
value: BitString,
) = writer.writeBitString(value)
},
)
val OCTET_STRING =
BasicDerAdapter(
name = "OCTET STRING",
tagClass = DerHeader.TAG_CLASS_UNIVERSAL,
tag = 4L,
codec =
object : BasicDerAdapter.Codec<ByteString> {
override fun decode(reader: DerReader): ByteString = reader.readOctetString()
override fun encode(
writer: DerWriter,
value: ByteString,
) = writer.writeOctetString(value)
},
)
val NULL =
BasicDerAdapter(
name = "NULL",
tagClass = DerHeader.TAG_CLASS_UNIVERSAL,
tag = 5L,
codec =
object : BasicDerAdapter.Codec<Unit?> {
override fun decode(reader: DerReader): Unit? = null
override fun encode(
writer: DerWriter,
value: Unit?,
) {
}
},
)
val OBJECT_IDENTIFIER =
BasicDerAdapter(
name = "OBJECT IDENTIFIER",
tagClass = DerHeader.TAG_CLASS_UNIVERSAL,
tag = 6L,
codec =
object : BasicDerAdapter.Codec<String> {
override fun decode(reader: DerReader): String = reader.readObjectIdentifier()
override fun encode(
writer: DerWriter,
value: String,
) = writer.writeObjectIdentifier(value)
},
)
val UTF8_STRING =
BasicDerAdapter(
name = "UTF8",
tagClass = DerHeader.TAG_CLASS_UNIVERSAL,
tag = 12L,
codec =
object : BasicDerAdapter.Codec<String> {
override fun decode(reader: DerReader): String = reader.readUtf8String()
override fun encode(
writer: DerWriter,
value: String,
) = writer.writeUtf8(value)
},
)
/**
* Permits alphanumerics, spaces, and these:
*
* ```
* ' () + , - . / : = ?
* ```
*
* TODO(jwilson): constrain to printable string characters.
*/
val PRINTABLE_STRING =
BasicDerAdapter(
name = "PRINTABLE STRING",
tagClass = DerHeader.TAG_CLASS_UNIVERSAL,
tag = 19L,
codec =
object : BasicDerAdapter.Codec<String> {
override fun decode(reader: DerReader): String = reader.readUtf8String()
override fun encode(
writer: DerWriter,
value: String,
) = writer.writeUtf8(value)
},
)
/**
* Based on International Alphabet No. 5. Note that there are bytes that IA5 and US-ASCII
* disagree on interpretation.
*
* TODO(jwilson): constrain to IA5 characters.
*/
val IA5_STRING =
BasicDerAdapter(
name = "IA5 STRING",
tagClass = DerHeader.TAG_CLASS_UNIVERSAL,
tag = 22L,
codec =
object : BasicDerAdapter.Codec<String> {
override fun decode(reader: DerReader): String = reader.readUtf8String()
override fun encode(
writer: DerWriter,
value: String,
) = writer.writeUtf8(value)
},
)
/**
* A timestamp like "191216030210Z" or "191215190210-0800" for 2019-12-15T19:02:10-08:00. The
* cutoff of the 2-digit year is 1950-01-01T00:00:00Z.
*/
val UTC_TIME =
BasicDerAdapter(
name = "UTC TIME",
tagClass = DerHeader.TAG_CLASS_UNIVERSAL,
tag = 23L,
codec =
object : BasicDerAdapter.Codec<Long> {
override fun decode(reader: DerReader): Long {
val string = reader.readUtf8String()
return parseUtcTime(string)
}
override fun encode(
writer: DerWriter,
value: Long,
) {
val string = formatUtcTime(value)
return writer.writeUtf8(string)
}
},
)
internal fun parseUtcTime(string: String): Long {
val utc = TimeZone.getTimeZone("GMT")
val dateFormat =
SimpleDateFormat("yyMMddHHmmss'Z'").apply {
timeZone = utc
set2DigitYearStart(Date(-631152000000L)) // 1950-01-01T00:00:00Z.
}
try {
val parsed = dateFormat.parse(string)
return parsed.time
} catch (e: ParseException) {
throw ProtocolException("Failed to parse UTCTime $string")
}
}
internal fun formatUtcTime(date: Long): String {
val utc = TimeZone.getTimeZone("GMT")
val dateFormat =
SimpleDateFormat("yyMMddHHmmss'Z'").apply {
timeZone = utc
set2DigitYearStart(Date(-631152000000L)) // 1950-01-01T00:00:00Z.
}
return dateFormat.format(date)
}
/**
* A timestamp like "191216030210Z" or "20191215190210-0800" for 2019-12-15T19:02:10-08:00. This
* is the same as [UTC_TIME] with the exception of the 4-digit year.
*/
val GENERALIZED_TIME =
BasicDerAdapter(
name = "GENERALIZED TIME",
tagClass = DerHeader.TAG_CLASS_UNIVERSAL,
tag = 24L,
codec =
object : BasicDerAdapter.Codec<Long> {
override fun decode(reader: DerReader): Long {
val string = reader.readUtf8String()
return parseGeneralizedTime(string)
}
override fun encode(
writer: DerWriter,
value: Long,
) {
val string = formatGeneralizedTime(value)
return writer.writeUtf8(string)
}
},
)
/** Decodes any value without interpretation as [AnyValue]. */
val ANY_VALUE =
object : DerAdapter<AnyValue> {
override fun matches(header: DerHeader): Boolean = true
override fun fromDer(reader: DerReader): AnyValue {
reader.read("ANY") { header ->
val bytes = reader.readUnknown()
return AnyValue(
tagClass = header.tagClass,
tag = header.tag,
constructed = header.constructed,
length = header.length,
bytes = bytes,
)
}
}
override fun toDer(
writer: DerWriter,
value: AnyValue,
) {
writer.write("ANY", value.tagClass, value.tag) {
writer.writeOctetString(value.bytes)
writer.constructed = value.constructed
}
}
}
internal fun parseGeneralizedTime(string: String): Long {
val utc = TimeZone.getTimeZone("GMT")
val dateFormat =
SimpleDateFormat("yyyyMMddHHmmss'Z'").apply {
timeZone = utc
}
try {
val parsed = dateFormat.parse(string)
return parsed.time
} catch (e: ParseException) {
throw ProtocolException("Failed to parse GeneralizedTime $string")
}
}
internal fun formatGeneralizedTime(date: Long): String {
val utc = TimeZone.getTimeZone("GMT")
val dateFormat =
SimpleDateFormat("yyyyMMddHHmmss'Z'").apply {
timeZone = utc
}
return dateFormat.format(date)
}
/**
* Returns a composite adapter for a struct or data class. This may be used for both SEQUENCE and
* SET types.
*
* The fields are specified as a list of member adapters. When decoding, a value for each
* non-optional member but be included in sequence.
*
* TODO: for sets, sort by tag when encoding.
* TODO: for set ofs, sort by encoded value when encoding.
*/
fun <T> sequence(
name: String,
vararg members: DerAdapter<*>,
decompose: (T) -> List<*>,
construct: (List<*>) -> T,
): BasicDerAdapter<T> {
val codec =
object : BasicDerAdapter.Codec<T> {
override fun decode(reader: DerReader): T {
return reader.withTypeHint {
val list = mutableListOf<Any?>()
while (list.size < members.size) {
val member = members[list.size]
list += member.fromDer(reader)
}
if (reader.hasNext()) {
throw ProtocolException("unexpected ${reader.peekHeader()} at $reader")
}
return@withTypeHint construct(list)
}
}
override fun encode(
writer: DerWriter,
value: T,
) {
val list = decompose(value)
writer.withTypeHint {
for (i in list.indices) {
val adapter = members[i] as DerAdapter<Any?>
adapter.toDer(writer, list[i])
}
}
}
}
return BasicDerAdapter(
name = name,
tagClass = DerHeader.TAG_CLASS_UNIVERSAL,
tag = 16L,
codec = codec,
)
}
/** Returns an adapter that decodes as the first of a list of available types. */
fun choice(vararg choices: DerAdapter<*>): DerAdapter<Pair<DerAdapter<*>, Any?>> {
return object : DerAdapter<Pair<DerAdapter<*>, Any?>> {
override fun matches(header: DerHeader): Boolean = true
override fun fromDer(reader: DerReader): Pair<DerAdapter<*>, Any?> {
val peekedHeader =
reader.peekHeader()
?: throw ProtocolException("expected a value at $reader")
val choice =
choices.firstOrNull { it.matches(peekedHeader) }
?: throw ProtocolException(
"expected a matching choice but was $peekedHeader at $reader",
)
return choice to choice.fromDer(reader)
}
override fun toDer(
writer: DerWriter,
value: Pair<DerAdapter<*>, Any?>,
) {
val (adapter, v) = value
(adapter as DerAdapter<Any?>).toDer(writer, v)
}
override fun toString(): String = choices.joinToString(separator = " OR ")
}
}
/**
* This decodes a value into its contents using a preceding member of the same SEQUENCE. For
* example, extensions type IDs specify what types to use for the corresponding values.
*
* If the hint is unknown [chooser] should return null which will cause the value to be decoded as
* an opaque byte string.
*
* This may optionally wrap the contents in a tag.
*/
fun usingTypeHint(chooser: (Any?) -> DerAdapter<*>?): DerAdapter<Any?> {
return object : DerAdapter<Any?> {
override fun matches(header: DerHeader): Boolean = true
override fun toDer(
writer: DerWriter,
value: Any?,
) {
// If we don't understand this hint, encode the body as a byte string. The byte string
// will include a tag and length header as a prefix.
val adapter = chooser(writer.typeHint) as DerAdapter<Any?>?
when {
adapter != null -> adapter.toDer(writer, value)
else -> writer.writeOctetString(value as ByteString)
}
}
override fun fromDer(reader: DerReader): Any? {
val adapter = chooser(reader.typeHint) as DerAdapter<Any?>?
return when {
adapter != null -> adapter.fromDer(reader)
else -> reader.readUnknown()
}
}
}
}
/**
* Object class to adapter type. This approach limits us to one adapter per Kotlin class, which
* might be too few for values like UTF_STRING and OBJECT_IDENTIFIER that share a Kotlin class but
* have very different ASN.1 interpretations.
*/
private val defaultAnyChoices =
listOf(
Boolean::class to BOOLEAN,
BigInteger::class to INTEGER_AS_BIG_INTEGER,
BitString::class to BIT_STRING,
ByteString::class to OCTET_STRING,
Unit::class to NULL,
Nothing::class to OBJECT_IDENTIFIER,
Nothing::class to UTF8_STRING,
String::class to PRINTABLE_STRING,
Nothing::class to IA5_STRING,
Nothing::class to UTC_TIME,
Long::class to GENERALIZED_TIME,
AnyValue::class to ANY_VALUE,
)
fun any(
vararg choices: Pair<KClass<*>, DerAdapter<*>> = defaultAnyChoices.toTypedArray(),
isOptional: Boolean = false,
optionalValue: Any? = null,
): DerAdapter<Any?> {
return object : DerAdapter<Any?> {
override fun matches(header: DerHeader): Boolean = true
override fun toDer(
writer: DerWriter,
value: Any?,
) {
when {
isOptional && value == optionalValue -> {
// Write nothing.
}
else -> {
for ((type, adapter) in choices) {
if (type.isInstance(value) || (value == null && type == Unit::class)) {
(adapter as DerAdapter<Any?>).toDer(writer, value)
return
}
}
}
}
}
override fun fromDer(reader: DerReader): Any? {
if (isOptional && !reader.hasNext()) return optionalValue
val peekedHeader =
reader.peekHeader()
?: throw ProtocolException("expected a value at $reader")
for ((_, adapter) in choices) {
if (adapter.matches(peekedHeader)) {
return adapter.fromDer(reader)
}
}
throw ProtocolException("expected any but was $peekedHeader at $reader")
}
}
}
}