task 추가

This commit is contained in:
ByeonJungHun
2024-01-11 15:47:36 +09:00
parent 2a9caec167
commit 76584fb0ba
54 changed files with 709 additions and 122 deletions

Binary file not shown.

View File

@@ -0,0 +1,38 @@
Role Name
=========
A brief description of the role goes here.
Requirements
------------
Any pre-requisites that may not be covered by Ansible itself or the role should be mentioned here. For instance, if the role uses the EC2 module, it may be a good idea to mention in this section that the boto package is required.
Role Variables
--------------
A description of the settable variables for this role should go here, including any variables that are in defaults/main.yml, vars/main.yml, and any variables that can/should be set via parameters to the role. Any variables that are read from other roles and/or the global scope (ie. hostvars, group vars, etc.) should be mentioned here as well.
Dependencies
------------
A list of other roles hosted on Galaxy should go here, plus any details in regards to parameters that may need to be set for other roles, or variables that are used from other roles.
Example Playbook
----------------
Including an example of how to use your role (for instance, with variables passed in as parameters) is always nice for users too:
- hosts: servers
roles:
- { role: username.rolename, x: 42 }
License
-------
BSD
Author Information
------------------
An optional section for the role authors to include contact information, or a website (HTML is not allowed).

View File

@@ -0,0 +1,15 @@
---
# defaults file for password
encrypt: 0 # strings 0 , encrypted 1
debug_mode: False
sshrootlogin: forced-commands-only
sshmainport: 2222
iptables_rules:
- { source: "10.10.45.0/24", target: "DROP" }
- { source: "10.10.47.0/24", target: "DROP" }
- { source: "10.10.48.0/24", target: "DROP" }
- { source: "10.10.50.0/24", target: "DROP" }
- { source: "10.10.37.0/24", target: "DROP" }
delete_rule: False
add_rule: True

View File

@@ -0,0 +1,44 @@
#!/usr/bin/python3
import base64, random, string, os
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from Crypto.Util.Padding import pad, unpad
try:
encrypt_flag=True if os.sys.argv[1].lower()=='1' else False
except Exception as err:
encrypt_flag=False
def generate_password(length=8, num_uppercase=1, num_lowercase=1, num_digits=1, num_sp_char=1):
sp_char = '!@#$'
all_chars = string.ascii_letters + string.digits + sp_char
password = [
*random.choices(string.ascii_uppercase, k=num_uppercase),
*random.choices(string.ascii_lowercase, k=num_lowercase),
*random.choices(string.digits, k=num_digits),
*random.choices(sp_char, k=num_sp_char)
]
remaining_length = length - (num_uppercase + num_lowercase + num_digits + num_sp_char)
password += random.choices(all_chars, k=remaining_length)
random.shuffle(password)
return ''.join(password)
def encrypt(plain_text, key):
manual_iv = b'PhilinnovatorDEV'
cipher = AES.new(key, AES.MODE_CBC, iv=manual_iv)
ct_bytes = cipher.encrypt(pad(plain_text.encode(), 16))
ct = base64.b64encode(ct_bytes).decode('utf-8')
return ct
key = b'PhilinnovatorDEVPhilinnovatorDEV'
plain_text = generate_password()
if encrypt_flag:
encrypted_text = encrypt(plain_text, key)
print(encrypted_text)
else:
print(plain_text)

View File

@@ -0,0 +1,11 @@
import hvac
str_url = "http://10.10.43.98:31080"
str_token = "hvs.CAESIMV6zCg-GpUP4pQgVA5f1ZXkgyJZrqOC6QDCegrpiAX9Gh4KHGh2cy5ORkpkc2ZyVUxYd09qUVFtQldRNDBjS3I"
client = hvac.Client(url=str_url, token=str_token)
str_mount_point = 'kv'
str_secret_path = 'host1'
read_secret_result = client.secrets.kv.v1.read_secret(mount_point=str_mount_point, path=str_secret_path)
print(read_secret_result)

View File

