3 Copyright (C) 2004-2007 Chris Porter.
10 #include <sys/types.h>
11 #include <sys/socket.h>
14 #include <sys/ioctl.h>
18 #include <netinet/in.h>
19 #include <arpa/inet.h>
21 #include "../lib/sstring.h"
22 #include "../lib/irc_string.h"
23 #include "../core/config.h"
24 #include "../core/events.h"
25 #include "../lib/version.h"
26 #include "../core/schedule.h"
28 #include "nterfacer.h"
31 MODULE_VERSION("1.1p" PROTOCOL_VERSION
);
33 struct service_node
*tree
= NULL
;
34 struct esocket_events nterfacer_events
;
35 struct esocket
*nterfacer_sock
;
36 struct rline
*rlines
= NULL
;
37 unsigned short nterfacer_token
= BLANK_TOKEN
;
38 struct nterface_auto_log
*nrl
;
40 struct service_node
*ping
= NULL
;
42 struct permitted
*permits
;
45 int ping_handler(struct rline
*ri
, int argc
, char **argv
);
46 static void nterfacer_sendcallback(struct rline
*ri
, int error
, char *buf
);
50 int debug_mode
= getcopyconfigitemintpositive("nterfacer", "debug", 0);
52 nrl
= nterface_open_log("nterfacer", "logs/nterfacer.log", debug_mode
);
54 loaded
= load_permits();
55 nterface_log(nrl
, NL_INFO
, "Loaded %d permit%s successfully.", loaded
, loaded
==1?"":"s");
60 nterfacer_events
.on_accept
= nterfacer_accept_event
;
61 nterfacer_events
.on_line
= nterfacer_line_event
;
62 nterfacer_events
.on_disconnect
= NULL
;
64 nterfacer_token
= esocket_token();
66 ping
= register_service("nterfacer");
70 register_handler(ping
, "ping", 0, ping_handler
);
73 accept_fd
= setup_listening_socket();
75 nterface_log(nrl
, NL_ERROR
, "Unable to setup listening socket!");
77 nterfacer_sock
= esocket_add(accept_fd
, ESOCKET_UNIX_DOMAIN
, &nterfacer_events
, nterfacer_token
);
80 /* the main unix domain socket must NOT have a disconnect event. */
81 nterfacer_events
.on_disconnect
= nterfacer_disconnect_event
;
84 void free_handler(struct handler
*hp
) {
85 struct rline
*li
, *pi
= NULL
;
88 if(li
->handler
== hp
) {
90 esocket_write_line(li
->socket
, "%d,OE%d,%s", li
->id
, BF_UNLOADED
, "Service was unloaded.");
91 } else if(li
->callback
) {
92 nterfacer_sendcallback(li
, BF_UNLOADED
, "Service was unloaded.");
108 freesstring(hp
->command
);
112 void free_handlers(struct service_node
*tp
) {
113 struct handler
*hp
, *lp
;
115 for(hp
=tp
->handlers
;hp
;) {
125 struct service_node
*tp
, *lp
;
129 deregister_service(ping
);
139 if((accept_fd
!= -1) && nterfacer_sock
) {
140 esocket_clean_by_token(nterfacer_token
);
141 nterfacer_sock
= NULL
;
145 if(permits
&& permit_count
) {
146 for(i
=0;i
<permit_count
;i
++) {
147 freesstring(permits
[i
].hostname
);
148 freesstring(permits
[i
].password
);
155 nrl
= nterface_close_log(nrl
);
156 nscheckfreeall(POOL_NTERFACER
);
159 int load_permits(void) {
160 int loaded_lines
= 0, i
, j
;
161 struct permitted
*new_permits
, *resized
, *item
;
162 struct hostent
*host
;
163 array
*hostnamesa
, *passwordsa
;
164 sstring
**hostnames
, **passwords
;
166 hostnamesa
= getconfigitems("nterfacer", "hostname");
167 passwordsa
= getconfigitems("nterfacer", "password");
168 if(!hostnamesa
|| !passwordsa
)
170 if(hostnamesa
->cursi
!= passwordsa
->cursi
) {
171 nterface_log(nrl
, NL_ERROR
, "Different number of hostnames/passwords in config file.");
175 hostnames
= (sstring
**)hostnamesa
->content
;
176 passwords
= (sstring
**)passwordsa
->content
;
178 new_permits
= ntmalloc(hostnamesa
->cursi
* sizeof(struct permitted
));
179 memset(new_permits
, 0, hostnamesa
->cursi
* sizeof(struct permitted
));
182 for(i
=0;i
<hostnamesa
->cursi
;i
++) {
183 item
->hostname
= getsstring(hostnames
[i
]->content
, hostnames
[i
]->length
);
185 host
= gethostbyname(item
->hostname
->content
);
187 nterface_log(nrl
, NL_WARNING
, "Couldn't resolve hostname: %s (item %d).", item
->hostname
->content
, i
+ 1);
188 freesstring(item
->hostname
);
192 item
->ihost
= (*(struct in_addr
*)host
->h_addr_list
[0]).s_addr
;
193 for(j
=0;j
<loaded_lines
;j
++) {
194 if(new_permits
[j
].ihost
== item
->ihost
) {
195 nterface_log(nrl
, NL_WARNING
, "Host with items %d and %d is identical, dropping item %d.", j
+ 1, i
+ 1, i
+ 1);
201 freesstring(item
->hostname
);
205 item
->password
= getsstring(passwords
[i
]->content
, passwords
[i
]->length
);
206 nterface_log(nrl
, NL_DEBUG
, "Loaded permit, hostname: %s.", item
->hostname
->content
);
217 resized
= ntrealloc(new_permits
, sizeof(struct permitted
) * loaded_lines
);
224 permit_count
= loaded_lines
;
229 int setup_listening_socket(void) {
230 struct sockaddr_in sin
;
232 unsigned int opt
= 1;
234 fd
= socket(AF_INET
, SOCK_STREAM
, 0);
236 /* also shamelessly ripped from proxyscan */
238 nterface_log(nrl
, NL_ERROR
, "Unable to open listening socket (%d).", errno
);
242 if(setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char *) &opt
, sizeof(opt
)) != 0) {
243 nterface_log(nrl
, NL_ERROR
, "Unable to set SO_REUSEADDR on listen socket.");
247 /* Initialiase the addresses */
248 memset(&sin
, 0, sizeof(sin
));
249 sin
.sin_family
= AF_INET
;
250 sin
.sin_port
= htons(getcopyconfigitemintpositive("nterfacer", "port", NTERFACER_PORT
));
252 if(bind(fd
, (struct sockaddr
*) &sin
, sizeof(sin
))) {
253 nterface_log(nrl
, NL_ERROR
, "Unable to bind listen socket (%d).", errno
);
260 if(ioctl(fd
, FIONBIO
, &opt
)) {
261 nterface_log(nrl
, NL_ERROR
, "Unable to set listen socket non-blocking.");
269 struct service_node
*register_service(char *name
) {
270 struct service_node
*np
= ntmalloc(sizeof(service_node
));
273 np
->name
= getsstring(name
, strlen(name
));
287 struct handler
*register_handler(struct service_node
*service
, char *command
, int args
, handler_function fp
) {
288 struct handler
*hp
= ntmalloc(sizeof(handler
));
291 hp
->command
= getsstring(command
, strlen(command
));
301 hp
->next
= service
->handlers
;
302 hp
->service
= service
;
303 service
->handlers
= hp
;
308 void deregister_handler(struct handler
*hl
) {
309 struct service_node
*service
= (struct service_node
*)hl
->service
;
310 struct handler
*np
, *lp
= NULL
;
311 for(np
=service
->handlers
;np
;lp
=np
,np
=np
->next
) {
316 service
->handlers
= np
->next
;
324 void deregister_service(struct service_node
*service
) {
325 struct service_node
*sp
, *lp
= NULL
;
327 for(sp
=tree
;sp
;lp
=sp
,sp
=sp
->next
) {
338 if(!sp
) /* already freed */
341 free_handlers(service
);
343 freesstring(service
->name
);
348 void nterfacer_accept_event(struct esocket
*socket
) {
349 struct sockaddr_in sin
;
350 unsigned int addrsize
= sizeof(sin
);
351 int newfd
= accept(socket
->fd
, (struct sockaddr
*)&sin
, &addrsize
), i
;
352 struct sconnect
*temp
;
353 struct permitted
*item
= NULL
;
354 struct esocket
*newsocket
;
355 unsigned int opt
= 1;
358 nterface_log(nrl
, NL_WARNING
, "Unable to accept nterfacer fd!");
362 if(ioctl(newfd
, FIONBIO
, &opt
)) {
363 nterface_log(nrl
, NL_ERROR
, "Unable to set accepted socket non-blocking.");
368 for(i
=0;i
<permit_count
;i
++) {
369 if(permits
[i
].ihost
== sin
.sin_addr
.s_addr
) {
376 nterface_log(nrl
, NL_INFO
, "Unauthorised connection from %s closed", inet_ntoa(sin
.sin_addr
));
381 temp
= (struct sconnect
*)ntmalloc(sizeof(struct sconnect
));
388 /* do checks on hostname first */
390 newsocket
= esocket_add(newfd
, ESOCKET_UNIX_DOMAIN_CONNECTED
, &nterfacer_events
, nterfacer_token
);
396 newsocket
->tag
= temp
;
398 nterface_log(nrl
, NL_INFO
, "New connection from %s.", item
->hostname
->content
);
400 temp
->status
= SS_IDLE
;
403 esocket_write_line(newsocket
, "nterfacer " PROTOCOL_VERSION
);
406 void derive_key(unsigned char *out
, char *password
, char *segment
, unsigned char *noncea
, unsigned char *nonceb
, unsigned char *extra
, int extralen
) {
409 SHA256_Update(&c
, (unsigned char *)password
, strlen(password
));
410 SHA256_Update(&c
, (unsigned char *)":", 1);
411 SHA256_Update(&c
, (unsigned char *)segment
, strlen(segment
));
412 SHA256_Update(&c
, (unsigned char *)":", 1);
413 SHA256_Update(&c
, noncea
, 16);
414 SHA256_Update(&c
, (unsigned char *)":", 1);
415 SHA256_Update(&c
, nonceb
, 16);
416 SHA256_Update(&c
, (unsigned char *)":", 1);
417 SHA256_Update(&c
, extra
, extralen
);
418 SHA256_Final(out
, &c
);
421 SHA256_Update(&c
, out
, 32);
422 SHA256_Final(out
, &c
);
425 int nterfacer_line_event(struct esocket
*sock
, char *newline
) {
426 struct sconnect
*socket
= sock
->tag
;
427 char *response
, *theirnonceh
= NULL
, *theirivh
= NULL
;
428 unsigned char theirnonce
[16], theiriv
[16];
431 switch(socket
->status
) {
433 if(strcasecmp(newline
, ANTI_FULL_VERSION
)) {
434 nterface_log(nrl
, NL_INFO
, "Protocol mismatch from %s: %s", socket
->permit
->hostname
->content
, newline
);
437 unsigned char challenge
[32];
438 char ivhex
[16 * 2 + 1], noncehex
[16 * 2 + 1];
440 if(!get_entropy(challenge
, 32) || !get_entropy(socket
->iv
, 16)) {
441 nterface_log(nrl
, NL_ERROR
, "Unable to open challenge/IV entropy bin!");
445 int_to_hex(challenge
, socket
->challenge
, 32);
446 int_to_hex(socket
->iv
, ivhex
, 16);
448 memcpy(socket
->response
, challenge_response(socket
->challenge
, socket
->permit
->password
->content
), sizeof(socket
->response
));
449 socket
->response
[sizeof(socket
->response
) - 1] = '\0'; /* just in case */
451 socket
->status
= SS_VERSIONED
;
452 if(!generate_nonce(socket
->ournonce
, 1)) {
453 nterface_log(nrl
, NL_ERROR
, "Unable to generate nonce!");
456 int_to_hex(socket
->ournonce
, noncehex
, 16);
458 if(esocket_write_line(sock
, "%s %s %s", socket
->challenge
, ivhex
, noncehex
))
464 for(response
=newline
;*response
;response
++) {
465 if((*response
== ' ') && (*(response
+ 1))) {
467 theirivh
= response
+ 1;
473 for(response
=theirivh
;*response
;response
++) {
474 if((*response
== ' ') && (*(response
+ 1))) {
476 theirnonceh
= response
+ 1;
482 if(!theirivh
|| (strlen(theirivh
) != 32) || !hex_to_int(theirivh
, theiriv
, sizeof(theiriv
)) ||
483 !theirnonceh
|| (strlen(theirnonceh
) != 32) || !hex_to_int(theirnonceh
, theirnonce
, sizeof(theirnonce
))) {
484 nterface_log(nrl
, NL_INFO
, "Protocol error drop: %s", socket
->permit
->hostname
->content
);
488 if(!memcmp(socket
->ournonce
, theirnonce
, sizeof(theirnonce
))) {
489 nterface_log(nrl
, NL_INFO
, "Bad nonce drop: %s", socket
->permit
->hostname
->content
);
493 if(!strncasecmp(newline
, socket
->response
, sizeof(socket
->response
))) {
494 unsigned char theirkey
[32], ourkey
[32];
496 derive_key(ourkey
, socket
->permit
->password
->content
, socket
->challenge
, socket
->ournonce
, theirnonce
, (unsigned char *)"SERVER", 6);
498 derive_key(theirkey
, socket
->permit
->password
->content
, socket
->response
, theirnonce
, socket
->ournonce
, (unsigned char *)"CLIENT", 6);
499 nterface_log(nrl
, NL_INFO
, "Authed: %s", socket
->permit
->hostname
->content
);
500 socket
->status
= SS_AUTHENTICATED
;
501 switch_buffer_mode(sock
, ourkey
, socket
->iv
, theirkey
, theiriv
);
503 if(esocket_write_line(sock
, "Oauth"))
506 nterface_log(nrl
, NL_INFO
, "Bad CR drop: %s", socket
->permit
->hostname
->content
);
511 case SS_AUTHENTICATED
:
512 nterface_log(nrl
, NL_INFO
|NL_LOG_ONLY
, "L(%s): %s", socket
->permit
->hostname
->content
, newline
);
513 reason
= nterfacer_new_rline(newline
, sock
, &number
);
515 if(reason
== RE_SOCKET_ERROR
)
517 if(reason
!= RE_BAD_LINE
) {
518 if(esocket_write_line(sock
, "%d,E%d,%s", number
, reason
, request_error(reason
)))
531 int nterfacer_new_rline(char *line
, struct esocket
*socket
, int *number
) {
532 char *sp
, *p
, *parsebuf
= NULL
, *pp
, commandbuf
[MAX_BUFSIZE
], *args
[MAX_ARGS
], *newp
;
534 struct service_node
*service
;
535 struct rline
*prequest
;
539 if(!line
|| !line
[0] || (line
[0] == ','))
542 for(sp
=line
;*sp
;sp
++)
546 if(!*sp
|| !*(sp
+ 1))
551 for(service
=tree
;service
;service
=service
->next
)
552 if(!strcmp(service
->name
->content
, line
))
563 *number
= positive_atoi(sp
+ 1);
565 if((*number
< 1) || (*number
> 0xffff))
569 nterface_log(nrl
, NL_DEBUG
, "Unable to find service: %s", line
);
570 return RE_SERVICER_NOT_FOUND
;
575 for(pp
=p
+1;*pp
;pp
++) {
576 if((*pp
== '\\') && *(pp
+ 1)) {
577 if(*(pp
+ 1) == ',') {
579 } else if(*(pp
+ 1) == '\\') {
583 } else if(*pp
== ',') {
590 if(*pp
== '\0') { /* if we're at the end already, we have no arguments */
593 argcount
= 1; /* we have a comma, so we have one already */
598 for(hl
=service
->handlers
;hl
;hl
=hl
->next
)
599 if(!strncmp(hl
->command
->content
, commandbuf
, sizeof(commandbuf
)))
603 return RE_COMMAND_NOT_FOUND
;
606 parsebuf
= (char *)ntmalloc(strlen(pp
) + 1);
607 MemCheckR(parsebuf
, RE_MEM_ERROR
);
609 for(newp
=args
[0]=parsebuf
,pp
++;*pp
;pp
++) {
610 if((*pp
== '\\') && *(pp
+ 1)) {
611 if(*(pp
+ 1) == ',') {
613 } else if(*(pp
+ 1) == '\\') {
617 } else if(*pp
== ',') {
619 args
[argcount
++] = newp
;
620 if(argcount
> MAX_ARGS
) {
622 return RE_TOO_MANY_ARGS
;
630 if(argcount
< hl
->args
) {
631 if(argcount
&& parsebuf
)
633 return RE_WRONG_ARG_COUNT
;
636 prequest
= (struct rline
*)ntmalloc(sizeof(struct rline
));
639 if(argcount
&& parsebuf
)
644 prequest
->service
= service
;
645 prequest
->handler
= hl
;
646 prequest
->buf
[0] = '\0';
647 prequest
->curpos
= prequest
->buf
;
648 prequest
->tag
= NULL
;
649 prequest
->id
= *number
;
650 prequest
->next
= rlines
;
651 prequest
->socket
= socket
;
652 prequest
->callback
= NULL
;
655 re
= (hl
->function
)(prequest
, argcount
, args
);
657 if(argcount
&& parsebuf
)
663 void nterfacer_disconnect_event(struct esocket
*sock
) {
664 struct sconnect
*socket
= sock
->tag
;
668 nterface_log(nrl
, NL_INFO
, "Disconnected from %s.", socket
->permit
->hostname
->content
);
671 for(li
=rlines
;li
;li
=li
->next
)
672 if(li
->socket
&& (li
->socket
->tag
== socket
))
678 int ri_append(struct rline
*li
, char *format
, ...) {
679 char buf
[MAX_BUFSIZE
], escapedbuf
[MAX_BUFSIZE
* 2 + 1], *p
, *tp
;
680 int sizeleft
= sizeof(li
->buf
) - (li
->curpos
- li
->buf
);
683 va_start(ap
, format
);
685 if(vsnprintf(buf
, sizeof(buf
), format
, ap
) >= sizeof(buf
)) {
692 for(tp
=escapedbuf
,p
=buf
;*p
||(*tp
='\0');*tp
++=*p
++)
693 if((*p
== ',') || (*p
== '\\'))
697 if(li
->curpos
== li
->buf
) {
698 li
->curpos
+=snprintf(li
->curpos
, sizeleft
, "%s", escapedbuf
);
700 li
->curpos
+=snprintf(li
->curpos
, sizeleft
, ",%s", escapedbuf
);
704 if(sizeof(li
->buf
) - (li
->curpos
- li
->buf
) > 0) {
711 int ri_error(struct rline
*li
, int error_code
, char *format
, ...) {
712 char buf
[MAX_BUFSIZE
], escapedbuf
[MAX_BUFSIZE
* 2 + 1], *p
, *tp
;
713 struct rline
*pp
, *lp
= NULL
;
717 if(li
->socket
|| li
->callback
) {
718 va_start(ap
, format
);
719 vsnprintf(buf
, sizeof(buf
), format
, ap
);
722 for(tp
=escapedbuf
,p
=buf
;*p
||(*tp
='\0');*tp
++=*p
++)
723 if((*p
== ',') || (*p
== '\\'))
726 if(esocket_write_line(li
->socket
, "%d,OE%d,%s", li
->id
, error_code
, escapedbuf
))
727 retval
= RE_SOCKET_ERROR
;
729 if(error_code
== 0) /* :P */
732 nterfacer_sendcallback(li
, error_code
, escapedbuf
);
736 for(pp
=rlines
;pp
;lp
=pp
,pp
=pp
->next
) {
751 int ri_final(struct rline
*li
) {
752 struct rline
*pp
, *lp
= NULL
;
756 if(esocket_write_line(li
->socket
, "%d,OO%s", li
->id
, li
->buf
))
757 retval
= RE_SOCKET_ERROR
;
758 } else if(li
->callback
) {
759 nterfacer_sendcallback(li
, 0, li
->buf
);
762 for(pp
=rlines
;pp
;lp
=pp
,pp
=pp
->next
) {
777 int ping_handler(struct rline
*ri
, int argc
, char **argv
) {
790 static const int XMAXARGS
= 50;
792 static void execrline(void *arg
) {
793 struct sched_rline
*sr
= arg
;
795 char *argv
[XMAXARGS
], *buf
;
800 for(i
=0;i
<sr
->argc
;i
++) {
802 buf
+=strlen(buf
) + 1;
805 re
= (sr
->hl
->function
)(&sr
->rl
, sr
->argc
, argv
);
808 Error("nterfacer", ERR_WARNING
, "sendline: error occured calling %p %d: %s", sr
->hl
->function
, re
, request_error(re
));
811 void *nterfacer_sendline(char *service
, char *command
, int argc
, char **argv
, rline_callback callback
, void *tag
) {
812 struct service_node
*servicep
;
813 struct rline
*prequest
;
814 struct sched_rline
*sr
;
819 for(servicep
=tree
;servicep
;servicep
=servicep
->next
)
820 if(!strcmp(servicep
->name
->content
, service
))
824 Error("nterfacer", ERR_STOP
, "Over maximum arguments.");
827 Error("nterfacer", ERR_WARNING
, "sendline: service not found: %s", service
);
831 for(hl
=servicep
->handlers
;hl
;hl
=hl
->next
)
832 if(!strcmp(hl
->command
->content
, command
))
836 Error("nterfacer", ERR_WARNING
, "sendline: command not found: %s", command
);
840 if(argc
< hl
->args
) {
841 Error("nterfacer", ERR_WARNING
, "sendline: wrong number of arguments: %s", command
);
845 /* we have to create a copy of the arguments for reentrancy reasons, grr */
848 totallen
+=strlen(argv
[i
]) + 1;
850 /* HACKY but allows existing code to still work */
851 sr
= (struct sched_rline
*)ntmalloc(sizeof(struct sched_rline
) + totallen
);
860 for(i
=0;i
<argc
;i
++) {
861 size_t len
= strlen(argv
[i
]) + 1;
862 memcpy(buf
, argv
[i
], len
);
867 prequest
->service
= servicep
;
868 prequest
->handler
= hl
;
869 prequest
->buf
[0] = '\0';
870 prequest
->curpos
= prequest
->buf
;
873 prequest
->socket
= NULL
;
874 prequest
->callback
= callback
;
876 prequest
->next
= rlines
;
879 scheduleoneshot(time(NULL
), execrline
, sr
);
884 void nterfacer_freeline(void *tag
) {
885 struct sched_rline
*prequest
= tag
;
887 prequest
->rl
.callback
= NULL
;
888 if(prequest
->schedule
)
889 deleteschedule(prequest
->schedule
, execrline
, NULL
);
892 #define MAX_LINES 8192
895 static void nterfacer_sendcallback(struct rline
*ri
, int error
, char *buf
) {
896 char *lines
[MAX_LINES
+1];
897 char newbuf
[MAX_BUFSIZE
+5];
898 char *s
, *d
, *laststart
;
901 for(s
=buf
,laststart
=d
=newbuf
;*s
;s
++) {
902 if((*s
== '\\') && *(s
+ 1)) {
903 if(*(s
+ 1) == ',') {
905 } else if(*(s
+ 1) == '\\') {
909 } else if(*s
== ',') {
911 if(linec
>= MAX_LINES
- 5) {
912 nterfacer_sendcallback(ri
, BF_OVER
, "Buffer overflow.");
916 lines
[linec
++] = laststart
;
923 lines
[linec
++] = laststart
;
925 ri
->callback(error
, linec
, lines
, ri
->tag
);