All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.plugins.secrets.configuration.postgresql.yaml Maven / Gradle / Ivy

provider:  
  metadata:
      name: PostgreSQL
      category: Database API Standard
      message: Make sure this PostgreSQL database password gets changed and removed from the code.
  detection:
    post:
      # Potential FPs here are environment variables, templates and string substitutions.
      patternNot:
        # ://test:test@
        - "(?i)^test$"
        # password
        # db_pass
        # my_passwd
        - "(?i)^(db|my)?_?pass(word|wd)?$"
        # $my_password
        # $$my_password
        # $db_password
        - "(?i)^\\${1,2}\\w*pass(word)?$"
        # [mypass123]
        - "^\\[[\\w\\t \\-]+\\]$"
        # 
        - "^<[\\w\\t -]{1,10}>?"
        # sprintf("postgres://%s:%s@%s:@s/", ...)
        # %v
        - "^%[sv]$"
        # $MY_PASSWORD
        # $MY_PASSWORD$
        - "^\\${1,2}\\w+\\$?$"
        # $(MY_PASSWORD)
        - "^\\$\\([^)]+\\)$"
        # ${ENV_VAR}
        # ${ENV_VAR:-default}
        # ://${self:db.username}:${self:db.password}@
        - "\\$\\{[^\\}]+\\}"
        # {password}
        # {{password}}
        - "^\\{++[^}]++\\}++$"
        # #{password}
        - "^#\\{[^}]++}#?$"
        # ***
        - "^\\*{3,}$"
        # "postgres://"+user+":"+password+"@"+server+":"+port+"/"
        - "^\"\\s*\\+[^\"]+\\+\\s*\""
        # 'postgres://'+user+'+'password+'@'+server+':'+port+'/'
        - "^'\\s*\\+[^']+\\+\\s*'"
        # `postgres://`+user+`+`password+`@`+server+`:`+port+`/`
        - "^`\\s*\\+[^`]+\\+\\s*`"
        # "postgres://{}:{}@{}:{}/".format(...)
        # string.Format("postgres://{0}:{1}@{2}:{3}/", ...)
        - "^\\{\\d*\\}$"
        # os.environ['DB_PASSWORD']
        - "\\b(get)?env(iron)?\\b"
        # `cat /dev/urandom | ...`
        - "(?i)^`[\\w.\\-/]+\b"

  rules:
    # Note:
    # The rules below treat the password "postgres" as a real password. It's the default password for the default
    # database user on a fresh PostgreSQL installation, so it should be changed.

    - id: postgres-url
      rspecKey: S6698
      metadata:
        name: PostgreSQL database passwords should not be disclosed
      detection:
        pre:
          scopes:
            - main
          include:
            content:
              - postgres
              - postgresql
              - postgis  
          reject:
            ext:
              - .adoc
              - .example
              - .html
              - .md
              - .mdx
              - .template
            paths:
              - "**/appsettings.Development.json"
              - "**/appsettings.Local.json"
        matching:
          # Look for URIs in the format "protocol://username:password@server:port/..."
          # The protocol can be either "postgres", "postgresql", or "postgis". It can also be followed by a subprotocol,
          # e.g. "postgresql+psycopg".
          # Certain special characters need to be percent-encoded so we can break matching when we find them.
          #
          # A negative lookbehind is added to avoid regex-based false positives.
          pattern: "(?is)\\bpostg(?:res(?:ql)?|is)(?:\\+\\w+)?://[^:@/ ]++:([^@/ ]++)@"
          context:
            matchNot:
              patternBefore:
                pattern: (?i)regex
                maxCharDistance: 50
      examples:
        # From the RSPEC
        - text: |
            # Noncompliant code example
            uri = "postgres://foouser:[email protected]/testdb"
          containsSecret: true
          match: foopass
        - text: |
            # Compliant solution
            import os

            user     = os.environ["PG_USER"]
            password = os.environ["PG_PASSWORD"]
            uri      = f"postgres://{user}:{password}@example.com/testdb"
          containsSecret: false
        # True positive matches
        - text: |
            SqlSettingsDefaultDataSource = "postgres://mmuser:mostest@localhost/mattermost_test?sslmode=disable&connect_timeout=10&binary_parameters=yes"
          containsSecret: true
          match: mostest
        - text: |
            passwordFile := fs.String("password", "../../../tools/secrets/password.txt", "password file")
            databasePrefix := fs.String("database-prefix", "postgres://postgres:postgres_password_padded_for_security@localhost:5432/ocr2vrf-test", "database prefix")
            databaseSuffixes := fs.String("database-suffixes", "sslmode=disable", "database parameters to be added")
          containsSecret: true
          match: postgres_password_padded_for_security
        - text: |
            driver: postgres
            dsn: postgres://foouser:foopass@localhost:5432/testdb?sslmode=disable
            table: footable
          containsSecret: true
          match: foopass
        - text: |
            AIRFLOW_CONN_METADATA_DB=postgres+psycopg2://airflow:airflow@postgres:5432/airflow
            AIRFLOW_VAR__METADATA_DB_SCHEMA=airflow
          containsSecret: true
          match: airflow
        - text: |
            let urlstr = "postgres://postgres:[email protected]:55432/conn_test".to_owned();
          containsSecret: true
          match: password!12345
        # Exclusions due to preconditions
        - text: |
            SqlSettingsDefaultDataSource = "postgres://mmuser:mostest@localhost/mattermost_test?sslmode=disable&connect_timeout=10&binary_parameters=yes"
          fileName: Doc.md
          containsSecret: false
        # Exclusions due to context
        - text: |
              Regex regex("(postgis://.*:)(.*)(@.*)");
          containsSecret: false
        - text: |
              Regex regex(
                  "(postgres://.*:)(.*)(@.*)"
              );
          containsSecret: false
        # Exclusions due to postconditions
        - text: |
            def test_it_returns_the_default_database_url
              assert_equal "postgres://test:test@#{@host}:#{@port}/test", @container.database_url
            end
          containsSecret: false
        - text: |
            backend "pg" {
              conn_str = "postgres://user:[email protected]/terraform_backend"
            }
          containsSecret: false
        - text: |
            backend "pg" {
              conn_str = "postgres://$DB_USER$:[email protected]/terraform_backend"
            }
          containsSecret: false
        - text: |
            DATABASE_URL="postgresql://postgres:[YOUR-PASSWORD]@db.uzapyutenknggogexmmw.supabase.co:5432/postgres"
          containsSecret: false
        - text: |
            "postgres://:@/"
          containsSecret: false
        - text: |
            connStr = fmt.Sprintf("postgres://%s:%s@:%s/%s%ssslmode=%s&host=%s",
              url.PathEscape(dbUser), url.PathEscape(dbPasswd), port, dbName, dbParam, dbsslMode, host)
          containsSecret: false
        - text: |
            url := fmt.Sprintf("postgres://%v:%v@%v:%v/%v", user, pass, host, port, name)
          containsSecret: false
        - text: |
            Hanami::Model.configure do
              pass    = CGI.escape("#{$env.db_password}").gsub('+', '%20')
              str_cnn = "postgres://#{$env.db_username}:#{pass}@#{$env.db_host}:#{$env.db_port}/#{$env.db_name}?max_connections=#{$env.db_max_connections}"
              adapter :sql, str_cnn
            end
          containsSecret: false
        - text: |
            spec:
              containers:
                - env:
                  - name: POSTGRES_CONNECTION_URI
                    value: "postgresql://$(POSTGRES_USER):$(POSTGRES_PASSWORD)@$(POSTGRES_SERVER):$(POSTGRES_PORT)/$(POSTGRES_DATABASE)"
          containsSecret: false
        - text: |
            if (!newConfig.DATABASE_URL) {
              const encodedUser = encodeURIComponent(newConfig.POSTHOG_DB_USER)
              const encodedPassword = encodeURIComponent(newConfig.POSTHOG_DB_PASSWORD)
              newConfig.DATABASE_URL = `postgres://${encodedUser}:${encodedPassword}@${newConfig.POSTHOG_POSTGRES_HOST}:${newConfig.POSTHOG_POSTGRES_PORT}/${newConfig.POSTHOG_DB_NAME}`
            }
          containsSecret: false
        - text: |
            export const dbConnection = `postgres://${process.env.DB_USER}:${process.env.DB_PASSWORD}@${process.env.DB_HOST}/${process.env.DB_NAME}`
          containsSecret: false
        - text: |
            DATABASE_URL: "postgresql://${self:custom.db_credentials.username}:${self:custom.db_credentials.password}@${self:custom.db_host}:${self:custom.db_port}/blink?schema=public"
          containsSecret: false
        - text: |
            services:
              w3bapp:
                environment:
                  SRV_APPLET_MGR__Postgres_Master: postgresql://${POSTGRES_USER:-w3badmin}:${POSTGRES_PASSWORD:-PaSsW0Rd}@postgres:5432/${POSTGRES_DB:-w3bstream}?sslmode=disable&application_name=mgr
                  SRV_APPLET_MGR__Postgres_ConnMaxLifetime: 10m
                  SRV_APPLET_MGR__Postgres_PoolSize: 5
          # The password in this format is handled by the rule "postgres-url-password-from-env-with-default"
          containsSecret: false
        - text: |
            string url = $"postgresql://{user}:{password}@{host}/{database}";
          containsSecret: false
        - text: |
            @property
            def database_url(self) -> Optional[PostgresDsn]:
                return (
                    f"postgresql+asyncpg://{self.POSTGRES_USER}:{self.POSTGRES_PASSWORD}@"
                    f"{self.POSTGRES_HOST}:{self.POSTGRES_PORT}/{self.POSTGRES_DB}"
                )
          containsSecret: false
        - text: |
            const database =
              process.env.NODE_ENV === "test"
                ? process.env.POSTGRES_DB_TEST
                : process.env.POSTGRES_DB;

            const connectionString = `postgresql://${process.env.POSTGRES_USER}:${process.env.POSTGRES_PASSWORD}@${process.env.POSTGRES_HOST}:${process.env.POSTGRES_PORT}/${database}`;
          containsSecret: false
        - text: |
            engine = create_engine(
                f"postgresql://neylsoncrepalde:{os.environ['PGPASS']}@database-igti.cfowiwu0gidv.us-east-2.rds.amazonaws.com:5432/postgres"
            )
          containsSecret: false
        - text: |
            "postgresql://{{user}}:{{password}}@{{host}}/{{database}}"
          containsSecret: false
        - text: |
            client.secrets.database.configure(
                name='db-connection-name',
                plugin_name='postgresql-database-plugin',
                allowed_roles='role-name',
                connection_url=f'postgresql://{{{{username}}}}:{{{{password}}}}@postgres:5432/postgres?sslmode=disable',
                username='db-username',
                password='db-password',
            )
          containsSecret: false
        - text: |
            "postgresql+psycopg2://scott123:*****@host.name.com/dbname"
          containsSecret: false
        - text: |
            dbconn="postgresql+psycopg2://"+str(conn_login)+":"+str(conn_password)+"@"+str(conn_host)+":"+str(conn_port)+"/"+str(conn_schema)
          containsSecret: false
        - text: |
            "p_engine = create_engine('postgresql://'+p_username+':'+p_pwd+'@'+p_host+':'+str(p_port)+'/'+p_dbname)\n",
          containsSecret: false
        - text: |
            # postgresql://username:password@host:port/database
            conn_string = "postgresql://{}:{}@{}:{}/{}" \
                .format(DB_USER, DB_PASSWORD, DB_ENDPOINT, DB_PORT, DB)
          containsSecret: false
        - text: |
            # Connect to Postgres DB
            self.engine = create_engine('postgresql+psycopg2://{0}:{1}@localhost/cirtkit'.format(DB_USER, DB_PASSWD))
          containsSecret: false
        - text: |
            export const PostgresUrl: DbEnvUrl = {
              envVar: "POSTGRES_URL",
              url:
                `postgresql://${DefaultDbConnection.username}:` +
                `${DefaultDbConnection.password}@${DefaultDbConnection.host}:` +
                `${DefaultDbConnection.port}/${DefaultDbConnection.database}` +
                `?schema=${process.env.DB_SCHEMA}`
            };
          containsSecret: false

    - id: postgres-url-password-from-env-with-default
      rspecKey: S6698
      metadata:
        name: PostgreSQL database passwords should not be disclosed
      detection:
        pre:
          scopes:
            - main
          include:
            content:
              - postgres
              - postgresql
              - postgis
          reject:
            ext:
              - .adoc
              - .example
              - .html
              - .md
              - .mdx
              - .template
            paths:
              - "**/appsettings.Development.json"
              - "**/appsettings.Local.json"
        matching:
          # Look for URIs in the format "protocol://username:${ENV_VAR:-default_password}@server:port/..."
          # The portion "${ENV_VAR:-default_password}" contains a default password that's used if the environment
          # variable isn't set. It's that default password that we're matching.
          # The protocol can be either "postgres", "postgresql", or "postgis". It can also be followed by a subprotocol,
          # e.g. "postgresql+psycopg".
          # Certain special characters need to be percent-encoded so we can break matching when we find them.
          pattern: "\\bpostg(?:res(?:ql)?|is)(?:\\+\\w+)?://[^:@/ ]+(?::[^:@/ ]+){0,100}?:\\$\\{[^:]+:-([^@/ ]+)\\}@"
      examples:
        - text: |
            environment:
              PUBLIC_URL: http://localhost:${PROXY_PORT:-1337}
              POSTGRES_MIGRATIONS: 1
              POSTGRES_MIGRATIONS_SOURCE: postgres://postgres:${POSTGRES_PASSWORD:-secretpgpassword}@postgres:5432/postgres?sslmode=disable
          containsSecret: true
          match: secretpgpassword
        - text: |
            OPENPROJECT_RAILS__RELATIVE__URL__ROOT: "${OPENPROJECT_RAILS__RELATIVE__URL__ROOT:-}"
            DATABASE_URL: postgresql://${DB_USERNAME:-postgres}:${DB_PASSWORD:-postgres}@${DB_HOST:-db}:${DB_PORT:-5432}/${DB_DATABASE:-openproject}
            OPENPROJECT_EDITION: ${OPENPROJECT_EDITION:-standard}
          containsSecret: true
          match: postgres
        - text: |
            OPENPROJECT_RAILS__RELATIVE__URL__ROOT: "${OPENPROJECT_RAILS__RELATIVE__URL__ROOT:-}"
            DATABASE_URL: postgresql://${DB_USERNAME:-postgres}:${DB_PASSWORD:-postgres}@${DB_HOST:-db}:${DB_PORT:-5432}/${DB_DATABASE:-openproject}
            OPENPROJECT_EDITION: ${OPENPROJECT_EDITION:-standard}
          fileName: Doc.html
          containsSecret: false

    - id: postgres-env-pg_password-unquoted
      rspecKey: S6698
      metadata:
        name: PostgreSQL database passwords should not be disclosed
      detection:
        pre:
          scopes:
            - main
          include:
            content:
              - PG_PASSWORD
          reject:
            ext:
              - .adoc
              - .example
              - .html
              - .md
              - .mdx
              - .template
            paths:
              - "**/appsettings.Development.json"
              - "**/appsettings.Local.json"
        matching:
          # looks for occurrences of the string `PG_PASSWORD=` followed by a value that is not enclosed in single or double quotes.
          pattern: "\\bPG_PASSWORD=(?!\\\\?[\"'`]|\\$\\()([^\\s]+)(?:$|\\s)"
      examples:
        # From the RSPEC
        - text: |
            PG_USER=postgres
            PG_PASSWORD=password
            PG_DB=postgres
          containsSecret: false
        - text: |
            environment:
            - PG_USER=
            - PG_PASSWORD=
            - PG_DB=postgres
          containsSecret: false
        # True positive matches
        - text: |
            PG_HOST=localhost
            PG_PASSWORD=P@ssw0rd
            PG_USER=postgres
          containsSecret: true
          match: P@ssw0rd
        - text: |
            if [ "${PG_PASSWORD-}" == "" ]; then
              PG_PASSWORD=dev_DVwgY7H5p3QgiZQr3tCo5X
            fi
          containsSecret: true
          match: dev_DVwgY7H5p3QgiZQr3tCo5X
        # True negative matches
        - text: |
            PG_PASSWORD=`cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 10 | head -n 1`
          containsSecret: false
        - text: |
            PG_PASSWORD=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 10 | head -n 1)
          containsSecret: false
        # Exclusions due to preconditions
        - text: |
            if [ "${PG_PASSWORD-}" == "" ]; then
              PG_PASSWORD=dev_DVwgY7H5p3QgiZQr3tCo5X
            fi
          fileName: Doc.adoc
          containsSecret: false
        # Exclusions due to postconditions
        - text: |
            PG_USER=$DB_USER
            PG_PASSWORD=$DB_PASS
            PG_PORT=5436
          containsSecret: false
        - text: |
            PG_USER=${PG_USER}
            PG_PASSWORD=${PG_PASSWORD}
            PG_DATABASE=${PG_DATABASE}
          containsSecret: false
        - text: |
            PG_USER=env("PG_USER")
            PG_PASSWORD=env("PG_PASSWORD")
            PG_DATABASE=env("PG_DATABASE")
          containsSecret: false
        - text: |
            PG_USER=os.getenv("PG_USER")
            PG_PASSWORD=os.getenv("PG_PASSWORD")
            PG_DATABASE=os.getenv("PG_DATABASE")
          containsSecret: false
        - text: |
            PG_USER=os.environ['PG_USER']
            PG_PASSWORD=os.environ['PG_PASSWORD']
            PG_DATABASE=os.environ['PG_DATABASE']
          containsSecret: false

    - id: postgres-env-pg_password-quoted
      rspecKey: S6698
      metadata:
        name: PostgreSQL database passwords should not be disclosed
      detection:
        pre:
          scopes:
            - main
          include:
            content:
              - PG_PASSWORD
          reject:
            ext:
              - .adoc
              - .example
              - .html
              - .md
              - .mdx
              - .template
            paths:
              - "**/appsettings.Development.json"
              - "**/appsettings.Local.json"
        matching:
          pattern: "\\bPG_PASSWORD=\\\\?[\"'](?!\\$\\()([^\\r\\n\"']+)\\\\?[\"']"
      examples:
        # From the RSPEC
        - text: |
            PG_USER="postgres"
            PG_PASSWORD="password"
            PG_DB="postgres"
          containsSecret: false
        - text: |
            environment:
            - PG_USER=""
            - PG_PASSWORD=""
            - PG_DB="postgres"
          containsSecret: false
        # True positive matches
        - text: |
            PG_HOST="localhost"
            PG_PASSWORD="P@ssw0rd"
            PG_USER="postgres"
          containsSecret: true
          match: P@ssw0rd
        - text: |
            if [ "${PG_PASSWORD-}" == "" ]; then
              PG_PASSWORD="dev_DVwgY7H5p3QgiZQr3tCo5X"
            fi
          containsSecret: true
          match: dev_DVwgY7H5p3QgiZQr3tCo5X
        # True negative matches
        - text: |
            PG_PASSWORD=`cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 10 | head -n 1`
          containsSecret: false
        - text: |
            PG_PASSWORD="$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 10 | head -n 1)"
          containsSecret: false
        # Exclusions due to preconditions
        - text: |
            if [ "${PG_PASSWORD-}" == "" ]; then
              PG_PASSWORD="dev_DVwgY7H5p3QgiZQr3tCo5X"
            fi
          fileName: Doc.example
          containsSecret: false
        # Exclusions due to postconditions
        - text: |
            PG_USER="$DB_USER"
            PG_PASSWORD="$DB_PASS"
            PG_PORT="5436"
          containsSecret: false
        - text: |
            PG_USER="${PG_USER}"
            PG_PASSWORD="${PG_PASSWORD}"
            PG_DATABASE="${PG_DATABASE}"
          containsSecret: false
        - text: |
            PG_USER=env("PG_USER")
            PG_PASSWORD=env("PG_PASSWORD")
            PG_DATABASE=env("PG_DATABASE")
          containsSecret: false
        - text: |
            PG_USER=os.getenv("PG_USER")
            PG_PASSWORD=os.getenv("PG_PASSWORD")
            PG_DATABASE=os.getenv("PG_DATABASE")
          containsSecret: false
        - text: |
            PG_USER=os.environ['PG_USER']
            PG_PASSWORD=os.environ['PG_PASSWORD']
            PG_DATABASE=os.environ['PG_DATABASE']
          containsSecret: false

    - id: psql-cli-unquoted
      rspecKey: S6698
      metadata:
        name: PostgreSQL database passwords should not be disclosed
      detection:
        pre:
          scopes:
            - main
          include:
            content:
              - psql
          reject:
            ext:
              - .adoc
              - .example
              - .html
              - .md
              - .mdx
              - .template
            paths:
              - "**/appsettings.Development.json"
              - "**/appsettings.Local.json"

        matching:
          pattern: "\\bPGPASSWORD=(?!\\\\?[\"'])([^\\s;]+).{1,40}\\bpsql\\b"
      examples:
        - text: |
            PGPASSWORD=password psql -h localhost
          containsSecret: false
        - text: |
            PGPASSWORD=*** psql -h localhost
          containsSecret: false
        - text: |
            PGPASSWORD=${POSTGRES_PASSWORD} psql -h localhost
          containsSecret: false
        - text: |
            PGPASSWORD=P@ssw0rd psql -h localhost
          containsSecret: true
          match: P@ssw0rd
        - text: |
            PGPASSWORD=P@ssw0rd psql -h localhost
          fileName: Doc.template
          containsSecret: false

    - id: psql-cli-quoted
      rspecKey: S6698
      metadata:
        name: PostgreSQL database passwords should not be disclosed
      detection:
        pre:
          scopes:
            - main
          include:
            content:
              - psql
          reject:
            ext:
              - .adoc
              - .example
              - .html
              - .md
              - .mdx
              - .template
            paths:
              - "**/appsettings.Development.json"
              - "**/appsettings.Local.json"

        matching:
          pattern: "\\bPGPASSWORD=\\\\?[\"']([^\\r\\n\"']+)\\\\?[\"'].{1,40}\\bpsql\\b"
      examples:
        - text: |
            PGPASSWORD="password" psql -h localhost
          containsSecret: false
        - text: |
            PGPASSWORD="***" psql -h localhost
          containsSecret: false
        - text: |
            PGPASSWORD="${POSTGRES_PASSWORD}" psql -h localhost
          containsSecret: false
        - text: |
            PGPASSWORD="P@ssw0rd" psql -h localhost
          containsSecret: true
          match: P@ssw0rd
        - text: |
            PGPASSWORD="P@ssw0rd" psql -h localhost
          fileName: Doc.mdx
          containsSecret: false




© 2015 - 2025 Weber Informatics LLC | Privacy Policy