@@ -0,0 +1,108 @@
#!/usr/bin/python3
#-*- coding: utf-8 -*-
import os, sys, time, errno, socket, signal, psutil, random, logging.handlers, subprocess, paramiko, hvac
from xlwt import Workbook, XFStyle, Borders, Font, Pattern
from socket import error as SocketError
process_time = time.strftime("%Y%m%d_%H%M", time.localtime())
excel_file_name = '/mnt/e/excel/{}.xls'.format(process_time)
def process_close(flag=True, result=''):
if flag:
print("[Success]")
else:
print("[Fail]:{}".format(result))
sys.exit(0)
def set_header(sheet, header_list):
# 폰트 설정
font = Font()
font.bold = True
# 테두리 설정
borders = Borders()
borders.left = Borders.THIN
borders.right = Borders.THIN
borders.top = Borders.THIN
borders.bottom = Borders.THIN
# 배경색 설정
pattern = Pattern()
pattern.pattern = Pattern.SOLID_PATTERN
pattern.pattern_fore_colour = 22 # #E2EFDA는 xlwt에서 인덱스 22에 해당하는 색입니다.
hdrstyle = XFStyle()
hdrstyle.font = font
hdrstyle.borders = borders
hdrstyle.pattern = pattern
for idx, header in enumerate(header_list):
sheet.write(0, idx, header, hdrstyle)
sheet.col(idx).width = len(header) * 800
def write_data(sheet, data_list):
datestyle = XFStyle()
datestyle.num_format_str = 'YYYY-MM-DD'
for row_num, data in enumerate(data_list, start=1):
for col_num, cell_data in enumerate(data):
if col_num == 7:
sheet.write(row_num, col_num, cell_data, datestyle)
elif col_num in [1, 4, 5]:
formatted_data = u'{}'.format(cell_data) if cell_data else ''
sheet.write(row_num, col_num, formatted_data)
else:
sheet.write(row_num, col_num, cell_data)
def excel_write(header_list=[], data_list=[], filename='', sheetTitle=''):
workbook = Workbook(style_compression=2, encoding='utf-8')
sheet = workbook.add_sheet(sheetTitle)
set_header(sheet, header_list)
write_data(sheet, data_list)
sheet.panes_frozen = True
sheet.vert_split_pos = 0
sheet.horz_split_pos = 1
workbook.save(filename)
def main():
header_list=['번호','호스트 유형','호스트명','호스트 IP','포트번호','프로토콜','인증방법','1차 로그인 계정명','1차 로그인 비밀번호','1차 로그인 계정명','2차 로그인 비밀번호','용도','비고']
data_list=[]
openfile=open('/tmp/host_list','r')
readfile=openfile.readlines()
openfile.close()
for idx, host_data in enumerate(readfile):
try:
if idx==0: continue
host_num=idx
hosttype=host_data.strip().split(' ')[0]
print(hosttype)
hostname=host_data.strip().split(' ')[1]
host_ips=host_data.strip().split(' ')[2]
port_num=int(host_data.strip().split(' ')[3])
protocol='SSH'
auth_con='Password'
username=host_data.strip().split(' ')[4]
first_pw=host_data.strip().split(' ')[5]
rootuser=host_data.strip().split(' ')[6]
secon_pw=host_data.strip().split(' ')[7]
descript='-'
remarks_='-'
data_list.append([host_num,hosttype,hostname,host_ips,port_num,protocol,auth_con,username,first_pw,rootuser,secon_pw,descript,remarks_,])
except:
continue
excel_write(header_list, data_list, excel_file_name, 'TEST')
DEBUG=False
try:
if os.sys.argv[1]: DEBUG=True
except:
pass
main()
process_close()

View File

@@ -0,0 +1,21 @@
#!/usr/bin/python3
#-*- coding: utf-8 -*-
import base64, random, string, os
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from Crypto.Util.Padding import pad, unpad
try:
encrypted_text=os.sys.argv[1]
except:
encrypted_text="q6i1/JxyNe1OUrO0JKu+Z4WQTyQZam2yIJTp43dl1pI="
def decrypt(ct, key):
manual_iv = b'PhilinnovatorDEV'
ct_bytes = base64.b64decode(ct)
cipher = AES.new(key, AES.MODE_CBC, iv=manual_iv)
return unpad(cipher.decrypt(ct_bytes), 16).decode('utf-8')
key = b'PhilinnovatorDEVPhilinnovatorDEV'
print(decrypt(encrypted_text, key))

View File

