final Map<String, Settings> authzDyn = settings.getGroups("searchguard.dynamic.authz"); final boolean enabled = ads.getAsBoolean("enabled", true); final boolean httpEnabled = enabled && ads.getAsBoolean("http_enabled", true); final boolean transportEnabled = enabled && ads.getAsBoolean("transport_enabled", true); final String authzBackendClazz = ads.get("authorization_backend.type", "noop"); final AuthorizationBackend authorizationBackend; authorizationBackend = newInstance( authzBackendClazz,"z", Settings.builder().put(esSettings).put(ads.getAsSettings("authorization_backend.config")).build(), configPath); final Map<String, Settings> dyn = settings.getGroups("searchguard.dynamic.authc"); final boolean enabled = ads.getAsBoolean("enabled", true); final boolean httpEnabled = enabled && ads.getAsBoolean("http_enabled", true); final boolean transportEnabled = enabled && ads.getAsBoolean("transport_enabled", true); final String authBackendClazz = ads.get("authentication_backend.type", InternalAuthenticationBackend.class.getName()); if(authBackendClazz.equals(InternalAuthenticationBackend.class.getName()) //NOSONAR || authBackendClazz.equals("internal") authenticationBackend = newInstance( authBackendClazz,"c", Settings.builder().put(esSettings).put(ads.getAsSettings("authentication_backend.config")).build(), configPath); String httpAuthenticatorType = ads.get("http_authenticator.type"); //no default HTTPAuthenticator httpAuthenticator = httpAuthenticatorType==null?null: (HTTPAuthenticator) newInstance(httpAuthenticatorType,"h",
Builder settings = Settings.settingsBuilder() .put("cluster.name", DEFAULT_CLUSTER_NAME) .put("node.local", Boolean.toString(!remoteMode)) .put("path.home", pathHome); node = nodeBuilder().clusterName(clusterName).settings(settings).node(); node.start(); client = node.client(); client.admin().indices() .exists(Requests.indicesExistsRequest(indexKey)).actionGet() .isExists(); if (exists && newdb) { client.admin().indices().prepareDelete(indexKey).execute().actionGet(); client.admin().indices().create( new CreateIndexRequest(indexKey) .settings( Settings.builder() .put("index.number_of_shards", numberOfShards) .put("index.number_of_replicas", numberOfReplicas)
public SnapshotRestoreEvaluator(final Settings settings, AuditLog auditLog) { this.enableSnapshotRestorePrivilege = settings.getAsBoolean(ConfigConstants.SEARCHGUARD_ENABLE_SNAPSHOT_RESTORE_PRIVILEGE, ConfigConstants.SG_DEFAULT_ENABLE_SNAPSHOT_RESTORE_PRIVILEGE); this.restoreSgIndexEnabled = settings.getAsBoolean(ConfigConstants.SEARCHGUARD_UNSUPPORTED_RESTORE_SGINDEX_ENABLED, false); this.searchguardIndex = settings.get(ConfigConstants.SEARCHGUARD_CONFIG_INDEX_NAME, ConfigConstants.SG_DEFAULT_CONFIG_INDEX); this.auditLog = auditLog; }
public PinyinConfig(Settings settings) { this.keepFirstLetter=settings.getAsBoolean("keep_first_letter",true); this.keepSeparateFirstLetter=settings.getAsBoolean("keep_separate_first_letter",false); this.keepFullPinyin=settings.getAsBoolean("keep_full_pinyin", true); this.keepJoinedFullPinyin =settings.getAsBoolean("keep_joined_full_pinyin", false); this.keepNoneChinese=settings.getAsBoolean("keep_none_chinese",true); this.keepNoneChineseTogether=settings.getAsBoolean("keep_none_chinese_together",true); this.noneChinesePinyinTokenize =settings.getAsBoolean("none_chinese_pinyin_tokenize",true); this.keepOriginal=settings.getAsBoolean("keep_original", false); this.LimitFirstLetterLength=settings.getAsInt("limit_first_letter_length", 16); this.lowercase=settings.getAsBoolean("lowercase", true); this.trimWhitespace=settings.getAsBoolean("trim_whitespace", true); this.keepNoneChineseInFirstLetter =settings.getAsBoolean("keep_none_chinese_in_first_letter", true); this.keepNoneChineseInJoinedFullPinyin =settings.getAsBoolean("keep_none_chinese_in_joined_full_pinyin", false); this.removeDuplicateTerm =settings.getAsBoolean("remove_duplicated_term", false); this.fixedPinyinOffset =settings.getAsBoolean("fixed_pinyin_offset", false); this.ignorePinyinOffset =settings.getAsBoolean("ignore_pinyin_offset", true); } }
@BeforeClass public static void setUpBeforeClass() throws Exception { Builder builder = Settings.settingsBuilder(); builder.put("path.home", "target/data"); node = new NodeBuilder().settings(builder).node(); }
@BeforeClass public static void beforeClass() throws Exception { Stagemonitor.init(); elasticsearchPort = getAvailablePort(); logger.info("Elasticsearch port: {}", elasticsearchPort); final Settings settings = Settings.builder() .put("path.home", esHome.getAbsolutePath()) .put("node.name", "junit-es-node") .put("http.port", elasticsearchPort) .put("path.logs", "build/elasticsearch/logs") .put("path.data", "build/elasticsearch/data") node.client().admin().cluster().prepareHealth().setWaitForGreenStatus().get(); adminClient = client.admin(); adminClient.cluster().prepareHealth() .setWaitForYellowStatus().execute().actionGet();
@SuppressWarnings("resource") @Test public void testNodeClientDisallowedWithNonServerCertificate2() throws Exception { setup(); Assert.assertEquals(clusterInfo.numNodes, clusterHelper.nodeClient().admin().cluster().health(new ClusterHealthRequest().waitForGreenStatus()).actionGet().getNumberOfNodes()); Assert.assertEquals(ClusterHealthStatus.GREEN, clusterHelper.nodeClient().admin().cluster().health(new ClusterHealthRequest().waitForGreenStatus()).actionGet().getStatus()); final Settings tcSettings = Settings.builder() .put(minimumSearchGuardSettings(Settings.EMPTY).get(0)) .put("cluster.name", clusterInfo.clustername) .put("node.data", false) .put("node.master", false) .put("node.ingest", false) .put("path.home", ".") .put("discovery.initial_state_timeout","8s") .put("searchguard.ssl.transport.keystore_filepath", FileHelper.getAbsoluteFilePathFromClassPath("spock-keystore.jks")) .put(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_KEYSTORE_ALIAS,"spock") .build(); log.debug("Start node client"); try (Node node = new PluginAwareNode(false, tcSettings, Netty4Plugin.class, SearchGuardPlugin.class).start()) { Thread.sleep(50); Assert.assertEquals(1, node.client().admin().cluster().nodesInfo(new NodesInfoRequest()).actionGet().getNodes().size()); } }
public static void registerMngtRestApiHandler(final Settings settings) { if (enterpriseModulesDisabled()) { return; } if(!settings.getAsBoolean("http.enabled", true)) { try { final Class<?> clazz = Class.forName("com.floragunn.searchguard.dlic.rest.api.SearchGuardRestApiActions"); addLoadedModule(clazz); } catch (final Throwable e) { log.warn("Unable to register Rest Management Api Module due to {}", e.toString()); if(log.isDebugEnabled()) { log.debug("Stacktrace: ",e); } } } }
@Override protected ConfigUpdateNodeResponse nodeOperation(final NodeConfigUpdateRequest request) { final Map<String, Settings> setn = configurationRepository.reloadConfiguration(Arrays.asList(request.request.getConfigTypes())); String licenseText = null; if(setn.get("config") != null) { licenseText = setn.get("config").get("searchguard.dynamic.license"); } if(licenseText != null && !licenseText.isEmpty()) { try { final SearchGuardLicense license = new SearchGuardLicense(XContentHelper.convertToMap(XContentType.JSON.xContent(), LicenseHelper.validateLicense(licenseText), true), clusterService); if(!license.isValid()) { logger.warn("License "+license.getUid()+" is invalid due to "+license.getMsgs()); //throw an exception here if loading of invalid license should be denied } } catch (Exception e) { logger.error("Invalid license",e); return new ConfigUpdateNodeResponse(clusterService.localNode(), new String[0], "Invalid license: "+e); } } backendRegistry.get().invalidateCache(); return new ConfigUpdateNodeResponse(clusterService.localNode(), setn.keySet().toArray(new String[0]), null); } }
@Override public AuthCredentials extractCredentials(final RestRequest request, ThreadContext context) { if(context.getTransient(ConfigConstants.SG_XFF_DONE) != Boolean.TRUE) { throw new ElasticsearchSecurityException("xff not done"); } final String userHeader = settings.get("user_header"); final String rolesHeader = settings.get("roles_header"); final String rolesSeparator = settings.get("roles_separator", ","); if(log.isDebugEnabled()) { log.debug("headers {}", request.getHeaders()); log.debug("userHeader {}, value {}", userHeader, userHeader == null?null:request.header(userHeader)); log.debug("rolesHeader {}, value {}", rolesHeader, rolesHeader == null?null:request.header(rolesHeader)); } if (!Strings.isNullOrEmpty(userHeader) && !Strings.isNullOrEmpty((String) request.header(userHeader))) { String[] backendRoles = null; if (!Strings.isNullOrEmpty(rolesHeader) && !Strings.isNullOrEmpty((String) request.header(rolesHeader))) { backendRoles = ((String) request.header(rolesHeader)).split(rolesSeparator); } return new AuthCredentials((String) request.header(userHeader), backendRoles).markComplete(); } else { if(log.isTraceEnabled()) { log.trace("No '{}' header, send 401", userHeader); } return null; } }
LegacyConfigurationLoader(final Client client, ThreadPool threadPool, final Settings settings) { super(); this.client = client; //this.threadContext = threadPool.getThreadContext(); this.searchguardIndex = settings.get(ConfigConstants.SEARCHGUARD_CONFIG_INDEX_NAME, ConfigConstants.SG_DEFAULT_CONFIG_INDEX); log.debug("Index is: {}", searchguardIndex); }
public PrivilegesEvaluator(final ClusterService clusterService, final ThreadPool threadPool, final ConfigurationRepository configurationRepository, final ActionGroupHolder ah, final IndexNameExpressionResolver resolver, AuditLog auditLog, final Settings settings, final PrivilegesInterceptor privilegesInterceptor, final ClusterInfoHolder clusterInfoHolder) { super(); this.configurationRepository = configurationRepository; this.clusterService = clusterService; this.resolver = resolver; this.auditLog = auditLog; this.threadContext = threadPool.getThreadContext(); this.privilegesInterceptor = privilegesInterceptor; try { rolesMappingResolution = ConfigConstants.RolesMappingResolution.valueOf(settings.get(ConfigConstants.SEARCHGUARD_ROLES_MAPPING_RESOLUTION, ConfigConstants.RolesMappingResolution.MAPPING_ONLY.toString()).toUpperCase()); } catch (Exception e) { log.error("Cannot apply roles mapping resolution",e); rolesMappingResolution = ConfigConstants.RolesMappingResolution.MAPPING_ONLY; } this.checkSnapshotRestoreWritePrivileges = settings.getAsBoolean(ConfigConstants.SEARCHGUARD_CHECK_SNAPSHOT_RESTORE_WRITE_PRIVILEGES, ConfigConstants.SG_DEFAULT_CHECK_SNAPSHOT_RESTORE_WRITE_PRIVILEGES); this.clusterInfoHolder = clusterInfoHolder; //this.typeSecurityDisabled = settings.getAsBoolean(ConfigConstants.SEARCHGUARD_DISABLE_TYPE_SECURITY, false); configModel = new ConfigModel(ah, configurationRepository); irr = new IndexResolverReplacer(resolver, clusterService, clusterInfoHolder); snapshotRestoreEvaluator = new SnapshotRestoreEvaluator(settings, auditLog); sgIndexAccessEvaluator = new SearchGuardIndexAccessEvaluator(settings, auditLog); dlsFlsEvaluator = new DlsFlsEvaluator(settings, threadPool); termsAggregationEvaluator = new TermsAggregationEvaluator(); }
public void createIndexIfNotExists(String indexName, final int shards, final int replicas) { // create an index if not existent if (!this.elasticsearchClient.admin().indices().prepareExists(indexName).execute().actionGet().isExists()) { Settings.Builder settings = Settings.builder() .put("number_of_shards", shards) .put("number_of_replicas", replicas); this.elasticsearchClient.admin().indices().prepareCreate(indexName) .setSettings(settings) .setUpdateAllTypes(true) .execute().actionGet(); } else { //LOGGER.debug("Index with name {} already exists", indexName); } }
Settings.Builder settings = Settings.builder(); settings.put(index.getSettings()); CreateIndexResponse indexResponse = SHARED_NODE.client().admin().indices() .prepareCreate(index.getName()) .setSettings(settings) throw new IllegalStateException("Failed to create index " + index.getName()); SHARED_NODE.client().admin().cluster().prepareHealth(index.getName()).setWaitForStatus(ClusterHealthStatus.YELLOW).get(); PutMappingResponse mappingResponse = SHARED_NODE.client().admin().indices().preparePutMapping(index.getName()) .setType(entry.getKey()) .setSource(entry.getValue().getAttributes())
public boolean restAuthEnabled() { final boolean restInitiallyDisabled = staticSettings.getAsBoolean(ConfigConstants.SEARCHGUARD_UNSUPPORTED_DISABLE_REST_AUTH_INITIALLY, false); if(restInitiallyDisabled) { if(dynamicSgConfig == null) { if(log.isTraceEnabled()) { log.trace("dynamicSgConfig is null, initially static restDisabled"); } return false; } else { final boolean restDynamicallyDisabled = dynamicSgConfig.getAsBoolean("searchguard.dynamic.disable_rest_auth", false); if(log.isTraceEnabled()) { log.trace("searchguard.dynamic.disable_rest_auth {}", restDynamicallyDisabled); } return !restDynamicallyDisabled; } } else { return true; } }
private static void startElasticsearch() throws Exception { try { FileUtils.deleteDirectory(new File("build/elasticsearch")); } catch (IOException e) { // ignore } final Settings settings = Settings.builder() .put("path.home", "build/elasticsearch") .put("node.name", "junit-es-node") .put("path.logs", "build/elasticsearch/logs") .put("path.data", "build/elasticsearch/data") .put("transport.type", "local") .put("http.type", "netty4") .build(); node = new TestNode(settings, Collections.singletonList(Netty4Plugin.class)); node.start(); node.client().admin().cluster().prepareHealth().setWaitForGreenStatus().get(); }
@Test public void testTransportClientImpersonationWildcard() throws Exception { final Settings settings = Settings.builder() .putList("searchguard.authcz.impersonation_dn.CN=spock,OU=client,O=client,L=Test,C=DE", "*") .build(); setup(settings); Settings tcSettings = Settings.builder() .put("searchguard.ssl.transport.keystore_filepath", FileHelper.getAbsoluteFilePathFromClassPath("spock-keystore.jks")) .put(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_KEYSTORE_ALIAS,"spock") .put("path.home", ".") .put("request.headers.sg_impersonate_as", "worf") .build(); try (TransportClient tc = getInternalTransportClient(clusterInfo, tcSettings)) { NodesInfoRequest nir = new NodesInfoRequest(); Assert.assertEquals(clusterInfo.numNodes, tc.admin().cluster().nodesInfo(nir).actionGet().getNodes().size()); } }
@Test public void testAliasResolution() throws Exception { final Settings settings = Settings.builder() .build(); setup(settings); final RestHelper rh = nonSslRestHelper(); try (TransportClient tc = getInternalTransportClient()) { tc.index(new IndexRequest("concreteindex-1").type("doc").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet(); tc.admin().indices().aliases(new IndicesAliasesRequest().addAliasAction(AliasActions.add().indices("concreteindex-1").alias("calias-1"))).actionGet(); tc.index(new IndexRequest(".kibana-6").type("doc").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet(); tc.admin().indices().aliases(new IndicesAliasesRequest().addAliasAction(AliasActions.add().indices(".kibana-6").alias(".kibana"))).actionGet(); } Assert.assertEquals(HttpStatus.SC_OK, rh.executeGetRequest("calias-1/_search?pretty", encodeBasicHeader("aliastest", "nagilum")).getStatusCode()); Assert.assertEquals(HttpStatus.SC_OK, rh.executeGetRequest("calias-*/_search?pretty", encodeBasicHeader("aliastest", "nagilum")).getStatusCode()); Assert.assertEquals(HttpStatus.SC_OK, rh.executeGetRequest("*kibana/_search?pretty", encodeBasicHeader("aliastest", "nagilum")).getStatusCode()); Assert.assertEquals(HttpStatus.SC_OK, rh.executeGetRequest(".ki*ana/_search?pretty", encodeBasicHeader("aliastest", "nagilum")).getStatusCode()); Assert.assertEquals(HttpStatus.SC_OK, rh.executeGetRequest(".kibana/_search?pretty", encodeBasicHeader("aliastest", "nagilum")).getStatusCode()); }