【dotnet】安全编码规范

server/2025/2/8 11:57:04/

本文将从代码安全、数据安全、身份安全、通信安全四个维度,总结15个关键设计原则,并附典型场景的解决方案与代码示例,助你规避90%的安全风险:


一、代码安全:构建安全防线

1. 输入验证:第一道屏障
  • 漏洞场景:未过滤用户输入导致SQL注入、XSS攻击。
  • 防御方案
    // 使用白名单验证(正则表达式)
    if (!Regex.IsMatch(input, @"^[a-zA-Z0-9_\-@.]+$")) throw new ArgumentException("非法字符");// ASP.NET Core模型验证
    public class UserModel
    {[Required][StringLength(50, MinimumLength = 3)][RegularExpression(@"^[a-z0-9_]+$")] // 只允许小写字母、数字、下划线public string Username { get; set; }
    }
    
2. 安全使用第三方库
  • 风险点:过期的NuGet包包含已知漏洞(如Newtonsoft.Json旧版本反序列化漏洞)。
  • 工具链
    • 使用dotnet list package --vulnerable扫描项目。
    • 配置NuGet.config强制使用HTTPS源:
      <configuration><packageSources><add key="nuget.org" value="https://api.nuget.org/v3/index.json" /></packageSources>
      </configuration>
      
3. 安全异常处理
  • 反模式:暴露堆栈信息给用户。
  • 优化方案
    try { /* 业务代码 */ }
    catch (Exception ex)
    {// 记录完整错误_logger.LogError(ex, "操作失败");// 返回友好提示return BadRequest("请求处理失败,请联系管理员");
    }
    

二、数据安全:保护敏感信息

4. 数据库安全连接
  • 错误示例:硬编码数据库连接字符串。
  • 安全实践
    // appsettings.json中加密存储
    "ConnectionStrings": {"Default": "Server=.;Database=MyDB;User Id=sa;Password=***;"
    }
    // 使用ASP.NET Core数据保护API加密
    services.AddDataProtection();
    services.Configure<ConnectionStrings>(options =>options.Default = _protector.Unprotect(Configuration["ConnectionStrings:Default"]));
    
5. 密码存储规范
  • 致命错误:明文存储或使用MD5/SHA1哈希。
  • 正确方案
    // ASP.NET Core Identity密码哈希
    var user = new IdentityUser { UserName = "test" };
    var hashedPassword = _userManager.PasswordHasher.HashPassword(user, "P@ssw0rd");// 验证密码
    var result = _userManager.PasswordHasher.VerifyHashedPassword(user, hashedPassword, inputPassword);
    
6. 加密敏感数据
  • 场景:存储用户身份证号、银行卡号。
  • 方案
    // 使用AES-GCM加密(.NET 6+)
    byte[] key = ...; // 从安全存储获取
    var data = Encoding.UTF8.GetBytes("敏感信息");
    byte[] nonce = RandomNumberGenerator.GetBytes(12);var ciphertext = new byte[data.Length];
    var tag = new byte[16];
    using var aes = new AesGcm(key);
    aes.Encrypt(nonce, data, ciphertext, tag);// 存储 ciphertext + nonce + tag
    

三、身份安全:认证与授权