@@ -0,0 +1,45 @@
#!/usr/bin/python3
#-*- coding: utf-8 -*-
import base64, random, string, os
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from Crypto.Util.Padding import pad, unpad
try:
encrypt_flag=True if os.sys.argv[1].lower()=='1' else False
except Exception as err:
encrypt_flag=False
def generate_password(length=12, num_uppercase=3, num_lowercase=4, num_digits=3, num_sp_char=2):
sp_char = '!@#$'
all_chars = string.ascii_letters + string.digits + sp_char
password = [
*random.choices(string.ascii_uppercase, k=num_uppercase),
*random.choices(string.ascii_lowercase, k=num_lowercase),
*random.choices(string.digits, k=num_digits),
*random.choices(sp_char, k=num_sp_char)
]
remaining_length = length - (num_uppercase + num_lowercase + num_digits + num_sp_char)
password += random.choices(all_chars, k=remaining_length)
random.shuffle(password)
return ''.join(password)
def encrypt(plain_text, key):
manual_iv = b'PhilinnovatorDEV'
cipher = AES.new(key, AES.MODE_CBC, iv=manual_iv)
ct_bytes = cipher.encrypt(pad(plain_text.encode(), 16))
ct = base64.b64encode(ct_bytes).decode('utf-8')
return ct
key = b'PhilinnovatorDEVPhilinnovatorDEV'
plain_text = generate_password()
if encrypt_flag:
encrypted_text = encrypt(plain_text, key)
print(encrypted_text)
else:
print(plain_text)

View File

@@ -0,0 +1,17 @@
#!/usr/bin/python3
#-*- coding: utf-8 -*-
import hvac
import os
hostname=os.sys.argv[1]
str_url = "http://10.10.43.240:30803"
client = hvac.Client(url=str_url)
client.auth.approle.login(role_id="e96c5fd8-abde-084a-fde7-7450a9348a70", secret_id="5371706b-414a-11d3-f3fd-6cf98871aad1")
try:
data = client.secrets.kv.v2.read_secret_version(mount_point='host', path=hostname, raise_on_deleted_version=True)['data']['data']
print(data)
except Exception as err:
print(err)

View File

@@ -0,0 +1,21 @@
#!/usr/bin/python3
#-*- coding: utf-8 -*-
import hvac
import os
hostname=os.sys.argv[1]
accountid=os.sys.argv[2]
password=os.sys.argv[3]
adminuser=os.sys.argv[4]
adminpass=os.sys.argv[5]
str_url = "http://10.10.43.240:30803"
client = hvac.Client(url=str_url)
client.auth.approle.login(role_id="e96c5fd8-abde-084a-fde7-7450a9348a70", secret_id="5371706b-414a-11d3-f3fd-6cf98871aad1")
client.secrets.kv.v2.create_or_update_secret(
mount_point='host',
path=hostname,
secret=dict(accountid=f'{accountid}',password=f'{password}',adminuser=f'{adminuser}',adminpass=f'{adminpass}')
)

View File

@@ -0,0 +1,16 @@
---
- name: Reload systemd configuration
ansible.builtin.systemd:
daemon_reload: True
- name: Restart teleport service
ansible.builtin.systemd:
name: teleport
enabled: true
state: restarted
- name: restart sshd
service:
name: sshd
state: restarted
enabled: true

View File

@@ -0,0 +1,52 @@
galaxy_info:
author: your name
description: your role description
company: your company (optional)
# If the issue tracker for your role is not on github, uncomment the
# next line and provide a value
# issue_tracker_url: http://example.com/issue/tracker
# Choose a valid license ID from https://spdx.org - some suggested licenses:
# - BSD-3-Clause (default)
# - MIT
# - GPL-2.0-or-later
# - GPL-3.0-only
# - Apache-2.0
# - CC-BY-4.0
license: license (GPL-2.0-or-later, MIT, etc)
min_ansible_version: 2.1
# If this a Container Enabled role, provide the minimum Ansible Container version.
# min_ansible_container_version:
#
# Provide a list of supported platforms, and for each platform a list of versions.
# If you don't wish to enumerate all versions for a particular platform, use 'all'.
# To view available platforms and versions (or releases), visit:
# https://galaxy.ansible.com/api/v1/platforms/
#
# platforms:
# - name: Fedora
# versions:
# - all
# - 25
# - name: SomePlatform
# versions:
# - all
# - 1.0
# - 7
# - 99.99
galaxy_tags: []
# List tags for your role here, one per line. A tag is a keyword that describes
# and categorizes the role. Users find roles by searching for tags. Be sure to
# remove the '[]' above, if you add tags to this list.
#
# NOTE: A tag is limited to a single word comprised of alphanumeric characters.
# Maximum 20 tags per role.
dependencies: []
# List your role dependencies here, one per line. Be sure to remove the '[]' above,
# if you add dependencies to this list.

