This repository has been archived by the owner on Jan 22, 2024. It is now read-only.
/
core.c
1820 lines (1500 loc) · 53.9 KB
/
core.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*!
* @file core.c
* @brief Definitions of core components of the Meterpreter suite.
* @details Much of what exists in the core files is used in almost every area
* of the Meterpreter code base, and hence it's very important. Don't
* change this stuff unless you know what you're doing!
*/
#include "common.h"
DWORD packet_find_tlv_buf(Packet *packet, PUCHAR payload, DWORD payloadLength, DWORD index,
TlvType type, Tlv *tlv);
/*! @brief List element that contains packet completion routine details. */
typedef struct _PacketCompletionRoutineEntry
{
LPCSTR requestId; ///< Id of the request.
PacketRequestCompletion handler; ///< Handler to call on completion.
struct _PacketCompletionRoutineEntry *next; ///< Pointer to the next compleiont routine entry.
} PacketCompletionRoutineEntry;
/*!
* @brief Reference to the list of packet completion routines.
* @details This pointer is a singularly-linked list which contains references
* to PacketCompletionRouteEntry items, each of which is processed
* when packet_call_completion_handlers is invoked.
*/
PacketCompletionRoutineEntry *packetCompletionRoutineList = NULL;
/*!
* @brief Print a remote console message.
* @details Transmit a single string to the remote connection with instructions
* to print it to the screen or whatever medium has been established.
* @param remote Pointer to the \c Remote instance that the message should be
sent to
* @param fmt Format string.
* @param ... Varargs that will be printed to the \c fmt format string.
* @return Indication of success or failure.
* @retval ERROR_NOT_ENOUGH_MEMORY Unable to allocate memory for the request packet.
* @retval ERROR_SUCCESS Transmission was successful.
*/
DWORD send_core_console_write( Remote *remote, LPCSTR fmt, ... )
{
Packet *request = NULL;
CHAR buf[8192];
va_list ap;
DWORD res;
do
{
va_start(ap, fmt);
_vsnprintf(buf, sizeof(buf) - 1, fmt, ap);
va_end(ap);
// Create a message with the 'core_print' method
if (!(request = packet_create(PACKET_TLV_TYPE_REQUEST, "core_console_write")))
{
res = ERROR_NOT_ENOUGH_MEMORY;
break;
}
// Add the string to print
if ((res = packet_add_tlv_string(request, TLV_TYPE_STRING, buf)) != NO_ERROR)
break;
res = packet_transmit(remote, request, NULL);
} while (0);
// Cleanup on failure
if (res != ERROR_SUCCESS)
{
if (request)
packet_destroy(request);
}
return res;
}
/*!
* @todo I have no idea why this is here, need someone else to explain.
*/
HANDLE core_update_thread_token( Remote *remote, HANDLE token )
{
HANDLE temp = NULL;
#ifdef _WIN32
lock_acquire( remote->lock );
do
{
temp = remote->hThreadToken;
// A NULL token resets the state back to the server token
if(! token)
token = remote->hServerToken;
// Assign the thread token
remote->hThreadToken = token;
// Close the old token if its not one of the two active tokens
if( temp && temp != remote->hServerToken && temp != remote->hThreadToken ) {
CloseHandle(temp);
}
} while(0);
lock_release( remote->lock );
#else
/*
* XXX add POSIX implementation
*/
#endif
return(token);
}
/*!
* @brief Update the session/station/desktop to be used by multi threaded meterpreter for desktop related operations.
* @details We dont store the handles as it is more convienient to use strings, especially as we cant use the regular API
* to break out of sessions.
* @remark It is up to the caller to free any station/desktop name provided as internally we use \c strdup.
* @param remote Pointer to the remote connection.
* @param dwSessionID ID of the session which contains the window station in \c cpStationName.
* @param cpStationName Name of the window station that contains the desktop in \c cpDesktopName.
* @param cpDesktopName Name of the desktop to switch to.
*/
VOID core_update_desktop( Remote * remote, DWORD dwSessionID, char * cpStationName, char * cpDesktopName )
{
#ifdef _WIN32
DWORD temp_session = -1;
char * temp_station = NULL;
char * temp_desktop = NULL;
lock_acquire( remote->lock );
do
{
temp_session = remote->dwCurrentSessionId;
// A session id of -1 resets the state back to the servers real session id
if( dwSessionID = -1 )
dwSessionID = remote->dwOrigSessionId;
// Assign the new session id
remote->dwCurrentSessionId = dwSessionID;
temp_station = remote->cpCurrentStationName;
// A NULL station resets the station back to the origional process window station
if( !cpStationName )
cpStationName = remote->cpOrigStationName;
// Assign the current window station name to use
remote->cpCurrentStationName = _strdup( cpStationName );
// free the memory for the old station name if its not one of the two active names
if( temp_station && temp_station != remote->cpOrigStationName && temp_station != remote->cpCurrentStationName )
free( temp_station );
temp_desktop = remote->cpCurrentDesktopName;
// A NULL station resets the desktop back to the origional process desktop
if( !cpDesktopName )
cpDesktopName = remote->cpOrigDesktopName;
// Assign the current window desktop name to use
remote->cpCurrentDesktopName = _strdup( cpDesktopName );
// free the memory for the old desktop name if its not one of the two active names
if( temp_desktop && temp_desktop != remote->cpOrigDesktopName && temp_desktop != remote->cpCurrentDesktopName )
free( temp_desktop );
} while( 0 );
lock_release( remote->lock );
#endif
}
/*!
* @brief Create a packet of a given type (request/response) and method.
* @param type The TLV type that this packet represents.
* @param method TLV method type (can be \c NULL).
* @return Pointer to the newly created \c Packet.
*/
Packet *packet_create( PacketTlvType type, LPCSTR method )
{
Packet *packet = NULL;
BOOL success = FALSE;
do
{
if (!(packet = (Packet *)malloc(sizeof(Packet))))
break;
memset(packet, 0, sizeof(Packet));
// Initialize the header length and message type
packet->header.length = htonl(sizeof(TlvHeader));
packet->header.type = htonl((DWORD)type);
// Initialize the payload to be blank
packet->payload = NULL;
packet->payloadLength = 0;
// Add the method TLV if provided
if (method)
{
if (packet_add_tlv_string(packet, TLV_TYPE_METHOD, method) != ERROR_SUCCESS)
break;
}
success = TRUE;
} while (0);
// Clean up the packet on failure
if ((!success) && (packet))
{
packet_destroy(packet);
packet = NULL;
}
return packet;
}
/*!
* @brief Create a packet that is used to contain a subgroup.
* @returns An instance of a packet to use as a group container.
* @remarks Group packets can be used to arbitrarily nest groupings prior to
* sending the packet to the client.
*/
Packet* packet_create_group()
{
Packet* packet = NULL;
do
{
if (!(packet = (Packet*)malloc(sizeof(Packet))))
{
break;
}
memset(packet, 0, sizeof(Packet));
// we don't need to worry about the TLV header at this point
// so we'll ignore it
// Initialize the payload to be blank
packet->payload = NULL;
packet->payloadLength = 0;
return packet;
} while (0);
if (packet)
{
free(packet);
}
return NULL;
}
/*!
* @brief Add a group packet to the parent packet.
* @param packet Pointer to the container packet that the group is to be added to.
* @param type The type of group packet being added.
* @param groupPacket the packet containing the group data (created by `packet_create_group`).
* @returns Indication of success or failure.
* @remarks The function calls `packet_destroy` on the `groupPacket` if adding the packet succeeds.
*/
DWORD packet_add_group(Packet* packet, TlvType type, Packet* groupPacket)
{
DWORD result = packet_add_tlv_raw(packet, type, groupPacket->payload, groupPacket->payloadLength);
if (result == ERROR_SUCCESS)
{
packet_destroy(groupPacket);
return ERROR_SUCCESS;
}
return result;
}
/*!
* @brief Create a response packet from a request.
* @details Create a response packet from a request, referencing the requestors
* message identifier.
* @param request The request \c Packet to build a response for.
* @return Pointer to a new \c Packet.
*/
Packet *packet_create_response( Packet *request )
{
Packet *response = NULL;
Tlv method, requestId;
BOOL success = FALSE;
PacketTlvType responseType;
if (packet_get_type(request) == PACKET_TLV_TYPE_PLAIN_REQUEST)
responseType = PACKET_TLV_TYPE_PLAIN_RESPONSE;
else
responseType = PACKET_TLV_TYPE_RESPONSE;
do
{
// Get the request TLV's method
if (packet_get_tlv_string(request, TLV_TYPE_METHOD, &method) != ERROR_SUCCESS)
break;
// Try to allocate a response packet
if (!(response = packet_create(responseType, (PCHAR)method.buffer)))
break;
// Get the request TLV's request identifier
if (packet_get_tlv_string(request, TLV_TYPE_REQUEST_ID, &requestId) != ERROR_SUCCESS)
break;
// Add the request identifier to the packet
packet_add_tlv_string(response, TLV_TYPE_REQUEST_ID, (PCHAR)requestId.buffer);
success = TRUE;
} while (0);
// Cleanup on failure
if (!success)
{
if (response)
packet_destroy(response);
response = NULL;
}
return response;
}
/*!
* @brief Destroy the packet context and the payload buffer.
* @param packet Pointer to the \c Packet to destroy.
*/
VOID packet_destroy( Packet * packet )
{
if( packet == NULL )
return;
if( packet->payload )
{
memset( packet->payload, 0, packet->payloadLength );
free( packet->payload );
}
if( packet->decompressed_buffers )
{
while( TRUE )
{
DECOMPRESSED_BUFFER * buf = list_pop( packet->decompressed_buffers );
if( !buf )
break;
if( buf->buffer )
{
memset( buf->buffer, 0, buf->length );
free( buf->buffer );
}
free( buf );
}
list_destroy( packet->decompressed_buffers );
}
memset( packet, 0, sizeof(Packet) );
free( packet );
}
/*!
* @brief Add a string value TLV to a packet, including the \c NULL terminator.
* @param packet Pointer to the packet to add the value to.
* @param type TLV type for the value.
* @param str Pointer to the string value to add to the packet.
* @return Indication of success or failure.
* @retval ERROR_SUCCESS The operation completed successfully.
* @retval ERROR_NOT_ENOUGH_MEMORY Insufficient memory available.
*/
DWORD packet_add_tlv_string( Packet *packet, TlvType type, LPCSTR str )
{
return packet_add_tlv_raw(packet, type, (PUCHAR)str, (DWORD)strlen(str) + 1);
}
/*!
* @brief Add a wide-string value TLV to a packet, including the \c NULL terminator.
* @param packet Pointer to the packet to add the value to.
* @param type TLV type for the value.
* @param str Pointer to the wide-string value to add to the packet.
* @return Indication of success or failure.
* @retval ERROR_SUCCESS The operation completed successfully.
* @retval ERROR_NOT_ENOUGH_MEMORY Insufficient memory available.
*/
DWORD packet_add_tlv_wstring(Packet *packet, TlvType type, LPCWSTR str)
{
DWORD dwResult;
size_t charCount = wcslen(str);
LPSTR lpStr = (LPSTR)malloc(charCount + 1);
if (lpStr) {
wcstombs(lpStr, str, charCount);
lpStr[charCount] = 0;
dwResult = packet_add_tlv_raw(packet, type, (PUCHAR)lpStr, (DWORD)charCount + 1);
free(lpStr);
}
else {
dwResult = ERROR_NOT_ENOUGH_MEMORY;
}
return dwResult;
}
/*!
* @brief Add a unsigned integer value TLV to a packet.
* @param packet Pointer to the packet to add the value to.
* @param type TLV type for the value.
* @param val The value to add to the packet.
* @return Indication of success or failure.
* @retval ERROR_SUCCESS The operation completed successfully.
* @retval ERROR_NOT_ENOUGH_MEMORY Insufficient memory available.
*/
DWORD packet_add_tlv_uint( Packet *packet, TlvType type, UINT val )
{
val = htonl(val);
return packet_add_tlv_raw(packet, type, (PUCHAR)&val, sizeof(val));
}
/*!
* @brief Add a quad-work value TLV to a packet.
* @param packet Pointer to the packet to add the value to.
* @param type TLV type for the value.
* @param val The value to add to the packet.
* @return Indication of success or failure.
* @retval ERROR_SUCCESS The operation completed successfully.
* @retval ERROR_NOT_ENOUGH_MEMORY Insufficient memory available.
*/
DWORD packet_add_tlv_qword( Packet *packet, TlvType type, QWORD val )
{
val = htonq( val );
return packet_add_tlv_raw( packet, type, (PUCHAR)&val, sizeof(QWORD) );
}
/*!
* @brief Add a boolean value TLV to a packet.
* @param packet Pointer to the packet to add the value to.
* @param type TLV type for the value.
* @param val The value to add to the packet.
* @return Indication of success or failure.
* @retval ERROR_SUCCESS The operation completed successfully.
* @retval ERROR_NOT_ENOUGH_MEMORY Insufficient memory available.
*/
DWORD packet_add_tlv_bool(Packet *packet, TlvType type, BOOL val)
{
return packet_add_tlv_raw(packet, type, (PUCHAR)&val, 1);
}
/*!
* @brief Add a group TLV to a packet.
* @details A TLV group is a TLV that contains multiple sub-TLVs.
* @param packet Pointer to the packet to add the value to.
* @param type TLV type for the value.
* @param entries Pointer to the array of TLV entries to add.
* @param numEntries Count of the number of TLV entries in the \c entries array.
* @return Indication of success or failure.
* @retval ERROR_SUCCESS The operation completed successfully.
* @retval ERROR_NOT_ENOUGH_MEMORY Insufficient memory available.
*/
DWORD packet_add_tlv_group( Packet *packet, TlvType type, Tlv *entries, DWORD numEntries )
{
DWORD totalSize = 0,
offset = 0,
index = 0,
res = ERROR_SUCCESS;
PCHAR buffer = NULL;
// Calculate the total TLV size.
for (index = 0; index < numEntries; index++)
totalSize += entries[index].header.length + sizeof(TlvHeader);
do
{
// Allocate storage for the complete buffer
if (!(buffer = (PCHAR)malloc(totalSize)))
{
res = ERROR_NOT_ENOUGH_MEMORY;
break;
}
// Copy the memory into the new buffer
for (index = 0; index < numEntries; index++)
{
TlvHeader rawHeader;
// Convert byte order for storage
rawHeader.length = htonl(entries[index].header.length + sizeof(TlvHeader));
rawHeader.type = htonl((DWORD)entries[index].header.type);
// Copy the TLV header & payload
memcpy(buffer + offset, &rawHeader, sizeof(TlvHeader));
memcpy(buffer + offset + sizeof(TlvHeader), entries[index].buffer, entries[index].header.length);
// Update the offset into the buffer
offset += entries[index].header.length + sizeof(TlvHeader);
}
// Now add the TLV group with its contents populated
res = packet_add_tlv_raw(packet, type, buffer, totalSize);
} while (0);
// Free the temporary buffer
if (buffer)
free(buffer);
return res;
}
/*!
* @brief Add an array of TLVs to a packet.
* @param packet Pointer to the packet to add the values to.
* @param entries Pointer to the array of TLV entries to add.
* @param numEntries Count of the number of TLV entries in the \c entries array.
* @return Indication of success or failure.
* @retval ERROR_SUCCESS The operation completed successfully.
* @retval ERROR_NOT_ENOUGH_MEMORY Insufficient memory available.
*/
DWORD packet_add_tlvs( Packet *packet, Tlv *entries, DWORD numEntries )
{
DWORD index;
for (index = 0; index < numEntries; index++)
packet_add_tlv_raw(packet, (TlvType)entries[index].header.type, entries[index].buffer, entries[index].header.length);
return ERROR_SUCCESS;
}
/*!
* @brief Add a raw value TLV to a packet, with compression.
* @details The value given in the \c buf parameter will be compressed with zlib.
* @param packet Pointer to the packet to add the value to.
* @param type TLV type for the value.
* @param buf Pointer to the data that is to be compressed and added.
* @param length Number of bytes in \c buf to compress.
* @return Indication of success or failure.
* @retval ERROR_SUCCESS The operation completed successfully.
* @retval ERROR_NOT_ENOUGH_MEMORY Insufficient memory available.
*/
DWORD packet_add_tlv_raw_compressed( Packet *packet, TlvType type, LPVOID buf, DWORD length )
{
DWORD result = ERROR_SUCCESS;
DWORD headerLength = sizeof( TlvHeader );
PUCHAR newPayload = NULL;
BYTE * compressed_buf = NULL;
DWORD realLength = 0;
DWORD newPayloadLength = 0;
DWORD compressed_length = (DWORD)( 1.01 * ( length + 12 ) + 1 );
do
{
compressed_buf = (BYTE *)malloc( compressed_length );
if( !compressed_buf )
{
result = ERROR_NOT_ENOUGH_MEMORY;
break;
}
if( compress2( compressed_buf, &compressed_length, buf, length, Z_BEST_COMPRESSION ) != Z_OK )
{
result = ERROR_UNSUPPORTED_COMPRESSION;
break;
}
realLength = compressed_length + headerLength;
newPayloadLength = packet->payloadLength + realLength;
// Allocate/Reallocate the packet's payload
if( packet->payload )
newPayload = (PUCHAR)realloc(packet->payload, newPayloadLength);
else
newPayload = (PUCHAR)malloc(newPayloadLength);
if( !newPayload )
{
result = ERROR_NOT_ENOUGH_MEMORY;
break;
}
// Populate the new TLV
((LPDWORD)(newPayload + packet->payloadLength))[0] = htonl(realLength);
((LPDWORD)(newPayload + packet->payloadLength))[1] = htonl((DWORD)type);
memcpy(newPayload + packet->payloadLength + headerLength, compressed_buf, compressed_length );
// Update the header length and payload length
packet->header.length = htonl(ntohl(packet->header.length) + realLength);
packet->payload = newPayload;
packet->payloadLength = newPayloadLength;
result = ERROR_SUCCESS;
} while( 0 );
if( compressed_buf )
free( compressed_buf );
return result;
}
/*!
* @brief Add an arbitrary raw value TLV to a packet.
* @details The value given in the \c buf parameter will _not_ be compressed.
* @param packet Pointer to the packet to add the value to.
* @param type TLV type for the value.
* @param buf Pointer to the data that is to be added.
* @param length Number of bytes in \c buf to add.
* @return Indication of success or failure.
* @retval ERROR_SUCCESS The operation completed successfully.
* @retval ERROR_NOT_ENOUGH_MEMORY Insufficient memory available.
*/
DWORD packet_add_tlv_raw( Packet *packet, TlvType type, LPVOID buf, DWORD length )
{
DWORD headerLength = sizeof(TlvHeader);
DWORD realLength = length + headerLength;
DWORD newPayloadLength = packet->payloadLength + realLength;
PUCHAR newPayload = NULL;
// check if this TLV is to be compressed...
if( ( type & TLV_META_TYPE_COMPRESSED ) == TLV_META_TYPE_COMPRESSED )
return packet_add_tlv_raw_compressed( packet, type, buf, length );
// Allocate/Reallocate the packet's payload
if (packet->payload)
newPayload = (PUCHAR)realloc( packet->payload, newPayloadLength );
else
newPayload = (PUCHAR)malloc( newPayloadLength );
if (!newPayload)
return ERROR_NOT_ENOUGH_MEMORY;
// Populate the new TLV
((LPDWORD)(newPayload + packet->payloadLength))[0] = htonl(realLength);
((LPDWORD)(newPayload + packet->payloadLength))[1] = htonl((DWORD)type);
memcpy( newPayload + packet->payloadLength + headerLength, buf, length );
// Update the header length and payload length
packet->header.length = htonl(ntohl(packet->header.length) + realLength);
packet->payload = newPayload;
packet->payloadLength = newPayloadLength;
return ERROR_SUCCESS;
}
/*!
* @brief Check if a TLV is NULL-terminated.
* @details The function checks the data within the range of bytes specified by
* the \c length property of the TLV \c header.
* @param tlv Pointer to the TLV to check.
* @return Indication of whether the TLV is terminated with a \c NULL byte or not.
* @retval ERROR_SUCCESS A \c NULL byte is present.
* @retval ERROR_NOT_FOUND No \c NULL byte is present.
* @sa TlvHeader
*/
DWORD packet_is_tlv_null_terminated( Tlv *tlv )
{
if ((tlv->header.length) && (tlv->buffer[tlv->header.length - 1] != 0))
return ERROR_NOT_FOUND;
return ERROR_SUCCESS;
}
/*!
* @brief Get the TLV type of the packet.
* @param packet Pointer to the packet to get the type from.
* @return \c PacketTlvType for the given \c Packet.
*/
PacketTlvType packet_get_type( Packet *packet )
{
return (PacketTlvType)ntohl( packet->header.type );
}
/*!
* @brief Get the TLV meta-type of the packet.
* @param packet Pointer to the packet to get the meta-type from.
* @return \c TlvMetaType for the given \c Packet.
*/
TlvMetaType packet_get_tlv_meta( Packet *packet, Tlv *tlv )
{
return TLV_META_TYPE_MASK( tlv->header.type );
}
/*!
* @brief Get a TLV of a given type from the packet.
* @param packet Pointer to the packet to get the TLV from.
* @param type Type of TLV to get.
* @param tlv Pointer to the TLV that will receive the data.
* @return Indication of success or failure.
* @retval ERROR_SUCCESS The operation completed successfully.
* @retval ERROR_NOT_FOUND Unable to find the TLV.
*/
DWORD packet_get_tlv( Packet *packet, TlvType type, Tlv *tlv )
{
return packet_enum_tlv( packet, 0, type, tlv );
}
/*!
* @brief Get a string TLV from the packet.
* @param packet Pointer to the packet to get the TLV from.
* @param type Type of TLV to get.
* @param tlv Pointer to the TLV that will receive the data.
* @return Indication of success or failure.
* @retval ERROR_SUCCESS The operation completed successfully.
* @retval ERROR_NOT_FOUND Unable to find the TLV or the string
* value is not NULL-terminated.
*/
DWORD packet_get_tlv_string( Packet *packet, TlvType type, Tlv *tlv )
{
DWORD res;
if ((res = packet_get_tlv( packet, type, tlv )) == ERROR_SUCCESS)
res = packet_is_tlv_null_terminated( tlv );
return res;
}
/*!
* @brief Get a TLV of a given type from a group TLV in the packet.
* @param packet Pointer to the packet to get the TLV from.
* @param group Pointer to the group TLV to get the value from.
* @param type Type of TLV to get.
* @param tlv Pointer to the TLV that will receive the data.
* @return Indication of success or failure.
* @retval ERROR_SUCCESS The operation completed successfully.
* @retval ERROR_NOT_FOUND Unable to find the TLV.
*/
DWORD packet_get_tlv_group_entry( Packet *packet, Tlv *group, TlvType type, Tlv *entry )
{
return packet_find_tlv_buf( packet, group->buffer, group->header.length, 0, type, entry );
}
/*!
* @brief Enumerate a TLV (with the option of constraining its type).
* @param packet Pointer to the packet to get the TLV from.
* @param type Type of TLV to get (optional).
* @param tlv Pointer to the TLV that will receive the data.
* @return Indication of success or failure.
* @retval ERROR_SUCCESS The operation completed successfully.
* @retval ERROR_NOT_FOUND Unable to find the TLV.
*/
DWORD packet_enum_tlv( Packet *packet, DWORD index, TlvType type, Tlv *tlv )
{
return packet_find_tlv_buf( packet, packet->payload, packet->payloadLength, index, type, tlv );
}
/*!
* @brief Get the string value of a TLV.
* @param packet Pointer to the packet to get the TLV from.
* @param type Type of TLV to get (optional).
* @return Pointer to the string value, if found.
* @retval NULL The string value was not found in the TLV.
* @retval Non-NULL Pointer to the string value.
*/
PCHAR packet_get_tlv_value_string( Packet *packet, TlvType type )
{
Tlv stringTlv;
PCHAR string = NULL;
if (packet_get_tlv_string( packet, type, &stringTlv ) == ERROR_SUCCESS)
string = (PCHAR)stringTlv.buffer;
return string;
}
/*!
* @brief Get the unsigned int value of a TLV.
* @param packet Pointer to the packet to get the TLV from.
* @param type Type of TLV to get (optional).
* @return The value found in the TLV.
* @todo On failure, 0 is returned. We need to make sure this is the right
* thing to do because 0 might also be a valid value.
*/
UINT packet_get_tlv_value_uint( Packet *packet, TlvType type )
{
Tlv uintTlv;
if ((packet_get_tlv( packet, type, &uintTlv ) != ERROR_SUCCESS) || (uintTlv.header.length < sizeof(DWORD)))
return 0;
return ntohl(*(LPDWORD)uintTlv.buffer);
}
/*!
* @brief Get the raw value of a TLV.
* @param packet Pointer to the packet to get the TLV from.
* @param type Type of TLV to get (optional).
* @return The value found in the TLV.
*/
BYTE * packet_get_tlv_value_raw( Packet * packet, TlvType type )
{
Tlv tlv;
if( packet_get_tlv( packet, type, &tlv ) != ERROR_SUCCESS )
return NULL;
return tlv.buffer;
}
/*!
* @brief Get the quad-word value of a TLV.
* @param packet Pointer to the packet to get the TLV from.
* @param type Type of TLV to get (optional).
* @return The value found in the TLV.
* @todo On failure, 0 is returned. We need to make sure this is the right
* thing to do because 0 might also be a valid value.
*/
QWORD packet_get_tlv_value_qword( Packet *packet, TlvType type )
{
Tlv qwordTlv;
if( ( packet_get_tlv( packet, type, &qwordTlv ) != ERROR_SUCCESS ) || ( qwordTlv.header.length < sizeof(QWORD) ) )
return 0;
return ntohq( *(QWORD *)qwordTlv.buffer );
}
/*!
* @brief Get the boolean value of a TLV.
* @param packet Pointer to the packet to get the TLV from.
* @param type Type of TLV to get (optional).
* @return The value found in the TLV.
* @todo On failure, FALSE is returned. We need to make sure this is the right
* thing to do because FALSE might also be a valid value.
*/
BOOL packet_get_tlv_value_bool( Packet *packet, TlvType type )
{
Tlv boolTlv;
BOOL val = FALSE;
if (packet_get_tlv( packet, type, &boolTlv ) == ERROR_SUCCESS)
val = (BOOL)(*(PCHAR)boolTlv.buffer);
return val;
}
/*!
* @brief Add an exception to a packet.
* @details When adding an exception, both a TLV_EXCEPTION_CODE and TLV_EXCEPTION_STRING
* are added to the packet.
* @param packet Pointer to the packet to add the detail to.
* @param code Exception code.
* @param fmt Form string for the exception string.
* @param ... Varargs for the format string.
* @return Indication of success or failure.
* @retval ERROR_NOT_ENOUGH_MEMORY Unable to allocate memory for the request packet.
* @retval ERROR_SUCCESS Transmission was successful.
*/
DWORD packet_add_exception( Packet *packet, DWORD code, PCHAR fmt, ... )
{
DWORD codeNbo = htonl(code);
char buf[8192];
Tlv entries[2];
va_list ap;
// Ensure null termination
buf[sizeof(buf) - 1] = 0;
va_start(ap, fmt);
_vsnprintf(buf, sizeof(buf) - 1, fmt, ap);
va_end(ap);
// Populate the TLV group array
entries[0].header.type = TLV_TYPE_EXCEPTION_CODE;
entries[0].header.length = 4;
entries[0].buffer = (PUCHAR)&codeNbo;
entries[1].header.type = TLV_TYPE_EXCEPTION_STRING;
entries[1].header.length = (DWORD)strlen(buf) + 1;
entries[1].buffer = (PUCHAR)buf;
// Add the TLV group, or try to at least.
return packet_add_tlv_group( packet, TLV_TYPE_EXCEPTION, entries, 2 );
}
/*!
* @brief Get the result code from the packet
* @param packet Pointer to the packet to get thget the result code from
* @return The result code.
*/
DWORD packet_get_result( Packet *packet )
{
return packet_get_tlv_value_uint( packet, TLV_TYPE_RESULT );
}
/*
* Enumerate TLV entries in a buffer until hitting a given index (optionally for a given type as well).
*/
/*!
* @brief Enumerate TLV entries until hitting a given index or type.
* @details This function will iterate through the given payload until one of the following conditions is true:
* - The end of the payload is encountered
* - The specified index is reached
* - A TLV of the specified type is reached
*
* If the first condition is met, the function returns with a failure.
* @param packet Pointer to the packet to get the TLV from.
* @param payload Pointer to the payload to parse.
* @param index Index of the TLV entry to find (optional).
* @param type Type of TLV to get (optional).
* @param tlv Pointer to the TLV that will receive the data.
* @return Indication of success or failure.
* @retval ERROR_SUCCESS The operation completed successfully.
* @retval ERROR_NOT_FOUND Unable to find the TLV.
*/
DWORD packet_find_tlv_buf( Packet *packet, PUCHAR payload, DWORD payloadLength, DWORD index, TlvType type, Tlv *tlv )
{
DWORD currentIndex = 0;
DWORD offset = 0, length = 0;
BOOL found = FALSE;
PUCHAR current;
memset(tlv, 0, sizeof(Tlv));
do
{
// Enumerate the TLV's
for( current = payload, length = 0 ; !found && current ; offset += length, current += length )
{
TlvHeader *header = (TlvHeader *)current;
TlvType current_type = TLV_TYPE_ANY; // effectively '0'
if ((current + sizeof(TlvHeader) > payload + payloadLength) || (current < payload))
break;
// TLV's length
length = ntohl(header->length);
// Matching type?
current_type = (TlvType)ntohl( header->type );
// if the type has been compressed, temporarily remove the compression flag as compression is to be transparent.
if( ( current_type & TLV_META_TYPE_COMPRESSED ) == TLV_META_TYPE_COMPRESSED )
current_type = (TlvType)(current_type ^ TLV_META_TYPE_COMPRESSED);
// check if the types match?
if( (current_type != type) && (type != TLV_TYPE_ANY) )
continue;
// Matching index?
if (currentIndex != index)
{
currentIndex++;
continue;
}
if ((current + length > payload + payloadLength) || (current < payload))
break;
tlv->header.type = ntohl(header->type);
tlv->header.length = ntohl(header->length) - sizeof(TlvHeader);
tlv->buffer = payload + offset + sizeof(TlvHeader);
if( ( tlv->header.type & TLV_META_TYPE_COMPRESSED ) == TLV_META_TYPE_COMPRESSED )
{
DECOMPRESSED_BUFFER * decompressed_buf = NULL;
do
{
decompressed_buf = (DECOMPRESSED_BUFFER *)malloc( sizeof(DECOMPRESSED_BUFFER) );
if( !decompressed_buf )
break;
// the first DWORD in a compressed buffer is the decompressed buffer length.
decompressed_buf->length = ntohl( *(DWORD *)tlv->buffer );
if( !decompressed_buf->length )
break;
decompressed_buf->buffer = (BYTE *)malloc( decompressed_buf->length );
if( !decompressed_buf->buffer )
break;
tlv->header.length -= sizeof( DWORD );
tlv->buffer += sizeof( DWORD );
if( uncompress( (Bytef*)decompressed_buf->buffer, &decompressed_buf->length, tlv->buffer, tlv->header.length ) != Z_OK )
break;
tlv->header.type = tlv->header.type ^ TLV_META_TYPE_COMPRESSED;
tlv->header.length = decompressed_buf->length;
tlv->buffer = (PUCHAR)decompressed_buf->buffer;
if( !packet->decompressed_buffers )
packet->decompressed_buffers = list_create();
if( !packet->decompressed_buffers )
break;
// each packet has a list of decompressed buffers which is used to
// wipe and fee all decompressed buffers upon the packet being destroyed.
list_push( packet->decompressed_buffers, decompressed_buf );
found = TRUE;
} while( 0 );
if( !found && decompressed_buf )
{