├── README.md
├── LICENSE
└── smb-logger.c
/README.md:
--------------------------------------------------------------------------------
1 | # smb-logger
2 | Logs incoming attempts to connect to NetBIOS/SMB
3 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 2, June 1991
3 |
4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
6 | Everyone is permitted to copy and distribute verbatim copies
7 | of this license document, but changing it is not allowed.
8 |
9 | Preamble
10 |
11 | The licenses for most software are designed to take away your
12 | freedom to share and change it. By contrast, the GNU General Public
13 | License is intended to guarantee your freedom to share and change free
14 | software--to make sure the software is free for all its users. This
15 | General Public License applies to most of the Free Software
16 | Foundation's software and to any other program whose authors commit to
17 | using it. (Some other Free Software Foundation software is covered by
18 | the GNU Lesser General Public License instead.) You can apply it to
19 | your programs, too.
20 |
21 | When we speak of free software, we are referring to freedom, not
22 | price. Our General Public Licenses are designed to make sure that you
23 | have the freedom to distribute copies of free software (and charge for
24 | this service if you wish), that you receive source code or can get it
25 | if you want it, that you can change the software or use pieces of it
26 | in new free programs; and that you know you can do these things.
27 |
28 | To protect your rights, we need to make restrictions that forbid
29 | anyone to deny you these rights or to ask you to surrender the rights.
30 | These restrictions translate to certain responsibilities for you if you
31 | distribute copies of the software, or if you modify it.
32 |
33 | For example, if you distribute copies of such a program, whether
34 | gratis or for a fee, you must give the recipients all the rights that
35 | you have. You must make sure that they, too, receive or can get the
36 | source code. And you must show them these terms so they know their
37 | rights.
38 |
39 | We protect your rights with two steps: (1) copyright the software, and
40 | (2) offer you this license which gives you legal permission to copy,
41 | distribute and/or modify the software.
42 |
43 | Also, for each author's protection and ours, we want to make certain
44 | that everyone understands that there is no warranty for this free
45 | software. If the software is modified by someone else and passed on, we
46 | want its recipients to know that what they have is not the original, so
47 | that any problems introduced by others will not reflect on the original
48 | authors' reputations.
49 |
50 | Finally, any free program is threatened constantly by software
51 | patents. We wish to avoid the danger that redistributors of a free
52 | program will individually obtain patent licenses, in effect making the
53 | program proprietary. To prevent this, we have made it clear that any
54 | patent must be licensed for everyone's free use or not licensed at all.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | GNU GENERAL PUBLIC LICENSE
60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
61 |
62 | 0. This License applies to any program or other work which contains
63 | a notice placed by the copyright holder saying it may be distributed
64 | under the terms of this General Public License. The "Program", below,
65 | refers to any such program or work, and a "work based on the Program"
66 | means either the Program or any derivative work under copyright law:
67 | that is to say, a work containing the Program or a portion of it,
68 | either verbatim or with modifications and/or translated into another
69 | language. (Hereinafter, translation is included without limitation in
70 | the term "modification".) Each licensee is addressed as "you".
71 |
72 | Activities other than copying, distribution and modification are not
73 | covered by this License; they are outside its scope. The act of
74 | running the Program is not restricted, and the output from the Program
75 | is covered only if its contents constitute a work based on the
76 | Program (independent of having been made by running the Program).
77 | Whether that is true depends on what the Program does.
78 |
79 | 1. You may copy and distribute verbatim copies of the Program's
80 | source code as you receive it, in any medium, provided that you
81 | conspicuously and appropriately publish on each copy an appropriate
82 | copyright notice and disclaimer of warranty; keep intact all the
83 | notices that refer to this License and to the absence of any warranty;
84 | and give any other recipients of the Program a copy of this License
85 | along with the Program.
86 |
87 | You may charge a fee for the physical act of transferring a copy, and
88 | you may at your option offer warranty protection in exchange for a fee.
89 |
90 | 2. You may modify your copy or copies of the Program or any portion
91 | of it, thus forming a work based on the Program, and copy and
92 | distribute such modifications or work under the terms of Section 1
93 | above, provided that you also meet all of these conditions:
94 |
95 | a) You must cause the modified files to carry prominent notices
96 | stating that you changed the files and the date of any change.
97 |
98 | b) You must cause any work that you distribute or publish, that in
99 | whole or in part contains or is derived from the Program or any
100 | part thereof, to be licensed as a whole at no charge to all third
101 | parties under the terms of this License.
102 |
103 | c) If the modified program normally reads commands interactively
104 | when run, you must cause it, when started running for such
105 | interactive use in the most ordinary way, to print or display an
106 | announcement including an appropriate copyright notice and a
107 | notice that there is no warranty (or else, saying that you provide
108 | a warranty) and that users may redistribute the program under
109 | these conditions, and telling the user how to view a copy of this
110 | License. (Exception: if the Program itself is interactive but
111 | does not normally print such an announcement, your work based on
112 | the Program is not required to print an announcement.)
113 |
114 | These requirements apply to the modified work as a whole. If
115 | identifiable sections of that work are not derived from the Program,
116 | and can be reasonably considered independent and separate works in
117 | themselves, then this License, and its terms, do not apply to those
118 | sections when you distribute them as separate works. But when you
119 | distribute the same sections as part of a whole which is a work based
120 | on the Program, the distribution of the whole must be on the terms of
121 | this License, whose permissions for other licensees extend to the
122 | entire whole, and thus to each and every part regardless of who wrote it.
123 |
124 | Thus, it is not the intent of this section to claim rights or contest
125 | your rights to work written entirely by you; rather, the intent is to
126 | exercise the right to control the distribution of derivative or
127 | collective works based on the Program.
128 |
129 | In addition, mere aggregation of another work not based on the Program
130 | with the Program (or with a work based on the Program) on a volume of
131 | a storage or distribution medium does not bring the other work under
132 | the scope of this License.
133 |
134 | 3. You may copy and distribute the Program (or a work based on it,
135 | under Section 2) in object code or executable form under the terms of
136 | Sections 1 and 2 above provided that you also do one of the following:
137 |
138 | a) Accompany it with the complete corresponding machine-readable
139 | source code, which must be distributed under the terms of Sections
140 | 1 and 2 above on a medium customarily used for software interchange; or,
141 |
142 | b) Accompany it with a written offer, valid for at least three
143 | years, to give any third party, for a charge no more than your
144 | cost of physically performing source distribution, a complete
145 | machine-readable copy of the corresponding source code, to be
146 | distributed under the terms of Sections 1 and 2 above on a medium
147 | customarily used for software interchange; or,
148 |
149 | c) Accompany it with the information you received as to the offer
150 | to distribute corresponding source code. (This alternative is
151 | allowed only for noncommercial distribution and only if you
152 | received the program in object code or executable form with such
153 | an offer, in accord with Subsection b above.)
154 |
155 | The source code for a work means the preferred form of the work for
156 | making modifications to it. For an executable work, complete source
157 | code means all the source code for all modules it contains, plus any
158 | associated interface definition files, plus the scripts used to
159 | control compilation and installation of the executable. However, as a
160 | special exception, the source code distributed need not include
161 | anything that is normally distributed (in either source or binary
162 | form) with the major components (compiler, kernel, and so on) of the
163 | operating system on which the executable runs, unless that component
164 | itself accompanies the executable.
165 |
166 | If distribution of executable or object code is made by offering
167 | access to copy from a designated place, then offering equivalent
168 | access to copy the source code from the same place counts as
169 | distribution of the source code, even though third parties are not
170 | compelled to copy the source along with the object code.
171 |
172 | 4. You may not copy, modify, sublicense, or distribute the Program
173 | except as expressly provided under this License. Any attempt
174 | otherwise to copy, modify, sublicense or distribute the Program is
175 | void, and will automatically terminate your rights under this License.
176 | However, parties who have received copies, or rights, from you under
177 | this License will not have their licenses terminated so long as such
178 | parties remain in full compliance.
179 |
180 | 5. You are not required to accept this License, since you have not
181 | signed it. However, nothing else grants you permission to modify or
182 | distribute the Program or its derivative works. These actions are
183 | prohibited by law if you do not accept this License. Therefore, by
184 | modifying or distributing the Program (or any work based on the
185 | Program), you indicate your acceptance of this License to do so, and
186 | all its terms and conditions for copying, distributing or modifying
187 | the Program or works based on it.
188 |
189 | 6. Each time you redistribute the Program (or any work based on the
190 | Program), the recipient automatically receives a license from the
191 | original licensor to copy, distribute or modify the Program subject to
192 | these terms and conditions. You may not impose any further
193 | restrictions on the recipients' exercise of the rights granted herein.
194 | You are not responsible for enforcing compliance by third parties to
195 | this License.
196 |
197 | 7. If, as a consequence of a court judgment or allegation of patent
198 | infringement or for any other reason (not limited to patent issues),
199 | conditions are imposed on you (whether by court order, agreement or
200 | otherwise) that contradict the conditions of this License, they do not
201 | excuse you from the conditions of this License. If you cannot
202 | distribute so as to satisfy simultaneously your obligations under this
203 | License and any other pertinent obligations, then as a consequence you
204 | may not distribute the Program at all. For example, if a patent
205 | license would not permit royalty-free redistribution of the Program by
206 | all those who receive copies directly or indirectly through you, then
207 | the only way you could satisfy both it and this License would be to
208 | refrain entirely from distribution of the Program.
209 |
210 | If any portion of this section is held invalid or unenforceable under
211 | any particular circumstance, the balance of the section is intended to
212 | apply and the section as a whole is intended to apply in other
213 | circumstances.
214 |
215 | It is not the purpose of this section to induce you to infringe any
216 | patents or other property right claims or to contest validity of any
217 | such claims; this section has the sole purpose of protecting the
218 | integrity of the free software distribution system, which is
219 | implemented by public license practices. Many people have made
220 | generous contributions to the wide range of software distributed
221 | through that system in reliance on consistent application of that
222 | system; it is up to the author/donor to decide if he or she is willing
223 | to distribute software through any other system and a licensee cannot
224 | impose that choice.
225 |
226 | This section is intended to make thoroughly clear what is believed to
227 | be a consequence of the rest of this License.
228 |
229 | 8. If the distribution and/or use of the Program is restricted in
230 | certain countries either by patents or by copyrighted interfaces, the
231 | original copyright holder who places the Program under this License
232 | may add an explicit geographical distribution limitation excluding
233 | those countries, so that distribution is permitted only in or among
234 | countries not thus excluded. In such case, this License incorporates
235 | the limitation as if written in the body of this License.
236 |
237 | 9. The Free Software Foundation may publish revised and/or new versions
238 | of the General Public License from time to time. Such new versions will
239 | be similar in spirit to the present version, but may differ in detail to
240 | address new problems or concerns.
241 |
242 | Each version is given a distinguishing version number. If the Program
243 | specifies a version number of this License which applies to it and "any
244 | later version", you have the option of following the terms and conditions
245 | either of that version or of any later version published by the Free
246 | Software Foundation. If the Program does not specify a version number of
247 | this License, you may choose any version ever published by the Free Software
248 | Foundation.
249 |
250 | 10. If you wish to incorporate parts of the Program into other free
251 | programs whose distribution conditions are different, write to the author
252 | to ask for permission. For software which is copyrighted by the Free
253 | Software Foundation, write to the Free Software Foundation; we sometimes
254 | make exceptions for this. Our decision will be guided by the two goals
255 | of preserving the free status of all derivatives of our free software and
256 | of promoting the sharing and reuse of software generally.
257 |
258 | NO WARRANTY
259 |
260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
268 | REPAIR OR CORRECTION.
269 |
270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
278 | POSSIBILITY OF SUCH DAMAGES.
279 |
280 | END OF TERMS AND CONDITIONS
281 |
282 | How to Apply These Terms to Your New Programs
283 |
284 | If you develop a new program, and you want it to be of the greatest
285 | possible use to the public, the best way to achieve this is to make it
286 | free software which everyone can redistribute and change under these terms.
287 |
288 | To do so, attach the following notices to the program. It is safest
289 | to attach them to the start of each source file to most effectively
290 | convey the exclusion of warranty; and each file should have at least
291 | the "copyright" line and a pointer to where the full notice is found.
292 |
293 | {description}
294 | Copyright (C) {year} {fullname}
295 |
296 | This program is free software; you can redistribute it and/or modify
297 | it under the terms of the GNU General Public License as published by
298 | the Free Software Foundation; either version 2 of the License, or
299 | (at your option) any later version.
300 |
301 | This program is distributed in the hope that it will be useful,
302 | but WITHOUT ANY WARRANTY; without even the implied warranty of
303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
304 | GNU General Public License for more details.
305 |
306 | You should have received a copy of the GNU General Public License along
307 | with this program; if not, write to the Free Software Foundation, Inc.,
308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
309 |
310 | Also add information on how to contact you by electronic and paper mail.
311 |
312 | If the program is interactive, make it output a short notice like this
313 | when it starts in an interactive mode:
314 |
315 | Gnomovision version 69, Copyright (C) year name of author
316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
317 | This is free software, and you are welcome to redistribute it
318 | under certain conditions; type `show c' for details.
319 |
320 | The hypothetical commands `show w' and `show c' should show the appropriate
321 | parts of the General Public License. Of course, the commands you use may
322 | be called something other than `show w' and `show c'; they could even be
323 | mouse-clicks or menu items--whatever suits your program.
324 |
325 | You should also get your employer (if you work as a programmer) or your
326 | school, if any, to sign a "copyright disclaimer" for the program, if
327 | necessary. Here is a sample; alter the names:
328 |
329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program
330 | `Gnomovision' (which makes passes at compilers) written by James Hacker.
331 |
332 | {signature of Ty Coon}, 1 April 1989
333 | Ty Coon, President of Vice
334 |
335 | This General Public License does not permit incorporating your program into
336 | proprietary programs. If your program is a subroutine library, you may
337 | consider it more useful to permit linking proprietary applications with the
338 | library. If this is what you want to do, use the GNU Lesser General
339 | Public License instead of this License.
340 |
--------------------------------------------------------------------------------
/smb-logger.c:
--------------------------------------------------------------------------------
1 | /******************************************************************************
2 | SMB LOGGER
3 |
4 | A quick and dirty honetpot to catch incoming connections to
5 | Microsoft NetBIOS/SMB, such as the WannaCry botnet
6 |
7 |
8 | Tips for reading the code:
9 | - it runs on Windows, Linux, and Mac OS
10 | - it's IPv6 and IPv4 enabled
11 |
12 | ******************************************************************************/
13 | #define _CRT_SECURE_NO_WARNINGS 1
14 | #if defined(WIN32)
15 | #include
16 | #include
17 | #include
18 | #include
19 | #define sleep(secs) Sleep(1000*(secs))
20 | #define WSA(err) (WSA##err)
21 | typedef CRITICAL_SECTION pthread_mutex_t;
22 | #define pthread_mutex_lock(p) EnterCriticalSection(p)
23 | #define pthread_mutex_unlock(p) LeaveCriticalSection(p)
24 | #define pthread_mutex_init(p,q) InitializeCriticalSection(p)
25 | #define pthread_create(handle,x,pfn,data) (*(handle)) = _beginthread(pfn,0,data)
26 | typedef uintptr_t pthread_t;
27 | #define snprintf _snprintf
28 | #else
29 | #include
30 | #include
31 | #include
32 | #include
33 | #include
34 | #include
35 | #include
36 | #include
37 | #include
38 | #define WSAGetLastError() (errno)
39 | #define closesocket(fd) close(fd)
40 | #define WSA(err) (err)
41 | #endif
42 | #if defined(_MSC_VER)
43 | #pragma comment(lib, "ws2_32")
44 | #endif
45 |
46 | #include
47 | #include
48 | #include
49 | #include
50 | #include
51 |
52 | /******************************************************************************
53 | * A mutex so multiple threads printing output don't conflict with
54 | * each other
55 | ******************************************************************************/
56 | pthread_mutex_t output;
57 |
58 |
59 | /******************************************************************************
60 | * Arguments pass to each thread. Creating a thread only allows passing in
61 | * a single pointer, so we have to put everything we want passed to the
62 | * thread in a structure like this.
63 | ******************************************************************************/
64 | struct ThreadArgs {
65 | pthread_t handle;
66 | int fd;
67 | FILE *fp_passwords;
68 | FILE *fp_ips;
69 | FILE *fp_csv;
70 | struct sockaddr_in6 peer;
71 | socklen_t peerlen;
72 | char peername[256];
73 | };
74 |
75 |
76 | /******************************************************************************
77 | * Translate sockets error codes to helpful text for printing
78 | ******************************************************************************/
79 | static const char *
80 | error_msg(unsigned err)
81 | {
82 | static char buf[256];
83 | switch (err) {
84 | case WSA(ECONNRESET): return "TCP connection reset";
85 | case WSA(ECONNREFUSED): return "Connection refused";
86 | case WSA(ETIMEDOUT): return "Timed out";
87 | case WSA(ECONNABORTED): return "Connection aborted";
88 | case WSA(EACCES): return "Access denied";
89 | case WSA(EADDRINUSE): return "Port already in use";
90 | case 11: return "Timed out";
91 | case 0: return "TCP connection closed";
92 | default:
93 | snprintf(buf, sizeof(buf), "err#%u", err);
94 | return buf;
95 | }
96 | }
97 |
98 | /******************************************************************************
99 | * Print to stderr. Right now, it's just a wrapper aroun fprintf(stderr), but
100 | * I do it this way so I can later add different DEBUG levels.
101 | ******************************************************************************/
102 | int ERROR_MSG(const char *fmt, ...)
103 | {
104 | va_list marker;
105 | va_start(marker, fmt);
106 | vfprintf(stderr, fmt, marker);
107 | va_end(marker);
108 | return -1;
109 | }
110 |
111 | /******************************************************************************
112 | * On modern systems (Win7+, macOS, Linux, etc.), an "anyipv6" socket always
113 | * is backwards compatible with IPv4. So we create an IPv6 socket to handle
114 | * both versions simultaneously. This will inevitably fail on some system,
115 | * so eventually I'll have to write an IPv4 version of this function.
116 | ******************************************************************************/
117 | int
118 | create_ipv6_socket(int port)
119 | {
120 | int fd;
121 | int err;
122 | struct sockaddr_in6 localaddr;
123 |
124 | /* Create a generic socket. IPv6 includes IPv4 */
125 | fd = socket(AF_INET6, SOCK_STREAM, IPPROTO_TCP);
126 | if (fd <= 0) {
127 | ERROR_MSG("socket(AF_INET6): could not create socket: %s\n",
128 | error_msg(WSAGetLastError()));
129 | return -1;
130 | }
131 |
132 | /* Make it a dual stack IPv4/IPv6 socket. This step is unnecessary on
133 | * some operating systems/versions, but necessary on some others */
134 | {
135 | int no = 0;
136 | err = setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&no, sizeof(no));
137 | if (err != 0) {
138 | ERROR_MSG("setsockopt(!IPV6_V6ONLY): %s\n",
139 | error_msg(WSAGetLastError()));
140 | closesocket(fd);
141 | return -1;
142 | }
143 | }
144 |
145 | #ifndef WIN32
146 | /* Reuse address */
147 | {
148 | int yes = 1;
149 | err = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char*)&yes, sizeof(yes));
150 | if (err != 0) {
151 | ERROR_MSG("setsockopt(SO_REUSEADDR): %s\n",
152 | error_msg(WSAGetLastError()));
153 | closesocket(fd);
154 | return -1;
155 | }
156 | }
157 | #endif
158 |
159 | /* Bind to local port. Again note that while I"m binding for IPv6, it's
160 | * also setting up a service for IPv4. */
161 | memset(&localaddr, 0, sizeof(localaddr));
162 | localaddr.sin6_family = AF_INET6;
163 | localaddr.sin6_port = htons(port);
164 | localaddr.sin6_addr = in6addr_any;
165 | err = bind(fd, (struct sockaddr*)&localaddr, sizeof(localaddr));
166 | if (err < 0) {
167 | ERROR_MSG("bind(%u): %s\n", port,
168 | error_msg(WSAGetLastError()));
169 | closesocket(fd);
170 | return -1;
171 | }
172 |
173 | /* Now the final initializaiton step */
174 | err = listen(fd, 10);
175 | if (err < 0) {
176 | ERROR_MSG("listen(%u): %s\n", port,
177 | error_msg(WSAGetLastError()));
178 | closesocket(fd);
179 | return -1;
180 | }
181 |
182 | return fd;
183 | }
184 |
185 |
186 | /******************************************************************************
187 | * Blacklist some bad characters to avoid the most obvious attempts of
188 | * entering bad passwords designed to hack the system (shell injection,
189 | * HTML injection, SQL injection).
190 | ******************************************************************************/
191 | void
192 | print_string(FILE *fp, const char *str, int len)
193 | {
194 | int i;
195 | for (i = 0; i < len; i++) {
196 | char c = str[i];
197 | if (!isprint(c & 0xFF) || c == '\\' || c == '<' || c == '\'' || c == ' ' || c == '\"' || c == ',')
198 | fprintf(fp, "\\x%02x", c & 0xFF);
199 | else
200 | fprintf(fp, "%c", c);
201 | }
202 | }
203 |
204 | /******************************************************************************
205 | * Compares two strings, one nul-terminated, the other length encoded
206 | ******************************************************************************/
207 | int
208 | matches(const char *rhs, const char *lhs, int len)
209 | {
210 | if (strlen(rhs) == len && memcmp(rhs, lhs, len) == 0)
211 | return 1;
212 | else
213 | return 0;
214 | }
215 |
216 | /******************************************************************************
217 | * Print the results.
218 | ******************************************************************************/
219 | void
220 | print_passwords(FILE *fp, const char *login, int login_len, const char *password, int password_len)
221 | {
222 | if (fp == NULL)
223 | return;
224 |
225 | if (matches("shell", login, login_len) && matches("sh", password, password_len))
226 | return;
227 | if (matches("enable", login, login_len) && matches("system", password, password_len))
228 | return;
229 |
230 | /* pretty print the two fields */
231 | pthread_mutex_lock(&output);
232 | print_string(fp, login, login_len);
233 | fprintf(fp, " ");
234 | print_string(fp, password, password_len);
235 | fprintf(fp, "\n");
236 | fflush(fp);
237 | pthread_mutex_unlock(&output);
238 | }
239 |
240 | /******************************************************************************
241 | * Print which machines are connecting
242 | ******************************************************************************/
243 | void
244 | print_ip(FILE *fp, const char *hostname)
245 | {
246 | if (fp == NULL)
247 | return;
248 |
249 | pthread_mutex_lock(&output);
250 | fprintf(fp, "%s\n", hostname);
251 | fflush(fp);
252 | pthread_mutex_unlock(&output);
253 | }
254 |
255 |
256 | /******************************************************************************
257 | * Create a CSV formatted line with all the information on one line.
258 | ******************************************************************************/
259 | void
260 | print_csv(FILE *fp, time_t now, const char *hostname,
261 | const char *login, int login_len,
262 | const char *password, int password_len)
263 | {
264 | struct tm *tm;
265 | char str[128];
266 |
267 | if (fp == NULL)
268 | return;
269 |
270 | tm = gmtime(&now);
271 | if (tm == NULL) {
272 | perror("gmtime");
273 | return;
274 | }
275 |
276 | strftime(str, sizeof(str), "%Y-%m-%d %H:%M:%S", tm);
277 |
278 | pthread_mutex_lock(&output);
279 |
280 | /* time-integer, time-formatted, username, password*/
281 | fprintf(fp, "%u,%s,%s,",
282 | (unsigned)now,
283 | str,
284 | hostname);
285 | print_string(fp, login, login_len);
286 | fprintf(fp, ",");
287 | print_string(fp, password, password_len);
288 | fprintf(fp, "\n");
289 |
290 | fflush(fp);
291 | pthread_mutex_unlock(&output);
292 | }
293 |
294 |
295 | /******************************************************************************
296 | * Receive a NetBIOS datagram from across the TCP connection
297 | ******************************************************************************/
298 | int
299 | recv_netbios(int fd, unsigned char *buf, int sizeof_buf, int flags, int *type)
300 | {
301 | int done = 0;
302 | unsigned char c;
303 | int len;
304 | int netbios_len;
305 | int i;
306 | int offset = 0;
307 |
308 | /* receive the type field */
309 | len = recv(fd, (char*)&c, 1, flags);
310 | if (len <= 0) {
311 | ERROR_MSG("recv(1): %s\n",
312 | error_msg(WSAGetLastError()));
313 | return -1;
314 | }
315 | *type = c;
316 |
317 | /* reeive the length field */
318 | netbios_len = 0;
319 | for (i=0; i<3; i++) {
320 | len = recv(fd, (char*)&c, 1, flags);
321 | if (len <= 0)
322 | return -1;
323 | netbios_len <<= 8;
324 | netbios_len |= c;
325 | }
326 | if ((netbios_len >> 17) != 0) {
327 | fprintf(stderr, "bad netbios length: should never happen\n");
328 | return -1;
329 | }
330 | if (netbios_len > sizeof_buf) {
331 | fprintf(stderr, "netbios buffer overflow\n");
332 | return -1;
333 | }
334 |
335 | /* Now receive the NetBIOS payload */
336 | while (offset < netbios_len) {
337 | len = recv(fd, buf+offset, netbios_len - offset, flags);
338 | if (len <= 0)
339 | return -1;
340 | offset += len;
341 | }
342 |
343 | return netbios_len;
344 | }
345 |
346 | /******************************************************************************
347 | ******************************************************************************/
348 | void handle_smbv2_request(const unsigned char *buf, size_t buf_size, const char *peername)
349 | {
350 | }
351 |
352 | /******************************************************************************
353 | ******************************************************************************/
354 | void handle_smb_request(const unsigned char *buf, size_t buf_size, const char *peername)
355 | {
356 | size_t offset = 0;
357 |
358 | struct SMBv1_header {
359 | unsigned command;
360 | unsigned flags;
361 | unsigned flags2;
362 | unsigned char security_features[8];
363 | unsigned pid;
364 | unsigned tid;
365 | unsigned uid;
366 | unsigned mid;
367 |
368 | unsigned word_count;
369 | unsigned byte_count;
370 | } smb;
371 |
372 | /* ProtocolID
373 | * \xff SMB - SMBv1
374 | * \xfe SMB - SMBv2 or SMBv3
375 | */
376 | if (offset + 4 >= buf_size) {
377 | fprintf(stderr, "%s: truncated packet\n", peername);
378 | return;
379 | }
380 | if (memcmp(buf, "\xFE" "SMB", 4) == 0)
381 | handle_smbv2_request(buf, buf_size, peername);
382 | if (memcmp(buf, "\xFF" "SMB", 4) != 0) {
383 | fprintf(stderr, "%s: unknown SMB version\n", peername);
384 | return;
385 | }
386 |
387 | if (buf_size < 32) {
388 | fprintf(stderr, "%s: SMBv1 truncated, length=%u\n", peername, (unsigned)buf_size);
389 | return;
390 | }
391 |
392 | smb.command = buf[4];
393 | smb.status = buf[5] | buf[6]<<8 | buf[7]<<16 | buf[8]<<24;
394 | smb.flags = buf[9];
395 | smb.flags2 = buf[10] | buf[11]<<8;
396 | smb.pid = buf[12]<<16 | buf[13]<<24;
397 | memcpy(smb.security_features, buf+14, 8);
398 | smb.tid = buf[24] | buf[25]<<8;
399 | smb.pid |= buf[26] | buf[27]<<8;
400 | smb.uid = buf[28] | buf[29]<<8;
401 | smb.mid = buf[30] | buf[31]<<8;
402 |
403 | if (buf_size >= 32 + 3) {
404 | smb.word_count = buf[32];
405 | smb.byte_count = buf[33] | buf[34]<<8;
406 | offset = 35;
407 | } else {
408 | smb.word_count = 0;
409 | smb.byte_count = 0;
410 | offset = 32;
411 | }
412 |
413 | switch (smb.command) {
414 | case 0x72: /* Negotiate protocol */
415 | handle_negotiate_protocol(&smb, buf, offset, buf_size, peername);
416 | break;
417 | default:
418 | fprintf(stderr, "%s: command=0x%02x len=%u\n", peername, smb.command, buf_size-offset);
419 | }
420 |
421 | }
422 |
423 |
424 | /******************************************************************************
425 | ******************************************************************************/
426 | void
427 | str_append(char *str, size_t *offset, size_t sizeof_str, char c)
428 | {
429 | if (*offset + 1 < sizeof_str) {
430 | str[(*offset)++] = c;
431 | str[(*offset)] = '\0';
432 | }
433 | }
434 |
435 | void
436 | str_append_str(char *str, size_t *offset, size_t sizeof_str, const char *rhs, size_t rhs_len)
437 | {
438 | size_t i;
439 |
440 | for (i=0; i= 2) {
474 | unsigned char c;
475 |
476 | c = buf[offset++];
477 | if (c < 'A' || ('A' + 16) < c)
478 | c = 'A';
479 | letter = (c - 'A');
480 |
481 | c = buf[offset++];
482 | if (c < 'A' || ('A' + 16) < c)
483 | c = 'A';
484 | letter <<= 4;
485 | letter |= (c - 'A');
486 |
487 | if (isalnum(letter) || ispunct(letter)) {
488 | str_append(str, &str_offset, sizeof(str), letter);
489 | } else if (letter == ' ' && name_len > 2) {
490 | str_append(str, &str_offset, sizeof(str), letter);
491 | } else {
492 | str_append(str, &str_offset, sizeof(str), '<');
493 | str_append(str, &str_offset, sizeof(str), "01234567890ABCDEF"[letter>>4]);
494 | str_append(str, &str_offset, sizeof(str), "01234567890ABCDEF"[letter&0xF]);
495 | str_append(str, &str_offset, sizeof(str), '>');
496 | }
497 | name_len -= 2;
498 | }
499 | }
500 |
501 | /* Called name suffix */
502 | while (offset < buf_size) {
503 | size_t name_len = buf[offset++];
504 | unsigned letter = 0;
505 |
506 | if (name_len == 0)
507 | break;
508 |
509 | str_append(str, &str_offset, sizeof(str), '.');
510 |
511 | while (offset + 1 < buf_size && name_len >= 1) {
512 | unsigned char letter;
513 |
514 | letter = buf[offset++];
515 |
516 | if (isalnum(letter) || ispunct(letter)) {
517 | str_append(str, &str_offset, sizeof(str), letter);
518 | } else {
519 | str_append(str, &str_offset, sizeof(str), '<');
520 | str_append(str, &str_offset, sizeof(str), "01234567890ABCDEF"[letter>>4]);
521 | str_append(str, &str_offset, sizeof(str), "01234567890ABCDEF"[letter&0xF]);
522 | str_append(str, &str_offset, sizeof(str), '>');
523 | }
524 | name_len += 1;
525 | }
526 | }
527 |
528 | /* caller */
529 | str_append_str(str, &str_offset, sizeof(str), "\" caller=\"", strlen("\" caller=\""));
530 | if (offset < buf_size) {
531 | size_t name_len = buf[offset++];
532 | unsigned letter = 0;
533 |
534 | while (offset + 1 < buf_size && name_len >= 2) {
535 | unsigned char c;
536 |
537 | c = buf[offset++];
538 | if (c < 'A' || ('A' + 16) < c)
539 | c = 'A';
540 | letter = (c - 'A');
541 |
542 | c = buf[offset++];
543 | if (c < 'A' || ('A' + 16) < c)
544 | c = 'A';
545 | letter <<= 4;
546 | letter |= (c - 'A');
547 |
548 | if (isalnum(letter) || ispunct(letter)) {
549 | str_append(str, &str_offset, sizeof(str), letter);
550 | } else if (letter == ' ' && name_len > 2) {
551 | str_append(str, &str_offset, sizeof(str), letter);
552 | } else {
553 | str_append(str, &str_offset, sizeof(str), '<');
554 | str_append(str, &str_offset, sizeof(str), "01234567890ABCDEF"[letter>>4]);
555 | str_append(str, &str_offset, sizeof(str), "01234567890ABCDEF"[letter&0xF]);
556 | str_append(str, &str_offset, sizeof(str), '>');
557 | }
558 | name_len -= 2;
559 | }
560 | }
561 |
562 | /* Called name suffix */
563 | while (offset < buf_size) {
564 | size_t name_len = buf[offset++];
565 | unsigned letter = 0;
566 |
567 | if (name_len == 0)
568 | break;
569 |
570 | str_append(str, &str_offset, sizeof(str), '.');
571 |
572 | while (offset + 1 < buf_size && name_len >= 1) {
573 | unsigned char letter;
574 |
575 | letter = buf[offset++];
576 |
577 | if (isalnum(letter) || ispunct(letter)) {
578 | str_append(str, &str_offset, sizeof(str), letter);
579 | } else {
580 | str_append(str, &str_offset, sizeof(str), '<');
581 | str_append(str, &str_offset, sizeof(str), "01234567890ABCDEF"[letter>>4]);
582 | str_append(str, &str_offset, sizeof(str), "01234567890ABCDEF"[letter&0xF]);
583 | str_append(str, &str_offset, sizeof(str), '>');
584 | }
585 | name_len += 1;
586 | }
587 | }
588 | str_append_str(str, &str_offset, sizeof(str), "\" ", strlen("\" "));
589 |
590 | printf("%s\n", str);
591 | }
592 |
593 | /******************************************************************************
594 | * This is a thread created whenever a connection is accepted, which is then
595 | * responsible for handling the connection with blocking calls, and eventually
596 | * cleanup when the connection ends. We set a recv timeout so that the
597 | * connection won't stay alive indefinitely.
598 | ******************************************************************************/
599 | void *handle_connection(void *v_args)
600 | {
601 | struct ThreadArgs *args = (struct ThreadArgs *)v_args;
602 | int fd = args->fd;
603 | int netbios_length;
604 | int netbios_type;
605 | int flags = 0;
606 | const size_t buf_size = 128 * 1024 * 1024;
607 | unsigned char *buf;
608 |
609 | buf = malloc(buf_size);
610 | if (buf == 0) {
611 | fprintf(stderr, "out of memory, exiting\n");
612 | exit(1);
613 | }
614 |
615 | #ifdef MSG_NOSIGNAL
616 | flags |= MSG_NOSIGNAL;
617 | #endif
618 |
619 |
620 | /* Set receive timeout of 1 minute. Windows can go suck an egg by deciding
621 | * to be different here. */
622 | #ifdef WIN32
623 | {
624 | DWORD tv;
625 | int err;
626 |
627 | tv = 60000;
628 |
629 | err = setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, (char*)&tv, sizeof(tv));
630 | if (err) {
631 | ERROR_MSG("setsockopt(SO_RECVTIMEO): %s\n",
632 | error_msg(WSAGetLastError()));
633 | }
634 | }
635 | #else
636 | {
637 | struct timeval tv;
638 | int err;
639 |
640 | tv.tv_sec = 60;
641 | tv.tv_usec = 0;
642 |
643 | err = setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, (char*)&tv, sizeof(tv));
644 | if (err) {
645 | ERROR_MSG("setsockopt(SO_RECVTIMEO): %s\n",
646 | error_msg(WSAGetLastError()));
647 | }
648 | }
649 | #endif
650 |
651 |
652 | again:
653 |
654 | /* Get NetBIOS packet */
655 | netbios_type = 0;
656 | netbios_length = recv_netbios(fd, buf, buf_size, flags, &netbios_type);
657 | if (netbios_length <= 0)
658 | goto error;
659 |
660 | /* do different processing depending on type */
661 | switch (netbios_type) {
662 | case 0x00: /* message */
663 | handle_smb_request(buf, buf_size, args->peername);
664 | break;
665 | case 0x81: /* session request */
666 | handle_session_request(buf, buf_size, args->peername);
667 | send(fd, "\x82\x00\x00\x00", 4, flags);
668 | break;
669 | case 0x85:
670 | default:
671 | break;
672 | }
673 |
674 | goto again;
675 |
676 |
677 | end:
678 | closesocket(fd);
679 | ERROR_MSG("[-] %s: close()\n", args->peername);
680 | free(args);
681 | free(buf);
682 | return NULL;
683 | error:
684 | ERROR_MSG("[-] %s: recv(): %s\n", args->peername,
685 | error_msg(WSAGetLastError()));
686 | goto end;
687 | }
688 |
689 |
690 | /******************************************************************************
691 | ******************************************************************************/
692 | void
693 | daemon_thread(int port, FILE *fp_passwords, FILE *fp_ips, FILE *fp_csv)
694 | {
695 |
696 | int fd;
697 |
698 | fd = create_ipv6_socket(port);
699 | if (fd <= 0)
700 | return;
701 |
702 | for (;;) {
703 | int newfd;
704 | struct ThreadArgs *args;
705 |
706 | /* accept a new connection */
707 | newfd = accept(fd, 0, 0);
708 | if (newfd <= 0) {
709 | ERROR_MSG("accept(%u): %s\n", port,
710 | error_msg(WSAGetLastError()));
711 | break;
712 | }
713 |
714 | /* Create new structure to hold per-thread-dat */
715 | args = malloc(sizeof(*args));
716 | memset(args, 0, sizeof(*args));
717 | args->fd = newfd;
718 | args->fp_passwords = fp_passwords;
719 | args->fp_ips = fp_ips;
720 | args->fp_csv = fp_csv;
721 | args->peerlen = sizeof(args->peer);
722 | getpeername(args->fd, (struct sockaddr*)&args->peer, &args->peerlen);
723 | getnameinfo((struct sockaddr*)&args->peer, args->peerlen, args->peername, sizeof(args->peername), NULL, 0, NI_NUMERICHOST| NI_NUMERICSERV);
724 | if (memcmp(args->peername, "::ffff:", 7) == 0)
725 | memmove(args->peername, args->peername + 7, strlen(args->peername + 7) + 1);
726 | fprintf(stderr, "[+] %s: connect\n", args->peername);
727 |
728 | pthread_create(&args->handle, 0, handle_connection, args);
729 |
730 | #ifndef WIN32
731 | /* clean up the thread handle, otherwise we have a small memory
732 | * leak of handles. Thanks to Stefan Laudemann for pointing
733 | * this out. I suspect it's more than just 8 bytes for the handle,
734 | * but that there are kernel resources that we'll run out of
735 | * too. */
736 | pthread_detach(args->handle);
737 | #endif
738 | }
739 |
740 | closesocket(fd);
741 | }
742 |
743 | /******************************************************************************
744 | ******************************************************************************/
745 | FILE *
746 | open_output(int *in_i, char *argv[], int argc)
747 | {
748 | int i = *in_i;
749 | const char *filename = NULL;
750 |
751 | /* Allow either with/without space:
752 | * -cfilename.txt
753 | * or
754 | * -c filename.txt
755 | */
756 | if (argv[i][2] == '\0') {
757 | i = ++(*in_i);
758 | if (i >= argc) {
759 | fprintf(stderr, "expected parameter after -%c\n", argv[i][1]);
760 | exit(1);
761 | }
762 | filename = argv[i];
763 | }
764 | else
765 | filename = argv[i] + 2;
766 |
767 | /* If the filename is a dash, then redirect to console output*/
768 | if (strcmp(filename, "-") == 0)
769 | return stdout;
770 |
771 | /* If the filename is "NULL", then don't output anything */
772 | else if (strcmp(filename, "null") == 0)
773 | return NULL;
774 |
775 | /* Create a file to output to*/
776 | else {
777 | FILE *fp;
778 | fp = fopen(filename, "wt");
779 | if (fp == NULL) {
780 | perror(filename);
781 | exit(1);
782 | return NULL;
783 | }
784 | else
785 | return fp;
786 | }
787 | }
788 |
789 | /******************************************************************************
790 | ******************************************************************************/
791 | int
792 | main(int argc, char *argv[])
793 | {
794 | FILE *fp_passwords = stdout;
795 | FILE *fp_ips = stdout;
796 | FILE *fp_csv = NULL;
797 | int i;
798 | int port = 23;
799 |
800 | /*
801 | * One-time program startup stuff for legacy Windows.
802 | */
803 | #if defined(WIN32)
804 | {WSADATA x; WSAStartup(0x101, &x);}
805 | #endif
806 |
807 | pthread_mutex_init(&output, 0);
808 |
809 | fprintf(stderr, "\n--- smb-logger/0.1 ---\n");
810 | fprintf(stderr, "https://github.com/robertdavidgraham/smb-logger\n");
811 |
812 | /* Read configuration parameters */
813 | for (i = 1; i < argc; i++) {
814 | if (argv[i][0] != '-') {
815 | fprintf(stderr, "unknown parameter: %s\n", argv[i]);
816 | exit(1);
817 | }
818 | switch (argv[i][1]) {
819 | case 'p': /* port number to listen on */
820 | {
821 | char *arg;
822 | if (isdigit(argv[i][2])) {
823 | arg = &argv[i][2];
824 | } else {
825 | if (++i >= argc) {
826 | fprintf(stderr, "expected parameter after -%c\n", 'i');
827 | exit(1);
828 | }
829 | arg = argv[i];
830 | }
831 | if (strtoul(arg, 0, 0) < 1 || strtoul(arg, 0, 0) > 65535) {
832 | fprintf(stderr, "expected port number between 1..65535\n");
833 | exit(1);
834 | }
835 | port = strtoul(arg, 0, 0);
836 | }
837 | break;
838 | case 'h':
839 | case '?':
840 | case 'H':
841 | fprintf(stderr, "usage:\n smb-logger [-p listen-port]\n");
842 | exit(1);
843 | break;
844 | }
845 | }
846 |
847 | daemon_thread(port, fp_passwords, fp_ips, fp_csv);
848 |
849 | return 0;
850 | }
851 |
852 |
--------------------------------------------------------------------------------