2025数据安全产业积分赛WP

admin 2025年4月6日23:08:25评论1 views字数 18933阅读63分6秒阅读模式

3.1 数据安全题

题目:ez_upload

解题步骤:

上传phtml即可绕过

2025数据安全产业积分赛WP

搜索发现在/var/www/rssss4a/目录下

答案: /var/www/rssss4a/

3.2 数据分析题

题目: 溯源取证 题目1

解题步骤:

先进行磁盘的恢复

2025数据安全产业积分赛WP

打开后选中所有,换字体颜色得到flag

2025数据安全产业积分赛WP
2025数据安全产业积分赛WP

答案: b1e9517338f261396511359bce56bf58

题目:数据社工  题目2

解题步骤:

统计字频得到“博林科技”

2025数据安全产业积分赛WP

使用脚本

# -*- coding: gbk -*-import os# 设置文件夹路径,确保路径正确folder_path = r'C:\Users\cyborg\Desktop\2025数字中国创新大赛数字安全赛道'output_file = r'C:\Users\cyborg\Desktop\博林科技信息.txt'# 创建一个输出文件with open(output_file, 'w', encoding='utf-8') as outfile:# 遍历文件夹中的所有文件for dirpath, dirnames, filenames in os.walk(folder_path):for filename in filenames:            file_path = os.path.join(dirpath, filename)# 只处理文本文件类型,你可以根据需要修改if filename.endswith(('html''txt''md')):  # 可根据需要增加更多文件格式                try:                    with open(file_path, 'r', encoding='utf-8') as infile:                        content = infile.read()# 搜索包含 "博林科技" 的信息if'博林科技'in content:                            outfile.write(f'文件: {file_path}n')                            outfile.write(f'内容: {content}nn')print(f"已提取: {file_path}")  # 可选:输出提取的文件路径                except Exception as e:print(f"无法读取文件 {file_path}: {e}")print(f"所有包含 '博林科技' 的信息已保存到 {output_file}")答案:

答案: 江苏博林科技有限公司

题目: 数据社工 题目3

解题步骤:

在10.数据泄露与社会工程/附件/爬取的网页/43/8497.html文件源代码查看得到

2025数据安全产业积分赛WP
# -*- coding: gbk -*-import os# 设置文件夹路径,确保路径正确folder_path = r'C:\Users\cyborg\Desktop\2025数字中国创新大赛数字安全赛道'output_file = r'C:\Users\cyborg\Desktop\张华强信息.txt'# 创建一个输出文件with open(output_file, 'w', encoding='utf-8') as outfile:# 遍历文件夹中的所有文件for dirpath, dirnames, filenames in os.walk(folder_path):for filename in filenames:            file_path = os.path.join(dirpath, filename)# 只处理文本文件类型,你可以根据需要修改if filename.endswith(('html''txt''md')):  # 可根据需要增加更多文件格式                try:                    with open(file_path, 'r', encoding='utf-8') as infile:                        content = infile.read()# 搜索包含 "张华强" 的信息if'张华强'in content:                            outfile.write(f'文件: {file_path}n')                            outfile.write(f'内容: {content}nn')print(f"已提取: {file_path}")  # 可选:输出提取的文件路径                except Exception as e:print(f"无法读取文件 {file_path}: {e}")print(f"所有包含 '张华强' 的信息已保存到 {output_file}")

答案: 13891889377

题目: 数据社工  题目4

解题步骤:

在10.数据泄露与社会工程/附件/爬取的网页/40/5840.html页面查看源代码即可找到

2025数据安全产业积分赛WP
# -*- coding: gbk -*-import os# 设置文件夹路径,确保路径正确folder_path = r'C:\Users\cyborg\Desktop\2025数字中国创新大赛数字安全赛道'output_file = r'C:\Users\cyborg\Desktop\博林科技信息.txt'# 创建一个输出文件with open(output_file, 'w', encoding='utf-8') as outfile:# 遍历文件夹中的所有文件for dirpath, dirnames, filenames in os.walk(folder_path):for filename in filenames:            file_path = os.path.join(dirpath, filename)# 只处理文本文件类型,你可以根据需要修改if filename.endswith(('html''txt''md')):  # 可根据需要增加更多文件格式                try:                    with open(file_path, 'r', encoding='utf-8') as infile:                        content = infile.read()# 搜索包含 "博林科技" 的信息if'博林科技'in content:                            outfile.write(f'文件: {file_path}n')                            outfile.write(f'内容: {content}nn')print(f"已提取: {file_path}")  # 可选:输出提取的文件路径                except Exception as e:print(f"无法读取文件 {file_path}: {e}")print(f"所有包含 '博林科技' 的信息已保存到 {output_file}")