Binary file not shown.

View File

@@ -0,0 +1,103 @@
---
- name: "Create datasaker group"
ansible.builtin.group:
name: "datasaker"
state: present
when:
- add_rule == True
- name: Ensure user datasaker exists
user:
name: "{{ item }}"
create_home: yes
home: "/home/{{ item }}"
group: datasaker
shell: /bin/bash
with_items:
- datasaker
when:
- add_rule == True
- name: "Ensure .ssh directory exists for datasaker"
file:
path: /home/datasaker/.ssh
state: directory
owner: datasaker
group: datasaker
mode: '0700'
when:
- add_rule == True
- name: "Add authorized key for datasaker"
authorized_key:
user: datasaker
key: "{{ item }}"
with_items:
- "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDRP/Kjn7UBudTO4ZLtWXRJNDcOPGbm+5jLKax+1tVgN2n0MCmwwrbFJQJvdaE/wp4+PnMtEyt+IqdwFdUDah8tu9CIYZ2Jk2T18oU7hYGvymh+QJmZgCNvYcmM9ATJbXpns7y8VLDVbkSq9EJIB+emLt1ZV/C8cyvhlmBUwGQA6c3zMgzWl9MT0HLa7H88cNVVknZPY0vGIw+H0Y2JtDr62xyVNT7w8B+jh7Yu6nCnQchwx3IRWGATuKfi2FB3rhkDqNvM1h00JJosu5ooBn3g5xll+w+sVKIQxEWShI9zatYP9/zrce+uVYeZLfz52X8giJ9dns66vqEKdJtdp4By5RPxRSsdQ2QGAQ0UuBHKgweU2EzivLynu49oiShAiJPxmru4TiGtchl52dvw/E9rjZiCKTq697azHHLbwTiOgbHpnu7GrxNRMdXCON70RYJpfERg/SGxxmUNF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p97Itpo6Iqq+PuRcZOes0EiIQe2hOoYQEIHIRhf8CZ+Xf6W1+XZB+WxEzUe4GCCwgUdTB6RIr4ThDxwCBV0="
when:
- add_rule == True
- name: "sudoers_users file"
file:
path: /etc/sudoers.d/sudoers_users
state: touch
when:
- add_rule == True
- name: "Allow user to sudo"
lineinfile:
path: /etc/sudoers.d/sudoers_users
line: "{{ item }} ALL=(ALL) NOPASSWD:ALL"
state: present
with_items:
- datasaker
when:
- add_rule == True
- name: "selinux permissive"
command: "setenforce 0"
ignore_errors: yes
when:
- ansible_facts.os_family == "RedHat"
- name: "firewalld stop"
systemd:
name: firewalld
state: stopped
enabled: false
ignore_errors: yes
when:
- ansible_facts.os_family == "RedHat"
- name: Remove existing Port lines
lineinfile:
path: /etc/ssh/sshd_config
regexp: '^Port'
state: absent
- name: SSH Listen on Main Port
lineinfile:
dest: /etc/ssh/sshd_config
insertbefore: '^#*AddressFamily'
line: 'Port {{sshmainport}}'
state: present
owner: root
group: root
mode: 0640
notify: restart sshd
- name: "Create sshd_config.d directory"
ansible.builtin.file:
path: "/etc/ssh/sshd_config.d/"
state: directory
recurse: yes
owner: root
group: root
- name: "Setting sshd allow users"
template:
src: allow_users.j2
dest: "/etc/ssh/sshd_config.d/allow_users.conf"
notify: restart sshd

View File

