oid.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. // Copyright 2023 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. //nolint:staticcheck,gocritic // code copied from crypto/x509
  5. package legacyx509
  6. import (
  7. "bytes"
  8. "encoding/asn1"
  9. "errors"
  10. "math"
  11. "math/big"
  12. "math/bits"
  13. "strconv"
  14. "strings"
  15. "github.com/smallstep/certificates/internal/cast"
  16. )
  17. var errInvalidOID = errors.New("invalid oid")
  18. // An OID represents an ASN.1 OBJECT IDENTIFIER.
  19. type OID struct {
  20. der []byte
  21. }
  22. // ParseOID parses a Object Identifier string, represented by ASCII numbers separated by dots.
  23. func ParseOID(oid string) (OID, error) {
  24. var o OID
  25. return o, o.unmarshalOIDText(oid)
  26. }
  27. func newOIDFromDER(der []byte) (OID, bool) {
  28. if len(der) == 0 || der[len(der)-1]&0x80 != 0 {
  29. return OID{}, false
  30. }
  31. start := 0
  32. for i, v := range der {
  33. // ITU-T X.690, section 8.19.2:
  34. // The subidentifier shall be encoded in the fewest possible octets,
  35. // that is, the leading octet of the subidentifier shall not have the value 0x80.
  36. if i == start && v == 0x80 {
  37. return OID{}, false
  38. }
  39. if v&0x80 == 0 {
  40. start = i + 1
  41. }
  42. }
  43. return OID{der}, true
  44. }
  45. // OIDFromInts creates a new OID using ints, each integer is a separate component.
  46. func OIDFromInts(oid []uint64) (OID, error) {
  47. if len(oid) < 2 || oid[0] > 2 || (oid[0] < 2 && oid[1] >= 40) {
  48. return OID{}, errInvalidOID
  49. }
  50. length := base128IntLength(oid[0]*40 + oid[1])
  51. for _, v := range oid[2:] {
  52. length += base128IntLength(v)
  53. }
  54. der := make([]byte, 0, length)
  55. der = appendBase128Int(der, oid[0]*40+oid[1])
  56. for _, v := range oid[2:] {
  57. der = appendBase128Int(der, v)
  58. }
  59. return OID{der}, nil
  60. }
  61. func base128IntLength(n uint64) int {
  62. if n == 0 {
  63. return 1
  64. }
  65. return (bits.Len64(n) + 6) / 7
  66. }
  67. func appendBase128Int(dst []byte, n uint64) []byte {
  68. for i := base128IntLength(n) - 1; i >= 0; i-- {
  69. o := byte(n >> cast.Uint(i*7)) //nolint:gosec // masked to 7 bits below
  70. o &= 0x7f
  71. if i != 0 {
  72. o |= 0x80
  73. }
  74. dst = append(dst, o)
  75. }
  76. return dst
  77. }
  78. func base128BigIntLength(n *big.Int) int {
  79. if n.Cmp(big.NewInt(0)) == 0 {
  80. return 1
  81. }
  82. return (n.BitLen() + 6) / 7
  83. }
  84. func appendBase128BigInt(dst []byte, n *big.Int) []byte {
  85. if n.Cmp(big.NewInt(0)) == 0 {
  86. return append(dst, 0)
  87. }
  88. for i := base128BigIntLength(n) - 1; i >= 0; i-- {
  89. o := byte(big.NewInt(0).Rsh(n, uint(i)*7).Bits()[0]) //nolint:gosec // intentional truncation, masked to 0x7f immediately after
  90. o &= 0x7f
  91. if i != 0 {
  92. o |= 0x80
  93. }
  94. dst = append(dst, o)
  95. }
  96. return dst
  97. }
  98. // AppendText implements [encoding.TextAppender]
  99. func (o OID) AppendText(b []byte) ([]byte, error) {
  100. return append(b, o.String()...), nil
  101. }
  102. // MarshalText implements [encoding.TextMarshaler]
  103. func (o OID) MarshalText() ([]byte, error) {
  104. return o.AppendText(nil)
  105. }
  106. // UnmarshalText implements [encoding.TextUnmarshaler]
  107. func (o *OID) UnmarshalText(text []byte) error {
  108. return o.unmarshalOIDText(string(text))
  109. }
  110. // cutString slices s around the first instance of sep,
  111. // returning the text before and after sep.
  112. // The found result reports whether sep appears in s.
  113. // If sep does not appear in s, cut returns s, "", false.
  114. func cutString(s, sep string) (before, after string, found bool) {
  115. if i := strings.Index(s, sep); i >= 0 {
  116. return s[:i], s[i+len(sep):], true
  117. }
  118. return s, "", false
  119. }
  120. func (o *OID) unmarshalOIDText(oid string) error {
  121. // (*big.Int).SetString allows +/- signs, but we don't want
  122. // to allow them in the string representation of Object Identifier, so
  123. // reject such encodings.
  124. for _, c := range oid {
  125. isDigit := c >= '0' && c <= '9'
  126. if !isDigit && c != '.' {
  127. return errInvalidOID
  128. }
  129. }
  130. var (
  131. firstNum string
  132. secondNum string
  133. )
  134. var nextComponentExists bool
  135. firstNum, oid, nextComponentExists = cutString(oid, ".")
  136. if !nextComponentExists {
  137. return errInvalidOID
  138. }
  139. secondNum, oid, nextComponentExists = cutString(oid, ".")
  140. var (
  141. first = big.NewInt(0)
  142. second = big.NewInt(0)
  143. )
  144. if _, ok := first.SetString(firstNum, 10); !ok {
  145. return errInvalidOID
  146. }
  147. if _, ok := second.SetString(secondNum, 10); !ok {
  148. return errInvalidOID
  149. }
  150. if first.Cmp(big.NewInt(2)) > 0 || (first.Cmp(big.NewInt(2)) < 0 && second.Cmp(big.NewInt(40)) >= 0) {
  151. return errInvalidOID
  152. }
  153. firstComponent := first.Mul(first, big.NewInt(40))
  154. firstComponent.Add(firstComponent, second)
  155. der := appendBase128BigInt(make([]byte, 0, 32), firstComponent)
  156. for nextComponentExists {
  157. var strNum string
  158. strNum, oid, nextComponentExists = cutString(oid, ".")
  159. b, ok := big.NewInt(0).SetString(strNum, 10)
  160. if !ok {
  161. return errInvalidOID
  162. }
  163. der = appendBase128BigInt(der, b)
  164. }
  165. o.der = der
  166. return nil
  167. }
  168. // AppendBinary implements [encoding.BinaryAppender]
  169. func (o OID) AppendBinary(b []byte) ([]byte, error) {
  170. return append(b, o.der...), nil
  171. }
  172. // MarshalBinary implements [encoding.BinaryMarshaler]
  173. func (o OID) MarshalBinary() ([]byte, error) {
  174. return o.AppendBinary(nil)
  175. }
  176. // cloneBytes returns a copy of b[:len(b)].
  177. // The result may have additional unused capacity.
  178. // Clone(nil) returns nil.
  179. func cloneBytes(b []byte) []byte {
  180. if b == nil {
  181. return nil
  182. }
  183. return append([]byte{}, b...)
  184. }
  185. // UnmarshalBinary implements [encoding.BinaryUnmarshaler]
  186. func (o *OID) UnmarshalBinary(b []byte) error {
  187. oid, ok := newOIDFromDER(cloneBytes(b))
  188. if !ok {
  189. return errInvalidOID
  190. }
  191. *o = oid
  192. return nil
  193. }
  194. // Equal returns true when oid and other represents the same Object Identifier.
  195. func (oid OID) Equal(other OID) bool {
  196. // There is only one possible DER encoding of
  197. // each unique Object Identifier.
  198. return bytes.Equal(oid.der, other.der)
  199. }
  200. func parseBase128Int(bytes []byte, initOffset int) (ret, offset int, failed bool) {
  201. offset = initOffset
  202. var ret64 int64
  203. for shifted := 0; offset < len(bytes); shifted++ {
  204. // 5 * 7 bits per byte == 35 bits of data
  205. // Thus the representation is either non-minimal or too large for an int32
  206. if shifted == 5 {
  207. failed = true
  208. return
  209. }
  210. ret64 <<= 7
  211. b := bytes[offset]
  212. // integers should be minimally encoded, so the leading octet should
  213. // never be 0x80
  214. if shifted == 0 && b == 0x80 {
  215. failed = true
  216. return
  217. }
  218. ret64 |= int64(b & 0x7f)
  219. offset++
  220. if b&0x80 == 0 {
  221. ret = int(ret64)
  222. // Ensure that the returned value fits in an int on all platforms
  223. if ret64 > math.MaxInt32 {
  224. failed = true
  225. }
  226. return
  227. }
  228. }
  229. failed = true
  230. return
  231. }
  232. // EqualASN1OID returns whether an OID equals an asn1.ObjectIdentifier. If
  233. // asn1.ObjectIdentifier cannot represent the OID specified by oid, because
  234. // a component of OID requires more than 31 bits, it returns false.
  235. func (oid OID) EqualASN1OID(other asn1.ObjectIdentifier) bool {
  236. if len(other) < 2 {
  237. return false
  238. }
  239. v, offset, failed := parseBase128Int(oid.der, 0)
  240. if failed {
  241. // This should never happen, since we've already parsed the OID,
  242. // but just in case.
  243. return false
  244. }
  245. if v < 80 {
  246. a, b := v/40, v%40
  247. if other[0] != a || other[1] != b {
  248. return false
  249. }
  250. } else {
  251. a, b := 2, v-80
  252. if other[0] != a || other[1] != b {
  253. return false
  254. }
  255. }
  256. i := 2
  257. for ; offset < len(oid.der); i++ {
  258. v, offset, failed = parseBase128Int(oid.der, offset)
  259. if failed {
  260. // Again, shouldn't happen, since we've already parsed
  261. // the OID, but better safe than sorry.
  262. return false
  263. }
  264. if i >= len(other) || v != other[i] {
  265. return false
  266. }
  267. }
  268. return i == len(other)
  269. }
  270. // Strings returns the string representation of the Object Identifier.
  271. func (oid OID) String() string {
  272. var b strings.Builder
  273. b.Grow(32)
  274. const (
  275. valSize = 64 // size in bits of val.
  276. bitsPerByte = 7
  277. maxValSafeShift = (1 << (valSize - bitsPerByte)) - 1
  278. )
  279. var (
  280. start = 0
  281. val = uint64(0)
  282. numBuf = make([]byte, 0, 21)
  283. bigVal *big.Int
  284. overflow bool
  285. )
  286. for i, v := range oid.der {
  287. curVal := v & 0x7F
  288. valEnd := v&0x80 == 0
  289. if valEnd {
  290. if start != 0 {
  291. b.WriteByte('.')
  292. }
  293. }
  294. if !overflow && val > maxValSafeShift {
  295. if bigVal == nil {
  296. bigVal = new(big.Int)
  297. }
  298. bigVal = bigVal.SetUint64(val)
  299. overflow = true
  300. }
  301. if overflow {
  302. bigVal = bigVal.Lsh(bigVal, bitsPerByte).Or(bigVal, big.NewInt(int64(curVal)))
  303. if valEnd {
  304. if start == 0 {
  305. b.WriteString("2.")
  306. bigVal = bigVal.Sub(bigVal, big.NewInt(80))
  307. }
  308. numBuf = bigVal.Append(numBuf, 10)
  309. b.Write(numBuf)
  310. numBuf = numBuf[:0]
  311. val = 0
  312. start = i + 1
  313. overflow = false
  314. }
  315. continue
  316. }
  317. val <<= bitsPerByte
  318. val |= uint64(curVal)
  319. if valEnd {
  320. if start == 0 {
  321. if val < 80 {
  322. b.Write(strconv.AppendUint(numBuf, val/40, 10))
  323. b.WriteByte('.')
  324. b.Write(strconv.AppendUint(numBuf, val%40, 10))
  325. } else {
  326. b.WriteString("2.")
  327. b.Write(strconv.AppendUint(numBuf, val-80, 10))
  328. }
  329. } else {
  330. b.Write(strconv.AppendUint(numBuf, val, 10))
  331. }
  332. val = 0
  333. start = i + 1
  334. }
  335. }
  336. return b.String()
  337. }