答案: 61050119980416547X

题目: 数据社工 题目5

解题步骤:

根据手机号使用py脚本ocr找到车牌即可

2025数据安全产业积分赛WP

答案: 浙B QY318

题目:数据攻防 题目3

解题步骤:

写脚本提取出所有包含{"name": 的行,放到csv里面,用python排序计算重复数量

2025数据安全产业积分赛WP
# -*- coding: gbk -*-import csvimport jsonfrom collections import Counter# 读取 CSV 文件input_csv = 'out.csv'# 你的 CSV 文件名output_csv = 'ranked_output.csv'# 输出的 CSV 文件名# 存储去重后的数据data_list = []# 读取 CSV 文件并解析 JSONwith open(input_csv, 'r', encoding='gbk') as f:  # 你可以改成 utf-8 试试for line in f:        line = line.strip()if line:  # 确保行不为空            try:# **去除首尾多余的双引号,并将""替换回"**                cleaned_line = line.strip('"').replace('""''"')                data = json.loads(cleaned_line)  # 解析 JSON 数据                data_list.append(json.dumps(data, sort_keys=True))  # 统一格式化,便于去重统计            except json.JSONDecodeError:print(f"解析错误: {line}")# 统计出现次数counter = Counter(data_list)# 排序(按重复次数降序)sorted_data = sorted(counter.items(), key=lambda x: x[1], reverse=True)# 写入 CSVwith open(output_csv, 'w', newline='', encoding='gbk') as csvfile:    fieldnames = ['name''gender''phone''id_card''count']    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)    writer.writeheader()for item, count in sorted_data:        data = json.loads(item)  # 解析回 JSON 格式        data['count'] = count  # 添加统计次数        writer.writerow(data)print(f"数据已成功统计并保存到 {output_csv}")

答案: 4a7cb07cd31c9ef2090f5f9126c6a996

题目: 数据跨境 任务1

解题步骤:

直接运行脚本即可

# -*- coding: gbk -*-import jsonfrom collections import Counterfrom scapy.all import rdpcap, IP# 1. 读取敏感域名清单 JSON 文件with open("国外敏感域名清单.json""r", encoding="utf-8") as f:    sensitive_data = json.load(f)# 构建IP->域名映射字典sensitive_ip_to_domain = {}for category, cat_data in sensitive_data["categories"].items():    domains = cat_data["domains"]for domain, ip in domains.items():# 如果一个 IP 有多个域名,这里取第一个出现的if ip not in sensitive_ip_to_domain:            sensitive_ip_to_domain[ip] = domain# 2. 读取镜像流量的 pcap 文件(请确保 scapy 能读取该 pcap 文件)packets = rdpcap("某流量审计平台导出的镜像流量.pcap")# 3. 遍历包,统计向敏感IP发送流量包的次数ip_counter = Counter()for pkt in packets:if IP in pkt:        dst_ip = pkt[IP].dstif dst_ip in sensitive_ip_to_domain:            ip_counter[dst_ip] += 1# 4. 找出访问次数最多的敏感IP,并输出结果if ip_counter:    most_common_ip, count = ip_counter.most_common(1)[0]    domain = sensitive_ip_to_domain[most_common_ip]# 输出格式: 域名:IP地址:访问次数    result = f"{domain}:{most_common_ip}:{count}"print(result)else:print("没有访问清单中IP地址的流量。")

答案: chrome.com:57.195.144.48:20498

3.3 模型安全题

任务⼀:数据标注与完整性校

第⼀列为user_id(需要与在线团购平台中⽤⼾评价的⽤⼾ID对应,严格按照升序排列)

第⼆列为label(填写情感标注结果,仅⽀持0/1[负向情感/正向情感])

第三列为signature(填写基于⽤⼾ID、⽤⼾名、⼿机号⽣成的MD5签名,签名算法:32位⼩写 MD5[⽤⼾ID+⽤⼾名+⼿机号])

需要爬取网站的一些数据,提交主要是上面三列内容。

可以分解为两个任务,一个是爬取指定内容;另一个是对爬取的评论进行标注;情感分类标注,使用的是bert-base-chinese模型,代码如下:

import requestsimport pandas as pdimport hashlibfrom bs4 import BeautifulSoupfrom transformers import pipelinefrom tqdm import tqdmimport timeimport torch# 初始化BERT模型(确保输出LABEL_0=负面,LABEL_1=正面)print("Loading sentiment analysis model...")sentiment_analyzer = pipeline("text-classification",    model="bert-base-chinese",    device=0if torch.cuda.is_available() else-1)defget_product_reviews(product_id):"""获取指定商品ID的评论页面"""    url = f"http://47.117.187.156:32999/index.php?controller=product&action=detail&id={product_id}"    headers = {'User-Agent''Mozilla/5.0 (Windows NT 10.0; Win64; x64)'}try:        response = requests.get(url, headers=headers, timeout=10)        response.raise_for_status()return response.textexcept Exception as e:        print(f"Error fetching product {product_id}{str(e)[:50]}...")returnNonedefparse_reviews(html_content):"""解析HTML获取评论数据"""    soup = BeautifulSoup(html_content, 'html.parser')    reviews = []for review in soup.select('.review-item'):try:            reviews.append({'user_id': int(review.select_one('.user-id').text.split(':')[1].strip()),'username': review.select_one('.reviewer-name').text.split(':')[1].strip(),'phone': review.select_one('.reviewer-phone').text.split(':')[1].strip(),'comment': review.select_one('.review-content').text.strip()            })except Exception:continuereturn reviewsdefdetermine_sentiment(text):"""精确情感分析(0=负面,1=正面)"""try:        result = sentiment_analyzer(text[:512], truncation=True)[0]return0if result['label'] == 'LABEL_0'else1except:return0# 默认负面defgenerate_signature(user_id, username, phone):"""生成符合示例的MD5签名(严格小写)"""    input_str = f"{user_id}{username}{phone}".encode('utf-8')return hashlib.md5(input_str).hexdigest().lower()if __name__ == "__main__":# 配置参数    START_ID, END_ID = 1500# 爬取数据    print(f"Scraping products from {START_ID} to {END_ID}...")    all_reviews = []for pid in tqdm(range(START_ID, END_ID + 1)):if html := get_product_reviews(pid):            all_reviews.extend(parse_reviews(html))ifnot all_reviews:        print("No reviews found!")        exit()# 数据处理    df = pd.DataFrame(all_reviews)    df = df.drop_duplicates(subset=['user_id']).sort_values('user_id')# 情感分析(批量处理提升性能)    print("Analyzing sentiments...")    df['label'] = pd.Series(        sentiment_analyzer(            [text[:512for text in df['comment']],            truncation=True,            batch_size=32        )    ).apply(lambda x: 0if x['label'] == 'LABEL_0'else1)# 生成签名(完全匹配示例格式)    df['signature'] = df.apply(lambda x: generate_signature(x['user_id'], x['username'], x['phone']),        axis=1    )# 输出结果(严格三列,无表头)    output = df[['user_id''label''signature']]    output.to_csv('submit_1.csv', index=False, header=False)    print(f"Success! Results saved to submit_1.csv")    print("Label distribution:")    print(output['label'].value_counts())

任务⼆:数据清洗与特征⼯程

主要任务是:

第⼀列为product_id(需要与在线团购平台⾸⻚选项卡中的商品ID对应,严格按照升序排列)

第⼆列为sales(清洗后商品销量(负数或空值设为0))

第三列为category_id(根据商品名称,⽐对提供的商品分类表,找对最符合的标号)

第四列为reviews_number(填⼊商品ID下的评论总数,⽆评论则设置为0)

刚开始使用了自己写的一些规则进行标注,但是效果不是很好,就只能手动标注了。

先把商品名称爬下来,然后根据给的分类在category_id列进行手工标注,

2025数据安全产业积分赛WP
2025数据安全产业积分赛WP

最后再把自定义规则生成的category_id列替换即可,拿到分数还不错

2025数据安全产业积分赛WP
2025数据安全产业积分赛WP
import requestsimport pandas as pdimport refrom bs4 import BeautifulSoupfrom tqdm import tqdmimport timedeffetch_product_page(product_id, max_retries=3):"""获取商品页面 HTML(带重试机制)"""    url = f"http://47.117.187.156:32999/index.php?controller=product&action=detail&id={product_id}"    headers = {'User-Agent''Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'    }for attempt in range(max_retries):try:            response = requests.get(url, headers=headers, timeout=10)            response.raise_for_status()return response.textexcept Exception as e:if attempt == max_retries - 1:                print(f"Failed to fetch product {product_id}{str(e)[:50]}...")returnNone            time.sleep(2 ** attempt)  # 指数退避defparse_product_name(html):"""解析商品页面数据,提取商品名称"""    soup = BeautifulSoup(html, 'html.parser')try:        name = soup.select_one('section.product-detail h2').text.strip()return nameexcept Exception as e:        print(f"Parsing error: {e}")returnNonedefmain():# 配置参数    START_ID = 1    END_ID = 500    results = []# 进度条设置    pbar = tqdm(range(START_ID, END_ID + 1), desc="Processing Products")for product_id in pbar:        pbar.set_postfix({'current': product_id})        html = fetch_product_page(product_id)ifnot html:continue        name = parse_product_name(html)ifnot name:continue        results.append({'product_id': product_id, 'name': name})# 创建 DataFrame 并排序    df = pd.DataFrame(results)    df = df.sort_values('product_id').reset_index(drop=True)# 保存结果(确保 UTF-8 编码)    df.to_csv('product_names.csv', index=False, encoding='utf-8-sig')    print(f"n处理完成!共成功处理 {len(df)} 个商品")    print("结果已保存到 product_names.csv")    print("n数据样例:")    print(df.head())if __name__ == "__main__":    main()
import requestsimport pandas as pdimport refrom bs4 import BeautifulSoupfrom tqdm import tqdmimport time# 商品分类映射表(编号 -> 名称)CATEGORY_MAP = {1"手机"2"母婴用品"3"家居"4"书籍"5"蔬菜",6"厨房用具"7"办公"8"水果"9"宠物"10"运动",11"热水器"12"彩妆"13"保健品"14"酒水"15"玩具乐器",16"汽车"17"床上用品"18"洗护用品"19"五金"20"户外",21"珠宝"22"医疗器械"23"花卉园艺"24"游戏"25"园艺"}# 反向映射(名称 -> 编号)CATEGORY_REVERSE = {v: k for k, v in CATEGORY_MAP.items()}deffetch_product_page(product_id, max_retries=3):"""获取商品页面HTML(带重试机制)"""    url = f"http://47.117.187.156:32999/index.php?controller=product&action=detail&id={product_id}"    headers = {'User-Agent''Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'    }for attempt in range(max_retries):try:            response = requests.get(url, headers=headers, timeout=10)            response.raise_for_status()return response.textexcept Exception as e:if attempt == max_retries - 1:                print(f"Failed to fetch product {product_id}{str(e)[:50]}...")returnNone            time.sleep(2 ** attempt)  # 指数退避defclean_numeric(value):"""清洗数字数据(处理千分位、负值等)"""if pd.isna(value) or value == '':return0# 移除货币/单位符号和千分位逗号    cleaned = re.sub(r'[^d.-]''', str(value))try:        num = float(cleaned)return max(0, int(num)) if num.is_integer() else max(0, num)except ValueError:return0defparse_product_data(html):"""解析商品页面数据"""    soup = BeautifulSoup(html, 'html.parser')try:# 商品名称        name = soup.select_one('section.product-detail h2').text.strip()# 价格和销量(使用增强清洗)        price = clean_numeric(soup.select_one('.price').text)        sales = clean_numeric(soup.select_one('#productSales').text)# 评论数量        reviews_count = len(soup.select('.review-item'))return {'name': name,'sales': sales,'reviews_count': reviews_count        }except Exception as e:        print(f"Parsing error: {e}")returnNonedefdetect_category(product_name):"""增强版商品分类检测"""# 预处理:统一小写+去除特殊字符    cleaned_name = re.sub(r'[^wu4e00-u9fa5]''', product_name.lower())# 优先匹配的专有名词(需完全匹配)    priority_terms = {'热水器'11,'洗发水'18,'阿甘'18,  # 处理"阿甘精油洗发水"类特殊案例'沐浴露'18,'洗面奶'12# 彩妆类    }# 检查优先术语for term, cat_id in priority_terms.items():if term in cleaned_name:return cat_id# 分类关键词权重表(分类ID -> 关键词列表)    category_keywords = {11: ['热水器''电热水器''燃气热水'],18: ['洗发''护发''沐浴''洗护''精油'],12: ['彩妆''口红''粉底''眼影'],# 其他分类...    }# 权重计分    scores = {cat_id: 0for cat_id in category_keywords}for cat_id, keywords in category_keywords.items():for kw in keywords:if kw in cleaned_name:                scores[cat_id] += len(kw)  # 长关键词权重更高# 返回最高分分类(需超过阈值)if scores and max(scores.values()) >= 2:  # 至少匹配2个字符return max(scores.items(), key=lambda x: x[1])[0]# 最后尝试模糊匹配for cat_name, cat_id in CATEGORY_REVERSE.items():if len(cat_name) >= 2and cat_name in cleaned_name:return cat_idreturn0# 默认分类defmain():# 配置参数    START_ID = 1    END_ID = 500    results = []# 进度条设置    pbar = tqdm(range(START_ID, END_ID + 1), desc="Processing Products")for product_id in pbar:        pbar.set_postfix({'current': product_id})        html = fetch_product_page(product_id)ifnot html:continue        data = parse_product_data(html)ifnot data:continue# 分类检测        category_id = detect_category(data['name'])        results.append({'product_id': product_id,'sales': data['sales'],'category_id': category_id,'reviews_number': data['reviews_count']        })# 创建DataFrame并排序    df = pd.DataFrame(results)    df = df.sort_values('product_id').reset_index(drop=True)# 保存结果(确保UTF-8编码)    df.to_csv('submit_2.csv'              columns=['product_id''sales''category_id''reviews_number'],              index=False              encoding='utf-8')    print(f"n处理完成!共成功处理 {len(df)} 个商品")    print("结果已保存到 submit_2.csv")    print("n数据样例:")    print(df.head())if __name__ == "__main__":    main()

任务三:隐私保护与恶意检测

主要任务是:

第⼀列为user_id(需要与在线团购平台中⽤⼾评价的⽤⼾ID对应,严格按照升序排列)

第⼆列为desensitization(根据脱敏规则填写脱敏后的⼿机号)

第三列为code_check(根据user_id,判断所对应的使⽤设备字符串是否包含恶意代码规则所述内 容,存在则为FALSE,不存在恶意代码则为TRUE)

很简单用AI就行,把要求的数据爬下来,然后把加一列放ua头。

先爬取用户id、评价、ua头信息,按照要求处理并排序;处理效果如图:

2025数据安全产业积分赛WP

喂给ai让他直接给出带有恶意代码的用户id

2025数据安全产业积分赛WP

9, 43, 70, 73, 138, 145, 180, 182, 189, 191, 201, 213, 216, 221, 229, 235,  244, 253, 256, 263, 292, 293, 305, 338 353, 357, 380, 386, 387, 394, 442, 444,  , 446, 448, 450, 452, 460, 470, 486, 496, 498 789, 802, 804, 805, 812, 818, 819,  , 823, 831, 845, 847, 859, 864, 877, 888, 898, 906, 911, 919, 922, 927, 928, 945,  977, 994, 998, 999

然后保留表中user_id、desensitization列加上 code_check;把 code_check 列全写成 TRUE,然后用脚本替换上面的这些 id 对应的 code_check 值为 FALSE。即可

import requestsimport pandas as pdimport refrom bs4 import BeautifulSoupfrom tqdm import tqdmimport timedeffetch_product_page(product_id):"""获取商品页面HTML"""    url = f"http://47.117.187.156:32999/index.php?controller=product&action=detail&id={product_id}"    headers = {'User-Agent''Mozilla/5.0'}try:        response = requests.get(url, headers=headers, timeout=10)        response.raise_for_status()return response.textexcept Exception as e:        print(f"Error fetching product {product_id}{str(e)[:50]}...")returnNonedefdesensitize_phone(phone):"""手机号脱敏处理"""if len(phone) != 11ornot phone.isdigit():return phonereturnf"{phone[:3]}****{phone[-4:]}"defparse_user_data(html, product_id):"""解析用户数据(仅提取所需字段)"""    soup = BeautifulSoup(html, 'html.parser')    users = []for item in soup.select('.review-item'):try:            user_id = int(item.select_one('.user-id').text.split(':')[1].strip())            phone = item.select_one('.reviewer-phone').text.split(':')[1].strip()            comment = item.select_one('.review-content').text.strip()            user_agent = item.select_one('.user-agent').text if item.select_one('.user-agent'else""            users.append({'user_id': user_id,'desensitization': desensitize_phone(phone),'comment': comment,'user_agent': user_agent            })except Exception as e:            print(f"Parsing error in product {product_id}{e}")continuereturn usersdefmain(start_id=1, end_id=500):"""主处理函数"""    all_users = []for product_id in tqdm(range(start_id, end_id + 1), desc="Processing Products"):        html = fetch_product_page(product_id)ifnot html:continue        users = parse_user_data(html, product_id)if users:            all_users.extend(users)ifnot all_users:        print("No user data found!")return# 创建DataFrame并排序去重    df = pd.DataFrame(all_users)    df = df.sort_values('user_id').drop_duplicates('user_id')# 保存结果(UTF-8编码)    df.to_csv('data.csv'              columns=['user_id''desensitization''comment''user_agent'],              index=False,              encoding='utf-8-sig')    print(f"nSuccess! Saved {len(df)} users to user_data.csv")    print("Data sample:")    print(df.head())if __name__ == "__main__":    main()
import pandas as pd# 定义需要修改的user_id列表user_ids_to_modify = [9437073138145180182189191201213216221229235244253256263292293305338,353357380386387394442444446448450452460470486496498789802804805812818819,823831845847859864877888898906911919922927928945977994998999]# 读取CSV文件input_file = 'F:\CTF\比赛\2025数字中国\model\input\data.csv'output_file = 'submit_3.csv'# 输出文件路径# 加载数据df = pd.read_csv(input_file)# 修改指定user_id的code_check值df.loc[df['user_id'].isin(user_ids_to_modify), 'code_check'] = False# 保存修改后的数据到新的CSV文件df.to_csv(output_file, index=False)print(f"更新后的文件已保存到 {output_file}")

样本对抗与数据投毒

任务⼀:对抗样本攻击

题目给了三个文件:训练好的模型⽂件.pkl(基于scikit-learn的逻辑回归模型);TF-IDF词向量器.pkl(将⽂本转换为TF-IDF特征向量,⽤于模型推理。); 原始⽂本数据集.csv

相当于白盒测试了;给的特征工程方法:TF-IDF。这种特征工程主要思想:如果在一篇文章中出现的频率TF高,并且在其他文章中很少出现;这个词就会占据很大的权重,被其认为这个词有类别区分的能力,可以用来做分类。那么按照其特性,我们可以在原样数据集中添加混淆的词,由于限制是<=5字符;针对这种评论性的任务,那么只能找主观意义上词义明确的词(一般人都会用的词)。

我这里最开始是使用:差差差;棒棒棒。来作为混淆字符,“差差差”加到好评文字后面,也就是answer==1的时候插入差差差,等于0插入棒棒棒,插入到原样数据集后再进行下一步测试。

我是使用了四组的混淆词,就已经把分数刷到90分以上:

1、差差差;棒棒棒;

2、差差差;不错;

3、差差差;不错,喜欢

4、不好,差评;不错,喜欢

为什么会选这些词,是有个技巧,后面会说到。

给我们的原始数据集为:

2025数据安全产业积分赛WP

创建一个新表,sample_id和answer列不变,把混淆词插入到sample值后面,然后存到adversarial_examples里。由于给了模型文件,同时说远端平台测试也是用的这些,那么我们直接可以在本地进行分类预测;把新表作为模型的输入数据集,将预测的结果0,1存到predictions列即可,方便后面对比刷分。

sample_id
adversarial_examples
predictions
answer
id
text
0 or 1
0 or 1

从第一组混淆词开始,得到反转率为:0.44;那么开始技巧,翻出最后保存的新表,可以看到好评反转成差评的效果还是不错的。

2025数据安全产业积分赛WP

但是在后面的差评反转好评的效果就不是很好,几乎是全军覆没。

2025数据安全产业积分赛WP

那我们先从好评的内容(没反转过来的)找找,肯定是有词权重更高,

2025数据安全产业积分赛WP
2025数据安全产业积分赛WP
2025数据安全产业积分赛WP

以这三个为例,没反转过来的这些中,不错出现的频率挺高,那么我们把好评的混淆词改为不错。然后再过一遍上面的流程。发现反转率已经到0.625。那么按照这个技巧继续找相关的影响词:好评没反转过来的,里面找好评权重高的词;差评没反转过来的,里面找差评权重高的词。

最终我是找到了:不好,差评;不错,喜欢。

这一组,最终的反转率也是在0.93。可能还有更好的词,例如好评反转差评,字符*,也有可能。

最后再把adversarial_examples列改为加的混淆词,把answer列删除即可提交。

import pandas as pdimport joblibfrom sklearn.feature_extraction.text import CountVectorizer# 读取原始CSV文件df = pd.read_csv('F:\CTF\比赛\2025数字中国\AI\样本对抗与数据投毒\mode\原始数据集_1000条.csv')  # 替换为你的文件名# 加载模型model = joblib.load('F:\CTF\比赛\2025数字中国\AI\样本对抗与数据投毒\mode\sentiment_model.pkl')# 加载向量化器vectorizer = joblib.load('F:\CTF\比赛\2025数字中国\AI\样本对抗与数据投毒\mode\tfidf_vectorizer.pkl')# 根据answer值修改sample列df['sample'] = df.apply(lambda row: row['sample'] + "差评,不好"if row['answer'] == 1else row['sample'] + "不错,喜欢", axis=1)# 添加的文本:1、差差差;棒棒棒;反转率:0.44 2、差差差;不错 反转率:0.625 3、差差差;不错,喜欢 反转率:0.871 4、不好,差评;不错,喜欢 反转率:0.93new_df = pd.DataFrame({'sample_id': df['sample_id'],'adversarial_examples': df['sample'],'answer': df['answer']})# 提取文本数据列texts = new_df['adversarial_examples']# 单行测试# texts = ["从这个价格来说,绝对是匠心工艺,强烈推荐大家购买,很难得遇到面料和质感这么舒服的,这绝不是刷单,我自己也是做鞋子衣服的,实在话差差差"]# 将文本转换为特征向量X = vectorizer.transform(texts)# 使用模型进行预测predictions = model.predict(X)# 将预测结果添加到数据框中# new_df['predictions'] = predictions# 打印预测结果# print(predictions)new_df = pd.DataFrame({'sample_id': new_df['sample_id'],'adversarial_examples': new_df['adversarial_examples'],'predictions': predictions,'answer': new_df['answer']})new_df.to_csv('F:\CTF\比赛\2025数字中国\AI\样本对抗与数据投毒\mode\submit4.csv', index=False, encoding='utf-8-sig')a = 0for i in range(len(new_df['answer'])):if new_df['answer'][i] != predictions[i]:        a = a + 1rang = a / len(new_df['answer'])print("反转率为:", rang)

原文始发于微信公众号(EuSRC安全实验室):2025数据安全产业积分赛WP

免责声明:文章中涉及的程序(方法)可能带有攻击性,仅供安全研究与教学之用,读者将其信息做其他用途,由读者承担全部法律及连带责任,本站不承担任何法律及连带责任;如有问题可邮件联系(建议使用企业邮箱或有效邮箱,避免邮件被拦截,联系方式见首页),望知悉。
  • 左青龙
  • 微信扫一扫
  • weinxin
  • 右白虎
  • 微信扫一扫
  • weinxin
admin
  • 本文由 发表于 2025年4月6日23:08:25
  • 转载请保留本文链接(CN-SEC中文网:感谢原作者辛苦付出):
                   2025数据安全产业积分赛WPhttps://cn-sec.com/archives/3917440.html
                  免责声明:文章中涉及的程序(方法)可能带有攻击性,仅供安全研究与教学之用,读者将其信息做其他用途,由读者承担全部法律及连带责任,本站不承担任何法律及连带责任;如有问题可邮件联系(建议使用企业邮箱或有效邮箱,避免邮件被拦截,联系方式见首页),望知悉.

发表评论

匿名网友 填写信息