7. JWT安全实践
  • 配置要点
    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>{options.TokenValidationParameters = new TokenValidationParameters{ValidateIssuer = true,ValidIssuer = "myapp.com",ValidateAudience = true,ValidAudience = "myapp-users",ValidateLifetime = true,ClockSkew = TimeSpan.Zero, // 禁止时间偏移容忍IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey))};});
    
8. 防范CSRF攻击
  • ASP.NET Core方案
    services.AddAntiforgery(options => 
    {options.HeaderName = "X-CSRF-TOKEN"; // 自定义Header名称options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
    });// 在视图中注入Token
    <form method="post">@Html.AntiForgeryToken()<!-- 表单内容 -->
    </form>
    
9. 权限最小化原则
  • RBAC模型示例
    [Authorize(Roles = "Admin")]
    public class AdminController : Controller { /* 管理功能 */ }// 细粒度策略授权
    services.AddAuthorization(options =>
    {options.AddPolicy("DeletePolicy", policy => policy.RequireAssertion(context =>context.User.IsInRole("Admin") && context.User.HasClaim(c => c.Type == "CanDelete")));
    });
    

四、通信安全:通道与协议

10. 强制HTTPS
  • Startup配置
    services.AddHttpsRedirection(options =>
    {options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect;options.HttpsPort = 443;
    });// Kestrel强制HTTPS
    webBuilder.ConfigureKestrel(serverOptions =>
    {serverOptions.ConfigureHttpsDefaults(listenOptions =>{listenOptions.SslProtocols = SslProtocols.Tls12 | SslProtocols.Tls13;});
    });
    
11. API速率限制
  • ASP.NET Core 7+方案
    // 每个客户端每分钟100次请求
    builder.Services.AddRateLimiter(options =>
    {options.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, string>(context =>RateLimitPartition.GetFixedWindowLimiter(context.Connection.RemoteIpAddress?.ToString(),factory => new FixedWindowRateLimiterOptions{AutoReplenishment = true,PermitLimit = 100,Window = TimeSpan.FromMinutes(1)}));
    });
    
12. 安全Headers配置
  • 中间件示例
    app.Use(async (context, next) =>
    {context.Response.Headers.Add("Content-Security-Policy", "default-src 'self'; script-src 'self' 'unsafe-inline'");context.Response.Headers.Add("X-Content-Type-Options", "nosniff");context.Response.Headers.Add("Referrer-Policy", "strict-origin-when-cross-origin");await next();
    });
    

五、高级防御技巧

13. 安全日志审计
  • 结构化日志示例
    _logger.LogInformation("用户 {UserId} 从 {IP} 登录成功", user.Id, HttpContext.Connection.RemoteIpAddress);
    
14. 防范DDoS攻击
  • 云原生方案
    • 启用Azure/AWS的WAF(Web应用防火墙)。
    • 使用Cloudflare速率限制规则。
    • 配置健康检查自动缩放实例。
15. 依赖安全扫描
  • CI/CD集成
    # GitHub Actions示例
    - name: 安全扫描uses: ossf/scorecard-action@v2with:results_file: results.sarifresults_format: sarif
    

工具链推荐

  1. 静态分析:SonarQube、Roslyn Analyzers
  2. 动态测试:OWASP ZAP、Burp Suite
  3. 密钥管理:Azure Key Vault、HashiCorp Vault
  4. 监控告警:Application Insights、Sentry

总结

安全设计需贯穿开发全生命周期,核心原则是最小权限、纵深防御、不信任任何输入。建议:

  • 使用Security Code Scan等工具集成到CI流程
  • 定期进行渗透测试与漏洞扫描
  • 建立安全编码规范与应急响应机制

http://www.ppmy.cn/server/165945.html

相关文章

C++字符串相关内容

字符串 字符串&#xff0c;本质上是一个接一个字符的一组字符。字母、数字、符号等。 const char* 字符串名 字符后面会有一个空终止符&#xff0c;为0。 字符串从指针的内存地址开始&#xff0c;然后继续下去&#xff0c;直到它碰到0&#xff0c;然后意识到字符串终止了。 …

零基础Vue入门6——Vue router

本节重点&#xff1a; 路由定义路由跳转 前面几节学习的都是单页面的功能&#xff08;都在专栏里面https://blog.csdn.net/zhanggongzichu/category_12883540.html&#xff09;&#xff0c;涉及到项目研发都是有很多页面的&#xff0c;这里就需要用到路由&#xff08;vue route…

【Docker】 Manifest与Buildx:多架构镜像管理的解析与实践

一.manifest的概述 manifest包含了镜像的层、标签、作者等关键信息&#xff0c;并支持多架构镜像的管理。通过Manifest List&#xff0c;开发者能够为同一应用提供适用于不同架构的镜像&#xff0c;从而确保其在各类平台上的兼容性。实际上是把不同操作系统和架构打包成独立的一…

组学数据分析实操系列 | (二)一键实现MaxQuant非标定量蛋白质组学搜库结果的生信分析

前言 上一篇我们介绍了如何通过MaxQuant软件对非标定量蛋白质组学原始数据进行分析得到搜库结果&#xff0c;下一步该怎么做呢&#xff1f;今天和大家分享一个非常实用的工具——LFQ-Analyst。该工具由蒙纳士大学的组学和生信平台开发&#xff0c;是一个交互式Web应用程序&…

I.MX6ULL 中断介绍下

GIC重点寄存器 1.中断分发器寄存器&#xff08;Distributor register &#xff09; a.Distributor Control Register(中断分发控制寄存器), GICD_CTLR Purpose Enables the forwarding of pending interrupts from the Distributor to the CPU interfaces 使能将挂起的中断从…

高端入门:Ollama 本地高效部署DeepSeek模型深度搜索解决方案

目录 一、Ollama 介绍 二、Ollama下载 2.1 官网下载 2.2 GitHub下载 三、模型库 四、Ollmal 使用 4.1 模型运行&#xff08;下载&#xff09; 4.2 模型提问 五、Ollama 常用命令 相关推荐 一、Ollama 介绍 Ollama是一个专为在本地机器上便捷部署和运行大型语言模型&…

深度探索未来的搜索引擎 —— DeepSeek

随着信息时代的进步&#xff0c;我们每天都在生成、分享和消费大量的数据&#xff0c;如何从海量的内容中迅速找到有价值的信息&#xff0c;成为了现代社会的重要课题。传统的搜索引擎虽然在很长时间内引领了互联网的发展&#xff0c;但随着技术的进步和用户需求的变化&#xf…

Flutter List 的 every 如果回调函数抛出异常 应该如何处理

在使用 List 的 every 方法时&#xff0c;如果回调函数抛出异常&#xff0c;可以通过以下几种方式进行处理&#xff1a; 1. 在回调函数内部捕获异常 在回调函数内部使用 try-catch 语句捕获可能抛出的异常&#xff0c;并根据具体情况进行处理。这样可以避免异常直接导致 ever…