-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
rpc.lua
3490 lines (3054 loc) · 108 KB
/
rpc.lua
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
---
-- RPC Library supporting a very limited subset of operations.
--
-- The library works over both the UDP and TCP protocols. A subset of nfs and
-- mountd procedures are supported. The nfs and mountd programs support
-- versions 1 through 3. Authentication is supported using the NULL RPC
-- Authentication protocol
--
-- The library contains the following classes:
-- * <code>Comm </code>
-- ** Handles network connections.
-- ** Handles low-level packet sending, receiving, decoding and encoding.
-- ** Stores rpc programs info: socket, protocol, program name, id and version.
-- ** Used by Mount, NFS, RPC and Portmap.
-- * <code>Portmap</code>
-- ** Contains RPC constants.
-- ** Handles communication with the portmap RPC program.
-- * <code>Mount</code>
-- ** Handles communication with the mount RPC program.
-- * <code>NFS</code>
-- ** Handles communication with the nfs RPC program.
-- * <code>Helper</code>
-- ** Provides easy access to common RPC functions.
-- ** Implemented as a static class where most functions accept host and port parameters.
-- * <code>Util</code>
-- ** Mostly static conversion routines.
--
-- The portmapper dynamically allocates TCP/UDP ports to RPC programs. So in
-- in order to request a list of NFS shares from the server we need to:
-- * Make sure that we can talk to the portmapper on port 111 TCP or UDP.
-- * Query the portmapper for the ports allocated to the NFS program.
-- * Query the NFS program for a list of shares on the ports returned by the portmap program.
--
-- The Helper class contains functions that facilitate access to common
-- RPC program procedures through static class methods. Most functions accept
-- host and port parameters. As the Helper functions query the portmapper to
-- get the correct RPC program port, the port supplied to these functions
-- should be the rpcbind port 111/tcp or 111/udp.
--
-- The following sample code illustrates how scripts can use the <code>Helper</code> class
-- to interface the library:
--
-- <code>
-- -- retrieve a list of NFS export
-- status, mounts = rpc.Helper.ShowMounts( host, port )
--
-- -- iterate over every share
-- for _, mount in ipairs( mounts ) do
--
-- -- get the NFS attributes for the share
-- status, attribs = rpc.Helper.GetAttributes( host, port, mount.name )
-- .... process NFS attributes here ....
-- end
-- </code>
--
-- RPC transaction IDs (XID) are not properly implemented as a random ID is
-- generated for each client call. The library makes no attempt to verify
-- whether the returned XID is valid or not.
--
-- Therefore TCP is the preferred method of communication and the library
-- always attempts to connect to the TCP port of the RPC program first.
-- This behaviour can be overridden by setting the rpc.protocol argument.
-- The portmap service is always queried over the protocol specified in the
-- port information used to call the Helper function from the script.
--
-- When multiple versions exists for a specific RPC program the library
-- always attempts to connect using the highest available version.
--
-- @copyright Same as Nmap--See https://nmap.org/book/man-legal.html
--
-- @author Patrik Karlsson <[email protected]>
--
-- @args nfs.version number If set overrides the detected version of nfs
-- @args mount.version number If set overrides the detected version of mountd
-- @args rpc.protocol table If set overrides the preferred order in which
-- protocols are tested. (ie. "tcp", "udp")
local datafiles = require "datafiles"
local datetime = require "datetime"
local math = require "math"
local nmap = require "nmap"
local stdnse = require "stdnse"
local string = require "string"
local table = require "table"
local tableaux = require "tableaux"
_ENV = stdnse.module("rpc", stdnse.seeall)
-- Version 0.3
--
-- Created 01/24/2010 - v0.1 - created by Patrik Karlsson <[email protected]>
-- Revised 02/22/2010 - v0.2 - cleanup, revised the way TCP/UDP are handled fo
-- encoding an decoding
-- Revised 03/13/2010 - v0.3 - re-worked library to be OO
-- Revised 04/18/2010 - v0.4 - Applied patch from Djalal Harouni with improved
-- error checking and re-designed Comm class. see:
-- http:https://seclists.org/nmap-dev/2010/q2/232
-- Revised 06/02/2010 - v0.5 - added code to the Util class to check for file
-- types and permissions.
-- Revised 06/04/2010 - v0.6 - combined Portmap and RPC classes in the
-- same Portmap class.
--
-- RPC args using the nmap.registry.args
RPC_args = {
["rpcbind"] = { proto = 'rpc.protocol' },
["nfs"] = { ver = 'nfs.version' },
["mountd"] = { ver = 'mount.version' },
}
-- Defines the order in which to try to connect to the RPC programs
-- TCP appears to be more stable than UDP in most cases, so try it first
local RPC_PROTOCOLS = (nmap.registry.args and nmap.registry.args[RPC_args['rpcbind'].proto] and
type(nmap.registry.args[RPC_args['rpcbind'].proto]) == 'table') and
nmap.registry.args[RPC_args['rpcbind'].proto] or { "tcp", "udp" }
-- used to cache the contents of the rpc datafile
local RPC_PROGRAMS, RPC_NUMBERS
-- local mutex to synchronize I/O operations on nmap.registry[host.ip]['portmapper']
local mutex = nmap.mutex("rpc")
-- Supported protocol versions
RPC_version = {
["rpcbind"] = { min=2, max=4 },
["nfs"] = { min=1, max=3 },
["mountd"] = { min=1, max=3 },
}
-- Low-level communication class
Comm = {
--- Creates a new rpc Comm object
--
-- @param program name string
-- @param version number containing the program version to use
-- @return a new Comm object
new = function(self, program, version)
local o = {}
setmetatable(o, self)
self.__index = self
o.program = program
o.program_id = Util.ProgNameToNumber(program)
o.checkprogver = true
o:SetVersion(version)
return o
end,
--- Connects to the remote program
--
-- @param host table
-- @param port table
-- @param timeout [optional] socket timeout in ms
-- @return status boolean true on success, false on failure
-- @return string containing error message (if status is false)
Connect = function(self, host, port, timeout)
local status, err, socket
status, err = self:ChkProgram()
if (not(status)) then
return status, err
end
status, err = self:ChkVersion()
if (not(status)) then
return status, err
end
timeout = timeout or stdnse.get_timeout(host, 10000)
local new_socket = function(...)
local socket = nmap.new_socket(...)
socket:set_timeout(timeout)
return socket
end
if ( port.protocol == "tcp" ) then
if nmap.is_privileged() then
-- Try to bind to a reserved port
for i = 1, 10, 1 do
local resvport = math.random(512, 1023)
socket = new_socket()
status, err = socket:bind(nil, resvport)
if status then
status, err = socket:connect(host, port)
if status or err == "TIMEOUT" then break end
socket:close()
end
end
else
socket = new_socket()
status, err = socket:connect(host, port)
end
else
if nmap.is_privileged() then
-- Try to bind to a reserved port
for i = 1, 10, 1 do
local resvport = math.random(512, 1023)
socket = new_socket("udp")
status, err = socket:bind(nil, resvport)
if status then
status, err = socket:connect(host, port)
if status or err == "TIMEOUT" then break end
socket:close()
end
end
else
socket = new_socket("udp")
status, err = socket:connect(host, port)
end
end
if (not(status)) then
return status, string.format("%s connect error: %s",
self.program, err)
else
self.socket = socket
self.host = host
self.ip = host.ip
self.port = port.number
self.proto = port.protocol
return status, nil
end
end,
--- Disconnects from the remote program
--
-- @return status boolean true on success, false on failure
-- @return string containing error message (if status is false)
Disconnect = function(self)
local status, err = self.socket:close()
if (not(status)) then
return status, string.format("%s disconnect error: %s",
self.program, err)
end
self.socket=nil
return status, nil
end,
--- Checks if the rpc program is supported
--
-- @return status boolean true on success, false on failure
-- @return string containing error message (if status is false)
ChkProgram = function(self)
if (not(RPC_version[self.program])) then
return false, string.format("RPC library does not support: %s protocol",
self.program)
end
return true, nil
end,
--- Checks if the rpc program version is supported
--
-- @return status boolean true on success, false on failure
-- @return string containing error message (if status is false)
ChkVersion = function(self)
if not self.checkprogver then return true end
if ( self.version > RPC_version[self.program].max or
self.version < RPC_version[self.program].min ) then
return false, string.format("RPC library does not support: %s version %d",
self.program,self.version)
end
return true, nil
end,
--- Sets the rpc program version
--
-- @return status boolean true
SetVersion = function(self, version)
if self.checkprogver then
if (RPC_version[self.program] and RPC_args[self.program] and
nmap.registry.args and nmap.registry.args[RPC_args[self.program].ver]) then
self.version = tonumber(nmap.registry.args[RPC_args[self.program].ver])
elseif (not(self.version) and version) then
self.version = version
end
else
self.version = version
end
return true, nil
end,
--- Sets the verification of the specified program and version support
-- before trying to connecting.
-- @param check boolean to enable or disable checking of program and version support.
SetCheckProgVer = function(self, check)
self.checkprogver = check
end,
--- Sets the RPC program ID to use.
-- @param progid number Program ID to set.
SetProgID = function(self, progid)
self.program_id = progid
end,
--- Checks if <code>data</code> contains enough bytes to read the <code>needed</code> amount
--
-- If it doesn't it attempts to read the remaining amount of bytes from the
-- socket. Unlike <code>socket.receive_bytes</code>, reading less than
-- <code>needed</code> is treated as an error.
--
-- @param data string containing the current buffer
-- @param pos number containing the current offset into the buffer
-- @param needed number containing the number of bytes needed to be available
-- @return status success or failure
-- @return data string containing the data passed to the function and the additional data appended to it or error message on failure
GetAdditionalBytes = function( self, data, pos, needed )
local toread = needed - ( data:len() - pos + 1 )
-- Do the loop ourselves instead of receive_bytes. Pathological case:
-- * read less than needed and timeout
-- * receive_bytes returns short but we don't know if it's eof or timeout
-- * Try again. If it was timeout, we've doubled the timeout waiting for bytes that aren't coming.
while toread > 0 do
local status, tmp = self.socket:receive()
if status then
toread = toread - #tmp
data = data .. tmp
else
return false, string.format("getAdditionalBytes read %d bytes before error: %s",
needed - toread, tmp)
end
end
return true, data
end,
--- Creates a RPC header
--
-- @param xid number. If no xid was provided, a random one will be used.
-- @param procedure number containing the procedure to call. Defaults to <code>0</code>.
-- @param auth table containing the authentication data to use. Defaults to NULL authentication.
-- @return status boolean true on success, false on failure
-- @return string of bytes on success, error message on failure
CreateHeader = function( self, xid, procedure, auth )
local RPC_VERSION = 2
local packet
-- Defaulting to NULL Authentication
local auth = auth or {type = Portmap.AuthType.NULL}
local xid = xid or math.random(1234567890)
local procedure = procedure or 0
packet = string.pack( ">I4 I4 I4 I4 I4 I4", xid, Portmap.MessageType.CALL, RPC_VERSION,
self.program_id, self.version, procedure )
if auth.type == Portmap.AuthType.NULL then
packet = packet .. string.pack( ">I4 I4 I4 I4", 0, 0, 0, 0 )
elseif auth.type == Portmap.AuthType.UNIX then
packet = packet .. Util.marshall_int32(auth.type)
local blob = (
Util.marshall_int32(math.floor(nmap.clock())) --time
.. Util.marshall_vopaque(auth.hostname or 'localhost')
.. Util.marshall_int32(auth.uid or 0)
.. Util.marshall_int32(auth.gid or 0)
)
if auth.gids then --len prefix gid list
blob = blob .. Util.marshall_int32(#auth.gids)
for _,gid in ipairs(auth.gids) do
blob = blob .. Util.marshall_int32(gid)
end
else
blob = blob .. Util.marshall_int32(0)
end
packet = (packet .. Util.marshall_vopaque(blob)
.. string.pack( ">I4 I4", 0, 0 ) --AUTH_NULL verf
)
else
return false, "Comm.CreateHeader: invalid authentication type specified"
end
return true, packet
end,
--- Decodes the RPC header (without the leading 4 bytes as received over TCP)
--
-- @param data string containing the buffer of bytes read so far
-- @param pos number containing the current offset into data
-- @return pos number containing the offset after the decoding
-- @return header table containing <code>xid</code>, <code>type</code>, <code>state</code>,
-- <code>verifier</code> and ( <code>accept_state</code> or <code>denied_state</code> )
DecodeHeader = function( self, data, pos )
local header = {}
local status
local HEADER_LEN = 20
header.verifier = {}
pos = pos or 1
if ( data:len() - pos + 1 < HEADER_LEN ) then
local tmp
status, tmp = self:GetAdditionalBytes( data, pos, HEADER_LEN - ( data:len() - pos ) )
if not status then
stdnse.debug4("Comm.DecodeHeader: failed to call GetAdditionalBytes")
return -1, nil
end
data = data .. tmp
end
header.xid, header.type, header.state, pos = string.unpack(">I4 I4 I4", data, pos)
if ( header.state == Portmap.State.MSG_DENIED ) then
header.denied_state, pos = string.unpack(">I4", data, pos )
return pos, header
end
header.verifier.flavor, pos = string.unpack(">I4", data, pos)
header.verifier.length, pos = string.unpack(">I4", data, pos)
if header.verifier.length - 8 > 0 then
status, data = self:GetAdditionalBytes( data, pos, header.verifier.length - 8 )
if not status then
stdnse.debug4("Comm.DecodeHeader: failed to call GetAdditionalBytes")
return -1, nil
end
header.verifier.data, pos = string.unpack("c" .. header.verifier.length - 8, data, pos )
end
header.accept_state, pos = string.unpack(">I4", data, pos )
return pos, header
end,
--- Reads the response from the socket
--
-- @return status true on success, false on failure
-- @return data string containing the raw response or error message on failure
ReceivePacket = function( self )
local status
if ( self.proto == "udp" ) then
-- There's not much we can do in here to check if we received all data
-- as the packet contains no length field. It's up to each decoding function
-- to do appropriate checks
return self.socket:receive_bytes(1)
else
local tmp, lastfragment, length
local data, pos = "", 1
-- Maximum number of allowed attempts to parse the received bytes. This
-- prevents the code from looping endlessly on invalid content.
local retries = 400
repeat
retries = retries - 1
lastfragment = false
status, data = self:GetAdditionalBytes( data, pos, 4 )
if ( not(status) ) then
return false, "Comm.ReceivePacket: failed to call GetAdditionalBytes"
end
tmp, pos = string.unpack(">I4", data, pos )
length = tmp & 0x7FFFFFFF
if (tmp & 0x80000000) == 0x80000000 then
lastfragment = true
end
status, data = self:GetAdditionalBytes( data, pos, length )
if ( not(status) ) then
return false, "Comm.ReceivePacket: failed to call GetAdditionalBytes"
end
--
-- When multiple packets are received they look like this
-- H = Header data
-- D = Data
--
-- We don't want the Header
--
-- HHHHDDDDDDDDDDDDDDHHHHDDDDDDDDDDD
-- ^ ^ ^ ^
-- 1 5 18 22
--
-- eg. we want
-- data:sub(5, 18) and data:sub(22)
--
local bufcopy = data:sub(pos)
if 1 ~= pos - 4 then
bufcopy = data:sub(1, pos - 5) .. bufcopy
pos = pos - 4
else
pos = 1
end
pos = pos + length
data = bufcopy
until (lastfragment == true) or (retries == 0)
if retries == 0 then
return false, "Aborted after too many retries"
end
return true, data
end
end,
--- Encodes a RPC packet
--
-- @param xid number containing the transaction ID
-- @param proc number containing the procedure to call
-- @param auth table containing authentication information
-- @param data string containing the packet data
-- @return packet string containing the encoded packet data
EncodePacket = function( self, xid, proc, auth, data )
local status, packet = self:CreateHeader( xid, proc, auth )
local len
if ( not(status) ) then
return
end
packet = packet .. ( data or "" )
if ( self.proto == "udp") then
return packet
else
-- set the high bit as this is our last fragment
len = 0x80000000 + packet:len()
return string.pack(">I4", len) .. packet
end
end,
SendPacket = function( self, packet )
if ( self.host and self.port ) then
return self.socket:sendto(self.host, self.port, packet)
else
return self.socket:send( packet )
end
end,
GetSocketInfo = function(self)
return self.socket:get_info()
end,
}
--- Portmap (rpcbind) class
Portmap =
{
PROTOCOLS = {
['tcp'] = 6,
['udp'] = 17,
},
-- TODO: add more Authentication Protocols
AuthType =
{
NULL = 0,
UNIX = 1,
},
-- TODO: complete Authentication stats and error messages
AuthState =
{
AUTH_OK = 0,
AUTH_BADCRED = 1,
AUTH_REJECTEDCRED = 2,
AUTH_BADVERF = 3,
AUTH_REJECTEDVERF = 4,
AUTH_TOOWEAK = 5,
AUTH_INVALIDRESP = 6,
AUTH_FAILED = 7,
},
AuthMsg =
{
[0] = "Success.",
[1] = "bad credential (seal broken).",
[2] = "client must begin new session.",
[3] = "bad verifier (seal broken).",
[4] = "verifier expired or replayed.",
[5] = "rejected for security reasons.",
[6] = "bogus response verifier.",
[7] = "reason unknown.",
},
MessageType =
{
CALL = 0,
REPLY = 1
},
Procedure =
{
[2] =
{
GETPORT = 3,
DUMP = 4,
CALLIT = 5,
},
[3] =
{
DUMP = 4,
},
[4] =
{
DUMP = 4,
},
},
State =
{
MSG_ACCEPTED = 0,
MSG_DENIED = 1,
},
AcceptState =
{
SUCCESS = 0,
PROG_UNAVAIL = 1,
PROG_MISMATCH = 2,
PROC_UNAVAIL = 3,
GARBAGE_ARGS = 4,
SYSTEM_ERR = 5,
},
AcceptMsg =
{
[0] = "RPC executed successfully.",
[1] = "remote hasn't exported program.",
[2] = "remote can't support version.",
[3] = "program can't support procedure.",
[4] = "procedure can't decode params.",
[5] = "errors like memory allocation failure.",
},
RejectState =
{
RPC_MISMATCH = 0,
AUTH_ERROR = 1,
},
RejectMsg =
{
[0] = "RPC version number != 2.",
[1] = "remote can't authenticate caller.",
},
new = function(self,o)
o = o or {}
setmetatable(o, self)
self.__index = self
return o
end,
--- Dumps a list of RCP programs from the portmapper
--
-- @param comm object handles rpc program information and
-- low-level packet manipulation
-- @return status boolean true on success, false on failure
-- @return result table containing RPC program information or error message
-- on failure. The table has the following format:
--
-- <code>
-- table[program_id][protocol]["port"] = <port number>
-- table[program_id][protocol]["version"] = <table of versions>
-- table[program_id][protocol]["addr"] = <IP address, for RPCv3 and higher>
-- </code>
--
-- Where
-- o program_id is the number associated with the program
-- o protocol is one of "tcp", "udp", "tcp6", or "udp6", or another netid
-- reported by the system.
--
Dump = function(self, comm)
local status, data, packet, response, pos, header
local program_table = setmetatable({}, { __mode = 'v' })
packet = comm:EncodePacket( nil, Portmap.Procedure[comm.version].DUMP,
{ type=Portmap.AuthType.NULL }, data )
if (not(comm:SendPacket(packet))) then
return false, "Portmap.Dump: Failed to send data"
end
status, data = comm:ReceivePacket()
if ( not(status) ) then
return false, "Portmap.Dump: Failed to read data from socket"
end
pos, header = comm:DecodeHeader( data, 1 )
if ( not(header) ) then
return false, "Portmap.Dump: Failed to decode RPC header"
end
if header.type ~= Portmap.MessageType.REPLY then
return false, "Portmap.Dump: Packet was not a reply"
end
if header.state ~= Portmap.State.MSG_ACCEPTED then
if (Portmap.RejectMsg[header.denied_state]) then
return false,
string.format("Portmap.Dump: RPC call failed: %s",
Portmap.RejectMsg[header.denied_state])
else
return false,
string.format("Portmap.Dump: RPC call failed: code %d",
header.state)
end
end
if header.accept_state ~= Portmap.AcceptState.SUCCESS then
if (Portmap.AcceptMsg[header.accept_state]) then
return false,
string.format("Portmap.Dump: RPC accepted state: %s",
Portmap.AcceptMsg[header.accept_state])
else
return false,
string.format("Portmap.Dump: RPC accepted state code %d",
header.accept_state)
end
end
while true do
local vfollows
local program, version, protocol, port
status, data = comm:GetAdditionalBytes( data, pos, 4 )
if ( not(status) ) then
return false, "Portmap.Dump: Failed to call GetAdditionalBytes"
end
vfollows, pos = string.unpack(">I4", data, pos)
if ( vfollows == 0 ) then
break
end
program, version, pos = string.unpack(">I4 I4", data, pos)
local addr, owner
if comm.version > 2 then
local len
len, pos = string.unpack(">I4", data, pos)
pos, protocol = Util.unmarshall_vopaque(len, data, pos)
-- workaround for NetApp 5.0: trim trailing null bytes
protocol = protocol:match("[^\0]*")
len, pos = string.unpack(">I4", data, pos)
pos, addr = Util.unmarshall_vopaque(len, data, pos)
len, pos = string.unpack(">I4", data, pos)
pos, owner = Util.unmarshall_vopaque(len, data, pos)
if protocol:match("^[tu][cd]p6?$") then
-- RFC 5665
local upper, lower
addr, upper, lower = addr:match("^(.-)%.(%d+)%.(%d+)$")
if addr then
port = tonumber(upper) * 0x100 + tonumber(lower)
end
end
else
protocol, port, pos = string.unpack(">I4 I4", data, pos)
if ( protocol == Portmap.PROTOCOLS.tcp ) then
protocol = "tcp"
elseif ( protocol == Portmap.PROTOCOLS.udp ) then
protocol = "udp"
end
end
program_table[program] = program_table[program] or {}
program_table[program][protocol] = program_table[program][protocol] or {}
program_table[program][protocol]["port"] = port
program_table[program][protocol]["addr"] = addr
program_table[program][protocol]["owner"] = owner
program_table[program][protocol]["version"] = program_table[program][protocol]["version"] or {}
table.insert( program_table[program][protocol]["version"], version )
-- parts of the code rely on versions being in order
-- this way the highest version can be chosen by choosing the last element
table.sort( program_table[program][protocol]["version"] )
end
nmap.registry[comm.ip]['portmapper'] = program_table
return true, nmap.registry[comm.ip]['portmapper']
end,
--- Calls the portmap callit call and returns the raw response
--
-- @param comm object handles rpc program information and
-- low-level packet manipulation
-- @param program string name of the program
-- @param protocol string containing either "tcp" or "udp"
-- @param version number containing the version of the queried program
-- @return status true on success, false on failure
-- @return data string containing the raw response
Callit = function( self, comm, program, protocol, version )
if ( not( Portmap.PROTOCOLS[protocol] ) ) then
return false, ("Portmap.Callit: Protocol %s not supported"):format(protocol)
end
if ( Util.ProgNameToNumber(program) == nil ) then
return false, ("Portmap.Callit: Unknown program name: %s"):format(program)
end
local data = string.pack(">I4 I4 I4 I4", Util.ProgNameToNumber(program), version, 0, 0 )
local packet = comm:EncodePacket(nil, Portmap.Procedure[comm.version].CALLIT,
{ type=Portmap.AuthType.NULL }, data )
if (not(comm:SendPacket(packet))) then
return false, "Portmap.Callit: Failed to send data"
end
data = ""
local status, data = comm:ReceivePacket()
if ( not(status) ) then
return false, "Portmap.Callit: Failed to read data from socket"
end
local pos, header = comm:DecodeHeader( data, 1 )
if ( not(header) ) then
return false, "Portmap.Callit: Failed to decode RPC header"
end
if header.type ~= Portmap.MessageType.REPLY then
return false, "Portmap.Callit: Packet was not a reply"
end
return true, data
end,
--- Queries the portmapper for the port of the selected program,
-- protocol and version
--
-- @param comm object handles rpc program information and
-- low-level packet manipulation
-- @param program string name of the program
-- @param protocol string containing either "tcp" or "udp"
-- @param version number containing the version of the queried program
-- @return number containing the port number
GetPort = function( self, comm, program, protocol, version )
local status, data, response, header, pos, packet
local xid
if ( not( Portmap.PROTOCOLS[protocol] ) ) then
return false, ("Portmap.GetPort: Protocol %s not supported"):format(protocol)
end
if ( Util.ProgNameToNumber(program) == nil ) then
return false, ("Portmap.GetPort: Unknown program name: %s"):format(program)
end
data = string.pack(">I4 I4 I4 I4", Util.ProgNameToNumber(program), version,
Portmap.PROTOCOLS[protocol], 0 )
packet = comm:EncodePacket(xid, Portmap.Procedure[comm.version].GETPORT,
{ type=Portmap.AuthType.NULL }, data )
if (not(comm:SendPacket(packet))) then
return false, "Portmap.GetPort: Failed to send data"
end
data = ""
status, data = comm:ReceivePacket()
if ( not(status) ) then
return false, "Portmap.GetPort: Failed to read data from socket"
end
pos, header = comm:DecodeHeader( data, 1 )
if ( not(header) ) then
return false, "Portmap.GetPort: Failed to decode RPC header"
end
if header.type ~= Portmap.MessageType.REPLY then
return false, "Portmap.GetPort: Packet was not a reply"
end
if header.state ~= Portmap.State.MSG_ACCEPTED then
if (Portmap.RejectMsg[header.denied_state]) then
return false, string.format("Portmap.GetPort: RPC call failed: %s",
Portmap.RejectMsg[header.denied_state])
else
return false,
string.format("Portmap.GetPort: RPC call failed: code %d",
header.state)
end
end
if header.accept_state ~= Portmap.AcceptState.SUCCESS then
if (Portmap.AcceptMsg[header.accept_state]) then
return false, string.format("Portmap.GetPort: RPC accepted state: %s",
Portmap.AcceptMsg[header.accept_state])
else
return false, string.format("Portmap.GetPort: RPC accepted state code %d",
header.accept_state)
end
end
status, data = comm:GetAdditionalBytes( data, pos, 4 )
if ( not(status) ) then
return false, "Portmap.GetPort: Failed to call GetAdditionalBytes"
end
return true, string.unpack(">I4", data, pos)
end,
}
--- Mount class handling communication with the mountd program
--
-- Currently supports versions 1 through 3
-- Can be called either directly or through the static Helper class
--
Mount = {
StatMsg = {
[1] = "Not owner.",
[2] = "No such file or directory.",
[5] = "I/O error.",
[13] = "Permission denied.",
[20] = "Not a directory.",
[22] = "Invalid argument.",
[63] = "Filename too long.",
[10004] = "Operation not supported.",
[10006] = "A failure on the server.",
},
StatCode = {
MNT_OK = 0,
MNTERR_PERM = 1,
MNTERR_NOENT = 2,
MNTERR_IO = 5,
MNTERR_ACCES = 13,
MNTERR_NOTDIR = 20,
MNTERR_INVAL = 22,
MNTERR_NAMETOOLONG = 63,
MNTERR_NOTSUPP = 10004,
MNTERR_SERVERFAULT = 10006,
},
Procedure =
{
MOUNT = 1,
DUMP = 2,
UMNT = 3,
UMNTALL = 4,
EXPORT = 5,
},
new = function(self,o)
o = o or {}
setmetatable(o, self)
self.__index = self
return o
end,
--- Requests a list of NFS export from the remote server
--
-- @param comm object handles rpc program information and
-- low-level packet manipulation
-- @return status success or failure
-- @return entries table containing a list of share names (strings)
Export = function(self, comm)
local msg_type = 0
local packet
local pos = 1
local header = {}
local entries = {}
local data = ""
local status
if comm.proto ~= "tcp" and comm.proto ~= "udp" then
return false, "Mount.Export: Protocol should be either udp or tcp"
end
packet = comm:EncodePacket(nil, Mount.Procedure.EXPORT,
{ type=Portmap.AuthType.UNIX }, nil )
if (not(comm:SendPacket( packet ))) then
return false, "Mount.Export: Failed to send data"
end
status, data = comm:ReceivePacket()
if ( not(status) ) then
return false, "Mount.Export: Failed to read data from socket"
end
-- make sure we have at least 24 bytes to unpack the header
status, data = comm:GetAdditionalBytes( data, pos, 24 )
if (not(status)) then
return false, "Mount.Export: Failed to call GetAdditionalBytes"
end
pos, header = comm:DecodeHeader( data, pos )
if not header then
return false, "Mount.Export: Failed to decode header"
end
if header.type ~= Portmap.MessageType.REPLY then
return false, "Mount.Export: packet was not a reply"
end
if header.state ~= Portmap.State.MSG_ACCEPTED then
if (Portmap.RejectMsg[header.denied_state]) then
return false, string.format("Mount.Export: RPC call failed: %s",
Portmap.RejectMsg[header.denied_state])
else
return false, string.format("Mount.Export: RPC call failed: code %d",
header.state)
end
end
if header.accept_state ~= Portmap.AcceptState.SUCCESS then
if (Portmap.AcceptMsg[header.accept_state]) then
return false, string.format("Mount.Export: RPC accepted state: %s",
Portmap.AcceptMsg[header.accept_state])
else
return false, string.format("Mount.Export: RPC accepted state code %d",
header.accept_state)
end
end
-- Decode directory entries
--
-- [entry]
-- 4 bytes - value follows (1 if more data, 0 if not)
-- [Directory]