public static void Set() { Stop(); DirectoryWithAcl.CreateDirectory(LibDirMnt, "755", "root", "root"); MountManagement.Dir(LibDir); #region [ torrc generation ] if (File.Exists(MainFilePath)) { if (File.Exists(MainFilePathBackup)) { File.Delete(MainFilePathBackup); } File.Copy(MainFilePath, MainFilePathBackup); } var lines = new List <string>(); foreach (var svc in ServiceModel.Services) { if (string.IsNullOrEmpty(svc.Name) || string.IsNullOrEmpty(svc.IpAddress) || string.IsNullOrEmpty(svc.TorPort)) { continue; } //HiddenServiceDir /var/lib/tor/hidden_service/ //HiddenServicePort 80 127.0.0.1:8080 var dire = $"{LibDirMnt}/{svc.Name}"; DirectoryWithAcl.CreateDirectory(dire, "755", "root", "root"); lines.Add($"HiddenServiceDir {dire}"); lines.Add($"HiddenServicePort {svc.TorPort} {svc.IpAddress}"); } FileWithAcl.WriteAllLines(MainFilePath, lines, "700", "tor", "root"); #endregion Start(); }
public string CreateLauncherUnit(string name, string exeName, string exePath) { var unitName = $"app-{name.ToLower()}-{exeName.ToLower().Replace(".exe", "")}-launcher.service"; var fileName = $"{Parameter.AppsUnits}/{unitName}"; if (File.Exists(fileName)) { File.Delete(fileName); } var oldUnitName = $"{Parameter.ApplicativeUnits}/{unitName}"; if (File.Exists(oldUnitName)) { File.Delete(oldUnitName); } var lines = new List <string> { "[Unit]", $"Description=External Volume Unit, Application: {exeName} Launcher Service", $"After=app-{name.ToLower()}-02-mount.service".Replace(" ", ""), "", "[Service]", $"ExecStart=/usr/bin/mono {exePath}", "Restart=on-failure", "RemainAfterExit=no", "TasksMax=infinity", "LimitNOFILE=1024000", "", "[Install]", "WantedBy=applicative.target" }; FileWithAcl.WriteAllLines(fileName, lines, "644", "root", "wheel"); Systemctl.DaemonReload(); return(unitName); }
private static void WriteTimerServiceFile() { const string file = "/usr/lib64/systemd/system/tt.service"; if (File.Exists(file)) { File.Delete(file); } var timerText = new List <string> { "[Unit]", "Description=Description=Anthilla OS - Triggers and Timers Target", "After=etc-systemd-system-tt.target.wants.mount", "Before=tt.target", "Requires=etc-systemd-system-tt.target.wants.mount", "", "[Service]", "ExecStartPre=/usr/bin/systemctl daemon-reload", "ExecStart=/usr/bin/systemctl start tt.target", "", "[Install]", "WantedBy=multi-user.target", "" }; FileWithAcl.WriteAllLines(file, timerText, "644", "root", "wheel"); }
public void GenerateReport() { DirectoryWithAcl.CreateDirectory(ReportDir, "755", "root", "wheel"); try { var lines = new List <string> { "+================================+", $"| Antd Report @ {DateTime.Now:yyyy-MM-dd} |", "+================================+", "", Bash.Execute("uname -a"), $"uptime: {Bash.Execute("uptime | awk -F ',' '{print $1 $2}'").Trim()}", $"processes: {Bash.Execute("ps -aef | wc | awk -F ' ' '{ print $1 }'").Trim()}", $"users logged: {Bash.Execute("who | awk -F ' ' '{print $1}' |sort -u | wc |awk -F ' ' '{print $1}'").Trim()}", $"sessions open: {Bash.Execute("who | sort -u | wc |awk -F ' ' '{print $1}'").Trim()}", $"load: {Bash.Execute("uptime | awk -F ',' '{print $4 $5 $6}' | awk -F ':' '{print $2}'").Trim()}", "" }; lines.AddRange(GetSecurityReport()); FileWithAcl.WriteAllLines($"{ReportDir}/{Timestamp.Now}-antd-report.txt", lines, "644", "root", "wheel"); } catch (Exception ex) { ConsoleLogger.Error($"unable to create the log report: {ex.Message}"); } }
private static void WriteTimerMountFile() { const string file = "/usr/lib64/systemd/system/etc-systemd-system-tt.target.wants.mount"; if (File.Exists(file)) { File.Delete(file); } var timerText = new List <string> { "[Unit]", "Description=Description=Anthilla OS - Triggers and Timers Target Units Binding", "After=mnt-cdrom.mount", "Before=tt.service tt.target", "", "[Mount]", "What=/mnt/cdrom/Units/tt.target.wants", "Where=/etc/systemd/system/tt.target.wants", "Type=bind", "Options=bind", "", "[Install]", "WantedBy=multi-user.target", "" }; FileWithAcl.WriteAllLines(file, timerText, "644", "root", "wheel"); }
public void Set() { Enable(); Stop(); #region [ named.conf generation ] if (File.Exists(MainFilePath)) { if (File.Exists(MainFilePathBackup)) { File.Delete(MainFilePathBackup); } File.Copy(MainFilePath, MainFilePathBackup); } var lines = new List <string> { "options {" }; FileWithAcl.WriteAllLines(MainFilePath, lines, "644", "root", "wheel"); #endregion Start(); }
public static void CreateSmartCardCertificate(string name, string passphrase, string upn, string email, string c, string st, string l, string o, string ou) { var config = $"{CaIntermediateDirectory}/{name}.openssl.cnf"; if (!File.Exists(config)) { var applicationSetting = new AppConfiguration().Get(); FileWithAcl.WriteAllLines(config, CaConfigurationFiles.IntermediateCaSmartCardOpensslCnf( CaIntermediateDirectory, $"http://{GetThisIp()}:{applicationSetting.AntdPort}/services/ca/crl", upn ), "644", "root", "wheel"); } var key = $"{CaIntermediateDirectory}/private/{name}.key.pem"; if (!File.Exists(key)) { Bash.Execute($"openssl genrsa -aes256 -out {key} -passout pass:{passphrase} 2048"); Bash.Execute($"chmod 400 ${key}"); } var csr = $"{CaIntermediateDirectory}/csr/{name}.csr.pem"; if (!File.Exists(key)) { Bash.Execute($"openssl req -config {config} -key {key} -new -sha256 -out {csr} -passin pass:{passphrase} -subj \"/C={c}/ST={st}/L={l}/O={o}/OU={ou}/CN={name}/emailAddress={email}\""); } var cert = $"{CaIntermediateDirectory}/certs/{name}.cert.pem"; if (!File.Exists(cert)) { Bash.Execute($"openssl ca -config {config} -extensions usr_cert -days 375 -notext -md sha256 -in {csr} -out {cert}"); Bash.Execute($"chmod 444 ${cert}"); } }
public static void Backup(string dir) { var acls = Bash.Execute($"getfacl -R {dir}").SplitBash(); var destination = SetAclBackupFilePath(dir); FileWithAcl.WriteAllLines(destination, acls, "644", "root", "wheel"); }
private static bool SetUnitForTunnel(string remoteHost) { var lines = new List <string> { "[Unit]", "Description=ExtUnit, VpnConnection", "", "[Service]", $"ExecStart=/usr/bin/ssh -o Tunnel=ethernet -f -w 1:1 root@{remoteHost} true", "SuccessExitStatus=1 2 3 4 5 6 7 8 9 0", "RemainAfterExit=yes", "Type=oneshot", "", "[Install]", "WantedBy=antd.target" }; var unitName = $"/mnt/cdrom/Units/antd.target.wants/antd-{remoteHost}-vpn.service"; ConsoleLogger.Log(unitName); if (!File.Exists(unitName)) { FileWithAcl.WriteAllLines(unitName, lines, "644", "root", "wheel"); Systemctl.DaemonReload(); } Systemctl.Restart($"antd-{remoteHost}-vpn.service"); return(Systemctl.IsActive($"antd-{remoteHost}-vpn.service")); }
public string CreatePrepareUnit(string name, string frameworkDir) { var unitName = $"app-{name.ToLower()}-01-prepare.service".Replace(" ", ""); var fileName = $"{Parameter.AppsUnits}/{unitName}"; if (File.Exists(fileName)) { File.Delete(fileName); } var oldUnitName = $"{Parameter.ApplicativeUnits}/{unitName}"; if (File.Exists(oldUnitName)) { File.Delete(oldUnitName); } var lines = new List <string> { "[Unit]", "Description=External Volume Unit, Application: {name} Prepare Service", $"Before=app-{name.ToLower()}-02-mount.service".Replace(" ", ""), "", "[Service]", $"ExecStart=/bin/mkdir -p {frameworkDir}", "SuccessExitStatus=0", "RemainAfterExit=yes", "", "[Install]", "WantedBy=applicative.target" }; FileWithAcl.WriteAllLines(fileName, lines, "644", "root", "wheel"); Systemctl.DaemonReload(); return(unitName); }
public static void PrepareConfigurationFile() { // /data/ca/openssl.cnf if (!File.Exists($"{CaMainDirectory}/openssl.cnf")) { FileWithAcl.WriteAllLines($"{CaMainDirectory}/openssl.cnf", CaConfigurationFiles.RootCaOpensslCnf(CaMainDirectory), "644", "root", "wheel"); } }
public static void PrepareIntermediateConfigurationFile() { if (!File.Exists($"{CaIntermediateDirectory}/openssl.cnf")) { var applicationSetting = new AppConfiguration().Get(); FileWithAcl.WriteAllLines($"{CaIntermediateDirectory}/openssl.cnf", CaConfigurationFiles.IntermediateCaOpensslCnf(CaIntermediateDirectory, $"http://{GetThisIp()}:{applicationSetting.AntdPort}/services/ca/crl"), "644", "root", "wheel"); } }
public static void SetAcl(string guid, string[] rules) { var acls = ServiceModel.Settings; var model = acls.FirstOrDefault(_ => _.Guid == guid); if (model == null) { return; } FileWithAcl.WriteAllLines(model.Acl, rules, "644", "root", "wheel"); }
public static void SetRmmodList(List <string> objects) { var lines = objects; try { FileWithAcl.WriteAllLines(RmmodFile, lines, "644", "root", "wheel"); } catch (Exception ex) { ConsoleLogger.Error($"[host parameters] rmmod configuration set error: {ex.Message}"); } }
public static void Setup() { if (!Directory.Exists("/mnt/cdrom/Units")) { return; } if (!Directory.Exists("/mnt/cdrom/Units/antd.target.wants")) { return; } var edit = false; if (!File.Exists(Service01PreparePath)) { FileWithAcl.WriteAllLines(Service01PreparePath, Service01Prepare(), "644", "root", "wheel"); edit = true; } if (!File.Exists(Service02MountPath)) { FileWithAcl.WriteAllLines(Service02MountPath, Service02Mount(), "644", "root", "wheel"); edit = true; } if (!File.Exists(Service03LauncherPath)) { FileWithAcl.WriteAllLines(Service03LauncherPath, Service03Launcher(), "644", "root", "wheel"); edit = true; } if (edit) { Systemctl.DaemonReload(); if (Systemctl.IsActive(Service01PrepareUnit) == false) { Systemctl.Restart(Service01PrepareUnit); } if (Systemctl.IsActive(Service02MountUnit) == false) { Systemctl.Restart(Service02MountUnit); } if (Systemctl.IsActive(Service03LauncherUnit) == false) { Systemctl.Restart(Service03LauncherUnit); } } }
public static void CreateCertificateChain() { var file1 = $"{CaMainDirectory}/certs/ca.cert.pem"; var line1 = File.ReadAllLines(file1); var file2 = $"{CaIntermediateDirectory}/certs/intermediate.cert.pem"; var line2 = File.ReadAllLines(file2); line2.ToList().AddRange(line1); var chain = $"{CaIntermediateDirectory}/certs/ca-chain.cert.pem"; if (!File.Exists(chain)) { FileWithAcl.WriteAllLines(chain, line2, "644", "root", "wheel"); } }
private void SaveKeepalived(string publicIp, List <NodeModel> nodes) { ConsoleLogger.Log("[cluster] init keepalived"); const string keepalivedService = "keepalived.service"; if (Systemctl.IsActive(keepalivedService)) { ConsoleLogger.Log("[cluster] stop service"); Systemctl.Stop(keepalivedService); } ConsoleLogger.Log("[cluster] set configuration file"); var clusterInfo = ClusterConfiguration.GetClusterInfo(); var lines = new List <string> { "vrrp_script chk_haproxy {", " script \"killall -0 haproxy\"", " interval 2", " weight 2", "}", "", "vrrp_instance RH_INT {", $" interface {clusterInfo.NetworkInterface}", " state MASTER", " virtual_router_id 51", $" priority {clusterInfo.Priority}", " virtual_ipaddress {", $" {clusterInfo.VirtualIpAddress}", " }", " track_script {", " chk_haproxy", " }", "}", }; FileWithAcl.WriteAllLines(KeepalivedFileOutput, lines); //if(Systemctl.IsEnabled(keepalivedService) == false) { // Systemctl.Enable(keepalivedService); // ConsoleLogger.Log("[cluster] keepalived enabled"); //} //if(Systemctl.IsActive(keepalivedService) == false) { // Systemctl.Restart(keepalivedService); // ConsoleLogger.Log("[cluster] keepalived restarted"); //} Systemctl.Enable(keepalivedService); ConsoleLogger.Log("[cluster] keepalived enabled"); Systemctl.Restart(keepalivedService); ConsoleLogger.Log("[cluster] keepalived restarted"); }
private static void SetHostnameFile(GlusterConfigurationModel conf) { var linesToAdd = new List <string>(); foreach (var node in conf.Nodes) { linesToAdd.Add($"{node.Ip} {node.Hostname}.{Host.InternalDomainPrimary} {node.Hostname}"); } const string file = "/etc/hosts"; var hostsLines = File.ReadAllLines(file).ToList(); foreach (var line in linesToAdd) { if (!hostsLines.Contains(line)) { hostsLines.Add(line); } } FileWithAcl.WriteAllLines(file, hostsLines, "644", "root", "wheel"); }
public static void AddAcl(string dir) { var backupFile = SetAclBackupFilePath(dir); FileWithAcl.WriteAllLines(backupFile, GetDefaultTemplate(), "644", "root", "wheel"); var acls = ServiceModel.Settings; if (acls.Any(_ => _.Path == dir)) { return; } var model = new AclPersistentSettingModel { Path = dir, Acl = backupFile }; acls.Add(model); ServiceModel.Settings = acls; Save(ServiceModel); }
private static void WriteTimerTargetFile() { const string file = "/usr/lib64/systemd/system/tt.target"; if (File.Exists(file)) { File.Delete(file); } var timerText = new List <string> { "[Unit]", "Description=Description=Anthilla OS - Triggers and Timers Target", "After=etc-systemd-system-tt.target.wants.mount", "AllowIsolate=yes", "", "[Install]", "WantedBy=multi-user.target", "" }; FileWithAcl.WriteAllLines(file, timerText, "644", "root", "wheel"); }
public static void SaveTemplate(string name, string[] rules) { var file = $"{StoreDirTemplate}/{name}"; FileWithAcl.WriteAllLines(file, rules, "644", "root", "wheel"); }
public static void Set() { Stop(); #region [ named.conf generation ] if (File.Exists(MainFilePath)) { if (File.Exists(MainFilePathBackup)) { File.Delete(MainFilePathBackup); } File.Copy(MainFilePath, MainFilePathBackup); } var o = ServiceModel; var lines = new List <string>(); if (!string.IsNullOrEmpty(o.User) && !string.IsNullOrEmpty(o.Group)) { lines.Add($"user {o.User} {o.Group};"); } if (!string.IsNullOrEmpty(o.Processes)) { lines.Add($"worker_processes {o.Processes};"); } if (!string.IsNullOrEmpty(o.FileLimit)) { lines.Add($"worker_rlimit_nofile {o.FileLimit};"); } if (!string.IsNullOrEmpty(o.ErrorLog)) { lines.Add($"error_log {o.ErrorLog};"); } lines.Add(""); lines.Add("events {"); if (!string.IsNullOrEmpty(o.EventsWorkerConnections)) { lines.Add($" worker_connections {o.EventsWorkerConnections};"); } if (!string.IsNullOrEmpty(o.EventsMultiAccept)) { lines.Add($" multi_accept {o.EventsMultiAccept};"); } if (!string.IsNullOrEmpty(o.EventsUse)) { lines.Add($" use {o.EventsUse};"); } if (!string.IsNullOrEmpty(o.EventsAcceptMutex)) { lines.Add($" accept_mutex {o.EventsAcceptMutex};"); } lines.Add("}"); lines.Add(""); lines.Add("http {"); if (!string.IsNullOrEmpty(o.Http.Aio)) { lines.Add($" aio {o.Http.Aio};"); } if (!string.IsNullOrEmpty(o.Http.Directio)) { lines.Add($" directio {o.Http.Directio};"); } if (!string.IsNullOrEmpty(o.Http.AccessLog)) { lines.Add($" access_log {o.Http.AccessLog};"); } if (!string.IsNullOrEmpty(o.Http.KeepaliveTimeout)) { lines.Add($" keepalive_timeout {o.Http.KeepaliveTimeout};"); } if (!string.IsNullOrEmpty(o.Http.KeepaliveRequests)) { lines.Add($" keepalive_requests {o.Http.KeepaliveRequests};"); } if (!string.IsNullOrEmpty(o.Http.Sendfile)) { lines.Add($" sendfile {o.Http.Sendfile};"); } if (!string.IsNullOrEmpty(o.Http.SendfileMaxChunk)) { lines.Add($" sendfile_max_chunk {o.Http.SendfileMaxChunk};"); } if (!string.IsNullOrEmpty(o.Http.TcpNopush)) { lines.Add($" tcp_nopush {o.Http.TcpNopush};"); } if (!string.IsNullOrEmpty(o.Http.TcpNodelay)) { lines.Add($" tcp_nodelay {o.Http.TcpNodelay};"); } if (!string.IsNullOrEmpty(o.Http.Include)) { lines.Add($" include {o.Http.Include};"); } if (!string.IsNullOrEmpty(o.Http.DefaultType)) { lines.Add($" default_type {o.Http.DefaultType};"); } if (!string.IsNullOrEmpty(o.Http.LogFormat)) { lines.Add($" log_format {o.Http.LogFormat};"); } if (!string.IsNullOrEmpty(o.Http.RequestPoolSize)) { lines.Add($" request_pool_size {o.Http.RequestPoolSize};"); } if (!string.IsNullOrEmpty(o.Http.OutputBuffers)) { lines.Add($" output_buffers 1 {o.Http.OutputBuffers};"); } if (!string.IsNullOrEmpty(o.Http.PostponeOutput)) { lines.Add($" postpone_output {o.Http.PostponeOutput};"); } if (!string.IsNullOrEmpty(o.Http.ResetTimedoutConnection)) { lines.Add($" reset_timedout_connection {o.Http.ResetTimedoutConnection};"); } if (!string.IsNullOrEmpty(o.Http.SendTimeout)) { lines.Add($" send_timeout {o.Http.SendTimeout};"); } if (!string.IsNullOrEmpty(o.Http.ServerTokens)) { lines.Add($" server_tokens {o.Http.ServerTokens};"); } if (!string.IsNullOrEmpty(o.Http.ClientHeaderBufferSize)) { lines.Add($" client_header_buffer_size {o.Http.ClientHeaderBufferSize};"); } if (!string.IsNullOrEmpty(o.Http.ClientHeaderTimeout)) { lines.Add($" client_header_timeout {o.Http.ClientHeaderTimeout};"); } if (!string.IsNullOrEmpty(o.Http.ClientBodyBufferSize)) { lines.Add($" client_body_buffer_size {o.Http.ClientBodyBufferSize};"); } if (!string.IsNullOrEmpty(o.Http.ClientBodyTimeout)) { lines.Add($" client_body_timeout {o.Http.ClientBodyTimeout};"); } if (!string.IsNullOrEmpty(o.Http.LargeClientHeaderBuffers)) { lines.Add($" large_client_header_buffers {o.Http.LargeClientHeaderBuffers};"); } if (!string.IsNullOrEmpty(o.Http.Gzip)) { lines.Add($" gzip {o.Http.Gzip};"); } if (!string.IsNullOrEmpty(o.Http.GzipMinLength)) { lines.Add($" gzip_min_length {o.Http.GzipMinLength};"); } if (!string.IsNullOrEmpty(o.Http.GzipProxied)) { lines.Add($" gzip_proxied {o.Http.GzipProxied};"); } if (!string.IsNullOrEmpty(o.Http.GzipTypes)) { lines.Add($" gzip_types {o.Http.GzipTypes};"); } if (!string.IsNullOrEmpty(o.Http.GzipBuffers)) { lines.Add($" gzip_buffers 256 {o.Http.GzipBuffers};"); } if (!string.IsNullOrEmpty(o.Http.GzipCompLevel)) { lines.Add($" gzip_comp_level {o.Http.GzipCompLevel};"); } if (!string.IsNullOrEmpty(o.Http.GzipHttpVersion)) { lines.Add($" gzip_http_version {o.Http.GzipHttpVersion};"); } if (!string.IsNullOrEmpty(o.Http.GzipVary)) { lines.Add($" gzip_vary {o.Http.GzipHttpVersion};"); } if (!string.IsNullOrEmpty(o.Http.GzipDisable)) { lines.Add($" gzip_disable \"{o.Http.GzipDisable}\";"); } if (!string.IsNullOrEmpty(o.Http.OpenFileCacheMax) && !string.IsNullOrEmpty(o.Http.OpenFileCacheInactive)) { lines.Add($" open_file_cache max={o.Http.OpenFileCacheMax} inactive={o.Http.OpenFileCacheInactive};"); } if (!string.IsNullOrEmpty(o.Http.OpenFileCacheValid)) { lines.Add($" open_file_cache_valid {o.Http.OpenFileCacheValid};"); } if (!string.IsNullOrEmpty(o.Http.OpenFileCacheMinUses)) { lines.Add($" open_file_cache_min_uses {o.Http.OpenFileCacheMinUses};"); } if (!string.IsNullOrEmpty(o.Http.OpenFileCacheErrors)) { lines.Add($" open_file_cache_min_uses {o.Http.OpenFileCacheErrors};"); } if (!string.IsNullOrEmpty(o.Http.ServerNamesHashBucketSize)) { lines.Add($" server_names_hash_bucket_size {o.Http.ServerNamesHashBucketSize};"); } lines.Add(""); foreach (var upstr in o.Upstreams) { lines.Add($"upstream {upstr.Name} {{ server {upstr.Server} fail_timeout=0; }}"); } lines.Add(""); foreach (var s in o.Servers) { lines.Add("server {"); if (!string.IsNullOrEmpty(s.Listen)) { lines.Add($" listen {s.Listen};"); } if (!string.IsNullOrEmpty(s.ServerName)) { lines.Add($" server_name {s.ServerName};"); } if (!string.IsNullOrEmpty(s.ServerTokens)) { lines.Add($" server_tokens {s.ServerTokens};"); } if (!string.IsNullOrEmpty(s.Root)) { lines.Add($" root {s.Root};"); } if (!string.IsNullOrEmpty(s.ClientMaxBodySize)) { lines.Add($" client_max_body_size {s.ClientMaxBodySize};"); } if (!string.IsNullOrEmpty(s.ReturnRedirect)) { lines.Add($" return {s.ReturnRedirect};"); } if (!string.IsNullOrEmpty(s.SslCertificate)) { lines.Add($" ssl_certificate {s.SslCertificate};"); } if (!string.IsNullOrEmpty(s.SslTrustedCertificate)) { lines.Add($" ssl_trusted_certificate {s.SslTrustedCertificate};"); } if (!string.IsNullOrEmpty(s.SslCertificateKey)) { lines.Add($" ssl_certificate_key {s.SslCertificateKey};"); } if (!string.IsNullOrEmpty(s.AccessLog)) { lines.Add($" access_log {s.AccessLog};"); } if (!string.IsNullOrEmpty(s.ErrorLog)) { lines.Add($" error_log {s.ErrorLog};"); } lines.Add(""); foreach (var l in s.Locations) { lines.Add($" location {l.Path} {{"); if (!string.IsNullOrEmpty(l.ProxyPass)) { lines.Add($" proxy_pass {l.ProxyPass};"); } if (!string.IsNullOrEmpty(l.ProxyPassHeader)) { lines.Add($" proxy_pass_header {l.ProxyPassHeader};"); } if (!string.IsNullOrEmpty(l.ProxyReadTimeout)) { lines.Add($" proxy_read_timeout {l.ProxyReadTimeout};"); } if (!string.IsNullOrEmpty(l.ProxyConnectTimeout)) { lines.Add($" proxy_connect_timeout {l.ProxyConnectTimeout};"); } lines.Add(" proxy_set_header Host $host;"); lines.Add(" proxy_set_header X-Frame-Options SAMEORIGIN;"); lines.Add(" proxy_set_header X-Real-IP $remote_addr;"); lines.Add(" proxy_set_header X-Forwarded-Proto $scheme;"); lines.Add(" proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;"); lines.Add(" proxy_set_header Connection \"\";"); if (!string.IsNullOrEmpty(l.ProxyBuffering)) { lines.Add($" proxy_buffering {l.ProxyBuffering};"); } if (!string.IsNullOrEmpty(l.ClientMaxBodySize)) { lines.Add($" client_max_body_size {l.ClientMaxBodySize};"); } if (!string.IsNullOrEmpty(l.ProxyRedirect)) { lines.Add($" proxy_redirect {l.ProxyRedirect};"); } if (!string.IsNullOrEmpty(l.ProxyHttpVersion)) { lines.Add($" proxy_http_version {l.ProxyHttpVersion};"); } if (!string.IsNullOrEmpty(l.Aio)) { lines.Add($" aio {l.Aio};"); } if (!string.IsNullOrEmpty(l.ProxySslSessionReuse)) { lines.Add($" proxy_ssl_session_reuse {l.ProxySslSessionReuse};"); } lines.Add(" }"); lines.Add(""); } lines.Add("}"); } lines.Add("}"); FileWithAcl.WriteAllLines(MainFilePath, lines, "644", "nginx", "nginx"); SetParametersFiles(); #endregion Start(); }
public static void Set() { Enable(); Stop(); #region [ syslog-ng.conf generation ] if (File.Exists(MainFilePath)) { if (File.Exists(MainFilePathBackup)) { File.Delete(MainFilePathBackup); } File.Copy(MainFilePath, MainFilePathBackup); } var lines = new List <string> { "@version: 3.7", "@include \"scl.conf\"", "options {" }; var options = ServiceModel; lines.Add($"threaded({options.Threaded});"); lines.Add($"chain_hostnames({options.ChainHostname});"); lines.Add($"stats_freq({options.StatsFrequency});"); lines.Add($"mark_freq({options.MarkFrequency});"); lines.Add("bad_hostname(\"^gconfd$\");"); lines.Add($"check_hostname({options.CheckHostname});"); lines.Add($"create_dirs({options.CreateDirectories});"); lines.Add($"dir_perm({options.DirAcl});"); lines.Add($"dns_cache({options.DnsCache});"); lines.Add($"keep_hostname({options.KeepHostname});"); lines.Add($"perm({options.Acl});"); lines.Add("time_reap(30);"); lines.Add("time_reopen(10);"); lines.Add($"use_dns({options.UseDns});"); lines.Add($"use_fqdn({options.UseFqdn});"); lines.Add("flush_lines(0);"); lines.Add("};"); lines.Add(""); lines.Add("source s_Int0 {internal();};"); lines.Add("source s_Net1 {"); lines.Add($"udp(port({options.PortLevelApplication}) flags(\"sanitize-utf8\",\"syslog-protocol\"));"); lines.Add($"tcp(port({options.PortLevelApplication}) flags(\"sanitize-utf8\",\"syslog-protocol\"));"); lines.Add("};"); lines.Add("source s_Net2 {"); lines.Add($"udp(port({options.PortLevelSecurity}) flags(\"sanitize-utf8\",\"syslog-protocol\"));"); lines.Add($"tcp(port({options.PortLevelSecurity}) flags(\"sanitize-utf8\",\"syslog-protocol\"));"); lines.Add("};"); lines.Add("source s_Net3 {"); lines.Add($"udp(port({options.PortLevelSystem}) flags(\"sanitize-utf8\",\"syslog-protocol\"));"); lines.Add($"tcp(port({options.PortLevelSystem}) flags(\"sanitize-utf8\",\"syslog-protocol\"));"); lines.Add("};"); lines.Add(""); lines.Add("destination d_Net1 {{ file(\"/var/log/00_HOSTS_00/$HOST/$YEAR/$MONTH/$DAY/Application.log\" owner(root) group(wheel) perm(0644) dir_perm(0755) create_dirs(yes)); }};"); lines.Add("destination d_Net2 { file(\"/var/log/00_HOSTS_00/$HOST/$YEAR/$MONTH/$DAY/Security.log\" owner(root) group(wheel) perm(0644) dir_perm(0755) create_dirs(yes)); };"); lines.Add("destination d_Net3 { file(\"/var/log/00_HOSTS_00/$HOST/$YEAR/$MONTH/$DAY/System.log\" owner(root) group(wheel) perm(0644) dir_perm(0755) create_dirs(yes)); };"); lines.Add("destination d_Int0 { file(\"/var/log/00_HOSTS_00/$HOST/$YEAR/$MONTH/$DAY/Int0.log\" owner(root) group(wheel) perm(0644) dir_perm(0755) create_dirs(yes)); };"); lines.Add(""); lines.Add("log {source(s_Net1); destination(d_Net1);};"); lines.Add("log {source(s_Net2); destination(d_Net2);};"); lines.Add("log {source(s_Net3); destination(d_Net3);};"); lines.Add("log {source(s_Int0); destination(d_Int0);};"); lines.Add(""); FileWithAcl.WriteAllLines(MainFilePath, lines, "644", "root", "wheel"); #endregion Start(); }
public static void Set() { Enable(); Stop(); #region [ smb.conf generation ] if (File.Exists(MainFilePath)) { if (File.Exists(MainFilePathBackup)) { File.Delete(MainFilePathBackup); } File.Copy(MainFilePath, MainFilePathBackup); } var global = ServiceModel; var lines = new List <string> { "[global]", $"dos charset = {global.DosCharset}", $"workgroup = {global.Workgroup}", $"server string = {global.ServerString}", $"map to guest = {global.MapToGuest}", $"obey pam restrictions = {global.ObeyPamRestrictions}", $"guest account = {global.GuestAccount}", $"pam password change = {global.PamPasswordChange}", $"passwd program = {global.PasswdProgram}", $"unix password sync = {global.UnixPasswordSync}", $"reset on zero vc = {global.ResetOnZeroVc}", $"hostname lookups = {global.HostnameLookups}", $"load printers = {global.LoadPrinters}", $"printcap name = {global.PrintcapName}", $"disable spoolss = {global.DisableSpoolss}", $"template shell = {global.TemplateShell}", $"winbind enum users = {global.WinbindEnumUsers}", $"winbind enum groups = {global.WinbindEnumGroups}", $"winbind use default domain = {global.WinbindUseDefaultDomain}", $"winbind nss info = {global.WinbindNssInfo}", $"winbind refresh tickets = {global.WinbindRefreshTickets}", $"winbind normalize names = {global.WinbindNormalizeNames}", $"recycle:touch = {global.RecycleTouch}", $"recycle:keeptree = {global.RecycleKeeptree}", $"recycle:repository = {global.RecycleRepository}", $"nfs4:chown = {global.Nfs4Chown}", $"nfs4:acedup = {global.Nfs4Acedup}", $"nfs4:mode = {global.Nfs4Mode}", $"shadow:format = {global.ShadowFormat}", $"shadow:localtime = {global.ShadowLocaltime}", $"shadow:sort = {global.ShadowSort}", $"shadow:snapdir = {global.ShadowSnapdir}", $"rpc_server:default = {global.RpcServerDefault}", $"rpc_server:svcctl = {global.RpcServerSvcctl}", $"rpc_server:srvsvc = {global.RpcServerSrvsvc}", $"rpc_server:eventlog = {global.RpcServerEventlog}", $"rpc_server:ntsvcs = {global.RpcServerNtsvcs}", $"rpc_server:winreg = {global.RpcServerWinreg}", $"rpc_server:spoolss = {global.RpcServerSpoolss}", $"rpc_daemon:spoolssd = {global.RpcDaemonSpoolssd}", $"rpc_server:tcpip = {global.RpcServerTcpip}", $"idmap config * : backend = {global.IdmapConfigBackend}", $"read only = {global.ReadOnly}", $"guest ok = {global.GuestOk}", $"aio read size = {global.AioReadSize}", $"aio write size = {global.AioWriteSize}", $"ea support = {global.EaSupport}", $"directory name cache size = {global.DirectoryNameCacheSize}", $"case sensitive = {global.CaseSensitive}", $"map readonly = {global.MapReadonly}", $"store dos attributes = {global.StoreDosAttributes}", $"wide links = {global.WideLinks}", $"dos filetime resolution = {global.DosFiletimeResolution}", $"vfs objects = {global.VfsObjects}", "" }; var resources = ServiceModel.Resources; foreach (var resource in resources) { lines.Add($"[{resource.Name}]"); if (!string.IsNullOrEmpty(resource.Comment)) { lines.Add($"comment = {resource.Comment}"); } lines.Add($"path = {resource.Path}"); lines.Add(""); } FileWithAcl.WriteAllLines(MainFilePath, lines, "644", "root", "wheel"); #endregion Start(); }
public AssetClusterModule() { Get["/cluster"] = x => { var syncedMachines = ClusterConfiguration.GetNodes(); var config = ClusterConfiguration.GetClusterInfo(); foreach (var node in syncedMachines) { var services = _api.Get <List <RssdpServiceModel> >(node.ModelUrl + "device/services"); node.Services = services; } var importPortMapping = syncedMachines .Select(_ => _.Services) .Merge() .Select(_ => _.Name) .ToHashSet() .Select(_ => new Cluster.PortMapping { ServiceName = _, ServicePort = "", VirtualPort = "" }) .ToList() ; var existingPortMapping = config.PortMapping.ToList(); foreach (var i in importPortMapping) { if (existingPortMapping.FirstOrDefault(_ => _.ServiceName == i.ServiceName) == null) { existingPortMapping.Add(i); } } config.PortMapping = existingPortMapping.ToList(); var model = new PageAssetClusterModel { Info = config, ClusterNodes = syncedMachines.OrderBy(_ => _.Hostname).ThenBy(_ => _.PublicIp).ToList(), NetworkAdapters = IPv4.GetAllLocalDescription().ToList() }; return(JsonConvert.SerializeObject(model)); }; Post["/cluster/save"] = x => { string config = Request.Form.Config; string ip = Request.Form.Ip; var model = JsonConvert.DeserializeObject <List <NodeModel> >(config); var model2 = JsonConvert.DeserializeObject <Cluster.Configuration>(ip); ClusterConfiguration.SaveNodes(model); ClusterConfiguration.SaveConfiguration(model2); new Do().ClusterChanges(); DeployClusterConfiguration(); return(HttpStatusCode.OK); }; Post["Accept Configuration", "/cluster/accept"] = x => { string file = Request.Form.File; string content = Request.Form.Content; if (string.IsNullOrEmpty(file)) { return(HttpStatusCode.BadRequest); } if (string.IsNullOrEmpty(content)) { return(HttpStatusCode.BadRequest); } ConsoleLogger.Log($"[cluster] received config for file: {file}"); DirectoryWatcherCluster.Stop(); try { FileWithAcl.WriteAllText(file, content, "644", "root", "wheel"); } catch (Exception) { ConsoleLogger.Warn(""); DirectoryWatcherCluster.Start(); return(HttpStatusCode.InternalServerError); } DirectoryWatcherCluster.Start(); var dict = Dicts.DirsAndServices; if (dict.ContainsKey(file)) { ConsoleLogger.Log("[cluster] restart service bind to config file"); var services = dict[file]; foreach (var svc in services) { Systemctl.Enable(svc); Systemctl.Restart(svc); } } ConsoleLogger.Log("[cluster] apply changes after new config"); new Do().HostChanges(); new Do().NetworkChanges(); DeployClusterConfiguration(); return(HttpStatusCode.OK); }; #region [ Handshake + cluster init ] Post["/asset/handshake/start", true] = async(x, ct) => { string conf = Request.Form.HostJson; var remoteNode = JsonConvert.DeserializeObject <NodeModel>(conf); if (remoteNode == null) { return(HttpStatusCode.InternalServerError); } const string pathToPrivateKey = "/root/.ssh/id_rsa"; const string pathToPublicKey = "/root/.ssh/id_rsa.pub"; if (!File.Exists(pathToPublicKey)) { var k = Bash.Execute($"ssh-keygen -t rsa -N '' -f {pathToPrivateKey}"); ConsoleLogger.Log(k); } var key = File.ReadAllText(pathToPublicKey); if (string.IsNullOrEmpty(key)) { return(HttpStatusCode.InternalServerError); } var dict = new Dictionary <string, string> { { "ApplePie", key } }; var r = new ApiConsumer().Post($"{remoteNode.ModelUrl}asset/handshake", dict); if (r != HttpStatusCode.OK) { return(HttpStatusCode.InternalServerError); } //ho fatto l'handshake, quindi il nodo richiesto è pronto per essere integrato nel cluster //1. controllo la configurazione var clusterConfiguration = ClusterConfiguration.GetClusterInfo(); if (string.IsNullOrEmpty(clusterConfiguration.Guid)) { clusterConfiguration.Guid = Guid.NewGuid().ToString(); } if (string.IsNullOrEmpty(clusterConfiguration.Priority)) { clusterConfiguration.Priority = "100"; } if (string.IsNullOrEmpty(clusterConfiguration.NetworkInterface)) { clusterConfiguration.NetworkInterface = ""; } if (string.IsNullOrEmpty(clusterConfiguration.VirtualIpAddress)) { clusterConfiguration.VirtualIpAddress = ""; } //2. salvo la configurazione ClusterConfiguration.SaveConfiguration(clusterConfiguration); //3. controllo i nodi presenti nella configurazione var clusterNodes = ClusterConfiguration.GetNodes(); var iplocals = IPv4.GetAllLocalAddress().ToList(); var disc = await ServiceDiscovery.Rssdp.Discover(); //4. per prima cosa controllo l'host locale var localNode = disc.FirstOrDefault(_ => iplocals.Contains(_.PublicIp)); //5. se non c'è lo aggiungo if (clusterNodes.FirstOrDefault(_ => _.MachineUid == localNode.MachineUid && _.PublicIp == localNode.PublicIp) == null) { clusterNodes.Add(localNode); } //7. se non c'è lo aggiungo if (clusterNodes.FirstOrDefault(_ => _.MachineUid == remoteNode.MachineUid && _.PublicIp == remoteNode.PublicIp) == null) { clusterNodes.Add(remoteNode); } //8. salvo la configurazione dei nodi ClusterConfiguration.SaveNodes(clusterNodes); //9. riavvio/avvio il servizio di cluster new Do().ClusterChanges(); DeployClusterConfiguration(); return(HttpStatusCode.OK); }; Post["/asset/handshake"] = x => { string apple = Request.Form.ApplePie; var info = apple.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries); if (info.Length < 2) { return(HttpStatusCode.InternalServerError); } var key = info[0]; var remoteUser = info[1]; const string user = "******"; var model = new AuthorizedKeyModel { RemoteUser = remoteUser, User = user, KeyValue = key }; var authorizedKeysConfiguration = new AuthorizedKeysConfiguration(); authorizedKeysConfiguration.AddKey(model); try { DirectoryWithAcl.CreateDirectory("/root/.ssh"); const string authorizedKeysPath = "/root/.ssh/authorized_keys"; if (File.Exists(authorizedKeysPath)) { var f = File.ReadAllText(authorizedKeysPath); if (!f.Contains(apple)) { FileWithAcl.AppendAllLines(authorizedKeysPath, new List <string> { apple }, "644", "root", "wheel"); } } else { FileWithAcl.WriteAllLines(authorizedKeysPath, new List <string> { apple }, "644", "root", "wheel"); } Bash.Execute($"chmod 600 {authorizedKeysPath}", false); Bash.Execute($"chown {user}:{user} {authorizedKeysPath}", false); return(HttpStatusCode.OK); } catch (Exception ex) { ConsoleLogger.Log(ex); return(HttpStatusCode.InternalServerError); } }; Post["/cluster/deploy"] = x => { var clusterConfiguration = Request.Form.Cluster; Cluster.DeployConf model = Newtonsoft.Json.JsonConvert.DeserializeObject <Cluster.DeployConf>(clusterConfiguration); ClusterConfiguration.SaveConfiguration(model.Configuration); ClusterConfiguration.SaveNodes(model.Nodes); new Do().ClusterChanges(); return(HttpStatusCode.OK); }; //Post["/asset/wol"] = x => { // string mac = Request.Form.MacAddress; // CommandLauncher.Launch("wol", new Dictionary<string, string> { { "$mac", mac } }); // return HttpStatusCode.OK; //}; //Get["/asset/nmasp/{ip}"] = x => { // string ip = x.ip; // var result = CommandLauncher.Launch("nmap-ip-fast", new Dictionary<string, string> { { "$ip", ip } }).Where(_ => !_.Contains("MAC Address")).Skip(5).Reverse().Skip(1).Reverse(); // var list = new List<NmapScanStatus>(); // foreach(var r in result) { // var a = r.SplitToList(" ").ToArray(); // var mo = new NmapScanStatus { // Protocol = a[0], // Status = a[1], // Type = a[2] // }; // list.Add(mo); // } // list = list.OrderBy(_ => _.Protocol).ToList(); // return JsonConvert.SerializeObject(list); //}; #endregion }
public static void Set() { Enable(); Stop(); if (File.Exists(MainFilePath)) { if (File.Exists(MainFilePathBackup)) { File.Delete(MainFilePathBackup); } File.Copy(MainFilePath, MainFilePathBackup); } #region [ fake journald.conf generation ] var fakeOptions = ServiceModel; fakeOptions.Storage = "volatile"; var fakeLines = new List <string> { "[Journal]", fakeOptions.Storage == "#" ? "#Storage=" : $"Storage={fakeOptions.Storage}", fakeOptions.Compress == "#" ? "#Compress=" : $"Compress={fakeOptions.Compress}", fakeOptions.Seal == "#" ? "#Seal=" : $"Seal={fakeOptions.Seal}", fakeOptions.SplitMode == "#" ? "#SplitMode=" : $"SplitMode={fakeOptions.SplitMode}", fakeOptions.SyncIntervalSec == "#" ? "#SyncIntervalSec=" : $"SyncIntervalSec={fakeOptions.SyncIntervalSec}", fakeOptions.RateLimitInterval == "#" ? "#RateLimitInterval=" : $"RateLimitInterval={fakeOptions.RateLimitInterval}", fakeOptions.RateLimitBurst == "#" ? "#RateLimitBurst=" : $"RateLimitBurst={fakeOptions.RateLimitBurst}", fakeOptions.SystemMaxUse == "#" ? "#SystemMaxUse=" : $"SystemMaxUse={fakeOptions.SystemMaxUse}", fakeOptions.SystemKeepFree == "#" ? "#SystemKeepFree=" : $"SystemKeepFree={fakeOptions.SystemKeepFree}", fakeOptions.SystemMaxFileSize == "#" ? "#SystemMaxFileSize=" : $"SystemMaxFileSize={fakeOptions.SystemMaxFileSize}", fakeOptions.RuntimeMaxUse == "#" ? "#RuntimeMaxUse=" : $"RuntimeMaxUse={fakeOptions.RuntimeMaxUse}", fakeOptions.RuntimeKeepFree == "#" ? "#RuntimeKeepFree=" : $"RuntimeKeepFree={fakeOptions.RuntimeKeepFree}", fakeOptions.RuntimeMaxFileSize == "#" ? "#RuntimeMaxFileSize=" : $"RuntimeMaxFileSize={fakeOptions.RuntimeMaxFileSize}", fakeOptions.MaxRetentionSec == "#" ? "#MaxRetentionSec=" : $"MaxRetentionSec={fakeOptions.MaxRetentionSec}", fakeOptions.MaxFileSec == "#" ? "#MaxFileSec=" : $"MaxFileSec={fakeOptions.MaxFileSec}", fakeOptions.ForwardToSyslog == "#" ? "#ForwardToSyslog=" : $"ForwardToSyslog={fakeOptions.ForwardToSyslog}", fakeOptions.ForwardToKMsg == "#" ? "#ForwardToKMsg=" : $"ForwardToKMsg={fakeOptions.ForwardToKMsg}", fakeOptions.ForwardToConsole == "#" ? "#ForwardToConsole=" : $"ForwardToConsole={fakeOptions.ForwardToConsole}", fakeOptions.ForwardToWall == "#" ? "#ForwardToWall=" : $"ForwardToWall={fakeOptions.ForwardToWall}", fakeOptions.TtyPath == "#" ? "#TTYPath=" : $"TTYPath={fakeOptions.TtyPath}", fakeOptions.MaxLevelStore == "#" ? "#MaxLevelStore=" : $"MaxLevelStore={fakeOptions.MaxLevelStore}", fakeOptions.MaxLevelSyslog == "#" ? "#MaxLevelSyslog=" : $"MaxLevelSyslog={fakeOptions.MaxLevelSyslog}", fakeOptions.MaxLevelKMsg == "#" ? "#MaxLevelKMsg=" : $"MaxLevelKMsg={fakeOptions.MaxLevelKMsg}", fakeOptions.MaxLevelConsole == "#" ? "#MaxLevelConsole=" : $"MaxLevelConsole={fakeOptions.MaxLevelConsole}", fakeOptions.MaxLevelWall == "#" ? "#MaxLevelWall=" : $"MaxLevelWall={fakeOptions.MaxLevelWall}" }; FileWithAcl.WriteAllLines(MainFilePath, fakeLines, "644", "root", "wheel"); #endregion Start(); Remount(); #region [ journald.conf generation ] var lines = new List <string> { "[Journal]" }; var options = ServiceModel; lines.Add(options.Storage == "#" ? "#Storage=" : $"Storage={options.Storage}"); lines.Add(options.Compress == "#" ? "#Compress=" : $"Compress={options.Compress}"); lines.Add(options.Seal == "#" ? "#Seal=" : $"Seal={options.Seal}"); lines.Add(options.SplitMode == "#" ? "#SplitMode=" : $"SplitMode={options.SplitMode}"); lines.Add(options.SyncIntervalSec == "#" ? "#SyncIntervalSec=" : $"SyncIntervalSec={options.SyncIntervalSec}"); lines.Add(options.RateLimitInterval == "#" ? "#RateLimitInterval=" : $"RateLimitInterval={options.RateLimitInterval}"); lines.Add(options.RateLimitBurst == "#" ? "#RateLimitBurst=" : $"RateLimitBurst={options.RateLimitBurst}"); lines.Add(options.SystemMaxUse == "#" ? "#SystemMaxUse=" : $"SystemMaxUse={options.SystemMaxUse}"); lines.Add(options.SystemKeepFree == "#" ? "#SystemKeepFree=" : $"SystemKeepFree={options.SystemKeepFree}"); lines.Add(options.SystemMaxFileSize == "#" ? "#SystemMaxFileSize=" : $"SystemMaxFileSize={options.SystemMaxFileSize}"); lines.Add(options.RuntimeMaxUse == "#" ? "#RuntimeMaxUse=" : $"RuntimeMaxUse={options.RuntimeMaxUse}"); lines.Add(options.RuntimeKeepFree == "#" ? "#RuntimeKeepFree=" : $"RuntimeKeepFree={options.RuntimeKeepFree}"); lines.Add(options.RuntimeMaxFileSize == "#" ? "#RuntimeMaxFileSize=" : $"RuntimeMaxFileSize={options.RuntimeMaxFileSize}"); lines.Add(options.MaxRetentionSec == "#" ? "#MaxRetentionSec=" : $"MaxRetentionSec={options.MaxRetentionSec}"); lines.Add(options.MaxFileSec == "#" ? "#MaxFileSec=" : $"MaxFileSec={options.MaxFileSec}"); lines.Add(options.ForwardToSyslog == "#" ? "#ForwardToSyslog=" : $"ForwardToSyslog={options.ForwardToSyslog}"); lines.Add(options.ForwardToKMsg == "#" ? "#ForwardToKMsg=" : $"ForwardToKMsg={options.ForwardToKMsg}"); lines.Add(options.ForwardToConsole == "#" ? "#ForwardToConsole=" : $"ForwardToConsole={options.ForwardToConsole}"); lines.Add(options.ForwardToWall == "#" ? "#ForwardToWall=" : $"ForwardToWall={options.ForwardToWall}"); lines.Add(options.TtyPath == "#" ? "#TTYPath=" : $"TTYPath={options.TtyPath}"); lines.Add(options.MaxLevelStore == "#" ? "#MaxLevelStore=" : $"MaxLevelStore={options.MaxLevelStore}"); lines.Add(options.MaxLevelSyslog == "#" ? "#MaxLevelSyslog=" : $"MaxLevelSyslog={options.MaxLevelSyslog}"); lines.Add(options.MaxLevelKMsg == "#" ? "#MaxLevelKMsg=" : $"MaxLevelKMsg={options.MaxLevelKMsg}"); lines.Add(options.MaxLevelConsole == "#" ? "#MaxLevelConsole=" : $"MaxLevelConsole={options.MaxLevelConsole}"); lines.Add(options.MaxLevelWall == "#" ? "#MaxLevelWall=" : $"MaxLevelWall={options.MaxLevelWall}"); FileWithAcl.WriteAllLines(MainFilePath, lines, "644", "root", "wheel"); #endregion Start(); }
public static void Set() { Enable(); Stop(); #region [ named.conf generation ] if (File.Exists(MainFilePath)) { if (File.Exists(MainFilePathBackup)) { File.Delete(MainFilePathBackup); } File.Copy(MainFilePath, MainFilePathBackup); } var lines = new List <string>(); var options = ServiceModel; lines.Add($"Port {options.Port}"); lines.Add($"PermitRootLogin {options.PermitRootLogin}"); lines.Add($"PermitTunnel {options.PermitTunnel}"); lines.Add($"MaxAuthTries {options.MaxAuthTries}"); lines.Add($"MaxSessions {options.MaxSessions}"); lines.Add($"RsaAuthentication {options.RsaAuthentication}"); lines.Add($"PubkeyAuthentication {options.PubkeyAuthentication}"); lines.Add($"UsePam {options.UsePam}"); lines.Add("#AddressFamily any"); lines.Add("#ListenAddress 0.0.0.0"); lines.Add("#ListenAddress ::"); lines.Add("#Protocol 2"); lines.Add("#HostKey /etc/ssh/ssh_host_key"); lines.Add("#HostKey /etc/ssh/ssh_host_rsa_key"); lines.Add("#HostKey /etc/ssh/ssh_host_dsa_key"); lines.Add("#HostKey /etc/ssh/ssh_host_ecdsa_key"); lines.Add("#HostKey /etc/ssh/ssh_host_ed25519_key"); lines.Add("#KeyRegenerationInterval 1h"); lines.Add("#ServerKeyBits 1024"); lines.Add("#RekeyLimit default none"); lines.Add("#SyslogFacility AUTH"); lines.Add("#LogLevel INFO"); lines.Add("#LoginGraceTime 2m"); lines.Add("#StrictModes yes"); lines.Add("#AuthorizedKeysFile .ssh/authorized_keys"); lines.Add("#AuthorizedPrincipalsFile none"); lines.Add("#AuthorizedKeysCommand none"); lines.Add("#AuthorizedKeysCommandUser nobody"); lines.Add("#RhostsRSAAuthentication no"); lines.Add("#HostbasedAuthentication no"); lines.Add("#IgnoreUserKnownHosts no"); lines.Add("#IgnoreRhosts yes"); lines.Add("PasswordAuthentication no"); lines.Add("#PermitEmptyPasswords no"); lines.Add("#ChallengeResponseAuthentication yes"); lines.Add("#KerberosAuthentication no"); lines.Add("#KerberosOrLocalPasswd yes"); lines.Add("#KerberosTicketCleanup yes"); lines.Add("#KerberosGetAFSToken no"); lines.Add("#GSSAPIAuthentication no"); lines.Add("#GSSAPICleanupCredentials yes"); lines.Add("#AllowAgentForwarding yes"); lines.Add("#AllowTcpForwarding yes"); lines.Add("#GatewayPorts no"); lines.Add("#X11Forwarding no"); lines.Add("#X11DisplayOffset 10"); lines.Add("#X11UseLocalhost yes"); lines.Add("#PermitTTY yes"); lines.Add("PrintMotd no"); lines.Add("PrintLastLog no"); lines.Add("#TCPKeepAlive yes"); lines.Add("#UseLogin no"); lines.Add("#UsePrivilegeSeparation sandbox"); lines.Add("#PermitUserEnvironment no"); lines.Add("#Compression delayed"); lines.Add("#ClientAliveInterval 0"); lines.Add("#ClientAliveCountMax 3"); lines.Add("#UseDNS no"); lines.Add("#PidFile /run/sshd.pid"); lines.Add("#MaxStartups 10:30:100"); lines.Add("#PermitTunnel no"); lines.Add("#ChrootDirectory none"); lines.Add("#VersionAddendum none"); lines.Add("#Banner none"); lines.Add("#UseLPK yes"); lines.Add("#LpkLdapConf /etc/ldap.conf"); lines.Add("#LpkServers ldap://10.1.7.1/ ldap://10.1.7.2/"); lines.Add("#LpkUserDN ou=users,dc=phear,dc=org"); lines.Add("#LpkGroupDN ou=groups,dc=phear,dc=org"); lines.Add("#LpkBindDN cn=Manager,dc=phear,dc=org"); lines.Add("#LpkBindPw secret"); lines.Add("#LpkServerGroup mail"); lines.Add("#LpkFilter (hostAccess=master.phear.org)"); lines.Add("#LpkForceTLS no"); lines.Add("#LpkSearchTimelimit 3"); lines.Add("#LpkBindTimelimit 3"); lines.Add("#LpkPubKeyAttr sshPublicKey"); lines.Add("Subsystem sftp /usr/lib64/misc/sftp"); lines.Add("AcceptEnv LANG LC_*"); FileWithAcl.WriteAllLines(MainFilePath, lines, "644", "root", "wheel"); #endregion Start(); }
public static void Set() { Stop(); #region [ dhcpd.conf generation ] var lines = new List <string>(); var options = ServiceModel; if (!string.IsNullOrEmpty(options.KeyName) && !string.IsNullOrEmpty(options.KeySecret)) { lines.Add($"key \"{options.KeyName}\" {{"); lines.Add("algorithm hmac-md5;"); lines.Add($"secret \"{options.KeySecret}\";"); lines.Add("};"); } lines.Add(""); var classes = options.Classes; foreach (var cls in classes) { lines.Add($"class \"{cls.Name}\" {{"); lines.Add($"match if binary-to-ascii(16,8,\":\",substring(hardware, 1, 2)) = \"{cls.VendorMacAddress}\";"); lines.Add("}"); } lines.Add(""); lines.Add("authoritative;"); foreach (var allow in options.Allow) { lines.Add($"allow {allow};"); } if (!string.IsNullOrEmpty(options.UpdateStaticLeases)) { lines.Add($"update-static-leases {options.UpdateStaticLeases};"); } if (!string.IsNullOrEmpty(options.UpdateConflictDetection)) { lines.Add($"update-conflict-detection {options.UpdateConflictDetection};"); } if (!string.IsNullOrEmpty(options.UseHostDeclNames)) { lines.Add($"use-host-decl-names {options.UseHostDeclNames};"); } if (!string.IsNullOrEmpty(options.DoForwardUpdates)) { lines.Add($"do-forward-updates {options.DoForwardUpdates};"); } if (!string.IsNullOrEmpty(options.DoReverseUpdates)) { lines.Add($"do-reverse-updates {options.DoReverseUpdates};"); } if (!string.IsNullOrEmpty(options.LogFacility)) { lines.Add($"log-facility {options.LogFacility};"); } if (!string.IsNullOrEmpty(options.OptionRouters)) { lines.Add($"option routers {options.OptionRouters};"); } if (!string.IsNullOrEmpty(options.OptionLocalProxy)) { lines.Add($"option local-proxy-config code {options.OptionLocalProxy};"); } if (!string.IsNullOrEmpty(options.OptionDomainName)) { lines.Add($"option domain-name \"{options.OptionDomainName}\";"); } if (!string.IsNullOrEmpty(options.ZoneName) && !string.IsNullOrEmpty(options.ZonePrimaryAddress)) { lines.Add($"zone {options.ZoneName} {{ primary {options.ZonePrimaryAddress}; }}"); } if (!string.IsNullOrEmpty(options.DdnsUpdateStyle)) { lines.Add($"ddns-update-style {options.DdnsUpdateStyle};"); } if (!string.IsNullOrEmpty(options.DdnsUpdates)) { lines.Add($"ddns-updates {options.DdnsUpdates};"); } if (!string.IsNullOrEmpty(options.DdnsDomainName)) { lines.Add($"ddns-domainname \"{options.DdnsDomainName}\";"); } if (!string.IsNullOrEmpty(options.DdnsRevDomainName)) { lines.Add($"ddns-rev-domainname \"{options.DdnsRevDomainName}\";"); } if (!string.IsNullOrEmpty(options.DefaultLeaseTime)) { lines.Add($"default-lease-time {options.DefaultLeaseTime};"); } if (!string.IsNullOrEmpty(options.MaxLeaseTime)) { lines.Add($"max-lease-time {options.MaxLeaseTime};"); } lines.Add(""); foreach (var subnet in options.Subnets) { lines.Add($"subnet {subnet.SubnetIpFamily} netmask {subnet.SubnetIpMask} {{"); if (!string.IsNullOrEmpty(subnet.SubnetOptionRouters)) { lines.Add($"option routers {subnet.SubnetOptionRouters}"); } if (!string.IsNullOrEmpty(subnet.SubnetNtpServers)) { lines.Add($"option ntp-servers {subnet.SubnetNtpServers}"); } if (!string.IsNullOrEmpty(subnet.SubnetTimeServers)) { lines.Add($"option time-servers {subnet.SubnetTimeServers}"); } if (!string.IsNullOrEmpty(subnet.SubnetDomainNameServers)) { lines.Add($"option domain-name-servers {subnet.SubnetDomainNameServers}"); } if (!string.IsNullOrEmpty(subnet.SubnetBroadcastAddress)) { lines.Add($"option broadcast-address {subnet.SubnetBroadcastAddress}"); } if (!string.IsNullOrEmpty(subnet.SubnetMask)) { lines.Add($"option subnet-mask {subnet.SubnetMask}"); } if (!string.IsNullOrEmpty(subnet.ZoneName) && !string.IsNullOrEmpty(subnet.ZonePrimaryAddress)) { lines.Add($"zone {subnet.ZoneName} {{ primary {subnet.ZonePrimaryAddress}; }}"); } lines.Add(""); var pools = subnet.Pools; foreach (var pool in pools) { lines.Add("pool {"); if (!string.IsNullOrEmpty(pool.ClassName)) { lines.Add($"allow members of \"{pool.ClassName}\";"); } if (!string.IsNullOrEmpty(pool.PoolRangeEnd) && !string.IsNullOrEmpty(pool.PoolRangeStart)) { lines.Add($"range {pool.PoolRangeStart} {pool.PoolRangeEnd};"); } lines.Add("}"); } lines.Add(""); lines.Add("pool {"); if (!string.IsNullOrEmpty(subnet.PoolDynamicRangeEnd) && !string.IsNullOrEmpty(subnet.PoolDynamicRangeStart)) { lines.Add($"range dynamic-bootp {subnet.PoolDynamicRangeStart} {subnet.PoolDynamicRangeEnd};"); } lines.Add("}"); lines.Add("}"); } lines.Add(""); var reservations = options.Reservations; foreach (var reservation in reservations) { lines.Add($"host {reservation.HostName} {{ hardware ethernet {reservation.MacAddress}; fixed-address {reservation.IpAddress}; }}"); } FileWithAcl.WriteAllLines(MainFilePath, lines, "644", "root", "wheel"); #endregion Start(); }
public static void Create(string name, string time, string command) { var timerFile = $"{TargetDirectory}/{name}.timer"; if (File.Exists(timerFile)) { File.Delete(timerFile); } var timerText = new List <string> { "[Unit]", $"Description={name} Timer", "", "[Timer]", $"OnCalendar={time}", "Persistent=true", "", "[Install]", "WantedBy=tt.target", "" }; FileWithAcl.WriteAllLines(timerFile, timerText, "644", "root", "wheel"); var serviceFile = $"{TargetDirectory}/{name}.service"; if (File.Exists(serviceFile)) { File.Delete(serviceFile); } var serviceText = new List <string> { "[Unit]", $"Description={name} Service", "", "[Service]", "Type=oneshot", "ExecStartPre=/bin/bash -c \"/usr/bin/systemctl set-environment TTDATE=$(/bin/date +'%%Y%%m%%d-%%H%%M%%S')\"", $"ExecStart={command}", "", "[Install]", "WantedBy=tt.target", "" }; FileWithAcl.WriteAllLines(serviceFile, serviceText, "644", "root", "wheel"); var schedulerConfiguration = new TimerConfiguration(); var tryget = schedulerConfiguration.Get().Timers.FirstOrDefault(_ => _.Alias == name); if (tryget == null) { schedulerConfiguration.AddTimer(new TimerModel { Alias = name, Command = command, Time = time, IsEnabled = true }); } Bash.Execute($"chown root:wheel {timerFile}", false); Bash.Execute($"chown root:wheel {serviceFile}", false); Bash.Execute($"ln -s {timerFile} {Parameter.TimerUnitsLinks}/{name}.timer"); Bash.Execute($"ln -s {serviceFile} {Parameter.TimerUnitsLinks}/{name}.service"); Bash.Execute("systemctl daemon-reload", false); }
public static bool AddNsUpdateConfiguration(NsUpdateConfiguration conf) { if (string.IsNullOrEmpty(conf.Id)) { return(false); } var file = $"{NsUpdateDir}/{conf.Id}{NsUpdateConfigurationExt}"; var lines = new List <string>(); if (!string.IsNullOrEmpty(conf.ServerName)) { lines.Add($"server {conf.ServerName} {conf.ServerPort}"); } if (!string.IsNullOrEmpty(conf.LocalAddress)) { lines.Add($"local {conf.LocalAddress} {conf.LocalPort}"); } if (!string.IsNullOrEmpty(conf.ZoneName)) { lines.Add($"zone {conf.ZoneName}"); } if (!string.IsNullOrEmpty(conf.ClassName)) { lines.Add($"class {conf.ClassName}"); } if (!string.IsNullOrEmpty(conf.KeySecret)) { lines.Add($"key {conf.KeyName} {conf.KeySecret}"); } if (!string.IsNullOrEmpty(conf.NxDomain)) { lines.Add($"prereq nxdomain {conf.NxDomain}"); } if (!string.IsNullOrEmpty(conf.YxDomain)) { lines.Add($"prereq yxdomain {conf.YxDomain}"); } if (!string.IsNullOrEmpty(conf.NxRrset)) { lines.Add($"prereq nxrrset {conf.NxRrset}"); } if (!string.IsNullOrEmpty(conf.YxRrset)) { lines.Add($"prereq yxrrset {conf.YxRrset}"); } if (!string.IsNullOrEmpty(conf.Delete)) { lines.Add($"update delete {conf.Delete}"); } if (!string.IsNullOrEmpty(conf.Add)) { lines.Add($"update add {conf.Add}"); } lines.Add("show"); lines.Add("send"); try { FileWithAcl.WriteAllLines(file, lines, "644", "root", "wheel"); } catch (Exception) { return(false); } return(File.Exists(file)); }