!55 开源之夏2023-openGauss权限扫描

Merge pull request !55 from 陈贤文/master
This commit is contained in:
opengauss_bot 2023-10-23 08:31:17 +00:00 committed by Gitee
commit 8eba41dd00
No known key found for this signature in database
GPG Key ID: 173E9B9CA92EEF8F
68 changed files with 4775 additions and 0 deletions

33
OpenGaussPrivilegeScan/.gitignore vendored Normal file
View File

@ -0,0 +1,33 @@
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/

View File

@ -0,0 +1,403 @@
## Gauss数据库权限识别项目
使用postgresql驱动和MyBatis连接OpenGauss识别数据库三权分立的管理员权限识别用户或角色对数据库和表格的操作权限识别所有用户列表。
![](https://cdn.jsdelivr.net/gh/52chen/imagebed2023@main/image-20230918165423593.png)
**使用方法**
通过git下载源码
导入`/lib/opengauss-jdbc-3.1.0.jar /lib/postgresql.jar ` jar包
更新Maven依赖
更新数据库链接信息
**软件需求**
- JDK 8
- SpringBoot 2.4.2
- Maven
- mybatis-plus 3.5.3
- LayUI
### 2.1 工程布局
![](https://cdn.jsdelivr.net/gh/52chen/imagebed2023@main/image-20230925200022010.png)
```sh
OpenGaussPrivilegeScan
│ .gitignore
│ pom.xml
│ README.md
├─lib
│ └─openGauss-3.1.0-JDBC
│ opengauss-jdbc-3.1.0.jar
│ postgresql.jar
│ README_cn.md
│ README_en.md
├─src
│ ├─main
│ │ ├─java
│ │ │ └─com
│ │ │ └─mcx
│ │ │ └─gaussprivilege
│ │ │ │ GaussTestApplication.java
│ │ │ │
│ │ │ ├─controller
│ │ │ │ AuditAdminController.java
│ │ │ │ CreateRoleAdminController.java
│ │ │ │ PgUserController.java
│ │ │ │ RolDatPrivilegeController.java
│ │ │ │ RolTablePrivilegeController.java
│ │ │ │ SysAdminController.java
│ │ │ │ TableController.java
│ │ │ │ TestController.java
│ │ │ │
│ │ │ ├─dao
│ │ │ │ AuditAdminMapper.java
│ │ │ │ CreateRoleAdminMapper.java
│ │ │ │ PgUserMapper.java
│ │ │ │ RolDatPrivilegeMapper.java
│ │ │ │ RolTablePrivilegeMapper.java
│ │ │ │ SysAdminMapper.java
│ │ │ │ TableMapper.java
│ │ │ │ TbClassMapper.java
│ │ │ │
│ │ │ ├─entity
│ │ │ │ PgUser.java
│ │ │ │ RolDatPrivilege.java
│ │ │ │ RoleAdmin.java
│ │ │ │ RolTablePrivilege.java
│ │ │ │ Table.java
│ │ │ │ TbClass.java
│ │ │ │
│ │ │ ├─service
│ │ │ │ AuditAdminService.java
│ │ │ │ CreateRoleAdminService.java
│ │ │ │ PgUserService.java
│ │ │ │ RolDatPrivilegeService.java
│ │ │ │ RolTablePrivilegeService.java
│ │ │ │ SysAdminService.java
│ │ │ │ TableService.java
│ │ │ │ TbClassService.java
│ │ │ │
│ │ │ └─test
│ │ │ jdbcDriverTest.java
│ │ │
│ │ └─resources
│ │ │ application.properties
│ │ │ GaussApiTest.http
│ │ │
│ │ ├─JDBCLIB
│ │ │ opengauss-jdbc-3.1.0.jar
│ │ │ postgresql.jar
│ │ │
│ │ └─static
│ │ │ index.html
│ │ │
│ │ ├─image
│ │ │ 三权分立-安全.drawio.svg
│ │ │ 三权分立-审计.drawio.svg
│ │ │ 三权分立-系统.drawio.svg
│ │ │ 三权分立.drawio
│ │ │ 三权分立.png
```
### 2.2 项目配置文件
pom.xml 依赖文件如下
```xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mcx</groupId>
<artifactId>GaussPrivilegeScan</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>GaussPrivilegeScan</name>
<description>GaussPrivilegeScan</description>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-boot.version>2.4.2</spring-boot.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.3</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.70</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
<scope>provided</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring-boot.version}</version>
<configuration>
<mainClass>com.mcx.gaussprivilege.GaussTestApplication</mainClass>
<skip>true</skip>
</configuration>
<executions>
<execution>
<id>repackage</id>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
```
手动导入postgresql和opengauss的jar包。
![image-20230925200022010](https://cdn.jsdelivr.net/gh/52chen/imagebed2023@main/image-20230925200022010.png)
application.properties
```properties
server.port=8080
#spring.datasource.url=jdbc:postgresql://103.91.210.232:11343/db_department
spring.datasource.url=jdbc:postgresql://192.168.161.18:5432/db_department
spring.datasource.username=admin_department
spring.datasource.password=OpenGauss@123
spring.datasource.driver-class-name=org.postgresql.Driver
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
mybatis-plus.configuration.map-underscore-to-camel-case=true
```
### 2.3 创建实体类
![image-20230918163959285](https://cdn.jsdelivr.net/gh/52chen/imagebed2023@main/image-20230918163959285.png)
举例:
在entitys目录下创建“RolTablePrivilege.java”实体类
```java
package com.example.gausstest.entity;
import lombok.Data;
@Data
public class RolTablePrivilege {
private String rolName;
private String tableName;
private String privileges;
}
```
### 2.4 创建Mapper
![image-20230918164037128](https://cdn.jsdelivr.net/gh/52chen/imagebed2023@main/image-20230918164037128.png)
在dao目录下创建“RolTablePrivilegeMapper.java”
```java
package com.example.gausstest.dao;
import entity.com.mcx.gaussprivilege.RolTablePrivilege;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface RolTablePrivilegeMapper {
@Select("SELECT grantee AS rol_name, table_name, string_agg(privilege_type, ', ') AS privileges FROM information_schema.role_table_grants GROUP BY grantee,table_name")
List<RolTablePrivilege> getAllRolTablePrivileges();
}
```
### 2.5 创建Service
![image-20230918164111898](https://cdn.jsdelivr.net/gh/52chen/imagebed2023@main/image-20230918164111898.png)
在service目录下创建“RolTablePrivilegeService.java”文件。
```java
package com.example.gausstest.service;
import dao.com.mcx.gaussprivilege.RolTablePrivilegeMapper;
import entity.com.mcx.gaussprivilege.RolTablePrivilege;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class RolTablePrivilegeService {
@Autowired
RolTablePrivilegeMapper rolTablePrivilegeMapper;
public List<RolTablePrivilege> getAllRolTablePrivileges() {
return rolTablePrivilegeMapper.getAllRolTablePrivileges();
}
}
```
### 2.6 创建Controller
![image-20230918164148839](https://cdn.jsdelivr.net/gh/52chen/imagebed2023@main/image-20230918164148839.png)
在controller目录下创建“RolTablePrivilege.java"文件。
```java
package com.example.gausstest.controller;
import entity.com.mcx.gaussprivilege.RolTablePrivilege;
import service.com.mcx.gaussprivilege.RolTablePrivilegeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class RolTablePrivilegeController {
@Autowired
RolTablePrivilegeService rolTablePrivilegeService;
@GetMapping("/rolTablePrivileges")
public List<RolTablePrivilege> getAllRolTablePrivileges() {
return rolTablePrivilegeService.getAllRolTablePrivileges();
}
}
```
### 2.7 创建Application
```java
package com.example.gausstest;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class GaussTestApplication {
public static void main(String[] args) {
SpringApplication.run(GaussTestApplication.class, args);
}
}
```
### 2.8 测试
浏览器中访问: localhost:8080
![](https://cdn.jsdelivr.net/gh/52chen/imagebed2023@main/image-20230918165423593.png)
接口调试:
IDEA中打印的日志
![在这里插入图片描述](https://raw.githubusercontent.com/52chen/imagebed2023/main/c1bb59d192f1489381428d1dbfb687c0.png)
### 2.9 8080端口转发
> 这里设置了一个端口转发:
>
> 访问: [权限扫描仪表盘 (cpolar.cn)](https://a0a4901.r2.cpolar.cn/)
转发自https://www.cnblogs.com/probezy/p/16742417.html
在没有公网IP的情况下想要实现外网访问内网可以通过cpolar内网穿透来解决只需要简单安装客户端就可以创建隧道将本地端口映射到公网上生成公网地址。
> - 支持永久免费使用随机域名、1M带宽、4条免费隧道
> - 支持http/https/tcp协议
> - 不限制流量
比如将本地8080端口下的web服务发布到公网可访问
> cpolar下载地址https://www.cpolar.com/
注册并安装cpolar内网穿透。
浏览器访问http://localhost:9200/登录cpolar web UI管理界面
左侧仪表盘——隧道管理——创建隧道
隧道名称:可自定义
协议http
本地地址8080填写你想要映射的本地端口号
域名类型:免费选择“随机域名”,付费用户可选择配置固定的二级子域名或者自定义域名
地区:选择合适的
![img](https://raw.githubusercontent.com/52chen/imagebed2023/main/25691-20220929173410026-283141293.png)
隧道创建成功后可在状态——在线隧道列表查看到所映射的公网地址公网用户访问该公网地址就可以访问到在本地内网搭建的web服务。
![img](https://raw.githubusercontent.com/52chen/imagebed2023/main/25691-20220929173415845-554180780.png)

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,740 @@
# openGauss-安全管理机制项目报告
> 主要内容:
>
> openGauss数据库权限管理模型、权限规划示例、权限识别项目具体实施方法
# 1. 项目信息
## 1.1 openGauss数据库权限管理模型
由于数据库中存储着大量重要数据和各类敏感信息并且为持有不同权限的合法用户提供数据共享服务这就要求数据库具备完善的安全防御机制来抵抗来自内部和外部的恶意攻击以保障数据不丢失、隐私不泄露以及数据不被篡改等。当前openGauss数据库已经构建了纵深防御的安全体系保障数据库在应用中的安全。完善的权限管理机制可以有效阻断恶意用户的越权操作。
常见的权限控制模型有三种:**基于策略的访问控制模型,基于角色的访问控制模型以及基于会话和角色的访问控制模型。**openGauss数据库采用**基于角色的权限访问控制模型(RBAC)**,利用角色来组织和管理权限,能够大大简化对权限的授权管理。借助角色机制,当给一组权限相同的用户授权时,只需将权限授予角色,再将角色授予这组用户即可,不需要对用户逐一授权。而且利用角色权限分离可以很好地控制不同用户拥有不同的权限,相互制约达到平衡。
### 1.1.1 基于角色的权限访问控制模型(RBAC)
`RBAC`思想简单地说,一个用户拥有若干角色,每一个角色拥有若干权限,每一个角色拥有若干个菜单,这样,就构造成“用户-角色-权限”、“角色-菜单” 的授权模型。在这种模型中,用户与角色、角色与权限、角色与菜单之间构成了多对多的关系。
在openGauss数据库中用户和角色是基本相同的概念唯一的区别是在创建角色的时默认没有LOGIN权限也不会自动创建同名的模 也就是说一个拥有LOGIN权限的角色可以被认为是一个用户。在以下的介绍中我们统一通过用户(USER) 来连接、访问数据库以及执行SQL通过角色(ROLE来组织和管理权限。我们通过将不同的权限打包成角色授予用户使得用户获得该角色中的所有权限。同时通过改变角色的权限该角色所包含的所有成员的权限也会被自动修改。
在openGauss数据库系统中权限分为两种**系统权限和对象权限**。
- 系统权限是指系统规定用户使用数据库的权限,比如登录数据库、创建数据库、创建用户/角色、创建安全策略等。
- 对象权限是指在数据库、模式、表、视图、函数等数据库对象上执行特殊动作的权限,不同的对象类型与不同的权限相关联,比如数据库的连接权限,表的查看、更新、插入等权限,函数的执行权限等。基于特定的对象来描述对象权限才是有意义的。
#### **系统权限**
系统权限又称用户属性,具有特定属性的用户会获得指定属性所对应的权限。**系统权限无法通过角色ROLE被继承。**在创建用户或角色时可以通过SQL语句CREATE ROLE/USER指定用户具有某些属性或者通过ALTER ROLE/USER的方式给用户/角色添加用户属性或取消用户属性。
openGauss数据库支持如下系统权限的授予和回收
| 系统权限 | 权限范围 |
| ----------- | ------------------------------------------------------------ |
| SYSADMIN | 允许用户创建数据库,创建表空间 允许用户创建用户/角色 允许用户查看、删除审计日志 允许用户查看其它用户的数据 |
| MONADMIN | 允许用户对系统模式dbe_perf及该模式下的监控视图或函数进行查看和权限管理 |
| OPRADMIN | 允许用户使用Roach工具执行数据库备份和恢复 |
| POLADMIN | 允许用户创建资源标签、创建动态数据脱敏策略和统一审计策略 |
| AUDITADMIN | 允许用户查看、删除审计日志 |
| CREATEDB | 允许用户创建数据库 |
| USEFT | 允许用户创建外表 |
| CREATEROLE | 允许用户创建用户/角色 |
| INHERIT | 允许用户继承所在组的角色的权限 |
| LOGIN | 允许用户登录数据库 |
| REPLICATION | 允许用户执行流复制相关操作 |
openGauss提供SQL语句CREATE/ALTER ROLE/USER实现系统权限的授予和回收示例如下
```shell
#例1创建角色role1同时授予role1创建数据库的权限
openGauss=# CREATE ROLE role1 WITH CREATEDB password 'openGauss@2021';
CREATE ROLE
#例2授予角色role1监控管理员的权限同时取消创建数据库的权限
openGauss=# ALTER ROLE role1 WITH MONADMIN NOCREATEDB;
ALTER ROLE
#例3查看系统表pg_authid或系统视图pg_roles获取角色role1的相关信息
openGauss=# SELECT rolname,rolcreatedb,rolmonitoradmin FROM pg_authid WHERE rolname= 'role1';
rolname | rolcreatedb | rolmonitoradmin
---------+-------------+-----------------
role1 | f | t
(1 row)
```
#### **对象权限**
对象所有者缺省具有该对象上的所有操作权限比如修改、删除对象的权限查看对象的权限将对象的操作权限授予其他用户或撤销已经授予的操作权限等。其中对象的ALTER、 DROP、COMMENT、INDEX、VACUUM以及对象的可再授予权限属于所有者固有的权限隐式拥有。但对象所有者可以撤消自己的普通权限例如使表对自己以及其他人都只可读。
**对象权限可以通过角色ROLE被继承这样方便用户将这些单个的权限打包成一个角色进行权限管理。**openGauss数据库针对每一类数据库对象支持如下对象权限
| 对象 | 权限 | 权限说明 |
| ---------- | ---------- | ------------------------------------------------ |
| TABLESPACE | CREATE | 允许用户在指定的表空间中创建表 |
| | ALTER | 允许用户对指定的表空间执行ALTER语句修改属性 |
| | DROP | 允许用户删除指定的表空间 |
| | COMMENT | 允许用户对指定的表空间定义或修改注释 |
| DATABASE | CONNECT | 允许用户连接到指定的数据库 |
| | TEMP | 允许用户在指定的数据库中创建临时表 |
| | CREATE | 允许用户在指定的数据库里创建模式 |
| | ALTER | 允许用户对指定的数据库执行ALTER语句修改属性 |
| | DROP | 允许用户删除指定的数据库 |
| | COMMENT | 允许用户对指定的数据库定义或修改注释 |
| SCHEMA | CREATE | 允许用户在指定的模式中创建新的对象 |
| | USAGE | 允许用户访问包含在指定模式内的对象 |
| | ALTER | 允许用户对指定的模式执行ALTER语句修改属性 |
| | DROP | 允许用户删除指定的模式 |
| | COMMENT | 允许用户对指定的模式定义或修改注释 |
| FUNCTION | EXECUTE | 允许用户使用指定的函数 |
| | ALTER | 允许用户对指定的函数执行ALTER语句修改属性 |
| | DROP | 允许用户删除指定的函数 |
| | COMMENT | 允许用户对指定的函数定义或修改注释 |
| TABLE | INSERT | 允许用户对指定的表执行INSERT语句插入数据 |
| | DELETE | 允许用户对指定的表执行DELETE语句删除表中数据 |
| | UPDATE | 允许用户对指定的表执行UPDATE语句 |
| | SELECT | 允许用户对指定的表执行SELECT语句 |
| | TRUNCATE | 允许用户执行TRUNCATE语句删除指定表中的所有记录 |
| | REFERENCES | 允许用户对指定的表创建一个外键约束 |
| | TRIGGER | 允许用户在指定的表上创建触发器 |
| | ALTER | 允许用户对指定的表执行ALTER语句修改属性 |
| | DROP | 允许用户删除指定的表 |
| | COMMENT | 允许用户对指定的表定义或修改注释 |
| | INDEX | 允许用户在指定表上创建索引,并管理指定表上的索引 |
| | VACUUM | 允许用户对指定的表执行ANALYZE和VACUUM操作 |
openGauss提供SQL语句GRANT/REVOKE实现对象权限的授予和回收
```shell
#创建连接
[omm@localhost root]$ gsql -d postgres -r
gsql ((openGauss 3.1.0 build 4e931f9a) compiled at 2022-09-29 14:40:01 commit 0 last mr release)
Non-SSL connection (SSL connection is recommended when requiring high-security)
Type "help" for help.
#创建测试数据
openGauss=# create database testdb;
CREATE DATABASE
openGauss=# \c testdb
Non-SSL connection (SSL connection is recommended when requiring high-security)
You are now connected to database "testdb" as user "omm".
testdb=# create user test identified by 'test@123';
NOTICE: The encrypted password contains MD5 ciphertext, which is not secure.
CREATE ROLE
testdb=# create user user1 identified by 'test@123';
NOTICE: The encrypted password contains MD5 ciphertext, which is not secure.
CREATE ROLE
testdb=# alter database testdb owner to test;
ALTER DATABASE
testdb=# set search_path to test;
SET
testdb=# create table tbl1 (id int);
CREATE TABLE
testdb=# insert into tbl1 values(1),(2),(3);
INSERT 0 3
#例1将对表tbl1进行select的权限以及将select再赋权的权限授予用户user1,
#赋权后用户user1有权对tbl执行select操作且user1有权限将select权限再赋予其他用户
[omm@home ~]$ gsql -d testdb -c "GRANT select ON TABLE test.tbl1 TO user1 WITH GRANT OPTION"
GRANT
[omm@home ~]$ gsql -d testdb -U user1 -W test@123 -c "select * from test.tbl1"
ERROR: permission denied for schema test
LINE 1: select * from test.tbl1
^
DETAIL: N/A
#如上因为user1没有test模式的usage权限所以即便给他授权了模式下的表的select权限也访问不了
gsql -d testdb -c "GRANT usage ON schema test TO user1"
[omm@home ~]$ gsql -d testdb -c "GRANT usage ON schema test TO user1"
GRANT
[omm@home ~]$ gsql -d testdb -U user1 -W test@123 -c "select * from test.tbl1"
id
----
1
2
3
(3 rows)
#此时user1没有对表alter、drop的权限
[omm@home ~]$ gsql -d testdb -U user1 -W test@123 -c "drop table test.tbl1"
ERROR: permission denied for relation tbl1
DETAIL: N/A
[omm@home ~]$ gsql -d testdb -U user1 -W test@123 -c "alter table test.tbl1 add column name text"
ERROR: permission denied for relation tbl1
DETAIL: N/A
#例2将对表tbl1进行alter和drop的权限赋给用户user1
#赋权后用户user1有权对tbl1进行修改ALTER和删除DROP操作
[omm@home ~]$ gsql -d testdb -c "GRANT alter, drop ON TABLE test.tbl1 TO user1;"
GRANT
[omm@home ~]$ gsql -d testdb -U user1 -W test@123 -c "alter table test.tbl1 add column name text"
ALTER TABLE
#例3撤销用户user1对表tbl进行select的权限
[omm@home ~]$ gsql -d testdb -U user1 -W test@123 -c "select * from test.tbl1"
id | name
----+------
1 |
2 |
3 |
(3 rows)
[omm@home ~]$ gsql -d testdb -c "REVOKE select ON test.tbl1 FROM user1"
REVOKE
#撤销后用户user1对tbl进行select操作会报错
[omm@home ~]$ gsql -d testdb -U user1 -W test@123 -c "select * from test.tbl1"
ERROR: permission denied for relation tbl1
DETAIL: N/A
```
本次项目的目的就在于区分对象权限的情况:
![image-20230905204613892](https://fastly.jsdelivr.net/gh/52chen/imagebed2023@main/uPic/image-20230905204613892.png)
> `CREATE USER`
>
> 通过CREATE USER创建的用户默认具有LOGIN权限。
> 通过CREATE USER创建用户的同时系统会在执行该命令的数据库中为该用户创建一个同名的SCHEMA。
> 系统管理员在普通用户同名schema下创建的对象所有者为schema的同名用户非系统管理员
>
> `CREATE ROLE`
> 角色是拥有数据库对象和权限的实体。在不同的环境中角色可以认为是一个用户,一个组或者兼顾两者。
> 在数据库中添加一个新角色,角色无登录权限。
> 创建角色的用户必须具备CREATE ROLE的权限或者是系统管理员。
>
> `schema`
>
> Schema又称作模式。通过管理Schema允许多个用户使用同一数据库而不相互干扰可以将数据库对象组织成易于管理的逻辑组同时便于将第三方应用添加到相应的Schema下而不引起冲突。
>
>
### 1.1.2 三权分立机制
伴随着数据库的发展以及所面向业务场景的扩展对数据库权限分离以及权限管理的细粒度划化提出了更高的要求为了满足多样化用户的业务安全要求openGauss数据库针对权限模型进行了更细粒度的权限划分使得用户可以更灵活地依据实际业务进行用户权限分配和管理除了基本系统权限和对象权限的划分外还有一些高阶的权限管理机制用来满足客户的业务诉求比如三权分立机制。
openGauss安装完成后会得到一个具有最高权限的超级用户。数据库超级用户的高权限意味着该用户可以做任何系统管理操作和数据管理操作,甚至可以修改数据库对象,包括接下来将要介绍的审计日志信息。对于企业管理来说,手握超级用户权限的管理人员可以在无人知晓的情况下改变数据行为,这带来的后果是不可想象的。
为了很好地解决权限高度集中的问题在openGauss系统中引入三权分立角色模型如图所示。三权分立角色模型最关键的**三个角色为安全管理员、系统管理员和审计管理员**。其中,安全管理员用于创建数据管理用户;系统管理员对创建的用户进行赋权;审计管理员则审计安全管理员、系统管理员、普通用户实际的操作行为。
![三权分立](https://raw.githubusercontent.com/52chen/imagebed2023/main/2021042510524970.png)
通过三权分立角色模型实现权限的分派,且三个管理员角色独立行使权限,相互制约制衡。使得整个系统的权限不会因为权限集中而引入安全的风险。
事实上,产品使用过程中的安全是技术本身与组织管理双重保障的结果,在系统实现三权分立模型后,需要有三个对应的产品自然人分别握有对应的账户信息,以达到真正权限分离的目的。
三权分立是对系统权限管理机制的补充核心思想是将管理数据库对象的权限、管理用户的权限和管理审计日志的权限分离从而避免一个管理员拥有过度集中的权利带来的高风险。通过将GUC参数`enableSeparationOfDuty`设置为on来打开三权分立开关。
```shell
openGauss=# select name,setting,unit,context from pg_settings where name ~ 'enableSeparationOfDuty';
name | setting | unit | context
------------------------+---------+------+------------
enableSeparationOfDuty | off | | postmaster
(1 row)
```
```sql
ALTER SYSTEM SET enableSeparationOfDuty TO 'on';
-- 开启分离
```
三权分立开关打开后, SYSADMIN的权限范围将缩小不再包括允许创建用户/角色的权限也不再包括允许查看、删除数据库审计日志的权限。SYSADMINCREATEROLEAUDITADMIN三种系统权限的权限范围互相隔离互不影响而且一个用户仅能被赋予其中一个属性。
三权分立打开后的权限范围如下:
| 系统权限 | 权限范围 |
| ---------- | ------------------------------ |
| SYSADMIN | 允许用户创建数据库,创建表空间 |
| CREATEROLE | 允许用户创建用户/角色 |
| AUDITADMIN | 允许用户查看、删除审计日志 |
> ```sql
> SHOW audit_enabled; #查询审计是否开启
> ```
#### 列级访问控制
在一些业务场景中,数据表中的某些列存储了重要的信息,需要对用户不可见,但其他列的数据又需要用户能够查看或操作,此时就需要针对数据表的特定列做访问控制,实现针对用户的列级别的访问控制。
openGauss提供SQL语句GRANT/REVOKE实现针对列对象的权限授予和回收
```shell
#创建测试数据
gsql -d postgres -r
create database testdb;
\c testdb
create user test identified by 'test@123';
create user user1 identified by 'test@123';
alter database testdb owner to test;
set search_path to test;
create table tbl (id int,name varchar(20));
insert into tbl values(1,'test1'),(2,'test2'),(3,'test3');
#例1将对表tbl的第一列(id)进行select的权限和对表tbl的第二列(name)进行update的权限授予用户user1
#赋权后用户user1有权对tbl的第一列执行select操作和对第二列执行update操作
[omm@home ~]$ gsql -d testdb -c "GRANT select(id),update(name) ON TABLE test.tbl TO user1;"
GRANT
[omm@home ~]$ gsql -d testdb -U user1 -W test@123 -c "select id from test.tbl"
ERROR: permission denied for schema test
LINE 1: select id from test.tbl
^
DETAIL: N/A
#如上因为user1没有test模式的usage权限所以即便给他授权了模式下的表的select权限也访问不了
[omm@home ~]$ gsql -d testdb -c "GRANT usage ON schema test TO user1"
GRANT
[omm@home ~]$ gsql -d testdb -U user1 -W test@123 -c "select id from test.tbl"
id
----
1
2
3
(3 rows)
[omm@home ~]$ gsql -d testdb -U user1 -W test@123 -c "select name from test.tbl"
ERROR: permission denied for relation tbl
DETAIL: N/A
[omm@home ~]$ gsql -d testdb -U user1 -W test@123 -c "update test.tbl set name = 'haha' where id=3"
UPDATE 1
[omm@home ~]$ gsql -d testdb -U user1 -W test@123 -c "update test.tbl set id = 4 where id=3"
ERROR: permission denied for relation tbl
DETAIL: N/A
#例2撤销用户user1对表tbl的第一列id进行select的权限
#撤销后用户user1不再具有查看表tbl的第一列id数据的权限
[omm@home ~]$ gsql -d testdb -c "REVOKE select(id) ON test.tbl FROM user1"
REVOKE
[omm@home ~]$ gsql -d testdb -U user1 -W test@123 -c "select id from test.tbl"
ERROR: permission denied for relation tbl
DETAIL: N/A
```
#### 行级访问控制
在实际业务中还存在另外一种场景同一张数据表只允许用户查看满足特定条件的行数据此时就需要将访问控制精确到数据表的行级别使得不同用户执行相同的SQL查询、更新或删除操作读取到的结果是不同的。
用户可以在数据表上创建行级访问控制(row level security)策略该策略是针对特定数据库用户、特定SQL操作生效的表达式。当数据库用户访问数据表时满足策略条件的行对用户可见不满足条件的行对用户不可见从而实现针对用户的行级别的访问控制。
![img](https://fastly.jsdelivr.net/gh/52chen/imagebed2023@main/uPic/b2c31bea13d4fbc8a600eea7fe1fefcf.jpeg)
openGauss提供SQL语句CREATE/ALTER/DROP ROW LEVEL SECURITY进行行级访问权限策略的创建/修改/删除操作:
```shell
#创建测试数据
gsql -d postgres -r
create database testdb;
\c testdb
create user test identified by 'test@123';
create user mary identified by 'test@123';
create user tom identified by 'test@123';
alter database testdb owner to test;
set search_path to test;
#步骤1创建信息表pat_info记录医院病人的个人信息
create table pat_info(patience varchar(20),doctor varchar(20),age int);
insert into pat_info values('peter','mary',25),('bob','mary',56),('julie','tom',38)
#查询表数据
[omm@home ~]$ gsql -d testdb -U test -W test@123 -c "select * from test.pat_info"
patience | doctor | age
----------+--------+-----
peter | mary | 25
bob | mary | 56
julie | tom | 38
(3 rows)
#步骤2:创建行级访问控制策略,使得医生只能查看属于自己的病人信息:
[omm@home ~]$ gsql -d testdb -c "CREATE ROW LEVEL SECURITY POLICY rls_select ON test.pat_info FOR select USING(doctor=current_user)"
CREATE ROW LEVEL SECURITY POLICY
#步骤3打开信息表pat_info上的行级访问控制开关
[omm@home ~]$ gsql -d testdb -c "ALTER TABLE test.pat_info ENABLE ROW LEVEL SECURITY;"
ALTER TABLE
#步骤4将信息表pat_info的查看权限赋予所有人
[omm@home ~]$ gsql -d testdb -c "grant select on table test.pat_info to public;"
GRANT
#步骤5Mary医生的查看结果
[omm@home ~]$ gsql -d testdb -U mary -W test@123 -c "select * from test.pat_info"
ERROR: permission denied for schema test
LINE 1: select * from test.pat_info
^
DETAIL: N/A
[omm@home ~]$
[omm@home ~]$ gsql -d testdb -c "GRANT usage ON schema test TO mary"
GRANT
[omm@home ~]$ gsql -d testdb -U mary -W test@123 -c "select * from test.pat_info"
patience | doctor | age
----------+--------+-----
peter | mary | 25
bob | mary | 56
(2 rows)
#Tom医生的查看结果
[omm@home ~]$ gsql -d testdb -c "GRANT usage ON schema test TO tom"
GRANT
[omm@home ~]$ gsql -d testdb -U tom -W test@123 -c "select * from test.pat_info"
```
## 1.2 权限查询命令示例
> vmware启动后opengauss可能没有打开需要人工开启
>
> ```sh
> su - omm #有空格 有’-
> ```
1、查询当前数据所有用户及其权限\du
![image-20230907101238084](https://fastly.jsdelivr.net/gh/52chen/imagebed2023@main/uPic/image-20230907101238084.png)
或者通过`PG_USER\pg_authid`可以查看数据库中所有用户的列表还可以查看用户IDUSESYSID和用户权限。
```sql
SELECT * FROM pg_user;
SELECT * FROM pg_authid;
```
2、查看数据库中包含的表
例如,在`PG_TABLES`系统表中查看public schema中包含的所有表。
```sql
SELECT distinct(tablename) FROM pg_tables WHERE SCHEMANAME = 'public';
```
> ```sql
> create user testUser identified by 'test@123';
> -- 查询用户
> SELECT * FROM pg_user;
> -- 查询角色
> SELECT * FROM pg_roles;
> -- 在 PostgreSQL 中创建一个用户user会自动创建一个与该用户同名的角色role
> -- 用户和角色在 PostgreSQL 中是密切相关的概念,可以说用户就是一个具有登录能力的角色。
> ```
3、查询用户数据库的权限
```shell
opengauss=# select a.datname,b.rolname,string_agg(a.pri_t,',') from (select datname,(aclexplode(COALESCE(datacl, acldefault('d'::"char",datdba)))).grantee as grantee,(aclexplode(COALESCE(datacl, acldefault('d'::"char", datdba)))).privilege_type as pri_t from pg_database where datname not like 'template%') a,pg_roles b where (a.grantee=b.oid or a.grantee=0) and b.rolname='opengauss' group by a.datname,b.rolname;
datname | rolname | string_agg
---------------+-----------+--------------------------------------------
testdb | opengauss | TEMPORARY,CONNECT
db_department | opengauss | TEMPORARY,CONNECT
postgres | opengauss | TEMPORARY,CONNECT
opengauss | opengauss | TEMPORARY,CONNECT,CREATE,TEMPORARY,CONNECT
(4 rows)
```
显示用户opengauss对于opengauss数据库具有`TEMPORARY,CONNECT,CREATE,TEMPORARY,CONNECT`等权限
4、根据用户名查询table 权限,可以通过视图`information_schema.table_privileges`来查看为了方便展示sql如下
```shell
opengauss=# select table_name,table_schema,grantee,string_agg(privilege_type,',') from information_schema.table_privileges where grantee='opengauss' group by table_name,table_schema,grantee;
```
> 具体解释如下:
>
> - `SELECT table_name, table_schema, grantee, string_agg(privilege_type, ',')`:选择 `table_name`、`table_schema`、`grantee` 和使用逗号分隔的权限类型privilege_type的聚合结果。
> - `FROM information_schema.table_privileges`:从 `information_schema` 系统表中查询表级别的权限信息。
> - `WHERE grantee='test'`筛选出授权对象grantee`test` 的记录。
> - `GROUP BY table_name, table_schema, grantee`:按照 `table_name`、`table_schema` 和 `grantee` 进行分组。
>
> 通过执行这条查询语句,可以获取用户或角色 `test` 对每个表的权限信息。查询结果将包括表的名称、所属的模式schema、授权对象`test`)、以逗号分隔的权限类型列表。这可以帮助管理员查看特定用户或角色在数据库中有权访问哪些表,并了解其所具有的权限类型。
![image-20230907101858817](https://fastly.jsdelivr.net/gh/52chen/imagebed2023@main/uPic/image-20230907101858817.png)
如图所示omm对于各个表都具有权限。
## 1.3 方案描述
需求:
设计用户权限检查项,开发扫描程序,实现数据库权限扫描功能,扫描数据库中是否有违规操作的可能和安全隐患,完成设计文档。
### 1.3.1 三权分立权限安全策略
扫描当前数据库中安全管理员、系统管理员和审计管理员,三权分立开启之后,权限管理更加严格,如图无法给审计管理员赋予系统管理员的权限。
![三权分立-审计.drawio](https://cdn.jsdelivr.net/gh/52chen/imagebed2023@main/%E4%B8%89%E6%9D%83%E5%88%86%E7%AB%8B-%E5%AE%A1%E8%AE%A1.drawio.svg)
**1安全管理员rolcreaterole**
```sql
CREATE USER poladmin WITH CREATEROLE password "gauss@123";
# 决定一个角色是否可以创建新角色也就是执行CREATE ROLE和CREATE USER。 一个拥有CREATEROLE权限的角色也可以修改和删除其他角色。
SELECT rolname,rolsuper,rolcreaterole,rolsystemadmin,rolauditadmin FROM pg_roles WHERE rolcreaterole = 'true';
SELECT *
FROM pg_roles
WHERE rolcreaterole = 'true' AND rolname != 'omm';
-- 如果有查询结果表明存在违规
```
非[三权分立](https://docs.opengauss.org/zh/docs/3.0.0/docs/Developerguide/三权分立.html)时只有系统管理员和具有CREATEROLE属性的系统管理员用户才能创建、修改或删除角色。三权分立下只有初始用户和具有CREATEROLE属性的安全管理员的用户才能创建、修改或删除角色下面以安全管理员为例
- 查询createrole的用户只能是具有该createrole权限不能具有审计和系统管理权限。
```sql
select table_name,table_schema,grantee,string_agg(privilege_type,',') from information_schema.table_privileges where grantee='audadmin' group by table_name,table_schema,grantee;
```
![三权分立-安全.drawio](https://cdn.jsdelivr.net/gh/52chen/imagebed2023@main/%E4%B8%89%E6%9D%83%E5%88%86%E7%AB%8B-%E5%AE%89%E5%85%A8.drawio.svg)
**2 审计管理员rolauditadmin**
```sql
CREATE USER poladmin WITH AUDITADMIN password "gauss@123";
# AUDITADMIN | NOAUDITADMIN 定义角色是否有审计管理属性。
SELECT *
FROM pg_roles
WHERE rolauditadmin = 'true' AND rolname != 'omm';
```
![三权分立-审计.drawio](https://cdn.jsdelivr.net/gh/52chen/imagebed2023@main/三权分立-审计.drawio.svg)
**3系统管理员rolsystemadmin**
```sql
CREATE USER poladmin WITH SYSADMIN password "gauss@123";
# SYSADMIN | NOSYSADMIN 决定一个新角色是否为“系统管理员”具有SYSADMIN属性的角色拥有系统最高权限。缺省为NOSYSADMIN。
SELECT *
FROM pg_roles
WHERE rolsystemadmin = 'true' AND rolname != 'omm';
```
![三权分立-系统.drawio](https://cdn.jsdelivr.net/gh/52chen/imagebed2023@main/%E4%B8%89%E6%9D%83%E5%88%86%E7%AB%8B-%E7%B3%BB%E7%BB%9F.drawio.svg)
### 1.3.2 表格、数据库权限安全策略
#### 1查询用户对各个表的权限
实现思路:
根据SQL语句
```sql
SELECT grantee AS rol_name, table_name, string_agg(privilege_type, ', ') AS privileges FROM information_schema.role_table_grants GROUP BY grantee,table_name;
```
设计SpringBoot的restful接口使用mybtais负责dao编写entity层entity层的名字叫`Rol_Table_Privilege`编写service层给出controller编写对应的网页的layui风格的使用这个接口的表格的ajax代码.
展示结果为:
<img src="https://cdn.jsdelivr.net/gh/52chen/imagebed2023@main/image-20230917134347380.png" alt="image-20230917134347380" style="zoom: 50%;" />
还可以根据指定用户查询所有数据表或者指定数据表的权限:
SQL代码为
```sql
select table_name,table_schema,grantee,string_agg(privilege_type,',') from information_schema.table_privileges where grantee='admin_department' group by table_name,table_schema,grantee;
-- 查询当前数据库下当前用户对表的权限
```
#### 2查询用户对各个数据库的权限
实现思路:
根据SQL语句
```sql
SELECT b.rolname, a.datname, string_agg(a.pri_t, ',') AS privileges
FROM (
SELECT datname, grantee, privilege_type AS pri_t
FROM (
SELECT
datname,
(aclexplode(COALESCE(datacl, acldefault('d'::"char", datdba)))).grantee AS grantee,
(aclexplode(COALESCE(datacl, acldefault('d'::"char", datdba)))).privilege_type AS privilege_type
FROM pg_database
WHERE datname NOT LIKE 'template%'
) subquery
) a
JOIN pg_roles b ON a.grantee = b.oid OR a.grantee = 0
WHERE b.rolname NOT LIKE 'gs%'
GROUP BY a.datname, b.rolname;
-- 优化为一行的版本为:
SELECT b.rolname, a.datname, string_agg(a.pri_t, ',') AS privileges FROM (SELECT datname, grantee, privilege_type AS pri_t FROM (SELECT datname, (aclexplode(COALESCE(datacl, acldefault('d'::"char", datdba)))).grantee AS grantee, (aclexplode(COALESCE(datacl, acldefault('d'::"char", datdba)))).privilege_type AS privilege_type FROM pg_database WHERE datname NOT LIKE 'template%') subquery) a JOIN pg_roles b ON a.grantee = b.oid OR a.grantee = 0 WHERE b.rolname NOT LIKE 'gs%' GROUP BY a.datname, b.rolname;
```
设计SpringBoot的restful接口使用mybtais负责dao编写entity层entity层的名字叫`Rol_Table_Privilege`编写service层给出controller编写对应的网页的layui风格的使用这个接口的表格的ajax代码.
展示结果为:
![image-20230917134608083](https://cdn.jsdelivr.net/gh/52chen/imagebed2023@main/image-20230917134608083.png)
同理还可以根据指定用户查询所有数据库或者指定数据库的权限。
#### 3当前数据库的表格
实现思路:
根据SQL语句
```sql
SELECT table_catalog AS database,table_schema,table_name
FROM information_schema.tables
WHERE table_type = 'BASE TABLE'
AND table_schema NOT IN ('pg_catalog', 'information_schema','dbe_pldeveloper','db4ai');
-- 查询当前所有公开的表格包括所在数据库所在schema名字 Table
```
设计SpringBoot的restful接口使用mybtais负责dao编写entity层entity层的名字叫`Table`编写service层给出controller编写对应的网页的layui风格的使用这个接口的表格的ajax代码.
```SQL
GRANT SELECT ON SCHEMA public TO testuser;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO testuser;
-- 授予 testuser 用户在 public 模式下所有表的查询权限,包括 tb_class 表
GRANT SELECT ON tb_class TO testuser;
-- 授予 testuser 用户 tb_class 表的查询权限。
```
效果:
![image-20230925161127677](https://cdn.jsdelivr.net/gh/52chen/imagebed2023@main/image-20230925161127677.png)
### 1.3.3 角色、用户权限安全策略
**1管理员可以有多个但是安全管理员只能有一个**
```sql
SELECT rolname FROM pg_roles WHERE rolsuper = true;
-- 查询初始用户也就是超级管理员
```
实现思路:
根据所有用户的列表中,我们可以查找超级管理员的数据,如果超过一个,就存在安全隐患,展示出隐患信息。
**2查询所有用户、角色信息**
实现思路:
根据SQL语句
```sql
SELECT usesysid,usename,usesuper
FROM pg_user;
```
设计SpringBoot的restful接口使用mybtais负责dao编写entity层entity层的名字叫`PgUser`编写service层给出controller编写对应的网页的layui风格的使用这个接口的表格的ajax代码.
展示结果为:
<img src="https://cdn.jsdelivr.net/gh/52chen/imagebed2023@main/image-20230917135238547.png" alt="image-20230917135238547" style="zoom:50%;" />
**3禁止新建以“gs_role_”开头的用户/角色,也禁止将已有的用户/角色重命名为以“gs_role_”开头**
```sql
SELECT * FROM pg_user;
-- 查询的结果不能包含gs_role开头否则存在违规
SELECT *
FROM pg_user
WHERE usename LIKE 'gs_role%';
-- 如果有查询结果表明存在违规
```
**4非[三权分立](https://docs.opengauss.org/zh/docs/3.1.0/docs/Developerguide/三权分立.html)下openGauss用户帐户只能由系统管理员rolsystemadmin或拥有CREATEROLE属性的安全管理员创建和删除。三权分立时用户帐户只能由初始用户omm和安全管理员rolcreaterole创建。**
![image-20230915171817953](https://cdn.jsdelivr.net/gh/52chen/imagebed2023@main/image-20230915171817953.png)
如上图Data的连接账号的是admin_department是一个系统管理员(sysadmin),不是安全管理员,因此无法创建账户,如果没有开启三权分立,那么就可以创建账号。
# 2. 项目进度
## 2.1 已完成工作
根据原定方案和时间规划,完成一篇技术文档, 完成一个主要是能识别数据库三权分立的管理员权限识别用户或角色对数据库和表格的操作权限识别所有用户列表的项目已经将项目提交PR到https://gitee.com/opengauss/examples/pulls/55 。
## 2.2 遇到的问题及解决方案
问题:访问数据库用户和角色权限
解决方案通过SQL查询系统表格得到数据。
问题openGauss数据安全策略设计
解决方案研读三权分立的原理和三权分立的基本要求通过SQL查询得到的权限数据评判数据库权限安全。
2.3 后续工作安排
继续完善安全策略的设计,或许可以将安全评判的标准设计进入数据库内部,集成为一个功能。
# 附录:
参考文档:
1、https://blog.csdn.net/myneth/article/details/129036436
2、https://www.kancloud.cn/sinkiang/skadmin_document/1267757
3、schema介绍https://www.jb51.net/article/275164.htm
4、[RDS实践](https://www.alibabacloud.com/help/zh/rds/apsaradb-rds-for-postgresql/manage-permissions-in-an-apsaradb-rds-for-postgesql-instance)
5、[sks-admin](https://github.com/DengSinkiang/sk-admin/tree/master)
6、 [postgresql查询权限](https://www.modb.pro/db/398722)
7、[gauss5.0手册](https://docs.opengauss.org/zh/docs/5.0.0/docs/DatabaseAdministrationGuide/%E7%AE%A1%E7%90%86%E7%94%A8%E6%88%B7%E5%8F%8A%E6%9D%83%E9%99%90.html)

View File

@ -0,0 +1,182 @@
![openGauss Logo](https://opengauss.org/img/brand/view/logo2.jpg)
## 什么是openGauss-connector-JDBC
openGauss是一款开源的关系型数据库管理系统它具有多核高性能、全链路安全性、智能运维等企业级特性。
openGauss内核早期源自开源数据库PostgreSQL融合了华为在数据库领域多年的内核经验在架构、事务、存储引擎、优化器及ARM架构上进行了适配与优化。作为一个开源数据库期望与广泛的开发者共同构建一个多元化技术的开源数据库社区。
Java数据库连接Java Database Connectivity简称**JDBC**是Java语言中用来规范客户端程序如何来访问数据库的应用程序接口提供了诸如查询和更新数据库中数据的方法。openGauss-connector-JDBC就是提供给用户通过Java语言访问数据库的应用程序接口。用户可以使用openGauss官网提供的jar包[参考直接获取部分](#安装)也可以自行构建jar包[参考从源码构建部分](#从源码构建)以使用JDBC操作数据库。
## 直接获取
在使用openGauss JDBC 驱动之前,请确保您的服务器已经可以正常运行 openGauss 数据库参考openGauss[快速入门](https://opengauss.org/zh/docs/latest/docs/Quickstart/Quickstart.html))。
### 从maven中央仓库获取
Java开发者可从maven中央仓库中直接获取jar包坐标如下
```
<groupId>org.opengauss</groupId>
<artifactId>opengauss-jdbc</artifactId>
```
### 从社区官网下载安装包
1. 在官网下载安装包。
点击[链接](https://opengauss.org/zh/download.html)在openGauss Connectors部分下根据您部署数据库的服务器的对应系统选择JDBC_${version}的下载按钮。${version}即您需要的版本号。
2. 解压压缩包。
```
tar -zxvf openGauss-${version}-JDBC.tar.gz
```
3. 解压后可以看到同级目录下出现了两个jar包分别是opengauss-jdbc-${version}.jar和postgresql.jar。opengauss-jdbc-${version}.jar是可以与PG-JDBC共存的包, 包名自2.0.1之后的版本全部从org.postgresql变更为org.opengauss,并且驱动名称从jdbc:postgresql://替换为jdbc:opengauss://。目前从maven中央仓库中获取的也是这个包。
## 从源码构建
### 概述
openGauss JDBC 驱动目前提供3种构建方式。一是通过一键式脚本build.sh进行构建。二是通过脚本进行逐步构建。三是通过mvn命令进行构建。
### 操作系统和软件依赖要求
openGauss JDBC 驱动的生成支持以下操作系统:
- CentOS 7.6x86架构
- openEuler-20.03-LTSaarch64架构
- Windows
适配其他系统,参照博客[openGauss数据库编译指导](https://opengauss.org/zh/blogs/blogs.html?post/xingchen/opengauss_compile/)
以下表格列举了编译openGauss的软件要求。
建议使用从列出的操作系统安装盘或安装源中获取的以下依赖软件的默认安装包进行安装。如果不存在以下软件,请参考推荐的软件版本。
软件及环境依赖要求如下:
| 软件及环境要求 | 推荐版本 |
| ------------------- | ---------- |
| maven | 3.6.1 |
| java | 1.8 |
| Git Bash (Windows) | 无推荐版本 |
### 下载openGauss-connector-jdbc源码
可以从开源社区下载openGauss-connector-jdbc源码。
```
git clone https://gitee.com/opengauss/openGauss-connector-jdbc.git
```
现在我们已经拥有完整的openGauss-connector-jdbc代码把它存储在以下目录中以sda为例
- /sda/openGauss-connector-jdbc
### jar包生成
#### 使用一键式脚本生成jar包Linux/windows
openGauss-connector-jdbc中的build.sh是编译过程中的重要脚本工具。该工具可快速进行代码编译和打包。
只需使用如下格式的命令即可编译openGauss-connector-jdbc。
1. 执行如下命令进入到代码目录:
```
[user@linux sda]$ cd /sda/openGauss-connector-jdbc/
```
2. 执行如下命令使用build.sh进行打包
```
[user@linux openGauss-connector-jdbc]$ sh build.sh
```
结束后会显示如下内容,表示打包成功:
```
Successfully make postgresql.jar
Successfully make opengauss-jdbc-${version} jar package
packaging jdbc...
Successfully make jdbc jar package in openGauss-${version}-${platform}-${bit}-Jdbc.tar.gz
clean up temporary directory!
now, all packages has finished!
```
成功编译后会出现两个jar包分别是opengauss-jdbc-${version}.jar与postgresql.jar。编译后的jar包路径为**/sda/openGauss-connector-jdbc/output**。
#### 使用mvn命令生成jar包Windows 或 Linux
1. 准备 Java 与 Maven环境。
2. 执行如下命令进入到代码目录:
```
[user@linux sda]$ cd /sda/openGauss-connector-jdbc
```
3. 执行mvn命令
```
[user@linux openGauss-connector-jdbc]$ mvn clean install -Dgpg.skip -Dmaven.test.skip=true
```
Linux系统下构建成功后会显示如下结果
```
[INFO] Reactor Summary:
[INFO]
[INFO] openGauss JDBC Driver ............................. SUCCESS [5.344s]
[INFO] PostgreSQL JDBC Driver aggregate .................. SUCCESS [0.004s]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 5.439s
[INFO] Finished at: Tue Aug 31 21:55:01 EDT 2021
[INFO] Final Memory: 44M/1763M
[INFO] ------------------------------------------------------------------------
```
构建成功后会出现两个jar包分别是opengauss-jdbc-${version}.jar与original-opengauss-jdbc-${version}.jar。jar包路径为/sda/openGauss-connector-jdbc/pgjdbc/target/。
**注意:默认的mvn编译出的jdbc包名为org.postgresql,它与maven中央仓库的包名org.opengauss不同,想打包此包名请参考build.sh脚本**
## JDBC的使用
参考[基于JDBC开发](https://opengauss.org/zh/docs/latest/docs/Developerguide/%E5%9F%BA%E4%BA%8EJDBC%E5%BC%80%E5%8F%91.html)。
## 文档
更多安装指南、教程和API请参考[用户文档](https://gitee.com/opengauss/docs)。
## 社区
### 治理
查看openGauss是如何实现开放[治理](https://gitee.com/opengauss/community/blob/master/governance.md)。
### 交流
- WeLink开发者的交流平台。
- IRC频道`#opengauss-meeting`(仅用于会议纪要)。
- 邮件列表https://opengauss.org/zh/community/onlineCommunication.html
## 贡献
欢迎大家来参与贡献。详情请参阅我们的[社区贡献](https://opengauss.org/zh/contribution.html)。
## 发行说明
请参见[发行说明](https://opengauss.org/zh/docs/2.0.0/docs/Releasenotes/Releasenotes.html)。
## 许可证
[MulanPSL-2.0](http://license.coscl.org.cn/MulanPSL2/)

View File

@ -0,0 +1,200 @@
![openGauss Logo](https://opengauss.org/img/brand/view/logo2.jpg)
## What is openGauss-connector-jdbc
openGauss is an open source relational database management system. It has multi-core high-performance, full link security, intelligent operation and maintenance for enterprise features. openGauss, which is early originated from PostgreSQL, integrates Huawei's core experience in database field for many years. It optimizes the architecture, transaction, storage engine, optimizer and ARM architecture. At the meantime, openGauss as a global database open source community, aims to further advance the development and enrichment of the database software/hardware application ecosystem.
**Java Database Connectivity** (**JDBC**) is an application programming interface (API) for the programming language Java, which defines how a client may access a database. It is a Java-based data access technology used for Java database connectivity. It provides methods to query and update data in a database, and is oriented toward relational databases. openGauss-connector-jdbc is to provide users with access to the database through the Java language application interface . Users can use the jar package provided by the openGauss official website (refer to the [Direct Access section](#1)) or build their own jar package ([refer to the Building from Source section](#BuildfromSource) to operate the database using JDBC.
## Direct access {#1}
Before using the openGauss JDBC driver, make sure your server is up and running with the openGauss database (refer to the openGauss [Quickstart](https://opengauss.org/en/docs/latest/docs/Quickstart/Quickstart.html))。
### Get from maven central repository
Java developers can get jar packages directly from the maven central repository with the following coordinates:
```
<groupId>org.opengauss</groupId>
<artifactId>opengauss-jdbc</artifactId>
```
### Get from the community website
1. Download the installation package from the official website.
Click on [link](https://opengauss.org/en/download.html) and under the openGauss Connectors section, select the download button for JDBC_${version} according to the corresponding system of the server where you are deploying the database. ${version} is the version number you need.
2. Decompress the zip file.
```
tar -zxvf openGauss-${version}-JDBC.tar.gz
```
3. After unpacking, you can see two jar packages in the same directory, opengauss-jdbc-${version}.jar and postgresql.jar. opengauss-jdbc-${version}.jar is a package that can coexist with PG-JDBC, the package name is changed from 2.0.1 to org.postgresql.jar. postgresql to org.opengauss, and the driver name is replaced from jdbc:postgresql:// to jdbc:opengauss://. This is the same package that is currently available from the maven central repository.
### INSTALLING THE DRIVER
To install the driver, the postgresql.jar file has to be in the classpath.
ie: under LINUX/SOLARIS (the example here is my linux box):
export CLASSPATH=.:/usr/local/pgsql/share/java/postgresql.jar
or
```
export CLASSPATH=.:/usr/local/pgsql/share/java/opengauss-jdbc-${version}.jar
```
## Build from Source {#BuildfromSource}
### Overview
The openGauss JDBC driver currently offers 3 ways to build. One is to build via the one-click script build.sh. The second is a step-by-step build via script. The third is to build via the mvn command.
This will compile the correct driver for your JVM, and build a .jar file (Java ARchive) called postgresql.jar and opengauss-jdbc--${version}.jar in output/, and you can get openGauss-${version}-jdbc.tar.gz too.
Notice: postgresql.jar is conflict use with postgres database. Because all class was in package org.postgresql. opengauss-jdbc-${version}.jar is compatibility with postgres database, all java package renamed `org.opengauss`, and jdbc driver is: `jdbc:opengauss:/`
Remember: Once you have compiled the driver, it will work on ALL platforms that support that version of the API. You don't need to build it for each platform.
### OS and Software Dependency Requirements
The openGauss JDBC driver is generated to support the following operating systems:
- CentOS 7.6x86 architecture
- openEuler-20.03-LTSaarch64 architecture
- Windows
The following table lists the software requirements for compiling the openGauss-connector-jdbc.
You are advised to use the default installation packages of the following dependent software in the listed OS installation CD-ROMs or sources. If the following software does not exist, refer to the recommended versions of the software.
Software dependency requirements are as follows:
| Software and Environment Requirements | Recommended Version |
| ------------------------------------- | ------------------- |
| maven | 3.6.1 |
| java | 1.8 |
| Git Bash (Windows) | - |
### Downloading openGauss-connector-jdbc
You can download openGauss-connector-jdbc from open source community.
```
git clone https://gitee.com/opengauss/openGauss-connector-jdbc.git
```
Now we have completed openGauss-connector-jdbc code. For example, we store it in following directories.
- /sda/openGauss-connector-jdbc
### Compiling
#### Getting jar packages with one-click scripting (Linux/Windows)
The build.sh in the openGauss-connector-jdbc directory is an important scripting tool for the compilation process. This tool allows for quick code compilation and packaging.
so you can compile the openGauss-connector-jdbc by one command with build.sh. In build.sh, maven and java8 will be installed automatically and use to build target.
1. Execute the following command to get to the code directory:
```
[user@linux sda]$ cd /sda/openGauss-connector-jdbc
```
2. Execute the following command to package using build.sh:
```
[user@linux openGauss-connector-jdbc]$ sh build.sh
```
When finished, the following will be displayed to indicate successful packaging:
```
Successfully make postgresql.jar
Successfully make opengauss-jdbc-${version} jar package
packaging jdbc...
Successfully make jdbc jar package in openGauss-${version}-${platform}-${bit}-Jdbc.tar.gz
clean up temporary directory!
now, all packages has finished!!
```
After successful compilation, two jar packages will appear, opengauss-jdbc-${version}.jar and postgresql.jar. compiled jar package path is:**/sda/openGauss-connector-jdbc/output**.
#### Getting jar packages using the mvn command (Windows or Linux)
1. Prepare the Java and Maven environments.
2. Execute the following command to get to the code directory
```
[user@linux sda]$ cd /sda/openGauss-connector-jdbc
```
3. Execute the mvn command:
```
[user@linux openGauss-connector-jdbc]$ mvn clean install -Dgpg.skip -Dmaven.test.skip=true
```
A successful build on a Linux system will display the following result:
```
[INFO] Reactor Summary:
[INFO]
[INFO] openGauss JDBC Driver ............................. SUCCESS [5.344s]
[INFO] PostgreSQL JDBC Driver aggregate .................. SUCCESS [0.004s]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 5.439s
[INFO] Finished at: Tue Aug 31 21:55:01 EDT 2021
[INFO] Final Memory: 44M/1763M
[INFO] ------------------------------------------------------------------------
```
Two jar packages will appear after a successful build, opengauss-jdbc-${version}.jar and original-opengauss-jdbc-${version}.jar. jar package path is /sda/openGauss-connector-jdbc/pgjdbc /target/.
**notice: this build artifact's package name is org.postgresql which different with maven central repository. if you want build package with org.opengauss, please refer to build.sh.**
## Using JDBC
Reference [JDBC-based development](https://opengauss.org/en/docs/latest/docs/Developerguide/development-based-on-jdbc.html).
## Docs
For more details about the installation guide, tutorials, and APIs, please see the [User Documentation](https://gitee.com/opengauss/docs).
## Community
### Governance
Check out how openGauss implements open governance [works](https://gitee.com/opengauss/community/blob/master/governance.md).
### Communication
- WeLink- Communication platform for developers.
- IRC channel at `#opengauss-meeting` (only for meeting minutes logging purpose)
- Mailing-list: https://opengauss.org/en/community/onlineCommunication.html
## Contribution
Welcome contributions. See our [Contributor](https://opengauss.org/en/contribution.html) for more details.
## Release Notes
For the release notes, see our [RELEASE](https://opengauss.org/en/docs/2.0.0/docs/Releasenotes/Releasenotes.html).
## License
[MulanPSL-2.0](http://license.coscl.org.cn/MulanPSL2/)

View File

@ -0,0 +1,89 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mcx</groupId>
<artifactId>OpenGaussPrivilegeScan</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>gaussTest</name>
<description>gaussTest</description>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-boot.version>2.4.2</spring-boot.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.3</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.70</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
<scope>provided</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring-boot.version}</version>
<configuration>
<mainClass>com.mcx.gaussprivilege.GaussTestApplication</mainClass>
<skip>true</skip>
</configuration>
<executions>
<execution>
<id>repackage</id>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,13 @@
package com.mcx.gaussprivilege;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class GaussTestApplication {
public static void main(String[] args) {
SpringApplication.run(GaussTestApplication.class, args);
}
}

View File

@ -0,0 +1,46 @@
package com.mcx.gaussprivilege.controller;
import com.mcx.gaussprivilege.entity.RoleAdmin;
import com.mcx.gaussprivilege.service.AuditAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpSession;
import java.util.List;
@RestController
public class AuditAdminController {
@Autowired
private AuditAdminService auditAdminService;
/*
SELECT rolname,rolsuper,rolcreaterole,rolsystemadmin,rolauditadmin FROM pg_roles WHERE rolcreaterole = 'true';
执行结果为[{"rolname":"omm","rolsuper":"t","rolcreaterole":"t","rolsystemadmin":"t","rolauditadmin":"t"},
{"rolname":"safeadmin","rolsuper":"f","rolcreaterole":"t","rolsystemadmin":"f","rolauditadmin":"f"}]
设计SpringBoot的restful接口使用mybtais负责dao编写entity层entity层的名字叫createRoleAdmin
编写service层给出controller编写对应的网页的layui风格的使用这个接口的表格
*/
@GetMapping("/auditadmin")
public List<RoleAdmin> getAuditAdminList(HttpSession httpSession) {
List<RoleAdmin> roleAdminList = auditAdminService.getAuditAdminList();
return roleAdminList;
}
@GetMapping("/auditadminerr")
public String getAuditAdminErr(){
List<RoleAdmin> roleAdminList = auditAdminService.getAuditAdminList();
String msg = "";
msg ="该数据库的审计管理员权限正常";
for (RoleAdmin admin : roleAdminList) {
if (!admin.getRolname().equals("omm")&&(admin.isRolcreaterole()|| admin.isRolsuper()|| admin.isRolsystemadmin())){
msg = "如果三权分立开关已经开启,那么该数据库的审计管理违规持有权限";
}
}
System.out.println("msg = " + msg);
return msg;
}
}

View File

@ -0,0 +1,48 @@
package com.mcx.gaussprivilege.controller;
import com.mcx.gaussprivilege.entity.RoleAdmin;
import com.mcx.gaussprivilege.service.CreateRoleAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpSession;
import java.util.List;
@RestController
public class CreateRoleAdminController {
@Autowired
private final CreateRoleAdminService createRoleAdminService;
public CreateRoleAdminController(CreateRoleAdminService createRoleAdminService) {
this.createRoleAdminService = createRoleAdminService;
}
/*
*/
@GetMapping("/creroladmin")
public List<RoleAdmin> getCreateRoleAdminList(HttpSession httpSession) {
List<RoleAdmin> roleAdminList = createRoleAdminService.getCreateRoleAdminList();
return roleAdminList;
}
@GetMapping("/creroladminerr")
public String getCreateRoleAdminErr(){
List<RoleAdmin> roleAdminList = createRoleAdminService.getCreateRoleAdminList();
String msg = "";
msg ="该数据库的安全管理员权限正常";
for (RoleAdmin admin : roleAdminList) {
if (!admin.getRolname().equals("omm")&&(admin.isRolauditadmin()|| admin.isRolsuper()|| admin.isRolsystemadmin())){
msg = "如果三权分立开关已经开启,那么该数据库的安全管理违规持有权限";
}
}
System.out.println("msg = " + msg);
return msg;
}
}

View File

@ -0,0 +1,20 @@
package com.mcx.gaussprivilege.controller;
import com.mcx.gaussprivilege.entity.PgUser;
import com.mcx.gaussprivilege.service.PgUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class PgUserController {
@Autowired
private PgUserService userService;
@GetMapping("/pgusers")
public List<PgUser> getAllUsers() {
return userService.getAllUsers();
}
}

View File

@ -0,0 +1,26 @@
package com.mcx.gaussprivilege.controller;
import com.mcx.gaussprivilege.entity.RolDatPrivilege;
import com.mcx.gaussprivilege.service.RolDatPrivilegeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* 展示用户数据库权限表
*/
@RestController
public class RolDatPrivilegeController {
private final RolDatPrivilegeService rolDatPrivilegeService;
@Autowired
public RolDatPrivilegeController(RolDatPrivilegeService rolDatPrivilegeService) {
this.rolDatPrivilegeService = rolDatPrivilegeService;
}
@GetMapping("/rol-dat-privileges")
public List<RolDatPrivilege> getRolDatPrivileges() {
return rolDatPrivilegeService.getRolDatPrivileges();
}
}

View File

@ -0,0 +1,19 @@
package com.mcx.gaussprivilege.controller;
import com.mcx.gaussprivilege.entity.RolTablePrivilege;
import com.mcx.gaussprivilege.service.RolTablePrivilegeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class RolTablePrivilegeController {
@Autowired
RolTablePrivilegeService rolTablePrivilegeService;
@GetMapping("/rolTablePrivileges")
public List<RolTablePrivilege> getAllRolTablePrivileges() {
return rolTablePrivilegeService.getAllRolTablePrivileges();
}
}

View File

@ -0,0 +1,44 @@
package com.mcx.gaussprivilege.controller;
import com.mcx.gaussprivilege.entity.RoleAdmin;
import com.mcx.gaussprivilege.service.SysAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpSession;
import java.util.List;
@RestController
public class SysAdminController {
@Autowired
private SysAdminService sysAdminService;
/*
SELECT rolname,rolsuper,rolcreaterole,rolsystemadmin,rolauditadmin FROM pg_roles WHERE rolcreaterole = 'true';
执行结果为[{"rolname":"omm","rolsuper":"t","rolcreaterole":"t","rolsystemadmin":"t","rolauditadmin":"t"},
{"rolname":"safeadmin","rolsuper":"f","rolcreaterole":"t","rolsystemadmin":"f","rolauditadmin":"f"}]
设计SpringBoot的restful接口使用mybtais负责dao编写entity层entity层的名字叫createRoleAdmin
编写service层给出controller编写对应的网页的layui风格的使用这个接口的表格
*/
@GetMapping("/sysadmin")
public List<RoleAdmin> getSysAdminList(HttpSession httpSession) {
return sysAdminService.getSysAdminList();
}
@GetMapping("/sysadminerr")
public String getSysAdminErr(){
List<RoleAdmin> roleAdminList = sysAdminService.getSysAdminList();
String msg = "";
msg ="该数据库的系统管理员权限正常";
for (RoleAdmin admin : roleAdminList) {
if (!admin.getRolname().equals("omm")&&(admin.isRolcreaterole()|| admin.isRolsuper()|| admin.isRolauditadmin())){
msg = "如果三权分立开关已经开启,那么该数据库的系统管理违规持有权限";
}
}
System.out.println("msg = " + msg);
return msg;
}
}

View File

@ -0,0 +1,26 @@
package com.mcx.gaussprivilege.controller;
import com.mcx.gaussprivilege.entity.Table;
import com.mcx.gaussprivilege.service.TableService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/tables")
public class TableController {
private final TableService tableService;
@Autowired
public TableController(TableService tableService) {
this.tableService = tableService;
}
@GetMapping
public List<Table> getAllTables() {
return tableService.getAllTables();
}
}

View File

@ -0,0 +1,26 @@
package com.mcx.gaussprivilege.controller;
import com.mcx.gaussprivilege.entity.TbClass;
import com.mcx.gaussprivilege.service.TbClassService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
@Controller
@ResponseBody
@RequestMapping("/gadb")
public class TestController {
@Autowired
TbClassService tbClassService;
@GetMapping("/query")
public List<TbClass> queryData(){
return tbClassService.query();
}
}

View File

@ -0,0 +1,13 @@
package com.mcx.gaussprivilege.dao;
import com.mcx.gaussprivilege.entity.RoleAdmin;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface AuditAdminMapper {
@Select("SELECT rolname, rolsuper, rolcreaterole, rolsystemadmin, rolauditadmin FROM pg_roles WHERE rolauditadmin = 'true'")
List<RoleAdmin> getAuditAdminList();
}

View File

@ -0,0 +1,13 @@
package com.mcx.gaussprivilege.dao;
import com.mcx.gaussprivilege.entity.RoleAdmin;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface CreateRoleAdminMapper {
@Select("SELECT rolname, rolsuper, rolcreaterole, rolsystemadmin, rolauditadmin FROM pg_roles WHERE rolcreaterole = 'true'")
List<RoleAdmin> getCreateRoleAdminList();
}

View File

@ -0,0 +1,13 @@
package com.mcx.gaussprivilege.dao;
import com.mcx.gaussprivilege.entity.PgUser;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface PgUserMapper {
@Select("SELECT usesysid, usename, usesuper FROM pg_user")
List<PgUser> getAllUsers();
}

View File

@ -0,0 +1,20 @@
package com.mcx.gaussprivilege.dao;
import com.mcx.gaussprivilege.entity.RolDatPrivilege;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface RolDatPrivilegeMapper {
// @Select("SELECT b.rolname, a.datname, array_agg(a.pri_t) AS privileges" +
// " FROM (SELECT datname, grantee, privilege_type AS pri_t FROM" +
// " (SELECT datname, aclexplode(COALESCE(datacl, acldefault('d'::\"char\", datdba))).grantee AS grantee," +
// " aclexplode(COALESCE(datacl, acldefault('d'::\"char\", datdba))).privilege_type AS privilege_type" +
// " FROM pg_database WHERE datname NOT LIKE 'template%') subquery) a" +
// " JOIN pg_roles b ON a.grantee = b.oid OR a.grantee = 0" +
// " WHERE b.rolname NOT LIKE 'gs%' GROUP BY a.datname, b.rolname")
@Select("SELECT b.rolname, a.datname, string_agg(a.pri_t, ',') AS privileges FROM (SELECT datname, grantee, privilege_type AS pri_t FROM (SELECT datname, (aclexplode(COALESCE(datacl, acldefault('d'::\"char\", datdba)))).grantee AS grantee, (aclexplode(COALESCE(datacl, acldefault('d'::\"char\", datdba)))).privilege_type AS privilege_type FROM pg_database WHERE datname NOT LIKE 'template%') subquery) a JOIN pg_roles b ON a.grantee = b.oid OR a.grantee = 0 WHERE b.rolname NOT LIKE 'gs%' GROUP BY a.datname, b.rolname;")
List<RolDatPrivilege> getRolDatPrivileges();
}

View File

@ -0,0 +1,13 @@
package com.mcx.gaussprivilege.dao;
import com.mcx.gaussprivilege.entity.RolTablePrivilege;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface RolTablePrivilegeMapper {
@Select("SELECT grantee AS rol_name, table_name, string_agg(privilege_type, ', ') AS privileges FROM information_schema.role_table_grants GROUP BY grantee,table_name")
List<RolTablePrivilege> getAllRolTablePrivileges();
}

View File

@ -0,0 +1,13 @@
package com.mcx.gaussprivilege.dao;
import com.mcx.gaussprivilege.entity.RoleAdmin;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface SysAdminMapper {
@Select("SELECT rolname, rolsuper, rolcreaterole, rolsystemadmin, rolauditadmin FROM pg_roles WHERE rolsystemadmin = 'true'")
List<RoleAdmin> getSysAdminList();
}

View File

@ -0,0 +1,16 @@
package com.mcx.gaussprivilege.dao;
import com.mcx.gaussprivilege.entity.Table;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface TableMapper {
@Select("SELECT table_catalog AS database, table_schema, table_name " +
"FROM information_schema.tables " +
"WHERE table_type = 'BASE TABLE' " +
"AND table_schema NOT IN ('pg_catalog', 'information_schema','dbe_pldeveloper','db4ai')")
List<Table> getAllTables();
}

View File

@ -0,0 +1,9 @@
package com.mcx.gaussprivilege.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.mcx.gaussprivilege.entity.TbClass;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface TbClassMapper extends BaseMapper<TbClass> {
}

View File

@ -0,0 +1,12 @@
package com.mcx.gaussprivilege.entity;
import lombok.Data;
@Data
public class PgUser {
private Integer usesysid;
private String usename;
private Boolean usesuper;
// getter and setter methods
}

View File

@ -0,0 +1,12 @@
package com.mcx.gaussprivilege.entity;
import lombok.Data;
import java.util.List;
@Data
public class RolDatPrivilege {
private String rolname;
private String datname;
private String privileges;
}

View File

@ -0,0 +1,10 @@
package com.mcx.gaussprivilege.entity;
import lombok.Data;
@Data
public class RolTablePrivilege {
private String rolName;
private String tableName;
private String privileges;
}

View File

@ -0,0 +1,16 @@
package com.mcx.gaussprivilege.entity;
import lombok.*;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Data
public class RoleAdmin {
private String rolname;
private boolean rolsuper;
private boolean rolcreaterole;
private boolean rolsystemadmin;
private boolean rolauditadmin;
}

View File

@ -0,0 +1,10 @@
package com.mcx.gaussprivilege.entity;
import lombok.Data;
@Data
public class Table {
private String database;
private String tableSchema;
private String tableName;
}

View File

@ -0,0 +1,16 @@
package com.mcx.gaussprivilege.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName("tb_class")
public class TbClass {
private String c_id;
private String c_name;
private String c_age;
}

View File

@ -0,0 +1,17 @@
package com.mcx.gaussprivilege.service;
import com.mcx.gaussprivilege.dao.AuditAdminMapper;
import com.mcx.gaussprivilege.entity.RoleAdmin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class AuditAdminService {
@Autowired
AuditAdminMapper auditAdminMapper;
public List<RoleAdmin> getAuditAdminList() {
return auditAdminMapper.getAuditAdminList();
}
}

View File

@ -0,0 +1,20 @@
package com.mcx.gaussprivilege.service;
import com.mcx.gaussprivilege.dao.CreateRoleAdminMapper;
import com.mcx.gaussprivilege.entity.RoleAdmin;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class CreateRoleAdminService {
private final CreateRoleAdminMapper createRoleAdminMapper;
public CreateRoleAdminService(CreateRoleAdminMapper createRoleAdminMapper) {
this.createRoleAdminMapper = createRoleAdminMapper;
}
public List<RoleAdmin> getCreateRoleAdminList() {
return createRoleAdminMapper.getCreateRoleAdminList();
}
}

View File

@ -0,0 +1,16 @@
package com.mcx.gaussprivilege.service;
import com.mcx.gaussprivilege.dao.PgUserMapper;
import com.mcx.gaussprivilege.entity.PgUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class PgUserService {
@Autowired
private PgUserMapper pgUserMapper;
public List<PgUser> getAllUsers() {
return pgUserMapper.getAllUsers();
}
}

View File

@ -0,0 +1,21 @@
package com.mcx.gaussprivilege.service;
import com.mcx.gaussprivilege.dao.RolDatPrivilegeMapper;
import com.mcx.gaussprivilege.entity.RolDatPrivilege;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class RolDatPrivilegeService {
private final RolDatPrivilegeMapper rolDatPrivilegeMapper;
@Autowired
public RolDatPrivilegeService(RolDatPrivilegeMapper rolDatPrivilegeMapper) {
this.rolDatPrivilegeMapper = rolDatPrivilegeMapper;
}
public List<RolDatPrivilege> getRolDatPrivileges() {
return rolDatPrivilegeMapper.getRolDatPrivileges();
}
}

View File

@ -0,0 +1,19 @@
package com.mcx.gaussprivilege.service;
import com.mcx.gaussprivilege.dao.RolTablePrivilegeMapper;
import com.mcx.gaussprivilege.entity.RolTablePrivilege;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class RolTablePrivilegeService {
@Autowired
RolTablePrivilegeMapper rolTablePrivilegeMapper;
public List<RolTablePrivilege> getAllRolTablePrivileges() {
return rolTablePrivilegeMapper.getAllRolTablePrivileges();
}
}

View File

@ -0,0 +1,17 @@
package com.mcx.gaussprivilege.service;
import com.mcx.gaussprivilege.dao.SysAdminMapper;
import com.mcx.gaussprivilege.entity.RoleAdmin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class SysAdminService {
@Autowired
SysAdminMapper sysAdminMapper;
public List<RoleAdmin> getSysAdminList() {
return sysAdminMapper.getSysAdminList();
}
}

View File

@ -0,0 +1,22 @@
package com.mcx.gaussprivilege.service;
import com.mcx.gaussprivilege.dao.TableMapper;
import com.mcx.gaussprivilege.entity.Table;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class TableService {
private final TableMapper tableMapper;
@Autowired
public TableService(TableMapper tableMapper) {
this.tableMapper = tableMapper;
}
public List<Table> getAllTables() {
return tableMapper.getAllTables();
}
}

View File

@ -0,0 +1,19 @@
package com.mcx.gaussprivilege.service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mcx.gaussprivilege.dao.TbClassMapper;
import com.mcx.gaussprivilege.entity.TbClass;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class TbClassService {
@Autowired
private TbClassMapper tbClassMapper;
public List<TbClass> query(){
QueryWrapper<TbClass> wrapper = new QueryWrapper<>();
return this.tbClassMapper.selectList(wrapper);
}
}

View File

@ -0,0 +1,46 @@
package com.mcx.gaussprivilege.test;
import java.sql.*;
public class jdbcDriverTest {
public static void main(String[] args) {
// JDBC连接信息
String url = "jdbc:postgresql://192.168.1.49:123/opengauss";//远程ip连接没有用
String username = "opengauss";
String password = "gauss@123";
// 注册OpenGauss JDBC驱动程序
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
return;
}
try (Connection connection = DriverManager.getConnection(url, username, password)) {
// 连接成功创建PreparedStatement对象以执行SQL语句
// String sql = "select a.datname,b.rolname,string_agg(a.pri_t,',') from (select datname,(aclexplode(COALESCE(datacl, acldefault('d'::\"char\",datdba)))).grantee as grantee,(aclexplode(COALESCE(datacl, acldefault('d'::\"char\", datdba)))).privilege_type as pri_t from pg_database where datname not like 'template%') a,pg_roles b where (a.grantee=b.oid or a.grantee=0) and b.rolname='opengauss' group by a.datname,b.rolname;";
// String sql = "SELECT rolname,rolsuper,rolcreaterole,rolsystemadmin,rolauditadmin FROM pg_roles WHERE rolcreaterole = 'true';";
String sql ="SELECT * FROM (SELECT datname, grantee, privilege_type AS pri_t FROM (SELECT datname, (aclexplode(COALESCE(datacl, acldefault('d'::\"char\", datdba)))).grantee AS grantee, (aclexplode(COALESCE(datacl, acldefault('d'::\"char\", datdba)))).privilege_type AS privilege_type FROM pg_database WHERE datname NOT LIKE 'template%') subquery) a JOIN pg_roles b ON a.grantee = b.oid OR a.grantee = 0 WHERE b.rolname NOT LIKE 'gs%' GROUP BY a.datname, b.rolname;";
PreparedStatement statement = connection.prepareStatement(sql);
/*
*/
// 执行查询
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
String user = resultSet.getString("rol_name");
String table_name = resultSet.getString("table_name");
String privileges = resultSet.getString("privileges");
System.out.println("rol_name: " + user);
System.out.println("Table Name: " + table_name);
System.out.println("Privileges: " + privileges);
System.out.println("-----------------------------");
}
resultSet.close();
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,5 @@
#测试获取所有表格参数
GET http://localhost:8080/tables
Accept: application/json
###

View File

@ -0,0 +1,10 @@
server.port=8080
#spring.datasource.url=jdbc:postgresql://103.91.210.232:11343/db_department
spring.datasource.url=jdbc:postgresql://192.168.161.18:5432/db_department
spring.datasource.username=admin_department
spring.datasource.password=OpenGauss@123
spring.datasource.driver-class-name=org.postgresql.Driver
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
mybatis-plus.configuration.map-underscore-to-camel-case=true

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 10 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 10 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 10 KiB

View File

@ -0,0 +1,46 @@
<mxfile host="Electron" modified="2023-09-16T09:07:56.416Z" agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) draw.io/21.2.8 Chrome/112.0.5615.165 Electron/24.2.0 Safari/537.36" etag="DS6mNPUcs1X1ggw6hn5q" version="21.2.8" type="device">
<diagram name="第 1 页" id="Q_RMDecdKkPYmLVFq2oc">
<mxGraphModel dx="1036" dy="614" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="827" pageHeight="1169" math="0" shadow="0">
<root>
<mxCell id="0" />
<mxCell id="1" parent="0" />
<mxCell id="GeBEahTKlZRlFO_gMOTx-1" value="" style="dashed=0;outlineConnect=0;html=1;align=center;labelPosition=center;verticalLabelPosition=bottom;verticalAlign=top;shape=mxgraph.weblogos.myspace;fillColor=#003399;strokeColor=none" vertex="1" parent="1">
<mxGeometry x="340" y="160" width="63" height="70.2" as="geometry" />
</mxCell>
<mxCell id="GeBEahTKlZRlFO_gMOTx-2" value="" style="shape=step;perimeter=stepPerimeter;whiteSpace=wrap;html=1;fixedSize=1;rotation=45;" vertex="1" parent="1">
<mxGeometry x="414" y="300" width="120" height="30" as="geometry" />
</mxCell>
<mxCell id="GeBEahTKlZRlFO_gMOTx-3" value="&lt;font style=&quot;font-size: 16px;&quot;&gt;安全管理员&lt;br&gt;可创建&lt;br&gt;不可审&lt;br&gt;不可管&lt;/font&gt;" style="text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" vertex="1" parent="1">
<mxGeometry x="330" y="260" width="103" height="30" as="geometry" />
</mxCell>
<mxCell id="GeBEahTKlZRlFO_gMOTx-5" value="" style="dashed=0;outlineConnect=0;html=1;align=center;labelPosition=center;verticalLabelPosition=bottom;verticalAlign=top;shape=mxgraph.weblogos.myspace;fillColor=#003399;strokeColor=none" vertex="1" parent="1">
<mxGeometry x="520" y="380" width="63" height="70.2" as="geometry" />
</mxCell>
<mxCell id="GeBEahTKlZRlFO_gMOTx-6" value="&lt;font style=&quot;font-size: 16px;&quot;&gt;审计管理员&lt;br&gt;不可创建&lt;br&gt;可审&lt;br&gt;不可管&lt;/font&gt;" style="text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" vertex="1" parent="1">
<mxGeometry x="583" y="410" width="103" height="30" as="geometry" />
</mxCell>
<mxCell id="GeBEahTKlZRlFO_gMOTx-7" value="" style="dashed=0;outlineConnect=0;html=1;align=center;labelPosition=center;verticalLabelPosition=bottom;verticalAlign=top;shape=mxgraph.weblogos.myspace;fillColor=#003399;strokeColor=none" vertex="1" parent="1">
<mxGeometry x="200" y="380" width="63" height="70.2" as="geometry" />
</mxCell>
<mxCell id="GeBEahTKlZRlFO_gMOTx-8" value="&lt;font style=&quot;font-size: 16px;&quot;&gt;系统管理员&lt;br&gt;不可创建&lt;br&gt;不可审&lt;br&gt;可管理&lt;/font&gt;" style="text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" vertex="1" parent="1">
<mxGeometry x="97" y="410" width="103" height="30" as="geometry" />
</mxCell>
<mxCell id="GeBEahTKlZRlFO_gMOTx-9" value="&lt;font style=&quot;font-size: 14px;&quot;&gt;审计日志&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;/font&gt;" style="rounded=1;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="373" y="420" width="60" height="120" as="geometry" />
</mxCell>
<mxCell id="GeBEahTKlZRlFO_gMOTx-10" value="" style="shape=step;perimeter=stepPerimeter;whiteSpace=wrap;html=1;fixedSize=1;rotation=-225;" vertex="1" parent="1">
<mxGeometry x="240" y="320" width="120" height="30" as="geometry" />
</mxCell>
<mxCell id="GeBEahTKlZRlFO_gMOTx-13" value="" style="shape=step;perimeter=stepPerimeter;whiteSpace=wrap;html=1;fixedSize=1;rotation=0;" vertex="1" parent="1">
<mxGeometry x="270" y="440" width="90" height="25" as="geometry" />
</mxCell>
<mxCell id="GeBEahTKlZRlFO_gMOTx-14" value="" style="shape=step;perimeter=stepPerimeter;whiteSpace=wrap;html=1;fixedSize=1;rotation=-180;" vertex="1" parent="1">
<mxGeometry x="444" y="440" width="90" height="25" as="geometry" />
</mxCell>
<mxCell id="GeBEahTKlZRlFO_gMOTx-15" value="" style="ellipse;whiteSpace=wrap;html=1;aspect=fixed;fillColor=none;fontColor=#ffffff;strokeColor=#A50040;strokeWidth=2;" vertex="1" parent="1">
<mxGeometry x="490" y="320" width="210" height="210" as="geometry" />
</mxCell>
</root>
</mxGraphModel>
</diagram>
</mxfile>

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

View File

@ -0,0 +1,556 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<!--GPT Prompt-->
<!--GPT Prompt
Layui设计网页包含3部分设置3个内容改为侧边导航点击了侧边导航栏之后页面内容要切换成对应的内容而且页面内容要居中不能遮挡导航栏点击了侧边导航栏之后页面内容切换成对应的内容其他部分的内容不要显示了具体结果都用Thymeleaf 来渲染。
1、第一部分是三权分立管理员扫描结果包含三个子模块第一个模块是安全管理员列表和权限安全隐患情况第二个模块是系统管理员列表和权限安全隐患情况第三个模块是审计管理员列表和权限安全隐患情况
2、第二部分是表格权限扫描包含三个子模块第一个模块是当前数据库下所有的表的根据用户和表名分类的权限列表和权限安全隐患情况第二个模块是当前数据库下当前用户对表的权限列表和权限安全隐患情况第三个模块是所有公开的表格包括所在数据库所在schema名字列表和权限安全隐患情况
3、第三部分是用户角色权限扫描包含以“gs_role_”开头的用户/角色列表,
最下面中间增加一个刷新当前页面的按钮。
-->
<head>
<meta charset="utf-8">
<title>权限扫描仪表盘</title>
<link rel="stylesheet" href="layui/css/layui.css">
<style>
.layui-container {
margin-top: 30px;
}
.image{
display: flex;
justify-content: center;
}
.layui-side {
position: fixed;
left: 0;
top: 0;
bottom: 0;
width: 200px;
background-color: #fff;
border-right: 1px solid #e6e6e6;
z-index: 999;
}
.layui-body {
margin-left: 30px;
/*左侧边界的宽度定义*/
padding: 15px;
}
.layui-nav-tree .layui-nav-item>a {
font-size: 16px !important;
}
.layui-nav-tree .layui-nav-child {
background-color: #f9fafc;
}
.layui-nav-tree .layui-nav-child dd a {
font-size: 14px !important;
}
.layui-nav-tree .layui-this {
background-color: #f3f8ff !important;
}
.layui-nav-tree .layui-this a {
color: #000 !important;
font-weight: bold;
}
/* 新增样式 */
.content-section {
margin: auto;
max-width: 800px;
}
.content-item {
display: none;
}
.show {
display: block;
}
</style>
<script src="https://cdn.staticfile.org/layui/2.6.8/layui.min.js"></script>
</head>
<body>
<div class="layui-layout layui-layout-admin">
<div class="layui-header">
<div class="layui-logo">权限扫描仪表盘</div>
</div>
<!-- 侧边导航栏-->
<div class="layui-side layui-bg-white">
<div class="layui-nav-tree">
<ul class="layui-nav layui-nav-tree" lay-filter="test">
<li class="layui-nav-item">
<a href="javascript:;">三权分立权限扫描</a>
<dl class="layui-nav-child">
<dd><a href="javascript:;" onclick="showContent('security-admin-1')">安全管理员列表和权限安全隐患情况</a></dd>
<dd><a href="javascript:;" onclick="showContent('security-admin-2')">系统管理员列表和权限安全隐患情况</a></dd>
<dd><a href="javascript:;" onclick="showContent('security-admin-3')">审计管理员列表和权限安全隐患情况</a></dd>
</dl>
</li>
<li class="layui-nav-item">
<a href="javascript:;">表格及数据库权限扫描</a>
<dl class="layui-nav-child">
<dd><a href="javascript:;" onclick="showContent('table-permissions-1')">各用户对各表权限</a></dd>
<dd><a href="javascript:;" onclick="showContent('table-permissions-2')">各用户对各数据库权限</a></dd>
<dd><a href="javascript:;" onclick="showContent('table-permissions-3')">所有公开的表格</a></dd>
</dl>
</li>
<li class="layui-nav-item">
<a href="javascript:;" onclick="showContent('user-roles')">用户角色权限</a>
</li>
<li class="layui-nav-item">
<a href="javascript:;" onclick="refreshPage()">展示所有数据</a>
</li>
</ul>
</div>
</div>
<!--主题内容-->
<div class="layui-body">
<div id="content-section" class="content-section">
<!-- 安全管理员列表和权限安全隐患情况-->
<div id="security-admin-1" class="content-item">
<h1>1.1 安全管理员列表和权限安全隐患情况</h1><br>
<h2>安全管理员列表</h2>
<table id="createRoleAdminTable" class="layui-table">
<thead>
<tr>
<th>用户名</th>
<th>是否超级用户</th>
<th>是否具备创建角色权限</th>
<th>是否系统管理员</th>
<th>是否审计管理员</th>
</tr>
</thead>
<tbody></tbody>
</table>
<!-- <h3>安全信息: </h3>-->
<h2 id="creRolAdminErr"></h2>
<br><br><br><br>
<div class="image">
<img src="image/三权分立-安全.drawio.svg" width= 60%/>
</div>
<br>
通过三权分立角色模型实现权限的分派,且三个管理员角色独立行使权限,相互制约制衡。使得整个系统的权限不会因为权限集中而引入安全的风险。
<br><br><br><br>
</div>
<!-- 系统管理员列表和权限安全隐患情况-->
<div id="security-admin-2" class="content-item">
<h1>1.2 系统管理员列表和权限安全隐患情况</h1><br>
<h2>系统管理员列表</h2>
<table id="sysAdminTable" class="layui-table">
<thead>
<tr>
<th>用户名</th>
<th>是否超级用户</th>
<th>是否具备创建角色权限</th>
<th>是否系统管理员</th>
<th>是否审计管理员</th>
</tr>
</thead>
<tbody></tbody>
</table>
<h2 id="sysAdminErr"></h2>
<br>
<div class="image">
<img src="image/三权分立-系统.drawio.svg" width= 60%/>
</div>
<br>
通过三权分立角色模型实现权限的分派,且三个管理员角色独立行使权限,相互制约制衡。使得整个系统的权限不会因为权限集中而引入安全的风险。<br><br>
<br><br><br><br>
</div>
<!-- 审计管理员列表和权限安全隐患情况-->
<div id="security-admin-3" class="content-item">
<h1>1.3 审计管理员列表和权限安全隐患情况</h1><br>
<h2>审计管理员列表</h2>
<table id="auditAdminTable" class="layui-table">
<thead>
<tr>
<th>用户名</th>
<th>是否超级用户</th>
<th>是否具备创建角色权限</th>
<th>是否系统管理员</th>
<th>是否审计管理员</th>
</tr>
</thead>
<tbody></tbody>
</table>
<!-- <h3>安全信息: </h3>-->
<h2 id="auditAdminErr"></h2>
<br>
<div class="image">
<img src="image/三权分立-审计.drawio.svg" width= 60%/>
</div>
<br>
通过三权分立角色模型实现权限的分派,且三个管理员角色独立行使权限,相互制约制衡。使得整个系统的权限不会因为权限集中而引入安全的风险。
<br><br><br><br>
</div>
<div id="table-permissions-1" class="content-item">
<h1>2.1 各用户对各表权限</h1><br><br><!-- 当前数据库下所有表的根据用户和表名分类的权限列表和权限安全隐患情况的内容 -->
<table class="layui-table" id="rolTablePrivilegesTable">
<thead>
<tr>
<th>角色名称</th>
<th>表格名称</th>
<th>权限</th>
</tr>
</thead>
<tbody></tbody>
</table>
<br><br><br><br>
</div>
<div id="table-permissions-2" class="content-item">
<h1>2.2 各用户对各数据库权限</h1>
<table id="rol-dat-table" class="layui-table">
<!-- 当前数据库下当前用户对表的权限列表和权限安全隐患情况的内容 -->
</table>
<br><br><br><br>
</div>
<div id="table-permissions-3" class="content-item">
<h1>2.3 所有公开的表格</h1>
<table id="table_list" class="layui-table">
<!-- 所有公开的表格的内容 -->
</table>
</div>
<div id="user-roles" class="content-item">
<h1>3 用户角色权限策略</h1><br><br>
<h2>所有用户信息表</h2>
<table id="pgUserTable" class="layui-table">
<!-- 所有用户信息-->
</table><br><br>
<br>
<h3>根据表格分析:</h3><br>
<h3>1管理员可以有多个但是安全管理员只能有一个</h3>
<br>
如表格上所示,超级管理只有一个是正确的,符合权限要求。<br><br>
<br>
<h3>2禁止新建以“gs_role_”开头的用户/角色,也禁止将已有的用户/角色重命名为以“gs_role_”开头</h3>
<br>
如表格上所示没有以“gs_role_”开头的用户/角色,符合权限要求。<br><br>
<h3>3用户帐户创建原则</h3><br><br>
<a href="https://docs.opengauss.org/zh/docs/3.1.0/docs/Developerguide/三权分立.html">三权分立</a>openGauss用户帐户只能由系统管理员rolsystemadmin或拥有CREATEROLE属性的安全管理员创建和删除。
<br>
三权分立时用户帐户只能由初始用户omm和安全管理员rolcreaterole创建。
<br>
</div>
</div>
</div>
</div>
<script src="https://cdn.staticfile.org/jquery/3.5.1/jquery.min.js"></script>
<!--//安全管理员信息脚本-->
<script>
//安全管理员信息
$(document).ready(function() {
$.ajax({
url: "/creroladminerr",
dataType: "text",
success: function(creRolAdminErr) {
$("#creRolAdminErr").text(creRolAdminErr);
}
});
});
<!-- 创建安全管理员脚本-->
$(function () {
$.ajax({
url: '/creroladmin',
type: 'GET',
dataType: 'json',
success: function (data) {
var createRoleAdminHtml = '';
for (var i in data) {
createRoleAdminHtml += '<tr>' +
'<td>' + data[i].rolname + '</td>' +
'<td>' + (data[i].rolsuper ? '是' : '否') + '</td>' +
'<td>' + (data[i].rolcreaterole ? '是' : '否') + '</td>' +
'<td>' + (data[i].rolsystemadmin ? '是' : '否') + '</td>' +
'<td>' + (data[i].rolauditadmin ? '是' : '否') + '</td>' +
'</tr>';
}
$('#createRoleAdminTable tbody').html(createRoleAdminHtml);
layui.use('table', function () {
layui.table.render({
elem: '#createRoleAdminTable',
page: true,
limit: 10
});
});
}
});
});
</script>
<!--系统管理员信息-->
<script>
//系统管理员信息
$(document).ready(function() {
$.ajax({
url: "/sysadminerr",
dataType: "text",
success: function(sysAdminErr) {
$("#sysAdminErr").text(sysAdminErr);
}
});
});
<!-- 创建系统管理员脚本-->
$(function () {
$.ajax({
url: '/sysadmin',
type: 'GET',
dataType: 'json',
success: function (data) {
var sysAdminHtml = '';
for (var i in data) {
sysAdminHtml += '<tr>' +
'<td>' + data[i].rolname + '</td>' +
'<td>' + (data[i].rolsuper ? '是' : '否') + '</td>' +
'<td>' + (data[i].rolcreaterole ? '是' : '否') + '</td>' +
'<td>' + (data[i].rolsystemadmin ? '是' : '否') + '</td>' +
'<td>' + (data[i].rolauditadmin ? '是' : '否') + '</td>' +
'</tr>';
}
$('#sysAdminTable tbody').html(sysAdminHtml);
layui.use('table', function () {
layui.table.render({
elem: '#sysAdminTable',
page: true,
limit: 10
});
});
}
});
});
</script>
<!--//审计管理员信息-->
<script>
//审计管理员信息
$(document).ready(function() {
$.ajax({
url: "/auditadminerr",
dataType: "text",
success: function(auditAdminErr) {
$("#auditAdminErr").text(auditAdminErr);
}
});
});
<!-- 创建审计管理员脚本-->
$(function () {
$.ajax({
url: '/auditadmin',
type: 'GET',
dataType: 'json',
success: function (data) {
var auditAdminHtml = '';
for (var i in data) {
auditAdminHtml += '<tr>' +
'<td>' + data[i].rolname + '</td>' +
'<td>' + (data[i].rolsuper ? '是' : '否') + '</td>' +
'<td>' + (data[i].rolcreaterole ? '是' : '否') + '</td>' +
'<td>' + (data[i].rolsystemadmin ? '是' : '否') + '</td>' +
'<td>' + (data[i].rolauditadmin ? '是' : '否') + '</td>' +
'</tr>';
}
$('#auditAdminTable tbody').html(auditAdminHtml);
layui.use('table', function () {
layui.table.render({
elem: '#auditAdminTable',
page: true,
limit: 10
});
});
}
});
});
</script>
<!--获取RolTablePrivilege用户对每个表的权限-->
<script>
<!-- 创建获取RolTablePrivilege-->
$(function () {
$.ajax({
url: '/rolTablePrivileges',
type: 'GET',
dataType: 'json',
success: function (data) {
var rolTablePrivileges = '';
for (var i in data) {
rolTablePrivileges += '<tr>' +
'<td>' + data[i].rolName + '</td>' +
'<td>' + data[i].tableName + '</td>' +
'<td>' + data[i].privileges + '</td>' +
'</tr>';
}
$('#rolTablePrivilegesTable tbody').html(rolTablePrivileges);
layui.use('table', function () {
layui.table.render({
elem: '#rolTablePrivilegesTable',
page: true,
limit: 10
});
});
}
});
});
</script>
<!--获取RolDatPrivilege,用户对每个数据库的权限-->
<script>
layui.use(['table'], function () {
var table = layui.table;
// 使用Ajax请求数据
$.ajax({
url: '/rol-dat-privileges',
type: 'GET',
dataType: 'json',
success: function (data) {
renderTable(data);
},
error: function () {
layer.msg('获取数据失败');
}
});
// 渲染表格
function renderTable(data) {
table.render({
elem: '#rol-dat-table',
data: data,
cols: [[
{field: 'rolname', title: '角色名'},
{field: 'datname', title: '数据库名'},
{field: 'privileges', title: '权限', templet: '#privilegesTpl'}
]],
page: true // 开启分页功能
});
}
// 权限列的模板
layui.laytpl('{{# layui.each(d.privileges, function(index, item){ }}{{ item }}&nbsp;&nbsp;{{# }); }}').render(data, function(html){
$('#privilegesTpl').html(html);
});
});
</script>
<!--获取Table_list,展示所有表格-->
<script>
layui.use('table', function () {
var table = layui.table;
// 渲染表格
table.render({
elem: '#table_list',
url: '/tables',
method: 'get',
parseData: function(res) {
return {
"code": 0,
"msg": "",
"count": res.length,
"data": res
};
},
cols: [[
{field: 'database', title: '所属数据库'},
{field: 'tableSchema', title: '表格Schema'},
{field: 'tableName', title: '表名'}
]]
});
});
</script>
<!--Pg用户全部数据-->
<script>
layui.use('table', function () {
var table = layui.table;
// 渲染表格
table.render({
elem: '#pgUserTable',
url: '/pgusers',
method: 'get',
parseData: function(res) {
return {
"code": 0,
"msg": "",
"count": res.length,
"data": res
};
},
cols: [[
{field: 'usesysid', title: '用户ID'},
{field: 'usename', title: '用户名'},
{field: 'usesuper', title: '超级用户', templet: function (d) {
return d.usesuper ? '是' : '否';
}}
]]
});
});
</script>
<!-- 页面调整脚本 首次打开自动展示全部信息,点击导航栏对应信息回自动展示所选信息-->
<script>
// 获取要显示的内容区域元素
var contentItems = document.getElementsByClassName("content-item");
function showContent(contentId) {
// 遍历所有内容区域元素
for (var i = 0; i < contentItems.length; i++) {
var contentItem = contentItems[i];
// 如果内容区域的 id 和传入的 contentId 匹配,则显示该内容区域,否则隐藏
if (contentItem.id === contentId) {
contentItem.classList.add("show");
} else {
contentItem.classList.remove("show");
}
}
}
// 在页面加载完毕后执行刷新页面操作
window.onload = function () {
refreshPage();
};
function refreshPage() {
// 显示所有内容区域
for (var i = 0; i < contentItems.length; i++) {
contentItems[i].classList.add("show");
}
}
</script>
</body>
</html>

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1 @@
html #layuicss-skincodecss{display:none;position:absolute;width:1989px}.layui-code-h3,.layui-code-view{position:relative;font-size:12px}.layui-code-view{display:block;margin:10px 0;padding:0;border:1px solid #eee;border-left-width:6px;background-color:#FAFAFA;color:#333;font-family:Courier New}.layui-code-h3{padding:0 10px;height:40px;line-height:40px;border-bottom:1px solid #eee}.layui-code-h3 a{position:absolute;right:10px;top:0;color:#999}.layui-code-view .layui-code-ol{position:relative;overflow:auto}.layui-code-view .layui-code-ol li{position:relative;margin-left:45px;line-height:20px;padding:0 10px;border-left:1px solid #e2e2e2;list-style-type:decimal-leading-zero;*list-style-type:decimal;background-color:#fff}.layui-code-view .layui-code-ol li:first-child{padding-top:10px}.layui-code-view .layui-code-ol li:last-child{padding-bottom:10px}.layui-code-view pre{margin:0}.layui-code-notepad{border:1px solid #0C0C0C;border-left-color:#3F3F3F;background-color:#0C0C0C;color:#C2BE9E}.layui-code-notepad .layui-code-h3{border-bottom:none}.layui-code-notepad .layui-code-ol li{background-color:#3F3F3F;border-left:none}.layui-code-demo .layui-code{visibility:visible!important;margin:-15px;border-top:none;border-right:none;border-bottom:none}.layui-code-demo .layui-tab-content{padding:15px;border-top:none}

File diff suppressed because one or more lines are too long

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

File diff suppressed because one or more lines are too long

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 701 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 299 KiB

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,13 @@
package com.mcx.gaussprivilege;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class GaussTestApplicationTests {
@Test
void contextLoads() {
}
}