r4088: Get medieval on our ass about malloc.... :-). Take control of all our allocation
[amitay/samba.git] / source3 / rpc_parse / parse_prs.c
1 /* 
2    Unix SMB/CIFS implementation.
3    Samba memory buffer functions
4    Copyright (C) Andrew Tridgell              1992-1997
5    Copyright (C) Luke Kenneth Casson Leighton 1996-1997
6    Copyright (C) Jeremy Allison               1999
7    Copyright (C) Andrew Bartlett              2003.
8    
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 2 of the License, or
12    (at your option) any later version.
13    
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18    
19    You should have received a copy of the GNU General Public License
20    along with this program; if not, write to the Free Software
21    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22 */
23
24 #include "includes.h"
25
26 #undef DBGC_CLASS
27 #define DBGC_CLASS DBGC_RPC_PARSE
28
29 /**
30  * Dump a prs to a file: from the current location through to the end.
31  **/
32 void prs_dump(char *name, int v, prs_struct *ps)
33 {
34         prs_dump_region(name, v, ps, ps->data_offset, ps->buffer_size);
35 }
36
37
38 /**
39  * Dump from the start of the prs to the current location.
40  **/
41 void prs_dump_before(char *name, int v, prs_struct *ps)
42 {
43         prs_dump_region(name, v, ps, 0, ps->data_offset);
44 }
45
46
47 /**
48  * Dump everything from the start of the prs up to the current location.
49  **/
50 void prs_dump_region(char *name, int v, prs_struct *ps,
51                      int from_off, int to_off)
52 {
53         int fd, i;
54         pstring fname;
55         if (DEBUGLEVEL < 50) return;
56         for (i=1;i<100;i++) {
57                 if (v != -1) {
58                         slprintf(fname,sizeof(fname)-1, "/tmp/%s_%d.%d.prs", name, v, i);
59                 } else {
60                         slprintf(fname,sizeof(fname)-1, "/tmp/%s.%d.prs", name, i);
61                 }
62                 fd = open(fname, O_WRONLY|O_CREAT|O_EXCL, 0644);
63                 if (fd != -1 || errno != EEXIST) break;
64         }
65         if (fd != -1) {
66                 write(fd, ps->data_p + from_off, to_off - from_off);
67                 close(fd);
68                 DEBUG(0,("created %s\n", fname));
69         }
70 }
71
72
73
74 /*******************************************************************
75  debug output for parsing info.
76
77  XXXX side-effect of this function is to increase the debug depth XXXX
78
79  ********************************************************************/
80 void prs_debug(prs_struct *ps, int depth, const char *desc, const char *fn_name)
81 {
82         DEBUG(5+depth, ("%s%06x %s %s\n", tab_depth(depth), ps->data_offset, fn_name, desc));
83 }
84
85
86 /**
87  * Initialise an expandable parse structure.
88  *
89  * @param size Initial buffer size.  If >0, a new buffer will be
90  * created with malloc().
91  *
92  * @return False if allocation fails, otherwise True.
93  **/
94 BOOL prs_init(prs_struct *ps, uint32 size, TALLOC_CTX *ctx, BOOL io)
95 {
96         ZERO_STRUCTP(ps);
97         ps->io = io;
98         ps->bigendian_data = RPC_LITTLE_ENDIAN;
99         ps->align = RPC_PARSE_ALIGN;
100         ps->is_dynamic = False;
101         ps->data_offset = 0;
102         ps->buffer_size = 0;
103         ps->data_p = NULL;
104         ps->mem_ctx = ctx;
105
106         if (size != 0) {
107                 ps->buffer_size = size;
108                 if((ps->data_p = (char *)SMB_MALLOC((size_t)size)) == NULL) {
109                         DEBUG(0,("prs_init: malloc fail for %u bytes.\n", (unsigned int)size));
110                         return False;
111                 }
112                 memset(ps->data_p, '\0', (size_t)size);
113                 ps->is_dynamic = True; /* We own this memory. */
114         }
115
116         return True;
117 }
118
119 /*******************************************************************
120  Delete the memory in a parse structure - if we own it.
121  ********************************************************************/
122
123 void prs_mem_free(prs_struct *ps)
124 {
125         if(ps->is_dynamic)
126                 SAFE_FREE(ps->data_p);
127         ps->is_dynamic = False;
128         ps->buffer_size = 0;
129         ps->data_offset = 0;
130 }
131
132 /*******************************************************************
133  Clear the memory in a parse structure.
134  ********************************************************************/
135
136 void prs_mem_clear(prs_struct *ps)
137 {
138         if (ps->buffer_size)
139                 memset(ps->data_p, '\0', (size_t)ps->buffer_size);
140 }
141
142 /*******************************************************************
143  Allocate memory when unmarshalling... Always zero clears.
144  ********************************************************************/
145
146 #if defined(PARANOID_MALLOC_CHECKER)
147 char *prs_alloc_mem_(prs_struct *ps, size_t size, unsigned int count)
148 #else
149 char *prs_alloc_mem(prs_struct *ps, size_t size, unsigned int count)
150 #endif
151 {
152         char *ret = NULL;
153
154         if (size) {
155                 /* We can't call the type-safe version here. */
156 #if defined(PARANOID_MALLOC_CHECKER)
157                 ret = talloc_zero_array_(ps->mem_ctx, size, count);
158 #else
159                 ret = talloc_zero_array(ps->mem_ctx, size, count);
160 #endif
161         }
162         return ret;
163 }
164
165 /*******************************************************************
166  Return the current talloc context we're using.
167  ********************************************************************/
168
169 TALLOC_CTX *prs_get_mem_context(prs_struct *ps)
170 {
171         return ps->mem_ctx;
172 }
173
174 /*******************************************************************
175  Hand some already allocated memory to a prs_struct.
176  ********************************************************************/
177
178 void prs_give_memory(prs_struct *ps, char *buf, uint32 size, BOOL is_dynamic)
179 {
180         ps->is_dynamic = is_dynamic;
181         ps->data_p = buf;
182         ps->buffer_size = size;
183 }
184
185 /*******************************************************************
186  Take some memory back from a prs_struct.
187  ********************************************************************/
188
189 char *prs_take_memory(prs_struct *ps, uint32 *psize)
190 {
191         char *ret = ps->data_p;
192         if(psize)
193                 *psize = ps->buffer_size;
194         ps->is_dynamic = False;
195         prs_mem_free(ps);
196         return ret;
197 }
198
199 /*******************************************************************
200  Set a prs_struct to exactly a given size. Will grow or tuncate if neccessary.
201  ********************************************************************/
202
203 BOOL prs_set_buffer_size(prs_struct *ps, uint32 newsize)
204 {
205         if (newsize > ps->buffer_size)
206                 return prs_force_grow(ps, newsize - ps->buffer_size);
207
208         if (newsize < ps->buffer_size) {
209                 char *new_data_p = SMB_REALLOC(ps->data_p, newsize);
210                 /* if newsize is zero, Realloc acts like free() & returns NULL*/
211                 if (new_data_p == NULL && newsize != 0) {
212                         DEBUG(0,("prs_set_buffer_size: Realloc failure for size %u.\n",
213                                 (unsigned int)newsize));
214                         DEBUG(0,("prs_set_buffer_size: Reason %s\n",strerror(errno)));
215                         return False;
216                 }
217                 ps->data_p = new_data_p;
218                 ps->buffer_size = newsize;
219         }
220
221         return True;
222 }
223
224 /*******************************************************************
225  Attempt, if needed, to grow a data buffer.
226  Also depends on the data stream mode (io).
227  ********************************************************************/
228
229 BOOL prs_grow(prs_struct *ps, uint32 extra_space)
230 {
231         uint32 new_size;
232         char *new_data;
233
234         ps->grow_size = MAX(ps->grow_size, ps->data_offset + extra_space);
235
236         if(ps->data_offset + extra_space <= ps->buffer_size)
237                 return True;
238
239         /*
240          * We cannot grow the buffer if we're not reading
241          * into the prs_struct, or if we don't own the memory.
242          */
243
244         if(UNMARSHALLING(ps) || !ps->is_dynamic) {
245                 DEBUG(0,("prs_grow: Buffer overflow - unable to expand buffer by %u bytes.\n",
246                                 (unsigned int)extra_space));
247                 return False;
248         }
249         
250         /*
251          * Decide how much extra space we really need.
252          */
253
254         extra_space -= (ps->buffer_size - ps->data_offset);
255         if(ps->buffer_size == 0) {
256                 /*
257                  * Ensure we have at least a PDU's length, or extra_space, whichever
258                  * is greater.
259                  */
260
261                 new_size = MAX(MAX_PDU_FRAG_LEN,extra_space);
262
263                 if((new_data = SMB_MALLOC(new_size)) == NULL) {
264                         DEBUG(0,("prs_grow: Malloc failure for size %u.\n", (unsigned int)new_size));
265                         return False;
266                 }
267                 memset(new_data, '\0', (size_t)new_size );
268         } else {
269                 /*
270                  * If the current buffer size is bigger than the space needed, just 
271                  * double it, else add extra_space.
272                  */
273                 new_size = MAX(ps->buffer_size*2, ps->buffer_size + extra_space);               
274
275                 if ((new_data = SMB_REALLOC(ps->data_p, new_size)) == NULL) {
276                         DEBUG(0,("prs_grow: Realloc failure for size %u.\n",
277                                 (unsigned int)new_size));
278                         return False;
279                 }
280
281                 memset(&new_data[ps->buffer_size], '\0', (size_t)(new_size - ps->buffer_size));
282         }
283         ps->buffer_size = new_size;
284         ps->data_p = new_data;
285
286         return True;
287 }
288
289 /*******************************************************************
290  Attempt to force a data buffer to grow by len bytes.
291  This is only used when appending more data onto a prs_struct
292  when reading an rpc reply, before unmarshalling it.
293  ********************************************************************/
294
295 BOOL prs_force_grow(prs_struct *ps, uint32 extra_space)
296 {
297         uint32 new_size = ps->buffer_size + extra_space;
298         char *new_data;
299
300         if(!UNMARSHALLING(ps) || !ps->is_dynamic) {
301                 DEBUG(0,("prs_force_grow: Buffer overflow - unable to expand buffer by %u bytes.\n",
302                                 (unsigned int)extra_space));
303                 return False;
304         }
305
306         if((new_data = SMB_REALLOC(ps->data_p, new_size)) == NULL) {
307                 DEBUG(0,("prs_force_grow: Realloc failure for size %u.\n",
308                         (unsigned int)new_size));
309                 return False;
310         }
311
312         memset(&new_data[ps->buffer_size], '\0', (size_t)(new_size - ps->buffer_size));
313
314         ps->buffer_size = new_size;
315         ps->data_p = new_data;
316
317         return True;
318 }
319
320 /*******************************************************************
321  Get the data pointer (external interface).
322 ********************************************************************/
323
324 char *prs_data_p(prs_struct *ps)
325 {
326         return ps->data_p;
327 }
328
329 /*******************************************************************
330  Get the current data size (external interface).
331  ********************************************************************/
332
333 uint32 prs_data_size(prs_struct *ps)
334 {
335         return ps->buffer_size;
336 }
337
338 /*******************************************************************
339  Fetch the current offset (external interface).
340  ********************************************************************/
341
342 uint32 prs_offset(prs_struct *ps)
343 {
344         return ps->data_offset;
345 }
346
347 /*******************************************************************
348  Set the current offset (external interface).
349  ********************************************************************/
350
351 BOOL prs_set_offset(prs_struct *ps, uint32 offset)
352 {
353         if(offset <= ps->data_offset) {
354                 ps->data_offset = offset;
355                 return True;
356         }
357
358         if(!prs_grow(ps, offset - ps->data_offset))
359                 return False;
360
361         ps->data_offset = offset;
362         return True;
363 }
364
365 /*******************************************************************
366  Append the data from one parse_struct into another.
367  ********************************************************************/
368
369 BOOL prs_append_prs_data(prs_struct *dst, prs_struct *src)
370 {
371         if (prs_offset(src) == 0)
372                 return True;
373
374         if(!prs_grow(dst, prs_offset(src)))
375                 return False;
376
377         memcpy(&dst->data_p[dst->data_offset], src->data_p, (size_t)prs_offset(src));
378         dst->data_offset += prs_offset(src);
379
380         return True;
381 }
382
383 /*******************************************************************
384  Append some data from one parse_struct into another.
385  ********************************************************************/
386
387 BOOL prs_append_some_prs_data(prs_struct *dst, prs_struct *src, int32 start, uint32 len)
388 {       
389         if (len == 0)
390                 return True;
391
392         if(!prs_grow(dst, len))
393                 return False;
394         
395         memcpy(&dst->data_p[dst->data_offset], src->data_p + start, (size_t)len);
396         dst->data_offset += len;
397
398         return True;
399 }
400
401 /*******************************************************************
402  Append the data from a buffer into a parse_struct.
403  ********************************************************************/
404
405 BOOL prs_copy_data_in(prs_struct *dst, char *src, uint32 len)
406 {
407         if (len == 0)
408                 return True;
409
410         if(!prs_grow(dst, len))
411                 return False;
412
413         memcpy(&dst->data_p[dst->data_offset], src, (size_t)len);
414         dst->data_offset += len;
415
416         return True;
417 }
418
419 /*******************************************************************
420  Copy some data from a parse_struct into a buffer.
421  ********************************************************************/
422
423 BOOL prs_copy_data_out(char *dst, prs_struct *src, uint32 len)
424 {
425         if (len == 0)
426                 return True;
427
428         if(!prs_mem_get(src, len))
429                 return False;
430
431         memcpy(dst, &src->data_p[src->data_offset], (size_t)len);
432         src->data_offset += len;
433
434         return True;
435 }
436
437 /*******************************************************************
438  Copy all the data from a parse_struct into a buffer.
439  ********************************************************************/
440
441 BOOL prs_copy_all_data_out(char *dst, prs_struct *src)
442 {
443         uint32 len = prs_offset(src);
444
445         if (!len)
446                 return True;
447
448         prs_set_offset(src, 0);
449         return prs_copy_data_out(dst, src, len);
450 }
451
452 /*******************************************************************
453  Set the data as X-endian (external interface).
454  ********************************************************************/
455
456 void prs_set_endian_data(prs_struct *ps, BOOL endian)
457 {
458         ps->bigendian_data = endian;
459 }
460
461 /*******************************************************************
462  Align a the data_len to a multiple of align bytes - filling with
463  zeros.
464  ********************************************************************/
465
466 BOOL prs_align(prs_struct *ps)
467 {
468         uint32 mod = ps->data_offset & (ps->align-1);
469
470         if (ps->align != 0 && mod != 0) {
471                 uint32 extra_space = (ps->align - mod);
472                 if(!prs_grow(ps, extra_space))
473                         return False;
474                 memset(&ps->data_p[ps->data_offset], '\0', (size_t)extra_space);
475                 ps->data_offset += extra_space;
476         }
477
478         return True;
479 }
480
481 /******************************************************************
482  Align on a 2 byte boundary
483  *****************************************************************/
484  
485 BOOL prs_align_uint16(prs_struct *ps)
486 {
487         BOOL ret;
488         uint8 old_align = ps->align;
489
490         ps->align = 2;
491         ret = prs_align(ps);
492         ps->align = old_align;
493         
494         return ret;
495 }
496
497 /******************************************************************
498  Align on a 8 byte boundary
499  *****************************************************************/
500  
501 BOOL prs_align_uint64(prs_struct *ps)
502 {
503         BOOL ret;
504         uint8 old_align = ps->align;
505
506         ps->align = 8;
507         ret = prs_align(ps);
508         ps->align = old_align;
509         
510         return ret;
511 }
512
513 /*******************************************************************
514  Align only if required (for the unistr2 string mainly)
515  ********************************************************************/
516
517 BOOL prs_align_needed(prs_struct *ps, uint32 needed)
518 {
519         if (needed==0)
520                 return True;
521         else
522                 return prs_align(ps);
523 }
524
525 /*******************************************************************
526  Ensure we can read/write to a given offset.
527  ********************************************************************/
528
529 char *prs_mem_get(prs_struct *ps, uint32 extra_size)
530 {
531         if(UNMARSHALLING(ps)) {
532                 /*
533                  * If reading, ensure that we can read the requested size item.
534                  */
535                 if (ps->data_offset + extra_size > ps->buffer_size) {
536                         DEBUG(0,("prs_mem_get: reading data of size %u would overrun buffer.\n",
537                                         (unsigned int)extra_size ));
538                         return NULL;
539                 }
540         } else {
541                 /*
542                  * Writing - grow the buffer if needed.
543                  */
544                 if(!prs_grow(ps, extra_size))
545                         return NULL;
546         }
547         return &ps->data_p[ps->data_offset];
548 }
549
550 /*******************************************************************
551  Change the struct type.
552  ********************************************************************/
553
554 void prs_switch_type(prs_struct *ps, BOOL io)
555 {
556         if ((ps->io ^ io) == True)
557                 ps->io=io;
558 }
559
560 /*******************************************************************
561  Force a prs_struct to be dynamic even when it's size is 0.
562  ********************************************************************/
563
564 void prs_force_dynamic(prs_struct *ps)
565 {
566         ps->is_dynamic=True;
567 }
568
569 /*******************************************************************
570  Stream a uint8.
571  ********************************************************************/
572
573 BOOL prs_uint8(const char *name, prs_struct *ps, int depth, uint8 *data8)
574 {
575         char *q = prs_mem_get(ps, 1);
576         if (q == NULL)
577                 return False;
578
579     if (UNMARSHALLING(ps))
580                 *data8 = CVAL(q,0);
581         else
582                 SCVAL(q,0,*data8);
583
584     DEBUG(5,("%s%04x %s: %02x\n", tab_depth(depth), ps->data_offset, name, *data8));
585
586         ps->data_offset += 1;
587
588         return True;
589 }
590
591 /*******************************************************************
592  Stream a uint16.
593  ********************************************************************/
594
595 BOOL prs_uint16(const char *name, prs_struct *ps, int depth, uint16 *data16)
596 {
597         char *q = prs_mem_get(ps, sizeof(uint16));
598         if (q == NULL)
599                 return False;
600
601     if (UNMARSHALLING(ps)) {
602                 if (ps->bigendian_data)
603                         *data16 = RSVAL(q,0);
604                 else
605                         *data16 = SVAL(q,0);
606     } else {
607                 if (ps->bigendian_data)
608                         RSSVAL(q,0,*data16);
609                 else
610                         SSVAL(q,0,*data16);
611         }
612
613         DEBUG(5,("%s%04x %s: %04x\n", tab_depth(depth), ps->data_offset, name, *data16));
614
615         ps->data_offset += sizeof(uint16);
616
617         return True;
618 }
619
620 /*******************************************************************
621  Stream a uint32.
622  ********************************************************************/
623
624 BOOL prs_uint32(const char *name, prs_struct *ps, int depth, uint32 *data32)
625 {
626         char *q = prs_mem_get(ps, sizeof(uint32));
627         if (q == NULL)
628                 return False;
629
630         if (UNMARSHALLING(ps)) {
631                 if (ps->bigendian_data)
632                         *data32 = RIVAL(q,0);
633                 else
634                         *data32 = IVAL(q,0);
635         } else {
636                 if (ps->bigendian_data)
637                         RSIVAL(q,0,*data32);
638                 else
639                         SIVAL(q,0,*data32);
640         }
641
642         DEBUG(5,("%s%04x %s: %08x\n", tab_depth(depth), ps->data_offset, name, *data32));
643
644         ps->data_offset += sizeof(uint32);
645
646         return True;
647 }
648
649 /*******************************************************************
650  Stream a NTSTATUS
651  ********************************************************************/
652
653 BOOL prs_ntstatus(const char *name, prs_struct *ps, int depth, NTSTATUS *status)
654 {
655         char *q = prs_mem_get(ps, sizeof(uint32));
656         if (q == NULL)
657                 return False;
658
659         if (UNMARSHALLING(ps)) {
660                 if (ps->bigendian_data)
661                         *status = NT_STATUS(RIVAL(q,0));
662                 else
663                         *status = NT_STATUS(IVAL(q,0));
664         } else {
665                 if (ps->bigendian_data)
666                         RSIVAL(q,0,NT_STATUS_V(*status));
667                 else
668                         SIVAL(q,0,NT_STATUS_V(*status));
669         }
670
671         DEBUG(5,("%s%04x %s: %s\n", tab_depth(depth), ps->data_offset, name, 
672                  nt_errstr(*status)));
673
674         ps->data_offset += sizeof(uint32);
675
676         return True;
677 }
678
679 /*******************************************************************
680  Stream a WERROR
681  ********************************************************************/
682
683 BOOL prs_werror(const char *name, prs_struct *ps, int depth, WERROR *status)
684 {
685         char *q = prs_mem_get(ps, sizeof(uint32));
686         if (q == NULL)
687                 return False;
688
689         if (UNMARSHALLING(ps)) {
690                 if (ps->bigendian_data)
691                         *status = W_ERROR(RIVAL(q,0));
692                 else
693                         *status = W_ERROR(IVAL(q,0));
694         } else {
695                 if (ps->bigendian_data)
696                         RSIVAL(q,0,W_ERROR_V(*status));
697                 else
698                         SIVAL(q,0,W_ERROR_V(*status));
699         }
700
701         DEBUG(5,("%s%04x %s: %s\n", tab_depth(depth), ps->data_offset, name, 
702                  dos_errstr(*status)));
703
704         ps->data_offset += sizeof(uint32);
705
706         return True;
707 }
708
709
710 /******************************************************************
711  Stream an array of uint8s. Length is number of uint8s.
712  ********************************************************************/
713
714 BOOL prs_uint8s(BOOL charmode, const char *name, prs_struct *ps, int depth, uint8 *data8s, int len)
715 {
716         int i;
717         char *q = prs_mem_get(ps, len);
718         if (q == NULL)
719                 return False;
720
721         if (UNMARSHALLING(ps)) {
722                 for (i = 0; i < len; i++)
723                         data8s[i] = CVAL(q,i);
724         } else {
725                 for (i = 0; i < len; i++)
726                         SCVAL(q, i, data8s[i]);
727         }
728
729     DEBUG(5,("%s%04x %s: ", tab_depth(depth), ps->data_offset ,name));
730     if (charmode)
731                 print_asc(5, (unsigned char*)data8s, len);
732         else {
733         for (i = 0; i < len; i++)
734                         DEBUG(5,("%02x ", data8s[i]));
735         }
736     DEBUG(5,("\n"));
737
738         ps->data_offset += len;
739
740         return True;
741 }
742
743 /******************************************************************
744  Stream an array of uint16s. Length is number of uint16s.
745  ********************************************************************/
746
747 BOOL prs_uint16s(BOOL charmode, const char *name, prs_struct *ps, int depth, uint16 *data16s, int len)
748 {
749         int i;
750         char *q = prs_mem_get(ps, len * sizeof(uint16));
751         if (q == NULL)
752                 return False;
753
754         if (UNMARSHALLING(ps)) {
755                 if (ps->bigendian_data) {
756                         for (i = 0; i < len; i++)
757                                 data16s[i] = RSVAL(q, 2*i);
758                 } else {
759                         for (i = 0; i < len; i++)
760                                 data16s[i] = SVAL(q, 2*i);
761                 }
762         } else {
763                 if (ps->bigendian_data) {
764                         for (i = 0; i < len; i++)
765                                 RSSVAL(q, 2*i, data16s[i]);
766                 } else {
767                         for (i = 0; i < len; i++)
768                                 SSVAL(q, 2*i, data16s[i]);
769                 }
770         }
771
772         DEBUG(5,("%s%04x %s: ", tab_depth(depth), ps->data_offset, name));
773         if (charmode)
774                 print_asc(5, (unsigned char*)data16s, 2*len);
775         else {
776                 for (i = 0; i < len; i++)
777                         DEBUG(5,("%04x ", data16s[i]));
778         }
779     DEBUG(5,("\n"));
780
781         ps->data_offset += (len * sizeof(uint16));
782
783         return True;
784 }
785
786 /******************************************************************
787  Start using a function for streaming unicode chars. If unmarshalling,
788  output must be little-endian, if marshalling, input must be little-endian.
789  ********************************************************************/
790
791 static void dbg_rw_punival(BOOL charmode, const char *name, int depth, prs_struct *ps,
792                                                         char *in_buf, char *out_buf, int len)
793 {
794         int i;
795
796         if (UNMARSHALLING(ps)) {
797                 if (ps->bigendian_data) {
798                         for (i = 0; i < len; i++)
799                                 SSVAL(out_buf,2*i,RSVAL(in_buf, 2*i));
800                 } else {
801                         for (i = 0; i < len; i++)
802                                 SSVAL(out_buf, 2*i, SVAL(in_buf, 2*i));
803                 }
804         } else {
805                 if (ps->bigendian_data) {
806                         for (i = 0; i < len; i++)
807                                 RSSVAL(in_buf, 2*i, SVAL(out_buf,2*i));
808                 } else {
809                         for (i = 0; i < len; i++)
810                                 SSVAL(in_buf, 2*i, SVAL(out_buf,2*i));
811                 }
812         }
813
814         DEBUG(5,("%s%04x %s: ", tab_depth(depth), ps->data_offset, name));
815         if (charmode)
816                 print_asc(5, (unsigned char*)out_buf, 2*len);
817         else {
818                 for (i = 0; i < len; i++)
819                         DEBUG(5,("%04x ", out_buf[i]));
820         }
821     DEBUG(5,("\n"));
822 }
823
824 /******************************************************************
825  Stream a unistr. Always little endian.
826  ********************************************************************/
827
828 BOOL prs_uint16uni(BOOL charmode, const char *name, prs_struct *ps, int depth, uint16 *data16s, int len)
829 {
830         char *q = prs_mem_get(ps, len * sizeof(uint16));
831         if (q == NULL)
832                 return False;
833
834         dbg_rw_punival(charmode, name, depth, ps, q, (char *)data16s, len);
835         ps->data_offset += (len * sizeof(uint16));
836
837         return True;
838 }
839
840 /******************************************************************
841  Stream an array of uint32s. Length is number of uint32s.
842  ********************************************************************/
843
844 BOOL prs_uint32s(BOOL charmode, const char *name, prs_struct *ps, int depth, uint32 *data32s, int len)
845 {
846         int i;
847         char *q = prs_mem_get(ps, len * sizeof(uint32));
848         if (q == NULL)
849                 return False;
850
851         if (UNMARSHALLING(ps)) {
852                 if (ps->bigendian_data) {
853                         for (i = 0; i < len; i++)
854                                 data32s[i] = RIVAL(q, 4*i);
855                 } else {
856                         for (i = 0; i < len; i++)
857                                 data32s[i] = IVAL(q, 4*i);
858                 }
859         } else {
860                 if (ps->bigendian_data) {
861                         for (i = 0; i < len; i++)
862                                 RSIVAL(q, 4*i, data32s[i]);
863                 } else {
864                         for (i = 0; i < len; i++)
865                                 SIVAL(q, 4*i, data32s[i]);
866                 }
867         }
868
869         DEBUG(5,("%s%04x %s: ", tab_depth(depth), ps->data_offset, name));
870         if (charmode)
871                 print_asc(5, (unsigned char*)data32s, 4*len);
872         else {
873                 for (i = 0; i < len; i++)
874                         DEBUG(5,("%08x ", data32s[i]));
875         }
876     DEBUG(5,("\n"));
877
878         ps->data_offset += (len * sizeof(uint32));
879
880         return True;
881 }
882
883 /******************************************************************
884  Stream an array of unicode string, length/buffer specified separately,
885  in uint16 chars. The unicode string is already in little-endian format.
886  ********************************************************************/
887
888 BOOL prs_buffer5(BOOL charmode, const char *name, prs_struct *ps, int depth, BUFFER5 *str)
889 {
890         char *p;
891         char *q = prs_mem_get(ps, str->buf_len * sizeof(uint16));
892         if (q == NULL)
893                 return False;
894
895         if (UNMARSHALLING(ps)) {
896                 str->buffer = PRS_ALLOC_MEM(ps,uint16,str->buf_len);
897                 if (str->buffer == NULL)
898                         return False;
899         }
900
901         /* If the string is empty, we don't have anything to stream */
902         if (str->buf_len==0)
903                 return True;
904
905         p = (char *)str->buffer;
906
907         dbg_rw_punival(charmode, name, depth, ps, q, p, str->buf_len);
908         
909         ps->data_offset += (str->buf_len * sizeof(uint16));
910
911         return True;
912 }
913
914 /******************************************************************
915  Stream a "not" unicode string, length/buffer specified separately,
916  in byte chars. String is in little-endian format.
917  ********************************************************************/
918
919 BOOL prs_buffer2(BOOL charmode, const char *name, prs_struct *ps, int depth, BUFFER2 *str)
920 {
921         char *p;
922         char *q = prs_mem_get(ps, str->buf_len);
923         if (q == NULL)
924                 return False;
925
926         if (UNMARSHALLING(ps)) {
927                 if ( str->buf_len ) {
928                         str->buffer = PRS_ALLOC_MEM(ps, uint16, str->buf_len);
929                         if ( str->buffer == NULL )
930                                 return False;
931                 }
932         }
933
934         p = (char *)str->buffer;
935
936         dbg_rw_punival(charmode, name, depth, ps, q, p, str->buf_len/2);
937         ps->data_offset += str->buf_len;
938
939         return True;
940 }
941
942 /******************************************************************
943  Stream a string, length/buffer specified separately,
944  in uint8 chars.
945  ********************************************************************/
946
947 BOOL prs_string2(BOOL charmode, const char *name, prs_struct *ps, int depth, STRING2 *str)
948 {
949         unsigned int i;
950         char *q = prs_mem_get(ps, str->str_max_len);
951         if (q == NULL)
952                 return False;
953
954         if (UNMARSHALLING(ps)) {
955                 str->buffer = PRS_ALLOC_MEM(ps,unsigned char, str->str_max_len);
956                 if (str->buffer == NULL)
957                         return False;
958         }
959
960         if (UNMARSHALLING(ps)) {
961                 for (i = 0; i < str->str_str_len; i++)
962                         str->buffer[i] = CVAL(q,i);
963         } else {
964                 for (i = 0; i < str->str_str_len; i++)
965                         SCVAL(q, i, str->buffer[i]);
966         }
967
968     DEBUG(5,("%s%04x %s: ", tab_depth(depth), ps->data_offset, name));
969     if (charmode)
970                 print_asc(5, (unsigned char*)str->buffer, str->str_str_len);
971         else {
972         for (i = 0; i < str->str_str_len; i++)
973                         DEBUG(5,("%02x ", str->buffer[i]));
974         }
975     DEBUG(5,("\n"));
976
977         ps->data_offset += str->str_str_len;
978
979         return True;
980 }
981
982 /******************************************************************
983  Stream a unicode string, length/buffer specified separately,
984  in uint16 chars. The unicode string is already in little-endian format.
985  ********************************************************************/
986
987 BOOL prs_unistr2(BOOL charmode, const char *name, prs_struct *ps, int depth, UNISTR2 *str)
988 {
989         char *p;
990         char *q = prs_mem_get(ps, str->uni_str_len * sizeof(uint16));
991         if (q == NULL)
992                 return False;
993
994         /* If the string is empty, we don't have anything to stream */
995         if (str->uni_str_len==0)
996                 return True;
997
998         if (UNMARSHALLING(ps)) {
999                 str->buffer = PRS_ALLOC_MEM(ps,uint16,str->uni_max_len);
1000                 if (str->buffer == NULL)
1001                         return False;
1002         }
1003
1004         p = (char *)str->buffer;
1005
1006         dbg_rw_punival(charmode, name, depth, ps, q, p, str->uni_str_len);
1007         
1008         ps->data_offset += (str->uni_str_len * sizeof(uint16));
1009
1010         return True;
1011 }
1012
1013 /******************************************************************
1014  Stream a unicode string, length/buffer specified separately,
1015  in uint16 chars. The unicode string is already in little-endian format.
1016  ********************************************************************/
1017
1018 BOOL prs_unistr3(BOOL charmode, const char *name, UNISTR3 *str, prs_struct *ps, int depth)
1019 {
1020         char *p;
1021         char *q = prs_mem_get(ps, str->uni_str_len * sizeof(uint16));
1022         if (q == NULL)
1023                 return False;
1024
1025         if (UNMARSHALLING(ps)) {
1026                 str->str.buffer = PRS_ALLOC_MEM(ps,uint16,str->uni_str_len);
1027                 if (str->str.buffer == NULL)
1028                         return False;
1029         }
1030
1031         p = (char *)str->str.buffer;
1032
1033         dbg_rw_punival(charmode, name, depth, ps, q, p, str->uni_str_len);
1034         ps->data_offset += (str->uni_str_len * sizeof(uint16));
1035
1036         return True;
1037 }
1038
1039 /*******************************************************************
1040  Stream a unicode  null-terminated string. As the string is already
1041  in little-endian format then do it as a stream of bytes.
1042  ********************************************************************/
1043
1044 BOOL prs_unistr(const char *name, prs_struct *ps, int depth, UNISTR *str)
1045 {
1046         unsigned int len = 0;
1047         unsigned char *p = (unsigned char *)str->buffer;
1048         uint8 *start;
1049         char *q;
1050         uint32 max_len;
1051         uint16* ptr;
1052
1053         if (MARSHALLING(ps)) {
1054
1055                 for(len = 0; str->buffer[len] != 0; len++)
1056                         ;
1057
1058                 q = prs_mem_get(ps, (len+1)*2);
1059                 if (q == NULL)
1060                         return False;
1061
1062                 start = (uint8*)q;
1063
1064                 for(len = 0; str->buffer[len] != 0; len++) 
1065                 {
1066                         if(ps->bigendian_data) 
1067                         {
1068                                 /* swap bytes - p is little endian, q is big endian. */
1069                                 q[0] = (char)p[1];
1070                                 q[1] = (char)p[0];
1071                                 p += 2;
1072                                 q += 2;
1073                         } 
1074                         else 
1075                         {
1076                                 q[0] = (char)p[0];
1077                                 q[1] = (char)p[1];
1078                                 p += 2;
1079                                 q += 2;
1080                         }
1081                 }
1082
1083                 /*
1084                  * even if the string is 'empty' (only an \0 char)
1085                  * at this point the leading \0 hasn't been parsed.
1086                  * so parse it now
1087                  */
1088
1089                 q[0] = 0;
1090                 q[1] = 0;
1091                 q += 2;
1092
1093                 len++;
1094
1095                 DEBUG(5,("%s%04x %s: ", tab_depth(depth), ps->data_offset, name));
1096                 print_asc(5, (unsigned char*)start, 2*len);     
1097                 DEBUG(5, ("\n"));
1098         }
1099         else { /* unmarshalling */
1100         
1101                 uint32 alloc_len = 0;
1102                 q = ps->data_p + prs_offset(ps);
1103
1104                 /*
1105                  * Work out how much space we need and talloc it.
1106                  */
1107                 max_len = (ps->buffer_size - ps->data_offset)/sizeof(uint16);
1108
1109                 /* the test of the value of *ptr helps to catch the circumstance
1110                    where we have an emtpty (non-existent) string in the buffer */
1111                 for ( ptr = (uint16 *)q; *ptr++ && (alloc_len <= max_len); alloc_len++)
1112                         /* do nothing */ 
1113                         ;
1114
1115                 if (alloc_len < max_len)
1116                         alloc_len += 1;
1117
1118                 /* should we allocate anything at all? */
1119                 str->buffer = PRS_ALLOC_MEM(ps,uint16,alloc_len);
1120                 if ((str->buffer == NULL) && (alloc_len > 0))
1121                         return False;
1122
1123                 p = (unsigned char *)str->buffer;
1124
1125                 len = 0;
1126                 /* the (len < alloc_len) test is to prevent us from overwriting
1127                    memory that is not ours...if we get that far, we have a non-null
1128                    terminated string in the buffer and have messed up somewhere */
1129                 while ((len < alloc_len) && (*(uint16 *)q != 0))
1130                 {
1131                         if(ps->bigendian_data) 
1132                         {
1133                                 /* swap bytes - q is big endian, p is little endian. */
1134                                 p[0] = (unsigned char)q[1];
1135                                 p[1] = (unsigned char)q[0];
1136                                 p += 2;
1137                                 q += 2;
1138                         } else {
1139
1140                                 p[0] = (unsigned char)q[0];
1141                                 p[1] = (unsigned char)q[1];
1142                                 p += 2;
1143                                 q += 2;
1144                         }
1145
1146                         len++;
1147                 } 
1148                 if (len < alloc_len)
1149                 {
1150                         /* NULL terminate the UNISTR */
1151                         str->buffer[len++] = '\0';
1152                 }
1153
1154                 DEBUG(5,("%s%04x %s: ", tab_depth(depth), ps->data_offset, name));
1155                 print_asc(5, (unsigned char*)str->buffer, 2*len);       
1156                 DEBUG(5, ("\n"));
1157         }
1158
1159         /* set the offset in the prs_struct; 'len' points to the
1160            terminiating NULL in the UNISTR so we need to go one more
1161            uint16 */
1162         ps->data_offset += (len)*2;
1163         
1164         return True;
1165 }
1166
1167
1168 /*******************************************************************
1169  Stream a null-terminated string.  len is strlen, and therefore does
1170  not include the null-termination character.
1171  ********************************************************************/
1172
1173 BOOL prs_string(const char *name, prs_struct *ps, int depth, char *str, int max_buf_size)
1174 {
1175         char *q;
1176         int i;
1177         int len;
1178
1179         if (UNMARSHALLING(ps))
1180                 len = strlen(&ps->data_p[ps->data_offset]);
1181         else
1182                 len = strlen(str);
1183
1184         len = MIN(len, (max_buf_size-1));
1185
1186         q = prs_mem_get(ps, len+1);
1187         if (q == NULL)
1188                 return False;
1189
1190         for(i = 0; i < len; i++) {
1191                 if (UNMARSHALLING(ps))
1192                         str[i] = q[i];
1193                 else
1194                         q[i] = str[i];
1195         }
1196
1197         /* The terminating null. */
1198         str[i] = '\0';
1199
1200         if (MARSHALLING(ps)) {
1201                 q[i] = '\0';
1202         }
1203
1204         ps->data_offset += len+1;
1205
1206         dump_data(5+depth, q, len);
1207
1208         return True;
1209 }
1210
1211 /*******************************************************************
1212  prs_uint16 wrapper. Call this and it sets up a pointer to where the
1213  uint16 should be stored, or gets the size if reading.
1214  ********************************************************************/
1215
1216 BOOL prs_uint16_pre(const char *name, prs_struct *ps, int depth, uint16 *data16, uint32 *offset)
1217 {
1218         *offset = ps->data_offset;
1219         if (UNMARSHALLING(ps)) {
1220                 /* reading. */
1221                 return prs_uint16(name, ps, depth, data16);
1222         } else {
1223                 char *q = prs_mem_get(ps, sizeof(uint16));
1224                 if(q ==NULL)
1225                         return False;
1226                 ps->data_offset += sizeof(uint16);
1227         }
1228         return True;
1229 }
1230
1231 /*******************************************************************
1232  prs_uint16 wrapper.  call this and it retrospectively stores the size.
1233  does nothing on reading, as that is already handled by ...._pre()
1234  ********************************************************************/
1235
1236 BOOL prs_uint16_post(const char *name, prs_struct *ps, int depth, uint16 *data16,
1237                                 uint32 ptr_uint16, uint32 start_offset)
1238 {
1239         if (MARSHALLING(ps)) {
1240                 /* 
1241                  * Writing - temporarily move the offset pointer.
1242                  */
1243                 uint16 data_size = ps->data_offset - start_offset;
1244                 uint32 old_offset = ps->data_offset;
1245
1246                 ps->data_offset = ptr_uint16;
1247                 if(!prs_uint16(name, ps, depth, &data_size)) {
1248                         ps->data_offset = old_offset;
1249                         return False;
1250                 }
1251                 ps->data_offset = old_offset;
1252         } else {
1253                 ps->data_offset = start_offset + (uint32)(*data16);
1254         }
1255         return True;
1256 }
1257
1258 /*******************************************************************
1259  prs_uint32 wrapper. Call this and it sets up a pointer to where the
1260  uint32 should be stored, or gets the size if reading.
1261  ********************************************************************/
1262
1263 BOOL prs_uint32_pre(const char *name, prs_struct *ps, int depth, uint32 *data32, uint32 *offset)
1264 {
1265         *offset = ps->data_offset;
1266         if (UNMARSHALLING(ps) && (data32 != NULL)) {
1267                 /* reading. */
1268                 return prs_uint32(name, ps, depth, data32);
1269         } else {
1270                 ps->data_offset += sizeof(uint32);
1271         }
1272         return True;
1273 }
1274
1275 /*******************************************************************
1276  prs_uint32 wrapper.  call this and it retrospectively stores the size.
1277  does nothing on reading, as that is already handled by ...._pre()
1278  ********************************************************************/
1279
1280 BOOL prs_uint32_post(const char *name, prs_struct *ps, int depth, uint32 *data32,
1281                                 uint32 ptr_uint32, uint32 data_size)
1282 {
1283         if (MARSHALLING(ps)) {
1284                 /* 
1285                  * Writing - temporarily move the offset pointer.
1286                  */
1287                 uint32 old_offset = ps->data_offset;
1288                 ps->data_offset = ptr_uint32;
1289                 if(!prs_uint32(name, ps, depth, &data_size)) {
1290                         ps->data_offset = old_offset;
1291                         return False;
1292                 }
1293                 ps->data_offset = old_offset;
1294         }
1295         return True;
1296 }
1297
1298 /* useful function to store a structure in rpc wire format */
1299 int tdb_prs_store(TDB_CONTEXT *tdb, char *keystr, prs_struct *ps)
1300 {
1301     TDB_DATA kbuf, dbuf;
1302     kbuf.dptr = keystr;
1303     kbuf.dsize = strlen(keystr)+1;
1304     dbuf.dptr = ps->data_p;
1305     dbuf.dsize = prs_offset(ps);
1306     return tdb_store(tdb, kbuf, dbuf, TDB_REPLACE);
1307 }
1308
1309 /* useful function to fetch a structure into rpc wire format */
1310 int tdb_prs_fetch(TDB_CONTEXT *tdb, char *keystr, prs_struct *ps, TALLOC_CTX *mem_ctx)
1311 {
1312     TDB_DATA kbuf, dbuf;
1313     kbuf.dptr = keystr;
1314     kbuf.dsize = strlen(keystr)+1;
1315
1316     dbuf = tdb_fetch(tdb, kbuf);
1317     if (!dbuf.dptr)
1318             return -1;
1319
1320     prs_init(ps, 0, mem_ctx, UNMARSHALL);
1321     prs_give_memory(ps, dbuf.dptr, dbuf.dsize, True);
1322
1323     return 0;
1324
1325
1326 /*******************************************************************
1327  hash a stream.
1328  ********************************************************************/
1329 BOOL prs_hash1(prs_struct *ps, uint32 offset, uint8 sess_key[16], int len)
1330 {
1331         char *q;
1332
1333         q = ps->data_p;
1334         q = &q[offset];
1335
1336 #ifdef DEBUG_PASSWORD
1337         DEBUG(100, ("prs_hash1\n"));
1338         dump_data(100, sess_key, 16);
1339         dump_data(100, q, len);
1340 #endif
1341         SamOEMhash((uchar *) q, sess_key, len);
1342
1343 #ifdef DEBUG_PASSWORD
1344         dump_data(100, q, len);
1345 #endif
1346
1347         return True;
1348 }
1349
1350
1351 /*******************************************************************
1352  Create a digest over the entire packet (including the data), and 
1353  MD5 it with the session key.
1354  ********************************************************************/
1355 static void netsec_digest(struct netsec_auth_struct *a,
1356                           int auth_flags,
1357                           RPC_AUTH_NETSEC_CHK * verf,
1358                           char *data, size_t data_len,
1359                           uchar digest_final[16]) 
1360 {
1361         uchar whole_packet_digest[16];
1362         static uchar zeros[4];
1363         struct MD5Context ctx3;
1364         
1365         /* verfiy the signature on the packet by MD5 over various bits */
1366         MD5Init(&ctx3);
1367         /* use our sequence number, which ensures the packet is not
1368            out of order */
1369         MD5Update(&ctx3, zeros, sizeof(zeros));
1370         MD5Update(&ctx3, verf->sig, sizeof(verf->sig));
1371         if (auth_flags & AUTH_PIPE_SEAL) {
1372                 MD5Update(&ctx3, verf->confounder, sizeof(verf->confounder));
1373         }
1374         MD5Update(&ctx3, (const unsigned char *)data, data_len);
1375         MD5Final(whole_packet_digest, &ctx3);
1376         dump_data_pw("whole_packet_digest:\n", whole_packet_digest, sizeof(whole_packet_digest));
1377         
1378         /* MD5 this result and the session key, to prove that
1379            only a valid client could had produced this */
1380         hmac_md5(a->sess_key, whole_packet_digest, sizeof(whole_packet_digest), digest_final);
1381 }
1382
1383 /*******************************************************************
1384  Calculate the key with which to encode the data payload 
1385  ********************************************************************/
1386 static void netsec_get_sealing_key(struct netsec_auth_struct *a,
1387                                    RPC_AUTH_NETSEC_CHK *verf,
1388                                    uchar sealing_key[16]) 
1389 {
1390         static uchar zeros[4];
1391         uchar digest2[16];
1392         uchar sess_kf0[16];
1393         int i;
1394
1395         for (i = 0; i < sizeof(sess_kf0); i++) {
1396                 sess_kf0[i] = a->sess_key[i] ^ 0xf0;
1397         }
1398         
1399         dump_data_pw("sess_kf0:\n", sess_kf0, sizeof(sess_kf0));
1400         
1401         /* MD5 of sess_kf0 and 4 zero bytes */
1402         hmac_md5(sess_kf0, zeros, 0x4, digest2);
1403         dump_data_pw("digest2:\n", digest2, sizeof(digest2));
1404         
1405         /* MD5 of the above result, plus 8 bytes of sequence number */
1406         hmac_md5(digest2, verf->seq_num, sizeof(verf->seq_num), sealing_key);
1407         dump_data_pw("sealing_key:\n", sealing_key, 16);
1408 }
1409
1410 /*******************************************************************
1411  Encode or Decode the sequence number (which is symmetric)
1412  ********************************************************************/
1413 static void netsec_deal_with_seq_num(struct netsec_auth_struct *a,
1414                                      RPC_AUTH_NETSEC_CHK *verf)
1415 {
1416         static uchar zeros[4];
1417         uchar sequence_key[16];
1418         uchar digest1[16];
1419
1420         hmac_md5(a->sess_key, zeros, sizeof(zeros), digest1);
1421         dump_data_pw("(sequence key) digest1:\n", digest1, sizeof(digest1));
1422
1423         hmac_md5(digest1, verf->packet_digest, 8, sequence_key);
1424
1425         dump_data_pw("sequence_key:\n", sequence_key, sizeof(sequence_key));
1426
1427         dump_data_pw("seq_num (before):\n", verf->seq_num, sizeof(verf->seq_num));
1428         SamOEMhash(verf->seq_num, sequence_key, 8);
1429         dump_data_pw("seq_num (after):\n", verf->seq_num, sizeof(verf->seq_num));
1430 }
1431
1432 /*******************************************************************
1433 creates an RPC_AUTH_NETSEC_CHK structure.
1434 ********************************************************************/
1435 static BOOL init_rpc_auth_netsec_chk(RPC_AUTH_NETSEC_CHK * chk,
1436                               const uchar sig[8],
1437                               const uchar packet_digest[8],
1438                               const uchar seq_num[8], const uchar confounder[8])
1439 {
1440         if (chk == NULL)
1441                 return False;
1442
1443         memcpy(chk->sig, sig, sizeof(chk->sig));
1444         memcpy(chk->packet_digest, packet_digest, sizeof(chk->packet_digest));
1445         memcpy(chk->seq_num, seq_num, sizeof(chk->seq_num));
1446         memcpy(chk->confounder, confounder, sizeof(chk->confounder));
1447
1448         return True;
1449 }
1450
1451
1452 /*******************************************************************
1453  Encode a blob of data using the netsec (schannel) alogrithm, also produceing
1454  a checksum over the original data.  We currently only support
1455  signing and sealing togeather - the signing-only code is close, but not
1456  quite compatible with what MS does.
1457  ********************************************************************/
1458 void netsec_encode(struct netsec_auth_struct *a, int auth_flags, 
1459                    enum netsec_direction direction,
1460                    RPC_AUTH_NETSEC_CHK * verf,
1461                    char *data, size_t data_len)
1462 {
1463         uchar digest_final[16];
1464         uchar confounder[8];
1465         uchar seq_num[8];
1466         static const uchar nullbytes[8];
1467
1468         static const uchar netsec_seal_sig[8] = NETSEC_SEAL_SIGNATURE;
1469         static const uchar netsec_sign_sig[8] = NETSEC_SIGN_SIGNATURE;
1470         const uchar *netsec_sig = NULL;
1471
1472         DEBUG(10,("SCHANNEL: netsec_encode seq_num=%d data_len=%lu\n", a->seq_num, (unsigned long)data_len));
1473         
1474         if (auth_flags & AUTH_PIPE_SEAL) {
1475                 netsec_sig = netsec_seal_sig;
1476         } else if (auth_flags & AUTH_PIPE_SIGN) {
1477                 netsec_sig = netsec_sign_sig;
1478         }
1479
1480         /* fill the 'confounder' with random data */
1481         generate_random_buffer(confounder, sizeof(confounder));
1482
1483         dump_data_pw("a->sess_key:\n", a->sess_key, sizeof(a->sess_key));
1484
1485         RSIVAL(seq_num, 0, a->seq_num);
1486
1487         switch (direction) {
1488         case SENDER_IS_INITIATOR:
1489                 SIVAL(seq_num, 4, 0x80);
1490                 break;
1491         case SENDER_IS_ACCEPTOR:
1492                 SIVAL(seq_num, 4, 0x0);
1493                 break;
1494         }
1495
1496         dump_data_pw("verf->seq_num:\n", seq_num, sizeof(verf->seq_num));
1497
1498         init_rpc_auth_netsec_chk(verf, netsec_sig, nullbytes,
1499                                  seq_num, confounder);
1500                                 
1501         /* produce a digest of the packet to prove it's legit (before we seal it) */
1502         netsec_digest(a, auth_flags, verf, data, data_len, digest_final);
1503         memcpy(verf->packet_digest, digest_final, sizeof(verf->packet_digest));
1504
1505         if (auth_flags & AUTH_PIPE_SEAL) {
1506                 uchar sealing_key[16];
1507
1508                 /* get the key to encode the data with */
1509                 netsec_get_sealing_key(a, verf, sealing_key);
1510
1511                 /* encode the verification data */
1512                 dump_data_pw("verf->confounder:\n", verf->confounder, sizeof(verf->confounder));
1513                 SamOEMhash(verf->confounder, sealing_key, 8);
1514
1515                 dump_data_pw("verf->confounder_enc:\n", verf->confounder, sizeof(verf->confounder));
1516                 
1517                 /* encode the packet payload */
1518                 dump_data_pw("data:\n", (const unsigned char *)data, data_len);
1519                 SamOEMhash((unsigned char *)data, sealing_key, data_len);
1520                 dump_data_pw("data_enc:\n", (const unsigned char *)data, data_len);
1521         }
1522
1523         /* encode the sequence number (key based on packet digest) */
1524         /* needs to be done after the sealing, as the original version 
1525            is used in the sealing stuff... */
1526         netsec_deal_with_seq_num(a, verf);
1527
1528         return;
1529 }
1530
1531 /*******************************************************************
1532  Decode a blob of data using the netsec (schannel) alogrithm, also verifiying
1533  a checksum over the original data.  We currently can verify signed messages,
1534  as well as decode sealed messages
1535  ********************************************************************/
1536
1537 BOOL netsec_decode(struct netsec_auth_struct *a, int auth_flags,
1538                    enum netsec_direction direction, 
1539                    RPC_AUTH_NETSEC_CHK * verf, char *data, size_t data_len)
1540 {
1541         uchar digest_final[16];
1542
1543         static const uchar netsec_seal_sig[8] = NETSEC_SEAL_SIGNATURE;
1544         static const uchar netsec_sign_sig[8] = NETSEC_SIGN_SIGNATURE;
1545         const uchar *netsec_sig = NULL;
1546
1547         uchar seq_num[8];
1548
1549         DEBUG(10,("SCHANNEL: netsec_encode seq_num=%d data_len=%lu\n", a->seq_num, (unsigned long)data_len));
1550         
1551         if (auth_flags & AUTH_PIPE_SEAL) {
1552                 netsec_sig = netsec_seal_sig;
1553         } else if (auth_flags & AUTH_PIPE_SIGN) {
1554                 netsec_sig = netsec_sign_sig;
1555         }
1556
1557         /* Create the expected sequence number for comparison */
1558         RSIVAL(seq_num, 0, a->seq_num);
1559
1560         switch (direction) {
1561         case SENDER_IS_INITIATOR:
1562                 SIVAL(seq_num, 4, 0x80);
1563                 break;
1564         case SENDER_IS_ACCEPTOR:
1565                 SIVAL(seq_num, 4, 0x0);
1566                 break;
1567         }
1568
1569         DEBUG(10,("SCHANNEL: netsec_decode seq_num=%d data_len=%lu\n", a->seq_num, (unsigned long)data_len));
1570         dump_data_pw("a->sess_key:\n", a->sess_key, sizeof(a->sess_key));
1571
1572         dump_data_pw("seq_num:\n", seq_num, sizeof(seq_num));
1573
1574         /* extract the sequence number (key based on supplied packet digest) */
1575         /* needs to be done before the sealing, as the original version 
1576            is used in the sealing stuff... */
1577         netsec_deal_with_seq_num(a, verf);
1578
1579         if (memcmp(verf->seq_num, seq_num, sizeof(seq_num))) {
1580                 /* don't even bother with the below if the sequence number is out */
1581                 /* The sequence number is MD5'ed with a key based on the whole-packet
1582                    digest, as supplied by the client.  We check that it's a valid 
1583                    checksum after the decode, below
1584                 */
1585                 DEBUG(2, ("netsec_decode: FAILED: packet sequence number:\n"));
1586                 dump_data(2, (const char*)verf->seq_num, sizeof(verf->seq_num));
1587                 DEBUG(2, ("should be:\n"));
1588                 dump_data(2, (const char*)seq_num, sizeof(seq_num));
1589
1590                 return False;
1591         }
1592
1593         if (memcmp(verf->sig, netsec_sig, sizeof(verf->sig))) {
1594                 /* Validate that the other end sent the expected header */
1595                 DEBUG(2, ("netsec_decode: FAILED: packet header:\n"));
1596                 dump_data(2, (const char*)verf->sig, sizeof(verf->sig));
1597                 DEBUG(2, ("should be:\n"));
1598                 dump_data(2, (const char*)netsec_sig, sizeof(netsec_sig));
1599                 return False;
1600         }
1601
1602         if (auth_flags & AUTH_PIPE_SEAL) {
1603                 uchar sealing_key[16];
1604                 
1605                 /* get the key to extract the data with */
1606                 netsec_get_sealing_key(a, verf, sealing_key);
1607
1608                 /* extract the verification data */
1609                 dump_data_pw("verf->confounder:\n", verf->confounder, 
1610                              sizeof(verf->confounder));
1611                 SamOEMhash(verf->confounder, sealing_key, 8);
1612
1613                 dump_data_pw("verf->confounder_dec:\n", verf->confounder, 
1614                              sizeof(verf->confounder));
1615                 
1616                 /* extract the packet payload */
1617                 dump_data_pw("data   :\n", (const unsigned char *)data, data_len);
1618                 SamOEMhash((unsigned char *)data, sealing_key, data_len);
1619                 dump_data_pw("datadec:\n", (const unsigned char *)data, data_len);      
1620         }
1621
1622         /* digest includes 'data' after unsealing */
1623         netsec_digest(a, auth_flags, verf, data, data_len, digest_final);
1624
1625         dump_data_pw("Calculated digest:\n", digest_final, 
1626                      sizeof(digest_final));
1627         dump_data_pw("verf->packet_digest:\n", verf->packet_digest, 
1628                      sizeof(verf->packet_digest));
1629         
1630         /* compare - if the client got the same result as us, then
1631            it must know the session key */
1632         return (memcmp(digest_final, verf->packet_digest, 
1633                        sizeof(verf->packet_digest)) == 0);
1634 }