@@ -0,0 +1,36 @@
---
- name: get password
command: "{{ role_path }}/files/gen_password {{ encrypt }}"
register: user_password
delegate_to: 127.0.0.1
when: manual_password is not defined
- name: get admin password
command: "{{ role_path }}/files/gen_password {{ encrypt }}"
register: admin_password
delegate_to: 127.0.0.1
when: manual_password is not defined
- name: set fact user password
block:
- set_fact:
user_password: "{{ user_password.stdout }}"
rescue:
- set_fact:
user_password: "{{ manual_password }}"
always:
- debug:
msg: "{{ username }} : {{ user_password }}"
when: debug_mode == True
- name: set fact admin password
block:
- set_fact:
admin_password: "{{ admin_password.stdout }}"
rescue:
- set_fact:
admin_password: "{{ manual_password }}"
always:
- debug:
msg: "{{ adminuser }} : {{ admin_password }}"
when: debug_mode == True

View File

@@ -0,0 +1,21 @@
---
- include_tasks: 99_decrypt_password.yml
when:
- encrypt == 1
- manual_password is not defined
- name: user password change
user:
name: "{{ item }}"
password: "{{ user_password | password_hash('sha512') }}"
state: present
with_items:
- "{{ username }}"
- name: admin password change
user:
name: "{{ item }}"
password: "{{ admin_password | password_hash('sha512') }}"
state: present
with_items:
- "{{ adminuser }}"

View File

@@ -0,0 +1,21 @@
---
- name: Check if ansible_port is defined
set_fact:
ansible_port: "{{ ansible_port | default(22) }}"
- debug:
msg: "{{ ansible_distribution }} {{ ansible_hostname }} {{ ansible_default_ipv4.address }} {{ ansible_port }} {{ username }} {{ user_password }} {{ adminuser }} {{ admin_password }}"
when: debug_mode == True
- name: put vault
command: "{{ role_path }}/files/vault_put {{ ansible_default_ipv4.address }} {{ username }} {{ user_password }} {{ adminuser }} {{ admin_password }}"
delegate_to: 127.0.0.1
- name: get vault
command: "{{ role_path }}/files/vault_get {{ ansible_default_ipv4.address }} {{ username }} {{ user_password }} {{ adminuser }} {{ admin_password }}"
register: get_vault
delegate_to: 127.0.0.1
- debug:
msg: "{{get_vault.stdout_lines}}"
when: debug_mode == True

View File

@@ -0,0 +1,27 @@
---
- name: user_password decrypt
command: "{{ role_path }}/files/decrypt_password {{ user_password }}"
register: user_password
delegate_to: 127.0.0.1
- name: admin_password decrypt
command: "{{ role_path }}/files/decrypt_password {{ admin_password }}"
register: admin_password
delegate_to: 127.0.0.1
when:
- encrypt == 1
- manual_password is not defined
- name: admin_password re fact
set_fact:
admin_password: "{{ admin_password.stdout }}"
when:
- encrypt == 1
- manual_password is not defined
- name: user_password re fact
set_fact:
user_password: "{{ user_password.stdout }}"
when:
- encrypt == 1
- manual_password is not defined

View File

@@ -0,0 +1,15 @@
---
- include: 00_host_setting.yml
tags: host
- include: 01_get_password.yml
tags: password
- include: 02_change_password.yml
tags: change
- include: 03_vault.yml
tags: vault
#
#- include: 04_excel_export.yml
# tags: excel

View File

@@ -0,0 +1,22 @@
AllowUsers datasaker@10.10.43.*
AllowUsers *@10.20.142.*
{% if ansible_distribution == "Ubuntu" %}
AllowUsers ubuntu@10.10.43.*
{% endif %}
{% if ansible_distribution == "CentOS" %}
AllowUsers centos@10.10.43.*
{% endif %}
{% if ansible_distribution == "RedHat" %}
AllowUsers redhat@10.10.43.*
{% endif %}
{% if admin_users is defined %}
{% for user in admin_users %}
AllowUsers {{ user.name }}@{{ user.ip }}
{% endfor %}
{% endif %}
{% if allow_users is defined %}
{% for user in allow_users %}
AllowUsers {{ user.name }}@{{ user.ip }}
{% endfor %}
{% endif %}

View File

@@ -0,0 +1,2 @@
localhost

View File

@@ -0,0 +1,5 @@
---
- hosts: localhost
remote_user: root
roles:
- password

View File

@@ -0,0 +1,2 @@
---
# vars file for password