Google Cloud SQL — irregular authentication failures - postgresql

I have an App Engine Flex java service (REST backend, 1 instance, always up) which connects to Cloud SQL instance using IAM authentication (service account). Everything seems to work fine most of the time but sometimes I'm having timeouts on REST calls and my service and its clients experiencing DoS.
GCP logs shows me that I had 7365 occurrences of this error during last 7 days which is insane:
org.springframework.dao.DataAccessResourceFailureException: Unable to acquire JDBC Connection; nested exception is org.hibernate.exception.JDBCConnectionException: Unable to acquire JDBC Connection
I was thinking of limited availability of Cloud SQL Instance itself b/c mine is not highly available, but I see those errors in Postgres log (which is my Cloud SQL DB) which
shows that the instance itself is available but credentials are not ok:
2022-06-16 08:33:33.316 UTC [610407]: [1-1] db=db-dev,user=connect-xxx#appspot FATAL: Cloud SQL IAM service account authentication failed for user "connect-xxx#appspot"
2022-06-16 08:33:33.316 UTC [610407]: [1-1] db=db-dev,user=connect-xxx#appspot DETAIL: Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.
Connection matched pg_hba.conf line 21: "local all +cloudsqliamserviceaccount cloudsql-iam-svc-acct"
I was thinking of some issues in Cloud SQL Auth Proxy but its logs don't show anything that could help.
My connection settings:
<bean id="hikariConfig" class="com.zaxxer.hikari.HikariConfig">
<property name="poolName" value="springHikariCP" />
<property name="connectionTestQuery" value="SELECT 1" />
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="connectionTimeout" value="600000"/>
<property name="jdbcUrl" value="jdbc:postgresql://127.0.0.1:3306/db-dev?cloudSqlInstance=connect-xxx:europe-west9:dev&socketFactory=com.google.cloud.sql.postgres.SocketFactory" />
<property name="username" value="connect-xxx#appspot"/>
<!-- IAM auth -->
<property name="password" value="dummy"/>
<property name="dataSourceProperties">
<props>
<prop key="sslmode">disable</prop>
<prop key="enableIamAuth">true</prop>
</props>
</property>
<!---->
</bean>
My App Engine service has 1vCPU & 4 gigs of RAM.
I see some spikes in CPU usage (up to 80%) but they are not coincide with DoS. Mem usage is always not higher than 1.5 gigs.
My Postgres instance has 1vCPU & 3.75 gigs of RAM.
CPU usage is always about 5%, mem usage is about 2 gigs, always not more than 6 transactions per second.
Any ideas?
UPD regarding SQL proxy:
I use
beta_settings:
cloud_sql_instances: connect-xxx:europe-west9:dev=tcp:3306
in my app.yaml. I also clearly use 3306 port in connection string.
Cloud SQL Proxy is there and also listening on 3306:
docker logs yyy
2022/06/21 15:44:23 current FDs rlimit set to 1048576, wanted limit is 8500. Nothing to do here.
2022/06/21 15:44:24 Listening on 0.0.0.0:3306 for connect-xxx:europe-west9:dev
2022/06/21 15:44:24 Ready for new connections
2022/06/21 15:44:24 Generated RSA key in 731.70246ms
systemd-r 246 systemd-resolve 14u IPv4 13413 0t0 TCP 127.0.0.53:53 (LISTEN)
container 345 root 11u IPv4 14603 0t0 TCP 127.0.0.1:45795 (LISTEN)
sshd 422 root 3u IPv4 14545 0t0 TCP *:22 (LISTEN)
sshd 422 root 4u IPv6 14546 0t0 TCP *:22 (LISTEN)
dockerd 447 root 27u IPv4 17276 0t0 TCP 172.17.0.1:3306 (LISTEN)
PG Socket factory dep:
<dependency>
<groupId>com.google.cloud.sql</groupId>
<artifactId>postgres-socket-factory</artifactId>
<version>1.6.0</version>
</dependency>
UPDATE 2:
Google confirmed this is an issue on their side and they will roll out the fix in a few weeks.

Related

You should use a persistent object cache. Why does Memcached on Wordpress not work on a LAMP stack with multiple virtual hosts?

