oid.go 8.6 KB

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