Files
mars_nwe_pcab/native/main.c

74 lines
17 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/* SPDX-License-Identifier: GPL-2.0-or-later */
#define _GNU_SOURCE
#include "core.h"
#include "supervisor.h"
#include "admin.h"
#include <civetweb.h>
#include <pthread.h>
#include <openssl/crypto.h>
#include <arpa/inet.h>
#include <ifaddrs.h>
#include <netinet/in.h>
#include <sys/stat.h>
#include <sys/file.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <time.h>
#include <errno.h>
#define SESSIONS 128
#define MAX_BODY (MAX_CONF*6)
static pthread_mutex_t api_lock=PTHREAD_MUTEX_INITIALIZER;
static char assets[PATH_MAX]="/usr/local/share/mars-vme/www",port[8]="8787",bind_ip[64]="0.0.0.0",pem[PATH_MAX],extra_host[256];
static int tls,initial_start=1;
static volatile sig_atomic_t quitting;
struct session {char token[65],csrf[65];time_t until,absolute;};
struct attempt {char ip[48];int count;time_t until;};
static struct session sessions[SESSIONS];static struct attempt attempts[256];
static time_t mono(void){struct timespec t;clock_gettime(CLOCK_MONOTONIC,&t);return t.tv_sec;}
static const char *reason(int code){switch(code){case 200:return "OK";case 303:return "See Other";case 400:return "Bad Request";case 401:return "Unauthorized";case 403:return "Forbidden";case 404:return "Not Found";case 405:return "Method Not Allowed";case 409:return "Conflict";case 429:return "Too Many Requests";default:return "Internal Server Error";}}
static int send_data(struct mg_connection*c,int code,const char*type,const char*s,size_t n,const char*cookie,const char*location){mg_printf(c,"HTTP/1.1 %d %s\r\nContent-Type: %s\r\nContent-Length: %zu\r\nConnection: close\r\nCache-Control: no-store\r\nX-Content-Type-Options: nosniff\r\nX-Frame-Options: DENY\r\nReferrer-Policy: no-referrer\r\nContent-Security-Policy: default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'\r\n",code,reason(code),type,n);if(cookie)mg_printf(c,"Set-Cookie: %s\r\n",cookie);if(location)mg_printf(c,"Location: %s\r\n",location);mg_printf(c,"\r\n");if(n)mg_write(c,s,n);return code;}
static int reply(struct mg_connection*c,int code,json_object*o,const char*cookie){const char*s=json_object_to_json_string_ext(o,JSON_C_TO_STRING_PLAIN);int r=send_data(c,code,"application/json; charset=utf-8",s,strlen(s),cookie,NULL);json_object_put(o);return r;}
static int error(struct mg_connection*c,int code,const char*s){json_object*o=json_object_new_object();addstr(o,"error",s);return reply(c,code,o,NULL);}
static int ok(struct mg_connection*c,const char*cookie){json_object*o=json_object_new_object();json_object_object_add(o,"ok",json_object_new_boolean(1));return reply(c,200,o,cookie);}
static int private_ip(const char*s){struct in_addr a;if(inet_pton(AF_INET,s,&a)!=1)return 0;uint32_t x=ntohl(a.s_addr);return (x>>24)==127||(x>>24)==10||(x>>20)==0xac1||(x>>16)==0xc0a8||(x>>16)==0xa9fe;}
static int allowed_host(const char*h){if(!h)return 0;char b[256];if(*extra_host&&!strcmp(h,extra_host))return 1;snprintf(b,sizeof b,"localhost:%s",port);if(!strcmp(h,b))return 1;struct ifaddrs*ifs;if(getifaddrs(&ifs))return 0;int ok=0;for(struct ifaddrs*p=ifs;p;p=p->ifa_next){if(!p->ifa_addr||p->ifa_addr->sa_family!=AF_INET)continue;char ip[INET_ADDRSTRLEN];if(!inet_ntop(AF_INET,&((struct sockaddr_in*)p->ifa_addr)->sin_addr,ip,sizeof ip))continue;snprintf(b,sizeof b,"%s:%s",ip,port);if(!strcmp(h,b))ok=1;}freeifaddrs(ifs);return ok;}
static void cookie_str(char out[256],const char*token){snprintf(out,256,"mars_session=%s; Path=/; HttpOnly; SameSite=Strict; Max-Age=%d%s",token,*token?28800:0,tls?"; Secure":"");}
static struct session* session_get(struct mg_connection*c){const char*h=mg_get_header(c,"Cookie");if(!h)return NULL;char token[65];if(mg_get_cookie(h,"mars_session",token,sizeof token)!=64)return NULL;time_t t=mono();for(int i=0;i<SESSIONS;i++){struct session*s=&sessions[i];if(s->until<=t||s->absolute<=t){memset(s,0,sizeof *s);continue;}if(!CRYPTO_memcmp(s->token,token,64)){s->until=t+1800;return s;}}return NULL;}
static struct session* new_session(void){time_t t=mono();int slot=-1;for(int i=0;i<SESSIONS;i++){if(sessions[i].until<=t||sessions[i].absolute<=t){slot=i;break;}}if(slot<0)return NULL;struct session*s=&sessions[slot];memset(s,0,sizeof *s);if(random_hex(s->token,32)||random_hex(s->csrf,32)){memset(s,0,sizeof *s);return NULL;}s->until=t+1800;s->absolute=t+28800;return s;}
static struct attempt* rate(const char*ip){time_t t=mono();int slot=-1;for(int i=0;i<256;i++){if(attempts[i].until<=t){if(slot<0)slot=i;}else if(!strcmp(attempts[i].ip,ip))return &attempts[i];}if(slot<0)return NULL;struct attempt*a=&attempts[slot];memset(a,0,sizeof *a);snprintf(a->ip,sizeof a->ip,"%s",ip);a->until=t+60;return a;}
static json_object *read_json(struct mg_connection*c,long long n){if(n<=0||n>MAX_BODY)return NULL;const char*ct=mg_get_header(c,"Content-Type");if(!ct||strncmp(ct,"application/json",16)||(ct[16]&&ct[16]!=';'))return NULL;char*b=malloc((size_t)n+1);if(!b)return NULL;size_t off=0;while(off<(size_t)n){int k=mg_read(c,b+off,(size_t)n-off);if(k<=0){free(b);return NULL;}off+=k;}b[n]=0;struct json_tokener*t=json_tokener_new();if(!t){free(b);return NULL;}json_tokener_set_flags(t,JSON_TOKENER_STRICT|JSON_TOKENER_VALIDATE_UTF8);json_object*o=json_tokener_parse_ex(t,b,(int)n);if(json_tokener_get_error(t)!=json_tokener_success||json_tokener_get_parse_end(t)!=(size_t)n||!json_object_is_type(o,json_type_object)){json_object_put(o);o=NULL;}json_tokener_free(t);OPENSSL_cleanse(b,(size_t)n);free(b);return o;}
static json_object *state(struct session*s,const char*current){json_object*o=json_object_new_object();int initial=auth_default();char h[65];sha(current,h);addstr(o,"text",initial?"":current);addstr(o,"revision",h);json_object_object_add(o,"groups",groups(initial?"":current));json_object_object_add(o,"devices",devices());json_object_object_add(o,"validation",validate(initial?"":current));json_object_object_add(o,"backups",initial?json_object_new_array():backups());addstr(o,"path",config_path);json_object_object_add(o,"services",json_object_new_boolean(!no_services&&!initial));addstr(o,"csrf",s->csrf);json_object_object_add(o,"defaultPassword",json_object_new_boolean(initial));return o;}
/* Full before/after comparison. No external shell command or temporary cleartext diff file. */
static char *comparison(const char*a,const char*b){if(!strcmp(a,b))return strdup("");char*s=NULL;if(asprintf(&s,"--- Aktuell (vollständig) ---\n%s\n+++ Entwurf (vollständig) +++\n%s",a,b)<0)return NULL;return s;}
static int confirm(json_object*r){json_object*v=get(r,"confirm");return json_object_is_type(v,json_type_boolean)&&json_object_get_boolean(v);}
static int config_valid(const char*s){json_object*v=validate(s);int ok=json_object_array_length(get(v,"errors"))==0;json_object_put(v);return ok;}
static int process(struct mg_connection*c,const struct mg_request_info*r,json_object*req){const char*u=r->local_uri;int post=!strcmp(r->request_method,"POST");struct session*s=session_get(c);char cookie[256];if(post&&!strcmp(u,"/api/login")){struct attempt*a=rate(r->remote_addr);if(!a||a->count>=5)return error(c,429,"Zu viele Versuche. Eine Minute warten.");const char*user=js(req,"user");if(!user||strcmp(user,"admin")||!auth_verify(js(req,"password"))){a->count++;return error(c,401,"Anmeldung fehlgeschlagen.");}a->count=0;if(!(s=new_session()))return error(c,429,"Zu viele aktive Sitzungen.");cookie_str(cookie,s->token);return ok(c,cookie);}
const char*file=NULL,*type=NULL;if(!post){if(!strcmp(u,"/login")){file="login.html";type="text/html";}else if(!strcmp(u,"/login.js")){file="login.js";type="text/javascript";}else if(!strcmp(u,"/style.css")){file="style.css";type="text/css";}}
if(!file&&!s){if(!strcmp(u,"/"))return send_data(c,303,"text/plain","",0,NULL,"/login");return error(c,401,"Anmeldung erforderlich.");}
if(post){const char*csrf=mg_get_header(c,"X-Mars-CSRF");if(!csrf||strlen(csrf)!=64||CRYPTO_memcmp(csrf,s->csrf,64))return error(c,403,"CSRF-Prüfung fehlgeschlagen.");if(!strcmp(u,"/api/logout")){memset(s,0,sizeof *s);cookie_str(cookie,"");return ok(c,cookie);}if(!strcmp(u,"/api/password")){const char*next=js(req,"new"),*rep=js(req,"repeat");if(!auth_verify(js(req,"current"))||!next||!rep||strcmp(next,rep)||auth_set(next,0))return error(c,400,"Aktuelles Kennwort prüfen; neues Kennwort 10–256 Zeichen, zweimal identisch.");memset(sessions,0,sizeof sessions);cookie_str(cookie,"");return ok(c,cookie);}if(auth_default())return error(c,403,"Zuerst das Web-Standardkennwort ändern.");}
if(!post&&!file){if(!strcmp(u,"/")){file="index.html";type="text/html";}else if(!strcmp(u,"/app.js")){file="app.js";type="text/javascript";}}
if(file){char*p=NULL;asprintf(&p,"%s/%s",assets,file);char*d=p?read_file(p,MAX_CONF,0):NULL;free(p);if(!d)return error(c,404,"Datei fehlt.");char mime[64];snprintf(mime,sizeof mime,"%s; charset=utf-8",type);int code=send_data(c,200,mime,d,strlen(d),NULL,NULL);free(d);return code;}
if(!post&&!strcmp(u,"/api/status"))return reply(c,200,supervisor_status(),NULL);
if(!post&&!strcmp(u,"/api/monitor")){if(auth_default())return error(c,403,"Kennwort ändern.");return reply(c,200,monitor_data(),NULL);}
if(!strcmp(u,"/api/bindery")||!strcmp(u,"/api/print")){if(auth_default()||no_services)return error(c,403,"Kennwort ändern oder Dienstmodus verwenden.");if(!post)return error(c,405,"POST erforderlich.");const char *op=js(req,"op");if(!op)return error(c,400,"Aktion fehlt.");if(!strncmp(op,"trustee-",8)&&!supervisor_config_matches())return error(c,409,"Konfiguration seit Serverstart geändert. Dateiserver neu starten.");int readonly=!strcmp(op,"sessions")||!strcmp(op,"objects")||!strcmp(op,"properties")||!strcmp(op,"list")||!strcmp(op,"script-get")||!strcmp(op,"trustee-get")||!strcmp(op,"group-members");if(!readonly&&!confirm(req))return error(c,400,"Aktion bestätigen.");json_object *res=!strcmp(u,"/api/bindery")?bindery_call(req):print_call(req);return reply(c,get(res,"error")?400:200,res,NULL);}
char*current=read_file(config_path,MAX_CONF,0);if(!current)return error(c,500,"nwserv.conf nicht lesbar.");char rev[65];sha(current,rev);int ret=404;
if(!post&&!strcmp(u,"/api/state")){ret=reply(c,200,state(s,current),NULL);goto done;}if(!post&&!strcmp(u,"/api/download")){if(auth_default())ret=error(c,403,"Kennwort ändern.");else ret=send_data(c,200,"text/plain; charset=utf-8",current,strlen(current),NULL,NULL);goto done;}
if(!post){ret=error(c,404,"Nicht gefunden.");goto done;}const char*given=js(req,"revision");if(!given||strcmp(given,rev)){ret=error(c,409,"Konfiguration geändert. Bitte neu laden.");goto done;}
if(!strcmp(u,"/api/service")){const char*a=js(req,"action");if(!confirm(req)||!a||no_services||((!strcmp(a,"start")||!strcmp(a,"restart"))&&!config_valid(current))||supervisor_request(a)){ret=error(c,400,"Aktion nicht erlaubt oder Konfiguration ungültig.");goto done;}ret=reply(c,200,supervisor_status(),NULL);goto done;}
if(strcmp(u,"/api/preview")&&strcmp(u,"/api/save")){ret=error(c,404,"Nicht gefunden.");goto done;}const char*mode=js(req,"mode");char*candidate=NULL;if(mode&&!strcmp(mode,"guided"))candidate=merge(current,get(req,"groups"));else if(mode&&!strcmp(mode,"raw")){const char*t=js(req,"text");if(t&&strlen(t)<=MAX_CONF)candidate=strdup(t);}else if(mode&&!strcmp(mode,"backup"))candidate=backup_read(js(req,"name"));if(!candidate){ret=error(c,400,"Ungültiger Entwurf oder Backup.");goto done;}
json_object*v=validate(candidate);char hash[65];sha(candidate,hash);if(!strcmp(u,"/api/preview")){char*d=comparison(current,candidate);if(!d){json_object_put(v);ret=error(c,500,"Vorschau fehlgeschlagen.");}else{addstr(v,"candidate",candidate);addstr(v,"candidateHash",hash);addstr(v,"diff",d);free(d);ret=reply(c,200,v,NULL);}}else{const char*h=js(req,"candidateHash");if(json_object_array_length(get(v,"errors"))||!confirm(req)||!h||strcmp(h,hash)){ret=error(c,400,"Entwurf zuerst prüfen und bestätigen.");}else{char name[64];int rc=save_conf(current,rev,candidate,name);if(rc)ret=error(c,rc==-2?409:500,"Speichern fehlgeschlagen; Datei oder Backup prüfen.");else{json_object*o=json_object_new_object();addstr(o,"backup",name);json_object_object_add(o,"state",state(s,candidate));ret=reply(c,200,o,NULL);}}json_object_put(v);}free(candidate);
done:free(current);return ret;}
static int handle(struct mg_connection*c,void*data){(void)data;const struct mg_request_info*r=mg_get_request_info(c);const char*h=mg_get_header(c,"Host");if(!r||!r->local_uri||!private_ip(r->remote_addr)||!allowed_host(h))return error(c,403,"Host oder Clientnetz nicht erlaubt.");int post=!strcmp(r->request_method,"POST");if(!post&&strcmp(r->request_method,"GET"))return error(c,405,"Methode nicht erlaubt.");json_object*req=NULL;if(post){char expected[300];snprintf(expected,sizeof expected,"%s://%s",tls?"https":"http",h);const char*origin=mg_get_header(c,"Origin");if(!origin||strcmp(origin,expected))return error(c,403,"Origin-Prüfung fehlgeschlagen.");req=read_json(c,r->content_length);if(!req)return error(c,400,"Ungültiges JSON oder Anfragegröße.");}pthread_mutex_lock(&api_lock);int result=process(c,r,req);pthread_mutex_unlock(&api_lock);json_object_put(req);return result;}
static int begin_request(struct mg_connection*c){return handle(c,NULL);}
static void on_signal(int s){(void)s;quitting=1;}
static int set_path(char*d,size_t cap,const char*s){if(!s||strlen(s)>=cap)return -1;strcpy(d,s);return 0;}
static void usage(void){fprintf(stderr,"mars_vme [--config PATH] [--www PATH] [--bind IPv4] [--port N] [--pem PATH] [--host HOST:PORT] [--no-autostart] [--no-services] [--reset-password]\n");}
int main(int argc,char**argv){strcpy(config_path,"/usr/local/etc/mars_nwe/nwserv.conf");int reset=0;for(int i=1;i<argc;i++){char *a=argv[i],*v=i+1<argc?argv[i+1]:NULL;int bad=0;if(!strcmp(a,"--no-autostart"))initial_start=0;else if(!strcmp(a,"--no-services")){no_services=1;initial_start=0;}else if(!strcmp(a,"--reset-password"))reset=1;else if(!strcmp(a,"--config")){bad=set_path(config_path,sizeof config_path,v);i++;}else if(!strcmp(a,"--www")){bad=set_path(assets,sizeof assets,v);i++;}else if(!strcmp(a,"--bind")){bad=set_path(bind_ip,sizeof bind_ip,v);i++;}else if(!strcmp(a,"--port")){bad=set_path(port,sizeof port,v);i++;}else if(!strcmp(a,"--pem")){bad=set_path(pem,sizeof pem,v);i++;}else if(!strcmp(a,"--host")){bad=set_path(extra_host,sizeof extra_host,v);i++;}else{usage();return 2;}if(bad){usage();return 2;}}
struct in_addr addr;char*end;long pn=strtol(port,&end,10);if(*end||pn<1024||pn>65535||inet_pton(AF_INET,bind_ip,&addr)!=1||config_path[0]!='/'||assets[0]!='/'){usage();return 2;}if(!no_services&&(geteuid()!=0||strcmp(config_path,"/usr/local/etc/mars_nwe/nwserv.conf"))){fprintf(stderr,"NetWare-Dienststeuerung benötigt root und Standard-Konfigurationspfad. Für Tests --no-services.\n");return 1;}umask(0077);char*parent=strdup(config_path);char*slash=strrchr(parent,'/');*slash=0;if(snprintf(auth_path,sizeof auth_path,"%s/.mars-web-auth.json",parent)>=(int)sizeof auth_path||snprintf(backup_dir,sizeof backup_dir,"%s/.mars-web-backups",parent)>=(int)sizeof backup_dir){free(parent);return 2;}char*lockname=NULL;asprintf(&lockname,"%s/.mars-vme.lock",parent);free(parent);int lockfd=open(lockname,O_CREAT|O_RDWR|O_CLOEXEC|O_NOFOLLOW,0600);free(lockname);if(lockfd<0||flock(lockfd,LOCK_EX|LOCK_NB)){fprintf(stderr,"Andere mars_vme-Instanz aktiv oder Lock nicht zugänglich.\n");return 1;}char*conf=read_file(config_path,MAX_CONF,0);if(!conf||auth_init()){fprintf(stderr,"Konfiguration oder Kennwortdatei nicht lesbar.\n");free(conf);return 1;}
if(reset){char*pw=getpass("Neues Web-Kennwort: ");char*first=pw?strdup(pw):NULL;pw=getpass("Wiederholen: ");int rc=!first||!pw||strcmp(first,pw)||auth_set(first,0);if(first){OPENSSL_cleanse(first,strlen(first));free(first);}free(conf);return rc?1:0;}
tls=*pem!=0;char listen[128];snprintf(listen,sizeof listen,"%s:%s%s",bind_ip,port,tls?"s":"");const char*options[24];int k=0;options[k++]="listening_ports";options[k++]=listen;options[k++]="num_threads";options[k++]="4";options[k++]="request_timeout_ms";options[k++]="10000";options[k++]="enable_keep_alive";options[k++]="no";options[k++]="enable_directory_listing";options[k++]="no";/* no document_root: only explicitly mapped assets */if(tls){options[k++]="ssl_certificate";options[k++]=pem;options[k++]="ssl_protocol_version";options[k++]="4";}options[k]=NULL;signal(SIGINT,on_signal);signal(SIGTERM,on_signal);signal(SIGPIPE,SIG_IGN);if(tls&&!(mg_init_library(MG_FEATURES_TLS)&MG_FEATURES_TLS)){fprintf(stderr,"CivetWeb TLS nicht verfügbar.\n");free(conf);return 1;}if(!tls)mg_init_library(0);struct mg_callbacks cb={0};cb.begin_request=begin_request;struct mg_context*ctx=mg_start(&cb,NULL,options);if(!ctx){fprintf(stderr,"CivetWeb Start fehlgeschlagen.\n");free(conf);mg_exit_library();return 1;}fprintf(stderr,"mars_vme: %s://%s:%s (CivetWeb); %s\n",tls?"https":"http",bind_ip,port,auth_default()?"Initialkennwort aktiv":"Kennwort eingerichtet");if(initial_start&&config_valid(conf))supervisor_request("start");else if(initial_start)fprintf(stderr,"NetWare wartet auf gültige Einrichtung.\n");free(conf);while(!quitting){supervisor_tick();usleep(100000);}mg_stop(ctx);supervisor_shutdown();mg_exit_library();close(lockfd);return 0;}