Debian Codegraph @

ndr/ndr.go

raw symbols SCIP
1 // Package ndr is a partial implementation of NDR encoding: http://pubs.opengroup.org/onlinepubs/9629399/chap14.htm
2 package ndr
3
4 import (
5 "bytes"
6 "encoding/binary"
7 "fmt"
8 "math"
9 )
10
11 // Useful reference: https://docs.microsoft.com/en-us/windows/desktop/Rpc/rpc-ndr-engine
12
13 /*
14 Serialization Version 1
15 https://msdn.microsoft.com/en-us/library/cc243563.aspx
16
17 Common Header - https://msdn.microsoft.com/en-us/library/cc243890.aspx
18 8 bytes in total:
19 - First byte - Version: Must equal 1
20 - Second byte - 1st 4 bits: Endianess (0=Big; 1=Little); 2nd 4 bits: Character Encoding (0=ASCII; 1=EBCDIC)
21 - 3rd - Floating point representation
22 - 4th - Common Header Length: Must equal 8
23 - 5th - 8th - Filler: MUST be set to 0xcccccccc on marshaling, and SHOULD be ignored during unmarshaling.
24
25 Private Header - https://msdn.microsoft.com/en-us/library/cc243919.aspx
26 8 bytes in total:
27 - First 4 bytes - Indicates the length of a serialized top-level type in the octet stream. It MUST include the padding length and exclude the header itself.
28 - Second 4 bytes - Filler: MUST be set to 0 (zero) during marshaling, and SHOULD be ignored during unmarshaling.
29 */
30
31 const (
32 protocolVersion = 1
33 commonHeaderBytes = 8
34 privateHeaderBytes = 8
35 bigEndian = 0
36 littleEndian = 1
37 ascii = 0
38 ebcdic = 1
39 ieee = 0
40 vax = 1
41 cray = 2
42 ibm = 3
43 )
44
45 // CommonHeader implements the NDR common header: https://msdn.microsoft.com/en-us/library/cc243889.aspx
46 type CommonHeader struct {
47 Version uint8
48 Endianness binary.ByteOrder
49 CharacterEncoding uint8
50 //FloatRepresentation uint8
51 HeaderLength uint16
52 Filler []byte
53 }
54
55 // PrivateHeader implements the NDR private header: https://msdn.microsoft.com/en-us/library/cc243919.aspx
56 type PrivateHeader struct {
57 ObjectBufferLength uint32
58 Filler []byte
59 }
60
61 // ReadHeaders processes the bytes to return the NDR Common and Private headers.
62 func ReadHeaders(b *[]byte) (CommonHeader, PrivateHeader, int, error) {
63 ch, p, err := GetCommonHeader(b)
64 if err != nil {
65 return CommonHeader{}, PrivateHeader{}, 0, err
66 }
67 ph, err := GetPrivateHeader(b, &p, &ch.Endianness)
68 if err != nil {
69 return CommonHeader{}, PrivateHeader{}, 0, err
70 }
71 return ch, ph, p, err
72 }
73
74 // GetCommonHeader processes the bytes to return the NDR Common header.
75 func GetCommonHeader(b *[]byte) (CommonHeader, int, error) {
76 //The first 8 bytes comprise the Common RPC Header for type marshalling.
77 if len(*b) < commonHeaderBytes {
78 return CommonHeader{}, 0, Malformed{EText: "Not enough bytes."}
79 }
80 if (*b)[0] != protocolVersion {
81 return CommonHeader{}, 0, Malformed{EText: fmt.Sprintf("Stream does not indicate a RPC Type serialization of version %v", protocolVersion)}
82 }
83 endian := int((*b)[1] >> 4 & 0xF)
84 if endian != 0 && endian != 1 {
85 return CommonHeader{}, 1, Malformed{EText: "Common header does not indicate a valid endianness"}
86 }
87 charEncoding := uint8((*b)[1] & 0xF)
88 if charEncoding != 0 && charEncoding != 1 {
89 return CommonHeader{}, 1, Malformed{EText: "Common header does not indicate a valid charater encoding"}
90 }
91 var bo binary.ByteOrder
92 switch endian {
93 case littleEndian:
94 bo = binary.LittleEndian
95 case bigEndian:
96 bo = binary.BigEndian
97 }
98 l := bo.Uint16((*b)[2:4])
99 if l != commonHeaderBytes {
100 return CommonHeader{}, 4, Malformed{EText: fmt.Sprintf("Common header does not indicate a valid length: %v instead of %v", uint8((*b)[3]), commonHeaderBytes)}
101 }
102
103 return CommonHeader{
104 Version: uint8((*b)[0]),
105 Endianness: bo,
106 CharacterEncoding: charEncoding,
107 //FloatRepresentation: uint8(b[2]),
108 HeaderLength: l,
109 Filler: (*b)[4:8],
110 }, 8, nil
111 }
112
113 // GetPrivateHeader processes the bytes to return the NDR Private header.
114 func GetPrivateHeader(b *[]byte, p *int, bo *binary.ByteOrder) (PrivateHeader, error) {
115 //The next 8 bytes comprise the RPC type marshalling private header for constructed types.
116 if len(*b) < (privateHeaderBytes) {
117 return PrivateHeader{}, Malformed{EText: "Not enough bytes."}
118 }
119 var l uint32
120 buf := bytes.NewBuffer((*b)[*p : *p+4])
121 binary.Read(buf, *bo, &l)
122 if l%8 != 0 {
123 return PrivateHeader{}, Malformed{EText: "Object buffer length not a multiple of 8"}
124 }
125 *p += 8
126 return PrivateHeader{
127 ObjectBufferLength: l,
128 Filler: (*b)[4:8],
129 }, nil
130 }
131
132 // ReadUint8 reads bytes representing a thirty two bit integer.
133 func ReadUint8(b *[]byte, p *int) (i uint8) {
134 if len((*b)[*p:]) < 1 {
135 return
136 }
137 ensureAlignment(p, 1)
138 i = uint8((*b)[*p])
139 *p++
140 return
141 }
142
143 // ReadUint16 reads bytes representing a thirty two bit integer.
144 func ReadUint16(b *[]byte, p *int, e *binary.ByteOrder) (i uint16) {
145 if len((*b)[*p:]) < 2 {
146 return
147 }
148 ensureAlignment(p, 2)
149 i = (*e).Uint16((*b)[*p : *p+2])
150 *p += 2
151 return
152 }
153
154 // ReadUint32 reads bytes representing a thirty two bit integer.
155 func ReadUint32(b *[]byte, p *int, e *binary.ByteOrder) (i uint32) {
156 if len((*b)[*p:]) < 4 {
157 return
158 }
159 ensureAlignment(p, 4)
160 i = (*e).Uint32((*b)[*p : *p+4])
161 *p += 4
162 return
163 }
164
165 // ReadUint64 reads bytes representing a thirty two bit integer.
166 func ReadUint64(b *[]byte, p *int, e *binary.ByteOrder) (i uint64) {
167 if len((*b)[*p:]) < 8 {
168 return
169 }
170 ensureAlignment(p, 8)
171 i = (*e).Uint64((*b)[*p : *p+8])
172 *p += 8
173 return
174 }
175
176 // ReadBytes reads the number of bytes specified.
177 func ReadBytes(b *[]byte, p *int, s int, e *binary.ByteOrder) (r []byte) {
178 if len((*b)[*p:]) < s {
179 return
180 }
181 buf := bytes.NewBuffer((*b)[*p : *p+s])
182 r = make([]byte, s)
183 binary.Read(buf, *e, &r)
184 *p += s
185 return r
186 }
187
188 // ReadBool reads bytes representing a boolean.
189 func ReadBool(b *[]byte, p *int) bool {
190 if len((*b)[*p:]) < 1 {
191 return false
192 }
193 if ReadUint8(b, p) != 0 {
194 return true
195 }
196 return false
197 }
198
199 // ReadIEEEfloat32 reads bytes representing a IEEE formatted 32 bit float.
200 func ReadIEEEfloat32(b *[]byte, p *int, e *binary.ByteOrder) float32 {
201 ensureAlignment(p, 4)
202 return math.Float32frombits(ReadUint32(b, p, e))
203 }
204
205 // ReadIEEEfloat64 reads bytes representing a IEEE formatted 64 bit float.
206 func ReadIEEEfloat64(b *[]byte, p *int, e *binary.ByteOrder) float64 {
207 ensureAlignment(p, 8)
208 return math.Float64frombits(ReadUint64(b, p, e))
209 }
210
211 // Conformant - don't know the max count in advance
212 // Varying - don't know the actual count in advance
213
214 // ReadConformantVaryingString reads a Conformant and Varying String from the bytes slice.
215 // A conformant and varying string is a string in which the maximum number of elements is not known beforehand and therefore is included in the representation of the string.
216 // NDR represents a conformant and varying string as an ordered sequence of representations of the string elements, preceded by three unsigned long integers.
217 // The first integer gives the maximum number of elements in the string, including the terminator.
218 // The second integer gives the offset from the first index of the string to the first index of the actual subset being passed.
219 // The third integer gives the actual number of elements being passed, including the terminator.
220 func ReadConformantVaryingString(b *[]byte, p *int, e *binary.ByteOrder) (string, error) {
221 m := ReadUint32(b, p, e) // Max element count
222 o := ReadUint32(b, p, e) // Offset
223 a := ReadUint32(b, p, e) // Actual count
224 if a > (m-o) || o > m {
225 return "", Malformed{EText: fmt.Sprintf("Not enough bytes to read conformant varying string. Max: %d, Offset: %d, Actual: %d", m, o, a)}
226 }
227 //Unicode string so each element is 2 bytes
228 //move position based on the offset
229 if o > 0 {
230 *p += int(o * 2)
231 }
232 s := make([]rune, a, a)
233 for i := 0; i < len(s); i++ {
234 s[i] = rune(ReadUint16(b, p, e))
235 }
236 ensureAlignment(p, 4)
237 if len(s) > 0 {
238 // Remove any null terminator
239 if s[len(s)-1] == rune(0) {
240 s = s[:len(s)-1]
241 }
242 }
243 return string(s), nil
244 }
245
246 // NDR defines a special representation for an array whose elements are strings.
247 // In the NDR representation of an array of strings, any conformance information (maximum element counts)
248 // for the strings is removed from the string representations and included in the conformance information for the array,
249 // but any variance information (offsets and actual element counts) for the strings remains with the string representations.
250 //
251 // If the strings are conformant or if any dimension of the array is conformant, then the representation contains maximum element counts for all dimensions of the array and for the strings.
252 //
253 // If the strings are non-conformant and the array is non-conformant, then the representation does not contain any maximum element counts.
254 //
255 // If any dimension of the array is varying, then the representation contains offsets and actual counts for all dimensions of the array.
256 //
257 // If the array is non-varying, then the representation does not contain any offsets or actual counts for the array, although it does contain offsets and actual counts for the strings.
258 func ReadConformantVaryingStringArray(b *[]byte, p *int, e *binary.ByteOrder, n int) ([]string, error) {
259 // Read Max count for each dimension
260 sm := make([]int, n, n)
261 for i := range sm {
262 sm[i] = int(ReadUint32(b, p, e))
263 }
264 // max count for all the strings
265 m := int(ReadUint32(b, p, e))
266 // Read each elements header
267 h := make([]VaryingArrayHeader, n, n)
268 for i := range h {
269 // Offset for the dimension
270 h[i].Offset = int(ReadUint32(b, p, e))
271 // Actual count for the dimension
272 h[i].ActualCount = int(ReadUint32(b, p, e))
273 }
274 sa := make([]string, n, n)
275 for i := range sa {
276 o := int(ReadUint32(b, p, e)) // Offset
277 a := int(ReadUint32(b, p, e)) // Actual count
278 if a > (m-h[i].Offset) || h[i].Offset > m {
279 return sa, Malformed{EText: fmt.Sprintf("Not enough bytes to read conformant varying string. Max: %d, Offset: %d, Actual: %d", m, o, a)}
280 }
281 //Unicode string so each element is 2 bytes
282 //move position based on the offset
283 if o > 0 {
284 *p += int(o * 2)
285 }
286 s := make([]rune, a, a)
287 for i := 0; i < len(s); i++ {
288 s[i] = rune(ReadUint16(b, p, e))
289 }
290 ensureAlignment(p, 4)
291 if len(s) > 0 {
292 // Remove any null terminator
293 if s[len(s)-1] == rune(0) {
294 s = s[:len(s)-1]
295 }
296 }
297 sa[i] = string(s)
298 }
299 return sa, nil
300 }
301
302 type ConformantArrayHeader struct {
303 MaxCount int
304 }
305
306 type VaryingArrayHeader struct {
307 Offset int
308 ActualCount int
309 }
310
311 type ConformantVaryingArrayHeader struct {
312 ConformantArrayHeader
313 VaryingArrayHeader
314 }
315
316 // ReadUniDimensionalConformantArrayHeader reads a UniDimensionalConformantArrayHeader from the bytes slice.
317 func ReadUniDimensionalConformantArrayHeader(b *[]byte, p *int, e *binary.ByteOrder) (h ConformantArrayHeader, err error) {
318 if len((*b)[*p:]) < 4 {
319 err = Malformed{EText: "Not enough bytes to read uni-dimensional conformant array"}
320 return
321 }
322 // Max count int
323 h.MaxCount = int(ReadUint32(b, p, e))
324 return
325 }
326
327 // ReadMultiDimensionalConformantArrayHeader reads a MultiDimensionalConformantArrayHeader of n dimensions from the bytes slice.
328 func ReadMultiDimensionalConformantArrayHeader(b *[]byte, p *int, e *binary.ByteOrder, n int) ([]ConformantArrayHeader, error) {
329 if len((*b)[*p:]) < n*4 {
330 return []ConformantArrayHeader{}, Malformed{EText: "Not enough bytes to read conformant array"}
331 }
332 h := make([]ConformantArrayHeader, n, n)
333 for i := range h {
334 // Max count int for that dimension
335 h[i].MaxCount = int(ReadUint32(b, p, e))
336 }
337 return h, nil
338 }
339
340 // ReadUniDimensionalVaryingArrayHeader reads a UniDimensionalVaryingArrayHeader from the bytes slice.
341 func ReadUniDimensionalVaryingArrayHeader(b *[]byte, p *int, e *binary.ByteOrder) (h VaryingArrayHeader, err error) {
342 if len((*b)[*p:]) < 8 {
343 err = Malformed{EText: "Not enough bytes to read uni-dimensional varying array"}
344 return
345 }
346 h.Offset = int(ReadUint32(b, p, e))
347 h.ActualCount = int(ReadUint32(b, p, e))
348 return
349 }
350
351 // ReadMultiDimensionalVaryingArrayHeader reads a MultiDimensionalVaryingArrayHeader of n dimensions from the bytes slice.
352 func ReadMultiDimensionalVaryingArrayHeader(b *[]byte, p *int, e *binary.ByteOrder, n int) ([]VaryingArrayHeader, error) {
353 if len((*b)[*p:]) < n*4*2 {
354 return []VaryingArrayHeader{}, Malformed{EText: "Not enough bytes to read varying array"}
355 }
356 h := make([]VaryingArrayHeader, n, n)
357 for i := range h {
358 // Offset for the dimension
359 h[i].Offset = int(ReadUint32(b, p, e))
360 // Actual count for the dimension
361 h[i].ActualCount = int(ReadUint32(b, p, e))
362 }
363 return h, nil
364 }
365
366 // ReadUniDimensionalConformantVaryingArrayHeader reads a UniDimensionalConformantVaryingArrayHeader from the bytes slice.
367 func ReadUniDimensionalConformantVaryingArrayHeader(b *[]byte, p *int, e *binary.ByteOrder) (h ConformantVaryingArrayHeader, err error) {
368 if len((*b)[*p:]) < 12 {
369 err = Malformed{EText: "Not enough bytes to read uni-dimensional conformant varying array"}
370 return
371 }
372 h.MaxCount = int(ReadUint32(b, p, e))
373 h.Offset = int(ReadUint32(b, p, e))
374 h.ActualCount = int(ReadUint32(b, p, e))
375 if h.ActualCount > (h.MaxCount-h.Offset) || h.Offset > h.MaxCount {
376 err = Malformed{EText: fmt.Sprintf("Not enough bytes to read uni-dimensional conformant varying array. Max: %d, Offset: %d, Actual: %d", h.MaxCount, h.Offset, h.ActualCount)}
377 }
378 return
379 }
380
381 // ReadMultiDimensionalConformantVaryingArrayHeader reads a MultiDimensionalConformantVaryingArrayHeader of n dimensions from the bytes slice.
382 func ReadMultiDimensionalConformantVaryingArrayHeader(b *[]byte, p *int, e *binary.ByteOrder, n int) ([]ConformantVaryingArrayHeader, error) {
383 if len((*b)[*p:]) < n*4*3 {
384 return []ConformantVaryingArrayHeader{}, Malformed{EText: "Not enough bytes to read conformant varying array"}
385 }
386 h := make([]ConformantVaryingArrayHeader, n, n)
387 for i := range h {
388 h[i].MaxCount = int(ReadUint32(b, p, e))
389 }
390 for i := range h {
391 h[i].Offset = int(ReadUint32(b, p, e))
392 h[i].ActualCount = int(ReadUint32(b, p, e))
393 }
394 return h, nil
395 }
396
397 func ensureAlignment(p *int, byteSize int) {
398 if byteSize > 0 {
399 if s := *p % byteSize; s != 0 {
400 *p += byteSize - s
401 }
402 }
403 }
404
405 // ReadUTF16String returns a string that is UTF16 encoded in a byte slice. n is the number of bytes representing the string
406 func ReadUTF16String(n int, b *[]byte, p *int, e *binary.ByteOrder) string {
407 //Length divided by 2 as each run is 16bits = 2bytes
408 s := make([]rune, n/2, n/2)
409 for i := 0; i < len(s); i++ {
410 s[i] = rune(ReadUint16(b, p, e))
411 }
412 return string(s)
413 }
414
415 //func DebugByteSteamView(p int, b []byte) {
416 // fmt.Fprintf(os.Stderr, "Full %v\n", b)
417 // fmt.Fprintf(os.Stderr, "At pos %v\n", b[p:])
418 // fmt.Fprintln(os.Stderr, "uint32 view:")
419 // var e binary.ByteOrder = binary.LittleEndian
420 // var sl []int
421 // for p < len(b) {
422 // l := p
423 // i := ReadUint32(&b, &p, &e)
424 // if l+4 <= len(b) {
425 // fmt.Fprintf(os.Stderr, "%d:\t%v\t\t%d\n", l, b[l:l+4], i)
426 // } else {
427 // fmt.Fprintf(os.Stderr, "%d:\t%v\t\t%d\n", l, b[l:], i)
428 // }
429 //
430 // sc := l - 8
431 // if ReadUint32(&b, &sc, &e) == i {
432 // //Possible str
433 // sc -= 4
434 // sl = append(sl, sc)
435 // }
436 // }
437 // for _, i := range sl {
438 // sc := i
439 // s, e := ReadConformantVaryingString(&b, &i, &e)
440 // if e == nil {
441 // fmt.Fprintf(os.Stderr, "Potential string at %d: %s\n", sc, s)
442 // }
443 // }
444 //}