I have a LAMP stack with multiple virtual hosts. Memcached is not working in Wordpress, It used to untill I created more virtual hosts.
From WordPress I get:
You should use a persistent object cache
From W3 Total Cache, I get the following:
The following memcached servers are not responding or not running:
Database Cache: 127.0.0.1:11211.
Object Cache: 127.0.0.1:11211.
This message will automatically disappear once the issue is resolved.
My info.php here
lsof -i :11211
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
memcached 350432 memcache 22u IPv4 5140918 0t0 TCP localhost:11211 (LISTEN)
memcached 350432 memcache 23u IPv6 5140919 0t0 TCP ip6-localhost:11211 (LISTEN)
In /etc/memcached.conf I have set -l 127.0.0.1 and also l ::1 for ipv6.
-vv
Dec 23 20:24:46 a-c-d systemd-memcached-wrapper[369407]: authenticated() in cmd 0x01 is false
Dec 23 20:24:46 a-c-d systemd-memcached-wrapper[369407]: >24 Writing an error: Auth failure.
Dec 23 20:24:46 a-c-d systemd-memcached-wrapper[369407]: >24 Writing bin
var//log/apache2/error.log:
PHP message: [ERROR] WP_CACHE constant is not present in wp-config.php
PHP Warning: Trying to access array offset on value of type null in /var/www/html/example.com/public_html/wp-content/plugins/w3-total-cache/Util_Installed.php on line 145', referer: https://www.example.com/wp-adminplugin_status=all&paged=1&s
/plugins.php?
EDIT:
I can see here redis is enabled even though I have deleted it completely, this is weird.
Any help on how to resolve this would be really great, thanks!
I have tried everything I can think of. Logging as much as possible, researching the web. I exspect to get memcached to work again :)

Consume a restful service without port in Mule

I have a restful service deployed in public IP, and thus does not have a port number associated with it. I need to invoke that service, in mule and create a workflow.
I can consume a service with port number as specified below but am unable to do the same for a service which does not have a port number associated.
<http:listener-config name="HTTP_Listener_Configuration" host="localhost" port="8105" doc:name="HTTP Listener Configuration" />
<http:request-config name="HTTP_Request_Configuration" host="localhost" port="8080" basePath="/onlineexam" doc:name="HTTP Request Configuration"/>
Please help
It will always have a port. If the URL does not have one specified then it is using the default http port '80' so set the port attribute to 80.
I was also facing the issue despite adding default port 443 for my HTTPS request. Usually this issue persists when the hostname ends with .io or .org. Mine was .io
Adding this inside the <http:request > block helped:
<http:request-builder>
<http:header headerName="Host" value="hostname"/>
</http:request-builder>
This will overrirde the configuration host and port. So you would still have to mention host and port number in the request configuration which will be overridden.
For http, use port 80 and for HTTPS, use port 443

HAProxy https on Openshift ends in redirect loop on non-local gears

