public InvalidVersion(IO.ITagStream tag, int expected, int got) : base() { Debug.LogFile.WriteLine("Invalid versioning: expected {0} but got {1}" + Program.NewLine + "\tIn {2}", expected.ToString(), got.ToString(), tag.GetExceptionDescription()); }
public override void Write(IO.EndianWriter stream) { Compiler comp = stream.Owner as Compiler; uint elementsAddress = 0; int flags = ( (tagRef.IsNonResolving ? 1<<1 : 0) ); if (tagRef.Elements.Count > 1) { elementsAddress = stream.PositionUnsigned; foreach (string i in tagRef.Elements) stream.WriteTag(i); comp.MarkLocationFixup(tagRef.Name, stream, true); stream.Write(flags); stream.Write((int)-1); stream.WritePointer(elementsAddress); } else { comp.MarkLocationFixup(tagRef.Name, stream, true); stream.Write(flags); stream.WriteTag(tagRef.Elements[0]); stream.Write((int)0); } }
protected void exportRevenueDataDump_Click(object sender, EventArgs e) { try { List<System.Data.SqlClient.SqlParameter> spParams = new List<System.Data.SqlClient.SqlParameter>(); spParams.Add(Param.CreateParam("STARTDATE", System.Data.SqlDbType.Date, DateTime.Now)); spParams.Add(Param.CreateParam("ENTRYDATESTART", System.Data.SqlDbType.Date, "1/1/2002")); spParams.Add(Param.CreateParam("ENTRYDATEEND", System.Data.SqlDbType.Date, DateTime.Now)); spParams.Add(Param.CreateParam("COMPANYID", System.Data.SqlDbType.Int, Convert.ToInt32(dropDownCompany.SelectedValue))); spParams.Add(Param.CreateParam("TRANSITY", System.Data.SqlDbType.VarChar, "Y")); spParams.Add(Param.CreateParam("TRANSITN", System.Data.SqlDbType.VarChar, "N")); spParams.Add(Param.CreateParam("REVENUETYPE", System.Data.SqlDbType.VarChar, "M")); spParams.Add(Param.CreateParam("ORDERBY", System.Data.SqlDbType.VarChar, "CONTRACT_NUMBER")); spParams.Add(Param.CreateParam("SHOWCONSOLIDATED", System.Data.SqlDbType.Int, 1)); spParams.Add(Param.CreateParam("EXCLUDEMTA", System.Data.SqlDbType.Int, 1)); spParams.Add(Param.CreateParam("STARTYEAR", System.Data.SqlDbType.Int, Convert.ToInt32(dropDownStartYear.SelectedValue))); using (IO io = new IO(WebCommon.ConnectionString)) { WebCommon.ExportHtmlToExcel("RevenueFlashDataDump", WebCommon.DataTableToHtmlTable(io.ExecuteDataSetQuery(IO.CreateCommandFromStoredProc("OnlineFlash_GetRevFlashDataDump", spParams)).Tables[0], "RevenueFlashDataDump")); } } catch (Exception ex) { WebCommon.LogExceptionInfo(ex); } }
protected Terminal(IO.ICharacterInDevice inDevice, IO.ICharacterOutDevice outDevice) { this.In = IO.CharacterReader.Open(IO.Filter.CharacterInDevice.Open(inDevice, this.FilterInput)); this.Out = IO.CharacterWriter.Open(outDevice) ?? new IO.Null.CharacterWriter(); if (this.Out.NotNull()) this.Out.AutoFlush = true; }
////------------------------------------------------------------------------------------------------------------------------------ /// <summary> /// Initializes a new instance of the <see cref="FlacFrame"/> class. /// </summary> /// <param name="stream"> /// The stream. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown if stream is null. /// </exception> private FlacFrame(IO.FlacStream stream) { if (stream == null) throw new ArgumentNullException("stream"); FlacStream = stream; }
public VT100(IO.Net.Telnet.Server server) : this(server as IO.IByteDevice) { this.server = server; this.Echo = true; this.Out.Write('\x1b', '[', 'c'); // Request Identification string }
public InvalidVersion(IO.ITagStream tag, int expected, int expected_size, int got, int got_size) : base() { Debug.LogFile.WriteLine("Invalid versioning: expected {0} (0x{1}) but got {2} (0x{3})" + Program.NewLine + "\tIn {4}", expected.ToString(), expected_size.ToString("X4"), got.ToString(), got_size.ToString("X4"), tag.GetExceptionDescription()); }
public Base Build(String name, IO.TextSection section, String prefix) { if (name == null) throw new ArgumentNullException("name"); if (section == null) throw new ArgumentNullException("section"); if (prefix == null) throw new ArgumentNullException("prefix"); DataMap datamap = new DataMap(section, prefix); Base element = null; switch (datamap.Type) { case ElementType.Animation: element = new AnimatedImage(this, name, datamap, SpriteManager, AnimationManager, SoundManager); break; case ElementType.Static: element = new StaticImage(this, name, datamap, SpriteManager, AnimationManager, SoundManager); break; case ElementType.Text: element = new Text(this, name, datamap, SpriteManager, AnimationManager, SoundManager); break; case ElementType.None: default: element = new Base(this, name, datamap, SpriteManager, AnimationManager, SoundManager); break; } m_elements.Add(element); return element; }
protected void InitializeForExport(ProjectState state, IO.XmlStream s) { s.ReadAttributeOpt("export", ref mIsExported); // if (IsExported) // state.Compiler.AddExport(this); }
public override void UpdateWithIOEvent(IO.IOEvent ioEvent) { if (ioEvent.Equals(rightMousePress)) { Vector2 sceenPosition = IOState.MouseScreenPosition(); Company rightClickCompany = this.PlayerObject.ClickCompany(sceenPosition); if (rightClickCompany != null) { new AddTransportVehicleToCompany(this.LocalPlayer, rightClickCompany, vehicle); this.LocalPlayer.PopUIContext(); new CompanySelected(this.NextInStack, rightClickCompany); } } else if (ioEvent.Equals(leftMousePress)) { this.LocalPlayer.PopUIContext(); this.UpdateNextInStackIO(ioEvent); } else { this.UpdateNextInStackIO(ioEvent); } }
public Base Build(IO.TextSection section, String prefix) { if (section == null) throw new ArgumentNullException("section"); if (prefix == null) throw new ArgumentNullException("prefix"); return Build(prefix, section, prefix); }
/// <summary> /// Creates a new restore index /// </summary> /// <param name="path"> /// The path to the restore index file to create /// </param> /// <param name="header"> /// The restore index header to insert /// </param> /// <returns> /// A new restore index implementation /// </returns> public static IRestoreIndex Create(IO.Path path, Header header) { // create the restore index file and schema Database.Create(path, "SkyFloe.Sqlite.Resources.RestoreIndex.sql"); var index = (RestoreIndex)null; try { // connect to the database and add the header row index = new RestoreIndex(path); index.Execute( "INSERT INTO Header (" + "Version) " + "VALUES (@p0);", header.Version = CurrentVersion ); return index; } catch { if (index != null) index.Dispose(); try { Database.Delete(path); } catch { } throw; } }
public bool DoSkill(Network.WorldClient client, IO.InteractiveObject io) { if (!this.IsCraftSkill) { if (io.State == IO.InteractiveObjectState.FULL) { client.Action.RefreshDirection(3);//TODO: From player direction var packet = "GA" + this.ID + ";501;" + client.Character.ID + ";" + io.CellID + "," + this.GetJobTime(); client.Character.Map.Engine.Send(packet); return true; } else { return false; } } else { if (client.Action.CurrentJobCraftSkill == null) { client.Action.CurrentJobCraftSkill = new JobCraftSkill(this, client); var packet = "ECK3|" + this.GetJobCraftMax() + ";" + this.ID; client.Send(packet); return false; } else { return false; } } }
public Server(IO.Context context, ConnectionCallback callback, ITcpServerSocket socket, bool closeOnEnd = false) { this.callback = callback; this.socket = socket; this.closeOnEnd = closeOnEnd; this.Context = context; }
public void SaveToXml(IO.XmlEditor xml, string node) { xml.SaveNode("Forecolor", node, GetXmlFromColor(ForeColor)); xml.SaveNode("Backcolor", node, GetXmlFromColor(BackColor)); xml.SaveNode("Bordercolor", node, GetXmlFromColor(BorderColor)); xml.SaveNode("Hovercolor", node, GetXmlFromColor(HoverColor)); }
public void LoadFromXml(IO.XmlEditor xml, string node) { ForeColor = GetColorFromXml(xml, node, "Forecolor"); BackColor = GetColorFromXml(xml, node, "Backcolor"); BorderColor = GetColorFromXml(xml, node, "Bordercolor"); HoverColor = GetColorFromXml(xml, node, "Hovercolor"); }
public Boolean Load(IO.File file, Int32 pcxsize, out Point size, out Texture2D pixels, out Texture2D palette) { if (file == null) throw new ArgumentNullException("file"); size = new Point(Int32.MinValue, Int32.MinValue); pixels = null; palette = null; Byte[] filedata = file.ReadBytes(pcxsize); if (filedata.Length != pcxsize) return false; IO.FileHeaders.PcxFileHeader header = new IO.FileHeaders.PcxFileHeader(filedata); Point tempsize = new Point(header.XMax - header.XMin + 1, header.YMax - header.YMin + 1); if (header.Manufacturer != 10 || header.Encoding != 1 || header.Version > 5 || header.BitsPerPixel != 8) return false; if (header.ColorPlanes != 1) return false; if (tempsize.X <= 0 || tempsize.Y <= 0) return false; size = tempsize; Int32 readoffset = 0; pixels = LoadPixels(filedata, size, header.BytesPerLine, ref readoffset); palette = LoadPalette(filedata, ref readoffset); return true; }
public void Write(IO.EndianWriter stream) { Compiler comp = stream.Owner as Compiler; Import import = comp.OwnerState.Importer as Import; int real_count = import.Groups.Count; stream.Write("dynamic tag groups", false); stream.Write((short)DataArray.MaxValue); stream.Write((short)Item.Size); stream.Write(true); stream.Write(true); stream.Write((short)0); MiscGroups.data.Write(stream); stream.Write((short)real_count);//stream.Write((short)Datums.Count); stream.Write((short)real_count);//stream.Write((short)Datums.Count); stream.Write(real_count); stream.WritePointer(stream.PositionUnsigned + 4); #region Write tag group datums foreach (Import.TagGroup tg in import.Groups.Values) { stream.Write((short)0); // Header stream.Write((short)0); // Flags comp.AddLocationFixup(tg.Name, stream, false); stream.Write((int)0); } #endregion #region Write null datums Item i = new Item(); int count = DataArray.MaxValue - real_count; for (int x = 0; x < count; x++) i.Write(stream); #endregion }
/// <summary> /// Creates a new backup index /// </summary> /// <param name="path"> /// The path to the backup index file to create /// </param> /// <param name="header"> /// The backup index header to insert /// </param> /// <returns> /// A new backup index implementation /// </returns> public static IBackupIndex Create(IO.Path path, Header header) { // create the backup index file and schema Database.Create(path, "SkyFloe.Sqlite.Resources.BackupIndex.sql"); var index = (BackupIndex)null; try { // connect to the database and add the header row index = new BackupIndex(path); index.Execute( "INSERT INTO Header (" + " Version, " + " CryptoIterations, " + " ArchiveSalt, " + " PasswordHash, " + " PasswordSalt) " + "VALUES (@p0, @p1, @p2, @p3, @p4);", header.Version = CurrentVersion, header.CryptoIterations, header.ArchiveSalt, header.PasswordHash, header.PasswordSalt ); return index; } catch { if (index != null) index.Dispose(); try { Database.Delete(path); } catch { } throw; } }
public unsafe PdbInfo(IO.FileStream inputStream, Metadata.Reader reader) { this.reader = reader; this.pdbFunctionMap = PdbFile.LoadFunctionMap(inputStream, out tokenToSourceMapping, out sourceServerData, reader); //inputStream.Seek(0L, IO.SeekOrigin.Begin); //this.remapTable = PdbFile.LoadRemapTable(inputStream); }
public int AddMarketTargets(MarketTarget marketTargets) { try { List<SqlParameter> spParams = new List<SqlParameter>(); spParams.Add(Param.CreateParam("MARKETID", SqlDbType.VarChar, marketTargets.marketId)); spParams.Add(Param.CreateParam("COMPANYID", SqlDbType.Int, marketTargets.companyId)); spParams.Add(Param.CreateParam("UPDATEDBY", SqlDbType.VarChar, Security.GetCurrentUserId)); spParams.Add(Param.CreateParam("DIRECTBUCKET1", SqlDbType.Int, marketTargets.directBucket1)); spParams.Add(Param.CreateParam("DIRECTBUCKET2", SqlDbType.Int, marketTargets.directBucket2)); spParams.Add(Param.CreateParam("DIRECTBUCKET3", SqlDbType.Int, marketTargets.directBucket3)); spParams.Add(Param.CreateParam("DIRECTBUCKET4", SqlDbType.Int, marketTargets.directBucket4)); spParams.Add(Param.CreateParam("DIRECTBUCKET5", SqlDbType.Int, marketTargets.directBucket5)); spParams.Add(Param.CreateParam("DIRECTBUCKET6", SqlDbType.Int, marketTargets.directBucket6)); spParams.Add(Param.CreateParam("AGENCYBUCKET1", SqlDbType.Int, marketTargets.agencyBucket1)); spParams.Add(Param.CreateParam("AGENCYBUCKET2", SqlDbType.Int, marketTargets.agencyBucket2)); spParams.Add(Param.CreateParam("AGENCYBUCKET3", SqlDbType.Int, marketTargets.agencyBucket3)); spParams.Add(Param.CreateParam("AGENCYBUCKET4", SqlDbType.Int, marketTargets.agencyBucket4)); spParams.Add(Param.CreateParam("AGENCYBUCKET5", SqlDbType.Int, marketTargets.agencyBucket5)); spParams.Add(Param.CreateParam("AGENCYBUCKET6", SqlDbType.Int, marketTargets.agencyBucket6)); using (IO io = new IO(WebCommon.KPIConnectionString)) { marketTargets.targetId = Convert.ToInt32(io.ExecuteScalarQuery(IO.CreateCommandFromStoredProc("KPI_ADDMARKETTARGETS", spParams))); } return marketTargets.targetId; } catch (Exception ex) { WebCommon.LogExceptionInfo(ex); throw new Exception("An error occurred while trying to add the targets for the Market."); } }
/// <summary> /// Creates a new AGIConnectionHandler to handle the given socket connection. /// </summary> /// <param name="socket">the socket connection to handle.</param> /// <param name="mappingStrategy">the strategy to use to determine which script to run.</param> public AGIConnectionHandler(IO.SocketConnection socket, IMappingStrategy mappingStrategy, bool SC511_CAUSES_EXCEPTION, bool SCHANGUP_CAUSES_EXCEPTION) { this.socket = socket; this.mappingStrategy = mappingStrategy; this._SC511_CAUSES_EXCEPTION = SC511_CAUSES_EXCEPTION; this._SCHANGUP_CAUSES_EXCEPTION = SCHANGUP_CAUSES_EXCEPTION; }
public XvdFile(string path) { _filePath = path; _io = new IO(path); LoadKeysFromDisk(); }
/// <summary> /// Gets the color from a XML node. /// </summary> /// <param name="xml">The XML Editor instance.</param> /// <param name="node">The node.</param> /// <param name="key">The key.</param> /// <returns></returns> protected Color GetColorFromXml(IO.XmlEditor xml, string node, string key) { return Color.FromArgb(xml.TryGetAttributeValue(key, node, "A").ToInt(), xml.TryGetAttributeValue(key, node, "R").ToInt(), xml.TryGetAttributeValue(key, node, "G").ToInt(), xml.TryGetAttributeValue(key, node, "B").ToInt()); }
/// <summary> /// 0: message /// </summary> /// <param name="w"></param> /// <param name="datas"></param> public void Pack(IO.Writer w, params object[] datas) { var p = new Packet(new PacketHeader {ID = ID}); p.Writer.Write((string)datas[0]); p.Write(w); }
public static bool AddRateDetail(Hashtable values) { try { using (IO io = new IO(WebCommon.ConnectionString)) { io.ExecuteActionQuery(IO.CreateCommandFromStoredProc("MASTERDATA_ADDRATEDETAIL", Param.CreateParam("RATEID", SqlDbType.Int, values["RATENAME"]), Param.CreateParam("RATELOCALRENEW", SqlDbType.Decimal, values["RATELOCALRENEW"]), Param.CreateParam("RATELOCALNEW", SqlDbType.Decimal, values["RATELOCALNEW"]), Param.CreateParam("RATENATIONALRENEW", SqlDbType.Decimal, values["RATENATIONALRENEW"]), Param.CreateParam("RATENATIONALNEW", SqlDbType.Decimal, values["RATENATIONALNEW"]), Param.CreateParam("RATEEFFECTIVEDATE", SqlDbType.Date, values["RATEEFFECTIVEDATE"]), Param.CreateParam("ACTIVE", SqlDbType.VarChar, values["ACTIVE"]), Param.CreateParam("ISPACKAGE", SqlDbType.Int, values["ISPACKAGE"]), Param.CreateParam("ENTEREDBY", SqlDbType.VarChar, Security.GetCurrentUserId))); } } catch (Exception ex) { WebCommon.LogExceptionInfo(ex); return false; } return true; }
public void Write(IO.EndianWriter stream) { int orgPos = stream.Position; if (address != 0) { if (offsets.Count == 0) { string name = (stream.Owner as Compiler).GetLocationName(this); Debug.LogFile.WriteLine("LocationWriteback: unused address! There are no references to '{0}'", name); } else foreach (uint tempPos in offsets) { stream.PositionUnsigned = tempPos; stream.WritePointer(address); } } else { string name = (stream.Owner as Compiler).GetLocationName(this); Debug.LogFile.WriteLine("LocationWriteback: failed to writeback! '{0}'s address was not set, {1} memory locations will be null!", name, offsets.Count.ToString()); } stream.Position = orgPos; }
public InvalidVersion(IO.ITagStream tag, string msg) { Debug.LogFile.WriteLine("Invalid versioning ({0})" + Program.NewLine + "\tIn {1}", msg, tag.GetExceptionDescription()); }
public ResourceGroupManager(IO.FileSystem fileSystem) { if (fileSystem == null) throw new ArgumentNullException("fileSystem"); FileSystem = fileSystem; }
private Oscillograph(IO.IStringStream stream) : base(stream) { IList<string> initCommands = new List<string>() { {"Hdr Off"}, {"Measurement:Meas1:State OFF"}, {"Measurement:Meas2:State OFF"}, {"Measurement:Meas3:State OFF"}, {"Measurement:Meas4:State OFF"}, {"Measurement:Meas1:Type Delay"}, {"Measurement:Meas1:Delay:Direction Forwards"}, {"Measurement:Meas1:Delay:Edge1 Rise"}, {"Measurement:Meas1:Delay:Edge2 Rise"}, {"Measurement:Meas1:Source CH1"}, {"Measurement:Meas1:Source2 CH2"}, {"Measurement:Meas1:State ON"}, {"Measurement:Meas2:Type Delay"}, {"Measurement:Meas2:Delay:Direction Forwards"}, {"Measurement:Meas2:Delay:Edge1 Fall"}, {"Measurement:Meas2:Delay:Edge2 Fall"}, {"Measurement:Meas2:Source CH1"}, {"Measurement:Meas2:Source2 CH2"}, {"Measurement:Meas2:State ON"} }; this.InitCommands = initCommands; }
public override void Bad() { byte data; if (IO.staticFive == 5) { /* init data */ data = 0; /* POTENTIAL FLAW: Read data from console with ReadLine*/ try { string stringNumber = Console.ReadLine(); if (stringNumber != null) { data = byte.Parse(stringNumber.Trim()); } } catch (IOException exceptIO) { IO.Logger.Log(NLog.LogLevel.Warn, "Error with stream reading", exceptIO); } catch (FormatException exceptNumberFormat) { IO.Logger.Log(NLog.LogLevel.Warn, "Error with number parsing", exceptNumberFormat); } } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run * but ensure data is inititialized before the Sink to avoid compiler errors */ data = 0; } if (IO.staticFive == 5) { /* POTENTIAL FLAW: if data == byte.MaxValue, this will overflow */ byte result = (byte)(data + 1); IO.WriteLine("result: " + result); } }
/* GoodG2B2() - use goodsource and badsink by reversing statements in first if */ private void GoodG2B2() { byte data; if (5 == 5) { /* FIX: Use a hardcoded number that won't cause underflow, overflow, divide by zero, or loss-of-precision issues */ data = 2; } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run * but ensure data is inititialized before the Sink to avoid compiler errors */ data = 0; } if (5 == 5) { /* POTENTIAL FLAW: if (data*data) > byte.MaxValue, this will overflow */ byte result = (byte)(data * data); IO.WriteLine("result: " + result); } }
/* goodB2G2() - use badsource and goodsink by reversing the blocks in the second switch */ private void GoodB2G2(HttpRequest req, HttpResponse resp) { string data; switch (6) { case 6: data = ""; /* initialize data in case there are no cookies */ /* Read data from cookies */ { HttpCookieCollection cookieSources = req.Cookies; if (cookieSources != null) { /* POTENTIAL FLAW: Read data from the first cookie value */ data = cookieSources[0].Value; } } break; default: /* INCIDENTAL: CWE 561 Dead Code, the code below will never run * but ensure data is inititialized before the Sink to avoid compiler errors */ data = null; break; } switch (7) { case 7: /* FIX: use URLEncoder.encode to hex-encode non-alphanumerics */ if (data != null) { data = HttpUtility.UrlEncode("", Encoding.UTF8); resp.AddHeader("Location", "/author.jsp?lang=" + data); } break; default: /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ IO.WriteLine("Benign, fixed string"); break; } }
private void GoodB2G1Sink(int data) { if (goodB2G1Private) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ IO.WriteLine("Benign, fixed string"); } else { /* Need to ensure that the array is of size > 3 and < 101 due to the GoodSource and the large_fixed BadSource */ int[] array = { 0, 1, 2, 3, 4 }; /* FIX: Fully verify data before reading from array at location data */ if (data >= 0 && data < array.Length) { IO.WriteLine(array[data]); } else { IO.WriteLine("Array index out of bounds"); } } }
public override void Bad() { byte data; if (5 == 5) { /* POTENTIAL FLAW: Use a random value */ data = (byte)(new Random().Next(byte.MinValue, byte.MaxValue)); } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run * but ensure data is inititialized before the Sink to avoid compiler errors */ data = 0; } if (5 == 5) { /* POTENTIAL FLAW: if (data*data) > byte.MaxValue, this will overflow */ byte result = (byte)(data * data); IO.WriteLine("result: " + result); } }
/* goodG2B() - use goodsource and badsink */ public static void GoodG2BSink(byte[] dataSerialized, HttpRequest req, HttpResponse resp) { try { string data; var binForm = new BinaryFormatter(); using (var memStream = new MemoryStream()) { memStream.Write(dataSerialized, 0, dataSerialized.Length); memStream.Seek(0, SeekOrigin.Begin); data = (string)binForm.Deserialize(memStream); } /* POTENTIAL FLAW: Instantiate object of class named in data (which may be from external input) */ var container = Activator.CreateInstance(null, data); Object tempClassObj = container.Unwrap(); IO.WriteLine(tempClassObj.GetType().ToString()); /* Use tempClassObj in some way */ } catch (SerializationException exceptSerialize) { IO.Logger.Log(NLog.LogLevel.Warn, "SerializationException in deserialization", exceptSerialize); } }
public override void Bad(HttpRequest req, HttpResponse resp) { string data; if (IO.StaticReturnsTrue()) { using (SecureString securePwd = new SecureString()) { using (SecureString secureUser = new SecureString()) { for (int i = 0; i < "AP@ssw0rd".Length; i++) { /* INCIDENTAL: CWE-798 Use of Hard-coded Credentials */ securePwd.AppendChar("AP@ssw0rd"[i]); } for (int i = 0; i < "user".Length; i++) { /* INCIDENTAL: CWE-798 Use of Hard-coded Credentials */ securePwd.AppendChar("user"[i]); } /* POTENTIAL FLAW: Set data to credentials (without hashing or encryption) */ data = secureUser.ToString() + ":" + securePwd.ToString(); } } } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run * but ensure data is inititialized before the Sink to avoid compiler errors */ data = null; } if (IO.StaticReturnsTrue()) { /* NOTE: potential incidental issues with not setting secure or HttpOnly flag */ /* POTENTIAL FLAW: Store data directly in cookie */ resp.AppendCookie(new HttpCookie("auth", data)); } }
/* goodB2G() - use badsource and goodsink */ private void GoodB2G() { int dataCopy; { int data; data = int.MinValue; /* Initialize data */ /* get environment variable ADD */ /* POTENTIAL FLAW: Read data from an environment variable */ { string stringNumber = Environment.GetEnvironmentVariable("ADD"); if (stringNumber != null) // avoid NPD incidental warnings { try { data = int.Parse(stringNumber.Trim()); } catch (FormatException exceptNumberFormat) { IO.Logger.Log(NLog.LogLevel.Warn, exceptNumberFormat, "Number format exception parsing data from string"); } } } dataCopy = data; } { int data = dataCopy; /* FIX: Add a check to prevent an overflow from occurring */ if (Math.Abs((long)data) <= (long)Math.Sqrt(int.MaxValue)) { int result = (int)(data * data); IO.WriteLine("result: " + result); } else { IO.WriteLine("data value is too large to perform squaring."); } } }
public override void Bad(HttpRequest req, HttpResponse resp) { string data; switch (6) { case 6: data = ""; /* initialize data in case there are no cookies */ /* Read data from cookies */ { HttpCookieCollection cookieSources = req.Cookies; if (cookieSources != null) { /* POTENTIAL FLAW: Read data from the first cookie value */ data = cookieSources[0].Value; } } break; default: /* INCIDENTAL: CWE 561 Dead Code, the code below will never run * but ensure data is inititialized before the Sink to avoid compiler errors */ data = null; break; } switch (7) { case 7: /* POTENTIAL FLAW: Input from file not verified */ if (data != null) { resp.AddHeader("Location", "/author.jsp?lang=" + data); } break; default: /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ IO.WriteLine("Benign, fixed string"); break; } }
/* goodG2B() - use goodsource and badsink by reversing the block outside the * for statement with the one in the for statement */ private void GoodG2B() { string data; /* FIX: Use a hardcoded string */ data = "foo"; for (int i = 0; i < 1; i++) { SqlConnection dbConnection = null; try { dbConnection = IO.GetDBConnection(); /* POTENTIAL FLAW: Set the database user name with the value of data * allowing unauthorized access to a portion of the DB */ dbConnection.ConnectionString = @"Data Source=" + "" + ";Initial Catalog=" + "" + ";User ID=" + data + ";Password="******""; dbConnection.Open(); } catch (SqlException exceptSql) { IO.Logger.Log(NLog.LogLevel.Warn, exceptSql, "Error getting database connection"); } finally { try { if (dbConnection != null) { dbConnection.Close(); } } catch (SqlException exceptSql) { IO.Logger.Log(NLog.LogLevel.Warn, exceptSql, "Error closing Connection"); } } } }
public override void Bad() { int data; if (privateTrue) { data = int.MinValue; /* Initialize data */ /* get environment variable ADD */ /* POTENTIAL FLAW: Read data from an environment variable */ { string stringNumber = Environment.GetEnvironmentVariable("ADD"); if (stringNumber != null) // avoid NPD incidental warnings { try { data = int.Parse(stringNumber.Trim()); } catch (FormatException exceptNumberFormat) { IO.Logger.Log(NLog.LogLevel.Warn, exceptNumberFormat, "Number format exception parsing data from string"); } } } } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run * but ensure data is inititialized before the Sink to avoid compiler errors */ data = 0; } if (privateTrue) { /* Need to ensure that the array is of size > 3 and < 101 due to the GoodSource and the large_fixed BadSource */ int[] array = { 0, 1, 2, 3, 4 }; /* POTENTIAL FLAW: Attempt to read from array at location data, which may be outside the array bounds */ IO.WriteLine(array[data]); } }
/* goodB2G1() - use badsource and goodsink by changing second privateFive==5 to privateFive!=5 */ private void GoodB2G1(HttpRequest req, HttpResponse resp) { string data; if (privateFive == 5) { data = ""; /* initialize data in case there are no cookies */ /* Read data from cookies */ { HttpCookieCollection cookieSources = req.Cookies; if (cookieSources != null) { /* POTENTIAL FLAW: Read data from the first cookie value */ data = cookieSources[0].Value; } } } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run * but ensure data is inititialized before the Sink to avoid compiler errors */ data = null; } if (privateFive != 5) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ IO.WriteLine("Benign, fixed string"); } else { if (data != null) { HttpCookie cookieSink = new HttpCookie("lang", HttpUtility.UrlEncode(data, Encoding.UTF8)); /* FIX: use URLEncoder.encode to hex-encode non-alphanumerics */ resp.AppendCookie(cookieSink); } } }
public static void BadSink(string data, HttpRequest req, HttpResponse resp) { if (CWE89_SQL_Injection__Web_ReadLine_ExecuteNonQuery_22a.badPublicStatic) { int?result = null; try { using (SqlConnection dbConnection = IO.GetDBConnection()) { dbConnection.Open(); using (SqlCommand badSqlCommand = new SqlCommand(null, dbConnection)) { /* POTENTIAL FLAW: data concatenated into SQL statement used in ExecuteNonQuery(), which could result in SQL Injection */ badSqlCommand.CommandText = "insert into users (status) values ('updated') where name='" + data + "'"; result = badSqlCommand.ExecuteNonQuery(); if (result != null) { IO.WriteLine("Name, " + data + ", updated successfully"); } else { IO.WriteLine("Unable to update records for user: "******"Error getting database connection", exceptSql); } } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run * but ensure data is inititialized before the Sink to avoid compiler errors */ data = null; } }
/* goodB2G2() - use badsource and goodsink by reversing statements in second if */ private void GoodB2G2(HttpRequest req, HttpResponse resp) { string data; if (PrivateReturnsTrue()) { /* POTENTIAL FLAW: Read data from a querystring using Params.Get */ data = req.Params.Get("name"); } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run * but ensure data is inititialized before the Sink to avoid compiler errors */ data = null; } if (PrivateReturnsTrue()) { int numberOfLoops; try { numberOfLoops = int.Parse(data); } catch (FormatException exceptNumberFormat) { IO.WriteLine("Invalid response. Numeric input expected. Assuming 1."); IO.Logger.Log(NLog.LogLevel.Warn, exceptNumberFormat, "Invalid response. Numeric input expected. Assuming 1."); numberOfLoops = 1; } /* FIX: loop number thresholds validated */ if (numberOfLoops >= 0 && numberOfLoops <= 5) { for (int i = 0; i < numberOfLoops; i++) { IO.WriteLine("hello world"); } } } }
/* goodB2G2() - use badsource and goodsink by reversing the blocks in the second switch */ private void GoodB2G2() { int data; switch (6) { case 6: /* POTENTIAL FLAW: Set data to a random value */ data = (new Random()).Next(); break; default: /* INCIDENTAL: CWE 561 Dead Code, the code below will never run * but ensure data is inititialized before the Sink to avoid compiler errors */ data = 0; break; } switch (7) { case 7: /* FIX: Add a check to prevent an overflow from occurring */ if (data < int.MaxValue) { int result = (int)(data + 1); IO.WriteLine("result: " + result); } else { IO.WriteLine("data value is too large to perform addition."); } break; default: /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ IO.WriteLine("Benign, fixed string"); break; } }
/* goodB2G1() - use badsource and goodsink by changing second 5==5 to 5!=5 */ private void GoodB2G1() { int data; if (5 == 5) { /* POTENTIAL FLAW: Set data to a value greater than the size of the array */ data = 100; } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run * but ensure data is inititialized before the Sink to avoid compiler errors */ data = 0; } if (5 != 5) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ IO.WriteLine("Benign, fixed string"); } else { /* Need to ensure that the array is of size > 3 and < 101 due to the GoodSource and the large_fixed BadSource */ int[] array = null; /* FIX: Verify that data is non-negative AND greater than 0 */ if (data > 0) { array = new int[data]; } else { IO.WriteLine("Array size is negative"); } /* do something with the array */ array[0] = 5; IO.WriteLine(array[0]); } }
/* Good1() changes 5==5 to 5!=5 */ private void Good1() { if (5 != 5) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ IO.WriteLine("Benign, fixed string"); } else { try { IO.WriteString("Enter float number: "); float num = 0; try { num = float.Parse(Console.ReadLine()); } catch (FormatException exceptNumberFormat) { IO.WriteLine("Error parsing number"); IO.Logger.Log(NLog.LogLevel.Warn, exceptNumberFormat, "Error parsing number"); } /* FIX: check for sign */ if (num < 0) { IO.WriteLine("Negative Number"); } else { IO.WriteLine("" + (int)(Math.Sqrt(num))); } } catch (IOException exceptIO) { IO.Logger.Log(NLog.LogLevel.Warn, exceptIO, "Error with stream reading"); } } }
/* goodB2G() - use BadSource and GoodSink */ private static void GoodB2G(HttpRequest req, HttpResponse resp) { string data; data = ""; /* Initialize data */ /* Read data from a database */ { try { /* setup the connection */ using (SqlConnection connection = IO.GetDBConnection()) { connection.Open(); /* prepare and execute a (hardcoded) query */ using (SqlCommand command = new SqlCommand(null, connection)) { command.CommandText = "select name from users where id=0"; command.Prepare(); using (SqlDataReader dr = command.ExecuteReader()) { /* POTENTIAL FLAW: Read data from a database query SqlDataReader */ data = dr.GetString(1); } } } } catch (SqlException exceptSql) { IO.Logger.Log(NLog.LogLevel.Warn, exceptSql, "Error with SQL statement"); } } Dictionary <int, string> dataDictionary = new Dictionary <int, string>(); dataDictionary.Add(0, data); dataDictionary.Add(1, data); dataDictionary.Add(2, data); CWE113_HTTP_Response_Splitting__Web_Database_addHeader_74b.GoodB2GSink(dataDictionary, req, resp); }
/* goodB2G() - use BadSource and GoodSink */ private static void GoodB2G() { string data; data = ""; /* Initialize data */ /* Read data from a database */ { try { /* setup the connection */ using (SqlConnection connection = IO.GetDBConnection()) { connection.Open(); /* prepare and execute a (hardcoded) query */ using (SqlCommand command = new SqlCommand(null, connection)) { command.CommandText = "select name from users where id=0"; command.Prepare(); using (SqlDataReader dr = command.ExecuteReader()) { /* POTENTIAL FLAW: Read data from a database query SqlDataReader */ data = dr.GetString(1); } } } } catch (SqlException exceptSql) { IO.Logger.Log(NLog.LogLevel.Warn, exceptSql, "Error with SQL statement"); } } Hashtable dataHashtable = new Hashtable(5); dataHashtable.Add(0, data); dataHashtable.Add(1, data); dataHashtable.Add(2, data); CWE94_Improper_Control_of_Generation_of_Code__Database_72b.GoodB2GSink(dataHashtable); }
/* goodG2B1() - use goodsource and badsink by setting the static variable to false instead of true */ private void GoodG2B1() { string data; goodG2B1PublicStatic = false; data = CWE23_Relative_Path_Traversal__Database_22b.GoodG2B1Source(); int p = (int)Environment.OSVersion.Platform; string root; if (p == (int)PlatformID.Win32NT || p == (int)PlatformID.Win32Windows || p == (int)PlatformID.Win32S || p == (int)PlatformID.WinCE) { /* running on Windows */ root = "C:\\uploads\\"; } else { /* running on non-Windows */ root = "/home/user/uploads/"; } if (data != null) { /* POTENTIAL FLAW: no validation of concatenated value */ if (File.Exists(root + data)) { try { using (StreamReader sr = new StreamReader(root + data)) { IO.WriteLine(sr.ReadLine()); } } catch (IOException exceptIO) { IO.Logger.Log(NLog.LogLevel.Warn, exceptIO, "Error with stream reading"); } } } }
public override void Bad(HttpRequest req, HttpResponse resp) { int data; if (privateTrue) { data = int.MinValue; /* initialize data in case there are no cookies */ /* Read data from cookies */ { HttpCookieCollection cookieSources = req.Cookies; if (cookieSources != null) { /* POTENTIAL FLAW: Read data from the first cookie value */ string stringNumber = cookieSources[0].Value; try { data = int.Parse(stringNumber.Trim()); } catch (FormatException exceptNumberFormat) { IO.Logger.Log(NLog.LogLevel.Warn, exceptNumberFormat, "Number format exception reading data from cookie"); } } } } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run * but ensure data is inititialized before the Sink to avoid compiler errors */ data = 0; } if (privateTrue) { /* POTENTIAL FLAW: if data == int.MinValue, this will overflow */ int result = (int)(data - 1); IO.WriteLine("result: " + result); } }
public override void Bad(HttpRequest req, HttpResponse resp) { string data; data = ""; /* Initialize data */ /* Read data from a database */ { try { /* setup the connection */ using (SqlConnection connection = IO.GetDBConnection()) { connection.Open(); /* prepare and execute a (hardcoded) query */ using (SqlCommand command = new SqlCommand(null, connection)) { command.CommandText = "select name from users where id=0"; command.Prepare(); using (SqlDataReader dr = command.ExecuteReader()) { /* POTENTIAL FLAW: Read data from a database query SqlDataReader */ data = dr.GetString(1); } } } } catch (SqlException exceptSql) { IO.Logger.Log(NLog.LogLevel.Warn, exceptSql, "Error with SQL statement"); } } LinkedList <string> dataLinkedList = new LinkedList <string>(); dataLinkedList.AddLast(data); dataLinkedList.AddLast(data); dataLinkedList.AddLast(data); CWE470_Unsafe_Reflection__Web_Database_73b.BadSink(dataLinkedList, req, resp); }
public override void Bad(HttpRequest req, HttpResponse resp) { int data; if (IO.STATIC_READONLY_FIVE == 5) { data = int.MinValue; /* initialize data in case id is not in query string */ /* POTENTIAL FLAW: Parse id param out of the URL querystring (without using getParam) */ { if (req.QueryString["id"] != null) { try { data = int.Parse(req.QueryString["id"]); } catch (FormatException exceptNumberFormat) { IO.Logger.Log(NLog.LogLevel.Warn, exceptNumberFormat, "Number format exception reading id from query string"); } } } } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run * but ensure data is inititialized before the Sink to avoid compiler errors */ data = 0; } if (IO.STATIC_READONLY_FIVE == 5) { if (data > 0) /* ensure we won't have an underflow */ { /* POTENTIAL FLAW: if (data*2) > int.MaxValue, this will overflow */ int result = (int)(data * 2); IO.WriteLine("result: " + result); } } }
/* goodG2B() - use goodsource and badsink by changing the first "if" so that * both branches use the GoodSource */ private void GoodG2B() { string data; if(IO.StaticReturnsTrueOrFalse()) { /* FIX: Use a hardcoded string */ data = "foo"; } else { /* FIX: Use a hardcoded string */ data = "foo"; } if(IO.StaticReturnsTrueOrFalse()) { try { int value = int.Parse(data); } catch (FormatException exceptNumberFormat) { /* POTENTIAL FLAW: Logging output is not neutralized */ IO.Logger.Log(NLog.LogLevel.Warn, exceptNumberFormat, "Failed to parse value = " + data); } } else { try { int value = int.Parse(data); } catch (FormatException exceptNumberFormat) { /* POTENTIAL FLAW: Logging output is not neutralized */ IO.Logger.Log(NLog.LogLevel.Warn, exceptNumberFormat, "Failed to parse value = " + data); } } }
/* goodG2B() - use goodsource and badsink */ public static void GoodG2BSink(LinkedList <string> dataLinkedList) { string data = dataLinkedList.Last.Value; /* POTENTIAL FLAW: unvalidated or sandboxed value */ if (data != null) { if (File.Exists(data)) { try { using (StreamReader sr = new StreamReader(data)) { IO.WriteLine(sr.ReadLine()); } } catch (IOException exceptIO) { IO.Logger.Log(NLog.LogLevel.Warn, exceptIO, "Error with stream reading"); } } } }
/* goodB2G() - use badsource and goodsink*/ private void GoodB2G() { sbyte data; /* POTENTIAL FLAW: Use a random value */ data = (sbyte)(new Random().Next(sbyte.MinValue, sbyte.MaxValue)); for (int k = 0; k < 1; k++) { if (data > 0) /* ensure we won't have an underflow */ { /* FIX: Add a check to prevent an overflow from occurring */ if (data < (sbyte.MaxValue / 2)) { sbyte result = (sbyte)(data * 2); IO.WriteLine("result: " + result); } else { IO.WriteLine("data value is too large to perform multiplication."); } } } }
private static void GoodB2G() { string data = GoodB2GSource(); /* FIX: Hash data before storing in a file */ { string salt = "ThisIsMySalt"; using (SHA512CryptoServiceProvider sha512 = new SHA512CryptoServiceProvider()) { byte[] buffer = Encoding.UTF8.GetBytes(string.Concat(salt, data)); byte[] hashedCredsAsBytes = sha512.ComputeHash(buffer); data = IO.ToHex(hashedCredsAsBytes); } } using (SecureString secureData = new SecureString()) { for (int i = 0; i < data.Length; i++) { secureData.AppendChar(data[i]); } File.WriteAllText(@"C:\Users\Public\WriteText.txt", secureData.ToString()); } }
/* GoodG2B2() - use goodsource and badsink by reversing statements in first if */ private void GoodG2B2() { int data; if (privateTrue) { /* FIX: Use a hardcoded number that won't cause underflow, overflow, divide by zero, or loss-of-precision issues */ data = 2; } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run * but ensure data is inititialized before the Sink to avoid compiler errors */ data = 0; } if (privateTrue) { /* Need to ensure that the array is of size > 3 and < 101 due to the GoodSource and the large_fixed BadSource */ int[] array = { 0, 1, 2, 3, 4 }; /* POTENTIAL FLAW: Attempt to read from array at location data, which may be outside the array bounds */ IO.WriteLine(array[data]); } }
public static void BadSink(int data) { if (CWE129_Improper_Validation_of_Array_Index__File_array_read_check_max_22a.badPublicStatic) { /* Need to ensure that the array is of size > 3 and < 101 due to the GoodSource and the large_fixed BadSource */ int[] array = { 0, 1, 2, 3, 4 }; /* POTENTIAL FLAW: Verify that data < array.Length, but don't verify that data > 0, so may be attempting to read out of the array bounds */ if (data < array.Length) { IO.WriteLine(array[data]); } else { IO.WriteLine("Array index out of bounds"); } } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run * but ensure data is inititialized before the Sink to avoid compiler errors */ data = 0; } }
/* goodB2G2() - use badsource and goodsink by reversing the blocks in the if in the sink function */ public static void GoodB2G2Sink(int data) { if (CWE129_Improper_Validation_of_Array_Index__File_array_read_check_max_22a.goodB2G2PublicStatic) { /* Need to ensure that the array is of size > 3 and < 101 due to the GoodSource and the large_fixed BadSource */ int[] array = { 0, 1, 2, 3, 4 }; /* FIX: Fully verify data before reading from array at location data */ if (data >= 0 && data < array.Length) { IO.WriteLine(array[data]); } else { IO.WriteLine("Array index out of bounds"); } } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run * but ensure data is inititialized before the Sink to avoid compiler errors */ data = 0; } }