I have a Tomcat 7 (JBoss EWS 2.0) app with HAProxy Web Load Balancer. Https works fine when there is only one server running but as soon as I add another one (by setting minimum number of gears to 2), a problem occurs.
I have checked out the GEAR cookie when connecting and as soon as it is the local gear local-569aaabf0c1e661db1000004 the connection is established, but the 569aadaa89f5cff3c9000058-petrfox GEAR cookie makes trouble.
The problem is that every attempt to connect, which is redirected (by the load balancer) to the newly started gear, ends in 302 redirect loop (by accessing https://dftestapp-petrfox.rhcloud.com/ I get 302 with header Location:https://dftestapp-petrfox.rhcloud.com/).
You can try it on the link above - if the page loads, just remove the GEAR cookie and refresh, you will be most probably redirected to the other one gear this time.
Generated HAProxy configuration (haproxy.cfg) is
#---------------------------------------------------------------------
# Example configuration for a possible web application. See the
# full configuration options online.
#
# http://haproxy.1wt.eu/download/1.4/doc/configuration.txt
#
#---------------------------------------------------------------------
#---------------------------------------------------------------------
# Global settings
#---------------------------------------------------------------------
global
# to have these messages end up in /var/log/haproxy.log you will
# need to:
#
# 1) configure syslog to accept network log events. This is done
# by adding the '-r' option to the SYSLOGD_OPTIONS in
# /etc/sysconfig/syslog
#
# 2) configure local2 events to go to the /var/log/haproxy.log
# file. A line like the following can be added to
# /etc/sysconfig/syslog
#
# local2.* /var/log/haproxy.log
#
#log 127.0.0.1 local2
maxconn 256
# turn on stats unix socket
stats socket /var/lib/openshift/569aaabf0c1e661db1000004/haproxy//run/stats level admin
#---------------------------------------------------------------------
# common defaults that all the 'listen' and 'backend' sections will
# use if not designated in their block
#---------------------------------------------------------------------
defaults
mode http
log global
option httplog
option dontlognull
option http-server-close
#option forwardfor except 127.0.0.0/8
option redispatch
retries 3
timeout http-request 10s
timeout queue 1m
timeout connect 10s
timeout client 1m
timeout server 1m
timeout http-keep-alive 10s
timeout check 10s
maxconn 128
listen stats 127.7.244.3:8080
mode http
stats enable
stats uri /
listen express 127.7.244.2:8080
cookie GEAR insert indirect nocache
option httpchk GET /
http-check expect rstatus 2..|3..|401
balance leastconn
server gear-569aadaa89f5cff3c9000058-petrfox ex-std-node827.prod.rhcloud.com:56761 check fall 2 rise 3 inter 2000 cookie 569aadaa89f5cff3c9000058-petrfox
server local-gear 127.7.244.1:8080 check fall 2 rise 3 inter 2000 cookie local-569aaabf0c1e661db1000004
I tried to turn off forcing https in my app (by removing <intercept-url pattern="/**" requires-channel="https"/> in applicationContext-security.xml), used just http and it worked. Therefore I assume there must be some more https configuration needed. But my question is where and what do I need to configure? I find it strange that it doesn't work with the generated configuration, because load balancing is something why one chooses Openshift and https is in some circumstances a must have. It is also strange to me that everything goes well when you are redirected to the local-gear.
I didn't find any material which would be any of help. Could you please help me with this problem?
UPDATE: I don't know where the problem is, but it could be in settings of the server. Here is the config file server.xml (which I had never changed)
<?xml version='1.0' encoding='utf-8'?>
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!-- Note: A "Server" is not itself a "Container", so you may not
define subcomponents such as "Valves" at this level.
Documentation at /docs/config/server.html
-->
<Server port="-1" shutdown="SHUTDOWN">
<!-- Security listener. Documentation at /docs/config/listeners.html
<Listener className="org.apache.catalina.security.SecurityListener" />
-->
<!--APR library loader. Documentation at /docs/apr.html -->
<Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />
<!--Initialize Jasper prior to webapps are loaded. Documentation at /docs/jasper-howto.html -->
<Listener className="org.apache.catalina.core.JasperListener" />
<!-- Prevent memory leaks due to use of particular java/javax APIs-->
<Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />
<Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
<Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener" />
<!-- Global JNDI resources
Documentation at /docs/jndi-resources-howto.html
-->
<GlobalNamingResources>
<!-- Editable user database that can also be used by
UserDatabaseRealm to authenticate users
-->
<Resource name="UserDatabase" auth="Container"
type="org.apache.catalina.UserDatabase"
description="User database that can be updated and saved"
factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
pathname="conf/tomcat-users.xml" />
</GlobalNamingResources>
<!-- A "Service" is a collection of one or more "Connectors" that share
a single "Container" Note: A "Service" is not itself a "Container",
so you may not define subcomponents such as "Valves" at this level.
Documentation at /docs/config/service.html
-->
<Service name="Catalina">
<!--The connectors can use a shared executor, you can define one or more named thread pools-->
<!--
<Executor name="tomcatThreadPool" namePrefix="catalina-exec-"
maxThreads="150" minSpareThreads="4"/>
-->
<!-- A "Connector" represents an endpoint by which requests are received
and responses are returned. Documentation at :
Java HTTP Connector: /docs/config/http.html (blocking & non-blocking)
Java AJP Connector: /docs/config/ajp.html
APR (HTTP/AJP) Connector: /docs/apr.html
Define a non-SSL HTTP/1.1 Connector on port 8080
-->
<Connector address="${OPENSHIFT_JBOSSEWS_IP}"
port="${OPENSHIFT_JBOSSEWS_HTTP_PORT}"
protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443"/>
<!-- A "Connector" using the shared thread pool-->
<!--
<Connector executor="tomcatThreadPool"
port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
-->
<!-- Define a SSL HTTP/1.1 Connector on port 8443
This connector uses the JSSE configuration, when using APR, the
connector should be using the OpenSSL style configuration
described in the APR documentation -->
<!--
<Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
maxThreads="150" scheme="https" secure="true"
clientAuth="false" sslProtocol="TLS" />
-->
<!-- Define an AJP 1.3 Connector on port 8009 -->
<!--Connector port="8009" protocol="AJP/1.3" redirectPort="8443" /-->
<!-- An Engine represents the entry point (within Catalina) that processes
every request. The Engine implementation for Tomcat stand alone
analyzes the HTTP headers included with the request, and passes them
on to the appropriate Host (virtual host).
Documentation at /docs/config/engine.html -->
<!-- You should set jvmRoute to support load-balancing via AJP ie :
<Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">
-->
<Engine name="Catalina" defaultHost="localhost">
<!--For clustering, please take a look at documentation at:
/docs/cluster-howto.html (simple how to)
/docs/config/cluster.html (reference documentation) -->
<!--
<Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
-->
<!-- Use the LockOutRealm to prevent attempts to guess user passwords
via a brute-force attack -->
<Realm className="org.apache.catalina.realm.LockOutRealm">
<!-- This Realm uses the UserDatabase configured in the global JNDI
resources under the key "UserDatabase". Any edits
that are performed against this UserDatabase are immediately
available for use by the Realm. -->
<Realm className="org.apache.catalina.realm.UserDatabaseRealm"
resourceName="UserDatabase"/>
</Realm>
<Host name="localhost" appBase="webapps"
unpackWARs="false" autoDeploy="true">
<!-- SingleSignOn valve, share authentication between web applications
Documentation at: /docs/config/valve.html -->
<!--
<Valve className="org.apache.catalina.authenticator.SingleSignOn" />
-->
<!-- RemoteIp valve, pass protocol header from proxy. -
http://tomcat.apache.org/tomcat-7.0-doc/api/org/apache/catalina/valves/RemoteIpValve.html
-->
<Valve
className="org.apache.catalina.valves.RemoteIpValve"
protocolHeader="x-forwarded-proto"
/>
<!-- Access log processes all example.
Documentation at: /docs/config/valve.html
Note: The pattern used is equivalent to using pattern="common" -->
<!--
<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
prefix="localhost_access_log." suffix=".txt"
pattern="%h %l %u %t "%r" %s %b" />
-->
</Host>
</Engine>
</Service>
</Server>
I had a similar problem with Too many redirects and the scalable Tomcat gear.
You can try to configure your server.xml and web.xml as the Technical FAQ suggests for Tomcat:
How do I redirect traffic to HTTPS.
Unfortunately, it didn't quite worked well for me. Everything was running ok if my app had only one gear - http traffic was being redirected to https. However, when I turned on the application scaling and the second gear was started, the Too many redirects error was appearing after every redeploy.
I was unable to resolve this. I've ended up in using the default Tomcat config and redirecting the unsecure traffic to https in my application's controllers (inspired by the Technical FAQ's answer for Node.js here). Everything works fine now.

MFP Server: Specifying a particular interface on a multi-homed host

MFP 7.0.0 with IF201506081356
on WebSphere Liberty 8.5.5.5 on Linux
My idea was to modify server.xml
<httpEndpoint id="defaultHttpEndpoint"
httpPort="9080"
httpsPort="9443"
host="*" > <=== change this to a specific ipaddress
And change this JNDI entry
<jndiEntry jndiName="ibm.worklight.admin.jmx.host" value="localhost"/>
to specify the same ipaddress.
After making those changes server does not initialise correctly, it attempts to access JMX on the localhost, even though nowhere in my serverl.xml is the word "localhost"
[6/11/15 13:19:24:232 CEST] 00000040 com.worklight.common.util.jmx.LibertyRuntimeMBeanHandler I Establishing REST connection to service:
jmx:rest://localhost:9443/IBMJMXConnectorREST SSL handler=null
That attempt just repeats ad nauseum ...
Is there some cached value somewhere? Something else I need to set?
During the startup of the runtimes "localhost" is always used for the JMX connection. It is a defect, an APAR will be created.

org.postgresql.util.PSQLException: FATAL: no pg_hba.conf entry for host

I am trying to connect to PostgreSQL database which is in remote location using Spring JDBC template. I am getting
org.postgresql.util.PSQLException: FATAL: no pg_hba.conf entry for host "139.126.243.71", user "guest", database "masterdb", SSL off error
I don't have access to pg_hba.conf file of the remote location.
This is the configuration I gave in my spring servlet.xml
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.postgresql.Driver"/>
<property name="url" value="jdbc:postgresql://100.64.35.52":5432/masterdb"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
Can we solve the issue by giving any properties?
It seems that DB server does not allow SSL off connection, You will have to enable it. Change URL from jdbc:postgresql://100.64.35.52":5432/masterdb to jdbc:postgresql://100.64.35.52":5432/masterdb?sslmode=require
Check mode details about ssl mode at http://www.postgresql.org/docs/9.1/static/libpq-ssl.html
You must apply below changes to connect:
Navigate to the the following location C:\Program Files (maybe x86)\PostgreSQL\(your version)\data
postgresql.conf file:
check the listen_addresses be = * ( by default its localhost in some postgres versions) if it isn't you must change it to *. It's used to listen on all interfaces.
pg_hba.conf file:
add a new row :
host all all 0.0.0.0/0 md5
( use of above row is better)
or
host guest masterdb 139.126.243.71 md5
And finally it's very important that the ssl mode is to be on. For this add below command in the end of your url:
?ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory
In Terms of Bean as
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.postgresql.Driver"/>
<property name="url" value="jdbc:postgresql://100.64.35.52":5432/masterdb?ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
Error explanation
The file pg_hba.conf (host-based authentication configuration file) is used to control the client authentication. This file is located in the database cluster's data directory.
The error java.sql.SQLException: FATAL: no pg_hba.conf entry for host "<your-host-ip>", user "<postgres-user>", database "<db-name>", SSL off means that Postgres accepts SSL connections but your are trying to connect without SSL.
Secured connection
If a certificate is requested from the client during SSL connection startup, it means that the DBA has set the clientcert parameter in pg_hba.conf. Note that if clientcert is not specified (or set to 0), the server will NOT insist that a client certificate be presented.
Check if database server is using SSL
Before trying to access your SSL enabled server from Java, make sure that you can get to it via psql.
If you want to connect with a given user at a given port:
$ psql -h <server-ip> -p <server-port> -d <db-name> -U <user>
Or if you want to connect at the default port with your current user:
$ psql -h <server-ip>
You should see an such output if you have established a SSL connection:
$ psql -h <server-ip> -d <db-name> -U <user>
psql (11.2, Server 9.6.5)
SSL connection (cipher: DHE-RSA-AES256-SHA, bits: 256)
Note that the last line contains 'SSL connection'.
JDBC connection parameters
ssl must be set if the server required a secured connection. Note that both ssl=true or ssl work but ssl=true is recommended for the coming future release of Postgres.
sslfactory provides the class name to use as the SSLSocketFactory when establishing a SSL connection.
The JDBC driver provdies an option to establish a SSL connection without doing any validation (but it's risky!).
A non-validating connection is established via a custom SSLSocketFactory class that is provided with the driver. Setting the connection URL parameter sslfactory=org.postgresql.ssl.NonValidatingFactory will turn off all SSL validation.
This was my case and why I also got the same error you had. So, to establish the connection I have:
jdbc:postgresql://<ip-address>:<port>/<db-name>?ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory
References
Postgres JDBC SSL
Postgres JDBC NonValidating
Postgres SSL-TCP
Combined settings
I tried the suggestions given by #craig-ringer
jdbc:postgresql://100.64.35.52":5432/masterdb?ssl=true
and given by #amit
jdbc:postgresql://100.64.35.52":5432/masterdb?sslmode=require
neither worked. But when I combined them to:
jdbc:postgresql://100.64.35.52":5432/masterdb?ssl=true&sslmode=require
It worked.
See my answer here, basically had to put user/pwd in url property
url="jdbc:postgresql://server:port/mydb?user=fred&password=secret"
You must have root access edit pg_hba.conf.
goto root user
edit /var/lib/pgsql/12/data/pg_hba.conf
host all all 139.126.243.71/32 trust
Restart Postgres [service postgresql-12.service restart].